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
+42 -3
View File
@@ -346,9 +346,48 @@ def upload_image_bytes(client: Cafe24Client, data: bytes) -> str:
return paths[0] if paths else ""
def set_main_image(client: Cafe24Client, product_no: int, image_path: str) -> dict[str, Any]:
"""대표이미지 교체 — 목록/작은목록/축소 이미지는 카페24가 리사이징(A 타입)."""
return update_product(client, product_no, detail_image=image_path, image_upload_type="A")
def set_main_image(
client: Cafe24Client,
product_no: int,
data: bytes,
*,
content_type: str = "image/jpeg",
shop_no: int = 1,
) -> dict[str, str]:
"""대표이미지 교체 — POST /admin/products/{no}/images (상품 이미지 등록).
body `{"shop_no":1,"request":{"image_upload_type":"A","detail_image":"data:<mime>;base64,…"}}`
→ `{"image":{detail_image, list_image, tiny_image, small_image}}` (새 /web/product/… 경로).
A(대표이미지등록)면 카페24가 상세이미지를 리사이징해 목록/작은목록/축소에도 넣는다.
⚠️ `/admin/products/images`(상세설명 에디터용, /web/upload/NNEditor/…) 로 올린 경로를
`PUT /admin/products/{no}` 의 detail_image 에 넣는 방식은 대표이미지가 바뀌지 않았다
(실물 — "업로드했는데 적용 안 됨"). 대표이미지는 반드시 이 전용 API 로 등록한다.
"""
import base64 # noqa: WPS433
if not data:
return {}
no = int(product_no)
b64 = base64.b64encode(data).decode("ascii")
payload = {
"shop_no": int(shop_no),
"request": {
"image_upload_type": "A",
"detail_image": f"data:{content_type or 'image/jpeg'};base64,{b64}",
},
}
response = client.post(f"/admin/products/{no}/images", json=payload, product_no=no, timeout=UPLOAD_TIMEOUT)
image = response.get("image")
if isinstance(image, list): # 문서는 dict — 목록으로 올 때도 첫 건을 쓴다
image = image[0] if image else {}
if not isinstance(image, dict):
return {}
return {
key: str(image.get(key) or "")
for key in ("detail_image", "list_image", "tiny_image", "small_image")
if image.get(key)
}
# ════════════════════════════════════════════════════════════
+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:
+40 -11
View File
@@ -28,6 +28,18 @@
var DEFAULT_TYPE = "S";
// 썸네일 <img> onerror — data-fallback(줄바꿈 구분)의 다음 후보로, 없으면 "없음".
window.cf24ThumbFallback = function (img) {
var rest = (img.getAttribute("data-fallback") || "").split("\n").filter(Boolean);
if (rest.length) {
img.setAttribute("data-fallback", rest.slice(1).join("\n"));
img.src = rest[0];
return;
}
img.onerror = null;
img.outerHTML = '<div class="cf24-opt-thumb-empty">없음</div>';
};
window.cf24SetupOptions = function (ctx) {
var root = ctx.root, no = ctx.productNo, modal = ctx.modal;
var apiJson = ctx.apiJson, esc = ctx.escHtml, setMsg = ctx.setMsg;
@@ -38,7 +50,7 @@
var count = root.querySelector("#cf24-options-count");
if (!openBtn || !body) return;
var state = { option: null, variants: [], displayTypes: {}, orphans: [] };
var state = { option: null, variants: [], displayTypes: {}, orphans: [], imageBase: "" };
openBtn.addEventListener("click", function () {
var nameEl = document.getElementById("cf24-name-text");
@@ -53,6 +65,7 @@
state.option = data.option;
state.variants = data.variants || [];
state.displayTypes = data.display_types || {};
state.imageBase = data.image_base || "";
render();
})
.catch(function (err) {
@@ -139,13 +152,29 @@
return "";
}
// 카페24가 경로는 주지만 파일이 없는 경우가 있다(깨진 그림) — 실패하면 "없음"으로 바꾼다.
// 카페24 이미지 경로는 "/web/product/big/…" 처럼 **상대경로**로 오기도 한다(옵션 연결
// 이미지 등). 그대로 src 에 넣으면 우리 도메인에서 찾다가 깨진다 — 쇼핑몰 주소를 붙인다.
// hidden 값(카페24에 다시 보내는 값)은 받은 그대로 둔다.
function imageUrl(path) {
path = String(path || "").trim();
if (!path) return "";
if (path.indexOf("//") === 0) return "https:" + path;
if (path.charAt(0) === "/") return state.imageBase ? state.imageBase + path : "";
return path;
}
// 후보(버튼 이미지 → 연결 이미지 → 품목 image) 중 첫 번째를 보여주고, 깨지면 다음
// 후보로 넘어간다(cf24ThumbFallback). 전부 실패하면 "없음".
var THUMB_EMPTY = '<div class="cf24-opt-thumb-empty">없음</div>';
function thumbHtml(src, title) {
return src
? '<img class="cf24-opt-thumb" src="' + esc(src) + '" alt="" title="' + esc(title || "") +
'" onerror="this.outerHTML=\'' + THUMB_EMPTY.replace(/"/g, "&quot;") + '\'" />'
: THUMB_EMPTY;
function thumbHtml(candidates, title) {
var urls = [];
(Array.isArray(candidates) ? candidates : [candidates]).forEach(function (c) {
var u = imageUrl(c);
if (u && urls.indexOf(u) < 0) urls.push(u);
});
if (!urls.length) return THUMB_EMPTY;
return '<img class="cf24-opt-thumb" src="' + esc(urls[0]) + '" alt="" title="' + esc(title || "") +
'" data-fallback="' + esc(urls.slice(1).join("\n")) + '" onerror="cf24ThumbFallback(this)" />';
}
// 썸네일 파일 선택 → 업로드 → hidden 두 개(option_image_file, option_link_image)에 경로
@@ -220,8 +249,8 @@
var v = r.value || { option_text: "", option_image_file: "", option_link_image: "", option_color: "" };
var variant = r.variant;
var isNewRow = r.index == null;
var thumbSrc = v.option_image_file || v.option_link_image ||
(state.option && state.option.has_option ? variantImageFor(state.option.options[0].option_name, v.option_text) : "");
var thumbSrc = [v.option_image_file, v.option_link_image,
state.option && state.option.has_option ? variantImageFor(state.option.options[0].option_name, v.option_text) : ""];
var code = variant ? variant.variant_code : "";
// data-index: options 응답 안 위치(옵션 PUT 짝맞춤용, 새 행은 빈 값) / data-pos: 처음 그린 순서(순서 변경 판정용)
return '<tr class="cf24-u-row' + (isNewRow ? " is-new" : "") + '" data-index="' + (isNewRow ? "" : r.index) + '" data-pos="' + (position == null ? "" : position) + '" data-code="' + esc(code) + '">' +
@@ -801,7 +830,7 @@
'<label class="cf24-side-field"><span>옵션명</span><input type="text" name="option_name" value="' + esc(o.option_name) + '" /></label>' +
'<label class="cf24-side-field cf24-side-field-type"><span>표시방식</span>' + typeSelect(o.option_display_type || DEFAULT_TYPE, "option_display_type") + "</label></div>";
o.option_value.forEach(function (v, vi) {
var src = v.option_image_file || v.option_link_image || variantImageFor(o.option_name, v.option_text);
var src = [v.option_image_file, v.option_link_image, variantImageFor(o.option_name, v.option_text)];
html += '<div class="cf24-opt-value" data-value="' + vi + '"><span class="cf24-opt-thumb-slot">' + thumbHtml(src) + "</span>" +
'<input type="text" name="option_text" value="' + esc(v.option_text) + '" placeholder="옵션값 이름" />' +
'<input type="hidden" name="option_image_file" value="' + esc(v.option_image_file) + '" />' +
@@ -822,7 +851,7 @@
variants.forEach(function (v) {
var label = v.options.map(function (o) { return o.value; }).join(" / ") || v.variant_code;
html += '<tr class="cf24-v-item" data-code="' + esc(v.variant_code) + '">' +
'<td class="cf24-v-imgcol">' + (v.image ? '<img class="cf24-v-img" src="' + esc(v.image) + '" alt="" />' : '<span class="cf24-v-img cf24-v-img-empty"></span>') + "</td>" +
'<td class="cf24-v-imgcol">' + (imageUrl(v.image) ? '<img class="cf24-v-img" src="' + esc(imageUrl(v.image)) + '" alt="" />' : '<span class="cf24-v-img cf24-v-img-empty"></span>') + "</td>" +
'<td class="cf24-v-name" title="' + esc(label) + '">' + esc(label) + "</td>" +
'<td class="cf24-v-syscode"><button type="button" class="cf24-v-copy" data-copy-text="' + esc(v.variant_code) + '">' + esc(v.variant_code) + "</button></td>" +
'<td class="cf24-v-code"><input type="text" name="custom_variant_code" maxlength="40" value="' + esc(v.custom_variant_code) + '" /></td>' +