File: /var/www/gestion-formularios.bdfschool/app/Imports/UploadParentImport.php
<?php
namespace App\Imports;
use App\Models\Parents;
use App\Models\Students;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
class UploadParentImport implements ToCollection, WithHeadingRow
{
protected $expectedHeaders = [
'rut',
'primer_nombre',
'segundo_nombre',
'primer_apellido',
'segundo_apellido',
'sexo',
'email',
'rut_alumno',
'tipo_apoderado'
];
public $errorMessage;
public $successMessage;
public function __construct() {}
public function collection(Collection $rows)
{
if ($rows->isEmpty()) {
$this->errorMessage = 'El archivo está vacío.';
return;
}
$headers = $rows->first()->keys()->toArray();
foreach ($this->expectedHeaders as $header) {
if (!in_array($header, $headers)) {
$this->errorMessage = 'Falta el encabezado requerido: ' . $header;
return;
}
}
$students = Students::all()->keyBy(function ($student) {
return str_replace('.', '', strtoupper(formateaRut($student->rut)));
});
$success = 0;
$errors = [];
foreach ($rows as $index => $row) {
$fila = $index + 2;
Log::info("fila $fila".print_r($row, true));
try {
$rut = str_replace('.', '', strtoupper(formateaRut($row['rut'] ?? '')));
if (empty($rut) || !validateRut($rut)) {
$errors[] = "Fila $fila: RUT del apoderado inválido.".$row['rut'];
continue;
}
$rutStudent = str_replace('.', '', strtoupper(formateaRut($row['rut_alumno'] ?? '')));
if (empty($rutStudent) || !isset($students[$rutStudent])) {
$errors[] = "Fila $fila: RUT de alumno $rutStudent no encontrado.";
continue;
}
Log::info(print_r([
'first_name' => strCapital($row['primer_nombre']),
'second_name' => strCapital($row['segundo_nombre']),
'last_name' => strCapital($row['primer_apellido']),
'second_last_name' => strCapital($row['segundo_apellido']),
'email' => strLower($row['email']),
'gender' => strtoupper($row['sexo']) === 'F' ? 'F' : 'M',
'financial_parent' => $row['tipo_apoderado'] == "FINANCIERO" ? 1 : 0,
'academic_parent' => $row['tipo_apoderado'] != "FINANCIERO" ? 1 : 0,
'status' => true,
'deleted' => false,
'user_created' => auth()->id(),
'created_at' => now(),
'updated_at' => now(),
'annual_load' => 1,
'annual_load_at' => now(),
], TRUE));
$parent = Parents::updateOrCreate(
['rut' => $rut],
[
'first_name' => strCapital($row['primer_nombre']),
'second_name' => strCapital($row['segundo_nombre']),
'last_name' => strCapital($row['primer_apellido']),
'second_last_name' => strCapital($row['segundo_apellido']),
'email' => strLower($row['email']),
'gender' => strtoupper($row['sexo']) === 'F' ? 'F' : 'M',
'financial_parent' => $row['tipo_apoderado'] == "FINANCIERO" ? 1 : 0,
'academic_parent' => $row['tipo_apoderado'] != "FINANCIERO" ? 1 : 0,
'status' => true,
'deleted' => false,
'user_created' => auth()->id(),
'created_at' => now(),
'updated_at' => now(),
'annual_load' => 1,
'annual_load_at' => now(),
]
);
$student_data = $students[$rutStudent] ?? null;
if ($student_data) {
if ($row['tipo_apoderado'] == "FINANCIERO") {
$student_data->parent_id = $parent->id;
} else {
$student_data->parent_academic_id = $parent->id;
}
$student_data->save();
}
$success++;
} catch (\Exception $e) {
$errors[] = "Fila $fila: Error al procesar. " . $e->getMessage();
Log::error("Fila $fila: " . $e->getMessage());
}
}
if (!empty($errors)) {
$this->errorMessage = implode('<br>', $errors);
}
if ($success > 0) {
$this->successMessage = "Importación realizada correctamente. Registros exitosos: $success.";
} elseif (empty($errors)) {
$this->errorMessage = "No se encontraron datos válidos para importar.";
}
}
}