# Patrol Management System Documentation

## System Overview

The Patrol Management System is a comprehensive Laravel-based solution designed to manage security patrol operations with strict client isolation and contract-driven functionality. The system follows a hierarchical structure ensuring data integrity and access control.

## System Hierarchy

### 1. Client Setup (Top Level)
- **Purpose**: Master client information and contract management
- **Entity**: `Client`
- **Key Fields**: name, address, contract period, service scope
- **Isolation**: Complete data separation between clients

### 2. Client-Based Services (Second Level)
- **Purpose**: Define service locations/zones under each client
- **Entity**: `ClientService`
- **Key Fields**: service_name, location_name, zone_area, service_type
- **Relationship**: Belongs to Client, has many Checkpoints

### 3. Checkpoint Management (Third Level)
- **Purpose**: Physical patrol points with QR code mapping
- **Entity**: `PatrolCheckpoint`
- **Key Fields**: checkpoint_code, checkpoint_name, GPS coordinates
- **Relationship**: Belongs to ClientService, has one QR Code

### 4. QR Code Generation
- **Purpose**: Unique QR codes for each checkpoint
- **Entity**: `CheckpointQRCode`
- **Features**: Digital signatures, expiration, validation
- **Security**: Fixed to physical location, non-transferable

### 5. Patrol Scheduling
- **Purpose**: Time-based patrol assignments
- **Entity**: `PatrolSchedule` + `PatrolTimeSlot`
- **Features**: Multiple time slots, repeat patterns, employee assignment
- **Validation**: Schedule-based access control

### 6. Employee Assignment
- **Purpose**: Map employees to client services
- **Entity**: `EmployeeAssignment`
- **Validation**: Service-based access permissions
- **Security**: Prevents cross-client access

### 7. Patrol Clocking & Reporting
- **Purpose**: Real-time patrol tracking and reporting
- **Entities**: `QRScan`, `PatrolLog`, `PatrolViolation`, `PatrolReport`
- **Features**: Geofence validation, time window checking, approval workflow

## Database Schema

### Core Tables

#### clients
```sql
- id (PK)
- name, email, phone, address
- status_id, tenant_id
- timestamps, soft_deletes
```

#### client_services
```sql
- id (PK)
- client_id (FK → clients)
- service_name, location_name, zone_area
- service_type (patrolling/security/monitoring)
- is_active, tenant_id
- timestamps, soft_deletes
```

#### patrol_checkpoints
```sql
- id (PK)
- service_id (FK → client_services)
- checkpoint_code, checkpoint_name
- latitude, longitude
- required_time, tolerance_minutes
- is_active, tenant_id
- timestamps
```

#### checkpoint_qr_codes
```sql
- id (PK)
- checkpoint_id (FK → patrol_checkpoints)
- qr_code (JSON with signature)
- qr_code_path (file location)
- is_active, generated_at, expires_at
- tenant_id
- timestamps
```

#### patrol_schedules
```sql
- id (PK)
- client_id (FK → clients)
- service_id (FK → client_services)
- employee_id (FK → users)
- schedule_name, schedule_date
- repeat_pattern (once/daily/weekly/monthly/custom)
- repeat_config (JSON)
- is_active, status_id, tenant_id
- timestamps, soft_deletes
```

#### patrol_time_slots
```sql
- id (PK)
- schedule_id (FK → patrol_schedules)
- day_of_week, start_time, end_time
- break_duration, is_active
- tenant_id
- timestamps
```

#### employee_assignments
```sql
- id (PK)
- client_id (FK → clients)
- service_id (FK → client_services)
- employee_id (FK → users)
- assignment_type, start_date, end_date
- is_active, tenant_id
- timestamps, soft_deletes
```

#### qr_scans
```sql
- id (PK)
- qr_code_id (FK → checkpoint_qr_codes)
- checkpoint_id (FK → patrol_checkpoints)
- employee_id (FK → users)
- scan_time, latitude, longitude, accuracy
- scan_result (success/failed/invalid)
- notes, photos (JSON)
- tenant_id
- timestamps
```

