# System Overview — Blazma LIMS

## 1. System Purpose

**Blazma** is a comprehensive **Laboratory Information Management System (LIMS)** designed for the Saudi Arabian healthcare market. It digitizes and automates the complete laboratory workflow from patient onboarding through test ordering, sample management, analysis, result reporting, and financial management.

The platform serves as both:
- A **B2C patient-facing platform** (web + mobile apps) where patients book lab tests
- A **B2B clinical operations platform** used by lab technicians, nurses, doctors, and lab managers

---

## 2. Business Domain

| Domain Area | Description |
|-------------|-------------|
| **Patient Management** | End-user (patient) registration, profiles, family members, insurance data |
| **Test Catalog** | Lab tests and packages organized by category, specimen, and type |
| **Order Management** | Full order lifecycle from cart → booking → sample collection → analysis → results |
| **Sample Tracking** | Barcode-based sample lifecycle: collection → processing → storage → disposal |
| **Quality Control (QC)** | Westgard Rules, QC lots, analyzer calibration, corrective actions |
| **Reporting** | PDF results (normal, smart, template-based, histopathology, genetics) |
| **Billing & Finance** | Invoices, credit notes, debit notes, wallet, ZATCA e-invoicing (B2C + B2B) |
| **Insurance** | NPHIES claims submission, approval workflows, insurance invoicing |
| **Inventory** | Warehouse management, purchase orders, reagent/kit tracking, vendor management |
| **Alerts & Notifications** | Multi-channel notifications (SMS, WhatsApp, Firebase Push, Email) with escalation |
| **AI Recommendations** | OpenAI-powered test recommendations based on patient symptoms/history |
| **White Label** | Multi-tenant white-labeling for partner labs |
| **Analytics & BI** | Sales forecasting, branch performance, TAT analysis, command center |

---

## 3. Major Features

### Core Clinical Features
- **Multi-location lab network** — manages multiple hospital/branch locations per profile
- **Home visit scheduling** — city-based home sample collection with time slots
- **Analyzer integration** — bidirectional communication with lab analyzers (LIS/ASTM)
- **HL7 messaging** — healthcare interoperability messaging
- **HESN Plus** — national health information network integration (Saudi MOH)
- **NPHIES** — national platform for health information exchange and insurance
- **Sample generation & storage** — specimen lifecycle tracking with storage units
- **Histopathology & Genetics** — specialized workflows for pathology and genetics testing

### Financial Features
- **ZATCA e-invoicing** — government-mandated electronic invoicing (B2C and B2B)
- **Multiple payment gateways** — Tamara (BNPL), PayFort, TAP, NearPay, Wallet, COD
- **Credit management** — credit limits, invoice enrollment, automatic billing
- **Insurance claims** — submission to insurance companies via NPHIES
- **Loyalty points** — point-based reward system

### Platform Features
- **Multi-tenant (PROFILE_ID)** — complete data isolation per lab profile
- **Role-based access control** — Spatie permissions with custom guards
- **Multi-language** — Arabic and English throughout (bilingual fields `_EN`/`_AR`)
- **White-label** — configurable branding per profile
- **API access** — RESTful API for mobile apps and third-party integrations
- **Telescope** — Laravel debugging and monitoring
- **Horizon** — Redis queue monitoring

---

## 4. Main Architecture Pattern

