feat(cafe24): 일괄수정 — 상세페이지 <style> 블록 통일
87개 상품의 상세설명 맨 위 <style> 을 정해진 내용으로 바꾸는 화면을 추가했다.
<style>
div {
text-align: center;
}
</style>
그냥 덮어쓰지 않고 검사 → 선택 → 적용 2단계로 만들었다. 상품 131번의 style 안에는
"비디오 태그 모바일 반응형 스타일" 같은 CSS 가 들어 있어서, 무엇이 지워지는지 보지
않고 87건을 일괄 실행하면 필요한 규칙이 조용히 사라진다. 검사 결과 표에 지금 들어
있는 CSS 를 그대로 보여주고, 변경이 필요한 상품만 자동 선택한다(이미 같은 내용이면
「이미 동일」로 제외).
맨 앞 <style> 블록 하나만 바꾼다. 아래쪽에 <style> 이 더 있으면 건드리지 않고
「블록 2개 · 주의」로 표시해 사람이 판단하게 한다 — 일괄 작업이 남의 CSS 를 조용히
지우는 것이 가장 위험하다. 블록이 없는 상품은 맨 앞에 넣는다.
상품 1건당 1요청으로 쪼갰다. 87건을 한 요청으로 묶으면 1분 가까이 걸려 프록시
타임아웃에 걸리고, 동시에 던지면 카페24 호출 제한(429)에 걸린다. 브라우저가 순차
호출하며 진행률을 보여주고, 한 건 실패가 나머지를 막지 않으며 어디까지 됐는지
화면에 남는다.
적용 순서는 단건 편집과 같은 원칙을 지킨다: 카페24 현재값 재조회 → BACKUP 버전 →
교체 → PUT → MANUAL 버전 + 감사로그(action=bulk_style). 검사 때 읽은 값을 재사용하지
않고 쓰기 직전에 다시 읽는다. PC/모바일 분리 상품은 모바일도 함께 바꾼다.
검증: 유닛테스트 51개 통과(신규 6개 — 앞 블록만 교체하고 뒤 블록 보존, 없을 때 삽입,
멱등, 포맷 후 탭 유지, 여러 줄 원문 정확히 절단). 실제 데이터로 미리보기 로직 확인:
비디오 CSS 가 "지워질 내용"에 잡히고, 이미 동일한 상품은 will_change=False,
style 없는 상품은 삽입 대상으로 판정. 라우트 13개 등록, 템플릿 렌더 확인.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,194 @@
|
||||
"""카페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
|
||||
|
||||
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 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,
|
||||
}
|
||||
Reference in New Issue
Block a user