Files
dbx-main/app/modules/cafe24/routes_bulk.py
T
king 9b9bafdf95 fix(cafe24): 카페24에서 바뀐 소스가 화면에 반영되지 않던 문제 — 캐시 금지 + 다시 읽기
카페24 관리자에서 소스를 고쳤는데 우리 화면은 예전 것을 보여주는 문제.

편집기 조각(GET /products/{no}/pane)과 목록 화면 응답에 캐시 헤더가 없었다.
브라우저가 이전 응답을 재사용하면 카페24의 현재값이 아닌 예전 소스가 그려진다.
그 상태에서 편집·적용하면 카페24 관리자에서 한 수정을 덮어쓰게 되므로, 단순한
표시 문제가 아니라 데이터 손실로 이어질 수 있다.

응답에 Cache-Control: no-store 를 붙이고 조각을 가져가는 fetch 에도
cache: "no-store" 를 걸었다. 일괄수정 검사 조회도 같다.

편집기에 [다시 읽기] 버튼을 추가했다. 카페24 관리자에서 방금 고친 경우 목록을
다시 그리지 않고 그 상품의 현재 소스만 강제로 받아온다. 편집 중이면 저장 안 됨
경고를 먼저 띄운다.

카페24 API 가 쓰기 직후 잠시 예전 값을 돌려줄 가능성도 있다(읽기 지연). 그 경우도
[다시 읽기] 로 확인할 수 있게 했다.

검증: 유닛테스트 51개 통과. 렌더된 편집기 JS 를 브라우저에서 구문 검사(new Function)
통과, no-store·다시 읽기 반영 확인. 라우트 13개.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-14 14:46:55 +09:00

196 lines
7.5 KiB
Python

