349 lines
13 KiB
PHP
349 lines
13 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers\Repuve;
|
|
|
|
use App\Http\Controllers\Controller;
|
|
use App\Http\Requests\Repuve\VehicleUpdateRequest;
|
|
use Notsoweb\ApiResponse\Enums\ApiResponse;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Support\Facades\Auth;
|
|
use Illuminate\Support\Facades\Log;
|
|
use App\Models\Record;
|
|
use App\Models\File;
|
|
use App\Models\Owner;
|
|
use App\Models\Tag;
|
|
use App\Models\Error;
|
|
|
|
class UpdateController extends Controller
|
|
{
|
|
|
|
public function vehicleUpdate(VehicleUpdateRequest $request)
|
|
{
|
|
try {
|
|
$folio = $request->input('folio');
|
|
$tagId = $request->input('tag_id');
|
|
|
|
// Buscar vehículo por folio y tag
|
|
$tag = Tag::with('vehicle.owner')->findOrFail($tagId);
|
|
|
|
// Validar que el tag corresponda al folio
|
|
if ($tag->folio !== $folio) {
|
|
return ApiResponse::BAD_REQUEST->response([
|
|
'message' => 'El folio no coincide con el tag RFID proporcionado',
|
|
'folio_request' => $folio,
|
|
'folio_tag' => $tag->folio,
|
|
]);
|
|
}
|
|
|
|
$vehicle = $tag->vehicle;
|
|
|
|
if (!$vehicle) {
|
|
return ApiResponse::NOT_FOUND->response([
|
|
'message' => 'No se encontró un vehículo asociado al tag',
|
|
]);
|
|
}
|
|
|
|
// Consultar API Repuve Nacional (verificar robo)
|
|
$isStolen = $this->checkIfStolen($folio);
|
|
|
|
if ($isStolen) {
|
|
return ApiResponse::FORBIDDEN->response([
|
|
'folio' => $folio,
|
|
'tag_id' => $tagId,
|
|
'stolen' => true,
|
|
'message' => 'El vehículo reporta robo. No se puede continuar con la actualización.',
|
|
]);
|
|
}
|
|
|
|
// Iniciar transacción
|
|
DB::beginTransaction();
|
|
|
|
// Obtener datos del vehículo de API Estatal
|
|
$vehicleData = $this->getVehicle2();
|
|
$ownerData = $this->getOwner();
|
|
|
|
// Actualizar propietario
|
|
$owner = Owner::updateOrCreate(
|
|
['rfc' => $ownerData['rfc']],
|
|
[
|
|
'name' => $ownerData['name'],
|
|
'paternal' => $ownerData['paternal'],
|
|
'maternal' => $ownerData['maternal'],
|
|
'curp' => $ownerData['curp'],
|
|
'address' => $ownerData['address'],
|
|
]
|
|
);
|
|
|
|
// Actualizar vehículo
|
|
$vehicle->update([
|
|
'anio_placa' => $vehicleData['ANIO_PLACA'],
|
|
// NO actualizar 'placa' - es UNIQUE
|
|
// NO actualizar 'numero_serie' - es UNIQUE (NIV/VIN)
|
|
'rfc' => $vehicleData['RFC'],
|
|
'folio' => $folio,
|
|
'vigencia' => $vehicleData['VIGENCIA'],
|
|
'fecha_impresion' => $vehicleData['FECHA_IMPRESION'],
|
|
'qr_hash' => $vehicleData['QR_HASH'],
|
|
'valido' => $vehicleData['VALIDO'],
|
|
'nombre' => $vehicleData['NOMBRE'],
|
|
'nombre2' => $vehicleData['NOMBRE2'],
|
|
'municipio' => $vehicleData['MUNICIPIO'],
|
|
'localidad' => $vehicleData['LOCALIDAD'],
|
|
'calle' => $vehicleData['CALLE'],
|
|
'calle2' => $vehicleData['CALLE2'],
|
|
'tipo' => $vehicleData['TIPO'],
|
|
'tipo_servicio' => $vehicleData['TIPO_SERVICIO'],
|
|
'marca' => $vehicleData['MARCA'],
|
|
'linea' => $vehicleData['LINEA'],
|
|
'sublinea' => $vehicleData['SUBLINEA'],
|
|
'modelo' => $vehicleData['MODELO'],
|
|
'numero_motor' => $vehicleData['NUMERO_MOTOR'],
|
|
'descripcion_origen' => $vehicleData['DESCRIPCION_ORIGEN'],
|
|
'color' => $vehicleData['COLOR'],
|
|
'codigo_postal' => $vehicleData['CODIGO_POSTAL'],
|
|
// NO actualizar 'serie_folio' - es UNIQUE
|
|
// NO actualizar 'sfolio' - es UNIQUE
|
|
// NO actualizar 'nrpv' - es UNIQUE (mantener el original)
|
|
'owner_id' => $owner->id,
|
|
]);
|
|
|
|
$record = Record::firstOrCreate(
|
|
['vehicle_id' => $vehicle->id],
|
|
[
|
|
'folio' => $folio,
|
|
'user_id' => Auth::id(),
|
|
]
|
|
);
|
|
|
|
// Enviar datos a API Repuve Nacional
|
|
$apiResponse = $this->sendToRepuveNacional($folio, $tagId, $vehicleData);
|
|
|
|
// Procesar respuesta de la API
|
|
if (isset($apiResponse['has_error']) && $apiResponse['has_error']) {
|
|
// Si hay error, busca bd
|
|
$error = Error::where('code', $apiResponse['error_code'])->first();
|
|
|
|
if (!$error) {
|
|
DB::rollBack();
|
|
return ApiResponse::BAD_REQUEST->response([
|
|
'message' => 'Código de error no encontrado en el catálogo',
|
|
'error_code' => $apiResponse['error_code'],
|
|
'error_message' => $apiResponse['error_message'],
|
|
]);
|
|
}
|
|
|
|
// guarda error
|
|
$record->update([
|
|
'error_id' => $error->id,
|
|
'api_response' => $apiResponse, // Guarda respuesta con error
|
|
'error_occurred_at' => now(),
|
|
]);
|
|
|
|
DB::commit();
|
|
|
|
// Retornar datos por error para que el usuario corrija
|
|
// Al volver a llamar esta función con datos corregidos, se repetirá el ciclo
|
|
return ApiResponse::OK->response([
|
|
'message' => 'Datos guardados con error. Corrija los datos y vuelva a enviar.',
|
|
'has_error' => true,
|
|
'can_retry' => true,
|
|
'error' => [
|
|
'code' => $error->code,
|
|
'description' => $error->description,
|
|
'occurred_at' => $record->error_occurred_at->toDateTimeString(),
|
|
],
|
|
'record' => [
|
|
'id' => $record->id,
|
|
'folio' => $record->folio,
|
|
],
|
|
'vehicle' => $vehicleData, // Retorna datos para edición
|
|
'owner' => $ownerData,
|
|
]);
|
|
}
|
|
|
|
// Si NO hay error, guarda registro OK y quita errores previos
|
|
$record->update([
|
|
'error_id' => null,
|
|
'api_response' => $apiResponse,
|
|
'error_occurred_at' => null,
|
|
]);
|
|
|
|
// Procesar archivos si existen
|
|
$uploadedFiles = [];
|
|
if ($request->hasFile('files')) {
|
|
$files = $request->file('files');
|
|
$fileNames = $request->input('names', []);
|
|
|
|
foreach ($files as $index => $file) {
|
|
$fileName = uniqid() . '_' . time() . '_' . $file->getClientOriginalName();
|
|
$path = $file->storeAs('records', $fileName, 'public');
|
|
$md5 = md5_file($file->getRealPath());
|
|
|
|
$fileRecord = File::create([
|
|
'name' => $fileNames[$index] ?? "Archivo " . ($index + 1),
|
|
'path' => $path,
|
|
'md5' => $md5,
|
|
'record_id' => $record->id,
|
|
]);
|
|
|
|
$uploadedFiles[] = [
|
|
'id' => $fileRecord->id,
|
|
'name' => $fileRecord->name,
|
|
'path' => $fileRecord->path,
|
|
'url' => $fileRecord->url,
|
|
];
|
|
}
|
|
}
|
|
|
|
DB::commit();
|
|
|
|
return ApiResponse::OK->response([
|
|
'message' => 'Vehículo actualizado exitosamente',
|
|
'has_error' => false,
|
|
'record' => [
|
|
'id' => $record->id,
|
|
'folio' => $record->folio,
|
|
'updated_at' => $record->updated_at->toDateTimeString(),
|
|
],
|
|
'vehicle' => [
|
|
'id' => $vehicle->id,
|
|
'placa' => $vehicle->placa,
|
|
'numero_serie' => $vehicle->numero_serie,
|
|
'marca' => $vehicle->marca,
|
|
'modelo' => $vehicle->modelo,
|
|
],
|
|
'owner' => [
|
|
'id' => $owner->id,
|
|
'full_name' => $owner->full_name,
|
|
'rfc' => $owner->rfc,
|
|
],
|
|
'tag' => [
|
|
'id' => $tag->id,
|
|
'folio' => $tag->folio,
|
|
],
|
|
'new_files' => $uploadedFiles,
|
|
'total_new_files' => count($uploadedFiles),
|
|
]);
|
|
|
|
} catch (\Exception $e) {
|
|
DB::rollBack();
|
|
|
|
Log::error('Error en actualizarVehiculo: ' . $e->getMessage(), [
|
|
'folio' => $folio ?? null,
|
|
'tag_id' => $tagId ?? null,
|
|
'trace' => $e->getTraceAsString()
|
|
]);
|
|
|
|
return ApiResponse::BAD_REQUEST->response([
|
|
'message' => 'Error al actualizar el vehículo',
|
|
'error' => $e->getMessage(),
|
|
]);
|
|
}
|
|
}
|
|
|
|
private function checkIfStolen(string $folio): bool
|
|
{
|
|
// Aquí api servicio de REPUVE Nacional
|
|
// simulamos con random
|
|
return (bool) rand(0, 1);
|
|
}
|
|
|
|
private function sendToRepuveNacional(string $folio, int $tagId, array $vehicleData): array
|
|
{
|
|
// Enviar datos a API Repuve Nacional
|
|
// Aquí se haría la llamada real a la API de Repuve Nacional
|
|
// Por ahora simulamos respuestas aleatorias usando la tabla errors
|
|
|
|
$hasError = (bool) rand(0, 1);
|
|
|
|
if ($hasError) {
|
|
// Obtener un error aleatorio de la tabla errors
|
|
$error = Error::inRandomOrder()->first();
|
|
|
|
if (!$error) {
|
|
// Si no hay errores en la tabla, retornar error genérico
|
|
return [
|
|
'has_error' => true,
|
|
'error_code' => 'ERR_UNKNOWN',
|
|
'error_message' => 'No hay errores registrados en el catálogo',
|
|
'timestamp' => now()->toDateTimeString(),
|
|
'folio' => $folio,
|
|
'tag_id' => $tagId,
|
|
'response_data' => null,
|
|
];
|
|
}
|
|
|
|
return [
|
|
'has_error' => true,
|
|
'error_code' => $error->code,
|
|
'error_message' => $error->description,
|
|
'timestamp' => now()->toDateTimeString(),
|
|
'folio' => $folio,
|
|
'tag_id' => $tagId,
|
|
'response_data' => null,
|
|
];
|
|
}
|
|
|
|
// Respuesta exitosa
|
|
return [
|
|
'has_error' => false,
|
|
'error_code' => null,
|
|
'error_message' => null,
|
|
'timestamp' => now()->toDateTimeString(),
|
|
'folio' => $folio,
|
|
'tag_id' => $tagId,
|
|
'response_data' => [
|
|
'status' => 'success',
|
|
'repuve_id' => 'REPUVE-' . strtoupper(uniqid()),
|
|
'validated' => true,
|
|
],
|
|
];
|
|
}
|
|
|
|
private function getVehicle2(): array
|
|
{
|
|
return [
|
|
"ANIO_PLACA" => "2027",
|
|
"PLACA" => "WNU730X",
|
|
"NO_SERIE" => "EXP-2025-201030",
|
|
"RFC" => "GME111116GJA",
|
|
"FOLIO" => "EXP-2025-201030",
|
|
"VIGENCIA" => "2026",
|
|
"FECHA_IMPRESION" => "10-01-2025",
|
|
"QR_HASH" => "Vu5TF4kYsbbltzjDdGQyenKfZoIk2wro34a5Gkh9JVh0CFxfPlrd92YEWK21JF.nLjQNyzKmqRvWYuPiS.kU7A--",
|
|
"VALIDO" => true,
|
|
"NOMBRE" => "GOLSYSTEMS DE MEXICO S DE RL DE CV",
|
|
"NOMBRE2" => "GOLS*MS DXICOE RL*CV",
|
|
"MUNICIPIO" => "CENTRO",
|
|
"LOCALIDAD" => "VILLAHERMOSA",
|
|
"CALLE" => "C BUGAMBILIAS 119 ",
|
|
"CALLE2" => "C BU*ILIA*18 ",
|
|
"TIPO" => "SEDAN",
|
|
"TIPO_SERVICIO" => "PARTICULAR",
|
|
"MARCA" => "CHEVROLET G.M.C.",
|
|
"LINEA" => "AVEO",
|
|
"SUBLINEA" => "PAQ. \"A\" LS",
|
|
"MODELO" => 2023,
|
|
"NUMERO_SERIE" => "EXP-2025-201030",
|
|
"NUMERO_MOTOR" => "H. EN WUHANLL,SGM",
|
|
"DESCRIPCION_ORIGEN" => "IMPORTADO",
|
|
"COLOR" => "AZUL",
|
|
"CODIGO_POSTAL" => "86181",
|
|
"SERIE_FOLIO" => "D3962242",
|
|
"SFOLIO" => "EXP-2025-201030"
|
|
];
|
|
}
|
|
|
|
private function getOwner(): array
|
|
{
|
|
return [
|
|
'name' => 'Nicolas',
|
|
'paternal' => 'Hernandez',
|
|
'maternal' => 'Castillo',
|
|
'rfc' => 'HECN660509HTCRSC01',
|
|
'curp' => 'HECN660509HTCRSC01',
|
|
'address' => 'Fracc Pomoca, Calle Armadillo MZ9 LT28',
|
|
];
|
|
}
|
|
}
|