Skip to main content

Server Actions API Reference

This document provides a comprehensive reference for all server actions available in the LyfeAI Provider system. Server actions are the primary method for data mutations and complex operations in this Next.js application.

Table of Contents

  1. Admin Actions
  2. AI Actions
  3. Care Plan Actions
  4. Chat Actions
  5. Communication Actions
  6. EHR Actions
  7. Order Actions
  8. Patient Actions
  9. Patient Portal AI Actions
  10. Portal Actions

Authentication & Authorization

All server actions require authentication unless specified otherwise. The system uses role-based access control (RBAC) with the following roles:

  • Admin: Full system access, user management, configuration
  • Doctor: Medical orders, care plans, full patient access
  • Nurse: Care plans, patient communication, limited ordering
  • Staff: Basic patient access, communication
  • Patient: Portal access only

Response Format

All server actions return a standardized response format:

{
success: boolean;
data?: any; // Success data
error?: string; // Error message
message?: string; // User-friendly message
fieldErrors?: any; // Field-specific validation errors
}

Admin Actions

User Management

addUser

Creates a new user in the system.

Parameters:

userData: {
name: string;
email: string;
role: "admin" | "doctor" | "nurse" | "staff";
password: string;
status: "active" | "inactive";
}

Returns:

{
success: boolean;
user?: User;
error?: string;
}

Authorization: Admin role required


updateUser

Updates an existing user's information.

Parameters:

userId: string;
updates: Partial<User>;

Returns:

{
success: boolean;
user?: User;
error?: string;
}

Authorization: Admin role required


deleteUser

Removes a user from the system.

Parameters:

userId: string;

Returns:

{
success: boolean;
error?: string;
}

Authorization: Admin role required


System Configuration

updateIntegrationStatus

Toggles integration connections (e.g., EHR systems).

Parameters:

integrationId: string;
status: boolean;

Returns:

{
success: boolean;
message: string;
}

Authorization: Admin role required


updateAIModelStatus

Activates or deactivates AI models.

Parameters:

modelId: string;
status: boolean;

Returns:

{
success: boolean;
message: string;
}

Authorization: Admin role required


exportAuditLogs

Exports audit logs for compliance purposes.

Parameters:

filters?: {
startDate?: string;
endDate?: string;
userId?: string;
action?: string;
}

Returns:

{
success: boolean;
downloadUrl?: string;
error?: string;
}

Authorization: Admin role required


Updates organization branding.

Parameters:

formData: FormData; // Contains logo file

Returns:

{
success: boolean;
logoUrl?: string;
error?: string;
}

Authorization: Admin role required


saveThemeSettings

Saves UI theme preferences.

Parameters:

settings: {
theme: string;
darkMode: boolean;
showProjectInfo: boolean;
}

Returns:

{
success: boolean;
settings?: object;
error?: string;
}

Authorization: Admin role required


AI Actions

Document Processing

processDocumentWithAI

Extracts patient data from medical documents using AI.

Parameters:

documentText: string;

Returns:

{
demographics: {
firstName: string;
lastName: string;
dateOfBirth: string;
gender: string;
mrn?: string;
ssn?: string;
address?: Address;
phone?: string;
email?: string;
};
medicalHistory: {
conditions: Array<{
name: string;
icd10Code?: string;
dateOfDiagnosis?: string;
status: string;
}>;
medications: Array<{
name: string;
dosage: string;
frequency: string;
startDate?: string;
}>;
allergies: Array<{
allergen: string;
reaction?: string;
severity?: string;
}>;
surgeries: Array<{
procedure: string;
date?: string;
outcome?: string;
}>;
};
vitalSigns?: {
bloodPressure?: string;
heartRate?: number;
temperature?: number;
weight?: string;
height?: string;
bmi?: number;
};
labResults?: Array<{
testName: string;
value: string;
unit?: string;
referenceRange?: string;
date?: string;
abnormal?: boolean;
}>;
immunizations?: Array<{
vaccine: string;
date?: string;
booster?: boolean;
}>;
insurance?: {
provider: string;
policyNumber: string;
groupNumber?: string;
effectiveDate?: string;
};
confidence: number;
extractedSections: string[];
processingNotes?: string[];
}

Authorization: Any authenticated user


addPatientWithInsights

Creates a patient record with AI-generated insights.

Parameters:

extractedData: ExtractedPatientData; // From processDocumentWithAI

