Controllers in Avalúo Vehicular follow the standard Laravel MVC pattern. Each controller extends the baseDocumentation 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.
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 viaAuth::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, andsistemas, then maps each vehicle to include aprogresoobject containing a percentage (0–100) and a three-step checklist:Inspección de fallas,Sistemas / Mecánica, andImágenes del vehículo.
- KPI queries — counts vehicles created today vs. yesterday, total vehicles, total completed appraisals, and total valuation sum (
dashboard
Data passed to view:
| Key | Type | Description |
|---|---|---|
vehiculosHoy | int | Vehicles registered today |
pendientes | int | Vehicles without a completed appraisal |
valoracionPromedio | float | Average final estimation across completed appraisals |
comparacionAyer | int | Vehicles registered yesterday (for delta display) |
vehiculos | Collection | Full vehicle list with eager-loaded relations and progress |
avaluos | int | Count of completed appraisals |
marcas | Collection | All brands for filter select |
años_vehiculo | Collection | Distinct manufacture years for filter select |
usuarios | Collection | User list for evaluator filter (admin sees all) |
isAdmin | bool | Role 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 allMarcaVehiculorecords and renders the new vehicle form (Registro/create/registro). -
store(CreateRequest $request)— Validates and creates aVehiculorecord. Convertsestado_operativofrom array to comma-separated string. Also creates an associatedCondicionGeneralrecord. Redirects toregistro.seleccionaron success. Ifkilometrajeequals0, it is stored as500000(indicating unknown high mileage). -
seleccionar($id)— Renders the method-selection screen (SelecccionarMetodo). Redirects to dashboard if anAvaluorecord 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. RequirescontinuarPolicy authorization. -
seleccionarEditar($id)— Renders the edit-mode method selector (Registro/update/EditSeleccion). RequirescontinuarPolicy authorization. -
edit($id)— Loads the vehicle edit form with existingVehiculo,CondicionGeneral, and all brands. RequiresupdatePolicy authorization. -
update(UpdateVehiculoRequest $request, $id)— Applies changes to theVehiculoand itsCondicionGeneral. RequiresupdatePolicy 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)— Authorizesviewon the vehicle, then checks if aSistemarecord already exists. If it does, redirects to the next step (resultados.avaluo.continuar). Otherwise, maps the fullSeccionTecnicacatalog to{titulo, componentes, valoracion, opciones}and rendersRegistro/create/evaluacion_mecanica. -
store(MecanicaRequest $request, $id)— Authorizesupdateon the vehicle. Iterates over$request->sistemas(each with nestedcomponentes) and bulk-inserts intoSistemaviaSistema::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 fullSeccionTecnicacatalog with already-evaluatedSistemarecords (keyed by"titulo__componente") and rendersRegistro/update/EditMecanica. -
update(Request $request, $id)— Same role-aware query asedit(). Loops over incoming systems and components, usingSistema::updateOrCreate()to upsert each record by{id_vehiculo, titulo, componente}.
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)— Authorizesviewon the vehicle. Redirects to the continuation route if anInspeccionalready exists. Otherwise, mapsSeccionFallato{titulo, caracteristicas, valoracion}and rendersRegistro/create/evaluacion_inspeccion. -
store(InspeccionRequest $request, $id)— Reads$request->input('data')— an array of inspection items each withnombre,caracteristica,tiene,valoracion, andobservaciones. Bulk-inserts all records viaInspeccion::insert(). -
edit($id)— Authorizesview. Merges the fullSeccionFallacatalog with already-evaluatedInspeccionrecords (keyed by"nombre__caracteristica") and rendersRegistro/update/EditInspeccion. -
update(Request $request, $id)— Authorizesupdate. Iterates over$request->input('data')and upserts each item viaInspeccion::updateOrCreate()matching on{id_vehiculo, nombre, caracteristica}.
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)— Authorizesview. 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 thepublicdisk with a unique name, and bulk-insertsVehiculoImagenrecords withurl,lado(position),descripcion, andfecha. Redirects to the appraisal result on success. -
edit($id)— Authorizesview. Loads all existingVehiculoImagenrecords for the vehicle and rendersRegistro/update/EditImagenes. -
update(UpdateImagenRequest $request, $id)— Authorizesupdate. Performs a three-way sync:- Identifies existing images not present in the request and deletes their physical files from storage and their DB records.
- Updates metadata (
lado,descripcion) for existing images that are retained. - Saves and inserts any new file uploads.
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)— Authorizesviewon the vehicle. Retrieves all related data (marca, inspecciones, condicion general, imagenes, evaluador, archivos), then calls the three private calculation methods. Writes the result toAvaluo::updateOrCreate()and rendersRegistro/create/resultadowith all factors and the final value.
-
evaluar_inspeccion($id)— Combines visual fault inspection and mechanical scores into a single condition factorC. 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 factorAfor model age. Computes vehicle age ascurrentYear − año_fabricacion, then applies the brand’stasa_krate:max(1 − (tasa_k × antiguedad), valor_residual). This ensures the vehicle never depreciates below its brand-defined residual value. -
DepreciacionKilometraje($id)— Calculates factorBfor 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 theSistematable. For each component with a non-null valoración, computesvaloracion × estadoand sums them. Returns1 − totalDeductions.
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)— Authorizesviewon the vehicle. Retrieves the vehicle, brand, and depreciation factors (re-computes them if noAvaluorecord exists yet). Generates the PDF viaLaravelMpdf::loadHtml(). Saves tostorage/app/public/pdfReportes/and upserts theArchivorecord. Filename format:Avaluo_{placa}_{Ymd_His}.pdf. -
Tecnica($id)— Aggregates mechanical system scores from theSistematable. Identical logic toAvaluoController::Tecnica(). Called internally bycalcularFactorInspeccion().
-
calcularFactoresDepreciacion($id, $vehiculo, $marca)— Returns an array of all six factors and values:factorReposicion,factorModelo,factorKilometraje,factorInspeccion,valorFinal,valorResidual. Uses savedAvaluodata if available, otherwise recalculates on the fly. -
calcularFactorInspeccion($idVehiculo)— Identical logic toAvaluoController::evaluar_inspeccion(). -
calcularFactorModelo($vehiculo, $marca)— Identical logic toAvaluoController::DepreciacionModelo(). -
calcularFactorKilometraje($vehiculo)— Identical logic toAvaluoController::DepreciacionKilometraje(). -
prepararDatosPdf($id, $vehiculo, $marca, $factores)— Assembles the full data array for the Blade template, including evaluator info, inspections, mechanical systems, accessories (whereaplica = 1), and vehicle images.
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) andcompartidosConmigo(appraisals shared with the current user). Admins see all shared records globally. Returns sharing statistics (total,activos,vencidos,renovados,conToken) via Inertia renderCompartido/ListShared. -
store(CreateRequest $request, $id)— Authorizesviewon the vehicle. Filters out the vehicle’s owner from the recipients list, and filters users who already have an active or renewed share. Creates anAvaluoCompartidorecord per new recipient. Generates a token only whenmotivo === 'acceso publico'. -
update(Request $request, $id)— Requires theupdate_avaluocompartidopermission. Updates dates,estado,motivo, andobservaciones. Generates or clears the public token based on whether the motivo changes to or from'acceso publico'. -
destroy($id)— Requires thedelete_avaluocompartidopermission. Admins can delete any share; evaluators can only delete shares of their own vehicles. -
renovar(Request $request, $id)— Requires theupdate_avaluocompartidopermission. Updatesfecha_fin, setsestadoto'renovado', and refreshesfecha_compartidotonow().
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 upAvaluoCompartidoby token. Returns404if not found. Returns403if the share is not inactivoorrenovadostate, or iffecha_finis in the past (and auto-transitions the record to'vencido'). Incrementscontador_vistas, eager-loads all related data, re-runs all depreciation calculations, and rendersCompartido/VistoPublicoAvaluo/AvaluoPublic.
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()— CheckshasRole('admin'), redirects back with error if not admin. Returns all users with their Spatie roles and the full role list viaInertia::render('User/ListUsers'). -
store(CreateUserRequest $request)— Validates the requested role exists in Spatie, creates the user withis_active = 0(initially inactive), hashes the password, and callssyncRoles(). -
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)— Requirespasswordof at least 8 characters. Hashes and saves the new password. -
changeRole(Request $request, $id)— Validates the role exists. Prevents self-role-change. CallssyncRoles()to swap the user’s role atomically. -
changeSuspension(Request $request, $id)— Validatesis_suspendedis boolean. Prevents self-suspension. Toggles theis_suspendedflag. -
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. Theadminrole 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 viasyncPermissions(). -
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 viaInertia::render('Depreciacion/DepreMarcaVehiculo'). -
store(CreateMarcaRequest $request)— Creates a brand record withnombre,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: removescondicionGeneral,inspecciones,sistemas,accesorios,archivos,imagenes,avaluo, andcompartidos(if any), then soft-deletes theVehiculoitself. -
restore($id)— Performs a cascading restore: restores all relations in the same order, then restores theVehiculo. 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.