From db19a2fcbf548fe8eb1cd1484f145ffa77c9398b Mon Sep 17 00:00:00 2001 From: king Date: Tue, 1 Sep 2026 14:26:24 +0900 Subject: [PATCH] =?UTF-8?q?feat(cupang):=20=ED=99=95=EC=A0=95=20=EC=8B=9C?= =?UTF-8?q?=20Google=20=EC=8A=A4=ED=94=84=EB=A0=88=EB=93=9C=EC=8B=9C?= =?UTF-8?q?=ED=8A=B8=EC=97=90=20=EC=B6=9C=EA=B3=A0=EC=9D=BC=20=EC=8B=9C?= =?UTF-8?q?=ED=8A=B8=20=EA=B8=B0=EB=A1=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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 --- .env.example | 8 + CLAUDE.md | 2 +- app/integrations/google_sheets.py | 223 ++++++++++++++++++ app/modules/cupang/export.py | 140 +++++++++++ app/modules/cupang/router.py | 151 +++++------- .../cupang/templates/cupang/box_calc.html | 10 +- requirements.txt | 2 + 7 files changed, 442 insertions(+), 94 deletions(-) create mode 100644 app/integrations/google_sheets.py create mode 100644 app/modules/cupang/export.py diff --git a/.env.example b/.env.example index 1b289ae..e0e56b5 100644 --- a/.env.example +++ b/.env.example @@ -26,6 +26,14 @@ CUSTOMER_ORDER_LIST_URL=/orderlist/ # DB/역할/스키마/센터 seed 생성: scripts/sql/cupang_db_init.sql 참고. # CUPANG_DB_URL=postgresql://cupang_app:replace-me@postgres-db:5432/cupang_db +# 쿠팡 밀크런 출고리스트를 기록할 Google 스프레드시트 (분배 확정 시 출고일 시트 생성) +# - 대상 문서는 반드시 "Google 스프레드시트" 형식(업로드한 .xlsx 는 파일>Google 스프레드시트로 저장) +# - 서비스 계정 이메일(client_email)에 해당 문서를 편집자로 공유해야 한다 +# CUPANG_SHEET_ID=1J74op7lBZOgE27p4R28I3RWsv0EtXdii +# GOOGLE_SHEETS_CREDENTIALS=/opt/www/main/secrets/google-sheets-sa.json +# 또는 파일 대신 JSON 본문을 통째로 (한 줄): +# GOOGLE_SHEETS_CREDENTIALS_JSON={"type":"service_account", ...} + # ─── 휴가 관리 모듈 (vacation_db) ─── # 설정해야 모듈이 동작한다(미설정 시 "설정 필요" 안내, JSON 폴백 없음). # DB/역할/스키마/공휴일 seed 생성: scripts/sql/vacation_db_init.sql 참고. diff --git a/CLAUDE.md b/CLAUDE.md index e1fc820..e6f3d16 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -31,7 +31,7 @@ Claude Code는 이 저장소에서 작업을 시작하기 전에 **반드시 아 - 반품관리 - 외부 쇼핑몰 API 연동 (카페24, 네이버 스마트스토어, 사방넷 등) - 개인경비 (`app/modules/expense/`, `expense_db`) -- 쿠팡 밀크런 (`app/modules/cupang/`, `cupang_db`) — 출고 달력/박스 계산/입고센터 관리, 상품은 `itemcode_db` 읽기 전용. 출고 묶음은 **박스 계산 화면의 [분배 확정] 으로만** 만든다(신규 등록 폼 없음, `/cupang/new` 는 박스 계산으로 리다이렉트). 확정 조건: 미배분 박스 0 + 담긴 센터마다 출고방식(택배/파렛트) 선택. 확정 시 센터마다 출고 묶음 1건(`status=출고준비`, 센터입고일=출고일+1일) + 출고리스트 엑셀 자동 다운로드(`GET /cupang/export.xlsx?date=`, 시트명 YYYYMMDD). 작업 중 상태는 `cupang_box_calc_drafts` 에 이름 붙여 임시 저장/불러오기. 쿠팡 발주 엑셀(xlsx) 다중 업로드 지원(`POST /cupang/api/box-calc/upload`, openpyxl) — F13 입고예정일의 하루 전 = 출고일, 22행부터 B=쿠팡상품코드·F=센터명·G=수량을 읽어 `cupang_products.coupang_item_code` 로 제품 매칭 후 센터별 합산 → 센터 단위로 박스 계산·자동 배분 +- 쿠팡 밀크런 (`app/modules/cupang/`, `cupang_db`) — 출고 달력/박스 계산/입고센터 관리, 상품은 `itemcode_db` 읽기 전용. 출고 묶음은 **박스 계산 화면의 [분배 확정] 으로만** 만든다(신규 등록 폼 없음, `/cupang/new` 는 박스 계산으로 리다이렉트). 확정 조건: 미배분 박스 0 + 담긴 센터마다 출고방식(택배/파렛트) 선택. 확정 시 센터마다 출고 묶음 1건(`status=출고준비`, 센터입고일=출고일+1일) + 출고리스트 엑셀 자동 다운로드(`GET /cupang/export.xlsx?date=`, 시트명 YYYYMMDD). 양식 생성은 `app/modules/cupang/export.py` 한 곳에서 만들어 xlsx·구글시트가 공유. `CUPANG_SHEET_ID` + 서비스 계정(`GOOGLE_SHEETS_CREDENTIALS[_JSON]`) 설정 시 확정과 동시에 Google 스프레드시트에 출고일 시트를 생성/덮어쓰기(`app/integrations/google_sheets.py`, 미설정이면 조용히 skip). 작업 중 상태는 `cupang_box_calc_drafts` 에 이름 붙여 임시 저장/불러오기. 쿠팡 발주 엑셀(xlsx) 다중 업로드 지원(`POST /cupang/api/box-calc/upload`, openpyxl) — F13 입고예정일의 하루 전 = 출고일, 22행부터 B=쿠팡상품코드·F=센터명·G=수량을 읽어 `cupang_products.coupang_item_code` 로 제품 매칭 후 센터별 합산 → 센터 단위로 박스 계산·자동 배분 - 휴가 관리 (`app/modules/vacation/`, `vacation_db`) — 월간 달력(구글식 bar)/연차·반차 신청/승인 워크플로/공휴일·연차 설정. 권한키 `vacation`·`vacation_approver` - 말레이시아 창고 재고관리 (`app/modules/malaysia/`, `malaysia_stock_db`) — 낱개(MT/MX/MZ) 입출고·조정, 세트(MY) BOM, 일일 재고조사(세트→낱개 자동 분해), 현재고 현황. 뚜껑(MD-)은 재고 집계 제외 — 단, 창고 랙에는 위치 확인용으로 배치 가능(`store.LID_ITEMS`). 상품은 `itemcode_db` 읽기 전용. 권한키 `malaysia` - 말레이시아 배송 (`app/modules/dispatch/`, `dispatch_db`) — TikTok·Shopee 출고관리. 플랫폼별 데이터 엑셀 업로드(TikTok=03_TikTok_Order_Export.xlsx, Shopee=Packing List.Doorstep Delivery.xlsx) → 1박스=1카드 출고 작업 리스트·SKU 피킹 요약·Kagayaku 전달표 자동 생성. 1박스 묶음 기준 Package ID > Tracking ID > Order ID, 같은 박스 같은 SKU 합산. 작업 상태 토글(`dispatch_logs` 기록). 받는 사람 이름/전화/주소는 박스 단위로 저장(작업 카드 표시 + 출고 엑셀 생성용 — 개인정보). 배치 다운로드 zip 에 업로드 원본 + 취합 출고 엑셀(`YYYY.MM.DD(Ddd)_tictoc|shopee.xlsx`) 포함. 엑셀은 openpyxl 파싱/생성. 권한키 `dispatch`. 상세는 `docs/DISPATCH_MODULE.md` diff --git a/app/integrations/google_sheets.py b/app/integrations/google_sheets.py new file mode 100644 index 0000000..6e4c100 --- /dev/null +++ b/app/integrations/google_sheets.py @@ -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 diff --git a/app/modules/cupang/export.py b/app/modules/cupang/export.py new file mode 100644 index 0000000..271b50e --- /dev/null +++ b/app/modules/cupang/export.py @@ -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 diff --git a/app/modules/cupang/router.py b/app/modules/cupang/router.py index ea5a6cb..38f6c5b 100644 --- a/app/modules/cupang/router.py +++ b/app/modules/cupang/router.py @@ -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}) # ════════════════════════════════════════════════════════════ diff --git a/app/modules/cupang/templates/cupang/box_calc.html b/app/modules/cupang/templates/cupang/box_calc.html index 74ef9fb..9326713 100644 --- a/app/modules/cupang/templates/cupang/box_calc.html +++ b/app/modules/cupang/templates/cupang/box_calc.html @@ -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); diff --git a/requirements.txt b/requirements.txt index 7c35860..b68d6d6 100644 --- a/requirements.txt +++ b/requirements.txt @@ -12,3 +12,5 @@ pdfplumber>=0.11 pillow>=10.0 # 카페24 OAuth 토큰 암호화 저장(Fernet) — app/integrations/cafe24/crypto.py cryptography>=42.0 +google-api-python-client>=2.100 +google-auth>=2.30