f7a3afcebf
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
938 lines
51 KiB
Python
938 lines
51 KiB
Python
"""입출고 관리 — 상수·검사·상태 계산(순수 함수, DB 없음).
|
||
|
||
흐름(2026-10-16 사용자 요청, 상용 ERP 참고 — 이카운트 "발주 대비 미입고 현황"·Odoo 분할 입고/잔량 종결):
|
||
발주 담당이 공장에 발주서(단품 코드·수량)를 넣고 → 물류에 들어올 때마다 입고 담당이 그날 들어온 수량을 입력(여러 번 나눠도 됨)
|
||
→ 품목마다 발주 − 누적 입고 = 미입고. 다 들어오면 입고완료, 더 들어오면 초과입고(확인 후 허용, 빨강 표시).
|
||
더 안 들어올 잔량은 발주 담당이 "종결"(이카운트 발주 종결 · Odoo No backorder) — 미입고 현황에서 빠지고 종결로 남는다.
|
||
"""
|
||
|
||
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
|
||
from typing import Any, Iterable
|
||
|
||
ROLE_ORDER = "order" # 발주 담당
|
||
ROLE_RECEIVE = "receive" # 입고 담당
|
||
ROLES = (ROLE_ORDER, ROLE_RECEIVE)
|
||
ROLE_LABELS = {ROLE_ORDER: "발주 담당", ROLE_RECEIVE: "입고 담당"}
|
||
|
||
MAX_QTY = 10_000_000
|
||
MAX_LINES = 200
|
||
MEMO_MAX = 500
|
||
|
||
# 품목 상태
|
||
LINE_NONE, LINE_PARTIAL, LINE_DONE, LINE_OVER = "none", "partial", "done", "over"
|
||
LINE_LABELS = {LINE_NONE: "미입고", LINE_PARTIAL: "부분입고", LINE_DONE: "입고완료", LINE_OVER: "초과입고"}
|
||
|
||
# 발주서 상태 — 진행(open·partial)은 미입고 현황에 나온다
|
||
ST_OPEN, ST_PARTIAL, ST_DONE, ST_OVER, ST_CLOSED, ST_CANCELLED = "open", "partial", "done", "over", "closed", "cancelled"
|
||
# 모든 품목이 입고완료·초과입고 = "전체 입고 완료"(2026-10-17 요청 — 초과가 있으면 화면에 "초과 포함"만 덧붙인다)
|
||
ORDER_LABELS = {ST_OPEN: "발주", ST_PARTIAL: "부분입고", ST_DONE: "전체 입고 완료", ST_OVER: "전체 입고 완료",
|
||
ST_CLOSED: "종결", ST_CANCELLED: "취소"}
|
||
ACTIVE_STATUSES = (ST_OPEN, ST_PARTIAL) # 아직 더 들어올 것이 있는 발주
|
||
STATUS_FILTERS = { # 목록 거르기
|
||
"active": ("진행 중", ACTIVE_STATUSES),
|
||
"done": ("완료", (ST_DONE, ST_OVER)),
|
||
"closed": ("종결·취소", (ST_CLOSED, ST_CANCELLED)),
|
||
"all": ("전체", tuple(ORDER_LABELS)),
|
||
}
|
||
|
||
|
||
WEEKDAYS_KO = "월화수목금토일"
|
||
|
||
|
||
def fmt_date(d: date | None) -> str:
|
||
"""날짜 서식 — 2026.10.17(토). 입출고 화면·메일 모두 이 모양(2026-10-17 요청). 화면 쪽은 _macros.html ymd 와 같다."""
|
||
if not d:
|
||
return ""
|
||
return f"{d:%Y.%m.%d}({WEEKDAYS_KO[d.weekday()]})"
|
||
|
||
|
||
def fmt_datetime(dt: datetime | None) -> str:
|
||
"""2026.10.17(토) 15:14 — 시각은 DB 에서 KST 로 읽는다(db._KstTimestamptzLoader)."""
|
||
return f"{fmt_date(dt)} {dt:%H:%M}" if dt else ""
|
||
|
||
|
||
def line_status(qty: int, received: int) -> str:
|
||
if received <= 0:
|
||
return LINE_NONE
|
||
if received < qty:
|
||
return LINE_PARTIAL
|
||
return LINE_DONE if received == qty else LINE_OVER
|
||
|
||
|
||
def order_status(lines: Iterable[dict[str, Any]], *, closed: bool = False, cancelled: bool = False) -> str:
|
||
"""lines: [{qty, received}]. 취소·종결이 먼저, 그다음 입고 합계로."""
|
||
if cancelled:
|
||
return ST_CANCELLED
|
||
if closed:
|
||
return ST_CLOSED
|
||
sts = [line_status(int(x["qty"]), int(x.get("received") or 0)) for x in lines]
|
||
if not sts or all(s == LINE_NONE for s in sts):
|
||
return ST_OPEN
|
||
if any(s in (LINE_NONE, LINE_PARTIAL) for s in sts):
|
||
return ST_PARTIAL
|
||
return ST_OVER if any(s == LINE_OVER for s in sts) else ST_DONE
|
||
|
||
|
||
def summarize(lines: list[dict[str, Any]]) -> dict[str, int]:
|
||
"""발주·입고·미입고(0 아래로 안 내려감)·초과 합계."""
|
||
ordered = sum(int(x["qty"]) for x in lines)
|
||
received = sum(int(x.get("received") or 0) for x in lines)
|
||
remaining = sum(max(int(x["qty"]) - int(x.get("received") or 0), 0) for x in lines)
|
||
over = sum(max(int(x.get("received") or 0) - int(x["qty"]), 0) for x in lines)
|
||
pct = min(100, round(received * 100 / ordered)) if ordered else 0
|
||
return {"ordered": ordered, "received": received, "remaining": remaining, "over": over, "pct": pct}
|
||
|
||
|
||
def decorate_lines(lines: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||
"""화면용 — 품목마다 미입고·초과·상태 이름."""
|
||
out = []
|
||
for x in lines:
|
||
qty, rec = int(x["qty"]), int(x.get("received") or 0)
|
||
st = line_status(qty, rec)
|
||
out.append({**x, "received": rec, "remaining": max(qty - rec, 0), "over": max(rec - qty, 0),
|
||
"status": st, "status_label": LINE_LABELS[st]})
|
||
return out
|
||
|
||
|
||
# ── 입력 검사 ────────────────────────────────────────────────
|
||
def parse_qty(raw: Any, *, label: str = "수량", allow_zero: bool = False) -> int:
|
||
s = str(raw if raw is not None else "").replace(",", "").strip()
|
||
if not s:
|
||
if allow_zero:
|
||
return 0
|
||
raise ValueError(f"{label}을(를) 입력하세요.")
|
||
try:
|
||
n = int(s)
|
||
except ValueError:
|
||
raise ValueError(f"{label}은(는) 정수로 입력하세요.") from None
|
||
if n < 0 or (n == 0 and not allow_zero):
|
||
raise ValueError(f"{label}은(는) {0 if allow_zero else 1} 이상이어야 합니다.")
|
||
if n > MAX_QTY:
|
||
raise ValueError(f"{label}이(가) 너무 큽니다.")
|
||
return n
|
||
|
||
|
||
def parse_date(raw: Any, *, label: str, required: bool = True) -> date | None:
|
||
s = str(raw or "").strip()
|
||
if not s:
|
||
if required:
|
||
raise ValueError(f"{label}을(를) 입력하세요.")
|
||
return None
|
||
try:
|
||
return date.fromisoformat(s)
|
||
except ValueError:
|
||
raise ValueError(f"{label} 형식이 올바르지 않습니다(YYYY-MM-DD).") from None
|
||
|
||
|
||
def validate_order(*, factory_id: Any, order_date: Any, due_date: Any, memo: Any,
|
||
codes: list[str], quantities: list[str], line_memos: list[str] | None = None) -> dict[str, Any]:
|
||
"""발주서 폼 → 정리된 값. 빈 줄(코드·수량 둘 다 없음)은 건너뛴다. 같은 제품 두 줄은 오류."""
|
||
errors: list[str] = []
|
||
try:
|
||
fid = int(str(factory_id or "").strip())
|
||
except ValueError:
|
||
fid = 0
|
||
if fid <= 0:
|
||
errors.append("공장을 고르세요.")
|
||
od = dd = None
|
||
try:
|
||
od = parse_date(order_date, label="발주일")
|
||
except ValueError as exc:
|
||
errors.append(str(exc))
|
||
try:
|
||
dd = parse_date(due_date, label="입고 예정일", required=False)
|
||
except ValueError as exc:
|
||
errors.append(str(exc))
|
||
if od and dd and dd < od:
|
||
errors.append("입고 예정일이 발주일보다 빠릅니다.")
|
||
line_memos = line_memos or []
|
||
lines: list[dict[str, Any]] = []
|
||
seen: set[str] = set()
|
||
for i, code in enumerate(codes):
|
||
code = (code or "").strip().upper()
|
||
raw_qty = quantities[i] if i < len(quantities) else ""
|
||
if not code and not str(raw_qty or "").strip():
|
||
continue
|
||
if not code:
|
||
errors.append(f"{i + 1}번째 줄: 제품을 고르세요.")
|
||
continue
|
||
if code in seen:
|
||
errors.append(f"{code}: 같은 제품이 두 줄에 있습니다 — 한 줄로 합쳐 주세요.")
|
||
continue
|
||
seen.add(code)
|
||
try:
|
||
qty = parse_qty(raw_qty, label=f"{code} 발주 수량")
|
||
except ValueError as exc:
|
||
errors.append(str(exc))
|
||
continue
|
||
lines.append({"item_code": code, "qty": qty,
|
||
"memo": str(line_memos[i] if i < len(line_memos) else "").strip()[:MEMO_MAX]})
|
||
if not lines and not any("줄" in e or "수량" in e for e in errors):
|
||
errors.append("발주할 제품을 한 줄 이상 넣으세요.")
|
||
if len(lines) > MAX_LINES:
|
||
errors.append(f"한 발주서에 {MAX_LINES}개 제품까지 넣을 수 있습니다.")
|
||
if errors:
|
||
raise ValueError("\n".join(errors))
|
||
return {"factory_id": fid, "order_date": od, "due_date": dd, "memo": str(memo or "").strip()[:MEMO_MAX], "lines": lines}
|
||
|
||
|
||
def validate_receipt(order_lines: list[dict[str, Any]], quantities: dict[int, Any], *,
|
||
receipt_date: Any, memo: Any) -> dict[str, Any]:
|
||
"""입고 입력 — quantities: {발주 줄 id: 입력값}. 빈칸·0 은 이번에 안 들어온 것.
|
||
over = 이번 입고로 발주를 넘는 품목(확인 받은 뒤 저장). order_lines 는 지금까지 누적 입고(received)를 포함."""
|
||
errors: list[str] = []
|
||
try:
|
||
rd = parse_date(receipt_date, label="입고일")
|
||
except ValueError as exc:
|
||
errors.append(str(exc))
|
||
rd = None
|
||
by_id = {int(x["id"]): x for x in order_lines}
|
||
items: list[dict[str, Any]] = []
|
||
over: list[dict[str, Any]] = []
|
||
for lid, raw in quantities.items():
|
||
line = by_id.get(int(lid))
|
||
if line is None:
|
||
errors.append("이 발주서에 없는 품목이 들어 있습니다.")
|
||
continue
|
||
try:
|
||
qty = parse_qty(raw, label=f"{line['item_code']} 입고 수량", allow_zero=True)
|
||
except ValueError as exc:
|
||
errors.append(str(exc))
|
||
continue
|
||
if qty == 0:
|
||
continue
|
||
items.append({"order_line_id": int(lid), "qty": qty})
|
||
after = int(line.get("received") or 0) + qty
|
||
if after > int(line["qty"]):
|
||
over.append({"item_code": line["item_code"], "item_name": line.get("item_name", ""),
|
||
"ordered": int(line["qty"]), "after": after, "over": after - int(line["qty"])})
|
||
if not items and not errors:
|
||
errors.append("입고 수량을 한 품목 이상 넣으세요.")
|
||
if errors:
|
||
raise ValueError("\n".join(errors))
|
||
return {"receipt_date": rd, "memo": str(memo or "").strip()[:MEMO_MAX], "items": items, "over": over}
|
||
|
||
|
||
def order_no(order_date: date, seq: int) -> str:
|
||
"""PO-YYMMDD-NN — 발주일 기준 그날 순번(01부터)."""
|
||
return f"PO-{order_date:%y%m%d}-{seq:02d}"
|
||
|
||
|
||
# ════════════════════════════════════════════════════════════
|
||
# 발주 메일(2026-10-16, 마이그레이션 003) — 받는 주소 검사, 본문(요약) 만들기. 보내기는 gmail.py
|
||
# ════════════════════════════════════════════════════════════
|
||
MAX_RECIPIENTS = 10
|
||
_EMAIL_RE = re.compile(r"^[A-Za-z0-9._%+\-']+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}$")
|
||
|
||
|
||
def parse_emails(raw: Any, *, label: str = "이메일", required: bool = False) -> list[str]:
|
||
"""'a@x.com, b@y.co.kr; c@z.com' → 주소 목록(순서 유지·중복 제거). 형식이 틀리면 ValueError."""
|
||
out: list[str] = []
|
||
for part in re.split(r"[\s,;]+", str(raw or "")):
|
||
if not part:
|
||
continue
|
||
if not _EMAIL_RE.match(part) or len(part) > 254:
|
||
raise ValueError(f"{label} 형식이 올바르지 않습니다: {part[:60]}")
|
||
if part.lower() not in [x.lower() for x in out]:
|
||
out.append(part)
|
||
if required and not out:
|
||
raise ValueError(f"{label}을(를) 입력하세요.")
|
||
if len(out) > MAX_RECIPIENTS:
|
||
raise ValueError(f"{label}은(는) {MAX_RECIPIENTS}개까지 넣을 수 있습니다.")
|
||
return out
|
||
|
||
|
||
def order_mail(order: dict[str, Any], *, sender_name: str, sender_email: str) -> dict[str, str]:
|
||
"""발주서 → 메일 제목·글 본문·HTML 본문(요약). order = db.get_order 결과.
|
||
품목마다 단가·금액(수량 × 단가)·전체 무게(개당 g × 수량, kg)·PP 사용량(전체 무게 − 은 무게, kg)·은 함유량(%·전체 무게 × %, kg)
|
||
— 발주 품목에 남긴 그때 값(004). 없으면 '-'. (2026-10-19 — 예전엔 PP(g/개)·개당 은 g)"""
|
||
lines = order["lines"]
|
||
first = (lines[0]["item_name"] or lines[0]["item_code"]) if lines else ""
|
||
more = f" 외 {len(lines) - 1}종" if len(lines) > 1 else ""
|
||
subject = f"[발주] {order['order_no']} · {order['factory_name']} · {first}{more}"
|
||
total = sum(int(x["qty"]) for x in lines)
|
||
money = order_totals(lines)
|
||
due = fmt_date(order["due_date"]) if order.get("due_date") else "협의"
|
||
greet = f"{order['factory_manager']}님, 안녕하세요." if order.get("factory_manager") else "안녕하세요."
|
||
who = sender_name or sender_email
|
||
facts = [("발주번호", order["order_no"]), ("발주일", fmt_date(order["order_date"])),
|
||
("입고 예정일", due), ("품목", f"{len(lines)}종 · 총 {total:,}개")]
|
||
if money["amount"] is not None:
|
||
note = f" (단가 미입력 {money['missing_price']}종 제외)" if money["missing_price"] else ""
|
||
facts.append(("발주 금액", f"{fmt_num(money['amount'])}원{note}"))
|
||
ag_kg = money["silver_g"] / Decimal(1000) if money["silver_g"] is not None else None
|
||
if money["pp_kg"] is not None:
|
||
facts.append(("전체 무게", f"{fmt_num(money['pp_kg'], 3)} kg"))
|
||
if money["pp_use_kg"] is not None:
|
||
facts.append(("PP 사용량", f"{fmt_num(money['pp_use_kg'], 3)} kg"))
|
||
if ag_kg is not None:
|
||
facts.append(("은(Ag) 총량", f"{fmt_num(ag_kg, 4)} kg"))
|
||
if order.get("memo"):
|
||
facts.append(("요청 사항", order["memo"]))
|
||
|
||
def cells(x: dict[str, Any]) -> dict[str, str]:
|
||
price, pct = to_dec(x.get("unit_price")), to_dec(x.get("silver_pct"))
|
||
amt = line_amount(int(x["qty"]), price)
|
||
use = line_usage(x)
|
||
total_kg, ag_kg = use["total_kg"], use["ag_kg"]
|
||
return {"price": fmt_num(price) if price is not None else "-", "amount": fmt_num(amt) if amt is not None else "-",
|
||
"weight": fmt_num(total_kg, 3) if total_kg is not None else "-",
|
||
"pp_use": fmt_num(total_kg - ag_kg, 3) if ag_kg is not None else "-",
|
||
"ag": (f"{fmt_num(pct, 4)}%" + (f" ({fmt_num(ag_kg, 4)}kg)" if ag_kg is not None else "")) if pct is not None else "-"}
|
||
|
||
# 글 본문(HTML 을 못 보는 메일 프로그램용)
|
||
text = [greet, "", "아래와 같이 제품 제작을 발주합니다.", ""]
|
||
text += [f"- {k}: {v}" for k, v in facts]
|
||
text += ["", "[발주 품목] 수량 · 단가 · 금액 · 전체 무게 · PP 사용량 · 은 함유량"]
|
||
for i, x in enumerate(lines, start=1):
|
||
c = cells(x)
|
||
text.append(f"{i}. {x['item_code']} {x['item_name']} — {int(x['qty']):,}개 · 단가 {c['price']} · 금액 {c['amount']}"
|
||
f" · 전체 무게 {c['weight'] + 'kg' if c['weight'] != '-' else '-'}"
|
||
f" · PP 사용량 {c['pp_use'] + 'kg' if c['pp_use'] != '-' else '-'} · 은 {c['ag']}"
|
||
+ (f" ({x['memo']})" if x.get("memo") else ""))
|
||
text += ["", "입고 예정일까지 물류로 입고 부탁드리며, 일정이 바뀌면 회신 부탁드립니다.", "", f"발주 담당: {who} ({sender_email})"]
|
||
# HTML 본문 — 값은 모두 escape
|
||
e = _html.escape
|
||
td = "padding:6px 10px;border:1px solid #d9dce1;"
|
||
r = "text-align:right;white-space:nowrap;"
|
||
# 요약 표 = 항목·값 두 쌍씩 한 줄(4열, 2026-10-19 — 예전 2열 × 8행). 요청 사항(길 수 있음)은 맨 아래 한 줄 전체.
|
||
# 칸 높이는 글자 한 줄에 맞게 — 받은 메일(메일 프로그램)에서 칸이 크게 늘어나 보여 줄 높이·글자 크기·위아래 여백을 칸마다 못 박는다.
|
||
ftd = "padding:4px 10px;border:1px solid #d9dce1;font-size:14px;line-height:20px;height:20px;vertical-align:middle;white-space:nowrap;"
|
||
fth = f"{ftd}background:#f6f7f9;text-align:left;font-weight:700;"
|
||
pairs = [(k, v) for k, v in facts if k != "요청 사항"]
|
||
fact_rows = ""
|
||
for i in range(0, len(pairs), 2):
|
||
cols = "".join(f'<th style="{fth}">{e(k)}</th><td style="{ftd}">{e(str(v))}</td>' for k, v in pairs[i:i + 2])
|
||
if len(pairs[i:i + 2]) == 1:
|
||
cols += f'<th style="{fth}"></th><td style="{ftd}"></td>'
|
||
fact_rows += f"<tr>{cols}</tr>"
|
||
if order.get("memo"): # 요청 사항은 길면 줄을 바꿔야 하므로 높이를 고정하지 않는다
|
||
memo_td = "padding:4px 10px;border:1px solid #d9dce1;font-size:14px;line-height:20px;vertical-align:middle;"
|
||
fact_rows += (f'<tr><th style="{fth}">요청 사항</th>'
|
||
f'<td colspan="3" style="{memo_td}">{e(str(order["memo"]))}</td></tr>')
|
||
rows = []
|
||
for i, x in enumerate(lines, start=1):
|
||
c = cells(x)
|
||
# 색상 있는 품목(006) = 줄 전체 배경 그 색 — 메일 프로그램이 tr 배경을 무시하기도 해서 칸마다도 칠한다
|
||
hexc = color_hex(x.get("color"))
|
||
ctd = f"{td}background:{hexc};" if hexc else td
|
||
tr_style = f' style="background:{hexc}"' if hexc else ""
|
||
rows.append(
|
||
f'<tr{tr_style}><td style="{ctd}text-align:center">{i}</td>'
|
||
f'<td style="{ctd}font-family:Consolas,monospace">{e(x["item_code"])}</td>'
|
||
f'<td style="{ctd}">{e(x["item_name"])}</td><td style="{ctd}{r}">{int(x["qty"]):,}</td>'
|
||
f'<td style="{ctd}{r}">{e(c["price"])}</td><td style="{ctd}{r}">{e(c["amount"])}</td>'
|
||
f'<td style="{ctd}{r}">{e(c["weight"])}</td><td style="{ctd}{r}">{e(c["pp_use"])}</td><td style="{ctd}{r}">{e(c["ag"])}</td>'
|
||
f'<td style="{ctd}">{e(x.get("memo") or "")}</td></tr>')
|
||
# 합계 줄(2026-10-21) — 금액 뒤 " 원", 무게 뒤 " kg", 무게는 소수 첫째 자리에서 반올림(정수 kg)
|
||
foot_amount = f'{fmt_num(money["amount"])} 원' if money["amount"] is not None else ""
|
||
foot_pp = f'{fmt_num(money["pp_kg"], 0)} kg' if money["pp_kg"] is not None else ""
|
||
foot_use = f'{fmt_num(money["pp_use_kg"], 0)} kg' if money["pp_use_kg"] is not None else ""
|
||
foot_ag = f'{fmt_num(ag_kg, 0)} kg' if ag_kg is not None else ""
|
||
bg = "background:#f6f7f9;"
|
||
html = (
|
||
'<div style="font-family:\'Malgun Gothic\',\'Apple SD Gothic Neo\',sans-serif;font-size:14px;color:#1d1d1f;line-height:1.6">'
|
||
f"<p>{e(greet)}<br>아래와 같이 제품 제작을 발주합니다.</p>"
|
||
f'<table cellpadding="0" cellspacing="0" style="border-collapse:collapse;margin:8px 0 0">{fact_rows}</table>'
|
||
# 두 표 사이 18px — 표 margin 은 메일 프로그램마다 무시되기도 해서 높이 18px 빈 줄로 띄운다
|
||
'<div style="height:18px;line-height:18px;font-size:1px"> </div>'
|
||
'<table style="border-collapse:collapse;min-width:640px;margin:0">'
|
||
f'<thead><tr style="{bg}"><th style="{td}">No</th><th style="{td}">제품 코드</th><th style="{td}">제품명</th>'
|
||
f'<th style="{td}">수량</th><th style="{td}">단가(원)</th><th style="{td}">금액(원)</th>'
|
||
f'<th style="{td}">전체 무게(kg)</th><th style="{td}">PP 사용량(kg)</th><th style="{td}">은(Ag) 함유량</th>'
|
||
f'<th style="{td}">비고</th></tr></thead>'
|
||
f'<tbody>{"".join(rows)}</tbody>'
|
||
f'<tfoot><tr><th colspan="3" style="{td}{bg}text-align:right">합계</th>'
|
||
f'<th style="{td}{bg}{r}">{total:,}</th><th style="{td}{bg}"></th><th style="{td}{bg}{r}">{e(foot_amount)}</th>'
|
||
f'<th style="{td}{bg}{r}">{e(foot_pp)}</th><th style="{td}{bg}{r}">{e(foot_use)}</th><th style="{td}{bg}{r}">{e(foot_ag)}</th>'
|
||
f'<th style="{td}{bg}"></th></tr></tfoot></table>'
|
||
"<p>입고 예정일까지 물류로 입고 부탁드리며, 일정이 바뀌면 회신 부탁드립니다.</p>"
|
||
f'<p style="color:#555">발주 담당: {e(who)} (<a href="mailto:{e(sender_email)}">{e(sender_email)}</a>)</p></div>'
|
||
)
|
||
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 == "text-decoration-line": # 서식 막대(Chrome execCommand)가 밑줄·취소선을 이렇게 만든다 — 메일 프로그램은 text-decoration 만 아는 곳이 많다
|
||
prop = "text-decoration"
|
||
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).
|
||
# ════════════════════════════════════════════════════════════
|
||
PRODUCT_LIMITS = {"unit_price": ("단가", Decimal("1000000000"), 2), "weight_g": ("무게", Decimal("1000000"), 2),
|
||
"silver_pct": ("은 함유량", Decimal("100"), 4)}
|
||
|
||
|
||
def to_dec(v: Any) -> Decimal | None:
|
||
if v is None or v == "":
|
||
return None
|
||
try:
|
||
return Decimal(str(v))
|
||
except (InvalidOperation, ValueError):
|
||
return None
|
||
|
||
|
||
def fmt_num(v: Any, places: int = 2) -> str:
|
||
"""1234.50 → '1,234.5', 1234 → '1,234' (소수 끝 0 은 뺀다)."""
|
||
d = to_dec(v)
|
||
if d is None:
|
||
return ""
|
||
q = d.quantize(Decimal(1).scaleb(-places), rounding=ROUND_HALF_UP)
|
||
s = f"{q:,.{places}f}"
|
||
return s.rstrip("0").rstrip(".") if "." in s else s
|
||
|
||
|
||
def silver_g(weight_g: Any, silver_pct: Any) -> Decimal | None:
|
||
w, p = to_dec(weight_g), to_dec(silver_pct)
|
||
if w is None or p is None:
|
||
return None
|
||
return (w * p / Decimal(100)).quantize(Decimal("0.0001"), rounding=ROUND_HALF_UP)
|
||
|
||
|
||
def line_usage(x: dict[str, Any]) -> dict[str, Decimal | None]:
|
||
"""발주 품목 한 줄의 발주 수량 전체 사용량(kg) — 전체 무게 = 개당 g × 수량, 은 = 전체 무게 × %, PP 사용량 = 전체 − 은
|
||
(은 함유량이 없으면 PP 사용량도 없음 — order_totals 의 pp_use_kg 와 같은 기준). 메일 표·발주서 화면 품목 표가 같이 쓴다."""
|
||
w, pct, q = to_dec(x.get("weight_g")), to_dec(x.get("silver_pct")), int(x["qty"])
|
||
total_kg = w * q / Decimal(1000) if w is not None else None
|
||
ag_kg = total_kg * pct / Decimal(100) if total_kg is not None and pct is not None else None
|
||
return {"total_kg": total_kg, "ag_kg": ag_kg, "pp_use_kg": total_kg - ag_kg if ag_kg is not None else None}
|
||
|
||
|
||
def line_amount(qty: int, unit_price: Any) -> Decimal | None:
|
||
p = to_dec(unit_price)
|
||
return None if p is None else (p * int(qty)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
|
||
|
||
|
||
def order_totals(lines: list[dict[str, Any]]) -> dict[str, Any]:
|
||
"""발주 금액 합(단가 있는 줄만, 없으면 None)·단가 없는 줄 수·PP 총량(= 전체 무게, kg)·은 총량(g)·
|
||
PP 사용량(kg, 무게·은 함유량이 다 있는 줄의 전체 무게 − 은 무게 — 메일 표, 2026-10-19)."""
|
||
amount = pp = ag = use = None
|
||
missing = 0
|
||
for x in lines:
|
||
q = int(x["qty"])
|
||
a = line_amount(q, x.get("unit_price"))
|
||
if a is None:
|
||
missing += 1
|
||
else:
|
||
amount = (amount or Decimal(0)) + a
|
||
w = to_dec(x.get("weight_g"))
|
||
if w is not None:
|
||
pp = (pp or Decimal(0)) + w * q / Decimal(1000)
|
||
p = to_dec(x.get("silver_pct"))
|
||
if w is not None and p is not None: # 개당 은 g 를 반올림하기 전 값으로 곱한다(합계 오차 방지)
|
||
ag = (ag or Decimal(0)) + w * p / Decimal(100) * q
|
||
use = (use or Decimal(0)) + w * q * (Decimal(100) - p) / Decimal(100000)
|
||
return {"amount": amount, "missing_price": missing if amount is not None else len(lines), "pp_kg": pp, "silver_g": ag,
|
||
"pp_use_kg": use}
|
||
|
||
|
||
def parse_decimal(raw: Any, *, key: str) -> Decimal | None:
|
||
"""상품 정보 칸 하나 — 빈칸은 None(미입력), 숫자·쉼표·0 이상·한도 안·소수 자리."""
|
||
label, limit, places = PRODUCT_LIMITS[key]
|
||
s = str(raw if raw is not None else "").replace(",", "").replace("%", "").strip()
|
||
if not s:
|
||
return None
|
||
try:
|
||
d = Decimal(s)
|
||
except InvalidOperation:
|
||
raise ValueError(f"{label}은(는) 숫자로 입력하세요.") from None
|
||
if not d.is_finite() or d < 0:
|
||
raise ValueError(f"{label}은(는) 0 이상이어야 합니다.")
|
||
if d > limit:
|
||
raise ValueError(f"{label}이(가) 너무 큽니다(최대 {fmt_num(limit, 0)}).")
|
||
return d.quantize(Decimal(1).scaleb(-places), rounding=ROUND_HALF_UP)
|
||
|
||
|
||
def validate_product_values(values: dict[str, Any]) -> dict[str, Decimal | None]:
|
||
"""{"unit_price","weight_g","silver_pct"} → 정리된 값. 틀리면 ValueError(칸 이름 포함)."""
|
||
return {k: parse_decimal(values.get(k), key=k) for k in PRODUCT_LIMITS}
|
||
|
||
|
||
def has_values(p: dict[str, Any]) -> bool:
|
||
"""단가·무게·은 함유량(·그룹·색상 006·박스 입수 007) 중 하나라도 넣었나 — 넣은 상품은 다시 불러와도 그대로 둔다."""
|
||
return (any(p.get(k) is not None for k in PRODUCT_LIMITS) or p.get("group_id") is not None
|
||
or (p.get("color") or "none") != "none" or any(p.get(k) is not None for k in BOX_FIELDS))
|
||
|
||
|
||
# ════════════════════════════════════════════════════════════
|
||
# 박스 입수(2026-10-21, 마이그레이션 007) — 통·뚜껑이 한 박스에 몇 개. 뚜껑이 없는 상품은 빈칸.
|
||
# 새 발주서 화면이 수량 → 통·뚜껑 박스 수(올림)·전체 파렛트(1파렛트 = PALLET_BOXES 박스, 올림)를 계산한다(메일엔 안 넣음).
|
||
# ════════════════════════════════════════════════════════════
|
||
BOX_FIELDS = {"body_per_box": "통 수량(박스)", "lid_per_box": "뚜껑 수량(박스)"}
|
||
MAX_PER_BOX = 1_000_000
|
||
PALLET_BOXES = 30
|
||
|
||
|
||
def parse_per_box(raw: Any, *, key: str) -> int | None:
|
||
"""박스 입수 칸 하나 — 빈칸은 None(없음·미입력), 1 이상 정수(쉼표 허용)."""
|
||
label = BOX_FIELDS[key]
|
||
s = str(raw if raw is not None else "").replace(",", "").strip()
|
||
if not s:
|
||
return None
|
||
if not s.isdigit():
|
||
raise ValueError(f"{label}은(는) 1 이상 정수로 입력하세요.")
|
||
n = int(s)
|
||
if n < 1:
|
||
raise ValueError(f"{label}은(는) 1 이상이어야 합니다(뚜껑이 없으면 빈칸).")
|
||
if n > MAX_PER_BOX:
|
||
raise ValueError(f"{label}이(가) 너무 큽니다.")
|
||
return n
|
||
|
||
|
||
def validate_box_values(values: dict[str, Any]) -> dict[str, int | None]:
|
||
return {k: parse_per_box(values.get(k), key=k) for k in BOX_FIELDS}
|
||
|
||
|
||
# ════════════════════════════════════════════════════════════
|
||
# 상품 그룹·색상(2026-10-21, 마이그레이션 006)
|
||
# 그룹에 은 함유량·색상을 한 번만 — 그룹 상품은 그룹 값, 그룹 없는 상품은 자기 값(effective_product).
|
||
# 색상 = 키 → (이름, 칸 색). 발주 메일 품목 표에서 색상 있는 품목 줄 전체 배경 = 칸 색(옅게 — 글자가 읽히게).
|
||
# ════════════════════════════════════════════════════════════
|
||
COLORS = {"none": ("색없음", ""), "orange": ("오렌지", "#FFD8B0"), "blue": ("파랑", "#CFE0FA"),
|
||
"gray": ("회색", "#DDDFE3"), "ivory": ("아이보리색", "#FFF6D9")}
|
||
MAX_GROUP_NAME = 100
|
||
|
||
|
||
def norm_color(raw: Any) -> str:
|
||
"""색상 키(none·orange·blue·gray·ivory). 빈칸 = none. 모르는 값은 ValueError."""
|
||
key = str(raw if raw is not None else "").strip().lower() or "none"
|
||
if key not in COLORS:
|
||
raise ValueError("색상은 " + "·".join(v[0] for v in COLORS.values()) + " 중에서 고르세요.")
|
||
return key
|
||
|
||
|
||
def color_hex(key: Any) -> str:
|
||
"""색상 키 → 칸 색(#RRGGBB). 색없음·모름 = ''."""
|
||
return COLORS.get(str(key or "none"), ("", ""))[1]
|
||
|
||
|
||
def color_name(key: Any) -> str:
|
||
return COLORS.get(str(key or "none"), COLORS["none"])[0]
|
||
|
||
|
||
def validate_group(values: dict[str, Any]) -> dict[str, Any]:
|
||
"""그룹 저장 값 — 이름(필수, 100자)·은 함유량(빈칸 = 미입력)·색상·순서."""
|
||
name = str(values.get("name") or "").strip()
|
||
if not name:
|
||
raise ValueError("그룹 이름을 넣으세요.")
|
||
if len(name) > MAX_GROUP_NAME:
|
||
raise ValueError(f"그룹 이름은 {MAX_GROUP_NAME}자까지입니다.")
|
||
try:
|
||
sort_order = int(str(values.get("sort_order") or "0").strip() or 0)
|
||
except ValueError:
|
||
raise ValueError("순서는 숫자로 넣으세요.") from None
|
||
return {"name": name, "silver_pct": parse_decimal(values.get("silver_pct"), key="silver_pct"),
|
||
"color": norm_color(values.get("color")), "sort_order": max(-9999, min(9999, sort_order))}
|
||
|
||
|
||
# ════════════════════════════════════════════════════════════
|
||
# 입고증 사진(2026-10-16, 마이그레이션 003)
|
||
# ════════════════════════════════════════════════════════════
|
||
MAX_PHOTOS = 10 # 입고 한 건에
|
||
MAX_PHOTO_BYTES = 10 * 1024 * 1024 # 한 장(브라우저가 줄여서 보내므로 보통 0.3~1MB)
|
||
|
||
|
||
def sniff_image(data: bytes) -> str | None:
|
||
"""파일 머리로 이미지 종류 판단(브라우저가 보낸 종류는 믿지 않는다). 모르면 None."""
|
||
if data[:3] == b"\xff\xd8\xff":
|
||
return "image/jpeg"
|
||
if data[:8] == b"\x89PNG\r\n\x1a\n":
|
||
return "image/png"
|
||
if data[:4] == b"RIFF" and data[8:12] == b"WEBP":
|
||
return "image/webp"
|
||
if data[:6] in (b"GIF87a", b"GIF89a"):
|
||
return "image/gif"
|
||
if data[4:12] in (b"ftypheic", b"ftypheix", b"ftypmif1", b"ftyphevc", b"ftypheif"):
|
||
return "image/heic" # 아이폰 원본 — 사파리 외 브라우저는 미리보기 못 함(내려받기)
|
||
return None
|
||
|
||
|
||
def validate_photos(files: list[tuple[str, bytes]], *, existing: int = 0) -> list[dict[str, Any]]:
|
||
"""[(파일 이름, 내용)] → [{filename, content_type, data}]. 빈 파일은 건너뛴다. 하나라도 틀리면 ValueError."""
|
||
out: list[dict[str, Any]] = []
|
||
for name, data in files:
|
||
if not data:
|
||
continue
|
||
name = (name or "photo").replace("\\", "/").rsplit("/", 1)[-1][:120]
|
||
if len(data) > MAX_PHOTO_BYTES:
|
||
raise ValueError(f"사진이 너무 큽니다(한 장 {MAX_PHOTO_BYTES // 1024 // 1024}MB까지): {name}")
|
||
ctype = sniff_image(data)
|
||
if ctype is None:
|
||
raise ValueError(f"사진 파일(JPG·PNG·WEBP·GIF·HEIC)만 올릴 수 있습니다: {name}")
|
||
out.append({"filename": name, "content_type": ctype, "data": data})
|
||
if existing + len(out) > MAX_PHOTOS:
|
||
raise ValueError(f"입고 한 건에 사진은 {MAX_PHOTOS}장까지입니다.")
|
||
return out
|
||
|
||
|
||
def rotate_image(data: bytes, degrees: int) -> bytes:
|
||
"""사진 내용을 시계 방향 90·270도로 돌려 같은 형식으로(2026-11-02). 휴대폰 사진의 회전 정보(EXIF)는 픽셀에 반영한 뒤 돌린다."""
|
||
from io import BytesIO # noqa: WPS433
|
||
|
||
from PIL import Image, ImageOps # noqa: WPS433
|
||
|
||
if degrees not in (90, 270):
|
||
raise ValueError("사진은 왼쪽·오른쪽으로만 돌릴 수 있습니다.")
|
||
kind = sniff_image(data)
|
||
if kind == "image/heic":
|
||
raise ValueError("HEIC 사진은 돌릴 수 없습니다 — JPG 로 바꿔 다시 올려 주세요.")
|
||
try:
|
||
im = Image.open(BytesIO(data))
|
||
if getattr(im, "n_frames", 1) > 1:
|
||
raise ValueError("움직이는 사진은 돌릴 수 없습니다.")
|
||
icc = im.info.get("icc_profile")
|
||
im = ImageOps.exif_transpose(im)
|
||
# PIL 의 ROTATE_n 은 반시계 방향 — 시계 90도 = ROTATE_270
|
||
im = im.transpose(Image.Transpose.ROTATE_270 if degrees == 90 else Image.Transpose.ROTATE_90)
|
||
fmt = {"image/jpeg": "JPEG", "image/png": "PNG", "image/webp": "WEBP", "image/gif": "GIF"}[kind]
|
||
opts: dict[str, Any] = {"icc_profile": icc} if icc and fmt != "GIF" else {}
|
||
if fmt in ("JPEG", "WEBP"):
|
||
opts["quality"] = 92
|
||
buf = BytesIO()
|
||
im.save(buf, format=fmt, **opts)
|
||
except ValueError:
|
||
raise
|
||
except Exception as exc: # noqa: BLE001 — 깨진 파일 등(원본은 그대로 둔다)
|
||
raise ValueError("이 사진은 돌릴 수 없습니다.") from exc
|
||
out = buf.getvalue()
|
||
if len(out) > MAX_PHOTO_BYTES:
|
||
raise ValueError(f"돌린 사진이 너무 큽니다(한 장 {MAX_PHOTO_BYTES // 1024 // 1024}MB까지).")
|
||
return out
|
||
|
||
|
||
# ════════════════════════════════════════════════════════════
|
||
# 입고 요청 메일(2026-10-19, 마이그레이션 005) — 입고 담당이 입고를 저장한 뒤 물류센터 입고 담당자에게
|
||
# "전산 등록 부탁" 메일(입고 담당 본인 Gmail). 받는 사람 = 옵션 → 물류센터 이메일, 참조 기본 = king@·bj@dbxcorp.co.kr.
|
||
# 본문 = 입고 상품 표(상품 이름·상품 코드·입고 수량·비고) + 입고증 사진을 본문 안 이미지(CID, 첨부 아님, 가로 600px 이하).
|
||
# ════════════════════════════════════════════════════════════
|
||
SETTING_LOGISTICS_EMAILS = "logistics_emails"
|
||
SETTING_RECEIPT_MAIL_CC = "receipt_mail_cc"
|
||
SETTING_ORDER_MAIL_CC = "order_mail_cc" # 발주 메일 참조 기본값(2026-10-19 — king@, 옵션 → 공장에서 고침)
|
||
SETTING_DEFAULTS = {SETTING_LOGISTICS_EMAILS: "", SETTING_RECEIPT_MAIL_CC: "king@dbxcorp.co.kr, bj@dbxcorp.co.kr",
|
||
SETTING_ORDER_MAIL_CC: "king@dbxcorp.co.kr"}
|
||
MAIL_IMAGE_MAX_W = 600
|
||
|
||
|
||
def clean_emails(raw: Any, *, label: str) -> str:
|
||
"""옵션 저장용 — 주소 검사 후 'a@x.com, b@y.com' 로 다시 씀(비우면 '')."""
|
||
return ", ".join(parse_emails(raw, label=label))
|
||
|
||
|
||
def mail_images(photos: list[dict[str, Any]]) -> tuple[list[dict[str, Any]], int]:
|
||
"""입고증 사진 → 메일 본문용 JPEG(가로 최대 600px, 세로는 비율대로, 회전 정보 반영).
|
||
반환 ([{cid, data, width, height}], 못 넣은 장수) — HEIC 등 서버가 못 여는 사진은 빼고 센다."""
|
||
from io import BytesIO # noqa: WPS433
|
||
|
||
from PIL import Image, ImageOps # noqa: WPS433
|
||
|
||
out: list[dict[str, Any]] = []
|
||
skipped = 0
|
||
for ph in photos:
|
||
try:
|
||
im = Image.open(BytesIO(bytes(ph["data"])))
|
||
if im.format == "JPEG":
|
||
im.draft("RGB", (MAIL_IMAGE_MAX_W * 2, MAIL_IMAGE_MAX_W * 2)) # 큰 JPEG 는 줄여서 읽기(빠름)
|
||
im = ImageOps.exif_transpose(im)
|
||
if im.mode not in ("RGB", "L"):
|
||
rgba = im.convert("RGBA")
|
||
bg = Image.new("RGB", rgba.size, (255, 255, 255))
|
||
bg.paste(rgba, mask=rgba.split()[-1])
|
||
im = bg
|
||
if im.width > MAIL_IMAGE_MAX_W:
|
||
im = im.resize((MAIL_IMAGE_MAX_W, max(1, round(im.height * MAIL_IMAGE_MAX_W / im.width))), Image.LANCZOS)
|
||
buf = BytesIO()
|
||
im.convert("RGB").save(buf, "JPEG", quality=85, optimize=True)
|
||
except Exception: # noqa: BLE001 — HEIC·깨진 파일은 본문에서 뺀다(입고 기록의 사진은 그대로)
|
||
skipped += 1
|
||
continue
|
||
out.append({"cid": f"inout-photo-{ph['id']}@dbx", "data": buf.getvalue(), "width": im.width, "height": im.height})
|
||
return out, skipped
|
||
|
||
|
||
def receipt_mail_subject(receipt_date: date) -> str:
|
||
d = receipt_date
|
||
return f"[입고 요청] {d.year}년 {d.month:02d}월 {d.day:02d}일({WEEKDAYS_KO[d.weekday()]}) 입고 요청 합니다."
|
||
|
||
|
||
def receipt_mail(order: dict[str, Any], receipt: dict[str, Any], *, images: list[dict[str, Any]], skipped: int = 0,
|
||
sender_name: str, sender_email: str) -> dict[str, str]:
|
||
"""입고 1건 → 제목·글 본문·HTML 본문. 이미지는 <img src="cid:…"> (보낼 때 gmail.build_message 가 본문에 붙임).
|
||
비고 = 그 발주 품목의 줄 메모. 값은 모두 escape."""
|
||
memo_of = {int(ln["id"]): (ln.get("memo") or "") for ln in order["lines"]}
|
||
rows = [{"name": x["item_name"], "code": x["item_code"], "qty": int(x["qty"]), "note": memo_of.get(int(x["order_line_id"]), "")}
|
||
for x in receipt["lines"]]
|
||
total = sum(r["qty"] for r in rows)
|
||
who = sender_name or sender_email
|
||
when = fmt_date(receipt["receipt_date"])
|
||
info = f"입고일 {when} · 발주번호 {order['order_no']} · 공장 {order['factory_name']}"
|
||
lead = "입고된 아래 리스트 상품을 전산 등록 부탁드립니다."
|
||
# 글 본문(HTML 을 못 보는 메일 프로그램용)
|
||
text = ["안녕하세요.", "", lead, "", info, "", "[입고 상품] 상품 이름 · 상품 코드 · 입고 수량 · 비고"]
|
||
text += [f"- {r['name']} · {r['code']} · {r['qty']:,}개" + (f" · {r['note']}" if r["note"] else "") for r in rows]
|
||
text.append(f"합계 {total:,}개")
|
||
if receipt.get("memo"):
|
||
text += ["", f"메모: {receipt['memo']}"]
|
||
if images or skipped:
|
||
text += ["", f"입고 인증 사진 {len(images)}장(본문 이미지)" + (f", 본문에 넣지 못한 사진 {skipped}장(HEIC 등)" if skipped else "")]
|
||
text += ["", f"입고 담당: {who} ({sender_email})"]
|
||
# HTML 본문
|
||
e = _html.escape
|
||
td = "padding:6px 10px;border:1px solid #d9dce1;"
|
||
r_ = "text-align:right;white-space:nowrap;"
|
||
bg = "background:#f6f7f9;"
|
||
body_rows = "".join(
|
||
f'<tr><td style="{td}">{e(r["name"])}</td><td style="{td}font-family:Consolas,monospace">{e(r["code"])}</td>'
|
||
f'<td style="{td}{r_}">{r["qty"]:,}</td><td style="{td}">{e(r["note"])}</td></tr>' for r in rows)
|
||
imgs = "".join(
|
||
f'<p style="margin:8px 0"><img src="cid:{e(im["cid"])}" width="{im["width"]}" height="{im["height"]}" alt="입고 인증 사진 {i}" '
|
||
f'style="display:block;width:{im["width"]}px;max-width:100%;height:auto;border:1px solid #d9dce1"></p>'
|
||
for i, im in enumerate(images, start=1))
|
||
photo_block = ""
|
||
if images or skipped:
|
||
photo_block = (f'<p style="margin:18px 0 4px"><b>입고 인증 사진</b> <span style="color:#777">{len(images)}장</span></p>{imgs}'
|
||
+ (f'<p style="color:#777">본문에 넣지 못한 사진 {skipped}장(HEIC 등) — ERP 입고 기록에서 볼 수 있습니다.</p>' if skipped else ""))
|
||
html = (
|
||
'<div style="font-family:\'Malgun Gothic\',\'Apple SD Gothic Neo\',sans-serif;font-size:14px;color:#1d1d1f;line-height:1.6">'
|
||
f"<p>안녕하세요.<br>{e(lead)}</p>"
|
||
f'<p style="color:#555;margin:0 0 8px">{e(info)}</p>'
|
||
'<table style="border-collapse:collapse;min-width:480px">'
|
||
f'<thead><tr style="{bg}"><th style="{td}">상품 이름</th><th style="{td}">상품 코드</th><th style="{td}">입고 수량</th>'
|
||
f'<th style="{td}">비고</th></tr></thead><tbody>{body_rows}</tbody>'
|
||
f'<tfoot><tr><th colspan="2" style="{td}{bg}text-align:right">합계</th><th style="{td}{bg}{r_}">{total:,}</th>'
|
||
f'<th style="{td}{bg}"></th></tr></tfoot></table>'
|
||
+ (f'<p style="margin:10px 0 0">메모: {e(str(receipt["memo"]))}</p>' if receipt.get("memo") else "")
|
||
+ photo_block
|
||
+ f'<p style="color:#555;margin-top:18px">입고 담당: {e(who)} (<a href="mailto:{e(sender_email)}">{e(sender_email)}</a>)</p></div>'
|
||
)
|
||
return {"subject": receipt_mail_subject(receipt["receipt_date"]), "text": "\n".join(text), "html": html}
|
||
|
||
|
||
def inline_preview_html(html: str, images: list[dict[str, Any]]) -> str:
|
||
"""미리보기 창용 — cid: 를 data: 로 바꿔 브라우저에서 바로 보이게(보내는 메일은 cid 그대로)."""
|
||
import base64 # noqa: WPS433
|
||
|
||
for im in images:
|
||
html = html.replace(f'src="cid:{_html.escape(im["cid"])}"',
|
||
f'src="data:image/jpeg;base64,{base64.b64encode(im["data"]).decode("ascii")}"')
|
||
return html
|
||
|
||
|
||
# ════════════════════════════════════════════════════════════
|
||
# 사방넷 입고 파일(2026-10-19) — 입고 1건 → 엑셀. 1행 제목 A 상품코드 · B 가용수량 · C 불용수량,
|
||
# A = 코드표(itemcode_db single_items)의 사방넷 코드, B = 입고 수량, C = 수량이 아니라 상품 이름(사용자 지정).
|
||
# ════════════════════════════════════════════════════════════
|
||
SABANGNET_HEADER = ("상품코드", "가용수량", "불용수량")
|
||
|
||
|
||
def sabangnet_rows(receipt: dict[str, Any], codes: dict[str, str]) -> tuple[list[list[Any]], list[str]]:
|
||
"""입고 품목 → (엑셀 줄 [사방넷 코드, 입고 수량, 상품 이름], 사방넷 코드가 없는 품목 "코드 이름" 목록)."""
|
||
rows: list[list[Any]] = []
|
||
missing: list[str] = []
|
||
for x in receipt["lines"]:
|
||
code = (codes.get(str(x["item_code"]).strip().upper()) or "").strip()
|
||
if not code:
|
||
missing.append(f"{x['item_code']} {x['item_name']}".strip())
|
||
rows.append([code, int(x["qty"]), str(x["item_name"] or "")])
|
||
return rows, missing
|
||
|
||
|
||
def sabangnet_xlsx(rows: list[list[Any]]) -> bytes:
|
||
"""제목 행(굵게·회색 바탕) + 줄. 상품코드·불용수량(상품 이름)은 글자 칸(앞자리 0 보존)."""
|
||
from io import BytesIO # noqa: WPS433
|
||
|
||
from openpyxl import Workbook # noqa: WPS433
|
||
from openpyxl.styles import Font, PatternFill # noqa: WPS433
|
||
|
||
wb = Workbook()
|
||
ws = wb.active
|
||
ws.title = "입고"
|
||
ws.append(list(SABANGNET_HEADER))
|
||
for c in ws[1]:
|
||
c.font = Font(bold=True)
|
||
c.fill = PatternFill(start_color="FFE7E9ED", end_color="FFE7E9ED", fill_type="solid")
|
||
for code, qty, name in rows:
|
||
ws.append([code, qty, name])
|
||
r = ws.max_row
|
||
ws.cell(row=r, column=1).number_format = "@"
|
||
ws.cell(row=r, column=3).number_format = "@"
|
||
for letter, col in (("A", 0), ("B", 1), ("C", 2)):
|
||
longest = max(sum(2 if ord(ch) > 0x1100 else 1 for ch in str(v)) for v in [SABANGNET_HEADER[col]] + [r[col] for r in rows])
|
||
ws.column_dimensions[letter].width = max(10, min(60, longest + 2))
|
||
buf = BytesIO()
|
||
wb.save(buf)
|
||
return buf.getvalue()
|
||
|
||
|
||
def sabangnet_filename(order: dict[str, Any], receipt: dict[str, Any]) -> str:
|
||
return f"사방넷_입고_{receipt['receipt_date']:%Y%m%d}_{order['order_no']}.xlsx"
|
||
|
||
|
||
# ════════════════════════════════════════════════════════════
|
||
# 발주 알림 메일(2026-10-19) — 발주 담당이 발주 메일을 보낼 때 입고 담당(옵션 → 담당자)에게 같은 Gmail 로 따로 자동 발송.
|
||
# 내용 = 발주번호·발주일·제품 코드·제품명·수량만(단가·무게 등은 넣지 않음), 제목 = 발주 메일과 같음.
|
||
# ════════════════════════════════════════════════════════════
|
||
def order_notice_mail(order: dict[str, Any], *, subject: str, sender_name: str, sender_email: str) -> dict[str, str]:
|
||
e = _html.escape
|
||
lines = order["lines"]
|
||
total = sum(int(x["qty"]) for x in lines)
|
||
who = sender_name or sender_email
|
||
when = fmt_date(order["order_date"])
|
||
text = ["입고 담당자님, 안녕하세요.", "", "아래와 같이 공장에 발주했습니다. 입고 준비에 참고해 주세요.", "",
|
||
f"- 발주번호: {order['order_no']}", f"- 발주일: {when}", "", "[발주 품목] 제품 코드 · 제품명 · 수량"]
|
||
text += [f"- {x['item_code']} · {x['item_name']} · {int(x['qty']):,}개" for x in lines]
|
||
text += [f"합계 {total:,}개", "", f"발주 담당: {who} ({sender_email})"]
|
||
td = "padding:4px 10px;border:1px solid #d9dce1;font-size:14px;line-height:20px;"
|
||
th = f"{td}background:#f6f7f9;font-weight:700;white-space:nowrap;"
|
||
r = "text-align:right;white-space:nowrap;"
|
||
facts = (f'<tr><th style="{th}text-align:left">발주번호</th><td style="{td}">{e(order["order_no"])}</td>'
|
||
f'<th style="{th}text-align:left">발주일</th><td style="{td}">{e(when)}</td></tr>')
|
||
rows = "".join(f'<tr><td style="{td}font-family:Consolas,monospace">{e(x["item_code"])}</td><td style="{td}">{e(x["item_name"])}</td>'
|
||
f'<td style="{td}{r}">{int(x["qty"]):,}</td></tr>' for x in lines)
|
||
html = (
|
||
'<div style="font-family:\'Malgun Gothic\',\'Apple SD Gothic Neo\',sans-serif;font-size:14px;color:#1d1d1f;line-height:1.6">'
|
||
"<p>입고 담당자님, 안녕하세요.<br>아래와 같이 공장에 발주했습니다. 입고 준비에 참고해 주세요.</p>"
|
||
f'<table cellpadding="0" cellspacing="0" style="border-collapse:collapse;margin:8px 0 0">{facts}</table>'
|
||
'<div style="height:18px;line-height:18px;font-size:1px"> </div>'
|
||
'<table cellpadding="0" cellspacing="0" style="border-collapse:collapse;min-width:420px">'
|
||
f'<thead><tr><th style="{th}">제품 코드</th><th style="{th}">제품명</th><th style="{th}">수량</th></tr></thead>'
|
||
f'<tbody>{rows}</tbody>'
|
||
f'<tfoot><tr><th colspan="2" style="{th}text-align:right">합계</th><th style="{th}{r}">{total:,}</th></tr></tfoot></table>'
|
||
f'<p style="color:#555;margin-top:18px">발주 담당: {e(who)} (<a href="mailto:{e(sender_email)}">{e(sender_email)}</a>)</p></div>'
|
||
)
|
||
return {"subject": subject, "text": "\n".join(text), "html": html}
|