.do

Design Examples

Complete examples of Business-as-Code designs

Complete examples showing how to design Business-as-Code applications from scratch.

SaaS Application

A complete SaaS platform design with subscriptions, billing, and team management.

Business Model

import { Person, Organization, SoftwareApplication } from 'schema.org.ai'
import { NAICS } from 'naics.org.ai'

// Define the SaaS product
const platform: SoftwareApplication = {
  $type: 'SoftwareApplication',
  name: 'ProjectHub',
  description: 'Project management platform for distributed teams',
  applicationCategory: 'Business Software',
  offers: [
    {
      $type: 'Offer',
      name: 'Starter',
      price: { value: 29, currency: 'USD', period: 'month' },
      features: ['5 projects', '10 team members', 'Basic support'],
    },
    {
      $type: 'Offer',
      name: 'Pro',
      price: { value: 99, currency: 'USD', period: 'month' },
      features: ['Unlimited projects', '50 team members', 'Priority support', 'Advanced analytics'],
    },
  ],
}

Data Model

// User type
interface User extends Person {
  $type: 'Person'
  $id: string
  email: string
  name: string
  avatar?: string
  role: 'owner' | 'admin' | 'member'
  status: 'active' | 'invited' | 'suspended'
}

// Organization/Team
interface Team extends Organization {
  $type: 'Organization'
  $id: string
  name: string
  plan: 'starter' | 'pro'
  members: string[] // User IDs
  owner: string // User ID
  createdAt: Date
}

// Subscription
interface Subscription {
  $type: 'Subscription'
  $id: string
  team: string // Team ID
  plan: 'starter' | 'pro'
  status: 'active' | 'past_due' | 'cancelled'
  currentPeriodStart: Date
  currentPeriodEnd: Date
  mrr: number
}

// Project
interface Project {
  $type: 'Project'
  $id: string
  name: string
  description: string
  team: string // Team ID
  members: string[] // User IDs
  status: 'active' | 'archived'
  createdAt: Date
}

Service Architecture

// User Service
const UserService = $.service({
  name: 'User Management',
  operations: {
    register: async (email: string, name: string) => {
      const user = await db.create($.Person, {
        email,
        name,
        status: 'invited',
      })
      await send($.Email.send, {
        to: email,
        template: 'verify-email',
        data: { userId: user.$id },
      })
      return user
    },

    verify: async (userId: string, code: string) => {
      const valid = await verifyCode(userId, code)
      if (valid) {
        await db.update($.Person, userId, { status: 'active' })
        await send($.User.verified, { userId })
      }
    },
  },
})

// Team Service
const TeamService = $.service({
  name: 'Team Management',
  operations: {
    create: async (name: string, owner: string) => {
      const team = await db.create($.Organization, {
        name,
        owner,
        members: [owner],
        plan: 'starter',
      })
      await send($.Team.created, { teamId: team.$id })
      return team
    },

    addMember: async (teamId: string, userId: string, role: string) => {
      await db.update($.Organization, teamId, {
        members: { $push: userId },
      })
      await send($.Team.member_added, { teamId, userId, role })
    },
  },
})

// Subscription Service
const SubscriptionService = $.service({
  name: 'Subscription Management',
  operations: {
    create: async (teamId: string, plan: string) => {
      const subscription = await db.create($.Subscription, {
        team: teamId,
        plan,
        status: 'active',
        currentPeriodStart: new Date(),
        currentPeriodEnd: addMonths(new Date(), 1),
        mrr: plan === 'pro' ? 99 : 29,
      })
      await send($.Subscription.created, { subscriptionId: subscription.$id })
      return subscription
    },

    upgrade: async (subscriptionId: string, newPlan: string) => {
      await db.update($.Subscription, subscriptionId, { plan: newPlan })
      await send($.Subscription.upgraded, { subscriptionId, newPlan })
    },
  },
})

Workflows

