Use Cases
E-Commerce Business
Build a complete autonomous e-commerce store with Business-as-Code
Build a complete, autonomous e-commerce store using Business-as-Code principles.
Overview
This use case demonstrates building an e-commerce business that:
- Manages product catalog autonomously
- Processes orders end-to-end
- Handles inventory automatically
- Provides AI-powered recommendations
- Optimizes pricing dynamically
- Delivers personalized experiences
Architecture
graph TB
subgraph Frontend["Customer Experience"]
UI[Web/Mobile UI]
Cart[Shopping Cart]
Checkout[Checkout Flow]
end
subgraph Core["Core Business Logic"]
Products[Product Catalog]
Orders[Order Management]
Inventory[Inventory Control]
Pricing[Dynamic Pricing]
end
subgraph AI["AI Services"]
Recommendations[Product Recommendations]
Content[Content Generation]
Decisions[Business Decisions]
end
subgraph Integration["Integrations"]
Payment[Payment Gateway]
Shipping[Shipping Provider]
Email[Email Service]
end
UI --> Cart
Cart --> Checkout
Checkout --> Orders
Orders --> Inventory
Orders --> Payment
Orders --> Shipping
Orders --> Email
Products --> Recommendations
Products --> Pricing
Products --> Content
Pricing -.->|AI| Decisions
Recommendations -.->|AI| Decisions
Content -.->|AI| Decisions
Complete Implementation
1. Business Setup
import $, { db, on, send, ai } from 'sdk.do'
// Create the store
const store = await $.Organization.create({
$type: 'Organization',
name: 'Acme Electronics',
description: 'Premium consumer electronics',
url: 'https://acme-electronics.com',
email: '[email protected]',
telephone: '+1-555-0100',
address: {
$type: 'PostalAddress',
streetAddress: '123 Commerce St',
addressLocality: 'Austin',
addressRegion: 'TX',
postalCode: '78701',
addressCountry: 'US',
},
})
// Create brand
const brand = await $.Brand.create({
$type: 'Brand',
name: 'Acme',
logo: 'https://acme-electronics.com/logo.png',
})
await db.relate(store, $.owns, brand)2. Product Management
// Product creation with AI-generated content
async function createProduct(productData: Partial<Product>) {
// AI generates marketing content
const content = await ai.generate('product-marketing', {
name: productData.name,
features: productData.features,
category: productData.category,
tone: 'engaging',
length: 'medium',
})
// AI suggests pricing
const pricing = await ai.decide('initial-pricing', {
product: productData,
category: productData.category,
competitors: await findCompetitors(productData),
costs: productData.costs,
})
// Create product
const product = await $.Product.create({
$type: 'Product',
name: productData.name,
description: content.description,
brand,
category: productData.category,
gtin: productData.gtin,
// Offers
offers: [
{
$type: 'Offer',
price: pricing.recommendedPrice,
priceCurrency: 'USD',
availability: $.InStock,
seller: store,
priceValidUntil: pricing.validUntil,
},
],
// Images
image: productData.images,
// Inventory
inventory: productData.initialStock,
reorderPoint: productData.reorderPoint || 20,
// Cost tracking
costPrice: productData.costs.unit,
// Additional properties
additionalProperty: content.keyFeatures.map((feature) => ({
$type: 'PropertyValue',
name: feature.name,
value: feature.value,
})),
})
await db.relate(store, $.sells, product)
await send($.Product.created, product)
return product
}
// Example: Create a product
const headphones = await createProduct({
name: 'Premium Wireless Headphones',
features: ['Active noise cancellation', 'Bluetooth 5.3', '40-hour battery life', 'Premium leather ear cups'],
category: 'Electronics > Audio > Headphones',
gtin: '1234567890123',
images: ['https://cdn.acme.com/headphones-1.jpg', 'https://cdn.acme.com/headphones-2.jpg'],
initialStock: 100,
reorderPoint: 20,
costs: {
unit: 75,
shipping: 5,
},
})3. Shopping Cart
// @errors: 7006
// @filename: sdk.do.d.ts
declare const $: any
declare const db: any
declare const ai: any
declare function send(event: any, data: any): Promise<void>
interface Product {
$id: string
offers: any[]
}
interface Person {
$id: string
}
interface ItemList {
$id: string
itemListElement: any[]
totalItems: number
status: string
}
interface OrderItem {
$type: string
orderItem: any
orderQuantity: number
price: number
}
// @filename: example.ts
// ---cut---
import { $, db, ai, send } from 'sdk.do'
// Shopping cart with AI recommendations
async function addToCart(customer: Person, product: Product, quantity: number) {
// Get or create active cart
let cart = await db.related(customer, $.has, $.ItemList).then((carts) => carts.find((c) => c.status === 'active'))
// ^?
if (!cart) {
cart = await $.ItemList.create({
$type: 'ItemList',
itemListElement: [],
totalItems: 0,
status: 'active',
createdAt: new Date(),
})
await db.relate(customer, $.has, cart)
// ^^^^^^^^^^
}
// Add item to cart
const item: OrderItem = {
$type: 'OrderItem',
orderItem: product,
orderQuantity: quantity,
price: product.offers[0].price,
}
cart.itemListElement.push(item)
cart.totalItems += quantity
await db.update($.ItemList, cart.$id, cart)
// AI recommends frequently-bought-together products
const recommendations = await ai.recommend({
// ^^^^^^^^^^^^^
type: $.Product,
basedOn: product,
strategy: 'frequently-bought-together',
limit: 3,
})
await send($.Cart.itemAdded, {
cart,
item,
recommendations,
})
return cart
}
// Calculate cart totals with tax and shipping
async function calculateCartTotal(cart: ItemList) {
const subtotal = cart.itemListElement.reduce((sum, item) => {
return sum + item.price * item.orderQuantity
}, 0)
const tax = subtotal * 0.08 // 8% tax
const shipping = subtotal > 50 ? 0 : 9.99 // Free shipping over $50
// ^^^^^^^^^^^^^^^
const total = subtotal + tax + shipping
return { subtotal, tax, shipping, total }
}4. Order Processing
// Complete order workflow
on($.Order.created, async (order) => {
try {
// Log order
await db.create($.OrderLog, {
order: order.$id,
stage: 'created',
timestamp: new Date(),
})
// Step 1: Validate inventory
const inventoryCheck = await Promise.all(
order.orderedItem.map(async (item) => {
const product = await db.get($.Product, item.orderItem.$id)
return {
product,
requested: item.orderQuantity,
available: product.inventory,
canFulfill: product.inventory >= item.orderQuantity,
}
})
)
const canFulfill = inventoryCheck.every((check) => check.canFulfill)
if (!canFulfill) {
// Out of stock
await send($.Order.cancel, {
order,
reason: 'out-of-stock',
details: inventoryCheck.filter((c) => !c.canFulfill),
})
return
}
// Step 2: Process payment
const payment = await send($.Payment.process, {
order,
amount: order.totalPrice,
currency: order.priceCurrency,
paymentMethod: order.paymentMethod,
customer: order.customer,
})
if (payment.status !== 'succeeded') {
await send($.Order.cancel, {
order,
reason: 'payment-failed',
details: payment.error,
})
return
}
// Step 3: Reserve inventory
for (const item of order.orderedItem) {
await db.decrement($.Product, item.orderItem.$id, {
inventory: item.orderQuantity,
})
}
// Step 4: Update order status
await db.update($.Order, order.$id, {
orderStatus: $.OrderProcessing,
paymentStatus: 'paid',
paidAt: new Date(),
})
// Step 5: Send confirmation
await send($.Email.send, {
to: order.customer.email,
template: 'order-confirmation',
data: {
order,
payment,
estimatedDelivery: addDays(new Date(), 3),
},
})
// Step 6: Trigger fulfillment
await send($.Order.fulfill, { order })
// Step 7: Update customer analytics
await db.increment(order.customer, $.stats.orderCount)
await db.increment(order.customer, $.stats.totalSpent, order.totalPrice)
} catch (error) {
await send($.Order.failed, {
order,
error: error.message,
stage: 'processing',
})
// Compensate: Refund if payment was taken
if (order.paymentStatus === 'paid') {
await send($.Payment.refund, {
payment: order.payment,
reason: 'order-processing-error',
})
}
throw error
}
})
// Order fulfillment
on($.Order.fulfill, async ({ order }) => {
// Create shipment
const shipment = await $.ParcelDelivery.create({
$type: 'ParcelDelivery',
partOfOrder: order,
trackingNumber: generateTrackingNumber(),
carrier: 'USPS',
deliveryAddress: order.shippingAddress,
expectedArrival: addDays(new Date(), 3),
hasDeliveryMethod: determineShippingMethod(order),
})
await db.update($.Order, order.$id, {
orderStatus: $.OrderInTransit,
orderDelivery: shipment,
})
// Notify warehouse
await send($.Warehouse.packOrder, {
order,
shipment,
priority: order.customer.membershipLevel === 'premium' ? 'high' : 'normal',
})
// Send shipping notification
await send($.Email.send, {
to: order.customer.email,
template: 'order-shipped',
data: { order, shipment },
})
await send($.Shipment.created, shipment)
})
// Delivery confirmation
on($.Shipment.delivered, async (shipment) => {
const order = shipment.partOfOrder
await db.update($.Order, order.$id, {
orderStatus: $.OrderDelivered,
deliveredAt: new Date(),
})
// Request review after 3 days
await send($.Email.schedule, {
to: order.customer.email,
template: 'request-review',
sendAt: addDays(new Date(), 3),
data: { order },
})
})5. Autonomous Inventory Management
// Monitor stock levels
on($.Product.updated, async (product) => {
if (product.inventory <= product.reorderPoint) {
await send($.Product.lowStock, product)
}
})
// Autonomous reordering
on($.Product.lowStock, async (product) => {
// AI analyzes reorder needs
const decision = await ai.decide('inventory-reorder', {
product,
currentStock: product.inventory,
reorderPoint: product.reorderPoint,
salesVelocity: await db.analyze('sales-velocity', {
product,
timeRange: '90d',
}),
seasonality: await db.analyze('seasonal-trends', {
product,
category: product.category,
}),
leadTime: 14, // days
stockoutCost: estimateStockoutCost(product),
})
if (decision.shouldReorder) {
// Create purchase order
const po = await $.Order.create({
$type: 'Order',
orderNumber: `PO-${Date.now()}`,
seller: product.manufacturer,
customer: store,
orderedItem: [
{
$type: 'OrderItem',
orderItem: product,
orderQuantity: decision.recommendedQuantity,
},
],
expectedDelivery: addDays(new Date(), decision.leadTime),
totalPrice: product.costPrice * decision.recommendedQuantity,
})
await send($.PurchaseOrder.created, po)
// If urgent, notify team
if (decision.urgency === 'high') {
await send($.Notification.send, {
to: $.Role.InventoryManager,
priority: 'high',
message: `Urgent reorder: ${product.name} (${product.inventory} left)`,
action: { review: po.$id },
})
}
}
})6. Dynamic Pricing
// Hourly pricing optimization
setInterval(async () => {
const products = await db.list($.Product, {
where: { isActive: true },
})
for (const product of products) {
try {
// Gather pricing context
const context = {
product,
currentPrice: product.offers[0].price,
costPrice: product.costPrice,
inventory: product.inventory,
// Demand metrics
demand: await db.analyze('product-demand', {
product,
timeRange: '7d',
}),
// Competition
competitors: await analyzeCompetition(product),
// Market trends
trends: await db.analyze('market-trends', {
category: product.category,
}),
// Business constraints
targetMargin: 0.4,
minPrice: product.costPrice * 1.2, // 20% minimum margin
maxDiscount: 0.3, // Max 30% off
}
// AI decides optimal price
const decision = await ai.decide('dynamic-pricing', context)
// Only update if change is significant
const priceChange = Math.abs(decision.recommendedPrice - context.currentPrice) / context.currentPrice
if (priceChange > 0.05 && decision.confidence > 0.85) {
// Update price
await db.update($.Product, product.$id, {
offers: [
{
$type: 'Offer',
price: decision.recommendedPrice,
priceCurrency: 'USD',
availability: $.InStock,
priceValidUntil: decision.validUntil,
},
],
})
// Log price change
await db.create($.PriceChange, {
product: product.$id,
oldPrice: context.currentPrice,
newPrice: decision.recommendedPrice,
reason: decision.reasoning,
confidence: decision.confidence,
projectedImpact: decision.projectedSales,
timestamp: new Date(),
})
await send($.Product.priceUpdated, {
product,
oldPrice: context.currentPrice,
newPrice: decision.recommendedPrice,
})
}
} catch (error) {
console.error(`Pricing error for ${product.name}:`, error)
}
}
}, 3600000) // Every hour7. Personalization & Recommendations
// Product page recommendations
on($.Product.viewed, async (event) => {
const { product, customer } = event
// Track view
await db.increment($.Product, product.$id, { viewCount: 1 })
await db.relate(customer, $.viewed, product)
// Get recommendations in parallel
const [similarProducts, frequentlyBought, personalizedRecs] = await Promise.all([
// Similar products
ai.recommend({
type: $.Product,
basedOn: product,
strategy: 'similar',
limit: 4,
}),
// Frequently bought together
ai.recommend({
type: $.Product,
basedOn: product,
strategy: 'frequently-bought-together',
limit: 3,
}),
// Personalized for customer
ai.recommend({
type: $.Product,
for: customer,
strategy: 'personalized',
context: {
currentProduct: product,
recentViews: await db.related(customer, $.viewed, $.Product, {
limit: 10,
sort: { viewedAt: -1 },
}),
},
limit: 6,
}),
])
await send($.UI.showRecommendations, {
customer,
sections: {
similar: similarProducts,
frequentlyBought,
forYou: personalizedRecs,
},
})
})
// Email personalization
on($.Email.beforeSend, async (email) => {
if (email.template === 'weekly-newsletter') {
const customer = email.to
// AI curates products for this customer
const curated = await ai.recommend({
type: $.Product,
for: customer,
strategy: 'newsletter-curation',
context: {
purchases: await db.related(customer, $.purchased, $.Product),
interests: customer.interests,
browsing: await db.related(customer, $.viewed, $.Product),
},
limit: 8,
})
// Update email data
email.data.products = curated
email.data.subject = await ai.generate('email-subject', {
customer,
products: curated,
tone: 'engaging',
})
}
})8. Customer Analytics
// Customer lifetime value tracking
on($.Order.completed, async (order) => {
const customer = order.customer
// Update customer metrics
await db.increment(customer, $.metrics.orderCount)
await db.increment(customer, $.metrics.revenue, order.totalPrice)
// Calculate LTV
const ltv = await db.aggregate($.Order, {
where: { customer: customer.$id },
aggregations: {
total: { $sum: 'totalPrice' },
count: { $count: '*' },
avgOrder: { $avg: 'totalPrice' },
},
})
await db.update($.Person, customer.$id, {
lifetimeValue: ltv.total,
averageOrderValue: ltv.avgOrder,
})
// Segment customer
const segment = await ai.analyze('customer-segmentation', {
customer,
metrics: ltv,
behavior: await analyzeCustomerBehavior(customer),
})
await db.update($.Person, customer.$id, {
segment: segment.segment,
})
// Trigger segment-specific actions
if (segment.segment === 'high-value' && !customer.vipStatus) {
await send($.Customer.promoteToVIP, { customer })
}
})9. Abandoned Cart Recovery
// Detect abandoned carts
setInterval(async () => {
const abandonedCarts = await db.list($.ItemList, {
where: {
status: 'active',
updatedAt: {
$gte: subHours(new Date(), 24),
$lte: subHours(new Date(), 1),
},
totalItems: { $gt: 0 },
},
})
for (const cart of abandonedCarts) {
const customer = await db.related(cart, $.belongsTo, $.Person).then((customers) => customers[0])
// AI decides recovery strategy
const strategy = await ai.decide('cart-recovery', {
cart,
customer,
cartValue: await calculateCartTotal(cart),
customerHistory: await db.related(customer, $.placed, $.Order),
})
if (strategy.shouldContact) {
await send($.Email.send, {
to: customer.email,
template: 'abandoned-cart',
data: {
cart,
discount: strategy.offerDiscount ? 0.1 : 0,
urgency: strategy.urgencyLevel,
},
})
await db.update($.ItemList, cart.$id, {
recoveryEmailSent: true,
recoveryEmailSentAt: new Date(),
})
}
}
}, 3600000) // Every hourComplete Example
See the full working example at:
Key Takeaways
- Start Simple: Begin with core order processing, add AI gradually
- Semantic Everything: Use Schema.org types throughout
- Event-Driven: Build workflows as event chains
- AI Native: Embed AI decisions where they add value
- Monitor & Learn: Track metrics, improve continuously
Next Steps
- SaaS Business → - Build subscription businesses
- Marketplace → - Two-sided platforms
- Architecture Guide → - System design