medOS ultra

Master Frontend API Guide

Reference guide to the frontend API/service layer.

7 min read diagramsUpdated 2026-04-16docs/frontend/MASTER_FRONTEND_API_GUIDE.md

Every API Call, Subscription, and Redux Action for the CDS System

Date: 2026-03-11 For: Frontend developers implementing CDS alerts, vitals scoring, and realtime clinical safety


1. Order-Time Medication Safety

What: Check allergies, interactions, pregnancy, age, dosage, duplication when doctor selects a drug

GET /v2/medication/orderRequests/calculateMedicationAllergyInteraction
  ?patientId={patientId}
  &medicationIds={comma-separated existing product IDs}
  &newItem={new product ID}
  &encounterId={encounterId}

Response shape (key safety fields per medication):

{
  order: {
    product: string,
    name: string,
    allergy: Array<{name, level, type}>,
    interaction: Array<{substanceA, substanceB, level, isPopupAlert, comment}>,
    duplicate: {product, orderCode, duplicateTotal} | undefined,
    duplacateOtherOrder: {product, name, duplicateTotal} | undefined,
    duplicateProductCategory: any | undefined,
    pregnancySafety: {action: 'WARN'|'BLOCK'|'NONE', category, recommendation?, gestationalAge?},
    ageSafety: {action: 'WARN'|'BLOCK', patientAgeYears, patientAgeMonths, minAge?, maxAge?, ageUnit},
    dosageLimitSafety: Array<{criteria, minDose?, maxDose?, unit?, warning?, isContraindicated}>,
    therapeuticDuplications: Array<{existingMedicationName, existingMedicationId, sharedCategory}>,
    lactationSafety: {action: 'WARN'|'BLOCK'|'NONE', category, recommendation?, infantRiskLevel?},
    isHighAlert: boolean,
    highAlertCategory: string,
    corollaryOrders: string[],
    alert: boolean,   // true if any alert fires
  },
  list: [...same shape for existing meds],
  staleDataResults: Array<{dataType, isStale, ageHours, ttlHours, message, messageEn}>,
}

How to handle:

const med = response.data.order;

// Tier 3 (Hard Stop) — blocks order
if (med.pregnancySafety?.action === 'BLOCK' ||
    med.ageSafety?.action === 'BLOCK' ||
    med.dosageLimitSafety?.some(d => d.isContraindicated) ||
    med.lactationSafety?.action === 'BLOCK' ||
    med.interaction?.some(i => i.isPopupAlert && i.level === 'major')) {
  // Show blocking modal — requires senior override
}

// Tier 2 (Soft Stop) — requires override reason
if (med.pregnancySafety?.action === 'WARN' || med.ageSafety?.action === 'WARN' || ...) {
  // Show interruptive modal with override reason dropdown
}

// Tier 1 (Info) — toast/banner
if (med.isHighAlert || med.corollaryOrders?.length > 0) {
  // Show info banner
}

Override reason codes for Tier 2 modals: CLINICALLY_JUSTIFIED · PATIENT_TOLERANT · BENEFITS_OUTWEIGH_RISKS · MONITORING_IN_PLACE · DOSE_VERIFIED · SENIOR_APPROVED · OTHER


2. Vitals Scoring (NEWS2 / MEWS) via Edge Function

What: Score vital signs using server-side GDL engine + get cross-domain CDS alerts

Option A: Via RTK Query (recommended)

import { useEvaluateGdlMutation } from '@store/flow-notification/cdsAlertsApi';

const [evaluateGdl] = useEvaluateGdlMutation();

const result = await evaluateGdl({
  encounterId: 'enc-123',
  patientId: 'pat-456',
  object: { shortKey: 'gt0010', valueNum: 45 },  // HR = 45
  date: '2026-03-11T10:00:00.000Z',
  rows: currentVitalRows,     // existing row data from the UI
  ruleSetCode: 'NEWS2',       // or 'MEWS'
}).unwrap();

// result = {
//   rows: [...scored rows with threshold values],
//   alerts: [...GDL alerts (threshold/calculation/interpretation)],
//   crossDomainAlerts: [...backend CDS alerts (stale data, vitals-med)],
//   newsScore: 8,
//   newsInterpretation: 'High',
//   latencyMs: 45,
// }

Option B: Via Redux thunk (with offline fallback)

import { runCdsThunks } from '@store/flow-notification/cdsThunks';

dispatch(runCdsThunks({
  object: { shortKey: 'gt0010', valueNum: 45 },
  date: '2026-03-11T10:00:00.000Z',
  rows: currentVitalRows,
  rules: localRules,           // only used for offline fallback
  encounterId: 'enc-123',
  patientId: 'pat-456',
  ruleSetCode: 'NEWS2',
}));

