stateset-embedded 1.23.4

Embeddable commerce library - the SQLite of commerce operations
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
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
//! Async Commerce API for PostgreSQL
//!
//! This module provides async access to commerce operations when using PostgreSQL.
//! All methods are truly async (no blocking).
//!
//! # Example
//!
//! ```rust,ignore
//! use stateset_embedded::{AsyncCommerce, CreateOrder, CreateOrderItem, CreateX402PaymentIntent, X402Asset, X402Network};
//! use rust_decimal_macros::dec;
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     let commerce = AsyncCommerce::connect("postgres://localhost/stateset").await?;
//!
//!     let cart_id = uuid::Uuid::new_v4();
//!
//!     // Ecommerce orders
//!     let order = commerce.orders().create(CreateOrder {
//!         customer_id: uuid::Uuid::new_v4(),
//!         items: vec![CreateOrderItem {
//!             sku: "SKU-001".into(),
//!             name: "Widget".into(),
//!             quantity: 2,
//!             unit_price: dec!(29.99),
//!             ..Default::default()
//!         }],
//!         ..Default::default()
//!     }).await?;
//!
//!     // Agentic commerce payment intent
//!     let intent = commerce
//!         .x402()
//!         .create_intent(CreateX402PaymentIntent {
//!             payer_address: "0xBuyer...".into(),
//!             payee_address: "0xSeller...".into(),
//!             amount: 100_000_000,
//!             asset: X402Asset::Usdc,
//!             network: X402Network::SetChain,
//!             cart_id: Some(cart_id),
//!             ..Default::default()
//!         })
//!         .await?;
//!
//!     let _active = commerce.x402().active_intent_for_cart(cart_id).await?;
//!
//!     Ok(())
//! }
//! ```