"""카페24 일괄수정 — 상세페이지 맨 위 `<style>` 블록 통일.
**미리보기 먼저, 적용은 확인 후.** 87개 상품을 한 번에 쓰는 작업이라, 무엇이
지워지는지 보지 않고 실행하면 남의 CSS(예: 비디오 반응형 스타일)가 조용히 사라진다.
그래서 두 단계로 나눈다.
1) 검사 GET /bulk/scan/{no} → 그 상품의 현재 <style> 내용과 교체 후 모양
2) 적용 POST /bulk/apply/{no} → 그 상품 하나만 실제로 반영
상품 1건당 1요청으로 쪼갠 이유:
- 87건을 한 요청으로 처리하면 1분 가까이 걸려 프록시 타임아웃에 걸린다.
- 브라우저가 순차 호출하며 진행률을 보여줄 수 있고, 한 건 실패가 나머지를 막지
않으며, 어디까지 됐는지 화면에 남는다.
적용 순서는 단건 편집(`routes_products.product_apply`)과 같은 원칙을 지킨다.
카페24 현재값 재조회 → BACKUP 버전 → 교체 → PUT → MANUAL 버전 + 감사로그
지문 대조는 하지 않는다 — 쓰기 직전에 방금 읽은 값을 그대로 쓰기 때문이다.
"""
from __future__ import annotations
import logging
from typing import Any
from fastapi import APIRouter, HTTPException, Request
from fastapi.responses import HTMLResponse
from app.integrations.cafe24 import Cafe24Error, build_cafe24_api, products
from . import store
from .common import base_ctx, guard, require_store
from .routes_products import _no_store
logger = logging.getLogger("cafe24.bulk")
bulk_router = APIRouter()
# 통일할 <style> 블록. 탭 들여쓰기까지 사용자가 준 모양 그대로 쓴다
# (format_html 은 <style> 안쪽을 건드리지 않으므로 그대로 저장된다).
TARGET_STYLE_BLOCK = "<style>\n\tdiv {\n\t\ttext-align: center;\n\t}\n</style>"
def _preview(html: str) -> dict[str, Any]:
"""현재 <style> 상태와 교체 후 모양을 요약한다."""
blocks = store.find_style_blocks(html or "")
current = blocks[0] if blocks else ""
after = store.replace_first_style_block(html or "", TARGET_STYLE_BLOCK)
return {
"style_count": len(blocks),
"current_style": current,
"already_target": current.strip() == TARGET_STYLE_BLOCK.strip(),
"will_change": after != (html or ""),
}
@bulk_router.get("/bulk", response_class=HTMLResponse)
def bulk_page(request: Request) -> HTMLResponse:
"""일괄수정 화면. 상품 목록만 서버에서 그리고, 검사는 브라우저가 순차 호출한다."""
from app.main import render_template # noqa: WPS433
checked = guard(request)
if not isinstance(checked, tuple):
return checked
st, user = checked
api = build_cafe24_api(st)
rows: list[dict[str, Any]] = []
error = ""
try:
raw_rows, _truncated = products.list_all_products(api.client)
st.upsert_products([products.normalize_product(r) for r in raw_rows])
rows = [
{
"product_no": normalized["product_no"],
"product_name": normalized["product_name"],
"display": normalized["display"],
"selling": normalized["selling"],
}
for normalized in (products.normalize_product(r) for r in raw_rows)
]
except Cafe24Error as exc:
error = str(exc)
logger.warning("카페24 상품 목록 조회 실패: %s", exc)
ctx = base_ctx(request, user, active_tab="bulk")
ctx.update(
{
"page_title": "카페24 — 일괄수정",
"page_subtitle": "상세페이지 <style> 블록 통일",
"rows": rows,
"total": len(rows),
"target_style": TARGET_STYLE_BLOCK,
"error": error,
}
)
return _no_store(render_template(request, "cafe24/bulk.html", ctx))
@bulk_router.get("/bulk/scan/{product_no}")
def bulk_scan(request: Request, product_no: int) -> dict[str, Any]:
"""상품 1건의 현재 <style> 상태(읽기 전용)."""
st, _user = require_store(request)
api = build_cafe24_api(st)
try:
desc = products.fetch_descriptions(api.client, product_no)
except Cafe24Error as exc:
raise HTTPException(status_code=502, detail=str(exc)) from None
pc = _preview(desc.description)
mobile = _preview(desc.mobile_description)
return {
"product_no": product_no,
"product_name": desc.product_name,
"separated_mobile": desc.separated_mobile,
"pc": pc,
# 분리 상품만 모바일을 따로 본다(미분리는 PC 값을 그대로 쓴다).
"mobile": mobile if desc.separated_mobile else None,
"will_change": pc["will_change"] or (desc.separated_mobile and mobile["will_change"]),
}
@bulk_router.post("/bulk/apply/{product_no}")
def bulk_apply(request: Request, product_no: int) -> dict[str, Any]:
"""상품 1건의 맨 위 <style> 을 통일된 블록으로 교체한다."""
st, user = require_store(request)
actor = str(user.get("email") or "")
api = build_cafe24_api(st)
# 1) 현재값을 다시 읽는다 — 로컬 값이나 방금 검사한 값을 믿지 않는다.
try:
current = products.fetch_descriptions(api.client, product_no)
except Cafe24Error as exc:
st.log_audit(
actor=actor, action="bulk_style", product_no=product_no,
result="FAIL", detail=f"현재값 조회 실패: {exc}",
)
raise HTTPException(status_code=502, detail=str(exc)) from None
# 2) BACKUP — 유일한 복구 수단
backup_id = st.add_revision(
product_no=product_no,
html_content=current.description,
revision_type=store.REVISION_BACKUP,
memo="일괄 style 교체 직전 자동 백업",
created_by=actor,
)
new_pc = store.format_html(
store.replace_first_style_block(current.description, TARGET_STYLE_BLOCK)
)
if current.separated_mobile:
new_mobile: str | None = store.format_html(
store.replace_first_style_block(current.mobile_description, TARGET_STYLE_BLOCK)
)
if new_mobile == current.mobile_description:
new_mobile = None
else:
new_mobile = new_pc
if new_pc == current.description and (
new_mobile is None or new_mobile == current.mobile_description
):
return {"product_no": product_no, "result": "SKIPPED", "detail": "이미 같은 내용", "backup_id": backup_id}
try:
products.update_descriptions(
api.client, product_no, description=new_pc, mobile_description=new_mobile
)
except Cafe24Error as exc:
st.log_audit(
actor=actor, action="bulk_style", product_no=product_no,
revision_id=backup_id, result="FAIL", detail=str(exc),
)
logger.warning("카페24 상품 %s 일괄 style 적용 실패: %s", product_no, exc)
raise HTTPException(status_code=502, detail=f"{exc} (직전 내용은 버전 {backup_id})") from None
revision_id = st.add_revision(
product_no=product_no,
html_content=new_pc,
revision_type=store.REVISION_MANUAL,
memo="일괄 style 교체",
created_by=actor,
)
st.log_audit(
actor=actor, action="bulk_style", product_no=product_no,
revision_id=revision_id, result="SUCCESS",
detail=f"style 통일 (백업 {backup_id}"
+ (", 모바일 동시 반영)" if new_mobile is not None else ")"),
)
return {
"product_no": product_no,
"result": "SUCCESS",
"backup_id": backup_id,
"revision_id": revision_id,
}