HEX
Server: Apache
System: Linux WWW 6.1.0-40-amd64 #1 SMP PREEMPT_DYNAMIC Debian 6.1.153-1 (2025-09-20) x86_64
User: web11 (1011)
PHP: 8.2.29
Disabled: NONE
Upload Files
File: /var/www/dvpis2025/dvpis.kaunokolegija.lt/src/Controller/EgzamCommissionSppController.php
<?php

namespace App\Controller;

use App\Entity\Lecturer;
use App\Entity\StudiesProgramPlan;
use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
use PhpOffice\PhpSpreadsheet\IOFactory;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use App\Entity\AcademicGroupPlan;
use App\Entity\StudentCountProgramPlan;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use App\Service\FileUploader;
use App\Entity\FinalEgzam;
use App\Entity\FinalProject;
use App\Entity\LecturerPosition;
use App\Entity\FinanceSource;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Doctrine\ORM\EntityManagerInterface;
use App\Service\DbDataFilter;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\Validator\Validator\ValidatorInterface;

/**
* EgzamCommissionSppController controller.
*
* @Security("
   is_granted('ROLE_DEPARTMENT_HEAD')
   or is_granted('ROLE_DEPARTMENT_ADMINISTRATOR')
   or is_granted('ROLE_ACADEMIC_UNIT_PROHEAD')
   ")
*/
#[Route(path: 'egzamcomspp')]
class EgzamCommissionSppController extends AbstractController
{
    public function __construct(
        private readonly EntityManagerInterface $em,
        private readonly AuthorizationCheckerInterface $authorizationChecker,
        private readonly DbDataFilter $dbDataFilter,
        private readonly ValidatorInterface $validator,
    ) {


        if ($this->authorizationChecker->isGranted('ROLE_ACADEMIC_UNIT_PROHEAD')) {
            $this->dbDataFilter->enableAcademicUnitFilter();
            return;
        }

        if ($this->authorizationChecker->isGranted('ROLE_DEPARTMENT_HEAD')) {
            $this->dbDataFilter->enableDepartmentFilter();
            return;
        }

        if ($this->authorizationChecker->isGranted('ROLE_DEPARTMENT_ADMINISTRATOR')) {
            $this->dbDataFilter->enableDepartmentFilter();
            return;
        }

        throw new AccessDeniedHttpException("Jūsų naudotojas negali pasiekti šio turinio");
    }

    /**
    * Lists all egzamcommissionspp entities.
    * @Security("
       is_granted('ROLE_DEPARTMENT_ADMINISTRATOR')
       or is_granted('ROLE_DEPARTMENT_HEAD')
       or is_granted('ROLE_ACADEMIC_UNIT_PROHEAD')
        ")
    * @Method("GET")
    */
    #[Route(path: '/', name: 'egzamcommissionspp_index')]
    public function indexAction()
    {


        return $this->render(
            'egzamcommissionspp/index.html.twig',
            [
                'spps' => $this->em
                    ->getRepository(AcademicGroupPlan::class)
                    ->findEgzamTypeSpp(),
                'studentCount' => $this->em
                    ->getRepository(StudentCountProgramPlan::class)
                    ->getAllByProgramCourseType(),
            ]
        );
    }

    /**
     * imports studies programs from excel
     *
     * @Security("is_granted('ROLE_STUDY_DEPARTMENT')")
     *
     * @Method({"GET","POST"})
     */
    #[Route(path: '/import_view', name: 'egzamcommissionspp_import_view')]
    public function showImportEgzamCommAction(Request $request, FileUploader $fileUploader)
    {

        $file = $request->files->get('fileToUpload');
        $uploadedFilePath = '';
        $fileImportReturn = [];
        if (!empty($file)) {
            $uploadedFilePath = $fileUploader->getTargetDir() . DIRECTORY_SEPARATOR . $fileUploader->upload($file);
            $fileImportReturn = $this->importData($uploadedFilePath);
            unlink($uploadedFilePath);
        }

        return $this->render('egzamcommissionspp/import.html.twig', [
                    'uploadedFilePath' => $uploadedFilePath,
                    'importErrors' => $fileImportReturn,
        ]);
    }

