Skip to main content

Orders Service — Application Logic

Status: populated Owner: TBD Last updated: 2026-04-18 Companion: Service Template

1. Commands

CommandUse case classKey stepsRoles
CreateOrderCommandCreateOrderUseCaseValidate patient/encounter, resolve order code, run CDS checks (allergy, drug-drug, duplicate, dosing), persist draft order, emit order.createdCLINICIAN, PRESCRIBER
ActivateOrderCommandActivateOrderUseCaseCheck for unacknowledged hard-stops, require acknowledgement for warnings, transition to active, emit order.activatedCLINICIAN, PRESCRIBER
AcknowledgeCdsAlertCommandAcknowledgeCdsAlertUseCaseRecord clinician acknowledgement with reason on CDS alert; required before activation when warning presentCLINICIAN, PRESCRIBER
HoldOrderCommandHoldOrderUseCaseTransition activeon-hold with reason; emit order.on-holdCLINICIAN
ResumeOrderCommandResumeOrderUseCaseTransition on-holdactive; re-run CDS if medication; emit order.activatedCLINICIAN
CancelOrderCommandCancelOrderUseCaseTransition to cancelled (from draft or active); reason required; emit order.cancelledCLINICIAN, PRESCRIBER, NURSE (own type)
CompleteOrderCommandCompleteOrderUseCaseCalled by fulfilment service via event; transition to completed; emit order.completedSystem (event-driven)
CorrectOrderCommandCorrectOrderUseCaseTransition to entered-in-error; audit previous state; emit order.correctedCLINICIAN, ADMIN
CreateOrderSetCommandCreateOrderSetUseCasePersist OrderSet template with order templatesCLINICIAN, ADMIN
InstantiateOrderSetCommandInstantiateOrderSetUseCaseCreate one draft Order per template; run CDS batch; return array of order IDsCLINICIAN, PRESCRIBER
CreateReferralCommandCreateReferralUseCaseCreate referral order type; validate referral detail; on activation emit referral.createdCLINICIAN
UpdateReferralStatusCommandUpdateReferralStatusUseCaseAccept inbound referral acceptance/rejection from receiving facilityCLINICIAN, ADMIN

2. Queries

QueryUse case classDescriptionRoles
GetOrderByIdQueryGetOrderUseCaseSingle order by orderIdCLINICIAN, NURSE, PATIENT (own)
ListPatientOrdersQueryListPatientOrdersUseCaseAll orders for a patient; filterable by type, status, date range, encounterCLINICIAN, NURSE, PATIENT (own)
ListEncounterOrdersQueryListEncounterOrdersUseCaseAll orders for a specific encounterCLINICIAN, NURSE
GetOrderSetByIdQueryGetOrderSetUseCaseSingle order set templateCLINICIAN
ListOrderSetsQueryListOrderSetsUseCaseAll order set templates for tenant; filterable by type, nameCLINICIAN, ADMIN
GetCdsAlertsForOrderQueryGetCdsAlertsUseCaseAll CDS alerts attached to an orderCLINICIAN
GetReferralDetailQueryGetReferralDetailUseCaseFull referral details including tracking statusCLINICIAN, PATIENT (own)
ListPendingReferralsQueryListPendingReferralsUseCaseAll active referrals awaiting schedulingCLINICIAN, ADMIN

3. Sequence Diagrams

3.1 Create and Activate Medication Order

Clinician → API: POST /v1/orders { orderType: "medication", patientId, encounterId, medicationDetail, ... }
API → CreateOrderUseCase: execute(command)
CreateOrderUseCase → PatientPort: assertPatientActive(patientId)
CreateOrderUseCase → EncounterPort: assertEncounterActive(encounterId)
CreateOrderUseCase → CdsPort: checkAllergy(patientId, medicationCode)
CreateOrderUseCase → CdsPort: checkDrugInteraction(patientId, medicationCode, activeMedications)
CreateOrderUseCase → CdsPort: checkDuplicate(patientId, medicationCode)
CreateOrderUseCase → CdsPort: checkDosing(medicationDetail)
alt hard-stop returned
CreateOrderUseCase → API: persist draft with hard-stop alert; return 201 with cdsAlerts[{level:"hard-stop"}]
end
alt warning returned
CreateOrderUseCase → API: persist draft with warning alert; return 201 with cdsAlerts[{level:"warning"}]
end
CreateOrderUseCase → OrderRepository: save(draft order) [+ outbox entry in transaction]
OutboxRelay → NATS: clinical.orders.{patientId} → order.created

