backbone-pos 0.5.33

Point of sale — cashier session, ticket + multi-tender; orchestrates billing (revenue) + payment (settlement), posts no GL directly
Documentation
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
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
//! Guarded route composition — the RECOMMENDED way to mount the POS module.
//!
//! Hand-authored (user-owned). Read documents + **validated writes** (open session / ring sale / sync
//! an offline ticket / add tender / close session / manager-PIN credentials); generic CRUD is NOT
//! mounted, so a caller cannot write a ticket with inconsistent totals or reopen a closed session.
//! `recognize_sale` drives billing + payment through ports (a composition layer), so it is
//! service/job-driven, not an HTTP route.
//!
//! Route bases carry no module prefix — the module mounts under its own scope (the composing service
//! nests it at `/api/v1/pos` or equivalent): `/sessions`, `/sales`, `/tenders`, `/cash-movements`,
//! `/receipts`, plus the newer `/sales/sync` (offline replay) and `/manager-pins` (credential verbs).
//!
//! The composing service supplies the port implementations the guarded surface needs:
//! a `PosTaxComputePort` (document-grade tax — every ring), a `PosCashVariancePort` (session-close
//! GL correction), and the `BillingPort`/`PaymentPort` pair (only the offline REFUND replay drives
//! them, through the same reversal pair `return_sale` uses).
//!
//! The module ships BARE of authentication (ADR-0029, the org-composed shape): the composing
//! service wraps this router in its org scope middleware (`org_auth` + the tenant router). The
//! handlers below extract [`OrgContext`] purely to read the acting node — the branch a session
//! opens at is the signed `acting_unit_id`, never a body field — while the fence itself is the
//! request's org scope on the request-dedicated connection.

use std::sync::Arc;

use axum::{extract::{Path, State}, http::StatusCode, response::IntoResponse, routing::{get, post}, Json, Router};
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
use sqlx::PgPool;
use uuid::Uuid;

use crate::application::service::pos_cart_pricing::CartPricingPort;
use crate::application::service::pos_events::PosEventSink;
use crate::application::service::pos_ports::{BillingPort, PaymentPort, PosCashVariancePort, PosTaxComputePort};
use crate::application::service::pos_write_service::{
    CartSaleLine, ManagerAuth, NewCartSale, NewCashMovement, NewClose, NewSale, NewSaleLine,
    NewSession, NewSyncSale, PosError, PosWriteService, SyncAction, SyncSaleLine, SyncTender,
};
use crate::application::service::pos_manager_pin::SetPin;
use crate::PosModule;

use backbone_auth::org::OrgContext;
use super::{
    create_pos_discount_read_routes, create_pos_floor_plan_read_routes, create_pos_invoice_read_routes,
    create_pos_opening_entry_read_routes, create_pos_profile_read_routes, create_pos_table_read_routes,
};

#[derive(Debug, Serialize)]
struct ErrorBody { error: String, message: String }
#[derive(Debug, Serialize)]
struct IdResponse { id: Uuid }
fn err(e: PosError) -> axum::response::Response {
    let s = StatusCode::from_u16(e.http_status()).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
    (s, Json(ErrorBody { error: e.code(), message: e.to_string() })).into_response()
}

/// The best-effort source address of a privileged request — feeds the PIN throttle ring. Reads the
/// proxy hop list first (the guarded surface sits behind one in production), then the direct peer.
/// `None` skips the per-address budget (service-to-service callers have no address).
fn source_ip(headers: &axum::http::HeaderMap) -> Option<String> {
    headers
        .get("x-forwarded-for")
        .and_then(|v| v.to_str().ok())
        .and_then(|v| v.split(',').next())
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
        .or_else(|| {
            headers
                .get(axum::http::header::USER_AGENT)
                .and_then(|v| v.to_str().ok())
                .map(|s| format!("ua:{}", utf8_prefix(s, 60)))
        })
}

/// Longest prefix of `s` no longer than `max` bytes that stops on a char boundary — a raw byte
/// slice panics when a multi-byte character straddles the cap, and this feeds the privileged
/// throttle path.
fn utf8_prefix(s: &str, max: usize) -> &str {
    let mut cut = s.len().min(max);
    while !s.is_char_boundary(cut) {
        cut -= 1;
    }
    &s[..cut]
}

