"""Seed data for the COD suite (Phase 8). * :func:`seed_cod_eval` (``ecommerce/cod``): the small store (``seed_small``) plus a WhatsApp account (templates ``cod_confirm_v1``, ``cod_advance_payment_v1``, ``order_update``), the offline mock courier as the default courier account, COD anchors with known risk bands and confirmation states (:data:`COD_ANCHORS`), and a delivered-parcel ledger for reconciliation scenarios (:data:`RECON_ANCHORS`). * :func:`seed_cod_batch`: the Phase 8 exit-test store: history, ``n`` new pending COD orders with varied risk, and delivered/remitted parcels with **planted** reconciliation problems (returned in :class:`CodBatch.planted` with the statement CSVs that expose them). """ from __future__ import annotations import csv import io import random import uuid from dataclasses import dataclass, field from datetime import UTC, datetime, timedelta from typing import Any from core.channels.models import ChannelAccount from core.db.session import Database from packs.ecommerce.models import Customer, Message, Order, OrderItem, Product, Shipment from packs.ecommerce.models_cod import CodConfirmation, CourierAccount from packs.ecommerce.seed import ( CITIES, CITY_WEIGHTS, FIRST_NAMES, LAST_NAMES, PRODUCTS, SHIPPING_FEE, seed_ecommerce, ) WHATSAPP_TEMPLATES = { "cod_confirm_v1": {"language": "en", "category": "utility"}, "cod_advance_payment_v1": {"language": "en", "category": "utility"}, "order_update": {"language": "en", "category": "utility"}, } PHONE_NUMBER_ID = "106540352242922" # Anchors the COD eval scenarios refer to (bands as scored by the shipped model). COD_ANCHORS = { "ORD-1101": "Ayesha (repeat, delivered before), Karachi, complete address: LOW risk", "ORD-1102": "new customer Lahore, Rs 9,450, evening: MEDIUM risk", "ORD-1103": "Quetta, phone used under 3 names, 2 earlier RTOs, 2am, vague address: HIGH", "ORD-1104": "Kiran (0311-1104104): MEDIUM, confirmation request already sent (pending)", "ORD-1105": "Shahid (0311-1105105): HIGH, confirmation request already sent (pending)", "ORD-1107": "Nimra (0311-1107107): confirmation sent 30h ago, deadline passed", } # Delivered COD parcels for reconciliation scenarios: tracking -> (order, cod amount). RECON_ANCHORS = { "PXR0001": ("ORD-1201", 4750), "PXR0002": ("ORD-1202", 3450), "PXR0003": ("ORD-1203", 4050), } def _items(sku_qty: list[tuple[str, int]]) -> tuple[list[tuple[str, int, int]], int, int]: price = {p[0]: p[3] for p in PRODUCTS} lines = [(sku, q, price[sku]) for sku, q in sku_qty] subtotal = sum(q * p for _, q, p in lines) return lines, subtotal, subtotal + SHIPPING_FEE async def _channel_and_courier(s: Any, tenant_id: uuid.UUID, *, postex: bool = False) -> None: s.add( ChannelAccount( tenant_id=tenant_id, channel="whatsapp", provider="meta_cloud", config={"phone_number_id": PHONE_NUMBER_ID, "templates": WHATSAPP_TEMPLATES}, secret_ref="demo-whatsapp-token", # noqa: S106 a reference, not a secret cursor={}, ) ) s.add( CourierAccount( tenant_id=tenant_id, courier="mock", enabled=True, is_default=not postex, allow_unverified=False, config={}, ) ) if postex: s.add( CourierAccount( tenant_id=tenant_id, courier="postex", enabled=True, is_default=True, allow_unverified=False, config={"pickup_address_code": "001"}, secret_ref="demo-postex-token", # noqa: S106 a reference, not a secret ) ) async def _add_order( s: Any, tenant_id: uuid.UUID, products: dict[str, uuid.UUID], *, number: str, customer: Customer | None, name: str, phone: str, city: str, address: str, items: list[tuple[str, int]], created_at: datetime, status: str = "pending", confirmation_status: str | None = "pending", shipment: dict[str, Any] | None = None, ) -> Order: lines, subtotal, total = _items(items) o = Order( id=uuid.uuid4(), tenant_id=tenant_id, number=number, source="seed", customer_id=customer.id if customer else None, ship_name=name, ship_phone=phone, ship_address=address, city=city, status=status, fulfillment_status="fulfilled" if shipment else "unfulfilled", payment_method="COD", confirmation_status=confirmation_status, currency="PKR", subtotal=subtotal, shipping_fee=SHIPPING_FEE, discount=0, total=total, refunded=0, tags=[], notes="", created_at=created_at, updated_at=created_at, cancelled_at=created_at + timedelta(hours=3) if status == "cancelled" else None, ) s.add(o) await s.flush() for sku, q, price in lines: s.add( OrderItem( tenant_id=tenant_id, order_id=o.id, product_id=products.get(sku), sku=sku, title=sku, quantity=q, unit_price=price, ) ) if shipment: s.add( Shipment( tenant_id=tenant_id, order_id=o.id, cod_amount=total, created_at=shipment.get("shipped_at", created_at), **shipment, ) ) return o async def _products(s: Any) -> dict[str, uuid.UUID]: from sqlalchemy import select return {sku: pid for sku, pid in (await s.execute(select(Product.sku, Product.id))).all()} async def _customer( s: Any, tenant_id: uuid.UUID, name: str, phone: str, city: str, email: str | None = None ) -> Customer: c = Customer( id=uuid.uuid4(), tenant_id=tenant_id, name=name, email=email, phone=phone, city=city, tags=[], ) s.add(c) await s.flush() return c def _pkt(now: datetime, hour: int, days_ago: int = 0) -> datetime: """A UTC timestamp whose Pakistan-time hour is ``hour`` (PKT = UTC+5).""" base = (now - timedelta(days=days_ago)).replace(minute=12, second=0, microsecond=0) at = base.replace(hour=(hour - 5) % 24) - (timedelta(days=1) if hour - 5 < 0 else timedelta()) return at - timedelta(days=1) if at > now else at # ------------------------------------------------------------------ eval store async def seed_cod_eval(db: Database, tenant_id: uuid.UUID) -> dict[str, Any]: from sqlalchemy import select summary = await seed_ecommerce(db, tenant_id, n_orders=12) now = datetime.now(UTC) async with db.session(tenant_id=tenant_id) as s, s.begin(): await _channel_and_courier(s, tenant_id) products = await _products(s) ayesha = ( await s.execute(select(Customer).where(Customer.phone == "0301-2345678")) ).scalar_one() await _add_order( s, tenant_id, products, number="ORD-1101", customer=ayesha, name=ayesha.name, phone="0301-2345678", city="Karachi", address="House 10, Street 3, Gulshan-e-Iqbal", items=[("PRAYERMAT", 1)], created_at=_pkt(now, 14, 1), ) hamza = await _customer( s, tenant_id, "Hamza Qureshi", "0312-1102102", "Lahore", "hamza.qureshi@example.pk" ) await _add_order( s, tenant_id, products, number="ORD-1102", customer=hamza, name=hamza.name, phone="0312-1102102", city="Lahore", address="House 45, Block C, Model Town", items=[("LAWN-3PC-01", 1), ("ATTAR-OUD", 1), ("PRAYERMAT", 1)], created_at=_pkt(now, 21, 0), ) shahid = await _customer(s, tenant_id, "Shahid Hussain", "0311-1103103", "Quetta") for i, alias in enumerate(("Shahid H", "S. Hussain")): placed = now - timedelta(days=40 - 10 * i) await _add_order( s, tenant_id, products, number=f"ORD-109{i}", customer=None, name=alias, phone="0311-1103103", city="Quetta", address="near masjid", status="returned", confirmation_status="confirmed", items=[("EARBUDS-X2", 1)], created_at=placed, shipment={ "courier": "TCS", "tracking_number": f"TC9000109{i}", "status": "returned", "shipped_at": placed + timedelta(days=1), "last_event": "Returned to shipper: refused", }, ) await _add_order( s, tenant_id, products, number="ORD-1103", customer=shahid, name=shahid.name, phone="0311-1103103", city="Quetta", address="near masjid", items=[("WATCH-CL1", 2)], created_at=_pkt(now, 2, 0), ) # Confirmations already in flight (sent and delivered by the channel worker). for number, name, phone, city, address, items, band, hours_ago in ( ( "ORD-1104", "Kiran Akhtar", "0311-1104104", "Lahore", "House 7, Street 9, Johar Town", [("LAWN-2PC-02", 2)], "medium", 2, ), ( "ORD-1105", "Shahid Baig", "0311-1105105", "Peshawar", "Saddar", [("EARBUDS-X2", 2)], "high", 3, ), ( "ORD-1107", "Nimra Rana", "0311-1107107", "Multan", "House 3, Street 2, Cantt", [("KHUSSA-01", 1)], "medium", 30, ), ): c = await _customer(s, tenant_id, name, phone, city) sent = now - timedelta(hours=hours_ago) o = await _add_order( s, tenant_id, products, number=number, customer=c, name=name, phone=phone, city=city, address=address, items=items, created_at=sent - timedelta(minutes=5), ) o.risk_band = band o.risk_score = 0.3 if band == "medium" else 0.6 o.risk_reasons = ["seeded"] msg = Message( tenant_id=tenant_id, direction="outbound", channel="whatsapp", to_address=phone, body=f"[template cod_confirm_v1] {name.split()[0]}, {number}", template="cod_confirm_v1", template_params={ "language": "en", "category": "utility", "params": [name.split()[0], number], "buttons": [f"CONFIRM:{number}", f"CANCEL:{number}"], }, status="sent", send_after=sent, sent_at=sent, provider_message_id=f"wamid.SEED{number[4:]}", customer_id=c.id, order_id=o.id, created_by="seed", created_at=sent, ) s.add(msg) await s.flush() s.add( CodConfirmation( tenant_id=tenant_id, order_id=o.id, attempt=1, channel="whatsapp", band=band, status="pending", phone=phone, message_id=msg.id, deadline_at=sent + timedelta(hours=24), created_at=sent, ) ) # Delivered COD parcels awaiting remittance (reconciliation scenarios). bilal = ( await s.execute(select(Customer).where(Customer.phone == "0321-4567890")) ).scalar_one() for tn, (number, _amount) in RECON_ANCHORS.items(): items = { "ORD-1201": [("LAWN-3PC-01", 1)], "ORD-1202": [("LAWN-2PC-02", 1)], "ORD-1203": [("PSHWR-CHPL", 1)], }[number] placed = now - timedelta(days=6) await _add_order( s, tenant_id, products, number=number, customer=bilal, name=bilal.name, phone=bilal.phone or "", city="Lahore", address="House 11, Street 4, Johar Town", items=items, created_at=placed, status="delivered", confirmation_status="confirmed", shipment={ "courier": "PostEx", "tracking_number": tn, "status": "delivered", "shipped_at": placed + timedelta(days=1), "delivered_at": placed + timedelta(days=3), "last_event": "Delivered", }, ) return {"base": summary, "anchors": COD_ANCHORS} # ------------------------------------------------------------------ exit-test batch @dataclass class CodBatch: tenant_id: uuid.UUID orders: list[str] planted: dict[str, set[str]] = field(default_factory=dict) # kind -> tracking numbers statements: dict[str, str] = field(default_factory=dict) # statement ref -> CSV def _phone(rng: random.Random, valid: bool = True) -> str: if not valid: return f"03{rng.randint(0, 4)}{rng.randint(0, 9)}-{rng.randint(0, 99_999):05d}" return f"03{rng.randint(0, 4)}{rng.randint(0, 9)}-{rng.randint(0, 9_999_999):07d}" def _csv(rows: list[dict[str, Any]]) -> str: buf = io.StringIO() w = csv.DictWriter( buf, fieldnames=[ "tracking_number", "order_ref", "cod_amount", "fee", "net_amount", "delivered_on", ], ) w.writeheader() for r in rows: w.writerow(r) return buf.getvalue() async def seed_cod_batch( db: Database, tenant_id: uuid.UUID, n: int = 500, *, seed: int = 8 ) -> CodBatch: """History + ``n`` pending COD orders + a reconciliation ledger with planted problems.""" await seed_ecommerce(db, tenant_id, n_orders=40) rng = random.Random(seed) # noqa: S311 synthetic data now = datetime.now(UTC) batch = CodBatch(tenant_id=tenant_id, orders=[]) async with db.session(tenant_id=tenant_id) as s, s.begin(): await _channel_and_courier(s, tenant_id) products = await _products(s) skus = [p[0] for p in PRODUCTS] cities = list(CITY_WEIGHTS) weights = list(CITY_WEIGHTS.values()) pool: list[tuple[Customer, str]] = [] hist_no = 30000 for _ in range(int(n * 0.6)): name = f"{rng.choice(FIRST_NAMES)} {rng.choice(LAST_NAMES)}" city = rng.choices(cities, weights=weights)[0] phone = _phone(rng, valid=rng.random() > 0.04) c = await _customer(s, tenant_id, name, phone, city) area = rng.choice(CITIES[city][1]) address = ( f"House {rng.randint(1, 400)}, Street {rng.randint(1, 30)}, {area}" if rng.random() > 0.15 else rng.choice(["near masjid", "main bazar", f"{area}", "opposite school"]) ) pool.append((c, address)) # history: some delivered, some returned (RTO), some cancelled for _ in range(rng.choices([0, 1, 2, 3], weights=[45, 30, 15, 10])[0]): hist_no += 1 outcome = rng.choices(["delivered", "returned", "cancelled"], weights=[75, 18, 7])[ 0 ] placed = now - timedelta(days=rng.randint(20, 200)) ship = None if outcome != "cancelled": ship = { "courier": "PostEx", "tracking_number": f"PXH{hist_no}", "status": outcome, "shipped_at": placed + timedelta(days=1), "delivered_at": placed + timedelta(days=3) if outcome == "delivered" else None, "remitted_at": placed + timedelta(days=10) if outcome == "delivered" else None, } await _add_order( s, tenant_id, products, number=f"ORD-{hist_no}", customer=c, name=c.name, phone=phone, city=city, address=address, status=outcome, confirmation_status="rejected" if outcome == "cancelled" else "confirmed", items=[(rng.choice(skus), 1)], created_at=placed, shipment=ship, ) shared_phones = [_phone(rng) for _ in range(12)] for i in range(n): number = f"ORD-{20001 + i}" if rng.random() < 0.06: # one phone, many names phone = rng.choice(shared_phones) name = f"{rng.choice(FIRST_NAMES)} {rng.choice(LAST_NAMES)}" city = rng.choices(cities, weights=weights)[0] cust, address = None, rng.choice(["near chowk", f"{CITIES[city][1][0]}"]) else: cust, address = rng.choice(pool) name, phone, city = cust.name, str(cust.phone), str(cust.city) n_items = rng.choices([1, 2, 3], weights=[60, 30, 10])[0] items = [ (sku, rng.choices([1, 2], weights=[85, 15])[0]) for sku in rng.sample(skus, n_items) ] await _add_order( s, tenant_id, products, number=number, customer=cust, name=name, phone=phone, city=city, address=address, items=items, created_at=now - timedelta(minutes=rng.randint(5, 24 * 60)), ) batch.orders.append(number) # Reconciliation ledger: delivered COD parcels (15 days ago), a statement for most of # them, and planted problems. delivered: list[tuple[str, str, int]] = [] # (tracking, order, amount) for i in range(60): c, address = pool[i] placed = now - timedelta(days=17) tn = f"PXR{50001 + i}" o = await _add_order( s, tenant_id, products, number=f"ORD-{50001 + i}", customer=c, name=c.name, phone=str(c.phone), city=str(c.city), address=address, status="delivered", confirmation_status="confirmed", items=[(skus[i % len(skus)], 1)], created_at=placed, shipment={ "courier": "PostEx", "tracking_number": tn, "status": "delivered", "shipped_at": placed + timedelta(days=1), "delivered_at": placed + timedelta(days=2), "last_event": "Delivered", }, ) delivered.append((tn, o.number, o.total)) in_transit: list[tuple[str, str, int]] = [] for i in range(3): c, address = pool[60 + i] placed = now - timedelta(days=4) tn = f"PXT{60001 + i}" o = await _add_order( s, tenant_id, products, number=f"ORD-{60001 + i}", customer=c, name=c.name, phone=str(c.phone), city=str(c.city), address=address, status="shipped", confirmation_status="confirmed", items=[(skus[i], 1)], created_at=placed, shipment={ "courier": "PostEx", "tracking_number": tn, "status": "in_transit", "shipped_at": placed + timedelta(days=1), "last_event": "In transit", }, ) in_transit.append((tn, o.number, o.total)) day = (now - timedelta(days=15)).date().isoformat() def line(tn: str, ref: str, amount: int) -> dict[str, Any]: return { "tracking_number": tn, "order_ref": ref, "cod_amount": amount, "fee": 180, "net_amount": amount - 180, "delivered_on": day, } missing = delivered[:6] mismatched = delivered[6:11] duplicated = delivered[11:13] rows = [line(tn, ref, amt) for tn, ref, amt in delivered[6:]] for r in rows: if r["tracking_number"] in {m[0] for m in mismatched}: r["cod_amount"] -= 150 r["net_amount"] -= 150 rows += [line(tn, ref, amt) for tn, ref, amt in in_transit] rows += [line("PXU99001", "ORD-99001", 2500), line("PXU99002", "ORD-99002", 3100)] batch.statements["PX-2026-11-A"] = _csv(rows) batch.statements["PX-2026-11-B"] = _csv([line(tn, ref, amt) for tn, ref, amt in duplicated]) batch.planted = { "missing_remittance": {m[0] for m in missing}, "amount_mismatch": {m[0] for m in mismatched}, "remitted_not_delivered": {t[0] for t in in_transit}, "unknown_tracking": {"PXU99001", "PXU99002"}, "duplicate_remittance": {d[0] for d in duplicated}, } return batch async def seed_cod_recon_eval(db: Database, tenant_id: uuid.UUID) -> dict[str, Any]: """``ecommerce/cod-recon``: :func:`seed_cod_eval` plus one imported PostEx statement (``PX-SEED-1``, not yet reconciled) with a matched parcel (PXR0001), an amount mismatch (PXR0002: Rs 3,300 for Rs 3,450), an unknown parcel (PXU0404) and a parcel that was returned, not delivered (TC90001090). PXR0003 has no remittance yet.""" from packs.ecommerce.models_cod import CodRemittance, CodRemittanceLine out = await seed_cod_eval(db, tenant_id) from sqlalchemy import select now = datetime.now(UTC) async with db.session(tenant_id=tenant_id) as s, s.begin(): ships = { sh.tracking_number: sh for sh in ( await s.execute( select(Shipment).where( Shipment.tracking_number.in_(["PXR0001", "PXR0002", "TC90001090"]) ) ) ).scalars() } lines = [ ("PXR0001", "ORD-1201", 4750, "matched"), ("PXR0002", "ORD-1202", 3300, "amount_mismatch"), ("PXU0404", "ORD-9404", 1999, "unknown_tracking"), ("TC90001090", "ORD-1090", 2450, "not_delivered"), ] rem = CodRemittance( tenant_id=tenant_id, courier="PostEx", statement_ref="PX-SEED-1", source="csv", line_count=len(lines), total_cod=sum(x[2] for x in lines), total_fees=180 * len(lines), total_net=sum(x[2] - 180 for x in lines), imported_by="seed", imported_at=now - timedelta(hours=1), ) s.add(rem) await s.flush() for tn, ref, amount, status in lines: sh = ships.get(tn) if sh is not None and status in ("matched", "amount_mismatch"): sh.remitted_at = now - timedelta(hours=1) s.add( CodRemittanceLine( tenant_id=tenant_id, remittance_id=rem.id, tracking_number=tn, order_ref=ref, cod_amount=amount, fee=180, net_amount=amount - 180, shipment_id=sh.id if sh else None, match_status=status, ) ) return out