fix: excel de registros con historial de tags

This commit is contained in:
Juan Felipe Zapata Moreno 2026-01-21 19:28:12 -06:00
parent b602687233
commit c725072291

View File

@ -1264,7 +1264,7 @@ public function exportSearchRecords(Request $request)
]);
}
// Preparar datos para Excel: una fila por cada entrada del historial
// Preparar datos para Excel: una fila por cada entrada del historial de tags
$excelRows = [];
foreach ($allRecords as $record) {
@ -1276,104 +1276,55 @@ public function exportSearchRecords(Request $request)
$modelo = $vehicle->modelo ?? '';
$moduleName = $record->module->name ?? '';
$operador = $record->user->name ?? $record->user->username ?? '';
$currentTagId = $vehicle->tag?->id;
// Obtener todos los logs ordenados por fecha ascendente
$vehicleLogs = $vehicle->vehicleTagLogs->sortBy('created_at');
$processedTags = [];
// Procesar tags del historial (excluyendo el tag actual)
// Generar una fila por cada log (cada acción en el historial)
foreach ($vehicleLogs as $log) {
$tagId = $log->tag_id;
$tag = $log->tag;
// Excluir el tag actual y solo procesar cada tag una vez
if ($tagId && $tagId !== $currentTagId && !in_array($tagId, $processedTags)) {
$processedTags[] = $tagId;
$tag = $log->tag;
// Determinar status basado en el tipo de acción y si tiene cancelación
$status = 'Asignado';
$tipoTramite = ucfirst($log->action_type);
$fecha = Carbon::parse($log->created_at);
// Buscar todos los logs relacionados con este tag
$tagLogs = $vehicleLogs->where('tag_id', $tagId);
// Buscar fecha de cancelación si existe
$cancelLog = $tagLogs
->whereIn('action_type', ['cancelacion', 'sustitucion'])
->whereNotNull('cancellation_at')
->first();
// Obtener fecha de asignación (inscripción o sustitución)
$assignedLog = $tagLogs
->whereIn('action_type', ['inscripcion', 'sustitucion'])
->first();
// Determinar fecha, status y tipo de trámite
$fecha = null;
$status = 'unknown';
$tipoTramite = '';
if ($cancelLog && $cancelLog->cancellation_at) {
$fecha = Carbon::parse($cancelLog->cancellation_at);
$status = 'Cancelado';
$tipoTramite = ucfirst($cancelLog->action_type);
} elseif ($assignedLog && $assignedLog->created_at) {
$fecha = Carbon::parse($assignedLog->created_at);
$status = $tag?->status?->name ?? ucfirst($assignedLog->action_type);
$tipoTramite = ucfirst($assignedLog->action_type);
}
// Si no hay fecha, usar el status del tag
if (!$fecha) {
$status = $tag?->status?->name ?? 'unknown';
}
// Obtener caja del tag
$caja = $tag?->package?->box_number ?? '';
$excelRows[] = [
'status' => $status,
'modulo' => $tag?->module?->name ?? $moduleName,
'operador' => $operador,
'tipo_tramite' => $tipoTramite,
'niv' => $niv,
'nrpv' => $nrpv,
'marca' => $marca,
'placa' => $placa,
'modelo' => $modelo,
'folio' => $tag?->folio ?? '',
'caja' => $caja,
'tag' => $tag?->tag_number ?? '',
'fecha' => $fecha ? $fecha->format('d/m/Y H:i') : '',
'sort_date' => $fecha ? $fecha->timestamp : 0,
];
}
}
// Agregar el registro principal (tag actual)
if ($vehicle->tag) {
$currentTag = $vehicle->tag;
$latestLog = $vehicle->vehicleTagLogs->first();
// Determinar fecha, status y tipo de trámite del tag actual
$fechaActual = null;
$statusActual = $currentTag->status?->name ?? 'unknown';
$tipoTramiteActual = '';
if ($latestLog) {
$tipoTramiteActual = ucfirst($latestLog->action_type);
if ($latestLog->cancellation_at) {
$fechaActual = Carbon::parse($latestLog->cancellation_at);
$statusActual = 'Cancelado';
} else {
$fechaActual = Carbon::parse($latestLog->created_at);
}
} else {
$fechaActual = $record->created_at ? Carbon::parse($record->created_at) : now();
// Si el log tiene cancellation_at, es una cancelación/sustitución del tag
if ($log->cancellation_at) {
$status = 'Cancelado';
$fecha = Carbon::parse($log->cancellation_at);
} elseif ($tag && $tag->status) {
$status = $tag->status->name;
}
$excelRows[] = [
'status' => $statusActual,
'status' => $status,
'modulo' => $tag?->module?->name ?? $moduleName,
'operador' => $operador,
'tipo_tramite' => $tipoTramite,
'niv' => $niv,
'nrpv' => $nrpv,
'marca' => $marca,
'placa' => $placa,
'modelo' => $modelo,
'folio' => $tag?->folio ?? '',
'caja' => $tag?->package?->box_number ?? '',
'tag' => $tag?->tag_number ?? '',
'fecha' => $fecha->format('d/m/Y H:i'),
'sort_date' => $fecha->timestamp,
];
}
// Si no hay logs pero hay tag asignado, agregar al menos una fila
if ($vehicleLogs->isEmpty() && $vehicle->tag) {
$currentTag = $vehicle->tag;
$fechaActual = $record->created_at ? Carbon::parse($record->created_at) : now();
$excelRows[] = [
'status' => $currentTag->status?->name ?? 'Asignado',
'modulo' => $currentTag->module?->name ?? $moduleName,
'operador' => $operador,
'tipo_tramite' => $tipoTramiteActual,
'tipo_tramite' => 'Inscripcion',
'niv' => $niv,
'nrpv' => $nrpv,
'marca' => $marca,
@ -1424,14 +1375,13 @@ public function exportSearchRecords(Request $request)
'C' => 'Operador',
'D' => 'Tipo de Trámite',
'E' => 'NIV',
'F' => 'NRPV',
'F' => 'NRPV/NCI',
'G' => 'Marca',
'H' => 'Placa',
'I' => 'Año',
'J' => 'Folio',
'K' => 'Caja',
'L' => 'Tag ID',
'M' => 'Fecha',
];
$row = 1;
@ -1456,7 +1406,6 @@ public function exportSearchRecords(Request $request)
$sheet->setCellValue('J' . $row, $item['folio']);
$sheet->setCellValue('K' . $row, $item['caja']);
$sheet->setCellValue('L' . $row, $item['tag']);
$sheet->setCellValue('M' . $row, $item['fecha']);
// Aplicar estilos a todas las columnas
foreach (range('A', 'M') as $col) {
@ -1469,26 +1418,23 @@ public function exportSearchRecords(Request $request)
$sheet->getStyle("I{$row}")->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
$sheet->getStyle("J{$row}")->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
$sheet->getStyle("K{$row}")->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
$sheet->getStyle("L{$row}")->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
$sheet->getStyle("M{$row}")->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
$row++;
}
// Ajustar anchos de columna
$sheet->getColumnDimension('A')->setWidth(15); // Estatus
$sheet->getColumnDimension('B')->setWidth(20); // Módulo
$sheet->getColumnDimension('B')->setWidth(25); // Módulo
$sheet->getColumnDimension('C')->setWidth(20); // Operador
$sheet->getColumnDimension('D')->setWidth(18); // Tipo de Trámite
$sheet->getColumnDimension('E')->setWidth(22); // NIV
$sheet->getColumnDimension('F')->setWidth(14); // NRPV
$sheet->getColumnDimension('F')->setWidth(14); // NRPV/NCI
$sheet->getColumnDimension('G')->setWidth(15); // Marca
$sheet->getColumnDimension('H')->setWidth(12); // Placa
$sheet->getColumnDimension('I')->setWidth(8); // Año
$sheet->getColumnDimension('J')->setWidth(18); // Folio
$sheet->getColumnDimension('K')->setWidth(10); // Caja
$sheet->getColumnDimension('L')->setWidth(28); // Tag ID
$sheet->getColumnDimension('M')->setWidth(18); // Fecha
$sheet->getColumnDimension('J')->setWidth(12); // Folio
$sheet->getColumnDimension('K')->setWidth(8); // Caja
$sheet->getColumnDimension('L')->setWidth(30); // Tag ID
// Guardar archivo
$writer = new Xlsx($spreadsheet);