# Modules — Blazma LIMS

## Module Map

The system is organized into the following functional modules. Each module has a dedicated Service class (or group of services), Controller(s), and associated Models.

---

## 1. 🔐 Authentication & User Management

**Boundary**: User registration, login, OTP verification, profile management

### Sub-modules:
- **End User Auth** — Patient sign up/sign in via mobile OTP or email
- **System User Auth** — Staff login via username/password
- **BM Admin Auth** — Super-admin login via Spatie Permissions
- **Operations Auth** — Internal operations panel access

### Key Components:
| Component | File |
|-----------|------|
| Controller | `WebController` (patient auth methods) |
| Controller | `UserController` (staff management) |
| Service | `EndUserService` |
| Models | `END_USER`, `SYSTEM_USER`, `BM_ADMINS` |
| Tables | `END_USER`, `SYSTEM_USER`, `BM_ADMINS`, `MOBILE_NO_VERIFICATION`, `END_USER_EMAIL_VERIFICATION`, `DEVICE_TOKENS` |

### Key Routes:
- `POST /signup` — Patient registration
- `POST /email/signup` — Email-based registration
- `POST /verify_mobile_no` — OTP verification
- `GET /signin`, `GET /signout` — Session management

---

## 2. 📦 Test Catalog & Pricing

**Boundary**: Managing available tests, packages, pricing, reference ranges, and specimen types

### Key Components:
| Component | File |
|-----------|------|
| Service | `LabService` |
| Service | `SymbolsService` |
| Models | `LAB_CATEGORY_PACKAGE`, `LAB_CATEGORY`, `PROFILE_LAB_CATEGORY_PACKAGE` |
| Tables | `LAB_CATEGORY_PACKAGE`, `LAB_CATEGORY`, `LAB_CATEGORY_PACKAGE_RESULT`, `PROFILE_PRICE_LIST`, `PROFILE_REFERENCE_RANGE`, `SPECIMEN_TYPE` |

### Responsibilities:
- Manage test/package catalog (global and profile-specific)
- Configure prices per profile, per price list, per insurance company
- Manage reference ranges (normal/abnormal result boundaries)
- Configure specimen requirements and instructions
- Link tests to categories, platforms, and packages

---

## 3. 🛒 Order Management

**Boundary**: Patient ordering flow from cart to confirmed order

### Key Components:
| Component | File |
|-----------|------|
| Controller | `WebController` (cart, order, confirm) |
| Service | `EndUserService`, `LabService` |
| Models | `END_USER_LAB_CART`, `END_USER_LAB_ORDER`, `END_USER_LAB_ORDER_PACKAGE` |
| Tables | `END_USER_LAB_CART`, `END_USER_LAB_ORDER`, `END_USER_LAB_ORDER_PACKAGE` |

### Order Flow:
```
Cart → Select Hospital & Time → Confirm → Payment → Order Created → Sample Collection
```

### Key Routes:
- `GET/POST /cart` — Cart management
- `DELETE /cart/{id}` — Remove cart item
- `GET /confirm` — Order confirmation page
- `POST /order` — Create order
- `GET /orders` — View orders
- `GET /orders/{id}` — Order details

---

## 4. 🧪 Sample & Lab Operations

**Boundary**: Lab staff operations from sample reception through analysis and results

### Key Components:
| Component | File |
|-----------|------|
| Controller | `LabController` |
| Controller | `LdmController` |
| Service | `LabService` |
| Models | `END_USER_LAB_ORDER_PACKAGE`, `BATCH`, `PICKUP`, `SAMPLE_GENERATION` |

### Workflow Stages:
1. **Collection** — Sample collected from patient (home or lab)
2. **Reception** — Sample received at lab, barcode assigned
3. **Pre-analytical** — Sample preparation
4. **Analysis** — Analyzer processes sample (ASTM/HL7)
5. **Result Entry** — Results entered manually or via analyzer
6. **Validation** — Results validated by lab supervisor
7. **Approval** — Final approval for result release
8. **Result Ready** — Notification sent to patient