    private function importData($filePath)
    {


        $lecturers = $this->em->getRepository(Lecturer::class)->getAllBySurnameName();
        $studiesProgramPlans = $this->em->getRepository(StudiesProgramPlan::class)->getAllByHash();

        $positions = $this->em->getRepository(LecturerPosition::class)->getAllByShortName();

        $financeSources = $this->em->getRepository(FinanceSource::class)->getAllByShortName();

        $objExcel = IOFactory::load($filePath);

        $worksheet = $objExcel->setActiveSheetIndex(0);

        $errors = [];
        foreach ($worksheet->getRowIterator() as $row) {
            $rowNumber = $row->getRowIndex();

            //insert values
            if ($rowNumber > 2) {
                $cellIterator = $row->getCellIterator();
                $cellIterator->setIterateOnlyExistingCells(false); // Loop all cells, even if it is not set

                $studiesProgramCode = trim($worksheet->getCell('A' . $row->getRowIndex())->getValue());
                $studiesForm = trim($worksheet->getCell('B' . $row->getRowIndex())->getValue());
                $studiesModuleType = trim($worksheet->getCell('C' . $row->getRowIndex())->getValue());
                $studiesModule = trim($worksheet->getCell('D' . $row->getRowIndex())->getValue());
                $semester = trim($worksheet->getCell('E' . $row->getRowIndex())->getValue());

                $sppHash = md5($studiesProgramCode . "_" . $studiesForm . "_" . $semester . "_" . $studiesModule);

                if (isset($studiesProgramPlans[$sppHash])) {
                    $studiesProgramPlan = $studiesProgramPlans[$sppHash];
                } else {
                    $errors[] = "Eilutė: " . $row->getRowIndex() . ": Studijų Programos Planas Nerastas! (" . $studiesProgramCode . " " . $studiesForm . " " . $semester . " " . $studiesModule . ")";
                    continue;
                }

                if ($studiesModuleType == 'SK-BD' || $studiesModuleType == 'SK-KE') {
                } else {
                    $errors[] = "Eilutė: " . $row->getRowIndex() . ": Studiju programa galima tik: 'SK-BD' arba 'SK-KE'!";
                    continue;
                }

                $finalProject = new FinalProject();
                $finalProject->setStudiesProgramPlan($studiesProgramPlan);

                $finalEgzam = new FinalEgzam();
                $finalEgzam->setStudiesProgramPlan($studiesProgramPlan);

                foreach ($cellIterator as $cell) {
                    if (!is_null($cell)) {
                        $column = $cell->getColumn();

                        switch ($cell->getColumn()) {
                            case 'F':
                                $excelLecturer = trim($cell->getCalculatedValue());
                                if (empty($lecturers[$excelLecturer])) {
                                    $errors[] = $cell->getColumn() . ":" . $row->getRowIndex() . ": Dėstytojas nerastas! (" . $excelLecturer . ")";
                                } else {
                                    $finalEgzam->setLecturer($lecturers[$excelLecturer]);
                                    $finalProject->setLecturer($lecturers[$excelLecturer]);
                                }

                                break;
                            case 'G':
                                $excelLecturerPosition = trim($cell->getCalculatedValue());
                                if (empty($excelLecturerPosition)) {
                                    $finalProject->setLecturerPosition($lecturers[$excelLecturer]->getPosition());
                                    $finalEgzam->setLecturerPosition($lecturers[$excelLecturer]->getPosition());
                                } elseif (empty($positions[$excelLecturerPosition])) {
                                    $errors[] = $cell->getColumn() . ":" . $row->getRowIndex() . ": Dėstytojo pareigybė nerasta! (" . $excelLecturerPosition . ")";
                                } else {
                                    $finalProject->setLecturerPosition($positions[$excelLecturerPosition]);
                                    $finalEgzam->setLecturerPosition($positions[$excelLecturerPosition]);
                                }
                                break;
                            case 'H':
                                $countWorks = trim($cell->getCalculatedValue());
                                $finalProject->setCountWorks(empty($countWorks) ? 0 : $countWorks);
                                break;
                            case 'I':
                                $excelHours = trim($cell->getCalculatedValue());
                                $finalProject->setHours(empty($excelHours) ? 0 : $excelHours);
                                break;
                            case 'J':
                                $excelHours = trim($cell->getCalculatedValue());
                                $finalProject->setDepartmentCommision(empty($excelHours) ? 0 : $excelHours);
                                break;
                            case 'k':
                                $excelHours = trim($cell->getCalculatedValue());
                                $finalEgzam->setPrepareTasks(empty($excelHours) ? 0 : $excelHours);
                                break;
                            case 'L':
                                $excelFinalCommisionHead = trim($cell->getCalculatedValue());
                                $finalProject->setFinalCommisionHead(empty($excelFinalCommisionHead) ? 0 : $excelFinalCommisionHead);
                                $finalEgzam->setFinalCommisionHead(empty($excelFinalCommisionHead) ? 0 : $excelFinalCommisionHead);
                                break;
                            case 'M':
                                $excelFinalCommision = trim($cell->getCalculatedValue());
                                $finalProject->setFinalCommision(empty($excelFinalCommision) ? 0 : $excelFinalCommision);
                                $finalEgzam->setFinalCommision(empty($excelFinalCommision) ? 0 : $excelFinalCommision);
                                break;
                            case 'N':
                                $isMain = trim($cell->getCalculatedValue());
                                $isNotFullTime = false;
                                if ($isMain == "Y") {
                                    $isNotFullTime = true;
                                }
                                $finalProject->setIsNotFullTime($isNotFullTime);
                                $finalEgzam->setIsNotFullTime($isNotFullTime);
                                break;
                            case 'O':
                                $excelFinanceSource = trim($cell->getCalculatedValue());

                                if (!empty($excelFinanceSource) && !empty($financeSources[$excelFinanceSource])) {
                                    $finalProject->setLecturerFinance($financeSources[$excelFinanceSource]);
                                    $finalEgzam->setLecturerFinance($financeSources[$excelFinanceSource]);
                                }

                                break;
                            default:
                                break;
                        }
                    }
                }

                if (empty($errors)) {
                    if ($studiesModuleType == 'SK-BD') {
                        //finalproject
                        $valid = $this->validator->validate($finalProject);
                        if (empty($valid[0])) {
                            $this->em->persist($finalProject);
                        } else {
                            $errors[] = $column . $rowNumber . ": " . $valid[0]->getMessage();
                        }
                    } else {
                        $valid = $this->validator->validate($finalEgzam);
                        if (empty($valid[0])) {
                            $this->em->persist($finalEgzam);
                        } else {
                            $errors[] = $column . $rowNumber . ": " . $valid[0]->getMessage();
                        }
                    }
                }
            }
        }

        if (empty($errors)) {
            try {
                $this->em->flush();
            } catch (UniqueConstraintViolationException $ex) {
//                $this->addFlash("warning", "Faile yra vienodų naujų įrašų. Prašome patikrinti duomenis! Detaliau: ".$ex->getPrevious()->getMessage());
                $errors[] = "Faile yra vienodų naujų įrašų. Prašome patikrinti duomenis! Detaliau: " . $ex->getPrevious()->getMessage();
            }
        }

        return $errors;
    }
}