diff --git a/app/modules/dispatch/CLAUDE.md b/app/modules/dispatch/CLAUDE.md index e444c48..c7696e0 100644 --- a/app/modules/dispatch/CLAUDE.md +++ b/app/modules/dispatch/CLAUDE.md @@ -10,5 +10,5 @@ - 작업 상태 토글(`dispatch_logs` 기록). - 받는 사람 이름/전화/주소는 상자 단위로 저장(작업 카드 표시 + 출고 엑셀 생성용) — **개인정보**, 로그·외부 전송 주의. - 배치 다운로드 zip 에 업로드 원본 + 취합 출고 엑셀(`YYYY.MM.DD(Ddd)_tictoc|shopee.xlsx`) 포함. -- 기간별 발송 수량 엑셀(`/dispatch/period-export`, **수퍼 관리자 전용**): 날짜별·아이템별 수량(`_N` 배수 반영, 콤보 미분해) + 아이템×날짜 요약 시트. +- 기간별 발송 수량 엑셀(`/dispatch/period-export`, **수퍼 관리자 전용**): 날짜별·아이템별 수량(`_N` 배수 반영, 세트는 BOM 으로 낱개 분해) + 아이템×날짜 요약 시트. - 엑셀은 openpyxl 파싱/생성. diff --git a/app/modules/dispatch/export.py b/app/modules/dispatch/export.py index af38943..8e48edb 100644 --- a/app/modules/dispatch/export.py +++ b/app/modules/dispatch/export.py @@ -247,18 +247,39 @@ def stock_filename(dispatch_date: str) -> str: # ── 기간별 발송 수량 엑셀(수퍼 관리자) ── +def missing_set_boms( + rows: list[dict[str, Any]], set_bom: dict[str, list[dict[str, Any]]] +) -> list[str]: + """세트(MY-)인데 BOM 이 없어 낱개로 풀 수 없는 코드 목록(정렬).""" + return sorted({ + b for b in (split_sku(r.get("seller_sku", ""))[0].strip().upper() for r in rows) + if b.startswith(_SET_PREFIX) and b not in set_bom + }) + + def aggregate_shipped( - rows: list[dict[str, Any]], name_map: dict[str, str] | None = None + rows: list[dict[str, Any]], + name_map: dict[str, str] | None = None, + set_bom: dict[str, list[dict[str, Any]]] | None = None, ) -> tuple[list[str], dict[str, str], dict[tuple[str, str], int]]: """날짜·SKU별 합산 행 → (날짜목록, {코드: 상품명}, {(날짜, 코드): 수량}). seller_sku 의 _N 접미사는 배수로 곱해 실제 아이템코드로 합친다 - (예: MT-0320_3 × 2 → MT-0320 6개). 콤보는 분해하지 않고 발송된 그대로 센다. + (예: MT-0320_3 × 2 → MT-0320 6개). 세트(set_bom 에 있는 코드)는 구성 낱개로 + 풀어 (수량 × 구성수량) 을 낱개 코드에 더한다. """ name_map = name_map or {} + set_bom = set_bom or {} dates: set[str] = set() names: dict[str, str] = {} qty: dict[tuple[str, str], int] = {} + + def _add(d: str, code: str, n: int, fallback: str) -> None: + key = (d, code) + qty[key] = qty.get(key, 0) + n + if not names.get(code): + names[code] = resolve_product_name(code, name_map, fallback=fallback) + for r in rows: base, mult = split_sku(r.get("seller_sku", "")) code = base.strip().upper() @@ -269,12 +290,15 @@ def aggregate_shipped( continue d = r.get("dispatch_date", "") or "" dates.add(d) - key = (d, code) - qty[key] = qty.get(key, 0) + pieces - if not names.get(code): - names[code] = resolve_product_name( - code, name_map, fallback=r.get("product_name", "") or "" - ) + comps = set_bom.get(code) + if comps: # 세트 → 낱개 분해 + for c in comps: + cc = str(c.get("component_code", "")).strip().upper() + n = pieces * int(c.get("component_qty", 0) or 0) + if cc and n > 0: + _add(d, cc, n, "") + else: + _add(d, code, pieces, r.get("product_name", "") or "") return sorted(dates), names, qty @@ -284,8 +308,9 @@ def build_period_xlsx( date_from: str, date_to: str, name_map: dict[str, str] | None = None, + set_bom: dict[str, list[dict[str, Any]]] | None = None, ) -> bytes: - """기간별 발송 수량 xlsx. 시트 2개. + """기간별 발송 수량 xlsx(세트는 낱개로 풀어 합산). 시트 2개. - 「날짜별」: 발송 날짜 / 아이템 코드 / 상품이름 / 수량 (날짜·코드 오름차순, 맨 끝 합계) - 「아이템별 요약」: 아이템 코드 / 상품이름 / 날짜1..N / 합계 (맨 끝 날짜별 합계 행) @@ -294,7 +319,7 @@ def build_period_xlsx( from openpyxl.styles import Alignment, Font, PatternFill from openpyxl.utils import get_column_letter - dates, names, qty = aggregate_shipped(rows, name_map) + dates, names, qty = aggregate_shipped(rows, name_map, set_bom) codes = sorted(names) head_fill = PatternFill("solid", fgColor="E2E8F0") diff --git a/app/modules/dispatch/router.py b/app/modules/dispatch/router.py index 1ef67f7..e5c6659 100644 --- a/app/modules/dispatch/router.py +++ b/app/modules/dispatch/router.py @@ -489,7 +489,7 @@ def period_export( ) -> Response: """기간(양끝 포함) 날짜별·아이템별 발송 수량 xlsx — 슈퍼 관리자 전용. - seller_sku 의 _N 배수는 반영, 콤보는 분해하지 않고 발송된 그대로 센다. + seller_sku 의 _N 배수 반영, 세트(MY-)는 itemcode_db BOM 으로 낱개로 풀어 합산. """ if not bool(user.get("is_super_admin")): raise HTTPException(status_code=403, detail="기간별 발송 수량은 슈퍼 관리자만 받을 수 있습니다.") @@ -510,8 +510,24 @@ def period_export( if not rows: raise HTTPException(status_code=404, detail=f"{f} ~ {t} 기간의 발송 데이터가 없습니다.") + # 세트 BOM 이 없으면 낱개로 못 푼 채 파일이 만들어진다 — 조용히 틀리지 말고 알린다. + set_bom, _sab = _itemcode_bom_and_sabangnet(request) + missing_sets = export.missing_set_boms(rows, set_bom) + if missing_sets: + reader = getattr(request.app.state, "malaysia_itemcode", None) + hint = getattr(reader, "last_error", "") or getattr(reader, "reason", "") + detail = ( + "세트 BOM 을 찾지 못해 낱개로 풀 수 없습니다: " + + ", ".join(missing_sets) + + ". itemcode_db 의 set_components 에 해당 세트 BOM 이 등록돼 있는지 확인하세요." + ) + if hint: + detail += f" (itemcode 리더 오류: {hint})" + raise HTTPException(status_code=422, detail=detail) + xlsx_bytes = export.build_period_xlsx( - rows=rows, date_from=f, date_to=t, name_map=_itemcode_name_map(request) + rows=rows, date_from=f, date_to=t, + name_map=_itemcode_name_map(request), set_bom=set_bom, ) fname = export.period_filename(f, t) headers = { diff --git a/app/modules/dispatch/templates/dispatch/batches.html b/app/modules/dispatch/templates/dispatch/batches.html index 4665bbd..86a8274 100644 --- a/app/modules/dispatch/templates/dispatch/batches.html +++ b/app/modules/dispatch/templates/dispatch/batches.html @@ -149,8 +149,8 @@