### Key Features:
- Barcode generation and scanning (Scandit integration)
- Batch grouping for analyzer runs
- Analyzer worklist management
- Sample storage tracking (HOSPITAL_STORAGE_UNIT)
- Sample disposal recording

---

## 5. 📊 Results & Reporting

**Boundary**: Generation and delivery of lab result reports

### Key Components:
| Component | File |
|-----------|------|
| Service | `NormalReportService` — Standard PDF report |
| Service | `NormalReportServiceV2` — V2 PDF report |
| Service | `SmartReportService` — AI-enhanced report |
| Service | `TemplateReportService` — Custom template report |
| Service | `TemplateReportV2Service` — V2 template report |
| Service | `IntegratedReportService` — Combined report |
| Service | `AiRecommendationReportService` — AI recommendation report |
| Jobs | `SmartReportReady`, `TemplateReportReady`, `NphiesResultStatusUpdate` |
| Tables | `END_USER_LAB_ORDER_PACKAGE_RESULT`, `END_USER_LAB_ORDER_PACKAGE_TEMPLATE`, `TEMPLATE`, `PROFILE_PROGRAMMABLE_COMMENT` |

### Report Types:
- **Normal Report** — Standard tabular result report
- **Smart Report** — Graphical, trend-based report
- **Template Report** — Custom HTML/PDF template (histopathology, genetics, culture)
- **QR Report** — QR code-accessible result

---

## 6. 💳 Payment Processing

**Boundary**: All payment methods and financial transaction management

### Key Components:
| Component | File |
|-----------|------|
| Controller | `PaymentController`, `PayfortController`, `TamaraController`, `TapController` |
| Service | `PaymentService` |
| Service | `TamaraService` — Tamara BNPL |
| Service | `PayfortService` — PayFort gateway |
| Service | `TapService` — TAP gateway |
| Service | `NearPayService` — NearPay POS |
| Tables | `PAYMENTS`, `ONLINE_PAYMENT_METHOD`, `PROFILE_ONLINE_PAYMENT_METHOD` |

### Payment Methods:
| Method | Type | Notes |
|--------|------|-------|
| **COD** | Cash on delivery | `POST /cod_order` |
| **Credit** | B2B credit | `POST /credit_order` |
| **Wallet** | Patient e-wallet | Balance deduction |
| **Tamara** | BNPL (Buy Now Pay Later) | Saudi BNPL provider |
| **PayFort** | Card payment | Amazon Payment Services |
| **TAP** | Card payment | TAP Payments |
| **NearPay** | POS terminal | Physical card terminal |
| **Bank Transfer** | Manual | ENABLE_BANK_TRANSFER flag |

---

## 7. 🏥 Insurance & Claims (NPHIES)

**Boundary**: Insurance claim submission, approval, and reconciliation

### Key Components:
| Component | File |
|-----------|------|
| Controller | `InsuranceController` |
| Service | `NphiesService` |
| Models | `INSURANCE_CLAIMS`, `INSURANCE_INVOICES`, `INSURANCE_COMPANY` |
| Jobs | `NphiesResultStatusUpdate` |

### Flow:
```
Order Created → Insurance Eligibility Check → 
Pre-authorization (if required) → 
Claim Submission to NPHIES → 
Approval Response → 
Invoice Generation → 
Reconciliation
```

---

## 8. 🧾 Invoicing & ZATCA E-Invoicing

**Boundary**: Invoice generation, credit/debit notes, ZATCA government compliance

