# SIGED Laravel 11 Module Structure

## Overview

This document provides a comprehensive guide to the SIGED military school management system module structure. The system is organized into 17 specialized modules, each handling a specific aspect of school management.

## System Architecture

### Directory Structure

```
app/
├── Models/
│   ├── Academic/
│   ├── Grades/
│   ├── Disciplinary/
│   ├── Attendance/
│   ├── Biometric/
│   ├── Uniforms/
│   ├── Financial/
│   ├── HR/
│   ├── Payroll/
│   ├── Refectory/
│   ├── Events/
│   ├── Ceremonial/
│   ├── Sports/
│   ├── Communication/
│   ├── Analytics/
│   ├── Portal/
│   └── System/
├── Http/
│   ├── Controllers/
│   │   ├── Academic/
│   │   ├── Grades/
│   │   ├── Disciplinary/
│   │   ├── Attendance/
│   │   ├── Biometric/
│   │   ├── Uniforms/
│   │   ├── Financial/
│   │   ├── HR/
│   │   ├── Payroll/
│   │   ├── Refectory/
│   │   ├── Events/
│   │   ├── Ceremonial/
│   │   ├── Sports/
│   │   ├── Communication/
│   │   ├── Analytics/
│   │   ├── Portal/
│   │   └── System/
│   └── Requests/
│       ├── Academic/
│       ├── Grades/
│       ├── Disciplinary/
│       ├── Attendance/
│       ├── Biometric/
│       ├── Uniforms/
│       ├── Financial/
│       ├── HR/
│       ├── Payroll/
│       ├── Refectory/
│       ├── Events/
│       ├── Ceremonial/
│       ├── Sports/
│       ├── Communication/
│       ├── Analytics/
│       ├── Portal/
│       └── System/
├── Services/
│   ├── Academic/
│   ├── Grades/
│   ├── Disciplinary/
│   ├── Attendance/
│   ├── Biometric/
│   ├── Uniforms/
│   ├── Financial/
│   ├── HR/
│   ├── Payroll/
│   ├── Refectory/
│   ├── Events/
│   ├── Ceremonial/
│   ├── Sports/
│   ├── Communication/
│   ├── Analytics/
│   ├── Portal/
│   └── System/
├── Enums/
│   ├── UserRole.php
│   ├── AttendanceStatus.php
│   ├── DisciplinaryStatus.php
│   └── PaymentStatus.php
└── Traits/
    ├── HasTenancy.php
    ├── HasAudit.php
    └── (More shared traits)
```

## Core Features

### Multi-Tenancy Support
All models implement the `HasTenancy` trait, automatically filtering data by `tenant_id`. This ensures complete data isolation between different school institutions.

```php
// Automatically filters by current tenant
$students = Student::all(); // Only returns current tenant's students

// Bypass tenancy filter if needed
$allStudents = Student::withoutTenant()->all();
```

### Audit Logging
The `HasAudit` trait automatically logs all changes to models:
- Creation
- Updates
- Deletions

All audit logs are stored in the `audit_logs` table with:
- User who made the change
- What changed (old vs new values)
- IP address and user agent
- Timestamp

### Soft Deletes
Most models implement soft deletes, allowing data recovery:

```php
$student->delete(); // Soft delete
$student->restore(); // Restore deleted record
$student->forceDelete(); // Permanent deletion
```

## Module Descriptions

### 1. Academic Module

**Purpose**: Manage students, classrooms, and subjects

**Key Models**:
- `Student`: Represents a student with personal and academic information
- `Classroom`: Represents a class/turma with capacity management
- `Subject`: Represents school subjects

**Key Features**:
- Student enrollment management
- Classroom capacity tracking
- Subject assignment to classrooms
- Bulk import/export of students

**Primary Routes**:
```
/admin/academic/students          - List, create, view students
/admin/academic/classrooms        - Manage classrooms
/admin/academic/subjects          - Manage subjects
```

**Database Tables**:
- `academic_students`
- `academic_classrooms`
- `academic_subjects`
- `academic_classroom_subject` (pivot)

### 2. Grades Module

**Purpose**: Manage student grades and report cards

**Key Models**:
- `Grade`: Individual grade entries
- `Bulletin`: Report cards/boletins

**Key Features**:
- Record grades by subject and bimester
- Calculate weighted averages
- Generate student report cards
- Track grade history

**Primary Routes**:
```
/admin/grades/grades              - Record grades
/admin/grades/bulletins           - Generate and view report cards
```

**Database Tables**:
- `grades`
- `bulletins`

### 3. Disciplinary Module

**Purpose**: Manage student disciplinary records and penalties