// Shared imports for every accessor module in this directory —
// `pub(crate)` so submodules can pull the whole prelude via `use super::*`.
pub(crate) use chrono::{DateTime, NaiveDate, Utc};
pub(crate) use rust_decimal::{Decimal, prelude::ToPrimitive};
pub(crate) use stateset_core::{
    // Cart types
    AddCartItem,
    // Shipment types
    AddShipmentEvent,
    // Work Order types
    AddWorkOrderMaterial,
    // Inventory types
    AdjustInventory,
    // Analytics types
    AnalyticsQuery,
    // BOM types
    BillOfMaterials,
    BomComponent,
    BomFilter,
    Cart,
    CartAddress,
    CartFilter,
    CartItem,
    CheckoutResult,
    // Warranty types
    ClaimResolution,
    // Currency types
    ConversionResult,
    ConvertCurrency,
    CreateBom,
    CreateBomComponent,
    CreateCart,
    // Customer types
    CreateCustomer,
    CreateCustomerAddress,
    CreateInventoryItem,
    // Invoice types
    CreateInvoice,
    CreateInvoiceItem,
    // Order types
    CreateOrder,
    CreateOrderItem,
    // Payment types
    CreatePayment,
    CreatePaymentMethod,
    // Product types
    CreateProduct,
    CreateProductVariant,
    // Purchase Order types
    CreatePurchaseOrder,
    CreatePurchaseOrderItem,
    CreateRefund,
    // Return types
    CreateReturn,
    CreateShipment,
    CreateShipmentItem,
    CreateSupplier,
    CreateWarranty,
    CreateWarrantyClaim,
    CreateWorkOrder,
    CreateWorkOrderTask,
    Currency,
    Customer,
    CustomerAddress,
    CustomerFilter,
    CustomerMetrics,
    DemandForecast,
    ExchangeRate,
    ExchangeRateFilter,
    FulfillmentMetrics,
    InventoryBalance,
    InventoryFilter,
    InventoryHealth,
    InventoryItem,
    InventoryMovement,
    InventoryReservation,
    InventoryTransaction,
    Invoice,
    InvoiceFilter,
    InvoiceItem,
    LowStockItem,
    Order,
    OrderFilter,
    OrderItem,
    OrderStatus,
    OrderStatusBreakdown,
    Payment,
    PaymentFilter,
    PaymentMethod,
    PaymentStatus,
    Product,
    ProductFilter,
    ProductPerformance,
    ProductVariant,
    PurchaseOrder,
    PurchaseOrderFilter,
    PurchaseOrderItem,
    ReceivePurchaseOrderItems,
    RecordInvoicePayment,
    Refund,
    ReserveInventory,
    Result,
    Return,
    ReturnFilter,
    ReturnMetrics,
    RevenueByPeriod,
    RevenueForecast,
    SalesSummary,
    SetCartPayment,
    SetCartShipping,
    SetExchangeRate,
    Shipment,
    ShipmentEvent,
    ShipmentFilter,
    ShipmentItem,
    ShippingRate,
    StockLevel,
    StoreCurrencySettings,
    Supplier,
    SupplierFilter,
    TimeGranularity,
    TopCustomer,
    TopProduct,
    UpdateBom,
    UpdateCart,
    UpdateCartItem,
    UpdateCustomer,
    UpdateInvoice,
    UpdateOrder,
    UpdatePayment,
    UpdateProduct,
    UpdatePurchaseOrder,
    UpdateReturn,
    UpdateShipment,
    UpdateSupplier,
    UpdateWarranty,
    UpdateWarrantyClaim,
    UpdateWorkOrder,
    UpdateWorkOrderTask,
    Warranty,
    WarrantyClaim,
    WarrantyClaimFilter,
    WarrantyFilter,
    WorkOrder,
    WorkOrderFilter,
    WorkOrderMaterial,
    WorkOrderTask,
};
pub(crate) use stateset_core::{
    AddCarton,
    AddCartonItem,
    AddLotCertificate,
    AdjustLocationInventory,
    AdjustLot,
    AllocateBackorder,
    ApAgingSummary,
    ApplyCreditMemo,
    ApplyPaymentToInvoices,
    ApplyPromotionsRequest,
    ApplyPromotionsResult,
    ArAgingFilter,
    ArAgingSummary,
    ArPaymentApplication,
    AutoPostingConfig,
    Backorder,
    BackorderAllocation,
    BackorderFilter,
    BackorderFulfillment,
    BackorderSummary,
    BalanceSheet,
    // Batch types
    BatchResult,
    Bill,
    BillFilter,
    BillItem,
    BillPayment,
    BillPaymentFilter,
    BillingCycle,
    BillingCycleFilter,
    BillingCycleStatus,
    CancelSubscription,
    Carton,
    CartonItem,
    ChangeSerialStatus,
    CollectionActivity,
    CollectionActivityFilter,
    CollectionStatus,
    CompletePick,
    CompletePutAway,
    CompleteShip,
    ConsumeLot,
    CostAdjustment,
    CostAdjustmentFilter,
    CostLayer,
    CostLayerFilter,
    CostMethod,
    CostRollup,
    CostTransaction,
    CostTransactionFilter,
    CostVariance,
    CostVarianceFilter,
    CouponCode,
    CouponFilter,
    CreateAutoPostingConfig,
    // Backorder types
    CreateBackorder,
    // Accounts Payable types
    CreateBill,
    CreateBillItem,
    CreateBillPayment,
    CreateBillingCycle,
    // Accounts Receivable types
    CreateCollectionActivity,
    CreateCostAdjustment,
    CreateCostLayer,
    CreateCouponCode,
    // Credit types
    CreateCreditAccount,
    CreateCreditMemo,
    CreateDefectCode,
    // General Ledger types
    CreateGlAccount,
    CreateGlPeriod,
    // Quality types
    CreateInspection,
    CreateJournalEntry,
    CreateLocation,
    // Lot types
    CreateLot,
    CreateNonConformance,
    CreatePackTask,
    CreatePaymentRun,
    CreatePickTask,
    // Promotion types
    CreatePromotion,
    CreatePutAway,
    CreateQualityHold,
    // Receiving types
    CreateReceipt,
    // Serial types
    CreateSerialNumber,
    CreateSerialNumbersBulk,
    CreateShipTask,
    CreateSubscription,
    // Subscription types
    CreateSubscriptionPlan,
    CreateTaxExemption,
    // Tax types
    CreateTaxJurisdiction,
    CreateTaxRate,
    // Warehouse types
    CreateWarehouse,
    // Fulfillment types
    CreateWave,
    CreateWriteOff,
    CreateZone,
    CreditAccount,
    CreditAccountFilter,
    CreditAgingBucket,
    CreditApplication,
    CreditApplicationFilter,
    CreditCheckResult,
    CreditHold,
    CreditHoldFilter,
    CreditMemo,
    CreditMemoFilter,
    CreditTransaction,
    CreditTransactionFilter,
    CustomerArAging,
    CustomerArSummary,
    CustomerCreditSummary,
    CustomerStatement,
    DefectCode,
    DunningLetterType,
    FulfillBackorder,
    GenerateStatementRequest,
    GlAccount,
    GlAccountFilter,
    GlPeriod,
    GlPeriodFilter,
    IncomeStatement,
    Inspection,
    InspectionFilter,
    InspectionItem,
    InventoryValuation,
    IssueCostLayers,
    // Cost Accounting types
    ItemCost,
    ItemCostFilter,
    JournalEntry,
    JournalEntryFilter,
    JournalEntryLine,
    Location,
    LocationFilter,
    LocationInventory,
    LocationInventoryFilter,
    LocationMovement,
    Lot,
    LotCertificate,
    LotFilter,
    LotLocation,
    LotTransaction,
    MergeLots,
    MoveInventory,
    MoveSerial,
    MovementFilter,
    NonConformance,
    NonConformanceFilter,
    PackTask,
    PackTaskFilter,
    PauseSubscription,
    PaymentAllocation,
    PaymentRun,
    PaymentRunFilter,
    PickTask,
    PickTaskFilter,
    PlaceCreditHold,
    ProductTaxCategory,
    Promotion,
    PromotionFilter,
    PromotionUsage,
    PutAway,
    PutAwayFilter,
    QualityHold,
    QualityHoldFilter,
    Receipt,
    ReceiptFilter,
    ReceiptItem,
    ReceiveItems,
    RecordCostVariance,
    RecordCreditTransaction,
    RecordInspectionResult,
    ReleaseCreditHold,
    ReleaseQualityHold,
    ReserveLot,
    ReserveSerialNumber,
    ReviewCreditApplication,
    SerialFilter,
    SerialHistory,
    SerialHistoryFilter,
    SerialLookupResult,
    SerialNumber,
    SerialReservation,
    SerialValidation,
    SetItemCost,
    ShipTask,
    ShipTaskFilter,
    SkipBillingCycle,
    SkuBackorderSummary,
    SkuCostSummary,
    SplitLot,
    SubmitCreditApplication,
    Subscription,
    SubscriptionEvent,
    SubscriptionEventType,
    SubscriptionFilter,
    SubscriptionPlan,
    SubscriptionPlanFilter,
    SupplierApSummary,
    TaxAddress,
    TaxCalculationRequest,
    TaxCalculationResult,
    TaxExemption,
    TaxJurisdiction,
    TaxJurisdictionFilter,
    TaxRate,
    TaxRateFilter,
    TaxSettings,
    TraceabilityResult,
    TransferLot,
    TransferSerialOwnership,
    TrialBalance,
    UpdateBackorder,
    UpdateBill,
    UpdateCreditAccount,
    UpdateGlAccount,
    UpdateInspection,
    UpdateLocation,
    UpdateLot,
    UpdateNonConformance,
    UpdatePromotion,
    UpdateReceipt,
    UpdateSerialNumber,
    UpdateSubscription,
    UpdateSubscriptionPlan,
    UpdateWarehouse,
    UpdateZone,
    Warehouse,
    WarehouseFilter,
    Wave,
    WaveFilter,
    WriteOff,
    WriteOffFilter,
    Zone,
};
pub(crate) use stateset_core::{
    // Cycle count types
    CreateCycleCount,
    // Fixed asset types
    CreateFixedAsset,
    // Revenue recognition types
    CreateRevenueContract,
    CycleCount,
    CycleCountFilter,
    DepreciationSchedule,
    FixedAsset,
    FixedAssetFilter,
    PerformanceObligation,
    RecordCycleCountLine,
    RevenueContract,
    RevenueContractFilter,
    RevenueSchedule,
    UpdateFixedAsset,
    UpdateRevenueContract,
};
pub(crate) use stateset_db::PostgresDatabase;
pub(crate) use stateset_observability::{Metrics, MetricsConfig, MetricsSnapshot, init_metrics};
pub(crate) use std::sync::Arc;
pub(crate) use uuid::Uuid;

