Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/alber1802/AvaluoVehicular/llms.txt

Use this file to discover all available pages before exploring further.

Controllers in Avalúo Vehicular follow the standard Laravel MVC pattern. Each controller extends the base App\Http\Controllers\Controller class and uses Inertia::render() to pass typed PHP data directly to React components, eliminating the need for a separate API layer. Controllers that touch vehicle or appraisal records use the AuthorizesRequests trait from Illuminate\Foundation\Auth\Access, delegating ownership and access checks to Laravel Policies rather than scattering if statements across business logic.

DashboardController

Namespace: App\Http\Controllers Responsibility: Computes KPI metrics and assembles the full vehicle listing for the dashboard. Applies role-based scoping — administrators see all vehicles and appraisals system-wide, while evaluators see only their own records. Key Methods:
  • index(Request $request) — The sole method. Detects the authenticated user’s role via Auth::user()->hasRole('admin'), then runs two sets of queries:
    • KPI queries — counts vehicles created today vs. yesterday, total vehicles, total completed appraisals, and total valuation sum (Avaluo::sum('final_estimacion')).
    • Vehicle listing — eager-loads imagenes, marca, avaluo, evaluador, inspecciones, and sistemas, then maps each vehicle to include a progreso object containing a percentage (0–100) and a three-step checklist: Inspección de fallas, Sistemas / Mecánica, and Imágenes del vehículo.
Inertia view: dashboard Data passed to view:
KeyTypeDescription
vehiculosHoyintVehicles registered today
pendientesintVehicles without a completed appraisal
valoracionPromediofloatAverage final estimation across completed appraisals
comparacionAyerintVehicles registered yesterday (for delta display)
vehiculosCollectionFull vehicle list with eager-loaded relations and progress
avaluosintCount of completed appraisals
marcasCollectionAll brands for filter select
años_vehiculoCollectionDistinct manufacture years for filter select
usuariosCollectionUser list for evaluator filter (admin sees all)
isAdminboolRole flag passed to React for conditional rendering

CreateRegistroController

Namespace: App\Http\Controllers\Registro Uses: AuthorizesRequests Responsibility: Manages the full vehicle record CRUD. Acts as the entry point and smart router for the multi-step appraisal workflow, determining where a user should be redirected based on which evaluation steps have been completed. Key Methods:
  • index() — Loads all MarcaVehiculo records and renders the new vehicle form (Registro/create/registro).
  • store(CreateRequest $request) — Validates and creates a Vehiculo record. Converts estado_operativo from array to comma-separated string. Also creates an associated CondicionGeneral record. Redirects to registro.seleccionar on success. If kilometraje equals 0, it is stored as 500000 (indicating unknown high mileage).
  • seleccionar($id) — Renders the method-selection screen (SelecccionarMetodo). Redirects to dashboard if an Avaluo record already exists for the vehicle, preventing duplicate evaluations.
  • show($id) — The workflow smart-router. Checks which evaluation steps exist for the vehicle, and redirects to the first incomplete step: SelecccionarMetodo → mechanical evaluation → inspection → images → final result. Requires continuar Policy authorization.
  • seleccionarEditar($id) — Renders the edit-mode method selector (Registro/update/EditSeleccion). Requires continuar Policy authorization.
  • edit($id) — Loads the vehicle edit form with existing Vehiculo, CondicionGeneral, and all brands. Requires update Policy authorization.
  • update(UpdateVehiculoRequest $request, $id) — Applies changes to the Vehiculo and its CondicionGeneral. Requires update Policy authorization.
Authorization: continuar and update policies on the Vehiculo model.

MecanicaController

Namespace: App\Http\Controllers\Registro Uses: AuthorizesRequests Responsibility: Handles the mechanical systems evaluation step. Reads component definitions from the SeccionTecnica catalog and stores individual component-level assessments in the Sistema table. Key Methods:
  • index($id) — Authorizes view on the vehicle, then checks if a Sistema record already exists. If it does, redirects to the next step (resultados.avaluo.continuar). Otherwise, maps the full SeccionTecnica catalog to {titulo, componentes, valoracion, opciones} and renders Registro/create/evaluacion_mecanica.
  • store(MecanicaRequest $request, $id) — Authorizes update on the vehicle. Iterates over $request->sistemas (each with nested componentes) and bulk-inserts into Sistema via Sistema::insert(). Redirects to the continuation route on success.
  • edit($id) — Role-aware query: admin users can access any vehicle; evaluators can only access their own. Merges the full SeccionTecnica catalog with already-evaluated Sistema records (keyed by "titulo__componente") and renders Registro/update/EditMecanica.
  • update(Request $request, $id) — Same role-aware query as edit(). Loops over incoming systems and components, using Sistema::updateOrCreate() to upsert each record by {id_vehiculo, titulo, componente}.
