# LIS Industry Standards Comparison Framework

## Research Sources

This framework is compiled from analysis of:
- **HL7 FHIR R5** specifications (ServiceRequest, DiagnosticReport, Specimen, Observation, Task)
- **OpenELIS Global 2** (open-source LIS, University of Washington / I-TECH)
- **Bika LIMS / SENAITE** (open-source LIMS, most detailed workflow definitions)
- **CLSI standards** (AUTO03, LIS02) for laboratory automation communications
- **ISO 15189** requirements for medical laboratory quality management
- **CAP** (College of American Pathologists) accreditation requirements
- **Industry knowledge** of Cerner PathNet, Epic Beaker, Sunquest/Clinisys, STARLIMS
- **Moon ERP LIS** current implementation (backend enums and models)

---

## 1. REQUEST-TO-REPORT WORKFLOW (Complete Lifecycle)

### Industry Standard: Three-Phase Model (ISO 15189)

```
PRE-EXAMINATION          EXAMINATION              POST-EXAMINATION
(Pre-Analytical)         (Analytical)             (Post-Analytical)
==================       =============            ================
Order entry              Sample processing        Result review
Patient prep             Analysis/Testing         Validation
Sample collection        QC verification          Reporting
Sample transport         Result calculation       Archival
Sample reception         Instrument interface     Sample storage/disposal
Sample accessioning
```

### Detailed Status Flow (Composite from All Systems)

```
1.  ORDER PLACED           Clinician/receptionist creates lab request
2.  ORDER ACCEPTED         Lab acknowledges the order
3.  SAMPLE COLLECTION DUE  Phlebotomist assigned, patient notified
4.  SAMPLE COLLECTED       Blood draw / specimen obtained, barcode printed
5.  SAMPLE IN TRANSIT      Sample moving from collection point to lab
6.  SAMPLE RECEIVED        Lab reception confirms receipt (accessioning)
7.  SAMPLE SORTED          Sample routed to correct section/bench
8.  SAMPLE PREPARED        Centrifugation, aliquoting if needed
9.  ANALYSIS ASSIGNED      Test assigned to worksheet/analyzer
10. ANALYSIS IN PROGRESS   Analyzer running or manual testing
11. QC CHECKED             Quality control reviewed for the run
12. RESULT ENTERED         Raw result captured (manual or instrument)
13. TECHNICAL VALIDATION   Technician reviews result (auto-verify or manual)
14. CLINICAL VALIDATION    Pathologist/supervisor reviews (if required)
15. RESULT APPROVED        Final sign-off
16. RESULT RELEASED        Report generated and sent to ordering clinician
17. SAMPLE STORED          Post-analysis storage with location tracking
18. SAMPLE DISPOSED        After retention period, sample destroyed
```

### System Comparison

| Phase | Cerner PathNet | Epic Beaker | SENAITE | OpenELIS | Moon ERP |
|-------|---------------|-------------|---------|----------|----------|
| Order Entry | CPOE integration | Orders module | Sample registration | Order entry | Request creation (pending) |
| Collection | Collection list | Collection worklist | Sampling workflow | Sample collection | Sample collected |
| Transport | Pneumatic tube tracking | Specimen tracking | Not built-in | Not built-in | Not explicit |
| Reception | Specimen receive | Specimen receipt | sample_received | Sample logged | Delivered/received |
| Sorting | Auto-routing rules | Work area routing | Partition/dispatch | Section assignment | Section processing |
| Analysis | Pending/In-progress | Testing | unassigned/assigned | NotStarted | In-progress |
| Tech Validation | Auto-verify rules | Auto-release rules | to_be_verified | TechnicalAcceptance | Validated (ResultStatus) |
| Clinical Validation | Pathologist review | Pathologist sign-off | verified | BiologistRejected/Finalized | Approved (ResultStatus) |
| Release | Result publish | Result release | published | Finalized | Released (ResultStatus) |
| Amendment | Result amendment | Result correction | invalidate/republish | correctedSincePatientReport | canReturn() |

---

## 2. TEST CANCELLATION FLOW

### Industry Standard

Professional LIS systems implement cancellation as a **parallel workflow** (not a status in the main chain), which is a critical architectural pattern.

