946 lines
36 KiB
PHP

<?php
namespace App\Http\Controllers\Repuve;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Requests\Repuve\VehicleUpdateRequest;
use Notsoweb\ApiResponse\Enums\ApiResponse;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Cache;
use App\Models\Record;
use App\Models\File;
use App\Models\Owner;
use App\Models\CatalogNameImg;
use App\Models\VehicleTagLog;
use App\Models\Tag;
use App\Services\RepuveService;
use App\Services\PadronEstatalService;
use Exception;
use Illuminate\Support\Facades\Auth;
use App\Jobs\ProcessRepuveResponse;
class UpdateController extends Controller
{
private RepuveService $repuveService;
private PadronEstatalService $padronEstatalService;
public function __construct(
RepuveService $repuveService,
PadronEstatalService $padronEstatalService
) {
$this->repuveService = $repuveService;
$this->padronEstatalService = $padronEstatalService;
}
/**
* Sustitución de TAG
* Proceso: Buscar TAG actual por folio del expediente, cancelarlo y asignar un nuevo TAG al vehículo
*/
public function tagSubstitution(Request $request)
{
try {
$request->validate([
'folio' => 'required|string|exists:records,folio',
'new_tag_folio' => 'required|string|exists:tags,folio',
'cancellation_reason_id' => 'nullable|exists:catalog_cancellation_reasons,id',
'cancellation_observations' => 'nullable|string|max:500',
]);
$folio = $request->input('folio');
$newTagFolio = $request->input('new_tag_folio');
$cancellationReasonId = $request->input('cancellation_reason_id');
$cancellationObservations = $request->input('cancellation_observations');
// Buscar el expediente por folio
$record = Record::with([
'vehicle.tag.status',
'vehicle.owner',
])->where('folio', $folio)->first();
if (!$record) {
return ApiResponse::NOT_FOUND->response([
'message' => 'No se encontró el expediente con el folio proporcionado',
'folio' => $folio,
]);
}
$vehicle = $record->vehicle;
$oldTag = $vehicle->tag;
if (!$oldTag) {
return ApiResponse::NOT_FOUND->response([
'message' => 'El vehículo no tiene un TAG asignado actualmente',
'folio' => $folio,
]);
}
// Verificar que el TAG antiguo esté asignado
if (!$oldTag->isAssigned()) {
return ApiResponse::BAD_REQUEST->response([
'message' => 'El TAG actual no está en estado asignado',
'tag_folio' => $oldTag->folio,
'current_status' => $oldTag->status->name,
]);
}
// Buscar el nuevo TAG por folio
$newTag = Tag::with('status')
->where('folio', $newTagFolio)
->first();
if (!$newTag) {
return ApiResponse::NOT_FOUND->response([
'message' => 'El nuevo TAG no existe',
'new_tag_folio' => $newTagFolio,
]);
}
// Verificar que el nuevo TAG esté disponible
if (!$newTag->isAvailable()) {
return ApiResponse::BAD_REQUEST->response([
'message' => 'El nuevo TAG no está disponible para asignación',
'new_tag_folio' => $newTagFolio,
'current_status' => $newTag->status->name,
]);
}
// Verificar robo del vehículo
$isStolen = $this->checkIfStolen($vehicle->niv);
if ($isStolen) {
return ApiResponse::FORBIDDEN->response([
'message' => 'El vehículo reporta robo. No se puede continuar con la sustitución.',
'niv' => $vehicle->niv,
]);
}
DB::beginTransaction();
// Cancelar el TAG anterior
$oldTag->markAsCancelled();
// Registrar log de cancelación del TAG anterior
VehicleTagLog::create([
'vehicle_id' => $vehicle->id,
'tag_id' => $oldTag->id,
'action_type' => 'sustitucion',
'cancellation_reason_id' => $cancellationReasonId,
'cancellation_observations' => $cancellationObservations,
'cancellation_at' => now(),
'cancelled_by' => Auth::id(),
'performed_by' => Auth::id(),
]);
// Actualizar el folio del record con el folio del nuevo TAG
$record->update([
'folio' => $newTagFolio
]);
// Asignar el nuevo TAG al vehículo (usa el nuevo folio)
$newTag->markAsAssigned($vehicle->id, $newTagFolio);
// 5. Registrar log de asignación del nuevo TAG
VehicleTagLog::create([
'vehicle_id' => $vehicle->id,
'tag_id' => $newTag->id,
'action_type' => 'sustitucion',
'performed_by' => Auth::id(),
]);
// 6. Enviar a REPUVE Nacional
$datosCompletos = $this->prepararDatosParaInscripcion($vehicle->niv);
ProcessRepuveResponse::dispatch($record->id, $datosCompletos);
DB::commit();
// Recargar relaciones para la respuesta
$record->load(['vehicle.tag.status', 'vehicle.owner']);
return ApiResponse::OK->response([
'message' => 'Sustitución de TAG realizada exitosamente',
'substitution_details' => [
'old_folio' => $folio,
'new_folio' => $newTagFolio,
'old_tag' => [
'folio' => $oldTag->folio,
'tag_number' => $oldTag->tag_number,
'status' => 'cancelled',
],
'new_tag' => [
'folio' => $newTag->folio,
'tag_number' => $newTag->tag_number,
'status' => 'assigned',
],
'performed_by' => Auth::user()->name,
'performed_at' => now()->format('Y-m-d H:i:s'),
],
'record' => $record,
]);
} catch (Exception $e) {
DB::rollBack();
return ApiResponse::INTERNAL_ERROR->response([
'message' => 'Error al realizar la sustitución del TAG',
'error' => $e->getMessage(),
]);
}
}
public function vehicleUpdate(VehicleUpdateRequest $request)
{
try {
$folio = $request->input('folio');
$tagNumber = $request->input('tag_number');
$niv = $request->input('niv');
$isStolen = $this->checkIfStolen($niv);
if ($isStolen) {
return ApiResponse::FORBIDDEN->response([
'niv' => $niv,
'stolen' => true,
'message' => 'El vehículo reporta robo. No se puede continuar con la actualización.',
]);
}
$record = Record::with(['vehicle.owner', 'vehicle.tag', 'files', 'error'])
->where('folio', $folio)
->first();
if (!$record) {
return ApiResponse::NOT_FOUND->response([
'message' => 'No se encontró el expediente',
'folio' => $folio,
]);
}
$vehicle = $record->vehicle;
$tag = $vehicle->tag;
if (!$tag) {
return ApiResponse::NOT_FOUND->response([
'message' => 'El TAG no coincide con el registrado en el expediente',
'tag_number' => $tagNumber,
]);
}
if ($vehicle->niv !== $niv) {
return ApiResponse::BAD_REQUEST->response([
'message' => 'El NIV no coincide con el registrado en el expediente',
]);
}
DB::beginTransaction();
$isManualUpdate = $request->has('vehicle') || $request->has('owner');
$hasVehicleChanges = false;
$hasOwnerChanges = false;
$owner = $vehicle->owner;
if ($isManualUpdate) {
if ($request->has('vehicle')) {
$vehicleData = $request->input('vehicle', []);
$allowedVehicleFields = [
'placa',
'marca',
'linea',
'sublinea',
'modelo',
'color',
'numero_motor',
'clase_veh',
'tipo_servicio',
'rfv',
'ofcexpedicion',
'fechaexpedicion',
'tipo_veh',
'numptas',
'observac',
'cve_vehi',
'nrpv',
'tipo_mov'
];
$vehicleData = array_filter(
array_intersect_key($vehicleData, array_flip($allowedVehicleFields)),
fn($value) => $value !== null && $value !== ''
);
if (!empty($vehicleData)) {
$vehicle->update($vehicleData);
$hasVehicleChanges = true;
}
}
if ($request->has('owner')) {
$ownerInput = $request->input('owner', []);
$allowedOwnerFields = [
'name',
'paternal',
'maternal',
'rfc',
'curp',
'address',
'tipopers',
'pasaporte',
'licencia',
'ent_fed',
'munic',
'callep',
'num_ext',
'num_int',
'colonia',
'cp',
'telefono'
];
$ownerData = array_filter(
array_intersect_key($ownerInput, array_flip($allowedOwnerFields)),
fn($value) => $value !== null && $value !== ''
);
if (!empty($ownerData)) {
// Si se cambió el RFC, buscar/crear otro propietario
if (isset($ownerData['rfc']) && $ownerData['rfc'] !== $owner->rfc) {
$owner = Owner::updateOrCreate(
['rfc' => $ownerData['rfc']],
$ownerData
);
$vehicle->update(['owner_id' => $owner->id]);
} else {
// Actualizar propietario existente
$owner->update($ownerData);
}
$hasOwnerChanges = true;
}
}
} else {
// Intentar obtener datos del caché primero
$vehicleDataEstatal = Cache::get("update_vehicle_{$niv}");
$ownerDataEstatal = Cache::get("update_owner_{$niv}");
// Si no hay
if (!$vehicleDataEstatal || !$ownerDataEstatal) {
$vehicleDataEstatal = $this->getVehicle($niv);
$ownerDataEstatal = $this->getOwner($niv);
}
// Limpiar caché
Cache::forget("update_vehicle_{$niv}");
Cache::forget("update_owner_{$niv}");
// Detectar si hay cambios
$hasVehicleChanges = $this->detectVehicleChanges($vehicle, $vehicleDataEstatal);
$hasOwnerChanges = $this->detectOwnerChanges($vehicle->owner, $ownerDataEstatal);
// Actualizar vehículo solo si hay cambios
if ($hasVehicleChanges) {
$vehicle->update($vehicleDataEstatal);
}
// Actualizar propietario solo si hay cambios
$owner = $vehicle->owner;
if ($hasOwnerChanges) {
$owner = Owner::updateOrCreate(
['rfc' => $ownerDataEstatal['rfc']],
$ownerDataEstatal
);
$vehicle->update(['owner_id' => $owner->id]);
}
}
$uploadedFiles = [];
$replacedFiles = [];
if ($request->hasFile('files')) {
$files = $request->file('files');
$nameIds = $request->input('name_id', []);
if (!empty($nameIds)) {
$validIds = CatalogNameImg::whereIn('id', $nameIds)->pluck('id')->toArray();
if (count($validIds) !== count($nameIds)) {
DB::rollBack();
return ApiResponse::BAD_REQUEST->response([
'message' => 'Algunos ids del catálogo de nombres no son válidos',
'provided_id' => $nameIds,
'valid_id' => $validIds,
]);
}
}
foreach ($files as $indx => $file) {
$nameId = $nameIds[$indx] ?? null;
if ($nameId === null) {
DB::rollBack();
return ApiResponse::BAD_REQUEST->response([
'message' => "Falta el nombre para el archivo, busca en el catálogo de nombres",
]);
}
$existingFile = File::where('record_id', $record->id)
->where('name_id', $nameId)
->first();
if ($existingFile) {
Storage::disk('public')->delete($existingFile->path);
$replacedFiles[] = [
'id' => $existingFile->id,
'name_id' => $nameId,
'old_path' => $existingFile->path,
];
$existingFile->delete();
}
// Obtener el nombre del catálogo para el nombre del archivo
$catalogName = CatalogNameImg::find($nameId);
$extension = $file->getClientOriginalExtension();
$fileName = $catalogName->name . '_' . date('dmY_His') . '.' . $extension;
$path = $file->storeAs("records/{$record->folio}", $fileName, 'public');
$md5 = md5_file($file->getRealPath());
$fileRecord = File::create([
'name_id' => $nameId,
'path' => $path,
'md5' => $md5,
'record_id' => $record->id,
]);
$uploadedFiles[] = [
'id' => $fileRecord->id,
'name' => $catalogName->name,
'path' => $fileRecord->path,
'url' => $fileRecord->url,
'replaced' => $existingFile !== null,
];
}
}
if ($hasVehicleChanges || $hasOwnerChanges || count($uploadedFiles) > 0) {
VehicleTagLog::create([
'vehicle_id' => $vehicle->id,
'tag_id' => $tag->id,
'action_type' => 'actualizacion',
'performed_by' => Auth::id()
]);
}
// Solo enviar a REPUVE Nacional si hay cambios
if ($hasVehicleChanges || $hasOwnerChanges || count($uploadedFiles) > 0) {
// Preparar datos completos para REPUVE
$datosCompletos = $this->prepararDatosParaInscripcion($niv);
// Enviar job
ProcessRepuveResponse::dispatch($record->id, $datosCompletos);
}
DB::commit();
$message = 'Vehículo actualizado exitosamente';
if (!$hasVehicleChanges && !$hasOwnerChanges && empty($uploadedFiles)) {
$message = 'No se detectaron cambios. Los datos ya estaban actualizados.';
} elseif (($hasVehicleChanges || $hasOwnerChanges) && !empty($uploadedFiles)) {
$message = 'Datos del vehículo/propietario y archivos actualizados exitosamente.';
} elseif (($hasVehicleChanges || $hasOwnerChanges) && empty($uploadedFiles)) {
$message = 'Datos del vehículo/propietario actualizados exitosamente. No se subieron archivos.';
} elseif (!$hasVehicleChanges && !$hasOwnerChanges && !empty($uploadedFiles)) {
$message = 'Archivos subidos exitosamente. No hubo cambios en los datos del vehículo/propietario.';
}
return ApiResponse::OK->response([
'message' => $message,
'has_error' => false,
'changes_made' => [
'vehicle_updated' => $hasVehicleChanges,
'owner_updated' => $hasOwnerChanges,
'files_uploaded' => count($uploadedFiles) > 0,
],
'record' => $record,
'vehicle' => $vehicle,
'owner' => $owner,
'files' => $record->files,
'uploaded_files' => $uploadedFiles,
'replaced_count' => count($replacedFiles),
'total_files' => File::where('record_id', $record->id)->count(),
]);
} catch (Exception $e) {
return ApiResponse::INTERNAL_ERROR->response([
'message' => 'Error al actualizar el vehículo',
'error' => $e->getMessage(),
]);
}
}
private function checkIfStolen(string $niv): bool
{
return $this->repuveService->verificarRobo($niv);
}
private function prepararDatosParaInscripcion(string $niv): array
{
$datos = $this->padronEstatalService->getVehiculoByNiv($niv);
return [
'ent_fed' => $datos['ent_fed'] ?? '',
'ofcexp' => $datos['ofcexp'] ?? '',
'fechaexp' => $datos['fechaexp'] ?? '',
'placa' => $datos['placa'] ?? '',
'tarjetacir' => $datos['tarjetacir'] ?? '',
'marca' => $datos['marca'] ?? '',
'submarca' => $datos['submarca'] ?? '',
'version' => $datos['version'] ?? '',
'clase_veh' => $datos['clase_veh'] ?? '',
'tipo_veh' => $datos['tipo_veh'] ?? '',
'tipo_uso' => $datos['tipo_uso'] ?? '',
'modelo' => $datos['modelo'] ?? '',
'color' => $datos['color'] ?? '',
'motor' => $datos['motor'] ?? '',
'niv' => $datos['niv'] ?? '',
'rfv' => $datos['rfv'] ?? '',
'numptas' => $datos['numptas'] ?? '',
'observac' => $datos['observac'] ?? '',
'tipopers' => $datos['tipopers'] ?? '',
'curp' => $datos['curp'] ?? '',
'rfc' => $datos['rfc'] ?? '',
'pasaporte' => $datos['pasaporte'] ?? '',
'licencia' => $datos['licencia'] ?? '',
'nombre' => $datos['nombre'] ?? '',
'ap_paterno' => $datos['ap_paterno'] ?? '',
'ap_materno' => $datos['ap_materno'] ?? '',
'munic' => $datos['munic'] ?? '',
'callep' => $datos['callep'] ?? '',
'num_ext' => $datos['num_ext'] ?? '',
'num_int' => $datos['num_int'] ?? '',
'colonia' => $datos['colonia'] ?? '',
'cp' => $datos['cp'] ?? '',
'cve_vehi' => $datos['cve_vehi'] ?? '',
'nrpv' => $datos['nrpv'] ?? '',
'tipo_mov' => $datos['tipo_mov'] ?? '',
];
}
private function detectVehicleChanges($vehicle, array $vehicleDataEstatal): bool
{
$fieldsToCompare = [
'placa',
'marca',
'linea',
'sublinea',
'modelo',
'color',
'numero_motor',
'clase_veh',
'tipo_servicio',
'rfv',
'ofcexpedicion',
'tipo_veh',
'numptas',
'observac',
'cve_vehi',
'nrpv',
'tipo_mov'
];
foreach ($fieldsToCompare as $field) {
$bdValue = $vehicle->$field ?? null;
$estatalValue = $vehicleDataEstatal[$field] ?? null;
if (strval($bdValue) !== strval($estatalValue)) {
return true;
}
}
return false;
}
private function detectOwnerChanges($owner, array $ownerDataEstatal): bool
{
$fieldsToCompare = [
'name',
'paternal',
'maternal',
'rfc',
'curp',
'address',
'tipopers',
'pasaporte',
'licencia',
'ent_fed',
'munic',
'callep',
'num_ext',
'num_int',
'colonia',
'cp'
];
foreach ($fieldsToCompare as $field) {
$bdValue = $owner->$field ?? null;
$estatalValue = $ownerDataEstatal[$field] ?? null;
if (strval($bdValue) !== strval($estatalValue)) {
return true;
}
}
return false;
}
private function getVehicle(string $niv): array
{
$datos = $this->padronEstatalService->getVehiculoByNiv($niv);
return $this->padronEstatalService->extraerDatosVehiculo($datos);
}
private function getOwner(string $niv): array
{
$datos = $this->padronEstatalService->getVehiculoByNiv($niv);
return $this->padronEstatalService->extraerDatosPropietario($datos);
}
/* --------------------------------------------------------- */
public function updateData(VehicleUpdateRequest $request, $id)
{
try {
$record = Record::with(['vehicle.owner', 'vehicle.tag', 'files', 'error'])
->findOrFail($id);
$vehicle = $record->vehicle;
$owner = $vehicle->owner;
$tag = $vehicle->tag;
DB::beginTransaction();
$hasVehicleChanges = false;
$hasOwnerChanges = false;
if ($request->has('vehicle')) {
$vehicleData = $request->input('vehicle', []);
$allowedVehicleFields = [
'placa',
'niv',
'marca',
'linea',
'sublinea',
'modelo',
'color',
'numero_motor',
'clase_veh',
'tipo_servicio',
'rfv',
'ofcexpedicion',
'fechaexpedicion',
'tipo_veh',
'numptas',
'observac',
'cve_vehi',
'nrpv',
'tipo_mov'
];
$vehicleData = array_filter(
array_intersect_key($vehicleData, array_flip($allowedVehicleFields)),
fn($value) => $value !== null && $value !== ''
);
if (!empty($vehicleData)) {
$vehicle->update($vehicleData);
$hasVehicleChanges = true;
}
}
// Actualizar propietario si se envían datos
if ($request->has('owner')) {
$ownerInput = $request->input('owner', []);
$allowedOwnerFields = [
'name',
'paternal',
'maternal',
'rfc',
'curp',
'address',
'tipopers',
'pasaporte',
'licencia',
'ent_fed',
'munic',
'callep',
'num_ext',
'num_int',
'colonia',
'cp',
'telefono'
];
$ownerData = array_filter(
array_intersect_key($ownerInput, array_flip($allowedOwnerFields)),
fn($value) => $value !== null && $value !== ''
);
if (!empty($ownerData)) {
// Si se intenta cambiar el RFC
if (isset($ownerData['rfc']) && $ownerData['rfc'] !== $owner->rfc) {
// Verificar que el nuevo RFC no exista ya
$existingOwner = Owner::where('rfc', $ownerData['rfc'])->first();
if ($existingOwner) {
DB::rollBack();
return ApiResponse::BAD_REQUEST->response([
'message' => 'El RFC ya existe en el sistema',
'rfc' => $ownerData['rfc'],
'owner_id' => $existingOwner->id,
]);
}
// Si no existe, actualizar el RFC del propietario actual
$owner->update($ownerData);
}
$hasOwnerChanges = true;
}
}
// Procesar archivos
$uploadedFiles = [];
$replacedFiles = [];
if ($request->hasFile('files')) {
$files = $request->file('files');
$nameIds = $request->input('name_id', []);
if (!empty($nameIds)) {
$validIds = CatalogNameImg::whereIn('id', $nameIds)->pluck('id')->toArray();
if (count($validIds) !== count($nameIds)) {
DB::rollBack();
return ApiResponse::BAD_REQUEST->response([
'message' => 'Algunos ids del catálogo de nombres no son válidos',
'provided_id' => $nameIds,
'valid_id' => $validIds,
]);
}
}
foreach ($files as $indx => $file) {
$nameId = $nameIds[$indx] ?? null;
if ($nameId === null) {
DB::rollBack();
return ApiResponse::BAD_REQUEST->response([
'message' => "Falta el nombre para el archivo, busca en el catálogo de nombres",
]);
}
$existingFile = File::where('record_id', $record->id)
->where('name_id', $nameId)
->first();
if ($existingFile) {
Storage::disk('public')->delete($existingFile->path);
$replacedFiles[] = [
'id' => $existingFile->id,
'name_id' => $nameId,
'old_path' => $existingFile->path,
];
$existingFile->delete();
}
// Obtener el nombre del catálogo para el nombre del archivo
$catalogName = CatalogNameImg::find($nameId);
$extension = $file->getClientOriginalExtension();
$fileName = $catalogName->name . '_' . date('dmY_His') . '.' . $extension;
$path = $file->storeAs("records/{$record->folio}", $fileName, 'public');
$md5 = md5_file($file->getRealPath());
$fileRecord = File::create([
'name_id' => $nameId,
'path' => $path,
'md5' => $md5,
'record_id' => $record->id,
]);
$uploadedFiles[] = [
'id' => $fileRecord->id,
'name' => $catalogName->name,
'path' => $fileRecord->path,
'url' => $fileRecord->url,
'replaced' => $existingFile !== null,
];
}
}
// Registrar el log de cambios si hubo actualizaciones
if ($hasVehicleChanges || $hasOwnerChanges || count($uploadedFiles) > 0) {
VehicleTagLog::create([
'vehicle_id' => $vehicle->id,
'tag_id' => $tag->id,
'action_type' => 'actualizacion',
'performed_by' => Auth::id()
]);
}
// datos para REPUVE Nacional usando datos actuales de la BD
if ($hasVehicleChanges || $hasOwnerChanges || count($uploadedFiles) > 0) {
// Recargar el vehículo y propietario con los datos actualizados
$vehicle->refresh();
$owner->refresh();
$datosCompletos = [
'ent_fed' => $owner->ent_fed ?? '',
'ofcexp' => $vehicle->ofcexpedicion ?? '',
'fechaexp' => $vehicle->fechaexpedicion ?? '',
'placa' => $vehicle->placa ?? '',
'tarjetacir' => $vehicle->rfv ?? '',
'marca' => $vehicle->marca ?? '',
'submarca' => $vehicle->linea ?? '',
'version' => $vehicle->sublinea ?? '',
'clase_veh' => $vehicle->clase_veh ?? '',
'tipo_veh' => $vehicle->tipo_veh ?? '',
'tipo_uso' => $vehicle->tipo_servicio ?? '',
'modelo' => $vehicle->modelo ?? '',
'color' => $vehicle->color ?? '',
'motor' => $vehicle->numero_motor ?? '',
'niv' => $vehicle->niv ?? '',
'rfv' => $vehicle->rfv ?? '',
'numptas' => $vehicle->numptas ?? '',
'observac' => $vehicle->observac ?? '',
'tipopers' => $owner->tipopers ?? '',
'curp' => $owner->curp ?? '',
'rfc' => $owner->rfc ?? '',
'pasaporte' => $owner->pasaporte ?? '',
'licencia' => $owner->licencia ?? '',
'nombre' => $owner->name ?? '',
'ap_paterno' => $owner->paternal ?? '',
'ap_materno' => $owner->maternal ?? '',
'munic' => $owner->munic ?? '',
'callep' => $owner->callep ?? '',
'num_ext' => $owner->num_ext ?? '',
'num_int' => $owner->num_int ?? '',
'colonia' => $owner->colonia ?? '',
'cp' => $owner->cp ?? '',
'cve_vehi' => $vehicle->cve_vehi ?? '',
'nrpv' => $vehicle->nrpv ?? '',
'tipo_mov' => $vehicle->tipo_mov ?? '',
];
// Enviar job a REPUVE Nacional
ProcessRepuveResponse::dispatch($record->id, $datosCompletos);
}
DB::commit();
// Recargar relaciones para la respuesta
$record->load(['vehicle.owner', 'vehicle.tag', 'files', 'error']);
$message = 'Expediente actualizado exitosamente';
if (!$hasVehicleChanges && !$hasOwnerChanges && empty($uploadedFiles)) {
$message = 'No se detectaron cambios. Los datos ya estaban actualizados.';
} elseif (($hasVehicleChanges || $hasOwnerChanges) && !empty($uploadedFiles)) {
$message = 'Datos del vehículo/propietario y archivos actualizados exitosamente.';
} elseif (($hasVehicleChanges || $hasOwnerChanges) && empty($uploadedFiles)) {
$message = 'Datos del vehículo/propietario actualizados exitosamente. No se subieron archivos.';
} elseif (!$hasVehicleChanges && !$hasOwnerChanges && !empty($uploadedFiles)) {
$message = 'Archivos subidos exitosamente. No hubo cambios en los datos del vehículo/propietario.';
}
return ApiResponse::OK->response([
'message' => $message,
'has_error' => false,
'changes_made' => [
'vehicle_updated' => $hasVehicleChanges,
'owner_updated' => $hasOwnerChanges,
'files_uploaded' => count($uploadedFiles) > 0,
],
'record' => $record,
'uploaded_files' => $uploadedFiles,
'replaced_count' => count($replacedFiles),
'total_files' => File::where('record_id', $record->id)->count(),
]);
} catch (Exception $e) {
DB::rollBack();
return ApiResponse::INTERNAL_ERROR->response([
'message' => 'Error al actualizar el expediente',
'error' => $e->getMessage(),
]);
}
}
public function resendToRepuve($id)
{
try {
$record = Record::with('vehicle.owner')
->where('id', $id)
->first();
$vehicle = $record->vehicle;
$owner = $vehicle->owner;
// Preparar datos actuales de la BD
$datosCompletos = [
'ent_fed' => $owner->ent_fed ?? '',
'ofcexp' => $vehicle->ofcexpedicion ?? '',
'fechaexp' => $vehicle->fechaexpedicion ?? '',
'placa' => $vehicle->placa ?? '',
'tarjetacir' => $vehicle->rfv ?? '',
'marca' => $vehicle->marca ?? '',
'submarca' => $vehicle->linea ?? '',
'version' => $vehicle->sublinea ?? '',
'clase_veh' => $vehicle->clase_veh ?? '',
'tipo_veh' => $vehicle->tipo_veh ?? '',
'tipo_uso' => $vehicle->tipo_servicio ?? '',
'modelo' => $vehicle->modelo ?? '',
'color' => $vehicle->color ?? '',
'motor' => $vehicle->numero_motor ?? '',
'niv' => $vehicle->niv ?? '',
'rfv' => $vehicle->rfv ?? '',
'numptas' => $vehicle->numptas ?? '',
'observac' => $vehicle->observac ?? '',
'tipopers' => $owner->tipopers ?? '',
'curp' => $owner->curp ?? '',
'rfc' => $owner->rfc ?? '',
'pasaporte' => $owner->pasaporte ?? '',
'licencia' => $owner->licencia ?? '',
'nombre' => $owner->name ?? '',
'ap_paterno' => $owner->paternal ?? '',
'ap_materno' => $owner->maternal ?? '',
'munic' => $owner->munic ?? '',
'callep' => $owner->callep ?? '',
'num_ext' => $owner->num_ext ?? '',
'num_int' => $owner->num_int ?? '',
'colonia' => $owner->colonia ?? '',
'cp' => $owner->cp ?? '',
'cve_vehi' => $vehicle->cve_vehi ?? '',
'nrpv' => $vehicle->nrpv ?? '',
'tipo_mov' => $vehicle->tipo_mov ?? '',
];
// reenviar a REPUVE Nacional
ProcessRepuveResponse::dispatch($record->id, $datosCompletos);
return ApiResponse::OK->response([
'message' => 'Solicitud de reenvío a REPUVE Nacional procesada exitosamente',
'folio' => $record->folio,
'record_id' => $record->id,
]);
} catch (Exception $e) {
return ApiResponse::INTERNAL_ERROR->response([
'message' => 'Error al procesar el reenvío',
'error' => $e->getMessage(),
]);
}
}
}