GDL shortKey → vital sign mapping:

shortKey Vital Backend Key
gt0005 Respiration Rate RR
gt0006 SpO2 SPO2
gt0008 Temperature TEMP
gt0009 Systolic BP BP_SYSTOLIC
gt0010 Heart Rate HR
gt0011 Consciousness CONSCIOUSNESS

3. Realtime Alert Subscription (Supabase Realtime)

What: Subscribe to encounter_journey_cache for live safety alerts pushed from backend

import { medbaseClient } from '@context/MedBaseProvider';

const subscription = medbaseClient
  .channel('encounter-alerts')
  .on('postgres_changes', {
    event: 'UPDATE',
    schema: 'public',
    table: 'encounter_journey_cache',
    filter: `encounter_id=eq.${encounterId}`,
  }, (payload) => {
    const cache = payload.new;
    const alerts = cache.active_alerts || [];
    const snapshot = cache.safety_snapshot;

    // Dispatch to Redux
    dispatch(setSafetyAlerts(alerts));
    dispatch(setSafetySnapshot(snapshot));
  })
  .subscribe();

// Cleanup
return () => subscription.unsubscribe();

Alert fields from realtime:

interface ActiveAlert {
  id: string;
  alertType: ClinicalAlertType;
  severity: 'high' | 'medium' | 'low';
  action: 'BLOCK' | 'WARN' | 'INFO';
  alertTier: 0 | 1 | 2 | 3;
  message: string;
  messageEn?: string;
  targetItem: string;
  targetItemName?: string;
  requiresAcknowledgement: boolean;
  createdAt: string;
  acknowledgedAt?: string;
  ruleSource: 'backend_safety_engine' | 'frontend_gdl_engine';
  // Type-specific details: allergyDetail, interactionDetail, pregnancyDetail,
  // ageDetail, dosageLimitDetail, lactationDetail, renalDetail, etc.
}

4. Manual CDS Re-Evaluation

What: Trigger the backend to re-run ALL rules for a patient

import { useRequestCdsEvaluationMutation } from '@store/flow-notification/cdsAlertsApi';

const [requestEval] = useRequestCdsEvaluationMutation();
await requestEval({ encounterId, patientId, reason: 'user_requested' });

5. Emit Vitals Event (when saving vitals form)

What: Push vitals to backend for cross-domain CDS checks

import { useEmitVitalsEventMutation } from '@store/flow-notification/cdsAlertsApi';

const [emitVitals] = useEmitVitalsEventMutation();
await emitVitals({
  encounterId,
  patientId,
  components: [
    { type: 'HR', value: 72 },
    { type: 'BP_SYSTOLIC', value: 120 },
    { type: 'TEMP', value: 37.2 },
    { type: 'RR', value: 18 },
    { type: 'SPO2', value: 98 },
  ],
  effectiveAt: new Date().toISOString(),
  newsScore: 2,
});

6. Medication Setup — Drug Information Tab Fields

What: Pharmacist configures safety parameters per drug

Field Type UI Control Example
pregnancyCategory string Radio: A/B/C/D/X/N 'X'
pregnancySafetyAction string Select: Default/WARN/BLOCK 'BLOCK'
lactationCategory string Select: L1-L5 'L4'
lactationSafetyAction string Select: Default/WARN/BLOCK 'WARN'
ageRestrictionMin number TextField 12
ageRestrictionMax number TextField undefined
ageRestrictionUnit string Select: years/months 'years'
ageRestrictionAction string Select: WARN/BLOCK 'BLOCK'
isHighAlert boolean Checkbox true
highAlertCategory string Select dropdown 'Anticoagulant'
corollaryOrders string[] Multi-tag input ['INR monitoring']
dosageLimit array Existing UI — no changes

Save payload: Add all fields to your medication item create/update API call.


7. Redux Store Shape

CDS Alerts Slice

import { addCdsAlert, removeCdsAlert, acknowledgeCdsAlert, clearAllCdsAlerts } from '@store/flow-notification/cdsAlertsSlice';

// State shape:
{
  cdsAlerts: {
    alerts: CdsAlert[]  // unified: frontend GDL + backend cross-domain
  }
}

RTK Query API Endpoints

import {
  useInsertAlertsMutation,
  useEmitVitalsEventMutation,
  useEmitClinicalAlertMutation,
  useEvaluateGdlMutation,
  useRequestCdsEvaluationMutation,
} from '@store/flow-notification/cdsAlertsApi';

8. Order-Time Flow Pipeline (Interactive Checks)

