feat(cupang): 밀크런 출고리스트 작성 팝업 — 구글 시트 출고일 시트 아래에 덧붙임

- 첫 화면 "+ 신규 등록" 옆 엑셀색 버튼 → 작성일·출고일·센터입고일(프로젝트 날짜 팝업),
  입고센터(시트 F열 + 등록 센터, 직접 입력), 출고방식(파렛트/택배), 코드표 검색 제품·수량, 출고, 작업자(기본 핫프렌즈)
- POST /cupang/api/outbound-sheet: 출고일 시트 YYYYMMDD(요일) 맨 아래에 기존 양식으로 추가
  (순번 이어짐·파렛트 배경색), 시트가 없으면 5행 양식째 생성. cupang_db 에는 저장하지 않음
- GET /cupang/api/outbound-sheet/centers: 입고센터 후보(10분 캐시)
- export.build_block 분리(기존 build_table 결과 동일), google_sheets 에 sheet_titles·read_ranges·append_block 추가
- 테스트: pytest(양식·입력 검사·덧붙일 위치·Sheets 요청·실제 앱), Playwright 화면 테스트

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-23 14:57:43 +09:00
parent 9883971beb
commit e63734c984
11 changed files with 1411 additions and 63 deletions
+170 -11
View File
@@ -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,
+13
View File
@@ -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 기준으로 **통째로 다시 써서**
팝업으로 적은 줄이 사라진다.
+55 -30
View File
@@ -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
+207 -21
View File
@@ -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."""
+60 -1
View File
@@ -1,6 +1,12 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20261013b" />{% endblock %}
{% block head_extra %}
{# 출고리스트 작성 팝업의 날짜 칸은 프로젝트 화면의 날짜 팝업을 그대로 쓴다 — project.js 는 PJ_LIB_ONLY 로 부품만 #}
<link rel="stylesheet" href="/static/project.css?v=20261022a" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
<link rel="stylesheet" href="/static/cupang.css?v=20261023a" />
<script>window.PJ_LIB_ONLY = true; window.PJ_HOLIDAYS = {{ (pj_kr_holidays or {}) | tojson }};</script>
{% endblock %}
{% block content %}
<section class="cpg">
@@ -9,6 +15,7 @@
<div class="cpg-actions-grid">
<div class="cpg-actions-main">
<a class="erp-btn erp-btn-primary" href="/cupang/box-calc">+ 신규 등록</a>
<button type="button" class="erp-btn cpg-btn-excel" id="cpg-ol-open">밀크런 출고리스트 작성</button>
<span class="cpg-settings-btns">
<a class="erp-btn erp-btn-outline cpg-sales-link" href="/cupang/sales">쿠팡 로켓 매출</a>
<a class="erp-btn erp-btn-outline" href="/cupang/products">제품명 설정</a>
@@ -168,10 +175,62 @@
<input type="hidden" name="next" id="cpg-del-next" />
</form>
<!-- 밀크런 출고리스트 작성 팝업 — 완료하면 구글 시트 출고일 시트 아래에 덧붙인다 -->
<div class="cpg-modal" id="cpg-ol-dlg" hidden>
<div class="cpg-modal-back" data-ol-close></div>
<div class="cpg-modal-box cpg-ol-box" role="dialog" aria-modal="true" aria-labelledby="cpg-ol-title">
<h3 id="cpg-ol-title">밀크런 출고리스트 작성</h3>
<div class="cpg-ol-grid">
<div class="erp-field"><span>작성일</span><input type="date" id="cpg-ol-doc-date" /></div>
<div class="erp-field"><span>출고일</span><input type="date" id="cpg-ol-ship-date" /></div>
<div class="erp-field"><span>센터입고일</span><input type="date" id="cpg-ol-arrival-date" /></div>
<label class="erp-field"><span>입고센터</span>
<select class="erp-select" id="cpg-ol-center"><option value="">불러오는 중…</option></select></label>
<label class="erp-field"><span>출고방식</span>
<select class="erp-select" id="cpg-ol-method">
<option value="파렛트">파렛트</option>
<option value="택배">택배</option>
</select></label>
<label class="erp-field cpg-ol-center-custom" hidden><span>새 입고센터</span>
<input class="erp-input" type="text" id="cpg-ol-center-new" maxlength="60" placeholder="센터 이름" /></label>
</div>
<div class="erp-field"><span>제품 (코드표에서 검색해 추가)</span>
<div class="cpg-ol-search">
<input class="erp-input" type="search" id="cpg-ol-search" autocomplete="off"
placeholder="제품코드 또는 제품명으로 검색" />
<ul class="cpg-ol-results" id="cpg-ol-results" hidden></ul>
</div>
</div>
<table class="cpg-ol-lines">
<thead><tr><th>제품코드</th><th>제품명</th><th>수량</th><th></th></tr></thead>
<tbody id="cpg-ol-lines"></tbody>
</table>
<p class="erp-muted cpg-ol-empty" id="cpg-ol-empty">위 검색창에서 제품을 골라 추가하세요.</p>
<div class="cpg-ol-grid cpg-ol-grid-2">
<label class="erp-field"><span>출고</span>
<input class="erp-input" type="text" id="cpg-ol-outbound" maxlength="100" placeholder="예) 2파렛트, 15박스" /></label>
<label class="erp-field"><span>작업자</span>
<input class="erp-input" type="text" id="cpg-ol-worker" maxlength="30" value="{{ outbound_worker }}" /></label>
</div>
<p class="erp-muted cpg-ol-target" id="cpg-ol-target"></p>
<p class="cpg-ol-error" id="cpg-ol-error" hidden></p>
<div class="cpg-ol-actions">
<button type="button" class="erp-btn erp-btn-outline" data-ol-close>취소</button>
<button type="button" class="erp-btn cpg-btn-excel" id="cpg-ol-submit">완료</button>
</div>
</div>
</div>
</section>
{% endblock %}
{% block scripts %}
<script src="/static/project.js?v=20261022c" defer></script>
<script src="/static/cupang-outbound.js?v=20261023a" defer></script>
<script>
(function () {
var dlg = document.getElementById("cpg-del-dlg");
+316
View File
@@ -0,0 +1,316 @@
/* 쿠팡 밀크런 — 밀크런 출고리스트 작성 팝업(cupang/index.html).
- 날짜 칸: 프로젝트 화면의 날짜 팝업(window.PJLib.enhanceDateInput)을 그대로 쓴다.
- 입고센터: 출고리스트 구글 시트에 적힌 센터 + 설정에 등록된 센터(GET /cupang/api/outbound-sheet/centers).
- 제품: 코드표(itemcode_db) 전체 목록(GET /cupang/api/products/all)에서 코드·이름으로 찾아 추가.
- [완료] → POST /cupang/api/outbound-sheet → 출고일 시트(YYYYMMDD(요일)) 맨 아래에 덧붙임. */
(function () {
"use strict";
var dlg = document.getElementById("cpg-ol-dlg");
var openBtn = document.getElementById("cpg-ol-open");
if (!dlg || !openBtn) return;
// project.js 가 대화상자 제목을 프로젝트 화면 것으로 바꿔 두므로 이 화면은 기본 제목으로 되돌린다.
if (window.ERP_DIALOG_TITLE === "KSN 프로그램") delete window.ERP_DIALOG_TITLE;
var NEW_CENTER = "__new__";
var DOW = ["일", "월", "화", "수", "목", "금", "토"];
function $(id) { return document.getElementById(id); }
var docDate = $("cpg-ol-doc-date"), shipDate = $("cpg-ol-ship-date"), arrivalDate = $("cpg-ol-arrival-date");
var centerSel = $("cpg-ol-center"), centerNew = $("cpg-ol-center-new");
var centerCustom = dlg.querySelector(".cpg-ol-center-custom");
var method = $("cpg-ol-method"), outbound = $("cpg-ol-outbound"), worker = $("cpg-ol-worker");
var search = $("cpg-ol-search"), results = $("cpg-ol-results");
var linesBody = $("cpg-ol-lines"), emptyMsg = $("cpg-ol-empty");
var target = $("cpg-ol-target"), errorBox = $("cpg-ol-error"), submitBtn = $("cpg-ol-submit");
var defaultWorker = worker.value;
var products = null; // 코드표 [{code, name, type}] — 처음 열 때 한 번 읽는다
var productsReason = "";
var arrivalAuto = true; // 센터입고일을 직접 고르기 전까지는 출고일 + 1일로 따라간다
var busy = false;
// 한국 날짜(브라우저 시간대와 무관) — 서버 today_kst 와 같은 날
function kstToday() { return new Date(Date.now() + 9 * 3600000).toISOString().slice(0, 10); }
function addDays(iso, n) {
var d = new Date(iso + "T00:00:00");
d.setDate(d.getDate() + n);
return d.getFullYear() + "-" + String(d.getMonth() + 1).padStart(2, "0") + "-" + String(d.getDate()).padStart(2, "0");
}
function sheetTitle(iso) {
var d = new Date(iso + "T00:00:00");
return iso.replace(/-/g, "") + "(" + DOW[d.getDay()] + ")";
}
if (window.PJLib && window.PJLib.enhanceDateInput) {
[docDate, shipDate, arrivalDate].forEach(function (inp) {
window.PJLib.enhanceDateInput(inp, { placeholder: "날짜 선택" });
});
}
function showError(msg) {
errorBox.textContent = msg || "";
errorBox.hidden = !msg;
}
// 고치기 시작하면 지난 안내는 지운다
dlg.addEventListener("input", function () { if (!busy) showError(""); });
dlg.addEventListener("change", function () { if (!busy) showError(""); });
function updateTarget() {
target.textContent = shipDate.value
? "완료하면 구글 시트 '" + sheetTitle(shipDate.value) + "' 시트 맨 아래에 추가합니다. (시트가 없으면 양식째 새로 만듭니다)"
: "출고일을 고르면 그 날짜 시트(YYYYMMDD(요일))에 추가합니다.";
}
shipDate.addEventListener("change", function () {
if (shipDate.value && (arrivalAuto || !arrivalDate.value)) {
arrivalDate.value = addDays(shipDate.value, 1);
arrivalAuto = true;
}
updateTarget();
});
arrivalDate.addEventListener("change", function () { arrivalAuto = !arrivalDate.value; });
// ── 입고센터 ─────────────────────────────────────
function fillCenters(names, reason) {
var keep = centerSel.value;
centerSel.innerHTML = "";
function add(value, label) {
var o = document.createElement("option");
o.value = value;
o.textContent = label;
centerSel.appendChild(o);
}
add("", names.length ? "센터 선택" : "센터 목록 없음");
names.forEach(function (n) { add(n, n); });
add(NEW_CENTER, "+ 직접 입력");
if (keep && (keep === NEW_CENTER || names.indexOf(keep) >= 0)) centerSel.value = keep;
centerCustom.hidden = centerSel.value !== NEW_CENTER;
if (reason) showError("입고센터 목록 일부를 불러오지 못했습니다: " + reason);
}
function loadCenters() {
return fetch("/cupang/api/outbound-sheet/centers", { headers: { Accept: "application/json" } })
.then(function (res) { return res.ok ? res.json() : Promise.reject(new Error(res.status)); })
.then(function (data) { fillCenters(data.centers || [], data.reason || ""); })
.catch(function () { fillCenters([], "서버 응답 없음"); });
}
centerSel.addEventListener("change", function () {
centerCustom.hidden = centerSel.value !== NEW_CENTER;
if (!centerCustom.hidden) centerNew.focus();
});
// ── 제품 검색(코드표) ─────────────────────────────
function loadProducts() {
if (products) return Promise.resolve();
return fetch("/cupang/api/products/all", { headers: { Accept: "application/json" } })
.then(function (res) { return res.ok ? res.json() : Promise.reject(new Error(res.status)); })
.then(function (data) {
products = data.results || [];
productsReason = data.enabled ? (data.error || "") : (data.reason || "코드표 미설정");
})
.catch(function () { products = []; productsReason = "서버 응답 없음"; });
}
var hits = [], activeHit = -1;
function renderResults() {
results.innerHTML = "";
var q = search.value.trim().toLowerCase();
if (!q) { results.hidden = true; return; }
hits = (products || []).filter(function (p) {
return p.code.toLowerCase().indexOf(q) >= 0 || p.name.toLowerCase().indexOf(q) >= 0;
}).slice(0, 30);
activeHit = hits.length ? 0 : -1;
if (!hits.length) {
var li = document.createElement("li");
li.className = "cpg-ol-noresult";
li.textContent = productsReason ? "코드표를 불러오지 못했습니다: " + productsReason : "검색 결과가 없습니다.";
results.appendChild(li);
}
hits.forEach(function (p, i) {
var li = document.createElement("li");
li.className = "cpg-ol-hit" + (i === activeHit ? " is-active" : "");
li.dataset.index = String(i);
var code = document.createElement("b");
code.textContent = p.code;
var name = document.createElement("span");
name.textContent = p.name;
li.appendChild(code);
li.appendChild(name);
results.appendChild(li);
});
results.hidden = false;
}
function moveActive(step) {
if (!hits.length) return;
activeHit = (activeHit + step + hits.length) % hits.length;
Array.prototype.forEach.call(results.querySelectorAll(".cpg-ol-hit"), function (li, i) {
li.classList.toggle("is-active", i === activeHit);
if (i === activeHit) li.scrollIntoView({ block: "nearest" });
});
}
function pickHit(i) {
var p = hits[i];
if (!p) return;
addLine(p.code, p.name);
search.value = "";
results.hidden = true;
}
search.addEventListener("input", renderResults);
search.addEventListener("keydown", function (e) {
if (e.isComposing || e.keyCode === 229) return; // 한글 조합 중 Enter 는 조합 확정
if (e.key === "ArrowDown") { e.preventDefault(); moveActive(1); }
else if (e.key === "ArrowUp") { e.preventDefault(); moveActive(-1); }
else if (e.key === "Enter") { e.preventDefault(); pickHit(activeHit); }
else if (e.key === "Escape" && !results.hidden) { e.stopPropagation(); results.hidden = true; }
});
// mousedown — 검색창 blur 로 목록이 닫히기 전에 고른다
results.addEventListener("mousedown", function (e) {
var li = e.target.closest(".cpg-ol-hit");
if (!li) return;
e.preventDefault();
pickHit(+li.dataset.index);
});
search.addEventListener("blur", function () { results.hidden = true; });
// ── 제품 줄 ─────────────────────────────────────
var linesTable = linesBody.closest("table");
function syncEmpty() {
var has = linesBody.children.length > 0;
emptyMsg.hidden = has;
linesTable.hidden = !has;
}
function addLine(code, name) {
var existing = Array.prototype.find.call(linesBody.children, function (tr) { return tr.dataset.code === code; });
if (existing) { existing.querySelector(".cpg-ol-qty").focus(); return; }
var tr = document.createElement("tr");
tr.dataset.code = code;
tr.dataset.name = name;
var tdCode = document.createElement("td");
tdCode.textContent = code;
var tdName = document.createElement("td");
tdName.textContent = name;
var tdQty = document.createElement("td");
var qty = document.createElement("input");
qty.type = "number";
qty.min = "1";
qty.step = "1";
qty.className = "erp-input cpg-ol-qty";
qty.setAttribute("aria-label", name + " 수량");
tdQty.appendChild(qty);
var tdDel = document.createElement("td");
var del = document.createElement("button");
del.type = "button";
del.className = "cpg-icon-btn is-danger";
del.textContent = "삭제";
del.addEventListener("click", function () { tr.remove(); syncEmpty(); });
tdDel.appendChild(del);
tr.appendChild(tdCode); tr.appendChild(tdName); tr.appendChild(tdQty); tr.appendChild(tdDel);
linesBody.appendChild(tr);
syncEmpty();
qty.focus();
}
// ── 열기 / 닫기 ─────────────────────────────────
function reset() {
docDate.value = kstToday();
shipDate.value = "";
arrivalDate.value = "";
arrivalAuto = true;
centerSel.value = "";
centerNew.value = "";
centerCustom.hidden = true;
method.value = "파렛트";
outbound.value = "";
worker.value = defaultWorker;
search.value = "";
results.hidden = true;
linesBody.innerHTML = "";
syncEmpty();
showError("");
updateTarget();
}
function open() {
reset();
dlg.hidden = false;
loadCenters();
loadProducts();
}
function close() {
if (busy) return;
dlg.hidden = true;
}
openBtn.addEventListener("click", open);
Array.prototype.forEach.call(dlg.querySelectorAll("[data-ol-close]"), function (el) {
el.addEventListener("click", close);
});
document.addEventListener("keydown", function (e) {
// 날짜 팝업이 떠 있으면 그 팝업이 먼저 닫힌다(그쪽이 Esc 를 가져간다)
if (e.key === "Escape" && !dlg.hidden && !document.querySelector(".pj-datepop")) close();
});
// ── 완료 ────────────────────────────────────────
function collect() {
var center = centerSel.value === NEW_CENTER ? centerNew.value.trim() : centerSel.value;
var lines = Array.prototype.map.call(linesBody.children, function (tr) {
return { code: tr.dataset.code, name: tr.dataset.name, quantity: tr.querySelector(".cpg-ol-qty").value };
});
if (!docDate.value) return { error: "작성일을 선택해 주세요." };
if (!shipDate.value) return { error: "출고일을 선택해 주세요." };
if (!arrivalDate.value) return { error: "센터입고일을 선택해 주세요." };
if (!center) return { error: "입고센터를 선택해 주세요." };
if (!lines.length) return { error: "제품을 1개 이상 추가해 주세요." };
for (var i = 0; i < lines.length; i++) {
if (!(parseInt(lines[i].quantity, 10) > 0)) return { error: lines[i].name + "의 수량을 입력해 주세요." };
}
return {
body: {
document_date: docDate.value,
ship_date: shipDate.value,
center_arrival_date: arrivalDate.value,
center: center,
ship_method: method.value,
outbound: outbound.value.trim(),
worker: worker.value.trim(),
lines: lines,
},
};
}
submitBtn.addEventListener("click", function () {
if (busy) return;
var got = collect();
if (got.error) { showError(got.error); return; }
showError("");
busy = true;
submitBtn.disabled = true;
submitBtn.textContent = "기록 중…";
fetch("/cupang/api/outbound-sheet", {
method: "POST",
headers: { "Content-Type": "application/json", Accept: "application/json" },
body: JSON.stringify(got.body),
})
.then(function (res) {
return res.json().catch(function () { return {}; }).then(function (data) {
if (!res.ok) throw new Error(typeof data.detail === "string" ? data.detail : "구글 시트에 기록하지 못했습니다.");
return data;
});
})
.then(function (data) {
busy = false;
close();
var msg = "'" + data.title + "' 시트 " + data.first_row + "~" + data.last_row + "행에 " +
data.line_count + "개 제품을 추가했습니다.";
if (window.erpConfirm && data.url) {
window.erpConfirm(msg + "\n구글 시트를 열어 볼까요?", { tone: "ok", okText: "시트 열기", cancelText: "닫기" })
.then(function (ok) { if (ok) window.open(data.url, "_blank", "noopener"); });
} else {
window.alert(msg);
}
})
.catch(function (err) { showError(err.message); })
.finally(function () {
busy = false;
submitBtn.disabled = false;
submitBtn.textContent = "완료";
});
});
})();
+43
View File
@@ -1602,3 +1602,46 @@ a.cpg-boxno-dl:hover { background: #1a5c38; border-color: #1a5c38; font-weight:
@media (max-width: 640px) {
.cpg-sales-form { grid-template-columns: minmax(0, 1fr); }
}
/* ── 밀크런 출고리스트 작성 (index.html 팝업 · cupang-outbound.js) ── */
/* 엑셀 초록 버튼 */
.cpg-btn-excel { background: #217346; color: #fff; padding: 8px 16px; }
.cpg-btn-excel:hover { background: #185c37; }
.cpg-btn-excel:disabled { opacity: .6; cursor: default; }
.cpg-ol-box { width: min(760px, calc(100vw - 32px)); max-height: calc(100vh - 48px); overflow-y: auto; gap: 12px; }
.cpg-ol-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 10px; }
.cpg-ol-grid-2 { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.cpg-ol-box .erp-input { box-sizing: border-box; }
/* 날짜 칸 = 프로젝트 날짜 버튼. 칸 너비에 맞추고, 지난 날짜도 빨강(마감 지남)으로 칠하지 않는다 */
.cpg-ol-box .pj-date-btn { width: 100%; margin-top: 0; height: 34px; justify-content: flex-start; }
.cpg-ol-box .pj-date-btn.is-overdue { color: var(--color-rich-black); }
.cpg-ol-search { position: relative; }
.cpg-ol-results {
position: absolute; z-index: 5; left: 0; right: 0; top: calc(100% + 4px);
margin: 0; padding: 4px; list-style: none; max-height: 260px; overflow-y: auto;
background: var(--color-canvas-white); border: 1px solid var(--color-subtle-ash);
border-radius: 8px; box-shadow: 0 8px 24px rgba(0, 0, 0, .14);
}
.cpg-ol-results[hidden] { display: none; }
.cpg-ol-hit { display: flex; gap: 10px; padding: 6px 8px; border-radius: 6px; cursor: pointer; font-size: 13px; color: var(--color-rich-black); }
.cpg-ol-hit b { flex: 0 0 auto; min-width: 96px; }
.cpg-ol-hit.is-active, .cpg-ol-hit:hover { background: #e8f3ec; }
.cpg-ol-noresult { padding: 8px; font-size: 13px; color: var(--color-midtone-gray); }
.cpg-ol-lines { width: 100%; border-collapse: collapse; font-size: 13px; }
.cpg-ol-lines th { text-align: center; font-weight: 600; background: #dbe9f7; padding: 6px 8px; border: 1px solid var(--color-subtle-ash); }
.cpg-ol-lines td { padding: 4px 8px; border: 1px solid var(--color-subtle-ash); text-align: center; }
.cpg-ol-lines td:nth-child(2) { text-align: left; }
.cpg-ol-lines[hidden] { display: none; }
.cpg-ol-box .cpg-ol-qty { width: 110px; min-width: 0; text-align: right; }
.cpg-ol-lines th:nth-child(1) { width: 120px; }
.cpg-ol-lines th:nth-child(3) { width: 130px; }
.cpg-ol-lines th:nth-child(4) { width: 56px; }
.cpg-ol-center-custom[hidden] { display: none; }
.cpg-ol-empty { margin: 0; }
.cpg-ol-empty[hidden] { display: none; }
.cpg-ol-target { margin: 0; font-size: 12px; }
.cpg-ol-error { margin: 0; font-size: 13px; color: #c22b10; }
.cpg-ol-actions { display: flex; gap: 6px; justify-content: flex-end; }
@media (max-width: 640px) {
.cpg-ol-grid, .cpg-ol-grid-2 { grid-template-columns: minmax(0, 1fr); }
}