Skip to main content

Commerce

Struct Commerce 

Source
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

Source

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()
})?;
Source

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")?;
Source

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()
})?;
Source

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()
})?;
Source

pub fn custom_objects(&self) -> CustomObjects

Access custom objects (custom states / metaobjects) operations.

Source

pub fn custom_states(&self) -> CustomObjects

Alias for custom_objects() (for users who prefer the “custom states” name).

Source

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()
})?;
Source

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()
})?;
Source

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)?;
Source

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)?;
Source

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)?;
Source

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)?);
Source

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)?;
Source

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()
})?;
Source

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);
Source

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);
        }
    }
}
Source

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);
Source

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));
Source

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);
Source

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);
Source

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);
Source

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);
Source

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);
Source

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);
Source

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);
Source

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)?;
Source

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);
Source

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);
Source

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);
Source

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());
Source

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);
Source

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);
Source

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,
)?;
Source

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.

Source

pub fn gift_cards(&self) -> GiftCards

Access gift card operations.

Provides gift card issuance, charging, refunding, and transaction history.

Source

pub fn store_credits(&self) -> StoreCredits

Access store credit operations.

Provides store credit management including balance adjustments and application to orders.

Source

pub fn segments(&self) -> Segments

Access customer segment operations.

Provides customer grouping, membership management, and segment targeting.

Source

pub fn shipping_zones(&self) -> ShippingZones

Access shipping zone and method operations.

Provides shipping zone management, method configuration, and rate calculation.

Source

pub fn channels(&self) -> Channels

Access sales / fulfillment channel operations.

Source

pub fn companies(&self) -> Companies

Access B2B company (account) operations.

Source

pub fn transfer_orders(&self) -> TransferOrders

Access transfer order operations (inter-warehouse stock movement).

Source

pub fn units_of_measure(&self) -> UnitsOfMeasure

Access units-of-measure operations (classes, UOMs, conversion rules).

Source

pub fn production_batches(&self) -> ProductionBatches

Access production batch operations.

Source

pub fn supplier_skus(&self) -> SupplierSkus

Access supplier SKU operations.

Source

pub fn fixed_assets(&self) -> FixedAssets

Access fixed asset register operations.

Source

pub fn maintenance(&self) -> Maintenance

Access backup, restore and export/import operations.

§Example
let commerce = stateset_embedded::Commerce::new("./store.db")?;
let report = commerce.maintenance().backup_to("./backups/nightly.db")?;
Source

pub fn revenue_recognition(&self) -> RevenueRecognition

Access revenue recognition (ASC 606) operations.

Source

pub fn vendor_returns(&self) -> VendorReturns

Access vendor return operations.

Source

pub fn vendor_credits(&self) -> VendorCredits

Access vendor credit operations.

Source

pub fn payment_obligations(&self) -> PaymentObligations

Access payment obligation operations.

Source

pub fn price_levels(&self) -> PriceLevels

Access price level (B2B pricing tier) operations.

Source

pub fn prepayments(&self) -> Prepayments

Access prepayment operations.

Source

pub fn price_schedules(&self) -> PriceSchedules

Access price schedule (time-bounded pricing) operations.

Source

pub fn activity_logs(&self) -> ActivityLogs

Access activity log (subject history) operations.

Source

pub fn integration_mappings(&self) -> IntegrationMappings

Access integration mapping operations.

Source

pub fn inbound_shipments(&self) -> InboundShipments

Access inbound shipment (ASN) operations.

Source

pub fn purgatory(&self) -> Purgatory

Access purgatory (order ingestion staging) operations.

Source

pub fn print_stations(&self) -> PrintStations

Access print station operations.

Source

pub fn edi_documents(&self) -> EdiDocuments

Access EDI document operations.

Source

pub fn integration_field_mappings(&self) -> IntegrationFieldMappings

Access integration field-mapping operations.

Source

pub fn topology_snapshots(&self) -> TopologySnapshots

Access customer operational topology snapshot operations.

Source

pub fn stock_snapshots(&self) -> StockSnapshots

Access stock snapshot (point-in-time inventory) operations.

Source

pub fn reviews(&self) -> Reviews

Access product review operations.

