# BLAZMA Project - Quick Reference Guide

## PROJECT AT A GLANCE

**Type:** Enterprise Laboratory Information Management System (LIMS)  
**Framework:** Laravel 12 (PHP 8.2+)  
**Database:** MySQL  
**Region:** Saudi Arabia Focus (ZATCA, NPHIES, HESN Plus integration)  
**Architecture:** MVC with microservices integration

---

## KEY STATISTICS

| Component | Count |
|-----------|-------|
| **Models** | 431 |
| **Controllers** | 42 |
| **Services** | 107 |
| **Jobs** | 49 |
| **Migrations** | 800 |
| **Routes** | 200+ |
| **Middleware** | 13 custom |
| **Exports** | 20+ |
| **Imports** | 10 |
| **CLI Commands** | 20+ |

---

## CORE ENTITIES & TABLES

```
ENDUSER (Patients/End Users)
  ↓ hasMany
ENDUSERLABORDER (Lab Orders)
  ↓ hasMany
ENDUSERLABORDERPACKAGE (Order Line Items)
  ↓ belongsTo
LABCATEGORYPACKAGE (Tests/Packages)
  
HOSPITAL (Lab/Clinic Locations)
  ↓ has
LABAVAILABLETIME (Booking Slots)

PROFILE (Organization/White Label)
  ↓ hasMany
HOSPITAL (Multiple locations per organization)

INVOICE (Billing)
  ↓ relatedTo
PAYMENT (Payment Records)
  ↓ relatedTo
ENDUSERLABORDER (Orders)

INSURANCE (Insurance Policies)
  ↓ relatedTo
INSURANCEAPPROVAL (Claims)
  ↓ relatedTo
ENDUSERLABORDER (Orders)

ALERT (Alert Rules)
  ↓ triggers
ALERTEVENT (Alert Occurrences)

QC (Quality Control)
  ↓ includes
QCRESULT (QC Test Results)

ERPINTEGRATION (ERP Sync)
  ↓ syncs
ENDUSERLABORDER (Orders to ERP)

ZATCA_INVOICE (E-Invoice)
  ↓ corresponds to
INVOICE (Billing Record)
```

---

## MAIN WORKFLOWS

### 1. ORDER TO DELIVERY
```
ENDUSER → Add to Cart → Select Hospital & Time → Payment 
→ Create Order (ENDUSERLABORDER) → Send to ERP → Collect Sample 
→ Analyze → Generate Result → Approve → Report Ready
```

### 2. PAYMENT PROCESSING
```
Select Payment Method → Determine Gateway (Tamara/PayFort/TAP/NearPay)
→ Process Payment → Create PAYMENT Record → Update Order Status
→ Send to ERP (ERPInvoice Job)
```

### 3. INVOICE & ERP SYNC
```
Order Confirmed → Create INVOICE → Determine ERP Company
→ Dispatch ERPInvoice Job → ERP Service sends to SAP/Focus/Dynamic
→ Update ERPINTEGRATION Status
```

### 4. INSURANCE CLAIM
```
Order Created with Insurance → Send to NPHIES API
→ Create INSURANCEAPPROVAL → Track claim status
→ Generate INSURANCEINVOICE
```

### 5. NOTIFICATION FLOW
```
Order Event → Create ENDUSERNOTIFICATION → Dispatch NotificationPush Job
→ Send via Email/SMS/Push → Track delivery
```

---

## CRITICAL SERVICES

### Payment Services
- **PaymentService** - Core payment processing
- **PayfortService** - PayFort gateway
- **TamaraService** - Tamara BNPL
- **TapService** - TAP gateway
- **NearPayService** - NearPay gateway

### Lab Services
- **LabService** - Lab operations (orders, results, etc.)
- **NormalReportService** - Generate standard reports
- **SmartReportService** - Advanced reports
- **IntegratedReportService** - Multi-source reports

### Integration Services
- **ERPService** - ERP sync (SAP, Focus, Dynamic)
- **HESNPlusService** - HESN Plus data exchange
- **NphiesService** - Insurance API
- **ZatcaService** - E-Invoice generation
- **HL7Service** - HL7 message handling
- **Ayenati/AyenatiService** - Healthcare integration