Returns:

{
success: boolean;
patient?: Patient;
insights?: string[];
summary?: string;
confidence?: number;
patientId?: string;
error?: string;
}

Authorization: Any authenticated user


Scheduling AI

optimizeSchedule

Provides AI-powered schedule optimization suggestions.

Parameters:

date: string; // ISO date string

Returns:

{
recommendations: Array<{
type: string;
description: string;
impact: string;
priority: "high" | "medium" | "low";
}>;
utilization: {
current: number;
optimal: number;
potential: number;
};
bottlenecks: string[];
opportunities: string[];
}

Authorization: Scheduling access required


predictNoShowRisk

Predicts appointment no-show probability.

Parameters:

date: string; // ISO date string

Returns:

Array<{
appointmentId: string;
patientName: string;
time: string;
riskScore: number; // 0-100
riskFactors: string[];
recommendations: string[];
}>

Authorization: Scheduling access required


suggestOptimalSlots

Recommends best appointment times based on patient profile.

Parameters:

patientProfile: {
age?: number;
conditions?: string[];
preferences?: any;
};
appointmentType: string;

Returns:

{
recommendedSlots: Array<{
date: string;
time: string;
reason: string;
score: number;
}>;
considerations: string[];
}

Authorization: Scheduling access required


Medical Imaging AI

analyzeImage

AI analysis of medical images.

Parameters:

imageName: string;

Returns:

{
findings: {
summary: string;
details: Array<{
finding: string;
location: string;
severity: string;
confidence: number;
}>;
};
anomalies: {
detected: boolean;
list: Array<{
type: string;
description: string;
urgency: string;
}>;
};
recommendations: string[];
preliminaryReport: string;
requiresReview: boolean;
}

Authorization: Medical staff required


generateRadiologyReport

Generates a formal radiology report from findings.

Parameters:

findings: any; // From analyzeImage

Returns:

{
report: string; // Formatted radiology report
}

Authorization: Radiologist role required


trackProgression

Tracks changes in imaging findings over time.

Parameters:

patientId: string;
studyType: string;

Returns:

Array<{
date: string;
findings: string;
changes: {
improved: string[];
worsened: string[];
stable: string[];
new: string[];
};
trend: "improving" | "worsening" | "stable";
visualComparison?: string;
}>

Authorization: Medical staff required


Care Plan Actions

createCarePlan

Creates a comprehensive care plan for a patient.

Parameters:

{
patientId: string;
name: string;
type: "diabetes" | "hypertension" | "post-surgical" | "chronic-pain" | "custom";
goals: Array<{
description: string;
targetDate: string;
metrics?: string;
}>;
interventions: Array<{
type: string;
description: string;
frequency: string;
assignedTo?: string;
}>;
notes?: string;
}

Returns:

{
success: boolean;
carePlan?: CarePlan;
message?: string;
error?: string;
}

Authorization: Doctor/Nurse role required


useCarePlanTemplate

Creates a care plan from predefined templates.

Parameters:

templateId: string;
patientId: string;

Returns:

{
success: boolean;
carePlan?: CarePlan;
message?: string;
error?: string;
}

Authorization: Doctor/Nurse role required


updateCarePlanGoal

Updates the status of a care plan goal.

Parameters:

carePlanId: string;
goalId: string;
status: "Not Started" | "In Progress" | "Completed";

Returns:

{
success: boolean;
message?: string;
error?: string;
}

Authorization: Care team member required


getActiveCarePlans

Retrieves all active care plans for a patient.

Parameters:

patientId: string;

Returns:

{
success: boolean;
carePlans?: CarePlan[];
error?: string;
}

Authorization: View patient access required


Chat Actions

generateAIResponse

Generates AI medical assistant responses.

Parameters:

userMessage: string;
conversationHistory: Array<{
role: "user" | "assistant" | "system";
content: string;
}>;

Returns:

{
success: boolean;
response: string;
}

Authorization: Any authenticated user

Note: Falls back to simulated responses if OpenAI is unavailable.


Communication Actions

sendMessage

Sends a message to a patient.

Parameters:

data: {
patientId: string;
content: string;
attachments?: File[];
}

Returns:

{
success: boolean;
message?: Message;
notification?: string;
error?: string;
}

Authorization: Provider access required


scheduleCall

Schedules a telehealth appointment.

Parameters:

{
patientId: string;
type: "phone" | "video";
date: string;
time: string;
duration: number; // minutes
notes?: string;
}

Returns:

{
success: boolean;
appointment?: Appointment;
message?: string;
error?: string;
}

Authorization: Provider access required


startCall

Initiates a telehealth call.

Parameters:

patientId: string;
type: "phone" | "video";

Returns:

{
success: boolean;
callUrl?: string;
message?: string;
error?: string;
}

Authorization: Provider access required


uploadAttachment

Uploads file attachments for messages.

Parameters:

file: File;

Returns:

{
success: boolean;
fileUrl?: string;
fileName?: string;
fileSize?: number;
error?: string;
}

Authorization: Any authenticated user


getConversationHistory

Retrieves patient communication history.

Parameters:

patientId: string;

Returns:

{
success: boolean;
messages?: Message[];
error?: string;
}

Authorization: View patient access required


EHR Actions

searchEHRPatient

Searches external EHR systems for patient matches.

Parameters:

query: string;
ehrSystem: string;

Returns:

Array<{
mrn: string;
name: string;
dateOfBirth: string;
gender: string;
lastVisit?: string;
matchConfidence: number;
source: string;
}>

Authorization: EHR integration access required


syncPatientData

Imports comprehensive patient data from EHR.

Parameters:

mrn: string;
ehrSystem: string;

Returns:

{
patient: Patient;
conditions: Condition[];
medications: Medication[];
allergies: Allergy[];
encounters: Encounter[];
labs: LabResult[];
vitals: VitalSign[];
immunizations: Immunization[];
documents: Document[];
providers: Provider[];
insuranceClaims: Claim[];
familyHistory: FamilyHistory[];
socialHistory: SocialHistory;
importSummary: {
totalRecords: number;
newRecords: number;
updatedRecords: number;
errors: string[];
};
}

Authorization: EHR integration access required


checkDuplicates

AI-powered duplicate patient detection.

Parameters:

patientData: any;

Returns:

{
hasDuplicates: boolean;
matches: Array<{
patientId: string;
confidence: number;
matchedFields: string[];
}>;
confidence: number;
}

Authorization: Data management access required


mergePatientRecords

Intelligently merges duplicate patient records.

Parameters:

patientId1: string;
patientId2: string;

Returns:

{
success: boolean;
mergedId: string;
message: string;
}

Authorization: Admin role required


validatePatientData

Validates patient data format and completeness.

Parameters:

patientData: any;

Returns:

{
isValid: boolean;
issues: string[];
confidence: number;
}

Authorization: Any authenticated user


enrichPatientData

Adds AI-generated insights and risk scores.

Parameters:

patientData: any;

Returns:

{
...patientData,
insights: {
riskScores: {
cardiovascular: number;
diabetes: number;
fallRisk: number;
readmission: number;
};
careGaps: string[];
recommendations: string[];
socialDeterminants: any;
};
}

Authorization: Medical staff required


Order Actions

submitOrder

Creates medical orders (labs, medications, imaging).

Parameters:

orderData: {
patientId: string;
type: "lab" | "medication" | "imaging" | "procedure";
priority: "routine" | "urgent" | "stat";
diagnosis: string;
icd10Code?: string;
clinicalIndication: string;
tests?: Array<{
code: string;
name: string;
specialInstructions?: string;
}>;
medications?: Array<{
name: string;
dosage: string;
route: string;
frequency: string;
duration: string;
quantity: number;
}>;
imagingDetails?: {
modality: string;
bodyPart: string;
contrast: boolean;
views?: string[];
};
}

Returns:

{
success: boolean;
order?: Order;
message?: string;
error?: string;
}

Authorization: Provider ordering privileges required


saveOrderAsDraft

Saves an incomplete order as a draft.

Parameters:

orderData: Partial<OrderData>;

Returns:

{
success: boolean;
draft?: Draft;
message?: string;
error?: string;
}

Authorization: Provider access required


acknowledgeResult

Marks test results as reviewed.

Parameters:

resultId: string;

Returns:

{
success: boolean;
message?: string;
acknowledgedAt?: string;
error?: string;
}

Authorization: Provider access required


viewResultDetails

Retrieves detailed test results.

Parameters:

resultId: string;

Returns:

{
success: boolean;
result?: {
id: string;
orderType: string;
orderDate: string;
resultDate: string;
status: string;
priority: string;
orderedBy: string;
performingLab?: string;
specimen?: {
type: string;
collectionDate: string;
collectionTime: string;
};
results: Array<{
testName: string;
value: string;
unit: string;
referenceRange: string;
flag?: string;
interpretation?: string;
}>;
comments?: string;
criticalValues?: Array<{
test: string;
value: string;
notifiedAt: string;
notifiedTo: string;
}>;
attachments?: Array<{
name: string;
url: string;
type: string;
}>;
};
error?: string;
}

Authorization: View results access required


createQuickOrder

Creates orders from common templates.

Parameters:

orderType: string; // "CBC", "CMP", "UA", etc.
patientId: string;

Returns:

{
success: boolean;
order?: Order;
message?: string;
error?: string;
}

Authorization: Provider ordering privileges required


Patient Actions

addPatient

Creates a new patient record.

Parameters:

formData: {
firstName: string;
lastName: string;
dateOfBirth: string;
gender: string;
mrn?: string;
ssn?: string;
email?: string;
phone?: string;
address?: {
street: string;
city: string;
state: string;
zipCode: string;
};
insurance?: {
provider: string;
policyNumber: string;
groupNumber?: string;
};
emergencyContact?: {
name: string;
relationship: string;
phone: string;
};
}

Returns:

{
success: boolean;
patient?: Patient;
message?: string;
error?: string;
fieldErrors?: Record<string, string>;
}

Authorization: Patient management access required


addImportedPatient

Adds a patient from external import.

Parameters:

patientData: any; // From import process

Returns:

{
success: boolean;
patient?: Patient;
message?: string;
error?: string;
}

Authorization: Import access required


testDatabaseConnection

Tests data store connectivity.

Parameters: None

Returns:

{
success: boolean;
message?: string;
error?: string;
}

Authorization: System access


getPatients

Retrieves the patient list.

Parameters:

includeHidden: boolean = false;

Returns:

Patient[]

Authorization: View patients access required


getHiddenPatients

Retrieves hidden/archived patients.

Parameters: None

Returns:

Patient[]

Authorization: Admin role required


getPatientById

Retrieves specific patient details.

Parameters:

id: string;

Returns:

Patient | null

Authorization: View patient access required


updatePatient

Updates patient information.

Parameters:

id: string;
formData: PatientFormData;

Returns:

{
success: boolean;
patient?: Patient;
message?: string;
error?: string;
fieldErrors?: Record<string, string>;
}

Authorization: Edit patient access required


deletePatient

Removes a patient record.

Parameters:

id: string;

Returns:

{
success: boolean;
message?: string;
error?: string;
}

Authorization: Admin role required


Patient Portal AI Actions

Voice & Document Processing

processVoiceInput

Converts voice to text for form fields.

Parameters:

audioBlob: string; // Base64 encoded audio
context: string; // Field context

Returns:

{
success: boolean;
transcription?: string;
confidence?: number;
error?: string;
}

Authorization: Patient portal access


processDocumentOCR

Extracts data from documents (insurance cards, IDs, prescriptions).

Parameters:

imageData: string;    // Base64 encoded image
documentType: string; // "insurance-card" | "driver-license" | "prescription"

Returns:

{
success: boolean;
extractedData?: any;
confidence?: number;
suggestions?: string[];
error?: string;
}

Authorization: Patient portal access


Health Analysis

performAIHealthAnalysis

Comprehensive AI health assessment.

Parameters:

onboardingData: {
demographics: any;
medicalHistory: any;
currentSymptoms?: any;
lifestyle?: any;
familyHistory?: any;
}

Returns:

{
riskScores: {
cardiovascular: { score: number; factors: string[] };
diabetes: { score: number; factors: string[] };
cancer: { score: number; factors: string[] };
mentalHealth: { score: number; factors: string[] };
};
recommendations: {
immediate: string[];
preventive: string[];
lifestyle: string[];
screenings: string[];
};
insights: {
summary: string;
strengths: string[];
concerns: string[];
priorities: string[];
};
followUpSuggestions: {
specialists: string[];
tests: string[];
timeline: string;
};
}

Authorization: Patient portal access


generateSmartFormSuggestions

Provides intelligent autocomplete suggestions.

Parameters:

fieldName: string;
currentValue: string;
context: OnboardingData;

Returns:

{
suggestions: string[];
}

Authorization: Patient portal access


Identity & Security

validateIdentityDocument