**Key Models**:
- `DisciplinaryRecord`: Incident reports
- `Penalty`: Applied penalties
- `Appeal`: Appeals against penalties

**Key Features**:
- Record disciplinary incidents
- Apply penalties with duration tracking
- Appeal management
- Severity classification

**Primary Routes**:
```
/admin/disciplinary/records       - Record incidents
/admin/disciplinary/penalties     - Manage penalties
/admin/disciplinary/appeals       - Process appeals
```

**Database Tables**:
- `disciplinary_records`
- `penalties`
- `appeals`

### 4. Attendance Module

**Purpose**: Track student attendance

**Key Models**:
- `Attendance`: Daily attendance records

**Key Features**:
- Record attendance by status (Present, Absent, Late, Excused, Justified)
- Bulk attendance entry
- Attendance statistics and reporting
- Absence tracking

**Primary Routes**:
```
/admin/attendance/attendance      - Record attendance
/admin/attendance/report/export   - Export attendance reports
```

**Database Tables**:
- `attendance`

### 5. Biometric Module

**Purpose**: Facial recognition and biometric authentication

**Key Models**:
- `FacialRecognition`: Facial data storage

**Key Features**:
- Enroll student facial recognition
- Verify identity using facial recognition
- Track enrollment dates and verification history
- Integration with biometric devices

**Primary Routes**:
```
/admin/biometric/facial-recognition - Manage facial recognition
```

**Database Tables**:
- `facial_recognition`

### 6. Uniforms Module

**Purpose**: Manage uniform requests and distribution

**Key Models**:
- `UniformRequest`: Student uniform requests

**Key Features**:
- Request uniform items
- Track delivery status
- Report on uniform inventory
- Support for different uniform types and sizes

**Primary Routes**:
```
/admin/uniforms/requests          - Manage uniform requests
```

**Database Tables**:
- `uniform_requests`

### 7. Financial Module

**Purpose**: Manage school finances, invoices, and payments

**Key Models**:
- `Account`: Student financial accounts
- `Invoice`: School invoices
- `Payment`: Payment records

**Key Features**:
- Student account management
- Invoice generation and tracking
- Payment processing and reconciliation
- Overdue invoice tracking
- Debt reporting
- Multiple payment method support

**Primary Routes**:
```
/admin/financial/accounts         - Manage financial accounts
/admin/financial/invoices         - Create and manage invoices
/admin/financial/payments         - Record payments
```

**Database Tables**:
- `financial_accounts`
- `invoices`
- `payments`

### 8. HR Module

**Purpose**: Manage employees and staff

**Key Models**:
- `Employee`: Staff member information

**Key Features**:
- Employee registration and management
- Department organization
- Hire date tracking
- Status management (active, inactive, etc.)
- Employee history tracking

**Primary Routes**:
```
/admin/hr/employees               - Manage employees
```

**Database Tables**:
- `employees`

### 9. Payroll Module

**Purpose**: Manage employee payroll and salaries

**Key Models**:
- `Payroll`: Payroll records

**Key Features**:
- Salary calculations
- Allowances and deductions management
- Period-based payroll generation
- Payroll receipt generation
- Payroll reports

**Primary Routes**:
```
/admin/payroll/payroll            - Manage payroll
```

**Database Tables**:
- `payroll`

### 10. Refectory Module

**Purpose**: Manage school cafeteria and meals

**Key Models**:
- `Menu`: Daily menu planning

**Key Features**:
- Daily/weekly menu planning
- Meal tracking
- Nutritional information management
- Bulk menu creation

**Primary Routes**:
```
/admin/refectory/menus            - Manage menus
```

**Database Tables**:
- `refectory_menus`

### 11. Events Module

**Purpose**: Manage school events

**Key Models**:
- `Event`: School events (graduations, presentations, etc.)
- `EventParticipant`: Event participation records

**Key Features**:
- Event scheduling and management
- Participant registration
- Capacity management
- Event type classification

**Primary Routes**:
```
/admin/events/events              - Manage events
```

**Database Tables**:
- `events`
- `event_participants`

### 12. Ceremonial Module

**Purpose**: Manage ceremonial activities and traditions

**Key Models**:
- `Ceremonial`: Ceremonial events and protocols

**Key Features**:
- Flag ceremony management
- Ceremonial squad management
- Band management
- Protocol tracking

**Primary Routes**:
```
/admin/ceremonial/ceremonial      - Manage ceremonies
```

**Database Tables**:
- `ceremonials`

### 13. Sports Module

**Purpose**: Manage sports programs and activities

**Key Models**:
- `Sport`: Sports/modalities
- `Athlete`: Student athletes
- `Match`: Sports matches

