pub(crate) use chrono::{DateTime, NaiveDate, Utc};
pub(crate) use rust_decimal::{Decimal, prelude::ToPrimitive};
pub(crate) use stateset_core::{
AddCartItem,
AddShipmentEvent,
AddWorkOrderMaterial,
AdjustInventory,
AnalyticsQuery,
BillOfMaterials,
BomComponent,
BomFilter,
Cart,
CartAddress,
CartFilter,
CartItem,
CheckoutResult,
ClaimResolution,
ConversionResult,
ConvertCurrency,
CreateBom,
CreateBomComponent,
CreateCart,
CreateCustomer,
CreateCustomerAddress,
CreateInventoryItem,
CreateInvoice,
CreateInvoiceItem,
CreateOrder,
CreateOrderItem,
CreatePayment,
CreatePaymentMethod,
CreateProduct,
CreateProductVariant,
CreatePurchaseOrder,
CreatePurchaseOrderItem,
CreateRefund,
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,
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,
CreateBackorder,
CreateBill,
CreateBillItem,
CreateBillPayment,
CreateBillingCycle,
CreateCollectionActivity,
CreateCostAdjustment,
CreateCostLayer,
CreateCouponCode,
CreateCreditAccount,
CreateCreditMemo,
CreateDefectCode,
CreateGlAccount,
CreateGlPeriod,
CreateInspection,
CreateJournalEntry,
CreateLocation,
CreateLot,
CreateNonConformance,
CreatePackTask,
CreatePaymentRun,
CreatePickTask,
CreatePromotion,
CreatePutAway,
CreateQualityHold,
CreateReceipt,
CreateSerialNumber,
CreateSerialNumbersBulk,
CreateShipTask,
CreateSubscription,
CreateSubscriptionPlan,
CreateTaxExemption,
CreateTaxJurisdiction,
CreateTaxRate,
CreateWarehouse,
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,
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::{
CreateCycleCount,
CreateFixedAsset,
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()
}
}
)+
};
}
pub struct AsyncCommerce {
db: Arc<PostgresDatabase>,
metrics: Metrics,
#[cfg(feature = "events")]
event_system: Arc<EventSystem>,
}
impl AsyncCommerce {
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()),
})
}
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()),
})
}
pub fn from_database(db: Arc<PostgresDatabase>) -> Self {
Self {
db,
metrics: init_metrics(MetricsConfig::default()),
#[cfg(feature = "events")]
event_system: Arc::new(EventSystem::new()),
}
}
pub fn orders(&self) -> AsyncOrders {
AsyncOrders::new(
self.db.clone(),
self.metrics.clone(),
#[cfg(feature = "events")]
self.event_system.clone(),
)
}
#[cfg(feature = "events")]
#[must_use]
pub fn events(&self) -> &EventSystem {
&self.event_system
}
pub fn inventory(&self) -> AsyncInventory {
AsyncInventory::new(self.db.clone(), self.metrics.clone())
}
pub fn customers(&self) -> AsyncCustomers {
AsyncCustomers::new(self.db.clone(), self.metrics.clone())
}
pub fn products(&self) -> AsyncProducts {
AsyncProducts::new(self.db.clone(), self.metrics.clone())
}
pub fn custom_objects(&self) -> AsyncCustomObjects {
AsyncCustomObjects::new(self.db.clone())
}
pub fn custom_states(&self) -> AsyncCustomObjects {
self.custom_objects()
}
pub fn returns(&self) -> AsyncReturns {
AsyncReturns::new(self.db.clone(), self.metrics.clone())
}
pub fn shipments(&self) -> AsyncShipments {
AsyncShipments::new(self.db.clone(), self.metrics.clone())
}
pub fn payments(&self) -> AsyncPayments {
AsyncPayments::new(self.db.clone(), self.metrics.clone())
}
pub fn warranties(&self) -> AsyncWarranties {
AsyncWarranties::new(self.db.clone())
}
pub fn gift_cards(&self) -> AsyncGiftCards {
AsyncGiftCards::new(self.db.clone())
}
pub fn store_credits(&self) -> AsyncStoreCredits {
AsyncStoreCredits::new(self.db.clone())
}
pub fn loyalty(&self) -> AsyncLoyalty {
AsyncLoyalty::new(self.db.clone())
}
pub fn bom(&self) -> AsyncBom {
AsyncBom::new(self.db.clone())
}
pub fn work_orders(&self) -> AsyncWorkOrders {
AsyncWorkOrders::new(self.db.clone())
}
pub fn purchase_orders(&self) -> AsyncPurchaseOrders {
AsyncPurchaseOrders::new(self.db.clone())
}
pub fn invoices(&self) -> AsyncInvoices {
AsyncInvoices::new(self.db.clone())
}
pub fn carts(&self) -> AsyncCarts {
AsyncCarts::new(self.db.clone(), self.metrics.clone())
}
pub fn analytics(&self) -> AsyncAnalytics {
AsyncAnalytics::new(self.db.clone())
}
pub fn currency(&self) -> AsyncCurrency {
AsyncCurrency::new(self.db.clone())
}
pub fn tax(&self) -> AsyncTax {
AsyncTax::new(self.db.clone())
}
pub fn promotions(&self) -> AsyncPromotions {
AsyncPromotions::new(self.db.clone())
}
pub fn subscriptions(&self) -> AsyncSubscriptions {
AsyncSubscriptions::new(self.db.clone(), self.metrics.clone())
}
pub fn quality(&self) -> AsyncQuality {
AsyncQuality::new(self.db.clone())
}
pub fn lots(&self) -> AsyncLots {
AsyncLots::new(self.db.clone())
}
pub fn serials(&self) -> AsyncSerials {
AsyncSerials::new(self.db.clone())
}
pub fn warehouse(&self) -> AsyncWarehouse {
AsyncWarehouse::new(self.db.clone())
}
pub fn receiving(&self) -> AsyncReceiving {
AsyncReceiving::new(self.db.clone())
}
pub fn fulfillment(&self) -> AsyncFulfillment {
AsyncFulfillment::new(self.db.clone())
}
pub fn accounts_payable(&self) -> AsyncAccountsPayable {
AsyncAccountsPayable::new(self.db.clone())
}
pub fn cost_accounting(&self) -> AsyncCostAccounting {
AsyncCostAccounting::new(self.db.clone())
}
pub fn credit(&self) -> AsyncCredit {
AsyncCredit::new(self.db.clone())
}
pub fn backorder(&self) -> AsyncBackorder {
AsyncBackorder::new(self.db.clone())
}
pub fn accounts_receivable(&self) -> AsyncAccountsReceivable {
AsyncAccountsReceivable::new(self.db.clone())
}
pub fn general_ledger(&self) -> AsyncGeneralLedger {
AsyncGeneralLedger::new(self.db.clone())
}
pub fn fixed_assets(&self) -> AsyncFixedAssets {
AsyncFixedAssets::new(self.db.clone())
}
pub fn revenue_recognition(&self) -> AsyncRevenueRecognition {
AsyncRevenueRecognition::new(self.db.clone())
}
pub fn x402(&self) -> AsyncX402 {
AsyncX402::new(self.db.clone())
}
pub fn database(&self) -> &PostgresDatabase {
&self.db
}
pub const fn metrics(&self) -> &Metrics {
&self.metrics
}
pub fn metrics_snapshot(&self) -> MetricsSnapshot {
self.metrics.snapshot()
}
}
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,
);