#[cfg(feature = "events")]
pub(crate) use crate::events::EventSystem;
#[cfg(feature = "events")]
pub(crate) use stateset_core::CommerceEvent;

pub(crate) use stateset_core::{
    A2APurchase, A2APurchaseFilter, A2ASkill, AgentCard, AgentCardFilter, CreateA2APurchase,
    CreateA2AQuote, CreateAgentCard, CreateX402PaymentIntent, PurchaseStatus, QuoteStatus,
    SignX402PaymentIntent, SkillQuote, SkillQuoteFilter, TrustLevel, UpdateAgentCard, X402Asset,
    X402CreditAccount, X402CreditAdjustment, X402CreditDirection, X402CreditTransaction,
    X402CreditTransactionFilter, X402IntentStatus, X402Network, X402PaymentIntent,
    X402PaymentIntentFilter, to_smallest_unit,
};
pub(crate) use stateset_core::{
    CreateCustomObject, CreateCustomObjectType, CustomObject, CustomObjectFilter, CustomObjectType,
    CustomObjectTypeFilter, UpdateCustomObject, UpdateCustomObjectType,
};

pub(crate) use stateset_core::{
    AdjustPoints, AdjustStoreCredit, CreateGiftCard, CreateLoyaltyProgram, CreateStoreCredit,
    CustomerId, EnrollCustomer, GiftCard, GiftCardFilter, GiftCardId, GiftCardTransaction,
    LoyaltyAccount, LoyaltyAccountFilter, LoyaltyAccountId, LoyaltyProgram, LoyaltyProgramId,
    LoyaltyTransaction, StoreCredit, StoreCreditFilter, StoreCreditTransaction, UpdateGiftCard,
};

