feat(카페24): 대표 이미지(썸네일) 예약 교체

- 편집기 아래 「예약 적용」 폼에 대표 이미지 파일 칸 — 고르면 그 시각에 교체
  (상세페이지·진열·판매와 한 예약에 같이 걸 수 있음, 이미지만도 가능)
- 마이그레이션 006: 예약 image_type/image_name + cafe24_schedule_images(BYTEA, CASCADE),
  "할 일 없는 예약" CHECK 에 이미지 포함
- worker: 이미지 먼저 set_main_image(즉시 교체와 같은 A 타입) → 스냅샷 → 상세페이지·진열/판매
- 예약 목록 「적용 내용」에 대표이미지 표시 + 미리보기 썸네일(GET /cafe24/schedules/{id}/image)
- 이미지 없는 예약 INSERT 는 006 컬럼을 안 써서 마이그레이션 전에도 기존 예약 등록 유지
- 테스트(경로·검증·worker 순서)·문서 갱신, cafe24.css 캐시 버전 올림

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-09 16:38:05 +09:00
parent 36834c65b2
commit 6822329ff2
17 changed files with 286 additions and 45 deletions
+1
View File
@@ -17,6 +17,7 @@
- 옵션/품목 팝업(단일 옵션 화면) 「모바일 스와이프 복사(코드)」: `// 상품명` + `"품목코드": "/web/…썸네일 경로",` 줄들을 클립보드로
(`cafe24-options.js` `swipeCode` — 행에 지금 보이는 썸네일 기준, 도메인/CDN 은 떼고 `/web/` 부터).
「모바일 스와이프 복사(이름)」은 키가 품목코드 대신 옵션값 이름(`swipeCode(tbody, true)`, 품목코드 있는 행만).
- 예약(편집기 아래 「예약 적용」): 대표 이미지(썸네일) · 상세페이지 · 진열 · 판매를 지정 시각에. 대표 이미지 파일은 `cafe24_schedule_images`(마이그레이션 006)에 보관, worker 가 이미지 먼저 교체.
- 권한키 `cafe24`(연결/해제는 admin 전용).
## 규칙
+31 -17
View File
@@ -819,27 +819,41 @@ class Cafe24Store:
set_selling: bool | None,
memo: str = "",
created_by: str = "",
image: bytes | None = None,
image_type: str = "",
image_name: str = "",
) -> int:
"""예약 등록. image 가 있으면 파일을 cafe24_schedule_images 에 같은 트랜잭션으로 남긴다(006).
이미지 없는 예약은 006 컬럼을 쓰지 않는다 — 마이그레이션 전에도 기존 예약 등록이 깨지지 않게.
"""
cols = ["product_no", "scheduled_at", "revision_id", "set_display", "set_selling", "memo", "created_by"]
vals: list[Any] = [int(product_no), scheduled_at, revision_id, set_display, set_selling,
(memo or "")[:500], created_by or ""]
if image:
cols += ["image_type", "image_name"]
vals += [image_type, (image_name or "")[:200]]
with self._pool.connection() as conn:
with conn.transaction():
row = conn.execute(
f"INSERT INTO cafe24_product_schedules ({', '.join(cols)}) " # noqa: S608 — 고정 컬럼명만
f"VALUES ({', '.join(['%s'] * len(cols))}) RETURNING id",
vals,
).fetchone()
if row and image:
conn.execute(
"INSERT INTO cafe24_schedule_images (schedule_id, data) VALUES (%s, %s)",
(row["id"], image),
)
return int(row["id"]) if row else 0
def get_schedule_image(self, schedule_id: int) -> bytes:
"""예약 대표 이미지 파일. 없으면 b""."""
with self._pool.connection() as conn:
row = conn.execute(
"""
INSERT INTO cafe24_product_schedules
(product_no, scheduled_at, revision_id, set_display, set_selling,
memo, created_by)
VALUES (%s,%s,%s,%s,%s,%s,%s)
RETURNING id
""",
(
int(product_no),
scheduled_at,
revision_id,
set_display,
set_selling,
(memo or "")[:500],
created_by or "",
),
"SELECT data FROM cafe24_schedule_images WHERE schedule_id = %s", (int(schedule_id),)
).fetchone()
return int(row["id"]) if row else 0
return bytes(row["data"]) if row else b""
def list_schedules(self, *, limit: int = 200) -> list[dict[str, Any]]:
"""예약 목록. 대기 중인 것을 먼저, 그다음 최근 처리 순."""
+37 -8
View File
@@ -1,8 +1,9 @@
"""카페24 예약관리 — 지정 시각에 상세페이지·진열/판매를 자동 적용.
"""카페24 예약관리 — 지정 시각에 대표 이미지·상세페이지·진열/판매를 자동 적용.
되돌리기(자동 복원)는 쓰지 않는다. 예약은 "그 시각에 이 내용을 적용" 하나뿐이다.
한 예약에서 세 가지를 각각 고를 수 있다.
한 예약에서 네 가지를 각각 고를 수 있다.
대표 이미지 고른 파일로 그 시각에 교체 (파일은 DB 보관 — 마이그레이션 006)
상세페이지 HTML 편집기에 있는 내용을 그 시각에 적용 (안 고르면 HTML 은 그대로)
진열 진열 / 미진열 / 변경 없음
판매 판매 / 중지 / 변경 없음
@@ -19,13 +20,14 @@ from __future__ import annotations
import logging
from fastapi import APIRouter, Form, Request
from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi import APIRouter, File, Form, HTTPException, Request, UploadFile
from fastapi.responses import HTMLResponse, RedirectResponse, Response
from app.integrations.cafe24 import Cafe24Error, build_cafe24_api, load_config, products
from . import store, writes
from .common import base_ctx, guard
from .routes_product_info import _read_image
from .routes_products import _no_store, load_product
logger = logging.getLogger("cafe24.schedules")
@@ -53,6 +55,7 @@ def schedules_page(request: Request) -> HTMLResponse:
has_html=bool(row.get("has_html")),
set_display=row.get("set_display"),
set_selling=row.get("set_selling"),
has_image=bool(row.get("image_type")),
),
"editable": store.is_editable(row.get("status") or ""),
"needs_review": row.get("status") == store.STATUS_NEEDS_REVIEW,
@@ -63,7 +66,7 @@ def schedules_page(request: Request) -> HTMLResponse:
ctx.update(
{
"page_title": "카페24 — 예약관리",
"page_subtitle": "지정 시각에 상세페이지·진열/판매 자동 적용",
"page_subtitle": "지정 시각에 대표 이미지·상세페이지·진열/판매 자동 적용",
"rows": rows,
"pending": sum(1 for r in rows if r["status"] == store.STATUS_PENDING),
"review": sum(1 for r in rows if r["needs_review"]),
@@ -85,12 +88,14 @@ def schedule_create(
set_selling: str = Form(""),
memo: str = Form(""),
list_query: str = Form(""),
image: UploadFile | None = File(None),
):
"""편집기에서 예약을 등록한다.
HTML 을 적용하는 예약이면 지금 편집기 내용을 DRAFT revision 으로 저장해 고정한다.
단건 적용과 같은 다듬기(URL 인코딩 → 소스 정리)를 거치므로, 예약이 실행됐을 때
저장되는 값이 화면에서 본 것과 같다.
대표 이미지 파일을 고르면 파일을 DB 에 보관했다가 그 시각에 교체한다(마이그레이션 006).
"""
checked = guard(request)
if not isinstance(checked, tuple):
@@ -105,9 +110,16 @@ def schedule_create(
display_flag = store.parse_tristate(set_display)
selling_flag = store.parse_tristate(set_selling)
if not want_html and display_flag is None and selling_flag is None:
image_data = b""
if image is not None and image.filename: # 파일을 안 고르면 브라우저가 이름 없는 빈 파트를 보낸다
try:
image_data = _read_image(image)
except HTTPException as exc:
return RedirectResponse(url=f"{back}&err={exc.detail}", status_code=303)
if not want_html and display_flag is None and selling_flag is None and not image_data:
return RedirectResponse(
url=f"{back}&err=예약할 내용을 하나 이상 선택하세요(상세페이지 / 진열 / 판매).",
url=f"{back}&err=예약할 내용을 하나 이상 선택하세요(대표 이미지 / 상세페이지 / 진열 / 판매).",
status_code=303,
)
@@ -146,9 +158,12 @@ def schedule_create(
set_selling=selling_flag,
memo=memo,
created_by=actor,
image=image_data or None,
image_type=(image.content_type or "").lower() if image_data and image else "",
image_name=(image.filename or "") if image_data and image else "",
)
detail = store.describe_schedule_action(
has_html=want_html, set_display=display_flag, set_selling=selling_flag
has_html=want_html, set_display=display_flag, set_selling=selling_flag, has_image=bool(image_data)
)
st.log_audit(
actor=actor, action="schedule_create", product_no=product_no,
@@ -179,6 +194,20 @@ def schedule_cancel(request: Request, schedule_id: int):
)
@schedules_router.get("/schedules/{schedule_id}/image")
def schedule_image(request: Request, schedule_id: int):
"""예약해 둔 대표 이미지 미리보기(목록 썸네일)."""
checked = guard(request)
if not isinstance(checked, tuple):
return checked
st, _user = checked
row = st.get_schedule(schedule_id)
data = st.get_schedule_image(schedule_id) if row.get("image_type") else b""
if not data:
return Response(status_code=404)
return Response(content=data, media_type=str(row["image_type"]), headers={"Cache-Control": "private, max-age=3600"})
@schedules_router.get("/schedules/preview/{product_no}")
def schedule_current_flags(request: Request, product_no: int) -> dict:
"""예약 폼의 기본값을 위해 현재 진열/판매 상태를 알려준다(JSON, 읽기 전용)."""
+3 -1
View File
@@ -452,10 +452,12 @@ def parse_schedule_at(value: object, *, now: datetime | None = None) -> datetime
def describe_schedule_action(
*, has_html: bool, set_display: bool | None, set_selling: bool | None
*, has_html: bool, set_display: bool | None, set_selling: bool | None, has_image: bool = False
) -> str:
"""예약 내용을 한 줄로 요약(목록·로그 표시용)."""
parts: list[str] = []
if has_image:
parts.append("대표이미지")
if has_html:
parts.append("상세페이지")
if set_display is not None:
@@ -156,7 +156,7 @@
<details class="cf24-details">
<summary>예약 적용 — 지정한 시각에 자동 반영</summary>
<form class="cf24-schedule-form" id="cf24-schedule-form" method="post"
action="/cafe24/schedules"
action="/cafe24/schedules" enctype="multipart/form-data"
data-confirm="지정한 시각에 자동으로 반영됩니다. 예약을 등록할까요?">
<input type="hidden" name="product_no" value="{{ product_no }}" />
<input type="hidden" name="list_query" value="{{ list_query }}" />
@@ -205,6 +205,15 @@
<option value="off">중지</option>
</select>
</label>
{# 대표 이미지(썸네일) — 고르면 그 시각에 교체. 파일은 DB 에 보관했다가 worker 가 올린다. #}
<div class="cf24-schedule-wide cf24-schedule-image">
<span>대표 이미지</span>
<label class="cf24-file-pick">
<input type="file" name="image" id="cf24-schedule-image" accept="image/jpeg,image/png,image/gif,image/webp" />
<span class="erp-btn erp-btn-outline">파일 선택</span>
<span class="cf24-file-name" id="cf24-schedule-image-name">변경 없음</span>
</label>
</div>
<label class="cf24-schedule-wide">
<span>메모</span>
<input class="cf24-schedule-input" type="text" name="memo" maxlength="200"
@@ -221,7 +230,8 @@
<a class="erp-btn erp-btn-outline" href="/cafe24/schedules">예약 목록</a>
</div>
<p class="cf24-muted" style="margin:8px 0 0;">
진열·판매만 바꾸려면 위 체크를 해제하세요. 셋 중 하나 이상은 선택해야 합니다.
대표 이미지·진열·판매만 바꾸려면 위 체크를 해제하세요. 넷 중 하나 이상은 선택해야 합니다.
대표 이미지는 JPG·PNG·GIF·WEBP, 10MB 이하(목록/축소 이미지는 카페24가 자동 생성).
</p>
</form>
</details>
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/cafe24.css?v=20261015a" />
<link rel="stylesheet" href="/static/cafe24.css?v=20261109a" />
{% endblock %}
{% block content %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/cafe24.css?v=20261103c" />
<link rel="stylesheet" href="/static/cafe24.css?v=20261109a" />
{% endblock %}
{% block content %}
@@ -561,6 +561,17 @@
// 날짜·시간도 두 개의 별도 input 값을 합쳐 서버가 기대하는 형식으로 만든다.
var schedForm = pane.querySelector("#cf24-schedule-form");
if (schedForm) {
var schedImg = schedForm.querySelector("#cf24-schedule-image");
var schedImgName = schedForm.querySelector("#cf24-schedule-image-name");
if (schedImg) schedImg.addEventListener("change", function () {
var f = schedImg.files && schedImg.files[0];
if (f && f.size > 10 * 1024 * 1024) {
window.erpAlert("10MB 를 넘는 파일은 올릴 수 없습니다.");
schedImg.value = "";
f = null;
}
schedImgName.textContent = f ? f.name + " (" + Math.round(f.size / 1024) + "KB) — 그 시각에 교체" : "변경 없음";
});
schedForm.addEventListener("submit", function (e) {
var box = document.getElementById("cf24-html-pc");
var holder = document.getElementById("cf24-schedule-html");
@@ -576,7 +587,8 @@
// 확인창이 비동기라 일단 제출을 멈추고, 확인을 받으면 다시 보낸다.
// (required 검사는 이미 통과한 뒤라 form.submit() 으로 보내도 안전하다)
e.preventDefault();
window.erpConfirm(schedForm.dataset.confirm).then(function (ok) {
var imgFile = schedImg && schedImg.files && schedImg.files[0];
window.erpConfirm(schedForm.dataset.confirm + (imgFile ? "\n\n대표 이미지: 「" + imgFile.name + "」(으)로 교체" : "")).then(function (ok) {
if (!ok) return;
dirty = false; // 예약 등록으로 화면을 떠나므로 편집 중 경고를 끈다.
schedForm.submit();
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/cafe24.css?v=20261015a" />
<link rel="stylesheet" href="/static/cafe24.css?v=20261109a" />
{% endblock %}
{% block content %}
@@ -37,7 +37,7 @@
<th style="width:130px;">예정 시각</th>
<th style="width:66px;">상품</th>
<th>상품명</th>
<th style="width:150px;">적용 내용</th>
<th style="width:170px;">적용 내용</th>
<th style="width:96px;">상태</th>
<th>메모 / 오류</th>
<th style="width:130px;">등록자</th>
@@ -53,7 +53,8 @@
<a href="/cafe24/?selected={{ r.product_no }}">{{ r.product_no }}</a>
</td>
<td>{{ r.product_name or '—' }}</td>
<td class="cf24-nowrap">{{ r.action_label }}</td>
<td class="cf24-nowrap">{{ r.action_label }}
{% if r.image_type %}<a href="/cafe24/schedules/{{ r.id }}/image" target="_blank" rel="noopener" title="{{ r.image_name }}"><img class="cf24-sched-img" src="/cafe24/schedules/{{ r.id }}/image" alt="{{ r.image_name }}" loading="lazy" /></a>{% endif %}</td>
<td class="cf24-nowrap">
{% if r.status == 'SUCCESS' %}<span class="erp-badge cf24-badge-ok">{{ r.status_label }}</span>
{% elif r.status == 'FAILED' %}<span class="cf24-err">{{ r.status_label }}</span>
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/cafe24.css?v=20261015a" />
<link rel="stylesheet" href="/static/cafe24.css?v=20261109a" />
{% endblock %}
{% block content %}
+7
View File
@@ -411,6 +411,13 @@ class FakeCafe24:
def post(self, path, *, json=None, **kw):
self.calls.append(("POST", path, json))
if path == f"/admin/products/{self.product_no}/images": # 대표이미지 등록(A 타입)
self._tick()
n = sum(1 for c in self.calls if c[1] == path)
image = {k: f"/web/product/{k.split('_')[0]}/{self.product_no}_{n}.png"
for k in ("detail_image", "list_image", "tiny_image", "small_image")}
self.state.update(image)
return {"image": image}
out = self._options_call("POST", path, json)
return copy.deepcopy(out) if out is not None else {}
+3
View File
@@ -649,6 +649,9 @@ def test_describe_schedule_action():
assert store.describe_schedule_action(
has_html=False, set_display=None, set_selling=None
) == "없음"
assert store.describe_schedule_action(
has_html=True, set_display=None, set_selling=None, has_image=True
) == "대표이미지 · 상세페이지"
def test_normalize_schedule_status():
+39 -7
View File
@@ -50,6 +50,7 @@ from app.timezone import now_kst
from . import store, writes
from .common import read_lag_grace_minutes
from .routes_products import load_product
logger = logging.getLogger("cafe24.worker")
@@ -77,9 +78,28 @@ def _summary(row: dict[str, Any]) -> str:
has_html=bool(row.get("revision_id")),
set_display=row.get("set_display"),
set_selling=row.get("set_selling"),
has_image=bool(row.get("image_type")),
)
def _apply_image(st: Any, api: Any, product_no: int, data: bytes, content_type: str) -> str:
"""예약 대표 이미지 교체(routes_product_info.product_image 와 같은 순서). 반환: 새 detail_image.
상세페이지·진열/판매보다 **먼저** 한다 — 뒤 단계가 실패해 재시도되면 같은 이미지를 한 번 더
올릴 뿐이라 안전하고, 앞 단계(시도 기록)가 SUCCESS 로 복구된 뒤 이미지가 빠지는 일이 없다.
"""
current, _ = load_product(st, api, product_no)
if not current:
raise Cafe24Error("카페24에서 상품을 찾지 못했습니다.")
images = products.set_main_image(api.client, product_no, data, content_type=content_type)
if not images.get("detail_image"):
raise Cafe24Error("카페24가 등록된 이미지 경로를 돌려주지 않았습니다.")
writes.remember_product_write(
st, product_no, {**current, **images, "updated_date": now_kst().isoformat(timespec="seconds")}
)
return str(images["detail_image"])
def _retry_or_fail(st: Any, row: dict[str, Any], token: str, error: str) -> str:
"""재시도 예산 안이면 PENDING + 대기, 아니면 FAILED. 반환: 결과 상태."""
retry_count = int(row.get("retry_count") or 0)
@@ -113,6 +133,8 @@ def run_one(st: Any, api: Any, row: dict[str, Any]) -> str:
def fence() -> bool:
return bool(st.renew_schedule_lease(schedule_id, token, ttl_seconds=lease))
image_type = str(row.get("image_type") or "")
new_image = ""
try:
html: str | None = None
if revision_id:
@@ -122,17 +144,26 @@ def run_one(st: Any, api: Any, row: dict[str, Any]) -> str:
html = str(revision.get("html_content") or "")
if not html.strip():
raise Cafe24Error(f"버전 {revision_id} 의 내용이 비어 있습니다.")
image = st.get_schedule_image(schedule_id) if image_type else b""
if image_type and not image:
raise Cafe24Error("예약해 둔 대표 이미지 파일을 찾을 수 없습니다.")
with writes.write_lock(
st, writes.product_lock_key(product_no), actor=ACTOR,
purpose=f"예약 #{schedule_id} 실행", wait_seconds=0,
) as lock:
outcome = writes.write_product(
st, api, product_no,
lock=lock, origin=store.ORIGIN_SCHEDULED, actor=ACTOR, html=html,
set_display=set_display, set_selling=set_selling,
schedule_id=schedule_id, target_revision_id=int(revision_id) if revision_id else None,
memo=f"예약 #{schedule_id} 적용", extra_fence=fence,
)
if image:
if not fence():
raise writes.WriteBusy("예약 lease 를 잃었습니다 — 다른 worker 가 처리합니다.")
new_image = _apply_image(st, api, product_no, image, image_type)
outcome = writes.WriteOutcome()
if html is not None or set_display is not None or set_selling is not None:
outcome = writes.write_product(
st, api, product_no,
lock=lock, origin=store.ORIGIN_SCHEDULED, actor=ACTOR, html=html,
set_display=set_display, set_selling=set_selling,
schedule_id=schedule_id, target_revision_id=int(revision_id) if revision_id else None,
memo=f"예약 #{schedule_id} 적용", extra_fence=fence,
)
except writes.WriteSetupError as exc:
st.finish_schedule(schedule_id, token=token, status=store.STATUS_PENDING, error=str(exc),
next_retry_at=now_kst() + timedelta(seconds=SETUP_RETRY_SECONDS))
@@ -171,6 +202,7 @@ def run_one(st: Any, api: Any, row: dict[str, Any]) -> str:
revision_id=outcome.revision_id or (int(revision_id) if revision_id else None),
schedule_id=schedule_id, result="SUCCESS",
detail=summary + (f" (백업 {outcome.backup_id})" if outcome.backup_id else "")
+ (f" / 대표이미지 → '{new_image}'" if new_image else "")
+ (f" / {note}" if note else ""),
)
logger.info("예약 #%s 상품 %s 적용 완료 — %s", schedule_id, product_no, summary)
+21
View File
@@ -746,6 +746,27 @@
grid-column: 1 / -1;
}
/* 예약 대표 이미지 — 칸 제목은 다른 칸과 같게, 파일 고르기는 가로 한 줄 */
.cf24-schedule-image {
display: flex;
flex-direction: column;
gap: 4px;
font-size: var(--text-caption, 12px);
color: var(--color-midtone-gray, #737373);
}
.cf24-schedule-grid label.cf24-file-pick {
flex-direction: row;
}
.cf24-sched-img {
display: block;
width: 48px;
height: 48px;
margin-top: 4px;
object-fit: cover;
border: 1px solid var(--color-border, #e5e5e5);
border-radius: 4px;
}
/* 날짜/시간을 별도 input 으로 나눈다 — datetime-local 은 한국어 로캘에서
"2026. 08. 14. 오후 07:00" 형태로 길어져 auto-fit minmax(160px, 1fr) 칸에
잘렸다(실측). 지금은 표시 텍스트를 우리가 직접 그리므로(아래 .cf24-dt-*) 폭을