// User onboarding workflow
const onboardingWorkflow = $.workflow('user-onboarding', async (user: User) => {
  // Send welcome email
  await $.step('welcome-email', () => send($.Email.send, { to: user.email, template: 'welcome' }))

  // Create demo project
  const project = await $.step('create-demo', () =>
    db.create($.Project, {
      name: 'Demo Project',
      team: user.team,
      members: [user.$id],
    })
  )

  // Schedule onboarding call
  await $.step('schedule-call', () =>
    send($.Meeting.schedule, {
      attendees: [user.email],
      subject: 'ProjectHub Onboarding',
    })
  )
})

// Subscription renewal workflow
const renewalWorkflow = $.workflow('subscription-renewal', async (subscription: Subscription) => {
  // Attempt payment
  const payment = await $.step('process-payment', async () => {
    try {
      return await send($.Payment.charge, {
        subscriptionId: subscription.$id,
        amount: subscription.mrr,
      })
    } catch (error) {
      return { success: false, error }
    }
  })

  if (payment.success) {
    // Update subscription
    await $.step('update-subscription', () =>
      db.update($.Subscription, subscription.$id, {
        currentPeriodStart: new Date(),
        currentPeriodEnd: addMonths(new Date(), 1),
        status: 'active',
      })
    )

    // Send receipt
    await $.step('send-receipt', () =>
      send($.Email.send, {
        to: subscription.team.owner.email,
        template: 'payment-receipt',
        data: { payment },
      })
    )
  } else {
    // Mark as past due
    await $.step('mark-past-due', () => db.update($.Subscription, subscription.$id, { status: 'past_due' }))

    // Send failure notification
    await $.step('notify-failure', () =>
      send($.Email.send, {
        to: subscription.team.owner.email,
        template: 'payment-failed',
        data: { subscription },
      })
    )
  }
})

E-commerce Platform

A complete e-commerce platform with products, orders, and fulfillment.

Data Model

import { Product, Order, Offer } from 'schema.org.ai'

interface StoreProduct extends Product {
  $type: 'Product'
  $id: string
  name: string
  description: string
  price: number
  inventory: number
  category: string
  images: string[]
  variants?: ProductVariant[]
}

interface ProductVariant {
  $id: string
  name: string
  price: number
  inventory: number
  attributes: Record<string, string> // { color: 'red', size: 'L' }
}

interface StoreOrder extends Order {
  $type: 'Order'
  $id: string
  orderNumber: string
  customer: string // Person ID
  items: OrderItem[]
  subtotal: number
  tax: number
  shipping: number
  total: number
  status: 'pending' | 'processing' | 'shipped' | 'delivered' | 'cancelled'
  shippingAddress: Address
  billingAddress: Address
}

interface OrderItem {
  product: string // Product ID
  variant?: string // Variant ID
  quantity: number
  price: number
}

Workflows

// Order processing workflow
const orderWorkflow = $.workflow('order-processing', async (order: StoreOrder) => {
  // Validate order
  const validation = await $.step('validate', async () => {
    // Check inventory
    for (const item of order.items) {
      const product = await db.get($.Product, item.product)
      if (product.inventory < item.quantity) {
        return { valid: false, reason: 'Insufficient inventory' }
      }
    }
    return { valid: true }
  })

  if (!validation.valid) {
    await send($.Order.rejected, { orderId: order.$id, reason: validation.reason })
    return
  }

  // Process payment
  const payment = await $.step('payment', async () => {
    return await send($.Payment.process, {
      orderId: order.$id,
      amount: order.total,
      customer: order.customer,
    })
  })

  if (!payment.success) {
    await send($.Order.payment_failed, { orderId: order.$id })
    return
  }

  // Reserve inventory
  await $.step('reserve-inventory', async () => {
    for (const item of order.items) {
      await db.update($.Product, item.product, {
        inventory: { $decrement: item.quantity },
      })
    }
  })

  // Update order status
  await $.step('confirm-order', async () => {
    await db.update($.Order, order.$id, {
      status: 'processing',
      paymentId: payment.id,
    })
  })

  // Create shipment
  const shipment = await $.step('create-shipment', async () => {
    return await send($.Shipment.create, {
      orderId: order.$id,
      items: order.items,
      address: order.shippingAddress,
    })
  })

  // Send confirmation email
  await $.step('send-confirmation', async () => {
    await send($.Email.send, {
      to: order.customer.email,
      template: 'order-confirmation',
      data: { order, shipment },
    })
  })
})

