feat(cupang): 확정 시 Google 스프레드시트에 출고일 시트 기록

- app/modules/cupang/export.py: 출고리스트 양식(셀/병합)을 한 곳에서 생성 →
  xlsx 다운로드와 구글 시트 기록이 같은 표를 쓴다
- app/integrations/google_sheets.py: 서비스 계정 기반 시트 쓰기 공통 계층
  (없거나 미설정이면 enabled=False 로 조용히 skip, 키는 로그에 남기지 않음)
- 확정 응답에 sheet 결과 포함, 화면에 성공/실패 메시지 표시
- env: CUPANG_SHEET_ID, GOOGLE_SHEETS_CREDENTIALS(_JSON) 추가
- requirements: google-api-python-client, google-auth

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
2026-09-01 14:26:24 +09:00
parent afa144fc02
commit db19a2fcbf
7 changed files with 442 additions and 94 deletions
+60 -91
View File
@@ -239,93 +239,66 @@ async def index(request: Request) -> HTMLResponse:
# ════════════════════════════════════════════════════════════
# 출고리스트 엑셀 — 확정한 출고일 기준 (쿠팡로켓 밀크런 양식)
# ════════════════════════════════════════════════════════════
EXPORT_COMPANY = "㈜더블엑스코퍼레이션"
EXPORT_WORKER = "핫프렌즈"
EXPORT_DOW = ["", "", "", "", "", "", ""]
EXPORT_HEADERS = [
"구분", "작성일", "출고일", "센터입고일", "입고센터", "출고방식",
"제품코드", "제품명", "수량", "출고", "작업자",
]
def _shipments_for_date(store: Any, ship_date: str) -> list[dict[str, Any]]:
"""해당 출고일의 출고 묶음(라인 포함) — 취소 제외, 센터명 순."""
heads = [
h for h in store.list_shipments(date_from=ship_date, date_to=ship_date)
if h.get("status") != "취소"
]
out: list[dict[str, Any]] = []
for h in sorted(heads, key=lambda x: (x.get("center_name_snapshot") or "")):
full = store.get_shipment(shipment_id=h["id"])
if full:
out.append(full)
return out
def _export_workbook(ship_date: str, shipments: list[dict[str, Any]]) -> Any:
"""출고 묶음 목록 → 스크린샷 양식의 워크북. 시트명은 출고일(YYYYMMDD)."""
from openpyxl import Workbook # noqa: WPS433
from openpyxl.styles import Alignment, Border, Font, Side # noqa: WPS433
from openpyxl.utils import get_column_letter # noqa: WPS433
def _push_to_google_sheet(store: Any, ship_date: str) -> dict[str, Any]:
"""확정한 출고일을 Google 스프레드시트에 시트 1장으로 기록.
d = _date.fromisoformat(ship_date)
tag = d.strftime("%Y%m%d")
- 대상 스프레드시트: 환경변수 `CUPANG_SHEET_ID`
- 인증: 서비스 계정(app/integrations/google_sheets.py). 미설정이면 조용히 skip.
- 실패해도 출고 묶음 저장은 이미 끝났으므로 예외를 밖으로 던지지 않는다.
"""
import os # noqa: WPS433
wb = Workbook()
ws = wb.active
ws.title = tag
from app.integrations.google_sheets import get_writer # noqa: WPS433
thin = Side(style="thin", color="000000")
box = Border(left=thin, right=thin, top=thin, bottom=thin)
center_align = Alignment(horizontal="center", vertical="center", wrap_text=True)
left_align = Alignment(horizontal="left", vertical="center", wrap_text=True)
from .export import ( # noqa: WPS433
COL_FIRST, COL_LAST, FIRST_DATA_ROW, HEADER_ROW, TITLE_ROW, WIDTHS,
build_table, sheet_title,
)
# 제목 (B2:L2)
ws.merge_cells(start_row=2, start_column=2, end_row=2, end_column=12)
title = ws.cell(row=2, column=2, value=f"{tag}({EXPORT_DOW[d.weekday()]}) 쿠팡로켓 밀크런 출고리스트")
title.font = Font(size=16, bold=True)
title.alignment = center_align
spreadsheet_id = (os.getenv("CUPANG_SHEET_ID") or "").strip()
if not spreadsheet_id:
return {"ok": False, "skipped": True, "reason": "CUPANG_SHEET_ID 미설정"}
ws.cell(row=4, column=2, value=EXPORT_COMPANY).font = Font(size=11)
writer = get_writer()
if not writer.enabled:
return {"ok": False, "skipped": True, "reason": writer.reason}
# 머리글 (B5:L5)
for i, name in enumerate(EXPORT_HEADERS):
c = ws.cell(row=5, column=2 + i, value=name)
c.font = Font(bold=True)
c.alignment = center_align
c.border = box
shipments = _shipments_for_date(store, ship_date)
if not shipments:
return {"ok": False, "skipped": True, "reason": "해당 출고일의 출고 묶음 없음"}
row = 6
seq = 0
document_date = ""
for sh in shipments:
lines = sh.get("lines") or []
if not lines:
continue
document_date = str(sh.get("document_date") or document_date)
start = row
for ln in lines:
seq += 1
ws.cell(row=row, column=2, value=seq) # 구분
ws.cell(row=row, column=8, value=ln.get("product_code") or "") # 제품코드
ws.cell(row=row, column=9, value=ln.get("product_name_snapshot") or "") # 제품명
ws.cell(row=row, column=10, value=int(ln.get("quantity") or 0)) # 수량
row += 1
end = row - 1
# 센터 단위로 병합되는 칸들
merged_cols = {
3: str(sh.get("document_date") or ""),
4: str(sh.get("ship_date") or ""),
5: str(sh.get("center_arrival_date") or ""),
6: sh.get("center_name_snapshot") or "",
7: sh.get("ship_method") or "",
11: sh.get("outbound_summary") or "",
12: EXPORT_WORKER,
}
for col, value in merged_cols.items():
if end > start:
ws.merge_cells(start_row=start, start_column=col, end_row=end, end_column=col)
ws.cell(row=start, column=col, value=value)
for r in range(start, end + 1):
for col in range(2, 13):
cell = ws.cell(row=r, column=col)
cell.border = box
cell.alignment = left_align if col == 9 else center_align
widths = {2: 6, 3: 12, 4: 12, 5: 12, 6: 11, 7: 10, 8: 12, 9: 26, 10: 8, 11: 12, 12: 11}
for col, w in widths.items():
ws.column_dimensions[get_column_letter(col)].width = w
ws.row_dimensions[2].height = 28
return wb
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,
)
except Exception as exc: # noqa: BLE001 - 시트 기록 실패는 경고로만 알린다
return {"ok": False, "skipped": False, "reason": f"{type(exc).__name__}: {exc}"}
return {"ok": True, "skipped": False, **res}
@router.get("/export.xlsx")
@@ -335,6 +308,8 @@ async def export_shipments_xlsx(request: Request, date: str = "") -> Any:
from fastapi.responses import StreamingResponse # noqa: WPS433
from .export import build_workbook # noqa: WPS433
guard = _guard(request)
if not isinstance(guard, tuple):
return guard
@@ -346,24 +321,15 @@ async def export_shipments_xlsx(request: Request, date: str = "") -> Any:
except ValueError:
raise HTTPException(status_code=400, detail="출고일자(date=YYYY-MM-DD)가 필요합니다.")
heads = [
s for s in store.list_shipments(date_from=ship_date, date_to=ship_date)
if s.get("status") != "취소"
]
shipments = []
for h in sorted(heads, key=lambda x: (x.get("center_name_snapshot") or "")):
full = store.get_shipment(shipment_id=h["id"])
if full:
shipments.append(full)
shipments = _shipments_for_date(store, ship_date)
if not shipments:
raise HTTPException(status_code=404, detail="해당 출고일의 출고 묶음이 없습니다.")
wb = _export_workbook(ship_date, shipments)
wb = build_workbook(ship_date, shipments)
buf = BytesIO()
wb.save(buf)
buf.seek(0)
tag = ship_date.replace("-", "")
filename = f"{tag}_cupang_milkrun.xlsx"
filename = f"{ship_date.replace('-', '')}_cupang_milkrun.xlsx"
return StreamingResponse(
buf,
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
@@ -1467,7 +1433,10 @@ async def box_calc_confirm(
raise HTTPException(status_code=400, detail=str(exc))
created.append({"id": ship["id"], "center_name": center["name"]})
return JSONResponse({"created": created, "ship_date": ship_date})
# 구글 스프레드시트에 출고일 시트 기록(설정돼 있을 때만).
sheet = _push_to_google_sheet(store, ship_date)
return JSONResponse({"created": created, "ship_date": ship_date, "sheet": sheet})
# ════════════════════════════════════════════════════════════