### Notification Services
- **EmailService** - Email sending
- **SMSService** - SMS sending
- **FCMService** - Push notifications
- **WhatsAppService** - WhatsApp messages
- **Notification/NotificationService** - Notification hub

### Utility Services
- **FileService** - File operations (AWS S3)
- **QRService** - QR code generation
- **TaxService** - Tax calculations
- **SymbolsService** - Symbol/formula handling

---

## AUTHENTICATION & MIDDLEWARE

### Authentication Layers
1. **WebAuth** - Session-based (web frontend)
2. **AccessTokenValidation** - API tokens
3. **AyenatiTokenAuth** - Ayenati API
4. **LdmAuth** - LDM API
5. **TerminalAuth** - Terminal/POS
6. **OperationsAuth** - Operations module
7. **MetaDataAuth** - Metadata API
8. **NupcoAuth** - NUPCO procurement

### Authorization
- Role-Based Access Control (RBAC)
- Profile-level authorization checks
- Model-level authorization methods

---

## EXTERNAL INTEGRATIONS

### Payment Gateways
- **Tamara** (BNPL) - https://api-sandbox.tamara.co
- **PayFort** (Amazon) - Credit/Debit cards
- **TAP** - Payments platform
- **NearPay** - Saudi payment

### Healthcare APIs
- **HESN Plus** - Health ID system
- **NPHIES** - Insurance claims
- **Ayenati** - Health data exchange
- **HL7** - Medical messaging
- **LDM** - Lab data management
- **LiveHealth** - Telemedicine
- **ZATCA** - E-Invoice (Saudi Arabia)

### Cloud & Storage
- **AWS S3** - File storage
- **AWS SES** - Email sending
- **Firebase** - Push notifications

### Developer Tools
- **Scandit** - Barcode/QR scanning
- **OpenAI** - AI recommendations
- **Google Chat** - Logging/alerts

---

## QUEUE JOBS (Background Processing)

### Financial Jobs
- `ERPInvoice` - Create invoice in ERP
- `ERPRefund` - Create refund in ERP
- `GenerateInvoiceNumber` - Invoice numbering
- `ExportInvoicesJob` - Bulk export

### Notification Jobs
- `NotificationPush` - Send notifications
- `SendEmailNotificationJob` - Email delivery
- `AlertDelivery` - Alert delivery
- `AlertEscalationEvent` - Escalate alerts

### Integration Jobs
- `HESNPlusSendData` - Sync to HESN Plus
- `ZatcaB2BInvoice` - E-invoice submission
- `NphiesResultStatusUpdate` - Insurance updates
- `SendHL7InProcessMessageJob` - HL7 messages

### Report Jobs
- `SmartReportReady` - Report notification
- `TatAnalysisReport` - TAT analysis
- `GenerateAiRecommendationJob` - AI analysis (Large: 58KB)

### Queue Configuration
- **Driver:** Redis
- **Default Queue:** default
- **ERP Queue:** erp (specialized)
- **Retry After:** 90 seconds
- **Failed Jobs Table:** failed_jobs

---

## DATABASE HIGHLIGHTS

### Core Tables (Sample)
```
END_USER (431k+ records expected)
HOSPITAL (Lab locations)
LAB_CATEGORY_PACKAGE (Tests/packages)
END_USER_LAB_ORDER (Orders - main transaction log)
END_USER_LAB_ORDER_PACKAGE (Order line items)
INVOICE (Billing records)
PAYMENT (Payment transactions)
INSURANCE_APPROVAL (Insurance claims)
ERP_INTEGRATION (ERP sync tracking)
ALERT (Alert configurations)
QC (Quality control records)
SAMPLE_GENERATION (Sample batches)
ZATCA_INVOICE (E-invoices)
```

### Indexes & Performance
- 800 migrations with optimizations
- Foreign key constraints
- Full-text search on ENDUSER
- Partition by date on transaction tables

---

## CONFIGURATION ESSENTIALS

