From 6c87a736a609ef0931cfdfa89c2c346020101d64 Mon Sep 17 00:00:00 2001 From: king Date: Tue, 27 Oct 2026 09:31:18 +0900 Subject: [PATCH] =?UTF-8?q?feat(outreach):=20=EC=84=A4=EC=A0=95=EC=97=90?= =?UTF-8?q?=20=EC=9D=B8=EC=8A=A4=ED=83=80=20DM=20=EB=AC=B8=EA=B5=AC=20?= =?UTF-8?q?=EC=B9=B8=20=E2=80=94=20=EB=B9=84=EC=9A=B0=EB=A9=B4=20=EB=A9=94?= =?UTF-8?q?=EC=9D=BC=20=EB=B3=B8=EB=AC=B8=EC=9C=BC=EB=A1=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - store: dm_body(최대 1000자)·dm_text, needs_name 을 메일/DM 구분별로 - 리스트 [DM 보내기] 복사 글·DM 미리보기가 DM 문구 사용 - 설정 화면: DM 문구 칸 + 글자 수, [기본 문구로 되돌리기]에 포함 - 설정은 outreach_settings JSON 이라 DB 변경 없음 Co-Authored-By: Claude Opus 5.5 --- app/modules/outreach/CLAUDE.md | 3 +- app/modules/outreach/router.py | 15 +++++----- app/modules/outreach/store.py | 19 ++++++++++++- .../outreach/templates/outreach/index.html | 4 +-- .../outreach/templates/outreach/settings.html | 14 ++++++++-- app/static/outreach.css | 3 ++ app/static/outreach.js | 18 ++++++++++-- tests/test_outreach.py | 28 ++++++++++++++++++- 8 files changed, 86 insertions(+), 18 deletions(-) diff --git a/app/modules/outreach/CLAUDE.md b/app/modules/outreach/CLAUDE.md index 9ce4301..18a0cfd 100644 --- a/app/modules/outreach/CLAUDE.md +++ b/app/modules/outreach/CLAUDE.md @@ -16,7 +16,8 @@ Gmail 연결 없으면 409(화면이 [Gmail 연결] 안내), 끊기면 남은 줄 실패. 서버 재시작 때 남은 '발송중' = 실패(`release_stuck`). - **인스타 DM = 반자동** — 인스타 공식 API 는 처음 연락하는 사람에게 DM 을 보낼 수 없다(상대가 먼저 보낸 24시간 안만, 자동 DM 은 약관 위반·계정 정지 위험). [DM 보내기] = 그 사람 이름이 든 문구 복사 + `https://ig.me/m/계정` 새 탭(누르는 순간 — 문구는 리스트 데이터에 미리 담음) → 붙여 넣어 보낸 뒤 [보냄](`dm-sent`, 기록). -- **설정** `/outreach/settings`(모듈 권한자 누구나): 메일 제목·본문(기본 = 미라네주방 공동구매 제안 문구, `store.DEFAULT_TEMPLATE`)·보내는 이름·끝 문구(수신 거부 안내 등)· + **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` 에, 순서 ◀▶). [기본 문구로 되돌리기] = 칸만(저장해야 적용). - 리스트 줄: 이름 바로 고치기(칸 떠나면 저장), [미리보기](메일 = 제목·HTML, DM = 글), 고른 줄 다시 대기·지우기(발송중은 못 지움), 걸러 보기(전체·메일·DM·대기·보냄·실패). diff --git a/app/modules/outreach/router.py b/app/modules/outreach/router.py index ce05399..b102674 100644 --- a/app/modules/outreach/router.py +++ b/app/modules/outreach/router.py @@ -110,11 +110,11 @@ def _view(r: dict[str, Any], template: dict[str, Any]) -> dict[str, Any]: out = {k: r.get(k) for k in ("id", "kind", "handle", "address", "name", "memo", "status", "sent_at", "sent_by", "sent_via", "last_error")} out["kind_label"] = store.KIND_LABELS.get(r["kind"], "") - out["needs_name"] = store.needs_name(template) and not (r.get("name") or "").strip() + out["needs_name"] = store.needs_name(template, r["kind"]) and not (r.get("name") or "").strip() if r["kind"] == "instagram": out["dm_link"] = store.dm_link(r["handle"]) out["profile_link"] = store.profile_link(r["handle"]) - out["dm_text"] = store.plain_text(template, r.get("name") or "") + out["dm_text"] = store.dm_text(template, r.get("name") or "") return out @@ -148,19 +148,19 @@ def settings_page(request: Request) -> Any: return got st, user = got return _render(request, "outreach/settings.html", user, { - "page_title": "안내문 발송 — 설정", "page_subtitle": "메일 제목 · 본문 · 사진", + "page_title": "안내문 발송 — 설정", "page_subtitle": "메일 제목 · 본문 · DM 문구 · 사진", "template": st.get_template(), "default": store.DEFAULT_TEMPLATE, "images": st.list_images(), - "max_images": 10, "msg": request.query_params.get("msg", ""), + "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("")) -> RedirectResponse: + footer: str = Form(""), ad_label: str = Form(""), dm_body: str = Form("")) -> RedirectResponse: user = _user(request) st = _db(request) try: - st.save_template({"subject": subject, "body": body, "sender_name": sender_name, "footer": footer, + 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"]) except ValueError as exc: raise HTTPException(status_code=400, detail=str(exc)) @@ -303,7 +303,8 @@ def api_preview(request: Request, rid: int) -> JSONResponse: html = store.html_body(t, r["name"], [f"img-{im['id']}" for im in st.list_images()]) for im in st.list_images(): html = html.replace(f"cid:img-{im['id']}", f"/outreach/images/{im['id']}") - return JSONResponse({"subject": store.subject_for(t, r["name"]), "html": html, "text": store.plain_text(t, r["name"]), + return JSONResponse({"subject": store.subject_for(t, r["name"]), "html": html, + "text": store.dm_text(t, r["name"]) if r["kind"] == "instagram" else store.plain_text(t, r["name"]), "kind": r["kind"], "to": r["handle"], "sender_name": t["sender_name"]}) diff --git a/app/modules/outreach/store.py b/app/modules/outreach/store.py index 34f13c6..47b8325 100644 --- a/app/modules/outreach/store.py +++ b/app/modules/outreach/store.py @@ -2,6 +2,7 @@ - 주소를 보고 정한다: `name@domain.tld` = 메일, `@계정`·`instagram.com/계정`·`ig.me/m/계정`·계정명만(영문·숫자·.·_) = 인스타 DM. - 본문 `{이름}` = 그 줄 이름. `**굵게**` 는 메일에서 굵은 글씨, DM 에서는 별표만 뺀다(인스타는 서식이 없음). 주소(https://…)는 메일에서 링크. +- DM 글 = 설정 `dm_body`(인스타 DM 용 문구). 비어 있으면 메일 본문 + 끝 문구. """ from __future__ import annotations @@ -27,6 +28,7 @@ DEFAULT_TEMPLATE: dict[str, Any] = { "sender_name": "미라네주방", "ad_label": False, "footer": "", + "dm_body": "", "body": """안녕하세요, {이름}님. 주방의 본질을 지키며 6년간 묵묵히 300억 매출의 신화를 써온 **'미라네주방'**입니다. 저희는 지난 6년간 제품력 하나로 국내/해외 800만 개 판매를 돌파하고 호주, 동남아 등 글로벌 시장에서 인정받았습니다. @@ -61,6 +63,7 @@ DEFAULT_TEMPLATE: dict[str, Any] = { https://miras.co.kr/""", } SUBJECT_MAX, BODY_MAX, FOOTER_MAX = 200, 20000, 2000 +DM_MAX = 1000 # 인스타 DM 한 통 글자 수 한도 def _ig_user(value: str) -> str | None: @@ -147,12 +150,18 @@ def normalize_template(value: dict[str, Any] | None) -> dict[str, Any]: v["subject"] = str(v["subject"] or "").strip()[:SUBJECT_MAX] v["body"] = str(v["body"] or "").replace("\r\n", "\n")[:BODY_MAX] 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] v["ad_label"] = bool(v["ad_label"]) return v -def needs_name(template: dict[str, Any]) -> bool: +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"] + 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 "") @@ -176,6 +185,14 @@ def plain_text(template: dict[str, Any], name: str) -> str: 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() + if not dm: + return plain_text(template, name) + return re.sub(r"\*\*(.+?)\*\*", r"\1", fill(dm, name)) + + _URL_RE = re.compile(r"https?://[^\s<>\"']+") diff --git a/app/modules/outreach/templates/outreach/index.html b/app/modules/outreach/templates/outreach/index.html index 7ca85ae..331d60a 100644 --- a/app/modules/outreach/templates/outreach/index.html +++ b/app/modules/outreach/templates/outreach/index.html @@ -2,7 +2,7 @@ {#- 안내문 발송(2026-10-27) — 리스트(주소 + 이름) → 메일은 [선택한 메일 보내기](본인 Gmail, 한 사람에 한 통), 인스타는 [DM 보내기](문구 복사 + DM 창) → 보낸 뒤 [보냄]. 주소를 보고 메일/DM 을 정한다(store.detect). 본문 {이름} = 그 줄 이름. -#} -{% block head_extra %}{% endblock %} +{% block head_extra %}{% endblock %} {% block content %}
@@ -99,4 +99,4 @@ {% endblock %} -{% block scripts %}{% endblock %} +{% block scripts %}{% endblock %} diff --git a/app/modules/outreach/templates/outreach/settings.html b/app/modules/outreach/templates/outreach/settings.html index 0d01c88..8b79b7d 100644 --- a/app/modules/outreach/templates/outreach/settings.html +++ b/app/modules/outreach/templates/outreach/settings.html @@ -1,7 +1,8 @@ {% extends "erp_base.html" %} -{#- 안내문 발송 설정(2026-10-27) — 메일 제목·본문({이름})·보내는 이름·끝 문구·(광고) 표시 + 본문 아래 사진. 메일·DM 모두 이 내용. -#} -{% block head_extra %}{% endblock %} +{#- 안내문 발송 설정(2026-10-27) — 메일 제목·본문({이름})·보내는 이름·끝 문구·(광고) 표시 + 본문 아래 사진. + 인스타 DM 문구는 따로(비우면 메일 본문 + 끝 문구로). -#} +{% block head_extra %}{% endblock %} {% block content %}
@@ -21,6 +22,13 @@ + +
인스타 DM 문구 + [DM 보내기]를 누르면 복사되는 글 — 비워 두면 메일 본문 + 끝 문구가 그대로 복사됩니다
+
@@ -56,4 +64,4 @@ {% endblock %} -{% block scripts %}{% endblock %} +{% block scripts %}{% endblock %} diff --git a/app/static/outreach.css b/app/static/outreach.css index 91ae217..972b808 100644 --- a/app/static/outreach.css +++ b/app/static/outreach.css @@ -66,6 +66,9 @@ .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-check { display: flex; align-items: baseline; gap: 6px; font-size: 13px; } .otr-set-actions { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; } .otr-images { display: flex; gap: 12px; flex-wrap: wrap; } diff --git a/app/static/outreach.js b/app/static/outreach.js index 355b935..632e6fc 100644 --- a/app/static/outreach.js +++ b/app/static/outreach.js @@ -1,6 +1,7 @@ /* 안내문 발송(2026-10-27) — 리스트 화면: 붙여 넣기 → 미리보기(메일/DM/오류) → 추가, 걸러 보기, 이름 고치기, 메일 = 고른 줄 [고른 메일 보내기](서버가 본인 Gmail 로 한 통씩, 보내는 동안 2초마다 다시 읽음), - DM = [DM 보내기](그 사람 이름이 들어간 문구를 클립보드에 + ig.me DM 창을 새 탭) → [보냄]. 설정 화면 = [기본 문구로 되돌리기]. */ + DM = [DM 보내기](그 사람 이름이 들어간 문구를 클립보드에 + ig.me DM 창을 새 탭) → [보냄]. + 설정 화면 = [기본 문구로 되돌리기], DM 문구 글자 수. */ (function () { "use strict"; @@ -43,15 +44,26 @@ defBtn.addEventListener("click", function () { let d = {}; try { d = JSON.parse(document.getElementById("otr-default-data").textContent); } catch (_) { d = {}; } - if (!confirm("제목·본문·보내는 이름·끝 문구를 기본 문구로 바꿀까요? ([저장]을 눌러야 적용)")) return; + 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; + dmCount(); }); } + // 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"); @@ -153,7 +165,7 @@ const r = rowOf(btn); if (!r) return; if (btn.dataset.act === "dm") { - if (r.needs_name) { toast("이름을 먼저 넣으세요 — 본문에 {이름}이 있습니다.", true); return; } + if (r.needs_name) { toast("이름을 먼저 넣으세요 — DM 문구에 {이름}이 있습니다.", true); return; } // 누르는 순간 바로(브라우저가 막지 않게) — 문구 복사 + DM 창 새 탭. 문구는 화면 데이터에 미리 있다. const win = window.open(r.dm_link, "_blank", "noopener"); const ok = await copyText(r.dm_text || ""); diff --git a/tests/test_outreach.py b/tests/test_outreach.py index 11dded6..819aeef 100644 --- a/tests/test_outreach.py +++ b/tests/test_outreach.py @@ -69,6 +69,20 @@ class RenderTests(unittest.TestCase): self.assertEqual(h.count('src="cid:'), 2) self.assertEqual(store.dm_link("mira.kitchen"), "https://ig.me/m/mira.kitchen") + def test_dm_body(self): + # DM 문구가 비면 메일 글(본문 + 끝 문구), 있으면 그것만 — 별표만 빼고 {이름}, 끝 문구·제목 없이 + self.assertEqual(store.dm_text(self.T, "김철수"), store.plain_text(self.T, "김철수")) + self.assertEqual(store.DEFAULT_TEMPLATE["dm_body"], "") + t = store.normalize_template({**self.T, "dm_body": " {이름}님, **미라네주방**입니다!\r\n메일 주소 알려주세요 "}) + self.assertEqual(store.dm_text(t, "미라"), "미라님, 미라네주방입니다!\n메일 주소 알려주세요") + self.assertEqual(len(store.normalize_template({"dm_body": "가" * 5000})["dm_body"]), store.DM_MAX) + # 이름 필요 = 그 구분으로 갈 글 기준 + no_name_dm = store.normalize_template({"subject": "{이름}님", "body": "{이름}", "dm_body": "안녕하세요"}) + self.assertTrue(store.needs_name(no_name_dm, "email")) + self.assertFalse(store.needs_name(no_name_dm, "instagram")) + self.assertTrue(store.needs_name(t, "instagram")) + self.assertTrue(store.needs_name(store.normalize_template({"body": "x", "footer": "{이름}"}), "instagram")) + class FakeDB: def __init__(self, template=None, images=()): @@ -296,6 +310,16 @@ def body(c): assert pv["subject"] == "(광고) 김철수님 제안" and "안녕하세요 김철수님" in pv["html"] and "수신 거부: 회신" in pv["text"] # 이름 고치기 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 + r = c.post("/outreach/settings", data={"subject": "{이름}님 제안", "body": "안녕하세요 {이름}님", "footer": "수신 거부: 회신", + "dm_body": "{이름}님, **DM** 문구입니다"}) + assert r.status_code == 303 and st.t["dm_body"] == "{이름}님, **DM** 문구입니다" + mira2 = next(x for x in c.get("/outreach/api/recipients").json()["rows"] if x["id"] == mira["id"]) + 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 # 메일 보내기 — Gmail 없음 = 409(재연결 안내) r = c.post("/outreach/api/send", json={"ids": [kim["id"]]}) assert r.status_code == 409 and r.json()["reconnect"] is True @@ -416,8 +440,10 @@ class OutreachDBTests(unittest.TestCase): st = self.st t = st.get_template() self.assertTrue(t["subject"]) - saved = st.save_template({"subject": "제목 {이름}", "body": "본문", "ad_label": True, "sender_name": "미라네"}, by="Me@X.com") + saved = st.save_template({"subject": "제목 {이름}", "body": "본문", "ad_label": True, "sender_name": "미라네", + "dm_body": "{이름}님 DM"}, by="Me@X.com") self.assertEqual((saved["subject"], saved["ad_label"], saved["updated_by"], saved["is_default"]), ("제목 {이름}", True, "me@x.com", False)) + self.assertEqual(st.get_template()["dm_body"], "{이름}님 DM") with self.assertRaises(ValueError): st.save_template({"subject": "", "body": "x"}, by="me") ids = [st.add_image(filename=f"{i}.jpg", data=b"\xff\xd8" + bytes([i]), width=10, height=10, by="me") for i in range(2)]