# Business Flows — Blazma LIMS

## 1. Core Order-to-Result Flow

This is the primary workflow of the system.

```
┌──────────────────────────────────────────────────────────────────┐
│  STEP 1: Patient Onboarding                                       │
│  Patient registers (mobile OTP or email) → END_USER created       │
└──────────────────────────────────────────────────────────────────┘
                              ↓
┌──────────────────────────────────────────────────────────────────┐
│  STEP 2: Test Discovery & Cart                                    │
│  Patient browses test catalog → adds to END_USER_LAB_CART        │
│  Optional: fills questionnaire (if test requires it)             │
└──────────────────────────────────────────────────────────────────┘
                              ↓
┌──────────────────────────────────────────────────────────────────┐
│  STEP 3: Order Confirmation                                       │
│  Patient selects hospital/branch, date, time slot                │
│  Applies coupon (optional)                                       │
└──────────────────────────────────────────────────────────────────┘
                              ↓
┌──────────────────────────────────────────────────────────────────┐
│  STEP 4: Payment                                                  │
│  COD / Credit / Wallet / Tamara / PayFort / TAP / NearPay        │
│  PAYMENTS record created                                         │
└──────────────────────────────────────────────────────────────────┘
                              ↓
┌──────────────────────────────────────────────────────────────────┐
│  STEP 5: Order Created                                            │
│  END_USER_LAB_ORDER → END_USER_LAB_ORDER_PACKAGE (per test)      │
│  Barcode/label generated                                         │
│  Notification sent to patient (SMS + Push)                       │
│  JOBS DISPATCHED:                                                │
│   - ZatcaInvoice (if applicable)                                 │
│   - ERPInvoice (if ERP enabled)                                  │
│   - HESNPlusSendData (if HESN enabled)                           │
└──────────────────────────────────────────────────────────────────┘
                              ↓
┌──────────────────────────────────────────────────────────────────┐
│  STEP 6: Sample Collection                                       │
│  Lab staff collects sample (lab visit or home visit)             │
│  Status: COLLECTED                                               │
│  Sample stored in HOSPITAL_STORAGE_UNIT                          │
└──────────────────────────────────────────────────────────────────┘
                              ↓
┌──────────────────────────────────────────────────────────────────┐
│  STEP 7: Pre-analytical Processing                               │
│  Sample preparation, centrifugation, aliquoting                  │
│  Status: PRE_ANALYTICAL                                          │
└──────────────────────────────────────────────────────────────────┘
                              ↓
┌──────────────────────────────────────────────────────────────────┐
│  STEP 8: Analysis                                                 │
│  Sample sent to analyzer                                         │
│  Results received via ASTM/HL7 or manual entry                   │
│  END_USER_LAB_ORDER_PACKAGE_RESULT records created               │
│  Status: ANALYZED                                                │
│  QC validation applied (Westgard rules checked)                  │
└──────────────────────────────────────────────────────────────────┘
                              ↓
┌──────────────────────────────────────────────────────────────────┐
│  STEP 9: Result Validation                                       │
│  Lab supervisor validates results                                │
│  Reference ranges applied, abnormal flags set                    │
│  Status: VALIDATED                                               │
└──────────────────────────────────────────────────────────────────┘
                              ↓
┌──────────────────────────────────────────────────────────────────┐
│  STEP 10: Result Approval & Release                              │
│  Lab manager approves and releases results                       │
│  Status: RESULT_READY                                            │
│  JOBS DISPATCHED:                                                │
│   - SmartReportReady (generate PDF)                              │
│   - TemplateReportReady (if template-based)                      │
│   - NotificationFired (notify patient)                           │
│   - HESNUpdateResult (sync to HESN)                              │
│   - NphiesResultStatusUpdate (insurance update)                  │
│   - HisResultReady (sync to HIS)                                 │
└──────────────────────────────────────────────────────────────────┘
                              ↓
┌──────────────────────────────────────────────────────────────────┐
│  STEP 11: Patient Receives Results                               │
│  Patient notified via SMS, Push, WhatsApp, Email                 │
│  Patient views results on web/app                                │
│  PDF report downloadable                                         │
└──────────────────────────────────────────────────────────────────┘
```

---

## 2. Payment Processing Flow

### 2.1 COD (Cash on Delivery)
```
POST /cod_order → WebController::CODOrder → 
EndUserService::createOrder(payment_method=COD) → 
PAYMENTS record (status=PENDING) created → 
Order confirmed
```

