File: /var/www/dtw.bradford/app/Imports/UploadColegiumImport.php
<?php
namespace App\Imports;
use App\Models\UploadStudentDebtDetail;
use Exception;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use PhpOffice\PhpSpreadsheet\Shared\Date;
class UploadColegiumImport implements ToCollection, WithHeadingRow
{
/**
* Define los encabezados esperados en el archivo.
*/
protected $expectedHeaders = [
'id',
'nombre',
'rut',
'subtotal',
'iva',
'total',
'fecha_de_creacion'
];
public $errorMessage;
public $successMessage;
public $register_id;
public $error_data = [];
public $records_processed = 0;
public function __construct()
{
}
/**
* @param Collection $rows
*/
public function collection(Collection $rows)
{
if (count($rows) < 1) {
$this->errorMessage = [
'type' => 'ERROR DE VALIDACIÓN',
'message' => 'El documento está vacío'
];
return;
}
// Verificar los encabezados en la primera fila.
$headers = $rows->first()->keys()->toArray();
// Comprobar que todos los encabezados coincidan.
foreach ($this->expectedHeaders as $header) {
if (!in_array($header, $headers)) {
$this->errorMessage = [
'type' => 'ERROR DE VALIDACIÓN',
'message' => 'Falta el encabezado requerido: ' . $header
];
return;
}
}
$this->records_processed = count($rows);
// Validar y preparar data para almacenamiento
$quantity_error = 0;
$num_row = 2;
$this->error_data = [];
$create_body = [];
foreach ($rows as $row) {
$validation_errors = 0;
$validation_messages = '';
try {
// Validación de data
if (empty($row['id'])) {
$validation_errors++;
$validation_messages .= ($validation_errors) . ': Debe ingresar id. ';
}
if (empty($row['nombre'])) {
$validation_errors++;
$validation_messages .= ($validation_errors) . ': Debe ingresar nombre. ';
}
if (empty($row['rut'])) {
$validation_errors++;
$validation_messages .= ($validation_errors) . ': Debe ingresar rut. ';
}
if (empty($row['subtotal'])) {
$validation_errors++;
$validation_messages .= ($validation_errors) . ': Debe subtotal. ';
}
if (empty($row['iva'])) {
$validation_errors++;
$validation_messages .= ($validation_errors) . ': Debe ingresar iva. ';
}
if (empty($row['total'])) {
$validation_errors++;
$validation_messages .= ($validation_errors) . ': Debe total. ';
}
// Validar rut
if (!validateRut(trim($row['rut']))) {
$validation_errors++;
$validation_messages .= ($validation_errors) . ': Rut inválido. ';
}
// Validar enteros
if (!is_int($row['id'])) {
$validation_errors++;
$validation_messages .= ($validation_errors) . ': ID inválido. ';
}
if (!is_int($row['subtotal'])) {
$validation_errors++;
$validation_messages .= ($validation_errors) . ': Subtotal inválido. ';
}
if (!is_int($row['iva'])) {
$validation_errors++;
$validation_messages .= ($validation_errors) . ': Iva inválido. ';
}
if (!is_int($row['total'])) {
$validation_errors++;
$validation_messages .= ($validation_errors) . ': Total inválido. ';
}
// Validar string
if (!is_string($row['nombre'])) {
$validation_errors++;
$validation_messages .= ($validation_errors) . ': El nombre debe ser un string. ';
}
// Validar fecha (formato excel)
try {
$date = Date::excelToDateTimeObject($row['fecha_de_creacion']);
$formated_date = $date->format('Y-m-d');
} catch (\Throwable $th) {
$validation_errors++;
$validation_messages .= ($validation_errors) . ': Fecha de creación inválida. ';
}
// Si hay algun error sumar 1 a cantidad de filas con error y procesar la data para almacenar en informe errores
if ($validation_errors > 0) {
$quantity_error++;
$data = [
'numero_de_linea' => $num_row,
'errores' => $validation_messages,
'fecha_de_carga' => date('d-m-Y H:i'),
];
$this->error_data[] = $data;
} else {
// Si no hay errores en la fila actual ni en las filas anteriores procesar la data para carga
if ($quantity_error == 0) {
$data = [
'register_id' => intval(trim($row['id'])),
'name' => trim($row['nombre']),
'rut' => strUpper(str_replace('.', '', formateaRut(trim($row['rut'])))),
'subtotal' => intval(trim($row['subtotal'])),
'iva' => intval(trim($row['iva'])),
'total' => intval(trim($row['total'])),
'date_creation' => ordenar_fechaServidor($formated_date),
// 'user_created' => auth()->user()->id,
'created_at' => ahoraServidor()
];
$create_body[] = $data;
}
}
} catch (\Exception $e) {
$quantity_error++;
$data = [
'numero_de_linea' => $num_row,
'errores' => $validation_messages .= ($validation_errors) . ': ' . $e->getMessage(),
'fecha_de_carga' => date('d-m-Y H:i'),
];
$this->error_data[] = $data;
}
$num_row++;
}
if ($quantity_error == 0) {
try {
// Inserción de datos
DB::beginTransaction();
$insert = DB::table('colegium_data_test')->insert($create_body);
if ($insert) {
DB::commit();
$this->successMessage = "Importación realizada correctamente.";
} else {
DB::rollBack();
$this->errorMessage = [
'type' => 'ERROR DE BASE DE DATOS',
'message' => 'Error de base de datos. Por favor intentelo nuevamente.'
];
}
} catch (Exception $e) {
DB::rollBack();
$this->errorMessage = [
'type' => 'ERROR DE BASE DE DATOS',
'message' => 'Error: ' . $e->getMessage()
];
}
} else {
$this->errorMessage = [
'type' => 'ERROR DE VALIDACIÓN',
'message' => 'Error de validación de datos. Revise informe de carga para mayor información.'
];
}
}
}