# Laravel Technical Architecture Blueprint
## Kampong Speu Provincial Demographic Management System (KSP-DMS)

**Document Code:** KSP-DMS-DOC-ARCH-01  
**Architecture Style:** Modular Monolith (MVC + Service Layer)  
**Target Runtime:** PHP 8.2 (Windows 11 / XAMPP)  
**Framework Version:** Laravel 10.x LTS / 11.x  
**Version:** 1.0 (Draft Proposal)  

---

## 1. Architectural Philosophy and Design Principles

KSP-DMS is engineered around five fundamental software architecture principles:
1. **Local-First Independence:** The application has zero runtime reliance on external SaaS APIs, CDN assets, or cloud database clusters. All CSS, JavaScript, fonts, and GeoJSON files are served locally.
2. **Separation of Concerns:** Business logic is decoupled from HTTP controllers into dedicated domain Services and Actions.
3. **Geographic Global Scopes:** Database queries automatically inherit the authenticated user's geographic boundary constraints through Eloquent Global Scopes.
4. **Strict Type Safety and Form Requests:** All input validation is isolated in dedicated Laravel `FormRequest` classes with bilingual validation rules.
5. **Stateless API & Stateful Web:** Blade web interfaces use secure cookie-based session state with CSRF protection; mobile REST endpoints use stateless Laravel Sanctum bearer tokens.

---

## 2. Directory Layout & Module Structure

```
ksp-dms/
├── app/
│   ├── Enums/                     # Typed enumerations (SubmissionStatus, Gender, EventType)
│   ├── Http/
│   │   ├── Controllers/           # Web MVC Controllers
│   │   │   ├── Admin/             # User & Geographic administration
│   │   │   ├── Api/V1/            # Versioned REST API controllers
│   │   │   ├── Demographic/       # Household, Person, Member controllers
│   │   │   ├── Event/             # Birth, Death, Migration controllers
│   │   │   └── Workflow/          # Submission, Review, Approval controllers
│   │   ├── Middleware/            # GeoScopeMiddleware, RoleMiddleware, LocaleMiddleware
│   │   └── Requests/              # Dedicated FormRequest validation classes
│   ├── Models/                    # Eloquent ORM Models with Scopes and Relationships
│   │   ├── Scopes/                # GeographicScope (Village/Commune/District isolation)
│   │   ├── Province.php
│   │   ├── District.php
│   │   ├── Commune.php
│   │   ├── Village.php
│   │   ├── Household.php
│   │   ├── Person.php
│   │   ├── HouseholdMember.php
│   │   ├── BirthEvent.php
│   │   ├── DeathEvent.php
│   │   ├── MigrationEvent.php
│   │   ├── DataSubmission.php
│   │   ├── AuditLog.php
│   │   └── DataQualityIssue.php
│   ├── Policies/                  # Authorization policies (HouseholdPolicy, EventPolicy)
│   └── Services/                  # Business logic services
│       ├── DemographicService.php # Household and member orchestration
│       ├── EventService.php       # Vital event processing and side effects
│       ├── SubmissionService.php  # Multi-tier review state machine
│       ├── QualityEngineService.php # Anomaly detection algorithms
│       ├── GisService.php         # GeoJSON aggregation builder
│       └── AuditService.php       # Immutable tamper-evident logging
├── config/                        # Laravel core configuration
├── database/
│   ├── factories/                 # Synthetic Cambodian test data generators
│   ├── migrations/                # Schema migrations in dependency order
│   └── seeders/                   # Administrative baseline & demo dataset seeders
├── resources/
│   ├── lang/                      # Bilingual localization dictionary
│   │   ├── en/                    # English translation strings
│   │   └── km/                    # Khmer translation strings (ភាសាខ្មែរ)
│   ├── js/                        # Leaflet GIS and Bootstrap scripts
│   ├── scss/ / css/               # Customized styling and Khmer typography rules
│   └── views/                     # Blade templates
│       ├── layouts/               # Master administrative layout with bilingual header
│       ├── dashboard/             # Executive statistical widgets
│       ├── households/            # Household CRUD and membership history
│       ├── persons/               # Citizen profiles
│       ├── events/                # Vital event registration forms
│       ├── workflow/              # Submission review and approval queues
│       ├── gis/                   # Leaflet thematic map explorer
│       └── reports/               # Demographic tables & population pyramids
├── routes/
│   ├── web.php                    # Web portal routes with session & CSRF protection
│   └── api.php                    # REST API v1 routes with Sanctum auth
└── tests/
    ├── Feature/                   # Comprehensive end-to-end integration tests
    └── Unit/                      # Domain logic and service unit tests
```

---

## 3. Core Component Pipelines

### 3.1 Geographic Isolation Pipeline (Middleware + Scope)
```
[Inbound HTTP Request]
         |
         v
[Authenticate User]
         |
         v
[GeoScopeMiddleware: Extracts user's assigned scope (Province, District, Commune, or Village)]
         |
         v
[Eloquent Model Global Scope (GeographicScope)]
         |
         v
[Appends `WHERE village_id IN (...)` automatically to every SELECT / UPDATE / DELETE]
         |
         v
[Database Execution via Prepared Statement]
```

### 3.2 Vital Event Side-Effect Processing
When a Vital Event (e.g. Death) is approved:
1. `EventService::approveDeath(DeathEvent $event)` initiates a database transaction.
2. Updates `DeathEvent` status to `APPROVED`.
3. Updates `Person` status to `DECEASED`.
4. Closes active `HouseholdMember` record with `end_date = death_date` and `residency_status = DECEASED`.
5. If the deceased was `is_head = true`, creates a `DataQualityIssue` flag alerting administrators to reassign the Head of Household.
6. Writes comprehensive record to `audit_logs`.
7. Commits transaction.

---

## 4. Technology Selection Rationale

| Requirement | Selected Technology | Technical Justification |
| :--- | :--- | :--- |
| **Server Engine** | PHP 8.2 + Laravel | Native XAMPP compatibility, robust ORM, built-in CSRF/Auth, rapid execution. |
| **Database** | MariaDB 10.4 (InnoDB) | High-concurrency ACID transactions, UTF8mb4 full unicode Khmer support. |
| **GIS Visualization** | Leaflet JS v1.9 | Lightweight (39KB), zero external API key requirements, runs offline. |
| **API Auth** | Laravel Sanctum | Lightweight token authentication, perfect for mobile sync without OAuth2 complexity. |
| **Styling** | Bootstrap 5.3 + Custom CSS | Clean, responsive, full support for Khmer font baseline alignment. |
