From cc68d5be676e8c56c1144b77f5a6c36e59ca0b99 Mon Sep 17 00:00:00 2001 From: king Date: Wed, 21 Oct 2026 15:13:47 +0900 Subject: [PATCH] =?UTF-8?q?feat(inout):=20=EB=B0=95=EC=8A=A4=20=EC=9E=85?= =?UTF-8?q?=EC=88=98=C2=B7=ED=8C=8C=EB=A0=9B=ED=8A=B8=20=EA=B3=84=EC=82=B0?= =?UTF-8?q?=C2=B7=EC=83=81=ED=92=88=20=EA=B7=B8=EB=A3=B9=20=ED=83=AD=C2=B7?= =?UTF-8?q?=EB=8B=AC=EB=A0=A5=20=EB=8B=A4=EC=8B=9C=20=EA=B7=B8=EB=A6=AC?= =?UTF-8?q?=EA=B8=B0=20=EC=A4=84=EC=9E=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 옵션 상품 그룹을 별도 탭으로, 상품 정보 제목 행 가운데·굵게·110% - 상품 정보에 통 수량(박스)·뚜껑 수량(박스)(마이그레이션 007, 뚜껑 없으면 빈칸) - 새 발주서: 줄마다 통·뚜껑 박스 수와 공배수 힌트, 합계 박스 → 파렛트(30박스) 계산 (화면 계산만, 발주 메일은 그대로) - 메뉴를 옮겨도 달력은 sessionStorage 에서 바로 복원, 서버 값이 바뀔 때만 다시 그림 Co-Authored-By: Claude Opus 5.5 --- app/modules/inout/CLAUDE.md | 13 ++- app/modules/inout/db.py | 28 +++++- app/modules/inout/router.py | 10 ++- app/modules/inout/store.py | 33 ++++++- .../inout/templates/inout/_calendar.html | 12 +++ .../inout/templates/inout/_options_panel.html | 38 +++++--- app/modules/inout/templates/inout/index.html | 4 +- .../inout/templates/inout/order_detail.html | 4 +- .../inout/templates/inout/order_form.html | 24 +++-- .../inout/templates/inout/pending.html | 4 +- app/static/inout.css | 24 ++++- app/static/inout.js | 89 +++++++++++++++++-- docs/DEPLOYMENT.md | 11 +++ docs/INOUT_MODULE.md | 11 +++ scripts/sql/inout_db_007_box_qty.sql | 21 +++++ tests/test_inout_db.py | 34 +++++++ 16 files changed, 315 insertions(+), 45 deletions(-) create mode 100644 scripts/sql/inout_db_007_box_qty.sql diff --git a/app/modules/inout/CLAUDE.md b/app/modules/inout/CLAUDE.md index 16a0e9b..42da405 100644 --- a/app/modules/inout/CLAUDE.md +++ b/app/modules/inout/CLAUDE.md @@ -62,7 +62,7 @@ ## 상품 그룹·색상 (006, 2026-10-21) -- 옵션 → 상품 정보 위 **그룹** 표(`inout_product_groups`: 이름·은 함유량·색상·순서, `POST /inout/settings/groups`·`…/{id}/delete`). +- 옵션 **상품 그룹** 탭(2026-10-21 상품 정보 탭에서 분리) = 그룹 표(`inout_product_groups`: 이름·은 함유량·색상·순서, `POST /inout/settings/groups`·`…/{id}/delete`). 상품 줄 **그룹** 고르기 → 그 상품의 은 함유량·색상 = 그룹 값(자기 값 칸은 숨김·보존, 그룹 지우면 자기 값으로). 그룹 없는 상품은 상품마다. 계산은 `db._PRODUCT_SELECT_006`(silver_pct·color = 그룹 적용 값, own_* = 자기 값) 한 곳 — 목록·발주서 제품 고르기·발주 품목 사본이 같은 값. - 색상 = 색없음·오렌지·파랑·회색·아이보리색(`store.COLORS` 키 none·orange·blue·gray·ivory → 이름·칸 색), 화면은 색 사각형 + 이름(`_macros.swatch`). @@ -70,6 +70,15 @@ - 006 확인(`groups_ready`)은 연결을 열기 **전에** — 미적용이면 1분 기억(발주 저장 트랜잭션 안에서 두 번째 연결을 잡아 동시 발주에서 풀이 바닥났었다). - 옵션 → 담당자 = 아이콘(구글 프로필 사진, 없으면 기본 아이콘) + 이름, 아래 이메일. +## 박스 입수·파렛트 (007, 2026-10-21) + +- 옵션 → 상품 정보 **통 수량(박스)**·**뚜껑 수량(박스)** = 통·뚜껑이 한 박스에 몇 개(`inout_products.body_per_box`·`lid_per_box`, 1 이상 정수, 뚜껑 없으면 빈칸, + `store.validate_box_values`). 상품 정보 표 제목 행 = 가운데·굵게·13.2px(예전 12px × 110%). +- **새 발주서** 줄마다 "통·뚜껑 박스" 칸(`inout.js boxCell`) = 통 ⌈수량 ÷ 통 입수⌉박스 · 뚜껑 ⌈수량 ÷ 뚜껑 입수⌉박스, 힌트 = 통·뚜껑 입수의 **최소공배수**(둘 다 꽉 차는 수량 단위, + 뚜껑 없으면 통 입수)와 지금 수량에 가까운 그 배수(누르면 수량 칸에), 배수면 "✓ 꽉 찹니다". 합계 줄 = 통·뚜껑·전체 박스 → **파렛트 ⌈전체 박스 ÷ 30⌉**(`store.PALLET_BOXES`) + 마지막 파렛트 박스 수. +- 화면 계산만 — 발주 품목 사본·발주서 화면·**발주 메일에는 넣지 않음**(사용자 지정). 값은 지금 상품 정보(`_form_page` 의 `body_per_box`, `/api/items`). +- 007 확인 `db.boxes_ready`(groups_ready 와 같은 방식 — 연결 열기 전, 미적용 1분 기억). 그룹·색상 조회(`_PRODUCT_SELECT_006`)는 `p.*` 라 새 열이 따라온다. + ## 오른쪽 달력 (2026-10-21) - 입출고 **모든 화면** 2열(`.io-split` = 왼쪽 `section.io` | 오른쪽 `_calendar.html`, 1100px 미만은 한 열 300px). 스크롤해도 위에 붙음. @@ -78,6 +87,8 @@ - 프로젝트 달력 모양(일요일 시작·요일 줄 회색·오늘 검은 동그라미·토 파랑·일/공휴일 빨강 — 공휴일 표는 `project.store.holiday_name` 재사용). 공휴일 이름은 숫자 아래 한 줄(`.io-cal-hol`, 8.5px — 5글자까지 다 보임, 더 길면 … + 말풍선에 전체 이름). - 날짜 칸 = 발주(발주일, 파랑)·입고(입고일, 초록) 건수(취소된 발주 제외), 누르면 그날 목록 팝업 → 발주서. 달 이동은 새로고침 없이 `GET /inout/api/calendar?month=YYYY-MM`(`db.calendar`). +- **메뉴를 옮겨도 달력은 다시 그리지 않음**(2026-10-21) — 마지막 달력(달·API 응답 글·칸 HTML)을 sessionStorage `io_cal_v1` 에 두고 `_calendar.html` 인라인 스크립트가 그리기 전에 붙임, + `inout.js` 는 서버 값을 다시 받아 **글이 달라졌을 때만** 다시 그린다(보던 달도 유지). `CAL_KEY` 는 `initCalendar` 안에 — 바깥 const 면 위에서 먼저 부를 때 TDZ 로 복원이 조용히 꺼진다. ## 시각 / 날짜 diff --git a/app/modules/inout/db.py b/app/modules/inout/db.py index ee87061..79868b9 100644 --- a/app/modules/inout/db.py +++ b/app/modules/inout/db.py @@ -25,9 +25,9 @@ from . import store _SCAN_LIMIT = 20000 # 목록에서 상태 거르기 전에 읽는 발주서 상한 # 상품 정보 + 그룹(006) — 그룹 상품은 그룹의 은 함유량·색상, 그룹 없는 상품은 자기 값(own_*). +# p.* 다음에 같은 이름(silver_pct·color)을 다시 고르면 dict_row 는 뒤의 값(그룹 적용 값)을 쓴다. p.* 라 007 박스 입수 등 새 열도 따라온다. _PRODUCT_SELECT_006 = ( - "SELECT p.item_code, p.item_name, p.unit_price, p.weight_g, p.imported_at, p.updated_by, p.updated_at, " - "p.group_id, g.name AS group_name, p.silver_pct AS own_silver_pct, COALESCE(p.color, 'none') AS own_color, " + "SELECT p.*, g.name AS group_name, p.silver_pct AS own_silver_pct, COALESCE(p.color, 'none') AS own_color, " "CASE WHEN g.id IS NULL THEN p.silver_pct ELSE g.silver_pct END AS silver_pct, " "CASE WHEN g.id IS NULL THEN COALESCE(p.color, 'none') ELSE g.color END AS color " "FROM inout_products p LEFT JOIN inout_product_groups g ON g.id = p.group_id" @@ -607,7 +607,13 @@ class InoutDBStore: 006 이면 줄에 group_id·color(상품 자기 색상)도 — 그룹 상품의 은 함유량·색상은 그룹 값이 쓰인다.""" self._need_products() grouped = self.groups_ready() and any("group_id" in r for r in rows) + boxed = self.boxes_ready() and any("body_per_box" in r for r in rows) with self._pool.connection() as conn, conn.transaction(): + if boxed: # 007 — 통·뚜껑 박스 입수(그룹과 무관, 상품마다) + for r in rows: + if "body_per_box" in r: + conn.execute("UPDATE inout_products SET body_per_box=%s, lid_per_box=%s WHERE item_code=%s", + (r.get("body_per_box"), r.get("lid_per_box"), r["code"])) if grouped: known = {int(g["id"]) for g in conn.execute("SELECT id FROM inout_product_groups").fetchall()} for r in rows: @@ -670,7 +676,7 @@ class InoutDBStore: _PRODUCT_SELECT_006 + " WHERE p.item_code ILIKE %(q)s OR p.item_name ILIKE %(q)s " "ORDER BY (p.item_code ILIKE %(p)s) DESC, p.item_code LIMIT %(n)s", args).fetchall() return conn.execute( - "SELECT item_code, item_name, unit_price, weight_g, silver_pct FROM inout_products " + "SELECT * FROM inout_products " "WHERE item_code ILIKE %(q)s OR item_name ILIKE %(q)s " "ORDER BY (item_code ILIKE %(p)s) DESC, item_code LIMIT %(n)s", args).fetchall() @@ -708,6 +714,22 @@ class InoutDBStore: self._groups_checked = time.monotonic() return ok + def boxes_ready(self) -> bool: + """007 이 적용됐나(상품 body_per_box·lid_per_box). groups_ready 와 같이 — 적용됐으면 계속, 아직이면 1분 기억, 연결 열기 전에 부른다.""" + if getattr(self, "_boxes_ok", False): + return True + if time.monotonic() - getattr(self, "_boxes_checked", -1e9) < 60: + return False + if not self.products_ready(): + return False + with self._pool.connection() as conn: + ok = bool(conn.execute( + "SELECT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'inout_products' " + "AND column_name = 'lid_per_box') AS ok").fetchone()["ok"]) + self._boxes_ok = ok + self._boxes_checked = time.monotonic() + return ok + def _need_groups(self) -> None: if not self.groups_ready(): raise ValueError("DB 마이그레이션 inout_db 006(상품 그룹·색상)이 아직 적용되지 않았습니다.") diff --git a/app/modules/inout/router.py b/app/modules/inout/router.py index a983431..1695d49 100644 --- a/app/modules/inout/router.py +++ b/app/modules/inout/router.py @@ -259,10 +259,13 @@ def _form_page(request: Request, user: dict[str, Any], st: Any, *, order: dict[s # 단가 — 이미 있던 품목은 발주 당시 값(사본), 새 품목은 지금 상품 정보 값(004). 금액은 화면이 수량 × 단가로 계산. snap = {x["item_code"]: x.get("unit_price") for x in (order["lines"] if order else [])} catalog = st.catalog_lookup([ln["code"] for ln in lines if ln["code"] and ln["code"] not in snap]) + boxes = st.catalog_lookup([ln["code"] for ln in lines if ln["code"]]) if st.boxes_ready() else {} for ln in lines: price = snap[ln["code"]] if ln["code"] in snap else (catalog.get(ln["code"]) or {}).get("unit_price") ln["price"] = float(price) if price is not None else None ln["price_label"] = store.fmt_num(price) if price is not None else "" + bx = boxes.get(ln["code"]) or {} # 박스 입수(007) — 지금 상품 정보 값(발주 품목에 남기지 않음) + ln["body_per_box"], ln["lid_per_box"] = bx.get("body_per_box"), bx.get("lid_per_box") reader = _items(request) catalog_n = st.catalog_count() return _render(request, "inout/order_form.html", user, { @@ -270,6 +273,7 @@ def _form_page(request: Request, user: dict[str, Any], st: Any, *, order: dict[s "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) or catalog_n > 0, "from_catalog": catalog_n > 0, + "boxes_ready": st.boxes_ready(), "pallet_boxes": store.PALLET_BOXES, }, status_code=status_code) @@ -861,6 +865,7 @@ def _options_ctx(request: Request, st: Any) -> dict[str, Any]: pr["silver_g"] = store.silver_g(pr.get("weight_g"), pr.get("silver_pct")) return {"products": products, "excluded": st.list_excluded(), "products_ready": st.products_ready(), "groups": st.list_groups(), "groups_ready": st.groups_ready(), "colors": store.COLORS, + "boxes_ready": st.boxes_ready(), "fmt_num": store.fmt_num, "factories": st.list_factories(include_inactive=True), "roles": roles, "role_labels": store.ROLE_LABELS, "settings": st.get_settings(), "settings_ready": st.settings_ready(), @@ -1016,6 +1021,8 @@ def settings_products_save(request: Request, payload: dict[str, Any] = Body(...) code = str((r or {}).get("code") or "").strip().upper() try: row = {"code": code, **store.validate_product_values(r)} + if "body_per_box" in (r or {}): # 007 — 통·뚜껑 박스 입수(빈칸 = 없음) + row.update(store.validate_box_values(r)) if "group_id" in (r or {}): # 006 — 그룹(빈칸 = 그룹 없음)·상품 자기 색상 gid = str(r.get("group_id") or "").strip() if gid and not gid.isdigit(): @@ -1112,7 +1119,8 @@ def api_items(request: Request, q: str = "") -> JSONResponse: "price": float(r["unit_price"]) if r["unit_price"] is not None else None, "weight_g": store.fmt_num(r["weight_g"]) if r["weight_g"] is not None else "", "silver_pct": store.fmt_num(r["silver_pct"], 4) if r["silver_pct"] is not None else "", - "color": r.get("color") or "none"} for r in rows]}) + "color": r.get("color") or "none", + "body_per_box": r.get("body_per_box"), "lid_per_box": r.get("lid_per_box")} for r in rows]}) reader = _items(request) if reader is None or not reader.enabled: return JSONResponse({"items": [], "enabled": False, diff --git a/app/modules/inout/store.py b/app/modules/inout/store.py index 78cd9b2..de12d59 100644 --- a/app/modules/inout/store.py +++ b/app/modules/inout/store.py @@ -442,9 +442,38 @@ def validate_product_values(values: dict[str, Any]) -> dict[str, Decimal | None] def has_values(p: dict[str, Any]) -> bool: - """단가·무게·은 함유량(·그룹·색상, 006) 중 하나라도 넣었나 — 넣은 상품은 다시 불러와도 그대로 둔다.""" + """단가·무게·은 함유량(·그룹·색상 006·박스 입수 007) 중 하나라도 넣었나 — 넣은 상품은 다시 불러와도 그대로 둔다.""" return (any(p.get(k) is not None for k in PRODUCT_LIMITS) or p.get("group_id") is not None - or (p.get("color") or "none") != "none") + or (p.get("color") or "none") != "none" or any(p.get(k) is not None for k in BOX_FIELDS)) + + +# ════════════════════════════════════════════════════════════ +# 박스 입수(2026-10-21, 마이그레이션 007) — 통·뚜껑이 한 박스에 몇 개. 뚜껑이 없는 상품은 빈칸. +# 새 발주서 화면이 수량 → 통·뚜껑 박스 수(올림)·전체 파렛트(1파렛트 = PALLET_BOXES 박스, 올림)를 계산한다(메일엔 안 넣음). +# ════════════════════════════════════════════════════════════ +BOX_FIELDS = {"body_per_box": "통 수량(박스)", "lid_per_box": "뚜껑 수량(박스)"} +MAX_PER_BOX = 1_000_000 +PALLET_BOXES = 30 + + +def parse_per_box(raw: Any, *, key: str) -> int | None: + """박스 입수 칸 하나 — 빈칸은 None(없음·미입력), 1 이상 정수(쉼표 허용).""" + label = BOX_FIELDS[key] + s = str(raw if raw is not None else "").replace(",", "").strip() + if not s: + return None + if not s.isdigit(): + raise ValueError(f"{label}은(는) 1 이상 정수로 입력하세요.") + n = int(s) + if n < 1: + raise ValueError(f"{label}은(는) 1 이상이어야 합니다(뚜껑이 없으면 빈칸).") + if n > MAX_PER_BOX: + raise ValueError(f"{label}이(가) 너무 큽니다.") + return n + + +def validate_box_values(values: dict[str, Any]) -> dict[str, int | None]: + return {k: parse_per_box(values.get(k), key=k) for k in BOX_FIELDS} # ════════════════════════════════════════════════════════════ diff --git a/app/modules/inout/templates/inout/_calendar.html b/app/modules/inout/templates/inout/_calendar.html index f4fdda6..95495aa 100644 --- a/app/modules/inout/templates/inout/_calendar.html +++ b/app/modules/inout/templates/inout/_calendar.html @@ -16,5 +16,17 @@
+ {# 화면을 옮겨도 달력이 다시 그려지지 않게 — 마지막 달력(sessionStorage, inout.js 가 저장)을 그리기 전에 바로 붙인다. + inout.js 는 서버 값을 다시 받아 바뀐 게 있을 때만 다시 그린다. #} +

n발주 n입고 · 날짜를 누르면 목록

diff --git a/app/modules/inout/templates/inout/_options_panel.html b/app/modules/inout/templates/inout/_options_panel.html index 4f493fb..725bc40 100644 --- a/app/modules/inout/templates/inout/_options_panel.html +++ b/app/modules/inout/templates/inout/_options_panel.html @@ -4,6 +4,7 @@
+
@@ -85,20 +86,16 @@ -