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
+223
View File
@@ -0,0 +1,223 @@
"""Google 스프레드시트 쓰기 공통 계층 (서비스 계정).
- 다른 모듈에서도 쓸 수 있게 `app/integrations/` 에 둔다.
- 인증: 구글 클라우드 **서비스 계정** JSON.
· `GOOGLE_SHEETS_CREDENTIALS` 서비스 계정 JSON 파일 경로
· `GOOGLE_SHEETS_CREDENTIALS_JSON` JSON 본문(파일 대신 환경변수로 넣을 때)
대상 스프레드시트를 서비스 계정 이메일(client_email)에 **편집자로 공유**해야 한다.
- 비밀값(키)은 로그·화면에 절대 출력하지 않는다.
- 라이브러리(google-api-python-client)가 없거나 설정이 비어 있으면
`enabled = False` 로 조용히 비활성화되고, 호출부는 건너뛴다.
"""
from __future__ import annotations
import json
import os
from typing import Any
SCOPES = ["https://www.googleapis.com/auth/spreadsheets"]
class GoogleSheetsWriter:
"""시트 1장을 통째로 다시 쓰는 용도의 얇은 래퍼."""
def __init__(self) -> None:
self.enabled = False
self.reason = ""
self._service: Any = None
self._client_email = ""
raw = (os.getenv("GOOGLE_SHEETS_CREDENTIALS_JSON") or "").strip()
path = (os.getenv("GOOGLE_SHEETS_CREDENTIALS") or "").strip()
if not raw and not path:
self.reason = "GOOGLE_SHEETS_CREDENTIALS(_JSON) 미설정"
return
try:
info = json.loads(raw) if raw else json.loads(
open(path, encoding="utf-8").read()
)
except (OSError, ValueError):
self.reason = "서비스 계정 JSON 을 읽지 못했습니다."
return
try:
from google.oauth2.service_account import Credentials
from googleapiclient.discovery import build
except ImportError:
self.reason = "google-api-python-client 미설치"
return
try:
creds = Credentials.from_service_account_info(info, scopes=SCOPES)
self._service = build("sheets", "v4", credentials=creds, cache_discovery=False)
except Exception as exc: # noqa: BLE001 - 인증 실패 사유만 남긴다
self.reason = f"서비스 계정 인증 실패: {type(exc).__name__}"
return
self._client_email = str(info.get("client_email") or "")
self.enabled = True
@property
def client_email(self) -> str:
"""공유 대상 확인용(비밀값 아님)."""
return self._client_email
# ────────────────────────────────────────────────
def _sheet_id(self, spreadsheet_id: str, title: str) -> int | None:
meta = self._service.spreadsheets().get(spreadsheetId=spreadsheet_id).execute()
for sh in meta.get("sheets", []):
props = sh.get("properties", {})
if props.get("title") == title:
return int(props.get("sheetId"))
return None
def _create_sheet(self, spreadsheet_id: str, title: str) -> int:
res = self._service.spreadsheets().batchUpdate(
spreadsheetId=spreadsheet_id,
body={"requests": [{"addSheet": {"properties": {"title": title}}}]},
).execute()
return int(res["replies"][0]["addSheet"]["properties"]["sheetId"])
def write_table(
self,
*,
spreadsheet_id: str,
title: str,
cells: dict[tuple[int, int], Any],
merges: list[tuple[int, int, int, int]],
header_row: int,
first_data_row: int,
last_row: int,
first_col: int,
last_col: int,
title_row: int,
widths: dict[int, int],
) -> dict[str, Any]:
"""시트를 만들고(있으면 비우고) 표를 통째로 기록한다.
좌표는 모두 1-based(엑셀과 동일). 반환값에 시트 URL 을 담는다.
"""
if not self.enabled:
raise RuntimeError(self.reason or "Google Sheets 미설정")
sheet_id = self._sheet_id(spreadsheet_id, title)
created = sheet_id is None
if created:
sheet_id = self._create_sheet(spreadsheet_id, title)
rows_n = max([r for (r, _c) in cells] or [1])
cols_n = last_col
matrix: list[list[Any]] = [["" for _ in range(cols_n)] for _ in range(rows_n)]
for (r, c), value in cells.items():
matrix[r - 1][c - 1] = value
requests: list[dict[str, Any]] = [
# 기존 내용/서식/병합 초기화 → 같은 날짜로 다시 확정해도 깨끗하게 덮어쓴다
{"unmergeCells": {"range": {"sheetId": sheet_id}}},
{"updateCells": {"range": {"sheetId": sheet_id}, "fields": "*"}},
]
for (r1, c1, r2, c2) in merges:
requests.append({
"mergeCells": {
"mergeType": "MERGE_ALL",
"range": {
"sheetId": sheet_id,
"startRowIndex": r1 - 1, "endRowIndex": r2,
"startColumnIndex": c1 - 1, "endColumnIndex": c2,
},
}
})
def _fmt(r1: int, c1: int, r2: int, c2: int, fmt: dict[str, Any], fields: str) -> dict[str, Any]:
return {
"repeatCell": {
"range": {
"sheetId": sheet_id,
"startRowIndex": r1 - 1, "endRowIndex": r2,
"startColumnIndex": c1 - 1, "endColumnIndex": c2,
},
"cell": {"userEnteredFormat": fmt},
"fields": fields,
}
}
requests.append(_fmt(
title_row, first_col, title_row, last_col,
{"horizontalAlignment": "CENTER", "verticalAlignment": "MIDDLE",
"textFormat": {"bold": True, "fontSize": 16}},
"userEnteredFormat(horizontalAlignment,verticalAlignment,textFormat)",
))
requests.append(_fmt(
header_row, first_col, header_row, last_col,
{"horizontalAlignment": "CENTER", "verticalAlignment": "MIDDLE",
"textFormat": {"bold": True}},
"userEnteredFormat(horizontalAlignment,verticalAlignment,textFormat)",
))
if last_row >= first_data_row:
requests.append(_fmt(
first_data_row, first_col, last_row, last_col,
{"horizontalAlignment": "CENTER", "verticalAlignment": "MIDDLE",
"wrapStrategy": "WRAP"},
"userEnteredFormat(horizontalAlignment,verticalAlignment,wrapStrategy)",
))
# 제품명 칸만 왼쪽 정렬
requests.append(_fmt(
first_data_row, 9, last_row, 9,
{"horizontalAlignment": "LEFT"},
"userEnteredFormat(horizontalAlignment)",
))
border = {"style": "SOLID", "color": {"red": 0, "green": 0, "blue": 0}}
requests.append({
"updateBorders": {
"range": {
"sheetId": sheet_id,
"startRowIndex": header_row - 1, "endRowIndex": last_row,
"startColumnIndex": first_col - 1, "endColumnIndex": last_col,
},
"top": border, "bottom": border, "left": border, "right": border,
"innerHorizontal": border, "innerVertical": border,
}
})
for col, width in widths.items():
requests.append({
"updateDimensionProperties": {
"range": {
"sheetId": sheet_id, "dimension": "COLUMNS",
"startIndex": col - 1, "endIndex": col,
},
"properties": {"pixelSize": int(width) * 8},
"fields": "pixelSize",
}
})
self._service.spreadsheets().batchUpdate(
spreadsheetId=spreadsheet_id, body={"requests": requests}
).execute()
self._service.spreadsheets().values().update(
spreadsheetId=spreadsheet_id,
range=f"'{title}'!A1",
valueInputOption="USER_ENTERED",
body={"values": matrix},
).execute()
return {
"created": created,
"title": title,
"url": f"https://docs.google.com/spreadsheets/d/{spreadsheet_id}/edit#gid={sheet_id}",
}
_writer: GoogleSheetsWriter | None = None
def get_writer() -> GoogleSheetsWriter:
"""프로세스 1개당 1회 초기화."""
global _writer # noqa: PLW0603
if _writer is None:
_writer = GoogleSheetsWriter()
return _writer
+140
View File
@@ -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
+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})
# ════════════════════════════════════════════════════════════
@@ -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);