.do
DesignBusiness-as-Code

Monetization

Add revenue streams, payments, and billing to your Business-as-Code

Monetization with Business-as-Code

Transform your business logic into revenue streams using semantic payment operations. This guide covers everything from pricing models to payment processing.

Revenue Models

Subscription Model

Recurring revenue with tiered pricing:

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

const SubscriptionBusiness = {
  // Define pricing tiers
  plans: {
    starter: {
      $type: $.Offer,
      name: 'Starter',
      price: { value: 29, currency: 'USD', period: 'month' },
      features: ['Basic features', '1 user', '10GB storage'],
      limits: {
        users: 1,
        storage: 10 * 1024 * 1024 * 1024, // 10GB in bytes
        apiCalls: 10000,
      },
    },
    professional: {
      $type: $.Offer,
      name: 'Professional',
      price: { value: 99, currency: 'USD', period: 'month' },
      features: ['Advanced features', '10 users', '100GB storage', 'Priority support'],
      limits: {
        users: 10,
        storage: 100 * 1024 * 1024 * 1024,
        apiCalls: 100000,
      },
    },
    enterprise: {
      $type: $.Offer,
      name: 'Enterprise',
      price: { value: 499, currency: 'USD', period: 'month' },
      features: ['All features', 'Unlimited users', '1TB storage', 'Dedicated support'],
      limits: {
        users: Infinity,
        storage: 1024 * 1024 * 1024 * 1024,
        apiCalls: Infinity,
      },
    },
  },

  // Create subscription
  subscribe: on($.Customer.subscribes, async ({ customer, plan }) => {
    // Create Stripe subscription
    const subscription = await api.stripe.subscriptions.create({
      customer: customer.stripeId,
      items: [{ price: SubscriptionBusiness.plans[plan].stripePriceId }],
      trial_period_days: 14,
      metadata: {
        $type: $.Subscription,
        plan,
        customerId: customer.id,
      },
    })

    // Save subscription
    await db.create($.Subscription, {
      $id: subscription.id,
      customer: customer.id,
      plan,
      status: 'trialing',
      currentPeriodStart: new Date(subscription.current_period_start * 1000),
      currentPeriodEnd: new Date(subscription.current_period_end * 1000),
    })

    // Provision resources
    await send($.Account.provision, {
      customer,
      plan,
      limits: SubscriptionBusiness.plans[plan].limits,
    })

    // Send confirmation
    await send($.Email.send, {
      to: customer.email,
      template: 'subscription-started',
      data: { plan, subscription },
    })
  }),

  // Handle subscription updates
  upgrade: on($.Subscription.upgraded, async ({ subscription, newPlan }) => {
    await api.stripe.subscriptions.update(subscription.stripeId, {
      items: [
        {
          id: subscription.stripeItemId,
          price: SubscriptionBusiness.plans[newPlan].stripePriceId,
        },
      ],
      proration_behavior: 'create_prorations',
    })

    await db.update($.Subscription, subscription.id, {
      plan: newPlan,
    })

    await send($.Account.updateLimits, {
      account: subscription.account,
      limits: SubscriptionBusiness.plans[newPlan].limits,
    })
  }),

  // Process renewals
  renew: on($.Stripe.invoice.paid, async (invoice) => {
    const subscription = await db.get($.Subscription, invoice.subscription)

    await db.update($.Subscription, subscription.id, {
      status: 'active',
      currentPeriodStart: new Date(invoice.period_start * 1000),
      currentPeriodEnd: new Date(invoice.period_end * 1000),
    })

    // Track MRR
    await send($.Metric.record, {
      name: 'MRR',
      value: invoice.amount_paid / 100,
      timestamp: new Date(),
    })
  }),

  // Handle failed payments
  failed: on($.Stripe.invoice.payment_failed, async (invoice) => {
    const subscription = await db.get($.Subscription, invoice.subscription)

    // Send payment failure notice
    await send($.Email.send, {
      to: subscription.customer.email,
      template: 'payment-failed',
      data: { invoice, retryDate: new Date(invoice.next_payment_attempt * 1000) },
    })

    // After 3 failures, cancel subscription
    if (invoice.attempt_count >= 3) {
      await send($.Subscription.cancel, {
        subscription,
        reason: 'payment_failed',
      })
    }
  }),
}

Usage-Based Pricing

Charge based on consumption:

const UsageBasedPricing = {
  // Pricing tiers
  pricing: {
    apiCalls: {
      tiers: [
        { from: 0, to: 10000, price: 0 }, // Free tier
        { from: 10001, to: 100000, price: 0.01 }, // $0.01 per call
        { from: 100001, to: 1000000, price: 0.008 }, // $0.008 per call
        { from: 1000001, to: Infinity, price: 0.005 }, // $0.005 per call
      ],
    },
    storage: {
      price: 0.023, // $0.023 per GB per month
      unit: 'GB',
    },
    bandwidth: {
      price: 0.085, // $0.085 per GB
      unit: 'GB',
    },
  },

  // Track usage
  track: on($.API.called, async (request) => {
    await db.create($.UsageRecord, {
      account: request.account,
      type: 'api-call',
      quantity: 1,
      timestamp: new Date(),
    })
  }),

  // Calculate charges
  calculate: async (account, startDate, endDate) => {
    // API calls
    const apiCalls = await db.count($.UsageRecord, {
      where: {
        account: account.id,
        type: 'api-call',
        timestamp: { $gte: startDate, $lte: endDate },
      },
    })

    let apiCharge = 0
    for (const tier of UsageBasedPricing.pricing.apiCalls.tiers) {
      if (apiCalls > tier.from) {
        const quantity = Math.min(apiCalls, tier.to) - tier.from
        apiCharge += quantity * tier.price
      }
    }

    // Storage (average over period)
    const storageRecords = await db.list($.StorageSnapshot, {
      where: {
        account: account.id,
        timestamp: { $gte: startDate, $lte: endDate },
      },
    })

    const avgStorage = storageRecords.reduce((sum, r) => sum + r.bytes, 0) / storageRecords.length
    const storageGB = avgStorage / (1024 * 1024 * 1024)
    const storageCharge = storageGB * UsageBasedPricing.pricing.storage.price

    // Bandwidth
    const bandwidth = await db.sum($.UsageRecord, 'quantity', {
      where: {
        account: account.id,
        type: 'bandwidth',
        timestamp: { $gte: startDate, $lte: endDate },
      },
    })

    const bandwidthGB = bandwidth / (1024 * 1024 * 1024)
    const bandwidthCharge = bandwidthGB * UsageBasedPricing.pricing.bandwidth.price

    return {
      apiCalls: { quantity: apiCalls, charge: apiCharge },
      storage: { quantity: storageGB, charge: storageCharge },
      bandwidth: { quantity: bandwidthGB, charge: bandwidthCharge },
      total: apiCharge + storageCharge + bandwidthCharge,
    }
  },

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

    const lastMonth = new Date(new Date().setMonth(new Date().getMonth() - 1))
    const startDate = new Date(lastMonth.setDate(1))
    const endDate = new Date(new Date().setDate(0)) // Last day of previous month

    for (const account of accounts) {
      const charges = await UsageBasedPricing.calculate(account, startDate, endDate)

      if (charges.total > 0) {
        const invoice = await db.create($.Invoice, {
          account: account.id,
          period: { start: startDate, end: endDate },
          lineItems: [
            {
              description: `API calls (${charges.apiCalls.quantity.toLocaleString()})`,
              quantity: charges.apiCalls.quantity,
              amount: charges.apiCalls.charge,
            },
            {
              description: `Storage (${charges.storage.quantity.toFixed(2)} GB)`,
              quantity: charges.storage.quantity,
              amount: charges.storage.charge,
            },
            {
              description: `Bandwidth (${charges.bandwidth.quantity.toFixed(2)} GB)`,
              quantity: charges.bandwidth.quantity,
              amount: charges.bandwidth.charge,
            },
          ],
          total: charges.total,
        })

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

Freemium Model

Free tier with paid upgrades:

const FreemiumModel = {
  // Free tier limits
  freeLimits: {
    users: 1,
    projects: 3,
    storage: 1 * 1024 * 1024 * 1024, // 1GB
    apiCalls: 1000,
  },

  // Check limits
  checkLimit: async (account, resource) => {
    const usage = await db.count($.UsageRecord, {
      where: {
        account: account.id,
        type: resource,
      },
    })

    const limit = account.plan === 'free' ? FreemiumModel.freeLimits[resource] : Infinity

    return {
      usage,
      limit,
      remaining: limit - usage,
      exceeded: usage >= limit,
    }
  },

  // Enforce limits
  enforce: on($.API.called, async (request) => {
    const limits = await FreemiumModel.checkLimit(request.account, 'apiCalls')

    if (limits.exceeded) {
      // Show upgrade prompt
      await send($.Modal.show, {
        user: request.user,
        type: 'upgrade-prompt',
        message: `You've reached your free tier limit of ${limits.limit} API calls. Upgrade to continue.`,
        cta: {
          text: 'Upgrade Now',
          action: $.Subscription.upgrade,
        },
      })

      return { error: 'Rate limit exceeded. Please upgrade.' }
    }

    // Process request
    return await processRequest(request)
  }),

  // Conversion triggers
  conversion: {
    // Prompt on limit reached
    limitReached: on($.Account.limitReached, async ({ account, resource }) => {
      await send($.Email.send, {
        to: account.user.email,
        template: 'upgrade-prompt-limit',
        data: {
          resource,
          limit: FreemiumModel.freeLimits[resource],
          benefit: `Upgrade to ${resource === 'apiCalls' ? 'unlimited' : '100x more'} ${resource}`,
        },
      })
    }),

    // Time-based prompts
    onboarding: on($.Account.daysOld(7), async (account) => {
      if (account.plan === 'free') {
        const usage = await db.count($.UsageRecord, {
          where: { account: account.id },
        })

        if (usage > FreemiumModel.freeLimits.apiCalls * 0.5) {
          await send($.Email.send, {
            to: account.user.email,
            template: 'upgrade-offer-active-user',
            discount: 0.2, // 20% off first month
          })
        }
      }
    }),
  },
}

Transaction/Marketplace Fees

Take a percentage of transactions:

const MarketplaceFees = {
  // Fee structure
  fees: {
    platform: 0.15, // 15% platform fee
    payment: 0.029 + 0.3, // Stripe: 2.9% + $0.30
    payout: 0.0025, // Payout fee: 0.25%
  },

  // Process transaction
  transaction: on($.Transaction.initiated, async (transaction) => {
    const { amount, buyer, seller } = transaction

    // Charge buyer
    const payment = await api.stripe.paymentIntents.create({
      amount: Math.round(amount * 100), // Convert to cents
      currency: 'usd',
      customer: buyer.stripeId,
      metadata: {
        transactionId: transaction.id,
        sellerId: seller.id,
      },
    })

    if (payment.status === 'succeeded') {
      // Calculate fees
      const platformFee = amount * MarketplaceFees.fees.platform
      const paymentFee = amount * MarketplaceFees.fees.payment.percentage + MarketplaceFees.fees.payment.fixed
      const sellerAmount = amount - platformFee - paymentFee

      // Hold in escrow
      await db.create($.Escrow, {
        transaction: transaction.id,
        amount: sellerAmount,
        releaseCondition: $.Service.completed,
      })

      // Record revenue
      await send($.Revenue.record, {
        type: 'platform-fee',
        amount: platformFee,
        transaction: transaction.id,
      })
    }
  }),

  // Release payment to seller
  release: on($.Service.completed, async (service) => {
    const escrow = await db.get($.Escrow, {
      where: { transaction: service.transaction },
    })

    // Transfer to seller (minus payout fee)
    const payoutFee = escrow.amount * MarketplaceFees.fees.payout
    const sellerPayout = escrow.amount - payoutFee

    await api.stripe.transfers.create({
      amount: Math.round(sellerPayout * 100),
      currency: 'usd',
      destination: service.seller.stripeAccountId,
      metadata: {
        transactionId: service.transaction,
        serviceId: service.id,
      },
    })

    // Update escrow
    await db.update($.Escrow, escrow.id, {
      status: 'released',
      releasedAt: new Date(),
    })

    // Notify seller
    await send($.Email.send, {
      to: service.seller.email,
      template: 'payout-processed',
      data: {
        amount: sellerPayout,
        service: service.id,
      },
    })
  }),
}

Payment Integration

Stripe Integration

Complete Stripe integration for subscriptions and payments:

const StripeIntegration = {
  // Setup customer
  createCustomer: on($.Customer.registered, async (customer) => {
    const stripeCustomer = await api.stripe.customers.create({
      email: customer.email,
      name: customer.name,
      metadata: {
        $type: $.Person,
        $id: customer.id,
      },
    })

    await db.update($.Customer, customer.id, {
      stripeId: stripeCustomer.id,
    })
  }),

  // Webhooks
  webhooks: {
    // Payment succeeded
    paymentSucceeded: on($.Stripe.payment_intent.succeeded, async (event) => {
      const payment = event.data.object

      await send($.Payment.record, {
        id: payment.id,
        amount: payment.amount / 100,
        customer: payment.customer,
        status: 'succeeded',
      })
    }),

    // Subscription created
    subscriptionCreated: on($.Stripe.customer.subscription.created, async (event) => {
      const subscription = event.data.object

      await send($.Subscription.activate, {
        stripeId: subscription.id,
        customer: subscription.customer,
        status: subscription.status,
      })
    }),

    // Subscription updated
    subscriptionUpdated: on($.Stripe.customer.subscription.updated, async (event) => {
      const subscription = event.data.object

      await db.update(
        $.Subscription,
        {
          where: { stripeId: subscription.id },
        },
        {
          status: subscription.status,
          currentPeriodEnd: new Date(subscription.current_period_end * 1000),
        }
      )
    }),

    // Payment failed
    paymentFailed: on($.Stripe.invoice.payment_failed, async (event) => {
      const invoice = event.data.object

      await send($.Alert.send, {
        type: 'payment-failed',
        invoice: invoice.id,
        customer: invoice.customer,
        attemptCount: invoice.attempt_count,
      })
    }),
  },
}

Invoice Management

Generate and manage invoices:

const InvoiceManagement = {
  // Generate invoice
  generate: on($.Invoice.generate, async ({ account, period }) => {
    const invoice = await db.create($.Invoice, {
      $type: $.Invoice,
      account: account.id,
      period,
      lineItems: [],
      subtotal: 0,
      tax: 0,
      total: 0,
      status: 'draft',
    })

    // Add subscription charges
    if (account.subscription) {
      const plan = await db.get($.Plan, account.subscription.plan)

      invoice.lineItems.push({
        description: `${plan.name} subscription`,
        quantity: 1,
        unitPrice: plan.price,
        amount: plan.price,
      })
    }

    // Add usage charges
    const usage = await calculateUsage(account, period)
    for (const [type, charge] of Object.entries(usage)) {
      if (charge.amount > 0) {
        invoice.lineItems.push({
          description: charge.description,
          quantity: charge.quantity,
          unitPrice: charge.unitPrice,
          amount: charge.amount,
        })
      }
    }

    // Calculate totals
    invoice.subtotal = invoice.lineItems.reduce((sum, item) => sum + item.amount, 0)
    invoice.tax = invoice.subtotal * 0.08 // 8% tax (varies by location)
    invoice.total = invoice.subtotal + invoice.tax

    await db.update($.Invoice, invoice.id, invoice)

    return invoice
  }),

  // Send invoice
  send: on($.Invoice.send, async (invoice) => {
    await send($.Email.send, {
      to: invoice.account.user.email,
      template: 'invoice',
      attachments: [
        {
          filename: `invoice-${invoice.id}.pdf`,
          content: await generateInvoicePDF(invoice),
        },
      ],
      data: { invoice },
    })

    await db.update($.Invoice, invoice.id, {
      status: 'sent',
      sentAt: new Date(),
    })
  }),

  // Process payment
  pay: on($.Invoice.pay, async (invoice) => {
    const payment = await api.stripe.paymentIntents.create({
      amount: Math.round(invoice.total * 100),
      currency: 'usd',
      customer: invoice.account.stripeId,
      metadata: {
        invoiceId: invoice.id,
      },
    })

    if (payment.status === 'succeeded') {
      await db.update($.Invoice, invoice.id, {
        status: 'paid',
        paidAt: new Date(),
        paymentId: payment.id,
      })

      await send($.Revenue.recognize, {
        amount: invoice.total,
        invoice: invoice.id,
      })
    }
  }),
}

Metrics & Analytics

Track key business metrics:

const BusinessMetrics = {
  // SaaS metrics
  saas: {
    // Monthly Recurring Revenue
    mrr: every($.Daily, async () => {
      const subscriptions = await db.list($.Subscription, {
        where: { status: 'active' },
      })

      const mrr = subscriptions.reduce((sum, sub) => {
        const monthly = sub.interval === 'year' ? sub.amount / 12 : sub.amount
        return sum + monthly
      }, 0)

      await send($.Metric.record, {
        name: 'MRR',
        value: mrr,
        timestamp: new Date(),
      })
    }),

    // Churn rate
    churn: every($.Monthly, async () => {
      const startCount = await db.count($.Subscription, {
        where: {
          createdAt: { $lt: startOfMonth },
        },
      })

      const churned = await db.count($.Subscription, {
        where: {
          cancelledAt: {
            $gte: startOfMonth,
            $lte: endOfMonth,
          },
        },
      })

      const churnRate = churned / startCount

      await send($.Metric.record, {
        name: 'Churn Rate',
        value: churnRate,
        timestamp: new Date(),
      })
    }),

    // Customer Lifetime Value
    ltv: async (customer) => {
      const totalRevenue = await db.sum($.Invoice, 'total', {
        where: {
          customer: customer.id,
          status: 'paid',
        },
      })

      const months = monthsBetween(customer.createdAt, new Date())

      return {
        total: totalRevenue,
        monthly: totalRevenue / months,
      }
    },

    // Customer Acquisition Cost
    cac: every($.Monthly, async () => {
      const marketingSpend = await db.sum($.Expense, 'amount', {
        where: {
          category: 'marketing',
          date: { $gte: startOfMonth, $lte: endOfMonth },
        },
      })

      const newCustomers = await db.count($.Customer, {
        where: {
          createdAt: { $gte: startOfMonth, $lte: endOfMonth },
        },
      })

      const cac = marketingSpend / newCustomers

      await send($.Metric.record, {
        name: 'CAC',
        value: cac,
        timestamp: new Date(),
      })
    }),
  },
}

Advanced Pricing Strategies

Dynamic Pricing

AI-powered dynamic pricing based on demand, competition, and customer value:

const DynamicPricing = {
  // Calculate optimal price
  calculate: async (product, context) => {
    const factors = {
      // Demand factors
      recentViews: await db.count($.ProductView, {
        where: {
          product: product.id,
          timestamp: { $gte: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000) },
        },
      }),
      inventoryLevel: product.inventory,
      seasonality: getSeasonalityFactor(product.category, new Date()),

      // Competition
      competitorPrices: await getCompetitorPrices(product.sku),

      // Customer value
      customerSegment: context.customer?.segment || 'standard',
      customerLifetimeValue: context.customer?.ltv || 0,
      purchaseHistory: context.customer
        ? await db.count($.Order, {
            where: { customer: context.customer.id },
          })
        : 0,
    }

    // AI determines optimal price
    const pricing = await ai.generate({
      prompt: `Determine optimal price based on factors`,
      schema: $.PriceRecommendation,
      context: factors,
      model: 'gpt-5',
    })

    return {
      price: pricing.price,
      basePrice: product.basePrice,
      adjustment: (pricing.price - product.basePrice) / product.basePrice,
      reasoning: pricing.reasoning,
      confidence: pricing.confidence,
    }
  },

  // Apply dynamic pricing
  apply: on($.Customer.views.Product, async ({ customer, product }) => {
    const pricing = await DynamicPricing.calculate(product, { customer })

    // Show personalized price
    await send($.Price.personalize, {
      customer,
      product,
      price: pricing.price,
      validUntil: new Date(Date.now() + 30 * 60 * 1000), // 30 minutes
    })

    // Track pricing decision
    await db.create($.PricingDecision, {
      product: product.id,
      customer: customer.id,
      suggestedPrice: pricing.price,
      basePrice: pricing.basePrice,
      factors: pricing,
      timestamp: new Date(),
    })
  }),

  // A/B test pricing
  experiment: async (product) => {
    const variants = [
      { price: product.basePrice * 0.9, name: '10% discount' },
      { price: product.basePrice, name: 'baseline' },
      { price: product.basePrice * 1.1, name: '10% premium' },
    ]

    // Assign customers to variants
    on($.Customer.views.Product, async ({ customer, product }) => {
      const variant = variants[customer.id % variants.length]

      await send($.Price.show, {
        customer,
        product,
        price: variant.price,
        experiment: {
          id: 'price-test-1',
          variant: variant.name,
        },
      })
    })

    // Analyze results after 1000 views
    every('* * * * *', async () => {
      const results = await db.aggregate($.PricingDecision, [
        { $match: { product: product.id } },
        {
          $group: {
            _id: '$experiment.variant',
            conversions: { $sum: '$converted' },
            revenue: { $sum: '$revenue' },
          },
        },
      ])

      if (results.totalViews > 1000) {
        const winner = results.reduce((best, current) =>
          current.revenue > best.revenue ? current : best
        )

        await db.update($.Product, product.id, {
          basePrice: winner.price,
          pricingStrategy: `Optimized via A/B test: ${winner.name}`,
        })
      }
    })
  },
}

Value-Based Pricing

Price based on customer value perception:

const ValueBasedPricing = {
  // Calculate value metrics
  calculateValue: async (customer, product) => {
    // Estimate ROI for customer
    const roi = await ai.generate({
      prompt: `Calculate ROI for ${customer.company} using ${product.name}`,
      schema: $.ROIAnalysis,
      context: {
        customerRevenue: customer.annualRevenue,
        customerSize: customer.employeeCount,
        productCapabilities: product.features,
        industryBenchmarks: await getIndustryBenchmarks(customer.industry),
      },
    })

    return {
      estimatedSavings: roi.annualSavings,
      timeToValue: roi.monthsToRoi,
      roi: roi.threeYearRoi,
      willingnessToPay: roi.annualSavings * 0.2, // Capture 20% of value
    }
  },

  // Tiered value pricing
  tiers: {
    startup: {
      criteria: { revenue: { $lt: 1000000 }, employees: { $lt: 10 } },
      priceMultiplier: 0.5,
      features: ['basic'],
    },
    smb: {
      criteria: {
        revenue: { $gte: 1000000, $lt: 10000000 },
        employees: { $gte: 10, $lt: 100 },
      },
      priceMultiplier: 1.0,
      features: ['basic', 'advanced'],
    },
    enterprise: {
      criteria: { revenue: { $gte: 10000000 }, employees: { $gte: 100 } },
      priceMultiplier: 3.0,
      features: ['basic', 'advanced', 'enterprise'],
    },
  },

  // Quote generation
  generateQuote: on($.Quote.requested, async ({ customer, products }) => {
    const tier = Object.entries(ValueBasedPricing.tiers).find(([, criteria]) =>
      matchesCriteria(customer, criteria.criteria)
    )[0]

    const quote = await db.create($.Quote, {
      customer: customer.id,
      tier,
      items: await Promise.all(
        products.map(async (product) => {
          const value = await ValueBasedPricing.calculateValue(customer, product)

          return {
            product: product.id,
            quantity: product.quantity,
            listPrice: product.basePrice,
            discount: 1 - ValueBasedPricing.tiers[tier].priceMultiplier,
            price: product.basePrice * ValueBasedPricing.tiers[tier].priceMultiplier,
            estimatedValue: value.estimatedSavings,
            roi: value.roi,
          }
        })
      ),
      validUntil: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000), // 30 days
    })

    // Generate proposal document
    const proposal = await ai.generate({
      prompt: 'Create compelling value proposition',
      schema: $.Proposal,
      context: { customer, quote },
    })

    await send($.Email.send, {
      to: customer.email,
      subject: 'Your Custom Quote',
      template: 'quote',
      attachments: [
        {
          filename: 'proposal.pdf',
          content: await generatePDF(proposal),
        },
      ],
      data: { quote, proposal },
    })
  }),
}

Psychological Pricing

Price optimization using behavioral economics:

const PsychologicalPricing = {
  // Charm pricing (ending in .99)
  charm: (price) => {
    const dollars = Math.floor(price)
    return dollars - 0.01 // e.g., $10.00 -> $9.99
  },

  // Prestige pricing (round numbers)
  prestige: (price) => {
    return Math.round(price / 10) * 10 // e.g., $47 -> $50
  },

  // Anchor pricing
  anchor: async (product) => {
    const originalPrice = product.basePrice * 1.5

    await db.update($.Product, product.id, {
      price: product.basePrice,
      wasPrice: originalPrice,
      discount: ((originalPrice - product.basePrice) / originalPrice) * 100,
      savings: originalPrice - product.basePrice,
    })
  },

  // Bundle pricing
  bundle: async (products) => {
    const totalValue = products.reduce((sum, p) => sum + p.price, 0)
    const bundlePrice = totalValue * 0.8 // 20% bundle discount

    return await db.create($.Bundle, {
      $type: $.ProductBundle,
      products: products.map((p) => p.id),
      price: bundlePrice,
      savings: totalValue - bundlePrice,
      savingsPercent: 20,
    })
  },

  // Decoy pricing
  decoy: async (product, plan) => {
    // Make the target plan look more attractive
    const plans = [
      {
        name: 'Basic',
        price: plan.price * 0.6,
        features: plan.features.slice(0, 3),
      },
      {
        name: 'Professional',
        price: plan.price,
        features: plan.features,
        popular: true, // Target plan
      },
      {
        name: 'Pro Plus', // Decoy - similar to Pro but slightly more expensive
        price: plan.price * 1.1,
        features: [...plan.features, '1 extra feature'],
      },
      {
        name: 'Enterprise',
        price: plan.price * 2,
        features: [...plan.features, ...['custom', 'white-label', 'sla']],
      },
    ]

    return plans
  },
}

Advanced Revenue Optimization

Retention & Expansion Revenue

const RevenueExpansion = {
  // Identify expansion opportunities
  identifyOpportunities: every($.Weekly, async () => {
    const accounts = await db.list($.Account, {
      where: {
        status: 'active',
        plan: { $ne: 'enterprise' },
      },
    })

    for (const account of accounts) {
      // Usage-based expansion
      const usage = await db.aggregate($.UsageRecord, [
        { $match: { account: account.id } },
        {
          $group: {
            _id: '$type',
            total: { $sum: '$quantity' },
            limit: { $first: account.limits },
          },
        },
      ])

      const highUsage = usage.filter((u) => u.total / u.limit > 0.8)

      if (highUsage.length > 0) {
        await send($.Opportunity.expansion, {
          type: 'usage-based',
          account,
          trigger: highUsage,
          recommendation: 'upgrade-plan',
          estimatedValue: calculateUpgradeValue(account, highUsage),
        })
      }

      // Feature-based expansion
      const featureRequests = await db.count($.FeatureRequest, {
        where: {
          account: account.id,
          feature: { $in: getPremiumFeatures() },
        },
      })

      if (featureRequests > 3) {
        await send($.Opportunity.expansion, {
          type: 'feature-based',
          account,
          recommendation: 'upgrade-plan',
          estimatedValue: calculateFeatureValue(account),
        })
      }

      // Seat-based expansion
      const activeUsers = await db.count($.User, {
        where: {
          account: account.id,
          lastActive: { $gte: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000) },
        },
      })

      if (activeUsers >= account.limits.users) {
        await send($.Opportunity.expansion, {
          type: 'seat-based',
          account,
          recommendation: 'add-seats',
          estimatedValue: (activeUsers - account.limits.users) * account.plan.pricePerSeat,
        })
      }
    }
  }),

  // Automated expansion plays
  execute: on($.Opportunity.expansion, async (opportunity) => {
    const { account, type, recommendation } = opportunity

    switch (type) {
      case 'usage-based':
        // Show in-app upgrade prompt
        await send($.Modal.show, {
          users: await getAccountUsers(account),
          type: 'upgrade-prompt',
          message: "You're close to your limit! Upgrade to continue growing.",
          cta: {
            text: 'Upgrade Now',
            action: $.Subscription.upgrade,
            discount: 0.1, // 10% off first month
          },
        })
        break

      case 'feature-based':
        // Email campaign
        await send($.Email.send, {
          to: account.owner.email,
          template: 'unlock-features',
          data: {
            features: getPremiumFeatures(),
            trial: true,
            trialDays: 14,
          },
        })
        break

      case 'seat-based':
        // Auto-upgrade with notification
        await send($.Subscription.addSeats, {
          account,
          seats: 5, // Add 5 seats
          prorated: true,
        })

        await send($.Email.send, {
          to: account.owner.email,
          template: 'seats-added',
          data: {
            seatsAdded: 5,
            newLimit: account.limits.users + 5,
            proratedCharge: calculateProration(account, 5),
          },
        })
        break
    }
  }),
}