#### Bika LIMS / SENAITE Model (Best Practice)
Cancellation is a **separate workflow** (`bika_cancellation_workflow`) that runs in parallel:
- States: `active` | `cancelled`
- Transitions: `cancel` (active -> cancelled), `reinstate` (cancelled -> active)
- Permission: `BIKA: Cancel and reinstate` (restricted to LabManager, Manager)
- Any object in any main-workflow state can be cancelled (it is a separate state variable `cancellation_state`)
- Cancelled items can be reinstated (un-cancelled) -- this is unique and important

#### Cancellation at Each Stage

| Stage | Can Cancel? | Who? | What Happens? |
|-------|------------|------|---------------|
| Before collection | YES | Receptionist, Lab Manager | Order voided, no charge |
| After collection, before processing | YES | Lab Manager, Supervisor | Sample may be disposed, partial charge possible |
| During processing | YES (with restrictions) | Lab Manager only | Current results discarded, reagent cost absorbed |
| After results entered but not released | YES (rare) | Lab Manager, Pathologist | Results voided, audit trail preserved |
| After results released | NO -- use Amendment | Pathologist, Lab Director | Cannot cancel; must amend/correct/retract |

#### Individual Test vs. Whole Request

- **Professional systems**: Allow cancellation of individual tests within a request (SENAITE: cancel individual analyses while request continues)
- **Request-level cancellation**: Only when ALL tests are cancelled
- **Partial cancellation**: Request status recalculates (e.g., if 3 of 5 tests cancelled, request remains active for remaining 2)
- **Moon ERP current**: `canCancel()` only at request level for Pending/SampleCollected states; no individual test cancellation in `RequestStatus`

#### Key Gap in Moon ERP
- No separate cancellation workflow (cancellation is a terminal state in RequestStatus)
- No reinstatement (undo cancel)
- No individual test-level cancellation (only whole request)
- InvestigationStatus has no Cancelled state (only Rejected)

---

## 3. TEST REJECTION vs RE-COLLECTION

### Industry Standard: Specimen Rejection Reasons

FHIR Specimen.status: `available` | `unavailable` | `unsatisfactory` | `entered-in-error`

#### Common Rejection Reasons (per CAP/CLSI)

**Pre-analytical rejection criteria:**
1. Hemolyzed sample
2. Lipemic sample
3. Clotted sample (for tests requiring anticoagulated blood)
4. Wrong tube type / anticoagulant
5. Insufficient quantity (QNS - Quantity Not Sufficient)
6. Unlabeled or mislabeled specimen
7. Specimen received past stability window
8. Wrong temperature during transport
9. Contaminated specimen
10. Wrong patient identification
11. Leaking container
12. Improper collection technique

#### Rejection Workflow (SENAITE Model)

```
Sample Received
  |
  v
[Lab Tech inspects sample]
  |
  +-- Quality OK --> Continue to analysis
  |
  +-- Quality NOT OK --> REJECT
       |
       +-- Rejection reason recorded
       +-- Rejection comment added
       +-- Sample marked as "rejected"
       +-- AUTOMATIC: New sample request generated (re-collection needed)
       +-- Notification sent to phlebotomist/collection point
       +-- Original sample retained (for audit) or disposed
```

#### Key Behaviors

| Question | Industry Standard | Moon ERP Current |
|----------|------------------|------------------|
| Does rejection create new sample auto? | YES (in SENAITE, Epic, Cerner) | NO |
| Is old result preserved? | YES (audit trail) | YES (ResultAuditLog exists) |
| Can rejected sample be reinstated? | NO (new sample must be collected) | NO (Rejected is terminal in InvestigationStatus) |
| Per-test or per-sample rejection? | BOTH (some tests may pass on same sample) | Per-investigation only (InvestigationStatus.Rejected) |
| Is rejection reason mandatory? | YES (configurable list) | Partial (notes field exists) |
| Does rejection affect billing? | Configurable (charge for collection, not analysis) | Not implemented |

#### SENAITE Analysis Rejection States
```
registered -> unassigned -> assigned -> [work] -> to_be_verified
                |              |                       |
                v              v                       v
            rejected       rejected                rejected
```
- Analysis can be rejected at: unassigned, assigned, or to_be_verified stages
- Rejected is a terminal state (no transitions out)
- Different from "retracted" (which means result was published then pulled back)

