# Architecture — Blazma LIMS

## 1. Framework & Language

- **Laravel 12.0** (PHP 8.2+)
- **PSR-4 autoloading** with `App\` namespace
- **Service Container** (IoC) — all services injected via constructor
- **Eloquent ORM** — 431 models, UPPERCASE table names
- **Blade** templating engine for server-side rendering
- **Vite** for frontend asset bundling

---

## 2. Application Layers

```
app/
├── Http/
│   ├── Controllers/          # 42 controllers (thin, delegate to services)
│   ├── Middleware/           # 13 middleware classes
│   └── Requests/             # Form request validation classes
├── Models/                   # 431 Eloquent models
│   └── Base/                 # Base model classes (extended by child models)
├── Services/                 # 107 service classes (ALL business logic)
│   ├── Alert/
│   ├── Ayenati/
│   ├── ERP/
│   ├── Master/               # Core lab domain services
│   ├── Metadata/
│   ├── Notification/
│   └── Zatca/
├── Jobs/                     # 49 async queue jobs
├── Console/
│   └── Commands/             # Artisan commands (20+)
├── Exports/                  # Excel export classes (20+)
├── Imports/                  # Excel import classes (10)
└── helpers.php               # Global helper functions (autoloaded)
```

---

## 3. Request Lifecycle

```
HTTP Request
    │
    ▼
Bootstrap (public/index.php)
    │
    ▼
Middleware Stack (CORS → Auth → NormalizeSlashes → Guard-specific)
    │
    ▼
Router (routes/web.php — 1,596 routes)
    │
    ▼
Controller (thin — validates, delegates, returns view/json)
    │
    ▼
Service Class (all business logic, DB operations)
    │
    ├──► Eloquent Models (DB queries)
    │         └──► MySQL (320 tables)
    │
    ├──► Queue Jobs (async dispatch to Redis)
    │         └──► Job Worker processes async
    │
    └──► External APIs (payment, HESN, NPHIES, etc.)