Churn Prevention

const ChurnPrevention = {
  // Predictive churn model
  predictChurn: every($.Daily, async () => {
    const accounts = await db.list($.Account, {
      where: { status: 'active' },
    })

    for (const account of accounts) {
      // Collect signals
      const signals = {
        // Usage signals
        loginFrequency: await calculateLoginFrequency(account),
        featureAdoption: await calculateFeatureAdoption(account),
        apiUsage: await calculateAPIUsage(account),

        // Support signals
        supportTickets: await db.count($.SupportTicket, {
          where: {
            account: account.id,
            createdAt: { $gte: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000) },
          },
        }),
        negativeTickets: await db.count($.SupportTicket, {
          where: {
            account: account.id,
            sentiment: 'negative',
          },
        }),

        // Billing signals
        paymentFailures: await db.count($.PaymentFailure, {
          where: { account: account.id },
        }),
        downgrades: await db.count($.Subscription, {
          where: {
            account: account.id,
            event: 'downgrade',
          },
        }),

        // Engagement signals
        nps: account.nps,
        lastNPSSurvey: account.lastNPSSurvey,
      }

      // AI predicts churn risk
      const prediction = await ai.generate({
        prompt: 'Predict churn risk and recommend interventions',
        schema: $.ChurnPrediction,
        context: signals,
        model: 'gpt-5',
      })

      if (prediction.risk === 'high') {
        await send($.Alert.churnRisk, {
          account,
          risk: prediction.risk,
          score: prediction.score,
          signals: prediction.signals,
          interventions: prediction.recommendations,
        })

        // Automated interventions
        await ChurnPrevention.intervene(account, prediction)
      }
    }
  }),

  // Intervention strategies
  intervene: async (account, prediction) => {
    const interventions = prediction.recommendations

    for (const intervention of interventions) {
      switch (intervention.type) {
        case 'success-manager-outreach':
          await send($.Task.create, {
            type: 'success-outreach',
            account,
            priority: 'high',
            dueDate: new Date(Date.now() + 24 * 60 * 60 * 1000),
            description: `High churn risk: ${intervention.reason}`,
          })
          break

        case 'offer-discount':
          await send($.Email.send, {
            to: account.owner.email,
            template: 'retention-offer',
            data: {
              discount: 0.3, // 30% off
              duration: '6 months',
              reason: 'valued-customer',
            },
          })
          break

        case 'training-session':
          await send($.Calendar.schedule, {
            type: 'training',
            account,
            topic: intervention.topic,
            duration: 60,
          })
          break

        case 'feature-enablement':
          // Enable premium features for free
          await db.update($.Account, account.id, {
            features: {
              ...account.features,
              [intervention.feature]: true,
            },
            featureGrants: {
              ...account.featureGrants,
              [intervention.feature]: {
                grantedAt: new Date(),
                expiresAt: new Date(Date.now() + 90 * 24 * 60 * 60 * 1000),
                reason: 'retention',
              },
            },
          })
          break
      }
    }
  },

  // Win-back campaigns
  winback: on($.Subscription.cancelled, async (subscription) => {
    // Immediate exit survey
    await send($.Email.send, {
      to: subscription.customer.email,
      template: 'exit-survey',
      data: { subscription },
    })

    // Wait 30 days
    setTimeout(
      async () => {
        const cancelReason = await db.get($.CancellationFeedback, {
          where: { subscription: subscription.id },
        })

        // Targeted win-back based on cancel reason
        const offer = await generateWinbackOffer(cancelReason)

        await send($.Email.send, {
          to: subscription.customer.email,
          template: 'win-back',
          data: {
            reason: cancelReason.reason,
            offer: offer,
            testimonials: await getRelevantTestimonials(cancelReason),
          },
        })
      },
      30 * 24 * 60 * 60 * 1000
    )
  }),
}