Authorization: view and update policies on the Vehiculo model.

InspeccionController

Namespace: App\Http\Controllers\Registro Uses: AuthorizesRequests Responsibility: Handles the visual fault inspection step. Reads fault definitions from the SeccionFalla catalog and stores per-characteristic presence/absence records in the Inspeccion table. Key Methods:
  • index($id) — Authorizes view on the vehicle. Redirects to the continuation route if an Inspeccion already exists. Otherwise, maps SeccionFalla to {titulo, caracteristicas, valoracion} and renders Registro/create/evaluacion_inspeccion.
  • store(InspeccionRequest $request, $id) — Reads $request->input('data') — an array of inspection items each with nombre, caracteristica, tiene, valoracion, and observaciones. Bulk-inserts all records via Inspeccion::insert().
  • edit($id) — Authorizes view. Merges the full SeccionFalla catalog with already-evaluated Inspeccion records (keyed by "nombre__caracteristica") and renders Registro/update/EditInspeccion.
  • update(Request $request, $id) — Authorizes update. Iterates over $request->input('data') and upserts each item via Inspeccion::updateOrCreate() matching on {id_vehiculo, nombre, caracteristica}.
Authorization: view and update policies on the Vehiculo model.

ImagenesController

Namespace: App\Http\Controllers\Registro Uses: AuthorizesRequests Responsibility: Manages vehicle photo uploads. Files are stored under storage/app/public/vehiculos/ using the public disk. Unique filenames are generated as vehiculo_{id}_{uniqid()}_{time()}.{ext}. Key Methods:
  • index($id) — Authorizes view. If no images exist for the vehicle, renders the upload form (Registro/create/imagenes_avaluo). If images already exist, redirects to the dashboard to prevent duplicate uploads.
  • store(ImagenesRequest $request, $id) — Iterates over $request->validated()['imagenes'], saves each file to the public disk with a unique name, and bulk-inserts VehiculoImagen records with url, lado (position), descripcion, and fecha. Redirects to the appraisal result on success.
  • edit($id) — Authorizes view. Loads all existing VehiculoImagen records for the vehicle and renders Registro/update/EditImagenes.
  • update(UpdateImagenRequest $request, $id) — Authorizes update. Performs a three-way sync:
    1. Identifies existing images not present in the request and deletes their physical files from storage and their DB records.
    2. Updates metadata (lado, descripcion) for existing images that are retained.
    3. Saves and inserts any new file uploads.
Authorization: view and update policies on the Vehiculo model.

AvaluoController

Namespace: App\Http\Controllers\Registro Uses: AuthorizesRequests Responsibility: Computes the final depreciated appraisal value and persists the result to the avaluo table. This is the financial engine of the application — it combines three depreciation factors (model age, mileage, and inspection condition) with a reposition factor to produce the final estimated value. Key Methods:
  • index($id) — Authorizes view on the vehicle. Retrieves all related data (marca, inspecciones, condicion general, imagenes, evaluador, archivos), then calls the three private calculation methods. Writes the result to Avaluo::updateOrCreate() and renders Registro/create/resultado with all factors and the final value.
Calculation Methods (public):
  • evaluar_inspeccion($id) — Combines visual fault inspection and mechanical scores into a single condition factor C. Uses a weighted average: (65 × Técnica + 35 × Fallas) / 100. Visual faults contribute positively (presence of a fault reduces the score). Returns a value between 0 and 1 (rounded to 3 decimal places).
  • DepreciacionModelo($id) — Calculates factor A for model age. Computes vehicle age as currentYear − año_fabricacion, then applies the brand’s tasa_k rate: max(1 − (tasa_k × antiguedad), valor_residual). This ensures the vehicle never depreciates below its brand-defined residual value.
  • DepreciacionKilometraje($id) — Calculates factor B for mileage. Applies a fixed linear rate: max(1 − (0.000001 × kilometraje), 0.05). The minimum floor is 0.05 (5%), ensuring extremely high-mileage vehicles retain at least 5% of base value.
  • Tecnica($id) — Aggregates mechanical system scores from the Sistema table. For each component with a non-null valoración, computes valoracion × estado and sums them. Returns 1 − totalDeductions.
