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");
|
||||
|
||||
+327
-166
@@ -1,8 +1,11 @@
|
||||
/* 쿠팡 밀크런 — 밀크런 출고리스트 작성 팝업(cupang/index.html).
|
||||
- 날짜 칸: 프로젝트 화면의 날짜 팝업(window.PJLib.enhanceDateInput)을 그대로 쓴다.
|
||||
- 입고센터: 출고리스트 엑셀(구글 드라이브 .xlsx)에 적힌 센터 + 설정에 등록된 센터(GET /cupang/api/outbound-sheet/centers).
|
||||
- 입고센터 카드: 하루에 센터가 여럿일 수 있어 센터마다 출고방식(기본 택배)·제품·출고를 따로 입력한다
|
||||
(#cpg-ol-center-tpl 템플릿, [+ 입고센터 추가]). 작성일·출고일·센터입고일·작업자는 공통.
|
||||
- 입고센터 후보: 출고리스트 엑셀(구글 드라이브 .xlsx)에 적힌 센터 + 설정에 등록된 센터(GET /cupang/api/outbound-sheet/centers).
|
||||
- 제품: 코드표(itemcode_db) 전체 목록(GET /cupang/api/products/all)에서 코드·이름으로 찾아 추가.
|
||||
- [완료] → POST /cupang/api/outbound-sheet → 출고일 시트(YYYYMMDD(요일)) 맨 아래에 덧붙임. */
|
||||
- [완료] → POST /cupang/api/outbound-sheet?stream=1 → 서버가 단계별 진행률을 한 줄씩(NDJSON) 보내면 막대·%로 표시,
|
||||
센터 순서대로 출고일 시트(YYYYMMDD(요일)) 맨 아래에 덧붙인다. */
|
||||
(function () {
|
||||
"use strict";
|
||||
var dlg = document.getElementById("cpg-ol-dlg");
|
||||
@@ -13,19 +16,20 @@
|
||||
if (window.ERP_DIALOG_TITLE === "KSN 프로그램") delete window.ERP_DIALOG_TITLE;
|
||||
|
||||
var NEW_CENTER = "__new__";
|
||||
var DEFAULT_METHOD = "택배";
|
||||
var DOW = ["일", "월", "화", "수", "목", "금", "토"];
|
||||
function $(id) { return document.getElementById(id); }
|
||||
var docDate = $("cpg-ol-doc-date"), shipDate = $("cpg-ol-ship-date"), arrivalDate = $("cpg-ol-arrival-date");
|
||||
var centerSel = $("cpg-ol-center"), centerNew = $("cpg-ol-center-new");
|
||||
var centerCustom = dlg.querySelector(".cpg-ol-center-custom");
|
||||
var method = $("cpg-ol-method"), outbound = $("cpg-ol-outbound"), worker = $("cpg-ol-worker");
|
||||
var search = $("cpg-ol-search"), results = $("cpg-ol-results");
|
||||
var linesBody = $("cpg-ol-lines"), emptyMsg = $("cpg-ol-empty");
|
||||
var worker = $("cpg-ol-worker");
|
||||
var centersBox = $("cpg-ol-centers"), addCenterBtn = $("cpg-ol-add-center"), centerTpl = $("cpg-ol-center-tpl");
|
||||
var target = $("cpg-ol-target"), errorBox = $("cpg-ol-error"), submitBtn = $("cpg-ol-submit");
|
||||
var progressBox = $("cpg-ol-progress"), progressStep = $("cpg-ol-progress-step"), progressPct = $("cpg-ol-progress-pct");
|
||||
var progressTrack = $("cpg-ol-progress-track"), progressBar = $("cpg-ol-progress-bar");
|
||||
var defaultWorker = worker.value;
|
||||
|
||||
var products = null; // 코드표 [{code, name, type}] — 처음 열 때 한 번 읽는다
|
||||
var productsReason = "";
|
||||
var centerNames = null; // 입고센터 후보 — 열 때마다 다시 읽는다(null = 불러오는 중)
|
||||
var arrivalAuto = true; // 센터입고일을 직접 고르기 전까지는 출고일 + 1일로 따라간다
|
||||
var busy = false;
|
||||
|
||||
@@ -57,7 +61,7 @@
|
||||
|
||||
function updateTarget() {
|
||||
target.textContent = shipDate.value
|
||||
? "완료하면 출고리스트 엑셀 '" + sheetTitle(shipDate.value) + "' 시트 맨 아래에 추가합니다. (시트가 없으면 양식째 새로 만듭니다)"
|
||||
? "완료하면 출고리스트 엑셀 '" + sheetTitle(shipDate.value) + "' 시트 맨 아래에 입고센터 순서대로 추가합니다. (시트가 없으면 양식째 새로 만듭니다)"
|
||||
: "출고일을 고르면 그 날짜 시트(YYYYMMDD(요일))에 추가합니다.";
|
||||
}
|
||||
|
||||
@@ -70,35 +74,20 @@
|
||||
});
|
||||
arrivalDate.addEventListener("change", function () { arrivalAuto = !arrivalDate.value; });
|
||||
|
||||
// ── 입고센터 ─────────────────────────────────────
|
||||
function fillCenters(names, reason) {
|
||||
var keep = centerSel.value;
|
||||
centerSel.innerHTML = "";
|
||||
function add(value, label) {
|
||||
var o = document.createElement("option");
|
||||
o.value = value;
|
||||
o.textContent = label;
|
||||
centerSel.appendChild(o);
|
||||
}
|
||||
add("", names.length ? "센터 선택" : "센터 목록 없음");
|
||||
names.forEach(function (n) { add(n, n); });
|
||||
add(NEW_CENTER, "+ 직접 입력");
|
||||
if (keep && (keep === NEW_CENTER || names.indexOf(keep) >= 0)) centerSel.value = keep;
|
||||
centerCustom.hidden = centerSel.value !== NEW_CENTER;
|
||||
if (reason) showError("입고센터 목록 일부를 불러오지 못했습니다: " + reason);
|
||||
}
|
||||
// ── 데이터 읽기 ─────────────────────────────────
|
||||
function loadCenters() {
|
||||
centerNames = null;
|
||||
cards().forEach(function (c) { c.fillCenters(); });
|
||||
return fetch("/cupang/api/outbound-sheet/centers", { headers: { Accept: "application/json" } })
|
||||
.then(function (res) { return res.ok ? res.json() : Promise.reject(new Error(res.status)); })
|
||||
.then(function (data) { fillCenters(data.centers || [], data.reason || ""); })
|
||||
.catch(function () { fillCenters([], "서버 응답 없음"); });
|
||||
.then(function (data) { return { names: data.centers || [], reason: data.reason || "" }; })
|
||||
.catch(function () { return { names: [], reason: "서버 응답 없음" }; })
|
||||
.then(function (got) {
|
||||
centerNames = got.names;
|
||||
cards().forEach(function (c) { c.fillCenters(); });
|
||||
if (got.reason) showError("입고센터 목록 일부를 불러오지 못했습니다: " + got.reason);
|
||||
});
|
||||
}
|
||||
centerSel.addEventListener("change", function () {
|
||||
centerCustom.hidden = centerSel.value !== NEW_CENTER;
|
||||
if (!centerCustom.hidden) centerNew.focus();
|
||||
});
|
||||
|
||||
// ── 제품 검색(코드표) ─────────────────────────────
|
||||
function loadProducts() {
|
||||
if (products) return Promise.resolve();
|
||||
return fetch("/cupang/api/products/all", { headers: { Accept: "application/json" } })
|
||||
@@ -110,103 +99,236 @@
|
||||
.catch(function () { products = []; productsReason = "서버 응답 없음"; });
|
||||
}
|
||||
|
||||
var hits = [], activeHit = -1;
|
||||
function renderResults() {
|
||||
results.innerHTML = "";
|
||||
var q = search.value.trim().toLowerCase();
|
||||
if (!q) { results.hidden = true; return; }
|
||||
hits = (products || []).filter(function (p) {
|
||||
return p.code.toLowerCase().indexOf(q) >= 0 || p.name.toLowerCase().indexOf(q) >= 0;
|
||||
}).slice(0, 30);
|
||||
activeHit = hits.length ? 0 : -1;
|
||||
if (!hits.length) {
|
||||
var li = document.createElement("li");
|
||||
li.className = "cpg-ol-noresult";
|
||||
li.textContent = productsReason ? "코드표를 불러오지 못했습니다: " + productsReason : "검색 결과가 없습니다.";
|
||||
results.appendChild(li);
|
||||
}
|
||||
hits.forEach(function (p, i) {
|
||||
var li = document.createElement("li");
|
||||
li.className = "cpg-ol-hit" + (i === activeHit ? " is-active" : "");
|
||||
li.dataset.index = String(i);
|
||||
var code = document.createElement("b");
|
||||
code.textContent = p.code;
|
||||
var name = document.createElement("span");
|
||||
name.textContent = p.name;
|
||||
li.appendChild(code);
|
||||
li.appendChild(name);
|
||||
results.appendChild(li);
|
||||
});
|
||||
results.hidden = false;
|
||||
}
|
||||
function moveActive(step) {
|
||||
if (!hits.length) return;
|
||||
activeHit = (activeHit + step + hits.length) % hits.length;
|
||||
Array.prototype.forEach.call(results.querySelectorAll(".cpg-ol-hit"), function (li, i) {
|
||||
li.classList.toggle("is-active", i === activeHit);
|
||||
if (i === activeHit) li.scrollIntoView({ block: "nearest" });
|
||||
});
|
||||
}
|
||||
function pickHit(i) {
|
||||
var p = hits[i];
|
||||
if (!p) return;
|
||||
addLine(p.code, p.name);
|
||||
search.value = "";
|
||||
results.hidden = true;
|
||||
}
|
||||
search.addEventListener("input", renderResults);
|
||||
search.addEventListener("keydown", function (e) {
|
||||
if (e.isComposing || e.keyCode === 229) return; // 한글 조합 중 Enter 는 조합 확정
|
||||
if (e.key === "ArrowDown") { e.preventDefault(); moveActive(1); }
|
||||
else if (e.key === "ArrowUp") { e.preventDefault(); moveActive(-1); }
|
||||
else if (e.key === "Enter") { e.preventDefault(); pickHit(activeHit); }
|
||||
else if (e.key === "Escape" && !results.hidden) { e.stopPropagation(); results.hidden = true; }
|
||||
});
|
||||
// mousedown — 검색창 blur 로 목록이 닫히기 전에 고른다
|
||||
results.addEventListener("mousedown", function (e) {
|
||||
var li = e.target.closest(".cpg-ol-hit");
|
||||
if (!li) return;
|
||||
e.preventDefault();
|
||||
pickHit(+li.dataset.index);
|
||||
});
|
||||
search.addEventListener("blur", function () { results.hidden = true; });
|
||||
// ── 입고센터 카드 ───────────────────────────────
|
||||
var cardList = [];
|
||||
function cards() { return cardList; }
|
||||
|
||||
// ── 제품 줄 ─────────────────────────────────────
|
||||
var linesTable = linesBody.closest("table");
|
||||
function syncEmpty() {
|
||||
var has = linesBody.children.length > 0;
|
||||
emptyMsg.hidden = has;
|
||||
linesTable.hidden = !has;
|
||||
function renumber() {
|
||||
cardList.forEach(function (c, i) {
|
||||
c.no.textContent = "입고센터 " + (i + 1);
|
||||
c.del.hidden = cardList.length < 2;
|
||||
});
|
||||
}
|
||||
function addLine(code, name) {
|
||||
var existing = Array.prototype.find.call(linesBody.children, function (tr) { return tr.dataset.code === code; });
|
||||
if (existing) { existing.querySelector(".cpg-ol-qty").focus(); return; }
|
||||
var tr = document.createElement("tr");
|
||||
tr.dataset.code = code;
|
||||
tr.dataset.name = name;
|
||||
var tdCode = document.createElement("td");
|
||||
tdCode.textContent = code;
|
||||
var tdName = document.createElement("td");
|
||||
tdName.textContent = name;
|
||||
var tdQty = document.createElement("td");
|
||||
var qty = document.createElement("input");
|
||||
qty.type = "number";
|
||||
qty.min = "1";
|
||||
qty.step = "1";
|
||||
qty.className = "erp-input cpg-ol-qty";
|
||||
qty.setAttribute("aria-label", name + " 수량");
|
||||
tdQty.appendChild(qty);
|
||||
var tdDel = document.createElement("td");
|
||||
var del = document.createElement("button");
|
||||
del.type = "button";
|
||||
del.className = "cpg-icon-btn is-danger";
|
||||
del.textContent = "삭제";
|
||||
del.addEventListener("click", function () { tr.remove(); syncEmpty(); });
|
||||
tdDel.appendChild(del);
|
||||
tr.appendChild(tdCode); tr.appendChild(tdName); tr.appendChild(tdQty); tr.appendChild(tdDel);
|
||||
linesBody.appendChild(tr);
|
||||
|
||||
function createCard() {
|
||||
var el = centerTpl.content.firstElementChild.cloneNode(true);
|
||||
function q(sel) { return el.querySelector(sel); }
|
||||
var card = {
|
||||
el: el,
|
||||
no: q(".cpg-ol-center-no"),
|
||||
del: q(".cpg-ol-center-del"),
|
||||
centerSel: q(".cpg-ol-center-sel"),
|
||||
centerNew: q(".cpg-ol-center-new"),
|
||||
centerCustom: q(".cpg-ol-center-custom"),
|
||||
method: q(".cpg-ol-method"),
|
||||
outbound: q(".cpg-ol-outbound"),
|
||||
search: q(".cpg-ol-search-input"),
|
||||
results: q(".cpg-ol-results"),
|
||||
linesTable: q(".cpg-ol-lines"),
|
||||
linesBody: q(".cpg-ol-lines tbody"),
|
||||
emptyMsg: q(".cpg-ol-empty"),
|
||||
};
|
||||
card.method.value = DEFAULT_METHOD;
|
||||
|
||||
card.fillCenters = function () {
|
||||
var sel = card.centerSel, keep = sel.value;
|
||||
sel.innerHTML = "";
|
||||
function add(value, label) {
|
||||
var o = document.createElement("option");
|
||||
o.value = value;
|
||||
o.textContent = label;
|
||||
sel.appendChild(o);
|
||||
}
|
||||
if (centerNames === null) { add("", "불러오는 중…"); return; }
|
||||
add("", centerNames.length ? "센터 선택" : "센터 목록 없음");
|
||||
centerNames.forEach(function (n) { add(n, n); });
|
||||
add(NEW_CENTER, "+ 직접 입력");
|
||||
if (keep && (keep === NEW_CENTER || centerNames.indexOf(keep) >= 0)) sel.value = keep;
|
||||
card.centerCustom.hidden = sel.value !== NEW_CENTER;
|
||||
};
|
||||
card.centerSel.addEventListener("change", function () {
|
||||
card.centerCustom.hidden = card.centerSel.value !== NEW_CENTER;
|
||||
if (!card.centerCustom.hidden) card.centerNew.focus();
|
||||
});
|
||||
|
||||
// 제품 검색(코드표)
|
||||
var hits = [], activeHit = -1;
|
||||
function renderResults() {
|
||||
var results = card.results;
|
||||
results.innerHTML = "";
|
||||
var text = card.search.value.trim().toLowerCase();
|
||||
if (!text) { results.hidden = true; return; }
|
||||
hits = (products || []).filter(function (p) {
|
||||
return p.code.toLowerCase().indexOf(text) >= 0 || p.name.toLowerCase().indexOf(text) >= 0;
|
||||
}).slice(0, 30);
|
||||
activeHit = hits.length ? 0 : -1;
|
||||
if (!hits.length) {
|
||||
var li = document.createElement("li");
|
||||
li.className = "cpg-ol-noresult";
|
||||
li.textContent = productsReason ? "코드표를 불러오지 못했습니다: " + productsReason : "검색 결과가 없습니다.";
|
||||
results.appendChild(li);
|
||||
}
|
||||
hits.forEach(function (p, i) {
|
||||
var li = document.createElement("li");
|
||||
li.className = "cpg-ol-hit" + (i === activeHit ? " is-active" : "");
|
||||
li.dataset.index = String(i);
|
||||
var code = document.createElement("b");
|
||||
code.textContent = p.code;
|
||||
var name = document.createElement("span");
|
||||
name.textContent = p.name;
|
||||
li.appendChild(code);
|
||||
li.appendChild(name);
|
||||
results.appendChild(li);
|
||||
});
|
||||
results.hidden = false;
|
||||
}
|
||||
function moveActive(step) {
|
||||
if (!hits.length) return;
|
||||
activeHit = (activeHit + step + hits.length) % hits.length;
|
||||
Array.prototype.forEach.call(card.results.querySelectorAll(".cpg-ol-hit"), function (li, i) {
|
||||
li.classList.toggle("is-active", i === activeHit);
|
||||
if (i === activeHit) li.scrollIntoView({ block: "nearest" });
|
||||
});
|
||||
}
|
||||
function pickHit(i) {
|
||||
var p = hits[i];
|
||||
if (!p) return;
|
||||
addLine(p.code, p.name);
|
||||
card.search.value = "";
|
||||
card.results.hidden = true;
|
||||
}
|
||||
card.search.addEventListener("input", renderResults);
|
||||
card.search.addEventListener("keydown", function (e) {
|
||||
if (e.isComposing || e.keyCode === 229) return; // 한글 조합 중 Enter 는 조합 확정
|
||||
if (e.key === "ArrowDown") { e.preventDefault(); moveActive(1); }
|
||||
else if (e.key === "ArrowUp") { e.preventDefault(); moveActive(-1); }
|
||||
else if (e.key === "Enter") { e.preventDefault(); pickHit(activeHit); }
|
||||
else if (e.key === "Escape" && !card.results.hidden) { e.stopPropagation(); card.results.hidden = true; }
|
||||
});
|
||||
// mousedown — 검색창 blur 로 목록이 닫히기 전에 고른다
|
||||
card.results.addEventListener("mousedown", function (e) {
|
||||
var li = e.target.closest(".cpg-ol-hit");
|
||||
if (!li) return;
|
||||
e.preventDefault();
|
||||
pickHit(+li.dataset.index);
|
||||
});
|
||||
card.search.addEventListener("blur", function () { card.results.hidden = true; });
|
||||
|
||||
// 제품 줄
|
||||
function syncEmpty() {
|
||||
var has = card.linesBody.children.length > 0;
|
||||
card.emptyMsg.hidden = has;
|
||||
card.linesTable.hidden = !has;
|
||||
}
|
||||
function addLine(code, name) {
|
||||
var existing = Array.prototype.find.call(card.linesBody.children, function (tr) { return tr.dataset.code === code; });
|
||||
if (existing) { existing.querySelector(".cpg-ol-qty").focus(); return; }
|
||||
var tr = document.createElement("tr");
|
||||
tr.dataset.code = code;
|
||||
tr.dataset.name = name;
|
||||
var tdCode = document.createElement("td");
|
||||
tdCode.textContent = code;
|
||||
var tdName = document.createElement("td");
|
||||
tdName.textContent = name;
|
||||
var tdQty = document.createElement("td");
|
||||
var qty = document.createElement("input");
|
||||
qty.type = "number";
|
||||
qty.min = "1";
|
||||
qty.step = "1";
|
||||
qty.className = "erp-input cpg-ol-qty";
|
||||
qty.setAttribute("aria-label", name + " 수량");
|
||||
tdQty.appendChild(qty);
|
||||
var tdDel = document.createElement("td");
|
||||
var del = document.createElement("button");
|
||||
del.type = "button";
|
||||
del.className = "cpg-icon-btn is-danger";
|
||||
del.textContent = "삭제";
|
||||
del.addEventListener("click", function () { tr.remove(); syncEmpty(); });
|
||||
tdDel.appendChild(del);
|
||||
tr.appendChild(tdCode); tr.appendChild(tdName); tr.appendChild(tdQty); tr.appendChild(tdDel);
|
||||
card.linesBody.appendChild(tr);
|
||||
syncEmpty();
|
||||
qty.focus();
|
||||
}
|
||||
syncEmpty();
|
||||
qty.focus();
|
||||
|
||||
card.del.addEventListener("click", function () {
|
||||
if (busy || cardList.length < 2) return;
|
||||
cardList.splice(cardList.indexOf(card), 1);
|
||||
el.remove();
|
||||
renumber();
|
||||
});
|
||||
|
||||
card.collect = function (no) {
|
||||
var label = cardList.length > 1 ? "입고센터 " + no + ": " : "";
|
||||
var center = card.centerSel.value === NEW_CENTER ? card.centerNew.value.trim() : card.centerSel.value;
|
||||
var lines = Array.prototype.map.call(card.linesBody.children, function (tr) {
|
||||
return { code: tr.dataset.code, name: tr.dataset.name, quantity: tr.querySelector(".cpg-ol-qty").value };
|
||||
});
|
||||
if (!center) return { error: label + "입고센터를 선택해 주세요.", focus: card.centerSel };
|
||||
if (!lines.length) return { error: label + "제품을 1개 이상 추가해 주세요.", focus: card.search };
|
||||
for (var i = 0; i < lines.length; i++) {
|
||||
if (!(parseInt(lines[i].quantity, 10) > 0)) {
|
||||
return { error: label + lines[i].name + "의 수량을 입력해 주세요.",
|
||||
focus: card.linesBody.children[i].querySelector(".cpg-ol-qty") };
|
||||
}
|
||||
}
|
||||
return { body: { center: center, ship_method: card.method.value, outbound: card.outbound.value.trim(), lines: lines } };
|
||||
};
|
||||
|
||||
cardList.push(card);
|
||||
centersBox.appendChild(el);
|
||||
card.fillCenters();
|
||||
renumber();
|
||||
return card;
|
||||
}
|
||||
|
||||
addCenterBtn.addEventListener("click", function () {
|
||||
if (busy) return;
|
||||
var card = createCard();
|
||||
card.el.scrollIntoView({ block: "nearest" });
|
||||
card.centerSel.focus();
|
||||
});
|
||||
|
||||
// ── 진행 막대 ───────────────────────────────────
|
||||
// 서버가 단계마다 {progress, until} 을 보낸다. 내려받기·올리기처럼 오래 걸리는 단계 동안에도 멈춰 보이지 않게
|
||||
// 다음 단계(until) 바로 앞까지 조금씩 채운다.
|
||||
var shown = 0, floor = 0, ceil = 0, creepTimer = 0;
|
||||
function paintProgress() {
|
||||
var pct = Math.round(shown);
|
||||
progressBar.style.width = pct + "%";
|
||||
progressPct.textContent = pct + "%";
|
||||
progressTrack.setAttribute("aria-valuenow", String(pct));
|
||||
}
|
||||
function setProgress(p, until, step) {
|
||||
floor = Math.max(floor, p);
|
||||
ceil = Math.max(floor, (until || p) - 1);
|
||||
if (p >= 100) ceil = floor = 100;
|
||||
shown = Math.max(shown, floor);
|
||||
if (step) progressStep.textContent = step;
|
||||
paintProgress();
|
||||
}
|
||||
function startProgress() {
|
||||
shown = floor = 0;
|
||||
ceil = 4;
|
||||
progressBox.classList.remove("is-error");
|
||||
progressStep.textContent = "준비 중";
|
||||
progressBox.hidden = false;
|
||||
paintProgress();
|
||||
clearInterval(creepTimer);
|
||||
creepTimer = setInterval(function () {
|
||||
if (shown < ceil) {
|
||||
shown = Math.min(ceil, shown + Math.max(0.3, (ceil - shown) * 0.08));
|
||||
paintProgress();
|
||||
}
|
||||
}, 200);
|
||||
}
|
||||
function stopProgress(error) {
|
||||
clearInterval(creepTimer);
|
||||
if (error) {
|
||||
progressBox.classList.add("is-error");
|
||||
progressStep.textContent = "기록하지 못했습니다";
|
||||
}
|
||||
}
|
||||
|
||||
// ── 열기 / 닫기 ─────────────────────────────────
|
||||
@@ -215,16 +337,12 @@
|
||||
shipDate.value = "";
|
||||
arrivalDate.value = "";
|
||||
arrivalAuto = true;
|
||||
centerSel.value = "";
|
||||
centerNew.value = "";
|
||||
centerCustom.hidden = true;
|
||||
method.value = "파렛트";
|
||||
outbound.value = "";
|
||||
worker.value = defaultWorker;
|
||||
search.value = "";
|
||||
results.hidden = true;
|
||||
linesBody.innerHTML = "";
|
||||
syncEmpty();
|
||||
cardList = [];
|
||||
centersBox.innerHTML = "";
|
||||
createCard();
|
||||
stopProgress(false);
|
||||
progressBox.hidden = true;
|
||||
showError("");
|
||||
updateTarget();
|
||||
}
|
||||
@@ -249,56 +367,100 @@
|
||||
|
||||
// ── 완료 ────────────────────────────────────────
|
||||
function collect() {
|
||||
var center = centerSel.value === NEW_CENTER ? centerNew.value.trim() : centerSel.value;
|
||||
var lines = Array.prototype.map.call(linesBody.children, function (tr) {
|
||||
return { code: tr.dataset.code, name: tr.dataset.name, quantity: tr.querySelector(".cpg-ol-qty").value };
|
||||
});
|
||||
if (!docDate.value) return { error: "작성일을 선택해 주세요." };
|
||||
if (!shipDate.value) return { error: "출고일을 선택해 주세요." };
|
||||
if (!arrivalDate.value) return { error: "센터입고일을 선택해 주세요." };
|
||||
if (!center) return { error: "입고센터를 선택해 주세요." };
|
||||
if (!lines.length) return { error: "제품을 1개 이상 추가해 주세요." };
|
||||
for (var i = 0; i < lines.length; i++) {
|
||||
if (!(parseInt(lines[i].quantity, 10) > 0)) return { error: lines[i].name + "의 수량을 입력해 주세요." };
|
||||
var centers = [];
|
||||
for (var i = 0; i < cardList.length; i++) {
|
||||
var got = cardList[i].collect(i + 1);
|
||||
if (got.error) return got;
|
||||
centers.push(got.body);
|
||||
}
|
||||
return {
|
||||
body: {
|
||||
document_date: docDate.value,
|
||||
ship_date: shipDate.value,
|
||||
center_arrival_date: arrivalDate.value,
|
||||
center: center,
|
||||
ship_method: method.value,
|
||||
outbound: outbound.value.trim(),
|
||||
worker: worker.value.trim(),
|
||||
lines: lines,
|
||||
centers: centers,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function setBusy(on) {
|
||||
busy = on;
|
||||
submitBtn.disabled = on;
|
||||
addCenterBtn.disabled = on;
|
||||
submitBtn.textContent = on ? "기록 중…" : "완료";
|
||||
}
|
||||
|
||||
// NDJSON 응답을 한 줄씩 읽어 onEvent 로 넘긴다. 마지막 줄(done/error)을 돌려준다.
|
||||
function readEvents(res, onEvent) {
|
||||
var last = null, buffered = "";
|
||||
function feed(text) {
|
||||
buffered += text;
|
||||
var parts = buffered.split("\n");
|
||||
buffered = parts.pop();
|
||||
parts.forEach(function (line) {
|
||||
if (!line.trim()) return;
|
||||
var ev = JSON.parse(line);
|
||||
last = ev;
|
||||
onEvent(ev);
|
||||
});
|
||||
}
|
||||
if (!res.body || !res.body.getReader || !window.TextDecoder) {
|
||||
return res.text().then(function (t) { feed(t + "\n"); return last; });
|
||||
}
|
||||
var reader = res.body.getReader(), decoder = new TextDecoder();
|
||||
function pump() {
|
||||
return reader.read().then(function (r) {
|
||||
if (r.done) { feed(decoder.decode() + "\n"); return last; }
|
||||
feed(decoder.decode(r.value, { stream: true }));
|
||||
return pump();
|
||||
});
|
||||
}
|
||||
return pump();
|
||||
}
|
||||
|
||||
submitBtn.addEventListener("click", function () {
|
||||
if (busy) return;
|
||||
var got = collect();
|
||||
if (got.error) { showError(got.error); return; }
|
||||
if (got.error) {
|
||||
showError(got.error);
|
||||
if (got.focus) got.focus.focus();
|
||||
return;
|
||||
}
|
||||
showError("");
|
||||
busy = true;
|
||||
submitBtn.disabled = true;
|
||||
submitBtn.textContent = "기록 중…";
|
||||
fetch("/cupang/api/outbound-sheet", {
|
||||
setBusy(true);
|
||||
startProgress();
|
||||
fetch("/cupang/api/outbound-sheet?stream=1", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", Accept: "application/json" },
|
||||
headers: { "Content-Type": "application/json", Accept: "application/x-ndjson, application/json" },
|
||||
body: JSON.stringify(got.body),
|
||||
})
|
||||
.then(function (res) {
|
||||
return res.json().catch(function () { return {}; }).then(function (data) {
|
||||
if (!res.ok) throw new Error(typeof data.detail === "string" ? data.detail : "출고리스트 파일에 기록하지 못했습니다.");
|
||||
return data;
|
||||
if (!res.ok) {
|
||||
return res.json().catch(function () { return {}; }).then(function (data) {
|
||||
throw new Error(typeof data.detail === "string" ? data.detail : "출고리스트 파일에 기록하지 못했습니다.");
|
||||
});
|
||||
}
|
||||
return readEvents(res, function (ev) {
|
||||
if (ev.progress != null) setProgress(ev.progress, ev.until, ev.step);
|
||||
});
|
||||
})
|
||||
.then(function (data) {
|
||||
busy = false;
|
||||
if (!data || data.error || !data.done) {
|
||||
throw new Error((data && data.error) || "출고리스트 파일에 기록하지 못했습니다.");
|
||||
}
|
||||
setProgress(100, 100, "완료");
|
||||
stopProgress(false);
|
||||
setBusy(false);
|
||||
close();
|
||||
var msg = "'" + data.title + "' 시트 " + data.first_row + "~" + data.last_row + "행에 " +
|
||||
data.line_count + "개 제품을 추가했습니다.";
|
||||
var where = (data.centers || []).map(function (c) {
|
||||
return "· " + c.center + " — " + c.first_row + "~" + c.last_row + "행 (" + c.line_count + "개 제품)";
|
||||
}).join("\n");
|
||||
var msg = "'" + data.title + "' 시트에 입고센터 " + (data.centers || []).length + "곳, " +
|
||||
data.line_count + "개 제품을 추가했습니다." + (where ? "\n" + where : "");
|
||||
if (window.erpConfirm && data.url) {
|
||||
window.erpConfirm(msg + "\n출고리스트 엑셀을 열어 볼까요?", { tone: "ok", okText: "파일 열기", cancelText: "닫기" })
|
||||
.then(function (ok) { if (ok) window.open(data.url, "_blank", "noopener"); });
|
||||
@@ -306,11 +468,10 @@
|
||||
window.alert(msg);
|
||||
}
|
||||
})
|
||||
.catch(function (err) { showError(err.message); })
|
||||
.finally(function () {
|
||||
busy = false;
|
||||
submitBtn.disabled = false;
|
||||
submitBtn.textContent = "완료";
|
||||
});
|
||||
.catch(function (err) {
|
||||
stopProgress(true);
|
||||
showError(err.message);
|
||||
})
|
||||
.finally(function () { setBusy(false); });
|
||||
});
|
||||
})();
|
||||
|
||||
+22
-3
@@ -1608,7 +1608,7 @@ a.cpg-boxno-dl:hover { background: #1a5c38; border-color: #1a5c38; font-weight:
|
||||
.cpg-btn-excel { background: #217346; color: #fff; padding: 8px 16px; }
|
||||
.cpg-btn-excel:hover { background: #185c37; }
|
||||
.cpg-btn-excel:disabled { opacity: .6; cursor: default; }
|
||||
.cpg-ol-box { width: min(760px, calc(100vw - 32px)); max-height: calc(100vh - 48px); overflow-y: auto; gap: 12px; }
|
||||
.cpg-ol-box { width: min(820px, calc(100vw - 32px)); max-height: calc(100vh - 48px); overflow-y: auto; gap: 12px; }
|
||||
.cpg-ol-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 10px; }
|
||||
.cpg-ol-grid-2 { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
.cpg-ol-box .erp-input { box-sizing: border-box; }
|
||||
@@ -1642,6 +1642,25 @@ a.cpg-boxno-dl:hover { background: #1a5c38; border-color: #1a5c38; font-weight:
|
||||
.cpg-ol-target { margin: 0; font-size: 12px; }
|
||||
.cpg-ol-error { margin: 0; font-size: 13px; color: #c22b10; }
|
||||
.cpg-ol-actions { display: flex; gap: 6px; justify-content: flex-end; }
|
||||
@media (max-width: 640px) {
|
||||
.cpg-ol-grid, .cpg-ol-grid-2 { grid-template-columns: minmax(0, 1fr); }
|
||||
.cpg-ol-grid-4 { grid-template-columns: repeat(4, minmax(0, 1fr)); }
|
||||
/* 입고센터 카드 — 센터마다 출고방식·제품·출고 */
|
||||
.cpg-ol-centers { display: flex; flex-direction: column; gap: 10px; }
|
||||
.cpg-ol-center {
|
||||
display: flex; flex-direction: column; gap: 10px; padding: 12px;
|
||||
border: 1px solid var(--color-subtle-ash); border-radius: 10px; background: #f7faf8;
|
||||
}
|
||||
.cpg-ol-center-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
|
||||
.cpg-ol-center-no { font-size: 14px; color: #217346; }
|
||||
.cpg-ol-center-del[hidden] { display: none; }
|
||||
.cpg-ol-add-center { align-self: flex-start; }
|
||||
/* 완료 진행 막대 */
|
||||
.cpg-ol-progress { display: flex; flex-direction: column; gap: 6px; }
|
||||
.cpg-ol-progress[hidden] { display: none; }
|
||||
.cpg-ol-progress-top { display: flex; justify-content: space-between; gap: 8px; font-size: 13px; color: var(--color-rich-black); }
|
||||
.cpg-ol-progress-top b { color: #217346; font-variant-numeric: tabular-nums; }
|
||||
.cpg-ol-progress-track { height: 12px; border-radius: 999px; background: #e3ece6; overflow: hidden; }
|
||||
.cpg-ol-progress-bar { width: 0; height: 100%; border-radius: 999px; background: #217346; transition: width .25s ease; }
|
||||
.cpg-ol-progress.is-error .cpg-ol-progress-bar { background: #c22b10; }
|
||||
@media (max-width: 640px) {
|
||||
.cpg-ol-grid, .cpg-ol-grid-2, .cpg-ol-grid-4 { grid-template-columns: minmax(0, 1fr); }
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user