# NE-SOS Backend Architecture

## Overview

NE-SOS is a multi-tenant incident management SaaS backend built with Laravel 11. The system is designed to handle the full incident lifecycle from citizen reporting to resolution, with strong tenant isolation and role-based access control.

## Core Architecture

### Multi-Tenancy Model

- **Tenants**: Organizations (utilities/municipalities)
- **Isolation**: Every table includes `organization_id` and is scoped by it
- **Resolution**:
  - Authenticated users: Organization determined by their account
  - Citizens: Incidents routed via Service Area mapping (geofence)

### Database Schema

#### Core Tables
- `organizations` - Tenant organizations
- `users` - System users (with nullable organization_id for SUPER_ADMIN)
- `roles` - System roles (SUPER_ADMIN, ORG_ADMIN, DISPATCHER, LEAD_AGENT, FIELD_AGENT, CITIZEN)
- `permissions` - System permissions
- `role_user` - User role assignments
- `permission_role` - Role permission assignments

#### Incident Management
- `incidents` - Main incident table
- `incident_types` - Incident type catalog (per org)
- `incident_media` - Attached media files
- `incident_status_events` - Status change history
- `assignments` - Assignment history

#### Routing & Teams
- `service_areas` - Geographic service areas (bounding boxes)
- `teams` - Agent teams
- `team_members` - Team membership

#### System
- `audit_logs` - Action audit trail
- `device_tokens` - FCM push notification tokens

### Incident Lifecycle

```
REPORTED → TRIAGED → ASSIGNED → IN_PROGRESS → RESOLVED → CLOSED
    ↓         ↓
 REJECTED  REJECTED
```

**Status Transitions:**
- Enforced at model level via `canTransitionTo()` method
- Status events logged in `incident_status_events`
- Timestamps set automatically (resolved_at, closed_at)

### Geographic Routing

**Service Areas:**
- Defined per organization
- Bounding box coordinates (min/max lat/lng)
- Future: Polygon support via `polygon_coordinates` JSON field

**Routing Logic:**
1. Find service area matching service_type and containing location
2. Route to that organization
3. Fallback to default organization for service type
4. Error if no match found

### Role-Based Access Control (RBAC)

**Roles:**
- SUPER_ADMIN: Platform owner, full access
- ORG_ADMIN: Organization administrator
- DISPATCHER: Triage and assign incidents
- LEAD_AGENT: Senior field agent
- FIELD_AGENT: Field agent
- CITIZEN: Citizen reporter

**Permissions:**
- Managed via `permissions` table
- Assigned to roles via `permission_role`
- Checked via policies (Laravel Policies)

**Access Rules:**
- Citizens: Own incidents only
- Org users: Incidents in their organization
- Super admin: All incidents
- Assignment: Only DISPATCHER/ORG_ADMIN
- Update: Agents can update assigned incidents

### API Design

**Versioning:** `/api/v1/`

**Authentication:** Laravel Sanctum (SPA token auth)

**Response Format:** JSON API Resources

**Error Handling:** Consistent JSON error responses

### Notifications

**Firebase Cloud Messaging (FCM):**
- Queue-based (database driver)
- Notifications for:
  - New incident → Dispatchers/Org Admins
  - Assignment → Assigned agent/team
  - Status change → Reporter + Org Admins

**Service Pattern:**
- `NotificationServiceInterface` abstraction
- `FcmNotificationService` implementation
- Easy to swap implementations

### File Storage

**Current:** Local filesystem (`storage/app/public`)

**Abstraction:** Ready for S3 via Laravel Filesystem

**Validation:**
- MIME type checking
- File size limits
- Configurable via `.env`

### Security Features

1. **Rate Limiting:** Incident creation endpoint
2. **File Validation:** Type and size
3. **Tenant Isolation:** Query-level enforcement
4. **RBAC:** Policy-based authorization
5. **Audit Logging:** All critical actions
6. **Input Validation:** FormRequest on all endpoints

### Testing Strategy

**Feature Tests:**
- Tenant isolation
- RBAC enforcement
- Status transitions
- Incident routing

**Test Coverage:**
- Critical business logic
- Security boundaries
- Data integrity

## Deployment Considerations

### Single VPS Deployment

- **Queue Driver:** Database (no Redis required)
- **Cache:** Database (can upgrade to Redis)
- **Storage:** Local (can upgrade to S3)
- **Session:** Database

### Scaling Path

1. **Queue:** Switch to Redis
2. **Cache:** Add Redis cache
3. **Storage:** Move to S3/CDN
4. **Database:** Read replicas
5. **Load Balancing:** Multiple app servers

## Key Design Decisions

1. **String-based assigned_to_type:** Simpler than polymorphic for MVP
2. **Bounding boxes:** Simpler than polygons for MVP, upgrade path available
3. **Database queues:** Simpler for VPS, upgrade path to Redis
4. **Local storage:** Simpler for MVP, upgrade path to S3
5. **Policy-based auth:** Laravel standard, maintainable

## Future Enhancements

1. **Polygon support:** Upgrade service areas from bounding boxes
2. **Real-time updates:** WebSockets for status changes
3. **Advanced routing:** ML-based incident routing
4. **Analytics:** Dashboard and reporting
5. **Mobile API:** Optimized endpoints for mobile apps

