diff --git a/app/modules/cupang/CLAUDE.md b/app/modules/cupang/CLAUDE.md index a63dd63..507807c 100644 --- a/app/modules/cupang/CLAUDE.md +++ b/app/modules/cupang/CLAUDE.md @@ -55,15 +55,20 @@ ## 밀크런 출고리스트 작성 (팝업 → 드라이브 엑셀 파일, 2026-10-23) - 첫 화면 "+ 신규 등록" 옆 엑셀색(#217346) 버튼 → 팝업(`index.html` + `static/cupang-outbound.js`). - 상자 계산 없이 센터 1곳을 **출고리스트 엑셀 파일에만** 적는다 — cupang_db 출고 묶음은 만들지 않는다(달력에 안 보임). + 상자 계산 없이 입고센터 여러 곳을 한 번에 **출고리스트 엑셀 파일에만** 적는다 — cupang_db 출고 묶음은 만들지 않는다(달력에 안 보임). - 대상 파일은 `router._outbound_target` — `CUPANG_OUTBOUND_XLSX_ID`(기본 `DEFAULT_OUTBOUND_XLSX_ID` = `1J74op7lBZOgE27p4R28I3RWsv0EtXdii`), 항상 `drive_xlsx`. `CUPANG_SHEET_ID`(분배 확정 동기화)와 따로라 그게 구글 시트 문서여도 팝업은 엑셀에만 쓴다. 드라이브 인증이 없거나 파일이 .xlsx 가 아니면 구글 시트로 대신 쓰지 않고 503(사유 표시). -- 입력: 작성일(기본 오늘)·출고일·센터입고일(출고일 고르면 +1일 자동) — 날짜 칸은 프로젝트 날짜 팝업 - (`PJLib.enhanceDateInput`, project.js 를 `PJ_LIB_ONLY` 로 로드). 입고센터(시트 F열 + 등록 센터, 직접 입력 가능), - 출고방식(파렛트/택배), 제품(코드표 `GET /cupang/api/products/all` 검색 → 코드·이름 자동, 수량 수기), 출고(수기), 작업자(기본 `export.WORKER`). -- `POST /cupang/api/outbound-sheet` → 시트 `YYYYMMDD(요일)`(출고일) 맨 아래에 `export.build_block` 으로 덧붙임 - (순번 B열 이어짐, 파렛트면 배경색). 시트가 없거나 5행 머리글이 없으면 양식째 새로 쓴다(`write_table`). - 위치 읽기~쓰기는 `writer.lock` 으로 한 덩어리. 입고센터 후보는 `GET /cupang/api/outbound-sheet/centers`(10분 캐시). +- 공통 입력: 작성일(기본 오늘)·출고일·센터입고일(출고일 고르면 +1일 자동)·작업자(기본 `export.WORKER`) — 날짜 칸은 프로젝트 날짜 팝업 + (`PJLib.enhanceDateInput`, project.js 를 `PJ_LIB_ONLY` 로 로드). +- **입고센터 카드**(`#cpg-ol-center-tpl`, [+ 입고센터 추가]·[센터 삭제], 최대 20곳): 센터마다 입고센터(시트 F열 + 등록 센터, 직접 입력 가능), + 출고방식(**기본 택배**/파렛트), 제품(코드표 `GET /cupang/api/products/all` 검색 → 코드·이름 자동, 수량 수기), 출고(수기). +- `POST /cupang/api/outbound-sheet` 본문 `{document_date, ship_date, center_arrival_date, worker, centers: [{center, ship_method, outbound, lines}]}` + (`centers` 없으면 본문 자체가 센터 1곳 — `_clean_outbound_entries`). 센터 순서대로 시트 `YYYYMMDD(요일)`(출고일) 맨 아래에 + `export.build_block` 으로 덧붙임(순번 B열 이어짐, 파렛트 센터만 배경색). 시트가 없거나 5행 머리글이 없으면 첫 센터는 양식째 새로 쓴다(`write_table`). + 전체가 `writer.lock` 한 덩어리 = 엑셀 내려받기 1번·올리기 1번(`_run_outbound_write`). 입고센터 후보는 `GET /cupang/api/outbound-sheet/centers`(10분 캐시). +- **진행 막대**: 팝업은 `?stream=1` 로 보내고 서버가 NDJSON 한 줄씩 `{progress, until, step}`(5 내려받기 → 40~80 센터별 추가 → 80 올리기) + … 마지막 `{done: true, ...결과}` 또는 `{error}`. 쓰기는 별도 스레드(잠금은 잡은 스레드에서 풀어야 함)가 하고 큐로 넘긴다. + 화면은 단계 사이에도 다음 단계(until) 바로 앞까지 조금씩 채우고 %를 같이 표시, 실패면 빨강. 입력 오류(400)·설정 없음(503)은 스트림 전 보통 JSON. - 주의: 같은 출고일에 [분배 확정]·출고 삭제가 일어나면 기존 동기화가 그 날짜 시트를 DB 기준으로 **통째로 다시 써서** 팝업으로 적은 줄이 사라진다. diff --git a/app/modules/cupang/router.py b/app/modules/cupang/router.py index b88d5b7..24f6b87 100644 --- a/app/modules/cupang/router.py +++ b/app/modules/cupang/router.py @@ -550,27 +550,62 @@ def outbound_sheet_centers( return JSONResponse({"centers": sorted(names), "reason": reason}) -@router.post("/api/outbound-sheet") -def outbound_sheet_write( - request: Request, - payload: dict[str, Any] = Body(...), - _: dict[str, Any] = Depends(_require_user), -) -> JSONResponse: - entry = _clean_outbound_entry(payload) - writer, spreadsheet_id, skip = _outbound_target() - if skip: - _log_sheet("manual-append", entry["ship_date"], skip) - raise HTTPException( - status_code=503, detail=f"출고리스트 엑셀 파일에 쓸 수 없습니다: {skip.get('reason') or '설정 확인 필요'}" - ) +_OUTBOUND_MAX_CENTERS = 20 + + +def _clean_outbound_entries(payload: dict[str, Any]) -> list[dict[str, Any]]: + """팝업 입력 → 입고센터마다 출고 묶음 1건. + + 공통(작성일·출고일·센터입고일·작업자) + `centers: [{center, ship_method, outbound, lines}]`. + `centers` 가 없으면 payload 자체를 센터 1곳으로 본다.""" + raw = payload.get("centers") + if raw is None: + return [_clean_outbound_entry(payload)] + if not isinstance(raw, list) or not raw: + raise HTTPException(status_code=400, detail="입고센터를 1곳 이상 추가해 주세요.") + if len(raw) > _OUTBOUND_MAX_CENTERS: + raise HTTPException(status_code=400, detail=f"입고센터는 한 번에 {_OUTBOUND_MAX_CENTERS}곳까지 입력할 수 있습니다.") + common = {k: payload.get(k) for k in ("document_date", "ship_date", "center_arrival_date", "worker")} + entries = [] + for i, c in enumerate(raw, start=1): + if not isinstance(c, dict): + raise HTTPException(status_code=400, detail=f"{i}번째 입고센터 정보를 확인해 주세요.") + try: + entries.append(_clean_outbound_entry({**c, **common})) + except HTTPException as exc: + prefix = f"{i}번째 입고센터: " if len(raw) > 1 else "" + raise HTTPException(status_code=exc.status_code, detail=prefix + str(exc.detail)) from None + return entries + + +def _run_outbound_write( + writer: Any, file_id: str, entries: list[dict[str, Any]], report: Any +) -> dict[str, Any]: + """센터들을 차례로 출고일 시트 아래에 덧붙인다(엑셀은 내려받기·올리기 1번씩). + + report(진행률, 다음 단계 진행률, 단계 이름) 로 진행 상황을 알린다. 실패는 HTTPException(502).""" from app.integrations.drive_xlsx import XlsxChangedError # noqa: WPS433 from app.integrations.google_drive import GoogleDriveError # noqa: WPS433 + ship_date = entries[0]["ship_date"] + n = len(entries) + + def run() -> list[dict[str, Any]]: + report(5, 40, "출고리스트 엑셀 내려받는 중") + writer.sheet_titles(spreadsheet_id=file_id) # 이 덩어리에서 한 번 내려받는다 + done = [] + for i, entry in enumerate(entries): + report(40 + 40 * i // n, 40 + 40 * (i + 1) // n, + f"{entry['center_name_snapshot']} 추가 중 ({i + 1}/{n})") + done.append(_append_outbound_entry(writer, file_id, entry)) + report(80, 100, "출고리스트 엑셀 올리는 중") + return done + try: # 시트 끝 위치를 읽고 쓰는 사이에 다른 요청이 끼어들지 않게 한 덩어리로 - res = _in_sheet(writer, lambda: _append_outbound_entry(writer, spreadsheet_id, entry)) + results = _in_sheet(writer, run) except Exception as exc: # noqa: BLE001 - 사유만 남긴다(비밀값 미출력) - _log_sheet("manual-append", entry["ship_date"], {"ok": False, "reason": type(exc).__name__}) + _log_sheet("manual-append", ship_date, {"ok": False, "reason": type(exc).__name__}) if isinstance(exc, XlsxChangedError): why = "다른 사람이 파일을 고치는 중입니다" elif isinstance(exc, GoogleDriveError): @@ -580,12 +615,83 @@ def outbound_sheet_write( raise HTTPException( status_code=502, detail=f"출고리스트 파일에 기록하지 못했습니다({why}). 잠시 후 다시 시도해 주세요." ) from exc - _log_sheet("manual-append", entry["ship_date"], - {"ok": True, "action": f"xlsx {spreadsheet_id} rows {res.get('first_row')}-{res.get('last_row')}"}) - center = entry["center_name_snapshot"] - if center not in _sheet_centers_cache["names"] and _sheet_centers_cache["sheet"] == spreadsheet_id: - _sheet_centers_cache["names"] = sorted([*_sheet_centers_cache["names"], center]) - return JSONResponse({"ok": True, **res, "line_count": len(entry["lines"])}) + + first, last = results[0], results[-1] + _log_sheet("manual-append", ship_date, + {"ok": True, "action": f"xlsx {file_id} centers {n} rows {first.get('first_row')}-{last.get('last_row')}"}) + if _sheet_centers_cache["sheet"] == file_id: + _sheet_centers_cache["names"] = sorted( + {*_sheet_centers_cache["names"], *(e["center_name_snapshot"] for e in entries)}) + return { + "ok": True, + "title": last.get("title"), + "url": last.get("url"), + "first_row": first.get("first_row"), + "last_row": last.get("last_row"), + "line_count": sum(len(e["lines"]) for e in entries), + "centers": [ + {"center": e["center_name_snapshot"], "first_row": r.get("first_row"), "last_row": r.get("last_row"), + "line_count": len(e["lines"])} + for e, r in zip(entries, results) + ], + } + + +@router.post("/api/outbound-sheet") +def outbound_sheet_write( + request: Request, + payload: dict[str, Any] = Body(...), + stream: bool = False, + _: dict[str, Any] = Depends(_require_user), +) -> Any: + """출고리스트 엑셀에 센터들을 덧붙인다. + + `?stream=1` 이면 한 줄에 JSON 하나씩(NDJSON) 진행 상황을 흘려보낸다 — + `{"progress", "until", "step"}` … 마지막에 `{"done": true, ...결과}` 또는 `{"error": 사유}`. + 입력 오류(400)·설정 없음(503)은 흘려보내기 전에 보통 JSON 오류로 돌려준다.""" + entries = _clean_outbound_entries(payload) + writer, file_id, skip = _outbound_target() + if skip: + _log_sheet("manual-append", entries[0]["ship_date"], skip) + raise HTTPException( + status_code=503, detail=f"출고리스트 엑셀 파일에 쓸 수 없습니다: {skip.get('reason') or '설정 확인 필요'}" + ) + if not stream: + return JSONResponse(_run_outbound_write(writer, file_id, entries, lambda *_a: None)) + + import queue # noqa: WPS433 + import threading # noqa: WPS433 + + from fastapi.responses import StreamingResponse # noqa: WPS433 + + events: Any = queue.Queue() + + def work() -> None: + # 잠금(writer.lock)은 잡은 스레드에서 풀어야 하므로 쓰기 전체를 스레드 하나에서 + try: + res = _run_outbound_write( + writer, file_id, entries, + lambda p, until, step: events.put({"progress": p, "until": until, "step": step}), + ) + events.put({"progress": 100, "until": 100, "step": "완료", "done": True, **res}) + except HTTPException as exc: + events.put({"error": str(exc.detail)}) + except Exception as exc: # noqa: BLE001 + events.put({"error": f"출고리스트 파일에 기록하지 못했습니다({type(exc).__name__})."}) + finally: + events.put(None) + + threading.Thread(target=work, name="cupang-outbound-write", daemon=True).start() + + def lines() -> Any: + while True: + item = events.get() + if item is None: + return + yield json.dumps(item, ensure_ascii=False) + "\n" + + return StreamingResponse(lines(), media_type="application/x-ndjson", + headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"}) @router.get("/export.xlsx") diff --git a/app/modules/cupang/templates/cupang/index.html b/app/modules/cupang/templates/cupang/index.html index 483096e..59b2f72 100644 --- a/app/modules/cupang/templates/cupang/index.html +++ b/app/modules/cupang/templates/cupang/index.html @@ -4,7 +4,7 @@ {# 출고리스트 작성 팝업의 날짜 칸은 프로젝트 화면의 날짜 팝업을 그대로 쓴다 — project.js 는 PJ_LIB_ONLY 로 부품만 #} - + {% endblock %} @@ -181,42 +181,62 @@