b0e816cbdc
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
756 lines
40 KiB
Python
756 lines
40 KiB
Python
"""카페24 상품 정보 패널 — 오른쪽 칸 JSON API.
|
|
|
|
화면(products.html 의 `_side.html` 조각)이 fetch 로 부른다. 전부 `def`(동기) 핸들러.
|
|
|
|
POST /products/{no}/basic 상품명 · 판매가 · 공급가 · 소비자가
|
|
POST /products/{no}/image 대표 이미지 교체 (multipart 파일)
|
|
GET /products/{no}/options 옵션 + 품목 조회 (읽기 지연 보정 포함)
|
|
POST /products/{no}/options 옵션 생성 (옵션 없는 상품 — 품목 자동 생성)
|
|
PUT /products/{no}/options 옵션명 · 옵션값 이름/이미지/표시방식 수정
|
|
DELETE /products/{no}/options 옵션 삭제 (품목도 함께 삭제 — 확인 후)
|
|
POST /products/{no}/options/image 옵션값 썸네일 업로드만 (경로 반환)
|
|
PUT /products/{no}/variants 품목 자체코드 · 추가금액 · 진열 · 판매 (행별 결과)
|
|
|
|
공통 규칙
|
|
- 카페24 호출은 `app.integrations.cafe24` 만 통한다(httpx 직접 호출 금지).
|
|
- 쓰기는 상품별 DB 잠금(writes.write_lock) 안에서 한다 — 같은 상품을 웹 여러
|
|
프로세스·예약 worker 가 동시에 쓰지 않게. 못 잡으면 409.
|
|
- 쓰기 전에 현재값을 읽되, **읽기 지연을 보정한 유효 현재값**과 비교해 바뀐
|
|
것만 보낸다(routes_products.load_product). 이걸 안 하면 "A→B 로 바꾼 직후
|
|
다시 B→A" 가 카페24의 예전 값(A)과 같다고 판단돼 무시된다.
|
|
- PUT 응답이 곧 현재값이다. 응답을 스냅샷(`save_write_snapshot`)에 남기고 화면도
|
|
응답으로 그린다 — 다시 GET 하지 않는다(GET 은 한동안 예전 값을 돌려준다).
|
|
PUT 이 성공한 뒤의 기록 실패는 쓰기 실패로 알리지 않는다(재전송을 부르지 않게).
|
|
- 품목은 **품목코드**(안정 식별자)로 짝짓는다. 옵션값 이름을 바꾼 직후 GET 품목이
|
|
예전 이름을 돌려줘도 스냅샷의 품목코드별 표기로 바로잡는다(store.apply_variant_patch).
|
|
- 모든 쓰기는 감사로그(`cafe24_audit_logs`)에 남긴다.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
from typing import Any
|
|
|
|
from fastapi import APIRouter, Body, File, HTTPException, Request, UploadFile
|
|
|
|
from app.integrations.cafe24 import Cafe24Error, build_cafe24_api, products
|
|
from app.timezone import now_kst
|
|
|
|
from . import store, writes
|
|
from .common import read_lag_grace_minutes, require_store, shop_nos
|
|
from .routes_products import load_product, locked_json, remember_write
|
|
|
|
logger = logging.getLogger("cafe24.product_info")
|
|
|
|
product_info_router = APIRouter()
|
|
|
|
# 업로드 허용 이미지 형식 (카페24 상품 이미지 규격)
|
|
_IMAGE_TYPES = {"image/jpeg", "image/png", "image/gif", "image/webp"}
|
|
|
|
|
|
def _http_from_cafe24(exc: Cafe24Error) -> HTTPException:
|
|
return HTTPException(status_code=502, detail=str(exc))
|
|
|
|
|
|
def _read_image(upload: UploadFile) -> bytes:
|
|
"""업로드 파일 검증 + 바이트. 형식/크기 오류는 400."""
|
|
content_type = (upload.content_type or "").lower()
|
|
if content_type not in _IMAGE_TYPES:
|
|
raise HTTPException(status_code=400, detail="JPG·PNG·GIF·WEBP 이미지만 올릴 수 있습니다.")
|
|
data = upload.file.read(products.IMAGE_MAX_BYTES + 1)
|
|
if not data:
|
|
raise HTTPException(status_code=400, detail="빈 파일입니다.")
|
|
if len(data) > products.IMAGE_MAX_BYTES:
|
|
raise HTTPException(status_code=400, detail="이미지는 10MB 를 넘을 수 없습니다.")
|
|
return data
|
|
|
|
|
|
def _scalar_view(product: dict[str, Any]) -> dict[str, Any]:
|
|
"""화면이 바로 쓰는 스칼라 값들(PUT 응답 또는 보정된 GET 에서)."""
|
|
snap = store.product_snapshot(product)
|
|
return {
|
|
"product_name": snap.get("product_name", ""),
|
|
"price": snap.get("price", ""),
|
|
"supply_price": snap.get("supply_price", ""),
|
|
"retail_price": snap.get("retail_price", ""),
|
|
"display": products._flag(snap.get("display")), # noqa: SLF001 — 같은 규칙 재사용
|
|
"selling": products._flag(snap.get("selling")), # noqa: SLF001
|
|
"detail_image": snap.get("detail_image", ""),
|
|
"list_image": snap.get("list_image", ""),
|
|
"tiny_image": snap.get("tiny_image", ""),
|
|
"small_image": snap.get("small_image", ""),
|
|
"updated_date": snap.get("updated_date", ""),
|
|
}
|
|
|
|
|
|
# ════════════════════════════════════════════════════════════
|
|
# 기본 정보 — 상품명 · 가격
|
|
# ════════════════════════════════════════════════════════════
|
|
@product_info_router.post("/products/{product_no}/basic")
|
|
def product_basic(
|
|
request: Request,
|
|
product_no: int,
|
|
payload: dict[str, Any] = Body(default_factory=dict),
|
|
) -> dict[str, Any]:
|
|
st, user = require_store(request)
|
|
actor = str(user.get("email") or "")
|
|
|
|
want: dict[str, str] = {}
|
|
if "product_name" in payload:
|
|
name = str(payload.get("product_name") or "").strip()
|
|
if not name:
|
|
raise HTTPException(status_code=400, detail="상품명을 입력하세요.")
|
|
if len(name) > store.NAME_MAX:
|
|
raise HTTPException(status_code=400, detail=f"상품명은 {store.NAME_MAX}자를 넘을 수 없습니다.")
|
|
want["product_name"] = name
|
|
try:
|
|
for key, label in (("price", "판매가"), ("supply_price", "공급가"), ("retail_price", "소비자가")):
|
|
if key in payload:
|
|
parsed = store.parse_price(payload.get(key), field=label)
|
|
if parsed is not None:
|
|
want[key] = parsed
|
|
except ValueError as exc:
|
|
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
|
if not want:
|
|
raise HTTPException(status_code=400, detail="바꿀 항목이 없습니다.")
|
|
|
|
api = build_cafe24_api(st)
|
|
with locked_json(st, product_no, actor=actor, purpose="상품명·가격 변경"):
|
|
try:
|
|
current, _ = load_product(st, api, product_no)
|
|
except Cafe24Error as exc:
|
|
writes.audit_safe(st, actor=actor, action="update_basic", product_no=product_no,
|
|
result="FAIL", detail=f"현재값 조회 실패: {exc}")
|
|
raise _http_from_cafe24(exc) from exc
|
|
if not current:
|
|
raise HTTPException(status_code=404, detail="카페24에서 상품을 찾지 못했습니다.")
|
|
|
|
changes: dict[str, str] = {}
|
|
before: dict[str, str] = {}
|
|
for key, value in want.items():
|
|
old = str(current.get(key) or "")
|
|
same = old == value if key == "product_name" else store.price_equal(old, value)
|
|
if not same:
|
|
changes[key] = value
|
|
before[key] = old
|
|
if not changes:
|
|
return {"ok": True, "changed": [], "product": _scalar_view(current)}
|
|
|
|
try:
|
|
updated = products.update_product(api.client, product_no, **changes)
|
|
except Cafe24Error as exc:
|
|
writes.audit_safe(st, actor=actor, action="update_basic", product_no=product_no,
|
|
result="FAIL", detail=f"{changes} 실패: {exc}")
|
|
logger.warning("카페24 상품 %s 기본정보 변경 실패: %s", product_no, exc)
|
|
raise _http_from_cafe24(exc) from exc
|
|
|
|
remember_write(st, product_no, updated if isinstance(updated, dict) else {})
|
|
shifted = (_keep_variant_sale_prices(st, api, product_no, before["price"], changes["price"])
|
|
if "price" in changes else {})
|
|
merged = {**current, **(updated if isinstance(updated, dict) else {}), **changes}
|
|
detail = ", ".join(f"{k}: '{before[k]}' → '{v}'" for k, v in changes.items())
|
|
if shifted.get("detail"):
|
|
detail += f" / 품목 추가금액 조정: {shifted['detail']}"
|
|
writes.audit_safe(st, actor=actor, action="update_basic", product_no=product_no,
|
|
result="SUCCESS", detail=detail)
|
|
logger.info("카페24 상품 %s 기본정보 변경 (%s): %s", product_no, actor, detail)
|
|
return {"ok": True, "changed": list(changes.keys()), "product": _scalar_view(merged),
|
|
"variants_shifted": shifted.get("count", 0), "variants_error": shifted.get("error", "")}
|
|
|
|
|
|
def _keep_variant_sale_prices(st: Any, api: Any, product_no: int, old_price: str, new_price: str) -> dict[str, Any]:
|
|
"""판매가가 바뀐 뒤 품목 판매 가격(판매가 + 추가금액)이 그대로이도록 추가금액을 옮긴다.
|
|
|
|
판매가는 이미 반영됐으므로 실패해도 예외를 올리지 않고 {"error": …} 로 알린다.
|
|
반환 {"count": 반영된 품목 수, "error": 사유, "detail": 감사 로그용}.
|
|
"""
|
|
try:
|
|
variants = _load_options_and_variants(st, api, product_no)["effective_variants"]
|
|
requests = store.build_variant_updates(store.shift_additional_amounts(variants, old_price, new_price))
|
|
except (Cafe24Error, ValueError) as exc:
|
|
logger.warning("카페24 상품 %s 품목 추가금액 조정 준비 실패: %s", product_no, exc)
|
|
return {"error": f"품목 추가금액 조정 실패: {exc}", "detail": f"실패 {exc}"}
|
|
if not requests:
|
|
return {}
|
|
results = products.update_variants(api.client, product_no, requests)
|
|
sent = {r["variant_code"]: r["additional_amount"] for r in requests}
|
|
ok = {r["variant_code"]: sent[r["variant_code"]] for r in results if r["status"] == products.VARIANT_OK}
|
|
bad = [r for r in results if r["status"] != products.VARIANT_OK]
|
|
if ok:
|
|
_save_snapshot_safe(st, product_no, "variants", {c: {"additional_amount": a} for c, a in ok.items()})
|
|
detail = "; ".join(f"{c}={a}" for c, a in ok.items())
|
|
error = ""
|
|
if bad:
|
|
error = f"품목 {len(bad)}건 추가금액 조정 실패 — {bad[0]['error']} (옵션/품목 창에서 확인하세요)"
|
|
detail += f" / 실패 {len(bad)}건: {bad[0]['error']}"
|
|
logger.warning("카페24 상품 %s 품목 추가금액 조정 %s건 실패: %s", product_no, len(bad), bad[0]["error"])
|
|
return {"count": len(ok), "error": error, "detail": detail}
|
|
|
|
|
|
# ════════════════════════════════════════════════════════════
|
|
# 대표 이미지
|
|
# ════════════════════════════════════════════════════════════
|
|
@product_info_router.post("/products/{product_no}/image")
|
|
def product_image(
|
|
request: Request,
|
|
product_no: int,
|
|
file: UploadFile = File(...),
|
|
) -> dict[str, Any]:
|
|
"""대표 이미지 교체 — POST /products/{no}/images (A 타입, base64 직접 등록).
|
|
|
|
A(대표이미지등록) 타입이면 목록/작은목록/축소 이미지는 카페24가 리사이징한다.
|
|
응답의 새 경로 4개로 화면을 그리고 스냅샷에 남긴다(GET 은 한동안 예전 이미지).
|
|
이 응답엔 updated_date 가 없어 스냅샷 시각은 지금으로 둔다 — 그보다 이전 레코드를
|
|
돌려주는 GET 은 지연으로 보고 새 이미지를 덮어씌운다(store.overlay_recent_write).
|
|
이전 이미지 경로는 감사로그에 남긴다.
|
|
"""
|
|
st, user = require_store(request)
|
|
actor = str(user.get("email") or "")
|
|
data = _read_image(file)
|
|
|
|
api = build_cafe24_api(st)
|
|
with locked_json(st, product_no, actor=actor, purpose="대표 이미지 교체"):
|
|
try:
|
|
current, _ = load_product(st, api, product_no)
|
|
except Cafe24Error as exc:
|
|
raise _http_from_cafe24(exc) from exc
|
|
if not current:
|
|
raise HTTPException(status_code=404, detail="카페24에서 상품을 찾지 못했습니다.")
|
|
before = str(current.get("detail_image") or "")
|
|
|
|
try:
|
|
images = products.set_main_image(
|
|
api.client, product_no, data, content_type=(file.content_type or "").lower()
|
|
)
|
|
if not images.get("detail_image"):
|
|
raise Cafe24Error("카페24가 등록된 이미지 경로를 돌려주지 않았습니다.")
|
|
except Cafe24Error as exc:
|
|
writes.audit_safe(st, actor=actor, action="set_main_image", product_no=product_no,
|
|
result="FAIL", detail=f"등록 실패: {exc}")
|
|
logger.warning("카페24 상품 %s 대표이미지 변경 실패: %s", product_no, exc)
|
|
raise _http_from_cafe24(exc) from exc
|
|
|
|
merged = {**current, **images, "updated_date": now_kst().isoformat(timespec="seconds")}
|
|
remember_write(st, product_no, merged)
|
|
writes.audit_safe(st, actor=actor, action="set_main_image", product_no=product_no,
|
|
result="SUCCESS", detail=f"'{before}' → '{images['detail_image']}'")
|
|
logger.info("카페24 상품 %s 대표이미지 변경 (%s)", product_no, actor)
|
|
return {"ok": True, "product": _scalar_view(merged)}
|
|
|
|
|
|
# ════════════════════════════════════════════════════════════
|
|
# 옵션 · 품목
|
|
# ════════════════════════════════════════════════════════════
|
|
def _variant_view(v: dict[str, Any]) -> dict[str, Any]:
|
|
opts = v.get("options") if isinstance(v.get("options"), list) else []
|
|
return {
|
|
"variant_code": str(v.get("variant_code") or ""),
|
|
"options": [
|
|
{"name": str(o.get("name") or ""), "value": str(o.get("value") or "")}
|
|
for o in opts if isinstance(o, dict)
|
|
],
|
|
# 첫 옵션의 옵션값 번호(value_no) — 화면이 이름보다 먼저 이것으로 옵션값과 짝짓는다.
|
|
"value_no": v.get("value_no"),
|
|
"custom_variant_code": str(v.get("custom_variant_code") or ""),
|
|
"additional_amount": str(v.get("additional_amount") or "0.00"),
|
|
"display": products._flag(v.get("display")), # noqa: SLF001
|
|
"selling": products._flag(v.get("selling")), # noqa: SLF001
|
|
"quantity": v.get("quantity"),
|
|
"use_inventory": products._flag(v.get("use_inventory"), default=False), # noqa: SLF001
|
|
"display_soldout": products._flag(v.get("display_soldout"), default=False), # noqa: SLF001
|
|
"image": str(v.get("image") or ""),
|
|
}
|
|
|
|
|
|
def _options_view(option: dict[str, Any]) -> dict[str, Any]:
|
|
raw_options = option.get("options") if isinstance(option.get("options"), list) else []
|
|
out_options = []
|
|
for o in raw_options:
|
|
if not isinstance(o, dict):
|
|
continue
|
|
values = o.get("option_value") if isinstance(o.get("option_value"), list) else []
|
|
out_options.append(
|
|
{
|
|
"option_code": str(o.get("option_code") or ""),
|
|
"option_name": str(o.get("option_name") or ""),
|
|
"option_display_type": str(o.get("option_display_type") or "S"),
|
|
"required_option": str(o.get("required_option") or "T"),
|
|
"option_value": [
|
|
{
|
|
"option_text": str(v.get("option_text") or ""),
|
|
"option_image_file": str(v.get("option_image_file") or ""),
|
|
"option_link_image": str(v.get("option_link_image") or ""),
|
|
"option_color": str(v.get("option_color") or ""),
|
|
"value_no": v.get("value_no"),
|
|
"pending": bool(v.get("pending")),
|
|
}
|
|
for v in values if isinstance(v, dict)
|
|
],
|
|
}
|
|
)
|
|
return {
|
|
"has_option": products._flag(option.get("has_option"), default=False), # noqa: SLF001
|
|
"option_type": str(option.get("option_type") or ""),
|
|
"option_list_type": str(option.get("option_list_type") or ""),
|
|
"option_preset_code": str(option.get("option_preset_code") or ""),
|
|
"options": out_options,
|
|
}
|
|
|
|
|
|
def _snapshot_sections(st: Any, product_no: int) -> tuple[dict[str, Any], dict[str, Any]]:
|
|
"""(옵션 섹션, 품목 섹션) — 각각 {"data":…, "written_at":…} 또는 {}."""
|
|
snap = st.get_write_snapshot(product_no) or {}
|
|
return snap.get("options") or {}, snap.get("variants") or {}
|
|
|
|
|
|
def _within(written_at: object) -> bool:
|
|
return store.within_grace(written_at, grace_minutes=read_lag_grace_minutes())
|
|
|
|
|
|
def _patch_variants(section: dict[str, Any], variants: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
|
"""GET 품목 목록에 품목코드별 쓰기 기록을 덮어씌운다(삭제한 품목은 뺀다)."""
|
|
data = section.get("data") or {}
|
|
if not isinstance(data, dict) or not data:
|
|
return list(variants)
|
|
out = []
|
|
for v in variants:
|
|
patched = store.apply_variant_patch(
|
|
v, data.get(str(v.get("variant_code") or "")),
|
|
section_written_at=section.get("written_at"), grace_minutes=read_lag_grace_minutes(),
|
|
)
|
|
if patched is not None:
|
|
out.append(patched)
|
|
return out
|
|
|
|
|
|
def _annotate(option: dict[str, Any], variants: list[dict[str, Any]], recent: list[str]) -> tuple[dict, list]:
|
|
"""옵션 1개 상품: 품목에 첫 옵션값 번호(value_no)를, 품목이 아직 안 보이는 최근 추가
|
|
옵션값에 pending 표시를 붙인다(화면이 "품목 없는 옵션값"으로 오해하지 않게)."""
|
|
groups = option.get("options") if isinstance(option.get("options"), list) else []
|
|
if len(groups) != 1 or not isinstance(groups[0], dict):
|
|
return option, variants
|
|
values = [v for v in (groups[0].get("option_value") or []) if isinstance(v, dict)]
|
|
by_text = {str(v.get("option_text") or ""): v.get("value_no") for v in values}
|
|
used: set[str] = set()
|
|
out_variants = []
|
|
for v in variants:
|
|
opts = v.get("options") if isinstance(v.get("options"), list) else []
|
|
first = str(opts[0].get("value") or "") if opts and isinstance(opts[0], dict) else ""
|
|
used.add(first)
|
|
out_variants.append({**v, "value_no": by_text.get(first)} if first in by_text else v)
|
|
recent_set = set(recent or [])
|
|
new_values = [
|
|
{**v, "pending": True} if str(v.get("option_text") or "") in recent_set
|
|
and str(v.get("option_text") or "") not in used else v
|
|
for v in values
|
|
]
|
|
return {**option, "options": [{**groups[0], "option_value": new_values}]}, out_variants
|
|
|
|
|
|
def _load_options_and_variants(st: Any, api: Any, product_no: int) -> dict[str, Any]:
|
|
raw_option = products.get_options(api.client, product_no)
|
|
osec, vsec = _snapshot_sections(st, product_no)
|
|
option, _stale = store.overlay_options(
|
|
raw_option, snapshot=osec.get("data"), written_at=osec.get("written_at"),
|
|
grace_minutes=read_lag_grace_minutes(),
|
|
)
|
|
raw_variants: list[dict[str, Any]] = []
|
|
variants: list[dict[str, Any]] = []
|
|
if products._flag(option.get("has_option"), default=False): # noqa: SLF001
|
|
raw_variants = products.list_variants(api.client, product_no)
|
|
variants = _patch_variants(vsec, raw_variants)
|
|
recent = _recent_values(osec)
|
|
shown_option, shown_variants = _annotate(option, variants, recent)
|
|
return {
|
|
"option": _options_view(shown_option),
|
|
"variants": [_variant_view(v) for v in shown_variants],
|
|
"raw_option": raw_option,
|
|
"effective_option": option,
|
|
"raw_variants": raw_variants,
|
|
"effective_variants": variants,
|
|
"options_section": osec,
|
|
"variants_section": vsec,
|
|
}
|
|
|
|
|
|
def _recent_values(osec: dict[str, Any]) -> list[str]:
|
|
data = osec.get("data") if isinstance(osec.get("data"), dict) else {}
|
|
if not data or not _within(osec.get("written_at")):
|
|
return []
|
|
return [str(v) for v in (data.get("_recent_values") or [])]
|
|
|
|
|
|
def _prior_signatures(osec: dict[str, Any]) -> list[str]:
|
|
data = osec.get("data") if isinstance(osec.get("data"), dict) else {}
|
|
if not data or not _within(osec.get("written_at")):
|
|
return []
|
|
return [str(s) for s in (data.get("_before_signatures") or []) if isinstance(s, str)]
|
|
|
|
|
|
def _unique(items: list[Any]) -> list[Any]:
|
|
out: list[Any] = []
|
|
for item in items:
|
|
if item not in out:
|
|
out.append(item)
|
|
return out
|
|
|
|
|
|
def _options_snapshot(
|
|
written: dict[str, Any], *, befores: list[dict[str, Any]], osec: dict[str, Any], recent: list[str]
|
|
) -> dict[str, Any]:
|
|
"""옵션 스냅샷 = 카페24 응답 + 쓰기 직전 모양들의 서명 + 최근 추가한 옵션값."""
|
|
signatures = _unique(_prior_signatures(osec) + [store.options_signature(b) for b in befores if b])
|
|
texts = {
|
|
str(v.get("option_text") or "")
|
|
for o in (written.get("options") or []) if isinstance(o, dict)
|
|
for v in (o.get("option_value") or []) if isinstance(v, dict)
|
|
}
|
|
keep = [t for t in _unique(_recent_values(osec) + list(recent)) if t in texts]
|
|
return {**written, "_before_signatures": signatures, "_recent_values": keep}
|
|
|
|
|
|
def _save_snapshot_safe(st: Any, product_no: int, section: str, data: Any, **kw: Any) -> str:
|
|
try:
|
|
st.save_write_snapshot(product_no, section, data, **kw)
|
|
except Exception as exc: # noqa: BLE001 — 카페24에는 이미 반영됐다
|
|
logger.exception("상품 %s %s 스냅샷 저장 실패", product_no, section)
|
|
return f"{type(exc).__name__}: {exc}"
|
|
return ""
|
|
|
|
|
|
@product_info_router.get("/products/{product_no}/options")
|
|
def options_get(request: Request, product_no: int) -> dict[str, Any]:
|
|
st, _user = require_store(request)
|
|
api = build_cafe24_api(st)
|
|
try:
|
|
loaded = _load_options_and_variants(st, api, product_no)
|
|
except Cafe24Error as exc:
|
|
raise _http_from_cafe24(exc) from exc
|
|
# image_base: 카페24가 "/web/product/…" 상대경로로 준 썸네일을 화면이 쇼핑몰 주소에
|
|
# 붙여 그리기 위한 값(그대로 src 에 넣으면 우리 도메인에서 찾다가 깨진다).
|
|
return {"ok": True, "option": loaded["option"], "variants": loaded["variants"],
|
|
"display_types": store.OPTION_DISPLAY_LABELS, "image_base": api.config.shop_base}
|
|
|
|
|
|
@product_info_router.post("/products/{product_no}/options")
|
|
def options_create(
|
|
request: Request,
|
|
product_no: int,
|
|
payload: dict[str, Any] = Body(default_factory=dict),
|
|
) -> dict[str, Any]:
|
|
"""옵션 없는 상품에 조합형 옵션 1개(옵션명 + 옵션값들)를 만든다. 품목은 자동 생성."""
|
|
st, user = require_store(request)
|
|
actor = str(user.get("email") or "")
|
|
try:
|
|
body = store.build_create_options_request(
|
|
str(payload.get("option_name") or ""),
|
|
store.parse_option_values(payload.get("values")),
|
|
display_type=str(payload.get("display_type") or "S"),
|
|
)
|
|
except ValueError as exc:
|
|
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
|
values = [v["option_text"] for v in body["options"][0]["option_value"]]
|
|
|
|
api = build_cafe24_api(st)
|
|
with locked_json(st, product_no, actor=actor, purpose="옵션 생성"):
|
|
try:
|
|
existing = products.get_options(api.client, product_no)
|
|
if products._flag(existing.get("has_option"), default=False): # noqa: SLF001
|
|
raise HTTPException(status_code=409, detail="이미 옵션이 있는 상품입니다. 수정하거나 삭제한 뒤 다시 만드세요.")
|
|
created = products.create_options(api.client, product_no, body)
|
|
except Cafe24Error as exc:
|
|
writes.audit_safe(st, actor=actor, action="create_options", product_no=product_no,
|
|
result="FAIL", detail=f"{body['options'][0]['option_name']} 실패: {exc}")
|
|
raise _http_from_cafe24(exc) from exc
|
|
|
|
osec, _vsec = _snapshot_sections(st, product_no)
|
|
record_error = _save_snapshot_safe(
|
|
st, product_no, "options",
|
|
_options_snapshot(created, befores=[existing], osec=osec, recent=values),
|
|
)
|
|
# 새 옵션의 품목은 새 품목코드다 — 이전 품목 기록은 모두 버린다(전체 초기화).
|
|
record_error = record_error or _save_snapshot_safe(st, product_no, "variants", {}, replace=True)
|
|
# 카페24가 자동 생성한 품목(코드 부여)을 바로 돌려준다 — 읽기 지연이 있어 짧게 재시도.
|
|
# 화면은 이 코드로 자체코드·추가금액을 이어서 PUT 한다. 다 안 보이면 pending 으로 표시.
|
|
variants = products.wait_for_variants(api.client, product_no, len(values))
|
|
writes.audit_safe(st, actor=actor, action="create_options", product_no=product_no, result="SUCCESS",
|
|
detail=f"옵션 '{body['options'][0]['option_name']}' 생성: {', '.join(values)}")
|
|
logger.info("카페24 상품 %s 옵션 생성 (%s)", product_no, actor)
|
|
if len(variants) < len(values):
|
|
logger.warning("카페24 상품 %s 옵션 생성 후 품목 %s/%s 건만 조회됨", product_no, len(variants), len(values))
|
|
shown_option, shown_variants = _annotate(created, variants, values)
|
|
return {"ok": True, "option": _options_view(shown_option),
|
|
"variants": [_variant_view(v) for v in shown_variants],
|
|
"missing_variants": max(0, len(values) - len(variants)),
|
|
"record_warning": record_error}
|
|
|
|
|
|
@product_info_router.put("/products/{product_no}/options")
|
|
def options_update(
|
|
request: Request,
|
|
product_no: int,
|
|
payload: dict[str, Any] = Body(default_factory=dict),
|
|
) -> dict[str, Any]:
|
|
"""옵션명 · 옵션값 이름/썸네일/연결이미지/색상 · 표시방식 수정.
|
|
|
|
카페24 PUT 은 `original_options`(수정 전)와 `options`(수정 후)를 짝지어 받는다.
|
|
수정 전 값은 화면이 들고 있던 것이 아니라 **지금 카페24에서 다시 읽은 값**(읽기
|
|
지연 보정 후)을 쓴다 — 그래야 다른 곳에서 바뀐 이름과 어긋나지 않는다.
|
|
이름을 바꾸면 품목코드별로 새 표기를 스냅샷에 남긴다(GET 품목이 예전 이름을
|
|
돌려주는 동안에도 품목이 옵션값과 제대로 짝지어 보이게).
|
|
"""
|
|
st, user = require_store(request)
|
|
actor = str(user.get("email") or "")
|
|
edited = payload.get("options")
|
|
if not isinstance(edited, list) or not edited:
|
|
raise HTTPException(status_code=400, detail="옵션 목록이 비어 있습니다.")
|
|
|
|
api = build_cafe24_api(st)
|
|
with locked_json(st, product_no, actor=actor, purpose="옵션 수정"):
|
|
try:
|
|
loaded = _load_options_and_variants(st, api, product_no)
|
|
except Cafe24Error as exc:
|
|
raise _http_from_cafe24(exc) from exc
|
|
if not loaded["option"]["has_option"]:
|
|
raise HTTPException(status_code=409, detail="옵션이 없는 상품입니다. 먼저 옵션을 만드세요.")
|
|
original = loaded["option"]["options"]
|
|
try:
|
|
body = store.build_update_options_request(
|
|
original, edited, option_list_type=str(payload.get("option_list_type") or ""),
|
|
)
|
|
except ValueError as exc:
|
|
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
|
if loaded["option"]["option_preset_code"]:
|
|
body["option_preset_code"] = loaded["option"]["option_preset_code"]
|
|
|
|
try:
|
|
updated = products.update_options(api.client, product_no, body)
|
|
except Cafe24Error as exc:
|
|
writes.audit_safe(st, actor=actor, action="update_options", product_no=product_no,
|
|
result="FAIL", detail=str(exc))
|
|
logger.warning("카페24 상품 %s 옵션 수정 실패: %s", product_no, exc)
|
|
raise _http_from_cafe24(exc) from exc
|
|
|
|
# ── 여기부터는 카페24에 반영된 뒤 — 기록 실패는 경고로만 알린다 ──
|
|
record_error = _save_snapshot_safe(
|
|
st, product_no, "options",
|
|
_options_snapshot(updated, befores=[loaded["raw_option"], loaded["effective_option"]],
|
|
osec=loaded["options_section"], recent=[]),
|
|
)
|
|
# 이름 바꾸기 표(수정 전 → 수정 후) — 위치로 짝지어진다(build_update_options_request).
|
|
rename: dict[tuple[str, str], tuple[str, str]] = {}
|
|
for o, n in zip(original, body["options"]):
|
|
for ov, nv in zip(o["option_value"], n["option_value"]):
|
|
rename[(o["option_name"], ov["option_text"])] = (n["option_name"], nv["option_text"])
|
|
raw_labels = {str(v.get("variant_code") or ""): v.get("options") for v in loaded["raw_variants"]}
|
|
previous = (loaded["variants_section"].get("data") or {}) if _within(
|
|
loaded["variants_section"].get("written_at")) else {}
|
|
label_patch: dict[str, Any] = {}
|
|
renamed_variants: list[dict[str, Any]] = []
|
|
for v in loaded["effective_variants"]:
|
|
code = str(v.get("variant_code") or "")
|
|
current = store.labels_as_json(v.get("options"))
|
|
new = [
|
|
dict(zip(("name", "value"), rename.get((o["name"], o["value"]), (o["name"], o["value"]))))
|
|
for o in current
|
|
]
|
|
renamed_variants.append({**v, "options": new})
|
|
if new != current and code:
|
|
prior = previous.get(code) if isinstance(previous.get(code), dict) else {}
|
|
history = [
|
|
[{"name": a, "value": b} for a, b in labels]
|
|
for labels in store.label_history(prior.get("_options_before"))
|
|
]
|
|
befores = _unique(history + [current, store.labels_as_json(raw_labels.get(code))])
|
|
label_patch[code] = {"options": new, "_options_before": [b for b in befores if b != new]}
|
|
if label_patch:
|
|
record_error = record_error or _save_snapshot_safe(st, product_no, "variants", label_patch)
|
|
summary = "; ".join(
|
|
f"{o['option_name']}: " + ", ".join(v["option_text"] for v in o["option_value"])
|
|
for o in body["options"]
|
|
)
|
|
writes.audit_safe(st, actor=actor, action="update_options", product_no=product_no,
|
|
result="SUCCESS", detail=summary[:900])
|
|
logger.info("카페24 상품 %s 옵션 수정 (%s)", product_no, actor)
|
|
|
|
shown_option, shown_variants = _annotate(updated, renamed_variants, [])
|
|
return {"ok": True, "option": _options_view(shown_option),
|
|
"variants": [_variant_view(v) for v in shown_variants],
|
|
"record_warning": record_error}
|
|
|
|
|
|
@product_info_router.delete("/products/{product_no}/options")
|
|
def options_delete(request: Request, product_no: int) -> dict[str, Any]:
|
|
"""옵션 삭제 — 카페24가 품목도 함께 지운다. 화면에서 확인창을 거친다."""
|
|
st, user = require_store(request)
|
|
actor = str(user.get("email") or "")
|
|
api = build_cafe24_api(st)
|
|
with locked_json(st, product_no, actor=actor, purpose="옵션 삭제"):
|
|
try:
|
|
before = products.get_options(api.client, product_no)
|
|
products.delete_options(api.client, product_no)
|
|
except Cafe24Error as exc:
|
|
writes.audit_safe(st, actor=actor, action="delete_options", product_no=product_no,
|
|
result="FAIL", detail=str(exc))
|
|
raise _http_from_cafe24(exc) from exc
|
|
names = ", ".join(
|
|
str(o.get("option_name") or "") for o in (before.get("options") or []) if isinstance(o, dict)
|
|
)
|
|
osec, _vsec = _snapshot_sections(st, product_no)
|
|
record_error = _save_snapshot_safe(
|
|
st, product_no, "options",
|
|
_options_snapshot({"has_option": "F", "options": []}, befores=[before], osec=osec, recent=[]),
|
|
)
|
|
# 품목 전체 초기화 — 빈 dict 병합(=변경 없음)이 아니라 명시적 replace.
|
|
record_error = record_error or _save_snapshot_safe(st, product_no, "variants", {}, replace=True)
|
|
writes.audit_safe(st, actor=actor, action="delete_options", product_no=product_no,
|
|
result="SUCCESS", detail=f"삭제된 옵션: {names or '(없음)'}")
|
|
logger.info("카페24 상품 %s 옵션 삭제 (%s)", product_no, actor)
|
|
return {"ok": True, "option": _options_view({"has_option": "F"}), "variants": [],
|
|
"record_warning": record_error}
|
|
|
|
|
|
@product_info_router.post("/products/{product_no}/options/image")
|
|
def option_image_upload(
|
|
request: Request,
|
|
product_no: int,
|
|
file: UploadFile = File(...),
|
|
) -> dict[str, Any]:
|
|
"""옵션값 썸네일 업로드만 한다. 경로를 돌려주면 화면이 옵션 저장(PUT)에 담는다."""
|
|
st, user = require_store(request)
|
|
actor = str(user.get("email") or "")
|
|
data = _read_image(file)
|
|
api = build_cafe24_api(st)
|
|
try:
|
|
path = products.upload_image_bytes(api.client, data)
|
|
except Cafe24Error as exc:
|
|
writes.audit_safe(st, actor=actor, action="upload_option_image", product_no=product_no,
|
|
result="FAIL", detail=str(exc))
|
|
raise _http_from_cafe24(exc) from exc
|
|
if not path:
|
|
raise HTTPException(status_code=502, detail="카페24가 업로드 경로를 돌려주지 않았습니다.")
|
|
writes.audit_safe(st, actor=actor, action="upload_option_image", product_no=product_no,
|
|
result="SUCCESS", detail=path)
|
|
return {"ok": True, "path": path}
|
|
|
|
|
|
@product_info_router.delete("/products/{product_no}/variants/{variant_code}")
|
|
def variant_delete(request: Request, product_no: int, variant_code: str) -> dict[str, Any]:
|
|
"""품목 1건 삭제. 옵션값은 남을 수 있다(카페24 모델) — 정리는 옵션 재생성으로."""
|
|
st, user = require_store(request)
|
|
actor = str(user.get("email") or "")
|
|
code = str(variant_code or "").strip().upper()
|
|
if not store.VARIANT_CODE_RE.match(code):
|
|
raise HTTPException(status_code=400, detail=f"품목코드 형식이 올바르지 않습니다: {code}")
|
|
api = build_cafe24_api(st)
|
|
with locked_json(st, product_no, actor=actor, purpose="품목 삭제"):
|
|
try:
|
|
products.delete_variant(api.client, product_no, code)
|
|
except Cafe24Error as exc:
|
|
writes.audit_safe(st, actor=actor, action="delete_variant", product_no=product_no,
|
|
result="FAIL", detail=f"{code}: {exc}")
|
|
raise _http_from_cafe24(exc) from exc
|
|
# 카페24 GET 은 한동안 삭제된 품목을 계속 돌려준다 — 삭제 표식을 남겨 걸러낸다.
|
|
# 표식은 이후 늦게 도착한 수정이 있어도 유지된다(store.merge_variant_snapshot).
|
|
record_error = _save_snapshot_safe(st, product_no, "variants", {code: {"_deleted": True}})
|
|
writes.audit_safe(st, actor=actor, action="delete_variant", product_no=product_no,
|
|
result="SUCCESS", detail=code)
|
|
logger.info("카페24 상품 %s 품목 %s 삭제 (%s)", product_no, code, actor)
|
|
return {"ok": True, "variant_code": code, "record_warning": record_error}
|
|
|
|
|
|
@product_info_router.put("/products/{product_no}/variants")
|
|
def variants_update(
|
|
request: Request,
|
|
product_no: int,
|
|
payload: dict[str, Any] = Body(default_factory=dict),
|
|
) -> dict[str, Any]:
|
|
"""품목 여러 건의 자체코드 · 추가금액 · 진열 · 판매 · 재고(사용·수량·품절표시)를 한 번에 바꾼다 — **행별 결과**.
|
|
|
|
응답 {"ok": 전부 성공?, "partial": 일부만?, "updated": {code: 반영된 값},
|
|
"failed": {code: 사유}, "unknown": {code: 사유}}
|
|
100건 묶음 중 일부가 실패해도 성공한 행은 성공으로 기록·표시한다(화면이 그 행을
|
|
다시 보내지 않게). 하나도 반영되지 않았으면 502.
|
|
진열·판매는 `CAFE24_SHOP_NOS` 의 다른 쇼핑몰에도 같은 값으로 보낸다 — 실패는 "shop_failed".
|
|
"""
|
|
st, user = require_store(request)
|
|
actor = str(user.get("email") or "")
|
|
rows = payload.get("rows")
|
|
if not isinstance(rows, list) or not rows:
|
|
raise HTTPException(status_code=400, detail="바꿀 품목이 없습니다.")
|
|
try:
|
|
requests = store.build_variant_updates(rows)
|
|
except ValueError as exc:
|
|
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
|
if not requests:
|
|
raise HTTPException(status_code=400, detail="바뀐 값이 없습니다.")
|
|
|
|
api = build_cafe24_api(st)
|
|
with locked_json(st, product_no, actor=actor, purpose="품목 수정"):
|
|
results = products.update_variants(api.client, product_no, requests)
|
|
|
|
# 카페24가 받아들인 행만 현재값으로 기록한다. 응답에 담긴 값이 있으면 그것을 우선한다.
|
|
sent = {r["variant_code"]: {k: v for k, v in r.items() if k != "variant_code"} for r in requests}
|
|
by_code: dict[str, dict[str, Any]] = {}
|
|
failed: dict[str, str] = {}
|
|
unknown: dict[str, str] = {}
|
|
for result in results:
|
|
code = result["variant_code"]
|
|
if result["status"] == products.VARIANT_OK:
|
|
patch = dict(sent.get(code) or {})
|
|
for key in ("custom_variant_code", "additional_amount", "display", "selling", "display_order",
|
|
"use_inventory", "display_soldout", "quantity"):
|
|
value = (result.get("variant") or {}).get(key)
|
|
if value is not None:
|
|
patch[key] = value
|
|
by_code[code] = patch
|
|
elif result["status"] == products.VARIANT_UNKNOWN:
|
|
unknown[code] = result["error"]
|
|
else:
|
|
failed[code] = result["error"]
|
|
record_error = _save_snapshot_safe(st, product_no, "variants", by_code) if by_code else ""
|
|
|
|
# 멀티쇼핑몰: 진열·판매는 쇼핑몰마다 따로라 기본몰(1)에 반영된 행의 진열·판매만
|
|
# 다른 쇼핑몰에도 똑같이 보낸다. 추가금액(통화가 다름)·자체코드·순서는 보내지 않는다.
|
|
flags = [
|
|
{"variant_code": code, **{k: sent[code][k] for k in ("display", "selling") if k in sent[code]}}
|
|
for code in by_code if {"display", "selling"} & set(sent.get(code) or {})
|
|
]
|
|
shop_failed: dict[str, str] = {}
|
|
for shop in (shop_nos()[1:] if flags else []):
|
|
bad = [r for r in products.update_variants(api.client, product_no, flags, shop_no=shop)
|
|
if r["status"] != products.VARIANT_OK]
|
|
if bad:
|
|
shop_failed[str(shop)] = f"{len(bad)}건 — {bad[0]['error']}"
|
|
|
|
detail = "; ".join(
|
|
f"{code}: " + ", ".join(f"{k}={v}" for k, v in patch.items()) for code, patch in by_code.items()
|
|
)
|
|
if flags and len(shop_nos()) > 1:
|
|
detail = f"[진열·판매 쇼핑몰 {','.join(map(str, shop_nos()))}] " + detail
|
|
if shop_failed:
|
|
detail += " / 다른 쇼핑몰 실패: " + "; ".join(f"{s}번 {e}" for s, e in shop_failed.items())
|
|
if failed or unknown:
|
|
detail = (f"성공 {len(by_code)} / 실패 {len(failed)} / 결과 모름 {len(unknown)} — " + detail)
|
|
first = next(iter({**failed, **unknown}.values()), "")
|
|
detail += f" / 오류: {first}"
|
|
result_label = "SUCCESS" if not (failed or unknown) else ("PARTIAL" if by_code else "FAIL")
|
|
writes.audit_safe(st, actor=actor, action="update_variants", product_no=product_no,
|
|
result=result_label, detail=detail[:900])
|
|
if not by_code:
|
|
first = next(iter({**failed, **unknown}.values()), "알 수 없는 오류")
|
|
note = " (일부는 반영됐을 수 있습니다 — 다시 불러와 확인하세요)" if unknown else ""
|
|
logger.warning("카페24 상품 %s 품목 수정 실패: %s", product_no, first)
|
|
raise HTTPException(status_code=502, detail=f"{first}{note}")
|
|
logger.info("카페24 상품 %s 품목 %s건 수정 (%s, 실패 %s, 모름 %s)",
|
|
product_no, len(by_code), actor, len(failed), len(unknown))
|
|
return {
|
|
"ok": not (failed or unknown),
|
|
"partial": bool(failed or unknown),
|
|
"updated": {code: _variant_view({"variant_code": code, **patch}) for code, patch in by_code.items()},
|
|
"failed": failed,
|
|
"unknown": unknown,
|
|
"shop_failed": shop_failed,
|
|
"record_warning": record_error,
|
|
}
|