#### Moon ERP Gaps
- No structured rejection reason catalog (just notes)
- No automatic re-collection request generation
- SampleStatus.Rejected exists but InvestigationStatus only allows rejection at Received/InProgress
- No per-test rejection within a sample (all tests on a sample share the same sample status)

---

## 4. OUTSOURCING / SEND-OUT FLOW

### Industry Standard

Professional LIS systems handle send-outs through a **referral subsystem**.

#### OpenELIS Referral Statuses
```java
public enum ReferralStatus {
    CREATED, SENT, RECEIVED, FINISHED, CANCELED
}
```

#### SENAITE Dispatch Model
- Samples can be "dispatched" from received, to_be_verified, verified, or published states
- Dispatch creates a reference to external lab
- Results can come back and be integrated

#### Complete Send-Out Workflow

```
TEST MARKED AS EXTERNAL
  |
  v
SAMPLE COLLECTED (normally)
  |
  v
SAMPLE RECEIVED AT LAB
  |
  +-- Tests that can be done internally --> Kanban (normal flow)
  |
  +-- Tests to be sent out --> REFERRAL WORKFLOW
       |
       v
  REFERRAL CREATED (pending)
       |
       v
  SAMPLE PREPARED FOR SENDING
  (aliquot if needed, same barcode or new barcode)
       |
       v
  REFERRAL SENT (to external lab)
       |
       v
  RESULTS RECEIVED (manual entry / portal / HL7 interface)
       |
       v
  RESULTS REVIEWED (internal validation still required)
       |
       v
  REFERRAL COMPLETED
```

#### Types of Send-Out

| Type | Description | Barcode | In Kanban? |
|------|------------|---------|------------|
| Always-outsourced test | Test configured with default external lab | New barcode for external lab (internal barcode retained) | NO - goes directly to referral list |
| Send-out from kanban | Test started internally, then sent out mid-process | Same barcode (aliquot may get new) | REMOVED from kanban, moved to referral list |
| Reference lab confirmation | Result needs external confirmation | Aliquot with new barcode | Stays in kanban as "pending confirmation" |

#### How Results Come Back

| Method | Systems | Description |
|--------|---------|-------------|
| Manual entry | All systems | Technician types results from faxed/emailed report |
| External lab portal | Moon ERP, some commercial | External lab logs into portal and enters results |
| HL7/ASTM interface | Cerner, Epic, large systems | Automated electronic message exchange |
| FHIR API | Modern systems | RESTful API integration |
| File import (CSV/Excel) | Mid-range systems | Batch import of results |

#### Moon ERP Current Implementation

**Strengths:**
- `ReferralStatus`: Pending -> Sent -> InProgress -> Resulted -> Completed (good)
- `ExternalSampleStatus`: PendingSend -> Sent -> ResultReceived (good)
- External lab portal exists (testlab user can enter results)
- `ReferralDirection` enum exists (inbound/outbound distinction)

**Gaps:**
- No automatic aliquoting for send-outs
- No HL7/ASTM interface for automated result receipt
- No concept of "always-outsourced" test (test-level default external lab)
- Send-out mid-kanban flow needs verification
- No external lab performance tracking (TAT, accuracy)

---

## 5. USER ROLES AND PERMISSIONS

### Industry Standard Roles

#### Bika LIMS / SENAITE Roles (11 built-in)

| Role | Description |
|------|-------------|
| **Manager** | System administrator, full access |
| **LabManager** | Laboratory director/supervisor |
| **LabClerk** | Receptionist / registration clerk |
| **Analyst** | Lab technician (performs testing) |
| **Sampler** | Phlebotomist / sample collector |
| **Preserver** | Sample preparation specialist |
| **Verifier** | Verification of results (separate from analyst) |
| **Publisher** | Can publish/release final reports |
| **RegulatoryInspector** | Read-only audit access |
| **Client** | External client portal access |
| **Owner** | Object creator (automatic) |

#### Professional LIS Role Matrix

