diff --git a/app/integrations/google_sheets.py b/app/integrations/google_sheets.py
index 2b251d3..0effa75 100644
--- a/app/integrations/google_sheets.py
+++ b/app/integrations/google_sheets.py
@@ -42,6 +42,37 @@ def _hex_color(value: str) -> dict[str, float]:
}
+def a1_sheet(title: str) -> str:
+ """A1 표기용 시트 이름 — 작은따옴표로 감싸고 안의 ' 는 '' 로."""
+ return "'" + title.replace("'", "''") + "'"
+
+
+def col_letter(col: int) -> str:
+ """1-based 열 번호 → 열 문자(A, B, …, AA)."""
+ letters = ""
+ while col > 0:
+ col, rem = divmod(col - 1, 26)
+ letters = chr(65 + rem) + letters
+ return letters
+
+
+def _repeat_cell(
+ sheet_id: int, r1: int, c1: int, r2: int, c2: int, fmt: dict[str, Any], fields: str
+) -> dict[str, Any]:
+ """1-based 양끝 포함 범위에 같은 서식을 입히는 요청."""
+ return {
+ "repeatCell": {
+ "range": {
+ "sheetId": sheet_id,
+ "startRowIndex": r1 - 1, "endRowIndex": r2,
+ "startColumnIndex": c1 - 1, "endColumnIndex": c2,
+ },
+ "cell": {"userEnteredFormat": fmt},
+ "fields": fields,
+ }
+ }
+
+
# 웹 핸들러가 sync def(스레드풀)라 여러 요청이 동시에 이 writer 를 쓸 수 있다.
# googleapiclient 의 HTTP 클라이언트(httplib2)는 스레드 안전하지 않고, 같은 날짜
# 시트를 동시에 지우고/쓰면 내용이 섞이므로 시트 작업은 한 번에 하나씩만 한다.
@@ -169,6 +200,144 @@ class GoogleSheetsWriter:
).execute()
return int(res["replies"][0]["addSheet"]["properties"]["sheetId"])
+ @property
+ def lock(self) -> Any:
+ """읽고 → 쓰기를 한 덩어리로 묶을 때 쓰는 잠금(같은 시트에 동시에 덧붙이지 않게).
+
+ RLock 이라 잡은 채로 이 writer 의 다른 메서드를 불러도 된다."""
+ return _LOCK
+
+ @_serialized
+ def sheet_titles(self, *, spreadsheet_id: str) -> list[str]:
+ """문서의 시트 이름 목록(탭 순서)."""
+ if not self.enabled:
+ raise RuntimeError(self.reason or "Google Sheets 미설정")
+ meta = self._service.spreadsheets().get(
+ spreadsheetId=spreadsheet_id, fields="sheets.properties.title"
+ ).execute()
+ return [str(sh.get("properties", {}).get("title") or "") for sh in meta.get("sheets", [])]
+
+ @_serialized
+ def read_ranges(
+ self, *, spreadsheet_id: str, ranges: list[str], chunk: int = 50
+ ) -> list[list[list[Any]]]:
+ """A1 범위 여러 개의 값(범위마다 2차원 목록). 요청 하나가 너무 길지 않게 나눠 읽는다."""
+ if not self.enabled:
+ raise RuntimeError(self.reason or "Google Sheets 미설정")
+ out: list[list[list[Any]]] = []
+ for i in range(0, len(ranges), chunk):
+ part = ranges[i:i + chunk]
+ res = self._service.spreadsheets().values().batchGet(
+ spreadsheetId=spreadsheet_id, ranges=part
+ ).execute()
+ got = res.get("valueRanges", [])
+ out.extend(vr.get("values", []) for vr in got)
+ out.extend([] for _ in range(len(part) - len(got)))
+ return out
+
+ @_serialized
+ def append_block(
+ self,
+ *,
+ spreadsheet_id: str,
+ title: str,
+ cells: dict[tuple[int, int], Any],
+ merges: list[tuple[int, int, int, int]],
+ first_row: int,
+ last_row: int,
+ first_col: int,
+ last_col: int,
+ left_cols: tuple[int, ...] = (9,),
+ highlight: str = "",
+ ) -> dict[str, Any]:
+ """이미 있는 시트의 first_row~last_row 에 표 한 덩어리를 쓴다(위쪽 내용은 그대로).
+
+ 서식은 write_table 의 데이터 행과 같다 — 가운데 정렬·줄바꿈·테두리, left_cols 만 왼쪽 정렬,
+ highlight("RRGGBB")가 있으면 그 덩어리 배경색. 좌표는 1-based."""
+ if not self.enabled:
+ raise RuntimeError(self.reason or "Google Sheets 미설정")
+
+ meta = self._service.spreadsheets().get(
+ spreadsheetId=spreadsheet_id,
+ fields="sheets.properties(sheetId,title,gridProperties.rowCount)",
+ ).execute()
+ props = next(
+ (sh.get("properties", {}) for sh in meta.get("sheets", [])
+ if sh.get("properties", {}).get("title") == title),
+ None,
+ )
+ if props is None:
+ raise LookupError(f"시트를 찾을 수 없습니다: {title}")
+ sheet_id = int(props.get("sheetId"))
+ row_count = int(props.get("gridProperties", {}).get("rowCount") or 0)
+
+ requests: list[dict[str, Any]] = []
+ if row_count < last_row:
+ # 격자보다 아래에는 값을 쓸 수 없으므로 행을 먼저 늘린다
+ requests.append({"appendDimension": {
+ "sheetId": sheet_id, "dimension": "ROWS", "length": last_row - row_count,
+ }})
+ 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,
+ },
+ }
+ })
+ requests.append(_repeat_cell(
+ sheet_id, first_row, first_col, last_row, last_col,
+ {"horizontalAlignment": "CENTER", "verticalAlignment": "MIDDLE", "wrapStrategy": "WRAP"},
+ "userEnteredFormat(horizontalAlignment,verticalAlignment,wrapStrategy)",
+ ))
+ for col in left_cols:
+ requests.append(_repeat_cell(
+ sheet_id, first_row, col, last_row, col,
+ {"horizontalAlignment": "LEFT"}, "userEnteredFormat(horizontalAlignment)",
+ ))
+ if highlight:
+ requests.append(_repeat_cell(
+ sheet_id, first_row, first_col, last_row, last_col,
+ {"backgroundColor": _hex_color(highlight)}, "userEnteredFormat(backgroundColor)",
+ ))
+ border = {"style": "SOLID", "color": {"red": 0, "green": 0, "blue": 0}}
+ requests.append({
+ "updateBorders": {
+ "range": {
+ "sheetId": sheet_id,
+ "startRowIndex": first_row - 1, "endRowIndex": last_row,
+ "startColumnIndex": first_col - 1, "endColumnIndex": last_col,
+ },
+ "top": border, "bottom": border, "left": border, "right": border,
+ "innerHorizontal": border, "innerVertical": border,
+ }
+ })
+ self._service.spreadsheets().batchUpdate(
+ spreadsheetId=spreadsheet_id, body={"requests": requests}
+ ).execute()
+
+ matrix = [
+ [cells.get((r, c), "") for c in range(first_col, last_col + 1)]
+ for r in range(first_row, last_row + 1)
+ ]
+ self._service.spreadsheets().values().update(
+ spreadsheetId=spreadsheet_id,
+ range=f"{a1_sheet(title)}!{col_letter(first_col)}{first_row}",
+ valueInputOption="USER_ENTERED",
+ body={"values": matrix},
+ ).execute()
+
+ return {
+ "created": False,
+ "title": title,
+ "first_row": first_row,
+ "last_row": last_row,
+ "url": f"https://docs.google.com/spreadsheets/d/{spreadsheet_id}/edit#gid={sheet_id}",
+ }
+
@_serialized
def delete_sheet(self, *, spreadsheet_id: str, title: str) -> dict[str, Any]:
"""이름이 정확히 일치하는 시트 1장을 삭제한다.
@@ -263,17 +432,7 @@ class GoogleSheetsWriter:
})
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,
- }
- }
+ return _repeat_cell(sheet_id, r1, c1, r2, c2, fmt, fields)
requests.append(_fmt(
title_row, first_col, title_row, last_col,
diff --git a/app/modules/cupang/CLAUDE.md b/app/modules/cupang/CLAUDE.md
index c67d0b8..d1ba209 100644
--- a/app/modules/cupang/CLAUDE.md
+++ b/app/modules/cupang/CLAUDE.md
@@ -45,3 +45,16 @@
- 구글 시트 양식 xlsx·csv 업로드(`sales_import.py`) — 같은 발주번호+SKU+출고일+센터+수량은 덮어씀.
- 광고비·할인 프로모션·장려금은 주차 단위(`cupang_sales_weekly`)로 보관, 순마진은 화면에서 계산.
- 초기 데이터는 `scripts/sql/cupang_sales_seed.sql`.
+
+## 밀크런 출고리스트 작성 (팝업 → 구글 시트, 2026-10-23)
+
+- 첫 화면 "+ 신규 등록" 옆 엑셀색(#217346) 버튼 → 팝업(`index.html` + `static/cupang-outbound.js`).
+ 상자 계산 없이 센터 1곳을 **구글 시트에만** 적는다 — cupang_db 출고 묶음은 만들지 않는다(달력에 안 보임).
+- 입력: 작성일(기본 오늘)·출고일·센터입고일(출고일 고르면 +1일 자동) — 날짜 칸은 프로젝트 날짜 팝업
+ (`PJLib.enhanceDateInput`, project.js 를 `PJ_LIB_ONLY` 로 로드). 입고센터(시트 F열 + 등록 센터, 직접 입력 가능),
+ 출고방식(파렛트/택배), 제품(코드표 `GET /cupang/api/products/all` 검색 → 코드·이름 자동, 수량 수기), 출고(수기), 작업자(기본 `export.WORKER`).
+- `POST /cupang/api/outbound-sheet` → 시트 `YYYYMMDD(요일)`(출고일) 맨 아래에 `export.build_block` 으로 덧붙임
+ (순번 B열 이어짐, 파렛트면 배경색). 시트가 없거나 5행 머리글이 없으면 양식째 새로 쓴다(`write_table`).
+ 위치 읽기~쓰기는 `writer.lock` 으로 한 덩어리. 입고센터 후보는 `GET /cupang/api/outbound-sheet/centers`(10분 캐시).
+- 주의: 같은 출고일에 [분배 확정]·출고 삭제가 일어나면 기존 동기화가 그 날짜 시트를 DB 기준으로 **통째로 다시 써서**
+ 팝업으로 적은 줄이 사라진다.
diff --git a/app/modules/cupang/export.py b/app/modules/cupang/export.py
index 6b273d3..851c330 100644
--- a/app/modules/cupang/export.py
+++ b/app/modules/cupang/export.py
@@ -94,37 +94,15 @@ def build_table(ship_date: str, shipments: list[dict[str, Any]]) -> dict[str, An
row = FIRST_DATA_ROW
seq = 0
for sh in shipments:
- lines = sh.get("lines") or []
- if not lines:
+ block = build_block(sh, start_row=row, start_seq=seq)
+ if block is None:
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))
+ cells.update(block["cells"])
+ merges.extend(block["merges"])
+ if block["is_pallet"]:
+ pallet_ranges.append((block["first_row"], block["last_row"]))
+ row = block["last_row"] + 1
+ seq = block["last_seq"]
return {
"title": title,
@@ -135,6 +113,53 @@ def build_table(ship_date: str, shipments: list[dict[str, Any]]) -> dict[str, An
}
+def build_block(sh: dict[str, Any], *, start_row: int, start_seq: int) -> dict[str, Any] | None:
+ """출고 묶음(센터) 1건 → start_row 부터 품목 1줄 = 1행. 품목이 없으면 None.
+
+ build_table(시트 전체)과 출고리스트 직접 작성(기존 시트 아래에 덧붙임)이 같이 쓴다.
+ 순번(B열)은 start_seq 다음 번호부터 이어진다.
+ """
+ lines = sh.get("lines") or []
+ if not lines:
+ return None
+ cells: dict[tuple[int, int], Any] = {}
+ merges: list[tuple[int, int, int, int]] = []
+ row, seq = start_row, start_seq
+ 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 ""
+ 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: sh.get("worker") or WORKER,
+ }
+ for col in MERGE_COLS:
+ cells[(start_row, col)] = block[col]
+ if end > start_row:
+ merges.append((start_row, col, end, col))
+
+ return {
+ "cells": cells,
+ "merges": merges,
+ "first_row": start_row,
+ "last_row": end,
+ "last_seq": seq,
+ "is_pallet": method == PALLET_METHOD,
+ }
+
+
def build_workbook(ship_date: str, shipments: list[dict[str, Any]]) -> Any:
"""xlsx 워크북(openpyxl). 시트명 = YYYYMMDD(요일)."""
from openpyxl import Workbook
diff --git a/app/modules/cupang/router.py b/app/modules/cupang/router.py
index 9a62e10..ca7be53 100644
--- a/app/modules/cupang/router.py
+++ b/app/modules/cupang/router.py
@@ -22,6 +22,7 @@ from app.timezone import today_kst
from fastapi import APIRouter, Body, Depends, File, Form, HTTPException, Request, UploadFile
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse
+from .export import WORKER as OUTBOUND_WORKER
from .holidays import holiday_name, is_holiday
from .store import SHIP_METHODS, parse_weight_g
@@ -222,6 +223,7 @@ def index(request: Request) -> HTMLResponse:
"months": months,
"selected_date": sel,
"sel_shipments": sel_shipments,
+ "outbound_worker": OUTBOUND_WORKER,
},
)
@@ -297,11 +299,6 @@ def _push_to_google_sheet(store: Any, ship_date: str) -> dict[str, Any]:
- 인증: 서비스 계정(app/integrations/google_sheets.py). 미설정이면 조용히 skip.
- 실패해도 출고 묶음 저장은 이미 끝났으므로 예외를 밖으로 던지지 않는다.
"""
- from .export import ( # noqa: WPS433
- COL_FIRST, COL_LAST, FIRST_DATA_ROW, HEADER_BG, HEADER_ROW, PALLET_BG,
- TITLE_ROW, WIDTHS_PX, build_table, sheet_title,
- )
-
writer, spreadsheet_id, skip = _sheet_target(store)
if skip:
return skip
@@ -310,28 +307,217 @@ def _push_to_google_sheet(store: Any, ship_date: str) -> dict[str, Any]:
if not shipments:
return {"ok": False, "skipped": True, "reason": "해당 출고일의 출고 묶음 없음"}
- 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_PX,
- header_bg=HEADER_BG,
- row_highlights=[(r1, r2, PALLET_BG) for (r1, r2) in table["pallet_ranges"]],
- )
+ res = _write_full_sheet(writer, spreadsheet_id, ship_date, shipments)
except Exception as exc: # noqa: BLE001 - 시트 기록 실패는 경고로만 알린다
return {"ok": False, "skipped": False, "reason": f"{type(exc).__name__}: {exc}"}
return {"ok": True, "skipped": False, **res}
+def _write_full_sheet(
+ writer: Any, spreadsheet_id: str, ship_date: str, shipments: list[dict[str, Any]]
+) -> dict[str, Any]:
+ """출고일 시트를 양식(1~5행)부터 통째로 다시 쓴다. 실패는 예외로 알린다."""
+ from .export import ( # noqa: WPS433
+ COL_FIRST, COL_LAST, FIRST_DATA_ROW, HEADER_BG, HEADER_ROW, PALLET_BG,
+ TITLE_ROW, WIDTHS_PX, build_table, sheet_title,
+ )
+
+ table = build_table(ship_date, shipments)
+ 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_PX,
+ header_bg=HEADER_BG,
+ row_highlights=[(r1, r2, PALLET_BG) for (r1, r2) in table["pallet_ranges"]],
+ )
+ return {**res, "first_row": FIRST_DATA_ROW, "last_row": table["last_row"]}
+
+
+# ════════════════════════════════════════════════════════════
+# 밀크런 출고리스트 직접 작성 — 상자 계산 없이 팝업에서 입력한 센터 1곳을
+# 구글 시트의 출고일 시트(YYYYMMDD(요일)) 맨 아래에 덧붙인다. cupang_db 에는 저장하지 않는다.
+# ════════════════════════════════════════════════════════════
+OUTBOUND_SHEET_METHODS: tuple[str, ...] = ("파렛트", "택배")
+_SHEET_CENTERS_TTL_SECONDS = 600
+_sheet_centers_cache: dict[str, Any] = {"at": 0.0, "sheet": "", "names": []}
+
+
+def _sheet_text(value: Any, *, label: str, max_len: int, required: bool = True) -> str:
+ text = str(value or "").strip()
+ if required and not text:
+ raise HTTPException(status_code=400, detail=f"{label}을(를) 입력해 주세요.")
+ if len(text) > max_len:
+ raise HTTPException(status_code=400, detail=f"{label}은(는) {max_len}자까지 입력할 수 있습니다.")
+ # USER_ENTERED 로 쓰므로 '=' 로 시작하면 수식이 된다 — 글자 그대로 남긴다.
+ return "'" + text if text.startswith("=") else text
+
+
+def _sheet_date(value: Any, *, label: str) -> str:
+ try:
+ return _date.fromisoformat(str(value or "").strip()).isoformat()
+ except ValueError:
+ raise HTTPException(status_code=400, detail=f"{label}을(를) 선택해 주세요.") from None
+
+
+def _clean_outbound_entry(payload: dict[str, Any]) -> dict[str, Any]:
+ """팝업 입력 → export.build_block 이 읽는 출고 묶음 모양."""
+ method = str(payload.get("ship_method") or "").strip()
+ if method not in OUTBOUND_SHEET_METHODS:
+ raise HTTPException(status_code=400, detail="출고방식은 파렛트 또는 택배 중에서 골라 주세요.")
+
+ raw_lines = payload.get("lines")
+ if not isinstance(raw_lines, list) or not raw_lines:
+ raise HTTPException(status_code=400, detail="제품을 1개 이상 추가해 주세요.")
+ if len(raw_lines) > 100:
+ raise HTTPException(status_code=400, detail="제품은 한 번에 100줄까지 입력할 수 있습니다.")
+ lines = []
+ for i, ln in enumerate(raw_lines, start=1):
+ if not isinstance(ln, dict):
+ raise HTTPException(status_code=400, detail=f"{i}번째 제품 정보를 확인해 주세요.")
+ try:
+ qty = int(str(ln.get("quantity") or "").replace(",", "").strip())
+ except ValueError:
+ qty = 0
+ if not 1 <= qty <= 1_000_000:
+ raise HTTPException(status_code=400, detail=f"{i}번째 제품의 수량을 확인해 주세요.")
+ lines.append({
+ "product_code": _sheet_text(ln.get("code"), label=f"{i}번째 제품코드", max_len=60),
+ "product_name_snapshot": _sheet_text(ln.get("name"), label=f"{i}번째 제품명", max_len=200),
+ "quantity": qty,
+ })
+
+ return {
+ "document_date": _sheet_date(payload.get("document_date"), label="작성일"),
+ "ship_date": _sheet_date(payload.get("ship_date"), label="출고일"),
+ "center_arrival_date": _sheet_date(payload.get("center_arrival_date"), label="센터입고일"),
+ "center_name_snapshot": _sheet_text(payload.get("center"), label="입고센터", max_len=60),
+ "ship_method": method,
+ "outbound_summary": _sheet_text(payload.get("outbound"), label="출고", max_len=100, required=False),
+ "worker": _sheet_text(payload.get("worker") or OUTBOUND_WORKER, label="작업자", max_len=30),
+ "lines": lines,
+ }
+
+
+def _sheet_centers(writer: Any, spreadsheet_id: str) -> list[str]:
+ """출고리스트 문서의 모든 시트 F열(입고센터, 6행부터)에 적힌 센터 이름. 10분 캐시."""
+ import time # noqa: WPS433
+
+ from app.integrations.google_sheets import a1_sheet # noqa: WPS433
+
+ from .export import FIRST_DATA_ROW # noqa: WPS433
+
+ cache = _sheet_centers_cache
+ if cache["sheet"] == spreadsheet_id and time.monotonic() - cache["at"] < _SHEET_CENTERS_TTL_SECONDS:
+ return list(cache["names"])
+ titles = writer.sheet_titles(spreadsheet_id=spreadsheet_id)
+ columns = writer.read_ranges(
+ spreadsheet_id=spreadsheet_id,
+ ranges=[f"{a1_sheet(t)}!F{FIRST_DATA_ROW}:F" for t in titles],
+ )
+ names = sorted({
+ str(row[0]).strip() for rows in columns for row in rows if row and str(row[0]).strip()
+ })
+ cache.update(at=time.monotonic(), sheet=spreadsheet_id, names=names)
+ return list(names)
+
+
+def _append_outbound_entry(writer: Any, spreadsheet_id: str, entry: dict[str, Any]) -> dict[str, Any]:
+ """출고일 시트 맨 아래에 덧붙인다. 시트가 없거나 양식(5행 머리글)이 없으면 양식째 만든다."""
+ from app.integrations.google_sheets import a1_sheet, col_letter # noqa: WPS433
+
+ from .export import ( # noqa: WPS433
+ COL_FIRST, COL_LAST, FIRST_DATA_ROW, HEADER_ROW, PALLET_BG, build_block, sheet_title,
+ )
+
+ title = sheet_title(entry["ship_date"])
+ rows: list[list[Any]] = []
+ if title in writer.sheet_titles(spreadsheet_id=spreadsheet_id):
+ rows = writer.read_ranges(
+ spreadsheet_id=spreadsheet_id,
+ ranges=[f"{a1_sheet(title)}!A1:{col_letter(COL_LAST)}"],
+ )[0]
+ last_row = max(
+ (i for i, row in enumerate(rows, start=1) if any(str(v).strip() for v in row)), default=0
+ )
+ if last_row < HEADER_ROW:
+ return _write_full_sheet(writer, spreadsheet_id, entry["ship_date"], [entry])
+
+ # 순번(B열)은 시트에 이미 있는 가장 큰 번호 다음부터
+ last_seq = 0
+ for row in rows[FIRST_DATA_ROW - 1:]:
+ text = str(row[1]).strip() if len(row) > 1 else ""
+ if text.isdigit():
+ last_seq = max(last_seq, int(text))
+ block = build_block(entry, start_row=last_row + 1, start_seq=last_seq)
+ return writer.append_block(
+ spreadsheet_id=spreadsheet_id,
+ title=title,
+ cells=block["cells"],
+ merges=block["merges"],
+ first_row=block["first_row"],
+ last_row=block["last_row"],
+ first_col=COL_FIRST,
+ last_col=COL_LAST,
+ highlight=PALLET_BG if block["is_pallet"] else "",
+ )
+
+
+@router.get("/api/outbound-sheet/centers")
+def outbound_sheet_centers(
+ request: Request, _: dict[str, Any] = Depends(_require_user)
+) -> JSONResponse:
+ """입고센터 후보 — 출고리스트 문서에 적힌 센터 + 설정에 등록된 센터."""
+ store = _store(request)
+ names = {c["name"] for c in store.list_centers()} if store else set()
+ reason = ""
+ writer, spreadsheet_id, skip = _sheet_target(store)
+ if skip:
+ reason = str(skip.get("reason") or "")
+ else:
+ try:
+ names.update(_sheet_centers(writer, spreadsheet_id))
+ except Exception as exc: # noqa: BLE001 - 목록은 등록 센터만으로도 쓸 수 있다
+ reason = f"구글 시트를 읽지 못했습니다({type(exc).__name__})"
+ return JSONResponse({"centers": sorted(names), "reason": reason})
+
+
+@router.post("/api/outbound-sheet")
+def outbound_sheet_write(
+ request: Request,
+ payload: dict[str, Any] = Body(...),
+ _: dict[str, Any] = Depends(_require_user),
+) -> JSONResponse:
+ entry = _clean_outbound_entry(payload)
+ writer, spreadsheet_id, skip = _sheet_target(_store(request))
+ if skip:
+ raise HTTPException(
+ status_code=503, detail=f"구글 시트에 쓸 수 없습니다: {skip.get('reason') or '설정 확인 필요'}"
+ )
+ try:
+ # 시트 끝 위치를 읽고 쓰는 사이에 다른 요청이 끼어들지 않게 한 덩어리로
+ with writer.lock:
+ res = _append_outbound_entry(writer, spreadsheet_id, entry)
+ except Exception as exc: # noqa: BLE001 - 사유만 남긴다(비밀값 미출력)
+ _log_sheet("manual-append", entry["ship_date"], {"ok": False, "reason": type(exc).__name__})
+ raise HTTPException(
+ status_code=502, detail=f"구글 시트에 기록하지 못했습니다({type(exc).__name__}). 잠시 후 다시 시도해 주세요."
+ ) from exc
+ _log_sheet("manual-append", entry["ship_date"], {"ok": True, "action": f"rows {res.get('first_row')}-{res.get('last_row')}"})
+ center = entry["center_name_snapshot"]
+ if center not in _sheet_centers_cache["names"] and _sheet_centers_cache["sheet"] == spreadsheet_id:
+ _sheet_centers_cache["names"] = sorted([*_sheet_centers_cache["names"], center])
+ return JSONResponse({"ok": True, **res, "line_count": len(entry["lines"])})
+
+
@router.get("/export.xlsx")
def export_shipments_xlsx(request: Request, date: str = "") -> Any:
"""출고일 기준 출고리스트 엑셀 다운로드. 시트명 = YYYYMMDD."""
diff --git a/app/modules/cupang/templates/cupang/index.html b/app/modules/cupang/templates/cupang/index.html
index 3271fc8..0ba90ac 100644
--- a/app/modules/cupang/templates/cupang/index.html
+++ b/app/modules/cupang/templates/cupang/index.html
@@ -1,6 +1,12 @@
{% extends "erp_base.html" %}
-{% block head_extra %}{% endblock %}
+{% block head_extra %}
+{# 출고리스트 작성 팝업의 날짜 칸은 프로젝트 화면의 날짜 팝업을 그대로 쓴다 — project.js 는 PJ_LIB_ONLY 로 부품만 #}
+
+
+
+
+{% endblock %}
{% block content %}
@@ -9,6 +15,7 @@
+ 신규 등록
+
쿠팡 로켓 매출
제품명 설정
@@ -168,10 +175,62 @@
+
+
+
+
+
밀크런 출고리스트 작성
+
+
+
+
+
+
위 검색창에서 제품을 골라 추가하세요.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
{% endblock %}
{% block scripts %}
+
+