### Key Components:
| Component | File |
|-----------|------|
| Controller | `InvoiceController`, `ZatcaController` |
| Service | `TaxService` |
| Services | `Services/Zatca/` — ZATCA-specific services |
| Jobs | `ZatcaInvoice`, `ZatcaRefund`, `ZatcaB2BInvoice`, `ZatcaB2BCredit`, `ZatcaB2BDebit` |
| Tables | `END_USER_INVOICE`, `ZATCA_INVOICE`, `ZATCA_B2B_INVOICE`, `END_USER_CREDIT_NOTE` |

### ZATCA Compliance:
- Generates cryptographically signed XML invoices
- QR code embedded in invoices (ZATCA standard)
- B2C invoices: simplified tax invoices
- B2B invoices: standard tax invoices with clearance
- Sequential invoice numbering per ZATCA requirements

---

## 9. 🔔 Notifications & Alerts

**Boundary**: Multi-channel notifications to patients and staff

### Key Components:
| Component | File |
|-----------|------|
| Controller | `NotificationController`, `AlertController` |
| Services | `Services/Notification/` |
| Service | `FCMService` — Firebase push |
| Service | `SMSService` — SMS (Unifonic/ConnectSaudi) |
| Service | `EmailService` — Email |
| Service | `WhatsAppService` — WhatsApp |
| Jobs | `NotificationFired`, `NotificationClosed`, `NotificationPush`, `NotificationRejection`, `AlertDelivery`, `AlertEscalationEvent`, `AlertTypeEvent`, `SendSMSJob`, `SendEmailJob`, `SendWhatsAppJob`, `SendEmailNotificationJob` |

### Notification Channels:
- Firebase FCM (push notifications to mobile apps)
- SMS (via Unifonic or ConnectSaudi, credentials in PROFILE)
- WhatsApp (via configurable WHATSAPP_PROVIDER)
- Email (via SMTP config in PROFILE)

### Alert System:
- Rule-based alerts (QC failures, delayed results, sample issues)
- Escalation chains (if not resolved within ESCALATION_HOURS)
- User group routing (ALERT_USER_GROUP)

---

## 10. 🤖 AI Recommendations

**Boundary**: AI-powered test recommendations based on patient symptoms

### Key Components:
| Component | File |
|-----------|------|
| Controller | `AiRecommendationController` |
| Service | `MyHealthAiService` |
| Job | `GenerateAiRecommendationJob` |
| Tables | `END_USER_AI_RECOMMENDATION`, `END_USER_AI_RECOMMENDATION_PACKAGES` |

### Flow:
```
Patient provides symptoms/data → 
OpenAI API called → 
Recommendations generated → 
(Auto-approve or Manual approval based on AI_AUTO_APPROVE flag) → 
Patient notified → Tests added to cart
```

---

## 11. 🔬 Quality Control (QC)

**Boundary**: Lab quality control via Westgard rules and QC lot management

### Key Components:
| Component | File |
|-----------|------|
| Service | `LabService` (QC section) |
| Tables | `QC`, `QC_LOT`, `QC_RESULT`, `QC_STATISTIC`, `QC_WESTGARD_RULE`, `CORRECTIVE_ACTIONS` |

### Features:
- QC lot and level management
- Multi-rule Westgard violation detection
- Control charts (Levey-Jennings)
- Corrective action tracking
- Automatic QC alerts

---

## 12. 🏪 Inventory / Warehouse

**Boundary**: Reagent, kit, and consumable inventory management

### Key Components:
| Component | File |
|-----------|------|
| Controller | `WarehouseController` |
| Service | `WarehouseService` |
| Tables | `PROFILE_INV_ITEM`, `PROFILE_PURCHASE_ORDER`, `PROFILE_PURCHASE_RECEIVED`, `PROFILE_INV_MAIN_TRANSACTION` |

### Features:
- Item catalog with type classification
- Vendor/supplier management
- Purchase requests → Purchase orders → Goods received
- Stock movements (in/out/adjustment)
- Kit composition management
- Test-reagent consumption tracking (items auto-consumed when tests run)
- PO payment tracking

---

## 13. 🏥 HESN Plus Integration