macro_rules! impl_opaque_debug {
    ($($name:ident),+ $(,)?) => {
        $(
            impl std::fmt::Debug for $name {
                fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                    f.debug_struct(stringify!($name)).finish_non_exhaustive()
                }
            }
        )+
    };
}

/// Async commerce interface for PostgreSQL.
///
/// This provides a fully async API for PostgreSQL users who want to avoid
/// blocking operations. All methods are `async` and execute without blocking.
///
/// # Example
///
/// ```rust,ignore
/// use stateset_embedded::AsyncCommerce;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let commerce = AsyncCommerce::connect("postgres://localhost/stateset").await?;
///
///     // All operations are async
///     let orders = commerce.orders().list(Default::default()).await?;
///
///     Ok(())
/// }
/// ```
pub struct AsyncCommerce {
    db: Arc<PostgresDatabase>,
    metrics: Metrics,
    #[cfg(feature = "events")]
    event_system: Arc<EventSystem>,
}

impl AsyncCommerce {
    /// Connect to PostgreSQL and create an async commerce instance.
    ///
    /// # Arguments
    ///
    /// * `url` - PostgreSQL connection string (e.g., `<postgres://user:pass@localhost/db>`)
    pub async fn connect(url: &str) -> Result<Self> {
        let db = PostgresDatabase::connect(url).await?;
        Ok(Self {
            db: Arc::new(db),
            metrics: init_metrics(MetricsConfig::default()),
            #[cfg(feature = "events")]
            event_system: Arc::new(EventSystem::new()),
        })
    }

    /// Connect with custom options.
    ///
    /// # Arguments
    ///
    /// * `url` - PostgreSQL connection string
    /// * `max_connections` - Maximum number of connections in the pool
    /// * `acquire_timeout_secs` - Timeout in seconds for acquiring a connection
    pub async fn connect_with_options(
        url: &str,
        max_connections: u32,
        acquire_timeout_secs: u64,
    ) -> Result<Self> {
        let db = PostgresDatabase::connect_with_options(url, max_connections, acquire_timeout_secs)
            .await?;
        Ok(Self {
            db: Arc::new(db),
            metrics: init_metrics(MetricsConfig::default()),
            #[cfg(feature = "events")]
            event_system: Arc::new(EventSystem::new()),
        })
    }

    /// Create from an existing `PostgresDatabase` instance.
    pub fn from_database(db: Arc<PostgresDatabase>) -> Self {
        Self {
            db,
            metrics: init_metrics(MetricsConfig::default()),
            #[cfg(feature = "events")]
            event_system: Arc::new(EventSystem::new()),
        }
    }

