Files
dbx-main/tests/test_cupang_outbound_sheet.py
T
king e63734c984 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>
2026-10-23 14:57:43 +09:00

301 lines
14 KiB
Python

"""쿠팡 밀크런 — 밀크런 출고리스트 직접 작성(팝업 → 구글 시트 출고일 시트 맨 아래에 덧붙임).
구글은 쓰지 않는다: 시트 쓰기는 가짜 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)