# BLAZMA PROJECT - DOCUMENTATION INDEX

## 📋 Available Documentation

This project has been comprehensively analyzed and documented for AI-powered code generation and documentation. All documentation is in Markdown format for easy integration with AI tools.

### 📄 Main Documentation Files

1. **TECHNICAL_DOCUMENTATION.md** (36 KB, 1062 lines)
   - **Purpose**: Complete technical reference
   - **Contents**:
     - Project overview & business domain
     - Complete directory structure
     - All 431 models with relationships & fillable fields
     - All 42 controllers with methods
     - Route organization (200+)
     - All 107 services with descriptions
     - Queue jobs configuration (49 jobs)
     - Database schema highlights (800 migrations)
     - Configuration file guide
     - Dependencies (composer.json, package.json)
     - External API integrations (16+)
     - Security & authorization
     - Business workflows (10 critical)
     - System statistics & metrics

2. **QUICK_REFERENCE.md** (10 KB)
   - **Purpose**: Quick lookup guide
   - **Contents**:
     - At-a-glance project summary
     - Key statistics
     - Core entities & relationships
     - Main workflows (5 critical paths)
     - Critical services (top 20)
     - Queue jobs overview
     - External integrations
     - Configuration essentials
     - Common tasks with examples
     - Deployment checklist

3. **DOCUMENTATION_INDEX.md** (this file)
   - **Purpose**: Navigation guide
   - **Contents**: This index and directory structure

---

## 🗂️ Project Structure

