# System Design Overview

## 1. Purpose & Scope
Sekaya is a Laravel 12 application providing an administrative and operational platform for managing associations, initiatives, projects, licensing, orders, performance tracking, and related domain entities. This document presents the high-level architecture, major subsystems, data flow, integration points, and non-functional design considerations (security, scalability, resilience, observability).

## 2. High-Level Architecture
The system follows a modular monolith pattern built on Laravel. Core layers:
- **Presentation Layer**: FilamentPHP (admin panel), Livewire v3 interactive components, Tailwind/Alpine-enhanced Blade views.
- **Application Layer**: HTTP Controllers, Filament Resources, Livewire components, Actions & Services orchestrating business logic.
- **Domain Layer**: Eloquent Models encapsulating relationships, domain invariants, permissions (Spatie Roles/Permissions), activity logging.
- **Infrastructure Layer**: Queues (Laravel Queue), Storage (DigitalOcean Object Storage), Database (PostgreSQL), Caching (Redis optional), SMS (Unifonic), Logging & Monitoring (Activity Log + Sentry), Media Library handling.

Requests flow through HTTP routing → middleware (auth, localization, permission checks) → controllers / Filament resources → services / models → persistence. Real-time-like interactions are provided via Livewire’s round-trip lifecycle.

## 3. Core Modules / Subsystems
1. **User & Authentication**: Laravel Breeze/Fortify style auth, Spatie Permissions for RBAC, FilamentUser contracts for panel access.
2. **Associations Management**: CRUD of associations, licensing verification, geographic scope management, audit logging.
3. **Licensing & Compliance**: License entities, expiration tracking, validation workflows, automated status updates.
4. **Projects & Initiatives**: Project charter, tasks, performance metrics, relational links to associations and users.
5. **Orders & Transactions**: Order creation (including location auto-map feature), status lifecycle.
6. **Location & Mapping**: State/City coordinate management with auto-map positioning logic (service-driven fallback chain).
7. **Media & Files**: Uploads handled by Spatie Media Library to S3; versioned, secure, permission-controlled access.
8. **Notifications & Messaging**: Email (Laravel Mail), SMS via Unifonic channel, system notifications in Filament.
9. **Activity & Audit Logging**: Spatie Activitylog for traceability of create/update/delete events.
10. **Migration & Legacy Data Import**: Commands for validating and migrating legacy database entities safely.
11. **Performance & Analytics**: Filament tables, dashboards, metrics widgets (extensible for KPIs).

## 4. Data Flow Overview
- **CRUD Operations**: Filament Resources define form schemas → validation → model persistence → activity logging → media attachments.
- **Interactive Updates**: Livewire components maintain server-side state; user events trigger server round trips; diffed DOM updates returned.
- **Background Processing**: Time-consuming tasks (imports, notifications, large data transformations) dispatched to queue workers.
- **External Integrations**: SMS events call Unifonic channel; file operations route to S3 driver; Sentry receives error events.
- **Legacy Migration**: Console commands read from old database connection (read-only) → transform/map → transactional write to primary DB.

### Example Request Lifecycle
1. User submits Filament form to create a License.
2. Input validated (Filament schema + optional FormRequest).
3. Service layer assigns default status, calculates derived fields (e.g., slug, expiration normalization).
4. Model saved (Eloquent). Activitylog records changes. Media attachments stored on S3.
5. Post-create events dispatched (e.g., send notification).

## 5. Security Architecture
- **RBAC**: Spatie Permissions define granular prefixes (view, create, update, delete, restore, force_delete). Resources implement permission checks per action.
- **Authentication**: Session-based, CSRF protection enabled, password hashing via Laravel.
- **Input Validation**: Filament form rules + FormRequest classes for complex scenarios.
- **Data Protection**: Proper mass-assignment control (`fillable`/`guarded`), encryption for sensitive attributes (if configured), S3-controlled access policies.
- **Audit & Traceability**: Activity logs retained for key entities; can be reviewed for compliance.
- **Environment Separation**: Credentials loaded via `.env`; no secrets committed.
- **Defense in Depth**: Middleware chains (auth, permission, throttling if applied), database constraints, prepared statements (via Eloquent), queue isolation.

