# BLAZMA Project - Comprehensive Technical Documentation

## 1. PROJECT OVERVIEW

**Project Name:** Blazma  
**Framework:** Laravel 12.0  
**PHP Version:** ^8.2  
**Database:** MySQL  
**Primary Domain:** Laboratory Information Management & Healthcare Services

### Business Domain:
Blazma is a comprehensive laboratory and healthcare management system that provides:
- **Laboratory Test Management**: Test ordering, scheduling, sample collection
- **Booking & Appointments**: Appointment booking for lab tests and home visits
- **Payment Processing**: Multiple payment gateways (Tamara, PayFort, TAP, NearPay)
- **Invoice & Billing**: Invoice generation, refunds, credit/debit notes
- **Insurance Integration**: Insurance approvals, claims, coverage policies
- **Result Management**: Test results, AI recommendations, report generation
- **Notification System**: Email, SMS, push notifications, alerts
- **ERP Integration**: Integration with SAP, Focus, Dynamic ERP systems
- **Healthcare Provider Network**: Hospitals, labs, pharmacies, doctors
- **API Integrations**: HESN Plus, NPHIES, Ayenati, LDM, LiveHealth
- **White Label Support**: Multi-tenant capability for different organizations
- **Quality Control**: QC procedures, Westgard rules, batch management
- **E-Signature & Compliance**: ZATCA integration (Saudi Arabia), PDF processing

---

## 2. DIRECTORY STRUCTURE

### Core Application Structure:
```
/var/www/html/blazmaNew/
├── app/
│   ├── Console/
│   │   └── Commands/              # 20+ CLI commands
│   ├── Enums/                     # Type enumerations
│   ├── Events/                    # Event classes
│   ├── Exceptions/                # Custom exceptions
│   ├── Exports/                   # 20+ Excel export classes
│   ├── Helpers/                   # AWSHelper.php, WestgardRules.php
│   ├── Http/
│   │   ├── Controllers/           # 40 main controllers
│   │   ├── Controllers/V2/        # API v2 controllers
│   │   ├── Controllers/Operations/# Operations controllers
│   │   └── Middleware/            # 13 custom middleware
│   ├── Imports/                   # 10 Excel import classes
│   ├── Jobs/                      # 49 queue jobs
│   ├── Listeners/                 # Event listeners
│   ├── Logging/                   # GoogleChatLogger
│   ├── Models/                    # 431 Eloquent models
│   │   └── Base/                  # Base model variations
│   ├── Providers/                 # Service providers
│   ├── Services/                  # 107 service classes
│   │   ├── Alert/                 # Alert service (5 types)
│   │   ├── Ayenati/               # HESN Plus integration
│   │   ├── ERP/                   # ERP integration (SAP, Focus, Dynamic)
│   │   ├── Metadata/              # Metadata service
│   │   └── Notification/          # Notification service
│   └── Traits/                    # FcmNotification.php
├── bootstrap/
├── config/                        # 20 config files
├── database/
│   ├── migrations/                # 800 migration files
│   ├── seeders/
│   └── factories/
├── resources/
├── routes/
│   └── web.php                    # 1911 lines of routes
├── storage/
├── tests/
├── vendor/
├── public/
├── .env                           # Environment configuration
├── composer.json
├── package.json
└── artisan
```

---

## 3. MODELS (431 Total)

### Key Core Models:

#### USER & AUTHORIZATION
- **ENDUSER**: Main end user/patient model (table: END_USER)
- **SYSTEMUSER**: System admin users
- **ROLE**: Role-based access control
- **PERMISSION**: Permissions system
- **ROLEHASPERMISSION**: Role-permission pivot

#### LAB OPERATIONS
- **LABCATEGORYPACKAGE**: Lab tests/packages (core entity)
- **LABCATEGORYPACKAGERESULT**: Test result definitions
- **LABCATEGORYPACKAGEQUESTIONNAIRE**: Questionnaires for tests
- **LABCATEGORY**: Test categories
- **LABAVAILABLETIME**: Appointment slots
- **LABSETTING**: Lab settings/configuration

#### ORDERS & TRANSACTIONS
- **ENDUSERLABORDER**: Lab order header (main order entity)
- **ENDUSERLABORDERPACKAGE**: Order line items
- **ENDUSERLABORDERPACKAGERESULT**: Order test results
- **ENDUSERLABORDERPACKAGETEMPLATE**: Result templates
- **ENDUSERLABORDERATTACHMENT**: Order attachments
- **INVOICE**: Generated invoices
- **ENDUSERINVOICE**: User-specific invoices
- **PAYMENT**: Payment records
- **ORDERREFUNDTRANSACTION**: Refund transactions

#### SAMPLE MANAGEMENT
- **SAMPLEGENERATION**: Sample generation batches
- **ENDUSERSAMPLESTORAGEUNIT**: Sample storage locations
- **ENDUSERSAMPLECOMMENT**: Sample comments
- **ENDUSERSAMPLEDISPOSE**: Sample disposal records

#### HOSPITAL & LOCATIONS
- **HOSPITAL**: Lab/hospital locations (core entity)
- **HOSPITALLOCATION**: Sub-locations within hospitals
- **HOSPITALSYSTEMUSER**: Hospital staff users
- **HOSPITALPOS**: Point of sale terminals
- **HOSPITALBANK**: Hospital banking info

#### INSURANCE
- **INSURANCE**: Insurance policies
- **INSURANCECOMPANY**: Insurance companies
- **INSURANCEAPPROVAL**: Insurance approvals
- **INSURANCECLAIM**: Insurance claims
- **INSURANCEINVOICE**: Insurance invoices

#### ERP & INTEGRATION
- **ERPINTEGRATION**: ERP sync records
- **ERPCOMPANIES**: ERP company configs
- **ZATCA_INVOICE**: ZATCA E-Invoice records
- **ZATCA_B2B_INVOICE**: ZATCA B2B invoices
- **PROFILEHIS**: HIS system configurations

#### NOTIFICATIONS & ALERTS
- **ENDUSERNOTIFICATION**: User notifications
- **SYSTEMUSERNOTIFICATION**: System notifications
- **ALERT**: Alert configurations
- **ALERTEVENT**: Alert event triggers
- **ALERTEVENTPROCESS**: Alert processing

#### QUALITY CONTROL
- **QC**: QC batch records
- **QCRESULT**: QC test results
- **QCLABCATEGORYPACKAGE**: QC-configured packages
- **QCANALYZER**: QC analyzer equipment
- **QC_WESTGARD_RULE**: Westgard rule definitions

#### FINANCIAL
- **ENDUSERWALLET**: Wallet/prepaid balance
- **COUPON**: Discount coupons
- **PROFILEBALANCE**: Profile financial balance
- **VAT**: VAT configuration

#### REFERENCE DATA
- **GENDER**: Gender types
- **NATIONALITY**: Nationalities
- **COUNTRY**: Countries
- **CITY**, **CITYSTATE**: Locations
- **SPECIALITY**: Doctor specialties

### Model Relationships (Examples):
```php
// ENDUSER -> ENDUSERLABORDER (One-to-Many)
public function eNDUSERLABORDERS() {
    return $this->hasMany(ENDUSERLABORDER::class, 'END_USER_ID');
}

// ENDUSERLABORDER -> ENDUSERLABORDERPACKAGE (One-to-Many)
public function eNDUSERLABORDERPACKAGES() {
    return $this->hasMany(ENDUSERLABORDERPACKAGE::class, 'END_USER_LAB_ORDER_ID');
}

// HOSPITAL -> LABCATEGORYPACKAGE (Many-to-Many)
public function tests() {
    return $this->belongsToMany(LABCATEGORYPACKAGE::class, 'LAB_CATEGORY_PACKAGE_HOSPITAL', 'HOSPITAL_ID', 'LAB_CATEGORY_PACKAGE_ID');
}

// ENDUSERLABORDER -> INSURANCE (Many-to-One)
public function insurance() {
    return $this->belongsTo(INSURANCE::class, 'INSURANCE_ID', 'ID');
}
```

---

## 4. CONTROLLERS (40 Main + 1 V2 + 1 Operations)

### Main Controllers:

| Controller | Purpose | Key Methods |
|-----------|---------|-----------|
| **WebController** | Frontend web pages | index, showPackages, showCart, Order, ShowResults |
| **LabController** | Lab API endpoints | GetPackagesByLabCategoryId, GetLabAvailableTime, UpdateCart, ViewCart, Order, GetResults |
| **ApiController** | General API | (main API handler) |
| **AlertController** | Alert management | (alert operations) |
| **ZatcaController** | E-Invoice generation | (ZATCA integration) |
| **PaymentController** | Payment operations | (payment processing) |
| **PayfortController** | PayFort gateway | (PayFort integration) |
| **TamaraController** | Tamara payments | (Tamara gateway) |
| **TapController** | TAP payments | (TAP gateway) |
| **InsuranceController** | Insurance operations | (insurance claims, approvals) |
| **InvoiceController** | Invoice generation | (invoice operations) |
| **NotificationController** | Notification mgmt | (notification operations) |
| **MetadataController** | Metadata API | (system metadata) |
| **TerminalController** | Terminal/POS | (terminal operations) |
| **UserController** | User management | (user operations) |
| **SalesController** | Sales operations | (sales management) |
| **WarehouseController** | Inventory mgmt | (warehouse operations) |
| **AiRecommendationController** | AI recommendations | (AI integration) |
| **MyHealthController** | MyHealth platform | (MyHealth features) |
| **ErpController** | ERP operations | (ERP sync) |
| **HlController** | Hospital Link | (HL integration) |
| **AyenatiController** | Ayenati/HESN | (HESN integration) |
| **LdmController** | LDM integration | (LDM API) |
| **LoyaltyController** | Loyalty program | (loyalty features) |
| **QuestionnaireController** | Questionnaires | (questionnaire mgmt) |
| **CommandCenterController** | Command center | (monitoring/control) |
| **BranchIncomeController** | Income reporting | (branch income) |
| **DiabeticDashboardController** | Diabetic tracking | (diabetes management) |
| **FitTestController** | Fitness testing | (fitness features) |
| **GeneticsExtractionController** | Genetics | (genetics analysis) |
| **LiveHealthController** | LiveHealth integration | (LiveHealth API) |
| **NewSalesController** | New sales module | (new sales features) |
| **SalesForecastController** | Forecast mgmt | (sales forecasting) |
| **WebhookController** | Webhook handlers | (webhook events) |
| **WhitelabelController** | White label ops | (multi-tenant) |
| **ExampleController** | Example/demo | (demo endpoints) |

### V2 API Controllers:
- **V2/TerminalController** - API v2 terminal endpoints

