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:
@@ -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 기준으로 **통째로 다시 써서**
|
||||
팝업으로 적은 줄이 사라진다.
|
||||
|
||||
+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")
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
{# 출고리스트 작성 팝업의 날짜 칸은 프로젝트 화면의 날짜 팝업을 그대로 쓴다 — project.js 는 PJ_LIB_ONLY 로 부품만 #}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261022a" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
<link rel="stylesheet" href="/static/cupang.css?v=20261023a" />
|
||||
<link rel="stylesheet" href="/static/cupang.css?v=20261023b" />
|
||||
<script>window.PJ_LIB_ONLY = true; window.PJ_HOLIDAYS = {{ (pj_kr_holidays or {}) | tojson }};</script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -181,42 +181,62 @@
|
||||
<div class="cpg-modal-box cpg-ol-box" role="dialog" aria-modal="true" aria-labelledby="cpg-ol-title">
|
||||
<h3 id="cpg-ol-title">밀크런 출고리스트 작성</h3>
|
||||
|
||||
<div class="cpg-ol-grid">
|
||||
<div class="cpg-ol-grid cpg-ol-grid-4">
|
||||
<div class="erp-field"><span>작성일</span><input type="date" id="cpg-ol-doc-date" /></div>
|
||||
<div class="erp-field"><span>출고일</span><input type="date" id="cpg-ol-ship-date" /></div>
|
||||
<div class="erp-field"><span>센터입고일</span><input type="date" id="cpg-ol-arrival-date" /></div>
|
||||
<label class="erp-field"><span>입고센터</span>
|
||||
<select class="erp-select" id="cpg-ol-center"><option value="">불러오는 중…</option></select></label>
|
||||
<label class="erp-field"><span>출고방식</span>
|
||||
<select class="erp-select" id="cpg-ol-method">
|
||||
<option value="파렛트">파렛트</option>
|
||||
<option value="택배">택배</option>
|
||||
</select></label>
|
||||
<label class="erp-field cpg-ol-center-custom" hidden><span>새 입고센터</span>
|
||||
<input class="erp-input" type="text" id="cpg-ol-center-new" maxlength="60" placeholder="센터 이름" /></label>
|
||||
</div>
|
||||
|
||||
<div class="erp-field"><span>제품 (코드표에서 검색해 추가)</span>
|
||||
<div class="cpg-ol-search">
|
||||
<input class="erp-input" type="search" id="cpg-ol-search" autocomplete="off"
|
||||
placeholder="제품코드 또는 제품명으로 검색" />
|
||||
<ul class="cpg-ol-results" id="cpg-ol-results" hidden></ul>
|
||||
</div>
|
||||
</div>
|
||||
<table class="cpg-ol-lines">
|
||||
<thead><tr><th>제품코드</th><th>제품명</th><th>수량</th><th></th></tr></thead>
|
||||
<tbody id="cpg-ol-lines"></tbody>
|
||||
</table>
|
||||
<p class="erp-muted cpg-ol-empty" id="cpg-ol-empty">위 검색창에서 제품을 골라 추가하세요.</p>
|
||||
|
||||
<div class="cpg-ol-grid cpg-ol-grid-2">
|
||||
<label class="erp-field"><span>출고</span>
|
||||
<input class="erp-input" type="text" id="cpg-ol-outbound" maxlength="100" placeholder="예) 2파렛트, 15박스" /></label>
|
||||
<label class="erp-field"><span>작업자</span>
|
||||
<input class="erp-input" type="text" id="cpg-ol-worker" maxlength="30" value="{{ outbound_worker }}" /></label>
|
||||
</div>
|
||||
|
||||
<!-- 입고센터 카드 — 센터마다 출고방식·제품·출고를 따로 입력(cupang-outbound.js 가 템플릿으로 만든다) -->
|
||||
<div class="cpg-ol-centers" id="cpg-ol-centers"></div>
|
||||
<button type="button" class="erp-btn erp-btn-outline cpg-ol-add-center" id="cpg-ol-add-center">+ 입고센터 추가</button>
|
||||
<template id="cpg-ol-center-tpl">
|
||||
<section class="cpg-ol-center">
|
||||
<header class="cpg-ol-center-head">
|
||||
<strong class="cpg-ol-center-no">입고센터 1</strong>
|
||||
<button type="button" class="cpg-icon-btn is-danger cpg-ol-center-del">센터 삭제</button>
|
||||
</header>
|
||||
<div class="cpg-ol-grid">
|
||||
<label class="erp-field"><span>입고센터</span>
|
||||
<select class="erp-select cpg-ol-center-sel"><option value="">불러오는 중…</option></select></label>
|
||||
<label class="erp-field"><span>출고방식</span>
|
||||
<select class="erp-select cpg-ol-method">
|
||||
<option value="택배">택배</option>
|
||||
<option value="파렛트">파렛트</option>
|
||||
</select></label>
|
||||
<label class="erp-field"><span>출고</span>
|
||||
<input class="erp-input cpg-ol-outbound" type="text" maxlength="100" placeholder="예) 2파렛트, 15박스" /></label>
|
||||
<label class="erp-field cpg-ol-center-custom" hidden><span>새 입고센터</span>
|
||||
<input class="erp-input cpg-ol-center-new" type="text" maxlength="60" placeholder="센터 이름" /></label>
|
||||
</div>
|
||||
<div class="erp-field"><span>제품 (코드표에서 검색해 추가)</span>
|
||||
<div class="cpg-ol-search">
|
||||
<input class="erp-input cpg-ol-search-input" type="search" autocomplete="off"
|
||||
placeholder="제품코드 또는 제품명으로 검색" />
|
||||
<ul class="cpg-ol-results" hidden></ul>
|
||||
</div>
|
||||
</div>
|
||||
<table class="cpg-ol-lines" hidden>
|
||||
<thead><tr><th>제품코드</th><th>제품명</th><th>수량</th><th></th></tr></thead>
|
||||
<tbody></tbody>
|
||||
</table>
|
||||
<p class="erp-muted cpg-ol-empty">위 검색창에서 제품을 골라 추가하세요.</p>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<p class="erp-muted cpg-ol-target" id="cpg-ol-target"></p>
|
||||
<div class="cpg-ol-progress" id="cpg-ol-progress" hidden>
|
||||
<div class="cpg-ol-progress-top">
|
||||
<span id="cpg-ol-progress-step">준비 중</span>
|
||||
<b id="cpg-ol-progress-pct">0%</b>
|
||||
</div>
|
||||
<div class="cpg-ol-progress-track" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0"
|
||||
aria-label="기록 진행률" id="cpg-ol-progress-track">
|
||||
<div class="cpg-ol-progress-bar" id="cpg-ol-progress-bar"></div>
|
||||
</div>
|
||||
</div>
|
||||
<p class="cpg-ol-error" id="cpg-ol-error" hidden></p>
|
||||
<div class="cpg-ol-actions">
|
||||
<button type="button" class="erp-btn erp-btn-outline" data-ol-close>취소</button>
|
||||
@@ -230,7 +250,7 @@
|
||||
|
||||
{% block scripts %}
|
||||
<script src="/static/project.js?v=20261022c" defer></script>
|
||||
<script src="/static/cupang-outbound.js?v=20261023b" defer></script>
|
||||
<script src="/static/cupang-outbound.js?v=20261023c" defer></script>
|
||||
<script>
|
||||
(function () {
|
||||
var dlg = document.getElementById("cpg-del-dlg");
|
||||
|
||||
Reference in New Issue
Block a user