From f4d7e9588f110a438699ee6895d68d64e68f8f34 Mon Sep 17 00:00:00 2001 From: king Date: Tue, 27 Oct 2026 12:09:40 +0900 Subject: [PATCH] =?UTF-8?q?feat(inout):=20=EB=B0=9C=EC=A3=BC=20=EB=A9=94?= =?UTF-8?q?=EC=9D=BC=20=EB=AF=B8=EB=A6=AC=EB=B3=B4=EA=B8=B0=EC=97=90?= =?UTF-8?q?=EC=84=9C=20=EB=B3=B8=EB=AC=B8=20=EB=B0=94=EB=A1=9C=20=EA=B3=A0?= =?UTF-8?q?=EC=B9=98=EA=B8=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 미리보기 창을 눌러 글·표를 고치면 고친 본문 그대로 발송(안 고치면 서버 본문). 서버가 허용 태그·인라인 서식만 남기고 글 버전도 다시 만든다. [원래 본문으로]·닫을 때 확인. Co-Authored-By: Claude Opus 5.5 --- app/modules/inout/CLAUDE.md | 2 + app/modules/inout/router.py | 4 + app/modules/inout/store.py | 131 ++++++++++++++++++ app/modules/inout/templates/inout/index.html | 4 +- .../inout/templates/inout/order_detail.html | 4 +- .../inout/templates/inout/order_form.html | 4 +- .../inout/templates/inout/pending.html | 4 +- app/static/inout.css | 2 + app/static/inout.js | 46 +++++- tests/test_inout_receipt_mail.py | 34 +++++ 10 files changed, 221 insertions(+), 14 deletions(-) diff --git a/app/modules/inout/CLAUDE.md b/app/modules/inout/CLAUDE.md index a010b56..50edc56 100644 --- a/app/modules/inout/CLAUDE.md +++ b/app/modules/inout/CLAUDE.md @@ -32,6 +32,8 @@ **휴가 모듈도 같은 연결을 쓴다**(2026-10-27) — 휴가 옵션 [Gmail 연결]은 세션 `_gmail_origin=vacation` 을 달고 같은 콜백(`/inout/gmail/callback`)으로 돌아오며, 콜백이 `_gmail_callback_vacation`(휴가 권한 확인, 휴가 옵션으로 복귀)으로 넘긴다. 토큰 표·끊기는 공용 — 바꾸면 휴가 메일(`vacation/notify.py`)도 확인. - 보낸 기록·재발송 확인. +- **본문 고치기**(2026-10-27): 발주 메일 미리보기 iframe 이 `designMode`(sandbox `allow-same-origin`, 스크립트 없음) — 고치면 [원래 본문으로]·닫을 때 확인, + 보낼 때만 `html` 을 함께 POST → `store.clean_mail_html`(허용 태그·표·인라인 서식만, url()·이벤트·스크립트 제거) + 글 버전 `mail_html_to_text`. 안 고치면 서버 본문 그대로. 입고 요청 메일은 고치기 없음(cid 사진). - **입고 담당 발주 알림 자동 발송**(2026-10-19): 발주 메일이 나가면 같은 Gmail 로 옵션 → 담당자의 입고 담당들에게 따로 보냄 — 제목은 발주 메일과 같고 내용은 발주번호·발주일·제품 코드·제품명·수량만(`store.order_notice_mail`, `router._send_order_notice`). 실패해도 공장 메일은 그대로(안내만), 미리보기 창에 받을 사람 안내. - **참조 기본값 `king@dbxcorp.co.kr`**(2026-10-19) — 미리보기 참조 칸에 미리 들어감, 옵션 → 공장 탭 "발주 메일 참조"에서 고침(`inout_settings` `order_mail_cc`, 행이 없으면 기본값 — 저장만 005 필요). diff --git a/app/modules/inout/router.py b/app/modules/inout/router.py index c5a5c78..d51d100 100644 --- a/app/modules/inout/router.py +++ b/app/modules/inout/router.py @@ -718,6 +718,8 @@ def mail_send(request: Request, order_id: int, payload: dict[str, Any] = Body(.. try: to = store.parse_emails(payload.get("to"), label="받는 사람", required=True) cc = store.parse_emails(payload.get("cc"), label="참조") + # 미리보기 창에서 본문을 고쳤으면 그 HTML(2026-10-27) — 안 고쳤으면 보내지 않고 서버가 만든 본문 그대로 + edited = store.clean_mail_html(payload["html"]) if payload.get("html") else None except ValueError as exc: raise HTTPException(status_code=400, detail=str(exc)) from None if order["mails"] and not payload.get("resend"): @@ -728,6 +730,8 @@ def mail_send(request: Request, order_id: int, payload: dict[str, Any] = Body(.. return JSONResponse({"ok": False, "reconnect": True, "message": "Gmail 이 연결되지 않았습니다 — 먼저 [Gmail 연결]을 하세요."}, status_code=409) mail = store.order_mail(order, sender_name=str(user.get("name") or ""), sender_email=email) + if edited is not None: + mail = {**mail, "html": edited, "text": store.mail_html_to_text(edited)} try: refresh = gmail.decrypt_token(email, row["refresh_token_enc"]) raw = gmail.build_message(sender_name=str(user.get("name") or ""), sender_email=email, to=to, cc=cc, diff --git a/app/modules/inout/store.py b/app/modules/inout/store.py index 030d389..0f3b7f0 100644 --- a/app/modules/inout/store.py +++ b/app/modules/inout/store.py @@ -9,6 +9,7 @@ from __future__ import annotations import html as _html +import html.parser as _html_parser import re from datetime import date, datetime from decimal import ROUND_HALF_UP, Decimal, InvalidOperation @@ -357,6 +358,136 @@ def order_mail(order: dict[str, Any], *, sender_name: str, sender_email: str) -> return {"subject": subject, "text": "\n".join(text), "html": html} +# 발주 메일 본문 고치기(2026-10-27) — 미리보기 창에서 사람이 고친 HTML 을 그대로 보낸다. +# 표·서식(인라인 style)은 남기고 스크립트·이벤트 속성·외부 리소스(url()·img)는 뺀다. 글 버전은 고친 HTML 에서 다시 만든다. +MAIL_HTML_MAX = 300_000 +_MAIL_TAGS = {"div", "p", "br", "span", "b", "strong", "i", "em", "u", "s", "strike", "font", "a", "ul", "ol", "li", + "h1", "h2", "h3", "h4", "blockquote", "sub", "sup", "hr", + "table", "thead", "tbody", "tfoot", "tr", "th", "td", "colgroup", "col", "caption"} +_MAIL_VOID = {"br", "hr", "col"} +_MAIL_DROP = {"script", "style", "iframe", "object", "embed", "head", "title", "template", "noscript", "svg", "math", + "textarea", "select", "button", "form", "input", "link", "meta"} +_MAIL_ATTRS = {"colspan", "rowspan", "cellpadding", "cellspacing", "border", "align", "valign", "width", "height", "color"} +_MAIL_STYLE_PROPS = {"color", "background", "background-color", "font-family", "font-size", "font-weight", "font-style", + "text-decoration", "text-align", "vertical-align", "white-space", "line-height", "height", "width", + "min-width", "max-width", "padding", "padding-top", "padding-right", "padding-bottom", "padding-left", + "margin", "margin-top", "margin-right", "margin-bottom", "margin-left", "border", "border-top", + "border-right", "border-bottom", "border-left", "border-color", "border-collapse", "border-spacing"} +_MAIL_STYLE_VALUE_RE = re.compile(r"^[#\w\s.,%()'\"-]{1,120}$") +_MAIL_ATTR_VALUE_RE = re.compile(r"^[#\w%.-]{1,20}$") + + +def _mail_style(value: str) -> str: + out = [] + for decl in value.split(";"): + prop, _, val = decl.partition(":") + prop, val = prop.strip().lower(), val.strip() + if prop in _MAIL_STYLE_PROPS and _MAIL_STYLE_VALUE_RE.match(val) and not re.search(r"url|expression|@import", val, re.I): + out.append(f"{prop}:{val}") + return ";".join(out) + + +class _MailSanitizer(_html_parser.HTMLParser): + def __init__(self) -> None: + super().__init__(convert_charrefs=True) + self.out: list[str] = [] + self.stack: list[str] = [] + self.skip = 0 + + def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None: + if tag in _MAIL_DROP: + self.skip += 1 + return + if self.skip or tag not in _MAIL_TAGS: + return + extra = "" + for k, v in attrs: + v = (v or "").strip() + if k == "style": + style = _mail_style(v) + if style: + extra += f' style="{_html.escape(style)}"' + elif k == "href" and tag == "a" and re.match(r"^(https?:|mailto:)", v, re.I): + extra += f' href="{_html.escape(v)}"' + elif k in _MAIL_ATTRS and _MAIL_ATTR_VALUE_RE.match(v): + extra += f' {k}="{_html.escape(v)}"' + self.out.append(f"<{tag}{extra}>") + if tag not in _MAIL_VOID: + self.stack.append(tag) + + def handle_startendtag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None: + if tag in _MAIL_VOID: + self.handle_starttag(tag, attrs) + + def handle_endtag(self, tag: str) -> None: + if tag in _MAIL_DROP: + 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() + self.out.append(f"") + if t == tag: + break + + def handle_data(self, data: str) -> None: + if not self.skip: + self.out.append(_html.escape(data, quote=False)) + + def result(self) -> str: + self.close() + while self.stack: + self.out.append(f"") + return "".join(self.out) + + +class _MailText(_html_parser.HTMLParser): + """HTML → 글 버전 — 문단·줄은 줄바꿈, 표 칸은 " | " 로 잇는다.""" + + _BLOCK = {"p", "div", "tr", "li", "h1", "h2", "h3", "h4", "blockquote", "table", "hr"} + + def __init__(self) -> None: + super().__init__(convert_charrefs=True) + self.parts: list[str] = [] + self.cell = False # 이 줄에 이미 칸이 있다 — 다음 칸 앞에 구분자 + + def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None: + if tag == "br" or tag in self._BLOCK: + self.parts.append("\n") + self.cell = False + elif tag in ("td", "th"): + if self.cell: + self.parts.append(" | ") + self.cell = True + if tag == "li": + self.parts.append("- ") + + def handle_data(self, data: str) -> None: + self.parts.append(re.sub(r"\s+", " ", data.replace("\xa0", " "))) + + +def clean_mail_html(html: Any) -> str: + """고친 메일 본문 HTML → 보낼 HTML(허용 태그·속성·글자 서식만). 너무 길거나 글이 없으면 ValueError.""" + raw = str(html or "") + if len(raw) > MAIL_HTML_MAX: + raise ValueError("메일 본문이 너무 깁니다.") + p = _MailSanitizer() + p.feed(raw) + out = p.result() + if not mail_html_to_text(out).strip(): + raise ValueError("메일 본문이 비어 있습니다.") + return out + + +def mail_html_to_text(html: str) -> str: + p = _MailText() + p.feed(str(html or "")) + p.close() + lines = [ln.strip() for ln in "".join(p.parts).split("\n")] + return re.sub(r"\n{3,}", "\n\n", "\n".join(lines)).strip() + + # ════════════════════════════════════════════════════════════ # 상품 정보(2026-10-16, 마이그레이션 004) — 단가·무게(개당 g = PP량)·은(Ag) 함유량(%) 수기 입력 # 은 함량(g/개) = 무게 × 은 함유량 ÷ 100 — 저장하지 않고 계산(silver_g). diff --git a/app/modules/inout/templates/inout/index.html b/app/modules/inout/templates/inout/index.html index f27d49e..f99a64d 100644 --- a/app/modules/inout/templates/inout/index.html +++ b/app/modules/inout/templates/inout/index.html @@ -1,6 +1,6 @@ {% extends "erp_base.html" %} {% from "inout/_macros.html" import order_badge, progress, due, n, ymd %} -{% block head_extra %}{% endblock %} +{% block head_extra %}{% endblock %} {% block content %}
{# 2열 — 왼쪽 화면 | 오른쪽 달력(2026-10-21) #} @@ -71,4 +71,4 @@ {% include "inout/_calendar.html" %}
{% endblock %} -{% block scripts %}{% endblock %} +{% block scripts %}{% endblock %} diff --git a/app/modules/inout/templates/inout/order_detail.html b/app/modules/inout/templates/inout/order_detail.html index 8a3c25a..464a1fa 100644 --- a/app/modules/inout/templates/inout/order_detail.html +++ b/app/modules/inout/templates/inout/order_detail.html @@ -20,7 +20,7 @@ {%- endmacro -%} -{% block head_extra %}{% endblock %} +{% block head_extra %}{% endblock %} {% block content %} {% set active = order.status in ('open', 'partial') %} @@ -258,4 +258,4 @@ {% include "inout/_calendar.html" %} {% endblock %} -{% block scripts %}{% endblock %} +{% block scripts %}{% endblock %} diff --git a/app/modules/inout/templates/inout/order_form.html b/app/modules/inout/templates/inout/order_form.html index a5a23a7..9848629 100644 --- a/app/modules/inout/templates/inout/order_form.html +++ b/app/modules/inout/templates/inout/order_form.html @@ -1,5 +1,5 @@ {% extends "erp_base.html" %} -{% block head_extra %}{% endblock %} +{% block head_extra %}{% endblock %} {% block content %}
{# 2열 — 왼쪽 화면 | 오른쪽 달력(2026-10-21) #} @@ -95,4 +95,4 @@ {% include "inout/_calendar.html" %}
{% endblock %} -{% block scripts %}{% endblock %} +{% block scripts %}{% endblock %} diff --git a/app/modules/inout/templates/inout/pending.html b/app/modules/inout/templates/inout/pending.html index f1ba15f..8713854 100644 --- a/app/modules/inout/templates/inout/pending.html +++ b/app/modules/inout/templates/inout/pending.html @@ -1,6 +1,6 @@ {% extends "erp_base.html" %} {% from "inout/_macros.html" import due, n, ymd %} -{% block head_extra %}{% endblock %} +{% block head_extra %}{% endblock %} {% block content %}
{# 2열 — 왼쪽 화면 | 오른쪽 달력(2026-10-21) #} @@ -91,4 +91,4 @@ {% include "inout/_calendar.html" %}
{% endblock %} -{% block scripts %}{% endblock %} +{% block scripts %}{% endblock %} diff --git a/app/static/inout.css b/app/static/inout.css index 435d452..c7240a8 100644 --- a/app/static/inout.css +++ b/app/static/inout.css @@ -192,6 +192,8 @@ .io-mail-fields input[readonly] { background: var(--color-ghost-gray); color: #3d3f42; } .io-mail-sentlist { margin: 0 0 12px; padding: 10px 12px; border-radius: 8px; background: #f3fbf5; border: 1px solid #cdeed6; font-size: 12.5px; } .io-mail-sentlist ul { margin: 4px 0 0; padding-left: 18px; } +.io-mail-edit-bar { display: flex; align-items: center; gap: 12px; margin: 0 0 6px; font-size: 12.5px; color: var(--color-midtone-gray); } +.io-mail-edit-bar .io-link-btn { margin-left: auto; } .io-mail-preview { width: 100%; height: 380px; border: 1px solid var(--color-subtle-ash); border-radius: 8px; background: #fff; } .io-mail-connect { padding: 8px 2px 4px; font-size: 13.5px; line-height: 1.7; } .io-mail-connect .erp-btn { margin-top: 6px; } diff --git a/app/static/inout.js b/app/static/inout.js index cea9858..8d3aaa8 100644 --- a/app/static/inout.js +++ b/app/static/inout.js @@ -731,7 +731,7 @@ // (입고 담당 본인 Gmail, 받는 사람 = 옵션 → 물류센터 이메일, 참조 기본 = 옵션 값, 본문에 입고증 사진) const mailBtn = document.getElementById("io-mail-btn"), mailDlg = document.getElementById("io-mail"); if (mailBtn && mailDlg) { - const om = initMail(mailDlg, { param: "mail", what: "발주 메일" }); + const om = initMail(mailDlg, { param: "mail", what: "발주 메일", editable: true }); const url = "/inout/orders/" + mailBtn.dataset.order + "/mail"; mailBtn.addEventListener("click", function () { om.open(url); }); if (mailBtn.dataset.open === "1") om.open(url); @@ -749,7 +749,7 @@ const body = dlg.querySelector("[data-mail-body]"), foot = dlg.querySelector("[data-mail-foot]"); const msgEl = dlg.querySelector(".io-dlg-msg"), sendBtn = dlg.querySelector("[data-mail-send]"); const titleEl = dlg.querySelector("[data-mail-title]"); - let base = "", data = null, sent = false; + let base = "", data = null, sent = false, edited = false; function say(text, bad) { msgEl.textContent = text || ""; msgEl.hidden = !text; msgEl.classList.toggle("is-bad", !!bad); } function esc(s) { const d = document.createElement("div"); d.textContent = s == null ? "" : String(s); return d.innerHTML; } function field(name) { return body.querySelector('[data-mail-field="' + name + '"]'); } @@ -794,10 +794,43 @@ (notice ? '

' + esc(notice) + "

" : "") + (receipt && data.photos_skipped ? '

HEIC 등 본문에 넣지 못하는 입고증 사진 ' + esc(data.photos_skipped) + "장은 빠집니다(입고 기록에는 그대로).

" : "") + (sentList ? '
보낸 기록
    ' + sentList + "
" : "") + - ''; - body.querySelector(".io-mail-preview").srcdoc = data.html; + (cfg.editable ? '
본문을 눌러 바로 고칠 수 있습니다 — 고친 내용 그대로 보냅니다.' + + '
' : "") + + ''; + edited = false; + setupPreview(body.querySelector(".io-mail-preview"), data.html); sendBtn.textContent = (data.sent || []).length ? "다시 발송" : "메일 발송"; } + // 발주 메일 본문 고치기(2026-10-27) — 미리보기 iframe 을 designMode 로. 스크립트는 막고(allow-scripts 없음) 부모만 문서에 손댈 수 있게 + // allow-same-origin. 보낼 때 고쳤으면 body HTML 을 같이 보낸다(서버가 허용 태그·서식만 남김). + function setupPreview(ifr, html) { + ifr.setAttribute("sandbox", cfg.editable ? "allow-same-origin" : ""); + if (!cfg.editable) { ifr.srcdoc = html; return; } + const reset = body.querySelector("[data-mail-reset]"); + ifr.addEventListener("load", function () { + const doc = ifr.contentDocument; + if (!doc) return; + doc.designMode = "on"; + doc.body.style.outline = "none"; + doc.addEventListener("input", function () { edited = true; reset.hidden = false; }); + }); + reset.onclick = async function () { + if (!(await confirmMsg("고친 내용을 버리고 원래 본문으로 되돌릴까요?"))) return; + edited = false; + reset.hidden = true; + ifr.srcdoc = data.html; + }; + ifr.srcdoc = html; + } + function editedHtml() { + const ifr = body.querySelector(".io-mail-preview"); + return cfg.editable && edited && ifr && ifr.contentDocument ? ifr.contentDocument.body.innerHTML : ""; + } + async function close() { + if (edited && !sent && !(await confirmMsg("고친 본문은 저장되지 않습니다. 닫을까요?"))) return; + edited = false; + dlg.close(); + } async function open(url, title) { base = url; if (title && titleEl) titleEl.textContent = title; @@ -815,7 +848,7 @@ say("보내는 중…"); try { const res = await fetch(base, { method: "POST", headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ to: to, cc: cc, resend: !!resend }) }); + body: JSON.stringify({ to: to, cc: cc, resend: !!resend, html: editedHtml() || undefined }) }); const out = await res.json(); if (out.resend_needed) { say(""); @@ -838,7 +871,8 @@ await load(); say("Gmail 연결을 끊었습니다."); }); - dlg.addEventListener("click", function (e) { if (e.target.closest("[data-close]")) dlg.close(); }); + dlg.addEventListener("click", function (e) { if (e.target.closest("[data-close]")) close(); }); + dlg.addEventListener("cancel", function (e) { if (edited && !sent) { e.preventDefault(); close(); } }); // Esc dlg.addEventListener("close", function () { const url = new URL(location.href); const had = url.searchParams.has(cfg.param); diff --git a/tests/test_inout_receipt_mail.py b/tests/test_inout_receipt_mail.py index 812d719..985214b 100644 --- a/tests/test_inout_receipt_mail.py +++ b/tests/test_inout_receipt_mail.py @@ -393,3 +393,37 @@ class OrderNoticeMailTests(OrderMailCcTests): self.assertIn("입고 담당이 옵션에 없어", r.json()["message"]) test_preview_cc_default_and_setting = test_save_option_admin_only = None + + +class OrderMailEditTests(OrderNoticeMailTests): + """미리보기 창에서 고친 발주 메일 본문을 그대로 보낸다(2026-10-27) — 입고 담당 알림은 원래 내용 그대로.""" + + def _post(self, body): + def fake_send(refresh, raw): + self.sent.append(email.message_from_bytes(raw, policy=policy.default)) + return "g" + + with patch.object(gmail, "decrypt_token", lambda e, enc: "refresh"), patch.object(gmail, "send", fake_send): + return self.c.post("/inout/orders/7/mail", json={"to": "f@x.com", **body}) + + def test_edited_body_sent_cleaned(self): + r = self._post({"html": '

납기 당겨 주세요

' + '
MW-03205,500
'}) + self.assertEqual(r.status_code, 200, r.text) + factory, notice = self.sent + h = factory.get_body(("html",)).get_content() + self.assertIn('

납기 당겨 주세요

', h) + self.assertIn('MW-0320', h) + for absent in ("onclick", "script", "alert"): + self.assertNotIn(absent, h) + self.assertIn("MW-0320 | 5,500", factory.get_body(("plain",)).get_content()) # 글 버전도 고친 본문에서 + self.assertIn("PO-261019-01", notice.get_body(("html",)).get_content()) # 알림은 서버가 만든 내용 + + def test_empty_edited_body_rejected(self): + r = self._post({"html": "


"}) + self.assertEqual(r.status_code, 400) + self.assertIn("비어 있습니다", r.json()["detail"]) + self.assertEqual(self.sent, []) + + test_preview_shows_notice_recipients = test_notice_sent_separately_same_subject_minimal_body = None + test_no_receivers_or_notice_failure_does_not_block = None