// Abandoned cart workflow
const abandonedCartWorkflow = $.workflow('abandoned-cart', async (cart) => {
  // Wait 1 hour
  await $.sleep(3600000)

  // Check if still abandoned
  const current = await db.get($.Cart, cart.$id)
  if (current.status !== 'abandoned') {
    return // Cart was completed
  }

  // Send recovery email
  await $.step('send-recovery', async () => {
    await send($.Email.send, {
      to: cart.customer.email,
      template: 'cart-recovery',
      data: { cart },
    })
  })

  // Wait another 23 hours
  await $.sleep(82800000)

  // Send discount offer if still abandoned
  const stillAbandoned = await db.get($.Cart, cart.$id)
  if (stillAbandoned.status === 'abandoned') {
    await $.step('send-discount', async () => {
      await send($.Email.send, {
        to: cart.customer.email,
        template: 'cart-discount',
        data: { cart, discount: 0.1 },
      })
    })
  }
})

Marketplace Platform

A two-sided marketplace connecting buyers and sellers.

Data Model

interface Seller extends Person {
  $type: 'Person'
  $id: string
  name: string
  email: string
  verified: boolean
  rating: number
  reviewCount: number
  skills: string[]
  hourlyRate: number
}

interface Listing {
  $type: 'Listing'
  $id: string
  seller: string // Seller ID
  title: string
  description: string
  category: string
  price: number
  availability: 'available' | 'booked' | 'unavailable'
}

interface Booking {
  $type: 'Booking'
  $id: string
  listing: string // Listing ID
  buyer: string // Person ID
  seller: string // Seller ID
  startDate: Date
  endDate: Date
  status: 'pending' | 'confirmed' | 'completed' | 'cancelled'
  total: number
}

Workflows

// Booking workflow
const bookingWorkflow = $.workflow('booking', async (booking: Booking) => {
  // Hold payment in escrow
  const escrow = await $.step('escrow-payment', async () => {
    return await send($.Payment.escrow, {
      bookingId: booking.$id,
      amount: booking.total,
      buyer: booking.buyer,
    })
  })

  // Notify seller
  await $.step('notify-seller', async () => {
    const seller = await db.get($.Person, booking.seller)
    await send($.Email.send, {
      to: seller.email,
      template: 'booking-request',
      data: { booking },
    })
  })

  // Wait for seller confirmation (24 hour timeout)
  const confirmation = await $.waitFor($.Booking.confirmed, {
    timeout: 86400000,
    filter: (b) => b.$id === booking.$id,
  })

  if (confirmation) {
    // Update booking status
    await $.step('confirm-booking', async () => {
      await db.update($.Booking, booking.$id, { status: 'confirmed' })
    })
  } else {
    // Auto-cancel and refund
    await $.step('auto-cancel', async () => {
      await send($.Payment.refund, { escrowId: escrow.id })
      await db.update($.Booking, booking.$id, { status: 'cancelled' })
    })
  }
})

// Completion and payout workflow
const completionWorkflow = $.workflow('booking-completion', async (booking: Booking) => {
  // Release payment to seller (85% after platform fee)
  await $.step('release-payment', async () => {
    await send($.Payment.release, {
      bookingId: booking.$id,
      seller: booking.seller,
      amount: booking.total * 0.85,
    })
  })

  // Request review from buyer
  await $.step('request-review', async () => {
    const buyer = await db.get($.Person, booking.buyer)
    await send($.Email.send, {
      to: buyer.email,
      template: 'request-review',
      data: { booking },
    })
  })

  // Update seller stats
  await $.step('update-stats', async () => {
    await db.update($.Person, booking.seller, {
      completedBookings: { $increment: 1 },
    })
  })
})

Next Steps


Example Tip: Start with these examples and adapt them to your specific business needs. The patterns shown here work for most business models.