    /// Access async order operations.
    pub fn orders(&self) -> AsyncOrders {
        AsyncOrders::new(
            self.db.clone(),
            self.metrics.clone(),
            #[cfg(feature = "events")]
            self.event_system.clone(),
        )
    }

    /// Access the event system for pub/sub and webhook management.
    ///
    /// Mirrors [`Commerce::events`](crate::Commerce::events) so that async
    /// PostgreSQL users can subscribe to the same [`CommerceEvent`] stream that
    /// the sync facade emits.
    #[cfg(feature = "events")]
    #[must_use]
    pub fn events(&self) -> &EventSystem {
        &self.event_system
    }

    /// Access async inventory operations.
    pub fn inventory(&self) -> AsyncInventory {
        AsyncInventory::new(self.db.clone(), self.metrics.clone())
    }

    /// Access async customer operations.
    pub fn customers(&self) -> AsyncCustomers {
        AsyncCustomers::new(self.db.clone(), self.metrics.clone())
    }

    /// Access async product operations.
    pub fn products(&self) -> AsyncProducts {
        AsyncProducts::new(self.db.clone(), self.metrics.clone())
    }

    /// Access async custom objects operations (custom states / metaobjects).
    pub fn custom_objects(&self) -> AsyncCustomObjects {
        AsyncCustomObjects::new(self.db.clone())
    }

    /// Alias for `custom_objects` (for users who prefer the "custom states" name).
    pub fn custom_states(&self) -> AsyncCustomObjects {
        self.custom_objects()
    }

    /// Access async return operations.
    pub fn returns(&self) -> AsyncReturns {
        AsyncReturns::new(self.db.clone(), self.metrics.clone())
    }

    /// Access async shipment operations.
    pub fn shipments(&self) -> AsyncShipments {
        AsyncShipments::new(self.db.clone(), self.metrics.clone())
    }

    /// Access async payment operations.
    pub fn payments(&self) -> AsyncPayments {
        AsyncPayments::new(self.db.clone(), self.metrics.clone())
    }

    /// Access async warranty operations.
    pub fn warranties(&self) -> AsyncWarranties {
        AsyncWarranties::new(self.db.clone())
    }

    /// Access async gift card operations.
    pub fn gift_cards(&self) -> AsyncGiftCards {
        AsyncGiftCards::new(self.db.clone())
    }

    /// Access async store credit operations.
    pub fn store_credits(&self) -> AsyncStoreCredits {
        AsyncStoreCredits::new(self.db.clone())
    }

    /// Access async loyalty operations.
    pub fn loyalty(&self) -> AsyncLoyalty {
        AsyncLoyalty::new(self.db.clone())
    }

    /// Access async BOM operations.
    pub fn bom(&self) -> AsyncBom {
        AsyncBom::new(self.db.clone())
    }

    /// Access async work order operations.
    pub fn work_orders(&self) -> AsyncWorkOrders {
        AsyncWorkOrders::new(self.db.clone())
    }

    /// Access async purchase order operations.
    pub fn purchase_orders(&self) -> AsyncPurchaseOrders {
        AsyncPurchaseOrders::new(self.db.clone())
    }

    /// Access async invoice operations.
    pub fn invoices(&self) -> AsyncInvoices {
        AsyncInvoices::new(self.db.clone())
    }

    /// Access async cart operations.
    pub fn carts(&self) -> AsyncCarts {
        AsyncCarts::new(self.db.clone(), self.metrics.clone())
    }

    /// Access async analytics operations.
    pub fn analytics(&self) -> AsyncAnalytics {
        AsyncAnalytics::new(self.db.clone())
    }

    /// Access async currency operations.
    pub fn currency(&self) -> AsyncCurrency {
        AsyncCurrency::new(self.db.clone())
    }

    /// Access async tax operations.
    pub fn tax(&self) -> AsyncTax {
        AsyncTax::new(self.db.clone())
    }

    /// Access async promotions operations.
    pub fn promotions(&self) -> AsyncPromotions {
        AsyncPromotions::new(self.db.clone())
    }

    /// Access async subscriptions operations.
    pub fn subscriptions(&self) -> AsyncSubscriptions {
        AsyncSubscriptions::new(self.db.clone(), self.metrics.clone())
    }

    /// Access async quality operations.
    pub fn quality(&self) -> AsyncQuality {
        AsyncQuality::new(self.db.clone())
    }

