diff --git a/app/modules/cafe24/sync_variant_flags.py b/app/modules/cafe24/sync_variant_flags.py new file mode 100644 index 0000000..c1df990 --- /dev/null +++ b/app/modules/cafe24/sync_variant_flags.py @@ -0,0 +1,113 @@ +"""일회성 — 모든 옵션 상품의 품목 진열·판매를 기본몰(1) 값으로 다른 멀티쇼핑몰에 맞춘다. + + # 미리보기(쓰지 않음): 바뀔 품목만 출력 + docker exec dbx-main python -m app.modules.cafe24.sync_variant_flags --shops 3,4 + # 실제 반영 — 출력(바꾸기 전 값 포함)을 파일로 남겨 둔다 + docker exec dbx-main python -m app.modules.cafe24.sync_variant_flags --shops 3,4 --apply > sync.log + +기본몰 값은 화면과 같은 기준(읽기 지연 보정)으로 읽는다. 다른 쇼핑몰에 없는 품목은 건너뛴다. +진열·판매만 보낸다(추가금액·자체코드는 건드리지 않음). 출력의 BEFORE 줄 = 되돌릴 때 쓸 원래 값. +""" +from __future__ import annotations + +import argparse +import json +import os +import sys +from typing import Any + + +def plan_flag_sync(base: list[dict[str, Any]], shop_variants: list[dict[str, Any]]) -> list[dict[str, Any]]: + """기본몰 품목(display/selling = bool) vs 다른 쇼핑몰 GET 품목('T'/'F') → 바꿀 PUT 요청.""" + from app.integrations.cafe24 import products # noqa: WPS433 + + other = {str(v.get("variant_code") or ""): v for v in shop_variants} + out = [] + for v in base: + o = other.get(v["variant_code"]) + if o is None: + continue + req = {k: ("T" if v[k] else "F") for k in ("display", "selling") + if products._flag(o.get(k)) != v[k]} # noqa: SLF001 + if req: + out.append({"variant_code": v["variant_code"], **req}) + return out + + +def main(argv: list[str] | None = None) -> int: + from app.integrations.cafe24 import build_cafe24_api # noqa: WPS433 + + from . import build_cafe24_store # noqa: WPS433 + + ap =argparse.ArgumentParser() + ap.add_argument("--shops", required=True, help="맞출 쇼핑몰 번호(쉼표), 예: 3,4") + ap.add_argument("--apply", action="store_true", help="실제로 카페24에 쓴다(없으면 미리보기)") + args = ap.parse_args(argv) + shops = [int(s) for s in args.shops.split(",") if s.strip().isdigit() and int(s) > 1] + if not shops: + print("--shops 에 2 이상 쇼핑몰 번호가 필요합니다.", file=sys.stderr) + return 2 + + st = build_cafe24_store(dsn=os.environ["CAFE24_DB_URL"]) + try: + return _run(st, build_cafe24_api(st), shops, args.apply) + finally: + st.close() + + +def _run(st: Any, api: Any, shops: list[int], apply: bool) -> int: + from app.integrations.cafe24 import products # noqa: WPS433 + + from . import writes # noqa: WPS433 + from .routes_product_info import _load_options_and_variants # noqa: WPS433 + + items, truncated = products.list_all_products(api.client) + if truncated: + print("상품이 상한(1000)을 넘어 일부만 처리합니다.", file=sys.stderr) + mode = "APPLY" if apply else "DRY-RUN" + total = failed = 0 + for item in items: + no = int(item["product_no"]) + if str(item.get("has_option") or "T") == "F": + continue + try: + base = _load_options_and_variants(st, api, no)["variants"] + except Exception as exc: # noqa: BLE001 — 한 상품 실패가 나머지를 막지 않게 + print(f"ERROR {no} 기본몰 조회 실패: {exc}") + failed += 1 + continue + for shop in shops: + try: + got = api.client.get(f"/admin/products/{no}/variants", params={"shop_no": shop}, product_no=no) + except Exception as exc: # noqa: BLE001 + print(f"ERROR {no} shop {shop} 조회 실패: {exc}") + failed += 1 + continue + shop_vars = got.get("variants") if isinstance(got.get("variants"), list) else [] + reqs = plan_flag_sync(base, shop_vars) + if not reqs: + continue + before = {str(v.get("variant_code")): {"display": v.get("display"), "selling": v.get("selling")} + for v in shop_vars if str(v.get("variant_code")) in {r["variant_code"] for r in reqs}} + print("BEFORE " + json.dumps({"product_no": no, "shop_no": shop, "variants": before}, ensure_ascii=False)) + print(f"{mode} {no} shop {shop}: {len(reqs)}건 " + json.dumps(reqs, ensure_ascii=False)) + total += len(reqs) + if not apply: + continue + bad = [r for r in products.update_variants(api.client, no, reqs, shop_no=shop) + if r["status"] != products.VARIANT_OK] + failed += len(bad) + writes.audit_safe( + st, actor="SYNC_SHOPS", action="update_variants", product_no=no, + result="FAIL" if bad else "SUCCESS", + detail=(f"[쇼핑몰 {shop} 진열·판매 = 기본몰] " + json.dumps(reqs, ensure_ascii=False) + + (f" / 실패 {len(bad)}: {bad[0]['error']}" if bad else ""))[:900], + ) + if bad: + print(f"ERROR {no} shop {shop}: 실패 {len(bad)}건 — {bad[0]['error']}") + print(f"{mode} 끝 — 상품 {len(items)}개 확인, 바꿀/바꾼 품목 {total}건, 오류 {failed}건") + return 1 if failed else 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/app/modules/cafe24/tests/test_cafe24.py b/app/modules/cafe24/tests/test_cafe24.py index 468efed..64a5859 100644 --- a/app/modules/cafe24/tests/test_cafe24.py +++ b/app/modules/cafe24/tests/test_cafe24.py @@ -1091,6 +1091,17 @@ def test_parse_shop_nos(): assert store.parse_shop_nos("2, 3,1,x,0,3") == [1, 2, 3] +def test_plan_flag_sync(): + from app.modules.cafe24.sync_variant_flags import plan_flag_sync + + base = [{"variant_code": "A", "display": True, "selling": False}, + {"variant_code": "B", "display": True, "selling": True}, + {"variant_code": "C", "display": False, "selling": False}] + shop = [{"variant_code": "A", "display": "F", "selling": "F"}, + {"variant_code": "B", "display": "T", "selling": "T"}] # C 는 그 쇼핑몰에 없음 + assert plan_flag_sync(base, shop) == [{"variant_code": "A", "display": "T"}] + + def test_parse_grace_minutes(): assert store.parse_grace_minutes("30") == 30 assert store.parse_grace_minutes("") == store.DEFAULT_READ_LAG_GRACE_MIN diff --git a/docs/CAFE24_MODULE.md b/docs/CAFE24_MODULE.md index 1580155..c5d0090 100644 --- a/docs/CAFE24_MODULE.md +++ b/docs/CAFE24_MODULE.md @@ -487,6 +487,8 @@ cafe24_oauth_tokens 저장 (예 `1,2,3`)의 다른 쇼핑몰에도 같은 값으로 PUT 한다. 추가금액(통화가 다름)·자체코드·순서는 기본몰만. 다른 쇼핑몰 실패는 응답 `shop_failed`·감사 기록에 남기고 화면에 경고(기본몰 반영은 유지). 쇼핑몰 목록 API(`/admin/shops`)는 `mall.read_store` 권한이 필요해 쓰지 않고 번호를 환경변수로 받는다. + 기존 상품 일괄 맞춤(일회성): `docker exec dbx-main python -m app.modules.cafe24.sync_variant_flags + --shops 3,4 [--apply]` — 없으면 미리보기, 출력 `BEFORE` 줄 = 원래 값(되돌리기용), 감사 actor `SYNC_SHOPS`. - "옵션별 상품 이름" 은 옵션값(`option_text`)이고, "옵션별 썸네일" 은 `option_image_file` (+ `option_link_image` 에도 같은 경로) 이며, 화면의 옵션값 썸네일은 **`option_image_file` → `option_link_image` → 그 옵션값을 가진 diff --git a/tests/test_cafe24_db.py b/tests/test_cafe24_db.py index 9199269..3bb5ebd 100644 --- a/tests/test_cafe24_db.py +++ b/tests/test_cafe24_db.py @@ -516,6 +516,31 @@ def test_route_09b_display_selling_to_all_shops(monkeypatch): assert list(resp.json()["shop_failed"]) == ["2"] +def test_sync_variant_flags_script(monkeypatch, capsys): + from app.integrations import cafe24 as integ + from app.integrations.cafe24 import products as cp + from app.modules.cafe24 import sync_variant_flags + + no, cafe = _new_product() + created = _create_options(no, ["A", "B"]) + a = created["variants"][0]["variant_code"] + before = [dict(v) for v in cafe.variants] + assert req("PUT", f"/cafe24/products/{no}/variants", + json={"rows": [{"variant_code": a, "display": "off"}]}).status_code == 200 + cafe.stale_variants = before # 다른 쇼핑몰(과 지연된 GET)은 아직 진열함 + monkeypatch.setenv("CAFE24_DB_URL", os.environ["CAFE24_TEST_DB_URL"]) + monkeypatch.setattr(integ, "build_cafe24_api", lambda st, **kw: fakes.FakeApi(MULTI)) + monkeypatch.setattr(cp, "list_all_products", lambda client: ([{"product_no": no}], False)) + + cafe.calls.clear() + assert sync_variant_flags.main(["--shops", "3"]) == 0 + assert not [c for c in cafe.calls if c[0] == "PUT"] # 미리보기는 쓰지 않음 + assert sync_variant_flags.main(["--shops", "3", "--apply"]) == 0 + puts = [c[2] for c in cafe.calls if c[0] == "PUT"] + assert puts == [{"shop_no": 3, "requests": [{"variant_code": a, "display": "F"}]}] + assert "BEFORE" in capsys.readouterr().out + + def test_route_10_rename_with_lagging_variants_keeps_rows(): no, cafe = _new_product() created = _create_options(no, ["Black", "Red"])