import { runMedicationFlowPipeline } from '@store/flow-notification/TaskFlowPipeline';

// Runs these steps in sequence (stops if any returns false):
// 1. checkMedicationPanelStep — special panel drug UI
// 2. checkNEDReasonStep — NED reason selection
// 3. checkHeberBiovacStep — HeberBiovac dose adjustment
// 4. checkAllergyStep — allergy/interaction check (calls backend API)
// 5. checkDuplicateStep — duplicate order detection
// 6. checkMaxDaysOrderStep — max days validation

const passed = await runMedicationFlowPipeline(itemData, {
  confirm,        // dialog confirm function
  patientId,
  existingDrugs: orders,
});
if (!passed) return; // user cancelled or check blocked

9. Complete Type Definitions

type ClinicalAlertType =
  | 'ALLERGY_WARNING' | 'DRUG_INTERACTION'
  | 'DUPLICATE_ORDER' | 'DUPLICATE_CATEGORY' | 'DUPLICATE_OTHER_ORDER'
  | 'PREGNANCY_WARNING' | 'PREGNANCY_CONTRAINDICATION'
  | 'AGE_CONTRAINDICATION' | 'MAX_DOSE_EXCEEDED'
  | 'THERAPEUTIC_DUPLICATION' | 'HIGH_ALERT_MEDICATION'
  | 'LACTATION_WARNING' | 'LACTATION_CONTRAINDICATION'
  | 'COROLLARY_ORDER' | 'STALE_DATA_WARNING'
  | 'RENAL_DOSE_ADJUSTMENT' | 'CRITICAL_LAB_VALUE'
  | 'VITALS_HOLD_MEDICATION' | 'NEWS_MEWS_SCORE'
  | 'BEERS_CRITERIA' | 'DRUG_DIAGNOSIS'
  | 'CONTRAST_METFORMIN' | 'QTC_PROLONGATION'
  | 'ANTIBIOTIC_PROPHYLAXIS_TIMING'
  | 'SURGICAL_CHECKLIST_HARD_STOP';

type ClinicalAlertTier = 0 | 1 | 2 | 3;
type ClinicalAlertAction = 'BLOCK' | 'WARN' | 'INFO';
type ClinicalAlertSeverity = 'high' | 'medium' | 'low';

type OverrideReasonCode =
  | 'CLINICALLY_JUSTIFIED' | 'PATIENT_TOLERANT'
  | 'BENEFITS_OUTWEIGH_RISKS' | 'MONITORING_IN_PLACE'
  | 'DOSE_VERIFIED' | 'SENIOR_APPROVED' | 'OTHER';

10. File Index

File What It Does
store/flow-notification/cdsThunks.ts Redux thunk: calls edge function, falls back to local engine
store/flow-notification/cdsAlertsApi.ts RTK Query: evaluateGdl, emitVitals, emitAlert, insertAlerts, requestEval
store/flow-notification/cdsAlertsSlice.tsx Redux slice: unified alert store (add/remove/acknowledge/clear)
store/flow-notification/TaskFlowPipeline.tsx Sequential order-time safety pipeline
store/flow-notification/TaskFlowSteps.tsx Individual pipeline steps (NED, allergy, duplicate, etc.)
services/cds/cdsEngine.ts Local GDL engine (offline fallback)
context/MedBaseProvider.tsx Supabase/Medbase client for realtime subscriptions

11. Detailed Docs Index

Doc Scope
CLINICAL_SAFETY_MASTER_FRONTEND_BLUEPRINT.md All alert types, tier system, TypeScript types, UI rendering patterns
AGE_DOSAGE_SAFETY_FRONTEND_BLUEPRINT.md Age restriction + dosage limit setup UI + order-time handling
PREGNANCY_SAFETY_FRONTEND_BLUEPRINT.md Pregnancy category setup + order-time modal patterns
MEDICATION_USAGE_MULTI_SELECT_BLUEPRINT.md Multi-select medication usage UI
UNIFIED_CDS_EDGE_FUNCTION_DESIGN.md GDL engine architecture, evaluate_gdl action, emission points
FRONTEND_WORKFLOW_MASTER_PLAN.md Workflow transition system integration
FRONTEND_WORKFLOW_ROUTING_CONTRACT.md apiType + actionType → backend endpoint mapping
FRONTEND_DEPARTMENT_QUEUES_GUIDE.md Department queue tables + realtime enrichment
FRONTEND_API_INTEGRATION_GUIDE.md MixDrug allergy alert API
FRONTEND_IMPLEMENTATION_PLAN.md Compounding room allergy alerts
Ask Anything