    /// Access async lot operations.
    pub fn lots(&self) -> AsyncLots {
        AsyncLots::new(self.db.clone())
    }

    /// Access async serial operations.
    pub fn serials(&self) -> AsyncSerials {
        AsyncSerials::new(self.db.clone())
    }

    /// Access async warehouse operations.
    pub fn warehouse(&self) -> AsyncWarehouse {
        AsyncWarehouse::new(self.db.clone())
    }

    /// Access async receiving operations.
    pub fn receiving(&self) -> AsyncReceiving {
        AsyncReceiving::new(self.db.clone())
    }

    /// Access async fulfillment operations.
    pub fn fulfillment(&self) -> AsyncFulfillment {
        AsyncFulfillment::new(self.db.clone())
    }

    /// Access async accounts payable operations.
    pub fn accounts_payable(&self) -> AsyncAccountsPayable {
        AsyncAccountsPayable::new(self.db.clone())
    }

    /// Access async cost accounting operations.
    pub fn cost_accounting(&self) -> AsyncCostAccounting {
        AsyncCostAccounting::new(self.db.clone())
    }

    /// Access async credit operations.
    pub fn credit(&self) -> AsyncCredit {
        AsyncCredit::new(self.db.clone())
    }

    /// Access async backorder operations.
    pub fn backorder(&self) -> AsyncBackorder {
        AsyncBackorder::new(self.db.clone())
    }

    /// Access async accounts receivable operations.
    pub fn accounts_receivable(&self) -> AsyncAccountsReceivable {
        AsyncAccountsReceivable::new(self.db.clone())
    }

    /// Access async general ledger operations.
    pub fn general_ledger(&self) -> AsyncGeneralLedger {
        AsyncGeneralLedger::new(self.db.clone())
    }

    /// Access async fixed asset register operations.
    pub fn fixed_assets(&self) -> AsyncFixedAssets {
        AsyncFixedAssets::new(self.db.clone())
    }

    /// Access async revenue recognition operations.
    pub fn revenue_recognition(&self) -> AsyncRevenueRecognition {
        AsyncRevenueRecognition::new(self.db.clone())
    }

    /// Access async x402 and A2A operations.
    pub fn x402(&self) -> AsyncX402 {
        AsyncX402::new(self.db.clone())
    }

    /// Get the underlying database for advanced operations.
    pub fn database(&self) -> &PostgresDatabase {
        &self.db
    }

    /// Access async metrics handle.
    pub const fn metrics(&self) -> &Metrics {
        &self.metrics
    }

    /// Return a point-in-time metrics snapshot.
    pub fn metrics_snapshot(&self) -> MetricsSnapshot {
        self.metrics.snapshot()
    }
}

// ============================================================================
// Async Orders
// ============================================================================

mod b2b;
mod core;
mod finance;
mod growth;
mod manufacturing;
mod storefront;
mod traceability;
mod warehouse;
mod x402;

pub use b2b::*;
pub use core::*;
pub use finance::*;
pub use growth::*;
pub use manufacturing::*;
pub use storefront::*;
pub use traceability::*;
pub use warehouse::*;
pub use x402::*;

impl_opaque_debug!(
    AsyncCommerce,
    AsyncFixedAssets,
    AsyncRevenueRecognition,
    AsyncGiftCards,
    AsyncStoreCredits,
    AsyncLoyalty,
    AsyncOrders,
    AsyncInventory,
    AsyncCustomers,
    AsyncProducts,
    AsyncCustomObjects,
    AsyncReturns,
    AsyncShipments,
    AsyncPayments,
    AsyncWarranties,
    AsyncBom,
    AsyncWorkOrders,
    AsyncPurchaseOrders,
    AsyncInvoices,
    AsyncCarts,
    AsyncAnalytics,
    AsyncCurrency,
    AsyncTax,
    AsyncPromotions,
    AsyncSubscriptions,
    AsyncQuality,
    AsyncLots,
    AsyncSerials,
    AsyncWarehouse,
    AsyncReceiving,
    AsyncFulfillment,
    AsyncAccountsPayable,
    AsyncCostAccounting,
    AsyncCredit,
    AsyncBackorder,
    AsyncAccountsReceivable,
    AsyncGeneralLedger,
    AsyncX402,
);