Merge branch 'feat/cupang-outbound-multi-center'

This commit is contained in:
2026-10-23 16:20:26 +09:00
8 changed files with 763 additions and 282 deletions
+12 -7
View File
@@ -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
View File
@@ -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")
+50 -30
View File
@@ -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
View File
@@ -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
View File
@@ -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); }
}
+3 -2
View File
@@ -95,8 +95,9 @@ NODE_PATH=<playwright 또는 playwright-core 경로> PJ_TEST_BROWSER=<Chrome/Edg
# 쿠팡 밀크런 출고리스트 작성 팝업 (Playwright, 2026-10-23)
`cupang/index.html` + `static/cupang-outbound.js` — "+ 신규 등록" 옆 엑셀색 버튼, 프로젝트 날짜 팝업(작성일 오늘·센터입고일 = 출고일+1),
입고센터 목록·직접 입력, 코드표 검색으로 제품 추가, [완료] 요청 값·성공 안내·실패 시 입력 유지, Esc, 390px 화면을 가짜 서버로 확인한다.
구글 시트·DB 연결 없음(시트 쓰기 자체는 `tests/test_cupang_outbound_sheet.py`).
입고센터 카드(추가·삭제·번호, 출고방식 기본 택배)·직접 입력, 코드표 검색으로 제품 추가, [완료] 요청 값·진행 막대와 %(가짜 서버가 NDJSON 으로
단계를 보내고 올리기 단계에서 멈춰 둠)·성공 안내·실패 시 빨간 막대와 입력 유지, Esc, 390px 화면을 가짜 서버로 확인한다.
구글·DB 연결 없음(엑셀 쓰기 자체는 `tests/test_cupang_outbound_sheet.py`).
```bash
python tests/js/render_cupang_index.py # → tests/js/.out/cupang_index_render.html
+137 -53
View File
@@ -10,6 +10,7 @@ const ROOT = path.resolve(__dirname, "../..");
const STATIC = path.join(ROOT, "app/static");
const OUT = path.join(__dirname, ".out");
const posts = [];
let releaseUpload = null; // 올리기 단계에서 멈춰 두었다가 진행 막대를 확인한 뒤 풀어 준다
const PRODUCTS = [
{ code: "MT-7000", name: "점보 7,000ml", type: "단품" },
@@ -23,6 +24,35 @@ function json(res, status, body) {
res.end(JSON.stringify(body));
}
// 실제 서버처럼 진행 상황을 NDJSON 한 줄씩
function streamWrite(res, body) {
res.statusCode = 200;
res.setHeader("Content-Type", "application/x-ndjson");
const send = ev => res.write(JSON.stringify(ev) + "\n");
send({ progress: 5, until: 40, step: "출고리스트 엑셀 내려받는 중" });
if (body.centers.some(c => c.center === "실패센터")) {
send({ error: "출고리스트 파일에 기록하지 못했습니다(HttpError). 잠시 후 다시 시도해 주세요." });
res.end();
return;
}
const n = body.centers.length;
body.centers.forEach((c, i) => send({ progress: 40 + Math.floor(40 * i / n), until: 40 + Math.floor(40 * (i + 1) / n),
step: c.center + " 추가 중 (" + (i + 1) + "/" + n + ")" }));
send({ progress: 80, until: 100, step: "출고리스트 엑셀 올리는 중" });
releaseUpload = function () {
let row = 10;
const centers = body.centers.map(c => {
const r = { center: c.center, first_row: row, last_row: row + c.lines.length - 1, line_count: c.lines.length };
row += c.lines.length;
return r;
});
send({ progress: 100, until: 100, step: "완료", done: true, ok: true, title: "20261026(월)",
first_row: 10, last_row: row - 1, line_count: centers.reduce((a, c) => a + c.line_count, 0), centers: centers,
url: "https://docs.google.com/spreadsheets/d/x/edit" });
res.end();
};
}
const server = http.createServer(function (req, res) {
const url = new URL(req.url, "http://localhost");
if (url.pathname === "/cupang/") {
@@ -36,10 +66,9 @@ const server = http.createServer(function (req, res) {
req.on("data", c => { raw += c; });
req.on("end", function () {
const body = JSON.parse(raw);
posts.push(body);
if (body.center === "실패센터") return json(res, 502, { detail: "출고리스트 파일에 기록하지 못했습니다(HttpError). 잠시 후 다시 시도해 주세요." });
json(res, 200, { ok: true, title: "20261026(월)", first_row: 10, last_row: 11, line_count: body.lines.length,
url: "https://docs.google.com/spreadsheets/d/x/edit#gid=1", created: false });
posts.push({ stream: url.searchParams.get("stream"), body: body });
if (body.centers.some(c => c.center === "잘못센터")) return json(res, 400, { detail: "2번째 입고센터: 입고센터를 입력해 주세요." });
streamWrite(res, body);
});
return;
}
@@ -62,6 +91,12 @@ async function pickDate(page, inputId, typed) {
await pop.waitFor({ state: "detached" });
}
async function addProduct(card, text, qty) {
await card.locator(".cpg-ol-search-input").fill(text);
await card.locator(".cpg-ol-search-input").press("Enter");
if (qty != null) await card.locator(".cpg-ol-qty").last().fill(String(qty));
}
(async function () {
let browser;
try {
@@ -80,86 +115,134 @@ async function pickDate(page, inputId, typed) {
assert.ok(btnBox.x > newBox.x + newBox.width - 1 && btnBox.x - (newBox.x + newBox.width) < 20, "신규 등록 바로 옆");
assert.ok(Math.abs(btnBox.y - newBox.y) < 3, "같은 줄");
assert.equal(await openBtn.evaluate(el => getComputedStyle(el).backgroundColor), "rgb(33, 115, 70)");
await page.screenshot({ path: path.join(OUT, "cupang-outbound-button.png"), clip: { x: 0, y: 0, width: 1600, height: 260 } });
// 팝업 열기 — 작성일 = 오늘(프로젝트 날짜 버튼), 작업자 = 핫프렌즈
// 팝업 열기 — 작성일 = 오늘, 작업자 = 핫프렌즈, 입고센터 카드 1장(출고방식 기본 택배, 삭제 버튼 숨김)
await openBtn.click();
await page.locator("#cpg-ol-dlg").waitFor({ state: "visible" });
assert.equal(await page.locator("#cpg-ol-doc-date + .pj-date-btn").innerText(), "calendar_month\n오늘".replace("\n", "\n"));
assert.equal(await page.locator("#cpg-ol-doc-date + .pj-date-btn").innerText(), "calendar_month\n오늘");
assert.equal(await page.locator("#cpg-ol-worker").inputValue(), "핫프렌즈");
assert.equal(await page.locator("#cpg-ol-method").inputValue(), "파렛트");
assert.deepEqual(await page.locator("#cpg-ol-method option").allInnerTexts(), ["파렛트", "택배"]);
await page.waitForFunction(() => document.querySelectorAll("#cpg-ol-center option").length === 4);
assert.deepEqual(await page.locator("#cpg-ol-center option").allInnerTexts(), ["센터 선택", "대구3", "인천32", "+ 직접 입력"]);
const cards = page.locator(".cpg-ol-center");
assert.equal(await cards.count(), 1);
const c1 = cards.nth(0);
assert.equal(await c1.locator(".cpg-ol-center-no").innerText(), "입고센터 1");
assert.ok(await c1.locator(".cpg-ol-center-del").isHidden(), "센터가 하나면 삭제 버튼 숨김");
assert.equal(await c1.locator(".cpg-ol-method").inputValue(), "택배");
assert.deepEqual(await c1.locator(".cpg-ol-method option").allInnerTexts(), ["택배", "파렛트"]);
await page.waitForFunction(() => document.querySelectorAll(".cpg-ol-center-sel option").length === 4);
assert.deepEqual(await c1.locator(".cpg-ol-center-sel option").allInnerTexts(), ["센터 선택", "대구3", "인천32", "+ 직접 입력"]);
assert.ok(await page.locator("#cpg-ol-progress").isHidden(), "처음엔 진행 막대 숨김");
// 출고일 → 센터입고일은 다음날로 자동
await pickDate(page, "cpg-ol-ship-date", "2026-10-26");
assert.equal(await page.locator("#cpg-ol-ship-date").inputValue(), "2026-10-26");
assert.equal(await page.locator("#cpg-ol-arrival-date").inputValue(), "2026-10-27");
assert.match(await page.locator("#cpg-ol-target").innerText(), /20261026\(월\)/);
// 필수값 확인
// 첫 센터: 필수값 확인 → 인천32 파렛트, 제품 2개
await page.locator("#cpg-ol-submit").click();
assert.equal(await page.locator("#cpg-ol-error").innerText(), "입고센터를 선택해 주세요.");
await page.locator("#cpg-ol-center").selectOption("인천32");
await c1.locator(".cpg-ol-center-sel").selectOption("인천32");
await page.locator("#cpg-ol-submit").click();
assert.equal(await page.locator("#cpg-ol-error").innerText(), "제품을 1개 이상 추가해 주세요.");
assert.ok(!(await page.locator(".cpg-ol-lines").isVisible()), "제품이 없으면 표를 숨김");
assert.ok(!(await c1.locator(".cpg-ol-lines").isVisible()), "제품이 없으면 표를 숨김");
await c1.locator(".cpg-ol-method").selectOption("파렛트");
await addProduct(c1, "점보", 1200);
await c1.locator(".cpg-ol-search-input").fill("ms-");
await c1.locator(".cpg-ol-hit", { hasText: "MS-1004" }).click();
await addProduct(c1, "MT-7000"); // 같은 제품은 줄을 늘리지 않는다
assert.equal(await c1.locator(".cpg-ol-lines tbody tr").count(), 2);
await c1.locator(".cpg-ol-outbound").fill("2파렛트");
// 코드표 검색 → Enter 로 첫 결과, 클릭으로 다음 결과
await page.locator("#cpg-ol-search").fill("점보");
assert.deepEqual(await page.locator(".cpg-ol-hit b").allInnerTexts(), ["MT-7000"]);
await page.locator("#cpg-ol-search").press("Enter");
await page.locator(".cpg-ol-qty").first().fill("1200");
await page.locator("#cpg-ol-search").fill("ms-");
await page.locator(".cpg-ol-hit", { hasText: "MS-1004" }).click();
assert.equal(await page.locator("#cpg-ol-lines tr").count(), 2);
assert.deepEqual(await page.locator("#cpg-ol-lines tr td:nth-child(2)").allInnerTexts(), ["점보 7,000ml", "미라네 4호세트"]);
// 센터 추가 → 2번 카드(기본 택배, 다른 센터 카드와 제품 목록 따로), 번호·삭제 버튼
await page.locator("#cpg-ol-add-center").click();
assert.equal(await cards.count(), 2);
const c2 = cards.nth(1);
assert.equal(await c2.locator(".cpg-ol-center-no").innerText(), "입고센터 2");
assert.ok(await c1.locator(".cpg-ol-center-del").isVisible() && await c2.locator(".cpg-ol-center-del").isVisible());
assert.equal(await c2.locator(".cpg-ol-method").inputValue(), "택배");
assert.equal(await c2.locator(".cpg-ol-lines tbody tr").count(), 0);
await page.locator("#cpg-ol-submit").click();
assert.equal(await page.locator("#cpg-ol-error").innerText(), "미라네 4호세트의 수량을 입력해 주세요.");
await page.locator(".cpg-ol-qty").nth(1).fill("60");
// 같은 제품을 또 고르면 줄을 늘리지 않고 그 수량 칸으로
await page.locator("#cpg-ol-search").fill("MT-7000");
await page.locator("#cpg-ol-search").press("Enter");
assert.equal(await page.locator("#cpg-ol-lines tr").count(), 2);
await page.locator("#cpg-ol-outbound").fill("2파렛트");
await page.screenshot({ path: path.join(OUT, "cupang-outbound-dialog.png") });
assert.equal(await page.locator("#cpg-ol-error").innerText(), "입고센터 1: 미라네 4호세트의 수량을 입력해 주세요.");
await c1.locator(".cpg-ol-qty").nth(1).fill("60");
await page.locator("#cpg-ol-submit").click();
assert.equal(await page.locator("#cpg-ol-error").innerText(), "입고센터 2: 입고센터를 선택해 주세요.");
await c2.locator(".cpg-ol-center-sel").selectOption("__new__");
await c2.locator(".cpg-ol-center-new").fill("이천1");
await addProduct(c2, "중형", 30);
// 3번 카드를 만든 뒤 가운데(이천1) 카드를 지우면 번호가 다시 매겨진다
await page.locator("#cpg-ol-add-center").click();
assert.equal(await cards.count(), 3);
await cards.nth(1).locator(".cpg-ol-center-del").click();
assert.equal(await cards.count(), 2);
const c2b = cards.nth(1);
assert.equal(await c2b.locator(".cpg-ol-center-no").innerText(), "입고센터 2");
assert.equal(await c2b.locator(".cpg-ol-lines tbody tr").count(), 0, "지운 카드의 제품은 따라오지 않음");
await c2b.locator(".cpg-ol-center-sel").selectOption("대구3");
await addProduct(c2b, "중형", 30);
await page.screenshot({ path: path.join(OUT, "cupang-outbound-dialog.png"), fullPage: true });
// 완료 → 서버로 보낸 값, 성공 안내
// 완료 → 진행 막대·% (올리기 단계에서 멈춘 동안 확인) → 성공 안내
await page.locator("#cpg-ol-submit").click();
await page.locator("#cpg-ol-progress").waitFor({ state: "visible" });
await page.waitForFunction(() => document.getElementById("cpg-ol-progress-step").textContent === "출고리스트 엑셀 올리는 중");
await page.waitForTimeout(600);
const mid = await page.evaluate(() => ({
pct: document.getElementById("cpg-ol-progress-pct").textContent,
width: parseFloat(document.getElementById("cpg-ol-progress-bar").style.width),
aria: document.getElementById("cpg-ol-progress-track").getAttribute("aria-valuenow"),
}));
assert.ok(mid.width >= 80 && mid.width < 100, "올리는 중엔 80~99% — " + mid.width);
assert.equal(mid.pct, Math.round(mid.width) + "%");
assert.equal(mid.aria, String(Math.round(mid.width)));
assert.equal(await page.locator("#cpg-ol-submit").innerText(), "기록 중…");
assert.ok(await page.locator("#cpg-ol-add-center").isDisabled(), "기록 중엔 센터 추가 막음");
await page.screenshot({ path: path.join(OUT, "cupang-outbound-progress.png") });
releaseUpload();
await page.locator(".erp-dialog").waitFor({ state: "visible" });
assert.match(await page.locator(".erp-dialog").innerText(), /'20261026\(월\)' 시트 10~11행에 2개 제품을 추가했습니다/);
assert.deepEqual(posts[0], {
const done = await page.locator(".erp-dialog").innerText();
assert.match(done, /'20261026\(월\)' 시트에 입고센터 2곳, 3개 제품을 추가했습니다/);
assert.match(done, /인천32 — 10~11행 \(2개 제품\)/);
assert.match(done, /대구3 — 12~12행 \(1개 제품\)/);
assert.equal(posts[0].stream, "1");
assert.deepEqual(posts[0].body, {
document_date: await page.evaluate(() => new Date(Date.now() + 9 * 3600000).toISOString().slice(0, 10)),
ship_date: "2026-10-26", center_arrival_date: "2026-10-27", center: "인천32", ship_method: "파렛트",
outbound: "2파렛트", worker: "핫프렌즈",
lines: [{ code: "MT-7000", name: "점보 7,000ml", quantity: "1200" }, { code: "MS-1004", name: "미라네 4호세트", quantity: "60" }],
ship_date: "2026-10-26", center_arrival_date: "2026-10-27", worker: "핫프렌즈",
centers: [
{ center: "인천32", ship_method: "파렛트", outbound: "2파렛트",
lines: [{ code: "MT-7000", name: "점보 7,000ml", quantity: "1200" }, { code: "MS-1004", name: "미라네 4호세트", quantity: "60" }] },
{ center: "대구3", ship_method: "택배", outbound: "",
lines: [{ code: "MT-3000", name: "중형 3,000ml", quantity: "30" }] },
],
});
assert.ok(await page.locator("#cpg-ol-dlg").isHidden(), "성공하면 팝업 닫힘");
await page.screenshot({ path: path.join(OUT, "cupang-outbound-done.png") });
await page.locator(".erp-dialog button", { hasText: "닫기" }).click();
// 다시 열면 비어 있고, 센터 직접 입력 + 실패 응답은 팝업 안에 보여 준다
// 다시 열면 카드 1장·빈 상태, 진행 막대 숨김. 직접 입력 센터 + 실패(스트림 중 오류)는 막대 빨강 + 팝업 안 안내
await openBtn.click();
assert.equal(await page.locator("#cpg-ol-lines tr").count(), 0);
assert.equal(await page.locator("#cpg-ol-ship-date").inputValue(), "");
assert.equal(await cards.count(), 1);
assert.equal(await cards.nth(0).locator(".cpg-ol-lines tbody tr").count(), 0);
assert.equal(await cards.nth(0).locator(".cpg-ol-method").inputValue(), "택배");
assert.ok(await page.locator("#cpg-ol-progress").isHidden());
await pickDate(page, "cpg-ol-ship-date", "10/30");
await pickDate(page, "cpg-ol-arrival-date", "11/2");
await pickDate(page, "cpg-ol-ship-date", "10/31");
assert.equal(await page.locator("#cpg-ol-arrival-date").inputValue(), "2026-11-02", "직접 고른 센터입고일은 유지");
await page.waitForFunction(() => document.querySelectorAll("#cpg-ol-center option").length === 4);
await page.locator("#cpg-ol-center").selectOption("__new__");
await page.locator("#cpg-ol-center-new").fill("실패센터");
await page.locator("#cpg-ol-method").selectOption("택배");
await page.locator("#cpg-ol-search").fill("중형");
await page.locator("#cpg-ol-search").press("Enter");
await page.locator(".cpg-ol-qty").first().fill("5");
await page.waitForFunction(() => document.querySelectorAll(".cpg-ol-center-sel option").length === 4);
const f1 = cards.nth(0);
await f1.locator(".cpg-ol-center-sel").selectOption("__new__");
await f1.locator(".cpg-ol-center-new").fill("실패센터");
await addProduct(f1, "중형", 5);
await page.locator("#cpg-ol-submit").click();
await page.waitForFunction(() => !document.getElementById("cpg-ol-error").hidden);
assert.match(await page.locator("#cpg-ol-error").innerText(), /출고리스트 파일에 기록하지 못했습니다/);
assert.ok(await page.locator("#cpg-ol-progress").evaluate(el => el.classList.contains("is-error")));
assert.ok(await page.locator("#cpg-ol-dlg").isVisible(), "실패하면 입력 유지");
assert.equal(posts[1].center, "실패센터");
assert.equal(posts[1].ship_method, "택배");
assert.equal(await page.locator("#cpg-ol-submit").innerText(), "완료");
assert.equal(posts[1].body.centers[0].center, "실패센터");
// 서버 입력 오류(400, 스트림 전)도 팝업 안에 보여 준다
await f1.locator(".cpg-ol-center-new").fill("잘못센터");
await page.locator("#cpg-ol-submit").click();
await page.waitForFunction(() => /2번째 입고센터/.test(document.getElementById("cpg-ol-error").textContent));
// Esc: 날짜 팝업이 떠 있으면 그것만 닫고, 다음 Esc 에 출고리스트 팝업 닫힘
await page.locator("#cpg-ol-doc-date + .pj-date-btn").click();
@@ -171,9 +254,10 @@ async function pickDate(page, inputId, typed) {
await page.keyboard.press("Escape");
assert.ok(await page.locator("#cpg-ol-dlg").isHidden());
// 좁은 화면에서도 가로 넘침 없음
// 좁은 화면에서도 가로 넘침 없음(센터 2장)
await page.setViewportSize({ width: 390, height: 844 });
await openBtn.click();
await page.locator("#cpg-ol-add-center").click();
const over = await page.evaluate(() => {
const box = document.querySelector(".cpg-ol-box");
return box.scrollWidth - box.clientWidth;
@@ -182,7 +266,7 @@ async function pickDate(page, inputId, typed) {
await page.screenshot({ path: path.join(OUT, "cupang-outbound-mobile.png") });
assert.deepEqual(errors, [], "브라우저 JS 오류 없음");
console.log("ALL PASS — 버튼 위치·색, 프로젝트 날짜 팝업, 센터 목록·직접 입력, 코드표 검색, 완료·실패, Esc, 모바일");
console.log("ALL PASS — 버튼, 날짜 팝업, 입고센터 카드(추가·삭제·번호·기본 택배), 코드표 검색, 진행 막대·%, 완료·실패, Esc, 모바일");
} finally {
if (browser) await browser.close();
await new Promise(resolve => server.close(resolve));
+85
View File
@@ -392,6 +392,91 @@ def test_sheet_target_picks_writer_by_drive_file_type(monkeypatch):
assert cupang_router._sheet_target(None)[2]["skipped"] is True
def _multi_payload() -> dict[str, Any]:
base = _payload()
return {
"document_date": base["document_date"], "ship_date": base["ship_date"],
"center_arrival_date": base["center_arrival_date"], "worker": "",
"centers": [
{"center": "인천32", "ship_method": "파렛트", "outbound": "2파렛트", "lines": base["lines"]},
{"center": "대구3", "ship_method": "택배", "outbound": "",
"lines": [{"code": "MT-3000", "name": "중형", "quantity": 30}]},
],
}
def test_clean_entries_per_center_shares_dates_and_worker():
entries = cupang_router._clean_outbound_entries(_multi_payload())
assert [e["center_name_snapshot"] for e in entries] == ["인천32", "대구3"]
assert [e["ship_method"] for e in entries] == ["파렛트", "택배"]
assert all(e["ship_date"] == "2026-10-26" and e["worker"] == WORKER for e in entries)
assert len(cupang_router._clean_outbound_entries(_payload())) == 1 # centers 없으면 센터 1곳
@pytest.mark.parametrize("centers, words", [
([], "1곳 이상"),
([{"center": "a", "ship_method": "택배", "lines": [{"code": "A", "name": "가", "quantity": 1}]}] * 21, "20곳"),
([{"center": "a", "ship_method": "택배", "lines": [{"code": "A", "name": "가", "quantity": 1}]},
{"center": "", "ship_method": "택배", "lines": [{"code": "A", "name": "가", "quantity": 1}]}], "2번째 입고센터: 입고센터"),
])
def test_clean_entries_rejects_bad_centers(centers, words):
with pytest.raises(HTTPException) as err:
cupang_router._clean_outbound_entries({**_multi_payload(), "centers": centers})
assert err.value.status_code == 400 and words in err.value.detail
def test_xlsx_multi_center_one_download_one_upload_with_progress():
drive = FakeDrive(_xlsx_bytes({"20261026(월)": _sheet_rows(4)}))
steps: list[tuple[int, int, str]] = []
res = cupang_router._run_outbound_write(
_xlsx_writer(drive), "f", cupang_router._clean_outbound_entries(_multi_payload()),
lambda p, until, step: steps.append((p, until, step)))
assert drive.uploads == 1
assert [(c["center"], c["first_row"], c["last_row"]) for c in res["centers"]] == [("인천32", 10, 11), ("대구3", 12, 12)]
assert (res["first_row"], res["last_row"], res["line_count"]) == (10, 12, 3)
ws = _load(drive)["20261026(월)"]
assert [ws[f"B{r}"].value for r in (10, 11, 12)] == [5, 6, 7] # 순번은 센터를 넘어 이어짐
assert ws["F12"].value == "대구3" and ws["G12"].value == "택배"
assert ws["B10"].fill.fgColor.rgb.endswith(PALLET_BG) and ws["B12"].fill.fill_type is None
assert [s[0] for s in steps] == [5, 40, 60, 80] and steps[1][2] == "인천32 추가 중 (1/2)"
assert all(p < until for p, until, _ in steps)
def test_xlsx_multi_center_new_sheet_then_append():
drive = FakeDrive(_xlsx_bytes({"20261023(금)": _sheet_rows(1)}))
res = cupang_router._run_outbound_write(
_xlsx_writer(drive), "f", cupang_router._clean_outbound_entries(_multi_payload()), lambda *a: None)
assert [(c["first_row"], c["last_row"]) for c in res["centers"]] == [(6, 7), (8, 8)] and drive.uploads == 1
ws = _load(drive)["20261026(월)"]
assert ws["B5"].value == "구분" and ws["B8"].value == 3 and ws["F8"].value == "대구3"
def test_outbound_write_streams_progress_lines(monkeypatch):
import asyncio
import json
drive = FakeDrive(_xlsx_bytes({"20261026(월)": _sheet_rows(4)}))
writer = _xlsx_writer(drive)
monkeypatch.setattr(cupang_router, "_outbound_target", lambda: (writer, "f", None))
async def collect(resp):
return [chunk async for chunk in resp.body_iterator]
resp = cupang_router.outbound_sheet_write(None, _multi_payload(), stream=True, _={})
assert resp.media_type == "application/x-ndjson" and resp.headers["x-accel-buffering"] == "no"
events = [json.loads(line) for chunk in asyncio.run(collect(resp)) for line in chunk.splitlines() if line]
assert [e["progress"] for e in events] == [5, 40, 60, 80, 100]
assert events[-1]["done"] is True and len(events[-1]["centers"]) == 2 and drive.uploads == 1
busy = FakeDrive(_xlsx_bytes({"20261026(월)": _sheet_rows(1)}))
busy.always_bump = True
w2 = _xlsx_writer(busy)
monkeypatch.setattr(cupang_router, "_outbound_target", lambda: (w2, "f", None))
resp = cupang_router.outbound_sheet_write(None, _multi_payload(), stream=True, _={})
last = json.loads(asyncio.run(collect(resp))[-1])
assert "다른 사람이 파일을 고치는 중" in last["error"] and busy.uploads == 0
def test_outbound_popup_writes_only_to_drive_xlsx(monkeypatch):
"""CUPANG_SHEET_ID 가 구글 시트 문서여도 팝업은 엑셀 파일(CUPANG_OUTBOUND_XLSX_ID)에만 쓴다."""
drive = FakeDrive(b"")