### 2.2 Online Payment (Tamara / TAP / PayFort)
```
Patient initiates payment → 
PaymentService::initiateGatewayPayment → 
Redirect to gateway → 
Patient completes payment on gateway → 
Gateway sends callback/webhook → 
[TamaraController|TapController|PayfortController]::Feedback → 
PaymentService::confirmPayment → 
PAYMENTS updated (status=PAID) → 
Order activated → 
ZatcaInvoice job dispatched
```

### 2.3 Wallet Payment
```
EndUserService::checkWalletBalance → 
PaymentService::deductWallet → 
END_USER_WALLET record created (type=DEBIT) → 
END_USER.WALLET_AMOUNT updated → 
Order confirmed
```

---

## 3. Insurance Claim Flow (NPHIES)

```
Order created → 
InsuranceController::submitClaim → 
NphiesService::createClaim → 
INSURANCE_CLAIMS record created (status=PENDING) → 
API call to NPHIES → 
[Async] NphiesResultStatusUpdate job polls for response → 
INSURANCE_CLAIMS updated (status=APPROVED|REJECTED) → 
If APPROVED: INSURANCE_INVOICES created
```

---

## 4. ZATCA E-Invoice Flow

```
Payment confirmed → 
ZatcaInvoice job dispatched → 
Services/Zatca/ZatcaService::generateInvoice → 
XML invoice generated (cryptographically signed) → 
QR code generated (base64 encoded) → 
ZATCA API called for clearance/reporting → 
ZATCA_INVOICE record created with response → 
Invoice linked to END_USER_INVOICE
```

### B2B ZATCA Flow:
```
B2B order confirmed → 
ZatcaB2BInvoice job → 
Standard tax invoice generated → 
ZATCA clearance API called → 
ZATCA_B2B_INVOICE record created
```

---

## 5. HESN Plus Sync Flow

```
Order result ready → 
HESNPlusSendData job dispatched → 
HESNPlusService::authenticate (get/refresh token) → 
HESN_PLUS_TOKEN checked/refreshed → 
Patient data + results sent to HESN Plus API → 
Response stored
```

---

## 6. AI Recommendation Flow

```
Patient provides symptoms/height/weight → 
WebController::storeAIDetails → 
END_USER updated (AI_SYMPTOMS, AI_HEIGHT, AI_WEIGHT) → 
GenerateAiRecommendationJob dispatched → 
MyHealthAiService::generateRecommendations → 
OpenAI API called with patient context → 
END_USER_AI_RECOMMENDATION created → 
END_USER_AI_RECOMMENDATION_PACKAGES created → 
If AI_AUTO_APPROVE=1: auto-approved → 
Else: manual approval required → 
Patient notified → 
Tests shown in /recommended-tests
```

---

## 7. Alert & Escalation Flow

```
Trigger event occurs (e.g., QC failure, delayed result) → 
Alert system checks ALERT definitions → 
ALERT_PROCESSING record created (STATUS=0) → 
AlertDelivery job dispatched → 
Notifications sent to ALERT_USER_GROUP members → 
If not resolved within ESCALATION_HOURS → 
AlertEscalationEvent job dispatched → 
Escalation notifications sent → 
ALERT_PROCESSING.IS_ESCALATION_SEND = 1
```

---

## 8. Notification Flow

```
Triggering event occurs (order, result, etc.) → 
NOTIFICATION_EVENTS matched → 
Notification template loaded (NOTIFICATION table) → 
Message personalized → 
NotificationFired job dispatched → 
Multi-channel delivery:
  ├── FCM (if DEVICE_TOKENS exist) → NotificationPush job
  ├── SMS → SendSMSJob → SMSService → Unifonic/ConnectSaudi API
  ├── WhatsApp → SendWhatsAppJob → WhatsAppService → Provider API
  └── Email → SendEmailJob → EmailService → SMTP
END_USER_NOTIFICATION record created
```

---

## 9. ERP Integration Flow

```
Invoice created → 
ERPInvoice job dispatched → 
ERP/ERPService::postInvoice → 
Dynamic/SAP API called → 
Journal entry created in ERP

Payment received → 
ERPInvoiceClientCash job dispatched (cash) or 
ERPInvoiceClient job (credit) → 
ERP payment posting

Refund processed → 
ERPRefund/ERPRefundClient/ERPRefundClientCash jobs → 
ERP credit memo created

Stock movement → 
ERPMovement job → 
ERP inventory update
```

---

## 10. Analyzer Integration Flow

