fix(cupang): 출고리스트 작성 팝업은 항상 드라이브 엑셀 파일에만 기록
- 서버 CUPANG_SHEET_ID 가 구글 시트 문서이거나 드라이브 인증이 없으면 자동 판별이 구글 시트로 써서 팝업 내용이 계속 구글 시트에 들어갔다 - router._outbound_target: CUPANG_OUTBOUND_XLSX_ID(기본 1J74op7lBZOgE27p4R28I3RWsv0EtXdii)만 보고 항상 drive_xlsx. 인증이 없거나 .xlsx 가 아니면 구글 시트로 대신 쓰지 않고 503(사유 표시) - 입고센터 후보도 같은 엑셀 파일에서 읽음, 로그에 기록한 파일 id 남김 - [분배 확정]·출고 삭제 동기화(CUPANG_SHEET_ID)는 그대로 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -31,6 +31,8 @@ CUSTOMER_ORDER_LIST_URL=/orderlist/
|
||||
# - .xlsx 는 Drive 권한이 필요하다: 서비스 계정(GOOGLE_SHEETS_CREDENTIALS) 또는 GOOGLE_SLIDES_OAUTH_REFRESH_TOKEN
|
||||
# - 서비스 계정이면 이메일(client_email)에 해당 파일을 편집자로 공유해야 한다
|
||||
# CUPANG_SHEET_ID=1J74op7lBZOgE27p4R28I3RWsv0EtXdii
|
||||
# "밀크런 출고리스트 작성" 팝업 전용 — 드라이브 .xlsx 파일 id(기본값 = 아래 id, 엑셀만·구글 시트로 대신 쓰지 않음)
|
||||
# CUPANG_OUTBOUND_XLSX_ID=1J74op7lBZOgE27p4R28I3RWsv0EtXdii
|
||||
#
|
||||
# [방식 A] 사용자 OAuth 리프레시 토큰 — 조직 정책으로 서비스 계정 키를 못 만들 때
|
||||
# 토큰 발급: python scripts/google_sheets_authorize.py --client-id .. --client-secret ..
|
||||
|
||||
@@ -55,7 +55,10 @@
|
||||
## 밀크런 출고리스트 작성 (팝업 → 드라이브 엑셀 파일, 2026-10-23)
|
||||
|
||||
- 첫 화면 "+ 신규 등록" 옆 엑셀색(#217346) 버튼 → 팝업(`index.html` + `static/cupang-outbound.js`).
|
||||
상자 계산 없이 센터 1곳을 **출고리스트 엑셀 파일에만** 적는다(위 "출고리스트 문서 동기화") — cupang_db 출고 묶음은 만들지 않는다(달력에 안 보임).
|
||||
상자 계산 없이 센터 1곳을 **출고리스트 엑셀 파일에만** 적는다 — cupang_db 출고 묶음은 만들지 않는다(달력에 안 보임).
|
||||
- 대상 파일은 `router._outbound_target` — `CUPANG_OUTBOUND_XLSX_ID`(기본 `DEFAULT_OUTBOUND_XLSX_ID` = `1J74op7lBZOgE27p4R28I3RWsv0EtXdii`),
|
||||
항상 `drive_xlsx`. `CUPANG_SHEET_ID`(분배 확정 동기화)와 따로라 그게 구글 시트 문서여도 팝업은 엑셀에만 쓴다.
|
||||
드라이브 인증이 없거나 파일이 .xlsx 가 아니면 구글 시트로 대신 쓰지 않고 503(사유 표시).
|
||||
- 입력: 작성일(기본 오늘)·출고일·센터입고일(출고일 고르면 +1일 자동) — 날짜 칸은 프로젝트 날짜 팝업
|
||||
(`PJLib.enhanceDateInput`, project.js 를 `PJ_LIB_ONLY` 로 로드). 입고센터(시트 F열 + 등록 센터, 직접 입력 가능),
|
||||
출고방식(파렛트/택배), 제품(코드표 `GET /cupang/api/products/all` 검색 → 코드·이름 자동, 수량 수기), 출고(수기), 작업자(기본 `export.WORKER`).
|
||||
|
||||
@@ -386,6 +386,28 @@ def _write_full_sheet(
|
||||
OUTBOUND_SHEET_METHODS: tuple[str, ...] = ("파렛트", "택배")
|
||||
_SHEET_CENTERS_TTL_SECONDS = 600
|
||||
_sheet_centers_cache: dict[str, Any] = {"at": 0.0, "sheet": "", "names": []}
|
||||
# 팝업이 쓰는 문서 — 항상 드라이브 엑셀(.xlsx) 파일. CUPANG_SHEET_ID(분배 확정 동기화)와 따로 둔다:
|
||||
# 서버의 CUPANG_SHEET_ID 가 구글 시트 문서를 가리켜도 팝업은 엑셀 파일에만 쓴다(구글 시트로 대신 쓰지 않음).
|
||||
DEFAULT_OUTBOUND_XLSX_ID = "1J74op7lBZOgE27p4R28I3RWsv0EtXdii"
|
||||
|
||||
|
||||
def _outbound_target() -> tuple[Any, str, dict[str, Any] | None]:
|
||||
"""(drive_xlsx writer, 엑셀 파일 id, skip 사유). 드라이브 인증이 없거나 .xlsx 가 아니면 skip."""
|
||||
import os # noqa: WPS433
|
||||
|
||||
from app.integrations import drive_xlsx # noqa: WPS433
|
||||
|
||||
file_id = (os.getenv("CUPANG_OUTBOUND_XLSX_ID") or "").strip() or DEFAULT_OUTBOUND_XLSX_ID
|
||||
writer = drive_xlsx.get_writer()
|
||||
if not writer.enabled:
|
||||
return None, "", {"ok": False, "skipped": True, "reason": writer.reason}
|
||||
try:
|
||||
kind = writer.file_kind(file_id)
|
||||
except Exception as exc: # noqa: BLE001 - 사유만(비밀값 없음)
|
||||
return None, "", {"ok": False, "skipped": True, "reason": str(exc) or type(exc).__name__}
|
||||
if kind != "xlsx":
|
||||
return None, "", {"ok": False, "skipped": True, "reason": f"출고리스트 파일이 엑셀(.xlsx)이 아닙니다({kind})"}
|
||||
return writer, file_id, None
|
||||
|
||||
|
||||
def _sheet_text(value: Any, *, label: str, max_len: int, required: bool = True) -> str:
|
||||
@@ -517,14 +539,14 @@ def outbound_sheet_centers(
|
||||
store = _store(request)
|
||||
names = {c["name"] for c in store.list_centers()} if store else set()
|
||||
reason = ""
|
||||
writer, spreadsheet_id, skip = _sheet_target(store)
|
||||
writer, spreadsheet_id, skip = _outbound_target()
|
||||
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__})"
|
||||
reason = f"출고리스트 파일을 읽지 못했습니다({str(exc) or type(exc).__name__})"
|
||||
return JSONResponse({"centers": sorted(names), "reason": reason})
|
||||
|
||||
|
||||
@@ -535,10 +557,11 @@ def outbound_sheet_write(
|
||||
_: dict[str, Any] = Depends(_require_user),
|
||||
) -> JSONResponse:
|
||||
entry = _clean_outbound_entry(payload)
|
||||
writer, spreadsheet_id, skip = _sheet_target(_store(request))
|
||||
writer, spreadsheet_id, skip = _outbound_target()
|
||||
if skip:
|
||||
_log_sheet("manual-append", entry["ship_date"], 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
|
||||
@@ -557,7 +580,8 @@ def outbound_sheet_write(
|
||||
raise HTTPException(
|
||||
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')}"})
|
||||
_log_sheet("manual-append", entry["ship_date"],
|
||||
{"ok": True, "action": f"xlsx {spreadsheet_id} 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])
|
||||
|
||||
+2
-1
@@ -536,7 +536,8 @@ 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`) 필요 |
|
||||
| `CUPANG_SHEET_ID` | 쿠팡 밀크런 [분배 확정]·출고 삭제 동기화 문서 — 구글 드라이브의 .xlsx 파일 id(기본 `1J74op7lBZOgE27p4R28I3RWsv0EtXdii`) 또는 구글 시트 id(형식 자동 판별). .xlsx 는 Drive 권한 인증(서비스 계정 또는 `GOOGLE_SLIDES_OAUTH_REFRESH_TOKEN`) 필요 |
|
||||
| `CUPANG_OUTBOUND_XLSX_ID` | 쿠팡 "밀크런 출고리스트 작성" 팝업이 쓰는 드라이브 .xlsx 파일 id(기본 `1J74op7lBZOgE27p4R28I3RWsv0EtXdii`). 엑셀 파일만(구글 시트로 대신 쓰지 않음) |
|
||||
| `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}/` 에 저장 |
|
||||
|
||||
@@ -392,6 +392,27 @@ def test_sheet_target_picks_writer_by_drive_file_type(monkeypatch):
|
||||
assert cupang_router._sheet_target(None)[2]["skipped"] is True
|
||||
|
||||
|
||||
def test_outbound_popup_writes_only_to_drive_xlsx(monkeypatch):
|
||||
"""CUPANG_SHEET_ID 가 구글 시트 문서여도 팝업은 엑셀 파일(CUPANG_OUTBOUND_XLSX_ID)에만 쓴다."""
|
||||
drive = FakeDrive(b"")
|
||||
writer = _xlsx_writer(drive)
|
||||
monkeypatch.setattr(drive_xlsx, "get_writer", lambda: writer)
|
||||
monkeypatch.setattr(drive_xlsx, "_KIND_CACHE", {})
|
||||
monkeypatch.setenv("CUPANG_SHEET_ID", "google-sheet-doc")
|
||||
monkeypatch.delenv("CUPANG_OUTBOUND_XLSX_ID", raising=False)
|
||||
got, file_id, skip = cupang_router._outbound_target()
|
||||
assert got is writer and file_id == cupang_router.DEFAULT_OUTBOUND_XLSX_ID and skip is None
|
||||
|
||||
drive.mime = drive_xlsx.SHEETS_MIME # 엑셀이 아니면 구글 시트로 대신 쓰지 않고 멈춘다
|
||||
monkeypatch.setattr(drive_xlsx, "_KIND_CACHE", {})
|
||||
got, _, skip = cupang_router._outbound_target()
|
||||
assert got is None and "엑셀(.xlsx)이 아닙니다" in skip["reason"]
|
||||
|
||||
writer.enabled, writer.reason = False, "Google 인증 미설정"
|
||||
got, _, skip = cupang_router._outbound_target()
|
||||
assert got is None and skip["reason"] == "Google 인증 미설정"
|
||||
|
||||
|
||||
# ── 실제 앱(하위 프로세스) — 버튼·팝업·API ──────────────────
|
||||
APP_CODE = '''
|
||||
from unittest.mock import patch
|
||||
@@ -423,7 +444,7 @@ with patch.object(main, "get_current_user_record", side_effect=lambda r: user),
|
||||
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 "출고리스트 파일에 쓸 수 없습니다" 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
|
||||
@@ -441,7 +462,7 @@ class OutboundSheetAppTests(unittest.TestCase):
|
||||
"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="")
|
||||
PERFORMANCE_AUTO_SYNC="false", CUPANG_SHEET_ID="", PYTHONIOENCODING="utf-8")
|
||||
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,
|
||||
|
||||
Reference in New Issue
Block a user