.do
Service TypesAutomation

Business Process Automation

Build services that automate complete business processes including invoice processing, expense management, scheduling, approvals, and document workflows

Build comprehensive services that automate end-to-end business processes, from invoice processing and expense management to scheduling, approvals, and document workflows.

Overview

Business process automation services replace manual, repetitive business operations with intelligent, automated workflows. They're essential for:

  • Invoice Processing: Extract, validate, approve, and pay invoices
  • Expense Management: Handle expense reports and reimbursements
  • Purchase Orders: Automate procurement workflows
  • Contract Management: Route contracts through approval chains
  • HR Processes: Onboarding, time-off requests, performance reviews
  • Compliance: Automated compliance checks and reporting

Core Concepts

Business Process Structure

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

// Define invoice processing service
const invoiceProcessingService = await $.Service.create({
  name: 'Automated Invoice Processing',
  type: $.ServiceType.Automation,
  subtype: 'business-process',

  // Process definition
  process: {
    name: 'Invoice to Payment',
    stages: [
      {
        id: 'receive',
        name: 'Receive Invoice',
        type: 'trigger',
        sources: ['email', 'upload', 'api'],
      },
      {
        id: 'extract',
        name: 'Extract Data',
        type: 'automated',
        technology: 'ocr-ai',
        timeout: 30000,
      },
      {
        id: 'validate',
        name: 'Validate Invoice',
        type: 'automated',
        checks: ['po-match', 'vendor-exists', 'amount-reasonable'],
      },
      {
        id: 'approve',
        name: 'Get Approval',
        type: 'human',
        routing: 'dynamic',
        sla: 86400000, // 24 hours
      },
      {
        id: 'pay',
        name: 'Process Payment',
        type: 'automated',
        integration: 'accounting-system',
      },
      {
        id: 'archive',
        name: 'Archive Documents',
        type: 'automated',
        retention: '7-years',
      },
    ],
  },

  // Pricing model
  pricing: {
    model: 'per-transaction',
    baseRate: 2.0,
    volume: [
      { min: 0, max: 100, rate: 2.0 },
      { min: 101, max: 1000, rate: 1.5 },
      { min: 1001, max: Infinity, rate: 1.0 },
    ],
    additionalCosts: {
      humanReview: 0.5,
      urgentProcessing: 1.0,
    },
  },
})

Invoice Processing Automation

Complete Invoice Workflow

// Automated invoice processing
on($.Invoice.received, async (invoice) => {
  const processState = {
    invoiceId: invoice.id,
    status: 'processing',
    stage: 'receive',
    data: {},
    approvals: [],
    startTime: Date.now(),
  }

  try {
    // Stage 1: Extract Invoice Data
    processState.stage = 'extract'
    await send($.ProcessProgress.updated, {
      invoiceId: invoice.id,
      stage: 'extract',
      status: 'running',
    })

    const extracted = await ai.extract({
      model: 'gpt-5',
      document: invoice.file,
      schema: {
        vendorName: 'string',
        vendorAddress: 'string',
        invoiceNumber: 'string',
        invoiceDate: 'date',
        dueDate: 'date',
        purchaseOrderNumber: 'string',
        lineItems: [
          {
            description: 'string',
            quantity: 'number',
            unitPrice: 'number',
            amount: 'number',
            category: 'string',
          },
        ],
        subtotal: 'number',
        taxAmount: 'number',
        taxRate: 'number',
        totalAmount: 'number',
        paymentTerms: 'string',
        bankDetails: {
          accountNumber: 'string',
          routingNumber: 'string',
          accountName: 'string',
        },
      },
    })

    processState.data.extracted = extracted

    // Stage 2: Validate Invoice
    processState.stage = 'validate'
    await send($.ProcessProgress.updated, {
      invoiceId: invoice.id,
      stage: 'validate',
      status: 'running',
    })

    const validation = await validateInvoice(extracted, invoice)

    if (!validation.valid) {
      // Check if issues are resolvable
      if (validation.severity === 'critical') {
        await send($.Invoice.rejected, {
          invoiceId: invoice.id,
          reason: 'validation-failed',
          issues: validation.issues,
        })
        return
      } else {
        // Flag for review but continue
        processState.data.validationWarnings = validation.issues
      }
    }

    processState.data.validation = validation

    // Stage 3: PO Matching
    if (extracted.purchaseOrderNumber) {
      const poMatch = await matchPurchaseOrder(extracted)

      if (!poMatch.matched) {
        await send($.Invoice.flagForReview, {
          invoiceId: invoice.id,
          reason: 'po-mismatch',
          details: poMatch.differences,
        })
      }

      processState.data.poMatch = poMatch
    }

    // Stage 4: Determine Approval Route
    processState.stage = 'approve'
    const approvalRoute = await determineApprovalRoute(extracted, processState.data)

    for (const approver of approvalRoute) {
      // Request approval
      const approval = await send($.Approval.request, {
        type: 'invoice',
        invoiceId: invoice.id,
        approverId: approver.id,
        amount: extracted.totalAmount,
        vendor: extracted.vendorName,
        dueDate: extracted.dueDate,
        deadline: new Date(Date.now() + 86400000), // 24 hours
      })

      // Wait for approval (with timeout)
      const approved = await waitForApproval(approval.id, 86400000)

      if (!approved) {
        // Escalate
        await send($.Approval.escalate, {
          approvalId: approval.id,
          reason: 'timeout',
        })
        continue
      }

      processState.approvals.push({
        approver: approver.id,
        approved: approved.decision === 'approved',
        timestamp: approved.timestamp,
        comments: approved.comments,
      })

      // Check if approval was denied
      if (approved.decision === 'denied') {
        await send($.Invoice.rejected, {
          invoiceId: invoice.id,
          reason: 'denied-by-approver',
          approver: approver.id,
          comments: approved.comments,
        })
        return
      }
    }

    // Stage 5: Create Accounting Entry
    processState.stage = 'accounting'
    await send($.ProcessProgress.updated, {
      invoiceId: invoice.id,
      stage: 'accounting',
      status: 'running',
    })

    const accountingEntry = await createAccountingEntry({
      type: 'accounts-payable',
      vendor: extracted.vendorName,
      amount: extracted.totalAmount,
      dueDate: extracted.dueDate,
      invoiceNumber: extracted.invoiceNumber,
      lineItems: extracted.lineItems.map((item) => ({
        account: getCategoryAccount(item.category),
        description: item.description,
        amount: item.amount,
      })),
    })

    processState.data.accountingEntry = accountingEntry

    // Stage 6: Schedule Payment
    processState.stage = 'payment'
    const payment = await schedulePayment({
      vendor: extracted.vendorName,
      amount: extracted.totalAmount,
      date: extracted.dueDate,
      invoiceNumber: extracted.invoiceNumber,
      bankDetails: extracted.bankDetails,
      reference: `INV-${extracted.invoiceNumber}`,
    })

    processState.data.payment = payment

    // Stage 7: Archive Documents
    processState.stage = 'archive'
    await archiveInvoiceDocuments({
      invoiceId: invoice.id,
      documents: [invoice.file],
      metadata: {
        vendor: extracted.vendorName,
        amount: extracted.totalAmount,
        date: extracted.invoiceDate,
        processedAt: new Date(),
      },
      retention: '7-years',
    })

    // Process complete
    processState.status = 'completed'
    await db.update(invoice, {
      status: 'processed',
      processedAt: new Date(),
      processData: processState.data,
    })

    await send($.Invoice.processed, {
      invoiceId: invoice.id,
      duration: Date.now() - processState.startTime,
      stages: ['extract', 'validate', 'approve', 'pay', 'archive'],
    })

    // Calculate and charge
    const cost = calculateInvoiceProcessingCost(invoiceProcessingService.pricing, processState)

    await send($.Payment.charge, {
      customerId: invoice.companyId,
      amount: cost,
      description: `Invoice Processing - ${extracted.vendorName}`,
      breakdown: {
        base: invoiceProcessingService.pricing.baseRate,
        approvals: processState.approvals.length * 0.5,
        total: cost,
      },
    })
  } catch (error) {
    processState.status = 'failed'
    await send($.Invoice.failed, {
      invoiceId: invoice.id,
      stage: processState.stage,
      error: error.message,
      processData: processState.data,
    })
  }
})

// Validate invoice data
async function validateInvoice(extracted: any, invoice: any) {
  const issues = []
  let severity = 'none'

  // Check required fields
  const requiredFields = ['vendorName', 'invoiceNumber', 'invoiceDate', 'totalAmount']
  for (const field of requiredFields) {
    if (!extracted[field]) {
      issues.push({
        field,
        issue: 'missing',
        severity: 'critical',
      })
      severity = 'critical'
    }
  }

  // Validate amounts
  const calculatedTotal = extracted.lineItems.reduce((sum: number, item: any) => sum + item.amount, 0)

  if (Math.abs(calculatedTotal - extracted.subtotal) > 0.01) {
    issues.push({
      field: 'subtotal',
      issue: 'mismatch',
      expected: calculatedTotal,
      actual: extracted.subtotal,
      severity: 'warning',
    })
    severity = severity === 'none' ? 'warning' : severity
  }

  // Check vendor exists
  const vendor = await db.findOne($.Vendor, {
    name: extracted.vendorName,
  })

  if (!vendor) {
    issues.push({
      field: 'vendorName',
      issue: 'unknown-vendor',
      severity: 'warning',
    })
    severity = severity === 'none' ? 'warning' : severity
  }

  // Check for duplicate invoice
  const duplicate = await db.findOne($.Invoice, {
    vendorName: extracted.vendorName,
    invoiceNumber: extracted.invoiceNumber,
    status: { in: ['processed', 'processing'] },
  })

  if (duplicate) {
    issues.push({
      field: 'invoiceNumber',
      issue: 'duplicate',
      existingInvoiceId: duplicate.id,
      severity: 'critical',
    })
    severity = 'critical'
  }

  return {
    valid: severity !== 'critical',
    severity,
    issues,
  }
}

// Match invoice to purchase order
async function matchPurchaseOrder(extracted: any) {
  const po = await db.findOne($.PurchaseOrder, {
    number: extracted.purchaseOrderNumber,
  })

  if (!po) {
    return {
      matched: false,
      reason: 'po-not-found',
    }
  }

  const differences = []

  // Check vendor
  if (po.vendorName !== extracted.vendorName) {
    differences.push({
      field: 'vendor',
      po: po.vendorName,
      invoice: extracted.vendorName,
    })
  }

  // Check amounts
  if (Math.abs(po.totalAmount - extracted.totalAmount) > 0.01) {
    differences.push({
      field: 'amount',
      po: po.totalAmount,
      invoice: extracted.totalAmount,
      difference: extracted.totalAmount - po.totalAmount,
    })
  }

  // Check line items
  for (const invoiceItem of extracted.lineItems) {
    const poItem = po.lineItems.find((item: any) => item.description === invoiceItem.description)

    if (!poItem) {
      differences.push({
        field: 'line-item',
        issue: 'not-in-po',
        item: invoiceItem.description,
      })
    } else if (Math.abs(poItem.amount - invoiceItem.amount) > 0.01) {
      differences.push({
        field: 'line-item-amount',
        item: invoiceItem.description,
        po: poItem.amount,
        invoice: invoiceItem.amount,
      })
    }
  }

  return {
    matched: differences.length === 0,
    po,
    differences,
  }
}

// Determine approval routing
async function determineApprovalRoute(extracted: any, processData: any) {
  const route = []

  // Amount-based routing
  if (extracted.totalAmount <= 1000) {
    // Manager approval only
    route.push({
      id: await getManagerApprover(extracted),
      level: 'manager',
      required: true,
    })
  } else if (extracted.totalAmount <= 10000) {
    // Manager + Director
    route.push({
      id: await getManagerApprover(extracted),
      level: 'manager',
      required: true,
    })
    route.push({
      id: await getDirectorApprover(extracted),
      level: 'director',
      required: true,
    })
  } else {
    // Manager + Director + VP
    route.push({
      id: await getManagerApprover(extracted),
      level: 'manager',
      required: true,
    })
    route.push({
      id: await getDirectorApprover(extracted),
      level: 'director',
      required: true,
    })
    route.push({
      id: await getVPApprover(extracted),
      level: 'vp',
      required: true,
    })
  }

  // Additional approval for flagged items
  if (processData.validationWarnings?.length > 0 || processData.poMatch?.differences?.length > 0) {
    route.push({
      id: await getFinanceApprover(),
      level: 'finance',
      required: true,
    })
  }

  return route
}

Expense Management Automation

// Expense report processing
const expenseManagementService = await $.Service.create({
  name: 'Expense Report Automation',
  type: $.ServiceType.Automation,
  subtype: 'business-process',

  process: {
    stages: [
      { id: 'submit', name: 'Submit Expenses' },
      { id: 'categorize', name: 'Auto-Categorize' },
      { id: 'policy-check', name: 'Policy Compliance' },
      { id: 'approve', name: 'Manager Approval' },
      { id: 'reimburse', name: 'Process Reimbursement' },
    ],
  },

  pricing: {
    model: 'per-report',
    rate: 1.5,
    additionalCosts: {
      receiptOCR: 0.1,
      policyViolation: 0.25,
    },
  },
})

// Handle expense submission
on($.ExpenseReport.submitted, async (report) => {
  try {
    // Extract data from receipts
    const receipts = []
    for (const receipt of report.receipts) {
      const data = await ai.extract({
        model: 'gpt-5',
        document: receipt.file,
        schema: {
          merchant: 'string',
          date: 'date',
          amount: 'number',
          category: 'string',
          paymentMethod: 'string',
          items: [
            {
              description: 'string',
              quantity: 'number',
              price: 'number',
            },
          ],
        },
      })

      receipts.push({
        receiptId: receipt.id,
        ...data,
      })
    }

    // Auto-categorize expenses
    const categorized = await ai.categorize({
      model: 'gpt-5',
      expenses: receipts,
      categories: await getExpenseCategories(),
      rules: await getCategoryRules(),
    })

    // Check against expense policy
    const policyCheck = await checkExpensePolicy(categorized, report.employeeId)

    // Route for approval
    const approvalRequired = policyCheck.violations.length > 0 || categorized.totalAmount > 500

    if (approvalRequired) {
      const manager = await getEmployeeManager(report.employeeId)

      await send($.Approval.request, {
        type: 'expense-report',
        reportId: report.id,
        approverId: manager.id,
        amount: categorized.totalAmount,
        expenses: categorized.expenses,
        violations: policyCheck.violations,
      })
    } else {
      // Auto-approve
      await processReimbursement(report, categorized)
    }
  } catch (error) {
    await send($.ExpenseReport.failed, {
      reportId: report.id,
      error: error.message,
    })
  }
})

// Check expense policy compliance
async function checkExpensePolicy(expenses: any, employeeId: string) {
  const policy = await db.findOne($.ExpensePolicy, {
    where: { active: true },
  })

  const violations = []

  for (const expense of expenses.expenses) {
    // Check category limits
    const categoryLimit = policy.categoryLimits[expense.category]
    if (categoryLimit && expense.amount > categoryLimit) {
      violations.push({
        expense: expense.receiptId,
        rule: 'category-limit',
        limit: categoryLimit,
        actual: expense.amount,
        severity: 'warning',
      })
    }

    // Check per-diem rates
    if (expense.category === 'meals') {
      const perDiem = policy.perDiemRates[expense.location] || policy.perDiemRates.default
      if (expense.amount > perDiem) {
        violations.push({
          expense: expense.receiptId,
          rule: 'per-diem',
          limit: perDiem,
          actual: expense.amount,
          severity: 'warning',
        })
      }
    }

    // Check receipt requirements
    if (expense.amount > policy.receiptRequired && !expense.receiptFile) {
      violations.push({
        expense: expense.receiptId,
        rule: 'receipt-required',
        severity: 'critical',
      })
    }

    // Check prohibited expenses
    if (policy.prohibitedCategories.includes(expense.category)) {
      violations.push({
        expense: expense.receiptId,
        rule: 'prohibited-category',
        category: expense.category,
        severity: 'critical',
      })
    }
  }

  return {
    compliant: violations.filter((v) => v.severity === 'critical').length === 0,
    violations,
  }
}

// Process reimbursement
async function processReimbursement(report: any, expenses: any) {
  // Create reimbursement payment
  const reimbursement = await db.create($.Reimbursement, {
    employeeId: report.employeeId,
    reportId: report.id,
    amount: expenses.totalAmount,
    expenses: expenses.expenses,
    status: 'pending',
  })

  // Schedule payment
  await send($.Payment.schedule, {
    payeeType: 'employee',
    payeeId: report.employeeId,
    amount: expenses.totalAmount,
    date: getNextPayrollDate(),
    reference: `Expense Reimbursement - ${report.id}`,
  })

  // Create accounting entries
  for (const expense of expenses.expenses) {
    await createAccountingEntry({
      type: 'expense',
      category: expense.category,
      amount: expense.amount,
      date: expense.date,
      employee: report.employeeId,
      reference: expense.receiptId,
    })
  }

  await db.update(report, {
    status: 'approved',
    approvedAt: new Date(),
    reimbursementId: reimbursement.id,
  })
}

Document Processing Automation

// Document workflow automation
const documentWorkflowService = await $.Service.create({
  name: 'Document Processing Workflow',
  type: $.ServiceType.Automation,
  subtype: 'business-process',

  process: {
    stages: [
      { id: 'receive', name: 'Receive Document' },
      { id: 'classify', name: 'Auto-Classify' },
      { id: 'extract', name: 'Extract Data' },
      { id: 'route', name: 'Route to Team' },
      { id: 'process', name: 'Process Document' },
      { id: 'archive', name: 'Archive' },
    ],
  },

  pricing: {
    model: 'per-document',
    rate: 0.5,
    additionalCosts: {
      classification: 0.1,
      extraction: 0.25,
      storage: 0.05,
    },
  },
})

// Handle document processing
on($.Document.received, async (document) => {
  try {
    // Classify document type
    const classification = await ai.classify({
      model: 'gpt-5',
      document: document.file,
      categories: ['invoice', 'contract', 'purchase-order', 'receipt', 'tax-document', 'other'],
    })

    await db.update(document, {
      type: classification.category,
      confidence: classification.confidence,
    })

    // Route based on document type
    switch (classification.category) {
      case 'invoice':
        await send($.Invoice.received, {
          documentId: document.id,
          file: document.file,
        })
        break

      case 'contract':
        await send($.Contract.received, {
          documentId: document.id,
          file: document.file,
        })
        break

      case 'purchase-order':
        await send($.PurchaseOrder.received, {
          documentId: document.id,
          file: document.file,
        })
        break

      default:
        // Manual review required
        await send($.Document.flagForReview, {
          documentId: document.id,
          reason: 'unknown-type',
          classification,
        })
    }
  } catch (error) {
    await send($.Document.failed, {
      documentId: document.id,
      error: error.message,
    })
  }
})

Contract Management Automation

// Contract lifecycle management
const contractManagementService = await $.Service.create({
  name: 'Contract Lifecycle Automation',
  type: $.ServiceType.Automation,
  subtype: 'business-process',

  process: {
    stages: [
      { id: 'draft', name: 'Create Draft' },
      { id: 'review', name: 'Legal Review' },
      { id: 'negotiate', name: 'Negotiation' },
      { id: 'approve', name: 'Approval Chain' },
      { id: 'sign', name: 'Electronic Signature' },
      { id: 'execute', name: 'Execute Contract' },
      { id: 'monitor', name: 'Monitor Obligations' },
    ],
  },

  pricing: {
    model: 'per-contract',
    baseRate: 10.0,
    additionalCosts: {
      legalReview: 5.0,
      electronicSignature: 2.0,
      monitoring: 1.0, // per month
    },
  },
})

// Contract processing
on($.Contract.created, async (contract) => {
  try {
    // Extract contract terms
    const terms = await ai.extract({
      model: 'gpt-5',
      document: contract.file,
      schema: {
        parties: [{ name: 'string', role: 'string' }],
        effectiveDate: 'date',
        expirationDate: 'date',
        autoRenewal: 'boolean',
        renewalTerms: 'string',
        value: 'number',
        paymentTerms: 'string',
        obligations: [{ party: 'string', obligation: 'string', deadline: 'date' }],
        terminationClauses: ['string'],
        governingLaw: 'string',
      },
    })

    // Store structured terms
    await db.update(contract, {
      terms,
      effectiveDate: terms.effectiveDate,
      expirationDate: terms.expirationDate,
      value: terms.value,
    })

    // Route for legal review if needed
    if (contract.value > 100000) {
      await send($.Review.request, {
        type: 'legal',
        contractId: contract.id,
        reviewerId: await getLegalReviewer(),
        priority: contract.urgent ? 'high' : 'normal',
      })
    }

    // Setup obligation monitoring
    for (const obligation of terms.obligations) {
      await scheduleObligationReminder(contract.id, obligation)
    }

    // Setup renewal reminder
    if (terms.expirationDate) {
      const reminderDate = new Date(terms.expirationDate)
      reminderDate.setDate(reminderDate.getDate() - 90) // 90 days before

      await send($.Reminder.schedule, {
        date: reminderDate,
        type: 'contract-renewal',
        contractId: contract.id,
        message: `Contract expiring in 90 days: ${contract.name}`,
      })
    }
  } catch (error) {
    await send($.Contract.failed, {
      contractId: contract.id,
      error: error.message,
    })
  }
})

Scheduling and Calendar Automation

// Meeting scheduling automation
const schedulingService = await $.Service.create({
  name: 'Smart Meeting Scheduler',
  type: $.ServiceType.Automation,
  subtype: 'business-process',

  pricing: {
    model: 'per-scheduling',
    rate: 0.25,
  },
})

// Intelligent scheduling
on($.Meeting.requested, async (request) => {
  try {
    // Get attendee calendars
    const attendees = await Promise.all(
      request.attendees.map(async (userId: string) => {
        const calendar = await getCalendar(userId)
        const availability = await getAvailability(calendar, request.timeframe)

        return {
          userId,
          availability,
          timezone: calendar.timezone,
          preferences: calendar.preferences,
        }
      })
    )

    // Find optimal time slot
    const optimalSlot = await ai.optimize({
      model: 'gpt-5',
      objective: 'maximize-attendee-satisfaction',
      constraints: {
        duration: request.duration,
        timeframe: request.timeframe,
        required: request.required,
        preferences: attendees.map((a) => a.preferences),
      },
      data: {
        availability: attendees.map((a) => a.availability),
      },
    })

    // Create meeting
    const meeting = await db.create($.Meeting, {
      title: request.title,
      description: request.description,
      startTime: optimalSlot.startTime,
      endTime: optimalSlot.endTime,
      attendees: request.attendees,
      location: await bookMeetingRoom(optimalSlot),
      organizer: request.organizer,
    })

    // Send invitations
    for (const attendee of attendees) {
      await send($.Calendar.invite, {
        userId: attendee.userId,
        meetingId: meeting.id,
        startTime: optimalSlot.startTime,
        endTime: optimalSlot.endTime,
        timezone: attendee.timezone,
      })
    }

    await send($.Meeting.scheduled, {
      meetingId: meeting.id,
      requestId: request.id,
      slot: optimalSlot,
    })
  } catch (error) {
    await send($.Meeting.failed, {
      requestId: request.id,
      error: error.message,
    })
  }
})

Pricing Models for Business Processes

Per-Transaction Pricing

const service = await $.Service.create({
  name: 'Invoice Processing',
  pricing: {
    model: 'per-transaction',
    baseRate: 2.0,
    volume: [
      { min: 0, max: 100, rate: 2.0 },
      { min: 101, max: 1000, rate: 1.5 },
      { min: 1001, max: Infinity, rate: 1.0 },
    ],
  },
})

Per-Document Pricing

const service = await $.Service.create({
  name: 'Document Processing',
  pricing: {
    model: 'per-document',
    rates: {
      simple: 0.5,
      moderate: 1.0,
      complex: 2.5,
    },
    classification: 'automatic',
  },
})

Subscription with Usage

const service = await $.Service.create({
  name: 'Expense Management',
  pricing: {
    model: 'subscription',
    plans: [
      {
        id: 'starter',
        price: 99.0,
        interval: 'month',
        includes: 100, // reports per month
        overage: 1.0,
      },
      {
        id: 'professional',
        price: 299.0,
        interval: 'month',
        includes: 500,
        overage: 0.75,
      },
    ],
  },
})

Best Practices

1. Audit Trail

Maintain complete audit logs:

async function logProcessStep(processId: string, step: string, data: any) {
  await db.create($.ProcessAuditLog, {
    processId,
    step,
    timestamp: new Date(),
    user: data.userId || 'system',
    action: data.action,
    before: data.before,
    after: data.after,
    metadata: data.metadata,
  })
}

2. Compliance Checks

Ensure regulatory compliance:

async function checkCompliance(process: any, data: any) {
  const checks = [checkDataPrivacy(data), checkFinancialRegulations(data), checkIndustryStandards(data)]

  const results = await Promise.all(checks)

  return {
    compliant: results.every((r) => r.compliant),
    violations: results.flatMap((r) => r.violations),
  }
}

3. SLA Monitoring

Track and enforce service level agreements:

async function monitorSLA(process: any) {
  const elapsed = Date.now() - process.startTime
  const slaThreshold = process.sla.responseTime

  if (elapsed > slaThreshold * 0.8) {
    await send($.Alert.create, {
      severity: 'warning',
      message: `Process ${process.id} approaching SLA threshold`,
    })
  }

  if (elapsed > slaThreshold) {
    await send($.Alert.create, {
      severity: 'critical',
      message: `Process ${process.id} exceeded SLA`,
    })
  }
}

Real-World Examples

Payroll Processing

const payrollService = await $.Service.create({
  name: 'Automated Payroll',
  process: {
    stages: ['collect-timesheets', 'calculate-pay', 'apply-deductions', 'generate-paystubs', 'process-payments', 'file-taxes'],
  },
  pricing: { model: 'per-employee', rate: 5.0 },
})

Procurement Workflow

const procurementService = await $.Service.create({
  name: 'Purchase Requisition',
  process: {
    stages: ['submit-request', 'budget-check', 'approval-chain', 'vendor-selection', 'create-po', 'track-delivery'],
  },
  pricing: { model: 'per-order', rate: 3.0 },
})

Customer Onboarding

const onboardingService = await $.Service.create({
  name: 'Customer Onboarding',
  process: {
    stages: ['welcome-email', 'account-setup', 'identity-verification', 'training-materials', 'first-success'],
  },
  pricing: { model: 'per-customer', rate: 10.0 },
})

Next Steps