From 6f3bffd840c1004a7cfc3273d17bc0a4a4a5b7bd Mon Sep 17 00:00:00 2001 From: king Date: Fri, 16 Oct 2026 15:21:05 +0900 Subject: [PATCH] =?UTF-8?q?feat(inout):=20=EC=9E=85=EC=B6=9C=EA=B3=A0=20?= =?UTF-8?q?=EA=B4=80=EB=A6=AC=20=EB=AA=A8=EB=93=88=20=E2=80=94=20=EA=B3=B5?= =?UTF-8?q?=EC=9E=A5=20=EC=A0=9C=EC=9E=91=20=EB=B0=9C=EC=A3=BC=20=C2=B7=20?= =?UTF-8?q?=EB=AC=BC=EB=A5=98=20=EC=9E=85=EA=B3=A0=20=C2=B7=20=EB=AF=B8?= =?UTF-8?q?=EC=9E=85=EA=B3=A0/=EC=B4=88=EA=B3=BC=20=EA=B4=80=EB=A6=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 새 모듈 app/modules/inout(/inout/, 권한키 inout) + 새 DB inout_db(사용자 승인, scripts/sql/inout_db_init.sql — 멱등). - 발주 담당이 공장에 발주서(PO-YYMMDD-NN, 제품 = itemcode_db 단품만 — 검색 + 저장 때 서버 재확인), 입고 담당이 물류에 들어온 수량을 여러 번 나눠 입력 → 품목별 발주·입고·미입고, 진행률, 입고 예정일 지연. - 미입고 현황: 제품별 합계 · 발주별(예정일 순) · 초과 입고. 잔량 종결/풀기, 입고 없는 발주 취소, 입고 기록 지우기. - 초과 입고: 확인 화면(409, 입력 유지) 후 [초과 입고로 저장] — 트랜잭션 안에서 발주서 잠그고 판단, Enter 는 일반 저장. - 옵션(ERP 관리자): 공장 목록, 발주 담당·입고 담당 지정(inout_roles). 관리자는 둘 다. - 상태는 저장하지 않고 누적 입고로 계산(store.order_status). 이카운트 "발주 대비 미입고"·Odoo 분할 입고/종결 참고. - 테스트: 순수 로직, 실제 PostgreSQL(앱 계정 inout_app — 권한 포함), 실제 앱 화면 흐름(권한별). 문서 INOUT_MODULE.md 등. Co-Authored-By: Claude Opus 5.5 --- .env.example | 5 + CLAUDE.md | 2 + app/main.py | 20 + app/modules/inout/__init__.py | 32 ++ app/modules/inout/db.py | 336 ++++++++++++ app/modules/inout/itemcode.py | 82 +++ app/modules/inout/router.py | 507 ++++++++++++++++++ app/modules/inout/store.py | 204 +++++++ .../inout/templates/inout/_macros.html | 18 + app/modules/inout/templates/inout/_nav.html | 14 + app/modules/inout/templates/inout/index.html | 61 +++ .../inout/templates/inout/order_detail.html | 133 +++++ .../inout/templates/inout/order_form.html | 79 +++ .../inout/templates/inout/pending.html | 91 ++++ .../inout/templates/inout/settings.html | 74 +++ app/static/inout.css | 124 +++++ app/static/inout.js | 227 ++++++++ app/store.py | 1 + docs/DATABASES.md | 1 + docs/DEPLOYMENT.md | 18 + docs/INOUT_MODULE.md | 89 +++ docs/PROJECT_OVERVIEW.md | 2 + scripts/sql/inout_db_init.sql | 152 ++++++ tests/test_inout_db.py | 166 ++++++ tests/test_inout_store.py | 89 +++ tests/test_inout_web.py | 185 +++++++ 26 files changed, 2712 insertions(+) create mode 100644 app/modules/inout/__init__.py create mode 100644 app/modules/inout/db.py create mode 100644 app/modules/inout/itemcode.py create mode 100644 app/modules/inout/router.py create mode 100644 app/modules/inout/store.py create mode 100644 app/modules/inout/templates/inout/_macros.html create mode 100644 app/modules/inout/templates/inout/_nav.html create mode 100644 app/modules/inout/templates/inout/index.html create mode 100644 app/modules/inout/templates/inout/order_detail.html create mode 100644 app/modules/inout/templates/inout/order_form.html create mode 100644 app/modules/inout/templates/inout/pending.html create mode 100644 app/modules/inout/templates/inout/settings.html create mode 100644 app/static/inout.css create mode 100644 app/static/inout.js create mode 100644 docs/INOUT_MODULE.md create mode 100644 scripts/sql/inout_db_init.sql create mode 100644 tests/test_inout_db.py create mode 100644 tests/test_inout_store.py create mode 100644 tests/test_inout_web.py diff --git a/.env.example b/.env.example index 3827037..c328a6b 100644 --- a/.env.example +++ b/.env.example @@ -144,6 +144,11 @@ CUSTOMER_ORDER_LIST_URL=/orderlist/ # CAFE24_MOBILE_DETAIL_FTP_PATH=/sde_design/mobile11/product/detail.html # CAFE24_PC_DETAIL_FTP_PATH=/sde_design/skin11/product/detail.html +# ─── 입출고 관리 모듈 (inout_db) — app/modules/inout ─── +# 본사 → 공장 발주, 물류 입고, 미입고 관리. 미설정 시 "설정 필요" 안내만. +# 초기화: scripts/sql/inout_db_init.sql (docs/INOUT_MODULE.md). 제품(단품)은 아래 ITEMCODE_DB_URL 재사용. +# INOUT_DB_URL=postgresql://inout_app:replace-me@postgres-db:5432/inout_db + # ─── 상품 검색 (itemcode_db 읽기 전용) ─── # cupang 설정 화면에서 제품명을 itemcode_db 에서 검색해 등록한다(읽기만). # 미설정 시 검색 비활성 → 수동 등록만 가능. diff --git a/CLAUDE.md b/CLAUDE.md index f9712fb..96ce7b9 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -42,6 +42,8 @@ Claude Code는 이 저장소에서 작업을 시작하기 전에 **반드시 아 - 긴급 공지 (`app/modules/notice/`, `project_db` 마이그레이션 024 `urgent_notice*`) — 수퍼관리자만 작성(`/notice/`, ERP 왼쪽 아래·Project ⚙ 옵션). 제목·내용(이미지 bytea)·띄울 시각·전체/고른 사람 → ERP 모든 화면(`erp_base.html`·`main.html`·`admin.html` 의 `static/erp-notice.js`) 가로·세로 정가운데에 [확인] 누를 때까지(Esc·바깥 클릭 무시), 확인 기록. 연결 풀은 `ProjectStore.pool` 공유, 새 환경변수 없음. PC 알림 프로그램은 아직 미지원. 상세는 `docs/NOTICE_MODULE.md` +- 입출고 관리 (`app/modules/inout/`, `inout_db`, 2026-10-16) — 본사 → 공장 제품 제작 발주(발주서 `PO-YYMMDD-NN`, 제품 = `itemcode_db.single_items` 단품만, 검색 `GET /inout/api/items`·저장 때 서버 재확인), 물류 입고를 여러 번 나눠 입력, 품목별 발주·입고·미입고, 미입고 현황(제품별 합계·발주별·지연), 초과 입고는 확인 화면 후 허용(트랜잭션 안에서 발주서 잠그고 판단, `confirm_over`), 잔량 종결·취소(입고 없을 때만). 상태는 저장하지 않고 누적 입고로 계산(`store.order_status`). 권한키 `inout`(조회), **발주 담당·입고 담당·공장은 모듈 옵션**(`/inout/settings`, ERP 관리자, `inout_roles`·`inout_factories`), 관리자는 둘 다. 이카운트 "발주 대비 미입고"·Odoo 분할 입고/종결 참고. 상세 `docs/INOUT_MODULE.md` + 상세는 `docs/PROJECT_OVERVIEW.md`. --- diff --git a/app/main.py b/app/main.py index c66993c..99745a8 100644 --- a/app/main.py +++ b/app/main.py @@ -24,6 +24,8 @@ from .modules.dispatch import build_dispatch_store from .modules.dispatch import router as dispatch_router from .modules.expense import CategoryStore, build_expense_store from .modules.expense import router as expense_router +from .modules.inout import build_inout_items, build_inout_store +from .modules.inout import router as inout_router from .modules.malaysia import build_malaysia_itemcode, build_malaysia_store from .modules.malaysia import router as malaysia_router from .modules.notice import build_notice_store @@ -59,6 +61,7 @@ MODULE_LABELS: dict[str, str] = { "cafe24": "카페24 상품관리", "performance": "실적", "asset": "자산관리", + "inout": "입출고 관리", "expense_approver": "개인경비", "vacation_approver": "휴가", } @@ -153,6 +156,7 @@ _MODULE_TEMPLATE_DIRS = [ BASE_DIR / "modules" / "performance" / "templates", BASE_DIR / "modules" / "asset" / "templates", BASE_DIR / "modules" / "notice" / "templates", + BASE_DIR / "modules" / "inout" / "templates", ] templates = Jinja2Templates(directory=str(BASE_DIR / "templates")) templates.env.loader = ChoiceLoader( @@ -218,6 +222,10 @@ app.state.performance_store = build_performance_store(dsn=env("PERFORMANCE_DB_UR app.state.asset_store = build_asset_store(dsn=env("ASSET_DB_URL") or None) # 긴급 공지(ERP 전체 화면 가운데): project_db 024 — 프로젝트 저장소의 연결 풀을 같이 쓴다(없으면 None → 503). app.state.notice_store = build_notice_store(app.state.project_store) +# 입출고 관리(본사 → 공장 발주, 물류 입고, 미입고): INOUT_DB_URL 없으면 store=None(라우터가 "설정 필요" 안내). +# 제품은 itemcode_db 단품(single_items) 읽기 전용 — ITEMCODE_DB_URL 재사용. +app.state.inout_store = build_inout_store(dsn=env("INOUT_DB_URL") or None) +app.state.inout_items = build_inout_items() # 모듈 라우터 등록 — 신규 모듈 추가 시 여기 한 줄. app.include_router(expense_router) @@ -230,6 +238,7 @@ app.include_router(cafe24_router) app.include_router(performance_router) app.include_router(asset_router) app.include_router(notice_router) +app.include_router(inout_router) def public_url_for(request: Request, route_name: str) -> str: @@ -422,6 +431,16 @@ def _menu_items_for(user_rec: dict[str, Any]) -> list[dict[str, Any]]: "status": "ready", "category": "관리", }, + { + "key": "inout", + "title": "입출고 관리", + "subtitle": "Inbound", + "description": "본사에서 공장으로 넣은 제작 발주와 물류 입고 수량을 맞춰 보고, 미입고·초과 입고를 관리합니다.", + "url": "/inout/", + "health_url": "/inout/health", + "status": "ready", + "category": "운영", + }, ] items.append({ "key": "asset", "title": "자산관리", "subtitle": "Asset Management", @@ -437,6 +456,7 @@ def _menu_items_for(user_rec: dict[str, Any]) -> list[dict[str, Any]]: def _icon_svg(name: str) -> str: """좌측 사이드바용 인라인 아이콘. 외부 의존 없는 작은 SVG.""" paths = { + "inout": '', "asset": '', "home": '', "expense": '', diff --git a/app/modules/inout/__init__.py b/app/modules/inout/__init__.py new file mode 100644 index 0000000..ec5190d --- /dev/null +++ b/app/modules/inout/__init__.py @@ -0,0 +1,32 @@ +"""입출고 관리(inout) 모듈 — 본사 → 공장 제품 제작 발주, 물류 입고(분할), 발주 대비 미입고·초과 관리. + +- 라우터: `router.py` (prefix=/inout) +- 저장소: `db.py` (inout_db / PostgreSQL) + `store.py` (상태·검사, 순수 함수) +- 제품: `itemcode.py` — itemcode_db.single_items(단품) 읽기 전용(ITEMCODE_DB_URL 재사용) +- 템플릿: `templates/inout/`, 화면 스크립트·스타일 `static/inout.{js,css}` + +INOUT_DB_URL 미설정이면 build_inout_store 가 None → 라우터가 "설정 필요" 안내(앱은 죽지 않음). +권한: 모듈 권한키 `inout`(조회), 발주 담당·입고 담당은 모듈 옵션(inout_roles)에서 지정, ERP 관리자는 둘 다 + 옵션. +상세 docs/INOUT_MODULE.md. +""" + +from typing import Any + +from .router import router + +__all__ = ["router", "build_inout_store", "build_inout_items"] + + +def build_inout_store(*, dsn: str | None) -> Any: + if not dsn: + return None + from .db import InoutDBStore # 지연 import + + return InoutDBStore(dsn) + + +def build_inout_items() -> Any: + """코드표 단품 리더(ITEMCODE_DB_URL). 미설정이면 enabled=False.""" + from .itemcode import SingleItemReader # 지연 import + + return SingleItemReader() diff --git a/app/modules/inout/db.py b/app/modules/inout/db.py new file mode 100644 index 0000000..7d0fc46 --- /dev/null +++ b/app/modules/inout/db.py @@ -0,0 +1,336 @@ +"""inout_db PostgreSQL 저장소 — 공장·담당자·발주서·입고. + +- 드라이버: psycopg 3 + pool(다른 모듈과 같은 패턴), 연결 `INOUT_DB_URL`. 스키마는 scripts/sql/inout_db_init.sql(앱이 만들지 않음). +- 상태(발주·부분입고·입고완료·초과·종결·취소)는 저장하지 않고 품목별 누적 입고로 계산한다(store.order_status) — 어긋날 일이 없다. +- 쓰기는 한 트랜잭션. 입고 저장은 발주서 행을 잠그고(FOR UPDATE) 그 안에서 누적 입고를 다시 읽어 초과를 판단한다 + (두 사람이 동시에 입고해도 초과 확인을 건너뛰지 않게). +""" + +from __future__ import annotations + +from datetime import date +from typing import Any + +from psycopg.rows import dict_row +from psycopg_pool import ConnectionPool + +from . import store + + +_SCAN_LIMIT = 20000 # 목록에서 상태 거르기 전에 읽는 발주서 상한 + + +class OverReceipt(Exception): + """확인 없이 발주보다 많이 입고하려 함 — over = [{item_code, item_name, ordered, after, over}].""" + + def __init__(self, over: list[dict[str, Any]]) -> None: + super().__init__("초과 입고") + self.over = over + + +def _norm_email(e: str) -> str: + return (e or "").strip().lower() + + +class InoutDBStore: + def __init__(self, dsn: str, *, min_size: int = 1, max_size: int = 5): + self._pool = ConnectionPool(conninfo=dsn, min_size=min_size, max_size=max_size, + kwargs={"row_factory": dict_row, "autocommit": True}, open=False) + self._pool.open(wait=False) + + def close(self) -> None: + self._pool.close() + + # ════════════════════════════════════════════════════════════ + # 공장 + # ════════════════════════════════════════════════════════════ + def list_factories(self, *, include_inactive: bool = False) -> list[dict[str, Any]]: + where = "" if include_inactive else "WHERE f.is_active" + with self._pool.connection() as conn: + return conn.execute( + "SELECT f.*, (SELECT count(*) FROM inout_orders o WHERE o.factory_id = f.id) AS order_count " + f"FROM inout_factories f {where} ORDER BY f.is_active DESC, f.sort_order, f.name" + ).fetchall() + + def save_factory(self, *, factory_id: int | None, name: str, contact: str = "", memo: str = "", + is_active: bool = True, sort_order: int = 0) -> int: + name = (name or "").strip() + if not name or len(name) > 100: + raise ValueError("공장 이름을 1~100자로 입력하세요.") + vals = (name, (contact or "").strip()[:200], (memo or "").strip()[:store.MEMO_MAX], bool(is_active), int(sort_order)) + with self._pool.connection() as conn: + dup = conn.execute("SELECT id FROM inout_factories WHERE lower(name) = lower(%s) AND id <> %s", + (name, factory_id or 0)).fetchone() + if dup: + raise ValueError(f"같은 이름의 공장이 이미 있습니다: {name}") + if factory_id: + row = conn.execute( + "UPDATE inout_factories SET name=%s, contact=%s, memo=%s, is_active=%s, sort_order=%s " + "WHERE id=%s RETURNING id", (*vals, factory_id)).fetchone() + if not row: + raise ValueError("공장을 찾을 수 없습니다.") + return int(row["id"]) + return int(conn.execute( + "INSERT INTO inout_factories (name, contact, memo, is_active, sort_order) VALUES (%s,%s,%s,%s,%s) RETURNING id", + vals).fetchone()["id"]) + + def delete_factory(self, factory_id: int) -> None: + """발주 기록이 없는 공장만 지운다(있으면 '사용 안 함'으로 숨김).""" + with self._pool.connection() as conn: + used = conn.execute("SELECT 1 FROM inout_orders WHERE factory_id=%s LIMIT 1", (factory_id,)).fetchone() + if used: + raise ValueError("발주 기록이 있는 공장은 지울 수 없습니다 — '사용 안 함'으로 바꾸세요.") + conn.execute("DELETE FROM inout_factories WHERE id=%s", (factory_id,)) + + # ════════════════════════════════════════════════════════════ + # 담당자(발주 담당·입고 담당) + # ════════════════════════════════════════════════════════════ + def list_roles(self) -> dict[str, list[str]]: + out: dict[str, list[str]] = {r: [] for r in store.ROLES} + with self._pool.connection() as conn: + for r in conn.execute("SELECT email, role FROM inout_roles ORDER BY email").fetchall(): + out.setdefault(r["role"], []).append(r["email"]) + return out + + def roles_of(self, email: str) -> set[str]: + with self._pool.connection() as conn: + rows = conn.execute("SELECT role FROM inout_roles WHERE email=%s", (_norm_email(email),)).fetchall() + return {r["role"] for r in rows} + + def set_role_members(self, role: str, emails: list[str], *, by: str) -> None: + """그 역할 담당자를 통째로 바꾼다(한 트랜잭션).""" + if role not in store.ROLES: + raise ValueError("알 수 없는 담당 종류입니다.") + clean = sorted({_norm_email(e) for e in emails if _norm_email(e)}) + with self._pool.connection() as conn, conn.transaction(): + conn.execute("DELETE FROM inout_roles WHERE role=%s AND NOT (email = ANY(%s))", (role, clean)) + for e in clean: + conn.execute("INSERT INTO inout_roles (email, role, created_by) VALUES (%s,%s,%s) ON CONFLICT DO NOTHING", + (e, role, _norm_email(by))) + + # ════════════════════════════════════════════════════════════ + # 발주서 + # ════════════════════════════════════════════════════════════ + def create_order(self, data: dict[str, Any], names: dict[str, str], *, by: str) -> dict[str, Any]: + """data = store.validate_order 결과, names = {코드: 단품 이름}. 반환 {id, order_no}.""" + with self._pool.connection() as conn, conn.transaction(): + self._require_factory(conn, data["factory_id"]) + conn.execute("SELECT pg_advisory_xact_lock(hashtext('inout_order_no'))") + prefix = store.order_no(data["order_date"], 0)[:-2] + row = conn.execute("SELECT max(order_no) AS m FROM inout_orders WHERE order_no LIKE %s", + (prefix + "%",)).fetchone() + last = row["m"] if row else None + seq = int(last.rsplit("-", 1)[1]) + 1 if last and last.rsplit("-", 1)[1].isdigit() else 1 + no = store.order_no(data["order_date"], seq) + oid = conn.execute( + "INSERT INTO inout_orders (order_no, factory_id, order_date, due_date, memo, created_by, updated_by) " + "VALUES (%s,%s,%s,%s,%s,%s,%s) RETURNING id", + (no, data["factory_id"], data["order_date"], data["due_date"], data["memo"], _norm_email(by), _norm_email(by)), + ).fetchone()["id"] + for i, ln in enumerate(data["lines"], start=1): + conn.execute("INSERT INTO inout_order_lines (order_id, line_no, item_code, item_name, qty, memo) " + "VALUES (%s,%s,%s,%s,%s,%s)", + (oid, i, ln["item_code"], names.get(ln["item_code"], ""), ln["qty"], ln["memo"])) + return {"id": int(oid), "order_no": no} + + def update_order(self, order_id: int, data: dict[str, Any], names: dict[str, str], *, by: str) -> None: + """머리글·품목 고치기. 입고된 품목은 뺄 수 없다(입고 기록이 사라지므로) — 수량은 바꿀 수 있다.""" + with self._pool.connection() as conn, conn.transaction(): + head = self._lock_order(conn, order_id) + if head["cancelled_at"]: + raise ValueError("취소된 발주서는 고칠 수 없습니다.") + self._require_factory(conn, data["factory_id"], allow_inactive_id=head["factory_id"]) + existing = {r["item_code"]: r for r in conn.execute( + "SELECT l.id, l.item_code, COALESCE(sum(rl.qty), 0) AS received FROM inout_order_lines l " + "LEFT JOIN inout_receipt_lines rl ON rl.order_line_id = l.id WHERE l.order_id=%s GROUP BY l.id", + (order_id,)).fetchall()} + wanted = {ln["item_code"] for ln in data["lines"]} + blocked = [c for c, r in existing.items() if c not in wanted and int(r["received"]) > 0] + if blocked: + raise ValueError("입고 기록이 있는 품목은 뺄 수 없습니다: " + ", ".join(sorted(blocked))) + for code, r in existing.items(): + if code not in wanted: + conn.execute("DELETE FROM inout_order_lines WHERE id=%s", (r["id"],)) + for i, ln in enumerate(data["lines"], start=1): + if ln["item_code"] in existing: + conn.execute("UPDATE inout_order_lines SET line_no=%s, qty=%s, memo=%s WHERE id=%s", + (i, ln["qty"], ln["memo"], existing[ln["item_code"]]["id"])) + else: + conn.execute("INSERT INTO inout_order_lines (order_id, line_no, item_code, item_name, qty, memo) " + "VALUES (%s,%s,%s,%s,%s,%s)", + (order_id, i, ln["item_code"], names.get(ln["item_code"], ""), ln["qty"], ln["memo"])) + conn.execute("UPDATE inout_orders SET factory_id=%s, order_date=%s, due_date=%s, memo=%s, updated_by=%s WHERE id=%s", + (data["factory_id"], data["order_date"], data["due_date"], data["memo"], _norm_email(by), order_id)) + + def set_closed(self, order_id: int, *, closed: bool, reason: str = "", by: str) -> None: + """종결(남은 미입고를 더 기다리지 않음) / 종결 풀기.""" + with self._pool.connection() as conn, conn.transaction(): + head = self._lock_order(conn, order_id) + if head["cancelled_at"]: + raise ValueError("취소된 발주서입니다.") + if closed: + conn.execute("UPDATE inout_orders SET closed_at=now(), closed_by=%s, close_reason=%s, updated_by=%s WHERE id=%s", + (_norm_email(by), (reason or "").strip()[:store.MEMO_MAX], _norm_email(by), order_id)) + else: + conn.execute("UPDATE inout_orders SET closed_at=NULL, closed_by='', close_reason='', updated_by=%s WHERE id=%s", + (_norm_email(by), order_id)) + + def cancel_order(self, order_id: int, *, by: str) -> None: + """잘못 넣은 발주 — 입고 기록이 없을 때만 취소(기록은 남김).""" + with self._pool.connection() as conn, conn.transaction(): + self._lock_order(conn, order_id) + if conn.execute("SELECT 1 FROM inout_receipts WHERE order_id=%s LIMIT 1", (order_id,)).fetchone(): + raise ValueError("입고 기록이 있는 발주서는 취소할 수 없습니다 — 남은 수량은 '종결'하세요.") + conn.execute("UPDATE inout_orders SET cancelled_at=now(), cancelled_by=%s, updated_by=%s WHERE id=%s", + (_norm_email(by), _norm_email(by), order_id)) + + def get_order(self, order_id: int) -> dict[str, Any] | None: + with self._pool.connection() as conn: + head = conn.execute( + "SELECT o.*, f.name AS factory_name FROM inout_orders o JOIN inout_factories f ON f.id = o.factory_id WHERE o.id=%s", + (order_id,)).fetchone() + if not head: + return None + lines = conn.execute( + "SELECT l.*, COALESCE(sum(rl.qty), 0)::int AS received FROM inout_order_lines l " + "LEFT JOIN inout_receipt_lines rl ON rl.order_line_id = l.id WHERE l.order_id=%s " + "GROUP BY l.id ORDER BY l.line_no", (order_id,)).fetchall() + receipts = conn.execute("SELECT * FROM inout_receipts WHERE order_id=%s ORDER BY receipt_date, id", + (order_id,)).fetchall() + rlines = conn.execute( + "SELECT rl.receipt_id, rl.order_line_id, rl.qty, l.item_code, l.item_name FROM inout_receipt_lines rl " + "JOIN inout_order_lines l ON l.id = rl.order_line_id JOIN inout_receipts r ON r.id = rl.receipt_id " + "WHERE r.order_id=%s ORDER BY l.line_no", (order_id,)).fetchall() + by_receipt: dict[int, list[dict[str, Any]]] = {} + for r in rlines: + by_receipt.setdefault(int(r["receipt_id"]), []).append(r) + lines = store.decorate_lines(lines) + status = store.order_status(lines, closed=bool(head["closed_at"]), cancelled=bool(head["cancelled_at"])) + return {**head, "lines": lines, "summary": store.summarize(lines), "status": status, + "status_label": store.ORDER_LABELS[status], + "receipts": [{**r, "lines": by_receipt.get(int(r["id"]), []), + "total": sum(int(x["qty"]) for x in by_receipt.get(int(r["id"]), []))} for r in receipts]} + + def list_orders(self, *, status: str = "active", factory_id: int | None = None, q: str = "", + date_from: date | None = None, date_to: date | None = None, limit: int = 500) -> list[dict[str, Any]]: + """목록 — 상태는 품목 합계로 계산한 뒤 거른다. q = 발주번호·제품 코드·제품 이름.""" + where, params = ["TRUE"], [] + if factory_id: + where.append("o.factory_id = %s") + params.append(factory_id) + if date_from: + where.append("o.order_date >= %s") + params.append(date_from) + if date_to: + where.append("o.order_date <= %s") + params.append(date_to) + if q.strip(): + like = "%" + q.strip().replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%" + where.append("(o.order_no ILIKE %s OR EXISTS (SELECT 1 FROM inout_order_lines x WHERE x.order_id = o.id " + "AND (x.item_code ILIKE %s OR x.item_name ILIKE %s)))") + params += [like, like, like] + with self._pool.connection() as conn: + heads = conn.execute( + "SELECT o.*, f.name AS factory_name FROM inout_orders o JOIN inout_factories f ON f.id = o.factory_id " + # 상태는 품목 합계로 계산해 아래에서 거르므로 넉넉히 읽는다(발주서는 많아야 연 수천 건) + f"WHERE {' AND '.join(where)} ORDER BY o.order_date DESC, o.id DESC LIMIT {_SCAN_LIMIT}", params + ).fetchall() + ids = [h["id"] for h in heads] + lines = conn.execute( + "SELECT l.order_id, l.item_code, l.item_name, l.qty, COALESCE(sum(rl.qty), 0)::int AS received " + "FROM inout_order_lines l LEFT JOIN inout_receipt_lines rl ON rl.order_line_id = l.id " + "WHERE l.order_id = ANY(%s) GROUP BY l.id ORDER BY l.line_no", (ids,)).fetchall() if ids else [] + by_order: dict[int, list[dict[str, Any]]] = {} + for ln in lines: + by_order.setdefault(int(ln["order_id"]), []).append(ln) + allowed = store.STATUS_FILTERS.get(status, store.STATUS_FILTERS["active"])[1] + out = [] + for h in heads: + ls = by_order.get(int(h["id"]), []) + st = store.order_status(ls, closed=bool(h["closed_at"]), cancelled=bool(h["cancelled_at"])) + if st not in allowed: + continue + names = [x["item_name"] or x["item_code"] for x in ls] + out.append({**h, "status": st, "status_label": store.ORDER_LABELS[st], "summary": store.summarize(ls), + "line_count": len(ls), "items_label": (names[0] + (f" 외 {len(names) - 1}종" if len(names) > 1 else "")) if names else ""}) + if len(out) >= limit: + break + return out + + # ════════════════════════════════════════════════════════════ + # 입고 + # ════════════════════════════════════════════════════════════ + def add_receipt(self, order_id: int, quantities: dict[int, Any], *, receipt_date: Any, memo: Any, + confirm_over: bool, by: str) -> dict[str, Any]: + """입고 1건 저장. 발주를 넘는 품목이 있는데 confirm_over 가 아니면 OverReceipt(아무것도 저장 안 함).""" + with self._pool.connection() as conn, conn.transaction(): + head = self._lock_order(conn, order_id) + if head["cancelled_at"]: + raise ValueError("취소된 발주서에는 입고할 수 없습니다.") + if head["closed_at"]: + raise ValueError("종결된 발주서입니다 — 입고하려면 발주 담당이 종결을 풀어야 합니다.") + lines = conn.execute( + "SELECT l.id, l.item_code, l.item_name, l.qty, COALESCE(sum(rl.qty), 0)::int AS received " + "FROM inout_order_lines l LEFT JOIN inout_receipt_lines rl ON rl.order_line_id = l.id " + "WHERE l.order_id=%s GROUP BY l.id", (order_id,)).fetchall() + data = store.validate_receipt(lines, quantities, receipt_date=receipt_date, memo=memo) + if data["over"] and not confirm_over: + raise OverReceipt(data["over"]) + rid = conn.execute("INSERT INTO inout_receipts (order_id, receipt_date, memo, created_by) VALUES (%s,%s,%s,%s) RETURNING id", + (order_id, data["receipt_date"], data["memo"], _norm_email(by))).fetchone()["id"] + for it in data["items"]: + conn.execute("INSERT INTO inout_receipt_lines (receipt_id, order_line_id, qty) VALUES (%s,%s,%s)", + (rid, it["order_line_id"], it["qty"])) + return {"id": int(rid), "over": data["over"], "total": sum(it["qty"] for it in data["items"])} + + def delete_receipt(self, order_id: int, receipt_id: int, *, by: str) -> None: + """잘못 넣은 입고 1건을 지운다(그 수량만큼 다시 미입고).""" + with self._pool.connection() as conn, conn.transaction(): + head = self._lock_order(conn, order_id) + if head["cancelled_at"]: + raise ValueError("취소된 발주서입니다.") + row = conn.execute("DELETE FROM inout_receipts WHERE id=%s AND order_id=%s RETURNING id", + (receipt_id, order_id)).fetchone() + if not row: + raise ValueError("입고 기록을 찾을 수 없습니다.") + conn.execute("UPDATE inout_orders SET updated_by=%s WHERE id=%s", (_norm_email(by), order_id)) + + # ════════════════════════════════════════════════════════════ + # 미입고 현황 — 진행 중(종결·취소 아님) 발주의 남은 수량, 그리고 초과 입고 + # ════════════════════════════════════════════════════════════ + def outstanding(self, *, factory_id: int | None = None, q: str = "") -> dict[str, list[dict[str, Any]]]: + where, params = ["o.closed_at IS NULL", "o.cancelled_at IS NULL"], [] + if factory_id: + where.append("o.factory_id = %s") + params.append(factory_id) + if q.strip(): + like = "%" + q.strip().replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%" + where.append("(l.item_code ILIKE %s OR l.item_name ILIKE %s OR o.order_no ILIKE %s)") + params += [like, like, like] + with self._pool.connection() as conn: + rows = conn.execute( + "SELECT o.id AS order_id, o.order_no, o.order_date, o.due_date, f.name AS factory_name, " + "l.item_code, l.item_name, l.qty, COALESCE(sum(rl.qty), 0)::int AS received " + "FROM inout_order_lines l JOIN inout_orders o ON o.id = l.order_id " + "JOIN inout_factories f ON f.id = o.factory_id " + "LEFT JOIN inout_receipt_lines rl ON rl.order_line_id = l.id " + f"WHERE {' AND '.join(where)} GROUP BY l.id, o.id, f.name " + "ORDER BY o.due_date NULLS LAST, o.order_date, o.id, l.line_no", params).fetchall() + rows = store.decorate_lines(rows) + return {"pending": [r for r in rows if r["remaining"] > 0], "over": [r for r in rows if r["over"] > 0]} + + # ── 내부 ── + @staticmethod + def _lock_order(conn: Any, order_id: int) -> dict[str, Any]: + head = conn.execute("SELECT * FROM inout_orders WHERE id=%s FOR UPDATE", (order_id,)).fetchone() + if not head: + raise LookupError("발주서를 찾을 수 없습니다.") + return head + + @staticmethod + def _require_factory(conn: Any, factory_id: int, *, allow_inactive_id: int | None = None) -> None: + row = conn.execute("SELECT is_active FROM inout_factories WHERE id=%s", (factory_id,)).fetchone() + if not row: + raise ValueError("공장을 찾을 수 없습니다.") + if not row["is_active"] and factory_id != allow_inactive_id: + raise ValueError("사용하지 않는 공장입니다(옵션에서 '사용'으로 바꾸세요).") diff --git a/app/modules/inout/itemcode.py b/app/modules/inout/itemcode.py new file mode 100644 index 0000000..28e5d0f --- /dev/null +++ b/app/modules/inout/itemcode.py @@ -0,0 +1,82 @@ +"""itemcode_db 읽기 전용 — 단품(single_items)만 검색·확인. + +입출고 발주서의 제품은 코드표 DB 의 단품 아이템에서만 고른다(2026-10-16 사용자 요청 — 세트는 공장 발주 대상이 아님). +itemcode_db 실제 스키마(운영 확인됨, malaysia/itemcode.py 와 같음): single_items(item_code, sabangnet_code, name). +환경변수 `ITEMCODE_DB_URL`(읽기 전용 역할 itemcode_ro) — cupang·malaysia 모듈과 공유. +미설정/실패 시 enabled=False, 빈 결과(앱/모듈을 죽이지 않음) — 그때 발주서 저장은 "코드표 연결 필요"로 막는다. +""" + +from __future__ import annotations + +import logging +import os +from typing import Any + +logger = logging.getLogger("inout.itemcode") + +_SEARCH_SQL = ( + "SELECT item_code, name FROM single_items " + "WHERE item_code ILIKE %(q)s OR name ILIKE %(q)s " + "ORDER BY (item_code ILIKE %(prefix)s) DESC, item_code ASC LIMIT %(limit)s" +) +_LOOKUP_SQL = "SELECT item_code, name FROM single_items WHERE upper(item_code) = ANY(%(codes)s)" + + +class SingleItemReader: + def __init__(self, dsn: str | None = None) -> None: + self._pool: Any = None + self.enabled = False + self.reason = "" + self.last_error = "" + self._configure(dsn if dsn is not None else os.getenv("ITEMCODE_DB_URL", "").strip()) + + def _configure(self, dsn: str) -> None: + if not dsn: + self.reason = "ITEMCODE_DB_URL 미설정 — 코드표(단품) 조회 비활성." + return + try: + from psycopg.rows import dict_row + from psycopg_pool import ConnectionPool + + self._pool = ConnectionPool(conninfo=dsn, min_size=1, max_size=3, + kwargs={"row_factory": dict_row, "autocommit": True}, open=False) + self._pool.open(wait=False) + self.enabled = True + except Exception as exc: # noqa: BLE001 — 설정/드라이버 문제로 모듈을 죽이지 않음 + self.reason = f"itemcode_db 연결 풀 생성 실패: {type(exc).__name__}" + + def search(self, query: str, *, limit: int = 30) -> list[dict[str, str]]: + """코드·이름 부분 일치(코드 앞부분 일치 먼저). 반환 [{"code","name"}]. 실패는 빈 목록.""" + q = (query or "").strip() + if not q or not self.enabled or not self._pool: + return [] + esc = q.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + rows = self._run(_SEARCH_SQL, {"q": f"%{esc}%", "prefix": f"{esc}%", "limit": int(limit)}) + return [{"code": str(r["item_code"]).strip(), "name": str(r.get("name") or "").strip()} for r in rows or []] + + def lookup(self, codes: list[str]) -> dict[str, str] | None: + """코드들 → {코드(대문자): 이름}. 단품 표에 없는 코드는 빠진다. 조회 불가면 None.""" + if not self.enabled or not self._pool: + return None + wanted = sorted({c.strip().upper() for c in codes if c and c.strip()}) + if not wanted: + return {} + rows = self._run(_LOOKUP_SQL, {"codes": wanted}) + if rows is None: + return None + return {str(r["item_code"]).strip().upper(): str(r.get("name") or "").strip() for r in rows} + + def _run(self, sql: str, params: dict[str, Any]) -> list[dict[str, Any]] | None: + try: + with self._pool.connection() as conn: + rows = conn.execute(sql, params).fetchall() + self.last_error = "" + return rows + except Exception as exc: # noqa: BLE001 — 모듈을 죽이지 않음 + self.last_error = f"{type(exc).__name__}" + logger.exception("itemcode(single_items) 조회 실패") + return None + + def close(self) -> None: + if self._pool is not None: + self._pool.close() diff --git a/app/modules/inout/router.py b/app/modules/inout/router.py new file mode 100644 index 0000000..bb5e582 --- /dev/null +++ b/app/modules/inout/router.py @@ -0,0 +1,507 @@ +"""입출고 관리 모듈 라우터 — 본사 → 공장 발주, 물류 입고(분할), 발주 대비 미입고·초과. + + GET /inout/ 발주 목록(상태·공장·기간·검색) + GET /inout/pending 미입고 현황(품목별 합계 + 발주별) · 초과 입고 + GET|POST /inout/orders/new 발주서 작성(발주 담당) + GET /inout/orders/{id} 발주서 — 품목별 발주·입고·미입고, 입고 기록, 입고 입력(입고 담당) + GET|POST /inout/orders/{id}/edit 발주서 고치기(발주 담당) + POST /inout/orders/{id}/close|reopen|cancel 종결·종결 풀기·취소(발주 담당) + POST /inout/orders/{id}/receipts 입고 저장(입고 담당) — 발주 초과면 확인 화면, confirm_over=1 로 다시 보내야 저장 + POST /inout/orders/{id}/receipts/{rid}/delete 잘못 넣은 입고 지우기(입고 담당) + GET|POST /inout/settings… 옵션 — 공장 목록·발주 담당·입고 담당(ERP 관리자) + GET /inout/api/items?q= 코드표 단품 검색(JSON) + +권한: 모듈 권한키 `inout`(조회). 발주 담당·입고 담당은 옵션(inout_roles)에서 지정, ERP 관리자는 둘 다 + 옵션. +""" + +from __future__ import annotations + +from datetime import date +from typing import Any +from urllib.parse import urlencode + +from fastapi import APIRouter, HTTPException, Query, Request +from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse + +from app.timezone import today_kst + +from . import store +from .db import OverReceipt + +router = APIRouter(prefix="/inout", tags=["inout"]) + + +# ──────────────────────────────────────────────────────────── +# 공용 헬퍼 +# ──────────────────────────────────────────────────────────── +def _store(request: Request) -> Any: + return getattr(request.app.state, "inout_store", None) + + +def _items(request: Request) -> Any: + return getattr(request.app.state, "inout_items", None) + + +def _user(request: Request) -> dict[str, Any]: + from app.main import get_current_user_record # noqa: WPS433 + from app.store import has_module # noqa: WPS433 + + user = get_current_user_record(request) + if user is None: + raise HTTPException(status_code=401, detail="로그인이 필요합니다.") + if not has_module(user, "inout"): + raise HTTPException(status_code=403, detail="입출고 관리 모듈 권한이 없습니다.") + return user + + +def _page_user(request: Request) -> Any: + """화면 주소 — 로그인 전이면 로그인으로 보냈다가 돌아온다.""" + from urllib.parse import quote # noqa: WPS433 + + from app.main import get_current_user_record # noqa: WPS433 + + if get_current_user_record(request) is None: + here = str(request.url.path) + ("?" + request.url.query if request.url.query else "") + return RedirectResponse(url="/login?next=" + quote(here, safe=""), status_code=303) + return _user(request) + + +def _is_admin(user: dict[str, Any]) -> bool: + from app.store import is_admin # noqa: WPS433 + + return is_admin(user) + + +def _perms(st: Any, user: dict[str, Any]) -> dict[str, bool]: + """발주 담당·입고 담당 — 옵션(inout_roles), ERP 관리자는 둘 다.""" + admin = _is_admin(user) + roles = set() if admin else st.roles_of(user.get("email", "")) + return {"admin": admin, "can_order": admin or store.ROLE_ORDER in roles, + "can_receive": admin or store.ROLE_RECEIVE in roles} + + +def _require(st: Any, user: dict[str, Any], what: str) -> dict[str, bool]: + p = _perms(st, user) + if what == "order" and not p["can_order"]: + raise HTTPException(status_code=403, detail="발주 담당만 할 수 있습니다(입출고 관리 → 옵션에서 지정).") + if what == "receive" and not p["can_receive"]: + raise HTTPException(status_code=403, detail="입고 담당만 할 수 있습니다(입출고 관리 → 옵션에서 지정).") + if what == "admin" and not p["admin"]: + raise HTTPException(status_code=403, detail="옵션은 ERP 관리자만 바꿀 수 있습니다.") + return p + + +def _render(request: Request, name: str, user: dict[str, Any], ctx: dict[str, Any], status_code: int = 200) -> HTMLResponse: + from app.main import build_erp_nav, render_template # noqa: WPS433 + + st = _store(request) + perms = _perms(st, user) if st is not None else {"admin": _is_admin(user), "can_order": False, "can_receive": False} + return render_template(request, name, { + "user": user, "is_admin": perms["admin"], "perms": perms, + "nav_items": build_erp_nav(user, active="inout"), + "msg": request.query_params.get("msg", ""), "today": today_kst(), + **ctx, + }, status_code=status_code) + + +def _config_needed(request: Request, user: dict[str, Any]) -> HTMLResponse: + from app.main import build_erp_nav, render_template # noqa: WPS433 + + return render_template(request, "denied.html", { + "reason": "입출고 관리 모듈이 아직 설정되지 않았습니다. scripts/sql/inout_db_init.sql 로 inout_db 를 만들고 " + "INOUT_DB_URL 환경변수를 설정한 뒤 컨테이너를 재기동하세요.", + "user": user, "is_admin": _is_admin(user), "nav_items": build_erp_nav(user, active="inout"), + }, status_code=503) + + +def _ctx(request: Request) -> Any: + """화면 공통 — (st, user) 또는 응답(로그인·설정 필요).""" + user = _page_user(request) + if not isinstance(user, dict): + return user + st = _store(request) + if st is None: + return _config_needed(request, user) + return st, user + + +def _redirect(url: str, msg: str = "") -> RedirectResponse: + return RedirectResponse(url=url + (("&" if "?" in url else "?") + urlencode({"msg": msg}) if msg else ""), status_code=303) + + +def _order_or_404(st: Any, order_id: int) -> dict[str, Any]: + order = st.get_order(order_id) + if order is None: + raise HTTPException(status_code=404, detail="발주서를 찾을 수 없습니다.") + return order + + +def _opt_int(v: Any) -> int | None: + try: + n = int(str(v or "").strip()) + except ValueError: + return None + return n if n > 0 else None + + +def _opt_date(v: Any) -> date | None: + try: + return date.fromisoformat(str(v or "").strip()) + except ValueError: + return None + + +# ──────────────────────────────────────────────────────────── +# 발주 목록 · 미입고 현황 +# ──────────────────────────────────────────────────────────── +@router.get("/", response_class=HTMLResponse) +def index(request: Request, status: str = "active", factory: str = "", q: str = "", date_from: str = Query("", alias="from"), + date_to: str = Query("", alias="to")) -> Any: + got = _ctx(request) + if not isinstance(got, tuple): + return got + st, user = got + status = status if status in store.STATUS_FILTERS else "active" + orders = st.list_orders(status=status, factory_id=_opt_int(factory), q=q, date_from=_opt_date(date_from), + date_to=_opt_date(date_to)) + return _render(request, "inout/index.html", user, { + "tab": "orders", "orders": orders, "factories": st.list_factories(include_inactive=True), + "filters": {"status": status, "factory": _opt_int(factory), "q": q, "from": date_from, "to": date_to}, + "status_filters": store.STATUS_FILTERS, + }) + + +@router.get("/pending", response_class=HTMLResponse) +def pending(request: Request, factory: str = "", q: str = "") -> Any: + got = _ctx(request) + if not isinstance(got, tuple): + return got + st, user = got + data = st.outstanding(factory_id=_opt_int(factory), q=q) + by_item: dict[str, dict[str, Any]] = {} + for r in data["pending"]: + it = by_item.setdefault(r["item_code"], {"item_code": r["item_code"], "item_name": r["item_name"], + "remaining": 0, "orders": 0, "earliest_due": None}) + it["remaining"] += r["remaining"] + it["orders"] += 1 + if r["due_date"] and (it["earliest_due"] is None or r["due_date"] < it["earliest_due"]): + it["earliest_due"] = r["due_date"] + items = sorted(by_item.values(), key=lambda x: (-x["remaining"], x["item_code"])) + return _render(request, "inout/pending.html", user, { + "tab": "pending", "rows": data["pending"], "over": data["over"], "items": items, + "factories": st.list_factories(include_inactive=True), "filters": {"factory": _opt_int(factory), "q": q}, + "total_remaining": sum(r["remaining"] for r in data["pending"]), + }) + + +# ──────────────────────────────────────────────────────────── +# 발주서 작성·수정 +# ──────────────────────────────────────────────────────────── +def _form_values(form: Any) -> dict[str, Any]: + return {"factory_id": form.get("factory_id", ""), "order_date": form.get("order_date", ""), + "due_date": form.get("due_date", ""), "memo": form.get("memo", ""), + "codes": form.getlist("item_code"), "names": form.getlist("item_name"), + "quantities": form.getlist("qty"), "line_memos": form.getlist("line_memo")} + + +def _validated(request: Request, st: Any, vals: dict[str, Any], *, keep_codes: set[str]) -> tuple[dict[str, Any], dict[str, str]]: + """폼 검사 + 코드표(단품) 확인. keep_codes = 이미 발주서에 있던 코드(코드표에서 빠졌어도 그대로 둔다).""" + data = store.validate_order(factory_id=vals["factory_id"], order_date=vals["order_date"], due_date=vals["due_date"], + memo=vals["memo"], codes=vals["codes"], quantities=vals["quantities"], + line_memos=vals["line_memos"]) + new_codes = [ln["item_code"] for ln in data["lines"] if ln["item_code"] not in keep_codes] + names: dict[str, str] = {} + if new_codes: + reader = _items(request) + found = reader.lookup(new_codes) if reader is not None else None + if found is None: + raise ValueError("코드표 DB(itemcode_db)에 연결할 수 없어 제품을 확인하지 못했습니다 — 잠시 뒤 다시 저장하세요" + + ("" if reader is None or reader.enabled else " (ITEMCODE_DB_URL 미설정)") + ".") + missing = [c for c in new_codes if c not in found] + if missing: + raise ValueError("코드표 단품에 없는 제품입니다: " + ", ".join(missing)) + names = {c: found[c] for c in new_codes} + return data, names + + +def _form_page(request: Request, user: dict[str, Any], st: Any, *, order: dict[str, Any] | None, vals: dict[str, Any], + error: str = "", status_code: int = 200) -> HTMLResponse: + lines = [{"code": (c or "").strip().upper(), "name": vals["names"][i] if i < len(vals["names"]) else "", + "qty": vals["quantities"][i] if i < len(vals["quantities"]) else "", + "memo": vals["line_memos"][i] if i < len(vals["line_memos"]) else ""} + for i, c in enumerate(vals["codes"]) if (c or "").strip() or (i < len(vals["quantities"]) and vals["quantities"][i])] + reader = _items(request) + return _render(request, "inout/order_form.html", user, { + "tab": "orders", "order": order, "vals": vals, "lines": lines, "error": error, + "factories": [f for f in st.list_factories(include_inactive=True) + if f["is_active"] or (order and f["id"] == order["factory_id"])], + "items_enabled": bool(reader is not None and reader.enabled), + }, status_code=status_code) + + +@router.get("/orders/new", response_class=HTMLResponse) +def order_new(request: Request) -> Any: + got = _ctx(request) + if not isinstance(got, tuple): + return got + st, user = got + _require(st, user, "order") + vals = {"factory_id": "", "order_date": today_kst().isoformat(), "due_date": "", "memo": "", + "codes": [], "names": [], "quantities": [], "line_memos": []} + return _form_page(request, user, st, order=None, vals=vals) + + +@router.post("/orders/new", response_class=HTMLResponse) +async def order_create(request: Request) -> Any: + got = _ctx(request) + if not isinstance(got, tuple): + return got + st, user = got + _require(st, user, "order") + vals = _form_values(await request.form()) + try: + data, names = _validated(request, st, vals, keep_codes=set()) + res = st.create_order(data, names, by=user.get("email", "")) + except ValueError as exc: + return _form_page(request, user, st, order=None, vals=vals, error=str(exc), status_code=400) + return _redirect(f"/inout/orders/{res['id']}", f"발주서 {res['order_no']} 을(를) 만들었습니다.") + + +@router.get("/orders/{order_id}/edit", response_class=HTMLResponse) +def order_edit(request: Request, order_id: int) -> Any: + got = _ctx(request) + if not isinstance(got, tuple): + return got + st, user = got + _require(st, user, "order") + order = _order_or_404(st, order_id) + vals = {"factory_id": str(order["factory_id"]), "order_date": order["order_date"].isoformat(), + "due_date": order["due_date"].isoformat() if order["due_date"] else "", "memo": order["memo"], + "codes": [x["item_code"] for x in order["lines"]], "names": [x["item_name"] for x in order["lines"]], + "quantities": [str(x["qty"]) for x in order["lines"]], "line_memos": [x["memo"] for x in order["lines"]]} + return _form_page(request, user, st, order=order, vals=vals) + + +@router.post("/orders/{order_id}/edit", response_class=HTMLResponse) +async def order_update(request: Request, order_id: int) -> Any: + got = _ctx(request) + if not isinstance(got, tuple): + return got + st, user = got + _require(st, user, "order") + order = _order_or_404(st, order_id) + vals = _form_values(await request.form()) + try: + data, names = _validated(request, st, vals, keep_codes={x["item_code"] for x in order["lines"]}) + st.update_order(order_id, data, names, by=user.get("email", "")) + except ValueError as exc: + return _form_page(request, user, st, order=order, vals=vals, error=str(exc), status_code=400) + return _redirect(f"/inout/orders/{order_id}", "발주서를 고쳤습니다.") + + +# ──────────────────────────────────────────────────────────── +# 발주서 화면 · 종결 · 취소 +# ──────────────────────────────────────────────────────────── +def _detail(request: Request, user: dict[str, Any], st: Any, order: dict[str, Any], *, receipt_form: dict[str, Any] | None = None, + error: str = "", over: list[dict[str, Any]] | None = None, status_code: int = 200) -> HTMLResponse: + return _render(request, "inout/order_detail.html", user, { + "tab": "orders", "order": order, "error": error, "over": over or [], + "receipt_form": receipt_form or {"receipt_date": today_kst().isoformat(), "memo": "", "qty": {}}, + "can_receive_now": order["status"] in (store.ST_OPEN, store.ST_PARTIAL, store.ST_DONE, store.ST_OVER), + }, status_code=status_code) + + +@router.get("/orders/{order_id}", response_class=HTMLResponse) +def order_detail(request: Request, order_id: int) -> Any: + got = _ctx(request) + if not isinstance(got, tuple): + return got + st, user = got + return _detail(request, user, st, _order_or_404(st, order_id)) + + +@router.post("/orders/{order_id}/close") +async def order_close(request: Request, order_id: int) -> Any: + got = _ctx(request) + if not isinstance(got, tuple): + return got + st, user = got + _require(st, user, "order") + form = await request.form() + try: + st.set_closed(order_id, closed=True, reason=str(form.get("reason") or ""), by=user.get("email", "")) + except (ValueError, LookupError) as exc: + return _redirect(f"/inout/orders/{order_id}", str(exc)) + return _redirect(f"/inout/orders/{order_id}", "종결했습니다 — 남은 미입고는 미입고 현황에서 빠집니다.") + + +@router.post("/orders/{order_id}/reopen") +def order_reopen(request: Request, order_id: int) -> Any: + got = _ctx(request) + if not isinstance(got, tuple): + return got + st, user = got + _require(st, user, "order") + try: + st.set_closed(order_id, closed=False, by=user.get("email", "")) + except (ValueError, LookupError) as exc: + return _redirect(f"/inout/orders/{order_id}", str(exc)) + return _redirect(f"/inout/orders/{order_id}", "종결을 풀었습니다.") + + +@router.post("/orders/{order_id}/cancel") +def order_cancel(request: Request, order_id: int) -> Any: + got = _ctx(request) + if not isinstance(got, tuple): + return got + st, user = got + _require(st, user, "order") + try: + st.cancel_order(order_id, by=user.get("email", "")) + except (ValueError, LookupError) as exc: + return _redirect(f"/inout/orders/{order_id}", str(exc)) + return _redirect(f"/inout/orders/{order_id}", "발주서를 취소했습니다.") + + +# ──────────────────────────────────────────────────────────── +# 입고 +# ──────────────────────────────────────────────────────────── +@router.post("/orders/{order_id}/receipts", response_class=HTMLResponse) +async def receipt_add(request: Request, order_id: int) -> Any: + got = _ctx(request) + if not isinstance(got, tuple): + return got + st, user = got + _require(st, user, "receive") + form = await request.form() + qty: dict[int, str] = {} + for k, v in form.items(): + if k.startswith("qty_") and k[4:].isdigit(): + qty[int(k[4:])] = str(v) + rf = {"receipt_date": str(form.get("receipt_date") or ""), "memo": str(form.get("memo") or ""), "qty": qty} + try: + res = st.add_receipt(order_id, qty, receipt_date=rf["receipt_date"], memo=rf["memo"], + confirm_over=form.get("confirm_over") == "1", by=user.get("email", "")) + except OverReceipt as exc: + return _detail(request, user, st, _order_or_404(st, order_id), receipt_form=rf, over=exc.over, status_code=409) + except LookupError: + raise HTTPException(status_code=404, detail="발주서를 찾을 수 없습니다.") from None + except ValueError as exc: + return _detail(request, user, st, _order_or_404(st, order_id), receipt_form=rf, error=str(exc), status_code=400) + note = f"입고 {res['total']:,}개를 저장했습니다." + (" (초과 입고 포함)" if res["over"] else "") + return _redirect(f"/inout/orders/{order_id}", note) + + +@router.post("/orders/{order_id}/receipts/{receipt_id}/delete") +def receipt_delete(request: Request, order_id: int, receipt_id: int) -> Any: + got = _ctx(request) + if not isinstance(got, tuple): + return got + st, user = got + _require(st, user, "receive") + try: + st.delete_receipt(order_id, receipt_id, by=user.get("email", "")) + except (ValueError, LookupError) as exc: + return _redirect(f"/inout/orders/{order_id}", str(exc)) + return _redirect(f"/inout/orders/{order_id}", "입고 기록을 지웠습니다 — 그만큼 다시 미입고로 잡힙니다.") + + +# ──────────────────────────────────────────────────────────── +# 옵션 — 공장·발주 담당·입고 담당(ERP 관리자) +# ──────────────────────────────────────────────────────────── +def _candidates() -> list[dict[str, str]]: + """담당자 후보 — 입출고 모듈 권한이 있는 등록 사용자.""" + from app.main import user_store # noqa: WPS433 + from app.store import has_module # noqa: WPS433 + + out = [] + for u in user_store.list_all(): + if has_module(u, "inout"): + out.append({"email": str(u.get("email") or "").lower(), "name": str(u.get("name") or "")}) + return sorted(out, key=lambda x: x["email"]) + + +@router.get("/settings", response_class=HTMLResponse) +def settings(request: Request) -> Any: + got = _ctx(request) + if not isinstance(got, tuple): + return got + st, user = got + _require(st, user, "admin") + roles = st.list_roles() + cands = _candidates() + known = {c["email"] for c in cands} + for emails in roles.values(): # 권한이 빠졌어도 담당으로 남아 있는 사람은 보여 줘야 뺄 수 있다 + for e in emails: + if e not in known: + cands.append({"email": e, "name": "(입출고 모듈 권한 없음)"}) + known.add(e) + reader = _items(request) + return _render(request, "inout/settings.html", user, { + "tab": "settings", "factories": st.list_factories(include_inactive=True), "roles": roles, + "role_labels": store.ROLE_LABELS, "candidates": cands, + "items_status": "연결됨" if reader is not None and reader.enabled else (reader.reason if reader else "없음"), + }) + + +@router.post("/settings/factories") +async def settings_factory_save(request: Request) -> Any: + got = _ctx(request) + if not isinstance(got, tuple): + return got + st, user = got + _require(st, user, "admin") + form = await request.form() + try: + st.save_factory(factory_id=_opt_int(form.get("id")), name=str(form.get("name") or ""), + contact=str(form.get("contact") or ""), memo=str(form.get("memo") or ""), + is_active=form.get("is_active") == "1", sort_order=_opt_int(form.get("sort_order")) or 0) + except ValueError as exc: + return _redirect("/inout/settings", str(exc)) + return _redirect("/inout/settings", "공장을 저장했습니다.") + + +@router.post("/settings/factories/{factory_id}/delete") +def settings_factory_delete(request: Request, factory_id: int) -> Any: + got = _ctx(request) + if not isinstance(got, tuple): + return got + st, user = got + _require(st, user, "admin") + try: + st.delete_factory(factory_id) + except ValueError as exc: + return _redirect("/inout/settings", str(exc)) + return _redirect("/inout/settings", "공장을 지웠습니다.") + + +@router.post("/settings/roles") +async def settings_roles(request: Request) -> Any: + got = _ctx(request) + if not isinstance(got, tuple): + return got + st, user = got + _require(st, user, "admin") + form = await request.form() + for role in store.ROLES: + st.set_role_members(role, [str(e) for e in form.getlist(f"{role}_email")], by=user.get("email", "")) + return _redirect("/inout/settings", "담당자를 저장했습니다.") + + +# ──────────────────────────────────────────────────────────── +# API · 상태 +# ──────────────────────────────────────────────────────────── +@router.get("/api/items") +def api_items(request: Request, q: str = "") -> JSONResponse: + """코드표 단품 검색 — 발주서 제품 고르기.""" + _user(request) + reader = _items(request) + if reader is None or not reader.enabled: + return JSONResponse({"items": [], "enabled": False, + "message": "코드표 DB(ITEMCODE_DB_URL)가 연결되지 않았습니다."}) + return JSONResponse({"items": reader.search(q, limit=30), "enabled": True}) + + +@router.get("/health") +def health(request: Request) -> dict[str, str]: + return {"status": "ok" if _store(request) is not None else "not_configured"} diff --git a/app/modules/inout/store.py b/app/modules/inout/store.py new file mode 100644 index 0000000..f240f60 --- /dev/null +++ b/app/modules/inout/store.py @@ -0,0 +1,204 @@ +"""입출고 관리 — 상수·검사·상태 계산(순수 함수, 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}" diff --git a/app/modules/inout/templates/inout/_macros.html b/app/modules/inout/templates/inout/_macros.html new file mode 100644 index 0000000..5af00c6 --- /dev/null +++ b/app/modules/inout/templates/inout/_macros.html @@ -0,0 +1,18 @@ +{# 상태 배지 — 발주서(open·partial·done·over·closed·cancelled) / 품목(none·partial·done·over) #} +{% macro status_badge(status, label) -%} +{{ label }} +{%- endmacro %} + +{# 진행률 막대 — 입고 ÷ 발주 #} +{% macro progress(summary) -%} + + +{{ summary.pct }}% +{%- endmacro %} + +{# 입고 예정일 — 지났는데 남은 게 있으면 빨강 "지연 N일" #} +{% macro due(due_date, today, active) -%} +{% if due_date %}{{ due_date.strftime('%Y-%m-%d') }}{% if active and due_date < today %} 지연 {{ (today - due_date).days }}일{% elif active %} D-{{ (due_date - today).days }}{% endif %}{% else %}-{% endif %} +{%- endmacro %} + +{% macro n(v) -%}{{ '{:,}'.format(v or 0) }}{%- endmacro %} diff --git a/app/modules/inout/templates/inout/_nav.html b/app/modules/inout/templates/inout/_nav.html new file mode 100644 index 0000000..ed4f7a3 --- /dev/null +++ b/app/modules/inout/templates/inout/_nav.html @@ -0,0 +1,14 @@ +{# 입출고 관리 공용 상단: 탭(발주 목록·미입고 현황·옵션) + 새 발주서 + 알림 문구(?msg=) #} +
+ 발주 목록 + 미입고 현황 + {% if perms.admin %}옵션{% endif %} + + + {% if perms.can_order %}발주 담당{% endif %} + {% if perms.can_receive %}입고 담당{% endif %} + {% if not perms.can_order and not perms.can_receive %}조회만 가능 — 담당 지정은 옵션(관리자){% endif %} + + {% if perms.can_order %}+ 새 발주서{% endif %} +
+{% if msg %}

