pub struct Commerce { /* private fields */ }Expand description
The main commerce interface.
This is the entry point to all commerce operations. Initialize it once and use the accessor methods to perform operations.
§Example
use stateset_embedded::Commerce;
// SQLite (default)
let commerce = Commerce::new("./store.db")?;
// Access different domains
let orders = commerce.orders();
let inventory = commerce.inventory();
let customers = commerce.customers();
let products = commerce.products();
let returns = commerce.returns();Implementations§
Source§impl Commerce
impl Commerce
Sourcepub fn orders(&self) -> Orders
pub fn orders(&self) -> Orders
Access order operations.
§Example
use stateset_embedded::{Commerce, CreateOrder, CreateOrderItem};
use rust_decimal_macros::dec;
use uuid::Uuid;
let commerce = Commerce::new("./store.db")?;
let order = commerce.orders().create(CreateOrder {
customer_id: Uuid::new_v4(),
items: vec![CreateOrderItem {
product_id: Uuid::new_v4(),
sku: "SKU-001".into(),
name: "Widget".into(),
quantity: 2,
unit_price: dec!(29.99),
..Default::default()
}],
..Default::default()
})?;Sourcepub fn inventory(&self) -> Inventory
pub fn inventory(&self) -> Inventory
Access inventory operations.
§Example
use stateset_embedded::{Commerce, CreateInventoryItem};
use rust_decimal_macros::dec;
let commerce = Commerce::new("./store.db")?;
// Create inventory item
commerce.inventory().create_item(CreateInventoryItem {
sku: "SKU-001".into(),
name: "Widget".into(),
initial_quantity: Some(dec!(100)),
..Default::default()
})?;
// Check stock
let stock = commerce.inventory().get_stock("SKU-001")?;
// Adjust stock
commerce.inventory().adjust("SKU-001", dec!(-5), "Sold")?;Sourcepub fn customers(&self) -> Customers
pub fn customers(&self) -> Customers
Access customer operations.
§Example
use stateset_embedded::{Commerce, CreateCustomer};
let commerce = Commerce::new("./store.db")?;
let customer = commerce.customers().create(CreateCustomer {
email: "alice@example.com".into(),
first_name: "Alice".into(),
last_name: "Smith".into(),
..Default::default()
})?;Sourcepub fn products(&self) -> Products
pub fn products(&self) -> Products
Access product operations.
§Example
use stateset_embedded::{Commerce, CreateProduct, CreateProductVariant};
use rust_decimal_macros::dec;
let commerce = Commerce::new("./store.db")?;
let product = commerce.products().create(CreateProduct {
name: "Premium Widget".into(),
description: Some("A high-quality widget".into()),
variants: Some(vec![CreateProductVariant {
sku: "WIDGET-001".into(),
price: dec!(49.99),
..Default::default()
}]),
..Default::default()
})?;Sourcepub fn custom_objects(&self) -> CustomObjects
pub fn custom_objects(&self) -> CustomObjects
Access custom objects (custom states / metaobjects) operations.
Sourcepub fn custom_states(&self) -> CustomObjects
pub fn custom_states(&self) -> CustomObjects
Alias for custom_objects() (for users who prefer the “custom states” name).
Sourcepub fn returns(&self) -> Returns
pub fn returns(&self) -> Returns
Access return operations.
§Example
use stateset_embedded::{Commerce, CreateReturn, CreateReturnItem, ReturnReason};
use uuid::Uuid;
let commerce = Commerce::new("./store.db")?;
let ret = commerce.returns().create(CreateReturn {
order_id: Uuid::new_v4(),
reason: ReturnReason::Defective,
items: vec![CreateReturnItem {
order_item_id: Uuid::new_v4(),
quantity: 1,
..Default::default()
}],
..Default::default()
})?;Sourcepub fn bom(&self) -> Bom
pub fn bom(&self) -> Bom
Access Bill of Materials (BOM) operations.
§Example
use stateset_embedded::{Commerce, CreateBom, CreateBomComponent};
use rust_decimal_macros::dec;
use uuid::Uuid;
let commerce = Commerce::new("./store.db")?;
let bom = commerce.bom().create(CreateBom {
product_id: Uuid::new_v4(),
name: "Widget Assembly".into(),
components: Some(vec![
CreateBomComponent {
name: "Part A".into(),
quantity: dec!(2),
..Default::default()
},
]),
..Default::default()
})?;Sourcepub fn work_orders(&self) -> WorkOrders
pub fn work_orders(&self) -> WorkOrders
Access work order operations.
§Example
use stateset_embedded::{Commerce, CreateWorkOrder};
use rust_decimal_macros::dec;
use uuid::Uuid;
let commerce = Commerce::new("./store.db")?;
let wo = commerce.work_orders().create(CreateWorkOrder {
product_id: Uuid::new_v4(),
quantity_to_build: dec!(100),
..Default::default()
})?;
// Start production
let wo = commerce.work_orders().start(wo.id)?;Sourcepub fn shipments(&self) -> Shipments
pub fn shipments(&self) -> Shipments
Access shipment operations.
§Example
use stateset_embedded::{Commerce, CreateShipment, CreateShipmentItem, ShippingCarrier};
use uuid::Uuid;
let commerce = Commerce::new("./store.db")?;
let shipment = commerce.shipments().create(CreateShipment {
order_id: Uuid::new_v4(),
carrier: Some(ShippingCarrier::Ups),
recipient_name: "Alice Smith".into(),
shipping_address: "123 Main St, City, ST 12345".into(),
items: Some(vec![CreateShipmentItem {
sku: "SKU-001".into(),
name: "Widget".into(),
quantity: 2,
..Default::default()
}]),
..Default::default()
})?;
// Ship with tracking number
let shipment = commerce.shipments().ship(shipment.id, Some("1Z999AA10123456784".into()))?;
// Mark as delivered
let shipment = commerce.shipments().mark_delivered(shipment.id)?;Sourcepub fn payments(&self) -> Payments
pub fn payments(&self) -> Payments
Access payment operations.
§Example
use stateset_embedded::{Commerce, CreatePayment, PaymentMethodType, CardBrand};
use rust_decimal_macros::dec;
use uuid::Uuid;
let commerce = Commerce::new("./store.db")?;
let payment = commerce.payments().create(CreatePayment {
order_id: Some(Uuid::new_v4()),
payment_method: PaymentMethodType::CreditCard,
amount: dec!(99.99),
card_brand: Some(CardBrand::Visa),
card_last4: Some("4242".into()),
..Default::default()
})?;
// Mark payment as completed
let payment = commerce.payments().mark_completed(payment.id)?;Sourcepub fn warranties(&self) -> Warranties
pub fn warranties(&self) -> Warranties
Access warranty operations.
§Example
use stateset_embedded::{Commerce, CreateWarranty, WarrantyType};
use uuid::Uuid;
let commerce = Commerce::new("./store.db")?;
let warranty = commerce.warranties().create(CreateWarranty {
customer_id: Uuid::new_v4(),
product_id: Some(Uuid::new_v4()),
warranty_type: Some(WarrantyType::Extended),
duration_months: Some(24),
..Default::default()
})?;
// Check if warranty is valid
assert!(commerce.warranties().is_valid(warranty.id)?);Sourcepub fn purchase_orders(&self) -> PurchaseOrders
pub fn purchase_orders(&self) -> PurchaseOrders
Access purchase order operations.
§Example
use stateset_embedded::{Commerce, CreatePurchaseOrder, CreatePurchaseOrderItem, CreateSupplier};
use rust_decimal_macros::dec;
let commerce = Commerce::new("./store.db")?;
// Create a supplier
let supplier = commerce.purchase_orders().create_supplier(CreateSupplier {
name: "Acme Supplies".into(),
email: Some("orders@acme.com".into()),
..Default::default()
})?;
// Create a purchase order
let po = commerce.purchase_orders().create(CreatePurchaseOrder {
supplier_id: supplier.id,
items: vec![CreatePurchaseOrderItem {
sku: "PART-001".into(),
name: "Widget Part".into(),
quantity: dec!(100),
unit_cost: dec!(5.99),
..Default::default()
}],
..Default::default()
})?;
// Approve and send
let po = commerce.purchase_orders().submit(po.id)?;
let po = commerce.purchase_orders().approve(po.id, "admin")?;
let po = commerce.purchase_orders().send(po.id)?;Sourcepub fn invoices(&self) -> Invoices
pub fn invoices(&self) -> Invoices
Access invoice operations.
§Example
use stateset_embedded::{Commerce, CreateInvoice, CreateInvoiceItem, RecordInvoicePayment};
use rust_decimal_macros::dec;
use uuid::Uuid;
let commerce = Commerce::new("./store.db")?;
let invoice = commerce.invoices().create(CreateInvoice {
customer_id: Uuid::new_v4(),
billing_email: Some("customer@example.com".into()),
items: vec![CreateInvoiceItem {
description: "Professional Services".into(),
quantity: dec!(10),
unit_price: dec!(150.00),
..Default::default()
}],
..Default::default()
})?;
// Send and record payment
let invoice = commerce.invoices().send(invoice.id)?;
let invoice = commerce.invoices().record_payment(invoice.id, RecordInvoicePayment {
amount: dec!(1500.00),
payment_method: Some("credit_card".into()),
..Default::default()
})?;Sourcepub fn carts(&self) -> Carts
pub fn carts(&self) -> Carts
Access cart and checkout operations.
§Example
use stateset_embedded::{Commerce, CreateCart, AddCartItem, CartAddress};
use rust_decimal_macros::dec;
use uuid::Uuid;
let commerce = Commerce::new("./store.db")?;
// Create a cart
let cart = commerce.carts().create(CreateCart {
customer_email: Some("alice@example.com".into()),
customer_name: Some("Alice Smith".into()),
..Default::default()
})?;
// Add items
commerce.carts().add_item(cart.id, AddCartItem {
sku: "SKU-001".into(),
name: "Widget".into(),
quantity: 2,
unit_price: dec!(29.99),
..Default::default()
})?;
// Set shipping address
commerce.carts().set_shipping_address(cart.id, CartAddress {
first_name: "Alice".into(),
last_name: "Smith".into(),
line1: "123 Main St".into(),
city: "Anytown".into(),
postal_code: "12345".into(),
country: "US".into(),
..Default::default()
})?;
// Complete checkout
let result = commerce.carts().complete(cart.id)?;
println!("Order created: {}", result.order_number);Sourcepub fn analytics(&self) -> Analytics
pub fn analytics(&self) -> Analytics
Access analytics and forecasting operations.
§Example
use stateset_embedded::{Commerce, AnalyticsQuery, TimePeriod};
let commerce = Commerce::new("./store.db")?;
// Get sales summary
let summary = commerce.analytics().sales_summary(
AnalyticsQuery::new().period(TimePeriod::Last30Days)
)?;
println!("Revenue: ${}", summary.total_revenue);
println!("Orders: {}", summary.order_count);
// Get top products
let top = commerce.analytics().top_products(
AnalyticsQuery::new().period(TimePeriod::ThisMonth).limit(10)
)?;
// Get inventory forecast
let forecasts = commerce.analytics().demand_forecast(None, 30)?;
for f in forecasts {
if let Some(days) = f.days_until_stockout {
if days < 14 {
println!("WARNING: {} will stock out in {} days", f.sku, days);
}
}
}Sourcepub fn currency(&self) -> CurrencyOps
pub fn currency(&self) -> CurrencyOps
Access currency and exchange rate operations.
§Example
use stateset_embedded::{Commerce, Currency, ConvertCurrency};
use rust_decimal_macros::dec;
let commerce = Commerce::new("./store.db")?;
// Get exchange rate
if let Some(rate) = commerce.currency().get_rate(Currency::USD, Currency::EUR)? {
println!("1 USD = {} EUR", rate.rate);
}
// Convert currency
let result = commerce.currency().convert(ConvertCurrency {
from: Currency::USD,
to: Currency::EUR,
amount: dec!(100.00),
})?;
println!("$100 USD = €{} EUR", result.converted_amount);
// Set exchange rates
commerce.currency().set_rate(stateset_embedded::SetExchangeRate {
base_currency: Currency::USD,
quote_currency: Currency::EUR,
rate: dec!(0.92),
source: Some("manual".into()),
})?;
// Update store settings
let settings = commerce.currency().get_settings()?;
println!("Base currency: {}", settings.base_currency);Sourcepub fn tax(&self) -> Tax
pub fn tax(&self) -> Tax
Access tax calculation and management operations.
Provides multi-jurisdiction tax calculation with support for:
- US sales tax (state, county, city levels)
- EU VAT (standard, reduced, zero-rated)
- Canadian GST/HST/PST/QST
- Customer exemptions (resale, non-profit, etc.)
§Example
use stateset_embedded::{Commerce, TaxCalculationRequest, TaxLineItem, TaxAddress, ProductTaxCategory};
use rust_decimal_macros::dec;
let commerce = Commerce::new("./store.db")?;
// Calculate tax for a transaction
let result = commerce.tax().calculate(TaxCalculationRequest {
line_items: vec![TaxLineItem {
id: "item-1".into(),
quantity: dec!(2),
unit_price: dec!(29.99),
tax_category: ProductTaxCategory::Standard,
..Default::default()
}],
shipping_address: TaxAddress {
country: "US".into(),
state: Some("CA".into()),
..Default::default()
},
..Default::default()
})?;
println!("Tax: ${}", result.total_tax);
println!("Total: ${}", result.total);
// Check effective rate for an address
let rate = commerce.tax().get_effective_rate(
&TaxAddress { country: "US".into(), state: Some("TX".into()), ..Default::default() },
ProductTaxCategory::Standard,
)?;
println!("Texas tax rate: {}%", rate * dec!(100));Sourcepub fn promotions(&self) -> Promotions
pub fn promotions(&self) -> Promotions
Access promotions and discount operations.
Provides comprehensive promotions engine supporting:
- Percentage and fixed amount discounts
- Buy X Get Y (BOGO) promotions
- Free shipping offers
- Tiered discounts based on spend/quantity
- Coupon code management
- Automatic promotions
§Example
use stateset_embedded::{Commerce, CreatePromotion, PromotionType, ApplyPromotionsRequest, PromotionLineItem};
use rust_decimal_macros::dec;
let commerce = Commerce::new("./store.db")?;
// Create a 20% off promotion
let promo = commerce.promotions().create(CreatePromotion {
name: "Summer Sale".into(),
promotion_type: PromotionType::PercentageOff,
percentage_off: Some(dec!(0.20)),
..Default::default()
})?;
// Activate it
commerce.promotions().activate(promo.id)?;
// Create a coupon code
commerce.promotions().create_coupon(stateset_embedded::CreateCouponCode {
promotion_id: promo.id,
code: "SUMMER20".into(),
usage_limit: Some(100),
..Default::default()
})?;
// Apply promotions to a cart
let result = commerce.promotions().apply(ApplyPromotionsRequest {
subtotal: dec!(100.00),
coupon_codes: vec!["SUMMER20".into()],
line_items: vec![PromotionLineItem {
id: "item-1".into(),
quantity: 2,
unit_price: dec!(50.00),
line_total: dec!(100.00),
..Default::default()
}],
..Default::default()
})?;
println!("Discount: ${}", result.total_discount);
println!("Final total: ${}", result.grand_total);Sourcepub fn subscriptions(&self) -> Subscriptions
pub fn subscriptions(&self) -> Subscriptions
Access subscription management operations.
§Example
use stateset_embedded::{Commerce, CreateSubscriptionPlan, CreateSubscription, BillingInterval};
use rust_decimal_macros::dec;
use uuid::Uuid;
let commerce = Commerce::new("./store.db")?;
// Create a subscription plan
let plan = commerce.subscriptions().create_plan(CreateSubscriptionPlan {
name: "Monthly Coffee Box".into(),
billing_interval: BillingInterval::Monthly,
price: dec!(29.99),
trial_days: Some(14),
..Default::default()
})?;
// Activate the plan
commerce.subscriptions().activate_plan(plan.id)?;
// Subscribe a customer
let subscription = commerce.subscriptions().subscribe(CreateSubscription {
customer_id: Uuid::new_v4(),
plan_id: plan.id,
..Default::default()
})?;
println!("Subscription #{} created", subscription.subscription_number);Sourcepub fn quality(&self) -> Quality
pub fn quality(&self) -> Quality
Access quality control operations.
§Example
use stateset_embedded::{Commerce, CreateInspection, InspectionType};
use uuid::Uuid;
let commerce = Commerce::new("./store.db")?;
let inspection = commerce.quality().create_inspection(CreateInspection {
inspection_type: InspectionType::Receiving,
reference_type: "purchase_order".into(),
reference_id: Uuid::new_v4(),
..Default::default()
})?;
println!("Created inspection #{}", inspection.inspection_number);Sourcepub fn lots(&self) -> Lots
pub fn lots(&self) -> Lots
Access lot/batch tracking operations.
§Example
use stateset_embedded::{Commerce, CreateLot};
use chrono::{Utc, Duration};
use rust_decimal_macros::dec;
let commerce = Commerce::new("./store.db")?;
let lot = commerce.lots().create(CreateLot {
lot_number: Some("LOT-2025-001".into()),
sku: "RAW-001".into(),
quantity_produced: dec!(1000),
expiration_date: Some(Utc::now() + Duration::days(365)),
..Default::default()
})?;
println!("Created lot {}", lot.lot_number);Sourcepub fn serials(&self) -> Serials
pub fn serials(&self) -> Serials
Access serial number management operations.
§Example
use stateset_embedded::{Commerce, CreateSerialNumber};
let commerce = Commerce::new("./store.db")?;
let serial = commerce.serials().create(CreateSerialNumber {
serial: Some("SN-12345-ABCD".into()),
sku: "LAPTOP-PRO-15".into(),
..Default::default()
})?;
println!("Created serial {}", serial.serial);Sourcepub fn warehouse(&self) -> WarehouseOps
pub fn warehouse(&self) -> WarehouseOps
Access warehouse and location management operations.
§Example
use stateset_embedded::{Commerce, CreateWarehouse, CreateLocation, WarehouseType, LocationType};
let commerce = Commerce::new("./store.db")?;
// Create a warehouse
let warehouse = commerce.warehouse().create_warehouse(CreateWarehouse {
code: "WH-001".into(),
name: "Main Distribution Center".into(),
warehouse_type: WarehouseType::Distribution,
..Default::default()
})?;
// Create a location
let location = commerce.warehouse().create_location(CreateLocation {
warehouse_id: warehouse.id,
location_type: LocationType::Pick,
zone: Some("A".into()),
aisle: Some("01".into()),
..Default::default()
})?;
println!("Created location {} in {}", location.code, warehouse.name);Sourcepub fn receiving(&self) -> Receiving
pub fn receiving(&self) -> Receiving
Access receiving and goods receipt operations.
§Example
use stateset_embedded::{Commerce, CreateReceipt, CreateReceiptItem, ReceiptType};
use rust_decimal_macros::dec;
let commerce = Commerce::new("./store.db")?;
// Create a receipt
let receipt = commerce.receiving().create_receipt(CreateReceipt {
receipt_type: ReceiptType::PurchaseOrder,
warehouse_id: 1,
items: vec![CreateReceiptItem {
sku: "WIDGET-001".into(),
expected_quantity: dec!(100),
..Default::default()
}],
..Default::default()
})?;
println!("Created receipt {}", receipt.receipt_number);Sourcepub fn fulfillment(&self) -> Fulfillment
pub fn fulfillment(&self) -> Fulfillment
Access fulfillment (pick/pack/ship) operations.
§Example
use stateset_embedded::{Commerce, CreateWave, PickTaskFilter};
use uuid::Uuid;
let commerce = Commerce::new("./store.db")?;
// Create a wave from orders
let wave = commerce.fulfillment().create_wave(CreateWave {
warehouse_id: 1,
order_ids: vec![Uuid::new_v4()],
..Default::default()
})?;
// Get picks for the wave
let picks = commerce.fulfillment().get_picks_for_wave(wave.id)?;Sourcepub fn accounts_payable(&self) -> AccountsPayable
pub fn accounts_payable(&self) -> AccountsPayable
Access accounts payable (bills and supplier payments) operations.
§Example
use stateset_embedded::{Commerce, CreateBill, CreateBillItem};
use rust_decimal_macros::dec;
use chrono::{Utc, Duration};
use uuid::Uuid;
let commerce = Commerce::new("./store.db")?;
// Create a bill from a supplier
let bill = commerce.accounts_payable().create_bill(CreateBill {
supplier_id: Uuid::new_v4(),
due_date: Utc::now() + Duration::days(30),
items: vec![CreateBillItem {
description: "Office supplies".into(),
quantity: dec!(1),
unit_price: dec!(150.00),
..Default::default()
}],
..Default::default()
})?;
// Get aging summary
let aging = commerce.accounts_payable().get_aging_summary()?;
println!("Total AP: ${}", aging.total);Sourcepub fn cost_accounting(&self) -> CostAccounting
pub fn cost_accounting(&self) -> CostAccounting
Access cost accounting operations.
§Example
use stateset_embedded::{Commerce, SetItemCost, CostMethod};
use rust_decimal_macros::dec;
let commerce = Commerce::new("./store.db")?;
// Set standard cost for an item
let cost = commerce.cost_accounting().set_item_cost(SetItemCost {
sku: "WIDGET-001".into(),
cost_method: Some(CostMethod::Average),
standard_cost: Some(dec!(10.00)),
..Default::default()
})?;
// Get inventory valuation
let valuation = commerce.cost_accounting().get_inventory_valuation(CostMethod::Average)?;
println!("Total inventory value: ${}", valuation.total_value);Sourcepub fn credit(&self) -> Credit
pub fn credit(&self) -> Credit
Access credit management operations.
§Example
use stateset_embedded::{Commerce, CreateCreditAccount};
use rust_decimal_macros::dec;
use uuid::Uuid;
let commerce = Commerce::new("./store.db")?;
// Create credit account for a customer
let account = commerce.credit().create_credit_account(CreateCreditAccount {
customer_id: Uuid::new_v4(),
credit_limit: dec!(10000.00),
payment_terms: Some("Net 30".into()),
..Default::default()
})?;
// Check credit for an order
let result = commerce.credit().check_credit(account.customer_id, dec!(5000.00))?;
println!("Credit approved: {}", result.approved);Sourcepub fn backorder(&self) -> Backorders
pub fn backorder(&self) -> Backorders
Access backorder management operations.
§Example
use stateset_embedded::{Commerce, CreateBackorder, BackorderPriority};
use rust_decimal_macros::dec;
use uuid::Uuid;
let commerce = Commerce::new("./store.db")?;
// Create a backorder when inventory is unavailable
let backorder = commerce.backorder().create_backorder(CreateBackorder {
order_id: Uuid::new_v4(),
customer_id: Uuid::new_v4(),
sku: "WIDGET-001".into(),
quantity: dec!(50),
priority: Some(BackorderPriority::High),
..Default::default()
})?;
// Get overdue backorders
let overdue = commerce.backorder().get_overdue_backorders()?;
println!("Overdue backorders: {}", overdue.len());Sourcepub fn accounts_receivable(&self) -> AccountsReceivable
pub fn accounts_receivable(&self) -> AccountsReceivable
Access accounts receivable operations.
Provides AR aging, collection activities, write-offs, credit memos, and customer statement generation.
§Example
use stateset_embedded::Commerce;
let commerce = Commerce::new("./store.db")?;
// Get AR aging summary
let aging = commerce.accounts_receivable().get_aging_summary()?;
println!("Current: ${}", aging.current);
println!("1-30 days: ${}", aging.days_1_30);
println!("31-60 days: ${}", aging.days_31_60);
println!("61-90 days: ${}", aging.days_61_90);
println!("90+ days: ${}", aging.days_over_90);
// Get DSO (Days Sales Outstanding)
let dso = commerce.accounts_receivable().get_dso(30)?;
println!("DSO (30 day): {}", dso);Sourcepub fn general_ledger(&self) -> GeneralLedger
pub fn general_ledger(&self) -> GeneralLedger
Access general ledger operations.
Provides chart of accounts management, journal entries, period management, and financial reporting.
§Example
use stateset_embedded::{Commerce, CreateJournalEntry};
use chrono::NaiveDate;
let commerce = Commerce::new("./store.db")?;
// Initialize standard chart of accounts
commerce.general_ledger().initialize_chart_of_accounts()?;
// Generate trial balance
let trial_balance = commerce.general_ledger().get_trial_balance(
NaiveDate::from_ymd_opt(2025, 1, 31).unwrap()
)?;
println!("Total Debits: ${}", trial_balance.total_debits);
println!("Total Credits: ${}", trial_balance.total_credits);
println!("Balanced: {}", trial_balance.is_balanced);
// Generate income statement
let income = commerce.general_ledger().get_income_statement(
NaiveDate::from_ymd_opt(2025, 1, 1).unwrap(),
NaiveDate::from_ymd_opt(2025, 1, 31).unwrap(),
)?;
println!("Revenue: ${}", income.total_revenue);
println!("Expenses: ${}", income.total_expenses);
println!("Net Income: ${}", income.net_income);Sourcepub fn x402(&self) -> X402
pub fn x402(&self) -> X402
Access x402 payment protocol and agent card operations.
Provides x402 stablecoin payment intents for AI agent commerce, including intent creation, signing, settlement tracking, and agent card management for A2A (agent-to-agent) commerce.
§Example
use stateset_embedded::{Commerce, CreateX402PaymentIntent, X402Network, X402Asset};
use rust_decimal_macros::dec;
let commerce = Commerce::new("./store.db")?;
// Create a payment intent
let intent = commerce.x402().create_intent(CreateX402PaymentIntent {
payer_address: "0xBuyer...".into(),
payee_address: "0xSeller...".into(),
amount: dec!(100.00),
asset: X402Asset::Usdc,
network: X402Network::SetChain,
..Default::default()
})?;
// Register an agent card
use stateset_embedded::{CreateAgentCard, A2ASkill};
let card = commerce.x402().register_agent(CreateAgentCard {
name: "Commerce Bot".into(),
wallet_address: "0xAgent...".into(),
public_key: "ed25519_pubkey_base64".into(),
supported_networks: vec![X402Network::SetChain],
supported_assets: vec![X402Asset::Usdc, X402Asset::SsUsd],
a2a_skills: Some(vec![A2ASkill::Sell, A2ASkill::Quote]),
..Default::default()
})?;
// Discover agents with specific capabilities
let sellers = commerce.x402().discover_agents(
Some(vec![X402Network::SetChain]),
Some(vec![X402Asset::Usdc]),
Some(vec!["Sell".to_string()]),
None,
)?;Sourcepub fn erc8004(&self) -> Erc8004
pub fn erc8004(&self) -> Erc8004
Access ERC-8004 trustless agent registries.
Provides identity, reputation, and validation registry operations for trustless agent discovery across organizational boundaries.
Sourcepub fn gift_cards(&self) -> GiftCards
pub fn gift_cards(&self) -> GiftCards
Access gift card operations.
Provides gift card issuance, charging, refunding, and transaction history.
Sourcepub fn store_credits(&self) -> StoreCredits
pub fn store_credits(&self) -> StoreCredits
Access store credit operations.
Provides store credit management including balance adjustments and application to orders.
Sourcepub fn segments(&self) -> Segments
pub fn segments(&self) -> Segments
Access customer segment operations.
Provides customer grouping, membership management, and segment targeting.
Sourcepub fn shipping_zones(&self) -> ShippingZones
pub fn shipping_zones(&self) -> ShippingZones
Access shipping zone and method operations.
Provides shipping zone management, method configuration, and rate calculation.
Sourcepub fn transfer_orders(&self) -> TransferOrders
pub fn transfer_orders(&self) -> TransferOrders
Access transfer order operations (inter-warehouse stock movement).
Sourcepub fn units_of_measure(&self) -> UnitsOfMeasure
pub fn units_of_measure(&self) -> UnitsOfMeasure
Access units-of-measure operations (classes, UOMs, conversion rules).
Sourcepub fn production_batches(&self) -> ProductionBatches
pub fn production_batches(&self) -> ProductionBatches
Access production batch operations.
Sourcepub fn supplier_skus(&self) -> SupplierSkus
pub fn supplier_skus(&self) -> SupplierSkus
Access supplier SKU operations.
Sourcepub fn fixed_assets(&self) -> FixedAssets
pub fn fixed_assets(&self) -> FixedAssets
Access fixed asset register operations.
Sourcepub fn maintenance(&self) -> Maintenance
pub fn maintenance(&self) -> Maintenance
Sourcepub fn revenue_recognition(&self) -> RevenueRecognition
pub fn revenue_recognition(&self) -> RevenueRecognition
Access revenue recognition (ASC 606) operations.
Sourcepub fn vendor_returns(&self) -> VendorReturns
pub fn vendor_returns(&self) -> VendorReturns
Access vendor return operations.
Sourcepub fn vendor_credits(&self) -> VendorCredits
pub fn vendor_credits(&self) -> VendorCredits
Access vendor credit operations.
Sourcepub fn payment_obligations(&self) -> PaymentObligations
pub fn payment_obligations(&self) -> PaymentObligations
Access payment obligation operations.
Sourcepub fn price_levels(&self) -> PriceLevels
pub fn price_levels(&self) -> PriceLevels
Access price level (B2B pricing tier) operations.
Sourcepub fn prepayments(&self) -> Prepayments
pub fn prepayments(&self) -> Prepayments
Access prepayment operations.
Sourcepub fn price_schedules(&self) -> PriceSchedules
pub fn price_schedules(&self) -> PriceSchedules
Access price schedule (time-bounded pricing) operations.
Sourcepub fn activity_logs(&self) -> ActivityLogs
pub fn activity_logs(&self) -> ActivityLogs
Access activity log (subject history) operations.
Sourcepub fn integration_mappings(&self) -> IntegrationMappings
pub fn integration_mappings(&self) -> IntegrationMappings
Access integration mapping operations.
Sourcepub fn inbound_shipments(&self) -> InboundShipments
pub fn inbound_shipments(&self) -> InboundShipments
Access inbound shipment (ASN) operations.
Sourcepub fn print_stations(&self) -> PrintStations
pub fn print_stations(&self) -> PrintStations
Access print station operations.
Sourcepub fn edi_documents(&self) -> EdiDocuments
pub fn edi_documents(&self) -> EdiDocuments
Access EDI document operations.
Sourcepub fn integration_field_mappings(&self) -> IntegrationFieldMappings
pub fn integration_field_mappings(&self) -> IntegrationFieldMappings
Access integration field-mapping operations.
Sourcepub fn topology_snapshots(&self) -> TopologySnapshots
pub fn topology_snapshots(&self) -> TopologySnapshots
Access customer operational topology snapshot operations.
Sourcepub fn stock_snapshots(&self) -> StockSnapshots
pub fn stock_snapshots(&self) -> StockSnapshots
Access stock snapshot (point-in-time inventory) operations.
Sourcepub fn reviews(&self) -> Reviews
pub fn reviews(&self) -> Reviews
Access product review operations.
Provides review creation, moderation, summaries, and helpful/reported tracking.
Sourcepub fn wishlists(&self) -> Wishlists
pub fn wishlists(&self) -> Wishlists
Access wishlist operations.
Provides wishlist creation, item management, and customer wish tracking.
Sourcepub fn loyalty(&self) -> Loyalty
pub fn loyalty(&self) -> Loyalty
Access loyalty program operations.
Provides loyalty program management, customer enrollment, points tracking, and reward catalog operations.
Sourcepub fn fraud(&self) -> Fraud
pub fn fraud(&self) -> Fraud
Access fraud detection operations.
Provides fraud risk assessment, rule management, and manual review workflows.
Sourcepub fn search_config(&self) -> SearchConfigs
pub fn search_config(&self) -> SearchConfigs
Access search configuration operations.
Provides search configuration management including active config selection.
Sourcepub fn calculate_cart_tax(&self, cart_id: Uuid) -> Result<TaxCalculationResult>
pub fn calculate_cart_tax(&self, cart_id: Uuid) -> Result<TaxCalculationResult>
Calculate and apply tax to a cart based on its shipping address.
This method:
- Retrieves the cart and its items
- Uses the shipping address to determine tax jurisdiction
- Calculates tax for each item based on jurisdiction and product category
- Applies customer exemptions if applicable
- Updates the cart with the calculated tax
§Example
use stateset_embedded::{Commerce, CreateCart, AddCartItem, CartAddress};
use rust_decimal_macros::dec;
use uuid::Uuid;
let commerce = Commerce::new("./store.db")?;
// Create a cart with items
let cart = commerce.carts().create(CreateCart {
customer_email: Some("alice@example.com".into()),
..Default::default()
})?;
commerce.carts().add_item(cart.id, AddCartItem {
sku: "SKU-001".into(),
name: "Widget".into(),
quantity: 2,
unit_price: dec!(29.99),
..Default::default()
})?;
// Set shipping address
commerce.carts().set_shipping_address(cart.id, CartAddress {
first_name: "Alice".into(),
last_name: "Smith".into(),
line1: "123 Main St".into(),
city: "Los Angeles".into(),
state: Some("CA".into()),
postal_code: "90210".into(),
country: "US".into(),
..Default::default()
})?;
// Calculate and apply tax
let result = commerce.calculate_cart_tax(cart.id)?;
println!("Tax: ${}", result.total_tax);
println!("Updated cart total: ${}", commerce.carts().get(cart.id)?.unwrap().grand_total);Sourcepub fn apply_cart_promotions(
&self,
cart_id: Uuid,
) -> Result<ApplyPromotionsResult>
pub fn apply_cart_promotions( &self, cart_id: Uuid, ) -> Result<ApplyPromotionsResult>
Calculate and apply promotions to a cart.
This method:
- Retrieves the cart and its items
- Finds all applicable automatic promotions
- Validates any coupon codes applied to the cart
- Calculates discounts respecting stacking rules
- Updates the cart with the calculated discount
§Example
use stateset_embedded::{Commerce, CreateCart, AddCartItem};
use rust_decimal_macros::dec;
let commerce = Commerce::new("./store.db")?;
// Create a cart with items
let cart = commerce.carts().create(CreateCart {
customer_email: Some("alice@example.com".into()),
..Default::default()
})?;
commerce.carts().add_item(cart.id, AddCartItem {
sku: "SKU-001".into(),
name: "Widget".into(),
quantity: 2,
unit_price: dec!(49.99),
..Default::default()
})?;
// Apply a coupon code
commerce.carts().apply_discount(cart.id, "SUMMER20")?;
// Calculate and apply promotions
let result = commerce.apply_cart_promotions(cart.id)?;
println!("Discount: ${}", result.total_discount);
println!("Applied promotions: {:?}", result.applied_promotions.len());
// Cart now has discount applied
let updated_cart = commerce.carts().get(cart.id)?.unwrap();
println!("New total: ${}", updated_cart.grand_total);Source§impl Commerce
impl Commerce
Sourcepub fn new(path: &str) -> Result<Self, CommerceError>
Available on crate feature sqlite only.
pub fn new(path: &str) -> Result<Self, CommerceError>
sqlite only.Create a new Commerce instance with a SQLite database.
§Arguments
path- Path to the SQLite database file. Creates if not exists.
§Example
use stateset_embedded::Commerce;
// File-based database
let commerce = Commerce::new("./my-store.db")?;
// In-memory database (useful for testing)
let commerce = Commerce::new(":memory:")?;Sourcepub fn sqlite(path: &str) -> Result<Self, CommerceError>
Available on crate feature sqlite only.
pub fn sqlite(path: &str) -> Result<Self, CommerceError>
sqlite only.Sourcepub fn in_memory() -> Result<Self, CommerceError>
Available on crate feature sqlite only.
pub fn in_memory() -> Result<Self, CommerceError>
sqlite only.Sourcepub fn sqlite_pool(
path: &str,
max_connections: u32,
) -> Result<Self, CommerceError>
Available on crate feature sqlite only.
pub fn sqlite_pool( path: &str, max_connections: u32, ) -> Result<Self, CommerceError>
sqlite only.Create a Commerce instance with SQLite and custom pool size.
§Arguments
path- Path to the SQLite database filemax_connections- Maximum number of connections in the pool
§Example
use stateset_embedded::Commerce;
// Create with larger connection pool for high concurrency
let commerce = Commerce::sqlite_pool("./store.db", 10)?;Sourcepub fn with_database(db: Arc<dyn Database>) -> Self
pub fn with_database(db: Arc<dyn Database>) -> Self
Create a Commerce instance with a pre-connected database.
This is useful when you want to manage the database connection yourself. Note: Tax operations and vector search will not be available when using this method.
Sourcepub fn builder() -> CommerceBuilder
pub fn builder() -> CommerceBuilder
Create a Commerce instance with custom configuration.
Use CommerceBuilder for more control over initialization.
Source§impl Commerce
impl Commerce
Sourcepub fn events(&self) -> &EventSystem
Available on crate feature events only.
pub fn events(&self) -> &EventSystem
events only.Access the event system for pub/sub and webhook management.
§Example
use stateset_embedded::Commerce;
use futures::StreamExt;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let commerce = Commerce::new("./store.db")?;
// Subscribe to all events
let mut subscription = commerce.events().subscribe();
// Process events in background
tokio::spawn(async move {
while let Some(event) = subscription.next().await {
println!("Event: {:?}", event);
}
});
Ok(())
}Sourcepub fn subscribe_events(&self) -> EventSubscription
Available on crate feature events only.
pub fn subscribe_events(&self) -> EventSubscription
events only.Subscribe to commerce events.
This is a convenience method that returns an event subscription for receiving real-time commerce events.
§Example
use stateset_embedded::Commerce;
use futures::StreamExt;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let commerce = Commerce::new("./store.db")?;
let mut subscription = commerce.subscribe_events();
while let Some(event) = subscription.next().await {
match event {
stateset_core::CommerceEvent::OrderCreated { order_id, .. } => {
println!("New order: {}", order_id);
}
_ => {}
}
}
Ok(())
}Sourcepub fn register_webhook(&self, webhook: Webhook) -> Uuid
Available on crate feature events only.
pub fn register_webhook(&self, webhook: Webhook) -> Uuid
events only.Register a webhook endpoint for event delivery.
§Example
use stateset_embedded::{Commerce, Webhook};
let commerce = Commerce::new("./store.db")?;
let webhook = Webhook::new(
"My Webhook",
"https://my-app.com/webhooks/stateset",
).with_secret("my-webhook-secret");
if let Some(id) = commerce.try_register_webhook(webhook) {
println!("Webhook registered: {}", id);
} else {
println!("Webhook registration failed");
}Sourcepub fn register_webhook_strict(
&self,
webhook: Webhook,
) -> Result<Uuid, WebhookRegistrationError>
Available on crate feature events only.
pub fn register_webhook_strict( &self, webhook: Webhook, ) -> Result<Uuid, WebhookRegistrationError>
events only.Register a webhook endpoint with explicit failure semantics.
Sourcepub fn try_register_webhook(&self, webhook: Webhook) -> Option<Uuid>
Available on crate feature events only.
pub fn try_register_webhook(&self, webhook: Webhook) -> Option<Uuid>
events only.Register a webhook endpoint, returning None when registration fails validation.
This is the safer API when you need to distinguish between a successful registration ID and a blocked/invalid webhook definition.
Sourcepub fn unregister_webhook(&self, id: Uuid) -> bool
Available on crate feature events only.
pub fn unregister_webhook(&self, id: Uuid) -> bool
events only.Unregister a webhook endpoint.
Sourcepub fn list_webhooks(&self) -> Vec<Webhook>
Available on crate feature events only.
pub fn list_webhooks(&self) -> Vec<Webhook>
events only.List all registered webhooks.
Sourcepub fn webhook_deliveries(&self, id: Uuid) -> Vec<WebhookDelivery>
Available on crate feature events only.
pub fn webhook_deliveries(&self, id: Uuid) -> Vec<WebhookDelivery>
events only.Get delivery history for a webhook (newest-first).
Sourcepub fn emit_event(&self, event: CommerceEvent)
Available on crate feature events only.
pub fn emit_event(&self, event: CommerceEvent)
events only.Emit a commerce event manually.
Events are typically emitted automatically by commerce operations, but you can also emit custom events using this method.
Source§impl Commerce
impl Commerce
Sourcepub const fn backend(&self) -> CommerceBackend
pub const fn backend(&self) -> CommerceBackend
Get the active database backend kind.
Sourcepub fn metrics_snapshot(&self) -> MetricsSnapshot
pub fn metrics_snapshot(&self) -> MetricsSnapshot
Capture a point-in-time metrics snapshot.
Sourcepub fn health_check(&self) -> CommerceHealth
pub fn health_check(&self) -> CommerceHealth
Run a lightweight engine health check.
The database probe uses orders().count(Default::default()) and does not
mutate state.