Clinician → API: POST /v1/orders/:id/activate
API → ActivateOrderUseCase: execute
alt unacknowledged hard-stop
ActivateOrderUseCase → API: throw CdsHardStopError (422)
end
alt warning not acknowledged
ActivateOrderUseCase → API: throw CdsWarningUnacknowledgedError (422)
end
ActivateOrderUseCase → OrderRepository: save(active order) [+ outbox]
OutboxRelay → NATS: clinical.orders.{patientId} → order.activated
NATS → pharmacy-service (medication), laboratory-service (lab), etc.
API → Clinician: 200 { status: "active" }

3.2 Referral Creation

Clinician → API: POST /v1/orders { orderType: "referral", referralDetail: { referToFacilityId, specialty, urgency } }
API → CreateReferralUseCase: execute
CreateReferralUseCase → PatientPort: assertPatientActive
CreateReferralUseCase → OrderRepository: save(draft) [+ outbox]
Clinician → API: POST /v1/orders/:id/activate
ActivateOrderUseCase → OrderRepository: save(active) [+ outbox: referral.created]
OutboxRelay → NATS: clinical.orders.{patientId} → referral.created
NATS → scheduling-service: proposed appointment creation
NATS → communication-service: referral notification

3.3 Order Set Instantiation

Clinician → API: POST /v1/order-sets/:setId/instantiate { patientId, encounterId }
API → InstantiateOrderSetUseCase: execute
InstantiateOrderSetUseCase → OrderSetRepository: loadTemplate(setId)
InstantiateOrderSetUseCase → [for each template entry]:
CreateOrderUseCase: execute(derived command)
CDS checks run per order
OrderRepository: save(draft order)
API → Clinician: 201 { orderIds: ["ord_01...", "ord_02...", ...], cdsAlerts: [...] }

4. Ports (Hexagonal Boundaries)

Port nameDirectionPurpose
OrderRepositoryPortOutboundPersist and query Order aggregates
OrderSetRepositoryPortOutboundPersist and query OrderSet templates
CdsPortOutboundCall CDS engine for allergy, interaction, duplicate, dosing checks
PatientPortOutboundAssert patient active/not deceased
EncounterPortOutboundAssert encounter active
AllergyPortOutboundRetrieve patient allergy list for CDS
OutboxPortOutboundWrite events to outbox atomically
EventPublisherPortOutboundNATS JetStream publisher (used by outbox relay)

5. CDS Check Details

CheckTriggerHard-stop or warning
Allergy checkMedication, procedure ordersHard-stop if confirmed allergy; warning if intolerance
Drug-drug interactionMedication ordersHard-stop for contraindicated combinations; warning for monitored combinations
Duplicate order checkAll order typesWarning if active identical order exists for patient within 24h
Dosing range checkMedication ordersHard-stop if dose exceeds maximum safe dose per weight; warning if above recommended

6. Error Handling

ErrorHTTP codeDomain code
Patient not found404PATIENT_NOT_FOUND
Patient deceased422PATIENT_DECEASED
Encounter not found or inactive422ENCOUNTER_INACTIVE
CDS hard-stop blocks activation422CDS_HARD_STOP
CDS warning not acknowledged422CDS_WARNING_UNACKNOWLEDGED
Order in terminal state409ORDER_TERMINAL_STATE
Optimistic lock conflict409OPTIMISTIC_LOCK_CONFLICT
Duplicate mutation409DUPLICATE_MUTATION
Module not entitled403MODULE_NOT_ENTITLED