Files
dbx-main/app/modules/cupang/export.py
T
king 0979a89ed9 feat(cupang): 쿠팡 로켓 매출 화면 + cupang_sales 테이블
- scripts/sql/cupang_db_006_sales.sql: cupang_sales(발주 라인) / cupang_sales_weekly(광고비·할인·장려금) 생성
- scripts/sql/cupang_sales_seed.sql: 구글 시트 초기 데이터 2,218행 + 주차비용 100건
  (공급가 합계가 시트 2024/2025 총계와 일치)
- /cupang/sales: 기간·센터·발주유형·검색 조회, 합계 KPI(공급가/원가/물류비/마진/순마진),
  행 추가·수정·삭제, 시트(xlsx·csv) 업로드 일괄 등록, 조회 조건 그대로 엑셀 다운로드
- 달력 상단에 "쿠팡 로켓 매출" 버튼 추가
- sales_import.py: 병합 머리글 3행 건너뛰고 라인/주차 소계 분리, 월계·총계는 저장하지 않음

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-02 16:03:08 +09:00

351 lines
13 KiB
Python

"""쿠팡로켓 밀크런 출고리스트 양식 생성.
- 한 벌의 표 데이터를 만들어 두 곳에서 같이 쓴다.
· 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)
# 열 너비 — 구글 시트 기준 픽셀. xlsx 는 문자폭(px/7)으로 환산해서 쓴다.
WIDTHS_PX = {
1: 10, # A (여백)
2: 45, # B 구분
3: 106, # C 작성일
4: 106, # D 출고일
5: 106, # E 센터입고일
6: 90, # F 입고센터
7: 80, # G 출고방식
8: 95, # H 제품코드
9: 210, # I 제품명
10: 60, # J 수량
11: 120, # K 출고
12: 90, # L 작업자
}
PX_PER_CHAR = 7.0
HEADER_BG = "DBE9F7" # 머리글 행 배경
PALLET_BG = "FAE2D5" # 출고방식이 파렛트인 센터 블록 배경
PALLET_METHOD = "파렛트"
TITLE_ROW = 2
COMPANY_ROW = 4
HEADER_ROW = 5
FIRST_DATA_ROW = 6
def with_dow(value: str) -> str:
"""YYYY-MM-DD → "YYYY-MM-DD(요일)". 날짜가 아니면 원문 그대로."""
text = (value or "").strip()
try:
d = _date.fromisoformat(text)
except ValueError:
return text
return f"{text}({DOW[d.weekday()]})"
def sheet_title(ship_date: str) -> str:
"""시트명 = 출고일 YYYYMMDD(요일)."""
d = _date.fromisoformat(ship_date)
return f"{d.strftime('%Y%m%d')}({DOW[d.weekday()]})"
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()]}) 쿠팡로켓 밀크런 출고리스트"
pallet_ranges: list[tuple[int, int]] = []
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
method = sh.get("ship_method") or ""
if method == PALLET_METHOD:
pallet_ranges.append((start, end))
block = {
# 날짜는 요일까지 표기 — 2026-09-03(목)
3: with_dow(str(sh.get("document_date") or "")),
4: with_dow(str(sh.get("ship_date") or "")),
5: with_dow(str(sh.get("center_arrival_date") or "")),
6: sh.get("center_name_snapshot") or "",
7: method,
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,
"pallet_ranges": pallet_ranges,
}
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, PatternFill, 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
header_fill = PatternFill("solid", fgColor=HEADER_BG)
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
head.fill = header_fill
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
# 파렛트 출고 블록은 배경색으로 구분
pallet_fill = PatternFill("solid", fgColor=PALLET_BG)
for (r1, r2) in table["pallet_ranges"]:
for row in range(r1, r2 + 1):
for col in range(COL_FIRST, COL_LAST + 1):
ws.cell(row=row, column=col).fill = pallet_fill
for col, px in WIDTHS_PX.items():
ws.column_dimensions[get_column_letter(col)].width = round(px / PX_PER_CHAR, 2)
ws.row_dimensions[TITLE_ROW].height = 28
return wb
# ── 상자 목록(상자 번호별 내용물) ──────────────────────────────
BOX_HEADERS = ["상자번호", "제품명", "제품코드", "수량"]
BOX_WIDTHS_PX = {1: 70, 2: 240, 3: 110, 4: 70}
def build_box_list_workbook(shipment: dict[str, Any], box_list: list[dict[str, Any]]) -> Any:
"""상자 번호 · 제품명 · 제품코드 · 수량 한 줄씩. 시트명 = YYYYMMDD(요일)."""
from openpyxl import Workbook
from openpyxl.styles import Alignment, Border, Font, PatternFill, Side
from openpyxl.utils import get_column_letter
ship_date = str(shipment.get("ship_date") or "")
center = str(shipment.get("center_name_snapshot") or "")
wb = Workbook()
ws = wb.active
ws.title = sheet_title(ship_date) if ship_date else "상자목록"
thin = Side(style="thin", color="000000")
box = Border(left=thin, right=thin, top=thin, bottom=thin)
center_align = Alignment(horizontal="center", vertical="center")
left_align = Alignment(horizontal="left", vertical="center")
ws.cell(row=1, column=1, value=f"{with_dow(ship_date)} {center} 상자 목록")
ws.cell(row=1, column=1).font = Font(size=14, bold=True)
ws.merge_cells(start_row=1, start_column=1, end_row=1, end_column=len(BOX_HEADERS))
header_fill = PatternFill("solid", fgColor=HEADER_BG)
for idx, name in enumerate(BOX_HEADERS, start=1):
cell = ws.cell(row=2, column=idx, value=name)
cell.font = Font(bold=True)
cell.alignment = center_align
cell.border = box
cell.fill = header_fill
row = 3
for entry in box_list:
contents = entry.get("items") or []
first = row
for it in contents:
ws.cell(row=row, column=1, value=entry.get("no"))
ws.cell(row=row, column=2, value=it.get("product_name") or "")
ws.cell(row=row, column=3, value=it.get("product_code") or "")
ws.cell(row=row, column=4, value=int(it.get("quantity") or 0))
row += 1
# 한 상자에 여러 제품이면 상자번호 칸을 세로로 합친다.
if row - first > 1:
ws.merge_cells(start_row=first, start_column=1, end_row=row - 1, end_column=1)
last = row - 1
for r in range(3, last + 1):
for col in range(1, len(BOX_HEADERS) + 1):
cell = ws.cell(row=r, column=col)
cell.border = box
cell.alignment = left_align if col == 2 else center_align
for col, px in BOX_WIDTHS_PX.items():
ws.column_dimensions[get_column_letter(col)].width = round(px / PX_PER_CHAR, 2)
ws.row_dimensions[1].height = 24
return wb
# ── 쿠팡 로켓 매출 ────────────────────────────────────────────
SALES_HEADERS = [
"주차", "순번", "발주번호", "발주유형", "발주일", "출고일", "센터입고일",
"SKUID", "바코드", "품목", "수량", "입고센터",
"공급단가", "공급가", "원가(단가)", "원가(발주량)",
"피킹비단가", "피킹비합계", "밀크런/쉽먼트", "물류비합계", "물류비중(%)",
"마진", "마진율(%)", "재고차감",
]
SALES_KEYS = [
"week_label", "seq", "po_no", "po_type", "order_date", "ship_date",
"center_arrival_date", "sku_id", "barcode", "item_name", "quantity",
"center_name", "supply_unit_price", "supply_amount", "cost_unit_price",
"cost_amount", "picking_unit_price", "picking_amount", "milkrun_amount",
"logistics_total", "logistics_ratio", "margin", "margin_rate",
"stock_deduct_memo",
]
SALES_WIDTHS_PX = {
1: 150, 2: 50, 3: 90, 4: 80, 5: 90, 6: 90, 7: 90, 8: 80, 9: 110,
10: 130, 11: 60, 12: 80, 13: 80, 14: 100, 15: 80, 16: 100,
17: 80, 18: 90, 19: 100, 20: 100, 21: 80, 22: 100, 23: 80, 24: 140,
}
MONEY_COLS = {13, 14, 15, 16, 17, 18, 19, 20, 22}
RATE_COLS = {21, 23}
def build_sales_workbook(rows: list[dict[str, Any]], totals: dict[str, Any]) -> Any:
"""매출 조회 결과 → xlsx. 마지막 행에 합계."""
from openpyxl import Workbook
from openpyxl.styles import Alignment, Border, Font, PatternFill, Side
from openpyxl.utils import get_column_letter
wb = Workbook()
ws = wb.active
ws.title = "쿠팡 로켓 매출"
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")
right_align = Alignment(horizontal="right", vertical="center")
header_fill = PatternFill("solid", fgColor=HEADER_BG)
for idx, name in enumerate(SALES_HEADERS, start=1):
cell = ws.cell(row=1, column=idx, value=name)
cell.font = Font(bold=True)
cell.alignment = center_align
cell.border = box
cell.fill = header_fill
for r_i, row in enumerate(rows, start=2):
for c_i, key in enumerate(SALES_KEYS, start=1):
value = row.get(key)
if key in ("quantity", "seq"):
value = int(value) if value not in (None, "") else None
elif c_i in MONEY_COLS or c_i in RATE_COLS:
value = float(value or 0)
cell = ws.cell(row=r_i, column=c_i, value=value)
cell.border = box
if c_i in MONEY_COLS:
cell.number_format = "#,##0"
cell.alignment = right_align
elif c_i in RATE_COLS:
cell.number_format = "0.00"
cell.alignment = right_align
elif c_i in (10, 1, 24):
cell.alignment = left_align
else:
cell.alignment = center_align
last = len(rows) + 2
total_fill = PatternFill("solid", fgColor="F2F2F2")
ws.cell(row=last, column=1, value=f"합계 {totals.get('count', 0)}")
for col, key in ((11, "quantity"), (14, "supply_amount"), (16, "cost_amount"),
(20, "logistics_total"), (22, "margin")):
ws.cell(row=last, column=col, value=float(totals.get(key) or 0))
ws.cell(row=last, column=21, value=float(totals.get("logistics_ratio") or 0))
ws.cell(row=last, column=23, value=float(totals.get("margin_rate") or 0))
for col in range(1, len(SALES_HEADERS) + 1):
cell = ws.cell(row=last, column=col)
cell.font = Font(bold=True)
cell.border = box
cell.fill = total_fill
if col in MONEY_COLS or col == 11:
cell.number_format = "#,##0"
cell.alignment = right_align
elif col in RATE_COLS:
cell.number_format = "0.00"
cell.alignment = right_align
for col, px in SALES_WIDTHS_PX.items():
ws.column_dimensions[get_column_letter(col)].width = round(px / PX_PER_CHAR, 2)
ws.freeze_panes = "A2"
ws.auto_filter.ref = f"A1:{get_column_letter(len(SALES_HEADERS))}{max(last - 1, 1)}"
return wb