diff --git a/CLAUDE.md b/CLAUDE.md index bc67f70..e1fc820 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -31,7 +31,7 @@ Claude Code는 이 저장소에서 작업을 시작하기 전에 **반드시 아 - 반품관리 - 외부 쇼핑몰 API 연동 (카페24, 네이버 스마트스토어, 사방넷 등) - 개인경비 (`app/modules/expense/`, `expense_db`) -- 쿠팡 밀크런 (`app/modules/cupang/`, `cupang_db`) — 출고 달력/박스 계산/입고센터 관리, 상품은 `itemcode_db` 읽기 전용. 출고 묶음은 **박스 계산 화면의 [분배 확정] 으로만** 만든다(신규 등록 폼 없음, `/cupang/new` 는 박스 계산으로 리다이렉트). 확정 조건: 미배분 박스 0 + 담긴 센터마다 출고방식(택배/파렛트) 선택. 확정 시 센터마다 출고 묶음 1건(`status=출고준비`, 센터입고일=출고일). 작업 중 상태는 `cupang_box_calc_drafts` 에 이름 붙여 임시 저장/불러오기. 쿠팡 발주 엑셀(xlsx) 다중 업로드 지원(`POST /cupang/api/box-calc/upload`, openpyxl) — F13 입고예정일의 하루 전 = 출고일, 22행부터 B=쿠팡상품코드·F=센터명·G=수량을 읽어 `cupang_products.coupang_item_code` 로 제품 매칭 후 센터별 합산 → 센터 단위로 박스 계산·자동 배분 +- 쿠팡 밀크런 (`app/modules/cupang/`, `cupang_db`) — 출고 달력/박스 계산/입고센터 관리, 상품은 `itemcode_db` 읽기 전용. 출고 묶음은 **박스 계산 화면의 [분배 확정] 으로만** 만든다(신규 등록 폼 없음, `/cupang/new` 는 박스 계산으로 리다이렉트). 확정 조건: 미배분 박스 0 + 담긴 센터마다 출고방식(택배/파렛트) 선택. 확정 시 센터마다 출고 묶음 1건(`status=출고준비`, 센터입고일=출고일+1일) + 출고리스트 엑셀 자동 다운로드(`GET /cupang/export.xlsx?date=`, 시트명 YYYYMMDD). 작업 중 상태는 `cupang_box_calc_drafts` 에 이름 붙여 임시 저장/불러오기. 쿠팡 발주 엑셀(xlsx) 다중 업로드 지원(`POST /cupang/api/box-calc/upload`, openpyxl) — F13 입고예정일의 하루 전 = 출고일, 22행부터 B=쿠팡상품코드·F=센터명·G=수량을 읽어 `cupang_products.coupang_item_code` 로 제품 매칭 후 센터별 합산 → 센터 단위로 박스 계산·자동 배분 - 휴가 관리 (`app/modules/vacation/`, `vacation_db`) — 월간 달력(구글식 bar)/연차·반차 신청/승인 워크플로/공휴일·연차 설정. 권한키 `vacation`·`vacation_approver` - 말레이시아 창고 재고관리 (`app/modules/malaysia/`, `malaysia_stock_db`) — 낱개(MT/MX/MZ) 입출고·조정, 세트(MY) BOM, 일일 재고조사(세트→낱개 자동 분해), 현재고 현황. 뚜껑(MD-)은 재고 집계 제외 — 단, 창고 랙에는 위치 확인용으로 배치 가능(`store.LID_ITEMS`). 상품은 `itemcode_db` 읽기 전용. 권한키 `malaysia` - 말레이시아 배송 (`app/modules/dispatch/`, `dispatch_db`) — TikTok·Shopee 출고관리. 플랫폼별 데이터 엑셀 업로드(TikTok=03_TikTok_Order_Export.xlsx, Shopee=Packing List.Doorstep Delivery.xlsx) → 1박스=1카드 출고 작업 리스트·SKU 피킹 요약·Kagayaku 전달표 자동 생성. 1박스 묶음 기준 Package ID > Tracking ID > Order ID, 같은 박스 같은 SKU 합산. 작업 상태 토글(`dispatch_logs` 기록). 받는 사람 이름/전화/주소는 박스 단위로 저장(작업 카드 표시 + 출고 엑셀 생성용 — 개인정보). 배치 다운로드 zip 에 업로드 원본 + 취합 출고 엑셀(`YYYY.MM.DD(Ddd)_tictoc|shopee.xlsx`) 포함. 엑셀은 openpyxl 파싱/생성. 권한키 `dispatch`. 상세는 `docs/DISPATCH_MODULE.md` diff --git a/app/modules/cupang/router.py b/app/modules/cupang/router.py index 9e1e465..ea5a6cb 100644 --- a/app/modules/cupang/router.py +++ b/app/modules/cupang/router.py @@ -16,7 +16,7 @@ from fractions import Fraction from typing import Any from urllib.parse import quote -from datetime import date as _date +from datetime import date as _date, timedelta as _timedelta from app.timezone import today_kst @@ -236,6 +236,141 @@ async def index(request: Request) -> HTMLResponse: ) +# ════════════════════════════════════════════════════════════ +# 출고리스트 엑셀 — 확정한 출고일 기준 (쿠팡로켓 밀크런 양식) +# ════════════════════════════════════════════════════════════ +EXPORT_COMPANY = "㈜더블엑스코퍼레이션" +EXPORT_WORKER = "핫프렌즈" +EXPORT_DOW = ["월", "화", "수", "목", "금", "토", "일"] +EXPORT_HEADERS = [ + "구분", "작성일", "출고일", "센터입고일", "입고센터", "출고방식", + "제품코드", "제품명", "수량", "출고", "작업자", +] + + +def _export_workbook(ship_date: str, shipments: list[dict[str, Any]]) -> Any: + """출고 묶음 목록 → 스크린샷 양식의 워크북. 시트명은 출고일(YYYYMMDD).""" + from openpyxl import Workbook # noqa: WPS433 + from openpyxl.styles import Alignment, Border, Font, Side # noqa: WPS433 + from openpyxl.utils import get_column_letter # noqa: WPS433 + + d = _date.fromisoformat(ship_date) + tag = d.strftime("%Y%m%d") + + wb = Workbook() + ws = wb.active + ws.title = tag + + thin = Side(style="thin", color="000000") + box = Border(left=thin, right=thin, top=thin, bottom=thin) + center_align = Alignment(horizontal="center", vertical="center", wrap_text=True) + left_align = Alignment(horizontal="left", vertical="center", wrap_text=True) + + # 제목 (B2:L2) + ws.merge_cells(start_row=2, start_column=2, end_row=2, end_column=12) + title = ws.cell(row=2, column=2, value=f"{tag}({EXPORT_DOW[d.weekday()]}) 쿠팡로켓 밀크런 출고리스트") + title.font = Font(size=16, bold=True) + title.alignment = center_align + + ws.cell(row=4, column=2, value=EXPORT_COMPANY).font = Font(size=11) + + # 머리글 (B5:L5) + for i, name in enumerate(EXPORT_HEADERS): + c = ws.cell(row=5, column=2 + i, value=name) + c.font = Font(bold=True) + c.alignment = center_align + c.border = box + + row = 6 + seq = 0 + document_date = "" + for sh in shipments: + lines = sh.get("lines") or [] + if not lines: + continue + document_date = str(sh.get("document_date") or document_date) + start = row + for ln in lines: + seq += 1 + ws.cell(row=row, column=2, value=seq) # 구분 + ws.cell(row=row, column=8, value=ln.get("product_code") or "") # 제품코드 + ws.cell(row=row, column=9, value=ln.get("product_name_snapshot") or "") # 제품명 + ws.cell(row=row, column=10, value=int(ln.get("quantity") or 0)) # 수량 + row += 1 + end = row - 1 + + # 센터 단위로 병합되는 칸들 + merged_cols = { + 3: str(sh.get("document_date") or ""), + 4: str(sh.get("ship_date") or ""), + 5: str(sh.get("center_arrival_date") or ""), + 6: sh.get("center_name_snapshot") or "", + 7: sh.get("ship_method") or "", + 11: sh.get("outbound_summary") or "", + 12: EXPORT_WORKER, + } + for col, value in merged_cols.items(): + if end > start: + ws.merge_cells(start_row=start, start_column=col, end_row=end, end_column=col) + ws.cell(row=start, column=col, value=value) + + for r in range(start, end + 1): + for col in range(2, 13): + cell = ws.cell(row=r, column=col) + cell.border = box + cell.alignment = left_align if col == 9 else center_align + + widths = {2: 6, 3: 12, 4: 12, 5: 12, 6: 11, 7: 10, 8: 12, 9: 26, 10: 8, 11: 12, 12: 11} + for col, w in widths.items(): + ws.column_dimensions[get_column_letter(col)].width = w + ws.row_dimensions[2].height = 28 + + return wb + + +@router.get("/export.xlsx") +async def export_shipments_xlsx(request: Request, date: str = "") -> Any: + """출고일 기준 출고리스트 엑셀 다운로드. 시트명 = YYYYMMDD.""" + from io import BytesIO # noqa: WPS433 + + from fastapi.responses import StreamingResponse # noqa: WPS433 + + guard = _guard(request) + if not isinstance(guard, tuple): + return guard + store, _user = guard + + ship_date = (date or "").strip() + try: + _date.fromisoformat(ship_date) + except ValueError: + raise HTTPException(status_code=400, detail="출고일자(date=YYYY-MM-DD)가 필요합니다.") + + heads = [ + s for s in store.list_shipments(date_from=ship_date, date_to=ship_date) + if s.get("status") != "취소" + ] + shipments = [] + for h in sorted(heads, key=lambda x: (x.get("center_name_snapshot") or "")): + full = store.get_shipment(shipment_id=h["id"]) + if full: + shipments.append(full) + if not shipments: + raise HTTPException(status_code=404, detail="해당 출고일의 출고 묶음이 없습니다.") + + wb = _export_workbook(ship_date, shipments) + buf = BytesIO() + wb.save(buf) + buf.seek(0) + tag = ship_date.replace("-", "") + filename = f"{tag}_cupang_milkrun.xlsx" + return StreamingResponse( + buf, + media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + headers={"Content-Disposition": f'attachment; filename="{filename}"'}, + ) + + # ════════════════════════════════════════════════════════════ # 출고 묶음 — 등록 / 수정 / 상세 # ════════════════════════════════════════════════════════════ @@ -1242,6 +1377,7 @@ async def box_calc_confirm( rules = {r["product_code"]: r for r in store.list_box_rules()} known_centers = {str(c["id"]): c for c in store.list_centers(include_inactive=True)} today = today_kst().isoformat() + arrival_date = (_date.fromisoformat(ship_date) + _timedelta(days=1)).isoformat() worker = str(user.get("name") or user.get("email") or "") plans: list[dict[str, Any]] = [] @@ -1296,7 +1432,10 @@ async def box_calc_confirm( except (TypeError, ValueError): boxes = 0 pieces = sum(merged.values()) - summary = f"{boxes}박스 · {pieces}개" if boxes else f"{pieces}개" + # 화면에서 고른 상자 종류별 박스 수(예: "쿠팡상자41"). 출고리스트 엑셀의 "출고" 칸. + summary = str(raw.get("box_summary") or "").strip() + if not summary: + summary = f"{boxes}박스 · {pieces}개" if boxes else f"{pieces}개" plans.append({"center": center, "method": method, "lines": lines, "summary": summary}) @@ -1312,8 +1451,8 @@ async def box_calc_confirm( header={ "document_date": today, "ship_date": ship_date, - # 센터입고일은 출고일과 같게 두고, 필요하면 출고 상세에서 고친다. - "center_arrival_date": ship_date, + # 센터입고일 = 출고일 다음 날(쿠팡 발주서의 입고예정일). 상세에서 고칠 수 있다. + "center_arrival_date": arrival_date, "center_id": center["id"], "center_name_snapshot": center["name"], "ship_method": plan["method"], diff --git a/app/modules/cupang/templates/cupang/box_calc.html b/app/modules/cupang/templates/cupang/box_calc.html index 9cc9784..74ef9fb 100644 --- a/app/modules/cupang/templates/cupang/box_calc.html +++ b/app/modules/cupang/templates/cupang/box_calc.html @@ -111,16 +111,8 @@ 등록된 입고센터가 없습니다. 입고센터 관리에서 먼저 센터를 추가하세요.