### **Core Application** (`/app`)
- **Models/** (431 total)
  - Primary models: ENDUSER, HOSPITAL, PROFILE, LABCATEGORYPACKAGE
  - Transaction models: ENDUSERLABORDER, INVOICE, PAYMENT
  - Integration models: ERPINTEGRATION, ZATCA_INVOICE, INSURANCE*
  - Utility models: ALERT, QC, NOTIFICATION*, ROLE, PERMISSION

- **Services/** (107 total)
  - Payment: PaymentService, PayfortService, TamaraService, etc.
  - Lab: LabService, NormalReportService, SmartReportService
  - Integration: ERPService, HESNPlusService, NphiesService, ZatcaService
  - Notification: EmailService, SMSService, FCMService, NotificationService
  - Utility: FileService, QRService, TaxService, etc.

- **Http/Controllers/** (42 total)
  - Main: LabController, WebController, ApiController (40)
  - V2: TerminalController (API v2)
  - Operations: CorrectiveActionsController

- **Http/Middleware/** (13 custom)
  - Authentication: WebAuth, AccessTokenValidation, Authenticate
  - API Auth: AyenatiTokenAuth, LdmAuth, MetaDataAuth, NupcoAuth, TerminalAuth
  - Utility: CorsMiddleware, NormalizeSlashes

- **Jobs/** (49 background jobs)
  - ERP: ERPInvoice, ERPRefund, ERPMovement (8 jobs)
  - Notification: NotificationPush, SendEmailNotificationJob (4 jobs)
  - Integration: HESNPlusSendData, ZatcaB2BInvoice, NphiesResultStatusUpdate (3 jobs)
  - Report: SmartReportReady, TatAnalysisReport, HisResultReady (3 jobs)
  - HL7: SendHL7InProcessMessageJob (1 job)
  - Others: GenerateAiRecommendationJob, PurchaseOrderJob, etc. (30 jobs)

- **Console/Commands/** (20+ CLI commands)
  - Database: MigrateQuestionnaireDataCommand, EnableResultAndOption
  - Alert: AlertFired, AlertEscalation
  - Financial: GenerateInvoiceNumber, AutoApprovalCommand
  - Maintenance: RepairEncryptedPdfs, UpdateDuplicatedInvoiceNumber
  - Others: SalesForecastCommand, AutoValidateCommand, etc.

- **Exports/** (20+ Excel exporters)
- **Imports/** (10 Excel importers)
- **Traits/** (1 main trait + 12 service traits)
- **Helpers/** (2 helper files)

### **Routes** (`/routes`)
- **web.php**: 1,911 lines
  - Public routes: /, /package, /offers, /signin, /signup
  - Authenticated routes: /cart, /order, /profile (WebAuth)
  - Payment routes: /tamara/payment, /cod_order, /credit_order
  - API routes: /lab, /orders, /results

### **Database** (`/database`)
- **migrations/**: 800 migration files
  - Schema: CREATE/ALTER/DROP operations
  - Constraints: Foreign keys, indexes
  - Coverage: All 431 models backed by migrations
  
- **seeders/**: Data seeding scripts
- **factories/**: Model factories for testing

### **Configuration** (`/config`)
- **app.php**: Application configuration
- **database.php**: MySQL connection (blazma database)
- **queue.php**: Redis queue configuration
- **mail.php**: Email setup (SES/SMTP)
- **services.php**: Third-party service configs
- **auth.php**: Authentication settings
- **cache.php**: Caching configuration
- **filesystems.php**: AWS S3 configuration
- **alert.php**: Alert system config
- **payfort.php**: PayFort configuration
- **horizon.php**: Queue monitoring
- Plus 8 more...

---

## 🔄 Data Flow & Key Workflows

### **Order to Invoice Workflow**
```
ENDUSER (patient)
  ↓ selects
LABCATEGORYPACKAGE (test/package)
  ↓ adds to
ENDUSERLABCART (shopping cart)
  ↓ checkout & pay via
PAYMENT (Tamara/PayFort/TAP/COD)
  ↓ creates
ENDUSERLABORDER (order header)
  ↓ contains
ENDUSERLABORDERPACKAGE (line items)
  ↓ generates
INVOICE (billing record)
  ↓ syncs to
ERPINTEGRATION → ERPInvoice Job → ERP (SAP/Focus/Dynamic)
```

### **Sample to Result Workflow**
```
ENDUSERLABORDER
  ↓ schedules
LABAVAILABLETIME (collection slot)
  ↓ collects sample
SAMPLEGENERATION (batch)
  ↓ stores in
ENDUSERSAMPLESTORAGEUNIT (storage location)
  ↓ runs QC
QC → QCRESULT (Westgard rules)
  ↓ analyzes
ENDUSERLABORDERPACKAGERESULT (test result)
  ↓ validates & approves
LAB_ORDER_STATUS_ID = 4 (completed)
  ↓ generates report & sends
NotificationPush Job → ENDUSERNOTIFICATION
```

### **Insurance Claim Workflow**
```
ENDUSERLABORDER (with INSURANCE_ID)
  ↓ submits to
INSURANCEAPPROVAL (approval request)
  ↓ sends to
NPHIES API (insurance system)
  ↓ receives
INSURANCECLAIM (claim record)
  ↓ tracks
INSURANCEINVOICE (insurance billing)
```

---

## 🔌 External Integrations

### **Payment Gateways**
- Tamara (BNPL): https://api-sandbox.tamara.co
- PayFort (Amazon): Credit/debit cards
- TAP: Payment platform
- NearPay: Saudi payments
- Wallet: Prepaid system
- COD: Cash on delivery

### **Healthcare/Insurance**
- HESN Plus: National health ID
- NPHIES: Insurance claims
- Ayenati: Health data exchange
- HL7: Medical messaging
- LDM: Lab data management
- LiveHealth: Telemedicine
- ZATCA: E-invoice (Saudi)

### **Cloud Services**
- AWS S3: File storage
- AWS SES: Email
- Firebase: Push notifications

### **Utilities**
- Scandit: Barcode scanning
- OpenAI: AI recommendations
- Google Chat: Logging

---

## 🔐 Authentication & Security

### **Authentication Methods**
1. **WebAuth**: Session-based frontend
2. **AccessTokenValidation**: API token
3. **AyenatiTokenAuth**: Ayenati API
4. **LdmAuth**: LDM API
5. **TerminalAuth**: Terminal/POS
6. **OperationsAuth**: Operations module

### **Authorization**
- Role-Based Access Control (RBAC)
- Model-level checks
- Profile-based multi-tenancy

---

## 📊 Key Statistics

| Metric | Count |
|--------|-------|
| Models | 431 |
| Controllers | 42 |
| Services | 107 |
| Jobs | 49 |
| Migrations | 800 |
| Routes | 200+ |
| Middleware | 13 |
| Commands | 20+ |
| External APIs | 16+ |
| PHP Dependencies | 40 |
| NPM Dependencies | 6 |

---

## 🚀 Getting Started with Documentation

### For API Documentation Generation
1. Start with **TECHNICAL_DOCUMENTATION.md** → "5. CONTROLLERS"
2. Reference **QUICK_REFERENCE.md** → "MAIN WORKFLOWS"
3. Use model details from → "3. MODELS"
4. Check routes in → "5. ROUTES"

### For System Architecture Diagrams
1. Review **TECHNICAL_DOCUMENTATION.md** → "2. DIRECTORY STRUCTURE"
2. Study **TECHNICAL_DOCUMENTATION.md** → "19. DATABASE SCHEMA HIGHLIGHTS"
3. Reference workflows in → "18. KEY BUSINESS WORKFLOWS"

### For Integration Documentation
1. Check **QUICK_REFERENCE.md** → "EXTERNAL INTEGRATIONS"
2. Reference **TECHNICAL_DOCUMENTATION.md** → "16. API INTEGRATIONS"
3. Review service details → "6. SERVICES"

### For Deployment & Setup
1. Review **QUICK_REFERENCE.md** → "DEPLOYMENT CHECKLIST"
2. Check .env variables in → "11. CONFIGURATION FILES"
3. Review queue setup in → "7. JOBS"

### For Database Documentation
1. Check **TECHNICAL_DOCUMENTATION.md** → "10. DATABASE MIGRATIONS"
2. Review schema in → "19. DATABASE SCHEMA HIGHLIGHTS"
3. Reference model relationships → "3. MODELS"

---

## 📝 Documentation Maintenance

This documentation is generated from a complete code analysis covering:
- ✅ All 431 models with relationships
- ✅ All 42 controllers with methods
- ✅ All 107 services with responsibilities
- ✅ All 49 queue jobs
- ✅ All 800 migrations
- ✅ 20 configuration files
- ✅ 13 middleware classes
- ✅ 40 composer/npm dependencies
- ✅ 16+ third-party integrations

**Last Updated**: March 11, 2025
**Analysis Scope**: 100% of primary codebase
**Documentation Format**: Markdown (AI-ready)

---

## 🎯 Using Documentation with AI Tools

This documentation is specifically structured for AI tools such as:
- **ChatGPT/Claude**: Paste sections for code analysis
- **GitHub Copilot**: Use as context for code completion
- **Documentation Generators**: Feed to create API docs
- **Diagram Generators**: Use for UML/flowchart generation
- **Code Generators**: Reference for code scaffolding

Each section is self-contained and can be extracted independently.

---

## 📚 File Locations

```
/var/www/html/blazmaNew/
├── TECHNICAL_DOCUMENTATION.md    ← Main reference (1062 lines)
├── QUICK_REFERENCE.md            ← Quick lookup (400 lines)
├── DOCUMENTATION_INDEX.md        ← This file
├── app/
│   ├── Models/                   ← 431 Eloquent models
│   ├── Services/                 ← 107 service classes
│   ├── Http/Controllers/         ← 42 controllers
│   ├── Jobs/                     ← 49 queue jobs
│   ├── Console/Commands/         ← 20+ CLI commands
│   └── ...
├── routes/
│   └── web.php                   ← 1,911 route lines
├── database/
│   └── migrations/               ← 800 migration files
├── config/                       ← 20 configuration files
├── composer.json                 ← PHP dependencies
├── package.json                  ← NPM dependencies
└── .env                          ← Environment config
```

---

## 🔍 Quick Navigation

**Need to find?**
- **A specific model**: See TECHNICAL_DOCUMENTATION.md → "3. MODELS"
- **A controller method**: See TECHNICAL_DOCUMENTATION.md → "4. CONTROLLERS"
- **A service**: See TECHNICAL_DOCUMENTATION.md → "6. SERVICES"
- **How a workflow works**: See QUICK_REFERENCE.md → "MAIN WORKFLOWS"
- **Configuration options**: See TECHNICAL_DOCUMENTATION.md → "11. CONFIGURATION"
- **External APIs**: See TECHNICAL_DOCUMENTATION.md → "16. API INTEGRATIONS"
- **Database tables**: See TECHNICAL_DOCUMENTATION.md → "19. DATABASE SCHEMA"
- **Background jobs**: See QUICK_REFERENCE.md → "QUEUE JOBS"

---

## 💡 Key Insights

**Blazma is:**
- ✅ Enterprise-grade Laboratory Management System
- ✅ Multi-tenant (white label support)
- ✅ Healthcare-focused (Saudi Arabia)
- ✅ Integration-heavy (16+ external APIs)
- ✅ Payment-diverse (6 gateway options)
- ✅ Async-first (Redis queue, 49 jobs)
- ✅ Scalable (service-oriented, 107 services)
- ✅ Regulated (ZATCA, NPHIES, HL7 compliance)

**Main Transaction Flow:**
Patient → Order → Payment → ERP Sync → Sample → Analysis → Result → Notification

**Core Models:**
ENDUSER → ENDUSERLABORDER → ENDUSERLABORDERPACKAGE → LABCATEGORYPACKAGE

---

**End of Documentation Index**

For questions or updates, refer to the main documentation files.