Formula:
valorAvaluo  = precio_referencial × C × A × B × 1.2  (factor reposición)
valorResidual = precio_referencial × 0.107
valorFinal   = max(valorAvaluo, valorResidual)
// Cap: if valorFinal ≥ precio_referencial, drop the reposition factor
if (valorFinal >= precio_referencial):
    valorFinal = precio_referencial × C × A × B
Authorization: view policy on the Vehiculo model.

ArchivoControler

Namespace: App\Http\Controllers Uses: AuthorizesRequests Responsibility: Generates a PDF appraisal report using mccarlosen/laravel-mpdf. Renders a Blade view (pdf.avaluo) with all vehicle data, then stores the output file in storage/app/public/pdfReportes/. The file path is persisted in the archivos table (upsert: regenerates and replaces any previous PDF for the same vehicle). Public Methods:
  • generarPdf($id) — Authorizes view on the vehicle. Retrieves the vehicle, brand, and depreciation factors (re-computes them if no Avaluo record exists yet). Generates the PDF via LaravelMpdf::loadHtml(). Saves to storage/app/public/pdfReportes/ and upserts the Archivo record. Filename format: Avaluo_{placa}_{Ymd_His}.pdf.
  • Tecnica($id) — Aggregates mechanical system scores from the Sistema table. Identical logic to AvaluoController::Tecnica(). Called internally by calcularFactorInspeccion().
Private Helper Methods:
  • calcularFactoresDepreciacion($id, $vehiculo, $marca) — Returns an array of all six factors and values: factorReposicion, factorModelo, factorKilometraje, factorInspeccion, valorFinal, valorResidual. Uses saved Avaluo data if available, otherwise recalculates on the fly.
  • calcularFactorInspeccion($idVehiculo) — Identical logic to AvaluoController::evaluar_inspeccion().
  • calcularFactorModelo($vehiculo, $marca) — Identical logic to AvaluoController::DepreciacionModelo().
  • calcularFactorKilometraje($vehiculo) — Identical logic to AvaluoController::DepreciacionKilometraje().
  • prepararDatosPdf($id, $vehiculo, $marca, $factores) — Assembles the full data array for the Blade template, including evaluator info, inspections, mechanical systems, accessories (where aplica = 1), and vehicle images.
Authorization: view policy on the Vehiculo model.

ShareController

Namespace: App\Http\Controllers\Share Uses: AuthorizesRequests Responsibility: Manages sharing completed appraisals with other users. Tracks who shared what, with whom, and for how long. Generates a random 40-character token (Str::random(40)) for public-access shares that enables the unauthenticated AvaluoPublicoController route. Key Methods:
  • index() — Builds two collections: misCompartidos (appraisals the current user shared) and compartidosConmigo (appraisals shared with the current user). Admins see all shared records globally. Returns sharing statistics (total, activos, vencidos, renovados, conToken) via Inertia render Compartido/ListShared.
  • store(CreateRequest $request, $id) — Authorizes view on the vehicle. Filters out the vehicle’s owner from the recipients list, and filters users who already have an active or renewed share. Creates an AvaluoCompartido record per new recipient. Generates a token only when motivo === 'acceso publico'.
  • update(Request $request, $id) — Requires the update_avaluocompartido permission. Updates dates, estado, motivo, and observaciones. Generates or clears the public token based on whether the motivo changes to or from 'acceso publico'.
  • destroy($id) — Requires the delete_avaluocompartido permission. Admins can delete any share; evaluators can only delete shares of their own vehicles.
  • renovar(Request $request, $id) — Requires the update_avaluocompartido permission. Updates fecha_fin, sets estado to 'renovado', and refreshes fecha_compartido to now().
Authorization: view policy on the Vehiculo model; Spatie permission checks for update_avaluocompartido and delete_avaluocompartido.

AvaluoPublicoController

Namespace: App\Http\Controllers\Share Responsibility: The only controller that handles unauthenticated access. Validates the share token, checks expiry and active state, increments a contador_vistas counter, and renders a full read-only appraisal view. Key Methods:
  • verPublico(string $token) — Looks up AvaluoCompartido by token. Returns 404 if not found. Returns 403 if the share is not in activo or renovado state, or if fecha_fin is in the past (and auto-transitions the record to 'vencido'). Increments contador_vistas, eager-loads all related data, re-runs all depreciation calculations, and renders Compartido/VistoPublicoAvaluo/AvaluoPublic.
