feat(performance): coupang sales - seller-delivery ordersheets + Rocket Growth orders by payment date, reconcile candidates

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-12 17:07:41 +09:00
parent 36283ae265
commit 53bead6691
6 changed files with 567 additions and 46 deletions
@@ -1064,15 +1064,18 @@ def test_coupang_hmac_and_connection_errors():
seen = {}
def fake_get(url, headers=None, timeout=None, status=200, body=None):
seen.setdefault("urls", []).append(url)
seen["url"], seen["auth"] = url, headers["Authorization"]
return httpx.Response(status, json=body if body is not None else {"code": 200, "data": []})
orig = httpx.get
orig = (httpx.get, cp.CALL_INTERVAL_SEC, cp.RG_CALL_INTERVAL_SEC)
try:
httpx.get = fake_get
httpx.get, cp.CALL_INTERVAL_SEC, cp.RG_CALL_INTERVAL_SEC = fake_get, 0, 0
msg = cp.CoupangAdapter().test_connection(ctx)
assert "연결 정상" in msg and "/vendors/A00012345/ordersheets?createdAtFrom=" in seen["url"]
assert "%2B09:00" in seen["url"] and "SK-SECRET" not in seen["auth"]
first, rg = seen["urls"]
assert "연결 정상" in msg and "로켓그로스" in msg and "/vendors/A00012345/ordersheets?createdAtFrom=" in first
assert "%2B09:00" in first and "SK-SECRET" not in seen["auth"]
assert "/rg_open_api/apis/api/v1/vendors/A00012345/rg/orders?paidDateFrom=" in rg
httpx.get = lambda url, headers=None, timeout=None: fake_get(url, headers, timeout, 403, {"message": "Access Denied"})
try:
cp.CoupangAdapter().test_connection(ctx)
@@ -1081,7 +1084,158 @@ def test_coupang_hmac_and_connection_errors():
else:
raise AssertionError("403 이면 인증 실패여야 합니다")
finally:
httpx.get = orig
httpx.get, cp.CALL_INTERVAL_SEC, cp.RG_CALL_INTERVAL_SEC = orig
def _cp_sheet(order_id, box, paid, items, *, status="INSTRUCT", ship=3000):
def money(n):
return {"currencyCode": "KRW", "units": n, "nanos": 0}
return {"shipmentBoxId": box, "orderId": order_id, "orderedAt": paid, "paidAt": paid, "status": status,
"orderer": {"name": "홍길동", "safeNumber": "0502-1111-2222"},
"receiver": {"name": "홍길동", "addr1": "서울 비밀구 1", "receiverNumber": "+82-10-1234-5678"},
"parcelPrintMessage": "문 앞", "shippingPrice": money(ship), "remotePrice": money(0),
"orderItems": [{"sequenceNo": f"{i + 1:03d}", "vendorItemId": 100 + i, "vendorItemName": n,
"sellerProductName": n, "sellerProductItemName": "1개", "shippingCount": q,
"salesPrice": money(p), "orderPrice": money(p * q), "discountPrice": money(dc),
"cancelCount": cc, "holdCountForCancel": 0, "canceled": cc >= q,
"etcInfoValues": ["개인 메모"]}
for i, (n, p, q, dc, cc) in enumerate(items)]}
def _cp_rg(order_id, paid_ms, items):
return {"vendorId": "A00012345", "orderId": order_id, "paidAt": paid_ms,
"orderItems": [{"vendorItemId": 900 + i, "productName": n, "salesQuantity": q, "unitSalesPrice": str(p),
"currency": "KRW"} for i, (n, p, q) in enumerate(items)]}
def _cp_server(sheets_by_status, rg_pages):
"""가짜 쿠팡 — 발주서는 상태별 목록(2쪽까지), 로켓그로스는 nextToken 쪽 넘김. 호출 기록을 남긴다."""
import httpx
from urllib.parse import parse_qs, urlparse
calls = []
def get(url, headers=None, timeout=None):
u = urlparse(url)
q = {k: v[0] for k, v in parse_qs(u.query).items()}
calls.append((u.path, q))
if u.path.endswith("/rg/orders"):
i = int(q.get("nextToken") or 0)
nxt = str(i + 1) if i + 1 < len(rg_pages) else ""
return httpx.Response(200, json={"code": 200, "message": "SUCCESS", "data": rg_pages[i], "nextToken": nxt})
rows = sheets_by_status.get(q["status"], [])
if q.get("nextToken") == "p2":
return httpx.Response(200, json={"code": 200, "data": rows[1:], "nextToken": ""})
return httpx.Response(200, json={"code": 200, "data": rows[:1], "nextToken": "p2" if len(rows) > 1 else ""})
return get, calls
KST_1012_0030_MS = 1791732600000 # 2026-10-12 00:30 KST = 10-11 15:30 UTC
def test_coupang_collect_sales():
"""쿠팡 매출 = 판매자배송 발주서 orderPrice(쿠폰 할인 전) + 로켓그로스 단가 × 수량, 결제일(한국 시간) 기준.
상태 6개 모두 조회·쪽 넘김, 결제일이 기간 밖이면 뺌, 결제 뒤 취소된 줄도 결제일 매출, 같은 발주서 두 번 와도 한 번.
구매자·수령자 정보는 저장하지 않는다."""
import httpx
from app.modules.performance.adapters import coupang as cp
sheets = {
"INSTRUCT": [_cp_sheet(1, 11, "2026-10-12T09:10:00+09:00", [("밀폐용기", 12000, 2, 1000, 0), ("뚜껑", 3000, 1, 0, 0)]),
_cp_sheet(2, 21, "2026-10-12T23:59:00+09:00", [("밀폐용기", 12000, 1, 0, 1)])], # 결제 뒤 취소
"FINAL_DELIVERY": [_cp_sheet(3, 31, "2026-10-11T23:50:00+09:00", [("밀폐용기", 12000, 1, 0, 0)]), # 전날 결제 — 뺌
_cp_sheet(1, 11, "2026-10-12T09:10:00+09:00", [("밀폐용기", 12000, 2, 1000, 0)])], # 같은 발주서 다시
}
rg_pages = [[_cp_rg(70, KST_1012_0030_MS, [("물병", 9900, 3)])], [_cp_rg(71, KST_1012_0030_MS + 3600_000, [("컵", 5000, 1)])]]
get, calls = _cp_server(sheets, rg_pages)
st = FakeStore()
creds = CredentialService(st, lambda: ring())
creds.save(next(a for a in all_adapters() if a.code == "coupang"),
{"vendor_id": "A00012345", "access_key": "AK-1", "secret_key": "SK-SECRET"})
orig = (httpx.get, cp.CALL_INTERVAL_SEC, cp.RG_CALL_INTERVAL_SEC)
httpx.get, cp.CALL_INTERVAL_SEC, cp.RG_CALL_INTERVAL_SEC = get, 0, 0
try:
r = SyncService(st, creds).sync_marketplace("coupang", date(2026, 10, 12), date(2026, 10, 12))
finally:
httpx.get, cp.CALL_INTERVAL_SEC, cp.RG_CALL_INTERVAL_SEC = orig
assert r["ok"], r
ev_ = {k[2]: v for k, v in st.events.items() if k[0] == "coupang"}
assert set(ev_) == {"coupang:1", "coupang:2", "coupang:rg:70", "coupang:rg:71"}, set(ev_)
assert ev_["coupang:1"]["amount"] == 24000 + 3000 and ev_["coupang:1"]["quantity"] == 3 # 배송비 제외, 중복 없음
assert ev_["coupang:1"]["discount_amount"] == 1000 and ev_["coupang:1"]["product_name"] == "밀폐용기 외 1건"
assert ev_["coupang:2"]["amount"] == 12000 and "취소" in ev_["coupang:2"]["order_status"]
assert ev_["coupang:rg:70"]["amount"] == 29700 and ev_["coupang:rg:70"]["sales_date"] == date(2026, 10, 12)
assert ev_["coupang:rg:71"]["amount"] == 5000 # 다음 쪽(nextToken)
assert {q["status"] for p, q in calls if p.endswith("/ordersheets")} == set(cp.STATUSES)
sheet_q = next(q for p, q in calls if p.endswith("/ordersheets"))
assert sheet_q["createdAtFrom"] == "2026-10-11+09:00" and sheet_q["createdAtTo"] == "2026-10-12+09:00" # 주문일 하루 앞부터
assert any(q.get("nextToken") == "p2" and q["status"] == "INSTRUCT" for p, q in calls if p.endswith("/ordersheets"))
rg_q = next(q for p, q in calls if p.endswith("/rg/orders"))
assert rg_q["paidDateFrom"] == "20261012" and rg_q["paidDateTo"] == "20261012"
assert "홍길동" not in repr(st.events) and "비밀구" not in repr(st.events) and "1234-5678" not in repr(st.events)
def test_coupang_spans_and_money():
from app.modules.performance.adapters import coupang as cp
assert cp.spans(date(2026, 1, 1), date(2026, 3, 5), 31) == [
(date(2026, 1, 1), date(2026, 1, 31)), (date(2026, 2, 1), date(2026, 3, 3)), (date(2026, 3, 4), date(2026, 3, 5))]
assert cp._won({"units": 15000, "nanos": 0}) == 15000 and cp._won("27,800") == 27800 and cp._won(None) == 0
assert cp._kst_day("2026-10-12T00:10:00+09:00") == date(2026, 10, 12)
assert cp._kst_day("2026-10-11T15:10:00Z") == date(2026, 10, 12) # UTC → 한국 날짜
assert cp._kst_day(KST_1012_0030_MS) == date(2026, 10, 12)
assert cp._kst_day("2026-10-12") == date(2026, 10, 12) and cp._kst_day("") is None
def test_coupang_reconcile_candidates_hide_personal():
"""원본 데이터 확인 — 날짜별 후보 금액(할인 전·후, 취소분 뺀 값, 로켓그로스)·판매량, 개인정보 항목은 아예 없음.
로켓그로스만 실패해도 판매자배송 결과는 보여 준다."""
import httpx
from app.modules.performance.adapters import coupang as cp
from app.modules.performance.adapters.base import AdapterContext
class Creds(dict):
def get(self, k, default=""):
return dict.get(self, k, default)
def has(self, k):
return bool(dict.get(self, k))
ctx = AdapterContext(code="coupang", credentials=Creds(vendor_id="A00012345", access_key="AK", secret_key="SK"))
sheets = {"INSTRUCT": [_cp_sheet(1, 11, "2026-10-12T09:10:00+09:00", [("밀폐용기", 12000, 2, 1000, 0)]),
_cp_sheet(2, 21, "2026-10-13T10:00:00+09:00", [("밀폐용기", 12000, 1, 0, 1)])]}
get, _calls = _cp_server(sheets, [[_cp_rg(70, KST_1012_0030_MS, [("물병", 9900, 3)])]])
orig = (httpx.get, cp.CALL_INTERVAL_SEC, cp.RG_CALL_INTERVAL_SEC)
httpx.get, cp.CALL_INTERVAL_SEC, cp.RG_CALL_INTERVAL_SEC = get, 0, 0
try:
rec = cp.CoupangAdapter().reconcile(ctx, date(2026, 10, 12), to=date(2026, 10, 13))
cands = {c["label"][:1]: c for c in rec["refund_candidates"]}
assert cands["①"]["days"] == {"2026-10-12": 24000 + 29700, "2026-10-13": 12000}
assert cands["②"]["days"]["2026-10-12"] == 24000 and cands["③"]["days"]["2026-10-12"] == 23000
assert cands["④"]["days"]["2026-10-13"] == 0 and cands["⑤"]["days"]["2026-10-12"] == 29700
assert next(c for c in rec["refund_candidates"] if c["label"].startswith("판매량"))["days"]["2026-10-12"] == 5
assert rec["days"][0] == {"date": "2026-10-12", "orders": 2, "amount": 53700, "claimed": 0, "ship": 3000}
assert rec["days"][1]["claimed"] == 12000 and rec["candidates_title"]
names = {f["name"] for p in rec["probes"] if p["ok"] for f in p["fields"]}
assert "orderItems.orderPrice.units" in names and not any(n.startswith(("orderer", "receiver")) for n in names)
assert "홍길동" not in repr(rec) and "비밀구" not in repr(rec) and "개인 메모" not in repr(rec) and "문 앞" not in repr(rec)
def deny_rg(url, headers=None, timeout=None): # 로켓그로스만 거부(403)
if "/rg/orders" in url:
return httpx.Response(403, json={"message": "Access Denied"})
return get(url, headers, timeout)
httpx.get = deny_rg
rec2 = cp.CoupangAdapter().reconcile(ctx, date(2026, 10, 12))
p = {x["key"]: x for x in rec2["probes"]}
assert p["seller"]["ok"] and not p["rg"]["ok"] and "403" in p["rg"]["error"]
assert rec2["refund_candidates"][0]["error"] and rec2["refund_candidates"][1]["days"]["2026-10-12"] == 24000
finally:
httpx.get, cp.CALL_INTERVAL_SEC, cp.RG_CALL_INTERVAL_SEC = orig
def test_elevenst_connection():