| Action | Receptionist | Phlebotomist | Lab Tech | Section Head | Pathologist | Lab Director | Billing | Quality |
|--------|-------------|-------------|----------|-------------|-------------|-------------|---------|---------|
| Create orders | YES | NO | NO | NO | NO | YES | NO | NO |
| Register patients | YES | NO | NO | NO | NO | NO | NO | NO |
| Collect samples | NO | YES | YES | YES | NO | NO | NO | NO |
| Receive samples | NO | NO | YES | YES | NO | NO | NO | NO |
| Enter results | NO | NO | YES | YES | NO | NO | NO | NO |
| Validate (technical) | NO | NO | YES* | YES | NO | NO | NO | NO |
| Validate (clinical) | NO | NO | NO | YES | YES | YES | NO | NO |
| Approve/release results | NO | NO | NO | NO | YES | YES | NO | NO |
| Cancel orders | YES** | NO | NO | YES | YES | YES | NO | NO |
| Cancel tests | NO | NO | NO | YES | NO | YES | NO | NO |
| Reject samples | NO | NO | YES | YES | NO | NO | NO | YES |
| Manage send-outs | NO | NO | NO | YES | NO | YES | NO | NO |
| View reports | YES (limited) | NO | YES (own section) | YES | YES | YES | YES | YES |
| Manage QC | NO | NO | YES | YES | NO | YES | NO | YES |
| Manage billing | NO | NO | NO | NO | NO | NO | YES | NO |
| Audit/compliance | NO | NO | NO | NO | NO | YES | NO | YES |
| Amend released results | NO | NO | NO | NO | YES | YES | NO | NO |

`*` = Only tests they did NOT perform (four-eyes principle)
`**` = Only before collection

#### Key Principles

1. **Separation of duties**: Person who enters results should NOT verify them (four-eyes / multi-verify)
2. **Section-based access**: Technicians see only their section's worklist
3. **Hierarchical override**: Director can do anything a subordinate can
4. **Audit trail**: Every action logged with user, timestamp, IP
5. **Time-based restrictions**: Some actions locked after certain window

#### Moon ERP Current
The LIS module uses the general Moon ERP roles/permissions system. Key permissions observed:
- `lis.investigations.approve`
- `lis.investigations.publish`
- General CRUD permissions per entity

**Gaps:**
- No dedicated phlebotomist role/screen
- No section-based access control (tech sees all sections)
- No four-eyes principle enforcement (same person can enter and validate)
- No verifier/publisher role separation

---

## 6. TEST STATUS LIFECYCLE (Complete)

### Industry Standard: Multi-Entity Status Model

Professional LIS systems track status at **four separate levels**:

#### Level 1: ORDER (Request) Status
```
FHIR ServiceRequest: draft -> active -> on-hold -> completed | revoked | entered-in-error
OpenELIS:            Entered -> Started -> Finished
SENAITE:             registered -> sample_due -> sample_received -> to_be_verified -> verified -> published
Moon ERP:            pending -> sample_collected -> in_progress -> partial_result -> completed | cancelled
```

#### Level 2: SAMPLE Status
```
FHIR Specimen:       available | unavailable | unsatisfactory | entered-in-error
OpenELIS:            Entered -> (Collected) -> Disposed | Rejected | Canceled
SENAITE:             registered -> to_be_sampled -> sample_due -> received -> (processing states)
Moon ERP:            pending -> collected -> delivered -> ready -> in_progress -> completed -> ready_for_result
                     Also: sent_out, rejected, received (backward compat)
```

#### Level 3: ANALYSIS/TEST Status
```
FHIR Task:           draft -> requested -> received -> accepted -> in-progress -> completed | failed | cancelled
OpenELIS:            NotStarted -> TechnicalAcceptance | TechnicalRejected -> BiologistRejected | Finalized
                     Also: SampleRejected, Canceled
SENAITE:             registered -> unassigned -> assigned -> to_be_verified -> verified -> published
                     Also: cancelled, retracted, rejected
Bika LIMS:           sample_registered -> to_be_sampled -> sampled -> sample_due -> sample_received ->
                     (attachment_due) -> to_be_verified -> verified -> published | retracted
Moon ERP:            (InvestigationStatus) pending -> collected -> received -> in_progress -> work_completed ->
                     results_added -> reviewed -> approved -> published | rejected
```