```
┌─────────────────────────────────────────────────────────────┐
│                    CLIENT LAYER                              │
│  Web Browser (Blade)  │  Mobile App (API)  │  Third-party   │
└─────────────────────────────────────────────────────────────┘
                              │
┌─────────────────────────────────────────────────────────────┐
│                  ROUTING LAYER (web.php)                     │
│          1,596 routes │ Middleware Guards                    │
└─────────────────────────────────────────────────────────────┘
                              │
┌─────────────────────────────────────────────────────────────┐
│               CONTROLLER LAYER (42 controllers)              │
│  Thin controllers — validate, delegate, return response      │
└─────────────────────────────────────────────────────────────┘
                              │
┌─────────────────────────────────────────────────────────────┐
│                SERVICE LAYER (107 services)                  │
│  ALL business logic lives here — never bypass this layer     │
└─────────────────────────────────────────────────────────────┘
                    │                    │
┌───────────────────┐    ┌───────────────────────────────────┐
│  MODEL LAYER      │    │  QUEUE LAYER (49 jobs, Redis)     │
│  431 Eloquent     │    │  Async: reports, notifications,   │
│  Models (MySQL)   │    │  ERP sync, HESN, ZATCA, SMS       │
└───────────────────┘    └───────────────────────────────────┘
         │
┌─────────────────────────────────────────────────────────────┐
│                   DATABASE (MySQL)                           │
│        320 tables │ UPPERCASE naming │ PROFILE_ID scoped     │
└─────────────────────────────────────────────────────────────┘
```

---

## 5. Technology Stack

| Layer | Technology |
|-------|-----------|
| **Framework** | Laravel 12.0 |
| **Language** | PHP 8.2+ |
| **Database** | MySQL (320 tables) |
| **Cache** | Redis (DB 1) |
| **Queue** | Redis + Laravel Horizon |
| **Session** | File-based |
| **File Storage** | AWS S3 (`blazma.com` bucket, `eu-west-1`) |
| **Email** | AWS SES (production), Log driver (dev) |
| **Push Notifications** | Firebase FCM |
| **PDF Generation** | DomPDF, Snappy (wkhtmltopdf), TCPDF, FPDI |
| **Barcode/QR** | milon/barcode, werneckbh/laravel-qr-code |
| **Excel** | Maatwebsite/Excel |
| **Frontend** | Blade templates + Vite |
| **Monitoring** | Laravel Telescope + Laravel Horizon |

---

## 6. Multi-Tenancy Model

The system uses **PROFILE_ID** as the primary tenant identifier.

- Each **PROFILE** represents a laboratory organization/company
- Under each PROFILE are multiple **HOSPITALs** (branches/locations)
- All data tables include `PROFILE_ID` for tenant isolation
- The `PROFILE` table stores per-tenant configuration (SMS credentials, payment keys, feature flags, branding)
- Environment variable `PROFILE_ID` (when set) switches to white-label mode for a specific tenant

---

## 7. User Types

| User Type | Table | Auth Method | Description |
|-----------|-------|-------------|-------------|
| **End User (Patient)** | `END_USER` | Mobile OTP / Email / Token | Patients booking tests |
| **System User (Staff)** | `SYSTEM_USER` | Username+Password / Token | Lab staff, technicians, doctors |
| **BM Admin** | `BM_ADMINS` | Email+Password (Spatie) | Platform super-administrators |
| **Operations** | `SYSTEM_USER` | OperationsAuth middleware | Internal operations team |
| **Terminal** | Custom token | TerminalAuth middleware | POS terminal access |
| **Ayenati** | Custom token | AyenatiTokenAuth middleware | Ayenati integration user |

---

## 8. Key Business Entities

```
PROFILE (Lab Organization)
  └── HOSPITAL (Branch/Location)
        └── LAB_CATEGORY (Test Category)
              └── LAB_CATEGORY_PACKAGE (Test/Package)
                    └── LAB_CATEGORY_PACKAGE_RESULT (Result parameters)

END_USER (Patient)
  └── END_USER_LAB_ORDER (Order)
        └── END_USER_LAB_ORDER_PACKAGE (Order line item / sample)
              ├── END_USER_LAB_ORDER_PACKAGE_RESULT (Test result values)
              ├── END_USER_LAB_ORDER_PACKAGE_TEMPLATE (Template-based result)
              ├── PAYMENTS (Payment transaction)
              └── END_USER_INVOICE (Invoice)

INSURANCE_CLAIMS → INSURANCE_INVOICES → NPHIES submission
ZATCA_INVOICE → Government e-invoice compliance
```
