Files
king 2f31604c4e 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>
2026-10-23 15:12:11 +09:00

346 lines
15 KiB
Python

"""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