### Operations Controllers:
- **Operations/CorrectiveActionsController** - Corrective actions management

---

## 5. ROUTES (1911 Lines in web.php)

### Route Groups & Organization:

#### PUBLIC ROUTES
- `/` - Home page (conditional: showProfileIndex or index)
- `/package` - Package listing
- `/offers` - Offers
- `/providers` - Provider listing
- `/signin`, `/email/signin` - Sign in pages
- `/signup`, `/email/signup` - Registration
- `/{PackageID}/package-details` - Package details
- `/{HospitalID}/lab` - Lab details

#### AUTHENTICATED ROUTES (middleware: 'WebAuth')
- `/profile` - User profile
- `/cart` - Shopping cart
- `/confirm` - Order confirmation
- `/order` - Order placement
- `/wallet` - Wallet/prepaid
- `/orders` - Order history
- `/orders/{OrderID}` - Order details
- `/artificial-intelligence` - AI recommendations
- `/map` - Location map

#### PAYMENT ROUTES
- `POST /tamara/payment` - Tamara payment
- `POST /cod_order` - Cash on delivery
- `POST /credit_order` - Credit order
- `GET /tamara/order/check` - Check Tamara order
- `GET /order/check` - Check prepaid order

#### SAMPLE ENDPOINTS
- `/samples/{SampleToken}/tracking` - Sample tracking
- `/orders/user-results/{OrderToken}/info` - Order info
- `/orders/user-results/{OrderToken}/tracking` - Order tracking
- `/orders/user-results/{OrderToken}/questionnaire` - Questionnaire

#### SETTINGS & INFO
- `/terms` - Terms of service
- `/privacy-policy` - Privacy policy
- `/contact` - Contact form
- `/faqs` - FAQs
- `/blogs`, `/blogs/{blogId}` - Blog

---

## 6. SERVICES (107 Total)

### Main Services:

#### ALERT SERVICES (5)
- **Alert/AlertService.php** - Alert management
- **Alert/Delivery/DeliveryService.php** - Alert delivery
- **Alert/Delivery/Email.php** - Email alerts
- **Alert/Delivery/Sms.php** - SMS alerts
- **Alert/Information/InformationService.php** - Alert info
- **Alert/Type/TypeService.php** - Alert types
- **Alert/Type/{AnalyzedDelayType, ApprovalDelayType, QcDelayType, TatStatType, ValidatedDelayType}.php** - Specific alert types

#### ERP SERVICES (8)
- **ERP/ERPService.php** - Main ERP service
- **ERP/SAP/SAP.php** - SAP integration
- **ERP/SAP/{Invoice, Refund, InvoiceClient, RefundClient, InvoiceClientCash, RefundClientCash}.php** - SAP operations
- **ERP/Focus/Focus.php** - Focus ERP
- **ERP/Focus/{Invoice, Refund}.php**
- **ERP/Dynamic/Dynamic.php** - Dynamic ERP
- **ERP/Dynamic/{Invoice, Refund, Movement, InvoiceClient, RefundClient, InvoiceClientCash, RefundClientCash}.php**

