.do
DesignBusiness-as-Code

Examples & Case Studies

Real-world Business-as-Code implementations and patterns

Learn from real-world Business-as-Code implementations. These examples demonstrate how to build complete businesses using the $ SDK.

Complete Business Examples

1. SaaS Subscription Business

A complete SaaS business with subscription billing, usage tracking, and customer lifecycle management.

import $, { db, ai, on, send, every, user, api } from 'sdk.do'

// Define business structure
const SaaSBusiness = {
  name: 'Acme Analytics',
  product: {
    $type: $.SoftwareApplication,
    name: 'Analytics Platform',
    category: 'Business Intelligence',
  },

  // Pricing tiers
  plans: {
    starter: { price: 29, features: ['basic-analytics', '1-user'] },
    pro: { price: 99, features: ['advanced-analytics', '10-users', 'api-access'] },
    enterprise: { price: 499, features: ['all-features', 'unlimited-users', 'white-label'] },
  },

  // Customer lifecycle
  lifecycle: {
    // New signup
    signup: on($.Customer.signup, async (customer) => {
      // Create account
      const account = await db.create($.Account, {
        $id: customer.email,
        $type: $.Account,
        customer: customer.id,
        plan: 'starter',
        status: 'trial',
        trialEnds: new Date(Date.now() + 14 * 24 * 60 * 60 * 1000), // 14 days
      })

      // Setup infrastructure
      await send($.Database.provision, { account })
      await send($.API.generateKey, { account })

      // Send welcome email
      await send($.Email.send, {
        to: customer.email,
        template: 'welcome',
        data: { customer, account },
      })

      // Notify team
      await api.slack.send({
        channel: 'sales',
        text: `New trial signup: ${customer.email} (${customer.company})`,
      })
    }),

    // Trial ending reminder
    trialEnding: every($.Daily, async () => {
      const accounts = await db.list($.Account, {
        where: {
          status: 'trial',
          trialEnds: {
            $gte: new Date(),
            $lte: new Date(Date.now() + 3 * 24 * 60 * 60 * 1000), // 3 days
          },
        },
      })

      for (const account of accounts) {
        await send($.Email.send, {
          to: account.customer.email,
          template: 'trial-ending',
          data: { account, daysRemaining: 3 },
        })
      }
    }),

    // Convert to paid
    conversion: on($.Subscription.created, async (subscription) => {
      await db.update($.Account, subscription.account, {
        status: 'active',
        plan: subscription.plan,
      })

      await send($.Email.send, {
        to: subscription.customer.email,
        template: 'subscription-confirmed',
        data: { subscription },
      })

      // Track conversion
      await send($.Analytics.track, {
        event: 'conversion',
        customer: subscription.customer,
        plan: subscription.plan,
        value: subscription.amount,
      })
    }),

    // Handle churn
    churn: on($.Subscription.cancelled, async (subscription) => {
      // Send exit survey
      await send($.Email.send, {
        to: subscription.customer.email,
        template: 'exit-survey',
        data: { subscription },
      })

      // Downgrade account after grace period
      setTimeout(
        async () => {
          await db.update($.Account, subscription.account, {
            status: 'cancelled',
            plan: null,
          })
        },
        7 * 24 * 60 * 60 * 1000
      ) // 7 days grace period
    }),
  },

  // Usage-based billing
  billing: {
    // Track API usage
    trackUsage: on($.API.called, async (call) => {
      await db.create($.UsageRecord, {
        account: call.account,
        endpoint: call.endpoint,
        timestamp: new Date(),
        units: 1,
      })
    }),

    // Generate monthly invoices
    generateInvoices: every('0 0 1 * *', async () => {
      // First day of month
      const accounts = await db.list($.Account, {
        where: { status: 'active' },
      })

      for (const account of accounts) {
        // Calculate usage
        const usage = await db.list($.UsageRecord, {
          where: {
            account: account.id,
            timestamp: {
              $gte: new Date(new Date().setDate(1)), // Start of month
              $lt: new Date(), // Now
            },
          },
        })

        // Calculate charges
        const baseCharge = account.plan === 'pro' ? 99 : account.plan === 'enterprise' ? 499 : 29
        const usageCharge = Math.max(0, (usage.length - 10000) * 0.01) // $0.01 per call over 10k

        // Create invoice
        const invoice = await send($.Invoice.create, {
          account,
          amount: baseCharge + usageCharge,
          items: [
            { description: `${account.plan} plan`, amount: baseCharge },
            { description: 'API usage', amount: usageCharge, units: usage.length },
          ],
        })

        // Charge customer
        await send($.Payment.charge, { invoice })
      }
    }),
  },

  // Feature flags
  features: {
    check: async (account, feature) => {
      const plan = account.plan
      const features = SaaSBusiness.plans[plan]?.features || []
      return features.includes(feature)
    },
  },
}

