diff --git a/app/Http/Controllers/Repuve/ExcelController.php b/app/Http/Controllers/Repuve/ExcelController.php index 8583c12..42b92bb 100644 --- a/app/Http/Controllers/Repuve/ExcelController.php +++ b/app/Http/Controllers/Repuve/ExcelController.php @@ -335,11 +335,17 @@ public function constanciasSustituidas(Request $request) ->whereNotNull('cancellation_at') ->whereBetween('cancellation_at', [$fechaInicio, $fechaFin]); }) - // sustitucion_primera_vez: un solo log sin cancellation_at, filtrar por created_at + // sustitucion_primera_vez activo: un solo log sin cancellation_at, filtrar por created_at ->orWhere(function ($q) use ($fechaInicio, $fechaFin) { $q->where('action_type', 'sustitucion_primera_vez') ->whereNull('cancellation_at') ->whereBetween('created_at', [$fechaInicio, $fechaFin]); + }) + // sustitucion_primera_vez cancelado: fue el tag viejo en una sustitución posterior + ->orWhere(function ($q) use ($fechaInicio, $fechaFin) { + $q->where('action_type', 'sustitucion_primera_vez') + ->whereNotNull('cancellation_at') + ->whereBetween('cancellation_at', [$fechaInicio, $fechaFin]); }); }) ->when($moduleId, function ($query) use ($moduleId) { @@ -356,8 +362,8 @@ public function constanciasSustituidas(Request $request) // PREPARACIÓN DE DATOS $data = $logs->map(function ($log) { - // sustitucion_primera_vez: un solo log, el log mismo ES el nuevo TAG asignado - if ($log->action_type === 'sustitucion_primera_vez') { + // sustitucion_primera_vez activo (sin cancellation_at): el log mismo ES el nuevo TAG asignado + if ($log->action_type === 'sustitucion_primera_vez' && is_null($log->cancellation_at)) { return [ 'niv' => $log->vehicle->niv ?? '', 'nrpv' => $log->vehicle->nrpv ?? '', @@ -376,9 +382,8 @@ public function constanciasSustituidas(Request $request) $newTagLog = VehicleTagLog::with('tag') ->where('vehicle_id', $log->vehicle_id) ->whereIn('action_type', ['sustitucion_primera_vez', 'sustitucion']) - ->whereNull('cancellation_at') ->where('id', '!=', $log->id) - ->where('created_at', '>=', $log->created_at) + ->where('created_at', '>=', $log->cancellation_at ?? $log->created_at) ->orderBy('created_at', 'asc') ->first(); @@ -407,8 +412,8 @@ public function constanciasSustituidas(Request $request) 'placa' => $log->vehicle->placa ?? '', 'modelo' => $log->vehicle->modelo ?? '', 'folio_ant' => $folioAnt, - 'folio_act' => $newTagLog?->tag?->folio ?? '', - 'chip' => substr($newTagLog?->tag?->rfid ?? $newTagLog?->tag?->tag_number ?? '', 0, 24), + 'folio_act' => $newTagLog?->tag?->folio ?? $log->tag->folio ?? '', + 'chip' => substr($newTagLog?->tag?->rfid ?? $newTagLog?->tag?->tag_number ?? $log->tag->rfid ?? $log->tag->tag_number ?? '', 0, 24), 'fecha' => $log->cancellation_at?->format('d/m/Y') ?? $log->created_at->format('d/m/Y'), 'observaciones' => $log->cancellationReason?->name ?? $log->cancellation_observations ?? '', ];