Verifies government-issued IDs.

Parameters:

documentData: {
type: string;
frontImage: string;
backImage?: string;
}

Returns:

{
isValid: boolean;
extractedInfo: {
name: string;
dateOfBirth: string;
documentNumber: string;
expirationDate: string;
address?: string;
};
securityChecks: {
tampering: boolean;
expired: boolean;
formatValid: boolean;
};
confidence: number;
}

Authorization: Patient portal access


performBiometricVerification

Face recognition and liveness detection.

Parameters:

faceImageData: string; // Base64 encoded image

Returns:

{
verified: boolean;
livenessCheck: {
passed: boolean;
confidence: number;
};
faceMatch: {
matched: boolean;
confidence: number;
};
securityFlags: string[];
}

Authorization: Patient portal access


Device Integration

connectWearableDevice

Connects health tracking devices.

Parameters:

deviceType: string; // "fitbit" | "apple-health" | "garmin" | etc.
authToken: string;

Returns:

{
connected: boolean;
deviceInfo: {
name: string;
lastSync: string;
dataTypes: string[];
};
importedData: {
steps: number;
heartRate: number;
sleep: number;
lastUpdated: string;
};
}

Authorization: Patient portal access


generatePersonalizedWelcome

Creates a personalized onboarding message.

Parameters:

analysisResult: AIAnalysisResult;
patientName: string;

Returns:

{
success: boolean;
message: string;
nextSteps: string[];
}

Authorization: Patient portal access


Portal Actions

sendPatientPortalInvite

Sends portal sync invitation to patient.

Parameters:

{
patientId: string;
patientName: string;
contactMethod: "email" | "sms";
contactInfo: string;
portal: "mychart" | "healow" | "followmyhealth" | "patientfusion";
message?: string;
}

Returns:

{
success: boolean;
requestId: string;
portalLink: string;
expiresAt: string;
}

Authorization: Provider access required


trackPortalSync

Monitors portal sync progress.

Parameters:

requestId: string;

Returns:

{
status: "pending" | "authenticating" | "syncing" | "completed" | "failed";
progress: number; // 0-100
message: string;
details?: {
recordsFound: number;
recordsImported: number;
currentStep: string;
};
}

Authorization: Provider access required


getPortalSyncStatus

Gets final sync results.

Parameters:

requestId: string;

Returns:

{
importSummary: {
demographics: number;
conditions: number;
medications: number;
allergies: number;
immunizations: number;
encounters: number;
labResults: number;
documents: number;
totalRecords: number;
};
errors: string[];
warnings: string[];
}

Authorization: Provider access required


getImportedPortalData

Retrieves all imported patient data.

Parameters:

requestId: string;

Returns:

{
patient: Patient;
medicalHistory: MedicalHistory;
medications: Medication[];
allergies: Allergy[];
immunizations: Immunization[];
encounters: Encounter[];
labResults: LabResult[];
documents: Document[];
timeline: TimelineEvent[];
}

Authorization: Provider access required


generatePortalSyncQRCode

Creates QR code for mobile portal sync.

Parameters:

data: {
patientId: string;
portal: string;
expiresIn: number; // minutes
}

Returns:

{
qrCode: string; // Base64 encoded QR code image
data: string; // Encoded data
expiresAt: string; // ISO timestamp
}

Authorization: Provider access required


processPortalWebhook

Handles callbacks from patient portals.

Parameters:

webhookData: {
event: string;
requestId: string;
status: string;
data?: any;
}

Returns:

{
processed: boolean;
action: string;
nextStep?: string;
}

Authorization: System webhook endpoint


Error Handling

All server actions implement consistent error handling:

  1. Validation Errors: Return fieldErrors object with field-specific messages
  2. Authorization Errors: Return generic error message
  3. System Errors: Log internally and return user-friendly error message
  4. Network Errors: Automatic retry with exponential backoff (where applicable)

Rate Limiting

The following actions have rate limits:

  • AI document processing: 100 requests per hour
  • Image analysis: 50 requests per hour
  • Portal sync requests: 10 per patient per day
  • Voice processing: 200 requests per hour

Best Practices

  1. Always check success field before accessing data
  2. Handle errors gracefully with user-friendly messages
  3. Use field validation on the client before calling actions
  4. Implement optimistic updates where appropriate
  5. Cache responses when data doesn't change frequently
  6. Use proper TypeScript types for all parameters and returns