```

---

## 4. Controllers — Responsibilities & Locations

All controllers live in `app/Http/Controllers/`. Controllers must:
- Validate input (use `$request->validate()` or FormRequest)
- Call the appropriate Service method
- Return view or JSON response
- **Never** contain business logic directly

| Controller | Responsibility |
|-----------|---------------|
| `WebController` | Main patient-facing web app (booking, cart, orders, auth) |
| `LabController` | Lab operations (samples, results, analyzer integration) |
| `InvoiceController` | Invoice generation, ZATCA, credit/debit notes |
| `InsuranceController` | Insurance claims, NPHIES, approvals |
| `PaymentController` | Payment processing coordination |
| `PayfortController` | PayFort gateway callback handling |
| `TamaraController` | Tamara BNPL callback handling |
| `TapController` | TAP gateway callback handling |
| `SalesController` | Sales reports and dashboards |
| `NewSalesController` | New sales workflow |
| `BranchIncomeController` | Branch financial reports |
| `WarehouseController` | Inventory management |
| `NotificationController` | Notification management |
| `AlertController` | Alert system management |
| `AiRecommendationController` | AI test recommendation engine |
| `UserController` | System user management |
| `MetadataController` | Lookup data (countries, genders, etc.) |
| `MyHealthController` | Patient health scoring |
| `CommandCenterController` | Operations dashboard & stats |
| `QuestionnnaireController` | Patient questionnaires |
| `ZatcaController` | ZATCA compliance & e-invoicing |
| `AyenatiController` | Ayenati system integration |
| `HlController` | HL7 messaging |
| `LdmController` | LDM integration |
| `LiveHealthController` | LiveHealth integration |
| `ErpController` | ERP synchronization |
| `WhitelabelController` | White-label config |
| `SalesForecastController` | Sales forecasting |
| `LoyaltyController` | Loyalty points management |
| `FitTestController` | Fitness test workflows |
| `GeneticsExtractionController` | Genetics test workflows |
| `DiabeticDashboardController` | Diabetic patient tracking |
| `TerminalController` | POS terminal interface |
| `OperationsController` | Internal operations panel |
| `ApiController` | General mobile API endpoints |
| `WebhookController` | External webhook handlers |
| `V2/*` | Version 2 controllers (new API format) |
| `Operations/*` | Operations-specific controllers |

---

## 5. Service Layer — Structure

All business logic MUST live in `app/Services/`. Services are injected via constructor.

### Core Services

| Service | Responsibility |
|---------|---------------|
| `LabService` | Core lab operations, orders, samples, results |
| `EndUserService` | Patient CRUD, authentication, cart, ordering |
| `PaymentService` | Payment coordination, gateway selection, refunds |
| `TamaraService` | Tamara BNPL integration |
| `PayfortService` | PayFort payment gateway |
| `TapService` | TAP payment gateway |
| `NearPayService` | NearPay POS terminal |
| `NphiesService` | NPHIES insurance claims |
| `HESNPlusService` | HESN Plus national health data sync |
| `HESNService` | HESN legacy integration |
| `AyenatiService` | Ayenati integration |
| `HL7Service` | HL7 messaging |
| `LdmService` | LDM system integration |
| `LivehealthService` | LiveHealth EMR integration |
| `EmailService` | Email sending |
| `SMSService` | SMS sending (Unifonic / ConnectSaudi) |
| `WhatsAppService` | WhatsApp messaging |
| `FCMService` | Firebase push notifications |
| `FCMService` | Firebase Cloud Messaging |
| `FileService` | File upload, S3, image processing |
| `QRService` | QR code generation |
| `TaxService` | VAT/tax calculation |
| `LogService` | System logging |
| `SalesService` | Sales data aggregation |
| `NewSalesService` | New sales reporting |
| `BranchIncomeService` | Branch income reports |
| `WarehouseService` | Inventory / warehouse logic |
| `NormalReportService` | Standard PDF result report generation |
| `NormalReportServiceV2` | V2 result report generation |
| `SmartReportService` | Smart/AI-enhanced report generation |
| `TemplateReportService` | Template-based report generation |
| `TemplateReportV2Service` | V2 template report |
| `IntegratedReportService` | Combined/integrated report |
| `AiRecommendationReportService` | AI recommendation report |
| `MyHealthService` | Patient health score calculations |
| `MyHealthAiService` | AI health analysis |
| `LanguageService` | Localization / language switching |
| `SymbolsService` | Lab reference symbols management |
| `LinkService` | Deeplink management |
| `ApiService` | Mobile API helpers |
| `CommandCenterService` | Operations stats aggregation |
| `TerminalService` | POS terminal logic |
| `LeanAPIService` | Lean health API (practitioner / health ID) |
| `MTCService` | MTC integration |
| `FlagService` | Feature flag system |
| `MetadataService(s)` | Various metadata services in `Services/Metadata/` |
| `Alert/*` | Alert system services in `Services/Alert/` |
| `ERP/*` | ERP integration services in `Services/ERP/` |
| `Notification/*` | Notification services in `Services/Notification/` |
| `Zatca/*` | ZATCA e-invoice services in `Services/Zatca/` |

---

## 6. Middleware Stack

| Middleware | Purpose | Applied To |
|-----------|---------|-----------|
| `WebAuth` | End-user session authentication | Patient web routes |
| `AccessTokenValidation` | Bearer token validation for API | API routes |
| `AccessTokenOptional` | Optional bearer token (public+auth) | Mixed routes |
| `OperationsAuth` | Operations panel authentication + permissions | Operations routes |
| `TerminalAuth` | POS terminal token validation | Terminal routes |
| `AyenatiTokenAuth` | Ayenati system token validation | Ayenati routes |
| `LdmAuth` | LDM system authentication | LDM routes |
| `MetaDataAuth` | Metadata API authentication | Metadata routes |
| `NupcoAuth` | NUPCO authentication | NUPCO routes |
| `CorsMiddleware` | CORS headers for cross-origin requests | API routes |
| `NormalizeSlashes` | Normalize URL slashes | All routes |
| `RedirectToPayment` | Payment flow redirection | Payment routes |
| `Authenticate` | Laravel default auth | Admin routes |

---

## 7. Key Design Patterns

### Multi-Tenancy via PROFILE_ID
Every query that returns data must scope by `PROFILE_ID`. Example:
```php
// CORRECT
LAB_CATEGORY_PACKAGE::where('PROFILE_ID', $profileId)->get();

// WRONG - returns data for all tenants
LAB_CATEGORY_PACKAGE::all();
```

### Service Injection
```php
class LabController extends Controller
{
    public function __construct(private LabService $labService) {}

    public function someAction(Request $request)
    {
        $result = $this->labService->doSomething($request->validated());
        return response()->json($result);
    }
}
```

### Feature Flags (PROFILE table)
Many features are toggled per profile via boolean columns in `PROFILE`:
- `ENABLE_QC` — Quality Control module
- `ENABLE_WAREHOUSE` — Warehouse/inventory module
- `ENABLE_HISTOPATHOLOGY` — Histopathology module
- `ENABLE_GENETICS` — Genetics module
- `ENABLE_AI_RECOMMENDATION` — AI test recommendations
- `ENABLE_NEARPAY` — NearPay POS integration
- `ENABLE_DIABETIC` — Diabetic dashboard
- `ENABLE_LOYALTY` — Loyalty points system
- `ENABLE_SERIAL_BARCODE` — Serial barcode generation
- `ENABLE_NORMAL_REPORT_V2` — New report format
- `IS_LEAN_API_ENABLED` — Lean Health API
- etc. (50+ feature flags in PROFILE table)

### Queue Pattern
```php
// Always dispatch jobs for heavy/external operations
GenerateAiRecommendationJob::dispatch($orderId);
ZatcaInvoice::dispatch($invoiceId);
SendSMSJob::dispatch($mobile, $message);
HESNPlusSendData::dispatch($orderId);
```

### Bilingual Data
All content fields come in pairs:
```
NAME_EN, NAME_AR
DESCRIPTION_EN, DESCRIPTION_AR
TITLE_EN, TITLE_AR
```

---

## 8. Folder Map

```
/var/www/html/blazmaNew/
├── app/
│   ├── Console/Commands/         # Artisan commands
│   ├── Exports/                  # Excel exports (Maatwebsite)
│   ├── Http/
│   │   ├── Controllers/          # HTTP controllers
│   │   │   ├── Operations/       # Internal operations controllers
│   │   │   └── V2/               # API v2 controllers
│   │   └── Middleware/           # HTTP middleware
│   ├── Imports/                  # Excel imports
│   ├── Jobs/                     # Queue jobs
│   ├── Models/
│   │   └── Base/                 # Base/abstract models
│   ├── Services/                 # Business logic services
│   │   ├── Alert/
│   │   ├── Ayenati/
│   │   ├── ERP/
│   │   ├── Master/
│   │   ├── Metadata/
│   │   ├── Notification/
│   │   └── Zatca/
│   └── helpers.php               # Global helpers
├── config/                       # Laravel config files
├── database/
│   └── migrations/               # 800+ migrations
├── docs/
│   └── ai/                       # ← AI knowledge base (this folder)
├── public/                       # Web root
├── resources/
│   ├── views/                    # Blade templates
│   └── js/                       # Frontend JS
├── routes/
│   ├── web.php                   # 1,596 routes
│   └── console.php               # Console routes
├── storage/                      # Logs, cache, uploads
└── vendor/                       # Composer packages
```
