"""입출고 관리 — 상수·검사·상태 계산(순수 함수, 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 결과. 품목마다 단가·금액(수량 × 단가)·PP량(개당 g = 무게)·은 함유량(%·개당 g) — 발주 품목에 남긴 그때 값(004). 없으면 '-'.""" 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}")) if money["pp_kg"] is not None: facts.append(("PP 총량", f"{fmt_num(money['pp_kg'], 2)} kg")) if money["silver_g"] is not None: facts.append(("은(Ag) 총량", f"{fmt_num(money['silver_g'], 2)} g")) 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")) amt = line_amount(int(x["qty"]), price) ag = silver_g(w, pct) return {"price": fmt_num(price) if price is not None else "-", "amount": fmt_num(amt) if amt is not None else "-", "pp": fmt_num(w) if w is not None else "-", "ag": (f"{fmt_num(pct, 4)}%" + (f" ({fmt_num(ag, 4)}g)" if ag is not None else "")) if pct is not None else "-"} # 글 본문(HTML 을 못 보는 메일 프로그램용) text = [greet, "", "아래와 같이 제품 제작을 발주합니다.", ""] text += [f"- {k}: {v}" for k, v in facts] text += ["", "[발주 품목] 수량 · 단가 · 금액 · PP(g/개) · 은 함유량"] 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" · PP {c['pp'] + 'g' if c['pp'] != '-' 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;" fact_rows = "".join(f'{e(k)}' f'{e(str(v))}' for k, v in facts) rows = [] for i, x in enumerate(lines, start=1): c = cells(x) rows.append( f'{i}{e(x["item_code"])}' f'{e(x["item_name"])}{int(x["qty"]):,}' f'{e(c["price"])}{e(c["amount"])}' f'{e(c["pp"])}{e(c["ag"])}' f'{e(x.get("memo") or "")}') foot_amount = fmt_num(money["amount"]) if money["amount"] is not None else "" foot_pp = f'{fmt_num(money["pp_kg"], 2)} kg' if money["pp_kg"] is not None else "" foot_ag = f'{fmt_num(money["silver_g"], 2)} g' if money["silver_g"] is not None else "" bg = "background:#f6f7f9;" html = ( '
' f"

{e(greet)}
아래와 같이 제품 제작을 발주합니다.

" f'{fact_rows}
' '' f'' f'' f'' f'{"".join(rows)}' f'' f'' f'
No제품 코드제품명수량단가(원)금액(원)PP(g/개)은(Ag) 함유량비고
합계{total:,}{e(foot_amount)}{e(foot_pp)}{e(foot_ag)}
' "

입고 예정일까지 물류로 입고 부탁드리며, 일정이 바뀌면 회신 부탁드립니다.

" f'

발주 담당: {e(who)} ({e(sender_email)})

' ) 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).""" amount = pp = ag = 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 return {"amount": amount, "missing_price": missing if amount is not None else len(lines), "pp_kg": pp, "silver_g": ag} 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