#### patrol_logs
```sql
- id (PK)
- schedule_id (FK → patrol_schedules)
- checkpoint_id (FK → patrol_checkpoints)
- employee_id (FK → users)
- check_in_time, latitude, longitude
- status (on_time/late/missed/skipped)
- deviation_minutes, notes, photos
- tenant_id
- timestamps
```

#### patrol_violations
```sql
- id (PK)
- schedule_id (FK → patrol_schedules)
- checkpoint_id (FK → patrol_checkpoints)
- employee_id (FK → users)
- violation_type (missed_checkpoint/late_checkpoint/wrong_location)
- violation_time, latitude, longitude
- is_resolved, resolved_by, resolved_at
- tenant_id
- timestamps
```

#### patrol_reports
```sql
- id (PK)
- report_id (unique)
- client_id (FK → clients)
- service_id (FK → client_services)
- report_type (summary/performance/violations/coverage)
- report_period, start_date, end_date
- data (JSON), summary (JSON)
- status (draft/pending/checked/approved/rejected)
- prepared_by, checked_by, approved_by
- prepared_at, checked_at, approved_at
- tenant_id
- timestamps, soft_deletes
```

## Key Features

### 1. Client-Contract Driven Logic
- **Service Scope Validation**: Contracts define allowed service types
- **Time-Based Access**: Contract periods control system access
- **Data Isolation**: Complete separation of client data

### 2. QR Code Security
- **Digital Signatures**: SHA256 signatures prevent tampering
- **Location Binding**: QR codes fixed to GPS coordinates
- **Expiration Control**: Time-based QR code validity
- **Unique Mapping**: One QR code per checkpoint

### 3. Multi-Level Validation
- **Contract Validation**: Is client contract active and valid?
- **Service Validation**: Is employee assigned to this service?
- **Schedule Validation**: Is current time within scheduled hours?
- **Geofence Validation**: Is scan within acceptable GPS range?

### 4. Patrol Scheduling
- **Flexible Patterns**: Daily, weekly, monthly, custom schedules
- **Multiple Time Slots**: Several patrol windows per day
- **Repeat Configuration**: JSON-based schedule rules
- **Employee Assignment**: Service-based employee mapping

### 5. Reporting & Verification
- **Approval Workflow**: Prepare → Check → Approve
- **Report Types**: Summary, Performance, Violations, Coverage
- **Export Options**: PDF, Excel, CSV formats
- **Audit Trail**: Complete action history

## API Endpoints

### Client Management
```
GET    /api/clients                 - List clients
POST   /api/clients                 - Create client
GET    /api/clients/{id}            - Show client
PUT    /api/clients/{id}            - Update client
DELETE /api/clients/{id}            - Delete client
```

### Service Management
```
GET    /api/clients/{id}/services   - List client services
POST   /api/clients/{id}/services   - Create service
GET    /api/services/{id}          - Show service
PUT    /api/services/{id}           - Update service
DELETE /api/services/{id}           - Delete service
```

### Checkpoint Management
```
GET    /api/services/{id}/checkpoints     - List checkpoints
POST   /api/services/{id}/checkpoints     - Create checkpoint
GET    /api/checkpoints/{id}              - Show checkpoint
PUT    /api/checkpoints/{id}              - Update checkpoint
DELETE /api/checkpoints/{id}              - Delete checkpoint
POST   /api/checkpoints/{id}/qr-code      - Generate QR code
GET    /api/checkpoints/{id}/qr-code      - Get QR code
```

### Schedule Management
```
GET    /api/services/{id}/schedules       - List schedules
POST   /api/services/{id}/schedules       - Create schedule
GET    /api/schedules/{id}                - Show schedule
PUT    /api/schedules/{id}                - Update schedule
DELETE /api/schedules/{id}                - Delete schedule
POST   /api/schedules/{id}/time-slots     - Add time slot
PUT    /api/time-slots/{id}               - Update time slot
DELETE /api/time-slots/{id}               - Delete time slot
```

