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:
+3
-2
@@ -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
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -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"")
|
||||
|
||||
Reference in New Issue
Block a user