48cd7f0878
- 이름 목록: × 한 명씩 빼기·[전체 삭제], 이름 넣기는 목록에 더함
- 본문: 바로 고침(plaintext-only), {이름} 자리 = 분홍 칩, 이름 누르면 고친 글 + 이름 복사
- 저장한 본문(본문 오른쪽): 설정 DM 문구 + 저장한 것, 고르기·[저장]·[새 본문으로 저장]·× 지우기
- outreach_db 마이그레이션 002 outreach_dm_bodies + POST/PUT/DELETE /outreach/api/dm-bodies
(002 미적용이면 목록 안내만, API 503)
- 캐시 버전 20261030c, 단위·API·실제 PG·브라우저 테스트
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
234 lines
18 KiB
JavaScript
234 lines
18 KiB
JavaScript
// 안내문 발송 리스트 화면(2026-10-27) — 실제 브라우저(Chromium).
|
||
// python tests/js/render_outreach.py
|
||
// NODE_PATH=<playwright 경로> PJ_TEST_BROWSER=<Chrome 경로> node tests/js/outreach.browser.test.js
|
||
// 구분 배지(메일/DM)·걸러 보기, [DM 보내기] = 그 사람 이름이 든 문구 복사 + ig.me DM 창 새 탭, [보냄] 기록, 이름 없는 줄 표시,
|
||
// 붙여넣기 미리보기(메일/DM/오류) → 추가, 고른 메일 보내기(메일 줄만, 확인 창), 미리보기 창. 서버 API 는 테스트 안 가짜.
|
||
const fs = require("fs"), path = require("path");
|
||
const { chromium } = require("playwright");
|
||
const ROOT = path.join(__dirname, "..", "..");
|
||
const fails = [];
|
||
function check(name, cond, extra) {
|
||
if (cond) console.log("PASS " + name);
|
||
else { console.log("FAIL " + name + (extra !== undefined ? " → " + JSON.stringify(extra) : "")); fails.push(name); }
|
||
}
|
||
|
||
(async function () {
|
||
const exe = process.env.PJ_TEST_BROWSER;
|
||
const browser = await chromium.launch(exe ? { executablePath: exe } : {});
|
||
const calls = [];
|
||
let dmBodies = [], dmSeq = 0; // 저장한 DM 본문(가짜 서버)
|
||
try {
|
||
const ctx = await browser.newContext({ viewport: { width: 1400, height: 900 }, permissions: ["clipboard-read", "clipboard-write"] });
|
||
await ctx.route("**/*", function (r) {
|
||
const req = r.request(), u = new URL(req.url()), url = u.pathname;
|
||
if (u.host === "ig.me") return r.fulfill({ status: 200, contentType: "text/html", body: "<title>ig</title>" });
|
||
if (url.startsWith("/static/")) {
|
||
const f = path.join(ROOT, "app", url);
|
||
if (!fs.existsSync(f)) return r.fulfill({ status: 404, body: "" });
|
||
return r.fulfill({ status: 200, contentType: f.endsWith(".css") ? "text/css" : "application/javascript", body: fs.readFileSync(f) });
|
||
}
|
||
if (url.startsWith("/outreach/api/")) {
|
||
const body = req.postData() ? JSON.parse(req.postData()) : null;
|
||
calls.push({ method: req.method(), url: url, body: body });
|
||
const json = function (o, s) { return r.fulfill({ status: s || 200, contentType: "application/json", body: JSON.stringify(o) }); };
|
||
if (url === "/outreach/api/recipients/2/dm-sent") {
|
||
return json({ row: { id: 2, kind: "instagram", kind_label: "DM", handle: "mira.kitchen", address: "@mira.kitchen", name: "미라",
|
||
status: "보냄", sent_at: "2026-10-27T11:00:00+09:00", sent_via: "dm", dm_link: "https://ig.me/m/mira.kitchen",
|
||
profile_link: "https://www.instagram.com/mira.kitchen/", dm_text: "x", needs_name: false, last_error: "" } });
|
||
}
|
||
if (url === "/outreach/api/recipients/parse") {
|
||
return json({ rows: [
|
||
{ line: 1, address: "new@x.com", name: "새사람", kind: "email", kind_label: "메일", handle: "new@x.com", error: "", dup: false, exists: false },
|
||
{ line: 2, address: "@hong", name: "홍", kind: "instagram", kind_label: "DM", handle: "hong", error: "", dup: false, exists: false },
|
||
{ line: 3, address: "홍길동", name: "", kind: null, kind_label: "오류", handle: "", error: "이메일도 인스타그램 주소도 아닙니다: 홍길동", dup: false, exists: false }] });
|
||
}
|
||
if (url === "/outreach/api/recipients" && req.method() === "POST") return json({ ok: true, added: 2, existed: 0, invalid: 1 });
|
||
if (url === "/outreach/api/send") return json({ ok: true, queued: body.ids.length }, 202);
|
||
const dmb = /^\/outreach\/api\/dm-bodies(?:\/(\d+))?$/.exec(url);
|
||
if (dmb) { // 저장한 DM 본문 — 새로 저장·고치기·지우기(제목 = 첫 줄)
|
||
const title = function (b) { return b.split("\n").map(function (x) { return x.trim(); }).filter(Boolean)[0] || ""; };
|
||
let id = dmb[1] ? +dmb[1] : 0;
|
||
if (req.method() === "POST") { id = ++dmSeq; dmBodies.unshift({ id: id, title: title(body.body), body: body.body, updated_by: "me", updated_at: "" }); }
|
||
if (req.method() === "PUT") { const b = dmBodies.find(function (x) { return x.id === id; }); b.body = body.body; b.title = title(body.body); }
|
||
if (req.method() === "DELETE") dmBodies = dmBodies.filter(function (x) { return x.id !== id; });
|
||
return json({ id: id, items: dmBodies });
|
||
}
|
||
if (url === "/outreach/api/recipients/1/preview") {
|
||
return json({ subject: "누적매출 300억", html: "<p>안녕하세요, 김철수님.</p>", text: "안녕하세요, 김철수님.", kind: "email", to: "kim@miras.co.kr", sender_name: "미라네주방" });
|
||
}
|
||
if (url === "/outreach/api/recipients" && req.method() === "GET") {
|
||
const data = JSON.parse(fs.readFileSync(path.join(__dirname, ".out", "outreach.html"), "utf8")
|
||
.match(/<script type="application\/json" id="otr-data">([\s\S]*?)<\/script>/)[1]);
|
||
return json(data);
|
||
}
|
||
return json({});
|
||
}
|
||
const page = url === "/outreach/dm" ? "outreach_dm.html" : "outreach.html"; // DM 수동 보내기 탭(2026-10-30)
|
||
r.fulfill({ status: 200, contentType: "text/html; charset=utf-8", body: fs.readFileSync(path.join(__dirname, ".out", page), "utf8") });
|
||
});
|
||
const p = await ctx.newPage();
|
||
p.on("dialog", function (d) { d.accept(); });
|
||
// http 테스트 주소는 보안 컨텍스트가 아니라 navigator.clipboard 가 없다 → 화면이 쓰는 예비 복사(execCommand)를 잡아 본다
|
||
// (운영은 https 라 navigator.clipboard.writeText 로 복사)
|
||
await p.addInitScript(function () {
|
||
const orig = document.execCommand.bind(document);
|
||
document.execCommand = function (cmd) {
|
||
if (cmd === "copy") { const a = document.activeElement; window.__copied = a && "value" in a ? a.value : ""; return true; }
|
||
return orig.apply(document, arguments);
|
||
};
|
||
});
|
||
await p.goto("http://erp.test/outreach/");
|
||
await p.waitForTimeout(200);
|
||
const rowsInfo = function () {
|
||
return p.evaluate(function () {
|
||
return Array.from(document.querySelectorAll("#otr-tbody tr")).map(function (tr) {
|
||
return { id: +tr.dataset.id, kind: tr.querySelector(".otr-kind").textContent, name: tr.querySelector(".otr-name").value,
|
||
status: tr.querySelector(".otr-st").textContent, noname: tr.classList.contains("is-noname"),
|
||
acts: Array.from(tr.querySelectorAll("[data-act]")).map(function (b) { return b.dataset.act; }) };
|
||
});
|
||
});
|
||
};
|
||
const r0 = await rowsInfo();
|
||
check("구분 배지 = 주소를 보고 메일/DM, DM 줄은 [DM 보내기]·[보냄], 메일 줄은 [미리보기]",
|
||
JSON.stringify(r0.map(function (r) { return r.kind; })) === '["메일","DM","메일","메일"]' &&
|
||
JSON.stringify(r0[1].acts) === '["dm","dm-sent"]' && JSON.stringify(r0[0].acts) === '["preview"]', r0);
|
||
check("본문 {이름} 인데 이름 없는 줄 = 표시", r0[2].noname && !r0[0].noname, r0[2]);
|
||
const cnt = await p.evaluate(function () {
|
||
const o = {}; document.querySelectorAll("[data-cnt]").forEach(function (n) { o[n.dataset.cnt] = n.textContent; }); return o;
|
||
});
|
||
check("걸러 보기 개수", cnt.all === "4" && cnt.email === "3" && cnt.instagram === "1" && cnt["보냄"] === "1", cnt);
|
||
await p.click('[data-filter="instagram"]');
|
||
check("DM 만 보기", (await rowsInfo()).length === 1);
|
||
await p.click('[data-filter="all"]');
|
||
// DM 보내기 — 문구 복사 + DM 창
|
||
const [igPage] = await Promise.all([ctx.waitForEvent("page"), p.click('tr[data-id="2"] [data-act="dm"]')]);
|
||
await igPage.waitForLoadState().catch(function () {});
|
||
const clip = await p.evaluate(function () {
|
||
return navigator.clipboard ? navigator.clipboard.readText() : (window.__copied || "");
|
||
});
|
||
check("[DM 보내기] = ig.me/m/계정 새 탭", /ig\.me\/m\/mira\.kitchen/.test(igPage.url()), igPage.url());
|
||
check("[DM 보내기] = 이름이 들어간 DM 문구 복사(별표 없음)", clip.indexOf("안녕하세요, 미라님.") === 0 && clip.indexOf("**") < 0 &&
|
||
clip.indexOf("'미라네주방'입니다") > 0, clip.slice(0, 80));
|
||
await igPage.close();
|
||
await p.click('tr[data-id="2"] [data-act="dm-sent"]');
|
||
await p.waitForTimeout(100);
|
||
const r1 = await rowsInfo();
|
||
check("[보냄] → 보냄, 버튼 빠짐", r1[1].status === "보냄" && JSON.stringify(r1[1].acts) === '["dm"]' &&
|
||
calls.some(function (c) { return c.url === "/outreach/api/recipients/2/dm-sent"; }), r1[1]);
|
||
// 미리보기 창
|
||
await p.click('tr[data-id="1"] [data-act="preview"]');
|
||
await p.waitForTimeout(100);
|
||
const pv = await p.evaluate(function () {
|
||
return { shown: !document.getElementById("otr-preview").hidden, subject: document.getElementById("otr-pv-subject").textContent,
|
||
doc: document.getElementById("otr-pv-frame").srcdoc };
|
||
});
|
||
check("미리보기 창 = 제목·본문(그 사람 이름)", pv.shown && /누적매출 300억/.test(pv.subject) && /김철수님/.test(pv.doc), pv);
|
||
await p.keyboard.press("Escape");
|
||
// 고른 메일 보내기 — 전부 고르면 메일·대기만(1·3), DM·보냄 빠짐
|
||
await p.check("#otr-check-all");
|
||
check("고른 줄 수 표시", /고른 줄 4 · 보낼 메일 2/.test(await p.textContent("#otr-selected")), await p.textContent("#otr-selected"));
|
||
await p.click("#otr-send");
|
||
await p.waitForTimeout(200);
|
||
const sendCall = calls.find(function (c) { return c.url === "/outreach/api/send"; });
|
||
check("고른 메일 보내기 → 메일·대기 줄만 보냄", !!sendCall && JSON.stringify(sendCall.body.ids) === "[1,3]", sendCall);
|
||
// 탭 [발송 리스트][DM 수동 보내기] + 설정 = 맨 오른쪽 톱니 아이콘(2026-10-30)
|
||
const gear = await p.evaluate(function () {
|
||
const g = document.querySelector(".otr-gear"), top = document.querySelector(".otr-tabs").getBoundingClientRect(), r = g.getBoundingClientRect();
|
||
return { href: g.getAttribute("href"), icon: g.textContent.trim(), right: Math.round(top.right - r.right),
|
||
font: getComputedStyle(g.querySelector(".material-symbols-outlined")).fontFamily };
|
||
});
|
||
check("설정 = 맨 오른쪽 톱니(글자 대신 아이콘)", gear.href === "/outreach/settings" && gear.icon === "settings" && gear.right <= 2 &&
|
||
/Material Symbols/.test(gear.font), gear);
|
||
const tabs = await p.$$eval(".otr-tab", function (els) { return els.map(function (e) { return [e.textContent.trim(), e.getAttribute("href"), e.classList.contains("is-active")]; }); });
|
||
check("탭 = 발송 리스트(선택됨) · DM 수동 보내기", JSON.stringify(tabs) === JSON.stringify([["forward_to_inbox발송 리스트", "/outreach/", true], ["chatDM 수동 보내기", "/outreach/dm", false]]), tabs);
|
||
// DM 수동 보내기 탭 — 왼쪽 이름(넣기 + 목록) | 오른쪽 본문. 이름 누르면 문구 {이름} 바뀌고 복사 + 짧은 안내
|
||
await p.click('.otr-tab[href="/outreach/dm"]');
|
||
await p.waitForSelector("#otr-dm-names");
|
||
const lay = await p.evaluate(function () {
|
||
const l = document.getElementById("otr-dm-names").getBoundingClientRect(), r = document.getElementById("otr-dm-body").getBoundingClientRect();
|
||
return { leftOfBody: l.right < r.left, active: document.querySelector(".otr-tab.is-active").getAttribute("href"),
|
||
body: document.getElementById("otr-dm-body").textContent };
|
||
});
|
||
check("DM 탭 — 왼쪽 이름 목록, 오른쪽 본문({이름} 그대로)", lay.leftOfBody && lay.active === "/outreach/dm" && lay.body.includes("{이름}"), lay);
|
||
await p.fill("#otr-dm-text", "이름\n김민지\t메모\n\n박서준, x\n김민지");
|
||
await p.click("#otr-dm-load");
|
||
const names = await p.$$eval("#otr-dm-names .otr-dm-name", function (els) { return els.map(function (e) { return e.textContent; }); });
|
||
check("DM 수동 — 이름 목록(첫 칸, 머리글·빈 줄·같은 이름 뺌)", JSON.stringify(names) === '["김민지","박서준"]', names);
|
||
await p.click('#otr-dm-names .otr-dm-name[data-i="1"]');
|
||
await p.waitForTimeout(100);
|
||
const dm = await p.evaluate(async function () {
|
||
const t = document.getElementById("otr-toast");
|
||
return { body: document.getElementById("otr-dm-body").textContent, clip: navigator.clipboard ? await navigator.clipboard.readText() : (window.__copied || ""),
|
||
toast: t && !t.hidden ? t.textContent : "", active: document.querySelector(".otr-dm-name.is-active").textContent };
|
||
});
|
||
check("이름 누르면 오른쪽 문구 = 그 이름, 클립보드 복사, 안내", dm.active === "박서준" && dm.body.includes("박서준") && !dm.body.includes("{이름}") &&
|
||
dm.clip === dm.body && /박서준 님 문구를 클립보드에 복사/.test(dm.toast), dm);
|
||
await p.waitForTimeout(1800);
|
||
check("안내는 잠깐 뒤 사라짐", await p.evaluate(function () { return document.getElementById("otr-toast").hidden; }));
|
||
// 이름 한 명 빼기(×) — 고른 사람(박서준)은 그대로 골라짐
|
||
await p.click('#otr-dm-names [data-del="0"]');
|
||
let st = await p.evaluate(function () {
|
||
return { names: Array.from(document.querySelectorAll("#otr-dm-names .otr-dm-name")).map(function (e) { return e.textContent; }),
|
||
active: (document.querySelector("#otr-dm-names .is-active") || {}).textContent, sum: document.getElementById("otr-dm-sum").textContent };
|
||
});
|
||
check("이름 한 명 빼기(×) — 고른 사람은 그대로", JSON.stringify(st.names) === '["박서준"]' && st.active === "박서준" && st.sum === "1명", st);
|
||
// 본문 고치기 — 맨 앞에 글을 더 쓰고 이름을 다시 누르면 고친 글 + 이름이 복사
|
||
await p.click("#otr-dm-body");
|
||
await p.keyboard.press("Control+Home");
|
||
await p.keyboard.type("추가 인사");
|
||
await p.keyboard.press("Enter"); // 줄바꿈도 글(\n)로
|
||
await p.click('#otr-dm-names .otr-dm-name[data-i="0"]');
|
||
await p.waitForTimeout(100);
|
||
st = await p.evaluate(function () {
|
||
return { clip: window.__copied || "", tags: Array.from(document.querySelectorAll("#otr-dm-body .otr-dm-tag")).map(function (e) { return e.textContent; }) };
|
||
});
|
||
check("본문 고친 글 그대로(줄바꿈 포함) + 이름 칩(분홍) — 복사도 고친 글", /^추가 인사\n안녕/.test(st.clip) && st.clip.includes("박서준") && !st.clip.includes("{이름}") &&
|
||
st.tags.length > 0 && st.tags.every(function (t) { return t === "박서준"; }), st);
|
||
// 새 본문으로 저장 → 오른쪽 목록, 설정 DM 문구 ↔ 저장 본문 고르기, 하나씩 지우기
|
||
await p.click("#otr-dm-saveas");
|
||
await p.waitForTimeout(150);
|
||
const saved = calls.filter(function (c) { return c.url === "/outreach/api/dm-bodies" && c.method === "POST"; }).pop();
|
||
st = await p.evaluate(function () {
|
||
return { items: Array.from(document.querySelectorAll("#otr-dm-bodies .otr-dm-name")).map(function (e) { return e.textContent.trim(); }),
|
||
cur: document.getElementById("otr-dm-cur").textContent, save: !document.getElementById("otr-dm-save").disabled };
|
||
});
|
||
check("새 본문으로 저장 — {이름} 자리는 {이름} 으로 저장, 목록에 첫 줄 제목", !!saved && /^추가 인사\n/.test(saved.body.body) && saved.body.body.includes("{이름}") &&
|
||
!saved.body.body.includes("박서준") && st.items.length === 2 && /^추가 인사/.test(st.items[1]) && /추가 인사/.test(st.cur) && st.save, { saved: saved, st: st });
|
||
await p.click('#otr-dm-bodies [data-body="settings"]');
|
||
const back = await p.evaluate(function () { return document.getElementById("otr-dm-body").textContent; });
|
||
await p.click('#otr-dm-bodies [data-body="1"]');
|
||
const again = await p.evaluate(function () { return document.getElementById("otr-dm-body").textContent; });
|
||
check("목록에서 본문 고르기 — 설정 DM 문구 ↔ 저장한 본문", !/^추가 인사/.test(back) && /^추가 인사\n?안녕/.test(again), { back: back.slice(0, 20), again: again.slice(0, 20) });
|
||
await p.click('#otr-dm-bodies [data-delbody="1"]');
|
||
await p.waitForTimeout(150);
|
||
st = await p.evaluate(function () { return document.querySelectorAll("#otr-dm-bodies .otr-dm-name").length; });
|
||
check("저장한 본문 하나 지우기(×)", st === 1 && calls.some(function (c) { return c.method === "DELETE" && c.url === "/outreach/api/dm-bodies/1"; }), st);
|
||
await p.click("#otr-dm-clear");
|
||
st = await p.evaluate(function () { return { n: document.querySelectorAll("#otr-dm-names .otr-dm-name").length, tag: document.querySelector("#otr-dm-body .otr-dm-tag").textContent }; });
|
||
check("이름 전체 삭제 — 본문은 {이름} 으로", st.n === 0 && st.tag === "{이름}", st);
|
||
await p.goBack();
|
||
await p.waitForSelector("#otr-add-open");
|
||
// 리스트 추가 — 미리보기(판별) → 추가
|
||
await p.click("#otr-add-open");
|
||
await p.fill("#otr-add-text", "new@x.com 새사람\n@hong 홍\n홍길동");
|
||
check("미리보기 전엔 [리스트에 추가] 꺼짐", await p.isDisabled("#otr-add-save"));
|
||
await p.click("#otr-add-preview");
|
||
await p.waitForTimeout(100);
|
||
const prev = await p.evaluate(function () {
|
||
return { kinds: Array.from(document.querySelectorAll("#otr-add-result .otr-kind")).map(function (n) { return n.textContent; }),
|
||
sum: document.getElementById("otr-add-sum").textContent, err: document.querySelector("#otr-add-result .otr-err").textContent };
|
||
});
|
||
check("붙여넣기 미리보기 = 메일/DM/오류 + 요약", JSON.stringify(prev.kinds) === '["메일","DM","오류"]' &&
|
||
/새로 2명 \(메일 1 · DM 1\) · 오류 1줄/.test(prev.sum) && /인스타그램 주소도 아닙니다/.test(prev.err), prev);
|
||
await p.click("#otr-add-save");
|
||
await p.waitForTimeout(150);
|
||
const add = calls.find(function (c) { return c.method === "POST" && c.url === "/outreach/api/recipients"; });
|
||
check("[리스트에 추가] → 붙여 넣은 글 그대로 서버로, 창 닫힘", !!add && /new@x\.com 새사람/.test(add.body.text) &&
|
||
await p.evaluate(function () { return document.getElementById("otr-add").hidden; }), add);
|
||
} finally {
|
||
await browser.close();
|
||
}
|
||
if (fails.length) { console.log("\n" + fails.length + " FAILED"); process.exit(1); }
|
||
console.log("\nALL PASS");
|
||
})().catch(function (e) { console.error(e); process.exit(1); });
|