Merge branch 'feat/outreach-settings-editor'

This commit is contained in:
2026-10-27 09:55:22 +09:00
16 changed files with 695 additions and 120 deletions
+13 -6
View File
@@ -2,7 +2,7 @@
> 이 모듈만 고칠 때 읽는 요약. 별도 상세 문서 없음 — 코드가 기준.
> 정적 파일: `app/static/outreach.js`, `app/static/outreach.css`. 템플릿: `templates/outreach/`. 테스트: `tests/test_outreach.py`,
> `tests/js/outreach.browser.test.js`(`render_outreach.py`).
> `tests/js/outreach.browser.test.js`·`outreach_settings.browser.test.js`(`render_outreach.py`). 편집기 = `app/static/vendor/quill/`(Quill 2.0.3, BSD).
> 다른 모듈과 연결: 메일 = 입출고 Gmail 연결(`inout_store.inout_gmail_tokens`, `app/modules/inout/gmail.py`, 콜백 `/inout/gmail/callback` 이
> 세션 `_gmail_origin=outreach` 를 보고 `_GMAIL_ORIGINS` 로 처리) — 입출고·휴가와 같은 연결.
@@ -10,14 +10,21 @@
- **주소를 보고 메일/DM 판별**(`store.detect`): `name@domain.tld` = 메일, `@계정`·`instagram.com/계정`·`ig.me/m/계정`·계정명만(영문·숫자·.·_) = 인스타 DM.
게시물 주소(`/p/`·`/reel/`)·한글만은 오류. 같은 주소는 한 번(`UNIQUE(kind, handle)`, 이메일·계정명 소문자).
- 리스트 추가 = 붙여넣기(한 줄에 한 사람 `주소, 이름` — 쉼표·탭·띄어쓰기, 순서는 어느 쪽이든, `store.parse_line`) → [미리보기](메일/DM/오류·중복·이미 있음) → [리스트에 추가].
- **본문 `{이름}`** = 그 줄 이름(제목에도). 이름이 빈 줄은 보내지 않고 실패('이름 없음'), 화면에 "이름 필요" 표시. `**굵게**` = 메일 굵은 글씨(DM 은 별표만 뺌), 주소 = 메일 링크.
- **본문 `{이름}`** = 그 줄 이름(제목에도). 이름이 빈 줄은 보내지 않고 실패('이름 없음'), 화면에 "이름 필요" 표시.
- **메일 본문 = HTML**(설정 편집기, `fmt: "html"`) — 저장·읽을 때마다 `store.sanitize_html`(허용 태그 p·br·strong·em·u·s·span·a·ul·ol·li 등,
style 은 color·background-color·font-size·font-weight·font-style·text-decoration·text-align 만, 링크는 http(s)/mailto, `&nbsp;` → 띄어쓰기, 빈 문단 = `<br>`).
예전 글·기본 문구(`fmt` 없음) = `text_to_html`(줄마다 문단, `**굵게**`, 주소 링크). 메일 글 버전·DM 대체 글·{이름} 찾기 = `html_to_text`.
`{이름}` 은 글자마다 서식이 달라도 `fill_html` 이 바꾼다. 메일 HTML 은 `<p>` 에 margin:0(메일 프로그램 문단 여백 없앰).
- **메일** = [고른 메일 보내기] → `db.claim_for_send`(고른 줄 중 메일·대기/실패만 '발송중'으로 한 UPDATE — 두 번 눌러도·두 사람이 눌러도 한 번) →
`send.send_batch`(백그라운드, **보내는 사람 본인 Gmail**, 한 사람에 한 통·1초 간격, 설정 사진 = 본문 아래 cid) → 보냄/실패 + `outreach_logs`.
Gmail 연결 없으면 409(화면이 [Gmail 연결] 안내), 끊기면 남은 줄 실패. 서버 재시작 때 남은 '발송중' = 실패(`release_stuck`).
- **인스타 DM = 반자동** — 인스타 공식 API 는 처음 연락하는 사람에게 DM 을 보낼 수 없다(상대가 먼저 보낸 24시간 안만, 자동 DM 은 약관 위반·계정 정지 위험).
[DM 보내기] = 그 사람 이름이 든 문구 복사 + `https://ig.me/m/계정` 새 탭(누르는 순간 — 문구는 리스트 데이터에 미리 담음) → 붙여 넣어 보낸 뒤 [보냄](`dm-sent`, 기록).
**DM 문구** = 설정 `dm_body`(`store.dm_text`, 최대 1000자 `DM_MAX`, `{이름}`, 별표만 뺌) — 비어 있으면 메일 본문 + 끝 문구. "이름 필요"도 구분별(`needs_name(t, kind)`).
- **설정** `/outreach/settings`(모듈 권한자 누구나): 메일 제목·본문(기본 = 미라네주방 공동구매 제안 문구, `store.DEFAULT_TEMPLATE`)·보내는 이름·끝 문구(수신 거부 안내 등)·인스타 DM 문구(2026-10-27)·
제목 앞 "(광고)" — 영리 목적 광고성 메일은 정보통신망법 제50조(제목 "(광고)"·수신 거부 방법) 대상일 수 있어 칸을 둠(법무 확인 권장).
본문 아래 사진 최대 10장(서버가 가로 700px JPEG 로 줄여 `outreach_images` 에, 순서 ◀▶). [기본 문구로 되돌리기] = 칸만(저장해야 적용).
**DM 문구** = 설정 `dm_body`(글, `store.dm_text`, 최대 1000자 `DM_MAX`, `{이름}`, 별표만 뺌) — 비어 있으면 메일 본문 글 + 끝 문구. "이름 필요"도 구분별(`needs_name(t, kind)`).
- **설정** `/outreach/settings`(모듈 권한자 누구나) — **세로 2단**: 왼쪽 메일(제목·"(광고)"·보내는 이름·본문 서식 편집기·끝 문구·본문 아래 사진),
오른쪽 인스타 DM(서식 없는 편집기·글자 수·[메일 본문 글 가져오기]), 위 막대 [저장]·[기본 문구로 되돌리기](칸만, 저장해야 적용) — 1100px 아래는 위아래.
입력 칸은 `form="otr-set-form"` 으로 위 막대 폼에 묶음(사진 폼과 겹치지 않게). 편집기 = Quill snow(글자 크기 px·굵게·기울임·밑줄·취소선·글자/배경 색·정렬·목록·링크·서식 지우기·되돌리기),
저장 = `getSemanticHTML()` → `body`(fmt=html), DM `getText()` → `dm_body`. **`{이름}` 빨강 굵게 = 화면에서만**(class `otr-nametag-on`, 서버 정리 때 class 가 빠져 메일에는 안 남음).
기본 본문 = 미라네주방 공동구매 제안 문구(`store.DEFAULT_TEMPLATE`, 글). "(광고)" — 영리 목적 광고성 메일은 정보통신망법 제50조 대상일 수 있어 칸을 둠(법무 확인 권장).
본문 아래 사진 최대 10장(서버가 가로 700px JPEG 로 줄여 `outreach_images` 에, 순서 ◀▶).
- 리스트 줄: 이름 바로 고치기(칸 떠나면 저장), [미리보기](메일 = 제목·HTML, DM = 글), 고른 줄 다시 대기·지우기(발송중은 못 지움), 걸러 보기(전체·메일·DM·대기·보냄·실패).
+3 -1
View File
@@ -48,8 +48,10 @@ class OutreachDBStore:
t = store.normalize_template(value)
if not t["subject"]:
raise ValueError("메일 제목을 쓰세요.")
if not t["body"].strip():
if not store.html_to_text(t["body"]).strip():
raise ValueError("본문을 쓰세요.")
if len(t["body"]) > store.BODY_MAX:
raise ValueError("본문이 너무 깁니다(서식 포함) — 줄여 주세요.")
with self._pool.connection() as conn:
conn.execute(
"INSERT INTO outreach_settings (key, value, updated_by, updated_at) VALUES ('template', %s, %s, now()) "
+8 -4
View File
@@ -136,7 +136,8 @@ def index(request: Request) -> Any:
rows = [_view(r, template) for r in st.list_recipients()]
return _render(request, "outreach/index.html", user, {
"page_title": "안내문 발송", "page_subtitle": "메일 일괄 발송 · 인스타 DM",
"template": template, "images": st.list_images(), "rows": rows, "logs": st.list_logs(limit=50),
"template": template, "body_text": store.html_to_text(template["body"]), "needs_name": store.needs_name(template),
"images": st.list_images(), "rows": rows, "logs": st.list_logs(limit=50),
"gmail": _gmail_state(request, user), "msg": request.query_params.get("msg", ""),
})
@@ -149,19 +150,22 @@ def settings_page(request: Request) -> Any:
st, user = got
return _render(request, "outreach/settings.html", user, {
"page_title": "안내문 발송 — 설정", "page_subtitle": "메일 제목 · 본문 · DM 문구 · 사진",
"template": st.get_template(), "default": store.DEFAULT_TEMPLATE, "images": st.list_images(),
"template": st.get_template(), "default": store.normalize_template(None), "images": st.list_images(),
"max_images": 10, "dm_max": store.DM_MAX, "msg": request.query_params.get("msg", ""),
})
@router.post("/settings")
def settings_save(request: Request, subject: str = Form(""), body: str = Form(""), sender_name: str = Form(""),
footer: str = Form(""), ad_label: str = Form(""), dm_body: str = Form("")) -> RedirectResponse:
footer: str = Form(""), ad_label: str = Form(""), dm_body: str = Form(""),
fmt: str = Form("text")) -> RedirectResponse:
"""body = 설정 화면 편집기 HTML(fmt=html, 서버가 다시 정리) — fmt 없이 오면 글로 본다."""
user = _user(request)
st = _db(request)
try:
st.save_template({"subject": subject, "body": body, "sender_name": sender_name, "footer": footer, "dm_body": dm_body,
"ad_label": ad_label in ("1", "on", "true")}, by=user["email"])
"ad_label": ad_label in ("1", "on", "true"), "fmt": "html" if fmt == "html" else "text"},
by=user["email"])
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc))
return RedirectResponse(url="/outreach/settings?" + urlencode({"msg": "설정을 저장했습니다."}), status_code=303)
+160 -18
View File
@@ -1,14 +1,16 @@
"""안내문 발송 — 순수 함수(DB 없음): 주소 판별(이메일 / 인스타그램), 리스트 붙여넣기 해석, {이름} 바꾸기, 메일 HTML·DM 글.
- 주소를 보고 정한다: `name@domain.tld` = 메일, `@계정`·`instagram.com/계정`·`ig.me/m/계정`·계정명만(영문·숫자·.·_) = 인스타 DM.
- 본문 `{이름}` = 그 줄 이름. `**굵게**` 는 메일에서 굵은 글씨, DM 에서는 별표만 뺀다(인스타는 서식이 없음). 주소(https://…)는 메일에서 링크.
- DM 글 = 설정 `dm_body`(인스타 DM 용 문구). 비어 있으면 메일 본문 + 끝 문구.
- 본문 `{이름}` = 그 줄 이름. 메일 본문 = 설정 화면 편집기의 HTML(`fmt: "html"`) — 저장·읽을 때마다 `sanitize_html`(허용 태그·스타일만).
예전 글·기본 문구(`fmt` 없음 = 글)는 `text_to_html`(`**굵게**` → 굵게, 주소 → 링크, 줄마다 문단).
- DM 글 = 설정 `dm_body`(인스타 DM 용 글, 서식 없음). 비어 있으면 메일 본문 글 + 끝 문구.
"""
from __future__ import annotations
import re
from html import escape
from html.parser import HTMLParser
from typing import Any
NAME_TAG = "{이름}"
@@ -29,6 +31,7 @@ DEFAULT_TEMPLATE: dict[str, Any] = {
"ad_label": False,
"footer": "",
"dm_body": "",
"fmt": "text", # body 형식 — 기본 문구는 글, 설정 화면에서 저장하면 "html"
"body": """안녕하세요, {이름}님.
주방의 본질을 지키며 6년간 묵묵히 300억 매출의 신화를 써온 **'미라네주방'**입니다.
저희는 지난 6년간 제품력 하나로 국내/해외 800만 개 판매를 돌파하고 호주, 동남아 등 글로벌 시장에서 인정받았습니다.
@@ -62,7 +65,7 @@ DEFAULT_TEMPLATE: dict[str, Any] = {
미라네주방 팀 드림
https://miras.co.kr/""",
}
SUBJECT_MAX, BODY_MAX, FOOTER_MAX = 200, 20000, 2000
SUBJECT_MAX, BODY_MAX, FOOTER_MAX = 200, 100000, 2000 # BODY_MAX = 정리한 HTML 길이
DM_MAX = 1000 # 인스타 DM 한 통 글자 수 한도
@@ -148,7 +151,9 @@ def normalize_template(value: dict[str, Any] | None) -> dict[str, Any]:
if k in v:
v[k] = val
v["subject"] = str(v["subject"] or "").strip()[:SUBJECT_MAX]
v["body"] = str(v["body"] or "").replace("\r\n", "\n")[:BODY_MAX]
body = str(v["body"] or "")[:BODY_MAX * 3]
v["body"] = sanitize_html(body if v["fmt"] == "html" else text_to_html(body))
v["fmt"] = "html"
v["footer"] = str(v["footer"] or "").replace("\r\n", "\n").strip()[:FOOTER_MAX]
v["dm_body"] = str(v["dm_body"] or "").replace("\r\n", "\n").strip()[:DM_MAX]
v["sender_name"] = str(v["sender_name"] or "").strip()[:60]
@@ -160,9 +165,10 @@ def needs_name(template: dict[str, Any], kind: str = "email") -> bool:
"""그 구분(메일/DM)으로 갈 글에 {이름}이 있는가 — DM 은 DM 문구(없으면 메일 본문)만 본다."""
if kind == "instagram" and (template.get("dm_body") or "").strip():
return NAME_TAG in template["dm_body"]
body = html_to_text(template.get("body") or "")
if kind == "instagram":
return NAME_TAG in (template.get("body") or "") or NAME_TAG in (template.get("footer") or "")
return NAME_TAG in (template.get("subject") or "") or NAME_TAG in (template.get("body") or "")
return NAME_TAG in body or NAME_TAG in (template.get("footer") or "")
return NAME_TAG in (template.get("subject") or "") or NAME_TAG in body
def fill(text: str, name: str) -> str:
@@ -174,17 +180,13 @@ def subject_for(template: dict[str, Any], name: str) -> str:
return ("(광고) " + s) if template.get("ad_label") and not s.startswith("(광고)") else s
def _body_text(template: dict[str, Any], name: str) -> str:
body = fill(template.get("body") or "", name).rstrip()
def plain_text(template: dict[str, Any], name: str) -> str:
"""메일 글 부분(HTML 메일의 글 버전)·DM 문구가 없을 때의 DM 글 — 본문 글 + 끝 문구."""
body = fill(html_to_text(template.get("body") or ""), name).rstrip()
footer = (template.get("footer") or "").strip()
return body + ("\n\n" + fill(footer, name) if footer else "")
def plain_text(template: dict[str, Any], name: str) -> str:
"""메일 글 부분·DM 글 — **굵게** 표시는 별표만 뺀다."""
return re.sub(r"\*\*(.+?)\*\*", r"\1", _body_text(template, name))
def dm_text(template: dict[str, Any], name: str) -> str:
"""인스타 DM 글 — DM 문구가 있으면 그것, 없으면 메일 글(plain_text). **굵게** 는 별표만 뺀다."""
dm = (template.get("dm_body") or "").strip()
@@ -193,18 +195,158 @@ def dm_text(template: dict[str, Any], name: str) -> str:
return re.sub(r"\*\*(.+?)\*\*", r"\1", fill(dm, name))
# ── 메일 본문 HTML ─────────────────────────────────────────
_URL_RE = re.compile(r"https?://[^\s<>\"']+")
_ALLOWED_TAGS = {"p", "br", "strong", "b", "em", "i", "u", "s", "strike", "span", "a", "ul", "ol", "li",
"h1", "h2", "h3", "blockquote", "sub", "sup"}
_DROP_WITH_CONTENT = {"script", "style", "iframe", "object", "head", "title", "template", "noscript", "svg", "math",
"textarea", "select"}
_STYLE_PROPS = {"color", "background-color", "font-size", "font-weight", "font-style", "text-decoration", "text-align"}
_STYLE_VALUE_RE = re.compile(r"^[#\w\s.,%()-]{1,60}$")
# {이름} — 편집기에서 글자마다 서식이 달라 태그가 끼어도 찾는다(태그는 남기고 글자만 이름으로)
_NAME_IN_HTML_RE = re.compile(r"\{((?:<[^>]*>)*)이((?:<[^>]*>)*)름((?:<[^>]*>)*)\}")
def _clean_style(value: str) -> str:
out = []
for decl in value.split(";"):
prop, _, val = decl.partition(":")
prop, val = prop.strip().lower(), val.strip()
if prop in _STYLE_PROPS and _STYLE_VALUE_RE.match(val) and not re.search(r"url|expression", val, re.I):
out.append(f"{prop}: {val}")
return "; ".join(out)
class _Sanitizer(HTMLParser):
"""허용 태그·속성(style 은 글자 서식만, a 는 http(s)/mailto 링크만)만 남기고 글은 escape. 태그 짝은 맞춰 닫는다.
편집기(Quill getSemanticHTML)가 띄어쓰기를 &nbsp; 로 내보내 보통 띄어쓰기로 바꾼다(메일은 pre-wrap 이라 여러 칸도 그대로)."""
def __init__(self) -> None:
super().__init__(convert_charrefs=True)
self.out: list[str] = []
self.stack: list[str] = []
self.skip = 0
self.empty_p = False # 지금 연 <p> 에 아직 글이 없다 — 닫을 때 <br> 을 넣어 빈 줄 높이를 지킨다
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
if tag in _DROP_WITH_CONTENT:
self.skip += 1
return
if self.skip or tag not in _ALLOWED_TAGS:
return
if tag == "br":
self.out.append("<br>")
self.empty_p = False
return
a = {k: v or "" for k, v in attrs}
extra = ""
style = _clean_style(a.get("style", ""))
if style:
extra += f' style="{escape(style)}"'
href = a.get("href", "").strip()
if tag == "a" and re.match(r"^(https?:|mailto:)", href, re.I):
extra += f' href="{escape(href)}"'
self.out.append(f"<{tag}{extra}>")
self.stack.append(tag)
if tag == "p":
self.empty_p = True
def handle_endtag(self, tag: str) -> None:
if tag in _DROP_WITH_CONTENT:
self.skip = max(0, self.skip - 1)
return
if self.skip or tag not in self.stack:
return
while self.stack:
t = self.stack.pop()
if t == "p" and self.empty_p:
self.out.append("<br>")
self.empty_p = False
self.out.append(f"</{t}>")
if t == tag:
break
def handle_data(self, data: str) -> None:
if self.skip:
return
text = data.replace("\r", "").replace("\n", " ").replace("\xa0", " ")
if not text.strip() and (not self.stack or self.stack[-1] in ("ul", "ol")):
return
if text:
self.out.append(escape(text, quote=False))
self.empty_p = False
def result(self) -> str:
self.close()
while self.stack:
self.handle_endtag(self.stack[-1])
return "".join(self.out)
def sanitize_html(html: str) -> str:
p = _Sanitizer()
p.feed(str(html or ""))
return p.result()
def text_to_html(text: str) -> str:
"""글(예전 본문·기본 문구) → 본문 HTML — 줄마다 문단, 빈 줄 = <p><br></p>, **굵게** → <strong>, 주소 → 링크."""
out = []
for line in str(text or "").replace("\r\n", "\n").rstrip("\n").split("\n"):
h = re.sub(r"\*\*(.+?)\*\*", r"<strong>\1</strong>", escape(line, quote=False))
h = _URL_RE.sub(lambda m: f'<a href="{m.group(0)}">{m.group(0)}</a>', h)
out.append(f"<p>{h or '<br>'}</p>")
return "".join(out)
class _Text(HTMLParser):
def __init__(self) -> None:
super().__init__(convert_charrefs=True)
self.parts: list[str] = []
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
if tag == "br":
self.parts.append("\x00") # 문단 끝 바로 앞의 <br>(빈 줄 표시)은 줄을 하나 더 만들지 않는다
elif tag == "li":
self.parts.append("- ")
def handle_endtag(self, tag: str) -> None:
if tag in ("p", "li", "h1", "h2", "h3", "blockquote"):
if self.parts and self.parts[-1] == "\x00":
self.parts.pop()
self.parts.append("\n")
def handle_data(self, data: str) -> None:
self.parts.append(data.replace("\xa0", " "))
def html_to_text(html: str) -> str:
"""본문 HTML → 글(메일 글 버전·DM·{이름} 찾기·리스트 화면 요약)."""
p = _Text()
p.feed(str(html or ""))
p.close()
return "".join(p.parts).replace("\x00", "\n").rstrip()
def fill_html(html: str, name: str) -> str:
return _NAME_IN_HTML_RE.sub(lambda m: escape(str(name or "").strip()) + m.group(1) + m.group(2) + m.group(3), str(html or ""))
def _p_margin(html: str) -> str:
"""메일 프로그램은 <p> 에 위아래 여백을 줘 편집기보다 줄 간격이 벌어진다 — margin:0 을 붙인다."""
return re.sub(r'<p( style=")?', lambda m: '<p style="margin:0;' if m.group(1) else '<p style="margin:0"', html)
def html_body(template: dict[str, Any], name: str, image_cids: list[str] | None = None) -> str:
"""메일 HTML — 사용자 글은 늘 escape, **굵게** → <b>, 주소 → 링크, 줄바꿈 그대로, 사진은 본문 아래(cid)."""
text = escape(_body_text(template, name))
text = re.sub(r"\*\*(.+?)\*\*", r"<b>\1</b>", text)
text = _URL_RE.sub(lambda m: f'<a href="{m.group(0)}" style="color:#1a56db">{m.group(0)}</a>', text)
"""메일 HTML — 본문(정리된 편집기 HTML, {이름} 바꿈) + 끝 문구(글 → escape·링크) + 사진은 본문 아래(cid)."""
body = fill_html(sanitize_html(template.get("body") or ""), name)
footer = (template.get("footer") or "").strip()
if footer:
body += "<p><br></p>" + text_to_html(fill(footer, name))
imgs = "".join(f'<p style="margin:12px 0 0"><img src="cid:{c}" alt="" style="max-width:100%;height:auto;border-radius:6px"></p>'
for c in (image_cids or []))
return ('<div style="font-family:Pretendard,\'Malgun Gothic\',sans-serif;font-size:14px;line-height:1.7;color:#111;white-space:pre-wrap">'
f"{text}</div>{imgs}")
f"{_p_margin(body)}</div>{imgs}")
def dm_link(handle: str) -> str:
@@ -2,10 +2,10 @@
{#- 안내문 발송(2026-10-27) — 리스트(주소 + 이름) → 메일은 [선택한 메일 보내기](본인 Gmail, 한 사람에 한 통), 인스타는 [DM 보내기](문구 복사 + DM 창)
→ 보낸 뒤 [보냄]. 주소를 보고 메일/DM 을 정한다(store.detect). 본문 {이름} = 그 줄 이름. -#}
{% block head_extra %}<link rel="stylesheet" href="/static/outreach.css?v=20261027b" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/outreach.css?v=20261027c" />{% endblock %}
{% block content %}
<section class="otr" id="otr" data-needs-name="{{ '1' if '{이름}' in (template.subject ~ template.body) else '' }}">
<section class="otr" id="otr" data-needs-name="{{ '1' if needs_name else '' }}">
<div class="otr-top">
<div class="otr-top-main">
@@ -31,7 +31,7 @@
<div class="erp-card otr-tpl">
<div class="otr-tpl-head"><b>보낼 내용</b><span class="erp-muted">(설정에서 바꿉니다)</span></div>
<div class="otr-tpl-subject">{% if template.ad_label %}(광고) {% endif %}{{ template.subject }}</div>
<div class="otr-tpl-body">{{ template.body[:160] }}{% if template.body | length > 160 %}…{% endif %}</div>
<div class="otr-tpl-body">{{ body_text[:160] }}{% if body_text | length > 160 %}…{% endif %}</div>
<div class="erp-muted otr-tpl-meta">보내는 이름 {{ template.sender_name or '—' }} · 본문 아래 사진 {{ images | length }}장 · <code>{이름}</code> = 줄마다 그 사람 이름</div>
</div>
@@ -99,4 +99,4 @@
<script type="application/json" id="otr-data">{{ {"rows": rows} | tojson }}</script>
{% endblock %}
{% block scripts %}<script src="/static/outreach.js?v=20261027b" defer></script>{% endblock %}
{% block scripts %}<script src="/static/outreach.js?v=20261027c" defer></script>{% endblock %}
@@ -1,67 +1,93 @@
{% extends "erp_base.html" %}
{#- 안내문 발송 설정(2026-10-27) — 메일 제목·본문({이름})·보내는 이름·끝 문구·(광고) 표시 + 본문 아래 사진.
인스타 DM 문구는 따로(비우면 메일 본문 + 끝 문구로). -#}
{% block head_extra %}<link rel="stylesheet" href="/static/outreach.css?v=20261027b" />{% endblock %}
{#- 안내문 발송 설정(2026-10-27) — 화면 세로 2단: 왼쪽 = 메일(제목·(광고)·보내는 이름·본문 서식 편집기·끝 문구·본문 아래 사진),
오른쪽 = 인스타 DM(서식 없는 편집기, 비우면 메일 본문 글 + 끝 문구). 두 편집기 모두 {이름} = 빨강 굵게(화면에서만).
편집기 = Quill(/static/vendor/quill). 입력 칸은 form="otr-set-form" 으로 위 막대의 저장 폼에 묶는다(사진 폼과 겹치지 않게). -#}
{% block head_extra %}
<link rel="stylesheet" href="/static/vendor/quill/quill.snow.css" />
<link rel="stylesheet" href="/static/outreach.css?v=20261027c" />
{% endblock %}
{% block content %}
<section class="otr otr-settings">
<div class="otr-top"><div class="otr-top-main"><a class="erp-btn erp-btn-outline" href="/outreach/">◀ 리스트</a></div></div>
<form method="post" action="/outreach/settings" id="otr-set-form" class="otr-set-bar">
<a class="erp-btn erp-btn-outline" href="/outreach/">◀ 리스트</a>
<span class="erp-muted otr-set-saved">{% if template.is_default %}기본 문구(아직 저장 안 함){% else %}마지막 저장 {{ template.updated_by }} · {{ template.updated_at[:16] | replace('T', ' ') }}{% endif %}</span>
<span class="otr-set-bar-gap"></span>
<input type="hidden" name="fmt" value="html" />
<input type="hidden" name="body" id="otr-body-input" />
<input type="hidden" name="dm_body" id="otr-dm-input" />
<button type="button" class="erp-btn erp-btn-outline" id="otr-default" title="칸만 바꿉니다 — [저장]을 눌러야 적용">기본 문구로 되돌리기</button>
<button type="submit" class="erp-btn erp-btn-primary">저장</button>
</form>
{% if msg %}<p class="otr-msg" role="status">{{ msg }}</p>{% endif %}
<form method="post" action="/outreach/settings" class="erp-card otr-set-card" id="otr-set-form">
<div class="otr-tpl-head"><b>메일 제목 · 본문</b>
<span class="erp-muted">{% if template.is_default %}기본 문구(아직 저장 안 함){% else %}마지막 저장 {{ template.updated_by }} · {{ template.updated_at[:16] | replace('T', ' ') }}{% endif %}</span></div>
<label class="erp-field otr-field"><span>메일 제목</span>
<input class="erp-input" type="text" name="subject" maxlength="200" required value="{{ template.subject }}" /></label>
<label class="otr-check"><input type="checkbox" name="ad_label" value="1"{% if template.ad_label %} checked{% endif %} />
제목 앞에 <b>(광고)</b> 붙이기 <span class="erp-muted">— 영리 목적 광고성 메일은 정보통신망법 제50조에 따라 제목 앞 "(광고)"·수신 거부 방법을 적어야 합니다(법무 확인 권장)</span></label>
<label class="erp-field otr-field"><span>보내는 이름</span>
<input class="erp-input" type="text" name="sender_name" maxlength="60" value="{{ template.sender_name }}" placeholder="받는 사람 메일함에 보이는 이름" /></label>
<label class="erp-field otr-field"><span>본문 <small class="erp-muted"><code>{이름}</code> = 그 사람 이름 · <code>**굵게**</code> = 메일에서 굵은 글씨(DM 은 별표만 빠짐) · 주소는 메일에서 링크</small></span>
<textarea class="erp-input otr-body" name="body" rows="24" required id="otr-body">{{ template.body }}</textarea></label>
<label class="erp-field otr-field"><span>끝 문구 <small class="erp-muted">(본문 맨 아래 — 수신 거부 안내 등, 비워도 됨)</small></span>
<textarea class="erp-input" name="footer" rows="2" maxlength="2000" placeholder="예: 더 이상 받기를 원하지 않으시면 이 메일에 '수신 거부'라고 회신해 주세요.">{{ template.footer }}</textarea></label>
<div class="otr-split">
{#- 왼쪽 — 메일 -#}
<div class="otr-col">
<div class="erp-card otr-set-card">
<div class="otr-col-head"><span class="otr-kind is-email">메일</span><b>이메일 안내문</b>
<span class="erp-muted">[고른 메일 보내기]로 내 Gmail 에서 한 사람에 한 통씩</span></div>
<label class="erp-field otr-field"><span>메일 제목</span>
<input class="erp-input" type="text" name="subject" form="otr-set-form" maxlength="200" required value="{{ template.subject }}" /></label>
<label class="otr-check"><input type="checkbox" name="ad_label" form="otr-set-form" value="1"{% if template.ad_label %} checked{% endif %} />
<span>제목 앞에 <b>(광고)</b> 붙이기 <span class="erp-muted">— 영리 목적 광고성 메일은 정보통신망법 제50조에 따라 제목 앞 "(광고)"·수신 거부 방법을 적어야 합니다(법무 확인 권장)</span></span></label>
<label class="erp-field otr-field"><span>보내는 이름</span>
<input class="erp-input" type="text" name="sender_name" form="otr-set-form" maxlength="60" value="{{ template.sender_name }}" placeholder="받는 사람 메일함에 보이는 이름" /></label>
<div class="erp-field otr-field"><span>본문 <small class="erp-muted"><code class="otr-tag">{이름}</code> = 그 사람 이름(빨강은 이 화면에서만 — 메일에는 이름이 본문 서식대로) · 되돌리기 Ctrl+Z</small></span>
<div class="otr-editor" id="otr-body-editor"></div></div>
<label class="erp-field otr-field"><span>끝 문구 <small class="erp-muted">(본문 맨 아래 — 수신 거부 안내 등, 비워도 됨)</small></span>
<textarea class="erp-input" name="footer" form="otr-set-form" rows="2" maxlength="2000" placeholder="예: 더 이상 받기를 원하지 않으시면 이 메일에 '수신 거부'라고 회신해 주세요.">{{ template.footer }}</textarea></label>
</div>
<div class="otr-tpl-head otr-tpl-sub"><b>인스타 DM 문구</b>
<span class="erp-muted">[DM 보내기]를 누르면 복사되는 글 — 비워 두면 메일 본문 + 끝 문구가 그대로 복사됩니다</span></div>
<label class="erp-field otr-field"><span>DM 문구 <small class="erp-muted"><code>{이름}</code> = 그 사람 이름 · 인스타는 서식이 없어 <code>**굵게**</code>는 별표만 빠짐 · 사진은 붙지 않음</small></span>
<textarea class="erp-input otr-body" name="dm_body" rows="10" maxlength="{{ dm_max }}" id="otr-dm-body"
placeholder="예: 안녕하세요, {이름}님! 누적 800만 개 판매 미라클통 '미라네주방'입니다. {이름}님과 공동구매를 함께하고 싶어 연락드렸어요. 자세한 제안서는 메일로 보내드릴 수 있습니다 — 편하신 메일 주소 알려주시면 감사하겠습니다 :)">{{ template.dm_body }}</textarea>
<small class="erp-muted otr-count" id="otr-dm-count" data-max="{{ dm_max }}"></small></label>
<div class="otr-set-actions">
<button type="submit" class="erp-btn erp-btn-primary">저장</button>
<button type="button" class="erp-btn erp-btn-outline" id="otr-default">기본 문구로 되돌리기</button>
<span class="erp-muted">되돌리기는 칸만 바꿉니다 — [저장]을 눌러야 적용</span>
</div>
</form>
<div class="erp-card otr-set-card" id="images">
<div class="otr-tpl-head"><b>본문 아래 사진</b><span class="erp-muted">메일 본문 맨 아래에 순서대로(최대 {{ max_images }}장, 가로 700px 로 줄여 저장). DM 에는 붙지 않습니다.</span></div>
<div class="otr-images">
{% for im in images %}
<figure class="otr-image">
<img src="/outreach/images/{{ im.id }}" alt="{{ im.filename }}" loading="lazy" />
<figcaption>{{ loop.index }}. {{ im.filename }}</figcaption>
<div class="otr-image-acts">
{% if not loop.first %}<form method="post" action="/outreach/settings/images/{{ im.id }}/move"><input type="hidden" name="direction" value="-1" /><button class="erp-btn erp-btn-outline erp-btn-sm" title="앞으로">◀</button></form>{% endif %}
{% if not loop.last %}<form method="post" action="/outreach/settings/images/{{ im.id }}/move"><input type="hidden" name="direction" value="1" /><button class="erp-btn erp-btn-outline erp-btn-sm" title="뒤로">▶</button></form>{% endif %}
<form method="post" action="/outreach/settings/images/{{ im.id }}/delete" onsubmit="return confirm('이 사진을 뺄까요?');"><button class="erp-btn erp-btn-outline erp-btn-sm otr-danger">빼기</button></form>
<div class="erp-card otr-set-card" id="images">
<div class="otr-tpl-head"><b>본문 아래 사진</b><span class="erp-muted">메일 본문 맨 아래에 순서대로(최대 {{ max_images }}장, 가로 700px 로 줄여 저장). DM 에는 붙지 않습니다.</span></div>
<div class="otr-images">
{% for im in images %}
<figure class="otr-image">
<img src="/outreach/images/{{ im.id }}" alt="{{ im.filename }}" loading="lazy" />
<figcaption>{{ loop.index }}. {{ im.filename }}</figcaption>
<div class="otr-image-acts">
{% if not loop.first %}<form method="post" action="/outreach/settings/images/{{ im.id }}/move"><input type="hidden" name="direction" value="-1" /><button class="erp-btn erp-btn-outline erp-btn-sm" title="앞으로">◀</button></form>{% endif %}
{% if not loop.last %}<form method="post" action="/outreach/settings/images/{{ im.id }}/move"><input type="hidden" name="direction" value="1" /><button class="erp-btn erp-btn-outline erp-btn-sm" title="뒤로">▶</button></form>{% endif %}
<form method="post" action="/outreach/settings/images/{{ im.id }}/delete" onsubmit="return confirm('이 사진을 뺄까요?');"><button class="erp-btn erp-btn-outline erp-btn-sm otr-danger">빼기</button></form>
</div>
</figure>
{% else %}
<p class="erp-muted">사진이 없습니다.</p>
{% endfor %}
</div>
</figure>
{% else %}
<p class="erp-muted">사진이 없습니다.</p>
{% endfor %}
{% if images | length < max_images %}
<form method="post" action="/outreach/settings/images" enctype="multipart/form-data" class="otr-upload">
<input type="file" name="files" accept="image/jpeg,image/png,image/webp,image/gif" multiple required />
<button type="submit" class="erp-btn erp-btn-primary">사진 넣기</button>
</form>
{% endif %}
</div>
</div>
{#- 오른쪽 — 인스타 DM -#}
<div class="otr-col">
<div class="erp-card otr-set-card otr-dm-card">
<div class="otr-col-head"><span class="otr-kind is-instagram">DM</span><b>인스타 DM 문구</b>
<span class="erp-muted">[DM 보내기]를 누르면 복사되는 글</span></div>
<p class="erp-muted otr-note">인스타 DM 은 글자 서식·사진이 없어 글만 씁니다. <code class="otr-tag">{이름}</code> = 그 사람 이름.
비워 두면 메일 본문 글 + 끝 문구가 그대로 복사됩니다.</p>
<div class="otr-editor otr-editor-plain" id="otr-dm-editor"
data-placeholder="예: 안녕하세요, {이름}님! 누적 800만 개 판매 미라클통 '미라네주방'입니다. {이름}님과 공동구매를 함께하고 싶어 연락드렸어요. 자세한 제안서는 메일로 보내드릴 수 있습니다 — 편하신 메일 주소 알려주시면 감사하겠습니다 :)"></div>
<div class="otr-dm-foot">
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" id="otr-dm-from-mail">메일 본문 글 가져오기</button>
<small class="erp-muted otr-count" id="otr-dm-count" data-max="{{ dm_max }}"></small>
</div>
</div>
</div>
{% if images | length < max_images %}
<form method="post" action="/outreach/settings/images" enctype="multipart/form-data" class="otr-upload">
<input type="file" name="files" accept="image/jpeg,image/png,image/webp,image/gif" multiple required />
<button type="submit" class="erp-btn erp-btn-primary">사진 넣기</button>
</form>
{% endif %}
</div>
</section>
<script type="application/json" id="otr-default-data">{{ default | tojson }}</script>
<script type="application/json" id="otr-current-data">{{ {"body": template.body, "dm_body": template.dm_body} | tojson }}</script>
{% endblock %}
{% block scripts %}<script src="/static/outreach.js?v=20261027b" defer></script>{% endblock %}
{% block scripts %}
<script src="/static/vendor/quill/quill.js"></script>
<script src="/static/outreach.js?v=20261027c" defer></script>
{% endblock %}
+40 -5
View File
@@ -65,12 +65,47 @@
.otr-set-card { display: flex; flex-direction: column; gap: 10px; }
.otr-field { display: flex; flex-direction: column; gap: 4px; }
.otr-field .erp-input { width: 100%; min-width: 0; box-sizing: border-box; }
.otr-body { font-size: 14px; line-height: 1.6; resize: vertical; }
.otr-tpl-sub { margin: 10px 0 0; padding-top: 14px; border-top: 1px solid var(--color-subtle-ash, #e5e5e5); }
.otr-count { align-self: flex-end; font-size: 12px; }
.otr-count.is-over { color: #c0392b; }
.otr-count { font-size: 12px; }
.otr-count.is-over { color: #c22b10; font-weight: 700; }
.otr-check { display: flex; align-items: baseline; gap: 6px; font-size: 13px; }
.otr-set-actions { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
/* 설정 — 위 저장 막대(스크롤해도 보임) + 세로 2단(왼쪽 메일 | 오른쪽 DM), 좁으면 위아래 */
.otr-set-bar { position: sticky; top: 0; z-index: 20; display: flex; align-items: center; gap: 8px; flex-wrap: wrap; margin: 0;
padding: 10px 14px; background: #fff; border: 1px solid #e3e5e8; border-radius: 10px; box-shadow: 0 2px 8px rgba(15, 23, 42, .06); }
.otr-set-saved { font-size: 12px; }
.otr-set-bar-gap { flex: 1; }
.otr-split { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 16px; align-items: start; }
.otr-col { display: flex; flex-direction: column; gap: 16px; min-width: 0; }
.otr-col-head { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; font-size: 15px; padding-bottom: 10px; border-bottom: 1px solid #eef0f2; }
.otr-col-head .erp-muted { font-size: 12px; }
.otr-dm-card { position: sticky; top: 72px; }
.otr-note { margin: 0; font-size: 12.5px; line-height: 1.6; }
.otr-dm-foot { display: flex; align-items: center; justify-content: space-between; gap: 8px; flex-wrap: wrap; }
.otr-tag { color: #e11d48; font-weight: 700; }
@media (max-width: 1100px) {
.otr-split { grid-template-columns: minmax(0, 1fr); }
.otr-dm-card { position: static; }
}
/* 편집기(Quill snow) — 메일과 같은 글꼴·크기·줄 간격, {이름} 빨강 굵게(화면에서만) */
.otr-settings .ql-toolbar.ql-snow { border-color: #d8dce2; border-radius: 8px 8px 0 0; background: #fafbfc; font-family: inherit; }
.otr-settings .ql-toolbar.ql-snow .ql-formats { margin-right: 8px; }
.otr-editor.ql-container.ql-snow { border-color: #d8dce2; border-radius: 0 0 8px 8px; font-family: Pretendard, 'Malgun Gothic', sans-serif; font-size: 14px; }
.otr-editor-plain.ql-container.ql-snow { border-top: 1px solid #d8dce2; border-radius: 8px; }
.otr-editor .ql-editor { min-height: 420px; max-height: 68vh; overflow-y: auto; line-height: 1.7; color: #111; }
.otr-editor-plain .ql-editor { min-height: 320px; }
.otr-editor .ql-editor.ql-blank::before { font-style: normal; color: #9aa1aa; }
.otr-editor .otr-nametag-on { color: #e11d48 !important; font-weight: 700 !important; }
.otr-settings .ql-snow .ql-picker.ql-size { width: 76px; }
.otr-settings .ql-snow .ql-picker.ql-size .ql-picker-label::before,
.otr-settings .ql-snow .ql-picker.ql-size .ql-picker-item::before { content: "기본"; }
.otr-settings .ql-snow .ql-picker.ql-size .ql-picker-label[data-value]::before,
.otr-settings .ql-snow .ql-picker.ql-size .ql-picker-item[data-value]::before { content: attr(data-value); }
.otr-settings .ql-toolbar .ql-undo, .otr-settings .ql-toolbar .ql-redo { font-size: 17px; line-height: 1; color: #444; }
.otr-settings .ql-snow .ql-tooltip { z-index: 5; }
.otr-settings .ql-snow .ql-tooltip::before { content: "링크:"; }
.otr-settings .ql-snow .ql-tooltip[data-mode=link]::before { content: "링크 주소:"; }
.otr-settings .ql-snow .ql-tooltip a.ql-action::after { content: "고치기"; }
.otr-settings .ql-snow .ql-tooltip a.ql-remove::before { content: "빼기"; }
.otr-settings .ql-snow .ql-tooltip.ql-editing a.ql-action::after { content: "저장"; }
.otr-images { display: flex; gap: 12px; flex-wrap: wrap; }
.otr-image { margin: 0; width: 200px; border: 1px solid #e3e5e8; border-radius: 8px; padding: 8px; display: flex; flex-direction: column; gap: 6px; }
.otr-image img { width: 100%; height: 150px; object-fit: cover; border-radius: 6px; background: #f6f7f9; }
+127 -23
View File
@@ -1,7 +1,7 @@
/* 안내문 발송(2026-10-27) — 리스트 화면: 붙여 넣기 → 미리보기(메일/DM/오류) → 추가, 걸러 보기, 이름 고치기,
메일 = 고른 줄 [고른 메일 보내기](서버가 본인 Gmail 로 한 통씩, 보내는 동안 2초마다 다시 읽음),
DM = [DM 보내기](그 사람 이름이 들어간 문구를 클립보드에 + ig.me DM 창을 새 탭) → [보냄].
설정 화면 = [기본 문구로 되돌리기], DM 문구 글자 수. */
설정 화면 = 세로 2단(메일 | DM) — 메일 본문 서식 편집기·DM 편집기(Quill), {이름} 빨강 굵게, [기본 문구로 되돌리기], DM 글자 수. */
(function () {
"use strict";
@@ -39,31 +39,135 @@
}
// ── 설정 화면 ──
const defBtn = document.getElementById("otr-default");
if (defBtn) {
defBtn.addEventListener("click", function () {
let d = {};
try { d = JSON.parse(document.getElementById("otr-default-data").textContent); } catch (_) { d = {}; }
if (!confirm("제목·본문·보내는 이름·끝 문구·DM 문구를 기본 문구로 바꿀까요? ([저장]을 눌러야 적용)")) return;
const f = document.getElementById("otr-set-form");
f.subject.value = d.subject || "";
f.body.value = d.body || "";
f.sender_name.value = d.sender_name || "";
f.footer.value = d.footer || "";
f.dm_body.value = d.dm_body || "";
f.ad_label.checked = !!d.ad_label;
const setForm = document.getElementById("otr-set-form");
if (setForm) {
if (window.Quill) initSettings(window.Quill, setForm);
else toast("편집기를 불러오지 못했습니다 — 새로 고침해 주세요.", true);
}
// 메일 본문 = 서식 편집기(글자 크기·굵게·기울임·밑줄·취소선·글자/배경 색·정렬·목록·링크·서식 지우기·되돌리기),
// DM = 서식 없는 편집기. 두 편집기 모두 {이름} = 빨강 굵게(class 만 — 저장하면 서버가 class 를 지워 메일에는 안 남음).
// 저장 = 메일 본문 getSemanticHTML() → body(fmt=html, 서버가 허용 태그만 남김), DM getText() → dm_body.
function initSettings(Quill, form) {
const TAG = "{이름}";
const SIZES = ["12px", "16px", "18px", "20px", "24px", "30px"]; // 없음(false) = 기본 14px
const Parchment = Quill.import("parchment");
Quill.register(new Parchment.ClassAttributor("nametag", "otr-nametag", { scope: Parchment.Scope.INLINE }), true);
const Size = Quill.import("attributors/style/size");
Size.whitelist = SIZES;
Quill.register(Size, true);
Quill.register(Quill.import("attributors/style/align"), true);
function readJson(id) {
try { return JSON.parse(document.getElementById(id).textContent) || {}; } catch (_) { return {}; }
}
const mail = new Quill("#otr-body-editor", {
theme: "snow", placeholder: "메일 본문",
modules: {
history: { userOnly: true },
toolbar: {
container: [
[{ size: [false].concat(SIZES) }],
["bold", "italic", "underline", "strike"],
[{ color: [] }, { background: [] }],
[{ align: [] }],
[{ list: "ordered" }, { list: "bullet" }],
["link", "clean"],
["undo", "redo"],
],
handlers: { undo: function () { mail.history.undo(); }, redo: function () { mail.history.redo(); } },
},
},
});
const dmEl = document.getElementById("otr-dm-editor");
const dm = new Quill(dmEl, { theme: "snow", placeholder: dmEl.dataset.placeholder || "",
formats: ["nametag"], modules: { toolbar: false, history: { userOnly: true } } });
// 도구 막대 — 되돌리기 아이콘, 한글 도움말
const tb = mail.getModule("toolbar").container;
tb.querySelector(".ql-undo").innerHTML = "&#8630;";
tb.querySelector(".ql-redo").innerHTML = "&#8631;";
const tips = { ".ql-size": "글자 크기", ".ql-bold": "굵게 (Ctrl+B)", ".ql-italic": "기울임 (Ctrl+I)", ".ql-underline": "밑줄 (Ctrl+U)",
".ql-strike": "취소선", ".ql-color": "글자 색", ".ql-background": "배경 색", ".ql-align": "정렬",
'.ql-list[value="ordered"]': "번호 목록", '.ql-list[value="bullet"]': "글머리 목록", ".ql-link": "링크",
".ql-clean": "서식 지우기", ".ql-undo": "되돌리기 (Ctrl+Z)", ".ql-redo": "다시 하기 (Ctrl+Y)" };
Object.keys(tips).forEach(function (sel) { tb.querySelectorAll(sel).forEach(function (el) { el.title = tips[sel]; }); });
// {이름} 빨강 굵게 — 지금 칠한 곳과 있어야 할 곳이 다를 때만 고친다(글자 칠 때마다 DOM 을 건드리지 않게, 한글 조합 중엔 쉼)
function markNames(q) {
if (q.composition && q.composition.isComposing) return;
const text = q.getText(), want = [];
for (let i = text.indexOf(TAG); i >= 0; i = text.indexOf(TAG, i + TAG.length)) {
const last = want[want.length - 1];
if (last && last[1] === i) last[1] = i + TAG.length; else want.push([i, i + TAG.length]);
}
const have = [];
let pos = 0;
q.getContents().ops.forEach(function (op) {
const len = typeof op.insert === "string" ? op.insert.length : 1;
if (op.attributes && op.attributes.nametag) {
const last = have[have.length - 1];
if (last && last[1] === pos) last[1] = pos + len; else have.push([pos, pos + len]);
}
pos += len;
});
if (JSON.stringify(want) === JSON.stringify(have)) return;
have.forEach(function (r) { q.formatText(r[0], r[1] - r[0], "nametag", false, "silent"); });
want.forEach(function (r) { q.formatText(r[0], r[1] - r[0], "nametag", "on", "silent"); });
}
function setMail(html) {
mail.setContents(mail.clipboard.convert({ html: html || "" }), "silent");
markNames(mail);
}
function setDm(text) {
dm.setText(text || "", "silent");
markNames(dm);
dmCount();
}
// DM 글자 수(인스타 DM 한 통 한도)
const countEl = document.getElementById("otr-dm-count"), dmMax = Number(countEl.dataset.max) || 1000;
function dmValue() { return dm.getText().replace(/\s+$/, ""); }
function dmCount() {
const n = dmValue().length;
countEl.textContent = n ? n + " / " + dmMax + "자" : "비어 있음 — 메일 본문 글 + 끝 문구가 복사됩니다";
countEl.classList.toggle("is-over", n > dmMax);
}
let dirty = false;
mail.on("text-change", function (d, o, source) { if (source !== "silent") { dirty = true; markNames(mail); } });
dm.on("text-change", function (d, o, source) { if (source !== "silent") { dirty = true; markNames(dm); dmCount(); } });
document.addEventListener("input", function (e) { if (e.target.form === form) dirty = true; });
window.addEventListener("beforeunload", function (e) { if (dirty) { e.preventDefault(); e.returnValue = ""; } });
const cur = readJson("otr-current-data");
setMail(cur.body);
setDm(cur.dm_body);
document.getElementById("otr-dm-from-mail").addEventListener("click", function () {
if (dmValue() && !confirm("지금 DM 문구를 메일 본문 글로 바꿀까요?")) return;
setDm(mail.getText().replace(/\s+$/, ""));
dirty = true;
});
document.getElementById("otr-default").addEventListener("click", function () {
if (!confirm("제목·본문·보내는 이름·끝 문구·DM 문구를 기본 문구로 바꿀까요? ([저장]을 눌러야 적용)")) return;
const d = readJson("otr-default-data");
form.elements.subject.value = d.subject || "";
form.elements.sender_name.value = d.sender_name || "";
form.elements.footer.value = d.footer || "";
form.elements.ad_label.checked = !!d.ad_label;
setMail(d.body);
setDm(d.dm_body);
dirty = true;
});
form.addEventListener("submit", function (e) {
if (!mail.getText().trim()) { e.preventDefault(); toast("메일 본문을 쓰세요.", true); mail.focus(); return; }
if (dmValue().length > dmMax) { e.preventDefault(); toast("DM 문구가 " + dmMax + "자를 넘습니다 — 줄여 주세요.", true); dm.focus(); return; }
document.getElementById("otr-body-input").value = mail.getSemanticHTML();
document.getElementById("otr-dm-input").value = dmValue();
dirty = false;
});
}
// DM 문구 글자 수(인스타 DM 한 통 한도) — 비어 있으면 메일 본문으로 간다는 안내
const dmBody = document.getElementById("otr-dm-body"), dmCountEl = document.getElementById("otr-dm-count");
function dmCount() {
if (!dmBody || !dmCountEl) return;
const n = dmBody.value.length, max = Number(dmCountEl.dataset.max) || 1000;
dmCountEl.textContent = n ? n + " / " + max + "자" : "비어 있음 — 메일 본문 + 끝 문구가 복사됩니다";
dmCountEl.classList.toggle("is-over", n >= max);
}
if (dmBody) { dmBody.addEventListener("input", dmCount); dmCount(); }
// ── 리스트 화면 ──
const root = document.getElementById("otr");
+31
View File
@@ -0,0 +1,31 @@
Copyright (c) 2017-2024, Slab
Copyright (c) 2014, Jason Chen
Copyright (c) 2013, salesforce.com
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+6
View File
@@ -0,0 +1,6 @@
# Quill 2.0.3
안내문 발송 설정 화면(메일 본문 서식 편집기·DM 편집기)에서 씁니다. 외부 CDN 없이 여기서 불러옵니다.
- 출처: npm `quill@2.0.3` (https://quilljs.com, https://github.com/slab/quill) — `dist/quill.js`, `dist/quill.snow.css` 원본 그대로
- 라이선스: BSD 3-Clause (`LICENSE`)
File diff suppressed because one or more lines are too long
+7
View File
@@ -0,0 +1,7 @@
/*!
* Quill Editor v2.0.3
* https://quilljs.com
* Copyright (c) 2017-2024, Slab
* Copyright (c) 2014, Jason Chen
* Copyright (c) 2013, salesforce.com
*/
File diff suppressed because one or more lines are too long
+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