7e459c1926
- 팝업에 입고센터 카드: [+ 입고센터 추가]·[센터 삭제], 센터마다 입고센터·출고방식·제품·출고를 따로 입력 (작성일·출고일·센터입고일·작업자는 공통), 출고방식 기본값 택배 - POST /cupang/api/outbound-sheet: centers 목록을 받아 센터 순서대로 출고일 시트 아래에 덧붙임 (엑셀 내려받기·올리기 1번씩, 순번 이어짐, 파렛트 센터만 배경색). centers 없으면 예전처럼 센터 1곳 - ?stream=1 이면 단계별 진행률을 NDJSON 으로 흘려보냄(내려받기 → 센터별 추가 → 올리기 → 완료/오류), 팝업은 막대 그래프와 %로 표시하고 단계 사이에도 조금씩 채움, 실패하면 빨간 막대 + 사유 - 테스트: pytest(센터별 입력 검사·여러 센터 한 번에 쓰기·진행 단계·스트림·충돌), Playwright(카드·진행 막대·완료·실패·모바일) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
557 lines
26 KiB
Python
557 lines
26 KiB
Python
"""쿠팡 밀크런 — 밀크런 출고리스트 직접 작성(팝업 → 출고리스트 문서의 출고일 시트 맨 아래에 덧붙임).
|
|
|
|
구글은 쓰지 않는다: 시트 쓰기는 가짜 writer/가짜 Sheets 서비스로 요청 모양만 확인하고,
|
|
드라이브 엑셀(.xlsx) 파일은 가짜 Drive 서비스에 진짜 xlsx 바이트를 두고 내려받기→고치기→올리기를 확인한다.
|
|
화면·API 는 격리된 하위 프로세스의 실제 앱(가짜 cupang store, Google 인증 없음)으로 확인한다.
|
|
"""
|
|
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 import drive_xlsx
|
|
from app.integrations.drive_xlsx import DriveXlsxWriter, XlsxChangedError
|
|
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'"
|
|
|
|
|
|
# ── 드라이브 엑셀(.xlsx) 파일 ────────────────────────────────
|
|
class FakeDrive:
|
|
"""files().get(mimeType/version) · get_media(xlsx 바이트) · update(새 내용)만 흉내."""
|
|
|
|
def __init__(self, data: bytes, mime: str = drive_xlsx.XLSX_MIME):
|
|
self.data, self.mime, self.version = data, mime, 1
|
|
self.uploads = 0
|
|
self.bump_on_meta: int | None = None # n번째 메타 조회 때 남이 고친 것처럼 version 을 올림
|
|
self.always_bump = False
|
|
self.meta_calls = 0
|
|
|
|
def files(self):
|
|
return self
|
|
|
|
def get(self, **kw):
|
|
self.meta_calls += 1
|
|
if self.always_bump or self.bump_on_meta == self.meta_calls:
|
|
self.version += 1
|
|
return _Exec({"mimeType": self.mime, "version": str(self.version)})
|
|
|
|
def get_media(self, **kw):
|
|
return _Exec(self.data)
|
|
|
|
def update(self, **kw):
|
|
self.data = kw["media_body"]._fd.getvalue()
|
|
self.version += 1
|
|
self.uploads += 1
|
|
return _Exec({"id": kw["fileId"]})
|
|
|
|
|
|
def _xlsx_writer(drive: FakeDrive) -> DriveXlsxWriter:
|
|
w = DriveXlsxWriter.__new__(DriveXlsxWriter)
|
|
w.enabled, w.reason, w.auth_mode, w._creds = True, "", "test", None
|
|
w._depth, w._book = 0, None
|
|
w._service = lambda: drive
|
|
return w
|
|
|
|
|
|
def _xlsx_bytes(sheets: dict[str, list[list[Any]]]) -> bytes:
|
|
from io import BytesIO
|
|
|
|
from openpyxl import Workbook
|
|
|
|
wb = Workbook()
|
|
wb.remove(wb.active)
|
|
for title, rows in sheets.items():
|
|
ws = wb.create_sheet(title)
|
|
for r, row in enumerate(rows, start=1):
|
|
for c, v in enumerate(row, start=1):
|
|
if v != "":
|
|
ws.cell(row=r, column=c, value=int(v) if c == 2 and str(v).isdigit() else v)
|
|
out = BytesIO()
|
|
wb.save(out)
|
|
return out.getvalue()
|
|
|
|
|
|
def _load(drive: FakeDrive):
|
|
from io import BytesIO
|
|
|
|
from openpyxl import load_workbook
|
|
|
|
return load_workbook(BytesIO(drive.data))
|
|
|
|
|
|
def _append(writer: DriveXlsxWriter, entry: dict[str, Any]) -> dict[str, Any]:
|
|
return cupang_router._in_sheet(writer, lambda: cupang_router._append_outbound_entry(writer, "f", entry))
|
|
|
|
|
|
def test_xlsx_append_below_existing_rows_and_upload_once():
|
|
drive = FakeDrive(_xlsx_bytes({"20261023(금)": _sheet_rows(9), "20261026(월)": _sheet_rows(4)}))
|
|
res = _append(_xlsx_writer(drive), cupang_router._clean_outbound_entry(_payload(center="=인천32")))
|
|
assert (res["first_row"], res["last_row"]) == (10, 11) and drive.uploads == 1
|
|
assert res["url"] == "https://docs.google.com/spreadsheets/d/f/edit"
|
|
ws = _load(drive)["20261026(월)"]
|
|
assert ws["B10"].value == 5 and ws["B11"].value == 6
|
|
assert ws["H10"].value == "MT-7000" and ws["J10"].value == 1200
|
|
assert ws["F10"].value == "=인천32" and ws["F10"].data_type == "s" # 수식이 아니라 글자
|
|
assert "F10:F11" in {str(m) for m in ws.merged_cells.ranges}
|
|
assert ws["B11"].fill.fgColor.rgb.endswith(PALLET_BG) and ws["B11"].border.left.style == "thin"
|
|
assert ws["I10"].alignment.horizontal == "left"
|
|
assert _load(drive)["20261023(금)"]["B14"].value == 9 # 다른 날짜 시트는 그대로
|
|
|
|
|
|
def test_xlsx_missing_sheet_gets_full_template_and_centers():
|
|
drive = FakeDrive(_xlsx_bytes({"20261023(금)": _sheet_rows(2)}))
|
|
writer = _xlsx_writer(drive)
|
|
res = _append(writer, cupang_router._clean_outbound_entry(_payload(ship_method="택배")))
|
|
assert (res["first_row"], res["last_row"]) == (6, 7) and drive.uploads == 1
|
|
wb = _load(drive)
|
|
assert wb.sheetnames == ["20261023(금)", "20261026(월)"]
|
|
ws = wb["20261026(월)"]
|
|
assert ws["B5"].value == "구분" and ws["B6"].value == 1 and ws["F6"].value == "인천32"
|
|
assert ws["B2"].value.startswith("20261026(월)") and ws["B5"].font.b
|
|
cupang_router._sheet_centers_cache.update(at=0.0, sheet="", names=[])
|
|
assert cupang_router._sheet_centers(writer, "f") == ["대구3", "인천32"]
|
|
assert drive.uploads == 1 # 읽기만 하면 올리지 않는다
|
|
|
|
|
|
def test_xlsx_conflict_retries_then_gives_up():
|
|
entry = cupang_router._clean_outbound_entry(_payload())
|
|
drive = FakeDrive(_xlsx_bytes({"20261026(월)": _sheet_rows(1)}))
|
|
drive.bump_on_meta = 2 # 첫 시도: 내려받은 뒤 올리기 전에 남이 고침 → 다시 내려받아 성공
|
|
res = _append(_xlsx_writer(drive), entry)
|
|
assert res["first_row"] == 7 and drive.uploads == 1
|
|
assert _load(drive)["20261026(월)"]["B7"].value == 2
|
|
|
|
busy = FakeDrive(_xlsx_bytes({"20261026(월)": _sheet_rows(1)}))
|
|
busy.always_bump = True
|
|
writer = _xlsx_writer(busy)
|
|
with pytest.raises(XlsxChangedError):
|
|
_append(writer, entry)
|
|
assert busy.uploads == 0 and writer._depth == 0 and writer._book is None
|
|
|
|
|
|
def test_xlsx_delete_sheet():
|
|
drive = FakeDrive(_xlsx_bytes({"a": [["x"]], "20261026(월)": _sheet_rows(3)}))
|
|
writer = _xlsx_writer(drive)
|
|
assert writer.delete_sheet(spreadsheet_id="f", title="없음")["action"] == "missing"
|
|
assert drive.uploads == 0
|
|
assert writer.delete_sheet(spreadsheet_id="f", title="20261026(월)")["action"] == "deleted"
|
|
assert _load(drive).sheetnames == ["a"]
|
|
assert writer.delete_sheet(spreadsheet_id="f", title="a")["action"] == "cleared"
|
|
assert _load(drive).sheetnames == ["a"] and _load(drive)["a"]["A1"].value is None
|
|
|
|
|
|
def test_xlsx_read_ranges_like_sheets_api():
|
|
drive = FakeDrive(_xlsx_bytes({"s'1": [["", "1", "x", ""], [], ["", "2.5"]]}))
|
|
got = _xlsx_writer(drive).read_ranges(spreadsheet_id="f", ranges=["'s''1'!A1:L", "'s''1'!B3:B", "'없음'!A1"])
|
|
assert got == [[["", "1", "x"], [], ["", "2.5"]], [["2.5"]], []]
|
|
|
|
|
|
def test_sheet_target_picks_writer_by_drive_file_type(monkeypatch):
|
|
drive = FakeDrive(b"")
|
|
writer = _xlsx_writer(drive)
|
|
monkeypatch.setattr(drive_xlsx, "get_writer", lambda: writer)
|
|
monkeypatch.setattr(drive_xlsx, "_KIND_CACHE", {})
|
|
monkeypatch.delenv("CUPANG_SHEET_ID", raising=False)
|
|
got, file_id, skip = cupang_router._sheet_target(None)
|
|
assert got is writer and file_id == cupang_router.DEFAULT_SHEET_ID and skip is None
|
|
drive.mime = "application/pdf"
|
|
monkeypatch.setattr(drive_xlsx, "_KIND_CACHE", {})
|
|
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"")
|
|
writer = _xlsx_writer(drive)
|
|
monkeypatch.setattr(drive_xlsx, "get_writer", lambda: writer)
|
|
monkeypatch.setattr(drive_xlsx, "_KIND_CACHE", {})
|
|
monkeypatch.setenv("CUPANG_SHEET_ID", "google-sheet-doc")
|
|
monkeypatch.delenv("CUPANG_OUTBOUND_XLSX_ID", raising=False)
|
|
got, file_id, skip = cupang_router._outbound_target()
|
|
assert got is writer and file_id == cupang_router.DEFAULT_OUTBOUND_XLSX_ID and skip is None
|
|
|
|
drive.mime = drive_xlsx.SHEETS_MIME # 엑셀이 아니면 구글 시트로 대신 쓰지 않고 멈춘다
|
|
monkeypatch.setattr(drive_xlsx, "_KIND_CACHE", {})
|
|
got, _, skip = cupang_router._outbound_target()
|
|
assert got is None and "엑셀(.xlsx)이 아닙니다" in skip["reason"]
|
|
|
|
writer.enabled, writer.reason = False, "Google 인증 미설정"
|
|
got, _, skip = cupang_router._outbound_target()
|
|
assert got is None and skip["reason"] == "Google 인증 미설정"
|
|
|
|
|
|
# ── 실제 앱(하위 프로세스) — 버튼·팝업·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 "미설정" in r["reason"], r
|
|
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 "출고리스트 엑셀 파일에 쓸 수 없습니다" 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"] = ""
|
|
for key in ("GOOGLE_SHEETS_CREDENTIALS", "GOOGLE_SHEETS_CREDENTIALS_JSON",
|
|
"GOOGLE_SHEETS_OAUTH_REFRESH_TOKEN", "GOOGLE_SLIDES_OAUTH_REFRESH_TOKEN"):
|
|
env[key] = ""
|
|
env.update(SESSION_SECRET_KEY="local-cupang-test-only", SESSION_COOKIE_SECURE="false",
|
|
PERFORMANCE_AUTO_SYNC="false", CUPANG_SHEET_ID="", PYTHONIOENCODING="utf-8")
|
|
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)
|