feat(outreach): 설정 화면 세로 2단(메일 | DM) + 메일 본문 서식 편집기, {이름} 빨강 굵게

- 설정 = 왼쪽 메일(제목·(광고)·보내는 이름·본문 편집기·끝 문구·사진), 오른쪽 인스타 DM, 위 저장 막대
- 메일 본문 = Quill 2.0.3 편집기(글자 크기·굵게·기울임·밑줄·취소선·색·배경·정렬·목록·링크·서식 지우기·되돌리기),
  vendor/quill 에 자체 호스팅
- 본문 HTML 저장(fmt=html) — 서버 sanitize_html 로 허용 태그·스타일만, 예전 글은 text_to_html 로 자동 변환
- {이름} 은 두 편집기에서 빨강 굵게(화면에서만, 메일에는 남지 않음), 글자마다 서식이 달라도 이름으로 바꿈
- DM 편집기: 서식 없음, 글자 수, [메일 본문 글 가져오기]
- 테스트: 정리기·예전 글 변환·웹 흐름, 설정 화면 브라우저 테스트 추가

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-27 09:55:13 +09:00
parent 77355b10e4
commit 9c166be404
16 changed files with 695 additions and 120 deletions
+142
View File
@@ -0,0 +1,142 @@
// 안내문 발송 설정 화면(2026-10-27) — 실제 브라우저(Chromium).
// python tests/js/render_outreach.py
// NODE_PATH=<playwright 경로> PJ_TEST_BROWSER=<Chrome 경로> node tests/js/outreach_settings.browser.test.js
// 세로 2단(메일 | DM), 저장해 둔 서식 본문 불러오기, {이름} 빨강 굵게(두 편집기, 글자 칠 때도), 서식 버튼,
// DM 글자 수·[메일 본문 글 가져오기], [저장] = body(편집기 HTML, fmt=html)·dm_body(글), [기본 문구로 되돌리기].
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 } : {});
let posted = null;
try {
const ctx = await browser.newContext({ viewport: { width: 1400, height: 900 } });
await ctx.route("**/*", function (r) {
const req = r.request(), url = new URL(req.url()).pathname;
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 === "/outreach/settings" && req.method() === "POST") {
posted = new URLSearchParams(req.postData() || "");
return r.fulfill({ status: 200, contentType: "text/html; charset=utf-8", body: "<p>saved</p>" });
}
r.fulfill({ status: 200, contentType: "text/html; charset=utf-8", body: fs.readFileSync(path.join(__dirname, ".out", "outreach_settings.html"), "utf8") });
});
const p = await ctx.newPage();
const errors = [];
p.on("pageerror", function (e) { errors.push(e.message); });
p.on("dialog", function (d) { d.accept(); });
await p.goto("http://erp.test/outreach/settings");
await p.waitForSelector("#otr-body-editor .ql-editor");
const cols = await p.evaluate(function () {
return Array.from(document.querySelectorAll(".otr-split > .otr-col")).map(function (c) {
const b = c.getBoundingClientRect(); return { x: Math.round(b.x), w: Math.round(b.width), top: Math.round(b.top),
head: c.querySelector(".otr-col-head b").textContent };
});
});
check("세로 2단 — 왼쪽 메일, 오른쪽 DM(나란히)", cols.length === 2 && cols[0].head === "이메일 안내문" && cols[1].head === "인스타 DM 문구" &&
cols[1].x >= cols[0].x + cols[0].w && cols[0].top === cols[1].top && Math.abs(cols[0].w - cols[1].w) < 4, cols);
const loaded = await p.evaluate(function () {
const ed = document.querySelector("#otr-body-editor .ql-editor");
const big = Array.from(ed.querySelectorAll("span")).find(function (s) { return s.textContent === "큰 파란 글씨"; });
return { big: big ? big.style.fontSize + "|" + big.style.color : "", list: ed.querySelectorAll("li").length,
center: !!ed.querySelector('p[style*="text-align: center"] strong, p.ql-align-center strong'),
tools: Array.from(document.querySelectorAll(".ql-toolbar button, .ql-toolbar .ql-picker")).map(function (b) { return b.title; }).filter(Boolean).length,
dm: document.querySelector("#otr-dm-editor .ql-editor").innerText.trim(),
count: document.getElementById("otr-dm-count").textContent };
});
check("저장해 둔 서식 본문 불러오기(글자 크기·색·목록·가운데 굵게)", loaded.big === "20px|rgb(0, 102, 204)" && loaded.list === 2 && loaded.center, loaded);
check("서식 도구 막대(한글 도움말)", loaded.tools >= 14, loaded.tools);
check("DM 문구 불러오기 + 글자 수", loaded.dm === "안녕하세요 {이름}님, DM 입니다" && loaded.count === "19 / 1000자", loaded);
const tags = function () {
return p.evaluate(function () {
return Array.from(document.querySelectorAll(".otr-nametag-on")).map(function (n) {
const cs = getComputedStyle(n);
return { ed: n.closest(".ql-container").id, text: n.textContent, color: cs.color, weight: cs.fontWeight };
});
});
};
const t0 = await tags();
check("{이름} = 빨강 굵게(메일·DM 편집기 모두)", t0.length === 2 && t0.every(function (t) {
return t.text === "{이름}" && t.color === "rgb(225, 29, 72)" && t.weight === "700";
}) && t0[0].ed === "otr-body-editor" && t0[1].ed === "otr-dm-editor", t0);
// 글자 치면 바로 — 새 {이름} 은 빨강, 바로 뒤에 친 글자는 아님
await p.evaluate(function () { const q = Quill.find(document.getElementById("otr-body-editor")); q.setSelection(q.getLength() - 1, 0); });
await p.keyboard.type(" {이름}님 감사");
await p.waitForTimeout(50);
const t1 = await tags();
check("새로 친 {이름}도 빨강, 뒤 글자는 그대로", t1.filter(function (t) { return t.ed === "otr-body-editor"; }).length === 2 &&
t1.every(function (t) { return t.text === "{이름}"; }), t1);
// 서식 — 글자 골라(목록의 굵지 않은 글자) 굵게 + 크기 24px
await p.evaluate(function () {
const q = Quill.find(document.getElementById("otr-body-editor"));
const i = q.getText().indexOf("하나"); q.setSelection(i, 2);
});
await p.click(".ql-toolbar .ql-bold");
await p.click(".ql-toolbar .ql-size .ql-picker-label");
await p.click('.ql-toolbar .ql-size .ql-picker-item[data-value="24px"]');
const fmt = await p.evaluate(function () {
const q = Quill.find(document.getElementById("otr-body-editor"));
return q.getFormat(q.getText().indexOf("하나"), 2);
});
check("고른 글자 굵게·글자 크기", fmt.bold === true && fmt.size === "24px", fmt);
// DM — 메일 본문 글 가져오기(확인 창) → 글자 수
await p.click("#otr-dm-from-mail");
const dm2 = await p.evaluate(function () {
return { text: document.querySelector("#otr-dm-editor .ql-editor").innerText, count: document.getElementById("otr-dm-count").textContent };
});
check("[메일 본문 글 가져오기] = 서식 빼고 글만", /^안녕하세요, \{이름\}님\.\n/.test(dm2.text) && /큰 파란 글씨/.test(dm2.text) &&
/ \/ 1000자$/.test(dm2.count), dm2);
await p.evaluate(function () { Quill.find(document.getElementById("otr-dm-editor")).setText("{이름}님 반가워요\n두 줄", "user"); });
// 저장 — 숨은 칸에 편집기 HTML·DM 글
await Promise.all([p.waitForNavigation(), p.click('#otr-set-form button[type="submit"]')]);
const body = posted && posted.get("body") || "";
fs.writeFileSync(path.join(__dirname, ".out", "outreach_settings_posted.html"), body); // 서버 정리(sanitize_html) 확인용
check("[저장] → fmt=html, body = 편집기 HTML(서식 그대로)", !!posted && posted.get("fmt") === "html" &&
/font-size: 20px/.test(body) && /font-size: 24px[^>]*>(<strong>)?하나|<strong[^>]*>(<span style="font-size: 24px;?">)?하나/.test(body) && /<ul>/.test(body) && body.indexOf("{이름}") >= 0,
body.slice(0, 400));
check("[저장] → 제목·DM 글(서식 없음)", posted.get("subject") === "{이름}님께 제안" && posted.get("dm_body").replace(/\r\n/g, "\n") === "{이름}님 반가워요\n두 줄",
{ s: posted.get("subject"), d: posted.get("dm_body") });
// 기본 문구로 되돌리기
await p.goto("http://erp.test/outreach/settings");
await p.waitForSelector("#otr-body-editor .ql-editor");
await p.click("#otr-default");
const def = await p.evaluate(function () {
return { mail: Quill.find(document.getElementById("otr-body-editor")).getText(),
bold: Array.from(document.querySelectorAll("#otr-body-editor strong")).map(function (n) { return n.textContent; }),
dm: Quill.find(document.getElementById("otr-dm-editor")).getText().trim(), count: document.getElementById("otr-dm-count").textContent,
subject: document.querySelector('input[name="subject"]').value, names: document.querySelectorAll("#otr-body-editor .otr-nametag-on").length };
});
check("[기본 문구로 되돌리기] = 기본 본문(**굵게** → 굵게)·DM 비움·제목", /^안녕하세요, \{이름\}님\.\n주방의 본질/.test(def.mail) &&
def.bold.indexOf("'미라네주방'") >= 0 && def.dm === "" && /^비어 있음/.test(def.count) && /^누적매출 300억/.test(def.subject) && def.names === 6, def);
// 좁은 화면 = 위아래
await p.setViewportSize({ width: 900, height: 900 });
const narrow = await p.evaluate(function () {
const c = document.querySelectorAll(".otr-split > .otr-col"); return c[1].getBoundingClientRect().top > c[0].getBoundingClientRect().bottom - 1;
});
check("좁은 화면 = 메일 위, DM 아래", narrow);
check("화면 스크립트 오류 없음", errors.length === 0, errors);
} 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); });
+13 -2
View File
@@ -1,6 +1,6 @@
"""안내문 발송 화면(index.html)을 진짜 ERP 셸로 렌더 — 브라우저 테스트용(2026-10-27).
python tests/js/render_outreach.py # → tests/js/.out/outreach.html
python tests/js/render_outreach.py # → tests/js/.out/outreach.html, outreach_settings.html
화면 데이터는 실제 router._view 로 만든다(저장소 없이 줄만 가짜).
"""
@@ -34,10 +34,21 @@ def main() -> None:
"status": "보냄", "sent_at": "2026-10-27T10:00:00+09:00", "sent_via": "gmail"},
]
ctx = {"user": {"email": "me@miras.co.kr", "name": "나", "picture": ""}, "is_admin": False, "nav_items": [],
"page_title": "안내문 발송", "page_subtitle": "", "template": t, "images": [], "rows": [_view(r, t) for r in raw],
"page_title": "안내문 발송", "page_subtitle": "", "template": t, "body_text": store.html_to_text(t["body"]),
"needs_name": store.needs_name(t), "images": [], "rows": [_view(r, t) for r in raw],
"logs": [], "gmail": {"available": True, "connected": True, "email": "me@miras.co.kr"}, "msg": ""}
with open(os.path.join(OUT_DIR, "outreach.html"), "w", encoding="utf-8") as f:
f.write(env.get_template("outreach/index.html").render(**ctx))
# 설정 화면 — 저장해 둔 서식 본문(HTML)·DM 문구로
saved = store.normalize_template({
"subject": "{이름}님께 제안", "fmt": "html", "dm_body": "안녕하세요 {이름}님, DM 입니다",
"body": '<p>안녕하세요, {이름}님.</p><p><br></p><p><span style="font-size: 20px; color: rgb(0, 102, 204)">큰 파란 글씨</span></p>'
'<ul><li>하나</li><li>둘</li></ul><p style="text-align: center"><strong>가운데 굵게</strong></p>'})
sctx = {**ctx, "page_title": "설정", "template": {**saved, "updated_by": "me@miras.co.kr", "updated_at": "2026-10-27T10:00:00",
"is_default": False},
"default": store.normalize_template(None), "max_images": 10, "dm_max": store.DM_MAX}
with open(os.path.join(OUT_DIR, "outreach_settings.html"), "w", encoding="utf-8") as f:
f.write(env.get_template("outreach/settings.html").render(**sctx))
if __name__ == "__main__":
+50 -5
View File
@@ -64,11 +64,46 @@ class RenderTests(unittest.TestCase):
h = store.html_body(self.T, "<script>x</script>", ["c1@dbx", "c2@dbx"])
self.assertIn("&lt;script&gt;x&lt;/script&gt;님", h)
self.assertNotIn("<script>", h)
self.assertIn("<b>미라네주방</b>", h)
self.assertIn("<strong>미라네주방</strong>", h)
self.assertIn('<a href="https://miras.co.kr/"', h)
self.assertEqual(h.count('src="cid:'), 2)
self.assertEqual(store.dm_link("mira.kitchen"), "https://ig.me/m/mira.kitchen")
def test_legacy_text_body_becomes_html(self):
# 예전 저장 글·기본 문구(fmt 없음) = 줄마다 문단, 빈 줄 유지, **굵게**·주소 변환 — 글로 되돌리면 별표만 빠진 원래 글
self.assertEqual(self.T["fmt"], "html")
self.assertEqual(self.T["body"], '<p>안녕하세요, {이름}님.</p><p><strong>미라네주방</strong>입니다.</p>'
'<p><a href="https://miras.co.kr/">https://miras.co.kr/</a></p>')
d = store.normalize_template(None)
self.assertEqual(store.html_to_text(d["body"]), store.DEFAULT_TEMPLATE["body"].replace("**", "").rstrip())
self.assertEqual(store.normalize_template({"body": d["body"], "fmt": "html"})["body"], d["body"]) # 다시 정리해도 같음
def test_editor_html_sanitized(self):
# 설정 편집기(Quill getSemanticHTML) HTML — 서식은 남기고 위험한 것은 뺀다, &nbsp; → 띄어쓰기, 빈 문단 = <br>
raw = ('<p>안녕하세요,&nbsp;<span class="otr-nametag-on">{이름}</span>님.</p><p></p>'
'<p style="text-align: center;"><span style="color: rgb(230, 0, 0); font-size: 20px; position: fixed;">빨강</span>'
'<script>alert(1)</script><img src=x onerror="alert(1)"><iframe src="//x"></iframe></p>'
'<ul><li><strong>하나</strong></li><li><em><u><s>둘</s></u></em></li></ul>'
'<p><a href="javascript:alert(1)" onclick="x">나쁜</a> <a href="https://a.com/?x=1&amp;y=2" target="_blank">좋은</a>'
'<span style="background-color: url(x)">배경</span>{<strong>이</strong>름}<div>안</div></p>')
t = store.normalize_template({"body": raw, "fmt": "html"})
self.assertEqual(t["body"],
'<p>안녕하세요, <span>{이름}</span>님.</p><p><br></p>'
'<p style="text-align: center"><span style="color: rgb(230, 0, 0); font-size: 20px">빨강</span></p>'
'<ul><li><strong>하나</strong></li><li><em><u><s>둘</s></u></em></li></ul>'
'<p><a>나쁜</a> <a href="https://a.com/?x=1&amp;y=2">좋은</a><span>배경</span>{<strong>이</strong>름}안</p>')
self.assertEqual(store.html_to_text(t["body"]), "안녕하세요, {이름}님.\n\n빨강\n- 하나\n- 둘\n나쁜 좋은배경{이름}안")
self.assertTrue(store.needs_name(t))
h = store.html_body(t, "<김>")
self.assertIn("안녕하세요, <span>&lt;김&gt;</span>님.", h)
self.assertIn("배경</span>&lt;김&gt;<strong></strong>안", h) # 글자마다 서식이 달라도 {이름} 을 바꾼다
self.assertIn('<p style="margin:0;text-align: center">', h) # 메일 프로그램 문단 여백 0
for bad in ("<script", "onerror", "javascript:", "<iframe", "position", "url(", "<img src=x", "class="):
self.assertNotIn(bad, h)
# 서식 포함 너무 긴 본문 = 저장 안 됨(정리 후 길이)
self.assertGreater(len(store.normalize_template({"body": "<p>" + "가" * (store.BODY_MAX + 10) + "</p>", "fmt": "html"})["body"]),
store.BODY_MAX)
def test_dm_body(self):
# DM 문구가 비면 메일 글(본문 + 끝 문구), 있으면 그것만 — 별표만 빼고 {이름}, 끝 문구·제목 없이
self.assertEqual(store.dm_text(self.T, "김철수"), store.plain_text(self.T, "김철수"))
@@ -196,7 +231,7 @@ class Store:
return {**self.t, "updated_by": "", "updated_at": "", "is_default": self.saved is None}
def save_template(self, value, by): # db.save_template 과 같은 검사
t = ostore.normalize_template(value)
if not t["subject"] or not t["body"].strip(): raise ValueError("메일 제목·본문을 쓰세요.")
if not t["subject"] or not ostore.html_to_text(t["body"]).strip(): raise ValueError("메일 제목·본문을 쓰세요.")
self.t = t; self.saved = by; return self.get_template()
def list_images(self, with_data=False): return []
def list_logs(self, limit=200): return []
@@ -288,7 +323,9 @@ def body(c):
assert "안내문 발송" in t and "누적매출 300억" in t and "Gmail 연결" in t and "고른 메일 보내기" in t
# 설정 — 기본 문구, 저장, (광고)
s = c.get("/outreach/settings").text
assert "기본 문구(아직 저장 안 함)" in s and "주방의 본질을 지키며" in s and "정보통신망법" in s
cur = lambda s: __import__("json").loads(s.split('id="otr-current-data">')[1].split("</script>")[0]) # noqa: E731
assert "기본 문구(아직 저장 안 함)" in s and "정보통신망법" in s and 'id="otr-body-editor"' in s and "/static/vendor/quill/quill.js" in s
assert cur(s)["body"].startswith("<p>안녕하세요, {이름}님.</p><p>주방의 본질을 지키며"), cur(s)
r = c.post("/outreach/settings", data={"subject": "{이름}님 제안", "body": "안녕하세요 {이름}님", "sender_name": "미라네주방",
"footer": "수신 거부: 회신", "ad_label": "1"})
assert r.status_code == 303 and st.saved == "me@miras.co.kr" and st.t["ad_label"] is True
@@ -311,7 +348,7 @@ def body(c):
# 이름 고치기
assert c.put(f"/outreach/api/recipients/{nobody['id']}", json={"name": "노바디"}).json()["row"]["needs_name"] is False
# 인스타 DM 문구 — 저장하면 DM 줄 글·미리보기가 그 문구로(메일은 그대로)
assert "인스타 DM 문구" in s and 'name="dm_body"' in s
assert "인스타 DM 문구" in s and 'name="dm_body"' in s and 'id="otr-dm-editor"' in s
r = c.post("/outreach/settings", data={"subject": "{이름}님 제안", "body": "안녕하세요 {이름}님", "footer": "수신 거부: 회신",
"dm_body": "{이름}님, **DM** 문구입니다"})
assert r.status_code == 303 and st.t["dm_body"] == "{이름}님, **DM** 문구입니다"
@@ -319,7 +356,15 @@ def body(c):
assert mira2["dm_text"] == "미라님, DM 문구입니다", mira2
assert c.get(f"/outreach/api/recipients/{mira['id']}/preview").json()["text"] == "미라님, DM 문구입니다"
assert "수신 거부: 회신" in c.get(f"/outreach/api/recipients/{kim['id']}/preview").json()["text"]
assert "**DM** 문구입니다" in c.get("/outreach/settings").text
assert cur(c.get("/outreach/settings").text)["dm_body"] == "{이름}님, **DM** 문구입니다"
# 서식 편집기 본문(fmt=html) — 서버가 정리해 저장, 메일 미리보기에 서식·이름
r = c.post("/outreach/settings", data={"subject": "{이름}님 제안", "fmt": "html", "dm_body": "",
"body": '<p>안녕&nbsp;<span style="color: rgb(230, 0, 0)" onclick="x">{이름}</span>님</p><script>x</script>'})
assert r.status_code == 303 and st.t["body"] == '<p>안녕 <span style="color: rgb(230, 0, 0)">{이름}</span>님</p>', st.t["body"]
pv = c.get(f"/outreach/api/recipients/{kim['id']}/preview").json()
assert '<span style="color: rgb(230, 0, 0)">김철수</span>님' in pv["html"] and pv["text"].startswith("안녕 김철수님"), pv
assert c.get("/outreach/").text.count("안녕 {이름}님") == 1 # 리스트 화면 '보낼 내용' = 글로
assert c.post("/outreach/settings", data={"subject": "x", "fmt": "html", "body": "<p></p><p><br></p>"}).status_code == 400
# 메일 보내기 — Gmail 없음 = 409(재연결 안내)
r = c.post("/outreach/api/send", json={"ids": [kim["id"]]})
assert r.status_code == 409 and r.json()["reconnect"] is True