Spaces:
Running

Aynkhn's picture
Deploy WorkPilot demo (part 2)
0776bd5 verified
Raw History Blame Contribute Delete
23.8 kB
"""COD confirmation tools (Phase 8): RTO risk scoring and the confirmation state machine.
| tool | tier | notes |
|------------------------------|------|----------------------------------------------------------|
| score_order_risk | T1 | LightGBM + TreeSHAP reasons -> ecom_rto_scores, order |
| get_confirmation_context | T0 | open attempt, WhatsApp window/templates, COD settings |
| find_open_confirmation | T0 | pending attempt by order number or customer phone |
| start_confirmation | T1 | open an attempt (deadline = now + timeout) |
| resolve_confirmation | T1 | confirmed / rejected (customer reply, auto, operator) |
| expire_confirmations | T1 | pending attempts past their deadline -> no_answer |
| create_payment_link | T1 | advance payment link (JazzCash/Easypaisa, stub provider) |
| cancel_order | T2 | auto only for one order the customer rejected |
| update_shipping_address | T2 | always reviewed (address changes are a fraud vector) |
Tenant settings (``tenants.settings["cod"]``), all optional::
{"confirm_on_create": false, # chain confirmation after orders/create webhooks
"confirm_timeout_hours": 24, # no answer after this -> no_answer + escalation
"bands": {"medium": 0.15, "high": 0.40},
"advance_payment": {"enabled": false, "provider": "jazzcash", "percent": 10,
"min_amount": 200}}
"""
from __future__ import annotations
import hashlib
import uuid
from datetime import UTC, datetime, timedelta
from typing import Any, Literal, Protocol
from pydantic import BaseModel, Field, model_validator
from sqlalchemy import select, update
from core.channels.phone import to_local
from core.channels.registry import account_for
from core.tools.spec import ToolContext, ToolResult
from packs.ecommerce.ml import rto_risk
from packs.ecommerce.ml.features import load_features
from packs.ecommerce.models import Customer, Order, Shipment
from packs.ecommerce.models_cod import CodConfirmation, RtoScore
from packs.ecommerce.outbox import window_open
from packs.ecommerce.tools.channels import phone_variants
from packs.ecommerce.tools.common import dry, fail, tenant_settings
from packs.ecommerce.views import ORDER_NUMBER, order_by_number
DEFAULT_TIMEOUT_HOURS = 24.0
COD_TEMPLATES = ("cod_confirm_v1", "cod_advance_payment_v1")
CUSTOMER_SOURCES = ("button", "keyword", "extractor")
FINAL_ORDER_STATES = ("shipped", "delivered", "returned", "cancelled")
async def cod_settings(ctx: ToolContext) -> dict[str, Any]:
return dict((await tenant_settings(ctx)).get("cod") or {})
def timeout_hours(settings: dict[str, Any]) -> float:
return float(settings.get("confirm_timeout_hours", DEFAULT_TIMEOUT_HOURS))
async def _order(ctx: ToolContext, number: str) -> Order | None:
return await order_by_number(ctx.session, number)
async def order_phone(ctx: ToolContext, o: Order) -> str | None:
"""The number on file for the order: the customer's phone, else the shipping phone."""
phone = None
if o.customer_id is not None:
phone = (
await ctx.session.execute(select(Customer.phone).where(Customer.id == o.customer_id))
).scalar_one_or_none()
return to_local(phone or o.ship_phone) or (phone or o.ship_phone)
async def pending_attempt(ctx: ToolContext, order_id: uuid.UUID) -> CodConfirmation | None:
return (
await ctx.session.execute(
select(CodConfirmation)
.where(CodConfirmation.order_id == order_id, CodConfirmation.status == "pending")
.order_by(CodConfirmation.created_at.desc())
.limit(1)
)
).scalar_one_or_none()
async def latest_attempt(ctx: ToolContext, order_id: uuid.UUID) -> CodConfirmation | None:
return (
await ctx.session.execute(
select(CodConfirmation)
.where(CodConfirmation.order_id == order_id)
.order_by(CodConfirmation.created_at.desc())
.limit(1)
)
).scalar_one_or_none()
def attempt_view(a: CodConfirmation | None, number: str | None = None) -> dict[str, Any] | None:
if a is None:
return None
return {
"attempt_id": str(a.id),
"order_number": number,
"attempt": a.attempt,
"channel": a.channel,
"band": a.band,
"status": a.status,
"decision": a.decision,
"decision_source": a.decision_source,
"message_id": str(a.message_id) if a.message_id else None,
"payment_link": a.payment_link,
"deadline_at": a.deadline_at.isoformat() if a.deadline_at else None,
"resolved_at": a.resolved_at.isoformat() if a.resolved_at else None,
"created_at": a.created_at.isoformat() if a.created_at else None,
}
# ---------------------------------------------------------------- score_order_risk (T1)
class ScoreRiskIn(BaseModel):
order_number: str = Field(pattern=ORDER_NUMBER)
stage: Literal["created", "confirmation", "manual"] = "manual"
def risk_card(s: rto_risk.Scored) -> dict[str, Any]:
"""The risk card UI payload: score, band and the top three reasons."""
return {
"score": s.score,
"band": s.band,
"reasons": s.reason_texts,
"reason_details": s.reasons,
"model_version": s.model_version,
}
async def score_order_risk(args: BaseModel, ctx: ToolContext) -> ToolResult:
a = ScoreRiskIn.model_validate(args)
o = await _order(ctx, a.order_number)
if o is None:
return fail(f"order {a.order_number} not found")
features = await load_features(ctx.session, o)
bands = (await cod_settings(ctx)).get("bands") or None
scored = rto_risk.get_model().score(features, bands)
card = {"order_number": o.number, **risk_card(scored), "features": features}
if ctx.dry_run:
return dry(card)
ctx.session.add(
RtoScore(
tenant_id=ctx.tenant_id,
order_id=o.id,
score=scored.score,
band=scored.band,
reasons=scored.reasons,
model_version=scored.model_version,
features=features,
stage=a.stage,
)
)
o.risk_score = scored.score
o.risk_band = scored.band
o.risk_reasons = scored.reason_texts
o.updated_at = datetime.now(UTC)
await ctx.session.flush()
return ToolResult(ok=True, data=card)
# ------------------------------------------------------- confirmation context (T0)
class OrderOnlyIn(BaseModel):
order_number: str = Field(pattern=ORDER_NUMBER)
async def get_confirmation_context(args: BaseModel, ctx: ToolContext) -> ToolResult:
"""Everything the confirmation graph needs to choose a route (no customer text)."""
a = OrderOnlyIn.model_validate(args)
o = await _order(ctx, a.order_number)
if o is None:
return fail(f"order {a.order_number} not found")
settings = await cod_settings(ctx)
phone = await order_phone(ctx, o)
acct = await account_for(ctx.session, "whatsapp")
templates = dict((acct.config or {}).get("templates") or {}) if acct is not None else {}
advance = dict(settings.get("advance_payment") or {})
pending = await pending_attempt(ctx, o.id)
customer_name = o.ship_name
if o.customer_id is not None:
customer_name = (
await ctx.session.execute(select(Customer.name).where(Customer.id == o.customer_id))
).scalar_one_or_none() or o.ship_name
return ToolResult(
ok=True,
data={
"order_number": o.number,
"payment_method": o.payment_method,
"status": o.status,
"confirmation_status": o.confirmation_status,
"total": o.total,
"customer_first_name": (customer_name or "Customer").split()[0],
"phone": phone,
"risk_band": o.risk_band,
"confirm_on_create": bool(settings.get("confirm_on_create", False)),
"timeout_hours": timeout_hours(settings),
"whatsapp_connected": acct is not None and acct.enabled,
"templates": sorted(t for t in templates if t in (*COD_TEMPLATES, "order_update")),
"window_open": phone is not None and await window_open(ctx.session, phone),
"advance_payment": {
"enabled": bool(advance.get("enabled", False)),
"provider": str(advance.get("provider") or "jazzcash"),
"amount": advance_amount(o.total, advance),
},
"open_attempt": attempt_view(pending, o.number),
},
)
def advance_amount(total: int, advance: dict[str, Any]) -> int:
pct = float(advance.get("percent", 10))
floor = int(advance.get("min_amount", 200))
return min(total, max(floor, round(total * pct / 100)))
# ------------------------------------------------------- find_open_confirmation (T0)
class FindOpenIn(BaseModel):
order_number: str | None = Field(default=None, pattern=ORDER_NUMBER)
phone: str | None = Field(default=None, min_length=7, max_length=20)
@model_validator(mode="after")
def one(self) -> FindOpenIn:
if not (self.order_number or self.phone):
raise ValueError("give order_number or phone")
return self
async def find_open_confirmation(args: BaseModel, ctx: ToolContext) -> ToolResult:
a = FindOpenIn.model_validate(args)
q = (
select(CodConfirmation, Order.number)
.join(Order, Order.id == CodConfirmation.order_id)
.where(CodConfirmation.status == "pending")
)
if a.order_number:
q = q.where(Order.number == a.order_number)
if a.phone:
q = q.where(CodConfirmation.phone.in_(phone_variants(a.phone)))
row = (
await ctx.session.execute(q.order_by(CodConfirmation.created_at.desc()).limit(1))
).first()
return ToolResult(ok=True, data={"attempt": attempt_view(row[0], row[1]) if row else None})
# ------------------------------------------------------------ start_confirmation (T1)
class StartConfirmationIn(BaseModel):
order_number: str = Field(pattern=ORDER_NUMBER)
channel: Literal["whatsapp", "manual"] = "whatsapp"
message_id: uuid.UUID | None = Field(default=None, description="the outbound request")
band: Literal["low", "medium", "high"] | None = None
payment_link: dict[str, Any] | None = None
async def start_confirmation(args: BaseModel, ctx: ToolContext) -> ToolResult:
a = StartConfirmationIn.model_validate(args)
o = await _order(ctx, a.order_number)
if o is None:
return fail(f"order {a.order_number} not found")
if o.status in FINAL_ORDER_STATES:
return fail(f"order {o.number} is {o.status}; nothing to confirm")
settings = await cod_settings(ctx)
now = datetime.now(UTC)
deadline = now + timedelta(hours=timeout_hours(settings))
effect = {
"order": o.number,
"channel": a.channel,
"band": a.band,
"status": "pending",
"timeout_hours": timeout_hours(settings),
}
if ctx.dry_run:
return dry(effect)
previous = await latest_attempt(ctx, o.id)
await ctx.session.execute(
update(CodConfirmation)
.where(CodConfirmation.order_id == o.id, CodConfirmation.status == "pending")
.values(status="superseded", resolved_at=now)
)
attempt = CodConfirmation(
tenant_id=ctx.tenant_id,
order_id=o.id,
attempt=(previous.attempt + 1) if previous else 1,
channel=a.channel,
band=a.band or o.risk_band,
status="pending",
phone=await order_phone(ctx, o),
message_id=a.message_id,
payment_link=a.payment_link,
deadline_at=deadline,
created_at=now,
)
ctx.session.add(attempt)
o.confirmation_status = "pending"
o.updated_at = now
await ctx.session.flush()
return ToolResult(ok=True, data={**effect, **(attempt_view(attempt, o.number) or {})})
# ---------------------------------------------------------- resolve_confirmation (T1)
class ResolveConfirmationIn(BaseModel):
order_number: str = Field(pattern=ORDER_NUMBER)
outcome: Literal["confirmed", "rejected"]
source: Literal["button", "keyword", "extractor", "auto", "operator", "address_change"]
reply_message_id: uuid.UUID | None = None
async def resolve_confirmation(args: BaseModel, ctx: ToolContext) -> ToolResult:
a = ResolveConfirmationIn.model_validate(args)
o = await _order(ctx, a.order_number)
if o is None:
return fail(f"order {a.order_number} not found")
if o.status in FINAL_ORDER_STATES:
return fail(f"order {o.number} is already {o.status}")
attempt = await pending_attempt(ctx, o.id)
if attempt is None and a.source in CUSTOMER_SOURCES:
# A late or repeated reply: the attempt was already resolved (or expired).
last = await latest_attempt(ctx, o.id)
if last is not None and last.status == a.outcome:
return ToolResult(
ok=True, data={"order": o.number, "status": a.outcome, "already": True}
)
if last is None or last.status != "no_answer":
return fail(f"no confirmation is pending for {o.number}")
attempt = last # a reply after the deadline still counts
effect = {
"order": o.number,
"outcome": a.outcome,
"source": a.source,
"order_status_after": "confirmed" if a.outcome == "confirmed" else o.status,
}
if ctx.dry_run:
return dry(effect)
now = datetime.now(UTC)
if attempt is None: # auto-confirmation (low risk) or an operator without an attempt
attempt = CodConfirmation(
tenant_id=ctx.tenant_id,
order_id=o.id,
attempt=1,
channel="auto" if a.source == "auto" else "manual",
band=o.risk_band,
status=a.outcome,
phone=await order_phone(ctx, o),
)
ctx.session.add(attempt)
attempt.status = a.outcome
attempt.decision = "CONFIRM" if a.outcome == "confirmed" else "CANCEL"
attempt.decision_source = a.source
attempt.reply_message_id = a.reply_message_id
attempt.resolved_at = now
o.confirmation_status = a.outcome
if a.outcome == "confirmed" and o.status == "pending":
o.status = "confirmed"
o.updated_at = now
await ctx.session.flush()
return ToolResult(ok=True, data={**effect, "attempt_id": str(attempt.id)})
# --------------------------------------------------------- expire_confirmations (T1)
class ExpireIn(BaseModel):
as_of: datetime | None = Field(default=None, description="default: now (tests inject)")
limit: int = Field(default=200, ge=1, le=1000)
async def expire_confirmations(args: BaseModel, ctx: ToolContext) -> ToolResult:
a = ExpireIn.model_validate(args)
now = a.as_of or datetime.now(UTC)
if now.tzinfo is None:
now = now.replace(tzinfo=UTC)
rows = (
await ctx.session.execute(
select(CodConfirmation, Order)
.join(Order, Order.id == CodConfirmation.order_id)
.where(CodConfirmation.status == "pending", CodConfirmation.deadline_at <= now)
.order_by(CodConfirmation.deadline_at, Order.number)
.limit(a.limit)
)
).all()
expired = [
{"order_number": o.number, "band": c.band, "total": o.total, "attempt_id": str(c.id)}
for c, o in rows
]
if ctx.dry_run:
return dry({"expire": [e["order_number"] for e in expired]})
for c, o in rows:
c.status = "no_answer"
c.decision_source = "timeout"
c.resolved_at = now
if o.confirmation_status == "pending":
o.confirmation_status = "no_answer"
o.updated_at = now
await ctx.session.flush()
return ToolResult(ok=True, data={"expired": expired, "count": len(expired)})
# ---------------------------------------------------------- create_payment_link (T1)
class PaymentLinkProvider(Protocol):
async def create(
self, provider: str, order_number: str, amount: int, reference: str
) -> dict[str, Any]: ...
class StubPaymentLinks:
"""Stand-in for a JazzCash / Easypaisa payment-link integration (no network). A real
provider implements the same one-method protocol (``set_payment_provider``)."""
async def create(
self, provider: str, order_number: str, amount: int, reference: str
) -> dict[str, Any]:
return {
"provider": provider,
"reference": reference,
"amount": amount,
"url": f"https://pay.workpilot.test/{provider}/{reference}",
"stub": True,
}
_payments: PaymentLinkProvider = StubPaymentLinks()
def set_payment_provider(p: PaymentLinkProvider | None) -> None:
global _payments
_payments = p or StubPaymentLinks()
class PaymentLinkIn(BaseModel):
order_number: str = Field(pattern=ORDER_NUMBER)
provider: Literal["jazzcash", "easypaisa"] = "jazzcash"
amount: int | None = Field(default=None, ge=1, description="default: tenant advance %")
async def create_payment_link(args: BaseModel, ctx: ToolContext) -> ToolResult:
a = PaymentLinkIn.model_validate(args)
o = await _order(ctx, a.order_number)
if o is None:
return fail(f"order {a.order_number} not found")
if o.payment_method != "COD" or o.status in FINAL_ORDER_STATES:
return fail(f"order {o.number} does not need an advance payment")
advance = dict((await cod_settings(ctx)).get("advance_payment") or {})
amount = a.amount or advance_amount(o.total, advance)
if amount > o.total:
return fail("advance cannot exceed the order total")
ref = "ADV-" + hashlib.sha256(f"{ctx.tenant_id}:{o.number}:{amount}".encode()).hexdigest()[:12]
effect = {"order": o.number, "provider": a.provider, "amount": amount, "reference": ref}
if ctx.dry_run:
return dry(effect)
link = await _payments.create(a.provider, o.number, amount, ref)
return ToolResult(ok=True, data={**effect, "link": link})
# --------------------------------------------------------------- cancel_order (T2)
class CancelOrderIn(BaseModel):
order_numbers: list[str] = Field(min_length=1, max_length=200)
reason: Literal["customer_rejected", "no_answer", "operator", "high_risk"]
note: str = Field(default="", max_length=300)
@model_validator(mode="after")
def numbers(self) -> CancelOrderIn:
import re
bad = [n for n in self.order_numbers if not re.fullmatch(ORDER_NUMBER, n)]
if bad:
raise ValueError(f"not order numbers: {bad[:3]}")
self.order_numbers = sorted(set(self.order_numbers))
return self
async def _active_shipment(ctx: ToolContext, order_id: uuid.UUID) -> Shipment | None:
return (
await ctx.session.execute(
select(Shipment)
.where(
Shipment.order_id == order_id,
Shipment.status.in_(("in_transit", "out_for_delivery", "failed_attempt")),
)
.limit(1)
)
).scalar_one_or_none()
async def cancel_order_facts(args: dict[str, Any], ctx: ToolContext) -> dict[str, Any]:
numbers = list(args.get("order_numbers") or [])
found = cancellable = rejected = 0
for n in numbers:
o = await _order(ctx, n)
if o is None:
continue
found += 1
if o.status not in FINAL_ORDER_STATES and await _active_shipment(ctx, o.id) is None:
cancellable += 1
last = await latest_attempt(ctx, o.id)
if (
last is not None
and last.status == "rejected"
and last.decision_source in CUSTOMER_SOURCES
):
rejected += 1
return {
"count": len(numbers),
"all_found": found == len(numbers),
"all_cancellable": cancellable == len(numbers),
"all_customer_rejected": rejected == len(numbers),
}
async def cancel_order(args: BaseModel, ctx: ToolContext) -> ToolResult:
a = CancelOrderIn.model_validate(args)
orders = []
for n in a.order_numbers:
o = await _order(ctx, n)
if o is None:
return fail(f"order {n} not found")
if o.status in FINAL_ORDER_STATES or await _active_shipment(ctx, o.id) is not None:
return fail(f"order {n} is {o.status} and can no longer be cancelled here")
orders.append(o)
effect = {
"cancel": [o.number for o in orders],
"reason": a.reason,
"status_after": "cancelled",
"cod_value": sum(o.total for o in orders),
}
if ctx.dry_run:
return dry(effect)
now = datetime.now(UTC)
for o in orders:
o.status = "cancelled"
o.cancelled_at = now
o.updated_at = now
if a.reason == "customer_rejected":
o.confirmation_status = "rejected"
line = f"[{now:%Y-%m-%d %H:%M}] cancelled ({a.reason}) by {ctx.actor}"
o.notes = (o.notes + "\n" + line).strip() if o.notes else line
await ctx.session.execute(
update(CodConfirmation)
.where(CodConfirmation.order_id == o.id, CodConfirmation.status == "pending")
.values(status="superseded", resolved_at=now)
)
await ctx.session.flush()
return ToolResult(ok=True, data={**effect, "cancelled": len(orders)})
# ----------------------------------------------------- update_shipping_address (T2)
class AddressChangeIn(BaseModel):
order_number: str = Field(pattern=ORDER_NUMBER)
address: str = Field(min_length=5, max_length=400)
city: str | None = Field(default=None, max_length=80)
async def address_facts(args: dict[str, Any], ctx: ToolContext) -> dict[str, Any]:
o = await _order(ctx, str(args.get("order_number") or ""))
if o is None:
return {"order_found": False, "shipped": False}
shipped = o.status in FINAL_ORDER_STATES or await _active_shipment(ctx, o.id) is not None
return {"order_found": True, "shipped": shipped}
async def update_shipping_address(args: BaseModel, ctx: ToolContext) -> ToolResult:
a = AddressChangeIn.model_validate(args)
o = await _order(ctx, a.order_number)
if o is None:
return fail(f"order {a.order_number} not found")
if o.status in FINAL_ORDER_STATES:
return fail(f"order {o.number} is {o.status}; the address can no longer change")
effect = {
"order": o.number,
"address_before": o.ship_address,
"address_after": a.address,
"city_before": o.city,
"city_after": a.city or o.city,
}
if ctx.dry_run:
return dry(effect)
now = datetime.now(UTC)
o.ship_address = a.address
if a.city:
o.city = a.city
line = f"[{now:%Y-%m-%d %H:%M}] shipping address changed by {ctx.actor}"
o.notes = (o.notes + "\n" + line).strip() if o.notes else line
o.updated_at = now
await ctx.session.flush()
return ToolResult(ok=True, data=effect)