export default SaaSBusiness

2. E-commerce Store

A complete e-commerce business with product catalog, inventory, and order fulfillment.

import $, { db, ai, on, send, every } from 'sdk.do'

const EcommerceBusiness = {
  name: 'Acme Shop',

  // Catalog management
  catalog: {
    // Sync products from supplier
    sync: every($.Daily, async () => {
      const products = await api.fetch('https://supplier.com/api/products')

      for (const product of products) {
        await db.create($.Product, {
          $id: product.sku,
          $type: $.Product,
          name: product.name,
          description: product.description,
          price: product.price,
          inventory: product.stock,
          supplier: product.supplier,
        })
      }
    }),

    // Generate product descriptions with AI
    enhance: on($.Product.created, async (product) => {
      if (!product.description || product.description.length < 50) {
        const description = await ai.generate({
          prompt: `Write a compelling product description for: ${product.name}`,
          schema: $.Text,
          maxTokens: 200,
        })

        await db.update($.Product, product.id, {
          description,
        })
      }
    }),
  },

  // Order processing
  orders: {
    // Create order from cart
    create: on($.Cart.checkout, async (cart) => {
      const order = await db.create($.Order, {
        $type: $.Order,
        customer: cart.customer,
        items: cart.items,
        total: cart.total,
        status: 'pending',
      })

      await send($.Payment.process, { order })
    }),

    // Process payment
    payment: on($.Payment.succeeded, async (payment) => {
      const order = payment.order

      // Update order status
      await db.update($.Order, order.id, {
        status: 'paid',
        paidAt: new Date(),
      })

      // Reserve inventory
      for (const item of order.items) {
        await send($.Inventory.reserve, {
          product: item.product,
          quantity: item.quantity,
          order: order.id,
        })
      }

      // Trigger fulfillment
      await send($.Order.fulfill, order)
    }),

    // Fulfill order
    fulfillment: on($.Order.fulfill, async (order) => {
      // Create shipment
      const shipment = await api.shippo.createShipment({
        to: order.shippingAddress,
        from: { address: 'Warehouse Address' },
        parcels: order.items.map((item) => ({
          weight: item.weight,
          dimensions: item.dimensions,
        })),
      })

      await db.update($.Order, order.id, {
        status: 'shipped',
        tracking: shipment.trackingNumber,
        carrier: shipment.carrier,
      })

      // Notify customer
      await send($.Email.send, {
        to: order.customer.email,
        template: 'order-shipped',
        data: {
          order,
          tracking: shipment.trackingNumber,
          estimatedDelivery: shipment.estimatedDelivery,
        },
      })
    }),

    // Handle returns
    returns: on($.Return.requested, async (returnRequest) => {
      const order = await db.get($.Order, returnRequest.order)

      // Create return label
      const label = await api.shippo.createReturnLabel({
        originalShipment: order.tracking,
      })

      // Send return instructions
      await send($.Email.send, {
        to: order.customer.email,
        template: 'return-label',
        data: { returnRequest, label },
      })

      // Process refund when return received
      on($.Return.received, async (receivedReturn) => {
        if (receivedReturn.id === returnRequest.id) {
          await send($.Refund.process, {
            order,
            amount: returnRequest.amount,
          })
        }
      })
    }),
  },

  // Inventory management
  inventory: {
    // Low stock alerts
    monitor: every($.Hourly, async () => {
      const lowStock = await db.list($.Product, {
        where: {
          inventory: { $lt: 10 },
          status: 'active',
        },
      })

      if (lowStock.length > 0) {
        await send($.Alert.send, {
          type: 'low-stock',
          products: lowStock,
          recipients: ['[email protected]'],
        })
      }
    }),

    // Automatic reordering
    reorder: on($.Product.lowStock, async (product) => {
      const po = await db.create($.PurchaseOrder, {
        supplier: product.supplier,
        items: [
          {
            product: product.id,
            quantity: 100, // Reorder quantity
          },
        ],
        status: 'pending',
      })

      await send($.Email.send, {
        to: product.supplier.email,
        template: 'purchase-order',
        data: { po },
      })
    }),
  },
}

