fix(cupang): 밀크런 출고리스트를 구글 드라이브 엑셀(.xlsx) 파일에 기록
- 출고리스트 문서(1J74op7lBZOgE27p4R28I3RWsv0EtXdii)는 구글 시트가 아니라 드라이브에 올린 .xlsx 라 Sheets API 로는 쓸 수 없었다 → app/integrations/drive_xlsx.py 추가: 내려받아 openpyxl 로 고친 뒤 같은 파일 id 에 다시 올림(GoogleSheetsWriter 와 같은 메서드, lock 블록 = 내려받기·올리기 1번씩) - 올리기 직전 파일 version 이 바뀌었으면 덮어쓰지 않고 처음부터 다시(최대 3번) - router._sheet_target: 드라이브에서 형식을 보고 xlsx/구글 시트 writer 선택, CUPANG_SHEET_ID 기본값 = 위 파일 (출고리스트 작성 팝업과 분배 확정·출고 삭제 동기화 모두 적용) - 팝업 문구 "구글 시트" → "출고리스트 엑셀", cupang-outbound.js 캐시 버전 올림 - 테스트: 가짜 Drive 에 진짜 xlsx 를 두고 덧붙이기·양식 생성·충돌 재시도·시트 삭제·범위 읽기·writer 선택 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+4
-3
@@ -26,9 +26,10 @@ CUSTOMER_ORDER_LIST_URL=/orderlist/
|
||||
# DB/역할/스키마/센터 seed 생성: scripts/sql/cupang_db_init.sql 참고.
|
||||
# CUPANG_DB_URL=postgresql://cupang_app:replace-me@postgres-db:5432/cupang_db
|
||||
|
||||
# 쿠팡 밀크런 출고리스트를 기록할 Google 스프레드시트 (분배 확정 시 출고일 시트 생성)
|
||||
# - 대상 문서는 반드시 "Google 스프레드시트" 형식(업로드한 .xlsx 는 파일>Google 스프레드시트로 저장)
|
||||
# - 서비스 계정 이메일(client_email)에 해당 문서를 편집자로 공유해야 한다
|
||||
# 쿠팡 밀크런 출고리스트 문서 (분배 확정·출고리스트 작성 팝업이 출고일 시트에 기록)
|
||||
# - 구글 드라이브에 올린 .xlsx 파일 id(기본값 = 아래 id). 구글 스프레드시트 문서 id 여도 된다(형식 자동 판별)
|
||||
# - .xlsx 는 Drive 권한이 필요하다: 서비스 계정(GOOGLE_SHEETS_CREDENTIALS) 또는 GOOGLE_SLIDES_OAUTH_REFRESH_TOKEN
|
||||
# - 서비스 계정이면 이메일(client_email)에 해당 파일을 편집자로 공유해야 한다
|
||||
# CUPANG_SHEET_ID=1J74op7lBZOgE27p4R28I3RWsv0EtXdii
|
||||
#
|
||||
# [방식 A] 사용자 OAuth 리프레시 토큰 — 조직 정책으로 서비스 계정 키를 못 만들 때
|
||||
|
||||
@@ -0,0 +1,345 @@
|
||||
"""Google 드라이브에 올려 둔 엑셀(.xlsx) 파일을 시트처럼 고쳐 쓰기(쿠팡 밀크런 출고리스트, 2026-10-23).
|
||||
|
||||
구글 시트 문서가 아니라 드라이브의 .xlsx 파일이면 Sheets API 로는 쓸 수 없다. 그래서
|
||||
파일을 내려받아(openpyxl) 고친 뒤 같은 파일 id 에 내용을 다시 올린다(링크·공유·이름 그대로).
|
||||
|
||||
- 인증은 google_drive 와 같다(서비스 계정 우선, 없으면 OAuth 리프레시 토큰 — Drive 권한 포함).
|
||||
- `GoogleSheetsWriter` 와 같은 메서드(sheet_titles·read_ranges·append_block·write_table·delete_sheet·lock)를
|
||||
같은 인자로 제공한다 → cupang 라우터는 어느 쪽인지 몰라도 된다(`file_kind` 로 골라 씀).
|
||||
- `with writer.lock:` 안의 호출은 내려받은 사본 하나를 같이 쓰고, 블록이 끝날 때 바뀐 게 있으면 한 번만 올린다.
|
||||
잠금 밖에서 부른 메서드는 호출마다 내려받고(바뀌면) 올린다.
|
||||
- 올리기 직전에 파일 version 을 다시 보고, 그 사이 누가 고쳤으면 `XlsxChangedError` — 덮어쓰지 않는다
|
||||
(호출부가 처음부터 다시 시도).
|
||||
- 비밀값은 로그·화면에 출력하지 않는다.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import threading
|
||||
from io import BytesIO
|
||||
from typing import Any
|
||||
|
||||
from app.integrations.google_drive import GoogleDriveError, GoogleDriveFiles, _friendly_drive
|
||||
|
||||
XLSX_MIME = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
||||
SHEETS_MIME = "application/vnd.google-apps.spreadsheet"
|
||||
_RANGE_RE = re.compile(r"^([A-Z]+)(\d*)(?::([A-Z]+)(\d*))?$")
|
||||
|
||||
# 같은 파일을 두 요청이 동시에 내려받아 고치면 나중 것이 앞의 것을 지우므로 한 번에 하나씩.
|
||||
_LOCK = threading.RLock()
|
||||
_KIND_CACHE: dict[str, str] = {}
|
||||
|
||||
|
||||
class XlsxChangedError(RuntimeError):
|
||||
"""내려받은 뒤 올리기 전에 다른 사람이 파일을 고쳤다."""
|
||||
|
||||
|
||||
def _col_num(letters: str) -> int:
|
||||
n = 0
|
||||
for ch in letters:
|
||||
n = n * 26 + (ord(ch) - 64)
|
||||
return n
|
||||
|
||||
|
||||
def _parse_range(a1: str) -> tuple[str, int, int, int | None, int | None]:
|
||||
""""'시트'!F6:F" → (시트, 첫 행, 첫 열, 끝 행|None, 끝 열|None). 끝이 비면 시트 끝까지."""
|
||||
sheet, _, ref = a1.rpartition("!")
|
||||
if sheet.startswith("'") and sheet.endswith("'"):
|
||||
sheet = sheet[1:-1].replace("''", "'")
|
||||
m = _RANGE_RE.match(ref.upper())
|
||||
if not sheet or not m:
|
||||
raise ValueError(f"지원하지 않는 범위: {a1}")
|
||||
c1, r1, c2, r2 = m.groups()
|
||||
if c2 is None: # 셀 하나
|
||||
c2, r2 = c1, r1
|
||||
return sheet, int(r1 or 1), _col_num(c1), (int(r2) if r2 else None), _col_num(c2)
|
||||
|
||||
|
||||
def _text(value: Any) -> str:
|
||||
"""Sheets API 의 FORMATTED_VALUE 처럼 문자열로(정수인 실수는 소수점 없이)."""
|
||||
if value is None:
|
||||
return ""
|
||||
if isinstance(value, float) and value.is_integer():
|
||||
return str(int(value))
|
||||
return str(value)
|
||||
|
||||
|
||||
def _put(cell: Any, value: Any) -> None:
|
||||
"""Sheets 의 USER_ENTERED 처럼 앞의 작은따옴표는 "글자 그대로" 표시로 보고 떼어 낸다."""
|
||||
if isinstance(value, str) and value.startswith("'"):
|
||||
cell.value = value[1:]
|
||||
cell.data_type = "s" # '=' 로 시작해도 수식이 되지 않게
|
||||
else:
|
||||
cell.value = value
|
||||
|
||||
|
||||
class DriveXlsxWriter(GoogleDriveFiles):
|
||||
"""드라이브 .xlsx 파일 하나를 GoogleSheetsWriter 처럼 다룬다(spreadsheet_id = 드라이브 파일 id)."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
super().__init__()
|
||||
self._depth = 0
|
||||
self._book: dict[str, Any] | None = None # {"id", "wb", "version", "dirty"}
|
||||
|
||||
# ── 내려받기 / 올리기 ───────────────────────────
|
||||
def file_kind(self, file_id: str) -> str:
|
||||
""""xlsx" | "sheets" | 그 밖의 mimeType. 실패는 GoogleDriveError(사유)."""
|
||||
if file_id in _KIND_CACHE:
|
||||
return _KIND_CACHE[file_id]
|
||||
meta = self._meta(file_id, "mimeType")
|
||||
mime = str(meta.get("mimeType") or "")
|
||||
kind = "xlsx" if mime == XLSX_MIME else "sheets" if mime == SHEETS_MIME else mime
|
||||
_KIND_CACHE[file_id] = kind
|
||||
return kind
|
||||
|
||||
def _meta(self, file_id: str, fields: str) -> dict[str, Any]:
|
||||
self._check()
|
||||
try:
|
||||
return self._service().files().get(fileId=file_id, fields=fields, supportsAllDrives=True).execute()
|
||||
except Exception as exc: # noqa: BLE001
|
||||
raise self._error(exc) from None
|
||||
|
||||
@staticmethod
|
||||
def _error(exc: Exception) -> GoogleDriveError:
|
||||
text = _friendly_drive(exc).replace("업무 파일 폴더", "출고리스트 엑셀 파일")
|
||||
return GoogleDriveError(text)
|
||||
|
||||
def _open(self, file_id: str) -> dict[str, Any]:
|
||||
from openpyxl import load_workbook
|
||||
|
||||
version = str(self._meta(file_id, "version").get("version") or "")
|
||||
try:
|
||||
data = self._service().files().get_media(fileId=file_id, supportsAllDrives=True).execute()
|
||||
except Exception as exc: # noqa: BLE001
|
||||
raise self._error(exc) from None
|
||||
return {"id": file_id, "wb": load_workbook(BytesIO(data)), "version": version, "dirty": False}
|
||||
|
||||
def _save(self, book: dict[str, Any]) -> None:
|
||||
from googleapiclient.http import MediaIoBaseUpload
|
||||
|
||||
now = str(self._meta(book["id"], "version").get("version") or "")
|
||||
if book["version"] and now != book["version"]:
|
||||
raise XlsxChangedError("출고리스트 엑셀 파일이 그 사이 바뀌었습니다.")
|
||||
out = BytesIO()
|
||||
book["wb"].save(out)
|
||||
out.seek(0)
|
||||
try:
|
||||
self._service().files().update(
|
||||
fileId=book["id"], media_body=MediaIoBaseUpload(out, mimetype=XLSX_MIME, resumable=False),
|
||||
fields="id", supportsAllDrives=True,
|
||||
).execute()
|
||||
except Exception as exc: # noqa: BLE001
|
||||
raise self._error(exc) from None
|
||||
|
||||
class _Session:
|
||||
def __init__(self, writer: "DriveXlsxWriter") -> None:
|
||||
self.w = writer
|
||||
|
||||
def __enter__(self) -> "DriveXlsxWriter":
|
||||
_LOCK.acquire()
|
||||
self.w._depth += 1
|
||||
return self.w
|
||||
|
||||
def __exit__(self, exc_type: Any, *_: Any) -> None:
|
||||
w = self.w
|
||||
try:
|
||||
w._depth -= 1
|
||||
if w._depth == 0:
|
||||
book, w._book = w._book, None
|
||||
if exc_type is None and book is not None and book["dirty"]:
|
||||
w._save(book)
|
||||
finally:
|
||||
_LOCK.release()
|
||||
|
||||
@property
|
||||
def lock(self) -> "DriveXlsxWriter._Session":
|
||||
"""이 블록 안의 호출은 내려받은 사본 하나를 같이 쓰고, 끝날 때 바뀐 게 있으면 한 번 올린다."""
|
||||
return DriveXlsxWriter._Session(self)
|
||||
|
||||
def _wb(self, file_id: str) -> Any:
|
||||
if self._book is None or self._book["id"] != file_id:
|
||||
if self._book is not None and self._book["dirty"]:
|
||||
self._save(self._book)
|
||||
self._book = self._open(file_id)
|
||||
return self._book["wb"]
|
||||
|
||||
def _touch(self) -> None:
|
||||
if self._book is not None:
|
||||
self._book["dirty"] = True
|
||||
|
||||
@staticmethod
|
||||
def _url(file_id: str) -> str:
|
||||
return f"https://docs.google.com/spreadsheets/d/{file_id}/edit"
|
||||
|
||||
# ── GoogleSheetsWriter 와 같은 메서드 ────────────
|
||||
def sheet_titles(self, *, spreadsheet_id: str) -> list[str]:
|
||||
with self.lock:
|
||||
return list(self._wb(spreadsheet_id).sheetnames)
|
||||
|
||||
def read_ranges(self, *, spreadsheet_id: str, ranges: list[str], chunk: int = 50) -> list[list[list[Any]]]:
|
||||
"""범위마다 값의 2차원 목록(문자열) — Sheets API 처럼 뒤쪽 빈 칸·빈 행은 잘라 낸다."""
|
||||
del chunk
|
||||
with self.lock:
|
||||
wb = self._wb(spreadsheet_id)
|
||||
out: list[list[list[Any]]] = []
|
||||
for a1 in ranges:
|
||||
title, r1, c1, r2, c2 = _parse_range(a1)
|
||||
if title not in wb.sheetnames:
|
||||
out.append([])
|
||||
continue
|
||||
ws = wb[title]
|
||||
rows = [
|
||||
[_text(v) for v in row]
|
||||
for row in ws.iter_rows(min_row=r1, max_row=r2 or ws.max_row, min_col=c1,
|
||||
max_col=c2 or ws.max_column, values_only=True)
|
||||
]
|
||||
for row in rows:
|
||||
while row and row[-1] == "":
|
||||
row.pop()
|
||||
while rows and not rows[-1]:
|
||||
rows.pop()
|
||||
out.append(rows)
|
||||
return out
|
||||
|
||||
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 에 표 한 덩어리(위쪽 내용은 그대로). 서식은 GoogleSheetsWriter 와 같다."""
|
||||
from openpyxl.styles import PatternFill
|
||||
|
||||
with self.lock:
|
||||
wb = self._wb(spreadsheet_id)
|
||||
if title not in wb.sheetnames:
|
||||
raise LookupError(f"시트 '{title}' 이(가) 없습니다.")
|
||||
ws = wb[title]
|
||||
for (r, c), value in cells.items():
|
||||
_put(ws.cell(row=r, column=c), value)
|
||||
for (r1, c1, r2, c2) in merges:
|
||||
ws.merge_cells(start_row=r1, start_column=c1, end_row=r2, end_column=c2)
|
||||
fill = PatternFill("solid", fgColor=highlight) if highlight else PatternFill(fill_type=None)
|
||||
_style_rows(ws, first_row, last_row, first_col, last_col, left_cols=left_cols, fill=fill)
|
||||
self._touch()
|
||||
return {
|
||||
"created": False, "title": title, "first_row": first_row, "last_row": last_row,
|
||||
"url": self._url(spreadsheet_id),
|
||||
}
|
||||
|
||||
def delete_sheet(self, *, spreadsheet_id: str, title: str) -> dict[str, Any]:
|
||||
"""시트 1장 삭제. 없으면 missing, 문서에 그 하나뿐이면 내용만 비운다(cleared)."""
|
||||
with self.lock:
|
||||
wb = self._wb(spreadsheet_id)
|
||||
if title not in wb.sheetnames:
|
||||
return {"ok": True, "action": "missing", "title": title}
|
||||
if len(wb.sheetnames) <= 1:
|
||||
_replace_sheet(wb, title)
|
||||
action = "cleared"
|
||||
else:
|
||||
wb.remove(wb[title])
|
||||
wb.active = min(wb.index(wb.active) if wb.active is not None else 0, len(wb.sheetnames) - 1)
|
||||
action = "deleted"
|
||||
self._touch()
|
||||
return {"ok": True, "action": action, "title": title}
|
||||
|
||||
def write_table(
|
||||
self,
|
||||
*,
|
||||
spreadsheet_id: str,
|
||||
title: str,
|
||||
cells: dict[tuple[int, int], Any],
|
||||
merges: list[tuple[int, int, int, int]],
|
||||
header_row: int,
|
||||
first_data_row: int,
|
||||
last_row: int,
|
||||
first_col: int,
|
||||
last_col: int,
|
||||
title_row: int,
|
||||
widths: dict[int, int],
|
||||
header_bg: str = "",
|
||||
row_highlights: list[tuple[int, int, str]] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""시트를 만들고(있으면 새로 갈아 끼우고) 표를 통째로 기록한다. 좌표 1-based, 색은 "RRGGBB"."""
|
||||
from openpyxl.styles import Alignment, Font, PatternFill
|
||||
from openpyxl.utils import get_column_letter
|
||||
|
||||
with self.lock:
|
||||
wb = self._wb(spreadsheet_id)
|
||||
created = title not in wb.sheetnames
|
||||
ws = _replace_sheet(wb, title)
|
||||
for (r, c), value in cells.items():
|
||||
_put(ws.cell(row=r, column=c), value)
|
||||
for (r1, c1, r2, c2) in merges:
|
||||
ws.merge_cells(start_row=r1, start_column=c1, end_row=r2, end_column=c2)
|
||||
|
||||
center = Alignment(horizontal="center", vertical="center", wrap_text=True)
|
||||
head = ws.cell(row=title_row, column=first_col)
|
||||
head.font = Font(size=16, bold=True)
|
||||
head.alignment = center
|
||||
ws.row_dimensions[title_row].height = 28
|
||||
header_fill = PatternFill("solid", fgColor=header_bg) if header_bg else PatternFill(fill_type=None)
|
||||
_style_rows(ws, header_row, header_row, first_col, last_col, left_cols=(), fill=header_fill)
|
||||
for col in range(first_col, last_col + 1):
|
||||
ws.cell(row=header_row, column=col).font = Font(bold=True)
|
||||
if last_row >= first_data_row:
|
||||
_style_rows(ws, first_data_row, last_row, first_col, last_col, left_cols=(9,), fill=None)
|
||||
for (r1, r2, color) in (row_highlights or []):
|
||||
fill = PatternFill("solid", fgColor=color)
|
||||
for row in range(r1, r2 + 1):
|
||||
for col in range(first_col, last_col + 1):
|
||||
ws.cell(row=row, column=col).fill = fill
|
||||
for col, px in widths.items():
|
||||
ws.column_dimensions[get_column_letter(col)].width = round(px / 7.0, 2)
|
||||
self._touch()
|
||||
return {"created": created, "title": title, "url": self._url(spreadsheet_id)}
|
||||
|
||||
|
||||
def _replace_sheet(wb: Any, title: str) -> Any:
|
||||
"""같은 이름의 빈 시트로 갈아 끼운다(탭 위치 유지). 없으면 맨 뒤에 새로."""
|
||||
if title in wb.sheetnames:
|
||||
index = wb.sheetnames.index(title)
|
||||
wb.remove(wb[title])
|
||||
return wb.create_sheet(title, index)
|
||||
return wb.create_sheet(title)
|
||||
|
||||
|
||||
def _style_rows(
|
||||
ws: Any, r1: int, r2: int, c1: int, c2: int, *, left_cols: tuple[int, ...], fill: Any
|
||||
) -> None:
|
||||
"""가운데 정렬·줄바꿈·얇은 검은 테두리, left_cols 만 왼쪽 정렬. fill 이 None 이면 배경은 그대로."""
|
||||
from openpyxl.styles import Alignment, Border, Side
|
||||
|
||||
thin = Side(style="thin", color="000000")
|
||||
box = Border(left=thin, right=thin, top=thin, bottom=thin)
|
||||
center = Alignment(horizontal="center", vertical="center", wrap_text=True)
|
||||
left = Alignment(horizontal="left", vertical="center", wrap_text=True)
|
||||
for row in range(r1, r2 + 1):
|
||||
for col in range(c1, c2 + 1):
|
||||
cell = ws.cell(row=row, column=col)
|
||||
cell.border = box
|
||||
cell.alignment = left if col in left_cols else center
|
||||
if fill is not None:
|
||||
cell.fill = fill
|
||||
|
||||
|
||||
_WRITER: DriveXlsxWriter | None = None
|
||||
_WRITER_LOCK = threading.Lock()
|
||||
|
||||
|
||||
def get_writer() -> DriveXlsxWriter:
|
||||
"""프로세스당 하나(설정이 비어 있으면 매번 다시 확인)."""
|
||||
global _WRITER
|
||||
with _WRITER_LOCK:
|
||||
if _WRITER is None or not _WRITER.enabled:
|
||||
_WRITER = DriveXlsxWriter()
|
||||
return _WRITER
|
||||
@@ -15,10 +15,16 @@
|
||||
- 양식 생성은 `export.py` 한 곳에서 만들어 xlsx·구글시트가 공유.
|
||||
- 작업 중 상태는 `cupang_box_calc_drafts` 에 이름 붙여 임시 저장/불러오기.
|
||||
|
||||
## 구글 시트 동기화
|
||||
## 출고리스트 문서 동기화 (드라이브 엑셀 파일)
|
||||
|
||||
- `CUPANG_SHEET_ID` + 인증(사용자 OAuth `GOOGLE_SHEETS_OAUTH_REFRESH_TOKEN` 또는 서비스 계정 `GOOGLE_SHEETS_CREDENTIALS[_JSON]`) 설정 시
|
||||
확정과 동시에 Google 스프레드시트에 출고일 시트를 생성/덮어쓰기(`app/integrations/google_sheets.py`, 미설정이면 조용히 skip).
|
||||
- 출고리스트 문서는 **구글 드라이브에 올린 .xlsx 파일**(`CUPANG_SHEET_ID`, 기본 `router.DEFAULT_SHEET_ID`
|
||||
= `1J74op7lBZOgE27p4R28I3RWsv0EtXdii`). `router._sheet_target` 이 드라이브에서 형식을 보고 writer 를 고른다:
|
||||
- .xlsx → `app/integrations/drive_xlsx.py` — 내려받아 openpyxl 로 고친 뒤 같은 파일 id 에 다시 올림
|
||||
(인증은 google_drive 와 같음: 서비스 계정 또는 `GOOGLE_SLIDES_OAUTH_REFRESH_TOKEN`/`GOOGLE_SHEETS_OAUTH_REFRESH_TOKEN`, Drive 권한).
|
||||
`with writer.lock:` 블록 = 내려받기 1번·올리기 1번. 올리기 직전 version 이 바뀌었으면(누가 고침) `_in_sheet` 가 처음부터 다시(3번).
|
||||
- 구글 시트 문서 → 예전처럼 `google_sheets.py`(Sheets API). 드라이브 인증이 없을 때도 이쪽.
|
||||
- 엑셀은 openpyxl 로 다시 저장하므로 파일 안 그림·차트는 사라진다(출고리스트에는 없음).
|
||||
- 인증이 없으면 조용히 skip. 확정과 동시에 출고일 시트를 생성/덮어쓰기.
|
||||
- 출고 삭제(건별/날짜 전체) 시에도 같은 날짜 시트 동기화 — 남은 출고가 있으면 다시 쓰고, 없으면 시트 삭제
|
||||
(문서에 시트가 하나뿐이면 내용만 비움).
|
||||
|
||||
@@ -46,10 +52,10 @@
|
||||
- 광고비·할인 프로모션·장려금은 주차 단위(`cupang_sales_weekly`)로 보관, 순마진은 화면에서 계산.
|
||||
- 초기 데이터는 `scripts/sql/cupang_sales_seed.sql`.
|
||||
|
||||
## 밀크런 출고리스트 작성 (팝업 → 구글 시트, 2026-10-23)
|
||||
## 밀크런 출고리스트 작성 (팝업 → 드라이브 엑셀 파일, 2026-10-23)
|
||||
|
||||
- 첫 화면 "+ 신규 등록" 옆 엑셀색(#217346) 버튼 → 팝업(`index.html` + `static/cupang-outbound.js`).
|
||||
상자 계산 없이 센터 1곳을 **구글 시트에만** 적는다 — cupang_db 출고 묶음은 만들지 않는다(달력에 안 보임).
|
||||
상자 계산 없이 센터 1곳을 **출고리스트 엑셀 파일에만** 적는다(위 "출고리스트 문서 동기화") — cupang_db 출고 묶음은 만들지 않는다(달력에 안 보임).
|
||||
- 입력: 작성일(기본 오늘)·출고일·센터입고일(출고일 고르면 +1일 자동) — 날짜 칸은 프로젝트 날짜 팝업
|
||||
(`PJLib.enhanceDateInput`, project.js 를 `PJ_LIB_ONLY` 로 로드). 입고센터(시트 F열 + 등록 센터, 직접 입력 가능),
|
||||
출고방식(파렛트/택배), 제품(코드표 `GET /cupang/api/products/all` 검색 → 코드·이름 자동, 수량 수기), 출고(수기), 작업자(기본 `export.WORKER`).
|
||||
|
||||
@@ -245,21 +245,57 @@ def _shipments_for_date(store: Any, ship_date: str) -> list[dict[str, Any]]:
|
||||
return out
|
||||
|
||||
|
||||
# 출고리스트 문서 — 구글 드라이브에 올려 둔 엑셀(.xlsx) 파일(2026-10-23). 구글 시트 문서여도 된다.
|
||||
DEFAULT_SHEET_ID = "1J74op7lBZOgE27p4R28I3RWsv0EtXdii"
|
||||
|
||||
|
||||
def _sheet_target(store: Any) -> tuple[Any, str, dict[str, Any] | None]:
|
||||
"""(writer, spreadsheet_id, skip 사유) — 설정이 없으면 skip 정보를 돌려준다."""
|
||||
"""(writer, 문서 id, skip 사유) — 쓸 수 없으면 skip 정보를 돌려준다.
|
||||
|
||||
문서 형식은 드라이브에서 보고 고른다 — .xlsx 파일이면 drive_xlsx(내려받아 고친 뒤 다시 올림),
|
||||
구글 시트 문서면 google_sheets. 두 writer 는 같은 메서드를 갖는다."""
|
||||
import os # noqa: WPS433
|
||||
|
||||
from app.integrations.google_sheets import get_writer # noqa: WPS433
|
||||
from app.integrations import drive_xlsx, google_sheets # noqa: WPS433
|
||||
|
||||
spreadsheet_id = (os.getenv("CUPANG_SHEET_ID") or "").strip()
|
||||
if not spreadsheet_id:
|
||||
return None, "", {"ok": False, "skipped": True, "reason": "CUPANG_SHEET_ID 미설정"}
|
||||
writer = get_writer()
|
||||
spreadsheet_id = (os.getenv("CUPANG_SHEET_ID") or "").strip() or DEFAULT_SHEET_ID
|
||||
drive = drive_xlsx.get_writer()
|
||||
if not drive.enabled:
|
||||
# 드라이브 인증이 없으면 예전처럼 Sheets API 로(구글 시트 문서일 때만 된다)
|
||||
writer = google_sheets.get_writer()
|
||||
if not writer.enabled:
|
||||
return None, "", {"ok": False, "skipped": True, "reason": writer.reason}
|
||||
return writer, spreadsheet_id, None
|
||||
try:
|
||||
kind = drive.file_kind(spreadsheet_id)
|
||||
except Exception as exc: # noqa: BLE001 - 사유만(비밀값 없음)
|
||||
return None, "", {"ok": False, "skipped": True, "reason": str(exc) or type(exc).__name__}
|
||||
if kind == "xlsx":
|
||||
return drive, spreadsheet_id, None
|
||||
if kind != "sheets":
|
||||
return None, "", {"ok": False, "skipped": True, "reason": f"엑셀·구글 시트 파일이 아닙니다({kind})"}
|
||||
writer = google_sheets.get_writer()
|
||||
if not writer.enabled:
|
||||
return None, "", {"ok": False, "skipped": True, "reason": writer.reason}
|
||||
return writer, spreadsheet_id, None
|
||||
|
||||
|
||||
def _in_sheet(writer: Any, fn: Any) -> Any:
|
||||
"""`with writer.lock:` 안에서 fn() — 읽기~쓰기를 한 덩어리로.
|
||||
|
||||
엑셀 파일(drive_xlsx)은 내려받은 뒤 올리기 전에 누가 파일을 고쳤으면 처음부터 다시(최대 3번)."""
|
||||
from app.integrations.drive_xlsx import XlsxChangedError # noqa: WPS433
|
||||
|
||||
for attempt in range(3):
|
||||
try:
|
||||
with writer.lock:
|
||||
return fn()
|
||||
except XlsxChangedError:
|
||||
if attempt == 2:
|
||||
raise
|
||||
return None
|
||||
|
||||
|
||||
def _sync_google_sheet_after_delete(store: Any, ship_date: str) -> dict[str, Any]:
|
||||
"""출고 삭제 후 구글 시트를 현재 상태에 맞춘다.
|
||||
|
||||
@@ -277,7 +313,8 @@ def _sync_google_sheet_after_delete(store: Any, ship_date: str) -> dict[str, Any
|
||||
return _push_to_google_sheet(store, ship_date)
|
||||
|
||||
try:
|
||||
res = writer.delete_sheet(spreadsheet_id=spreadsheet_id, title=sheet_title(ship_date))
|
||||
res = _in_sheet(writer, lambda: writer.delete_sheet(spreadsheet_id=spreadsheet_id,
|
||||
title=sheet_title(ship_date)))
|
||||
except Exception as exc: # noqa: BLE001 - 사유만 남긴다
|
||||
return {"ok": False, "skipped": False, "reason": f"{type(exc).__name__}: {exc}"}
|
||||
return {"ok": True, "skipped": False, **res}
|
||||
@@ -293,10 +330,10 @@ def _log_sheet(action: str, ship_date: str, res: dict[str, Any]) -> None:
|
||||
|
||||
|
||||
def _push_to_google_sheet(store: Any, ship_date: str) -> dict[str, Any]:
|
||||
"""확정한 출고일을 Google 스프레드시트에 시트 1장으로 기록.
|
||||
"""확정한 출고일을 출고리스트 문서(드라이브 엑셀 또는 구글 시트)에 시트 1장으로 기록.
|
||||
|
||||
- 대상 스프레드시트: 환경변수 `CUPANG_SHEET_ID`
|
||||
- 인증: 서비스 계정(app/integrations/google_sheets.py). 미설정이면 조용히 skip.
|
||||
- 대상 문서: 환경변수 `CUPANG_SHEET_ID`(기본 DEFAULT_SHEET_ID), 형식은 `_sheet_target` 이 고른다.
|
||||
- 인증: 서비스 계정 또는 OAuth(app/integrations/drive_xlsx.py·google_sheets.py). 미설정이면 조용히 skip.
|
||||
- 실패해도 출고 묶음 저장은 이미 끝났으므로 예외를 밖으로 던지지 않는다.
|
||||
"""
|
||||
writer, spreadsheet_id, skip = _sheet_target(store)
|
||||
@@ -308,7 +345,7 @@ def _push_to_google_sheet(store: Any, ship_date: str) -> dict[str, Any]:
|
||||
return {"ok": False, "skipped": True, "reason": "해당 출고일의 출고 묶음 없음"}
|
||||
|
||||
try:
|
||||
res = _write_full_sheet(writer, spreadsheet_id, ship_date, shipments)
|
||||
res = _in_sheet(writer, lambda: _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}
|
||||
@@ -344,7 +381,7 @@ def _write_full_sheet(
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 밀크런 출고리스트 직접 작성 — 상자 계산 없이 팝업에서 입력한 센터 1곳을
|
||||
# 구글 시트의 출고일 시트(YYYYMMDD(요일)) 맨 아래에 덧붙인다. cupang_db 에는 저장하지 않는다.
|
||||
# 출고리스트 문서(드라이브 엑셀 파일)의 출고일 시트(YYYYMMDD(요일)) 맨 아래에 덧붙인다. cupang_db 에는 저장하지 않는다.
|
||||
# ════════════════════════════════════════════════════════════
|
||||
OUTBOUND_SHEET_METHODS: tuple[str, ...] = ("파렛트", "택배")
|
||||
_SHEET_CENTERS_TTL_SECONDS = 600
|
||||
@@ -418,11 +455,12 @@ def _sheet_centers(writer: Any, spreadsheet_id: str) -> list[str]:
|
||||
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],
|
||||
)
|
||||
with writer.lock: # 엑셀 파일이면 한 번만 내려받는다
|
||||
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()
|
||||
})
|
||||
@@ -486,7 +524,7 @@ def outbound_sheet_centers(
|
||||
try:
|
||||
names.update(_sheet_centers(writer, spreadsheet_id))
|
||||
except Exception as exc: # noqa: BLE001 - 목록은 등록 센터만으로도 쓸 수 있다
|
||||
reason = f"구글 시트를 읽지 못했습니다({type(exc).__name__})"
|
||||
reason = f"출고리스트 파일을 읽지 못했습니다({type(exc).__name__})"
|
||||
return JSONResponse({"centers": sorted(names), "reason": reason})
|
||||
|
||||
|
||||
@@ -500,16 +538,24 @@ def outbound_sheet_write(
|
||||
writer, spreadsheet_id, skip = _sheet_target(_store(request))
|
||||
if skip:
|
||||
raise HTTPException(
|
||||
status_code=503, detail=f"구글 시트에 쓸 수 없습니다: {skip.get('reason') or '설정 확인 필요'}"
|
||||
status_code=503, detail=f"출고리스트 파일에 쓸 수 없습니다: {skip.get('reason') or '설정 확인 필요'}"
|
||||
)
|
||||
from app.integrations.drive_xlsx import XlsxChangedError # noqa: WPS433
|
||||
from app.integrations.google_drive import GoogleDriveError # noqa: WPS433
|
||||
|
||||
try:
|
||||
# 시트 끝 위치를 읽고 쓰는 사이에 다른 요청이 끼어들지 않게 한 덩어리로
|
||||
with writer.lock:
|
||||
res = _append_outbound_entry(writer, spreadsheet_id, entry)
|
||||
res = _in_sheet(writer, lambda: _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__})
|
||||
if isinstance(exc, XlsxChangedError):
|
||||
why = "다른 사람이 파일을 고치는 중입니다"
|
||||
elif isinstance(exc, GoogleDriveError):
|
||||
why = str(exc)
|
||||
else:
|
||||
why = type(exc).__name__
|
||||
raise HTTPException(
|
||||
status_code=502, detail=f"구글 시트에 기록하지 못했습니다({type(exc).__name__}). 잠시 후 다시 시도해 주세요."
|
||||
status_code=502, detail=f"출고리스트 파일에 기록하지 못했습니다({why}). 잠시 후 다시 시도해 주세요."
|
||||
) 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"]
|
||||
|
||||
@@ -175,7 +175,7 @@
|
||||
<input type="hidden" name="next" id="cpg-del-next" />
|
||||
</form>
|
||||
|
||||
<!-- 밀크런 출고리스트 작성 팝업 — 완료하면 구글 시트 출고일 시트 아래에 덧붙인다 -->
|
||||
<!-- 밀크런 출고리스트 작성 팝업 — 완료하면 출고리스트 엑셀(구글 드라이브 .xlsx) 출고일 시트 아래에 덧붙인다 -->
|
||||
<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">
|
||||
@@ -230,7 +230,7 @@
|
||||
|
||||
{% block scripts %}
|
||||
<script src="/static/project.js?v=20261022c" defer></script>
|
||||
<script src="/static/cupang-outbound.js?v=20261023a" defer></script>
|
||||
<script src="/static/cupang-outbound.js?v=20261023b" defer></script>
|
||||
<script>
|
||||
(function () {
|
||||
var dlg = document.getElementById("cpg-del-dlg");
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/* 쿠팡 밀크런 — 밀크런 출고리스트 작성 팝업(cupang/index.html).
|
||||
- 날짜 칸: 프로젝트 화면의 날짜 팝업(window.PJLib.enhanceDateInput)을 그대로 쓴다.
|
||||
- 입고센터: 출고리스트 구글 시트에 적힌 센터 + 설정에 등록된 센터(GET /cupang/api/outbound-sheet/centers).
|
||||
- 입고센터: 출고리스트 엑셀(구글 드라이브 .xlsx)에 적힌 센터 + 설정에 등록된 센터(GET /cupang/api/outbound-sheet/centers).
|
||||
- 제품: 코드표(itemcode_db) 전체 목록(GET /cupang/api/products/all)에서 코드·이름으로 찾아 추가.
|
||||
- [완료] → POST /cupang/api/outbound-sheet → 출고일 시트(YYYYMMDD(요일)) 맨 아래에 덧붙임. */
|
||||
(function () {
|
||||
@@ -57,7 +57,7 @@
|
||||
|
||||
function updateTarget() {
|
||||
target.textContent = shipDate.value
|
||||
? "완료하면 구글 시트 '" + sheetTitle(shipDate.value) + "' 시트 맨 아래에 추가합니다. (시트가 없으면 양식째 새로 만듭니다)"
|
||||
? "완료하면 출고리스트 엑셀 '" + sheetTitle(shipDate.value) + "' 시트 맨 아래에 추가합니다. (시트가 없으면 양식째 새로 만듭니다)"
|
||||
: "출고일을 고르면 그 날짜 시트(YYYYMMDD(요일))에 추가합니다.";
|
||||
}
|
||||
|
||||
@@ -290,7 +290,7 @@
|
||||
})
|
||||
.then(function (res) {
|
||||
return res.json().catch(function () { return {}; }).then(function (data) {
|
||||
if (!res.ok) throw new Error(typeof data.detail === "string" ? data.detail : "구글 시트에 기록하지 못했습니다.");
|
||||
if (!res.ok) throw new Error(typeof data.detail === "string" ? data.detail : "출고리스트 파일에 기록하지 못했습니다.");
|
||||
return data;
|
||||
});
|
||||
})
|
||||
@@ -300,7 +300,7 @@
|
||||
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: "닫기" })
|
||||
window.erpConfirm(msg + "\n출고리스트 엑셀을 열어 볼까요?", { tone: "ok", okText: "파일 열기", cancelText: "닫기" })
|
||||
.then(function (ok) { if (ok) window.open(data.url, "_blank", "noopener"); });
|
||||
} else {
|
||||
window.alert(msg);
|
||||
|
||||
@@ -536,6 +536,7 @@ docker compose down # 컨테이너 제거 (볼륨 유지)
|
||||
| `*_DB_HOST`, `*_DB_USER`, `*_DB_PASSWORD`, `*_DB_NAME` | 각 PostgreSQL DB 접속 정보 |
|
||||
| `EXPENSE_DB_URL` | 개인경비 DB DSN (예: `postgresql://expense_app:<pwd>@postgres-db:5432/expense_db`). 미설정 시 JSON 폴백 |
|
||||
| `CUPANG_DB_URL` | 쿠팡 밀크런 DB DSN (예: `postgresql://cupang_app:<pwd>@postgres-db:5432/cupang_db`). **필수** — 미설정 시 모듈 비활성(설정 필요 안내) |
|
||||
| `CUPANG_SHEET_ID` | 쿠팡 밀크런 출고리스트 문서 — 구글 드라이브의 .xlsx 파일 id(기본 `1J74op7lBZOgE27p4R28I3RWsv0EtXdii`) 또는 구글 시트 id. .xlsx 는 Drive 권한 인증(서비스 계정 또는 `GOOGLE_SLIDES_OAUTH_REFRESH_TOKEN`) 필요 |
|
||||
| `VACATION_DB_URL` | 휴가 관리 DB DSN (예: `postgresql://vacation_app:<pwd>@postgres-db:5432/vacation_db`). **필수** — 미설정 시 모듈 비활성(설정 필요 안내). 권한키 `vacation`/`vacation_approver` |
|
||||
| `ITEMCODE_DB_URL` | 상품 검색용 itemcode_db 읽기 전용 DSN. 미설정 시 검색 비활성(수동 입력). 테이블/컬럼은 `ITEMCODE_TABLE`/`ITEMCODE_CODE_COL`/`ITEMCODE_NAME_COL`/`ITEMCODE_TYPE_COL` 또는 `ITEMCODE_SEARCH_SQL` 로 지정 |
|
||||
| `DATA_DIR` | 영구 데이터 경로 (Docker 볼륨 마운트). 첨부파일은 `$DATA_DIR/uploads/expense/{item_id}/` 에 저장 |
|
||||
|
||||
@@ -37,7 +37,7 @@ const server = http.createServer(function (req, res) {
|
||||
req.on("end", function () {
|
||||
const body = JSON.parse(raw);
|
||||
posts.push(body);
|
||||
if (body.center === "실패센터") return json(res, 502, { detail: "구글 시트에 기록하지 못했습니다(HttpError). 잠시 후 다시 시도해 주세요." });
|
||||
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 });
|
||||
});
|
||||
@@ -156,7 +156,7 @@ async function pickDate(page, inputId, typed) {
|
||||
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.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, "택배");
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
"""쿠팡 밀크런 — 밀크런 출고리스트 직접 작성(팝업 → 구글 시트 출고일 시트 맨 아래에 덧붙임).
|
||||
"""쿠팡 밀크런 — 밀크런 출고리스트 직접 작성(팝업 → 출고리스트 문서의 출고일 시트 맨 아래에 덧붙임).
|
||||
|
||||
구글은 쓰지 않는다: 시트 쓰기는 가짜 writer/가짜 Sheets 서비스로 요청 모양만 확인하고,
|
||||
화면·API 는 격리된 하위 프로세스의 실제 앱(가짜 cupang store, CUPANG_SHEET_ID 미설정)으로 확인한다.
|
||||
드라이브 엑셀(.xlsx) 파일은 가짜 Drive 서비스에 진짜 xlsx 바이트를 두고 내려받기→고치기→올리기를 확인한다.
|
||||
화면·API 는 격리된 하위 프로세스의 실제 앱(가짜 cupang store, Google 인증 없음)으로 확인한다.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -18,6 +19,8 @@ from typing import Any
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
|
||||
from app.integrations import drive_xlsx
|
||||
from app.integrations.drive_xlsx import DriveXlsxWriter, XlsxChangedError
|
||||
from app.integrations.google_sheets import GoogleSheetsWriter, a1_sheet, col_letter
|
||||
from app.modules.cupang.export import PALLET_BG, WORKER, build_block, build_table
|
||||
|
||||
@@ -245,6 +248,150 @@ def test_a1_helpers():
|
||||
assert a1_sheet("20261026(월)") == "'20261026(월)'" and a1_sheet("a'b") == "'a''b'"
|
||||
|
||||
|
||||
# ── 드라이브 엑셀(.xlsx) 파일 ────────────────────────────────
|
||||
class FakeDrive:
|
||||
"""files().get(mimeType/version) · get_media(xlsx 바이트) · update(새 내용)만 흉내."""
|
||||
|
||||
def __init__(self, data: bytes, mime: str = drive_xlsx.XLSX_MIME):
|
||||
self.data, self.mime, self.version = data, mime, 1
|
||||
self.uploads = 0
|
||||
self.bump_on_meta: int | None = None # n번째 메타 조회 때 남이 고친 것처럼 version 을 올림
|
||||
self.always_bump = False
|
||||
self.meta_calls = 0
|
||||
|
||||
def files(self):
|
||||
return self
|
||||
|
||||
def get(self, **kw):
|
||||
self.meta_calls += 1
|
||||
if self.always_bump or self.bump_on_meta == self.meta_calls:
|
||||
self.version += 1
|
||||
return _Exec({"mimeType": self.mime, "version": str(self.version)})
|
||||
|
||||
def get_media(self, **kw):
|
||||
return _Exec(self.data)
|
||||
|
||||
def update(self, **kw):
|
||||
self.data = kw["media_body"]._fd.getvalue()
|
||||
self.version += 1
|
||||
self.uploads += 1
|
||||
return _Exec({"id": kw["fileId"]})
|
||||
|
||||
|
||||
def _xlsx_writer(drive: FakeDrive) -> DriveXlsxWriter:
|
||||
w = DriveXlsxWriter.__new__(DriveXlsxWriter)
|
||||
w.enabled, w.reason, w.auth_mode, w._creds = True, "", "test", None
|
||||
w._depth, w._book = 0, None
|
||||
w._service = lambda: drive
|
||||
return w
|
||||
|
||||
|
||||
def _xlsx_bytes(sheets: dict[str, list[list[Any]]]) -> bytes:
|
||||
from io import BytesIO
|
||||
|
||||
from openpyxl import Workbook
|
||||
|
||||
wb = Workbook()
|
||||
wb.remove(wb.active)
|
||||
for title, rows in sheets.items():
|
||||
ws = wb.create_sheet(title)
|
||||
for r, row in enumerate(rows, start=1):
|
||||
for c, v in enumerate(row, start=1):
|
||||
if v != "":
|
||||
ws.cell(row=r, column=c, value=int(v) if c == 2 and str(v).isdigit() else v)
|
||||
out = BytesIO()
|
||||
wb.save(out)
|
||||
return out.getvalue()
|
||||
|
||||
|
||||
def _load(drive: FakeDrive):
|
||||
from io import BytesIO
|
||||
|
||||
from openpyxl import load_workbook
|
||||
|
||||
return load_workbook(BytesIO(drive.data))
|
||||
|
||||
|
||||
def _append(writer: DriveXlsxWriter, entry: dict[str, Any]) -> dict[str, Any]:
|
||||
return cupang_router._in_sheet(writer, lambda: cupang_router._append_outbound_entry(writer, "f", entry))
|
||||
|
||||
|
||||
def test_xlsx_append_below_existing_rows_and_upload_once():
|
||||
drive = FakeDrive(_xlsx_bytes({"20261023(금)": _sheet_rows(9), "20261026(월)": _sheet_rows(4)}))
|
||||
res = _append(_xlsx_writer(drive), cupang_router._clean_outbound_entry(_payload(center="=인천32")))
|
||||
assert (res["first_row"], res["last_row"]) == (10, 11) and drive.uploads == 1
|
||||
assert res["url"] == "https://docs.google.com/spreadsheets/d/f/edit"
|
||||
ws = _load(drive)["20261026(월)"]
|
||||
assert ws["B10"].value == 5 and ws["B11"].value == 6
|
||||
assert ws["H10"].value == "MT-7000" and ws["J10"].value == 1200
|
||||
assert ws["F10"].value == "=인천32" and ws["F10"].data_type == "s" # 수식이 아니라 글자
|
||||
assert "F10:F11" in {str(m) for m in ws.merged_cells.ranges}
|
||||
assert ws["B11"].fill.fgColor.rgb.endswith(PALLET_BG) and ws["B11"].border.left.style == "thin"
|
||||
assert ws["I10"].alignment.horizontal == "left"
|
||||
assert _load(drive)["20261023(금)"]["B14"].value == 9 # 다른 날짜 시트는 그대로
|
||||
|
||||
|
||||
def test_xlsx_missing_sheet_gets_full_template_and_centers():
|
||||
drive = FakeDrive(_xlsx_bytes({"20261023(금)": _sheet_rows(2)}))
|
||||
writer = _xlsx_writer(drive)
|
||||
res = _append(writer, cupang_router._clean_outbound_entry(_payload(ship_method="택배")))
|
||||
assert (res["first_row"], res["last_row"]) == (6, 7) and drive.uploads == 1
|
||||
wb = _load(drive)
|
||||
assert wb.sheetnames == ["20261023(금)", "20261026(월)"]
|
||||
ws = wb["20261026(월)"]
|
||||
assert ws["B5"].value == "구분" and ws["B6"].value == 1 and ws["F6"].value == "인천32"
|
||||
assert ws["B2"].value.startswith("20261026(월)") and ws["B5"].font.b
|
||||
cupang_router._sheet_centers_cache.update(at=0.0, sheet="", names=[])
|
||||
assert cupang_router._sheet_centers(writer, "f") == ["대구3", "인천32"]
|
||||
assert drive.uploads == 1 # 읽기만 하면 올리지 않는다
|
||||
|
||||
|
||||
def test_xlsx_conflict_retries_then_gives_up():
|
||||
entry = cupang_router._clean_outbound_entry(_payload())
|
||||
drive = FakeDrive(_xlsx_bytes({"20261026(월)": _sheet_rows(1)}))
|
||||
drive.bump_on_meta = 2 # 첫 시도: 내려받은 뒤 올리기 전에 남이 고침 → 다시 내려받아 성공
|
||||
res = _append(_xlsx_writer(drive), entry)
|
||||
assert res["first_row"] == 7 and drive.uploads == 1
|
||||
assert _load(drive)["20261026(월)"]["B7"].value == 2
|
||||
|
||||
busy = FakeDrive(_xlsx_bytes({"20261026(월)": _sheet_rows(1)}))
|
||||
busy.always_bump = True
|
||||
writer = _xlsx_writer(busy)
|
||||
with pytest.raises(XlsxChangedError):
|
||||
_append(writer, entry)
|
||||
assert busy.uploads == 0 and writer._depth == 0 and writer._book is None
|
||||
|
||||
|
||||
def test_xlsx_delete_sheet():
|
||||
drive = FakeDrive(_xlsx_bytes({"a": [["x"]], "20261026(월)": _sheet_rows(3)}))
|
||||
writer = _xlsx_writer(drive)
|
||||
assert writer.delete_sheet(spreadsheet_id="f", title="없음")["action"] == "missing"
|
||||
assert drive.uploads == 0
|
||||
assert writer.delete_sheet(spreadsheet_id="f", title="20261026(월)")["action"] == "deleted"
|
||||
assert _load(drive).sheetnames == ["a"]
|
||||
assert writer.delete_sheet(spreadsheet_id="f", title="a")["action"] == "cleared"
|
||||
assert _load(drive).sheetnames == ["a"] and _load(drive)["a"]["A1"].value is None
|
||||
|
||||
|
||||
def test_xlsx_read_ranges_like_sheets_api():
|
||||
drive = FakeDrive(_xlsx_bytes({"s'1": [["", "1", "x", ""], [], ["", "2.5"]]}))
|
||||
got = _xlsx_writer(drive).read_ranges(spreadsheet_id="f", ranges=["'s''1'!A1:L", "'s''1'!B3:B", "'없음'!A1"])
|
||||
assert got == [[["", "1", "x"], [], ["", "2.5"]], [["2.5"]], []]
|
||||
|
||||
|
||||
def test_sheet_target_picks_writer_by_drive_file_type(monkeypatch):
|
||||
drive = FakeDrive(b"")
|
||||
writer = _xlsx_writer(drive)
|
||||
monkeypatch.setattr(drive_xlsx, "get_writer", lambda: writer)
|
||||
monkeypatch.setattr(drive_xlsx, "_KIND_CACHE", {})
|
||||
monkeypatch.delenv("CUPANG_SHEET_ID", raising=False)
|
||||
got, file_id, skip = cupang_router._sheet_target(None)
|
||||
assert got is writer and file_id == cupang_router.DEFAULT_SHEET_ID and skip is None
|
||||
drive.mime = "application/pdf"
|
||||
monkeypatch.setattr(drive_xlsx, "_KIND_CACHE", {})
|
||||
assert cupang_router._sheet_target(None)[2]["skipped"] is True
|
||||
|
||||
|
||||
# ── 실제 앱(하위 프로세스) — 버튼·팝업·API ──────────────────
|
||||
APP_CODE = '''
|
||||
from unittest.mock import patch
|
||||
@@ -270,13 +417,13 @@ with patch.object(main, "get_current_user_record", side_effect=lambda r: user),
|
||||
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"]
|
||||
assert r["centers"] == ["대구3", "이천1"] and "미설정" in r["reason"], r
|
||||
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 r.status_code == 503 and "출고리스트 파일에 쓸 수 없습니다" 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
|
||||
@@ -290,6 +437,9 @@ class OutboundSheetAppTests(unittest.TestCase):
|
||||
for key in ("ASSET", "CAFE24", "CUPANG", "VACATION", "PROJECT", "DISPATCH", "PERFORMANCE",
|
||||
"MALAYSIA_STOCK", "ITEMCODE", "EXPENSE", "INOUT"):
|
||||
env[key + "_DB_URL"] = ""
|
||||
for key in ("GOOGLE_SHEETS_CREDENTIALS", "GOOGLE_SHEETS_CREDENTIALS_JSON",
|
||||
"GOOGLE_SHEETS_OAUTH_REFRESH_TOKEN", "GOOGLE_SLIDES_OAUTH_REFRESH_TOKEN"):
|
||||
env[key] = ""
|
||||
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:
|
||||
|
||||
Reference in New Issue
Block a user