medOS ultra

RCM & Billing Engine

Country-agnostic RCM: 13 generic evaluators, JSON country packs, AI-assisted coding, e-Claim connector, medallion analytics.

7 min read diagramsUpdated 2026-03-26docs/architecture/architecture/08-rcm-billing-engine.md

Country-agnostic RCM. 13 generic evaluators. JSON country packs. AI-assisted coding. e-Claim connector. Medallion analytics.


Overview

MedOS RCM is a fully country-agnostic, data-driven billing engine. Zero localization lives in core code. All regional rules (LOS thresholds, penalty tiers, insurance quotas) are JSON config packs evaluated by 13 generic evaluators at runtime.

Core principle: ever-api-financial is a thin proxy with zero business rules. All validation logic runs in Deno Edge Functions on MedBase.


OPD vs IPD Billing Flow

OPD (Outpatient):
  Register → Consultation → [Skip Coder] → Direct to Invoice → Payment

IPD (Inpatient):
  Admit → Consult → Discharge → ปิดบัญชี (Close Account)
       → Medical Coder (ICD-10/CPT) → ส่งเบิก (Submit Claim)
       → รอ REP (Await Government Response) → ออกใบเรียกเก็บ (Issue Invoice)

Architecture Diagram

┌──────────────────────────────────────────────────────────────────────────────┐
│                      RCM PIPELINE                                            │
│                                                                              │
│  ┌─────────────────────────────────────────────────────────────────────────┐ │
│  │  ENCOUNTER + CLINICAL DATA (Write Model — MongoDB)                      │ │
│  │  Patient demographics, diagnoses, procedures, medications, LOS          │ │
│  └────────────────────────────────────┬────────────────────────────────────┘ │
│                                       │                                      │
│                          hospital_events trigger                             │
│                                       │                                      │
│                                       ▼                                      │
│  ┌─────────────────────────────────────────────────────────────────────────┐ │
│  │  BUSINESS RULES LAYER (Deno Edge Functions on MedBase)                  │ │
│  │                                                                         │ │
│  │  ┌─────────────────┐  ┌──────────────────┐  ┌───────────────────────┐  │ │
│  │  │ rcm-rule-engine │  │ coding-rules-    │  │ coding-ai-assistant   │  │ │
│  │  │ ───────────────  │  │ engine           │  │ ─────────────────────  │  │ │
│  │  │ 13 Evaluators    │  │ ──────────────── │  │ Claude/GPT-4o         │  │ │
│  │  │ (E1-E13)         │  │ ICD-10 validation│  │ ICD/CPT suggestion    │  │ │
│  │  │ JSON country     │  │ DRG grouping     │  │ Upcoding detection    │  │ │
│  │  │ packs drive all  │  │ Bundling rules   │  │ GOP report gen        │  │ │
│  │  │ logic            │  │ NCCI edits       │  │ Denial appeal draft   │  │ │
│  │  └────────┬─────────┘  └────────┬─────────┘  └───────────┬───────────┘  │ │
│  │           │                     │                         │              │ │
│  │           ▼                     ▼                         ▼              │ │
│  │  ┌──────────────────────────────────────────────────────────────────┐   │ │
│  │  │  OUTPUT: RcmValidationAlert[]                                    │   │ │
│  │  │  { alertType, severity, action: BLOCK|WARN|INFO, message,       │   │ │
│  │  │    schemeCode, countryCode, encounterId, details }               │   │ │
│  │  └──────────────────────────────────────────────────────────────────┘   │ │
│  └─────────────────────────────────────────────────────────────────────────┘ │
│                                       │                                      │
│                                       ▼                                      │
│  ┌─────────────────────────────────────────────────────────────────────────┐ │
│  │  PERSISTENCE (MedBase — Supabase Postgres)                              │ │
│  │                                                                         │ │
│  │  rcm_financial_alert      — Validation alerts per encounter             │ │
│  │  rcm_claim_batch          — Claim submission batches                    │ │
│  │  rcm_rep_response         — Government reimbursement responses          │ │
│  │  rcm_correction_queue     — Claims needing correction                   │ │
│  │  rcm_ai_suggestion_log    — AI coding suggestions with confidence       │ │
│  │  coding_worklist          — Coder assignment queue                      │ │
│  │  eclaim_delivery_log      — Submission audit trail                      │ │
│  └─────────────────────────────────────────────────────────────────────────┘ │
│                                       │                                      │
│                                       ▼                                      │
│  ┌─────────────────────────────────────────────────────────────────────────┐ │
│  │  e-CLAIM CONNECTOR (Deno Edge Function)                                 │ │
│  │                                                                         │ │
│  │  Actions: submit | importStatement | fetchAllClaims | syncStatus        │ │
│  │                                                                         │ │
│  │  Connector Packs:                                                       │ │
│  │  ┌──────────────┐  ┌─────────────┐  ┌──────────────┐  ┌─────────────┐ │ │
│  │  │ th-nhso      │  │ th-csmbs    │  │ jp-nhi       │  │ us-medicare  │ │ │
│  │  │ (Thai UC)    │  │ (Civil Svt) │  │ (Japan NHI)  │  │ (planned)   │ │ │
│  │  └──────────────┘  └─────────────┘  └──────────────┘  └─────────────┘ │ │
│  └─────────────────────────────────────────────────────────────────────────┘ │
│                                       │                                      │
│                                       ▼                                      │
│  ┌─────────────────────────────────────────────────────────────────────────┐ │
│  │  GOLD LAYER ANALYTICS (Medallion Architecture)                          │ │
│  │                                                                         │ │
│  │  Materialized Views (refreshed daily at 2:07 AM):                       │ │
│  │  gold_fact_claims        — Claim fact table for BI                      │ │
│  │  gold_monthly_kpi        — Monthly billing KPIs                         │ │
│  │  gold_denial_prediction  — Denial risk scoring                          │ │
│  │  gold_coding_metrics     — Coding audit facts                           │ │
│  │  gold_coding_coder_kpi   — Per-coder accuracy/speed                     │ │
│  │  gold_coding_ai_effectiveness — AI vs manual accuracy comparison        │ │
│  └─────────────────────────────────────────────────────────────────────────┘ │
└──────────────────────────────────────────────────────────────────────────────┘