export default EcommerceBusiness

3. Content Marketplace

A two-sided marketplace connecting content creators with buyers.

import $, { db, ai, on, send, every, user } from 'sdk.do'

const ContentMarketplace = {
  name: 'Creator Platform',

  // Creator onboarding
  creators: {
    apply: on($.Creator.applies, async (application) => {
      // Review application (could be manual or AI)
      const review = await ai.generate({
        prompt: `Review this creator application and decide if they should be approved: ${JSON.stringify(application)}`,
        schema: $.Review,
        model: 'gpt-5',
      })

      if (review.approved) {
        await db.create($.Creator, {
          $id: application.email,
          $type: $.Person,
          role: 'creator',
          portfolio: application.portfolio,
          status: 'active',
        })

        // Send approval email
        await send($.Email.send, {
          to: application.email,
          template: 'creator-approved',
        })

        // Setup payment account
        await api.stripe.createConnectedAccount({
          email: application.email,
          type: 'express',
        })
      } else {
        await send($.Email.send, {
          to: application.email,
          template: 'creator-rejected',
          reason: review.reason,
        })
      }
    }),

    // Upload content
    upload: on($.Content.uploaded, async (content) => {
      // Generate metadata with AI
      const metadata = await ai.generate({
        prompt: `Analyze this content and generate title, description, tags, and category: ${content.text.substring(0, 500)}`,
        schema: $.CreativeWork,
        model: 'claude-sonnet-4.5',
      })

      await db.update($.Content, content.id, {
        title: metadata.title,
        description: metadata.description,
        keywords: metadata.keywords,
        category: metadata.category,
      })

      // Notify moderators
      await send($.Moderation.queue, { content })
    }),
  },

  // Buyer experience
  buyers: {
    // Search and discovery
    search: on($.Buyer.searches, async (query) => {
      // Semantic search with AI
      const embedding = await ai.embed(query.text)

      const results = await db.search({
        collection: $.Content,
        embedding,
        limit: 20,
        where: {
          status: 'published',
          price: { $lte: query.maxPrice },
        },
      })

      await send($.SearchResults.show, {
        buyer: query.buyer,
        results,
      })
    }),

    // Purchase content
    purchase: on($.Purchase.initiated, async (purchase) => {
      // Process payment
      const payment = await api.stripe.createPaymentIntent({
        amount: purchase.amount,
        customer: purchase.buyer,
      })

      if (payment.status === 'succeeded') {
        // Grant access to content
        await db.create($.License, {
          content: purchase.content,
          buyer: purchase.buyer,
          type: purchase.licenseType,
          expiresAt: purchase.licenseType === 'subscription' ? new Date(Date.now() + 30 * 24 * 60 * 60 * 1000) : null,
        })

        // Pay creator (85% revenue share)
        await api.stripe.transfer({
          amount: purchase.amount * 0.85,
          destination: purchase.content.creator.stripeAccountId,
        })

        // Send confirmation
        await send($.Email.send, {
          to: purchase.buyer.email,
          template: 'purchase-confirmation',
          data: { purchase },
        })
      }
    }),
  },

  // Revenue optimization
  revenue: {
    // Dynamic pricing with AI
    optimize: every($.Weekly, async () => {
      const content = await db.list($.Content, {
        where: { status: 'published' },
      })

      for (const item of content) {
        const metrics = {
          views: item.views,
          purchases: item.purchases,
          conversionRate: item.purchases / item.views,
          currentPrice: item.price,
        }

        const recommendation = await ai.generate({
          prompt: `Recommend optimal pricing for this content based on metrics: ${JSON.stringify(metrics)}`,
          schema: $.PriceRecommendation,
          model: 'gpt-5',
        })

        if (Math.abs(recommendation.price - item.price) > item.price * 0.1) {
          // Only update if >10% difference
          await db.update($.Content, item.id, {
            price: recommendation.price,
            priceReason: recommendation.reason,
          })
        }
      }
    }),

    // Promote trending content
    promote: every($.Daily, async () => {
      const trending = await db.list($.Content, {
        where: {
          createdAt: { $gte: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000) },
        },
        sort: '-views',
        limit: 10,
      })

      await send($.Email.send, {
        to: 'subscribers',
        template: 'trending-content',
        data: { content: trending },
      })
    }),
  },
}

