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); }
}
+11
View File
@@ -91,3 +91,14 @@ node tests/js/inbox_panel.browser.test.js # Playwright: iframe 리다이렉
python tests/js/render_project.py # → tests/js/.out/project_render.html
NODE_PATH=<playwright 또는 playwright-core 경로> PJ_TEST_BROWSER=<Chrome/Edge 경로> node tests/js/image_copy.browser.test.js
```
# 쿠팡 밀크런 출고리스트 작성 팝업 (Playwright, 2026-10-23)
`cupang/index.html` + `static/cupang-outbound.js` — "+ 신규 등록" 옆 엑셀색 버튼, 프로젝트 날짜 팝업(작성일 오늘·센터입고일 = 출고일+1),
입고센터 목록·직접 입력, 코드표 검색으로 제품 추가, [완료] 요청 값·성공 안내·실패 시 입력 유지, Esc, 390px 화면을 가짜 서버로 확인한다.
구글 시트·DB 연결 없음(시트 쓰기 자체는 `tests/test_cupang_outbound_sheet.py`).
```bash
python tests/js/render_cupang_index.py # → tests/js/.out/cupang_index_render.html
NODE_PATH=<playwright 또는 playwright-core 경로> PJ_TEST_BROWSER=<Chrome/Edge 경로> node tests/js/cupang_outbound.browser.test.js
```
+190
View File
@@ -0,0 +1,190 @@
// 쿠팡 밀크런 — "밀크런 출고리스트 작성" 팝업을 실제 Chromium 에서 검증(DB·구글 미사용, 가짜 서버).
// python tests/js/render_cupang_index.py
// PJ_TEST_BROWSER=<설치된 Chrome/Edge 경로> node tests/js/cupang_outbound.browser.test.js
const assert = require("node:assert/strict");
const fs = require("node:fs");
const http = require("node:http");
const path = require("node:path");
const { chromium } = require("playwright");
const ROOT = path.resolve(__dirname, "../..");
const STATIC = path.join(ROOT, "app/static");
const OUT = path.join(__dirname, ".out");
const posts = [];
const PRODUCTS = [
{ code: "MT-7000", name: "점보 7,000ml", type: "단품" },
{ code: "MS-1004", name: "미라네 4호세트", type: "세트" },
{ code: "MT-3000", name: "중형 3,000ml", type: "단품" },
];
function json(res, status, body) {
res.statusCode = status;
res.setHeader("Content-Type", "application/json; charset=utf-8");
res.end(JSON.stringify(body));
}
const server = http.createServer(function (req, res) {
const url = new URL(req.url, "http://localhost");
if (url.pathname === "/cupang/") {
res.setHeader("Content-Type", "text/html; charset=utf-8");
res.end(fs.readFileSync(path.join(OUT, "cupang_index_render.html"))); return;
}
if (url.pathname === "/cupang/api/outbound-sheet/centers") return json(res, 200, { centers: ["대구3", "인천32"], reason: "" });
if (url.pathname === "/cupang/api/products/all") return json(res, 200, { enabled: true, reason: "", error: "", results: PRODUCTS });
if (url.pathname === "/cupang/api/outbound-sheet" && req.method === "POST") {
let raw = "";
req.on("data", c => { raw += c; });
req.on("end", function () {
const body = JSON.parse(raw);
posts.push(body);
if (body.center === "실패센터") return json(res, 502, { detail: "구글 시트에 기록하지 못했습니다(HttpError). 잠시 후 다시 시도해 주세요." });
json(res, 200, { ok: true, title: "20261026(월)", first_row: 10, last_row: 11, line_count: body.lines.length,
url: "https://docs.google.com/spreadsheets/d/x/edit#gid=1", created: false });
});
return;
}
const file = path.resolve(STATIC, "." + decodeURIComponent(url.pathname.slice(7)));
if (!url.pathname.startsWith("/static/") || !file.startsWith(STATIC + path.sep) || !fs.existsSync(file) || !fs.statSync(file).isFile()) {
res.statusCode = 404; res.end(); return;
}
const types = { ".css": "text/css", ".js": "text/javascript", ".woff2": "font/woff2", ".woff": "font/woff", ".png": "image/png", ".svg": "image/svg+xml" };
res.setHeader("Content-Type", types[path.extname(file)] || "application/octet-stream");
fs.createReadStream(file).pipe(res);
});
async function pickDate(page, inputId, typed) {
// 프로젝트 날짜 팝업: 버튼 → 팝업의 날짜 칸에 직접 입력 + Enter
await page.locator("#" + inputId + " + .pj-date-btn").click();
const pop = page.locator(".pj-datepop");
await pop.waitFor({ state: "visible" });
await pop.locator(".pj-dp-field").fill(typed);
await pop.locator(".pj-dp-field").press("Enter");
await pop.waitFor({ state: "detached" });
}
(async function () {
let browser;
try {
await new Promise(resolve => server.listen(0, "127.0.0.1", resolve));
browser = await chromium.launch({ headless: true, executablePath: process.env.PJ_TEST_BROWSER || undefined });
const page = await browser.newPage({ viewport: { width: 1600, height: 1000 } });
const errors = [];
page.on("pageerror", e => errors.push(e.message));
await page.goto("http://127.0.0.1:" + server.address().port + "/cupang/");
// 버튼: "+ 신규 등록" 바로 오른쪽, 엑셀 초록
const openBtn = page.locator("#cpg-ol-open");
await openBtn.waitFor({ state: "visible" });
const newBox = await page.locator("a", { hasText: "+ 신규 등록" }).boundingBox();
const btnBox = await openBtn.boundingBox();
assert.ok(btnBox.x > newBox.x + newBox.width - 1 && btnBox.x - (newBox.x + newBox.width) < 20, "신규 등록 바로 옆");
assert.ok(Math.abs(btnBox.y - newBox.y) < 3, "같은 줄");
assert.equal(await openBtn.evaluate(el => getComputedStyle(el).backgroundColor), "rgb(33, 115, 70)");
await page.screenshot({ path: path.join(OUT, "cupang-outbound-button.png"), clip: { x: 0, y: 0, width: 1600, height: 260 } });
// 팝업 열기 — 작성일 = 오늘(프로젝트 날짜 버튼), 작업자 = 핫프렌즈
await openBtn.click();
await page.locator("#cpg-ol-dlg").waitFor({ state: "visible" });
assert.equal(await page.locator("#cpg-ol-doc-date + .pj-date-btn").innerText(), "calendar_month\n오늘".replace("\n", "\n"));
assert.equal(await page.locator("#cpg-ol-worker").inputValue(), "핫프렌즈");
assert.equal(await page.locator("#cpg-ol-method").inputValue(), "파렛트");
assert.deepEqual(await page.locator("#cpg-ol-method option").allInnerTexts(), ["파렛트", "택배"]);
await page.waitForFunction(() => document.querySelectorAll("#cpg-ol-center option").length === 4);
assert.deepEqual(await page.locator("#cpg-ol-center option").allInnerTexts(), ["센터 선택", "대구3", "인천32", "+ 직접 입력"]);
// 출고일 → 센터입고일은 다음날로 자동
await pickDate(page, "cpg-ol-ship-date", "2026-10-26");
assert.equal(await page.locator("#cpg-ol-ship-date").inputValue(), "2026-10-26");
assert.equal(await page.locator("#cpg-ol-arrival-date").inputValue(), "2026-10-27");
assert.match(await page.locator("#cpg-ol-target").innerText(), /20261026\(월\)/);
// 필수값 확인
await page.locator("#cpg-ol-submit").click();
assert.equal(await page.locator("#cpg-ol-error").innerText(), "입고센터를 선택해 주세요.");
await page.locator("#cpg-ol-center").selectOption("인천32");
await page.locator("#cpg-ol-submit").click();
assert.equal(await page.locator("#cpg-ol-error").innerText(), "제품을 1개 이상 추가해 주세요.");
assert.ok(!(await page.locator(".cpg-ol-lines").isVisible()), "제품이 없으면 표를 숨김");
// 코드표 검색 → Enter 로 첫 결과, 클릭으로 다음 결과
await page.locator("#cpg-ol-search").fill("점보");
assert.deepEqual(await page.locator(".cpg-ol-hit b").allInnerTexts(), ["MT-7000"]);
await page.locator("#cpg-ol-search").press("Enter");
await page.locator(".cpg-ol-qty").first().fill("1200");
await page.locator("#cpg-ol-search").fill("ms-");
await page.locator(".cpg-ol-hit", { hasText: "MS-1004" }).click();
assert.equal(await page.locator("#cpg-ol-lines tr").count(), 2);
assert.deepEqual(await page.locator("#cpg-ol-lines tr td:nth-child(2)").allInnerTexts(), ["점보 7,000ml", "미라네 4호세트"]);
await page.locator("#cpg-ol-submit").click();
assert.equal(await page.locator("#cpg-ol-error").innerText(), "미라네 4호세트의 수량을 입력해 주세요.");
await page.locator(".cpg-ol-qty").nth(1).fill("60");
// 같은 제품을 또 고르면 줄을 늘리지 않고 그 수량 칸으로
await page.locator("#cpg-ol-search").fill("MT-7000");
await page.locator("#cpg-ol-search").press("Enter");
assert.equal(await page.locator("#cpg-ol-lines tr").count(), 2);
await page.locator("#cpg-ol-outbound").fill("2파렛트");
await page.screenshot({ path: path.join(OUT, "cupang-outbound-dialog.png") });
// 완료 → 서버로 보낸 값, 성공 안내
await page.locator("#cpg-ol-submit").click();
await page.locator(".erp-dialog").waitFor({ state: "visible" });
assert.match(await page.locator(".erp-dialog").innerText(), /'20261026\(월\)' 시트 10~11행에 2개 제품을 추가했습니다/);
assert.deepEqual(posts[0], {
document_date: await page.evaluate(() => new Date(Date.now() + 9 * 3600000).toISOString().slice(0, 10)),
ship_date: "2026-10-26", center_arrival_date: "2026-10-27", center: "인천32", ship_method: "파렛트",
outbound: "2파렛트", worker: "핫프렌즈",
lines: [{ code: "MT-7000", name: "점보 7,000ml", quantity: "1200" }, { code: "MS-1004", name: "미라네 4호세트", quantity: "60" }],
});
assert.ok(await page.locator("#cpg-ol-dlg").isHidden(), "성공하면 팝업 닫힘");
await page.screenshot({ path: path.join(OUT, "cupang-outbound-done.png") });
await page.locator(".erp-dialog button", { hasText: "닫기" }).click();
// 다시 열면 비어 있고, 센터 직접 입력 + 실패 응답은 팝업 안에 보여 준다
await openBtn.click();
assert.equal(await page.locator("#cpg-ol-lines tr").count(), 0);
assert.equal(await page.locator("#cpg-ol-ship-date").inputValue(), "");
await pickDate(page, "cpg-ol-ship-date", "10/30");
await pickDate(page, "cpg-ol-arrival-date", "11/2");
await pickDate(page, "cpg-ol-ship-date", "10/31");
assert.equal(await page.locator("#cpg-ol-arrival-date").inputValue(), "2026-11-02", "직접 고른 센터입고일은 유지");
await page.waitForFunction(() => document.querySelectorAll("#cpg-ol-center option").length === 4);
await page.locator("#cpg-ol-center").selectOption("__new__");
await page.locator("#cpg-ol-center-new").fill("실패센터");
await page.locator("#cpg-ol-method").selectOption("택배");
await page.locator("#cpg-ol-search").fill("중형");
await page.locator("#cpg-ol-search").press("Enter");
await page.locator(".cpg-ol-qty").first().fill("5");
await page.locator("#cpg-ol-submit").click();
await page.waitForFunction(() => !document.getElementById("cpg-ol-error").hidden);
assert.match(await page.locator("#cpg-ol-error").innerText(), /구글 시트에 기록하지 못했습니다/);
assert.ok(await page.locator("#cpg-ol-dlg").isVisible(), "실패하면 입력 유지");
assert.equal(posts[1].center, "실패센터");
assert.equal(posts[1].ship_method, "택배");
// Esc: 날짜 팝업이 떠 있으면 그것만 닫고, 다음 Esc 에 출고리스트 팝업 닫힘
await page.locator("#cpg-ol-doc-date + .pj-date-btn").click();
await page.locator(".pj-datepop").waitFor({ state: "visible" });
await page.waitForTimeout(50); // 날짜 팝업은 다음 틱에 Esc 처리를 건다(project.js openDatePopover)
await page.keyboard.press("Escape");
await page.locator(".pj-datepop").waitFor({ state: "detached" });
assert.ok(await page.locator("#cpg-ol-dlg").isVisible());
await page.keyboard.press("Escape");
assert.ok(await page.locator("#cpg-ol-dlg").isHidden());
// 좁은 화면에서도 가로 넘침 없음
await page.setViewportSize({ width: 390, height: 844 });
await openBtn.click();
const over = await page.evaluate(() => {
const box = document.querySelector(".cpg-ol-box");
return box.scrollWidth - box.clientWidth;
});
assert.ok(over <= 1, "모바일 팝업 가로 넘침 " + over);
await page.screenshot({ path: path.join(OUT, "cupang-outbound-mobile.png") });
assert.deepEqual(errors, [], "브라우저 JS 오류 없음");
console.log("ALL PASS — 버튼 위치·색, 프로젝트 날짜 팝업, 센터 목록·직접 입력, 코드표 검색, 완료·실패, Esc, 모바일");
} finally {
if (browser) await browser.close();
await new Promise(resolve => server.close(resolve));
}
})().catch(function (e) { console.error(e); process.exit(1); });
+46
View File
@@ -0,0 +1,46 @@
"""쿠팡 밀크런 첫 화면(달력 + 출고리스트 작성 팝업)을 실제 앱으로 렌더한다. DB·구글 미사용.
python tests/js/render_cupang_index.py -> tests/js/.out/cupang_index_render.html
(브라우저 테스트: tests/js/cupang_outbound.browser.test.js)
"""
import os
import sys
import tempfile
from pathlib import Path
from unittest.mock import patch
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT))
for key in ("ASSET", "CAFE24", "CUPANG", "VACATION", "PROJECT", "DISPATCH", "PERFORMANCE",
"MALAYSIA_STOCK", "ITEMCODE", "EXPENSE", "INOUT"):
os.environ[key + "_DB_URL"] = ""
os.environ.update(SESSION_SECRET_KEY="local-render-only", SESSION_COOKIE_SECURE="false",
PERFORMANCE_AUTO_SYNC="false", CUPANG_SHEET_ID="")
os.environ["DATA_DIR"] = tempfile.mkdtemp(prefix="cupang-render-")
from fastapi.testclient import TestClient # noqa: E402
import app.main as main # noqa: E402
user = {"email": "staff@test.local", "name": "staff", "role": "user", "is_super_admin": False,
"modules": {"cupang": True}}
class Store:
def list_shipments(self, **kw):
return []
def get_shipment(self, **kw):
return None
main.app.state.cupang_store = Store()
with patch.object(main, "get_current_user_record", side_effect=lambda r: user), \
patch.object(main, "get_session_user", side_effect=lambda r: user), \
patch.object(main.user_store, "get", side_effect=lambda e: user):
html = TestClient(main.app).get("/cupang/").text
out = ROOT / "tests/js/.out/cupang_index_render.html"
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(html, encoding="utf-8")
print("rendered:", out)
+300
View File
@@ -0,0 +1,300 @@
"""쿠팡 밀크런 — 밀크런 출고리스트 직접 작성(팝업 → 구글 시트 출고일 시트 맨 아래에 덧붙임).
구글은 쓰지 않는다: 시트 쓰기는 가짜 writer/가짜 Sheets 서비스로 요청 모양만 확인하고,
화면·API 는 격리된 하위 프로세스의 실제 앱(가짜 cupang store, CUPANG_SHEET_ID 미설정)으로 확인한다.
"""
from __future__ import annotations
import importlib
import os
import subprocess
import sys
import tempfile
import threading
import unittest
from pathlib import Path
from typing import Any
import pytest
from fastapi import HTTPException
from app.integrations.google_sheets import GoogleSheetsWriter, a1_sheet, col_letter
from app.modules.cupang.export import PALLET_BG, WORKER, build_block, build_table
# app.modules.cupang 패키지가 APIRouter 를 같은 이름(router)으로 내보내므로 모듈은 이렇게 가져온다
cupang_router = importlib.import_module("app.modules.cupang.router")
ROOT = Path(__file__).resolve().parents[1]
def _payload(**over: Any) -> dict[str, Any]:
body = {
"document_date": "2026-10-23",
"ship_date": "2026-10-26",
"center_arrival_date": "2026-10-27",
"center": "인천32",
"ship_method": "파렛트",
"outbound": "2파렛트",
"worker": "",
"lines": [
{"code": "MT-7000", "name": "점보 7,000ml", "quantity": "1,200"},
{"code": "MS-1004", "name": "미라네 4호세트", "quantity": 60},
],
}
body.update(over)
return body
# ── 양식(export) ─────────────────────────────────────────────
def test_build_block_continues_sequence_and_merges_center_columns():
entry = cupang_router._clean_outbound_entry(_payload())
block = build_block(entry, start_row=12, start_seq=7)
assert block["first_row"] == 12 and block["last_row"] == 13 and block["last_seq"] == 9
assert block["cells"][(12, 2)] == 8 and block["cells"][(13, 2)] == 9 # 순번 이어짐
assert block["cells"][(12, 8)] == "MT-7000" and block["cells"][(13, 10)] == 60
assert block["cells"][(12, 3)] == "2026-10-23(금)" # 작성일(요일)
assert block["cells"][(12, 4)] == "2026-10-26(월)"
assert block["cells"][(12, 6)] == "인천32" and block["cells"][(12, 7)] == "파렛트"
assert block["cells"][(12, 11)] == "2파렛트" and block["cells"][(12, 12)] == WORKER
assert (12, 6, 13, 6) in block["merges"] and (12, 12, 13, 12) in block["merges"]
assert block["is_pallet"] is True
assert build_block({"lines": []}, start_row=6, start_seq=0) is None
def test_build_table_layout_is_unchanged_for_confirmed_shipments():
ships = [
{"document_date": "2026-10-23", "ship_date": "2026-10-26", "center_arrival_date": "2026-10-27",
"center_name_snapshot": "대구3", "ship_method": "택배", "outbound_summary": "3박스",
"lines": [{"product_code": "A", "product_name_snapshot": "가", "quantity": 1}]},
{"document_date": "2026-10-23", "ship_date": "2026-10-26", "center_arrival_date": "2026-10-27",
"center_name_snapshot": "이천1", "ship_method": "파렛트", "outbound_summary": "",
"lines": [{"product_code": "B", "product_name_snapshot": "나", "quantity": 2},
{"product_code": "C", "product_name_snapshot": "다", "quantity": 3}]},
]
table = build_table("2026-10-26", ships)
assert table["title"] == "20261026(월) 쿠팡로켓 밀크런 출고리스트"
assert table["cells"][(5, 2)] == "구분" and table["cells"][(5, 12)] == "작업자"
assert [table["cells"][(r, 2)] for r in (6, 7, 8)] == [1, 2, 3]
assert table["last_row"] == 8 and table["pallet_ranges"] == [(7, 8)]
assert table["cells"][(6, 12)] == WORKER and (7, 6, 8, 6) in table["merges"]
# ── 입력 검사 ───────────────────────────────────────────────
def test_clean_entry_defaults_and_escapes():
entry = cupang_router._clean_outbound_entry(_payload(outbound="=HYPERLINK(1)"))
assert entry["worker"] == WORKER # 비우면 기본 작업자
assert entry["lines"][0]["quantity"] == 1200 # 쉼표 수량
assert entry["outbound_summary"] == "'=HYPERLINK(1)" # 수식으로 해석되지 않게
assert entry["center_name_snapshot"] == "인천32"
@pytest.mark.parametrize("over, words", [
({"ship_method": "화물"}, "출고방식"),
({"ship_date": ""}, "출고일"),
({"center_arrival_date": "2026-13-01"}, "센터입고일"),
({"center": " "}, "입고센터"),
({"lines": []}, "제품"),
({"lines": [{"code": "A", "name": "가", "quantity": 0}]}, "수량"),
({"lines": [{"code": "", "name": "가", "quantity": 1}]}, "제품코드"),
])
def test_clean_entry_rejects_bad_input(over, words):
with pytest.raises(HTTPException) as err:
cupang_router._clean_outbound_entry(_payload(**over))
assert err.value.status_code == 400 and words in err.value.detail
# ── 덧붙일 위치 ─────────────────────────────────────────────
class FakeWriter:
enabled = True
lock = threading.RLock()
def __init__(self, sheets: dict[str, list[list[Any]]]):
self.sheets = sheets
self.calls: list[tuple[str, dict[str, Any]]] = []
def sheet_titles(self, *, spreadsheet_id):
return list(self.sheets)
def read_ranges(self, *, spreadsheet_id, ranges):
out = []
for rng in ranges:
title = rng.split("!")[0].strip("'")
rows = self.sheets.get(title, [])
if "!F6:F" in rng:
out.append([[r[5]] for r in rows[5:] if len(r) > 5 and r[5]])
else:
out.append(rows)
return out
def write_table(self, **kw):
self.calls.append(("write_table", kw))
return {"created": True, "title": kw["title"], "url": "u"}
def append_block(self, **kw):
self.calls.append(("append_block", kw))
return {"created": False, "title": kw["title"], "first_row": kw["first_row"],
"last_row": kw["last_row"], "url": "u"}
def _sheet_rows(data_rows: int) -> list[list[Any]]:
rows: list[list[Any]] = [[], ["", "20261026(월) 쿠팡로켓 밀크런 출고리스트"], [], ["", "회사"],
["", "구분", "작성일"]]
for i in range(1, data_rows + 1):
rows.append(["", str(i), "", "", "", "대구3" if i == 1 else "", "", "X", "엑스", "5"])
return rows
def test_append_below_existing_rows_with_next_sequence():
writer = FakeWriter({"20261026(월)": _sheet_rows(4), "20261023(금)": _sheet_rows(9)})
entry = cupang_router._clean_outbound_entry(_payload())
res = cupang_router._append_outbound_entry(writer, "sheet", entry)
kind, kw = writer.calls[-1]
assert kind == "append_block" and kw["title"] == "20261026(월)"
assert (kw["first_row"], kw["last_row"]) == (10, 11) # 5행 양식 + 4줄 → 10행부터
assert kw["cells"][(10, 2)] == 5 and kw["cells"][(11, 2)] == 6
assert kw["highlight"] == PALLET_BG
assert res["first_row"] == 10
def test_missing_or_blank_sheet_gets_full_template():
for sheets in ({}, {"20261026(월)": [[], ["", "제목만"]]}):
writer = FakeWriter(sheets)
res = cupang_router._append_outbound_entry(
writer, "sheet", cupang_router._clean_outbound_entry(_payload(ship_method="택배")))
kind, kw = writer.calls[-1]
assert kind == "write_table" and kw["title"] == "20261026(월)"
assert kw["cells"][(5, 2)] == "구분" and kw["cells"][(6, 2)] == 1
assert kw["row_highlights"] == []
assert (res["first_row"], res["last_row"]) == (6, 7)
def test_sheet_centers_reads_column_f_of_every_sheet(monkeypatch):
monkeypatch.setattr(cupang_router, "_sheet_centers_cache", {"at": 0.0, "sheet": "", "names": []})
sheets = {"20261026(월)": _sheet_rows(2), "20261023(금)": _sheet_rows(1)}
sheets["20261023(금)"][5][5] = "인천32"
names = cupang_router._sheet_centers(FakeWriter(sheets), "sheet")
assert names == ["대구3", "인천32"]
# ── 구글 시트 writer.append_block 요청 모양 ─────────────────
class _Exec:
def __init__(self, result=None):
self.result = result or {}
def execute(self):
return self.result
class FakeService:
def __init__(self, row_count):
self.row_count = row_count
self.batch: list[dict[str, Any]] = []
self.updates: list[dict[str, Any]] = []
def spreadsheets(self):
return self
def values(self):
return self
def get(self, **kw):
return _Exec({"sheets": [{"properties": {"sheetId": 77, "title": "20261026(월)",
"gridProperties": {"rowCount": self.row_count}}}]})
def batchUpdate(self, **kw):
self.batch.append(kw["body"])
return _Exec()
def update(self, **kw):
self.updates.append(kw)
return _Exec()
def _writer(service):
w = GoogleSheetsWriter.__new__(GoogleSheetsWriter)
w.enabled, w.reason, w._service = True, "", service
return w
def test_append_block_grows_grid_and_writes_from_column_b():
service = FakeService(row_count=10)
entry = cupang_router._clean_outbound_entry(_payload())
block = build_block(entry, start_row=10, start_seq=4)
res = _writer(service).append_block(
spreadsheet_id="s", title="20261026(월)", cells=block["cells"], merges=block["merges"],
first_row=10, last_row=11, first_col=2, last_col=12, highlight=PALLET_BG)
reqs = service.batch[0]["requests"]
assert reqs[0] == {"appendDimension": {"sheetId": 77, "dimension": "ROWS", "length": 1}}
assert any("mergeCells" in r for r in reqs) and any("updateBorders" in r for r in reqs)
upd = service.updates[0]
assert upd["range"] == "'20261026(월)'!B10"
assert len(upd["body"]["values"]) == 2 and len(upd["body"]["values"][0]) == 11
assert upd["body"]["values"][0][0] == 5 # B10 = 순번 5
assert res["url"].endswith("#gid=77")
def test_append_block_missing_sheet_raises():
service = FakeService(row_count=100)
with pytest.raises(LookupError):
_writer(service).append_block(spreadsheet_id="s", title="없는시트", cells={}, merges=[],
first_row=6, last_row=6, first_col=2, last_col=12)
def test_a1_helpers():
assert col_letter(1) == "A" and col_letter(12) == "L" and col_letter(27) == "AA"
assert a1_sheet("20261026(월)") == "'20261026(월)'" and a1_sheet("a'b") == "'a''b'"
# ── 실제 앱(하위 프로세스) — 버튼·팝업·API ──────────────────
APP_CODE = '''
from unittest.mock import patch
from fastapi.testclient import TestClient
import app.main as main
user = {"email": "staff@test.local", "name": "staff", "role": "user", "is_super_admin": False,
"modules": {"cupang": True}}
class Store:
def list_shipments(self, **kw): return []
def get_shipment(self, **kw): return None
def list_centers(self, **kw): return [{"name": "대구3"}, {"name": "이천1"}]
main.app.state.cupang_store = Store()
with patch.object(main, "get_current_user_record", side_effect=lambda r: user), \\
patch.object(main, "get_session_user", side_effect=lambda r: user), \\
patch.object(main.user_store, "get", side_effect=lambda e: user):
c = TestClient(main.app)
html = c.get("/cupang/").text
assert 'id="cpg-ol-open"' in html and "밀크런 출고리스트 작성" in html
assert html.index("+ 신규 등록") < html.index("밀크런 출고리스트 작성") # 신규 등록 바로 옆
assert 'id="cpg-ol-dlg"' in html and 'value="핫프렌즈"' in html
assert "/static/project.js" in html and "/static/cupang-outbound.js" in html and "PJ_LIB_ONLY" in html
r = c.get("/cupang/api/outbound-sheet/centers").json()
assert r["centers"] == ["대구3", "이천1"] and "CUPANG_SHEET_ID" in r["reason"]
bad = c.post("/cupang/api/outbound-sheet", json={"ship_method": "택배"})
assert bad.status_code == 400, bad.text
good = {"document_date": "2026-10-23", "ship_date": "2026-10-26", "center_arrival_date": "2026-10-27",
"center": "대구3", "ship_method": "택배", "lines": [{"code": "A", "name": "가", "quantity": 1}]}
r = c.post("/cupang/api/outbound-sheet", json=good)
assert r.status_code == 503 and "CUPANG_SHEET_ID" in r.json()["detail"], r.text
assert c.get("/static/cupang-outbound.js").status_code == 200
user["modules"] = {"cupang": False}
assert c.post("/cupang/api/outbound-sheet", json=good).status_code == 403
print("OK")
'''
class OutboundSheetAppTests(unittest.TestCase):
def test_page_and_api(self):
env = dict(os.environ)
for key in ("ASSET", "CAFE24", "CUPANG", "VACATION", "PROJECT", "DISPATCH", "PERFORMANCE",
"MALAYSIA_STOCK", "ITEMCODE", "EXPENSE", "INOUT"):
env[key + "_DB_URL"] = ""
env.update(SESSION_SECRET_KEY="local-cupang-test-only", SESSION_COOKIE_SECURE="false",
PERFORMANCE_AUTO_SYNC="false", CUPANG_SHEET_ID="")
with tempfile.TemporaryDirectory(prefix="cupang-outbound-") as directory:
env["DATA_DIR"] = directory
res = subprocess.run([sys.executable, "-c", APP_CODE], cwd=ROOT, env=env, capture_output=True,
text=True, encoding="utf-8", timeout=120)
self.assertEqual(res.returncode, 0, res.stdout + res.stderr)
self.assertIn("OK", res.stdout)