#### Level 4: RESULT Status
```
FHIR Observation:    registered -> preliminary -> final -> amended | corrected | cancelled | entered-in-error
OpenELIS:            (tracked via Analysis status + date fields)
SENAITE:             (tracked via Analysis workflow)
Moon ERP:            pending -> entered -> validated -> approved -> released
```

### Backward Transitions (Status Regression)

| System | Can Go Backward? | How? |
|--------|-----------------|------|
| SENAITE | YES | `retract` (to_be_verified -> retracted, creates retest), `rollback_to_receive`, `invalidate` |
| OpenELIS | LIMITED | TechnicalRejected / BiologistRejected can cause re-testing |
| Bika LIMS | YES | `retract` reverses verification, creates new analysis copy |
| FHIR | YES | amended, corrected statuses after final |
| Moon ERP | YES | `canReturn()` on ResultStatus, `previousStatus()` method |

### Key Pattern: Retract vs. Reject vs. Cancel

| Action | Meaning | When Used | Creates New? |
|--------|---------|-----------|-------------|
| **Cancel** | Order/test should not be done | Before or during processing | NO |
| **Reject** | Sample/result is unacceptable | During processing or validation | YES (retest/recollect) |
| **Retract** | Published result needs to be pulled back | After release | YES (new corrected result) |
| **Invalidate** | Entire report is invalid | After publishing | YES (new sample may be needed) |
| **Amend** | Correct a released result | After release | NO (modifies existing) |

---

## 7. RESULT VALIDATION WORKFLOW

### Industry Standard: Two-Tier Validation

```
RESULT ENTERED
     |
     v
[AUTO-VERIFICATION RULES CHECK]
     |
     +-- ALL rules pass --> AUTO-VERIFIED (skip to approved)
     |
     +-- ANY rule fails --> MANUAL REVIEW REQUIRED
          |
          v
     TECHNICAL VALIDATION (Lab Technician / Supervisor)
          |
          +-- Accept -->
          |               |
          +-- Reject --> Retest
          |
          v
     CLINICAL VALIDATION (Pathologist) [if required]
          |
          +-- Accept --> APPROVED
          |
          +-- Reject --> Back to tech validation
          |
          +-- Add comment --> APPROVED with interpretive comment
          |
          v
     RELEASED (Report sent)
```

### Auto-Verification Rules (Professional LIS)

Professional systems like Cerner PathNet and Epic Beaker implement extensive auto-verify rule engines:

| Rule Type | Description | Example |
|-----------|-------------|---------|
| **Range check** | Result within defined acceptable range | Glucose 50-500 mg/dL |
| **Critical value check** | Result NOT in critical range | Potassium < 2.5 or > 6.5 |
| **Delta check** | Change from previous result within threshold | Hemoglobin change < 3 g/dL from last |
| **Linearity check** | Result within instrument's linear range | CRP < 200 mg/L |
| **QC status check** | Section QC passed for this analyte | Westgard rules passed |
| **Sample integrity check** | No flags (hemolysis, lipemia, icterus) | HIL indices within limits |
| **Repeat check** | If repeated, results agree within tolerance | Duplicate within 10% CV |
| **Logical check** | Cross-analyte consistency | ALT > AST when both ordered |
| **Patient demographics** | Age/gender-appropriate result | PSA not auto-verified for females |
| **Instrument flags** | No error flags from analyzer | No "?", "*", or error codes |

### Delta Check Details

```
Current Result vs. Previous Result (same patient, same test)
  |
  +-- Absolute difference: |current - previous| <= threshold
  +-- Percentage difference: |current - previous| / previous * 100 <= threshold%
  +-- Rate of change: consider time between results
  |
  +-- PASS: No significant change, can auto-verify
  +-- FAIL: Significant change, requires manual review
       |
       +-- Possible causes: patient condition change, wrong patient, mislabeled sample
```

### Critical Value Alert Workflow

```
RESULT IDENTIFIED AS CRITICAL
     |
     v
[System generates immediate alert]
     |
     +-- On-screen popup to technician
     +-- SMS/notification to pathologist
     +-- Phone call to ordering physician (MUST be documented)
     |
     v
[Physician notified and acknowledgment recorded]
     |
     +-- Who was called
     +-- Who answered
     +-- Date/time of notification
     +-- Read-back confirmation
     |
     v
[Critical value flagged on report]
```

### Result Amendment After Release