Revenue Analytics & Forecasting

const RevenueAnalytics = {
  // Real-time revenue tracking
  track: on($.Invoice.paid, async (invoice) => {
    // Record revenue
    await db.create($.RevenueEvent, {
      type: 'recognized',
      amount: invoice.amount,
      account: invoice.account,
      plan: invoice.subscription?.plan,
      timestamp: new Date(),
      metadata: {
        mrr: invoice.subscription?.amount / (invoice.subscription?.interval === 'year' ? 12 : 1),
        category: invoice.type,
      },
    })

    // Update account metrics
    const accountRevenue = await db.sum($.RevenueEvent, 'amount', {
      where: {
        account: invoice.account,
        type: 'recognized',
      },
    })

    await db.update($.Account, invoice.account, {
      totalRevenue: accountRevenue,
      ltv: calculateLTV(invoice.account, accountRevenue),
      lastPayment: new Date(),
    })
  }),

  // Revenue forecasting
  forecast: every($.Daily, async () => {
    // Get all active subscriptions
    const subscriptions = await db.list($.Subscription, {
      where: { status: 'active' },
    })

    // Calculate MRR
    const mrr = subscriptions.reduce((sum, sub) => {
      const monthly = sub.interval === 'year' ? sub.amount / 12 : sub.amount
      return sum + monthly
    }, 0)

    // Forecast next 12 months
    const forecast = []
    let projectedMRR = mrr

    for (let month = 1; month <= 12; month++) {
      // Apply growth rate (based on historical data)
      const growth = await calculateGrowthRate(subscriptions, month)
      const churnRate = await calculateChurnRate(subscriptions, month)

      projectedMRR = projectedMRR * (1 + growth) * (1 - churnRate)

      forecast.push({
        month,
        date: new Date(Date.now() + month * 30 * 24 * 60 * 60 * 1000),
        mrr: projectedMRR,
        arr: projectedMRR * 12,
        confidence: 1 - month * 0.05, // Decreasing confidence
      })
    }

    // Store forecast
    await db.create($.RevenueForecast, {
      generatedAt: new Date(),
      currentMRR: mrr,
      forecast,
      assumptions: {
        averageGrowth: await calculateAverageGrowth(),
        averageChurn: await calculateAverageChurn(),
      },
    })
  }),

  // Cohort analysis
  analyzeCohorts: every($.Monthly, async () => {
    // Group customers by signup month
    const cohorts = await db.aggregate($.Customer, [
      {
        $group: {
          _id: {
            year: { $year: '$createdAt' },
            month: { $month: '$createdAt' },
          },
          customers: { $push: '$_id' },
          count: { $sum: 1 },
        },
      },
    ])

    // Analyze retention for each cohort
    for (const cohort of cohorts) {
      const retention = []

      for (let month = 0; month <= 12; month++) {
        const activeCustomers = await db.count($.Subscription, {
          where: {
            customer: { $in: cohort.customers },
            status: 'active',
            createdAt: {
              $lte: new Date(cohort._id.year, cohort._id.month + month),
            },
          },
        })

        retention.push({
          month,
          active: activeCustomers,
          retention: activeCustomers / cohort.count,
        })
      }

      await db.create($.CohortAnalysis, {
        cohort: `${cohort._id.year}-${cohort._id.month}`,
        initialSize: cohort.count,
        retention,
        ltv: calculateCohortLTV(retention),
      })
    }
  }),
}

Next Steps


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