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:
@@ -0,0 +1,140 @@
|
||||
"""쿠팡로켓 밀크런 출고리스트 양식 생성.
|
||||
|
||||
- 한 벌의 표 데이터를 만들어 두 곳에서 같이 쓴다.
|
||||
· xlsx 다운로드(openpyxl)
|
||||
· Google 스프레드시트 기록(app/integrations/google_sheets.py)
|
||||
- 표 구조(스크린샷 양식)
|
||||
2행 B:L 제목 "YYYYMMDD(요일) 쿠팡로켓 밀크런 출고리스트"
|
||||
4행 B 회사명
|
||||
5행 B:L 머리글
|
||||
6행~ 품목 1줄 = 1행, 센터 단위로 작성일/출고일/센터입고일/입고센터/
|
||||
출고방식/출고/작업자 칸이 세로 병합
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date as _date
|
||||
from typing import Any
|
||||
|
||||
COMPANY = "㈜더블엑스코퍼레이션"
|
||||
WORKER = "핫프렌즈"
|
||||
DOW = ["월", "화", "수", "목", "금", "토", "일"]
|
||||
HEADERS = [
|
||||
"구분", "작성일", "출고일", "센터입고일", "입고센터", "출고방식",
|
||||
"제품코드", "제품명", "수량", "출고", "작업자",
|
||||
]
|
||||
# 열 번호(1-based): B=2 … L=12
|
||||
COL_FIRST = 2
|
||||
COL_LAST = 12
|
||||
# 센터 단위로 병합되는 열
|
||||
MERGE_COLS = (3, 4, 5, 6, 7, 11, 12)
|
||||
WIDTHS = {2: 6, 3: 12, 4: 12, 5: 12, 6: 11, 7: 10, 8: 12, 9: 26, 10: 8, 11: 12, 12: 11}
|
||||
|
||||
TITLE_ROW = 2
|
||||
COMPANY_ROW = 4
|
||||
HEADER_ROW = 5
|
||||
FIRST_DATA_ROW = 6
|
||||
|
||||
|
||||
def sheet_title(ship_date: str) -> str:
|
||||
"""시트명 = 출고일 YYYYMMDD."""
|
||||
return _date.fromisoformat(ship_date).strftime("%Y%m%d")
|
||||
|
||||
|
||||
def build_table(ship_date: str, shipments: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
"""출고 묶음(라인 포함) 목록 → 셀 값/병합 정보.
|
||||
|
||||
반환:
|
||||
title 제목 문자열
|
||||
cells {(row, col): value} (1-based, 시트 좌표 그대로)
|
||||
merges [(row1, col1, row2, col2), ...] (1-based, 양끝 포함)
|
||||
last_row 마지막 데이터 행
|
||||
"""
|
||||
d = _date.fromisoformat(ship_date)
|
||||
tag = d.strftime("%Y%m%d")
|
||||
title = f"{tag}({DOW[d.weekday()]}) 쿠팡로켓 밀크런 출고리스트"
|
||||
|
||||
cells: dict[tuple[int, int], Any] = {(TITLE_ROW, COL_FIRST): title,
|
||||
(COMPANY_ROW, COL_FIRST): COMPANY}
|
||||
merges: list[tuple[int, int, int, int]] = [(TITLE_ROW, COL_FIRST, TITLE_ROW, COL_LAST)]
|
||||
|
||||
for i, name in enumerate(HEADERS):
|
||||
cells[(HEADER_ROW, COL_FIRST + i)] = name
|
||||
|
||||
row = FIRST_DATA_ROW
|
||||
seq = 0
|
||||
for sh in shipments:
|
||||
lines = sh.get("lines") or []
|
||||
if not lines:
|
||||
continue
|
||||
start = row
|
||||
for ln in lines:
|
||||
seq += 1
|
||||
cells[(row, 2)] = seq
|
||||
cells[(row, 8)] = ln.get("product_code") or ""
|
||||
cells[(row, 9)] = ln.get("product_name_snapshot") or ""
|
||||
cells[(row, 10)] = int(ln.get("quantity") or 0)
|
||||
row += 1
|
||||
end = row - 1
|
||||
|
||||
block = {
|
||||
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: WORKER,
|
||||
}
|
||||
for col in MERGE_COLS:
|
||||
cells[(start, col)] = block[col]
|
||||
if end > start:
|
||||
merges.append((start, col, end, col))
|
||||
|
||||
return {"title": title, "cells": cells, "merges": merges, "last_row": row - 1}
|
||||
|
||||
|
||||
def build_workbook(ship_date: str, shipments: list[dict[str, Any]]) -> Any:
|
||||
"""xlsx 워크북(openpyxl). 시트명 = YYYYMMDD."""
|
||||
from openpyxl import Workbook
|
||||
from openpyxl.styles import Alignment, Border, Font, Side
|
||||
from openpyxl.utils import get_column_letter
|
||||
|
||||
table = build_table(ship_date, shipments)
|
||||
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
ws.title = sheet_title(ship_date)
|
||||
|
||||
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)
|
||||
|
||||
for (row, col), value in table["cells"].items():
|
||||
ws.cell(row=row, column=col, value=value)
|
||||
|
||||
for (r1, c1, r2, c2) in table["merges"]:
|
||||
ws.merge_cells(start_row=r1, start_column=c1, end_row=r2, end_column=c2)
|
||||
|
||||
title_cell = ws.cell(row=TITLE_ROW, column=COL_FIRST)
|
||||
title_cell.font = Font(size=16, bold=True)
|
||||
title_cell.alignment = center_align
|
||||
|
||||
for col in range(COL_FIRST, COL_LAST + 1):
|
||||
head = ws.cell(row=HEADER_ROW, column=col)
|
||||
head.font = Font(bold=True)
|
||||
head.alignment = center_align
|
||||
head.border = box
|
||||
|
||||
for row in range(FIRST_DATA_ROW, table["last_row"] + 1):
|
||||
for col in range(COL_FIRST, COL_LAST + 1):
|
||||
cell = ws.cell(row=row, column=col)
|
||||
cell.border = box
|
||||
cell.alignment = left_align if col == 9 else center_align
|
||||
|
||||
for col, width in WIDTHS.items():
|
||||
ws.column_dimensions[get_column_letter(col)].width = width
|
||||
ws.row_dimensions[TITLE_ROW].height = 28
|
||||
|
||||
return wb
|
||||
@@ -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})
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
|
||||
@@ -1331,6 +1331,10 @@
|
||||
var d = (data && data.ship_date) || picked;
|
||||
// 확정한 출고일의 출고리스트 엑셀을 내려받는다.
|
||||
window.location.href = "/cupang/export.xlsx?date=" + encodeURIComponent(d);
|
||||
// 구글 시트 기록 결과 (설정돼 있을 때만 동작)
|
||||
var sh = (data && data.sheet) || {};
|
||||
var sheetNote = sh.ok ? "구글 시트 " + (sh.title || "") + " 기록 완료"
|
||||
: (sh.skipped ? "" : "구글 시트 기록 실패 — " + (sh.reason || ""));
|
||||
// 업로드한 출고일이 여러 개면 남은 날짜 작업을 이어서 한다.
|
||||
var idx = dateOrder.indexOf(activeDate);
|
||||
if (idx >= 0 && dateOrder.length > 1) {
|
||||
@@ -1340,14 +1344,16 @@
|
||||
closeConfirm();
|
||||
activeDate = "";
|
||||
loadDate(dateOrder[Math.min(idx, dateOrder.length - 1)]);
|
||||
msg.textContent = done + " 출고 확정 완료 — 남은 출고일 " + dateOrder.length + "개";
|
||||
msg.textContent = done + " 출고 확정 완료 — 남은 출고일 " + dateOrder.length + "개" +
|
||||
(sheetNote ? " · " + sheetNote : "");
|
||||
poMsg.textContent = done + " 확정됨. 남은 날짜: " + dateOrder.join(", ");
|
||||
cfmOk.disabled = false;
|
||||
return;
|
||||
}
|
||||
var parts = d.split("-");
|
||||
// 달력으로 이동해 방금 만든 출고 묶음을 보여준다(엑셀 저장 뒤).
|
||||
cfmMsg.textContent = "출고리스트 엑셀을 저장했습니다. 달력으로 이동합니다…";
|
||||
cfmMsg.textContent = "출고리스트 엑셀을 저장했습니다." +
|
||||
(sheetNote ? " " + sheetNote + "." : "") + " 달력으로 이동합니다…";
|
||||
setTimeout(function () {
|
||||
window.location.href = "/cupang/?year=" + parts[0] + "&month=" + parseInt(parts[1], 10) + "&date=" + d;
|
||||
}, 1200);
|
||||
|
||||
Reference in New Issue
Block a user