Provides review creation, moderation, summaries, and helpful/reported tracking.

Source

pub fn wishlists(&self) -> Wishlists

Access wishlist operations.

Provides wishlist creation, item management, and customer wish tracking.

Source

pub fn loyalty(&self) -> Loyalty

Access loyalty program operations.

Provides loyalty program management, customer enrollment, points tracking, and reward catalog operations.

Source

pub fn fraud(&self) -> Fraud

Access fraud detection operations.

Provides fraud risk assessment, rule management, and manual review workflows.

Source

pub fn search_config(&self) -> SearchConfigs

Access search configuration operations.

Provides search configuration management including active config selection.

Source

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:

  1. Retrieves the cart and its items
  2. Uses the shipping address to determine tax jurisdiction
  3. Calculates tax for each item based on jurisdiction and product category
  4. Applies customer exemptions if applicable
  5. 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);
Source

pub fn apply_cart_promotions( &self, cart_id: Uuid, ) -> Result<ApplyPromotionsResult>

Calculate and apply promotions to a cart.

This method:

  1. Retrieves the cart and its items
  2. Finds all applicable automatic promotions
  3. Validates any coupon codes applied to the cart
  4. Calculates discounts respecting stacking rules
  5. 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

Source

pub fn new(path: &str) -> Result<Self, CommerceError>

Available on crate feature 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:")?;
Source

pub fn sqlite(path: &str) -> Result<Self, CommerceError>

Available on crate feature sqlite only.

Create a Commerce instance with SQLite (convenience method).

This is an alias for Commerce::new() with a clearer name.

§Example
use stateset_embedded::Commerce;

let commerce = Commerce::sqlite("./store.db")?;
Source

pub fn in_memory() -> Result<Self, CommerceError>

Available on crate feature sqlite only.

Create a Commerce instance with an in-memory SQLite database.

This is useful for testing or ephemeral data that doesn’t need persistence.

§Example
use stateset_embedded::Commerce;

let commerce = Commerce::in_memory()?;
// Data will be lost when commerce is dropped
Source

pub fn sqlite_pool( path: &str, max_connections: u32, ) -> Result<Self, CommerceError>

Available on crate feature sqlite only.

Create a Commerce instance with SQLite and custom pool size.

§Arguments
  • path - Path to the SQLite database file
  • max_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)?;
Source

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.

Source

pub fn builder() -> CommerceBuilder

Create a Commerce instance with custom configuration.

Use CommerceBuilder for more control over initialization.

Source§

impl Commerce

Source

pub fn events(&self) -> &EventSystem

Available on crate feature 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(())
}
Source

pub fn subscribe_events(&self) -> EventSubscription

Available on crate feature 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(())
}
Source

pub fn register_webhook(&self, webhook: Webhook) -> Uuid

Available on crate feature 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");
}
Source

pub fn register_webhook_strict( &self, webhook: Webhook, ) -> Result<Uuid, WebhookRegistrationError>

Available on crate feature events only.

Register a webhook endpoint with explicit failure semantics.

Source

pub fn try_register_webhook(&self, webhook: Webhook) -> Option<Uuid>

Available on crate feature 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.

Source

pub fn unregister_webhook(&self, id: Uuid) -> bool

Available on crate feature events only.

Unregister a webhook endpoint.

Source

pub fn list_webhooks(&self) -> Vec<Webhook>

Available on crate feature events only.

List all registered webhooks.

Source

pub fn webhook_deliveries(&self, id: Uuid) -> Vec<WebhookDelivery>

Available on crate feature events only.

Get delivery history for a webhook (newest-first).

Source

pub fn emit_event(&self, event: CommerceEvent)

Available on crate feature 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

Source

pub fn database(&self) -> &dyn Database

Get the underlying database (for advanced use cases).

Source

pub const fn backend(&self) -> CommerceBackend

Get the active database backend kind.

Source

pub const fn metrics(&self) -> &Metrics

Access engine metrics handle.

Source

pub fn metrics_snapshot(&self) -> MetricsSnapshot

Capture a point-in-time metrics snapshot.

Source

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.

Trait Implementations§

Source§

impl Debug for Commerce

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more