## 6. Scalability & Performance
- **Horizontal Scalability**: Stateless HTTP nodes behind load balancer; queue workers scaled independently.
- **Database Optimization**: Proper indexing (foreign keys, frequently queried columns), eager loading to avoid N+1.
- **Caching (Optional)**: Redis for sessions, cache, queue; can add model & query caching.
- **Asynchronous Work**: Queue offloads heavy jobs (imports, notifications). Batch processing for migrations.
- **Media & Asset Delivery**: S3 + optional CDN (CloudFront) for file distribution.
- **Optimization Tools**: `php artisan filament:optimize` for production panel performance; config/opcache caching.

## 7. Resilience & Reliability
- **Transactional Integrity**: Critical operations wrapped in DB transactions.
- **Retry & Backoff**: Queue jobs can be retried; failed jobs logged for inspection.
- **Graceful Degradation**: Non-essential widgets degrade without affecting core CRUD.
- **Backups**: Regular automated database and S3 backup strategy (see Server Key Features doc).

## 8. Observability
- **Logging**: Structured application logs; activity logs for domain events.
- **Monitoring**: Sentry for error aggregation; could integrate metrics (Prometheus) externally.
- **Tracing**: Laravel events and job IDs provide correlation; potential for OpenTelemetry integration.

## 9. Deployment Topology (Recommended)
- **Web Tier**: Containerized Laravel app (PHP-FPM + Nginx) or single image on managed platform (ECS/Fargate, Kubernetes, or Laravel Vapor alternative if adopted).
- **Queue Tier**: Dedicated worker containers scaled by workload.
- **Cache/Session**: Redis cluster (optional but recommended for scale).
- **Database**: Managed RDS (MySQL/PostgreSQL) with read replica for reporting if needed.
- **Storage**: DigitalOcean Object Storage bucket with lifecycle policies.
- **CDN**: CloudFront for media + static assets.

## 10. Extensibility Strategy
- **Modular Services**: New business capabilities added via services under `app/Services` and Filament Resources.
- **Events & Listeners**: Domain events support decoupled side-effects.
- **Policies & Permissions**: New resources integrate with permission prefixes seamlessly.
- **API Layer (Future)**: Eloquent API Resources can expose versioned REST endpoints if client-facing integration grows.

## 11. Risks & Mitigations
| Risk | Impact | Mitigation |
|------|--------|------------|
| Large legacy import slows DB | Performance degradation | Batch size tuning; queue offload; index verification |
| N+1 queries in complex tables | Increased latency | Consistent eager loading guidelines; profiling |
| Misconfigured permissions | Unauthorized access or blockage | Permission prefix standardization; automated tests |
| Media storage cost growth | Increased operational cost | Lifecycle policies; compression; CDN caching |
| Queue backlog | Delayed asynchronous tasks | Auto scale workers; job prioritization |

## 12. Compliance & Governance
- **Audit Trails**: Activity logging ensures traceability.
- **Data Residency**: Configurable region via chosen AWS services.
- **PII Handling**: Secure storage, encryption at rest (DigitalOcean Databases & S3), transport security (HTTPS/TLS).

## 13. Cross-References
For complementary detail consult:
- `DATABASE_DESIGN.md` – Table structures, indexing, migration patterns.
- `TECH_STACK.md` – Specific frameworks, versions, and rationale.
- `HOSTING_SERVER_TYPE.md` – Recommended infrastructure topology.
- `SERVER_KEY_FEATURES.md` – Operational, security, and resilience capabilities.

## 14. Summary
Sekaya’s system design emphasizes clean domain boundaries, secure and auditable operations, and readiness for horizontal scale through container deployment and asynchronous processing. The modular monolith approach accelerates development while leaving a path open for future service extraction if warranted.