#[cfg(test)]
mod tests {
    use super::utf8_prefix;

    #[test]
    fn utf8_prefix_never_splits_a_character() {
        // 16 four-byte emoji = 64 bytes: a 60-byte cap lands exactly on a boundary.
        let emoji = "😀".repeat(16);
        assert_eq!(utf8_prefix(&emoji, 60).len(), 60);
        // A cap one byte past the boundary backs off to it instead of splitting an emoji.
        assert_eq!(utf8_prefix(&emoji, 61).len(), 60);
        // A two-byte character straddling the cap backs off whole.
        let tailed = "a".repeat(59) + "é";
        assert_eq!(utf8_prefix(&tailed, 60), "a".repeat(59).as_str());
        assert_eq!(utf8_prefix("short", 60), "short");
        assert_eq!(utf8_prefix("", 60), "");
    }
}

/// The write surface's shared state: the write service plus the port implementations the guarded
/// verbs drive (tax on every ring, variance at close, billing+payment on offline refund replays).
#[derive(Clone)]
struct WriteState {
    svc: Arc<PosWriteService>,
    tax: Arc<dyn PosTaxComputePort>,
    variance: Arc<dyn PosCashVariancePort>,
    billing: Arc<dyn BillingPort>,
    payment: Arc<dyn PaymentPort>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct OpeningBalanceBody { method: String, amount: Decimal }

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct OpenSessionBody {
    pos_profile_id: Uuid,
    cashier_party_id: Uuid,
    opened_at: chrono::NaiveDateTime,
    #[serde(default)] opening_balances: Vec<OpeningBalanceBody>,
}
async fn open_session(State(st): State<WriteState>, org: OrgContext, Json(b): Json<OpenSessionBody>) -> axum::response::Response {
    // branch_id comes from the authenticated principal, never the request body (it is a business
    // column, not the tenancy axis): the signed acting node IS the branch the session opens at.
    // Tenancy is composition-installed (ADR-0029): no company field — the composing service's
    // org scope middleware fences the insert.
    let s = NewSession {
        pos_profile_id: b.pos_profile_id, branch_id: Some(org.acting_unit_id),
        cashier_party_id: b.cashier_party_id, opened_at: b.opened_at,
        opening_balances: b.opening_balances.into_iter().map(|o| (o.method, o.amount)).collect(),
    };
    match st.svc.open_session(s).await {
        Ok(id) => (StatusCode::CREATED, Json(IdResponse { id })).into_response(),
        Err(e) => err(e),
    }
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct SaleLineBody {
    item_id: Uuid,
    #[serde(default)] revenue_account_id: Option<Uuid>,
    #[serde(default)] description: Option<String>,
    /// Course grouping for kitchen routing (1 = starter, 2 = main, …); absent = not grouped.
    #[serde(default)] course: Option<i32>,
    quantity: Decimal,
    unit_price: Decimal,
    #[serde(default)] discount_amount: Decimal,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct RingSaleBody {
    pos_profile_id: Uuid,
    opening_entry_id: Uuid,
    #[serde(default)] customer_id: Option<Uuid>,
    /// Seat the draft at a dining table (restaurant lane). One draft per table is enforced
    /// server-side — a second draft on an occupied table is a typed 409, never a silent merge.
    #[serde(default)] pos_table_id: Option<Uuid>,
    /// Apply this tenant's order-level discount master to the whole ticket. The RATE is read from
    /// the master row server-side; a client-sent percentage has no field to land in.
    #[serde(default)] discount_id: Option<Uuid>,
    receipt_number: String,
    posting_at: chrono::NaiveDateTime,
    lines: Vec<SaleLineBody>,
}
async fn ring_sale(State(st): State<WriteState>, org: OrgContext, Json(b): Json<RingSaleBody>) -> axum::response::Response {
    // Tenancy is composition-installed (ADR-0029): the composing service's org scope middleware
    // fences the session lookup, so a session outside the caller's scope reads as plain absence —
    // a token for one unit cannot ring against another unit's opening_entry_id. EVERY money field
    // is server-derived: tax resolves through the register's templates via the tax port, and cash
    // rounding comes from the register's configuration — the body has no total fields at all (a
    // client can neither omit nor overstate the VAT or the pay-to total). The order-level discount
    // is likewise server-priced: only the master's id is accepted, never a rate.
    let sale = NewSale {
        pos_profile_id: b.pos_profile_id, opening_entry_id: b.opening_entry_id,
        branch_id: Some(org.acting_unit_id), customer_id: b.customer_id, pos_table_id: b.pos_table_id,
        discount_id: b.discount_id, receipt_number: b.receipt_number, posting_at: b.posting_at,
        lines: b.lines.into_iter().map(|l| NewSaleLine {
            item_id: l.item_id, revenue_account_id: l.revenue_account_id, description: l.description,
            course: l.course, quantity: l.quantity, unit_price: l.unit_price, discount_amount: l.discount_amount,
        }).collect(),
    };
    match st.svc.ring_sale(sale, &*st.tax).await {
        Ok(id) => (StatusCode::CREATED, Json(IdResponse { id })).into_response(),
        Err(e) => err(e),
    }
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct TenderBody {
    pos_invoice_id: Uuid,
    payment_method: String,
    amount: Decimal,
    #[serde(default)] reference_no: Option<String>,
}
async fn add_tender(State(st): State<WriteState>, Json(b): Json<TenderBody>) -> axum::response::Response {
    match st.svc.add_tender(b.pos_invoice_id, &b.payment_method, b.amount, b.reference_no).await {
        Ok(o) => (StatusCode::OK, Json(serde_json::json!({
            "paidTotal": o.paid_total, "changeDue": o.change_due, "fullyTendered": o.fully_tendered,
        }))).into_response(),
        Err(e) => err(e),
    }
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct CountedBody { method: String, amount: Decimal }

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ManagerBody {
    employee_party_id: Uuid,
    pin: String,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct CloseBody {
    opening_entry_id: Uuid,
    cashier_party_id: Uuid,
    closed_at: chrono::NaiveDateTime,
    #[serde(default)] counted: Vec<CountedBody>,
    /// Closing the till is privileged: the manager's PIN is verified server-side before anything is
    /// written (the close is the one POS verb that books a GL correction on its own account).
    manager: ManagerBody,
}
async fn close_session(State(st): State<WriteState>, headers: axum::http::HeaderMap, Json(b): Json<CloseBody>) -> axum::response::Response {
    // Tenancy is composition-installed (ADR-0029): the composing service's org scope middleware
    // fences the opening-entry lookup; no company field rides the verb.
    let c = NewClose {
        opening_entry_id: b.opening_entry_id, cashier_party_id: b.cashier_party_id,
        closed_at: b.closed_at, counted: b.counted.into_iter().map(|x| (x.method, x.amount)).collect(),
        manager: ManagerAuth { employee_party_id: b.manager.employee_party_id, pin: b.manager.pin },
        source_ip: source_ip(&headers),
    };
    match st.svc.close_session(c, &*st.variance).await {
        Ok(o) => (StatusCode::OK, Json(serde_json::json!({
            "closingId": o.closing_id, "differenceTotal": o.difference_total,
            "byMethod": o.by_method.iter().map(|m| serde_json::json!({
                "method": m.method, "expected": m.expected, "counted": m.counted, "difference": m.difference,
            })).collect::<Vec<_>>(),
            "variance": match &o.variance {
                None => serde_json::Value::Null,
                Some(v) => serde_json::json!({ "journalId": v.journal_id, "amount": v.amount, "direction": match v.direction {
                    crate::application::service::pos_ports::CashVarianceDirection::Over => "over",
                    crate::application::service::pos_ports::CashVarianceDirection::Short => "short",
                }}),
            },
        }))).into_response(),
        Err(e) => err(e),
    }
}

// ---- offline sync (the replay verb) -------------------------------------------

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct SyncSaleLineBody {
    client_uuid: Uuid,
    item_id: Uuid,
    #[serde(default)] revenue_account_id: Option<Uuid>,
    #[serde(default)] description: Option<String>,
    #[serde(default)] course: Option<i32>,
    quantity: Decimal,
    unit_price: Decimal,
    #[serde(default)] discount_amount: Decimal,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct SyncTenderBody {
    client_uuid: Uuid,
    method: String,
    amount: Decimal,
    #[serde(default)] reference_no: Option<String>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct SyncSaleBody {
    client_uuid: Uuid,
    pos_profile_id: Uuid,
    opening_entry_id: Uuid,
    #[serde(default)] rescue_opening_entry_id: Option<Uuid>,
    #[serde(default)] customer_id: Option<Uuid>,
    /// Seat/transfer the ticket to a dining table (restaurant lane): honored as the ticket's new
    /// seat on update; a table occupied by ANOTHER draft refuses with a typed 409.
    #[serde(default)] pos_table_id: Option<Uuid>,
    /// Order-level discount master (same server-priced contract as the online ring).
    #[serde(default)] discount_id: Option<Uuid>,
    posting_at: chrono::NaiveDateTime,
    #[serde(default)] lines: Vec<SyncSaleLineBody>,
    #[serde(default)] tenders: Vec<SyncTenderBody>,
    /// A refund replay names its parent ticket's client uuid — that makes the sync privileged
    /// (`manager` is then required and verified server-side).
    #[serde(default)] refund_of_client_uuid: Option<Uuid>,
    #[serde(default)] manager: Option<ManagerBody>,
}
async fn sync_from_ui(State(st): State<WriteState>, headers: axum::http::HeaderMap, org: OrgContext, Json(b): Json<SyncSaleBody>) -> axum::response::Response {
    // No total field exists on this body by design: the server recomputes every money field from the
    // lines + tenders through the same compute core the online ring uses. Tenancy is
    // composition-installed (ADR-0029): no company field — the replay namespaces inside the acting
    // unit's scope (the signed acting node IS the branch).
    let s = NewSyncSale {
        client_uuid: b.client_uuid,
        pos_profile_id: b.pos_profile_id,
        opening_entry_id: b.opening_entry_id,
        rescue_opening_entry_id: b.rescue_opening_entry_id,
        branch_id: Some(org.acting_unit_id),
        customer_id: b.customer_id,
        pos_table_id: b.pos_table_id,
        discount_id: b.discount_id,
        posting_at: b.posting_at,
        lines: b.lines.into_iter().map(|l| SyncSaleLine {
            client_uuid: l.client_uuid, item_id: l.item_id, revenue_account_id: l.revenue_account_id,
            description: l.description, course: l.course, quantity: l.quantity, unit_price: l.unit_price,
            discount_amount: l.discount_amount,
        }).collect(),
        tenders: b.tenders.into_iter().map(|t| SyncTender {
            client_uuid: t.client_uuid, method: t.method, amount: t.amount, reference_no: t.reference_no,
        }).collect(),
        refund_of_client_uuid: b.refund_of_client_uuid,
        manager: b.manager.map(|m| ManagerAuth { employee_party_id: m.employee_party_id, pin: m.pin }),
        source_ip: source_ip(&headers),
    };
    match st.svc.sync_from_ui(s, &*st.tax, &*st.billing, &*st.payment).await {
        Ok(o) => (StatusCode::OK, Json(serde_json::json!({
            "posInvoiceId": o.pos_invoice_id,
            "action": match o.action {
                SyncAction::Created => "created",
                SyncAction::Updated => "updated",
                SyncAction::ReplayFinalized => "replay_finalized",
            },
            "totals": {
                "netTotal": o.totals.net_total, "taxTotal": o.totals.tax_total,
                "grandTotal": o.totals.grand_total, "roundingAdjustment": o.totals.rounding_adjustment,
                "roundedTotal": o.totals.rounded_total, "paidTotal": o.totals.paid_total,
                "changeDue": o.totals.change_due,
            },
        }))).into_response(),
        Err(e) => err(e),
    }
}

// ---- manager PINs ---------------------------------------------------------------

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct SetPinBody {
    employee_party_id: Uuid,
    new_pin: String,
    /// Authority proof when the company already has credentials: the same manager's current PIN, or
    /// another manager's. Absent is valid only for the very first credential (bootstrap).
    #[serde(default)] current: Option<ManagerBody>,
}
async fn set_pin(State(st): State<WriteState>, headers: axum::http::HeaderMap, Json(b): Json<SetPinBody>) -> axum::response::Response {
    // Tenancy is composition-installed (ADR-0029): the credential namespaces inside the acting
    // unit's scope; no company field rides the verb.
    let s = SetPin {
        employee_party_id: b.employee_party_id,
        new_pin: b.new_pin,
        current: b.current.map(|m| ManagerAuth { employee_party_id: m.employee_party_id, pin: m.pin }),
        source_ip: source_ip(&headers),
    };
    match st.svc.set_pin(s).await {
        Ok(()) => StatusCode::NO_CONTENT.into_response(),
        Err(e) => err(e),
    }
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct VerifyPinBody { employee_party_id: Uuid, pin: String }
async fn verify_pin(State(st): State<WriteState>, headers: axum::http::HeaderMap, Json(b): Json<VerifyPinBody>) -> axum::response::Response {
    match st.svc.verify_pin(b.employee_party_id, &b.pin, source_ip(&headers).as_deref()).await {
        Ok(()) => StatusCode::NO_CONTENT.into_response(),
        Err(e) => err(e),
    }
}

// ---- priced ring (the promo cart seam) ---------------------------------------
//
// `POST /sales/priced` rings a ticket whose per-line prices are RESOLVED by promo (server-side
// discounts + order rules + bundles) instead of taken from the client. The composing service supplies a
// `CartPricingPort` implemented over promo's `resolve_cart`. The client still sends a `listPrice` per
// line (no price master exists yet — base price is not server-owned), but the DISCOUNT it pays is
// server-authoritative: a client cannot fake a promo. Tax + rounding are server-owned as on the plain
// ring.

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct PricedSaleLineBody {
    item_id: Uuid,
    #[serde(default)] item_group_id: Option<Uuid>,
    #[serde(default)] brand_id: Option<Uuid>,
    #[serde(default)] revenue_account_id: Option<Uuid>,
    #[serde(default)] description: Option<String>,
    #[serde(default)] course: Option<i32>,
    list_price: Decimal,
    quantity: Decimal,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct RingSalePricedBody {
    pos_profile_id: Uuid,
    opening_entry_id: Uuid,
    #[serde(default)] customer_id: Option<Uuid>,
    #[serde(default)] customer_group_id: Option<Uuid>,
    #[serde(default)] coupon_code: Option<String>,
    #[serde(default)] pos_table_id: Option<Uuid>,
    #[serde(default)] discount_id: Option<Uuid>,
    receipt_number: String,
    posting_at: chrono::NaiveDateTime,
    lines: Vec<PricedSaleLineBody>,
}

/// State for the priced route: the write state + the promo-backed pricer.
#[derive(Clone)]
struct PricedState {
    write: WriteState,
    pricing: Arc<dyn CartPricingPort>,
}

async fn ring_sale_priced(State(st): State<PricedState>, org: OrgContext, Json(b): Json<RingSalePricedBody>) -> axum::response::Response {
    // Tenancy is composition-installed (ADR-0029): the composing adapter binds the ambient org scope
    // around promo's cart pricer, so no company field rides the request (branch_id is a business
    // column and still comes off the signed acting node).
    let cart = NewCartSale {
        pos_profile_id: b.pos_profile_id, opening_entry_id: b.opening_entry_id,
        branch_id: Some(org.acting_unit_id), customer_id: b.customer_id, customer_group_id: b.customer_group_id,
        coupon_code: b.coupon_code, pos_table_id: b.pos_table_id, discount_id: b.discount_id,
        receipt_number: b.receipt_number, posting_at: b.posting_at,
        lines: b.lines.into_iter().map(|l| CartSaleLine {
            item_id: l.item_id, item_group_id: l.item_group_id, brand_id: l.brand_id,
            revenue_account_id: l.revenue_account_id, description: l.description, course: l.course,
            list_price: l.list_price, quantity: l.quantity,
        }).collect(),
    };
    match st.write.svc.ring_sale_priced(cart, &*st.pricing, &*st.write.tax).await {
        Ok(id) => (StatusCode::CREATED, Json(IdResponse { id })).into_response(),
        Err(e) => err(e),
    }
}

/// Mount ONLY the promo-priced ring route (`POST /sales/priced`). Merge this in
/// addition to `create_guarded_pos_routes` when the service has a promo-backed `CartPricingPort`.
pub fn create_guarded_pos_priced_route(
    pool: PgPool,
    pricing: Arc<dyn CartPricingPort>,
    sink: Arc<dyn PosEventSink>,
    tax: Arc<dyn PosTaxComputePort>,
) -> Router {
    create_guarded_pos_priced_route_inner(pool, pricing, sink, tax, None)
}

/// Like [`create_guarded_pos_priced_route`] but opts the priced-ring write service into
/// outbox-backed `PosTenderCompleted` staging (durable recognition). See
/// [`create_guarded_pos_routes_with_outbox`] for the service-side setup the schema implies.
pub fn create_guarded_pos_priced_route_with_outbox(
    pool: PgPool,
    pricing: Arc<dyn CartPricingPort>,
    sink: Arc<dyn PosEventSink>,
    tax: Arc<dyn PosTaxComputePort>,
    outbox_schema: String,
) -> Router {
    create_guarded_pos_priced_route_inner(pool, pricing, sink, tax, Some(outbox_schema))
}

fn create_guarded_pos_priced_route_inner(
    pool: PgPool,
    pricing: Arc<dyn CartPricingPort>,
    sink: Arc<dyn PosEventSink>,
    tax: Arc<dyn PosTaxComputePort>,
    outbox_schema: Option<String>,
) -> Router {
    let mut svc = PosWriteService::with_sink(pool, sink);
    if let Some(schema) = outbox_schema {
        svc = svc.with_outbox(schema);
    }
    let write = WriteState {
        svc: Arc::new(svc),
        tax,
        // The priced ring never books variance or drives a refund — placeholders that satisfy the
        // state shape; the routes that would use them are not mounted here.
        variance: Arc::new(NoVariance),
        billing: Arc::new(NoBilling),
        payment: Arc::new(NoPayment),
    };
    let st = PricedState { write, pricing };
    Router::new()
        .route("/sales/priced", post(ring_sale_priced))
        .with_state(st)

    // Bind the composer's request pool (ADR-0029 pool law) for the verbs:
    // under a tenant mount the writes go to the tenant's database; without
    // one the composed pool stays the fallback. Applied AFTER the routes —
    // a Router layer only wraps what was registered before the call.
    .layer(axum::middleware::from_fn(
        crate::request_pool::bind_request_pool,
    ))
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct CashMovementBody {
    pos_profile_id: Uuid,
    opening_entry_id: Uuid,
    cashier_party_id: Uuid,
    /// pay_in | pay_out | drop | no_sale
    movement_type: String,
    #[serde(default)] amount: Decimal,
    #[serde(default)] reason: Option<String>,
    moved_at: chrono::NaiveDateTime,
}
async fn record_cash_movement(State(st): State<WriteState>, Json(b): Json<CashMovementBody>) -> axum::response::Response {
    // Tenancy is composition-installed (ADR-0029): the composing service's org scope middleware
    // fences the session lookup; no company field rides the verb.
    let m = NewCashMovement {
        pos_profile_id: b.pos_profile_id, opening_entry_id: b.opening_entry_id,
        cashier_party_id: b.cashier_party_id, movement_type: b.movement_type, amount: b.amount,
        reason: b.reason, moved_at: b.moved_at,
    };
    match st.svc.record_cash_movement(m).await {
        Ok(id) => (StatusCode::CREATED, Json(IdResponse { id })).into_response(),
        Err(e) => err(e),
    }
}

async fn x_report(State(st): State<WriteState>, Path(opening_entry_id): Path<Uuid>) -> axum::response::Response {
    match st.svc.x_report(opening_entry_id).await {
        Ok(r) => (StatusCode::OK, Json(serde_json::json!({
            "openingEntryId": r.opening_entry_id,
            "grandTotal": r.grand_total,
            "invoiceCount": r.invoice_count,
            "byMethod": r.by_method.iter().map(|m| serde_json::json!({ "method": m.method, "expected": m.expected })).collect::<Vec<_>>(),
        }))).into_response(),
        Err(e) => err(e),
    }
}

async fn receipt(State(st): State<WriteState>, Path(pos_invoice_id): Path<Uuid>) -> axum::response::Response {
    match st.svc.receipt(pos_invoice_id).await {
        Ok(r) => {
            let text = r.render_text();
            let mut body = serde_json::to_value(&r).unwrap_or_else(|_| serde_json::json!({}));
            if let Some(obj) = body.as_object_mut() {
                obj.insert("text".to_string(), serde_json::Value::String(text));
            }
            (StatusCode::OK, Json(body)).into_response()
        }
        Err(e) => err(e),
    }
}

fn write_routes(st: WriteState) -> Router {
    Router::new()
        .route("/sessions", post(open_session))
        .route("/sessions/close", post(close_session))
        .route("/sessions/:opening_entry_id/x-report", get(x_report))
        .route("/sales", post(ring_sale))
        .route("/sales/sync", post(sync_from_ui))
        .route("/tenders", post(add_tender))
        .route("/cash-movements", post(record_cash_movement))
        .route("/receipts/:pos_invoice_id", get(receipt))
        .route("/manager-pins", post(set_pin))
        .route("/manager-pins/verify", post(verify_pin))
        .with_state(st)
}

/// Mount the POS module: read documents + validated writes, BARE of authentication. Generic mutation
/// is not mounted; sale recognition (billing + payment handoff) is service/job-driven via the ports.
/// The module keys nothing on tenancy (composition-installed, ADR-0029): the composing service wraps
/// this router in its org scope middleware, whose request-dedicated connection fences every
/// statement these routes issue. Unauthenticated requests never reach a handler — the org guard
/// rejects them first. Callers send no `company_id` in the body.
/// **Prefer this over `PosModule::all_crud_routes()` for any real deployment.**
///
/// `tax` resolves document-grade tax for every ring (implement over the tax module's
/// `calculate_document`); `variance` books the session-close GL correction; `billing` + `payment` are
/// driven only by offline REFUND replays (the same reversal pair `return_sale` uses).
///
/// Read routes ride the same request-dedicated connection, so the composed fence returns only rows
/// the caller's org scope entitles it to.
pub fn create_guarded_pos_routes(
    m: &PosModule,
    pool: PgPool,
    sink: Arc<dyn PosEventSink>,
    tax: Arc<dyn PosTaxComputePort>,
    variance: Arc<dyn PosCashVariancePort>,
    billing: Arc<dyn BillingPort>,
    payment: Arc<dyn PaymentPort>,
) -> Router {
    create_guarded_pos_routes_inner(m, pool, sink, tax, variance, billing, payment, None)
}

/// Like [`create_guarded_pos_routes`] but opts the write service into outbox-backed
/// `PosTenderCompleted` staging (durable recognition). The composing service must run
/// `backbone_outbox::outbox::migrate(pool, &outbox_schema)` at startup and a relay
/// (`backbone_outbox::runner`) that drains `{outbox_schema}.outbox_events` → recognition.
pub fn create_guarded_pos_routes_with_outbox(
    m: &PosModule,
    pool: PgPool,
    sink: Arc<dyn PosEventSink>,
    tax: Arc<dyn PosTaxComputePort>,
    variance: Arc<dyn PosCashVariancePort>,
    billing: Arc<dyn BillingPort>,
    payment: Arc<dyn PaymentPort>,
    outbox_schema: String,
) -> Router {
    create_guarded_pos_routes_inner(m, pool, sink, tax, variance, billing, payment, Some(outbox_schema))
}

fn create_guarded_pos_routes_inner(
    m: &PosModule,
    pool: PgPool,
    sink: Arc<dyn PosEventSink>,
    tax: Arc<dyn PosTaxComputePort>,
    variance: Arc<dyn PosCashVariancePort>,
    billing: Arc<dyn BillingPort>,
    payment: Arc<dyn PaymentPort>,
    outbox_schema: Option<String>,
) -> Router {
    let mut svc = PosWriteService::with_sink(pool, sink);
    if let Some(schema) = outbox_schema {
        svc = svc.with_outbox(schema);
    }
    let write = WriteState { svc: Arc::new(svc), tax, variance, billing, payment };
    let reads = Router::new()
        .merge(create_pos_profile_read_routes(m.pos_profile_service.clone()))
        .merge(create_pos_opening_entry_read_routes(m.pos_opening_entry_service.clone()))
        .merge(create_pos_invoice_read_routes(m.pos_invoice_service.clone()))
        // Restaurant lane: floor plans + tables (seating surfaces) and the discount masters (the
        // order-level discount rate source) as org-scoped reads.
        .merge(create_pos_floor_plan_read_routes(m.pos_floor_plan_service.clone()))
        .merge(create_pos_table_read_routes(m.pos_table_service.clone()))
        .merge(create_pos_discount_read_routes(m.pos_discount_service.clone()));
    Router::new()
        .merge(reads)
        .merge(write_routes(write))

    // Bind the composer's request pool (ADR-0029 pool law) for the verbs:
    // under a tenant mount the writes go to the tenant's database; without
    // one the composed pool stays the fallback. Applied AFTER the routes —
    // a Router layer only wraps what was registered before the call.
    .layer(axum::middleware::from_fn(
        crate::request_pool::bind_request_pool,
    ))
}

// --- placeholders for the priced-route-only state shape -------------------------
//
// The priced constructor mounts exactly one route; the state type carries every port so the handler
// compiles against the same shape. These implementations refuse if ever reached (they never are —
// no route mounts them), and their refusal is loud rather than silent.

struct NoVariance;
#[async_trait::async_trait]
impl PosCashVariancePort for NoVariance {
    async fn book_cash_variance(&self, _req: &crate::application::service::pos_ports::CashVarianceRequest) -> Result<crate::application::service::pos_ports::CashVarianceAck, crate::application::service::pos_ports::PosRejected> {
        Err(crate::application::service::pos_ports::PosRejected {
            code: "variance_not_mounted".into(),
            message: "this constructor mounts only the priced ring; variance booking is not mounted here".into(),
        })
    }
}
struct NoBilling;
#[async_trait::async_trait]
impl BillingPort for NoBilling {
    async fn raise_and_post(&self, _req: &crate::application::service::pos_ports::SaleInvoiceRequest) -> Result<crate::application::service::pos_ports::InvoiceAck, crate::application::service::pos_ports::PosRejected> {
        Err(crate::application::service::pos_ports::PosRejected { code: "billing_not_mounted".into(), message: "this constructor mounts only the priced ring".into() })
    }
    async fn credit_note(&self, _req: &crate::application::service::pos_ports::CreditNoteRequest) -> Result<crate::application::service::pos_ports::ReversalAck, crate::application::service::pos_ports::PosRejected> {
        Err(crate::application::service::pos_ports::PosRejected { code: "billing_not_mounted".into(), message: "this constructor mounts only the priced ring".into() })
    }
}
struct NoPayment;
#[async_trait::async_trait]
impl PaymentPort for NoPayment {
    async fn settle(&self, _req: &crate::application::service::pos_ports::SettlementRequest) -> Result<crate::application::service::pos_ports::SettlementAck, crate::application::service::pos_ports::PosRejected> {
        Err(crate::application::service::pos_ports::PosRejected { code: "payment_not_mounted".into(), message: "this constructor mounts only the priced ring".into() })
    }
    async fn refund(&self, _req: &crate::application::service::pos_ports::RefundRequest) -> Result<crate::application::service::pos_ports::ReversalAck, crate::application::service::pos_ports::PosRejected> {
        Err(crate::application::service::pos_ports::PosRejected { code: "payment_not_mounted".into(), message: "this constructor mounts only the priced ring".into() })
    }
}