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:
+207
-21
@@ -22,6 +22,7 @@ from app.timezone import today_kst
|
||||
from fastapi import APIRouter, Body, Depends, File, Form, HTTPException, Request, UploadFile
|
||||
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse
|
||||
|
||||
from .export import WORKER as OUTBOUND_WORKER
|
||||
from .holidays import holiday_name, is_holiday
|
||||
from .store import SHIP_METHODS, parse_weight_g
|
||||
|
||||
@@ -222,6 +223,7 @@ def index(request: Request) -> HTMLResponse:
|
||||
"months": months,
|
||||
"selected_date": sel,
|
||||
"sel_shipments": sel_shipments,
|
||||
"outbound_worker": OUTBOUND_WORKER,
|
||||
},
|
||||
)
|
||||
|
||||
@@ -297,11 +299,6 @@ def _push_to_google_sheet(store: Any, ship_date: str) -> dict[str, Any]:
|
||||
- 인증: 서비스 계정(app/integrations/google_sheets.py). 미설정이면 조용히 skip.
|
||||
- 실패해도 출고 묶음 저장은 이미 끝났으므로 예외를 밖으로 던지지 않는다.
|
||||
"""
|
||||
from .export import ( # noqa: WPS433
|
||||
COL_FIRST, COL_LAST, FIRST_DATA_ROW, HEADER_BG, HEADER_ROW, PALLET_BG,
|
||||
TITLE_ROW, WIDTHS_PX, build_table, sheet_title,
|
||||
)
|
||||
|
||||
writer, spreadsheet_id, skip = _sheet_target(store)
|
||||
if skip:
|
||||
return skip
|
||||
@@ -310,28 +307,217 @@ def _push_to_google_sheet(store: Any, ship_date: str) -> dict[str, Any]:
|
||||
if not shipments:
|
||||
return {"ok": False, "skipped": True, "reason": "해당 출고일의 출고 묶음 없음"}
|
||||
|
||||
table = build_table(ship_date, shipments)
|
||||
try:
|
||||
res = writer.write_table(
|
||||
spreadsheet_id=spreadsheet_id,
|
||||
title=sheet_title(ship_date),
|
||||
cells=table["cells"],
|
||||
merges=table["merges"],
|
||||
header_row=HEADER_ROW,
|
||||
first_data_row=FIRST_DATA_ROW,
|
||||
last_row=table["last_row"],
|
||||
first_col=COL_FIRST,
|
||||
last_col=COL_LAST,
|
||||
title_row=TITLE_ROW,
|
||||
widths=WIDTHS_PX,
|
||||
header_bg=HEADER_BG,
|
||||
row_highlights=[(r1, r2, PALLET_BG) for (r1, r2) in table["pallet_ranges"]],
|
||||
)
|
||||
res = _write_full_sheet(writer, spreadsheet_id, ship_date, shipments)
|
||||
except Exception as exc: # noqa: BLE001 - 시트 기록 실패는 경고로만 알린다
|
||||
return {"ok": False, "skipped": False, "reason": f"{type(exc).__name__}: {exc}"}
|
||||
return {"ok": True, "skipped": False, **res}
|
||||
|
||||
|
||||
def _write_full_sheet(
|
||||
writer: Any, spreadsheet_id: str, ship_date: str, shipments: list[dict[str, Any]]
|
||||
) -> dict[str, Any]:
|
||||
"""출고일 시트를 양식(1~5행)부터 통째로 다시 쓴다. 실패는 예외로 알린다."""
|
||||
from .export import ( # noqa: WPS433
|
||||
COL_FIRST, COL_LAST, FIRST_DATA_ROW, HEADER_BG, HEADER_ROW, PALLET_BG,
|
||||
TITLE_ROW, WIDTHS_PX, build_table, sheet_title,
|
||||
)
|
||||
|
||||
table = build_table(ship_date, shipments)
|
||||
res = writer.write_table(
|
||||
spreadsheet_id=spreadsheet_id,
|
||||
title=sheet_title(ship_date),
|
||||
cells=table["cells"],
|
||||
merges=table["merges"],
|
||||
header_row=HEADER_ROW,
|
||||
first_data_row=FIRST_DATA_ROW,
|
||||
last_row=table["last_row"],
|
||||
first_col=COL_FIRST,
|
||||
last_col=COL_LAST,
|
||||
title_row=TITLE_ROW,
|
||||
widths=WIDTHS_PX,
|
||||
header_bg=HEADER_BG,
|
||||
row_highlights=[(r1, r2, PALLET_BG) for (r1, r2) in table["pallet_ranges"]],
|
||||
)
|
||||
return {**res, "first_row": FIRST_DATA_ROW, "last_row": table["last_row"]}
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 밀크런 출고리스트 직접 작성 — 상자 계산 없이 팝업에서 입력한 센터 1곳을
|
||||
# 구글 시트의 출고일 시트(YYYYMMDD(요일)) 맨 아래에 덧붙인다. cupang_db 에는 저장하지 않는다.
|
||||
# ════════════════════════════════════════════════════════════
|
||||
OUTBOUND_SHEET_METHODS: tuple[str, ...] = ("파렛트", "택배")
|
||||
_SHEET_CENTERS_TTL_SECONDS = 600
|
||||
_sheet_centers_cache: dict[str, Any] = {"at": 0.0, "sheet": "", "names": []}
|
||||
|
||||
|
||||
def _sheet_text(value: Any, *, label: str, max_len: int, required: bool = True) -> str:
|
||||
text = str(value or "").strip()
|
||||
if required and not text:
|
||||
raise HTTPException(status_code=400, detail=f"{label}을(를) 입력해 주세요.")
|
||||
if len(text) > max_len:
|
||||
raise HTTPException(status_code=400, detail=f"{label}은(는) {max_len}자까지 입력할 수 있습니다.")
|
||||
# USER_ENTERED 로 쓰므로 '=' 로 시작하면 수식이 된다 — 글자 그대로 남긴다.
|
||||
return "'" + text if text.startswith("=") else text
|
||||
|
||||
|
||||
def _sheet_date(value: Any, *, label: str) -> str:
|
||||
try:
|
||||
return _date.fromisoformat(str(value or "").strip()).isoformat()
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=400, detail=f"{label}을(를) 선택해 주세요.") from None
|
||||
|
||||
|
||||
def _clean_outbound_entry(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""팝업 입력 → export.build_block 이 읽는 출고 묶음 모양."""
|
||||
method = str(payload.get("ship_method") or "").strip()
|
||||
if method not in OUTBOUND_SHEET_METHODS:
|
||||
raise HTTPException(status_code=400, detail="출고방식은 파렛트 또는 택배 중에서 골라 주세요.")
|
||||
|
||||
raw_lines = payload.get("lines")
|
||||
if not isinstance(raw_lines, list) or not raw_lines:
|
||||
raise HTTPException(status_code=400, detail="제품을 1개 이상 추가해 주세요.")
|
||||
if len(raw_lines) > 100:
|
||||
raise HTTPException(status_code=400, detail="제품은 한 번에 100줄까지 입력할 수 있습니다.")
|
||||
lines = []
|
||||
for i, ln in enumerate(raw_lines, start=1):
|
||||
if not isinstance(ln, dict):
|
||||
raise HTTPException(status_code=400, detail=f"{i}번째 제품 정보를 확인해 주세요.")
|
||||
try:
|
||||
qty = int(str(ln.get("quantity") or "").replace(",", "").strip())
|
||||
except ValueError:
|
||||
qty = 0
|
||||
if not 1 <= qty <= 1_000_000:
|
||||
raise HTTPException(status_code=400, detail=f"{i}번째 제품의 수량을 확인해 주세요.")
|
||||
lines.append({
|
||||
"product_code": _sheet_text(ln.get("code"), label=f"{i}번째 제품코드", max_len=60),
|
||||
"product_name_snapshot": _sheet_text(ln.get("name"), label=f"{i}번째 제품명", max_len=200),
|
||||
"quantity": qty,
|
||||
})
|
||||
|
||||
return {
|
||||
"document_date": _sheet_date(payload.get("document_date"), label="작성일"),
|
||||
"ship_date": _sheet_date(payload.get("ship_date"), label="출고일"),
|
||||
"center_arrival_date": _sheet_date(payload.get("center_arrival_date"), label="센터입고일"),
|
||||
"center_name_snapshot": _sheet_text(payload.get("center"), label="입고센터", max_len=60),
|
||||
"ship_method": method,
|
||||
"outbound_summary": _sheet_text(payload.get("outbound"), label="출고", max_len=100, required=False),
|
||||
"worker": _sheet_text(payload.get("worker") or OUTBOUND_WORKER, label="작업자", max_len=30),
|
||||
"lines": lines,
|
||||
}
|
||||
|
||||
|
||||
def _sheet_centers(writer: Any, spreadsheet_id: str) -> list[str]:
|
||||
"""출고리스트 문서의 모든 시트 F열(입고센터, 6행부터)에 적힌 센터 이름. 10분 캐시."""
|
||||
import time # noqa: WPS433
|
||||
|
||||
from app.integrations.google_sheets import a1_sheet # noqa: WPS433
|
||||
|
||||
from .export import FIRST_DATA_ROW # noqa: WPS433
|
||||
|
||||
cache = _sheet_centers_cache
|
||||
if cache["sheet"] == spreadsheet_id and time.monotonic() - cache["at"] < _SHEET_CENTERS_TTL_SECONDS:
|
||||
return list(cache["names"])
|
||||
titles = writer.sheet_titles(spreadsheet_id=spreadsheet_id)
|
||||
columns = writer.read_ranges(
|
||||
spreadsheet_id=spreadsheet_id,
|
||||
ranges=[f"{a1_sheet(t)}!F{FIRST_DATA_ROW}:F" for t in titles],
|
||||
)
|
||||
names = sorted({
|
||||
str(row[0]).strip() for rows in columns for row in rows if row and str(row[0]).strip()
|
||||
})
|
||||
cache.update(at=time.monotonic(), sheet=spreadsheet_id, names=names)
|
||||
return list(names)
|
||||
|
||||
|
||||
def _append_outbound_entry(writer: Any, spreadsheet_id: str, entry: dict[str, Any]) -> dict[str, Any]:
|
||||
"""출고일 시트 맨 아래에 덧붙인다. 시트가 없거나 양식(5행 머리글)이 없으면 양식째 만든다."""
|
||||
from app.integrations.google_sheets import a1_sheet, col_letter # noqa: WPS433
|
||||
|
||||
from .export import ( # noqa: WPS433
|
||||
COL_FIRST, COL_LAST, FIRST_DATA_ROW, HEADER_ROW, PALLET_BG, build_block, sheet_title,
|
||||
)
|
||||
|
||||
title = sheet_title(entry["ship_date"])
|
||||
rows: list[list[Any]] = []
|
||||
if title in writer.sheet_titles(spreadsheet_id=spreadsheet_id):
|
||||
rows = writer.read_ranges(
|
||||
spreadsheet_id=spreadsheet_id,
|
||||
ranges=[f"{a1_sheet(title)}!A1:{col_letter(COL_LAST)}"],
|
||||
)[0]
|
||||
last_row = max(
|
||||
(i for i, row in enumerate(rows, start=1) if any(str(v).strip() for v in row)), default=0
|
||||
)
|
||||
if last_row < HEADER_ROW:
|
||||
return _write_full_sheet(writer, spreadsheet_id, entry["ship_date"], [entry])
|
||||
|
||||
# 순번(B열)은 시트에 이미 있는 가장 큰 번호 다음부터
|
||||
last_seq = 0
|
||||
for row in rows[FIRST_DATA_ROW - 1:]:
|
||||
text = str(row[1]).strip() if len(row) > 1 else ""
|
||||
if text.isdigit():
|
||||
last_seq = max(last_seq, int(text))
|
||||
block = build_block(entry, start_row=last_row + 1, start_seq=last_seq)
|
||||
return writer.append_block(
|
||||
spreadsheet_id=spreadsheet_id,
|
||||
title=title,
|
||||
cells=block["cells"],
|
||||
merges=block["merges"],
|
||||
first_row=block["first_row"],
|
||||
last_row=block["last_row"],
|
||||
first_col=COL_FIRST,
|
||||
last_col=COL_LAST,
|
||||
highlight=PALLET_BG if block["is_pallet"] else "",
|
||||
)
|
||||
|
||||
|
||||
@router.get("/api/outbound-sheet/centers")
|
||||
def outbound_sheet_centers(
|
||||
request: Request, _: dict[str, Any] = Depends(_require_user)
|
||||
) -> JSONResponse:
|
||||
"""입고센터 후보 — 출고리스트 문서에 적힌 센터 + 설정에 등록된 센터."""
|
||||
store = _store(request)
|
||||
names = {c["name"] for c in store.list_centers()} if store else set()
|
||||
reason = ""
|
||||
writer, spreadsheet_id, skip = _sheet_target(store)
|
||||
if skip:
|
||||
reason = str(skip.get("reason") or "")
|
||||
else:
|
||||
try:
|
||||
names.update(_sheet_centers(writer, spreadsheet_id))
|
||||
except Exception as exc: # noqa: BLE001 - 목록은 등록 센터만으로도 쓸 수 있다
|
||||
reason = f"구글 시트를 읽지 못했습니다({type(exc).__name__})"
|
||||
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 = _sheet_target(_store(request))
|
||||
if skip:
|
||||
raise HTTPException(
|
||||
status_code=503, detail=f"구글 시트에 쓸 수 없습니다: {skip.get('reason') or '설정 확인 필요'}"
|
||||
)
|
||||
try:
|
||||
# 시트 끝 위치를 읽고 쓰는 사이에 다른 요청이 끼어들지 않게 한 덩어리로
|
||||
with writer.lock:
|
||||
res = _append_outbound_entry(writer, spreadsheet_id, entry)
|
||||
except Exception as exc: # noqa: BLE001 - 사유만 남긴다(비밀값 미출력)
|
||||
_log_sheet("manual-append", entry["ship_date"], {"ok": False, "reason": type(exc).__name__})
|
||||
raise HTTPException(
|
||||
status_code=502, detail=f"구글 시트에 기록하지 못했습니다({type(exc).__name__}). 잠시 후 다시 시도해 주세요."
|
||||
) from exc
|
||||
_log_sheet("manual-append", entry["ship_date"], {"ok": True, "action": f"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"])})
|
||||
|
||||
|
||||
@router.get("/export.xlsx")
|
||||
def export_shipments_xlsx(request: Request, date: str = "") -> Any:
|
||||
"""출고일 기준 출고리스트 엑셀 다운로드. 시트명 = YYYYMMDD."""
|
||||
|
||||
Reference in New Issue
Block a user