{{ msg }}

{% endif %} diff --git a/app/modules/inout/templates/inout/index.html b/app/modules/inout/templates/inout/index.html new file mode 100644 index 0000000..a93a79d --- /dev/null +++ b/app/modules/inout/templates/inout/index.html @@ -0,0 +1,61 @@ +{% extends "erp_base.html" %} +{% from "inout/_macros.html" import status_badge, progress, due, n %} +{% block head_extra %}{% endblock %} + +{% block content %} +
+ {% include "inout/_nav.html" %} + +
+ {# 상태 = 링크(다른 거르기 값 유지). 검색 칸 Enter 는 아래 [찾기] — 상태는 숨은 칸 값 그대로 #} + {% set keep = {'factory': filters.factory or '', 'q': filters.q, 'from': filters['from'], 'to': filters['to']} %} +
+ {% for key, f in status_filters.items() %} + {{ f[0] }} + {% endfor %} +
+ + + + ~ + + + +
+ +
+
+ + + + + + + {% for o in orders %} + {% set active = o.status in ('open', 'partial') %} + + + + + + + + + + + + + {% else %} + + {% endfor %} + +
발주번호공장제품발주일입고 예정일발주입고미입고진행상태
{% if filters.status == 'active' %}진행 중인 발주가 없습니다.{% else %}조건에 맞는 발주가 없습니다.{% endif %}
+
+
+
+{% endblock %} +{% block scripts %}{% endblock %} diff --git a/app/modules/inout/templates/inout/order_detail.html b/app/modules/inout/templates/inout/order_detail.html new file mode 100644 index 0000000..03128ed --- /dev/null +++ b/app/modules/inout/templates/inout/order_detail.html @@ -0,0 +1,133 @@ +{% extends "erp_base.html" %} +{% from "inout/_macros.html" import status_badge, progress, due, n %} +{% block head_extra %}{% endblock %} + +{% block content %} +{% set active = order.status in ('open', 'partial') %} +{% set receiving = perms.can_receive and can_receive_now %} +
+ {% include "inout/_nav.html" %} + +
+
+
+

{{ order.order_no }}

{{ status_badge(order.status, order.status_label) }} +
+
+
공장
{{ order.factory_name }}
+
발주일
{{ order.order_date.strftime('%Y-%m-%d') }}
+
입고 예정일
{{ due(order.due_date, today, active) }}
+
진행
{{ progress(order.summary) }}
+ {% if order.memo %}
메모
{{ order.memo }}
{% endif %} + {% if order.closed_at %}
종결
{{ order.closed_at.strftime('%Y-%m-%d') }} · {{ order.closed_by }}{% if order.close_reason %} — {{ order.close_reason }}{% endif %}
{% endif %} + {% if order.cancelled_at %}
취소
{{ order.cancelled_at.strftime('%Y-%m-%d') }} · {{ order.cancelled_by }}
{% endif %} +
+
+
+
발주
{{ n(order.summary.ordered) }}
+
입고
{{ n(order.summary.received) }}
+
미입고
{{ n(order.summary.remaining) }}
+ {% if order.summary.over %}
초과
+{{ n(order.summary.over) }}
{% endif %} +
+ {% if perms.can_order and not order.cancelled_at %} +
+ 발주서 고치기 + {% if order.closed_at %} +
+ {% elif order.summary.remaining %} +
+ + +
+ {% endif %} + {% if not order.receipts %} +
+ +
+ {% endif %} +
+ {% endif %} +
+ + {% if error %}{% endif %} + +
+ {# Enter 키 = 이 버튼(일반 저장). 없으면 폼의 첫 제출 버튼인 [초과 입고로 저장]이 눌려 확인 없이 초과가 저장된다 #} + {% if receiving %}{% endif %} +
+

품목

+ {% if receiving %}물류에 들어온 수량을 [이번 입고]에 넣고 저장 — 여러 번 나눠 넣어도 됩니다 + {% elif perms.can_receive and order.closed_at %}종결된 발주서 — 입고하려면 발주 담당이 종결을 풀어야 합니다{% endif %} +
+ + {% if over %} + + {% endif %} + +
+ + + {% if receiving %}{% endif %} + + {% for ln in order.lines %} + + + + + + + + + {% if receiving %}{% endif %} + + {% endfor %} + +
#제품 코드제품발주입고미입고상태이번 입고
{{ loop.index }}{{ ln.item_code }}{{ ln.item_name }}{% if ln.memo %}
{{ ln.memo }}
{% endif %}
{{ n(ln.qty) }}{{ n(ln.received) }}{{ n(ln.remaining) }}{% if ln.over %}
초과 +{{ n(ln.over) }}
{% endif %}
{{ status_badge(ln.status, ln.status_label) }}
+
+ {% if receiving %} +
+ + + + +
+ {% endif %} +
+ +
+

입고 기록

{{ order.receipts|length }}회
+ {% if order.receipts %} +
+ + {% if perms.can_receive and not order.cancelled_at %}{% endif %} + + {% for r in order.receipts %} + + + + + + {% if perms.can_receive and not order.cancelled_at %} + + {% endif %} + + {% endfor %} + +
입고일품목별 수량합계입력
{{ r.receipt_date.strftime('%Y-%m-%d') }}{% if r.memo %}
{{ r.memo }}
{% endif %}
{% for x in r.lines %}{{ x.item_code }} {{ n(x.qty) }}{% endfor %}{{ n(r.total) }}{{ r.created_by }}
{{ r.created_at.strftime('%Y-%m-%d %H:%M') }}
+
+
+ {% else %} +

아직 입고된 것이 없습니다.

+ {% endif %} +
+
+{% endblock %} +{% block scripts %}{% endblock %} diff --git a/app/modules/inout/templates/inout/order_form.html b/app/modules/inout/templates/inout/order_form.html new file mode 100644 index 0000000..18bdd96 --- /dev/null +++ b/app/modules/inout/templates/inout/order_form.html @@ -0,0 +1,79 @@ +{% extends "erp_base.html" %} +{% block head_extra %}{% endblock %} + +{% block content %} +
+ {% include "inout/_nav.html" %} + +
+
+

{% if order %}발주서 고치기 · {{ order.order_no }}{% else %}새 발주서{% endif %}

+ 제품은 코드표의 단품에서 고릅니다 +
+ {% if error %}{% endif %} + {% if not items_enabled %}{% endif %} + +
+ + + + +
+ +
+ + + + {% for ln in lines %} + {% set received = (order.lines | selectattr('item_code', 'equalto', ln.code) | map(attribute='received') | first) if order else 0 %} + + + + + + + + {% endfor %} + + +
#제품(코드·이름으로 검색)발주 수량줄 메모
+ + + + {% if received %}
입고 {{ '{:,}'.format(received) }}개 — 제품은 그대로, 수량만 바꿀 수 있습니다
{% endif %} +
{% if not received %}{% endif %}
+ + 합계 0개 · 0종 +
+
+ + + +
+ 취소 + +
+
+
+{% endblock %} +{% block scripts %}{% endblock %} diff --git a/app/modules/inout/templates/inout/pending.html b/app/modules/inout/templates/inout/pending.html new file mode 100644 index 0000000..b85709f --- /dev/null +++ b/app/modules/inout/templates/inout/pending.html @@ -0,0 +1,91 @@ +{% extends "erp_base.html" %} +{% from "inout/_macros.html" import due, n %} +{% block head_extra %}{% endblock %} + +{% block content %} +
+ {% include "inout/_nav.html" %} + +
+ + + + + 진행 중인 발주(종결·취소 제외)의 남은 수량 +
+ +
+
미입고 수량
{{ n(total_remaining) }}
+
미입고 제품
{{ n(items|length) }}종
+
미입고 발주 줄
{{ n(rows|length) }}
+
초과 입고
{{ n(over|length) }}건
+
+ +
+

제품별 미입고 합계

여러 발주에 걸친 남은 수량을 제품마다 더한 값
+
+ + + + {% for it in items %} + + + + + + {% else %} + + {% endfor %} + +
제품 코드제품미입고발주 건수가장 이른 입고 예정일
{{ it.item_code }}{{ it.item_name }}{{ n(it.remaining) }}{{ it.orders }}{{ due(it.earliest_due, today, True) }}
미입고된 제품이 없습니다. 모두 들어왔습니다.
+
+
+ + {% if rows %} +
+

발주별 미입고

입고 예정일이 이른 순 — 지난 것은 빨강
+
+ + + + + {% for r in rows %} + + + + + + + + {% endfor %} + +
입고 예정일발주번호공장제품 코드제품발주입고미입고
{{ due(r.due_date, today, True) }}{{ r.order_no }}
발주 {{ r.order_date.strftime('%Y-%m-%d') }}
{{ r.factory_name }}{{ r.item_code }}{{ r.item_name }}{{ n(r.qty) }}{{ n(r.received) }}{{ n(r.remaining) }}
+
+
+ {% endif %} + + {% if over %} +
+

초과 입고

발주보다 많이 들어온 제품 — 공장과 확인이 필요합니다
+
+ + + + {% for r in over %} + + + + + + {% endfor %} + +
발주번호공장제품 코드제품발주입고초과
+
+
+ {% endif %} +
+{% endblock %} +{% block scripts %}{% endblock %} diff --git a/app/modules/inout/templates/inout/settings.html b/app/modules/inout/templates/inout/settings.html new file mode 100644 index 0000000..aed2b8a --- /dev/null +++ b/app/modules/inout/templates/inout/settings.html @@ -0,0 +1,74 @@ +{% extends "erp_base.html" %} +{% block head_extra %}{% endblock %} + +{% block content %} +
+ {% include "inout/_nav.html" %} + +
+
+

담당자

ERP 관리자는 지정 없이도 둘 다 할 수 있습니다
+

+ 발주 담당 — 발주서 작성·고치기·잔량 종결·취소. 입고 담당 — 물류에 들어온 입고 수량 입력·지우기. + 그 밖의 사람은 조회만 합니다. 후보 = ERP 관리자 화면에서 입출고 관리 권한을 받은 사용자. +

+
+ + {% for role, label in role_labels.items() %}{% endfor %} + + {% for c in candidates %} + + + {% for role in role_labels %} + + {% endfor %} + + {% else %} + + {% endfor %} + +
사용자{{ label }}
{{ c.name or c.email }}
{{ c.email }}
입출고 관리 권한을 받은 사용자가 없습니다 — ERP 관리자 화면에서 먼저 권한을 주세요.
+
+
+
+ +
+

공장(발주처)

발주 기록이 있는 공장은 지우지 말고 '사용 안 함'으로
+ {# 줄마다 폼 하나(표 안에 폼을 넣을 수 없어 격자로) — 머리 줄과 같은 열 #} +
+
+ 이름담당자·연락처메모순서사용발주 +
+ {% for f in factories %} +
+ + + + + + + {{ f.order_count }}건 + + + {% if not f.order_count %}{% endif %} + +
+ {% endfor %} +
+ + + + + + + +
+
+
+ +

코드표(단품) 연결: {{ items_status }}

+
+
+{% endblock %} diff --git a/app/static/inout.css b/app/static/inout.css new file mode 100644 index 0000000..06388b7 --- /dev/null +++ b/app/static/inout.css @@ -0,0 +1,124 @@ +/* 입출고 관리(inout) — ERP 공용(erp.css·erp-shell.css) 위에 이 화면만의 것 */ +/* 공용 .erp-page 는 width:100% + 안쪽 여백(content-box)이라 표가 넓으면 48px 넘친다 — 이 화면에서만 테두리 기준으로 */ +.erp-page:has(> .io) { box-sizing: border-box; } +.io { display: flex; flex-direction: column; gap: 14px; min-width: 0; } /* 넓은 표는 안에서 가로 스크롤(페이지가 화면보다 넓어지지 않게) */ +.io-nav { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; } +.io-nav-gap { flex: 1 1 auto; } +.io-roles { display: inline-flex; gap: 4px; align-items: center; } +.io-flash { margin: 0; padding: 10px 14px; border-radius: 8px; background: #eef6ff; color: #0b4a8b; font-size: 13px; border: 1px solid #cfe3fb; } +.io-error { margin: 12px 20px 0; padding: 10px 14px; border-radius: 8px; background: #fbe9e6; color: #a1261b; border: 1px solid #efc6bf; font-size: 13px; } +.io > .io-error { margin: 0; } +.io-hint { color: #a1261b; font-size: 12px; } +.io-help { margin: 0; padding: 12px 20px 0; font-size: 12.5px; color: var(--color-midtone-gray); line-height: 1.6; } +.io-foot { margin: 0; } + +/* 거르기 줄 */ +.io-filter { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; } +.io-filter .erp-input, .io-filter .erp-select { width: auto; } +.io-search { min-width: 220px; } +.io-filter input[type="date"] { width: 150px; } +.io-date { display: inline-flex; align-items: center; gap: 6px; font-size: 12px; color: var(--color-midtone-gray); } +.io-seg { display: inline-flex; padding: 2px; border: 1px solid var(--color-subtle-ash); border-radius: 10px; background: #fff; } +.io-seg-btn { padding: 5px 12px; border-radius: 8px; font-size: 12.5px; color: var(--color-rich-black); text-decoration: none; white-space: nowrap; } +.io-seg-btn:hover { background: var(--color-ghost-gray); } +.io-seg-btn.is-active, .io-seg-btn.is-active:hover { background: var(--color-deep-black); color: #fff; } + +/* 표 */ +.io-table td, .io-table th { white-space: nowrap; } +.io-table td.io-items { white-space: normal; min-width: 160px; } +.io-num { text-align: right !important; font-variant-numeric: tabular-nums; } +.io-code { font-family: ui-monospace, Consolas, monospace; font-size: 12px; } +.io-order-no { font-weight: 600; color: var(--color-rich-black); text-decoration: none; font-family: ui-monospace, Consolas, monospace; } +.io-order-no:hover { text-decoration: underline; } +.io-row-link { cursor: pointer; } +.io-row-link.is-late td:first-child { box-shadow: inset 3px 0 0 #d93025; } +.io-remaining { color: #b45309; font-weight: 600; } +.io-over, .io-over-sub { color: #d93025; font-weight: 600; } +.io-over-sub { font-size: 11px; } +.io-late { color: #d93025; font-weight: 600; font-size: 12px; } +.io-block { overflow: visible; } + +/* 상태 배지 */ +.io-badge { display: inline-flex; align-items: center; padding: 2px 8px; border-radius: 999px; font-size: 11.5px; font-weight: 600; white-space: nowrap; border: 1px solid transparent; } +.io-st-open, .io-st-none { background: #eef0f2; color: #3d4148; } +.io-st-partial { background: #fff4e0; color: #9a5b00; border-color: #f6dcae; } +.io-st-done { background: #e6f8e9; color: #1e7a34; border-color: #c2efc8; } +.io-st-over { background: #fbe9e6; color: #b3261e; border-color: #efc6bf; } +.io-st-closed { background: #f4f4f5; color: #6b6f76; border-color: #dcdde0; } +.io-st-cancelled { background: #fff; color: #9aa0a6; border-color: #dcdde0; text-decoration: line-through; } + +/* 진행률 */ +.io-progress { display: inline-block; width: 80px; height: 6px; border-radius: 999px; background: #eceef1; overflow: hidden; vertical-align: middle; } +.io-progress-bar { display: block; height: 100%; background: #1e8e3e; border-radius: inherit; } +.io-progress-bar.is-over { background: #d93025; } +.io-progress-pct { margin-left: 6px; font-size: 12px; color: var(--color-midtone-gray); font-variant-numeric: tabular-nums; } + +/* 요약 숫자 */ +.io-kpis { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 10px; } +.io-kpi-remaining .erp-summary-value { color: #b45309; } +.io-kpi-over .erp-summary-value { color: #d93025; } + +/* 발주서 머리 */ +.io-head { padding: 16px 20px; display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 12px 20px; overflow: visible; } +.io-head-title { display: flex; align-items: center; gap: 10px; } +.io-head-title h2 { margin: 0; font-size: 18px; font-family: ui-monospace, Consolas, monospace; } +.io-head-meta { display: flex; flex-wrap: wrap; gap: 8px 24px; margin: 12px 0 0; } +.io-head-meta dt { font-size: 11.5px; color: var(--color-midtone-gray); } +.io-head-meta dd { margin: 2px 0 0; font-size: 13.5px; } +.io-head-meta .io-wide { flex-basis: 100%; } +.io-kpis-head { grid-template-columns: repeat(auto-fit, minmax(96px, 1fr)); align-self: start; min-width: 320px; } +.io-head-actions { grid-column: 1 / -1; display: flex; flex-wrap: wrap; gap: 8px; align-items: center; padding-top: 12px; border-top: 1px solid var(--color-subtle-ash); } +.io-head-actions form { display: inline-flex; gap: 6px; align-items: center; margin: 0; } +.io-close-reason { width: 200px; } + +/* 입고 입력 */ +.io-col-no { width: 36px; color: var(--color-midtone-gray); } +.io-col-recv { width: 130px; background: #f6fbf7; } +.io-table thead th.io-col-recv { background: #eaf6ee; color: #1e7a34; font-weight: 600; } +.io-qty { width: 110px; text-align: right; font-variant-numeric: tabular-nums; } +.io-receipt-bar { display: flex; align-items: flex-end; gap: 10px; flex-wrap: wrap; padding: 14px 20px; border-top: 1px solid var(--color-subtle-ash); background: #fafbfc; } +.io-receipt-bar .erp-field input { min-width: 150px; } +.io-grow { flex: 1 1 260px; } +.io-default-submit { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0 0 0 0); border: 0; } +.io-over-box { margin: 12px 20px 0; padding: 12px 16px; border-radius: 8px; background: #fbe9e6; border: 1px solid #efc6bf; color: #7a1d14; font-size: 13px; } +.io-over-box ul { margin: 6px 0 10px; padding-left: 18px; } +.io-chip { display: inline-block; margin: 2px 6px 2px 0; padding: 1px 8px; border-radius: 6px; background: var(--color-ghost-gray); font-size: 12px; white-space: nowrap; } + +/* 발주서 폼 */ +.io-order-form { overflow: visible; } +.io-lines .io-col-qty { width: 130px; } +.io-lines .io-col-del { width: 48px; text-align: center; } +.io-lines tfoot td { padding: 10px 16px; border-top: 1px solid var(--color-subtle-ash); } +.io-item-cell { position: relative; min-width: 320px; } +.io-item-search { width: 100%; } +.io-item-search.is-invalid { border-color: #d93025; box-shadow: 0 0 0 3px rgba(217, 48, 37, .12); } +.io-item-search[readonly] { background: var(--color-ghost-gray); } +.io-total { margin-left: 12px; } +.io-form-actions { display: flex; justify-content: flex-end; gap: 8px; padding: 14px 20px; border-top: 1px solid var(--color-subtle-ash); } +/* 검색 드롭다운 — 표 가로 스크롤 상자에 잘리지 않게 화면 기준(fixed), 위치는 inout.js 가 입력칸에 맞춤 */ +.io-suggest { position: fixed; z-index: 1000; max-height: 280px; overflow-y: auto; + background: #fff; border: 1px solid var(--color-subtle-ash); border-radius: 8px; box-shadow: 0 8px 24px rgba(0, 0, 0, .12); } +.io-suggest-item { padding: 7px 12px; font-size: 13px; cursor: pointer; white-space: normal; } +.io-suggest-item:hover, .io-suggest-item.is-active { background: #eef6ff; } +.io-suggest-empty { padding: 10px 12px; font-size: 12.5px; color: var(--color-midtone-gray); white-space: normal; } + +/* 옵션 */ +.io-settings { display: flex; flex-direction: column; gap: 14px; } +.io-col-check { width: 90px; text-align: center !important; } +.io-factories { padding: 6px 12px 12px; } +.io-factory-row { display: grid; grid-template-columns: minmax(140px, 1.2fr) minmax(140px, 1.2fr) minmax(120px, 1.5fr) 70px 50px 60px auto; + gap: 8px; align-items: center; padding: 6px 8px; margin: 0; border-bottom: 1px solid var(--color-subtle-ash); } +.io-factory-head { font-size: 12px; color: var(--color-midtone-gray); font-weight: 500; } +.io-factory-row .erp-input { width: 100%; min-width: 0; } +.io-factory-row.io-inactive .erp-input { color: var(--color-midtone-gray); background: var(--color-ghost-gray); } +.io-new-factory { border-bottom: 0; background: #fafbfc; border-radius: 8px; } +.io-factory-btns { display: inline-flex; gap: 6px; justify-content: flex-end; } +.io-check { display: inline-flex; justify-content: center; } + +@media (max-width: 900px) { + .io-kpis { grid-template-columns: repeat(2, minmax(0, 1fr)); } + .io-head { grid-template-columns: 1fr; } + .io-kpis-head { min-width: 0; } + .io-factory-row { grid-template-columns: 1fr 1fr; } + .io-factory-head { display: none; } +} diff --git a/app/static/inout.js b/app/static/inout.js new file mode 100644 index 0000000..30a5010 --- /dev/null +++ b/app/static/inout.js @@ -0,0 +1,227 @@ +/* 입출고 관리(inout) 화면 스크립트 — 화면 전환·저장은 서버(폼)가 하고, 여기는 입력을 돕기만 한다. + · 목록 줄 누르기 = 발주서로 + · 발주서 폼: 제품 줄 추가·지우기·번호·합계, 코드표 단품 검색(GET /inout/api/items?q=) 드롭다운 + · 발주서 화면: [남은 수량 모두 채우기], 이번 입고 합계 + · data-erp-confirm-btn: 버튼별 확인(formaction 이 있는 버튼 — 공용 data-erp-confirm 은 form.submit() 이라 누른 버튼이 사라짐) */ +(function () { + "use strict"; + + function confirmMsg(msg) { + return window.erpConfirm ? window.erpConfirm(msg) : Promise.resolve(window.confirm(msg)); + } + function alertMsg(msg) { + return window.erpAlert ? window.erpAlert(msg) : Promise.resolve(window.alert(msg)); + } + function num(v) { + const n = parseInt(String(v || "").replace(/[,\s]/g, ""), 10); + return Number.isFinite(n) && n > 0 ? n : 0; + } + function fmt(n) { return n.toLocaleString("ko-KR"); } + + // ── 목록 줄 누르기 → 발주서 ── + document.addEventListener("click", function (e) { + const row = e.target.closest(".io-row-link"); + if (!row || e.target.closest("a, button, input, select, label")) return; + if (window.getSelection && String(window.getSelection())) return; // 글자 고르는 중 + location.href = row.dataset.href; + }); + + // ── 버튼별 확인 ── + document.addEventListener("click", function (e) { + const btn = e.target.closest("[data-erp-confirm-btn]"); + if (!btn || btn.dataset.confirmed === "1") return; + e.preventDefault(); + confirmMsg(btn.dataset.erpConfirmBtn).then(function (ok) { + if (!ok) return; + btn.dataset.confirmed = "1"; + if (btn.form.requestSubmit) btn.form.requestSubmit(btn); else btn.click(); + }); + }); + + // ── 발주서 폼 ── + const form = document.getElementById("io-order-form"); + if (form) initOrderForm(form); + + function initOrderForm(form) { + const body = form.querySelector("#io-lines tbody"); + const tpl = document.getElementById("io-line-tpl"); + const totalQty = document.getElementById("io-total-qty"); + const totalLines = document.getElementById("io-total-lines"); + + function renumber() { + let q = 0, k = 0; + body.querySelectorAll(".io-line").forEach(function (tr, i) { + tr.querySelector(".io-col-no").textContent = String(i + 1); + const n = num(tr.querySelector(".io-qty").value); + if (tr.querySelector('input[name="item_code"]').value) { k++; q += n; } + }); + totalQty.textContent = fmt(q); + totalLines.textContent = fmt(k); + } + function addLine(focus) { + const tr = tpl.content.firstElementChild.cloneNode(true); + body.appendChild(tr); + wireSearch(tr.querySelector(".io-item-search")); + renumber(); + if (focus) tr.querySelector(".io-item-search").focus(); + return tr; + } + form.querySelector("#io-add-line").addEventListener("click", function () { addLine(true); }); + body.addEventListener("click", function (e) { + const del = e.target.closest(".io-del"); + if (!del) return; + const tr = del.closest(".io-line"); + const search = tr.querySelector(".io-item-search"); + if (search && search._ioBox) search._ioBox.remove(); // body 에 붙은 드롭다운도 함께 + tr.remove(); + if (!body.querySelector(".io-line")) addLine(false); + renumber(); + }); + body.addEventListener("input", renumber); // 수량을 바꾸거나 제품 글을 고치면(고른 것 풀림) 다시 셈 + body.addEventListener("io-chosen", renumber); // 검색 목록에서 제품을 고르면 + body.querySelectorAll(".io-item-search").forEach(wireSearch); + if (!body.querySelector(".io-line")) { addLine(false); addLine(false); addLine(false); } + renumber(); + + form.addEventListener("submit", function (e) { + // 검색 글만 있고 목록에서 고르지 않은 줄, 같은 제품 두 줄 — 서버도 막지만 여기서 먼저 알려 준다 + const codes = []; + let bad = null; + body.querySelectorAll(".io-line").forEach(function (tr) { + const code = tr.querySelector('input[name="item_code"]').value; + const text = tr.querySelector(".io-item-search").value.trim(); + if (!code && text && !bad) bad = { tr: tr, msg: "'" + text + "' — 검색 목록에서 제품을 골라 주세요." }; + if (code && codes.indexOf(code) >= 0 && !bad) bad = { tr: tr, msg: code + " — 같은 제품이 두 줄에 있습니다. 한 줄로 합쳐 주세요." }; + if (code) codes.push(code); + }); + if (bad) { + e.preventDefault(); + bad.tr.querySelector(".io-item-search").classList.add("is-invalid"); + alertMsg(bad.msg).then(function () { bad.tr.querySelector(".io-item-search").focus(); }); + } + }); + } + + // 코드표 단품 검색 드롭다운 — 고르면 숨은 칸(코드·이름)을 채우고 수량 칸으로. 글을 다시 고치면 고른 것을 지운다. + function wireSearch(input) { + if (!input || input.readOnly || input.dataset.wired) return; + input.dataset.wired = "1"; + const cell = input.closest(".io-item-cell"); + const codeEl = cell.querySelector('input[name="item_code"]'); + const nameEl = cell.querySelector('input[name="item_name"]'); + const box = document.createElement("div"); + box.className = "io-suggest"; + box.setAttribute("role", "listbox"); + box.hidden = true; + document.body.appendChild(box); // 표 가로 스크롤 상자 밖(fixed) — 아래 줄에서도 잘리지 않게 + input._ioBox = box; + let timer = 0, seq = 0, items = [], active = -1; + + function place() { + const r = input.getBoundingClientRect(); + const below = window.innerHeight - r.bottom; + box.style.left = r.left + "px"; + box.style.width = Math.max(r.width, 320) + "px"; + if (below < 200 && r.top > below) { box.style.top = ""; box.style.bottom = (window.innerHeight - r.top + 2) + "px"; } + else { box.style.bottom = ""; box.style.top = (r.bottom + 2) + "px"; } + } + window.addEventListener("resize", function () { if (!box.hidden) place(); }); + document.addEventListener("scroll", function () { if (!box.hidden) place(); }, true); + function close() { box.hidden = true; active = -1; input.setAttribute("aria-expanded", "false"); } + function paint() { + box.innerHTML = ""; + if (!items.length) { + const empty = document.createElement("div"); + empty.className = "io-suggest-empty"; + empty.textContent = box.dataset.message || "맞는 단품이 없습니다."; + box.appendChild(empty); + } + items.forEach(function (it, i) { + const opt = document.createElement("div"); + opt.className = "io-suggest-item" + (i === active ? " is-active" : ""); + opt.setAttribute("role", "option"); + const c = document.createElement("span"); + c.className = "io-code"; + c.textContent = it.code; + opt.appendChild(c); + opt.appendChild(document.createTextNode(" " + it.name)); + opt.addEventListener("mousedown", function (e) { e.preventDefault(); choose(i); }); + box.appendChild(opt); + }); + box.hidden = false; + place(); + input.setAttribute("aria-expanded", "true"); + } + function choose(i) { + const it = items[i]; + if (!it) return; + codeEl.value = it.code; + nameEl.value = it.name; + input.value = it.code + " · " + it.name; + input.classList.remove("is-invalid"); + close(); + const qty = input.closest("tr").querySelector(".io-qty"); + if (qty) qty.focus(); + input.dispatchEvent(new Event("io-chosen", { bubbles: true })); + } + async function search(q) { + const my = ++seq; + try { + const res = await fetch("/inout/api/items?q=" + encodeURIComponent(q), { headers: { Accept: "application/json" } }); + const data = await res.json(); + if (my !== seq) return; + items = data.items || []; + box.dataset.message = data.enabled === false ? (data.message || "코드표가 연결되지 않았습니다.") : ""; + active = items.length ? 0 : -1; + paint(); + } catch (_) { + if (my !== seq) return; + items = []; + box.dataset.message = "검색하지 못했습니다. 잠시 뒤 다시 입력하세요."; + paint(); + } + } + input.setAttribute("aria-autocomplete", "list"); + input.addEventListener("input", function () { + codeEl.value = ""; // 글을 고치면 고른 제품은 풀린다(다시 골라야 저장) + nameEl.value = ""; + clearTimeout(timer); + const q = input.value.trim(); + if (!q) { close(); return; } + timer = setTimeout(function () { search(q); }, 200); + }); + input.addEventListener("keydown", function (e) { + if (box.hidden) return; + if (e.key === "ArrowDown" || e.key === "ArrowUp") { + e.preventDefault(); + if (!items.length) return; + active = (active + (e.key === "ArrowDown" ? 1 : items.length - 1)) % items.length; + paint(); + } else if (e.key === "Enter") { + e.preventDefault(); // 고르기만 — 폼 저장 아님 + choose(active < 0 ? 0 : active); + } else if (e.key === "Escape") { + close(); + } + }); + input.addEventListener("blur", function () { setTimeout(close, 120); }); + } + + // ── 발주서 화면: 입고 입력 ── + const recvForm = document.getElementById("io-receipt-form"); + if (recvForm) { + const total = document.getElementById("io-recv-total"); + const inputs = Array.from(recvForm.querySelectorAll(".io-recv")); + const paintTotal = function () { + const t = inputs.reduce(function (s, i) { return s + num(i.value); }, 0); + if (total) total.textContent = t ? "(" + fmt(t) + "개)" : ""; + }; + recvForm.addEventListener("input", paintTotal); + const fill = document.getElementById("io-fill-remaining"); + if (fill) fill.addEventListener("click", function () { + inputs.forEach(function (i) { if (!i.value.trim() && num(i.dataset.remaining)) i.value = i.dataset.remaining; }); + paintTotal(); + }); + paintTotal(); + } +})(); diff --git a/app/store.py b/app/store.py index 257f62f..950e01f 100644 --- a/app/store.py +++ b/app/store.py @@ -34,6 +34,7 @@ MODULE_KEYS: tuple[str, ...] = ( "cafe24", "performance", "asset", + "inout", "expense_approver", "vacation_approver", ) diff --git a/docs/DATABASES.md b/docs/DATABASES.md index 8c4d9ba..fd983af 100644 --- a/docs/DATABASES.md +++ b/docs/DATABASES.md @@ -12,6 +12,7 @@ | `malaysia_stock_db` | 말레이시아 창고 재고관리 — 창고/아이템/세트 BOM/입출고 이력/일일 재고조사 | | `cafe24_db` | 카페24 연동 — OAuth 토큰/상품 캐시/상세페이지 버전/예약/감사·API 로그 | | `performance_db` | 실적(쇼핑몰 통합 매출) — 쇼핑몰 설정/수수료율 이력/API 인증정보(암호문)/연결 상태/매출 사건/동기화 기록 | +| `inout_db` | 입출고 관리 — 공장/발주 담당·입고 담당/발주서·발주 품목/입고·입고 품목 (2026-10-16, 앱 계정 `inout_app`, `INOUT_DB_URL`, 초기화 `scripts/sql/inout_db_init.sql`, 상세 `docs/INOUT_MODULE.md`) | --- diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md index 7ae4adf..5f09c64 100644 --- a/docs/DEPLOYMENT.md +++ b/docs/DEPLOYMENT.md @@ -264,6 +264,23 @@ docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d project_db < s docker exec postgres-db psql -U postgres -d project_db -c "SELECT to_regclass('goal_meeting_tasks') AS t;" ``` +## 입출고 관리 DB 생성 (inout_db, 2026-10-16) + +새 DB 라 기존 DB·데이터는 건드리지 않는다(초기화 SQL 은 멱등, DROP·TRUNCATE 없음). 비밀번호는 영문·숫자로(DSN 에 그대로 들어감). + +```bash +cd /opt/www/main && git pull +docker exec postgres-db psql -U postgres -lqt | cut -d| -f1 | grep -w inout_db || echo "inout_db 없음 — 새로 만든다" +read -s -p "inout_app password: " APP_PWD; echo +docker exec -i postgres-db psql -U postgres -v app_password="$APP_PWD" < scripts/sql/inout_db_init.sql +grep -q "^INOUT_DB_URL=" .env || echo "INOUT_DB_URL=postgresql://inout_app:${APP_PWD}@postgres-db:5432/inout_db" >> .env +docker compose up --build -d web +curl -s http://127.0.0.1:/inout/health # {"status":"ok"} +``` + +그다음 ERP 관리자 화면에서 쓸 사람에게 **입출고 관리** 권한 → 입출고 관리 → 옵션에서 공장·발주 담당·입고 담당 지정. +백업: 매일 `docker exec postgres-db pg_dump -U postgres inout_db > /var/backups/postgres/inout_db_$(date +%F).sql`. + ## 긴급 공지 마이그레이션 (024) 024는 `urgent_notices`·`urgent_notice_targets`·`urgent_notice_acks`·`urgent_notice_images` 테이블만 추가한다(기존 값 그대로, 다시 실행 가능). @@ -370,6 +387,7 @@ docker compose down # 컨테이너 제거 (볼륨 유지) | `APP_ENCRYPTION_KEY` | 쇼핑몰 API 인증정보 암호화 마스터 키(32바이트, `openssl rand -hex 32`). DB 에 저장하지 않음. **분실 시 저장된 인증정보 복구 불가 — 별도 안전 보관**. 쇼핑몰별 ID/Key/Secret 은 `.env` 에 넣지 않고 실적 → 설정 화면에서 입력 | | `APP_ENCRYPTION_KEY_VERSION` | 현재 마스터 키 버전(기본 1). 교체 시 올리고 예전 키는 `APP_ENCRYPTION_KEY_V{n}` 로 남긴 뒤 설정 화면에서 재암호화(`docs/PERFORMANCE_MODULE.md`) | | `PERFORMANCE_SYNC_DAYS` | [매출 업데이트] 수집 기간(오늘 포함 최근 N일, 기본 7, 최대 90) | +| `INOUT_DB_URL` | 입출고 관리 DB DSN (예: `postgresql://inout_app:@postgres-db:5432/inout_db`). 미설정 시 입출고 모듈 비활성(설정 필요 안내). 권한키 `inout`. 제품은 `ITEMCODE_DB_URL`(단품) 재사용 | --- diff --git a/docs/INOUT_MODULE.md b/docs/INOUT_MODULE.md new file mode 100644 index 0000000..864ef29 --- /dev/null +++ b/docs/INOUT_MODULE.md @@ -0,0 +1,89 @@ +# 입출고 관리(inout) 모듈 + +> `app/modules/inout/` · DB `inout_db` · URL `/inout/` · 권한키 `inout` · 2026-10-16 신설 + +본사가 공장에 **제품 제작 발주**를 넣고, 공장 물건이 **물류에 입고**될 때마다 입고 수량을 입력해서 +발주한 제품이 다 들어왔는지, **미입고**(덜 들어옴)·**초과 입고**(더 들어옴)가 있는지 관리한다. + +## 1. 참고한 상용 프로그램 + +| 프로그램 | 가져온 것 | +|---|---| +| 이카운트 ERP | 입고(구매입력)를 **발주서를 불러와서** 처리(발주번호 + 품목코드가 기준), **발주 대비 미입고 현황**(거래처별·품목별) | +| Odoo | 한 발주를 **여러 번 나눠 입고**, 덜 들어온 잔량은 "나중에 받기" 또는 **"더 안 받음(종결)"** 선택, 초과 입고는 확인 후 허용 | + +## 2. 흐름과 상태 + +``` +발주(open) ──입고 일부──▶ 부분입고(partial) ──남은 것 다 입고──▶ 입고완료(done) + │ │ └─발주보다 많이──▶ 초과입고(over) + │ └─[잔량 종결]──▶ 종결(closed) ─[종결 풀기]─▶ 원래 상태 + └─[발주 취소](입고 기록 없을 때만)──▶ 취소(cancelled) +``` + +- 상태는 **저장하지 않고** 품목별 누적 입고로 계산한다(`store.order_status`, `store.line_status`) — 어긋날 수 없다. +- 품목 상태: 미입고 / 부분입고 / 입고완료 / 초과입고. 발주서는 하나라도 남으면 부분입고(초과가 섞여 있어도). +- **미입고 현황**(`/inout/pending`)은 종결·취소가 아닌 발주의 남은 수량만 — 제품별 합계, 발주별(입고 예정일 순, 지난 것 빨강), 초과 입고 목록. +- **초과 입고**: 입고 저장 때 발주를 넘는 품목이 있으면 저장하지 않고 확인 화면(409, 넣은 숫자 유지) → [초과 입고로 저장](`confirm_over=1`). + 판단은 DB 트랜잭션 안에서 발주서 행을 잠그고(`FOR UPDATE`) 누적 입고를 다시 읽어 한다 — 동시에 입고해도 확인을 건너뛰지 않음. + Enter 키는 숨은 기본 버튼(일반 저장)으로 가게 해 확인 없이 초과가 저장되지 않게 했다. +- 발주서 고치기: 입고된 품목은 **뺄 수 없다**(입고 기록이 사라지므로) — 수량은 바꿀 수 있다(입고보다 줄이면 초과로 보임). +- 입고 기록 지우기(입고 담당): 잘못 넣은 1건을 지우면 그만큼 다시 미입고. +- 발주번호: `PO-YYMMDD-NN`(발주일 기준 그날 순번, advisory lock 으로 동시 생성해도 겹치지 않음). + +## 3. 권한·담당자 + +| 누구 | 할 수 있는 것 | +|---|---| +| 모듈 권한 `inout` | 발주 목록·발주서·미입고 현황 조회 | +| **발주 담당**(옵션에서 지정) | 발주서 작성·고치기·잔량 종결/풀기·취소 | +| **입고 담당**(옵션에서 지정) | 입고 수량 입력·입고 기록 지우기 | +| ERP 관리자(`role=admin`) | 위 전부 + **옵션**(공장 목록·담당자) | + +담당자 후보 = ERP 관리자 화면에서 `inout` 권한을 받은 사용자. 권한이 빠졌는데 담당으로 남은 사람도 옵션에 보여서 뺄 수 있다. +담당은 `inout_roles(email, role)` — role `order`(발주)·`receive`(입고). + +## 4. 제품 = 코드표 단품 + +발주 품목은 `itemcode_db.single_items`(단품)에서만 고른다(세트 아님) — `itemcode.py SingleItemReader`(읽기 전용, `ITEMCODE_DB_URL` 재사용, +cupang·malaysia 와 같은 DSN). 화면에서 코드·이름으로 검색(`GET /inout/api/items?q=`, 코드 앞부분 일치 먼저 30개), +저장할 때 서버가 다시 코드표에 있는지 확인(`lookup`) — 없으면 "코드표 단품에 없는 제품". 발주 줄에는 코드·**발주 당시 이름** 사본을 둔다. +이미 발주서에 있던 코드는 나중에 코드표에서 빠져도 그대로 고칠 수 있다. 코드표 연결이 안 되면 새 제품을 넣는 저장만 막힌다(안내 문구). + +## 5. 화면 + +| 주소 | 내용 | +|---|---| +| `/inout/` | 발주 목록 — 상태(진행 중·완료·종결·취소·전체)·공장·발주일 기간·검색(발주번호·제품 코드·이름), 진행률 막대, 지연 표시 | +| `/inout/pending` | 미입고 현황 — 요약 숫자, 제품별 합계, 발주별, 초과 입고 | +| `/inout/orders/new`, `/{id}/edit` | 발주서 폼 — 공장·발주일·입고 예정일·메모, 제품 줄(검색 드롭다운·수량·줄 메모), 합계 | +| `/inout/orders/{id}` | 발주서 — 품목별 발주·입고·미입고·상태, **이번 입고** 칸(입고 담당) + [남은 수량 모두 채우기], 입고 기록, 종결·취소 | +| `/inout/settings` | 옵션(관리자) — 담당자(발주·입고 체크), 공장(이름·연락처·메모·순서·사용, 발주 기록 없을 때만 지우기) | + +화면은 서버 폼(POST → 303 + `?msg=` 안내). `static/inout.js` 는 입력 보조만(제품 검색 드롭다운 — `position: fixed` 로 body 에 붙여 +표 가로 스크롤에 잘리지 않음, 줄 추가·삭제·합계, 남은 수량 채우기, 버튼별 확인 `data-erp-confirm-btn`). +공용 `.erp-page` 가 content-box 라 넓은 표에서 48px 넘치므로 이 화면만 `.erp-page:has(> .io) { box-sizing: border-box }`. + +## 6. DB (`inout_db`, `scripts/sql/inout_db_init.sql`) + +| 표 | 내용 | +|---|---| +| `inout_factories` | 공장 — 이름(대소문자 무시 유일)·연락처·메모·사용·순서 | +| `inout_roles` | 담당자 — (email, role: order/receive) | +| `inout_orders` | 발주서 — 번호·공장·발주일·입고 예정일·메모·종결(시각·사람·사유)·취소 | +| `inout_order_lines` | 발주 품목 — 단품 코드·이름 사본·수량·줄 메모, 발주서 안에서 코드 유일 | +| `inout_receipts` | 입고 1건(한 번 들어온 것) — 입고일·메모·입력자 | +| `inout_receipt_lines` | 입고 품목별 수량 | + +앱 계정 `inout_app` 은 SELECT/INSERT/UPDATE/DELETE + 시퀀스만. 초기화는 멱등(DROP·TRUNCATE 없음). 백업 권장: 매일 `pg_dump inout_db`. + +## 7. 테스트 + +```bash +python -m pytest tests/test_inout_store.py tests/test_inout_web.py # DB 없이(등록·미설정 화면·상태·검사) +INOUT_TEST_DB_URL=postgresql://inout_app:@127.0.0.1:5432/inout_db \ + python -m pytest tests/test_inout_db.py tests/test_inout_web.py # 로컬 테스트 DB(초기화 SQL 적용, 앱 계정 — 권한도 확인) +``` + +DB 테스트: 분할 입고·완료, 초과 확인, 미입고·종결·풀기·취소, 고치기(입고 품목 보호), 입고 지우기, 동시 발주번호, 담당자·공장. +화면 흐름 테스트: 옵션 → 발주 담당 발주(코드표 아닌 제품 거부) → 입고 담당 분할·초과 확인 → 미입고 현황 → 종결, 권한별 403. diff --git a/docs/PROJECT_OVERVIEW.md b/docs/PROJECT_OVERVIEW.md index 8234110..3ced7aa 100644 --- a/docs/PROJECT_OVERVIEW.md +++ b/docs/PROJECT_OVERVIEW.md @@ -21,6 +21,7 @@ | 쿠팡 밀크런 | 쿠팡 출고 일정 관리 (`app/modules/cupang/`) — 월간 달력 / 출고 묶음(헤더+라인) / 상자 입수량 자동계산 / 로켓 매출 관리 / 엑셀 내보내기. 상품은 `itemcode_db` 읽기 전용 참조 | | 휴가 (준비중) | 연차/반차/특별휴가 신청·잔여일수 관리 | | 말레이시아 재고 | 말레이시아 창고 재고관리 (`app/modules/malaysia/`) — 낱개 입출고/조정, 세트 BOM, 일일 재고조사(세트 분해 자동 반영), 현재고 현황. 상품명은 `itemcode_db` 읽기 전용 참조 | +| 입출고 관리 | 본사 → 공장 제품 제작 발주, 물류 입고(여러 번 나눠), 발주 대비 미입고·초과 입고 관리 (`app/modules/inout/`, `inout_db`) — 발주 담당·입고 담당·공장은 모듈 옵션에서 지정, 제품은 `itemcode_db` 단품 읽기 전용. `docs/INOUT_MODULE.md` | | 긴급 공지 | 수퍼관리자가 정한 시각에 전체/고른 사람의 ERP 화면 정가운데에 띄우는 공지(`app/modules/notice/`, project_db 024) — [확인] 전까지 다시 뜸, 확인 현황. `docs/NOTICE_MODULE.md` | | 실적 | 쇼핑몰 통합 매출 (`app/modules/performance/`) — 쇼핑몰별 어댑터로 수집 → `performance_db` 저장 → 일자×쇼핑몰 표·KPI·월/연 누적·그래프. 수수료율 이력, API 인증정보는 설정 화면 입력 + AES-256-GCM 암호화 저장. 1단계는 모의 데이터·구조까지(실제 API 는 쇼핑몰별로 순차 연동). `docs/PERFORMANCE_MODULE.md` | @@ -36,6 +37,7 @@ | `expense` / `vacation` / `cupang` / `malaysia` / `performance` | 접근 | 내부 모듈 진입 (`performance` 설정 화면·API 는 추가로 `admin` 필요) | | `expense_approver` | 결재 | 개인경비 승인/반려/정산 | | `asset` | 접근 | 자산관리 조회·등록·수정·배정·반납·보고서 | +| `inout` | 접근 | 입출고 관리 조회. 발주·입고 입력은 모듈 옵션의 발주 담당·입고 담당(ERP 관리자는 둘 다 + 옵션) | | `vacation_approver` | 결재 | 휴가 승인/반려 (모듈 미개발) | `admin` 역할은 모든 권한 자동 부여. 신규 사용자는 관리자 페이지(`/admin`)에서 이메일만으로 등록 가능. diff --git a/scripts/sql/inout_db_init.sql b/scripts/sql/inout_db_init.sql new file mode 100644 index 0000000..c7b6907 --- /dev/null +++ b/scripts/sql/inout_db_init.sql @@ -0,0 +1,152 @@ +-- ===================================================================== +-- inout_db 초기화 스크립트 (PostgreSQL) — 입출고 관리 모듈(2026-10-16) +-- ===================================================================== +-- 본사 → 공장 제품 제작 발주, 공장 → 물류 입고(여러 번 나눠 입고) 기록, 발주 대비 미입고·초과 관리. +-- 멱등(idempotent): 여러 번 실행해도 안전. 기존 데이터를 삭제하지 않는다. DROP/TRUNCATE 없음. +-- +-- 실행 방법 (운영 PostgreSQL 컨테이너명: postgres-db, 백업 먼저): +-- +-- 1) DB / 역할 / 테이블 생성 (superuser 로 1회) +-- read -s -p "inout_app password: " APP_PWD; echo +-- docker exec -i postgres-db psql -U postgres -v app_password="$APP_PWD" < scripts/sql/inout_db_init.sql +-- +-- 2) main-app .env 에 연결 정보 등록 +-- INOUT_DB_URL=postgresql://inout_app:@postgres-db:5432/inout_db +-- +-- 3) main-app 재기동 +-- cd /opt/www/main && docker compose up -d --build web +-- +-- 제품(단품)은 itemcode_db.single_items 를 읽기 전용으로 고른다(ITEMCODE_DB_URL 재사용) — 여기엔 코드·이름 사본만 둔다. +-- ===================================================================== + +\set ON_ERROR_STOP on + +SELECT 'CREATE DATABASE inout_db ENCODING ''UTF8'' TEMPLATE template0' +WHERE NOT EXISTS (SELECT 1 FROM pg_database WHERE datname = 'inout_db') +\gexec + +SELECT 'CREATE ROLE inout_app LOGIN PASSWORD ' || quote_literal(:'app_password') +WHERE NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'inout_app') +\gexec + +SELECT 'ALTER ROLE inout_app WITH LOGIN PASSWORD ' || quote_literal(:'app_password') +\gexec + +GRANT CONNECT ON DATABASE inout_db TO inout_app; + +\connect inout_db + +CREATE OR REPLACE FUNCTION inout_set_updated_at() RETURNS trigger AS $$ +BEGIN + NEW.updated_at := now(); + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +-- ════════════════════════════════════════════════════════════ +-- 1) 공장(발주처) — 옵션에서 추가·수정, 쓰지 않으면 숨김(발주 기록이 있으면 지우지 않는다) +-- ════════════════════════════════════════════════════════════ +CREATE TABLE IF NOT EXISTS inout_factories ( + id SERIAL PRIMARY KEY, + name TEXT NOT NULL CHECK (char_length(name) BETWEEN 1 AND 100), + contact TEXT NOT NULL DEFAULT '', -- 담당자·연락처(자유 글) + memo TEXT NOT NULL DEFAULT '', + is_active BOOLEAN NOT NULL DEFAULT TRUE, + sort_order INTEGER NOT NULL DEFAULT 0, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now() +); +CREATE UNIQUE INDEX IF NOT EXISTS uq_inout_factories_name ON inout_factories (lower(name)); +DROP TRIGGER IF EXISTS trg_inout_factories_updated ON inout_factories; +CREATE TRIGGER trg_inout_factories_updated BEFORE UPDATE ON inout_factories + FOR EACH ROW EXECUTE FUNCTION inout_set_updated_at(); +COMMENT ON TABLE inout_factories IS '입출고 — 공장(발주처) 목록'; + +-- ════════════════════════════════════════════════════════════ +-- 2) 담당자 — 옵션에서 지정. order = 발주 담당(발주서 작성·수정·종결), receive = 입고 담당(입고 수량 입력) +-- ERP 관리자는 지정 없이도 둘 다 할 수 있다(앱에서 판단). +-- ════════════════════════════════════════════════════════════ +CREATE TABLE IF NOT EXISTS inout_roles ( + email TEXT NOT NULL, + role TEXT NOT NULL CHECK (role IN ('order', 'receive')), + created_by TEXT NOT NULL DEFAULT '', + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + PRIMARY KEY (email, role) +); +COMMENT ON TABLE inout_roles IS '입출고 — 발주 담당(order)·입고 담당(receive)'; + +-- ════════════════════════════════════════════════════════════ +-- 3) 발주서(헤더) — 상태는 줄의 입고 합계로 앱이 계산(closed_at = 잔량 종결, cancelled_at = 취소) +-- ════════════════════════════════════════════════════════════ +CREATE TABLE IF NOT EXISTS inout_orders ( + id BIGSERIAL PRIMARY KEY, + order_no TEXT NOT NULL UNIQUE, -- PO-YYMMDD-NN (발주일 기준 순번) + factory_id INTEGER NOT NULL REFERENCES inout_factories(id), + order_date DATE NOT NULL, + due_date DATE NULL, -- 입고 예정일(납기) + memo TEXT NOT NULL DEFAULT '', + closed_at TIMESTAMPTZ NULL, -- 종결: 남은 미입고를 더 기다리지 않음 + closed_by TEXT NOT NULL DEFAULT '', + close_reason TEXT NOT NULL DEFAULT '', + cancelled_at TIMESTAMPTZ NULL, -- 취소(입고 기록이 없을 때만) + cancelled_by TEXT NOT NULL DEFAULT '', + created_by TEXT NOT NULL DEFAULT '', + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_by TEXT NOT NULL DEFAULT '', + updated_at TIMESTAMPTZ NOT NULL DEFAULT now() +); +CREATE INDEX IF NOT EXISTS idx_inout_orders_date ON inout_orders (order_date DESC, id DESC); +CREATE INDEX IF NOT EXISTS idx_inout_orders_factory ON inout_orders (factory_id); +DROP TRIGGER IF EXISTS trg_inout_orders_updated ON inout_orders; +CREATE TRIGGER trg_inout_orders_updated BEFORE UPDATE ON inout_orders + FOR EACH ROW EXECUTE FUNCTION inout_set_updated_at(); +COMMENT ON TABLE inout_orders IS '입출고 — 공장 제품 제작 발주서'; + +-- 발주 품목 — 제품은 itemcode_db.single_items(단품)의 코드·이름 사본(발주 당시 이름) +CREATE TABLE IF NOT EXISTS inout_order_lines ( + id BIGSERIAL PRIMARY KEY, + order_id BIGINT NOT NULL REFERENCES inout_orders(id) ON DELETE CASCADE, + line_no INTEGER NOT NULL, + item_code TEXT NOT NULL CHECK (char_length(item_code) BETWEEN 1 AND 64), + item_name TEXT NOT NULL DEFAULT '', + qty INTEGER NOT NULL CHECK (qty > 0), + memo TEXT NOT NULL DEFAULT '', + UNIQUE (order_id, item_code) +); +CREATE INDEX IF NOT EXISTS idx_inout_order_lines_item ON inout_order_lines (item_code); +COMMENT ON TABLE inout_order_lines IS '입출고 — 발주 품목(단품 코드·발주 수량)'; + +-- ════════════════════════════════════════════════════════════ +-- 4) 입고 — 한 번 들어온 것(날짜) = 입고 1건, 그 안에 품목별 수량. 한 발주에 여러 번 나눠 입고 가능. +-- ════════════════════════════════════════════════════════════ +CREATE TABLE IF NOT EXISTS inout_receipts ( + id BIGSERIAL PRIMARY KEY, + order_id BIGINT NOT NULL REFERENCES inout_orders(id) ON DELETE CASCADE, + receipt_date DATE NOT NULL, + memo TEXT NOT NULL DEFAULT '', + created_by TEXT NOT NULL DEFAULT '', + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); +CREATE INDEX IF NOT EXISTS idx_inout_receipts_order ON inout_receipts (order_id, receipt_date); + +CREATE TABLE IF NOT EXISTS inout_receipt_lines ( + id BIGSERIAL PRIMARY KEY, + receipt_id BIGINT NOT NULL REFERENCES inout_receipts(id) ON DELETE CASCADE, + order_line_id BIGINT NOT NULL REFERENCES inout_order_lines(id) ON DELETE CASCADE, + qty INTEGER NOT NULL CHECK (qty > 0), + UNIQUE (receipt_id, order_line_id) +); +CREATE INDEX IF NOT EXISTS idx_inout_receipt_lines_line ON inout_receipt_lines (order_line_id); +COMMENT ON TABLE inout_receipts IS '입출고 — 물류 입고(한 번 들어온 것)'; +COMMENT ON TABLE inout_receipt_lines IS '입출고 — 입고 품목별 수량'; + +-- ════════════════════════════════════════════════════════════ +-- 권한 — 앱 계정은 읽기·쓰기만(스키마 변경 없음) +-- ════════════════════════════════════════════════════════════ +GRANT USAGE ON SCHEMA public TO inout_app; +GRANT SELECT, INSERT, UPDATE, DELETE ON + inout_factories, inout_roles, inout_orders, inout_order_lines, inout_receipts, inout_receipt_lines + TO inout_app; +GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO inout_app; + +SELECT 'inout_db ready' AS status; diff --git a/tests/test_inout_db.py b/tests/test_inout_db.py new file mode 100644 index 0000000..2131ee3 --- /dev/null +++ b/tests/test_inout_db.py @@ -0,0 +1,166 @@ +"""입출고 저장소 — 실제 PostgreSQL(로컬 테스트 DB 전용, INOUT_TEST_DB_URL 이 localhost 일 때만). + + INOUT_TEST_DB_URL=postgresql://inout_app:@127.0.0.1:5432/inout_db python -m pytest tests/test_inout_db.py +scripts/sql/inout_db_init.sql 을 적용한 DB 에 앱 계정(inout_app)으로 붙는다 — 권한(GRANT)도 함께 확인된다. +가상의 공장·발주만 만든다(이름에 무작위 꼬리표). +""" +import os +import threading +import unittest +import uuid +from datetime import date +from urllib.parse import urlparse + +DSN = os.getenv("INOUT_TEST_DB_URL", "") +ENABLED = bool(DSN) and urlparse(DSN).hostname in ("localhost", "127.0.0.1") + + +@unittest.skipUnless(ENABLED, "INOUT_TEST_DB_URL(localhost) not set") +class InoutDbTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + from app.modules.inout.db import InoutDBStore + + cls.st = InoutDBStore(DSN) + cls.tag = uuid.uuid4().hex[:6] + cls.fid = cls.st.save_factory(factory_id=None, name=f"테스트공장-{cls.tag}", contact="김공장 010") + + @classmethod + def tearDownClass(cls): + cls.st.close() + + def order(self, lines, **over): + from app.modules.inout import store + + data = store.validate_order(factory_id=over.get("factory_id", self.fid), order_date=over.get("order_date", "2026-10-16"), + due_date=over.get("due_date", "2026-10-30"), memo="", + codes=[c for c, _q in lines], quantities=[str(q) for _c, q in lines]) + names = {c: f"{c} 이름" for c, _q in lines} + return self.st.create_order(data, names, by="Boss@Test.local") + + def line_ids(self, oid): + return {ln["item_code"]: ln["id"] for ln in self.st.get_order(oid)["lines"]} + + def test_partial_receipts_until_done(self): + o = self.order([("MT-A", 100), ("MT-B", 50)]) + self.assertRegex(o["order_no"], r"^PO-261016-\d{2}$") + ids = self.line_ids(o["id"]) + self.assertEqual(self.st.get_order(o["id"])["status"], "open") + self.st.add_receipt(o["id"], {ids["MT-A"]: "60"}, receipt_date="2026-10-20", memo="1차", confirm_over=False, by="w@x") + got = self.st.get_order(o["id"]) + self.assertEqual((got["status"], got["summary"]["received"], got["summary"]["remaining"]), ("partial", 60, 90)) + a = next(x for x in got["lines"] if x["item_code"] == "MT-A") + self.assertEqual((a["received"], a["remaining"], a["status"]), (60, 40, "partial")) + self.st.add_receipt(o["id"], {ids["MT-A"]: "40", ids["MT-B"]: "50"}, receipt_date="2026-10-22", memo="", + confirm_over=False, by="w@x") + got = self.st.get_order(o["id"]) + self.assertEqual((got["status"], got["summary"]["remaining"], len(got["receipts"])), ("done", 0, 2)) + self.assertEqual([r["total"] for r in got["receipts"]], [60, 90]) + # 진행 중 목록에서 빠지고 완료 목록에 + self.assertNotIn(o["id"], [x["id"] for x in self.st.list_orders(status="active", factory_id=self.fid)]) + self.assertIn(o["id"], [x["id"] for x in self.st.list_orders(status="done", factory_id=self.fid)]) + + def test_over_receipt_needs_confirm(self): + from app.modules.inout.db import OverReceipt + + o = self.order([("MT-C", 10)]) + ids = self.line_ids(o["id"]) + with self.assertRaises(OverReceipt) as ctx: + self.st.add_receipt(o["id"], {ids["MT-C"]: "12"}, receipt_date="2026-10-20", memo="", confirm_over=False, by="w@x") + self.assertEqual(ctx.exception.over[0]["over"], 2) + self.assertEqual(self.st.get_order(o["id"])["summary"]["received"], 0) # 확인 전엔 아무것도 저장 안 함 + self.st.add_receipt(o["id"], {ids["MT-C"]: "12"}, receipt_date="2026-10-20", memo="", confirm_over=True, by="w@x") + got = self.st.get_order(o["id"]) + self.assertEqual((got["status"], got["lines"][0]["over"]), ("over", 2)) + self.assertEqual([r["item_code"] for r in self.st.outstanding(factory_id=self.fid)["over"] + if r["order_id"] == o["id"]], ["MT-C"]) + + def test_outstanding_close_reopen_cancel(self): + o = self.order([("MT-D", 30), ("MT-E", 5)]) + ids = self.line_ids(o["id"]) + self.st.add_receipt(o["id"], {ids["MT-D"]: "10"}, receipt_date="2026-10-20", memo="", confirm_over=False, by="w@x") + pend = [r for r in self.st.outstanding(factory_id=self.fid)["pending"] if r["order_id"] == o["id"]] + self.assertEqual({r["item_code"]: r["remaining"] for r in pend}, {"MT-D": 20, "MT-E": 5}) + self.assertTrue(self.st.outstanding(q="MT-E")["pending"]) + self.st.set_closed(o["id"], closed=True, reason="공장 단종", by="boss@x") + self.assertEqual(self.st.get_order(o["id"])["status"], "closed") + self.assertFalse([r for r in self.st.outstanding(factory_id=self.fid)["pending"] if r["order_id"] == o["id"]]) + with self.assertRaisesRegex(ValueError, "종결"): + self.st.add_receipt(o["id"], {ids["MT-E"]: "1"}, receipt_date="2026-10-21", memo="", confirm_over=False, by="w@x") + self.st.set_closed(o["id"], closed=False, by="boss@x") + self.assertEqual(self.st.get_order(o["id"])["status"], "partial") + with self.assertRaisesRegex(ValueError, "입고 기록이 있는"): + self.st.cancel_order(o["id"], by="boss@x") + o2 = self.order([("MT-F", 1)]) + self.st.cancel_order(o2["id"], by="boss@x") + self.assertEqual(self.st.get_order(o2["id"])["status"], "cancelled") + self.assertIn(o2["id"], [x["id"] for x in self.st.list_orders(status="closed", factory_id=self.fid)]) + + def test_update_order_keeps_received_lines(self): + from app.modules.inout import store + + o = self.order([("MT-G", 10), ("MT-H", 10)]) + ids = self.line_ids(o["id"]) + self.st.add_receipt(o["id"], {ids["MT-G"]: "4"}, receipt_date="2026-10-20", memo="", confirm_over=False, by="w@x") + drop_g = store.validate_order(factory_id=self.fid, order_date="2026-10-16", due_date="", memo="", + codes=["MT-H"], quantities=["10"]) + with self.assertRaisesRegex(ValueError, "MT-G"): + self.st.update_order(o["id"], drop_g, {}, by="boss@x") + change = store.validate_order(factory_id=self.fid, order_date="2026-10-16", due_date="2026-11-05", memo="수정", + codes=["MT-G", "MT-I"], quantities=["3", "7"]) + self.st.update_order(o["id"], change, {"MT-I": "새 제품"}, by="boss@x") + got = self.st.get_order(o["id"]) + self.assertEqual([(x["item_code"], x["qty"], x["received"]) for x in got["lines"]], [("MT-G", 3, 4), ("MT-I", 7, 0)]) + self.assertEqual(got["lines"][0]["status"], "over") # 수량을 입고보다 줄이면 초과로 보임 + self.assertEqual((got["memo"], str(got["due_date"])), ("수정", "2026-11-05")) + + def test_delete_receipt_restores_remaining(self): + o = self.order([("MT-J", 10)]) + ids = self.line_ids(o["id"]) + r = self.st.add_receipt(o["id"], {ids["MT-J"]: "10"}, receipt_date="2026-10-20", memo="", confirm_over=False, by="w@x") + self.st.delete_receipt(o["id"], r["id"], by="w@x") + got = self.st.get_order(o["id"]) + self.assertEqual((got["status"], got["summary"]["remaining"], got["receipts"]), ("open", 10, [])) + with self.assertRaises(ValueError): + self.st.delete_receipt(o["id"], r["id"], by="w@x") + + def test_order_numbers_per_day_and_concurrent(self): + nos = [] + lock = threading.Lock() + + def make(): + n = self.order([("MT-K", 1)], order_date="2026-03-03")["order_no"] + with lock: + nos.append(n) + + threads = [threading.Thread(target=make) for _ in range(5)] + for t in threads: + t.start() + for t in threads: + t.join() + self.assertEqual(len(set(nos)), 5) # 동시에 만들어도 번호 겹치지 않음 + self.assertTrue(all(n.startswith("PO-260303-") for n in nos)) + + def test_roles_and_factories(self): + self.st.set_role_members("order", ["Boss@Test.local", " a@x "], by="admin@x") + self.st.set_role_members("receive", ["w@x"], by="admin@x") + self.assertEqual(self.st.list_roles()["order"], ["a@x", "boss@test.local"]) + self.assertEqual(self.st.roles_of("BOSS@test.local"), {"order"}) + self.st.set_role_members("order", ["a@x"], by="admin@x") # 통째로 바꿈 + self.assertEqual(self.st.list_roles()["order"], ["a@x"]) + with self.assertRaisesRegex(ValueError, "같은 이름"): + self.st.save_factory(factory_id=None, name=f"테스트공장-{self.tag}".upper()) + with self.assertRaisesRegex(ValueError, "발주 기록"): + self.order([("MT-L", 1)]) + self.st.delete_factory(self.fid) + fid2 = self.st.save_factory(factory_id=None, name=f"빈공장-{self.tag}") + self.st.delete_factory(fid2) + self.assertNotIn(fid2, [f["id"] for f in self.st.list_factories(include_inactive=True)]) + off = self.st.save_factory(factory_id=None, name=f"숨김공장-{self.tag}", is_active=False) + self.assertNotIn(off, [f["id"] for f in self.st.list_factories()]) + with self.assertRaisesRegex(ValueError, "사용하지 않는 공장"): + self.order([("MT-M", 1)], factory_id=off) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_inout_store.py b/tests/test_inout_store.py new file mode 100644 index 0000000..78896c4 --- /dev/null +++ b/tests/test_inout_store.py @@ -0,0 +1,89 @@ +"""입출고 관리 — 상태 계산·입력 검사(순수 함수, DB 없음).""" +import unittest +from datetime import date + +from app.modules.inout import store as s + + +class StatusTests(unittest.TestCase): + def test_line_status(self): + self.assertEqual([s.line_status(10, r) for r in (0, 4, 10, 12)], ["none", "partial", "done", "over"]) + + def test_order_status(self): + L = lambda *pairs: [{"qty": q, "received": r} for q, r in pairs] # noqa: E731 + self.assertEqual(s.order_status(L((10, 0), (5, 0))), "open") + self.assertEqual(s.order_status(L((10, 10), (5, 0))), "partial") # 하나라도 남으면 부분입고 + self.assertEqual(s.order_status(L((10, 12), (5, 3))), "partial") # 초과가 있어도 남은 게 있으면 부분입고 + self.assertEqual(s.order_status(L((10, 10), (5, 5))), "done") + self.assertEqual(s.order_status(L((10, 11), (5, 5))), "over") + self.assertEqual(s.order_status(L((10, 3)), closed=True), "closed") + self.assertEqual(s.order_status(L((10, 3)), closed=True, cancelled=True), "cancelled") + self.assertEqual(s.order_status([]), "open") + + def test_summarize_never_negative(self): + out = s.summarize([{"qty": 10, "received": 12}, {"qty": 5, "received": 1}]) + self.assertEqual(out, {"ordered": 15, "received": 13, "remaining": 4, "over": 2, "pct": 87}) + self.assertEqual(s.summarize([{"qty": 1, "received": 5}])["pct"], 100) # 막대는 100% 에서 멈춤 + self.assertEqual(s.summarize([])["pct"], 0) + + def test_order_no(self): + self.assertEqual(s.order_no(date(2026, 10, 6), 3), "PO-261006-03") + self.assertEqual(s.order_no(date(2026, 10, 6), 123), "PO-261006-123") + + +class ValidateOrderTests(unittest.TestCase): + def v(self, **over): + args = dict(factory_id="1", order_date="2026-10-16", due_date="2026-10-30", memo=" 메모 ", + codes=["mt-a ", "", "MT-B"], quantities=["1,200", "", "5"], line_memos=["a", "", ""]) + args.update(over) + return s.validate_order(**args) + + def test_ok_normalizes(self): + d = self.v() + self.assertEqual(d["factory_id"], 1) + self.assertEqual(d["memo"], "메모") + self.assertEqual([(x["item_code"], x["qty"], x["memo"]) for x in d["lines"]], [("MT-A", 1200, "a"), ("MT-B", 5, "")]) + + def test_errors_listed_together(self): + with self.assertRaises(ValueError) as ctx: + self.v(factory_id="", due_date="2026-10-01", codes=["MT-A", "mt-a", ""], quantities=["0", "3", "7"]) + msg = str(ctx.exception) + for part in ("공장을 고르세요", "입고 예정일이 발주일보다 빠릅니다", "1 이상", "같은 제품이 두 줄", "3번째 줄: 제품을 고르세요"): + self.assertIn(part, msg) + + def test_empty_and_bad_values(self): + with self.assertRaisesRegex(ValueError, "한 줄 이상"): + self.v(codes=["", ""], quantities=["", ""]) + with self.assertRaisesRegex(ValueError, "정수"): + self.v(codes=["MT-A"], quantities=["1.5"]) + with self.assertRaisesRegex(ValueError, "너무 큽니다"): + self.v(codes=["MT-A"], quantities=[str(s.MAX_QTY + 1)]) + with self.assertRaisesRegex(ValueError, "발주일 형식"): + self.v(order_date="16/10/2026") + self.assertIsNone(self.v(due_date="")["due_date"]) + + +class ValidateReceiptTests(unittest.TestCase): + LINES = [{"id": 1, "item_code": "MT-A", "item_name": "가", "qty": 10, "received": 8}, + {"id": 2, "item_code": "MT-B", "item_name": "나", "qty": 5, "received": 0}] + + def test_partial_zero_and_over(self): + d = s.validate_receipt(self.LINES, {1: "3", 2: "0"}, receipt_date="2026-10-20", memo="") + self.assertEqual(d["items"], [{"order_line_id": 1, "qty": 3}]) # 0·빈칸은 이번에 안 들어온 것 + self.assertEqual(d["over"], [{"item_code": "MT-A", "item_name": "가", "ordered": 10, "after": 11, "over": 1}]) + d = s.validate_receipt(self.LINES, {1: "2", 2: ""}, receipt_date="2026-10-20", memo="") + self.assertEqual(d["over"], []) # 딱 맞으면 초과 아님 + + def test_errors(self): + with self.assertRaisesRegex(ValueError, "한 품목 이상"): + s.validate_receipt(self.LINES, {1: "", 2: "0"}, receipt_date="2026-10-20", memo="") + with self.assertRaisesRegex(ValueError, "없는 품목"): + s.validate_receipt(self.LINES, {99: "1"}, receipt_date="2026-10-20", memo="") + with self.assertRaisesRegex(ValueError, "입고일"): + s.validate_receipt(self.LINES, {1: "1"}, receipt_date="", memo="") + with self.assertRaisesRegex(ValueError, "0 이상"): # 입고는 0(이번에 안 옴)까지 허용 + s.validate_receipt(self.LINES, {1: "-1"}, receipt_date="2026-10-20", memo="") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_inout_web.py b/tests/test_inout_web.py new file mode 100644 index 0000000..5d527c5 --- /dev/null +++ b/tests/test_inout_web.py @@ -0,0 +1,185 @@ +"""입출고 관리 — 실제 앱(메뉴·권한·화면·폼)을 격리된 하위 프로세스에서 확인. + +1) 등록·미설정: 메뉴·관리자 권한 칩·"설정 필요" 화면(DB 없이 늘 실행) +2) 전체 흐름(INOUT_TEST_DB_URL 이 localhost 일 때만): 옵션(공장·담당자) → 발주 담당 발주서 작성(코드표 단품만) + → 입고 담당 분할 입고 → 초과 입고 확인 → 미입고 현황 → 잔량 종결, 그리고 권한(조회만·담당 아님 403). +코드표(itemcode_db)는 가짜 리더로 바꾼다. 운영 DSN·데이터는 쓰지 않는다. +""" +import os +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path +from urllib.parse import urlparse + +ROOT = Path(__file__).resolve().parents[1] +DSN = os.getenv("INOUT_TEST_DB_URL", "") +DB_ENABLED = bool(DSN) and urlparse(DSN).hostname in ("localhost", "127.0.0.1") + +PRELUDE = ''' +from unittest.mock import patch +from fastapi.testclient import TestClient +import app.main as main + +def U(email, role="user", inout=True): + return {"email": email, "name": email.split("@")[0], "role": role, "is_super_admin": False, + "modules": {"inout": inout}} + +who = {"u": None} +users = [] + +class Items: + enabled = True + reason = "" + NAMES = {"MT-A": "가 단품", "MT-B": "나 단품", "MT-C": "다 단품"} + def search(self, q, limit=30): + return [{"code": c, "name": n} for c, n in self.NAMES.items() if q.upper() in c or q in n] + def lookup(self, codes): + return {c: self.NAMES[c] for c in codes if c in self.NAMES} + +def run(body): + with patch.object(main, "get_current_user_record", side_effect=lambda r: who["u"]), \\ + patch.object(main, "get_session_user", side_effect=lambda r: who["u"]), \\ + patch.object(main.user_store, "get", side_effect=lambda e: who["u"]), \\ + patch.object(main.user_store, "list_all", side_effect=lambda: users): + client = TestClient(main.app) + body(client) +''' + + +def _run(code: str, extra_env: dict[str, str] | None = None) -> subprocess.CompletedProcess: + env = dict(os.environ) + for key in ("ASSET", "CAFE24", "CUPANG", "VACATION", "PROJECT", "DISPATCH", "PERFORMANCE", "MALAYSIA_STOCK", + "ITEMCODE", "EXPENSE", "INOUT"): + env[key + "_DB_URL"] = "" + env.update(SESSION_SECRET_KEY="local-inout-test-only", SESSION_COOKIE_SECURE="false", PERFORMANCE_AUTO_SYNC="false") + env.update(extra_env or {}) + with tempfile.TemporaryDirectory(prefix="inout-web-") as directory: + env["DATA_DIR"] = directory + return subprocess.run([sys.executable, "-c", PRELUDE + code], cwd=ROOT, env=env, capture_output=True, + text=True, encoding="utf-8", timeout=90) + + +class InoutWebTests(unittest.TestCase): + def test_registered_and_unconfigured(self): + res = _run(''' +from app.store import MODULE_KEYS +admin = U("admin@test.local", role="admin") +users.append(admin) +who["u"] = admin +def body(c): + assert "inout" in MODULE_KEYS + assert main.MODULE_LABELS["inout"] == "입출고 관리" + assert any(x["key"] == "inout" and x["active"] for x in main.build_erp_nav(admin, active="inout")) + assert "입출고 관리" in c.get("/admin").text # 관리자 화면 권한 칩 + r = c.get("/inout/") + assert r.status_code == 503 and "INOUT_DB_URL" in r.text, r.status_code # DB 미설정 = 설정 필요 안내 + assert c.get("/inout/health").json() == {"status": "not_configured"} + who["u"] = U("nobody@test.local", inout=False) + assert c.get("/inout/").status_code == 403 # 모듈 권한 없음 + print("OK") +run(body) +''') + self.assertEqual(res.returncode, 0, res.stdout + res.stderr) + self.assertIn("OK", res.stdout) + + @unittest.skipUnless(DB_ENABLED, "INOUT_TEST_DB_URL(localhost) not set") + def test_full_flow(self): + res = _run(''' +import re, uuid +from app.modules.inout.db import InoutDBStore +main.app.state.inout_store = InoutDBStore(__import__("os").environ["INOUT_TEST_DB_URL"]) +main.app.state.inout_items = Items() +tag = uuid.uuid4().hex[:6] +admin, buyer, wh, viewer = (U("admin-%s@t.local" % tag, role="admin"), U("buyer-%s@t.local" % tag), + U("wh-%s@t.local" % tag), U("viewer-%s@t.local" % tag)) +users.extend([admin, buyer, wh, viewer]) + +def body(c): + # ── 옵션: 공장·담당자(관리자만) ── + who["u"] = buyer + assert c.get("/inout/settings").status_code == 403 + who["u"] = admin + page = c.get("/inout/settings") + assert page.status_code == 200 and buyer["email"] in page.text and "발주 담당" in page.text + r = c.post("/inout/settings/factories", data={"name": "공장-" + tag, "contact": "김 010", "is_active": "1"}, + follow_redirects=False) + assert r.status_code == 303 and "msg=" in r.headers["location"] + fid = re.search(r'name="id" value="(\\d+)" />\\s*