export default ContentMarketplace

Business Pattern Library

Pattern: Viral Loop

Incentivize users to invite others:

const ViralLoop = {
  // Reward referrer
  referral: on($.User.referred.by($.User), async ({ referrer, referred }) => {
    // Give both users credits
    await db.update($.Account, referrer.account, {
      credits: { $inc: 10 },
    })

    await db.update($.Account, referred.account, {
      credits: { $inc: 5 },
    })

    // Track referral
    await send($.Analytics.track, {
      event: 'referral',
      referrer,
      referred,
    })
  }),

  // Milestone rewards
  milestone: on($.User.referralCount.reaches(10), async (user) => {
    await db.update($.Account, user.account, {
      plan: 'pro',
      planReason: 'referral-reward',
    })

    await send($.Email.send, {
      to: user.email,
      template: 'referral-milestone',
      milestone: 10,
    })
  }),
}

Pattern: Freemium Conversion

Convert free users to paid:

const FreemiumConversion = {
  // Usage-based prompts
  limitReached: on($.Account.limitReached, async (account) => {
    await send($.Email.send, {
      to: account.user.email,
      template: 'upgrade-prompt',
      data: {
        currentUsage: account.usage,
        limit: account.limits[account.feature],
        benefit: 'Upgrade to continue using ' + account.feature,
      },
    })
  }),

  // Time-based campaigns
  trialEnding: every($.Daily, async () => {
    const accounts = await db.list($.Account, {
      where: {
        plan: 'free',
        createdAt: {
          $gte: new Date(Date.now() - 21 * 24 * 60 * 60 * 1000), // 21 days ago
          $lte: new Date(Date.now() - 14 * 24 * 60 * 60 * 1000), // 14 days ago
        },
      },
    })

    for (const account of accounts) {
      const usage = await db.count($.Event, {
        where: {
          account: account.id,
          type: 'feature_used',
        },
      })

      if (usage > 50) {
        // Active user
        await send($.Email.send, {
          to: account.user.email,
          template: 'upgrade-offer',
          discount: 0.2, // 20% off
          duration: '3 months',
        })
      }
    }
  }),
}

Pattern: Customer Retention

Reduce churn and increase lifetime value:

const CustomerRetention = {
  // Engagement monitoring
  engagement: every($.Daily, async () => {
    const accounts = await db.list($.Account, {
      where: { status: 'active' },
    })

    for (const account of accounts) {
      const lastActivity = await db.get($.Event, {
        where: {
          account: account.id,
          type: 'activity',
        },
        sort: '-timestamp',
        limit: 1,
      })

      const daysSinceActivity = (Date.now() - lastActivity.timestamp) / (24 * 60 * 60 * 1000)

      if (daysSinceActivity > 7) {
        // Send re-engagement email
        await send($.Email.send, {
          to: account.user.email,
          template: 're-engagement',
          data: {
            daysSinceActivity,
            newFeatures: await getNewFeaturesSince(lastActivity.timestamp),
          },
        })
      }
    }
  }),

  // Proactive support
  healthScore: on($.Account.healthScore.drops, async (account) => {
    // Assign success manager
    await send($.SuccessManager.assign, {
      account,
      priority: 'high',
      reason: 'health score drop',
    })

    // Schedule check-in
    await send($.Calendar.schedule, {
      type: 'check-in',
      account,
      duration: 30,
    })
  }),

  // Win-back campaigns
  churn: on($.Subscription.cancelled, async (subscription) => {
    // Wait 30 days
    setTimeout(
      async () => {
        await send($.Email.send, {
          to: subscription.customer.email,
          template: 'win-back',
          offer: {
            discount: 0.5, // 50% off
            duration: '6 months',
            features: 'all pro features',
          },
        })
      },
      30 * 24 * 60 * 60 * 1000
    )
  }),
}

Case Studies

Case Study 1: Newsletter Business

Challenge: Launch a paid newsletter business with minimal overhead

Solution: Business-as-Code automation

const NewsletterBusiness = {
  // Content creation
  content: every($.Weekly, async () => {
    // AI generates draft
    const draft = await ai.generate({
      prompt: 'Write a newsletter about this week in AI',
      schema: $.Article,
      model: 'gpt-5',
      maxTokens: 2000,
    })

    // Queue for review
    await send($.Content.review, { draft })
  }),

  // Subscriber management
  subscribers: {
    free: await db.list($.Person, { where: { subscription: 'free' } }),
    paid: await db.list($.Person, { where: { subscription: 'paid' } }),
  },

  // Publishing
  publish: on($.Article.approved, async (article) => {
    // Send to paid subscribers
    await send($.Email.send, {
      to: NewsletterBusiness.subscribers.paid,
      subject: article.headline,
      body: article.text,
    })

    // Send preview to free subscribers
    await send($.Email.send, {
      to: NewsletterBusiness.subscribers.free,
      subject: article.headline,
      body: article.text.substring(0, 500) + '... [Upgrade to read more]',
    })
  }),
}

// **Results**: Launched in 1 day, 0 employees, 1000 paid subscribers in 3 months

Case Study 2: API-First SaaS

Challenge: Build and scale an API product

Solution: Serverless Business-as-Code

// API endpoints automatically handle:
// - Authentication
// - Rate limiting
// - Usage tracking
// - Billing

const APIBusiness = {
  endpoint: on($.API.called, async (request) => {
    // Authenticate
    const account = await user.authenticate(request.token)

    // Check rate limit
    const allowed = await checkRateLimit(account)
    if (!allowed) {
      return { error: 'Rate limit exceeded' }
    }

    // Track usage
    await send($.Usage.track, {
      account,
      endpoint: request.endpoint,
      timestamp: new Date(),
    })

    // Execute request
    return await handleRequest(request)
  }),

  // Auto-scaling billing
  billing: every($.Monthly, async () => {
    const accounts = await db.list($.Account)

    for (const account of accounts) {
      const usage = await db.count($.Usage, {
        where: { account: account.id },
      })

      const charge = calculateCharge(usage, account.plan)

      await send($.Invoice.create, {
        account,
        amount: charge,
      })
    }
  }),
}

// **Results**: Scaled to 10M+ API calls/month with 0 infrastructure management

Next Steps


Documentation Status: These examples describe the planned API design for the .do platform. Code examples represent the intended interface and may not reflect the current implementation state.