feat(cupang): 밀크런 출고리스트 작성 팝업 — 구글 시트 출고일 시트 아래에 덧붙임
- 첫 화면 "+ 신규 등록" 옆 엑셀색 버튼 → 작성일·출고일·센터입고일(프로젝트 날짜 팝업), 입고센터(시트 F열 + 등록 센터, 직접 입력), 출고방식(파렛트/택배), 코드표 검색 제품·수량, 출고, 작업자(기본 핫프렌즈) - POST /cupang/api/outbound-sheet: 출고일 시트 YYYYMMDD(요일) 맨 아래에 기존 양식으로 추가 (순번 이어짐·파렛트 배경색), 시트가 없으면 5행 양식째 생성. cupang_db 에는 저장하지 않음 - GET /cupang/api/outbound-sheet/centers: 입고센터 후보(10분 캐시) - export.build_block 분리(기존 build_table 결과 동일), google_sheets 에 sheet_titles·read_ranges·append_block 추가 - 테스트: pytest(양식·입력 검사·덧붙일 위치·Sheets 요청·실제 앱), Playwright 화면 테스트 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -91,3 +91,14 @@ node tests/js/inbox_panel.browser.test.js # Playwright: iframe 리다이렉
|
||||
python tests/js/render_project.py # → tests/js/.out/project_render.html
|
||||
NODE_PATH=<playwright 또는 playwright-core 경로> PJ_TEST_BROWSER=<Chrome/Edge 경로> node tests/js/image_copy.browser.test.js
|
||||
```
|
||||
|
||||
# 쿠팡 밀크런 출고리스트 작성 팝업 (Playwright, 2026-10-23)
|
||||
|
||||
`cupang/index.html` + `static/cupang-outbound.js` — "+ 신규 등록" 옆 엑셀색 버튼, 프로젝트 날짜 팝업(작성일 오늘·센터입고일 = 출고일+1),
|
||||
입고센터 목록·직접 입력, 코드표 검색으로 제품 추가, [완료] 요청 값·성공 안내·실패 시 입력 유지, Esc, 390px 화면을 가짜 서버로 확인한다.
|
||||
구글 시트·DB 연결 없음(시트 쓰기 자체는 `tests/test_cupang_outbound_sheet.py`).
|
||||
|
||||
```bash
|
||||
python tests/js/render_cupang_index.py # → tests/js/.out/cupang_index_render.html
|
||||
NODE_PATH=<playwright 또는 playwright-core 경로> PJ_TEST_BROWSER=<Chrome/Edge 경로> node tests/js/cupang_outbound.browser.test.js
|
||||
```
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
// 쿠팡 밀크런 — "밀크런 출고리스트 작성" 팝업을 실제 Chromium 에서 검증(DB·구글 미사용, 가짜 서버).
|
||||
// python tests/js/render_cupang_index.py
|
||||
// PJ_TEST_BROWSER=<설치된 Chrome/Edge 경로> node tests/js/cupang_outbound.browser.test.js
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs");
|
||||
const http = require("node:http");
|
||||
const path = require("node:path");
|
||||
const { chromium } = require("playwright");
|
||||
const ROOT = path.resolve(__dirname, "../..");
|
||||
const STATIC = path.join(ROOT, "app/static");
|
||||
const OUT = path.join(__dirname, ".out");
|
||||
const posts = [];
|
||||
|
||||
const PRODUCTS = [
|
||||
{ code: "MT-7000", name: "점보 7,000ml", type: "단품" },
|
||||
{ code: "MS-1004", name: "미라네 4호세트", type: "세트" },
|
||||
{ code: "MT-3000", name: "중형 3,000ml", type: "단품" },
|
||||
];
|
||||
|
||||
function json(res, status, body) {
|
||||
res.statusCode = status;
|
||||
res.setHeader("Content-Type", "application/json; charset=utf-8");
|
||||
res.end(JSON.stringify(body));
|
||||
}
|
||||
|
||||
const server = http.createServer(function (req, res) {
|
||||
const url = new URL(req.url, "http://localhost");
|
||||
if (url.pathname === "/cupang/") {
|
||||
res.setHeader("Content-Type", "text/html; charset=utf-8");
|
||||
res.end(fs.readFileSync(path.join(OUT, "cupang_index_render.html"))); return;
|
||||
}
|
||||
if (url.pathname === "/cupang/api/outbound-sheet/centers") return json(res, 200, { centers: ["대구3", "인천32"], reason: "" });
|
||||
if (url.pathname === "/cupang/api/products/all") return json(res, 200, { enabled: true, reason: "", error: "", results: PRODUCTS });
|
||||
if (url.pathname === "/cupang/api/outbound-sheet" && req.method === "POST") {
|
||||
let raw = "";
|
||||
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 });
|
||||
});
|
||||
return;
|
||||
}
|
||||
const file = path.resolve(STATIC, "." + decodeURIComponent(url.pathname.slice(7)));
|
||||
if (!url.pathname.startsWith("/static/") || !file.startsWith(STATIC + path.sep) || !fs.existsSync(file) || !fs.statSync(file).isFile()) {
|
||||
res.statusCode = 404; res.end(); return;
|
||||
}
|
||||
const types = { ".css": "text/css", ".js": "text/javascript", ".woff2": "font/woff2", ".woff": "font/woff", ".png": "image/png", ".svg": "image/svg+xml" };
|
||||
res.setHeader("Content-Type", types[path.extname(file)] || "application/octet-stream");
|
||||
fs.createReadStream(file).pipe(res);
|
||||
});
|
||||
|
||||
async function pickDate(page, inputId, typed) {
|
||||
// 프로젝트 날짜 팝업: 버튼 → 팝업의 날짜 칸에 직접 입력 + Enter
|
||||
await page.locator("#" + inputId + " + .pj-date-btn").click();
|
||||
const pop = page.locator(".pj-datepop");
|
||||
await pop.waitFor({ state: "visible" });
|
||||
await pop.locator(".pj-dp-field").fill(typed);
|
||||
await pop.locator(".pj-dp-field").press("Enter");
|
||||
await pop.waitFor({ state: "detached" });
|
||||
}
|
||||
|
||||
(async function () {
|
||||
let browser;
|
||||
try {
|
||||
await new Promise(resolve => server.listen(0, "127.0.0.1", resolve));
|
||||
browser = await chromium.launch({ headless: true, executablePath: process.env.PJ_TEST_BROWSER || undefined });
|
||||
const page = await browser.newPage({ viewport: { width: 1600, height: 1000 } });
|
||||
const errors = [];
|
||||
page.on("pageerror", e => errors.push(e.message));
|
||||
await page.goto("http://127.0.0.1:" + server.address().port + "/cupang/");
|
||||
|
||||
// 버튼: "+ 신규 등록" 바로 오른쪽, 엑셀 초록
|
||||
const openBtn = page.locator("#cpg-ol-open");
|
||||
await openBtn.waitFor({ state: "visible" });
|
||||
const newBox = await page.locator("a", { hasText: "+ 신규 등록" }).boundingBox();
|
||||
const btnBox = await openBtn.boundingBox();
|
||||
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 } });
|
||||
|
||||
// 팝업 열기 — 작성일 = 오늘(프로젝트 날짜 버튼), 작업자 = 핫프렌즈
|
||||
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-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", "+ 직접 입력"]);
|
||||
|
||||
// 출고일 → 센터입고일은 다음날로 자동
|
||||
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\(월\)/);
|
||||
|
||||
// 필수값 확인
|
||||
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 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()), "제품이 없으면 표를 숨김");
|
||||
|
||||
// 코드표 검색 → 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호세트"]);
|
||||
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") });
|
||||
|
||||
// 완료 → 서버로 보낸 값, 성공 안내
|
||||
await page.locator("#cpg-ol-submit").click();
|
||||
await page.locator(".erp-dialog").waitFor({ state: "visible" });
|
||||
assert.match(await page.locator(".erp-dialog").innerText(), /'20261026\(월\)' 시트 10~11행에 2개 제품을 추가했습니다/);
|
||||
assert.deepEqual(posts[0], {
|
||||
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" }],
|
||||
});
|
||||
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();
|
||||
|
||||
// 다시 열면 비어 있고, 센터 직접 입력 + 실패 응답은 팝업 안에 보여 준다
|
||||
await openBtn.click();
|
||||
assert.equal(await page.locator("#cpg-ol-lines tr").count(), 0);
|
||||
assert.equal(await page.locator("#cpg-ol-ship-date").inputValue(), "");
|
||||
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.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-dlg").isVisible(), "실패하면 입력 유지");
|
||||
assert.equal(posts[1].center, "실패센터");
|
||||
assert.equal(posts[1].ship_method, "택배");
|
||||
|
||||
// Esc: 날짜 팝업이 떠 있으면 그것만 닫고, 다음 Esc 에 출고리스트 팝업 닫힘
|
||||
await page.locator("#cpg-ol-doc-date + .pj-date-btn").click();
|
||||
await page.locator(".pj-datepop").waitFor({ state: "visible" });
|
||||
await page.waitForTimeout(50); // 날짜 팝업은 다음 틱에 Esc 처리를 건다(project.js openDatePopover)
|
||||
await page.keyboard.press("Escape");
|
||||
await page.locator(".pj-datepop").waitFor({ state: "detached" });
|
||||
assert.ok(await page.locator("#cpg-ol-dlg").isVisible());
|
||||
await page.keyboard.press("Escape");
|
||||
assert.ok(await page.locator("#cpg-ol-dlg").isHidden());
|
||||
|
||||
// 좁은 화면에서도 가로 넘침 없음
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await openBtn.click();
|
||||
const over = await page.evaluate(() => {
|
||||
const box = document.querySelector(".cpg-ol-box");
|
||||
return box.scrollWidth - box.clientWidth;
|
||||
});
|
||||
assert.ok(over <= 1, "모바일 팝업 가로 넘침 " + over);
|
||||
await page.screenshot({ path: path.join(OUT, "cupang-outbound-mobile.png") });
|
||||
|
||||
assert.deepEqual(errors, [], "브라우저 JS 오류 없음");
|
||||
console.log("ALL PASS — 버튼 위치·색, 프로젝트 날짜 팝업, 센터 목록·직접 입력, 코드표 검색, 완료·실패, Esc, 모바일");
|
||||
} finally {
|
||||
if (browser) await browser.close();
|
||||
await new Promise(resolve => server.close(resolve));
|
||||
}
|
||||
})().catch(function (e) { console.error(e); process.exit(1); });
|
||||
@@ -0,0 +1,46 @@
|
||||
"""쿠팡 밀크런 첫 화면(달력 + 출고리스트 작성 팝업)을 실제 앱으로 렌더한다. DB·구글 미사용.
|
||||
|
||||
python tests/js/render_cupang_index.py -> tests/js/.out/cupang_index_render.html
|
||||
(브라우저 테스트: tests/js/cupang_outbound.browser.test.js)
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
for key in ("ASSET", "CAFE24", "CUPANG", "VACATION", "PROJECT", "DISPATCH", "PERFORMANCE",
|
||||
"MALAYSIA_STOCK", "ITEMCODE", "EXPENSE", "INOUT"):
|
||||
os.environ[key + "_DB_URL"] = ""
|
||||
os.environ.update(SESSION_SECRET_KEY="local-render-only", SESSION_COOKIE_SECURE="false",
|
||||
PERFORMANCE_AUTO_SYNC="false", CUPANG_SHEET_ID="")
|
||||
os.environ["DATA_DIR"] = tempfile.mkdtemp(prefix="cupang-render-")
|
||||
|
||||
from fastapi.testclient import TestClient # noqa: E402
|
||||
|
||||
import app.main as main # noqa: E402
|
||||
|
||||
user = {"email": "staff@test.local", "name": "staff", "role": "user", "is_super_admin": False,
|
||||
"modules": {"cupang": True}}
|
||||
|
||||
|
||||
class Store:
|
||||
def list_shipments(self, **kw):
|
||||
return []
|
||||
|
||||
def get_shipment(self, **kw):
|
||||
return None
|
||||
|
||||
|
||||
main.app.state.cupang_store = Store()
|
||||
with patch.object(main, "get_current_user_record", side_effect=lambda r: user), \
|
||||
patch.object(main, "get_session_user", side_effect=lambda r: user), \
|
||||
patch.object(main.user_store, "get", side_effect=lambda e: user):
|
||||
html = TestClient(main.app).get("/cupang/").text
|
||||
|
||||
out = ROOT / "tests/js/.out/cupang_index_render.html"
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
out.write_text(html, encoding="utf-8")
|
||||
print("rendered:", out)
|
||||
@@ -0,0 +1,300 @@
|
||||
"""쿠팡 밀크런 — 밀크런 출고리스트 직접 작성(팝업 → 구글 시트 출고일 시트 맨 아래에 덧붙임).
|
||||
|
||||
구글은 쓰지 않는다: 시트 쓰기는 가짜 writer/가짜 Sheets 서비스로 요청 모양만 확인하고,
|
||||
화면·API 는 격리된 하위 프로세스의 실제 앱(가짜 cupang store, CUPANG_SHEET_ID 미설정)으로 확인한다.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
|
||||
from app.integrations.google_sheets import GoogleSheetsWriter, a1_sheet, col_letter
|
||||
from app.modules.cupang.export import PALLET_BG, WORKER, build_block, build_table
|
||||
|
||||
# app.modules.cupang 패키지가 APIRouter 를 같은 이름(router)으로 내보내므로 모듈은 이렇게 가져온다
|
||||
cupang_router = importlib.import_module("app.modules.cupang.router")
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def _payload(**over: Any) -> dict[str, Any]:
|
||||
body = {
|
||||
"document_date": "2026-10-23",
|
||||
"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": "1,200"},
|
||||
{"code": "MS-1004", "name": "미라네 4호세트", "quantity": 60},
|
||||
],
|
||||
}
|
||||
body.update(over)
|
||||
return body
|
||||
|
||||
|
||||
# ── 양식(export) ─────────────────────────────────────────────
|
||||
def test_build_block_continues_sequence_and_merges_center_columns():
|
||||
entry = cupang_router._clean_outbound_entry(_payload())
|
||||
block = build_block(entry, start_row=12, start_seq=7)
|
||||
assert block["first_row"] == 12 and block["last_row"] == 13 and block["last_seq"] == 9
|
||||
assert block["cells"][(12, 2)] == 8 and block["cells"][(13, 2)] == 9 # 순번 이어짐
|
||||
assert block["cells"][(12, 8)] == "MT-7000" and block["cells"][(13, 10)] == 60
|
||||
assert block["cells"][(12, 3)] == "2026-10-23(금)" # 작성일(요일)
|
||||
assert block["cells"][(12, 4)] == "2026-10-26(월)"
|
||||
assert block["cells"][(12, 6)] == "인천32" and block["cells"][(12, 7)] == "파렛트"
|
||||
assert block["cells"][(12, 11)] == "2파렛트" and block["cells"][(12, 12)] == WORKER
|
||||
assert (12, 6, 13, 6) in block["merges"] and (12, 12, 13, 12) in block["merges"]
|
||||
assert block["is_pallet"] is True
|
||||
assert build_block({"lines": []}, start_row=6, start_seq=0) is None
|
||||
|
||||
|
||||
def test_build_table_layout_is_unchanged_for_confirmed_shipments():
|
||||
ships = [
|
||||
{"document_date": "2026-10-23", "ship_date": "2026-10-26", "center_arrival_date": "2026-10-27",
|
||||
"center_name_snapshot": "대구3", "ship_method": "택배", "outbound_summary": "3박스",
|
||||
"lines": [{"product_code": "A", "product_name_snapshot": "가", "quantity": 1}]},
|
||||
{"document_date": "2026-10-23", "ship_date": "2026-10-26", "center_arrival_date": "2026-10-27",
|
||||
"center_name_snapshot": "이천1", "ship_method": "파렛트", "outbound_summary": "",
|
||||
"lines": [{"product_code": "B", "product_name_snapshot": "나", "quantity": 2},
|
||||
{"product_code": "C", "product_name_snapshot": "다", "quantity": 3}]},
|
||||
]
|
||||
table = build_table("2026-10-26", ships)
|
||||
assert table["title"] == "20261026(월) 쿠팡로켓 밀크런 출고리스트"
|
||||
assert table["cells"][(5, 2)] == "구분" and table["cells"][(5, 12)] == "작업자"
|
||||
assert [table["cells"][(r, 2)] for r in (6, 7, 8)] == [1, 2, 3]
|
||||
assert table["last_row"] == 8 and table["pallet_ranges"] == [(7, 8)]
|
||||
assert table["cells"][(6, 12)] == WORKER and (7, 6, 8, 6) in table["merges"]
|
||||
|
||||
|
||||
# ── 입력 검사 ───────────────────────────────────────────────
|
||||
def test_clean_entry_defaults_and_escapes():
|
||||
entry = cupang_router._clean_outbound_entry(_payload(outbound="=HYPERLINK(1)"))
|
||||
assert entry["worker"] == WORKER # 비우면 기본 작업자
|
||||
assert entry["lines"][0]["quantity"] == 1200 # 쉼표 수량
|
||||
assert entry["outbound_summary"] == "'=HYPERLINK(1)" # 수식으로 해석되지 않게
|
||||
assert entry["center_name_snapshot"] == "인천32"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("over, words", [
|
||||
({"ship_method": "화물"}, "출고방식"),
|
||||
({"ship_date": ""}, "출고일"),
|
||||
({"center_arrival_date": "2026-13-01"}, "센터입고일"),
|
||||
({"center": " "}, "입고센터"),
|
||||
({"lines": []}, "제품"),
|
||||
({"lines": [{"code": "A", "name": "가", "quantity": 0}]}, "수량"),
|
||||
({"lines": [{"code": "", "name": "가", "quantity": 1}]}, "제품코드"),
|
||||
])
|
||||
def test_clean_entry_rejects_bad_input(over, words):
|
||||
with pytest.raises(HTTPException) as err:
|
||||
cupang_router._clean_outbound_entry(_payload(**over))
|
||||
assert err.value.status_code == 400 and words in err.value.detail
|
||||
|
||||
|
||||
# ── 덧붙일 위치 ─────────────────────────────────────────────
|
||||
class FakeWriter:
|
||||
enabled = True
|
||||
lock = threading.RLock()
|
||||
|
||||
def __init__(self, sheets: dict[str, list[list[Any]]]):
|
||||
self.sheets = sheets
|
||||
self.calls: list[tuple[str, dict[str, Any]]] = []
|
||||
|
||||
def sheet_titles(self, *, spreadsheet_id):
|
||||
return list(self.sheets)
|
||||
|
||||
def read_ranges(self, *, spreadsheet_id, ranges):
|
||||
out = []
|
||||
for rng in ranges:
|
||||
title = rng.split("!")[0].strip("'")
|
||||
rows = self.sheets.get(title, [])
|
||||
if "!F6:F" in rng:
|
||||
out.append([[r[5]] for r in rows[5:] if len(r) > 5 and r[5]])
|
||||
else:
|
||||
out.append(rows)
|
||||
return out
|
||||
|
||||
def write_table(self, **kw):
|
||||
self.calls.append(("write_table", kw))
|
||||
return {"created": True, "title": kw["title"], "url": "u"}
|
||||
|
||||
def append_block(self, **kw):
|
||||
self.calls.append(("append_block", kw))
|
||||
return {"created": False, "title": kw["title"], "first_row": kw["first_row"],
|
||||
"last_row": kw["last_row"], "url": "u"}
|
||||
|
||||
|
||||
def _sheet_rows(data_rows: int) -> list[list[Any]]:
|
||||
rows: list[list[Any]] = [[], ["", "20261026(월) 쿠팡로켓 밀크런 출고리스트"], [], ["", "회사"],
|
||||
["", "구분", "작성일"]]
|
||||
for i in range(1, data_rows + 1):
|
||||
rows.append(["", str(i), "", "", "", "대구3" if i == 1 else "", "", "X", "엑스", "5"])
|
||||
return rows
|
||||
|
||||
|
||||
def test_append_below_existing_rows_with_next_sequence():
|
||||
writer = FakeWriter({"20261026(월)": _sheet_rows(4), "20261023(금)": _sheet_rows(9)})
|
||||
entry = cupang_router._clean_outbound_entry(_payload())
|
||||
res = cupang_router._append_outbound_entry(writer, "sheet", entry)
|
||||
kind, kw = writer.calls[-1]
|
||||
assert kind == "append_block" and kw["title"] == "20261026(월)"
|
||||
assert (kw["first_row"], kw["last_row"]) == (10, 11) # 5행 양식 + 4줄 → 10행부터
|
||||
assert kw["cells"][(10, 2)] == 5 and kw["cells"][(11, 2)] == 6
|
||||
assert kw["highlight"] == PALLET_BG
|
||||
assert res["first_row"] == 10
|
||||
|
||||
|
||||
def test_missing_or_blank_sheet_gets_full_template():
|
||||
for sheets in ({}, {"20261026(월)": [[], ["", "제목만"]]}):
|
||||
writer = FakeWriter(sheets)
|
||||
res = cupang_router._append_outbound_entry(
|
||||
writer, "sheet", cupang_router._clean_outbound_entry(_payload(ship_method="택배")))
|
||||
kind, kw = writer.calls[-1]
|
||||
assert kind == "write_table" and kw["title"] == "20261026(월)"
|
||||
assert kw["cells"][(5, 2)] == "구분" and kw["cells"][(6, 2)] == 1
|
||||
assert kw["row_highlights"] == []
|
||||
assert (res["first_row"], res["last_row"]) == (6, 7)
|
||||
|
||||
|
||||
def test_sheet_centers_reads_column_f_of_every_sheet(monkeypatch):
|
||||
monkeypatch.setattr(cupang_router, "_sheet_centers_cache", {"at": 0.0, "sheet": "", "names": []})
|
||||
sheets = {"20261026(월)": _sheet_rows(2), "20261023(금)": _sheet_rows(1)}
|
||||
sheets["20261023(금)"][5][5] = "인천32"
|
||||
names = cupang_router._sheet_centers(FakeWriter(sheets), "sheet")
|
||||
assert names == ["대구3", "인천32"]
|
||||
|
||||
|
||||
# ── 구글 시트 writer.append_block 요청 모양 ─────────────────
|
||||
class _Exec:
|
||||
def __init__(self, result=None):
|
||||
self.result = result or {}
|
||||
|
||||
def execute(self):
|
||||
return self.result
|
||||
|
||||
|
||||
class FakeService:
|
||||
def __init__(self, row_count):
|
||||
self.row_count = row_count
|
||||
self.batch: list[dict[str, Any]] = []
|
||||
self.updates: list[dict[str, Any]] = []
|
||||
|
||||
def spreadsheets(self):
|
||||
return self
|
||||
|
||||
def values(self):
|
||||
return self
|
||||
|
||||
def get(self, **kw):
|
||||
return _Exec({"sheets": [{"properties": {"sheetId": 77, "title": "20261026(월)",
|
||||
"gridProperties": {"rowCount": self.row_count}}}]})
|
||||
|
||||
def batchUpdate(self, **kw):
|
||||
self.batch.append(kw["body"])
|
||||
return _Exec()
|
||||
|
||||
def update(self, **kw):
|
||||
self.updates.append(kw)
|
||||
return _Exec()
|
||||
|
||||
|
||||
def _writer(service):
|
||||
w = GoogleSheetsWriter.__new__(GoogleSheetsWriter)
|
||||
w.enabled, w.reason, w._service = True, "", service
|
||||
return w
|
||||
|
||||
|
||||
def test_append_block_grows_grid_and_writes_from_column_b():
|
||||
service = FakeService(row_count=10)
|
||||
entry = cupang_router._clean_outbound_entry(_payload())
|
||||
block = build_block(entry, start_row=10, start_seq=4)
|
||||
res = _writer(service).append_block(
|
||||
spreadsheet_id="s", title="20261026(월)", cells=block["cells"], merges=block["merges"],
|
||||
first_row=10, last_row=11, first_col=2, last_col=12, highlight=PALLET_BG)
|
||||
reqs = service.batch[0]["requests"]
|
||||
assert reqs[0] == {"appendDimension": {"sheetId": 77, "dimension": "ROWS", "length": 1}}
|
||||
assert any("mergeCells" in r for r in reqs) and any("updateBorders" in r for r in reqs)
|
||||
upd = service.updates[0]
|
||||
assert upd["range"] == "'20261026(월)'!B10"
|
||||
assert len(upd["body"]["values"]) == 2 and len(upd["body"]["values"][0]) == 11
|
||||
assert upd["body"]["values"][0][0] == 5 # B10 = 순번 5
|
||||
assert res["url"].endswith("#gid=77")
|
||||
|
||||
|
||||
def test_append_block_missing_sheet_raises():
|
||||
service = FakeService(row_count=100)
|
||||
with pytest.raises(LookupError):
|
||||
_writer(service).append_block(spreadsheet_id="s", title="없는시트", cells={}, merges=[],
|
||||
first_row=6, last_row=6, first_col=2, last_col=12)
|
||||
|
||||
|
||||
def test_a1_helpers():
|
||||
assert col_letter(1) == "A" and col_letter(12) == "L" and col_letter(27) == "AA"
|
||||
assert a1_sheet("20261026(월)") == "'20261026(월)'" and a1_sheet("a'b") == "'a''b'"
|
||||
|
||||
|
||||
# ── 실제 앱(하위 프로세스) — 버튼·팝업·API ──────────────────
|
||||
APP_CODE = '''
|
||||
from unittest.mock import patch
|
||||
from fastapi.testclient import TestClient
|
||||
import app.main as main
|
||||
|
||||
user = {"email": "staff@test.local", "name": "staff", "role": "user", "is_super_admin": False,
|
||||
"modules": {"cupang": True}}
|
||||
|
||||
class Store:
|
||||
def list_shipments(self, **kw): return []
|
||||
def get_shipment(self, **kw): return None
|
||||
def list_centers(self, **kw): return [{"name": "대구3"}, {"name": "이천1"}]
|
||||
|
||||
main.app.state.cupang_store = Store()
|
||||
with patch.object(main, "get_current_user_record", side_effect=lambda r: user), \\
|
||||
patch.object(main, "get_session_user", side_effect=lambda r: user), \\
|
||||
patch.object(main.user_store, "get", side_effect=lambda e: user):
|
||||
c = TestClient(main.app)
|
||||
html = c.get("/cupang/").text
|
||||
assert 'id="cpg-ol-open"' in html and "밀크런 출고리스트 작성" in html
|
||||
assert html.index("+ 신규 등록") < html.index("밀크런 출고리스트 작성") # 신규 등록 바로 옆
|
||||
assert 'id="cpg-ol-dlg"' in html and 'value="핫프렌즈"' in html
|
||||
assert "/static/project.js" in html and "/static/cupang-outbound.js" in html and "PJ_LIB_ONLY" in html
|
||||
r = c.get("/cupang/api/outbound-sheet/centers").json()
|
||||
assert r["centers"] == ["대구3", "이천1"] and "CUPANG_SHEET_ID" in r["reason"]
|
||||
bad = c.post("/cupang/api/outbound-sheet", json={"ship_method": "택배"})
|
||||
assert bad.status_code == 400, bad.text
|
||||
good = {"document_date": "2026-10-23", "ship_date": "2026-10-26", "center_arrival_date": "2026-10-27",
|
||||
"center": "대구3", "ship_method": "택배", "lines": [{"code": "A", "name": "가", "quantity": 1}]}
|
||||
r = c.post("/cupang/api/outbound-sheet", json=good)
|
||||
assert r.status_code == 503 and "CUPANG_SHEET_ID" in r.json()["detail"], r.text
|
||||
assert c.get("/static/cupang-outbound.js").status_code == 200
|
||||
user["modules"] = {"cupang": False}
|
||||
assert c.post("/cupang/api/outbound-sheet", json=good).status_code == 403
|
||||
print("OK")
|
||||
'''
|
||||
|
||||
|
||||
class OutboundSheetAppTests(unittest.TestCase):
|
||||
def test_page_and_api(self):
|
||||
env = dict(os.environ)
|
||||
for key in ("ASSET", "CAFE24", "CUPANG", "VACATION", "PROJECT", "DISPATCH", "PERFORMANCE",
|
||||
"MALAYSIA_STOCK", "ITEMCODE", "EXPENSE", "INOUT"):
|
||||
env[key + "_DB_URL"] = ""
|
||||
env.update(SESSION_SECRET_KEY="local-cupang-test-only", SESSION_COOKIE_SECURE="false",
|
||||
PERFORMANCE_AUTO_SYNC="false", CUPANG_SHEET_ID="")
|
||||
with tempfile.TemporaryDirectory(prefix="cupang-outbound-") as directory:
|
||||
env["DATA_DIR"] = directory
|
||||
res = subprocess.run([sys.executable, "-c", APP_CODE], cwd=ROOT, env=env, capture_output=True,
|
||||
text=True, encoding="utf-8", timeout=120)
|
||||
self.assertEqual(res.returncode, 0, res.stdout + res.stderr)
|
||||
self.assertIn("OK", res.stdout)
|
||||
Reference in New Issue
Block a user