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"{t}>") + 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"{self.stack.pop()}>") + 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 %}
' + esc(notice) + "
" : "") + (receipt && data.photos_skipped ? 'HEIC 등 본문에 넣지 못하는 입고증 사진 ' + esc(data.photos_skipped) + "장은 빠집니다(입고 기록에는 그대로).
" : "") + (sentList ? '납기 당겨 주세요
' + '| MW-0320 | 5,500 |
납기 당겨 주세요
', h) + self.assertIn('