feat(cupang): 출고리스트 작성 — 입고센터별 입력·기본 택배·완료 진행 막대(%)
- 팝업에 입고센터 카드: [+ 입고센터 추가]·[센터 삭제], 센터마다 입고센터·출고방식·제품·출고를 따로 입력 (작성일·출고일·센터입고일·작업자는 공통), 출고방식 기본값 택배 - POST /cupang/api/outbound-sheet: centers 목록을 받아 센터 순서대로 출고일 시트 아래에 덧붙임 (엑셀 내려받기·올리기 1번씩, 순번 이어짐, 파렛트 센터만 배경색). centers 없으면 예전처럼 센터 1곳 - ?stream=1 이면 단계별 진행률을 NDJSON 으로 흘려보냄(내려받기 → 센터별 추가 → 올리기 → 완료/오류), 팝업은 막대 그래프와 %로 표시하고 단계 사이에도 조금씩 채움, 실패하면 빨간 막대 + 사유 - 테스트: pytest(센터별 입력 검사·여러 센터 한 번에 쓰기·진행 단계·스트림·충돌), Playwright(카드·진행 막대·완료·실패·모바일) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+127
-21
@@ -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")
|
||||
|
||||
Reference in New Issue
Block a user