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:
@@ -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");
|
||||
|
||||
Reference in New Issue
Block a user