2 Commits

Author SHA1 Message Date
king 60d5ca417d Merge branch 'feat/cafe24-keep-variant-price' 2026-11-15 03:15:32 +09:00
king 2465874198 feat(카페24): 판매가 변경 시 품목 판매 가격 유지 — 추가금액 자동 조정
기본 정보에서 판매가를 바꾸면 같은 잠금 안에서 옵션 품목 추가금액을
(옛 판매가 - 새 판매가)만큼 옮겨 품목 판매 가격(판매가+추가금액)을 그대로 둔다.
품목 조정 실패는 판매가 저장을 되돌리지 않고 화면 메시지로 알린다.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 03:15:26 +09:00
5 changed files with 91 additions and 2 deletions
+1
View File
@@ -16,6 +16,7 @@
- 대표이미지는 `POST /admin/products/{no}/images` 에 base64 data URI + `image_upload_type=A`.
NNEditor 업로드 경로를 PUT `detail_image` 에 넣는 방식은 적용 안 됨.
- 옵션/품목 팝업 「판매 가격」 열: 기본 정보 판매가 + 추가금액을 보여주고, 입력하면 추가금액을 역산(`cafe24-options.js` `bindSalePrice`). 저장되는 값은 추가금액뿐.
- 기본 정보에서 판매가를 바꾸면 같은 잠금 안에서 품목 추가금액을 (옛 판매가 − 새 판매가)만큼 옮겨 품목 판매 가격을 유지(`_keep_variant_sale_prices`, `store.shift_additional_amounts`). 공급가·소비자가는 품목과 무관. 판매가는 이미 반영됐으므로 품목 조정 실패는 화면 메시지(`variants_error`)로만.
- 옵션/품목 팝업 옵션값 이름·자체 품목코드·추가금액·판매 가격 칸: Enter·↓ 아래 행, ↑ 위 행 같은 열로 이동(한글 조합 중에는 이동 안 함).
- 옵션/품목 팝업(단일 옵션 화면) 「모바일 스와이프 복사(코드)」: `// 상품명` + `"품목코드": "/web/…썸네일 경로",` 줄들을 클립보드로
(`cafe24-options.js` `swipeCode` — 행에 지금 보이는 썸네일 기준, 도메인/CDN 은 떼고 `/web/` 부터).
+35 -1
View File
@@ -145,12 +145,46 @@ def product_basic(
raise _http_from_cafe24(exc) from exc
remember_write(st, product_no, updated if isinstance(updated, dict) else {})
shifted = (_keep_variant_sale_prices(st, api, product_no, before["price"], changes["price"])
if "price" in changes else {})
merged = {**current, **(updated if isinstance(updated, dict) else {}), **changes}
detail = ", ".join(f"{k}: '{before[k]}' → '{v}'" for k, v in changes.items())
if shifted.get("detail"):
detail += f" / 품목 추가금액 조정: {shifted['detail']}"
writes.audit_safe(st, actor=actor, action="update_basic", product_no=product_no,
result="SUCCESS", detail=detail)
logger.info("카페24 상품 %s 기본정보 변경 (%s): %s", product_no, actor, detail)
return {"ok": True, "changed": list(changes.keys()), "product": _scalar_view(merged)}
return {"ok": True, "changed": list(changes.keys()), "product": _scalar_view(merged),
"variants_shifted": shifted.get("count", 0), "variants_error": shifted.get("error", "")}
def _keep_variant_sale_prices(st: Any, api: Any, product_no: int, old_price: str, new_price: str) -> dict[str, Any]:
"""판매가가 바뀐 뒤 품목 판매 가격(판매가 + 추가금액)이 그대로이도록 추가금액을 옮긴다.
판매가는 이미 반영됐으므로 실패해도 예외를 올리지 않고 {"error": …} 로 알린다.
반환 {"count": 반영된 품목 수, "error": 사유, "detail": 감사 로그용}.
"""
try:
variants = _load_options_and_variants(st, api, product_no)["effective_variants"]
requests = store.build_variant_updates(store.shift_additional_amounts(variants, old_price, new_price))
except (Cafe24Error, ValueError) as exc:
logger.warning("카페24 상품 %s 품목 추가금액 조정 준비 실패: %s", product_no, exc)
return {"error": f"품목 추가금액 조정 실패: {exc}", "detail": f"실패 {exc}"}
if not requests:
return {}
results = products.update_variants(api.client, product_no, requests)
sent = {r["variant_code"]: r["additional_amount"] for r in requests}
ok = {r["variant_code"]: sent[r["variant_code"]] for r in results if r["status"] == products.VARIANT_OK}
bad = [r for r in results if r["status"] != products.VARIANT_OK]
if ok:
_save_snapshot_safe(st, product_no, "variants", {c: {"additional_amount": a} for c, a in ok.items()})
detail = "; ".join(f"{c}={a}" for c, a in ok.items())
error = ""
if bad:
error = f"품목 {len(bad)}건 추가금액 조정 실패 — {bad[0]['error']} (옵션/품목 창에서 확인하세요)"
detail += f" / 실패 {len(bad)}건: {bad[0]['error']}"
logger.warning("카페24 상품 %s 품목 추가금액 조정 %s건 실패: %s", product_no, len(bad), bad[0]["error"])
return {"count": len(ok), "error": error, "detail": detail}
# ════════════════════════════════════════════════════════════
+18
View File
@@ -1071,6 +1071,24 @@ def parse_additional_amount(value: object) -> str | None:
return f"{number}.00"
def shift_additional_amounts(variants: list[dict], old_price: object, new_price: object) -> list[dict]:
"""판매가 old → new 일 때 품목 판매 가격(판매가 + 추가금액)이 그대로이도록 추가금액을 옮긴 행들.
build_variant_updates 에 그대로 넣는 화면 행 모양. 판매가가 같거나 숫자가 아니면 [].
"""
try:
delta = int(round(float(old_price))) - int(round(float(new_price))) # type: ignore[arg-type]
except (TypeError, ValueError):
return []
if not delta:
return []
return [
{"variant_code": str(v["variant_code"]),
"additional_amount": str(int(round(float(v.get("additional_amount") or 0))) + delta)}
for v in variants if v.get("variant_code")
]
def build_variant_updates(rows: list[dict]) -> list[dict]:
"""화면 행 목록 → PUT /variants `requests` 배열. 바뀔 것이 없는 행은 뺀다."""
out: list[dict] = []
@@ -929,6 +929,7 @@
window.erpAlert("상품명은 비울 수 없습니다.");
return;
}
if ("price" in payload) lines.push("\n※ 옵션 품목은 판매 가격이 그대로이도록 추가금액을 함께 조정합니다.");
window.erpConfirm("다음 항목을 카페24에 바로 반영합니다. 계속할까요?\n\n" + lines.join("\n"))
.then(function (ok) {
if (!ok) return;
@@ -943,7 +944,10 @@
form.querySelector('[name="retail_price"]').value = p.retail_price ? String(parseInt(p.retail_price, 10)) : "";
commitValues(form);
if (p.product_name) paintTitle(p.product_name);
setMsg(msg, (data.changed && data.changed.length) ? "카페24에 반영했습니다." : "변경된 값이 없어 보내지 않았습니다.", "is-ok");
var done = (data.changed && data.changed.length) ? "카페24에 반영했습니다." : "변경된 값이 없어 보내지 않았습니다.";
if (data.variants_shifted) done += " 품목 " + data.variants_shifted + "건 추가금액 조정.";
if (data.variants_error) setMsg(msg, done + " " + data.variants_error, "is-err");
else setMsg(msg, done, "is-ok");
})
.catch(function (err) { setMsg(msg, "실패: " + err.message, "is-err"); })
.then(function () { btn.disabled = false; });
+32
View File
@@ -1304,6 +1304,38 @@ def test_delete_variant_wrapper():
assert client.calls[-1][:2] == ("DELETE", "/admin/products/7/variants/P000000R000A")
def test_shift_additional_amounts_keeps_sale_price():
"""판매가 7900 → 12700: 품목 판매 가격(판매가+추가금액)은 그대로, 추가금액만 -4800."""
variants = [{"variant_code": "P000000R000A", "additional_amount": "0.00"},
{"variant_code": "P000000R000B", "additional_amount": "18000.00"}]
assert store.shift_additional_amounts(variants, "7900.00", "12700.00") == [
{"variant_code": "P000000R000A", "additional_amount": "-4800"},
{"variant_code": "P000000R000B", "additional_amount": "13200"},
]
assert store.shift_additional_amounts(variants, "7900.00", "7900") == []
assert store.shift_additional_amounts(variants, "", "7900") == []
def test_keep_variant_sale_prices_puts_shifted_amounts():
from types import SimpleNamespace
from app.modules.cafe24 import routes_product_info as rpi
client = _RouteClient({
"GET /admin/products/7/options": {"option": {"has_option": "T", "options": []}},
"GET /admin/products/7/variants": {"variants": [
{"variant_code": "P000000R000A", "additional_amount": "6000.00"}]},
"PUT /admin/products/7/variants": {"variants": [
{"variant_code": "P000000R000A", "additional_amount": "1000.00"}]},
})
st = fakes.MemoryStore()
out = rpi._keep_variant_sale_prices(st, SimpleNamespace(client=client), 7, "7900.00", "12900.00")
assert out["count"] == 1 and out["error"] == ""
put = [c for c in client.calls if c[0] == "PUT"][-1]
assert put[2]["requests"] == [{"variant_code": "P000000R000A", "additional_amount": "1000.00"}]
assert st.get_write_snapshot(7)["variants"]["data"]["P000000R000A"]["additional_amount"] == "1000.00"
def test_build_variant_updates():
rows = [
{"variant_code": "p000000r000a", "custom_variant_code": " ABC ", "additional_amount": "1,000", "display": "on"},