### .env Critical Settings
```
APP_NAME=Blazma
DB_CONNECTION=mysql
DB_HOST=localhost
QUEUE_CONNECTION=redis
PROFILE_ID=(white label ID)

# Payment Gateways
TAMARA_API_URL=https://api-sandbox.tamara.co
TAMARA_API_TOKEN=(token)
PAYFORT_MERCHANT_IDENTIFIER=(id)

# Healthcare APIs
HESN_PLUS_KEY=(key)
HESN_PLUS_SECRET=(secret)

# Cloud
AWS_BUCKET=blazma.com
AWS_ACCESS_KEY_ID=(id)
AWS_SECRET_ACCESS_KEY=(secret)

# AI
OPENAI_API_KEY=(api_key)
```

### Queue Worker Command
```bash
php artisan queue:listen --tries=1 --timeout=0
```

### Development Server
```bash
composer dev  # Starts Laravel server + queue listener + logs + vite
```

---

## KEY FILES TO UNDERSTAND

1. **routes/web.php** (1911 lines) - All web routes
2. **app/Http/Controllers/LabController.php** - Lab operations
3. **app/Http/Controllers/WebController.php** - Frontend
4. **app/Services/ERPService.php** - ERP integration
5. **app/Services/LabService.php** - Lab business logic
6. **app/Services/PaymentService.php** - Payment processing
7. **app/Services/Notification/NotificationService.php** - Notifications
8. **app/Models/ENDUSERLABORDER.php** - Main order model
9. **app/Jobs/ERPInvoice.php** - Invoice sync job
10. **database/migrations/** - Schema definitions (800 files)

---

## DEPLOYMENT CHECKLIST

- [ ] PHP 8.2+ installed
- [ ] MySQL database set up
- [ ] Redis server running (for queues)
- [ ] Composer dependencies installed
- [ ] NPM dependencies installed (Vite, Tailwind)
- [ ] .env configured (DB, APIs, credentials)
- [ ] Database migrations run
- [ ] Queue worker running (redis connection)
- [ ] AWS S3 credentials configured (file storage)
- [ ] Firebase service account configured (FCM)
- [ ] Email service configured (SES or SMTP)
- [ ] ZATCA certificate (for Saudi Arabia)
- [ ] White label profile configured (if multi-tenant)
- [ ] Third-party API keys added (Tamara, PayFort, etc.)

---

## COMMON TASKS

### Run Queue Worker
```bash
php artisan queue:listen --queue=default,erp
```

### Generate Invoice
```bash
php artisan tinker
# Then: \App\Jobs\GenerateInvoiceNumber::dispatch($order_id);
```

### Create Admin User
```bash
php artisan tinker
# Then create SYSTEMUSER with role
```

### Sync to ERP
```bash
# Automatic via ERPInvoice job, or manual:
\App\Jobs\ERPInvoice::dispatch($order_id);
```

### Test Payment Gateway
```bash
# Use sandbox credentials in .env
# Tamara: https://api-sandbox.tamara.co
```

### Check Failed Jobs
```bash
# Database table: failed_jobs
php artisan queue:failed
php artisan queue:retry {id}
```

---

## PROJECT ARCHITECTURE NOTES

✅ **Strengths:**
- Comprehensive healthcare domain modeling
- Multiple payment gateway support
- Extensive third-party integrations
- Background job processing for scalability
- Multi-tenant white label support
- Quality control workflows
- Insurance claim management
- AI-powered recommendations

⚠️ **Complexity Areas:**
- 431 models (requires careful navigation)
- Deep integration chains (order → ERP → ZATCA)
- Queue dependency (Redis required)
- Multi-currency/multi-language support
- Regulatory compliance (ZATCA, NPHIES)

🎯 **Best Practices Used:**
- Service-oriented architecture
- Queue jobs for async operations
- Trait composition for shared functionality
- Migration versioning
- Environment-based configuration
- Role-based access control

---

## DOCUMENTATION LOCATION

Full technical documentation available at:
```
/var/www/html/blazmaNew/TECHNICAL_DOCUMENTATION.md (1062 lines)
```

This quick reference covers the essential details needed to work with the Blazma platform.