```
Lab staff creates worklist → 
PROFILE_ANALYZER_WORK_LIST populated → 
Analyzer file generated (ASTM/HL7 format per ANALYZER_TYPE_FILE) → 
Results file received from analyzer → 
LabController::ResultUnitSample or ResultUnitSample → 
Results parsed and mapped via ANALYZER_PACKAGE_REFERENCE → 
END_USER_LAB_ORDER_PACKAGE_RESULT created → 
QC validation run → 
Alert triggered if QC failure
```

---

## 11. Queue Jobs Reference

All jobs use **Redis queue** via Laravel Horizon.

| Job | Trigger | Purpose |
|-----|---------|---------|
| `AlertDelivery` | Alert event fired | Send alert notifications |
| `AlertEscalationEvent` | Timer: not resolved | Escalate unresolved alerts |
| `AlertTypeEvent` | Specific alert type | Type-specific alert handling |
| `ERPInvoice` | Invoice created | Post invoice to ERP |
| `ERPInvoiceClient` | Credit invoice | Post credit invoice to ERP |
| `ERPInvoiceClientCash` | Cash payment | Post cash payment to ERP |
| `ERPMovement` | Stock movement | Post movement to ERP |
| `ERPRefund` | Refund issued | Post refund to ERP |
| `ERPRefundClient` | Credit refund | Post credit refund to ERP |
| `ERPRefundClientCash` | Cash refund | Post cash refund to ERP |
| `ExportInvoicesJob` | Manual export | Export invoices to Excel |
| `GenerateAiRecommendationJob` | Patient AI request | Call OpenAI, generate recommendations |
| `GenerateInvoiceNumber` | Invoice created | Assign sequential invoice number |
| `HESNPlusSendData` | Order/result event | Send data to HESN Plus |
| `HESNReceive` | HESN callback | Receive HESN data |
| `HESNRequisition` | Order created | Send requisition to HESN |
| `HESNUpdateResult` | Result ready | Update result in HESN |
| `HisLog` | HIS event | Log HIS interactions |
| `HisResultReady` | Result ready | Notify HIS of result |
| `ImportPriceListToUsersJob` | Price list update | Apply price list to users |
| `LogData` | Various events | Async logging |
| `Mtc` | MTC event | MTC integration task |
| `NotificationClosed` | Order closed | Send closure notification |
| `NotificationFired` | Trigger event | Send triggered notification |
| `NotificationPromotionReservationFired` | Promo booking | Promotion notification |
| `NotificationPromotionResult` | Promo result | Promotion result notification |
| `NotificationPush` | FCM event | Firebase push notification |
| `NotificationRejection` | Sample rejected | Rejection notification |
| `NphiesResultStatusUpdate` | NPHIES callback | Update claim/result status |
| `ProcessBranchTotalsReportJob` | Scheduled | Cache branch totals |
| `PurchaseOrderJob` | PO event | Purchase order processing |
| `RevenueReportTest` | Manual | Revenue report generation |
| `SalesDetailsReport` | Manual | Sales detail report |
| `SampleDetailsReport` | Manual | Sample detail report |
| `SendEmailJob` | Email trigger | Send email via SMTP |
| `SendEmailNotificationJob` | Notification | Send notification email |
| `SendHL7InProcessMessageJob` | HL7 event | Send HL7 in-process message |
| `SendSMSJob` | SMS trigger | Send SMS via provider |
| `SendWhatsAppJob` | WhatsApp trigger | Send WhatsApp message |
| `SmartReportReady` | Result ready | Generate smart PDF report |
| `TatAnalysisReport` | Scheduled | TAT analysis report |
| `TemplateReportReady` | Result ready | Generate template PDF report |
| `ZatcaB2BCredit` | B2B credit note | B2B ZATCA credit note |
| `ZatcaB2BDebit` | B2B debit note | B2B ZATCA debit note |
| `ZatcaB2BInvoice` | B2B invoice | B2B ZATCA invoice submission |
| `ZatcaInvoice` | Payment confirmed | B2C ZATCA invoice submission |
| `ZatcaRefund` | Refund issued | ZATCA refund/credit note |

---

## 12. Console Commands (Artisan)

| Command | Purpose |
|---------|---------|
| `ai:update-docs` | Update AI knowledge base (custom command) |
| Standard Laravel commands | queue:work, horizon, cache:clear, etc. |

---

## 13. Scheduled Tasks

Managed via `routes/console.php`:
- Branch totals caching (frequent, feeds dashboard)
- HESN Plus token refresh (before expiry)
- Alert scheduling checks
- Payment status polling (for async gateways)