13 Generic RCM Evaluators

Every evaluator is parameterized by the country pack JSON. No code changes needed to add rules.

# Evaluator What It Checks
E1 encounterOverlap OPD-to-IPD time gap merging (e.g., <4h for Thai NHSO)
E2 leaveDay Patient absence — LOS deduction when leave exceeds threshold
E3 latePenalty Late submission step-down penalty tiers (e.g., 100% → 95% → 85%)
E4 referralAutoApprove Referral auto-approval countdown timer
E5 losReclassification Minimum IP hours before reclassifying to OPD (e.g., 2h for Thai)
E6 oneDaySurgery One-day surgery eligibility (LOS 4-24h, CC level, procedure prefix)
E7 bariatricBmi BMI gatekeeper (40+ or 35+ with comorbidity) for bariatric coverage
E8 palliativeCare Palliative ICD code + monthly quota + annual cap
E9 rareDisease Rare disease installment tracker (annual budget, N installments)
E10 diagnosticPathway Prerequisite gates (e.g., abnormal CXR required before TB molecular)
E11 clinicalQuotas Per-period test/procedure limits (e.g., HIV CD4 per quarter)
E12 drugCatalogue Drug mismatch detection (registered vs ordered formulary)
E13 transportation Ambulance/transport cost formula

Country Pack Structure

{
  "countryCode": "TH",
  "schemeCode": "NHSO_UC",
  "schemeName": "Thai NHSO Universal Coverage",
  "effectivePeriod": { "from": "2024-01-01", "to": "2025-12-31" },
  "rules": {
    "encounterOverlap": { "opdToIpdMaxGapHours": 24, "opdToIpdWarningGapHours": 4 },
    "latePenalty": {
      "baseRate": 8350, "baseRateUnit": "THB/AdjRW",
      "tiers": [
        { "maxDays": 30, "payoutRate": 1.0 },
        { "maxDays": 60, "payoutRate": 0.95 },
        { "maxDays": 99999, "payoutRate": 0.85 }
      ]
    },
    "losReclassification": { "minIpHours": 2 },
    "oneDaySurgery": { "minLosHours": 4, "maxLosHours": 24 }
  },
  "messages": {
    "RCM_LATE_SUBMISSION_RISK": {
      "local": "ความเสี่ยงการส่งช้า Tier {tierIndex}: {daysSince} วันนับจากจำหน่าย",
      "en": "Late penalty tier {tierIndex}: {daysSince} days since discharge"
    }
  }
}

Adding a new country: Create 1 JSON file → register scheme code → deploy. Done.


AI-Assisted Medical Coding

The coding-ai-assistant Deno function provides:

Capability Model Output
ICD-10/CPT code suggestion Claude Sonnet / GPT-4o Codes with confidence scores
Upcoding risk detection LLM analysis Risk flags per encounter
GOP (Guarantee of Payment) LLM generation Report for commercial insurers
Denial appeal drafting LLM generation Appeal letter with clinical justification

The coding-rules-engine then validates AI suggestions against country-specific rules (syntax, laterality, age constraints, bundling, NCCI edits).


Financial Microservice Modules

Module Purpose
rcmValidation Thin proxy to Deno BRE (zero business rules in NestJS)
eclaimConnector Thin proxy to Deno e-claim submitter
payor / payorPlan Insurance company + plan master data
payorPlanEnrollment Patient-to-plan assignments
claimInvoice Claim document generation
salesOrder / invoice / receipt SO → Invoice → Payment lifecycle
accountReceivable AR ledger + aging + installments
settlement Payment reconciliation
reconciliation Bank/government statement matching
debtCollection Collection workflows
billingGroup / billingSubGroup Billing category taxonomy

Usage Metering & Stripe Integration

The usage-aggregator function:

  1. Aggregates usage_meterusage_rollups (visits, claims, codes per dimension)
  2. Aggregates product_eventsproduct_event_rollups (feature usage)
  3. Reports monthly totals to Stripe Metered Billing for SaaS pricing

Shared library: _shared/stripe-meter.ts — supports per-encounter, per-rule-eval, per-user billing models.


Why This Matters

For the Owner/CTO Benefit
Multi-country expansion New country = 1 JSON file. Thailand, Japan, Singapore, US — same codebase
Revenue protection 13 evaluators catch late penalties, overlap errors, quota violations before claim submission
AI productivity Coders get AI suggestions + confidence scores. Measurable via gold_coding_ai_effectiveness
Government integration e-Claim connector handles NHSO, CSMBS, NHI portals automatically
BI-ready analytics Medallion gold layer powers dashboards without ETL infrastructure
Zero vendor lock-in All rules are JSON. Swap evaluator logic or add new schemes without touching core
Ask Anything