```
RELEASED RESULT NEEDS CORRECTION
     |
     v
[Pathologist/Director initiates amendment]
     |
     +-- Original result preserved (never deleted)
     +-- Amendment reason documented
     +-- New result entered
     +-- Amendment flagged on report
     +-- Notification to ordering physician
     +-- Audit trail updated
     |
     v
[Amended report generated]
     +-- Shows both original and corrected values
     +-- Clearly marked as "AMENDED" or "CORRECTED"
     +-- Reason for amendment included
```

### Moon ERP Current

**Strengths:**
- Four-step validation: entered -> validated -> approved -> released
- `canReturn()` allows backward transition
- `previousStatus()` provides clear regression path
- `ResultAuditLog` model exists

**Gaps:**
- No auto-verification rule engine
- No delta check mechanism
- No critical value alert system
- No structured amendment workflow (just canReturn + re-enter)
- No multi-verify (SENAITE: `multi_verify` transition allows requiring N verifiers)
- No QC-linked validation (QcStatus exists but not connected to result validation)
- No four-eyes enforcement

---

## 8. SAMPLE TRACKING

### Industry Standard: Complete Sample Lifecycle

```
COLLECTION
  |-- Who collected (phlebotomist ID)
  |-- When collected (timestamp)
  |-- Where collected (location/ward)
  |-- How collected (venipuncture, capillary, etc.)
  |-- What collected (tube type, volume)
  |-- Patient consent recorded
  |
  v
TRANSPORT
  |-- Chain of custody log entry
  |-- Transport container/batch
  |-- Temperature monitoring (for sensitive specimens)
  |-- Courier/pneumatic tube tracking
  |
  v
RECEPTION / ACCESSIONING
  |-- Barcode scanned
  |-- Visual inspection (hemolysis, lipemia, clot, volume)
  |-- Accept or reject
  |-- Accession number assigned (if not pre-assigned)
  |-- Storage location recorded (temporary)
  |
  v
SORTING / ROUTING
  |-- Automated sorting (in large labs)
  |-- Manual distribution to sections
  |-- Each section receives and acknowledges
  |
  v
PREPARATION
  |-- Centrifugation (time, speed, duration logged)
  |-- Aliquoting (parent -> child samples)
  |   |-- Each aliquot gets sub-barcode
  |   |-- Volume tracked
  |   |-- Tests assigned to each aliquot
  |-- Decapping (automated or manual)
  |
  v
ANALYSIS
  |-- Loaded onto analyzer (position tracked)
  |-- Run ID / batch ID recorded
  |-- QC materials included in run
  |
  v
POST-ANALYSIS STORAGE
  |-- Storage location: freezer/fridge/room temp
  |-- Location: building > room > freezer > shelf > rack > box > position
  |-- Retention period based on test type / regulations
  |-- Temperature monitoring
  |
  v
DISPOSAL
  |-- After retention period expires
  |-- Disposal method recorded
  |-- Disposal date logged
  |-- Disposal authorized by
```

### Aliquoting (Sample Splitting)

| Feature | Professional LIS | Moon ERP |
|---------|-----------------|----------|
| Parent-child relationship | YES (tree structure) | NOT IMPLEMENTED |
| Auto-aliquot rules | YES (configurable per test) | NO |
| Volume tracking | YES (per aliquot) | NO |
| Sub-barcodes | YES (parent.01, parent.02) | NO |
| Split to different sections | YES | NO (section processing exists but no aliquoting) |
| Merge aliquots | Some systems | NO |

### Chain of Custody

| Feature | Professional LIS | Moon ERP |
|---------|-----------------|----------|
| Custody log | YES | YES (`LabSampleCustodyLog` model, `CustodyAction` enum) |
| Actions tracked | Collected, transferred, received, processed, stored, disposed | Created, collected, transferred, received, processed, stored, disposed |
| Location tracking | YES (granular) | PARTIAL (model exists) |
| Temperature monitoring | YES (IoT integration) | NO |
| Custody transfer sign-off | YES (dual signature) | NO |

### Storage Location Tracking

Professional systems track sample storage at:
```
Building > Floor > Room > Equipment (Freezer/Fridge) > Shelf > Rack > Box > Row > Column
```

Moon ERP: `LabRetentionPolicy` model exists, storage tracking not detailed.

---

## 9. COMPREHENSIVE GAP ANALYSIS: Moon ERP vs. Industry Standards

### SCORE CARD

| Area | Industry Standard Features | Moon ERP Has | Coverage |
|------|---------------------------|-------------|----------|
| **Request Lifecycle** | 8 statuses | 6 statuses | 75% |
| **Sample Lifecycle** | 10+ statuses | 10 statuses | 80% |
| **Investigation/Test Lifecycle** | 12+ statuses | 10 statuses | 75% |
| **Result Lifecycle** | 8 statuses (FHIR) | 5 statuses | 62% |
| **Cancellation** | Separate workflow, reinstate, per-test | Simple terminal status | 30% |
| **Rejection** | Structured reasons, auto-recollect, per-test | Basic rejection | 40% |
| **Send-out/Referral** | Full referral lifecycle | Good basic flow | 70% |
| **Auto-verification** | Rule engine (10+ rule types) | NOT IMPLEMENTED | 0% |
| **Delta checks** | Automatic comparison with history | NOT IMPLEMENTED | 0% |
| **Critical values** | Alert system with notification | NOT IMPLEMENTED | 0% |
| **Result amendment** | Structured amendment workflow | Basic return/re-enter | 35% |
| **Multi-verify** | Configurable N verifiers | NOT IMPLEMENTED | 0% |
| **Four-eyes principle** | Enforced separation | NOT IMPLEMENTED | 0% |
| **Aliquoting** | Parent-child sample splitting | NOT IMPLEMENTED | 0% |
| **Storage tracking** | Granular location | Basic model exists | 25% |
| **QC-linked validation** | QC must pass before results release | Models exist, not linked | 20% |
| **Chain of custody** | Full tracking | Good enum, basic model | 50% |
| **Section-based access** | Technician sees own section only | NOT IMPLEMENTED | 0% |
| **Role separation** | 11+ specialized roles | General ERP roles | 30% |
| **HL7/ASTM interface** | Instrument/system integration | Machine interface exists | 40% |
| **Audit trail** | Complete, immutable | ResultAuditLog exists | 50% |
| **Billing integration** | Per-test billing, insurance | Basic invoice system | 60% |
| **External lab portal** | Portal for result entry | YES, implemented | 80% |
| **QC (Westgard)** | Full Westgard rules, Levey-Jennings | Basic QC model | 30% |
| **Instrument flags (HIL)** | Hemolysis/Icterus/Lipemia indices | NOT IMPLEMENTED | 0% |

### Overall Estimated Coverage: ~40%

---

## 10. PRIORITY RECOMMENDATIONS

### P0 -- Critical (Required for Professional Lab Operation)

1. **Auto-verification rule engine** -- Without this, every result requires manual review (massive bottleneck)
2. **Critical value alerts** -- Patient safety requirement, CAP/CLIA mandatory
3. **Four-eyes principle** -- Person entering result must not be person verifying (regulatory requirement)
4. **Section-based access control** -- Hematology tech should not see biochemistry results

### P1 -- High (Industry Standard, Expected by Lab Directors)

5. **Delta checks** -- Catch mislabeled samples and dramatic patient changes
6. **Individual test cancellation** -- Not just whole request
7. **Structured rejection with auto-recollect** -- Current rejection is too basic
8. **Cancellation with reinstatement** -- Separate cancellation workflow
9. **Aliquoting** -- Essential for labs running multiple tests from one tube
10. **Multi-verify** -- Configurable: some tests need 1 verifier, some need 2

### P2 -- Medium (Differentiator, Competitive Advantage)

11. **Instrument flags (HIL indices)** -- Hemolysis/Icterus/Lipemia tracking
12. **Granular storage location tracking** -- Required for accreditation
13. **QC-linked result release** -- QC must pass before results can be validated
14. **Westgard rules engine** -- Industry-standard QC evaluation
15. **Result amendment workflow** -- Structured correction with dual reporting

### P3 -- Nice to Have (Advanced Features)

16. **HL7 v2 / FHIR integration** -- For interfacing with HIS/EMR
17. **Temperature monitoring integration** -- IoT for sample storage
18. **Reflex testing** -- Automatic add-on tests based on initial results
19. **Calculated fields** -- Formula-based result derivation
20. **TAT (Turnaround Time) monitoring** -- Real-time performance dashboards

