fix(cafe24): 대표이미지 적용 안 됨 + 옵션 썸네일 "없음" 오표시

- 대표이미지: NNEditor 업로드 경로를 PUT detail_image 에 넣던 방식은 카페24가
  반영하지 않았다. 문서의 전용 API POST /admin/products/{no}/images 에
  base64 data URI + image_upload_type=A 로 등록하고, 응답의 새 경로 4개로
  화면·스냅샷을 맞춘다(응답에 updated_date 가 없어 스냅샷 시각은 등록 시각).
- 옵션 썸네일: 카페24는 option_link_image 등을 "/web/product/big/…" 상대경로로
  준다. 그대로 src 에 넣어 우리 도메인에서 404 → "없음"으로 보였다. 옵션 GET 에
  image_base(쇼핑몰 주소)를 내려 붙여 그리고, 후보(버튼→연결→품목 이미지)가
  깨지면 다음 후보로 넘어간다. 카페24로 되보내는 hidden 값은 원본 그대로.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-09-28 00:33:17 +09:00
parent 81cd0ed0e9
commit e0dc818eab
7 changed files with 147 additions and 34 deletions
+20 -13
View File
@@ -29,6 +29,7 @@ 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
from .common import read_lag_grace_minutes, require_store
@@ -155,10 +156,13 @@ def product_image(
product_no: int,
file: UploadFile = File(...),
) -> dict[str, Any]:
"""대표 이미지 교체. 업로드(/products/images) → PUT detail_image(A 타입).
"""대표 이미지 교체 — 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 "")
@@ -169,25 +173,26 @@ def product_image(
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:
path = products.upload_image_bytes(api.client, data)
if not path:
raise Cafe24Error("카페24가 업로드 경로를 돌려주지 않았습니다.")
updated = products.set_main_image(api.client, product_no, path)
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:
st.log_audit(actor=actor, action="set_main_image", product_no=product_no,
result="FAIL", detail=f"업로드/적용 실패: {exc}")
result="FAIL", detail=f"등록 실패: {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 {})
merged = {**current, **(updated if isinstance(updated, dict) else {})}
if not merged.get("detail_image"):
merged["detail_image"] = path
merged = {**current, **images, "updated_date": now_kst().isoformat(timespec="seconds")}
remember_write(st, product_no, merged)
st.log_audit(actor=actor, action="set_main_image", product_no=product_no,
result="SUCCESS", detail=f"'{before}' → '{merged.get('detail_image')}' (업로드 {path})")
result="SUCCESS", detail=f"'{before}' → '{images['detail_image']}'")
logger.info("카페24 상품 %s 대표이미지 변경 (%s)", product_no, actor)
return {"ok": True, "product": _scalar_view(merged)}
@@ -294,8 +299,10 @@ def options_get(request: Request, product_no: int) -> dict[str, Any]:
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}
"display_types": store.OPTION_DISPLAY_LABELS, "image_base": api.config.shop_base}
@product_info_router.post("/products/{product_no}/options")
@@ -125,7 +125,7 @@
{% endblock %}
{% block scripts %}
<script src="/static/cafe24-options.js?v=20260919b"></script>
<script src="/static/cafe24-options.js?v=20260928a"></script>
<script>
(function () {
var pane = document.getElementById("cf24-editor-pane");
+28
View File
@@ -1193,6 +1193,34 @@ def test_upload_images_and_variants_wrappers():
assert client.calls[-1][0] == "DELETE"
def test_set_main_image_uses_product_images_endpoint():
"""대표이미지는 POST /products/{no}/images 에 data URI 로 A 타입 등록 — 새 경로 4개를 돌려준다."""
client = _RouteClient({
"POST /admin/products/13/images": {"image": {
"shop_no": 1, "product_no": 13,
"detail_image": "https://d/web/product/big/x.png",
"list_image": "https://d/web/product/medium/x.png",
"tiny_image": "https://d/web/product/tiny/x.png",
"small_image": "https://d/web/product/small/x.png",
}},
})
out = products.set_main_image(client, 13, b"\x89PNG", content_type="image/png")
assert out == {
"detail_image": "https://d/web/product/big/x.png",
"list_image": "https://d/web/product/medium/x.png",
"tiny_image": "https://d/web/product/tiny/x.png",
"small_image": "https://d/web/product/small/x.png",
}
method, path, body = client.calls[-1]
assert (method, path) == ("POST", "/admin/products/13/images")
assert body["shop_no"] == 1
assert body["request"]["image_upload_type"] == "A"
assert body["request"]["detail_image"].startswith("data:image/png;base64,")
# 상품 PUT(detail_image 경로 넣기)은 더 이상 쓰지 않는다
assert not [c for c in client.calls if c[0] == "PUT"]
assert products.set_main_image(client, 13, b"") == {}
def _run_all():
fns = [v for k, v in sorted(globals().items()) if k.startswith("test_") and callable(v)]
for fn in fns: