"""입출고 관리 — 상수·검사·상태 계산(순수 함수, DB 없음). 흐름(2026-10-16 사용자 요청, 상용 ERP 참고 — 이카운트 "발주 대비 미입고 현황"·Odoo 분할 입고/잔량 종결): 발주 담당이 공장에 발주서(단품 코드·수량)를 넣고 → 물류에 들어올 때마다 입고 담당이 그날 들어온 수량을 입력(여러 번 나눠도 됨) → 품목마다 발주 − 누적 입고 = 미입고. 다 들어오면 입고완료, 더 들어오면 초과입고(확인 후 허용, 빨강 표시). 더 안 들어올 잔량은 발주 담당이 "종결"(이카운트 발주 종결 · Odoo No backorder) — 미입고 현황에서 빠지고 종결로 남는다. """ from __future__ import annotations import html as _html import re 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}" # ════════════════════════════════════════════════════════════ # 발주 메일(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 결과.""" 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) due = order["due_date"].strftime("%Y-%m-%d") 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"]), ("발주일", order["order_date"].strftime("%Y-%m-%d")), ("입고 예정일", due), ("품목", f"{len(lines)}종 · 총 {total:,}개")] if order.get("memo"): facts.append(("요청 사항", order["memo"])) # 글 본문(HTML 을 못 보는 메일 프로그램용) text = [greet, "", "아래와 같이 제품 제작을 발주합니다.", ""] text += [f"- {k}: {v}" for k, v in facts] text += ["", "[발주 품목]"] for i, x in enumerate(lines, start=1): text.append(f"{i}. {x['item_code']} {x['item_name']} — {int(x['qty']):,}개" + (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;" fact_rows = "".join(f'{e(k)}' f'{e(str(v))}' for k, v in facts) item_rows = "".join( f'{i}{e(x["item_code"])}' f'{e(x["item_name"])}{int(x["qty"]):,}' f'{e(x.get("memo") or "")}' for i, x in enumerate(lines, start=1)) html = ( '
' f"

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

" f'{fact_rows}
' '' f'' f'{item_rows}' f'' f'
No제품 코드제품명수량비고
합계{total:,}
' "

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

" f'

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

' ) return {"subject": subject, "text": "\n".join(text), "html": html} # ════════════════════════════════════════════════════════════ # 입고증 사진(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