**Key Features**:
- Sport/modality management
- Athlete enrollment
- Match scheduling and results
- Coach assignment
- Training schedule management

**Primary Routes**:
```
/admin/sports/sports              - Manage sports
```

**Database Tables**:
- `sports`
- `athletes`
- `matches`

### 14. Communication Module

**Purpose**: Internal messaging and notifications

**Key Models**:
- `Message`: Internal messages

**Key Features**:
- Direct messaging between users
- Broadcast messaging
- WhatsApp integration capability
- Message read tracking
- Multiple communication channels

**Primary Routes**:
```
/admin/communication/messages     - Manage messages
```

**Database Tables**:
- `messages`

### 15. Analytics Module

**Purpose**: Data analysis and reporting

**Key Models**:
- `Report`: Generated analytics reports

**Key Features**:
- Custom report generation
- Data filtering and analysis
- Report export functionality
- Historical report storage
- AI-powered insights (extensible)

**Primary Routes**:
```
/admin/analytics/reports          - Generate and view reports
```

**Database Tables**:
- `analytics_reports`

### 16. Portal Module

**Purpose**: Multi-role portal access

**Key Models**:
- `PortalUser`: Portal access configuration

**Key Features**:
- Role-based access (Student, Teacher, Parent, Admin)
- Last login tracking
- Access log management
- Password reset management
- Portal permissions

**Primary Routes**:
```
/admin/portal/users               - Manage portal access
```

**Database Tables**:
- `portal_users`

### 17. System Module

**Purpose**: System configuration and maintenance

**Key Models**:
- `AuditLog`: System audit logs
- `Configuration`: System settings

**Key Features**:
- Audit log management and export
- System configuration
- Backup and restore functionality
- System monitoring
- Change tracking

**Primary Routes**:
```
/admin/system/audit-logs          - View audit logs
/admin/system/configurations      - System settings
```

**Database Tables**:
- `audit_logs`
- `configurations`

## Shared Components

### Traits

#### HasTenancy
- Provides automatic tenant filtering
- Scope methods for tenant-specific queries
- Prevents cross-tenant data access

#### HasAudit
- Automatic change logging
- User tracking
- IP address logging
- Audit log retrieval

### Enums

#### UserRole
Defines available user roles and their permissions:
- ADMIN
- DIRECTOR
- ACADEMIC_COORDINATOR
- TEACHER
- STUDENT
- PARENT
- STAFF
- SECURITY
- NURSE
- PSYCHOLOGIST
- HUMAN_RESOURCES
- ACCOUNTANT
- REFECTORY_MANAGER
- SPORTS_COORDINATOR
- CEREMONIAL_COORDINATOR

#### AttendanceStatus
- PRESENT
- ABSENT
- EXCUSED
- LATE
- JUSTIFIED

#### DisciplinaryStatus
- OPEN
- INVESTIGATING
- RESOLVED
- APPEALED
- CLOSED

#### PaymentStatus
- PENDING
- APPROVED
- PROCESSING
- COMPLETED
- FAILED
- CANCELLED
- REFUNDED

## Standard Controller Actions

Each module controller follows RESTful conventions:

```php
// List resources
GET    /admin/module/resources

// Create form
GET    /admin/module/resources/create

// Store new resource
POST   /admin/module/resources

// Show resource
GET    /admin/module/resources/{id}

// Edit form
GET    /admin/module/resources/{id}/edit

// Update resource
PUT    /admin/module/resources/{id}

// Delete resource
DELETE /admin/module/resources/{id}

// Custom actions
POST   /admin/module/resources/{id}/action-name
```

## Usage Examples

### Creating a Student

```php
use App\Services\Academic\AcademicService;

$service = app(AcademicService::class);

$student = $service->createStudent([
    'registration_number' => '2024001',
    'first_name' => 'João',
    'last_name' => 'Silva',
    'email' => 'joao@example.com',
    'date_of_birth' => '2008-05-15',
    'class_id' => 1,
    'status' => 'active',
]);
```

### Recording Attendance

```php
use App\Models\Attendance\Attendance;

Attendance::create([
    'student_id' => 1,
    'classroom_id' => 1,
    'date' => now(),
    'status' => 'present',
]);
```

### Creating a Grade

```php
use App\Models\Grades\Grade;

Grade::create([
    'student_id' => 1,
    'subject_id' => 1,
    'bimester' => 1,
    'grade' => 8.5,
    'weight' => 1.0,
    'type' => 'test',
]);
```

### Recording Disciplinary Incident

```php
use App\Models\Disciplinary\DisciplinaryRecord;

$record = DisciplinaryRecord::create([
    'student_id' => 1,
    'date' => now(),
    'description' => 'Disruptive behavior in class',
    'offense_type' => 'misconduct',
    'severity' => 'medium',
    'reported_by' => $teacher_id,
    'status' => 'open',
]);
```

