diff --git a/app/modules/dispatch/CLAUDE.md b/app/modules/dispatch/CLAUDE.md index 1e4565c..e444c48 100644 --- a/app/modules/dispatch/CLAUDE.md +++ b/app/modules/dispatch/CLAUDE.md @@ -10,4 +10,5 @@ - 작업 상태 토글(`dispatch_logs` 기록). - 받는 사람 이름/전화/주소는 상자 단위로 저장(작업 카드 표시 + 출고 엑셀 생성용) — **개인정보**, 로그·외부 전송 주의. - 배치 다운로드 zip 에 업로드 원본 + 취합 출고 엑셀(`YYYY.MM.DD(Ddd)_tictoc|shopee.xlsx`) 포함. +- 기간별 발송 수량 엑셀(`/dispatch/period-export`, **수퍼 관리자 전용**): 날짜별·아이템별 수량(`_N` 배수 반영, 콤보 미분해) + 아이템×날짜 요약 시트. - 엑셀은 openpyxl 파싱/생성. diff --git a/app/modules/dispatch/db.py b/app/modules/dispatch/db.py index 27eed66..926e541 100644 --- a/app/modules/dispatch/db.py +++ b/app/modules/dispatch/db.py @@ -309,6 +309,41 @@ class DispatchStore: for r in rows ] + def shipped_by_date_range( + self, *, date_from: str, date_to: str + ) -> list[dict[str, Any]]: + """기간(양끝 포함) 날짜·SKU별 합산 수량 — 기간별 발송 수량 엑셀용. + + 반환: [{"dispatch_date": "YYYY-MM-DD", "seller_sku", "product_name", "qty"}]. + _N 배수 반영은 호출부(export)에서 한다. + """ + with self._pool.connection() as conn: + rows = conn.execute( + """ + SELECT b.dispatch_date, i.seller_sku, + MAX(i.product_name) AS product_name, + SUM(i.quantity)::int AS qty + FROM dispatch_items i + JOIN dispatch_parcels p ON p.id = i.parcel_id + JOIN dispatch_batches b ON b.id = p.batch_id + WHERE b.dispatch_date BETWEEN %s AND %s + GROUP BY b.dispatch_date, i.seller_sku + ORDER BY b.dispatch_date ASC, i.seller_sku ASC + """, + (date_from, date_to), + ).fetchall() + return [ + { + "dispatch_date": r["dispatch_date"].isoformat() + if isinstance(r["dispatch_date"], date) + else str(r["dispatch_date"] or ""), + "seller_sku": r["seller_sku"] or "", + "product_name": r["product_name"] or "", + "qty": int(r["qty"] or 0), + } + for r in rows + ] + # ════════════════════════════════════════════════════════════ # 말레이시아 재고 차감 1회성 가드 # ════════════════════════════════════════════════════════════ diff --git a/app/modules/dispatch/export.py b/app/modules/dispatch/export.py index 255d81d..af38943 100644 --- a/app/modules/dispatch/export.py +++ b/app/modules/dispatch/export.py @@ -246,6 +246,122 @@ def stock_filename(dispatch_date: str) -> str: return f"{stamp}_sabangnet_outbound.xlsx" +# ── 기간별 발송 수량 엑셀(수퍼 관리자) ── +def aggregate_shipped( + rows: list[dict[str, Any]], name_map: dict[str, str] | None = None +) -> tuple[list[str], dict[str, str], dict[tuple[str, str], int]]: + """날짜·SKU별 합산 행 → (날짜목록, {코드: 상품명}, {(날짜, 코드): 수량}). + + seller_sku 의 _N 접미사는 배수로 곱해 실제 아이템코드로 합친다 + (예: MT-0320_3 × 2 → MT-0320 6개). 콤보는 분해하지 않고 발송된 그대로 센다. + """ + name_map = name_map or {} + dates: set[str] = set() + names: dict[str, str] = {} + qty: dict[tuple[str, str], int] = {} + for r in rows: + base, mult = split_sku(r.get("seller_sku", "")) + code = base.strip().upper() + if not code: + continue + pieces = int(r.get("qty", 0) or 0) * mult + if pieces <= 0: + 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 "" + ) + return sorted(dates), names, qty + + +def build_period_xlsx( + *, + rows: list[dict[str, Any]], + date_from: str, + date_to: str, + name_map: dict[str, str] | None = None, +) -> bytes: + """기간별 발송 수량 xlsx. 시트 2개. + + - 「날짜별」: 발송 날짜 / 아이템 코드 / 상품이름 / 수량 (날짜·코드 오름차순, 맨 끝 합계) + - 「아이템별 요약」: 아이템 코드 / 상품이름 / 날짜1..N / 합계 (맨 끝 날짜별 합계 행) + """ + from openpyxl import Workbook # noqa: WPS433 + from openpyxl.styles import Alignment, Font, PatternFill + from openpyxl.utils import get_column_letter + + dates, names, qty = aggregate_shipped(rows, name_map) + codes = sorted(names) + + head_fill = PatternFill("solid", fgColor="E2E8F0") + head_font = Font(bold=True) + bold = Font(bold=True) + + def _style_head(ws: Any) -> None: + for cell in ws[1]: + cell.fill = head_fill + cell.font = head_font + cell.alignment = Alignment(horizontal="center", vertical="center") + ws.freeze_panes = "A2" + + wb = Workbook() + + # 시트 1 — 날짜별 목록 + ws = wb.active + ws.title = "날짜별" + headers = ["발송 날짜", "아이템 코드", "상품이름", "수량"] + ws.append(headers) + total = 0 + for d in dates: + for code in codes: + n = qty.get((d, code)) + if not n: + continue + ws.append([d, code, names.get(code, ""), n]) + total += n + ws.append(["합계", "", "", total]) + for cell in ws[ws.max_row]: + cell.font = bold + _style_head(ws) + _autosize(ws, headers) + + # 시트 2 — 아이템(행) × 날짜(열) 요약 + ws2 = wb.create_sheet("아이템별 요약") + headers2 = ["아이템 코드", "상품이름", *dates, "합계"] + ws2.append(headers2) + for code in codes: + per_day = [qty.get((d, code), 0) for d in dates] + ws2.append([code, names.get(code, ""), *[n or None for n in per_day], sum(per_day)]) + day_totals = [sum(qty.get((d, c), 0) for c in codes) for d in dates] + ws2.append(["합계", "", *day_totals, sum(day_totals)]) + for cell in ws2[ws2.max_row]: + cell.font = bold + _style_head(ws2) + ws2.freeze_panes = "C2" + _autosize(ws2, headers2) + for i in range(3, len(headers2) + 1): # 날짜 열은 좁게 고정 + ws2.column_dimensions[get_column_letter(i)].width = 12 + + wb.properties.title = f"말레이시아 발송 수량 {date_from} ~ {date_to}" + + buf = io.BytesIO() + wb.save(buf) + return buf.getvalue() + + +def period_filename(date_from: str, date_to: str) -> str: + """기간별 발송 수량 파일명: 2026.10.01-2026.10.28_shipped_qty.xlsx.""" + def _stamp(v: str) -> str: + d = _parse_date(v) + return d.strftime("%Y.%m.%d") if d else (v or "").strip() + + return f"{_stamp(date_from)}-{_stamp(date_to)}_shipped_qty.xlsx" + + def _cell(value: Any) -> Any: """송장/전화번호 등이 숫자로 보이면 엑셀이 과학표기/반올림 하므로 문자열 보존.""" if isinstance(value, int): diff --git a/app/modules/dispatch/router.py b/app/modules/dispatch/router.py index 21459ab..1ef67f7 100644 --- a/app/modules/dispatch/router.py +++ b/app/modules/dispatch/router.py @@ -477,6 +477,56 @@ def stock_export( ) +_PERIOD_MAX_DAYS = 366 + + +@router.get("/period-export") +def period_export( + request: Request, + date_from: str, + date_to: str, + user: dict[str, Any] = Depends(_require_user), +) -> Response: + """기간(양끝 포함) 날짜별·아이템별 발송 수량 xlsx — 슈퍼 관리자 전용. + + seller_sku 의 _N 배수는 반영, 콤보는 분해하지 않고 발송된 그대로 센다. + """ + if not bool(user.get("is_super_admin")): + raise HTTPException(status_code=403, detail="기간별 발송 수량은 슈퍼 관리자만 받을 수 있습니다.") + st = _store(request) + if st is None: + raise HTTPException(status_code=503, detail="dispatch_db 미설정") + d_from = export._parse_date(date_from) + d_to = export._parse_date(date_to) + if d_from is None or d_to is None: + raise HTTPException(status_code=400, detail="시작일·종료일을 YYYY-MM-DD 로 입력하세요.") + if d_from > d_to: + d_from, d_to = d_to, d_from + if (d_to - d_from).days + 1 > _PERIOD_MAX_DAYS: + raise HTTPException(status_code=400, detail=f"기간은 최대 {_PERIOD_MAX_DAYS}일까지 가능합니다.") + + f, t = d_from.isoformat(), d_to.isoformat() + rows = st.shipped_by_date_range(date_from=f, date_to=t) + if not rows: + raise HTTPException(status_code=404, detail=f"{f} ~ {t} 기간의 발송 데이터가 없습니다.") + + xlsx_bytes = export.build_period_xlsx( + rows=rows, date_from=f, date_to=t, name_map=_itemcode_name_map(request) + ) + fname = export.period_filename(f, t) + headers = { + "Content-Disposition": ( + f"attachment; filename=\"shipped_{f}_{t}.xlsx\"; " + f"filename*=UTF-8''{quote(fname)}" + ) + } + return Response( + content=xlsx_bytes, + media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + headers=headers, + ) + + @router.post("/stock-deduct") def stock_deduct( request: Request, diff --git a/app/modules/dispatch/templates/dispatch/batches.html b/app/modules/dispatch/templates/dispatch/batches.html index ec16f78..4665bbd 100644 --- a/app/modules/dispatch/templates/dispatch/batches.html +++ b/app/modules/dispatch/templates/dispatch/batches.html @@ -114,7 +114,8 @@ -
기간 안 날짜별·아이템별 발송 수량을 엑셀로 받습니다. (수퍼 관리자 전용)
+