"""입출고 관리 — 상수·검사·상태 계산(순수 함수, DB 없음). 흐름(2026-10-16 사용자 요청, 상용 ERP 참고 — 이카운트 "발주 대비 미입고 현황"·Odoo 분할 입고/잔량 종결): 발주 담당이 공장에 발주서(단품 코드·수량)를 넣고 → 물류에 들어올 때마다 입고 담당이 그날 들어온 수량을 입력(여러 번 나눠도 됨) → 품목마다 발주 − 누적 입고 = 미입고. 다 들어오면 입고완료, 더 들어오면 초과입고(확인 후 허용, 빨강 표시). 더 안 들어올 잔량은 발주 담당이 "종결"(이카운트 발주 종결 · Odoo No backorder) — 미입고 현황에서 빠지고 종결로 남는다. """ from __future__ import annotations from datetime import date 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" 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)), } 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}"