### Processing Payment

```php
use App\Models\Financial\Payment;

$payment = Payment::create([
    'account_id' => 1,
    'invoice_id' => 1,
    'amount' => 500.00,
    'payment_method' => 'credit_card',
    'status' => 'completed',
    'payment_date' => now(),
]);
```

## API Documentation

The system provides RESTful API endpoints for all modules. Use the `/api/v1/` prefix:

```
GET    /api/v1/students              - List students
POST   /api/v1/students              - Create student
GET    /api/v1/students/{id}         - Get student details
PUT    /api/v1/students/{id}         - Update student
DELETE /api/v1/students/{id}         - Delete student
```

## Authentication & Authorization

All routes require:
1. **Authentication**: User must be logged in
2. **Tenancy**: User must belong to a tenant
3. **Authorization**: User must have permission for the action

Roles and permissions are managed through the `UserRole` enum.

## Database Considerations

### Migrations
Create migrations for all tables:
```bash
php artisan make:migration create_academic_students_table
php artisan make:migration create_academic_classrooms_table
# ... and so on for all modules
```

### Indexes
Recommended indexes for performance:
- `tenant_id` on all tables (for multi-tenancy)
- `student_id`, `user_id`, `employee_id` on related tables
- `date` fields for filtering
- `status` fields for scoping
- Composite indexes for common filter combinations

### Relationships
All relationships use:
- Foreign key constraints with `cascadeOnDelete()` or `cascadeOnUpdate()`
- Proper relationship types (HasOne, HasMany, BelongsTo, BelongsToMany)
- Eager loading with `with()` for performance

## Best Practices

### 1. Use Services for Business Logic
```php
// Good
$service = app(AcademicService::class);
$students = $service->listStudents($filters);

// Avoid
$students = Student::where(...)->get();
```

### 2. Validate Input
```php
// Use Form Request validation
class StoreStudentRequest extends FormRequest {
    public function rules() { ... }
}
```

### 3. Handle Transactions
```php
DB::transaction(function () {
    $invoice = Invoice::create(...);
    $payment = Payment::create(...);
});
```

### 4. Use Scopes for Common Filters
```php
// Good
$students = Student::active()->byClassroom($id)->get();

// Avoid
$students = Student::where('status', 'active')
    ->where('class_id', $id)
    ->get();
```

### 5. Audit Important Changes
All models use `HasAudit` trait for automatic logging.

## Extension Points

### Adding New Modules
1. Create Models directory: `app/Models/NewModule/`
2. Create Controller: `app/Http/Controllers/NewModule/`
3. Create Service: `app/Services/NewModule/`
4. Create Requests: `app/Http/Requests/NewModule/`
5. Add routes to `routes/modules.php`

### Integrating External APIs
Services provide a clean integration point:
```php
class PaymentService {
    public function processPayment(Payment $payment) {
        // Integrate with payment gateway
        $gateway = new PaymentGateway();
        $gateway->process($payment->amount);
    }
}
```

### Custom Reports
Use the Analytics module to generate custom reports:
```php
$report = Report::create([
    'name' => 'Monthly Enrollment Report',
    'type' => 'enrollment',
    'data' => [...],
    'filters' => [...],
]);
```

## Performance Optimization

### Eager Loading
```php
$students = Student::with('classroom', 'grades', 'attendance')->get();
```

### Query Optimization
```php
$students = Student::active()
    ->select('id', 'first_name', 'last_name', 'class_id')
    ->paginate(20);
```

### Caching
```php
$classrooms = Cache::remember('classrooms:active', 3600, function () {
    return Classroom::active()->get();
});
```

## Troubleshooting

### Tenant Filtering Not Working
Ensure user is authenticated and has `tenant_id` set:
```php
auth()->user()->tenant_id // Must not be null
```

### Audit Logs Not Recording
Check that model has `HasAudit` trait and user is authenticated:
```php
use App\Traits\HasAudit;

class MyModel extends Model {
    use HasAudit;
}
```

### Soft Deletes Not Working
Ensure model uses `SoftDeletes` trait:
```php
use Illuminate\Database\Eloquent\SoftDeletes;

class MyModel extends Model {
    use SoftDeletes;
}
```

## Support & Maintenance

- Review audit logs regularly for suspicious activity
- Keep backups of critical data
- Monitor system performance
- Test new features in staging environment
- Document custom modifications
- Keep Laravel and dependencies updated

---

**Last Updated**: June 2026
**Version**: 1.0
**Laravel Version**: 11.x
**PHP Version**: 8.3+