#### AYENATI/HESN SERVICES
- **Ayenati/AyenatiService.php** - Main Ayenati service
- **Ayenati/Traits/** - 12 helper traits (MessageHandlerTrait, ResultHandlerTrait, etc.)

#### NOTIFICATION SERVICES
- **Notification/NotificationService.php** - Main notification service
- **Notification/Type/TypeService.php** - Notification types
- **Notification/Type/{AnalyzerType, ProcessingLabType, ProcessingUnitType, PromotionIndividualTestType, PromotionPackageType, RejectionSampleType, TestType}.php**

#### CORE BUSINESS SERVICES
- **LabService.php** - Laboratory operations
- **PaymentService.php** - Payment processing
- **EmailService.php** - Email sending
- **SMSService.php** - SMS sending
- **FCMService.php** - Firebase Cloud Messaging
- **WhatsAppService.php** - WhatsApp integration
- **NewSalesService.php** - Sales management
- **EndUserService.php** - End user operations
- **TerminalService.php** - Terminal/POS operations
- **WarehouseService.php** - Inventory management

#### INTEGRATION SERVICES
- **HESNService.php** - HESN integration
- **HESNPlusService.php** - HESN Plus integration
- **LdmService.php** - LDM integration
- **HL7Service.php** - HL7 message handling
- **MyHealthService.php** - MyHealth platform
- **MyHealthAiService.php** - MyHealth AI features
- **LivehealthService.php** - LiveHealth integration
- **NphiesService.php** - NPHIES integration
- **Zatca/ZatcaService.php** - ZATCA e-invoice

#### REPORT SERVICES
- **NormalReportService.php** - Standard reports
- **NormalReportServiceV2.php** - Report v2
- **SmartReportService.php** - Smart reports
- **IntegratedReportService.php** - Integrated reports
- **TemplateReportService.php** - Template-based reports
- **TemplateReportV2Service.php** - Template v2

#### SPECIALIZED SERVICES
- **TaxService.php** - Tax calculations
- **PayfortService.php** - PayFort gateway
- **TamaraService.php** - Tamara payment gateway
- **TapService.php** - TAP payment gateway
- **NearPayService.php** - NearPay integration
- **AiRecommendationReportService.php** - AI recommendations
- **BranchIncomeService.php** - Branch income reporting
- **CommandCenterService.php** - Command center ops
- **SalesService.php** - Sales operations
- **FileService.php** - File management
- **ApiService.php** - API operations
- **QRService.php** - QR code generation
- **SymbolsService.php** - Symbol/formula handling
- **MTCService.php** - MTC service
- **LinkService.php** - Link management
- **LanguageService.php** - Language/localization
- **LogService.php** - Logging
- **FlagService.php** - Feature flags
- **Metadata/MetadataService.php** - Metadata
- **Master.php** - Master data service
- **LeanAPIService.php** - Lean API

---

## 7. JOBS (49 Total - Queue System)

### Main Queue Jobs:

#### ERP/ACCOUNTING JOBS
- **ERPInvoice.php** - Create invoice in ERP
- **ERPInvoiceClient.php** - Client invoice
- **ERPInvoiceClientCash.php** - Client cash invoice
- **ERPRefund.php** - Create refund in ERP
- **ERPRefundClient.php** - Client refund
- **ERPRefundClientCash.php** - Client cash refund
- **ERPMovement.php** - Inventory movement

#### INVOICE JOBS
- **GenerateInvoiceNumber.php** - Generate invoice numbers
- **ExportInvoicesJob.php** - Export invoices to file

#### NOTIFICATION JOBS
- **NotificationPush.php** - Push notifications
- **SendEmailNotificationJob.php** - Email notifications
- **NotificationPromotionReservationFired.php** - Promotion notifications
- **AlertDelivery.php** - Alert delivery
- **AlertEscalationEvent.php** - Alert escalation
- **AlertTypeEvent.php** - Alert type events

#### HL7/INTEGRATION JOBS
- **SendHL7InProcessMessageJob.php** - HL7 message sending
- **HL7ErrorLog.php** - HL7 error logging

#### HESN/INSURANCE JOBS
- **HESNRequisition.php** - HESN requisition
- **HESNReceive.php** - HESN receive message
- **HESNPlusSendData.php** - HESN Plus data sync
- **NphiesResultStatusUpdate.php** - NPHIES result updates

#### ZATCA JOBS
- **ZatcaB2BInvoice.php** - B2B e-invoice
- **ZatcaRefund.php** - E-invoice refund

#### REPORT JOBS
- **SmartReportReady.php** - Report ready notification
- **TatAnalysisReport.php** - TAT analysis report
- **HisResultReady.php** - HIS result notification

#### OTHER JOBS
- **GenerateAiRecommendationJob.php** - AI recommendations (58KB - large)
- **PurchaseOrderJob.php** - Purchase order processing
- **ExampleJob.php** - Example/test job

### Queue Configuration:
- **Default Queue Connection**: Redis
- **Queue Driver**: 'redis' (in config/queue.php)
- **Retry After**: 90 seconds
- **Failed Jobs Table**: 'failed_jobs'

---

## 8. EVENTS & LISTENERS

### Events:
- **Event.php** - Base event class
- **ExampleEvent.php** - Example event

### Listeners:
- **ExampleListener.php** - Example listener

*(Event-driven architecture is minimal; most event handling done through jobs)*

---

## 9. MIDDLEWARE (13 Custom)

| Middleware | Purpose |
|-----------|---------|
| **AccessTokenValidation** | Validate API access tokens |
| **AccessTokenOptional** | Make access tokens optional |
| **Authenticate** | User authentication |
| **AyenatiTokenAuth** | Ayenati API authentication |
| **CorsMiddleware** | CORS handling |
| **LdmAuth** | LDM API authentication |
| **MetaDataAuth** | Metadata API authentication |
| **NupcoAuth** | NUPCO API authentication |
| **OperationsAuth** | Operations module authentication |
| **TerminalAuth** | Terminal/POS authentication |
| **WebAuth** | Web frontend authentication |
| **NormalizeSlashes** | URL slash normalization |
| **RedirectToPayment** | Payment redirect |
| **ExampleMiddleware** | Example middleware |

---

## 10. DATABASE MIGRATIONS (800 Total)

### Migration Coverage:
- 800 migration files dating from 2021 to 2025
- Covers all core and feature tables
- Includes schema modifications, indexes, constraints

### Key Tables Covered:
- Core: ENDUSER, HOSPITAL, PROFILE, SYSTEMUSER, ROLE, PERMISSION
- Orders: END_USER_LAB_ORDER, END_USER_LAB_ORDER_PACKAGE, INVOICE
- Laboratory: LAB_CATEGORY_PACKAGE, LAB_CATEGORY_PACKAGE_RESULT, QC, SAMPLE_GENERATION
- Insurance: INSURANCE, INSURANCE_CLAIM, INSURANCE_APPROVAL, INSURANCE_INVOICE
- ERP: ERP_INTEGRATION, ZATCA_INVOICE, ZATCA_B2B_INVOICE
- Finance: PAYMENT, WALLET, COUPON, PROFILE_BALANCE
- Alerts: ALERT, ALERT_EVENT, ALERT_PROCESS, ALERT_SCHEDULING_PROCESS
- Quality: QC, QC_RESULT, QC_ANALYZER, QC_WESTGARD_RULE
- And 100+ more tables

---

## 11. CONFIGURATION FILES

### Key Config Files:

```
config/
├── app.php              - App configuration (Laravel)
├── database.php         - Database connections (MySQL)
├── queue.php            - Queue configuration (Redis)
├── mail.php             - Mail configuration
├── services.php         - Third-party services
├── auth.php             - Authentication
├── cache.php            - Cache configuration
├── cors.php             - CORS settings
├── filesystems.php      - File storage (AWS S3)
├── horizon.php          - Queue monitoring
├── logging.php          - Logging (Google Chat, Stack)
├── session.php          - Session handling
├── alert.php            - Alert configuration
├── barcode.php          - Barcode generation
├── image.php            - Image processing
├── laravel-fcm.php      - FCM configuration
├── payfort.php          - PayFort config
├── snappy.php           - PDF generation
├── telescope.php        - Debugging tool
```

### Key Environment Variables (.env):
```
APP_NAME=Blazma
APP_ENV=local
DB_HOST=localhost
DB_DATABASE=blazma
QUEUE_CONNECTION=redis
REDIS_HOST=127.0.0.1
AWS_BUCKET=blazma.com
TAMARA_API_URL=https://api-sandbox.tamara.co
HESN_PLUS_KEY=...
PAYFORT_*=...
OPENAI_API_KEY=...
PROFILE_ID=...
```

---

## 12. DEPENDENCIES

### Composer.json - require:
```
php: ^8.2
ext-gd: *
aranyasen/hl7: ^3.2          # HL7 message handling
aws/aws-sdk-php: ^3.369      # AWS S3
barryvdh/laravel-dompdf: ^3.1   # PDF generation
barryvdh/laravel-snappy: ^1.0   # PDF/image generation
brick/phonenumber: ^0.8.0       # Phone validation
firebase/php-jwt: ^7.0          # JWT tokens
intervention/image: ^3.11       # Image manipulation
laravel/framework: ^12.0        # Core framework
laravel/horizon: ^5.45          # Queue monitoring
laravel/tinker: ^2.10.1         # REPL
league/csv: ^9.28               # CSV handling
league/flysystem-aws-s3-v3: ^3.0 # S3 filesystem
maatwebsite/excel: ^3.1         # Excel import/export
milon/barcode: ^12.0            # Barcode generation
phpmailer/phpmailer: ^7.0       # Email
setasign/fpdf: ^1.8             # PDF library
setasign/fpdi: ^2.6             # PDF import
tecnickcom/tcpdf: ^6.10         # PDF generation
werneckbh/laravel-qr-code: ^0.1.3 # QR codes
yajra/laravel-datatables: ^12.0 # DataTables
```

### Composer.json - require-dev:
```
fakerphp/faker: ^1.23              # Fake data
laravel/pail: ^1.2.2               # Log viewing
laravel/pint: ^1.24                # Code formatting
laravel/sail: ^1.41                # Docker
laravel/telescope: ^5.2            # Debugging
mockery/mockery: ^1.6              # Mocking
nunomaduro/collision: ^8.6         # Error handler
phpunit/phpunit: ^11.5.3           # Testing
```

### Package.json - devDependencies:
```
@tailwindcss/vite: ^4.0.0         # Tailwind CSS
axios: ^1.11.0                    # HTTP client
concurrently: ^9.0.1              # Run multiple commands
laravel-vite-plugin: ^2.0.0       # Vite Laravel plugin
tailwindcss: ^4.0.0               # Utility-first CSS
vite: ^7.0.7                      # Build tool
```

---

## 13. HELPERS & UTILITIES

### Helper Files:
- **app/helpers.php** (100+ lines)
  - `GetFile()` - File retrieval
  - `symbolFormula()` - Formula evaluation for test results
  - `getResultImage()` - Generate result visualization positioning

### Helper Classes:
- **Helpers/AWSHelper.php** - AWS S3 operations
- **Helpers/WestgardRules.php** - Quality control rule evaluation

---

## 14. TRAITS

### Custom Traits:
- **FcmNotification.php** - Firebase Cloud Messaging integration
  - Methods: `sendNotification()`, `sendPushNotification()`
  - Features: JWT token generation, multiple device support

### Service Traits (in Ayenati/Traits/):
- **CommunicationTrait** - External communication
- **ErrorHandlerTrait** - Error handling
- **LogisticsHandlerTrait** - Shipping/logistics
- **MessageHandlerTrait** - Message processing
- **MessagePreparationTrait** - Message formatting
- **OIDHandlerTrait** - OID handling
- **ResultHandlerTrait** - Test results
- **SegmentCustomizationTrait** - HL7 segment customization
- **SpecimenHandlerTrait** - Sample handling
- **SpecimenLabelTrait** - Barcode/label generation
- **TransportHandlerTrait** - Transport management
- **UtilityTrait** - Utility functions
- **ValidationTrait** - Data validation

---

## 15. EXPORTS & IMPORTS

### Export Classes (20+):
- **AccountDetailsExport**, **AccountPriceListExport**, **AccountTotalsExport**
- **AnalysisResultsExport**, **BatchExport**, **CancellationDetailsExport**
- **DisposeExport**, **GenericExport**, **GeneticsBatchSamplesExport**
- **IncomeDetailsSummaryExport**, **IncomeReportExport**
- **DailyPerformanceExport**, **CriticalReportExport**
- **DiscountListExport**, **GeneticsResultsTemplateExport**
- Plus more...

### Import Classes (10):
- **ContractCartImport** - Contract data import
- **DiscountListImport** - Discount pricing
- **FollowersImport** - Follower data
- **LoincImport**, **LoincListImport** - LOINC codes
- **PriceListImport** - Pricing data
- **TatListImport** - TAT (turnaround time)
- **ValidationResultsImport** - Validation data
- **ImportValidationResultsNbsImport** - NBS validation
- **ImportValidationResultsV2NbsImport** - NBS v2 validation

---

## 16. API INTEGRATIONS

### External Services/APIs:

| Service | Purpose | Config |
|---------|---------|--------|
| **Tamara** | Buy-now-pay-later | TAMARA_API_URL, TAMARA_API_TOKEN |
| **PayFort** | Payment gateway | PAYFORT_MERCHANT_IDENTIFIER, etc. |
| **TAP** | Payment gateway | TAP_PUBLIC, TAP_SECRET |
| **NearPay** | Payment gateway | NEARPAY_SECRET |
| **HESN Plus** | Healthcare ID | HESN_PLUS_KEY, HESN_PLUS_SECRET |
| **NPHIES** | Insurance claims | NAFIS_ENDPOINT |
| **Ayenati** | Health data exchange | AYENATI_ENDPOINT, AYENATI_USERNAME |
| **HL7** | Medical messaging | HL7_ORGANIZATION_ID, etc. |
| **AWS S3** | File storage | AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY |
| **AWS SES** | Email sending | SES_KEY, SES_SECRET, SES_REGION |
| **Firebase** | Push notifications | FCM_SERVICE_ACCOUNT (in PROFILE) |
| **ZATCA** | E-Invoice (Saudi Arabia) | ZATCA integration |
| **LiveHealth** | Video consultations | LIVEHEALTH_URL, LIVEHEALTH_TOKEN |
| **LDM** | Laboratory Data Management | LDM_TEST_URL, LDM_USERNAME |
| **NUPCO** | Procurement | NUPCO_API_KEY |
| **Scandit** | Barcode scanning | SCANDIT_TOKEN |

### Third-Party Libraries:
- **Firebase PHP JWT** - JWT token generation
- **PHP-HL7** - HL7 message parsing
- **Laravel DataTables** - Server-side data tables
- **PHPMailer** - Email handling
- **Intervention Image** - Image manipulation
- **League CSV** - CSV handling
- **Barcode Libraries** - QR codes, barcodes

---

## 17. CONSOLE COMMANDS (20+)

### Available Commands:
- **MigrateQuestionnaireDataCommand** - Migrate questionnaire data
- **EnableResultAndOption** - Enable result options
- **AddCertificateToZatcaInvoice** - ZATCA certificate
- **BuildAntibioticDisc** - Build antibiotic disc data
- **AlertFired** - Fire alerts
- **SalesForecastCommand** - Generate sales forecast
- **RepairEncryptedPdfs** - PDF repair
- **AlertEscalation** - Escalate alerts
- **AutoValidateCommand** - Auto-validate results
- **GenerateInvoiceNumber** - Generate invoice numbers
- **ProfileTestReferenceRange** - Setup reference ranges
- **CloneTestWithResultsAndOptions** - Clone test configurations
- **AutoApprovalCommand** - Auto-approve results
- **AddTaxToTests** - Add tax to test prices
- **DispatchJob** - Dispatch queue jobs
- **AutoCalculateCostPrice** - Calculate cost prices
- Plus more...

---

## 18. KEY BUSINESS WORKFLOWS

### 1. **Order Creation Workflow**
```
ENDUSER -> Create Cart (ENDUSERLABCART)
        -> Add Tests/Packages (LABCATEGORYPACKAGE)
        -> Apply Coupon (COUPON)
        -> Select Hospital/Location
        -> Choose Time Slot (LABAVAILABLETIME)
        -> Select Payment Method (PAYMENT_METHOD)
        -> Create Order (ENDUSERLABORDER)
        -> Create Order Lines (ENDUSERLABORDERPACKAGE)
        -> Generate Invoice (INVOICE)
        -> Process Payment
        -> Dispatch ERPInvoice Job
```

### 2. **Sample Collection Workflow**
```
Order Created
  -> Schedule Collection Time
  -> Generate Barcode (BARCODE)
  -> Print Labels (SPECIMEN_LABEL)
  -> Collector arrives for sample
  -> Collection confirmed (ENDUSERLABORDERPACKAGE.COLLECTION_TIME)
  -> Store in Sample Storage (ENDUSERSAMPLESTORAGEUNIT)
  -> Generate Sample (SAMPLEGENERATION)
```

### 3. **Test Analysis Workflow**
```
Sample Collected
  -> Assign to Analyzer (QCANALYZER)
  -> Run QC (QC, QCRESULT)
  -> Analyze Test (ANALYZER)
  -> Generate Result (ENDUSERLABORDERPACKAGERESULT)
  -> Apply Reference Range (PROFILEREFERENCERANGE)
  -> Generate Report (TEMPLATE)
  -> Validate Result (LAB_ORDER_STATUS_ID = 3)
  -> Approve Result (LAB_ORDER_STATUS_ID = 4)
  -> Dispatch SmartReportReady Job
```

### 4. **Invoice & ERP Sync Workflow**
```
Order Confirmed & Paid
  -> Create Invoice (INVOICE)
  -> Determine ERP Company (ERPCOMPANIES)
  -> Create ERP Integration Record (ERPINTEGRATION)
  -> Dispatch ERPInvoice Job
  -> ERP Service fetches credentials (PROFILEERPCREDENTIAL)
  -> Create Invoice in ERP (SAP/Focus/Dynamic)
  -> Update ERP Status (ERPINTEGRATION.STATUS)
  -> If refund needed -> Dispatch ERPRefund Job
```

### 5. **Insurance Approval Workflow**
```
Order Created with Insurance
  -> Send to Insurance (INSURANCEAPPROVAL)
  -> Wait for approval
  -> If approved:
     -> Update ENDUSERLABORDER.INSURANCE_ID
     -> Create INSURANCECLAIM
     -> Create INSURANCE_INVOICE
  -> Track in Insurance invoice module
```

### 6. **Notification Workflow**
```
Order Event Triggered
  -> Create Notification (ENDUSERNOTIFICATION/SYSTEMUSERNOTIFICATION)
  -> Determine Delivery Method
  -> Dispatch NotificationPush Job (Push/Email/SMS)
  -> Track Delivery Status
```

### 7. **ZATCA E-Invoice Workflow**
```
Invoice Created in KSA
  -> Apply ZATCA Integration
  -> Generate E-Invoice (ZATCA_INVOICE)
  -> Sign with Certificate
  -> Submit to ZATCA
  -> Dispatch ZatcaB2BInvoice Job
  -> Track submission status
  -> Store ZATCA response
```

### 8. **HESN Plus Data Sync Workflow**
```
Result Available
  -> Check PROFILE.HESN_PLUS_ENABLED
  -> Format HL7 Message
  -> Dispatch HESNPlusSendData Job
  -> Send to HESN Plus API
  -> Update sync status
  -> Create HL7_ERRORLOG if failed
```

### 9. **AI Recommendation Workflow**
```
User Provides Health Data
  -> Store in ENDUSERAIRECOMMENDATION
  -> Dispatch GenerateAiRecommendationJob
  -> Call OpenAI API
  -> Generate Recommendation (ENDUSERAIRECOMMENDATIONPACKAGE)
  -> Suggest Related Tests
  -> Display to User
```

### 10. **Payment Processing Workflow**
```
Order Ready for Payment
  -> Determine Payment Method (PAYMENT_METHOD)
  -> If Credit Card -> PayFort Integration
  -> If Tamara -> Tamara Integration
  -> If TAP -> TAP Integration
  -> If COD -> Set Order Status
  -> Create PAYMENT Record
  -> If successful -> Proceed to ERP Sync
  -> If failed -> Retry or ask for alternative
```

---

## 19. DATABASE SCHEMA HIGHLIGHTS

### Primary Tables & Relationships:

```sql
-- Core User Tables
END_USER (ID, EMAIL, MOBILE_NUMBER, PASSWORD, ...)
SYSTEM_USER (ID, EMAIL, PASSWORD, ...)

-- Order Tables
END_USER_LAB_ORDER (ID, END_USER_ID, HOSPITAL_ID, PAYMENT_METHOD_ID, TOTAL_AMOUNT, ...)
END_USER_LAB_ORDER_PACKAGE (ID, END_USER_LAB_ORDER_ID, LAB_CATEGORY_PACKAGE_ID, PRICE, ...)

-- Lab Configuration
LAB_CATEGORY_PACKAGE (ID, NAME, PRICE, ...)
LAB_CATEGORY_PACKAGE_RESULT (ID, LAB_CATEGORY_PACKAGE_ID, NAME, MIN_NORMAL, MAX_NORMAL, ...)
LAB_CATEGORY_PACKAGE_QUESTIONNAIRE (ID, LAB_CATEGORY_PACKAGE_ID, QUESTION, ...)

-- Infrastructure
HOSPITAL (ID, NAME_EN, NAME_AR, PROFILE_ID, ...)
PROFILE (ID, NAME, ...)
HOSPITAL_LOCATION (ID, HOSPITAL_ID, ...)

-- Financial
INVOICE (ID, PROFILE_ID, INVOICE_NUMBER, TOTAL, ...)
END_USER_INVOICE (ID, END_USER_ID, INVOICE_ID, ...)
PAYMENT (ID, PROFILE_ID, AMOUNT, PAYMENT_METHOD, ...)
END_USER_WALLET (ID, END_USER_ID, BALANCE, ...)

-- Insurance
INSURANCE (ID, INSURANCE_COMPANY_ID, POLICY_NUMBER, ...)
INSURANCE_APPROVAL (ID, END_USER_LAB_ORDER_ID, STATUS, ...)
INSURANCE_CLAIM (ID, END_USER_LAB_ORDER_ID, ...)

-- ERP & Integration
ERP_INTEGRATION (ID, ORDER_ID, ERP_COMPANY_ID, STATUS, RESPONSE, ...)
ZATCA_INVOICE (ID, INVOICE_ID, QR_CODE, ...)

-- Quality Control
QC (ID, LAB_ID, STATUS, ...)
QC_RESULT (ID, QC_ID, TEST_ID, VALUE, ...)
QC_WESTGARD_RULE (ID, NAME, RULE_TYPE, ...)

-- Notifications & Alerts
ALERT (ID, NAME, CONDITION, ...)
ALERT_EVENT (ID, ALERT_ID, ORDER_ID, ...)
END_USER_NOTIFICATION (ID, END_USER_ID, MESSAGE, ...)

-- Samples
SAMPLE_GENERATION (ID, ORDER_ID, STATUS, ...)
END_USER_SAMPLE_STORAGE_UNIT (ID, SAMPLE_ID, LOCATION, ...)
```

---

## 20. SECURITY & AUTHORIZATION

### Authentication Methods:
- **Web Authentication**: Session-based (middleware: WebAuth)
- **API Authentication**: Token-based (middleware: AccessTokenValidation)
- **Special APIs**:
  - Ayenati: AyenatiTokenAuth
  - LDM: LdmAuth
  - Metadata: MetaDataAuth
  - NUPCO: NupcoAuth
  - Operations: OperationsAuth
  - Terminal: TerminalAuth

### Authorization:
- **Role-Based Access Control (RBAC)**:
  - ROLE table
  - PERMISSION table
  - ROLE_PRIVILEGE junction

### Model-Level Authorization:
- `ENDUSER::authorized($ID, $ProfileID)` - Check user's profile
- `ENDUSERLABORDER::authorized($ID, $ProfileID)` - Check order's profile
- `HOSPITAL::authorized($ID, $ProfileID)` - Check hospital's profile

---

## 21. LOGGING & MONITORING

### Logging Configuration:
- **Channels**: stack, single
- **Log Level**: debug
- **Google Chat Integration**: GoogleChatLogger.php
- **Horizon**: Queue monitoring dashboard

### Error Tracking:
- **Telescope**: Development debugging (Laravel Telescope)
- **HL7 Error Logs**: HL7_ERRORLOG table
- **Failed Jobs**: failed_jobs table

---

## 22. CACHING & PERFORMANCE

### Cache Configuration:
- **Cache Store**: file (can be changed to redis)
- **Cache Prefix**: (empty by default)
- **Memcached Support**: 127.0.0.1:11211

---

## 23. FILE STORAGE

### Filesystem Configuration:
- **Default Disk**: local
- **AWS S3 Disk**: Configured with bucket 'blazma.com'
- **URL**: http://blazma.local
- **Services**: AWS SDK PHP v3.369

---

## 24. EMAIL & MESSAGING

### Email Configuration:
- **Mailer**: log (development), SES (production)
- **From Address**: hello@example.com
- **SES Integration**: AWS SES configured
- **Alternative**: SMTP (mailhog for dev)

### SMS & Push:
- **FCM**: Firebase Cloud Messaging (FcmNotification trait)
- **SMS Services**: SMS service class available
- **WhatsApp**: WhatsApp service for messages

---

## 25. ENUMS & CONSTANTS

### Enums Directory: `app/Enums/`
- Type enumerations for various system entities

### Key Constants (in services):
- **ERPService**: PENDING, PROCESSING, SYNC, FAILED status constants
- **Alert Types**: GeneralType, QcDelayType, ApprovalDelayType, TatStatType, AnalyzedDelayType, ValidatedDelayType

---

## 26. TESTING

### Testing Framework:
- **PHPUnit**: ^11.5.3
- **Faker**: ^1.23 for fake data generation
- **Mockery**: ^1.6 for mocking

### Test Configuration:
- **Config**: phpunit.xml
- **Test Suite**: tests/ directory

---

## 27. DEPLOYMENT & DEVELOPMENT

### Development Setup:
- **Composer Scripts**:
  - `composer setup` - Complete setup
  - `composer dev` - Start dev server with queue listener, logs, and vite
  - `composer test` - Run tests

### Docker Support:
- **Laravel Sail**: ^1.41 for containerized development

### Build Tools:
- **Vite**: ^7.0.7 for frontend bundling
- **Tailwind CSS**: ^4.0.0 with Vite plugin

---

## 28. SYSTEM REQUIREMENTS

- **PHP**: ^8.2
- **Laravel**: ^12.0
- **MySQL**: Supported
- **Redis**: For queue system
- **Node.js**: For frontend build tools
- **Composer**: For PHP dependencies

---

## 29. KEY FILES & ENTRY POINTS

- **artisan** - CLI entry point
- **public/index.php** - Web entry point
- **routes/web.php** - Web route definitions (1911 lines)
- **app/Http/Controllers/WebController.php** - Main frontend controller
- **.env** - Environment configuration
- **config/** - System configuration
- **database/migrations/** - Database schema (800 files)

---

## 30. PROJECT STATISTICS

| Metric | Count |
|--------|-------|
| **Total Models** | 431 |
| **Controllers** | 40 main + 1 V2 + 1 Operations |
| **Services** | 107 |
| **Jobs** | 49 |
| **Middleware** | 13 custom |
| **Migrations** | 800 |
| **Routes** | 200+ in web.php |
| **Exports** | 20+ |
| **Imports** | 10 |
| **Helpers** | 2 files |
| **Traits** | 1 main + 12 service traits |
| **Commands** | 20+ |
| **Config Files** | 20 |
| **PHP Dependencies** | 31 (require), 9 (require-dev) |
| **NPM Dependencies** | 6 (devDependencies) |

---

## CONCLUSION

**Blazma** is a comprehensive, enterprise-grade laboratory information management system with extensive integration capabilities. It features:

✅ Multi-tenant architecture (white label support)
✅ Complex payment processing (6+ payment gateways)
✅ Healthcare system integrations (HESN Plus, NPHIES, ZATCA, HL7)
✅ ERP integration (SAP, Focus, Dynamic)
✅ Insurance management & claims
✅ Quality control & analytics
✅ AI-powered recommendations
✅ Scalable queue system (Redis)
✅ Professional invoice & billing
✅ Multi-channel notifications
✅ Role-based access control

The application demonstrates advanced Laravel patterns, microservices integration, and enterprise business logic implementation.

