HEX
Server: Apache/2.4.41 (Ubuntu)
System: Linux ip-172-31-42-149 5.15.0-1084-aws #91~20.04.1-Ubuntu SMP Fri May 2 07:00:04 UTC 2025 aarch64
User: ubuntu (1000)
PHP: 7.4.33
Disabled: pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals,pcntl_unshare,
Upload Files
File: /var/www/vhost/disk-apps/alq-cali.bikenow.co/app/Http/Controllers/Imports/StudentScheduleImport.php
<?php

namespace App\Http\Controllers\Imports;

use App\AcademyCategoriesSchedule;
use DB;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use App\AcademyUser;
use App\AcademyCategory;
use App\AcademySchedule;
use App\AcademyLocation;
use App\Http\Controllers\Controller;
use App\Module;
use Illuminate\Support\Facades\Auth;

class StudentScheduleImport implements ToCollection, WithHeadingRow
{
    public $request;
    public $cnt;
    public $messages = [];
    public $edit = [
        'creados'   => 0,
    ];

    /**
     * @param Collection $collection
     */

    public function rules(): array
    {
        return [
            '*.documento_alumno'  => 'required'
        ];
    }

    public function collection(Collection $rows)
    {
        DB::beginTransaction();
        $this->cnt = 0;
        $this->edit['creados'] = 0;
        $is_error = false;

        foreach ($rows as $key => $row) {
            $this->cnt++;

            if (!$row->filter()->isNotEmpty()) {
                $is_error = true;
                $this->addError(trans('messages.academy_users.tag65', ['position' => $this->cnt]), $this->cnt);
                break;
            }

            // Buscar estudiante por identificación
            $academyUser = AcademyUser::where('identification', $row["documento_alumno"])->first();
            if (!$academyUser) {
                $is_error = true;
                $this->addError('Alumno con documento ' . $row["documento_alumno"] . ' no está registrado', $this->cnt);
                continue;
            }

            // Buscar sede (ID o nombre)
            $sedeValue = trim($row['sede_alumno']);
            $academyLocation = is_numeric($sedeValue)
                ? AcademyLocation::where('id', $sedeValue)->where('active', true)->first()
                : AcademyLocation::where('name', $sedeValue)->where('active', true)->first();

            if (!$academyLocation) {
                $is_error = true;
                $this->addError('Sede "' . $row['sede_alumno'] . '" no encontrada o no se encuentra activa', $this->cnt);
                continue;
            }

            // Buscar categoría (ID o nombre)
            $categoriaValue = trim($row['categoria_alumno']);
            $academyCategories = is_numeric($categoriaValue)
                ? AcademyCategory::where('id', $categoriaValue)->where('active', true)->get()
                : AcademyCategory::where('name', $categoriaValue)->where('active', true)->get();

            if ($academyCategories->isEmpty()) {
                $is_error = true;
                $this->addError('Categoría "' . $row['categoria_alumno'] . '" no encontrada o no se encuentra activa', $this->cnt);
                continue;
            }

            // Filtrar solo las categorías que están asociadas a la sede
            $academyCategory = $academyCategories
                ->where('academy_location_id', $academyLocation->id)
                ->first();

            if (!$academyCategory) {
                $is_error = true;
                $this->addError('Categoría "' . $row['categoria_alumno'] . '" no encontrada en la sede "' . $row['sede_alumno'] . '"', $this->cnt);
                continue;
            }

            $removeSpaces = [\App\Http\Controllers\UtilController::class, 'removeSpaces'];

            // Buscar horario por ID o nombre
            $horarioValue = $removeSpaces($row['horario_alumno']);

            $academySchedules = is_numeric($horarioValue)
                ? AcademySchedule::where('id', $horarioValue)->get()
                : AcademySchedule::get()->filter(function ($schedule) use ($horarioValue, $removeSpaces) {
                    return $removeSpaces($schedule->name) == $removeSpaces($horarioValue);
                });

            if ($academySchedules->isEmpty()) {
                $is_error = true;
                $this->addError('Horario "' . $row['horario_alumno'] . '" no encontrado', $this->cnt);
                continue;
            }

            // Filtrar solo los horarios que tienen una relación con la categoría
            $validSchedule = AcademyCategoriesSchedule::whereIn('academy_schedule_id', $academySchedules->pluck('id'))
                ->where('academy_category_id', $academyCategory->id)
                ->pluck('academy_schedule_id')
                ->first();

            if (!$validSchedule) {
                $this->addError('El horario "' . $row['horario_alumno'] . '" no está relacionado con la categoría "' . $row['categoria_alumno'] . '" en la sede "' . $row['sede_alumno'] . '"', $this->cnt);
                continue;
            }

            // Actualizar AcademyUser con los nuevos valores
            $academyUser->update([
                'academy_category_id' => $academyCategory->id,
                'academy_location_id' => $academyLocation->id,
                'academy_schedule_id' => $validSchedule,
            ]);

            // Contar los registros creados/actualizados
            $this->edit['creados']++;
        }

        // Confirmar o revertir la transacción
        if ($is_error || sizeof($rows) <= 0) {
            DB::rollback();
        } else {
            DB::commit();
            $academyModule = Module::where("route", "academy")->first();
            $controller = new Controller;
            $controller->registerLog(Auth::user()->id, 'Importar horarios', json_encode($rows), "Update", $academyModule->id);
        }
    }

    private function addError($message, $line)
    {
        $this->messages[] = [
            'message' => $message . ', fila: ' . $line,
            'state' => false,
            'line' => $line
        ];
    }
}