### Employee Assignment
```
GET    /api/services/{id}/assignments     - List assignments
POST   /api/services/{id}/assignments     - Create assignment
GET    /api/assignments/{id}              - Show assignment
PUT    /api/assignments/{id}              - Update assignment
DELETE /api/assignments/{id}              - Delete assignment
```

### QR Scanning
```
POST   /api/qr-scans                      - Process QR scan
GET    /api/qr-scans                      - List scans
GET    /api/qr-scans/{id}                 - Show scan details
```

### Patrol Logs
```
GET    /api/patrol-logs                   - List patrol logs
GET    /api/patrol-logs/{id}              - Show log details
POST   /api/patrol-logs                   - Create manual log
```

### Reports
```
GET    /api/reports                       - List reports
POST   /api/reports                       - Generate report
GET    /api/reports/{id}                  - Show report
PUT    /api/reports/{id}/check            - Check report
PUT    /api/reports/{id}/approve          - Approve report
PUT    /api/reports/{id}/reject           - Reject report
GET    /api/reports/{id}/export/pdf       - Export PDF
GET    /api/reports/{id}/export/excel     - Export Excel
```

## Security Features

### 1. Data Isolation
- **Tenant-Based**: All queries filtered by tenant_id
- **Client Separation**: No cross-client data access
- **Service Boundaries**: Employees limited to assigned services

### 2. Access Control
- **Role-Based**: Different permissions for different user types
- **Assignment-Based**: Access based on employee assignments
- **Time-Based**: Schedule-based access windows

### 3. Validation Layers
- **Contract Validation**: Active contract requirement
- **Service Validation**: Employee-service assignment check
- **Schedule Validation**: Time window enforcement
- **Geofence Validation**: GPS location verification

### 4. Audit Trail
- **Complete Logging**: All actions recorded
- **User Tracking**: Who did what, when
- **Data Integrity**: Soft deletes prevent data loss

## Mobile App Integration

### QR Scanning Flow
1. **Validation**: Check QR code validity and signature
2. **Authorization**: Validate employee assignment
3. **Schedule Check**: Verify time window
4. **Geofence**: Validate GPS location
5. **Recording**: Create scan and log records
6. **Violation Handling**: Auto-create violations for issues

### Required Permissions
- Camera access for QR scanning
- Location services for GPS validation
- Network connectivity for real-time validation
- Storage for offline capability

## Implementation Notes

### Dependencies
- Laravel 9+
- MySQL/PostgreSQL database
- SimpleSoftwareIO/qrcode for QR generation
- Intervention/image for image processing
- DomPDF/Laravel-Excel for report generation

### Performance Considerations
- Database indexing on foreign keys and frequently queried fields
- Tenant-based query optimization
- Caching for frequently accessed data
- Background job processing for report generation

### Scalability Features
- Multi-tenant architecture
- Horizontal scaling support
- Database sharding capability
- Queue-based processing for heavy operations

## Testing Strategy

### Unit Tests
- Model relationships and validations
- Service class business logic
- QR code generation and validation

### Integration Tests
- API endpoint functionality
- Database transaction integrity
- Cross-client data isolation

### Security Tests
- Authorization bypass attempts
- QR code tampering attempts
- Cross-client data access attempts

## Deployment Considerations

### Environment Variables
```
APP_KEY=                    # QR code signatures
DB_CONNECTION=              # Database configuration
DEFAULT_TENANT_ID=          # Default tenant
QR_CODE_STORAGE_PATH=       # QR code file storage
REPORT_STORAGE_PATH=        # Generated reports storage
```

### Scheduled Tasks
```bash
# Daily report generation
0 2 * * * php artisan patrol:generate-daily-reports

# Cleanup expired QR codes
0 3 * * * php artisan patrol:cleanup-expired-qr-codes

# Schedule generation for recurring patterns
0 1 * * * php artisan patrol:generate-recurring-schedules
```

### Monitoring
- Database query performance
- QR code generation success rates
- Patrol completion rates
- Violation frequency analysis

This system provides a complete, secure, and scalable solution for patrol management with strict client isolation and comprehensive reporting capabilities.
