Legacy Pipeline Atlas worker-1snapshot 2026-07-15

MDClarity · task primitive

AutoSendLettersForFutureVisits

Overview

AutoSendLettersForFutureVisitsTask automatically generates and sends patient cost estimate letters for future scheduled visits. It evaluates all upcoming visits against configured AutoSendLetterConfig criteria, generates personalized letters with cost estimates, and sends them via email or SMS based on patient communication preferences.

Use this task when: You need to proactively send cost estimate letters to patients for their upcoming scheduled appointments, matching visits to configured auto-send criteria based on visit attributes, patient demographics, and financial thresholds.

Don't use this task when:


Parameters

Parameter Type Required Default Description
None - - - This task has no configurable parameters. It operates on all future visits (scheduled after current date/time) based on AutoSendLetterConfig rules.

Execution Flow

NoYesNoYesNo AutoGenerateOnlyYesYesNoStartAutoSendLettersForFutureVisitsLoad allAutoSendLetterConfigsGet all future visits withscheduled time nowGet most recent letters forfuture visitsGet quotes for future visitsGet visit change events forfuture visitsCreate AutoSendLetterItemfor each visitFor each visit itemFind matchingAutoSendLetterConfigConfig found?Add VisitNotQualified errorValidate visit is calculatedValidate benefits areappliedValidate patient consentand contact infoShould generate letter?Add error to send eventGenerate patient letter fromtemplateShould send letter?Save letter, skip sendingSend letter via email orSMSLog message API responseMark visit.LetterSent = trueSavePatientLetterSendEventMore visits?Save all visits and eventsEnd

Processing Algorithm

The task uses a multi-stage filtering and qualification algorithm:

Visit Qualification Process

  1. Load Future Visits: Retrieve all visits where ScheduledTime > DateTime.Now
  2. Load Configuration Rules: Get all active AutoSendLetterConfig records
  3. Match Each Visit to Config:
    • Filter by visit attributes (Facility, Insurance, Provider, VisitType, VisitStatus)
    • Filter by financial thresholds (MinDaysOut, MaxDaysOut, MinDepositAmount, MaxDepositAmount, MinTotalPatientAmount, MaxTotalPatientAmount)
    • Filter by patient attributes (MinPatientAge, MaxPatientAge)
    • Filter by custom property criteria
    • Select the first matching config (configs are typically non-overlapping)
  4. Validate Visit State:
    • Visit must be calculated (Calculated = true)
    • All quotes must have benefits applied (no ReviewCoinsurance or similar flags)
    • Visit must not have been sent already (unless resend criteria met)
  5. Validate Patient Eligibility:
    • Patient must have ElectronicCommunicationConsent = true
    • Patient must have valid email OR (phone + birthdate)
  6. Determine Generation vs Sending:
    • If AutoGenerateOnly = true: Generate letter but don't send
    • If already sent: Check if VisitResendCriteria matched by VisitChangeEvent
    • Otherwise: Generate and send letter

Resend Logic

Letters can be regenerated and resent if:

Common resend triggers:

Example Execution

For a visit scheduled 5 days out with $1200 patient amount:

Visit V-1
  ScheduledTime: DateTime.Now.AddDays(5)
  TotalPatientAmount: $1200
  DepositAmount: $400
  Calculated: true
  PatientKey: "PAT-001"
  FacilityKey: "FAC-001"
  InsuranceKey: "INS-123"

AutoSendLetterConfig ASLC-001
  MinDaysOut: 3
  MaxDaysOut: 10
  MinTotalPatientAmount: $1000
  MaxTotalPatientAmount: $2000
  LetterTemplate: "LT-ESTIMATE"
  Facilities: [] (empty = all facilities)
  Insurances: [] (empty = all insurances)

Step 1: Match Visit to Config
  ✓ DaysOut = 5 (between 3 and 10)
  ✓ TotalPatientAmount = $1200 (between $1000 and $2000)
  ✓ Facility matches (empty list = all facilities)
  ✓ Insurance matches (empty list = all insurances)
  Result: Config ASLC-001 selected

Step 2: Validate Visit
  ✓ Visit.Calculated = true
  ✓ All quotes have benefits applied
  ✓ Visit.LetterSent = false (no letter sent yet)
  Result: Visit qualifies for letter generation

Step 3: Validate Patient
  ✓ Patient.ElectronicCommunicationConsent = true
  ✓ Patient.Email = "[email]"
  ✓ Patient.PreferredPhone = "[id]"
  ✓ Patient.BirthDate = 1985-03-15
  Result: Patient qualifies for sending

Step 4: Generate and Send
  - Generate letter from template "LT-ESTIMATE"
  - Render with visit cost breakdown
  - Send via email (patient has email)
  - Log email API response
  - Set Visit.LetterSent = true
  - Set Visit.AutoSendLetterConfigKey = "ASLC-001"
  - Create PatientLetterSendEvent with no errors

Usage Examples

Example 1: Basic task execution (no parameters)

var task = new AutoSendLettersForFutureVisitsTask();
// Task uses system configuration from AutoSendLetterConfig table

Example 2: Running in a scheduled job

// Typically scheduled to run daily or multiple times per day
var job = new Job
{
    Key = "JOB-AUTOSEND-FUTURE",
    DisplayName = "Auto Send Letters for Future Visits",
    Tasks = new List<Task>
    {
        new AutoSendLettersForFutureVisitsTask()
    },
    Schedule = "0 8,12,16 * * *"  // Run at 8am, 12pm, 4pm daily
};

Example 3: Chaining with visit calculation

// Common pattern: Calculate visits first, then send letters
var job = new Job
{
    Tasks = new List<Task>
    {
        // First, ensure all future visits are calculated
        new LoadEntitiesFromQueryTask
        {
            Query = @"
                SELECT VisitKey
                FROM Visit
                WHERE ScheduledTime > GETDATE()
                AND Calculated = 0",
            EntityType = "Visit",
            Action = EntityAction.Calculate
        },
        // Then send letters for qualifying visits
        new AutoSendLettersForFutureVisitsTask()
    }
};

Related Tasks Comparison

Task Visit Scope Use Case Batch Mode GFE Compliance
AutoSendLettersForFutureVisits All future visits (scheduled > now) Proactive patient communication for upcoming appointments No Sets GFE compliance for future visits
AutoSendLettersTask Batch table visits Processing historical visits or specific visit batches Yes Sets GFE compliance for batch visits
SendHL7LettersTask Pending HL7 outbound messages Sending letters via HL7 integration to external systems No N/A - HL7 transmission

Key Differentiators:


Performance Considerations

Database Impact

External API Impact