기간별 발송 수량

기간 안 날짜별·아이템별 발송 수량을 엑셀로 받습니다. (수퍼 관리자 전용)

+ data-ko="기간 안 날짜별·아이템별 발송 수량을 엑셀로 받습니다. 세트는 낱개로 풀어 합산합니다. (수퍼 관리자 전용)" + data-en="Download shipped quantities per date and item for the period. Sets are split into singles. (Super admin only)">기간 안 날짜별·아이템별 발송 수량을 엑셀로 받습니다. 세트는 낱개로 풀어 합산합니다. (수퍼 관리자 전용)

~ diff --git a/app/modules/dispatch/tests/test_period_export.py b/app/modules/dispatch/tests/test_period_export.py index 6122d98..93d6775 100644 --- a/app/modules/dispatch/tests/test_period_export.py +++ b/app/modules/dispatch/tests/test_period_export.py @@ -21,7 +21,7 @@ _ROWS = [ def test_aggregate_multiplier_and_merge(): - """_N 배수 반영 + 대소문자/접미사 다른 같은 코드 합산, 빈 코드 제외, 콤보는 그대로.""" + """_N 배수 반영 + 대소문자/접미사 다른 같은 코드 합산, 빈 코드 제외(BOM 없으면 세트 그대로).""" dates, names, qty = export.aggregate_shipped(_ROWS, {"MT-0320": "상품A"}) assert dates == ["2026-10-01", "2026-10-02"], dates assert qty[("2026-10-01", "MT-0320")] == 4 # 1×3 + 1 @@ -31,11 +31,28 @@ def test_aggregate_multiplier_and_merge(): assert names["MY-0001"] == "Set" # 없으면 파싱된 이름 +_BOM = {"MY-0001": [ + {"component_code": "MT-0320", "component_qty": 1}, + {"component_code": "mt-0550", "component_qty": 2}, +]} + + +def test_aggregate_explodes_sets(): + """세트는 BOM 으로 낱개 분해해 같은 날 같은 낱개 코드에 합산.""" + dates, names, qty = export.aggregate_shipped(_ROWS, {"MT-0550": "상품B"}, _BOM) + assert ("2026-10-01", "MY-0001") not in qty + assert qty[("2026-10-01", "MT-0320")] == 8 # 1×3 + 1 + 세트 4×1 + assert qty[("2026-10-01", "MT-0550")] == 8 # 세트 4×2 + assert names["MT-0550"] == "상품B" + assert export.missing_set_boms(_ROWS, _BOM) == [] + assert export.missing_set_boms(_ROWS, {}) == ["MY-0001"] + + def test_build_period_xlsx_sheets(): from openpyxl import load_workbook data = export.build_period_xlsx( - rows=_ROWS, date_from="2026-10-01", date_to="2026-10-02", name_map={} + rows=_ROWS, date_from="2026-10-01", date_to="2026-10-02", name_map={}, set_bom=_BOM ) wb = load_workbook(io.BytesIO(data)) assert wb.sheetnames == ["날짜별", "아이템별 요약"] @@ -43,17 +60,17 @@ def test_build_period_xlsx_sheets(): ws = wb["날짜별"] rows = list(ws.iter_rows(values_only=True)) assert rows[0] == ("발송 날짜", "아이템 코드", "상품이름", "수량") - assert rows[1] == ("2026-10-01", "MT-0320", "A", 4) - assert rows[2] == ("2026-10-01", "MY-0001", "Set", 4) + assert rows[1] == ("2026-10-01", "MT-0320", "A", 8) + assert rows[2] == ("2026-10-01", "MT-0550", None, 8) assert rows[3] == ("2026-10-02", "MT-0320", "A", 2) - assert rows[-1][0] == "합계" and rows[-1][3] == 10 + assert rows[-1][0] == "합계" and rows[-1][3] == 18 ws2 = wb["아이템별 요약"] rows2 = list(ws2.iter_rows(values_only=True)) assert rows2[0] == ("아이템 코드", "상품이름", "2026-10-01", "2026-10-02", "합계") - assert rows2[1] == ("MT-0320", "A", 4, 2, 6) - assert rows2[2] == ("MY-0001", "Set", 4, None, 4) - assert rows2[3] == ("합계", None, 8, 2, 10) + assert rows2[1] == ("MT-0320", "A", 8, 2, 10) + assert rows2[2] == ("MT-0550", None, 8, None, 8) + assert rows2[3] == ("합계", None, 16, 2, 18) def test_period_filename(): @@ -62,6 +79,7 @@ def test_period_filename(): if __name__ == "__main__": test_aggregate_multiplier_and_merge() + test_aggregate_explodes_sets() test_build_period_xlsx_sheets() test_period_filename() print("OK") diff --git a/docs/DISPATCH_MODULE.md b/docs/DISPATCH_MODULE.md index 397c2b0..97f414e 100644 --- a/docs/DISPATCH_MODULE.md +++ b/docs/DISPATCH_MODULE.md @@ -53,7 +53,7 @@ | `GET /dispatch/batches/{id}/picking` | SKU별 피킹 요약 | | `GET /dispatch/batches/{id}/handover` | Kagayaku 전달 리스트(A4 인쇄용) | | `POST /dispatch/parcels/{id}/toggle` | 작업 상태 1개 토글(AJAX, 즉시 저장) | -| `GET /dispatch/period-export?date_from=&date_to=` | **수퍼 관리자 전용** 기간별 발송 수량 xlsx(배치 목록 오른쪽 카드). 시트 「날짜별」(날짜/아이템코드/상품이름/수량) + 「아이템별 요약」(아이템 × 날짜 피벗, 합계). `_N` 배수 반영, 콤보는 분해 안 함, 최대 366일 | +| `GET /dispatch/period-export?date_from=&date_to=` | **수퍼 관리자 전용** 기간별 발송 수량 xlsx(배치 목록 오른쪽 카드). 시트 「날짜별」(날짜/아이템코드/상품이름/수량) + 「아이템별 요약」(아이템 × 날짜 피벗, 합계). `_N` 배수 반영, 세트(MY-)는 itemcode_db BOM 으로 낱개 분해 후 합산(BOM 없는 세트가 있으면 422 로 목록 안내), 최대 366일 | 작업 상태(카드 버튼, 누르면 초록색): 상품준비 완료 → 포장완료 → 라벨부착 완료 → Kagayaku 전달 완료 → 택배스캔 확인. 모든 변경은 `dispatch_logs` 에 기록된다.