Authorization: None — this controller requires no authentication. Token validity is the access control mechanism.

UserRegistroController

Namespace: App\Http\Controllers\User Responsibility: Full user CRUD for administrators. Uses the Spatie Permission package for role management via syncRoles(). All methods are admin-gated (checked inline via hasRole('admin') or implicitly by admin-only access to the user list page). Key Methods:
  • index() — Checks hasRole('admin'), redirects back with error if not admin. Returns all users with their Spatie roles and the full role list via Inertia::render('User/ListUsers').
  • store(CreateUserRequest $request) — Validates the requested role exists in Spatie, creates the user with is_active = 0 (initially inactive), hashes the password, and calls syncRoles().
  • update(updateUserRequest $request, $id) — Updates name, email, and phone. Optionally re-syncs the user’s Spatie role if a new role is provided.
  • changePassword(Request $request, $id) — Requires password of at least 8 characters. Hashes and saves the new password.
  • changeRole(Request $request, $id) — Validates the role exists. Prevents self-role-change. Calls syncRoles() to swap the user’s role atomically.
  • changeSuspension(Request $request, $id) — Validates is_suspended is boolean. Prevents self-suspension. Toggles the is_suspended flag.
  • destroy($id) — Prevents deletion of admin accounts. Soft-deletes the user record.

RolesController

Namespace: App\Http\Controllers\RolesPermisos Responsibility: Full CRUD for Spatie roles and permissions. Calls app()[PermissionRegistrar::class]->forgetCachedPermissions() after every mutation to ensure changes take effect immediately without requiring a cache flush. Key Methods:
  • index() — Admin-gated. Returns paginated roles with permissions, paginated permissions, panel-scoped permissions (LIKE 'panel%'), and all permissions (for the assignment dropdowns).
  • store(RolesRequest $request) — Creates a role and syncs its initial permissions.
  • update(RolesRequest $request, $id) — Renames the role and re-syncs permissions.
  • destroyRole($id) — Admin-gated. The admin role is protected and cannot be deleted.
  • storePermission(PermisosRequest $request) — Creates a named Spatie permission.
  • updatePermission(Request $request, $id) — Renames a permission with a unique constraint that excludes the current record.
  • asignarPermisos(Request $request) — Admin-gated. Bulk-assigns a permission array to a role via syncPermissions().
  • destroyPermission($id) — Admin-gated. Deletes a named permission.

MarcasController

Namespace: App\Http\Controllers Responsibility: Manages the MarcaVehiculo catalog — the vehicle brand records that drive all depreciation calculations. Each brand stores tasa_k (annual depreciation coefficient) and valor_residual (minimum residual value floor), which are consumed by AvaluoController and ArchivoControler. Key Methods:
  • index() — Returns all brands ordered alphabetically via Inertia::render('Depreciacion/DepreMarcaVehiculo').
  • store(CreateMarcaRequest $request) — Creates a brand record with nombre, tasa_k, valor_residual, and the authenticated user’s ID.
  • update(UpdateMarcaRequest $request, $id) — Updates all fields on the brand record.
  • destroy($id) — Deletes the brand record. No soft-delete; the record is permanently removed.

ResourceReciclajeController

Namespace: App\Http\Controllers\Reciclaje Responsibility: Manages the recycle bin for soft-deleted vehicles. Uses Eloquent’s SoftDeletes scopes (onlyTrashed(), withTrashed()) to list, restore, or permanently destroy vehicle records and all their dependent relations. Key Methods:
  • index() — Role-scoped: admins see all soft-deleted vehicles; evaluators see only their own. Maps each vehicle to a flat DTO. Returns stats (total, eliminados_mes).
  • destroy($id) — Performs a cascading soft-delete: removes condicionGeneral, inspecciones, sistemas, accesorios, archivos, imagenes, avaluo, and compartidos (if any), then soft-deletes the Vehiculo itself.
  • restore($id) — Performs a cascading restore: restores all relations in the same order, then restores the Vehiculo. Accessible via ->withTrashed() route option.
  • forceDelete($id) — Admin-only. Permanently deletes all relations and their physical files from storage (Storage::disk('public')->delete()), then hard-deletes the vehicle. Accessible via ->withTrashed() route option.

Build docs developers (and LLMs) love