feat(inout): 발주 메일 미리보기에서 본문 바로 고치기
미리보기 창을 눌러 글·표를 고치면 고친 본문 그대로 발송(안 고치면 서버 본문). 서버가 허용 태그·인라인 서식만 남기고 글 버전도 다시 만든다. [원래 본문으로]·닫을 때 확인. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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).
|
||||
|
||||
Reference in New Issue
Block a user