---

## 11. REFERENCE: STATUS ENUM COMPARISON TABLE

### Request/Order Level

| Status | FHIR | OpenELIS | SENAITE | Bika | Moon ERP |
|--------|------|----------|---------|------|----------|
| Draft/Created | draft | - | - | - | - |
| Registered | - | Entered | sample_registered | sample_registered | pending |
| Active/Accepted | active | Started | sample_due | sample_due | - |
| Collection Due | - | - | to_be_sampled | to_be_sampled | - |
| Sample Collected | - | - | sampled | sampled | sample_collected |
| Received | - | - | sample_received | sample_received | - |
| In Progress | - | - | (via analysis states) | (via analysis states) | in_progress |
| Partial Result | - | - | - | - | partial_result |
| To Be Verified | - | - | to_be_verified | to_be_verified | - |
| Verified | - | - | verified | verified | - |
| Completed/Published | completed | Finished | published | published | completed |
| On Hold | on-hold | - | - | - | - |
| Cancelled/Revoked | revoked | - | cancelled | (separate workflow) | cancelled |
| Entered in Error | entered-in-error | - | - | - | - |
| Rejected | - | - | rejected | - | - |
| Dispatched | - | - | dispatched | - | - |
| Invalidated | - | - | invalidated | - | - |

### Analysis/Test Level

| Status | FHIR Observation | OpenELIS | SENAITE | Moon ERP (InvestigationStatus) |
|--------|-----------------|----------|---------|-------------------------------|
| Registered | registered | - | registered | pending |
| Collected | - | - | - | collected |
| Received | - | - | - | received |
| Unassigned | - | NotStarted | unassigned | - |
| Assigned | - | - | assigned | - |
| In Progress | - | - | - | in_progress |
| Work Completed | - | - | - | work_completed |
| Results Added | - | - | - | results_added |
| To Be Verified | preliminary | TechnicalAcceptance | to_be_verified | reviewed |
| Verified | - | Finalized | verified | approved |
| Published/Final | final | - | published | published |
| Cancelled | cancelled | Canceled | cancelled | - |
| Rejected | - | SampleRejected | rejected | rejected |
| Retracted | - | - | retracted | - |
| Amended | amended | - | - | - |
| Corrected | corrected | - | - | - |
| Entered in Error | entered-in-error | - | - | - |

### Result Level

| Status | FHIR | Moon ERP (ResultStatus) | Notes |
|--------|------|------------------------|-------|
| Pending | registered | pending | No result yet |
| Preliminary | preliminary | entered | Initial result captured |
| Technically Validated | - | validated | Tech review done |
| Clinically Validated | - | approved | Pathologist approved |
| Final/Released | final | released | Report sent |
| Amended | amended | (via canReturn) | Post-release correction |
| Corrected | corrected | (via canReturn) | Error correction |
| Cancelled | cancelled | - | Result voided |
| Entered in Error | entered-in-error | - | Should not exist |

---

## 12. ARCHITECTURAL RECOMMENDATIONS

### Key Design Patterns from Professional Systems

1. **Separate cancellation workflow** (Bika/SENAITE pattern): Run a parallel state machine for cancellation independent of the main workflow. This allows any entity in any state to be cancelled and potentially reinstated.

2. **Multi-entity status tracking**: Track status independently at Order, Sample, Analysis, and Result levels. Aggregate status at higher levels from lower-level entity statuses (e.g., Order status derived from its Analysis statuses).

3. **Worksheet/Worklist concept**: Group analyses into worksheets for batch processing, QC inclusion, and section-based work assignment. This is the primary "kanban" equivalent in professional LIS.

4. **Rule engine for auto-verification**: Implement a configurable rule engine (not hardcoded) that evaluates multiple criteria before auto-releasing results.

5. **Configurable workflow**: Allow lab administrators to configure which validation steps are required per test/section (some tests need pathologist review, others only tech validation).

6. **Event-driven status updates**: Use events/observers so that when all analyses in a request reach "verified," the request automatically transitions to "verified."

7. **Immutable audit log**: Every status change, result entry, and result modification must be logged with timestamp, user, IP, old value, new value, and reason.
