Files
dbx-main/app/modules/inout/store.py
T

649 lines
35 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""입출고 관리 — 상수·검사·상태 계산(순수 함수, DB 없음).
흐름(2026-10-16 사용자 요청, 상용 ERP 참고 — 이카운트 "발주 대비 미입고 현황"·Odoo 분할 입고/잔량 종결):
발주 담당이 공장에 발주서(단품 코드·수량)를 넣고 → 물류에 들어올 때마다 입고 담당이 그날 들어온 수량을 입력(여러 번 나눠도 됨)
→ 품목마다 발주 − 누적 입고 = 미입고. 다 들어오면 입고완료, 더 들어오면 초과입고(확인 후 허용, 빨강 표시).
더 안 들어올 잔량은 발주 담당이 "종결"(이카운트 발주 종결 · Odoo No backorder) — 미입고 현황에서 빠지고 종결로 남는다.
"""
from __future__ import annotations
import html as _html
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, w, pct = to_dec(x.get("unit_price")), to_dec(x.get("weight_g")), to_dec(x.get("silver_pct"))
q = int(x["qty"])
amt = line_amount(q, price)
total_kg = w * q / Decimal(1000) if w is not None else None # 전체 무게 = 개당 g × 수량
ag_kg = total_kg * pct / Decimal(100) if total_kg is not None and pct is not None else None
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)
rows.append(
f'<tr><td style="{td}text-align:center">{i}</td><td style="{td}font-family:Consolas,monospace">{e(x["item_code"])}</td>'
f'<td style="{td}">{e(x["item_name"])}</td><td style="{td}{r}">{int(x["qty"]):,}</td>'
f'<td style="{td}{r}">{e(c["price"])}</td><td style="{td}{r}">{e(c["amount"])}</td>'
f'<td style="{td}{r}">{e(c["weight"])}</td><td style="{td}{r}">{e(c["pp_use"])}</td><td style="{td}{r}">{e(c["ag"])}</td>'
f'<td style="{td}">{e(x.get("memo") or "")}</td></tr>')
foot_amount = fmt_num(money["amount"]) if money["amount"] is not None else ""
foot_pp = fmt_num(money["pp_kg"], 3) if money["pp_kg"] is not None else ""
foot_use = fmt_num(money["pp_use_kg"], 3) if money["pp_use_kg"] is not None else ""
foot_ag = f'{fmt_num(ag_kg, 4)} 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">&nbsp;</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-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_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:
"""단가·무게·은 함유량 중 하나라도 넣었나 — 넣은 상품은 다시 불러와도 그대로 둔다."""
return any(p.get(k) is not None for k in PRODUCT_LIMITS)
# ════════════════════════════════════════════════════════════
# 입고증 사진(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
# ════════════════════════════════════════════════════════════
# 입고 요청 메일(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"