.do
Use Cases

Healthcare Platform

Build a complete healthcare management system with Business-as-Code

Build a complete, autonomous healthcare management system using Business-as-Code principles.

Overview

This use case demonstrates building a healthcare platform that:

  • Manages patient registration and records securely
  • Schedules appointments with AI optimization
  • Handles medical records with HIPAA compliance
  • Processes prescriptions electronically
  • Manages insurance claims and billing
  • Provides telemedicine capabilities
  • Coordinates care across providers
  • Generates clinical insights and analytics

Architecture

graph TB subgraph Frontend["User Experience"] PatientPortal[Patient Portal] ProviderApp[Provider Application] AdminDash[Admin Dashboard] Mobile[Mobile App] end subgraph Core["Core Systems"] Patients[Patient Management] Providers[Provider Management] Appointments[Scheduling] Records[Medical Records] end subgraph Clinical["Clinical Operations"] Prescriptions[e-Prescribing] LabResults[Lab Results] Imaging[Medical Imaging] Notes[Clinical Notes] end subgraph Financial["Financial"] Claims[Insurance Claims] Billing[Patient Billing] Payments[Payment Processing] Eligibility[Insurance Verification] end subgraph AI["AI Services"] Diagnosis[Clinical Decision Support] Scheduling[Smart Scheduling] Triage[AI Triage] Insights[Population Health] end subgraph Compliance["Compliance & Security"] HIPAA[HIPAA Controls] Audit[Audit Logging] Consent[Consent Management] Encryption[Data Encryption] end subgraph Integration["External Systems"] EHR[EHR Systems] Labs[Lab Systems] Pharmacies[Pharmacy Networks] Payers[Insurance Payers] end PatientPortal --> Patients ProviderApp --> Providers Patients --> Records Providers --> Appointments Appointments --> Scheduling Records --> Notes Records --> Prescriptions Prescriptions --> Pharmacies LabResults --> Labs Claims --> Payers Eligibility --> Payers Scheduling -.->|AI| Scheduling Triage -.->|AI| Diagnosis Records -.->|AI| Insights Records --> HIPAA Patients --> HIPAA All --> Audit All --> Encryption

Core Entities

Patients

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

// Create patient record
const patient = await $.Patient.create({
  $type: 'Patient',

  // Demographics
  givenName: 'John',
  familyName: 'Smith',
  birthDate: '1985-06-15',
  gender: 'male',

  // Contact information
  email: '[email protected]',
  telephone: '+1-555-0123',
  address: {
    $type: 'PostalAddress',
    streetAddress: '123 Main St',
    addressLocality: 'Boston',
    addressRegion: 'MA',
    postalCode: '02101',
    addressCountry: 'US',
  },

  // Emergency contact
  emergencyContact: {
    $type: 'Person',
    givenName: 'Jane',
    familyName: 'Smith',
    telephone: '+1-555-0124',
    relationship: 'spouse',
  },

  // Insurance
  insuranceProvider: 'Blue Cross Blue Shield',
  insurancePolicyNumber: 'BC123456789',
  insuranceGroupNumber: 'GRP001',

  // Medical Record Number
  identifier: generateMRN(),

  // Status
  status: 'active',
  registeredAt: new Date(),

  // HIPAA consent
  consentGiven: true,
  consentDate: new Date(),
})

Healthcare Providers

// Create healthcare provider
const provider = await $.Physician.create({
  $type: 'Physician',

  // Personal information
  givenName: 'Sarah',
  familyName: 'Johnson',
  honorificPrefix: 'Dr.',

  // Medical credentials
  medicalSpecialty: ['Internal Medicine', 'Primary Care'],
  npiNumber: '1234567890',
  deaNumber: 'DJ1234567',
  stateLicense: {
    state: 'MA',
    number: 'MD123456',
    expirationDate: '2026-12-31',
  },

  // Contact
  email: '[email protected]',
  telephone: '+1-555-0200',

  // Organization
  worksFor: hospital,
  department: 'Internal Medicine',

  // Availability
  availableTime: [
    {
      daysOfWeek: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'],
      availableStartTime: '09:00',
      availableEndTime: '17:00',
    },
  ],

  // Settings
  acceptingNewPatients: true,
  appointmentDuration: 30, // minutes
})

Medical Records

// Create medical record
const medicalRecord = await $.MedicalRecord.create({
  $type: 'MedicalRecord',

  // Patient
  patient: patient.$id,

  // Vital Signs
  vitalSigns: {
    bloodPressure: {
      systolic: 120,
      diastolic: 80,
      unit: 'mmHg',
    },
    heartRate: {
      value: 72,
      unit: 'bpm',
    },
    temperature: {
      value: 98.6,
      unit: 'F',
    },
    weight: {
      value: 180,
      unit: 'lbs',
    },
    height: {
      value: 70,
      unit: 'inches',
    },
  },

  // Medical History
  medicalHistory: {
    conditions: ['Hypertension', 'Type 2 Diabetes'],
    surgeries: [
      {
        procedure: 'Appendectomy',
        date: '2010-05-15',
        hospital: 'General Hospital',
      },
    ],
    allergies: [
      {
        allergen: 'Penicillin',
        reaction: 'Hives',
        severity: 'moderate',
      },
    ],
    familyHistory: [
      {
        condition: 'Heart Disease',
        relation: 'father',
      },
    ],
  },

  // Current Medications
  medications: [
    {
      name: 'Lisinopril',
      dosage: '10mg',
      frequency: 'once daily',
      startDate: '2023-01-15',
    },
    {
      name: 'Metformin',
      dosage: '500mg',
      frequency: 'twice daily',
      startDate: '2023-01-15',
    },
  ],

  // Social History
  socialHistory: {
    smokingStatus: 'never',
    alcoholUse: 'occasional',
    exerciseFrequency: '3-4 times per week',
    occupation: 'Software Engineer',
  },

  // Created
  recordedDate: new Date(),
  recordedBy: provider,
})

await db.relate(patient, $.has, medicalRecord)

Business Functions

1. Patient Registration

Complete patient registration with insurance verification.

// Register new patient
async function registerPatient(params: {
  demographics: PatientDemographics
  insurance?: InsuranceInformation
  emergencyContact: EmergencyContact
  consent: ConsentForm
}) {
  const { demographics, insurance, emergencyContact, consent } = params

  // Validate consent
  if (!consent.hipaaConsent || !consent.signature) {
    throw new Error('HIPAA consent required')
  }

  // Check for duplicate patients
  const existing = await db.list($.Patient, {
    where: {
      givenName: demographics.givenName,
      familyName: demographics.familyName,
      birthDate: demographics.birthDate,
    },
  })

  if (existing.length > 0) {
    // Potential duplicate - flag for review
    await send($.Patient.duplicateDetected, {
      newPatient: demographics,
      existing: existing[0],
    })
  }

  // Create patient record
  const patient = await $.Patient.create({
    $type: 'Patient',
    ...demographics,
    emergencyContact,
    identifier: generateMRN(),
    status: 'active',
    registeredAt: new Date(),

    // Consent
    consentGiven: true,
    consentDate: new Date(),
    consentForm: consent,
  })

  // Verify insurance if provided
  if (insurance) {
    const verification = await verifyInsurance({
      patient,
      insurance,
    })

    await db.update($.Patient, patient.$id, {
      insuranceProvider: insurance.provider,
      insurancePolicyNumber: insurance.policyNumber,
      insuranceGroupNumber: insurance.groupNumber,
      insuranceVerified: verification.verified,
      insuranceVerifiedAt: verification.verified ? new Date() : null,
      insuranceCoverage: verification.coverage,
    })

    if (!verification.verified) {
      await send($.Alert.send, {
        to: $.Role.RegistrationStaff,
        priority: 'high',
        message: `Insurance verification failed for patient ${patient.identifier}`,
        data: { patient, verification },
      })
    }
  }

  // Create empty medical record
  const medicalRecord = await $.MedicalRecord.create({
    $type: 'MedicalRecord',
    patient: patient.$id,
    recordedDate: new Date(),
    medicalHistory: {},
    medications: [],
    allergies: [],
  })

  await db.relate(patient, $.has, medicalRecord)

  // Send welcome materials
  await send($.Email.send, {
    to: patient.email,
    template: 'patient-welcome',
    data: {
      patient,
      mrn: patient.identifier,
      portalUrl: `${process.env.PORTAL_URL}/register/${patient.$id}`,
    },
  })

  // Create patient portal account
  await send($.Portal.createAccount, {
    patient,
    email: patient.email,
  })

  await send($.Patient.registered, patient)

  // HIPAA audit log
  await db.create($.AuditLog, {
    action: 'patient.registered',
    actor: 'system',
    resource: patient.$id,
    timestamp: new Date(),
    ipAddress: params.metadata?.ipAddress,
  })

  return patient
}

// Insurance verification
async function verifyInsurance(params: { patient: Patient; insurance: InsuranceInformation }) {
  const { patient, insurance } = params

  // Call insurance verification service
  const verification = await send($.Insurance.verify, {
    provider: insurance.provider,
    policyNumber: insurance.policyNumber,
    groupNumber: insurance.groupNumber,
    subscriberName: `${patient.givenName} ${patient.familyName}`,
    subscriberDOB: patient.birthDate,
  })

  // Save verification result
  await db.create($.InsuranceVerification, {
    patient: patient.$id,
    provider: insurance.provider,
    policyNumber: insurance.policyNumber,
    verifiedAt: new Date(),
    verified: verification.status === 'active',
    coverage: verification.coverage,
    copay: verification.copay,
    deductible: verification.deductible,
    outOfPocketMax: verification.outOfPocketMax,
    effectiveDate: verification.effectiveDate,
    terminationDate: verification.terminationDate,
  })

  return {
    verified: verification.status === 'active',
    coverage: verification.coverage,
    copay: verification.copay,
    deductible: verification.deductible,
  }
}

2. Appointment Scheduling

AI-optimized appointment scheduling with automated reminders.

// Schedule appointment
async function scheduleAppointment(params: {
  patient: Patient
  provider: Physician
  appointmentType: string
  reason: string
  preferredDate?: Date
  preferredTime?: string
  isUrgent?: boolean
}) {
  const { patient, provider, appointmentType, reason, preferredDate, preferredTime, isUrgent } = params

  // Get provider availability
  const availability = await getProviderAvailability(provider, preferredDate)

  // AI scheduling optimization
  const scheduling = await ai.decide('optimal-appointment-time', {
    provider,
    patient,
    availability,
    appointmentType,
    isUrgent,
    preferredDate,
    preferredTime,
    patientHistory: await db.related(patient, $.has, $.Appointment),
  })

  if (!scheduling.availableSlots || scheduling.availableSlots.length === 0) {
    throw new Error('No available appointment slots')
  }

  // Create appointment
  const appointment = await $.MedicalAppointment.create({
    $type: 'MedicalAppointment',

    // Identifier
    identifier: `APT-${Date.now()}`,

    // Parties
    patient: patient.$id,
    physician: provider.$id,

    // Scheduling
    startDate: scheduling.recommendedSlot.start,
    endDate: scheduling.recommendedSlot.end,
    duration: provider.appointmentDuration,

    // Details
    appointmentType,
    description: reason,

    // Location
    location: {
      $type: 'MedicalClinic',
      name: provider.worksFor.name,
      address: provider.worksFor.address,
    },

    // Status
    appointmentStatus: 'scheduled',

    // Created
    createdAt: new Date(),
  })

  await db.relate(patient, $.has, appointment)
  await db.relate(provider, $.performs, appointment)

  // Send confirmation
  await send($.Email.send, {
    to: patient.email,
    template: 'appointment-confirmation',
    data: {
      appointment,
      patient,
      provider,
      date: format(appointment.startDate, 'MMMM d, yyyy'),
      time: format(appointment.startDate, 'h:mm a'),
    },
  })

  // Schedule reminders
  await scheduleAppointmentReminders(appointment)

  await send($.Appointment.scheduled, appointment)

  return appointment
}

// AI-powered appointment scheduling
async function getOptimalAppointmentTime(params: { provider: Physician; patient: Patient; appointmentType: string; isUrgent: boolean }) {
  const { provider, patient, appointmentType, isUrgent } = params

  // Get historical data
  const patientHistory = await db.related(patient, $.has, $.Appointment, {
    sort: { startDate: -1 },
    limit: 10,
  })

  const providerSchedule = await db.list($.Appointment, {
    where: {
      physician: provider.$id,
      startDate: { $gte: new Date() },
    },
    sort: { startDate: 1 },
  })

  // AI optimization
  const optimization = await ai.decide('schedule-optimization', {
    provider,
    patient,
    appointmentType,
    isUrgent,

    // Patterns
    patientPreferences: analyzePatientPreferences(patientHistory),
    providerLoad: analyzeProviderLoad(providerSchedule),

    // Constraints
    availability: provider.availableTime,
    buffer: 15, // minutes between appointments

    // Goals
    minimizeWaitTime: true,
    respectPreferences: true,
    balanceLoad: true,
  })

  return optimization
}

// Appointment reminders
async function scheduleAppointmentReminders(appointment: Appointment) {
  const patient = await db.get($.Patient, appointment.patient)

  // 24 hours before
  await send($.Email.schedule, {
    to: patient.email,
    template: 'appointment-reminder-24h',
    sendAt: subHours(appointment.startDate, 24),
    data: { appointment, patient },
  })

  await send($.SMS.schedule, {
    to: patient.telephone,
    message: `Reminder: You have an appointment tomorrow at ${format(appointment.startDate, 'h:mm a')}. Reply C to confirm.`,
    sendAt: subHours(appointment.startDate, 24),
  })

  // 2 hours before
  await send($.SMS.schedule, {
    to: patient.telephone,
    message: `Your appointment is in 2 hours at ${format(appointment.startDate, 'h:mm a')}. ${appointment.location.address.streetAddress}`,
    sendAt: subHours(appointment.startDate, 2),
  })
}

// No-show prediction and prevention
on($.Appointment.scheduled, async (appointment) => {
  const patient = await db.get($.Patient, appointment.patient)

  // Get patient history
  const history = await db.list($.Appointment, {
    where: {
      patient: patient.$id,
      startDate: { $lt: new Date() },
    },
  })

  // Calculate no-show risk
  const noShowRate = history.filter((a) => a.appointmentStatus === 'no-show').length / history.length

  // AI prediction
  const prediction = await ai.predict('no-show-risk', {
    patient,
    appointment,
    history,
    noShowRate,
  })

  if (prediction.risk === 'high' && prediction.confidence > 0.7) {
    // Additional outreach
    await send($.Task.create, {
      type: 'call-patient',
      priority: 'high',
      assignTo: $.Role.PatientCoordinator,
      dueDate: subDays(appointment.startDate, 1),
      description: `Call patient to confirm appointment (high no-show risk)`,
      data: { appointment, patient, prediction },
    })
  }
})

3. Clinical Workflows

Complete clinical workflows with AI assistance.

// Clinical encounter
async function recordEncounter(params: {
  appointment: Appointment
  provider: Physician
  chiefComplaint: string
  vitalSigns: VitalSigns
  examination: string
  assessment: string
  plan: string
}) {
  const { appointment, provider, chiefComplaint, vitalSigns, examination, assessment, plan } = params

  const patient = await db.get($.Patient, appointment.patient)
  const medicalRecord = await db.related(patient, $.has, $.MedicalRecord).then((records) => records[0])

  // Create clinical note
  const clinicalNote = await $.MedicalNote.create({
    $type: 'MedicalNote',

    // Encounter details
    patient: patient.$id,
    provider: provider.$id,
    appointment: appointment.$id,
    date: new Date(),

    // SOAP note
    subjective: chiefComplaint,
    objective: {
      vitalSigns,
      examination,
    },
    assessment,
    plan,

    // Status
    status: 'draft',
  })

  // Update medical record with vital signs
  await db.update($.MedicalRecord, medicalRecord.$id, {
    vitalSigns,
    lastUpdated: new Date(),
    lastUpdatedBy: provider.$id,
  })

  // AI clinical decision support
  const cds = await ai.analyze('clinical-decision-support', {
    patient,
    medicalRecord,
    chiefComplaint,
    vitalSigns,
    examination,
    assessment,
  })

  // Alert for critical findings
  if (cds.criticalFindings && cds.criticalFindings.length > 0) {
    await send($.Alert.send, {
      to: provider,
      priority: 'urgent',
      message: 'Critical findings detected',
      data: { patient, findings: cds.criticalFindings },
    })
  }

  // Suggest additional tests
  if (cds.suggestedTests && cds.suggestedTests.length > 0) {
    clinicalNote.suggestedTests = cds.suggestedTests
  }

  // Drug interaction check
  if (plan.includes('prescribe')) {
    const interactions = await checkDrugInteractions({
      patient,
      currentMedications: medicalRecord.medications,
      proposedMedications: extractMedicationsFromPlan(plan),
    })

    if (interactions.length > 0) {
      await send($.Alert.send, {
        to: provider,
        priority: 'high',
        message: 'Drug interactions detected',
        data: { patient, interactions },
      })
    }
  }

  await send($.ClinicalNote.created, clinicalNote)

  return clinicalNote
}

// AI clinical decision support
async function getClinicalDecisionSupport(params: { patient: Patient; symptoms: string[]; vitalSigns: VitalSigns; medicalHistory: MedicalHistory }) {
  const { patient, symptoms, vitalSigns, medicalHistory } = params

  // AI analysis
  const analysis = await ai.analyze('clinical-decision-support', {
    patient,
    symptoms,
    vitalSigns,
    medicalHistory,

    // Context
    age: calculateAge(patient.birthDate),
    gender: patient.gender,
    conditions: medicalHistory.conditions,
    medications: medicalHistory.medications,
    allergies: medicalHistory.allergies,
  })

  return {
    // Differential diagnosis
    differentialDiagnosis: analysis.possibleDiagnoses.map((d) => ({
      condition: d.name,
      probability: d.probability,
      reasoning: d.reasoning,
    })),

    // Recommended tests
    suggestedTests: analysis.recommendedTests,

    // Red flags
    criticalFindings: analysis.redFlags,

    // Treatment suggestions
    treatmentOptions: analysis.treatments,

    // References
    guidelines: analysis.clinicalGuidelines,

    confidence: analysis.confidence,
  }
}

// Drug interaction checking
async function checkDrugInteractions(params: { patient: Patient; currentMedications: Medication[]; proposedMedications: Medication[] }) {
  const { patient, currentMedications, proposedMedications } = params

  const allMedications = [...currentMedications, ...proposedMedications]

  // Check for interactions
  const interactions = await send($.DrugDatabase.checkInteractions, {
    medications: allMedications.map((m) => m.name),
  })

  // Check for allergies
  const allergyConflicts = []
  for (const med of proposedMedications) {
    const medicalRecord = await db.related(patient, $.has, $.MedicalRecord).then((records) => records[0])

    for (const allergy of medicalRecord.allergies) {
      const conflict = await send($.DrugDatabase.checkAllergy, {
        medication: med.name,
        allergen: allergy.allergen,
      })

      if (conflict) {
        allergyConflicts.push({
          medication: med.name,
          allergen: allergy.allergen,
          severity: allergy.severity,
        })
      }
    }
  }

  return [
    ...interactions.map((i) => ({
      type: 'drug-interaction',
      severity: i.severity,
      drugs: i.drugs,
      description: i.description,
      recommendation: i.recommendation,
    })),
    ...allergyConflicts.map((a) => ({
      type: 'allergy',
      severity: a.severity,
      medication: a.medication,
      allergen: a.allergen,
      recommendation: 'Do not prescribe - known allergy',
    })),
  ]
}

4. e-Prescribing

Electronic prescription management with automatic pharmacy routing.

// Create prescription
async function createPrescription(params: {
  patient: Patient
  provider: Physician
  medication: {
    name: string
    dosage: string
    quantity: number
    refills: number
    instructions: string
  }
  pharmacy?: Pharmacy
}) {
  const { patient, provider, medication, pharmacy } = params

  // Verify provider has DEA license if controlled substance
  if (isControlledSubstance(medication.name)) {
    if (!provider.deaNumber) {
      throw new Error('Provider does not have DEA license for controlled substances')
    }
  }

  // Check drug interactions
  const medicalRecord = await db.related(patient, $.has, $.MedicalRecord).then((records) => records[0])

  const interactions = await checkDrugInteractions({
    patient,
    currentMedications: medicalRecord.medications,
    proposedMedications: [medication],
  })

  if (interactions.some((i) => i.severity === 'severe')) {
    throw new Error('Severe drug interaction detected - prescription blocked')
  }

  // Get preferred pharmacy
  const targetPharmacy = pharmacy || (await db.related(patient, $.prefers, $.Pharmacy).then((pharmacies) => pharmacies[0]))

  if (!targetPharmacy) {
    throw new Error('No pharmacy specified')
  }

  // Create prescription
  const prescription = await $.Prescription.create({
    $type: 'Prescription',

    // Identifier
    identifier: `RX-${Date.now()}`,

    // Parties
    patient: patient.$id,
    prescribedBy: provider.$id,
    pharmacy: targetPharmacy.$id,

    // Medication
    drug: {
      $type: 'Drug',
      name: medication.name,
      dosageForm: medication.dosage,
      activeIngredient: medication.name,
    },

    // Instructions
    dosageInstruction: medication.instructions,
    quantity: medication.quantity,
    numberOfRefills: medication.refills,

    // Dates
    dateIssued: new Date(),
    validFrom: new Date(),
    validUntil: addYears(new Date(), 1),

    // Status
    status: 'pending',
  })

  // Send to pharmacy via NCPDP SCRIPT
  await send($.Pharmacy.submitPrescription, {
    prescription,
    pharmacy: targetPharmacy,
    format: 'ncpdp-script',
  })

  // Update medical record
  medicalRecord.medications.push({
    name: medication.name,
    dosage: medication.dosage,
    frequency: medication.instructions,
    startDate: new Date(),
    prescribedBy: provider.$id,
    prescriptionId: prescription.$id,
  })

  await db.update($.MedicalRecord, medicalRecord.$id, medicalRecord)

  // Notify patient
  await send($.Email.send, {
    to: patient.email,
    template: 'prescription-sent',
    data: {
      prescription,
      medication,
      pharmacy: targetPharmacy,
    },
  })

  await send($.Prescription.created, prescription)

  // HIPAA audit log
  await db.create($.AuditLog, {
    action: 'prescription.created',
    actor: provider.$id,
    resource: prescription.$id,
    patient: patient.$id,
    timestamp: new Date(),
  })

  return prescription
}

// Prescription status updates
on($.Pharmacy.statusUpdate, async ({ prescription, status, message }) => {
  await db.update($.Prescription, prescription.$id, {
    status,
    statusMessage: message,
    lastUpdated: new Date(),
  })

  const patient = await db.get($.Patient, prescription.patient)

  // Notify patient of status changes
  if (status === 'ready-for-pickup') {
    await send($.SMS.send, {
      to: patient.telephone,
      message: `Your prescription is ready for pickup at ${prescription.pharmacy.name}.`,
    })
  } else if (status === 'delayed') {
    await send($.Email.send, {
      to: patient.email,
      template: 'prescription-delayed',
      data: { prescription, reason: message },
    })
  }
})

5. Insurance Claims & Billing

Automated claims processing and patient billing.

// Submit insurance claim
async function submitClaim(params: { patient: Patient; provider: Physician; encounter: Encounter; services: BillingCode[]; diagnosis: DiagnosisCode[] }) {
  const { patient, provider, encounter, services, diagnosis } = params

  // Verify insurance
  const insuranceVerification = await db
    .list($.InsuranceVerification, {
      where: {
        patient: patient.$id,
        verified: true,
      },
      sort: { verifiedAt: -1 },
      limit: 1,
    })
    .then((verifications) => verifications[0])

  if (!insuranceVerification) {
    throw new Error('No valid insurance verification')
  }

  // Calculate claim amount
  const claimAmount = services.reduce((total, service) => {
    return total + service.amount
  }, 0)

  // Create claim
  const claim = await $.InsuranceClaim.create({
    $type: 'Invoice',
    identifier: `CLM-${Date.now()}`,

    // Parties
    patient: patient.$id,
    provider: provider.$id,
    broker: insuranceVerification.provider,

    // Services
    referencesOrder: services.map((service) => ({
      $type: 'OrderItem',
      orderItem: service.code,
      description: service.description,
      price: service.amount,
      orderQuantity: 1,
    })),

    // Diagnosis codes
    diagnosis: diagnosis.map((d) => d.code),

    // Amount
    totalPaymentDue: {
      $type: 'PriceSpecification',
      price: claimAmount,
      priceCurrency: 'USD',
    },

    // Dates
    dateIssued: new Date(),
    serviceDate: encounter.date,

    // Status
    paymentStatus: 'submitted',
  })

  // Submit via EDI
  await send($.EDI.submit837, {
    claim,
    format: '837-professional',
    clearinghouse: 'change-healthcare',
  })

  await send($.Claim.submitted, claim)

  return claim
}

// Handle claim responses
on($.EDI.received835, async (era) => {
  // ERA (Electronic Remittance Advice)
  const claim = await db.get($.InsuranceClaim, era.claimId)

  if (era.status === 'paid') {
    // Update claim
    await db.update($.InsuranceClaim, claim.$id, {
      paymentStatus: 'paid',
      paidAmount: era.paidAmount,
      adjustments: era.adjustments,
      paidAt: new Date(),
    })

    // Calculate patient responsibility
    const patientBalance = claim.totalPaymentDue.price - era.paidAmount

    if (patientBalance > 0) {
      // Create patient invoice
      await send($.PatientBilling.createInvoice, {
        claim,
        amount: patientBalance,
        reason: 'insurance-balance',
      })
    }

    await send($.Claim.paid, { claim, era })
  } else if (era.status === 'denied') {
    // Update claim
    await db.update($.InsuranceClaim, claim.$id, {
      paymentStatus: 'denied',
      denialReason: era.denialReason,
      denialCode: era.denialCode,
    })

    // Check if appealable
    const appealable = await ai.decide('claim-appeal', {
      claim,
      denialReason: era.denialReason,
      denialCode: era.denialCode,
    })

    if (appealable.shouldAppeal) {
      await send($.Claim.appeal, {
        claim,
        reason: appealable.appealReason,
      })
    } else {
      // Bill patient
      await send($.PatientBilling.createInvoice, {
        claim,
        amount: claim.totalPaymentDue.price,
        reason: 'insurance-denied',
      })
    }

    await send($.Claim.denied, { claim, era })
  }
})

// Patient billing
async function createPatientInvoice(params: { patient: Patient; claim: InsuranceClaim; amount: number; reason: string }) {
  const { patient, claim, amount, reason } = params

  // Create invoice
  const invoice = await $.Invoice.create({
    $type: 'Invoice',
    identifier: `INV-${Date.now()}`,

    // Parties
    provider: claim.provider,
    customer: patient.$id,

    // Amount
    totalPaymentDue: {
      $type: 'PriceSpecification',
      price: amount,
      priceCurrency: 'USD',
    },

    // Related claim
    referencesOrder: claim,

    // Dates
    dateIssued: new Date(),
    paymentDueDate: addDays(new Date(), 30),

    // Status
    paymentStatus: 'due',
  })

  // Send invoice
  await send($.Email.send, {
    to: patient.email,
    template: 'patient-invoice',
    data: {
      invoice,
      patient,
      amount,
      reason,
      paymentUrl: `${process.env.PORTAL_URL}/billing/pay/${invoice.$id}`,
    },
  })

  await send($.Invoice.created, invoice)

  return invoice
}

6. Telemedicine

Complete telemedicine platform with video consultations.

// Create telemedicine session
async function createTelehealthAppointment(params: { patient: Patient; provider: Physician; appointmentType: string; reason: string; scheduledTime: Date }) {
  const { patient, provider, appointmentType, reason, scheduledTime } = params

  // Create appointment
  const appointment = await $.MedicalAppointment.create({
    $type: 'MedicalAppointment',
    identifier: `TEL-${Date.now()}`,

    patient: patient.$id,
    physician: provider.$id,

    startDate: scheduledTime,
    endDate: addMinutes(scheduledTime, provider.appointmentDuration),

    appointmentType: 'telemedicine',
    description: reason,

    // Virtual location
    location: {
      $type: 'VirtualLocation',
      url: null, // Generated before appointment
    },

    appointmentStatus: 'scheduled',
    createdAt: new Date(),
  })

  // Generate video session 15 minutes before
  await send($.Task.schedule, {
    executeAt: subMinutes(scheduledTime, 15),
    action: async () => {
      const videoSession = await send($.Video.createSession, {
        appointment: appointment.$id,
        participants: [patient.$id, provider.$id],
        duration: provider.appointmentDuration,
      })

      await db.update($.MedicalAppointment, appointment.$id, {
        'location.url': videoSession.joinUrl,
      })

      // Send join links
      await send($.Email.send, {
        to: patient.email,
        template: 'telehealth-join',
        data: {
          appointment,
          joinUrl: videoSession.patientJoinUrl,
        },
      })

      await send($.Email.send, {
        to: provider.email,
        template: 'telehealth-join',
        data: {
          appointment,
          joinUrl: videoSession.providerJoinUrl,
        },
      })
    },
  })

  return appointment
}

// Virtual waiting room
on($.Video.participantJoined, async ({ session, participant }) => {
  const appointment = await db.get($.Appointment, session.appointment)

  // Patient arrived
  if (participant === appointment.patient) {
    // Notify provider
    await send($.Notification.send, {
      to: appointment.physician,
      message: `Patient ${appointment.patient.name} is in the virtual waiting room`,
      action: { join: session.providerJoinUrl },
    })

    // Update appointment status
    await db.update($.Appointment, appointment.$id, {
      appointmentStatus: 'in-waiting-room',
    })
  }

  // Provider arrived - start appointment
  if (participant === appointment.physician) {
    await db.update($.Appointment, appointment.$id, {
      appointmentStatus: 'in-progress',
      startedAt: new Date(),
    })
  }
})

// Session recording and transcription
on($.Video.sessionEnded, async ({ session, recording }) => {
  const appointment = await db.get($.Appointment, session.appointment)

  // Update appointment
  await db.update($.Appointment, appointment.$id, {
    appointmentStatus: 'completed',
    completedAt: new Date(),
    recordingUrl: recording.url,
  })

  // AI transcription
  const transcription = await ai.transcribe('medical-visit', {
    audio: recording.url,
    speakers: ['patient', 'provider'],
    medicalTerminology: true,
  })

  // AI clinical note generation
  const clinicalNote = await ai.generate('clinical-note-from-transcript', {
    transcript: transcription.text,
    patient: appointment.patient,
    provider: appointment.physician,
    format: 'soap',
  })

  // Create draft clinical note
  await $.MedicalNote.create({
    $type: 'MedicalNote',
    patient: appointment.patient,
    provider: appointment.physician,
    appointment: appointment.$id,
    date: new Date(),

    transcript: transcription.text,
    subjective: clinicalNote.subjective,
    objective: clinicalNote.objective,
    assessment: clinicalNote.assessment,
    plan: clinicalNote.plan,

    status: 'draft',
    generatedByAI: true,
  })

  // Notify provider to review
  await send($.Notification.send, {
    to: appointment.physician,
    message: 'AI-generated clinical note ready for review',
    action: { review: appointment.$id },
  })
})

7. Population Health & Analytics

Population health management with predictive analytics.

// Population health analytics
async function analyzePopulationHealth(params: { organization: Organization; population?: 'all' | 'high-risk' | 'chronic-disease'; timeRange?: string }) {
  const { organization, population = 'all', timeRange = '1y' } = params

  const startDate = subtractTimeRange(new Date(), timeRange)

  // Get patient population
  let patients = await db.list($.Patient, {
    where: {
      organization: organization.$id,
      status: 'active',
    },
  })

  // Filter by population segment
  if (population === 'high-risk') {
    patients = patients.filter((p) => p.riskScore > 70)
  } else if (population === 'chronic-disease') {
    patients = await db.list($.Patient, {
      where: {
        organization: organization.$id,
        'medicalHistory.conditions': {
          $in: ['Diabetes', 'Hypertension', 'Heart Disease', 'COPD'],
        },
      },
    })
  }

  // Aggregate health metrics
  const metrics = {
    // Demographics
    totalPatients: patients.length,
    averageAge: patients.reduce((sum, p) => sum + calculateAge(p.birthDate), 0) / patients.length,
    genderDistribution: groupBy(patients, 'gender'),

    // Chronic conditions
    chronicDiseasePrevalence: await calculateConditionPrevalence(patients),

    // Utilization
    hospitalizations: await db.count($.Encounter, {
      where: {
        patient: { $in: patients.map((p) => p.$id) },
        encounterType: 'inpatient',
        startDate: { $gte: startDate },
      },
    }),
    erVisits: await db.count($.Encounter, {
      where: {
        patient: { $in: patients.map((p) => p.$id) },
        encounterType: 'emergency',
        startDate: { $gte: startDate },
      },
    }),

    // Preventive care
    screeningCompliance: await calculateScreeningCompliance(patients),
    vaccineCompliance: await calculateVaccineCompliance(patients),

    // Outcomes
    readmissionRate: await calculateReadmissionRate(patients, startDate),
    controlledConditions: await calculateControlledConditionRate(patients),
  }

  // AI insights
  const insights = await ai.analyze('population-health', {
    patients,
    metrics,
    timeRange,
  })

  return {
    metrics,
    insights: {
      highRiskPatients: insights.highRiskPatients,
      gaps: insights.careGaps,
      opportunities: insights.interventionOpportunities,
      trends: insights.trends,
      predictions: insights.predictions,
    },
  }
}

// Risk stratification
async function stratifyPatientRisk(patient: Patient) {
  const medicalRecord = await db.related(patient, $.has, $.MedicalRecord).then((records) => records[0])

  // Get recent encounters
  const encounters = await db.list($.Encounter, {
    where: {
      patient: patient.$id,
      startDate: { $gte: subMonths(new Date(), 12) },
    },
  })

  // AI risk assessment
  const riskAssessment = await ai.analyze('patient-risk-stratification', {
    patient,
    medicalRecord,
    encounters,

    factors: {
      age: calculateAge(patient.birthDate),
      chronicConditions: medicalRecord.conditions.length,
      medications: medicalRecord.medications.length,
      hospitalizations: encounters.filter((e) => e.encounterType === 'inpatient').length,
      erVisits: encounters.filter((e) => e.encounterType === 'emergency').length,
      socialDeterminants: medicalRecord.socialHistory,
    },
  })

  // Update patient record
  await db.update($.Patient, patient.$id, {
    riskScore: riskAssessment.score,
    riskLevel: riskAssessment.level,
    riskFactors: riskAssessment.factors,
    lastRiskAssessment: new Date(),
  })

  return riskAssessment
}

// Care gap identification
async function identifyCareGaps(patient: Patient) {
  const medicalRecord = await db.related(patient, $.has, $.MedicalRecord).then((records) => records[0])

  const age = calculateAge(patient.birthDate)

  // Preventive care guidelines
  const gaps = []

  // Age-based screenings
  if (age >= 50 && !hasRecentScreening(patient, 'colonoscopy', 10)) {
    gaps.push({
      type: 'screening',
      service: 'colonoscopy',
      reason: 'Due for colorectal cancer screening',
      priority: 'high',
    })
  }

  if (patient.gender === 'female' && age >= 40 && !hasRecentScreening(patient, 'mammogram', 2)) {
    gaps.push({
      type: 'screening',
      service: 'mammogram',
      reason: 'Due for breast cancer screening',
      priority: 'high',
    })
  }

  // Condition-based monitoring
  if (medicalRecord.conditions.includes('Diabetes')) {
    if (!hasRecentTest(patient, 'hba1c', 3)) {
      gaps.push({
        type: 'monitoring',
        service: 'HbA1c test',
        reason: 'Diabetes monitoring',
        priority: 'medium',
      })
    }

    if (!hasRecentExam(patient, 'diabetic-eye-exam', 12)) {
      gaps.push({
        type: 'monitoring',
        service: 'Diabetic eye exam',
        reason: 'Annual diabetic eye exam',
        priority: 'medium',
      })
    }
  }

  // Vaccinations
  if (!hasRecentVaccination(patient, 'flu', 1)) {
    gaps.push({
      type: 'vaccination',
      service: 'Influenza vaccine',
      reason: 'Annual flu vaccine',
      priority: 'low',
    })
  }

  return gaps
}

HIPAA Compliance

Access Controls

// HIPAA access control
async function checkHIPAAAccess(params: { user: Person; patient: Patient; action: string }) {
  const { user, patient, action } = params

  // Check if user has necessary role
  const roles = await db.related(user, $.hasRole, $.Role)
  const hasRole = roles.some((r) => ['physician', 'nurse', 'admin', 'billing'].includes(r.roleName))

  if (!hasRole) {
    await logAccessDenied(user, patient, action, 'insufficient-role')
    throw new Error('Access denied: Insufficient role')
  }

  // Check if user has direct care relationship
  const hasCareRelationship = await db.exists({
    from: user,
    via: $.treats,
    to: patient,
  })

  // Check if user is part of care team
  const careTeam = await db.related(patient, $.careTeam, $.Person)
  const onCareTeam = careTeam.some((p) => p.$id === user.$id)

  // Check if access is for legitimate purpose
  if (!hasCareRelationship && !onCareTeam) {
    // Require justification
    await send($.Access.requireJustification, {
      user,
      patient,
      action,
    })

    await logAccessAttempt(user, patient, action, 'requires-justification')
    throw new Error('Access requires justification')
  }

  // Log access
  await logAccessGranted(user, patient, action)

  return true
}

// Audit logging
async function logAccessGranted(user: Person, patient: Patient, action: string) {
  await db.create($.AuditLog, {
    action: `hipaa.access.${action}`,
    actor: user.$id,
    resource: patient.$id,
    resourceType: 'patient',
    result: 'granted',
    timestamp: new Date(),
    ipAddress: getCurrentIPAddress(),
    userAgent: getCurrentUserAgent(),
  })
}

Best Practices

1. HIPAA Compliance

  • Access Controls: Implement role-based access with audit logging
  • Encryption: Encrypt all PHI at rest and in transit
  • Audit Trails: Log all access to patient data
  • Minimum Necessary: Only access data needed for treatment
  • Business Associate Agreements: Required for all vendors

2. Clinical Safety

  • Drug Interaction Checks: Always check before prescribing
  • Clinical Decision Support: Use AI to catch potential issues
  • Alert Fatigue: Balance safety with usability
  • Critical Results: Flag and alert on critical findings
  • Error Prevention: Implement safeguards and validations

3. Data Quality

  • Standardized Codes: Use ICD-10, CPT, SNOMED, LOINC
  • Structured Data: Prefer structured over free text
  • Data Validation: Validate all clinical data entry
  • Interoperability: Support HL7 FHIR, C-CDA, NCPDP SCRIPT

4. Patient Experience

  • Self-Service: Enable patients to manage their care
  • Communication: Timely notifications and reminders
  • Transparency: Clear billing and cost information
  • Accessibility: Support multiple languages and devices

5. Provider Experience

  • Reduce Documentation: Use AI to generate clinical notes
  • Smart Scheduling: Optimize provider time
  • Clinical Workflows: Streamline common tasks
  • Decision Support: Provide relevant information at point of care

Complete Implementation

See the full working example at:

Key Takeaways

  1. HIPAA Compliance: Non-negotiable requirement for healthcare
  2. Clinical Safety: Use AI to improve safety and outcomes
  3. Interoperability: Support standard healthcare protocols
  4. Patient-Centered: Design for patient empowerment
  5. Provider Efficiency: Reduce administrative burden
  6. Data-Driven Care: Use analytics for population health

Next Steps


Questions? Check the patterns or join our Discord