Spaces:
Running

File size: 23,805 Bytes
0776bd5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
"""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)