**Boundary**: Saudi MOH national health platform data exchange

### Key Components:
| Component | File |
|-----------|------|
| Service | `HESNPlusService` |
| Service | `HESNService` (legacy) |
| Jobs | `HESNPlusSendData`, `HESNReceive`, `HESNRequisition`, `HESNUpdateResult` |
| Tables | `HESN_PLUS_TOKEN`, `HESN_PLUS_DIRECTORATE`, `PROFILE_HESN` |

---

## 14. 🔌 External System Integrations

**Boundary**: Third-party and government system integrations

| Integration | Service | Jobs | Purpose |
|-------------|---------|------|---------|
| **Ayenati** | `AyenatiService` | — | Ayenati EMR system |
| **HL7** | `HL7Service` | `SendHL7InProcessMessageJob` | Healthcare interoperability |
| **LDM** | `LdmService` | — | LDM laboratory system |
| **LiveHealth** | `LivehealthService` | — | LiveHealth EMR |
| **ERP** | `Services/ERP/` | `ERPInvoice*`, `ERPRefund*`, `ERPMovement*` | ERP (Dynamic/SAP) sync |
| **Lean API** | `LeanAPIService` | — | Saudi health ID & practitioner |

---

## 15. 📈 Sales & Analytics

**Boundary**: Financial reporting and business intelligence

### Key Components:
| Component | File |
|-----------|------|
| Controller | `SalesController`, `NewSalesController`, `BranchIncomeController`, `SalesForecastController` |
| Service | `SalesService`, `NewSalesService`, `BranchIncomeService` |
| Jobs | `SalesDetailsReport`, `TatAnalysisReport`, `RevenueReportTest`, `ProcessBranchTotalsReportJob` |

### Reports Available:
- Sales by branch, period, test, insurance company
- TAT (Turn-Around-Time) analysis
- Branch income reports
- Sales forecasting with targets
- Revenue reports

---

## 16. 🏷️ White Label / Multi-tenant

**Boundary**: Per-tenant branding and configuration

### Key Components:
| Component | File |
|-----------|------|
| Controller | `WhitelabelController` |
| Tables | `WHITE_LABEL_*`, `PROFILE` (branding columns) |

### Features:
- Custom logos, colors, fonts
- Custom landing pages
- Social media links
- App store links
- Featured services and statistics

---

## 17. 🎁 Loyalty Program

**Boundary**: Point-based rewards for patient engagement

### Key Components:
| Component | File |
|-----------|------|
| Controller | `LoyaltyController` |
| Tables | `END_USER_POINT`, `PROFILE_LOYALTY_TEST` |

### Configuration (in PROFILE):
- `ENABLE_LOYALTY` — feature flag
- `POINT_EARN_PER_AMOUNT` — points earned per SAR
- `VALUE_OF_POINT` — SAR value of each point

---

## 18. 🩺 Diabetic Dashboard

**Boundary**: Specialized tracking for diabetic patient clinical data

### Key Components:
| Component | File |
|-----------|------|
| Controller | `DiabeticDashboardController` |
| Tables | `diabetic_patient_visits`, `diabetic_*` (10 lookup tables) |

---

## 19. 🧬 Genetics & Histopathology

**Boundary**: Specialized lab workflows for genetics and pathology

### Key Components:
| Component | File |
|-----------|------|
| Controller | `GeneticsExtractionController` |
| Tables | `GENETICS_BATCHES`, `HISTOPATHOLOGY_BATCH` |

---

## 20. 🖥️ Command Center (Operations)

**Boundary**: Real-time operational dashboard for lab managers

### Key Components:
| Component | File |
|-----------|------|
| Controller | `CommandCenterController` |
| Service | `CommandCenterService` |

### Metrics Provided:
- Processing branch statistics
- Total sample stats
- Results stats
- TAT stats
- Rejection rate
- Critical result rate
- QC stats
- Best/worst performing tests
