From 2465874198564501291bea854ee527df6e161014 Mon Sep 17 00:00:00 2001 From: king Date: Sun, 15 Nov 2026 03:15:26 +0900 Subject: [PATCH] =?UTF-8?q?feat(=EC=B9=B4=ED=8E=9824):=20=ED=8C=90?= =?UTF-8?q?=EB=A7=A4=EA=B0=80=20=EB=B3=80=EA=B2=BD=20=EC=8B=9C=20=ED=92=88?= =?UTF-8?q?=EB=AA=A9=20=ED=8C=90=EB=A7=A4=20=EA=B0=80=EA=B2=A9=20=EC=9C=A0?= =?UTF-8?q?=EC=A7=80=20=E2=80=94=20=EC=B6=94=EA=B0=80=EA=B8=88=EC=95=A1=20?= =?UTF-8?q?=EC=9E=90=EB=8F=99=20=EC=A1=B0=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 기본 정보에서 판매가를 바꾸면 같은 잠금 안에서 옵션 품목 추가금액을 (옛 판매가 - 새 판매가)만큼 옮겨 품목 판매 가격(판매가+추가금액)을 그대로 둔다. 품목 조정 실패는 판매가 저장을 되돌리지 않고 화면 메시지로 알린다. Co-Authored-By: Claude Opus 5.5 --- app/modules/cafe24/CLAUDE.md | 1 + app/modules/cafe24/routes_product_info.py | 36 ++++++++++++++++++- app/modules/cafe24/store.py | 18 ++++++++++ .../cafe24/templates/cafe24/products.html | 6 +++- app/modules/cafe24/tests/test_cafe24.py | 32 +++++++++++++++++ 5 files changed, 91 insertions(+), 2 deletions(-) diff --git a/app/modules/cafe24/CLAUDE.md b/app/modules/cafe24/CLAUDE.md index 6055895..a0f011c 100644 --- a/app/modules/cafe24/CLAUDE.md +++ b/app/modules/cafe24/CLAUDE.md @@ -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/` 부터). diff --git a/app/modules/cafe24/routes_product_info.py b/app/modules/cafe24/routes_product_info.py index 56766fb..de6bf44 100644 --- a/app/modules/cafe24/routes_product_info.py +++ b/app/modules/cafe24/routes_product_info.py @@ -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} # ════════════════════════════════════════════════════════════ diff --git a/app/modules/cafe24/store.py b/app/modules/cafe24/store.py index 7380c0e..44c5dcf 100644 --- a/app/modules/cafe24/store.py +++ b/app/modules/cafe24/store.py @@ -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] = [] diff --git a/app/modules/cafe24/templates/cafe24/products.html b/app/modules/cafe24/templates/cafe24/products.html index aa4bc3a..41bfafa 100644 --- a/app/modules/cafe24/templates/cafe24/products.html +++ b/app/modules/cafe24/templates/cafe24/products.html @@ -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; }); diff --git a/app/modules/cafe24/tests/test_cafe24.py b/app/modules/cafe24/tests/test_cafe24.py index 64a5859..53337f1 100644 --- a/app/modules/cafe24/tests/test_cafe24.py +++ b/app/modules/cafe24/tests/test_cafe24.py @@ -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"},