Skip to main content

Overview

GIMA (Gestión Inteligente para el Mantenimiento de Activos) is built on a modern, scalable architecture using Laravel as the core framework. The system provides comprehensive asset maintenance management with role-based access control, real-time tracking, and automated workflows.

Technology Stack

Backend Framework

Laravel 11.xModern PHP framework providing:
  • Eloquent ORM for database interactions
  • API routing and middleware
  • Queue management
  • Event broadcasting

Authentication

Laravel SanctumToken-based authentication for:
  • API token generation
  • SPA authentication
  • Mobile app support
  • Secure session management

Authorization

Spatie Laravel PermissionRole and permission management:
  • Role-based access control (RBAC)
  • Permission inheritance
  • Guard support
  • Dynamic permission assignment

Database

MySQL / PostgreSQLRelational database for:
  • Asset tracking
  • Maintenance records
  • User management
  • Audit trails

Core Components

1. Authentication Layer

The authentication system uses Laravel Sanctum to provide stateless API authentication:
// User model with Sanctum support
class User extends Authenticatable
{
    use HasApiTokens;  // Sanctum token support
    use HasRoles;      // Spatie permission support
    use HasFactory, Notifiable;
    
    protected $fillable = [
        'name',
        'email',
        'password',
        'telefono',
        'estado',
        'aprobado_por',
        'fecha_aprobacion',
    ];
    
    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
            'estado' => UserStatusEnum::class,
            'fecha_aprobacion' => 'datetime',
        ];
    }
}
All API requests require a valid Bearer token obtained through the /autenticacion/iniciar-sesion endpoint.

2. Authorization Layer

GIMA implements a hierarchical role-based permission system using Spatie Laravel Permission:
  1. Admin - Full system access with all permissions
  2. Supervisor - Asset and maintenance management
  3. Técnico - Task execution and reporting
  4. Reporter - Fault reporting and view-only access
Each role inherits specific permissions defined in RolesSeeder.php
// Protecting routes with role middleware
Route::middleware('auth:sanctum')->group(function () {
    // Admin-only routes
    Route::prefix('admin')
        ->middleware('role:admin')
        ->group(function () {
            Route::get('dashboard', [AdminController::class, 'index']);
        });
    
    // Supervisor and Admin routes
    Route::prefix('supervision')
        ->middleware('role:supervisor|admin')
        ->group(function () {
            Route::get('auditoria', [AuditoriaController::class, 'index']);
        });
});

3. Data Layer

The system uses Eloquent ORM with strongly-typed relationships and enums:

Models

  • User: Users with roles and permissions
  • Activo: Assets being maintained
  • Mantenimiento: Maintenance records
  • Reporte: Fault reports
  • Repuesto: Spare parts inventory
  • Ubicacion: Physical locations

Enums

  • EstadoActivo: Asset states
  • TipoMantenimiento: Maintenance types
  • EstadoMantenimiento: Maintenance status
  • EstadoReporte: Report status
  • NivelPrioridad: Priority levels

4. Business Logic Layer

The application follows Laravel’s MVC architecture:
app/
├── Http/
│   ├── Controllers/     # Request handling and response
│   ├── Middleware/      # Request filtering
│   └── Requests/        # Form validation
├── Models/              # Eloquent models
├── Enums/               # Typed enumerations
└── Services/            # Business logic

Database Schema Overview

Core Relationships

// Asset relationships
class Activo extends Model
{
    // An asset belongs to an article type
    public function articulo(): BelongsTo
    {
        return $this->belongsTo(Articulos::class, 'articulo_id');
    }
    
    // An asset has a physical location
    public function ubicacion(): BelongsTo
    {
        return $this->belongsTo(Ubicacion::class, 'ubicacion_id');
    }
    
    // An asset has many maintenance records
    public function mantenimientos(): HasMany
    {
        return $this->hasMany(Mantenimiento::class, 'activo_id');
    }
    
    // An asset can have multiple fault reports
    public function reportes(): HasMany
    {
        return $this->hasMany(Reporte::class, 'activo_id');
    }
}
All model relationships use Eloquent’s type-hinted return types for better IDE support and type safety.

API Architecture

Request Flow

  1. Authentication: Client sends Bearer token in Authorization header
  2. Route Matching: Laravel router matches request to endpoint
  3. Middleware: auth:sanctum validates token, role checks permissions
  4. Controller: Processes request and calls service layer
  5. Service Layer: Executes business logic
  6. Model Layer: Interacts with database via Eloquent
  7. Response: JSON response returned to client

API Structure

api/
├── autenticacion/
│   ├── POST /iniciar-sesion       # Login
│   ├── POST /registrar            # Register
│   └── GET  /perfil               # Get profile (auth)
├── admin/                         # Admin routes (role:admin)
├── supervision/                   # Supervisor routes (role:supervisor|admin)
├── tecnica/                       # Technical routes (role:tecnico|supervisor|admin)
└── reportes/                      # Reporter routes (role:reporter|admin)

Security Features

Token Authentication

  • Stateless API tokens via Sanctum
  • Token expiration policies
  • Token revocation support
  • Secure token storage

Authorization

  • Role-based access control
  • Permission-level granularity
  • Route protection middleware
  • User approval workflow

Data Protection

  • Password hashing (bcrypt)
  • Mass assignment protection
  • SQL injection prevention
  • XSS protection

Audit Trail

  • User activity logging
  • Model change tracking
  • Audit table for compliance
  • Timestamp tracking

Performance Considerations

Eager Loading

// Load related models to prevent N+1 queries
$activos = Activo::with(['articulo', 'ubicacion', 'mantenimientos'])
    ->where('estado', EstadoActivo::OPERATIVO)
    ->get();

Caching

// Spatie Permission caches roles and permissions
app()[PermissionRegistrar::class]->forgetCachedPermissions();

Indexing

Database indexes on:
  • Foreign keys (activo_id, usuario_id, etc.)
  • Status fields (estado, prioridad)
  • Search fields (codigo, email)

Deployment Architecture

  • Web Server: Nginx or Apache with PHP-FPM
  • Application: Laravel running on PHP 8.2+
  • Database: MySQL 8.0+ or PostgreSQL 14+
  • Cache: Redis for session and cache storage
  • Queue: Redis or database for background jobs
  • Storage: Local filesystem or S3 for file uploads

Environment Configuration

# .env configuration
APP_NAME=GIMA
APP_ENV=production
APP_DEBUG=false
APP_URL=https://gima.example.com

# Database
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=gima

# Sanctum
SANCTUM_STATEFUL_DOMAINS=gima.example.com

Next Steps

Roles & Permissions

Learn about the role hierarchy and permission system

Asset Management

Understand asset lifecycle and tracking

Maintenance Types

Explore preventive, corrective, and predictive maintenance

API Reference

View complete API endpoint documentation

Build docs developers (and LLMs) love