{% else %} -
- -
-

추가한 센터가 여기에 표시됩니다.

+

발주 파일을 업로드하면 센터가 여기에 표시됩니다.

{% endif %} @@ -1242,10 +1234,28 @@ }); } }); + // 출고 엑셀 "출고" 칸 — 상자 종류별 박스 수 (예: 쿠팡상자41, 3호상자2) + var byType = {}; + var order = []; + rows.forEach(function (a) { + var t; + if (a.key.indexOf("m:") === 0) { + t = mixTypeOf(a.key); + } else { + var code = a.key.slice(2); + var hit = calc.results.filter(function (r) { return r.product_code === code; })[0]; + t = (hit && hit.box_name) || "쿠팡상자"; + } + if (!(t in byType)) { byType[t] = 0; order.push(t); } + byType[t] += a.count; + }); + var boxSummary = order.map(function (t) { return t + byType[t]; }).join(", "); + return { center_id: cid, ship_method: methods[String(cid)] || "", boxes: boxes, + box_summary: boxSummary, items: items }; }); @@ -1319,6 +1329,8 @@ }) .then(function (data) { var d = (data && data.ship_date) || picked; + // 확정한 출고일의 출고리스트 엑셀을 내려받는다. + window.location.href = "/cupang/export.xlsx?date=" + encodeURIComponent(d); // 업로드한 출고일이 여러 개면 남은 날짜 작업을 이어서 한다. var idx = dateOrder.indexOf(activeDate); if (idx >= 0 && dateOrder.length > 1) { @@ -1334,8 +1346,11 @@ return; } var parts = d.split("-"); - // 달력으로 이동해 방금 만든 출고 묶음을 보여준다. - window.location.href = "/cupang/?year=" + parts[0] + "&month=" + parseInt(parts[1], 10) + "&date=" + d; + // 달력으로 이동해 방금 만든 출고 묶음을 보여준다(엑셀 저장 뒤). + cfmMsg.textContent = "출고리스트 엑셀을 저장했습니다. 달력으로 이동합니다…"; + setTimeout(function () { + window.location.href = "/cupang/?year=" + parts[0] + "&month=" + parseInt(parts[1], 10) + "&date=" + d; + }, 1200); }) .catch(function (err) { cfmMsg.textContent = (err && err.message) || "확정 실패 — 다시 시도하세요.";