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 @@ -
+
+

사방넷 출고 다운로드

+ + {% if is_super %} +
+

기간별 발송 수량

+

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

+
+ + ~ + +
+ +
+
+ {% endif %} + {% endblock %} @@ -264,6 +283,53 @@ render(); })(); +// ── 기간별 발송 수량 엑셀(수퍼 관리자) ── +(function () { + var btn = document.getElementById('dsp-pe-dl'); + if (!btn) return; + var fromEl = document.getElementById('dsp-pe-from'); + var toEl = document.getElementById('dsp-pe-to'); + var note = document.getElementById('dsp-pe-note'); + function pad(n) { return (n < 10 ? '0' : '') + n; } + function iso(d) { return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate()); } + function en() { return (window.dspLang && window.dspLang() === 'en'); } + // 기본: 이번 달 1일 ~ 오늘 + var now = new Date(); + fromEl.value = iso(new Date(now.getFullYear(), now.getMonth(), 1)); + toEl.value = iso(now); + + btn.onclick = function () { + var f = fromEl.value, t = toEl.value; + if (!f || !t) { alert(en() ? 'Pick both dates.' : '시작일과 종료일을 고르세요.'); return; } + btn.disabled = true; + note.textContent = en() ? 'Preparing…' : '만드는 중…'; + var url = '/dispatch/period-export?date_from=' + encodeURIComponent(f) + '&date_to=' + encodeURIComponent(t); + fetch(url) + .then(function (r) { + if (!r.ok) { + return r.json().catch(function () { return {}; }).then(function (j) { + throw new Error((j && j.detail) || ('HTTP ' + r.status)); + }); + } + var cd = r.headers.get('Content-Disposition') || ''; + var m = cd.match(/filename\*=UTF-8''([^;]+)/); + var name = m ? decodeURIComponent(m[1]) : ('shipped_' + f + '_' + t + '.xlsx'); + return r.blob().then(function (b) { + var a = document.createElement('a'); + a.href = URL.createObjectURL(b); + a.download = name; + document.body.appendChild(a); a.click(); a.remove(); + setTimeout(function () { URL.revokeObjectURL(a.href); }, 1000); + note.textContent = ''; + }); + }) + .catch(function (e) { + note.textContent = (e && e.message) || (en() ? 'Failed' : '실패'); + }) + .then(function () { btn.disabled = false; }); + }; +})(); + // ── 받는 사람 찾기(이름/주문/패키지/송장 번호 부분 일치) ── (function () { var wrap = document.getElementById('dsp-search'); diff --git a/app/modules/dispatch/tests/test_period_export.py b/app/modules/dispatch/tests/test_period_export.py new file mode 100644 index 0000000..6122d98 --- /dev/null +++ b/app/modules/dispatch/tests/test_period_export.py @@ -0,0 +1,67 @@ +"""기간별 발송 수량 엑셀(export.aggregate_shipped / build_period_xlsx) 테스트. + +DB 없이 집계·엑셀 생성만 검증한다. + python -m app.modules.dispatch.tests.test_period_export +또는 pytest 로 실행 가능. +""" + +from __future__ import annotations + +import io + +from app.modules.dispatch import export + +_ROWS = [ + {"dispatch_date": "2026-10-02", "seller_sku": "MT-0320", "product_name": "A", "qty": 2}, + {"dispatch_date": "2026-10-01", "seller_sku": "MT-0320_3", "product_name": "A", "qty": 1}, + {"dispatch_date": "2026-10-01", "seller_sku": "mt-0320", "product_name": "A", "qty": 1}, + {"dispatch_date": "2026-10-01", "seller_sku": "MY-0001", "product_name": "Set", "qty": 4}, + {"dispatch_date": "2026-10-02", "seller_sku": "", "product_name": "", "qty": 9}, +] + + +def test_aggregate_multiplier_and_merge(): + """_N 배수 반영 + 대소문자/접미사 다른 같은 코드 합산, 빈 코드 제외, 콤보는 그대로.""" + 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 + assert qty[("2026-10-02", "MT-0320")] == 2 + assert qty[("2026-10-01", "MY-0001")] == 4 + assert names["MT-0320"] == "상품A" # itemcode 이름 우선 + assert names["MY-0001"] == "Set" # 없으면 파싱된 이름 + + +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={} + ) + wb = load_workbook(io.BytesIO(data)) + assert wb.sheetnames == ["날짜별", "아이템별 요약"] + + 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[3] == ("2026-10-02", "MT-0320", "A", 2) + assert rows[-1][0] == "합계" and rows[-1][3] == 10 + + 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) + + +def test_period_filename(): + assert export.period_filename("2026-10-01", "2026-10-28") == "2026.10.01-2026.10.28_shipped_qty.xlsx" + + +if __name__ == "__main__": + test_aggregate_multiplier_and_merge() + test_build_period_xlsx_sheets() + test_period_filename() + print("OK") diff --git a/docs/DISPATCH_MODULE.md b/docs/DISPATCH_MODULE.md index c1fbf38..397c2b0 100644 --- a/docs/DISPATCH_MODULE.md +++ b/docs/DISPATCH_MODULE.md @@ -53,6 +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일 | 작업 상태(카드 버튼, 누르면 초록색): 상품준비 완료 → 포장완료 → 라벨부착 완료 → Kagayaku 전달 완료 → 택배스캔 확인. 모든 변경은 `dispatch_logs` 에 기록된다. @@ -145,6 +146,7 @@ Product Name, Quantity, Recipient(받는 사람), Phone(전화), Address(주소) ```bash python -m app.modules.dispatch.tests.test_grouping # 앱 의존성 설치 환경에서 +python -m app.modules.dispatch.tests.test_period_export # 기간별 발송 수량 엑셀 ``` ---