ReportsCreator.php 99.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
<?php
/**
 * @file
 * Contains \Drupal\query_example\Controller\QueryExampleController.
 */

namespace Drupal\epal\Controller;

use Drupal\Core\Entity\Query\QueryFactory;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Drupal\Core\Controller\ControllerBase;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Drupal\Core\Database\Database;
use Drupal\Core\Database\Connection;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;

//use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\Core\TypedData\Plugin\DataType\TimeStamp;

use Drupal\Core\Language\LanguageManagerInterface;

27 28 29
class ReportsCreator extends ControllerBase
{

30 31 32 33 34
    const ERR_DB = -1;
    const NO_CLASS_LIM_DOWN = -2;
    const SMALL_CLS = 1;
    const NON_SMALL_CLS = 2;

35 36 37 38 39 40 41 42 43 44 45
    protected $entity_query;
    protected $entityTypeManager;
    protected $logger;
    protected $connection;

    public function __construct(
        EntityTypeManagerInterface $entityTypeManager,
        QueryFactory $entity_query,
        Connection $connection,
        LoggerChannelFactoryInterface $loggerChannel
    ) {
46

47 48 49 50 51
            $this->entityTypeManager = $entityTypeManager;
            $this->entity_query = $entity_query;
            $connection = Database::getConnection();
            $this->connection = $connection;
            $this->logger = $loggerChannel->get('epal');
52 53
    }

54
    public static function create(ContainerInterface $container)
55 56
    {
        return new static(
57 58 59 60 61
            $container->get('entity_type.manager'),
            $container->get('entity.query'),
            $container->get('database'),
            $container->get('logger.factory')
        );
62 63
    }

64 65
    public function makeReportUsers(Request $request)
    {
66

67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
        try {
            if (!$request->isMethod('GET')) {
                return $this->respondWithStatus([
                    "message" => t("Method Not Allowed")
                ], Response::HTTP_METHOD_NOT_ALLOWED);
            }

            //user validation
            $authToken = $request->headers->get('PHP_AUTH_USER');
            $users = $this->entityTypeManager->getStorage('user')->loadByProperties(array('name' => $authToken));
            $user = reset($users);
            if (!$user) {
                return $this->respondWithStatus([
                    'message' => t("User not found"),
                ], Response::HTTP_FORBIDDEN);
            }

            //user role validation
            $roles = $user->getRoles();
            $validRole = false;
            foreach ($roles as $role) {
                if ($role === "ministry") {
                    $validRole = true;
                    break;
                }
            }
            if (!$validRole) {
                return $this->respondWithStatus([
                    'message' => t("User Invalid Role"),
                ], Response::HTTP_FORBIDDEN);
            }

            $list = array();

            //υπολογισμός αριθμού αιτήσεων
            $sCon = $this->connection
                ->select('epal_student', 'eStudent')
104 105
                ->fields('eStudent', array('id'))
                ->condition('eStudent.delapp', 0, '=');
106 107 108 109 110 111 112 113 114
            $numApplications = $sCon->countQuery()->execute()->fetchField();
            array_push($list, (object) array('name' => "Αριθμός Αιτήσεων (συνολικά)", 'numStudents' => $numApplications));

            //υπολογισμός αριθμού αιτήσεων ανά τάξη
            $classes = [1 => 'Α', 2 => 'Β', 3 => 'Γ', 4 => 'Δ'];
            foreach ($classes as $i => $label) {
                $sCon = $this->connection
                    ->select('epal_student', 'eStudent')
                    ->fields('eStudent', array('id'))
115 116
                    ->condition('eStudent.currentclass', strval($i), '=')
                    ->condition('eStudent.delapp', 0, '=');
117 118 119
                $numApplications = $sCon->countQuery()->execute()->fetchField();
                array_push($list, (object) array('name' => "Αριθμός Αιτήσεων για {$label} Τάξη", 'numStudents' => $numApplications));
            }
120

121 122 123 124
            //υπολογισμός αριθμού αιτήσεων για δεύτερη περίοδο
            $sCon = $this->connection
                ->select('epal_student', 'eStudent')
                ->fields('eStudent', array('id'))
125 126
                ->condition('eStudent.second_period', 1, '=')
                ->condition('eStudent.delapp', 0, '=');
127 128 129
            $numApplications = $sCon->countQuery()->execute()->fetchField();
            array_push($list, (object) array('name' => "Αριθμός Αιτήσεων B' περιόδου", 'numStudents' => $numApplications));

Ασπασία Κατσή's avatar
Ασπασία Κατσή committed
130 131 132 133 134 135 136 137 138

            //υπολογισμός αριθμού αιτήσεων για τρίτη περίοδο
            $datelimit = '31-8-2017';
            $datelimitInt = strtotime($datelimit);

            $sCon = $this->connection
                ->select('epal_student', 'eStudent')
                ->fields('eStudent', array('id'))
                ->condition('eStudent.second_period', 1, '=')
139 140
                ->condition('created', $datelimitInt, '>=')
                ->condition('eStudent.delapp', 0, '=');
Ασπασία Κατσή's avatar
Ασπασία Κατσή committed
141 142 143 144
            $numApplications = $sCon->countQuery()->execute()->fetchField();
            array_push($list, (object) array('name' => "Αριθμός Αιτήσεων περιόδου Σεπτεμβρίου", 'numStudents' => $numApplications));


145 146
            //υπολογισμός αριθμού χρηστών
            $sCon = $this->connection
147
                ->select('applicant_users', 'eUser')
148 149 150 151 152 153 154 155 156 157 158 159 160 161
                ->fields('eUser', array('id'));
            $numUsers = $sCon->countQuery()->execute()->fetchField();
            array_push($list, (object) array('name' => "Αριθμός Εγγεγραμένων Χρηστών με ρόλο Αιτούντα", 'numStudents' => $numUsers));

            return $this->respondWithStatus($list, Response::HTTP_OK);
        } //end try

        catch (\Exception $e) {
            $this->logger->warning($e->getMessage());
            return $this->respondWithStatus([
                "message" => t("An unexpected problem occured during report")
            ], Response::HTTP_INTERNAL_SERVER_ERROR);
        }
    }
162 163 164



165 166
    public function makeGeneralReport(Request $request)
    {
167

168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
        try {
            if (!$request->isMethod('GET')) {
                return $this->respondWithStatus([
                    "message" => t("Method Not Allowed")
                ], Response::HTTP_METHOD_NOT_ALLOWED);
            }

            //user validation
            $authToken = $request->headers->get('PHP_AUTH_USER');
            $users = $this->entityTypeManager->getStorage('user')->loadByProperties(array('name' => $authToken));
            $user = reset($users);
            if (!$user) {
                return $this->respondWithStatus([
                    'message' => t("User not found"),
                ], Response::HTTP_FORBIDDEN);
            }

            //user role validation
            $roles = $user->getRoles();
            $validRole = false;
            foreach ($roles as $role) {
                if ($role === "ministry") {
                    $validRole = true;
                    break;
                }
            }
            if (!$validRole) {
                return $this->respondWithStatus([
                    'message' => t("User Invalid Role"),
                ], Response::HTTP_FORBIDDEN);
            }

            //υπολογισμός αριθμού δηλώσεων
            $sCon = $this->connection
                ->select('epal_student', 'eStudent')
203 204
                ->fields('eStudent', array('id'))
                ->condition('eStudent.delapp', 0, '=');
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
            $numTotal = $sCon->countQuery()->execute()->fetchField();

            //υπολογισμός αριθμού δηλώσεων που ικανοποιήθηκαν στην i προτίμηση
            $numData = array();
            for ($i=0; $i < 3; $i++) {
                $sCon = $this->connection
                    ->select('epal_student_class', 'eStudent')
                    ->fields('eStudent', array('id', 'distribution_id'))
                    ->condition('eStudent.distribution_id', $i+1, '=')
                    ->condition('eStudent.finalized', 1, '=');
                array_push($numData, $sCon->countQuery()->execute()->fetchField());
            }

            // υπολογισμός αριθμού δηλώσεων που ΔΕΝ ικανοποιήθηκαν
            /*
220 221 222 223 224 225 226 227 228 229 230 231 232
			$sCon = $this->connection
				->select('epal_student_class', 'eStudent')
				->fields('eStudent', array('student_id'));
			$epalStudents = $sCon->execute()->fetchAll(\PDO::FETCH_OBJ);
			$studentIds = array();
			foreach ($epalStudents as $epalStudent)
				array_push($studentIds, $epalStudent->student_id);
			$sCon = $this->connection
				->select('epal_student', 'eStudent')
				->fields('eStudent', array('id'))
				->condition('eStudent.id', $studentIds, 'NOT IN');
			$numNoAllocated = $sCon->countQuery()->execute()->fetchField();
			*/
233 234
            $sCon = $this->connection->select('epal_student', 'epalStudent')
                ->condition('epalStudent.delapp', 0, '=');
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
            $sCon->leftJoin('epal_student_class', 'eStudent', 'eStudent.student_id = epalStudent.id');
            $sCon->fields('eStudent', array('student_id'))
                ->fields('epalStudent', array('id'))
                ->isNull('eStudent.student_id');
            $numNoAllocated = $sCon->countQuery()->execute()->fetchField();

            //υπολογισμός αριθμού δηλώσεων που τοποθετήθηκαν προσωρινά σε ολιγομελή τμήματα
            $numInSmallClasses = 0;
            $sCon = $this->connection
                ->select('epal_student_class', 'eStudent')
                ->fields('eStudent', array('id'))
                ->condition('eStudent.finalized', 0, '=');
            $numInSmallClasses = $sCon->countQuery()->execute()->fetchField();

            $list = array(
                array('name' => "Αριθμός Δηλώσεων Προτίμησης", 'numStudents' => $numTotal),
                array('name' => "Αριθμός μαθητών που τοποθετήθηκαν στην πρώτη τους προτίμηση", 'numStudents' => $numData[0]),
                array('name' => "Αριθμός μαθητών που τοποθετήθηκαν στην δεύτερή τους προτίμηση", 'numStudents' => $numData[1]),
                array('name' => "Αριθμός μαθητών που τοποθετήθηκαν στην τρίτη τους προτίμηση", 'numStudents' => $numData[2]),
                array('name' => "Αριθμός μαθητών που δεν τοποθετήθηκαν σε καμμία τους προτίμηση", 'numStudents' => $numNoAllocated),
                array('name' => "Αριθμός μαθητών που τοποθετήθηκαν προσωρινά σε ολιγομελή τμήματα", 'numStudents' => $numInSmallClasses)
            );

            return $this->respondWithStatus($list, Response::HTTP_OK);
        } //end try

        catch (\Exception $e) {
            $this->logger->warning($e->getMessage());
            return $this->respondWithStatus([
                "message" => t("An unexpected problem occured during report")
            ], Response::HTTP_INTERNAL_SERVER_ERROR);
        }
    }
268 269


270 271
    public function makeReportCompleteness(Request $request, $regionId, $adminId, $schId)
    {
272

273 274 275 276 277 278
        try {
            if (!$request->isMethod('GET')) {
                return $this->respondWithStatus([
                    "message" => t("Method Not Allowed")
				], Response::HTTP_METHOD_NOT_ALLOWED);
            }
279

280 281 282 283 284
            //user validation
            $authToken = $request->headers->get('PHP_AUTH_USER');
            $users = $this->entityTypeManager->getStorage('user')->loadByProperties(array('name' => $authToken));
            $user = reset($users);
            if (!$user) {
285
				return $this->respondWithStatus([
286 287 288 289 290 291 292 293 294
					'message' => t("User not found"),
				], Response::HTTP_FORBIDDEN);
            }

            //user role validation
            $roles = $user->getRoles();
            $validRole = false;
            foreach ($roles as $role) {
                if ($role === "ministry" || $role === "regioneduadmin" || $role === "eduadmin") {
295
                    $validRole = $role;
296 297 298
                    break;
                }
            }
299
            if ($validRole === false) {
300 301 302 303 304
				return $this->respondWithStatus([
					'message' => t("User Invalid Role"),
				], Response::HTTP_FORBIDDEN);
            }

305 306 307 308 309 310
            if (!$this->canReportOn($user, $role, $regionId, $adminId, $schId)) {
				return $this->respondWithStatus([
					'message' => t('User access to area forbidden'),
				], Response::HTTP_FORBIDDEN);
            }

311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
            $list = array();

            //βρες ανώτατο επιτρεπόμενο όριο μαθητών
            $limitUp = $this->retrieveUpLimit();

            //βρες όλα τα σχολεία που πληρούν τα κριτήρια / φίλτρα
            $sCon = $this->connection->select('eepal_school_field_data', 'eSchool');
			$sCon->join('eepal_region_field_data', 'eRegion', 'eRegion.id = eSchool.region_edu_admin_id');
			$sCon->join('eepal_admin_area_field_data', 'eAdmin', 'eAdmin.id = eSchool.edu_admin_id');
			$sCon->leftJoin('eepal_sectors_in_epal_field_data', 'sectors', 'sectors.epal_id = eSchool.id');
			$sCon->fields('eSchool', array('id', 'name', 'capacity_class_a', 'region_edu_admin_id', 'edu_admin_id', 'operation_shift'))
				->fields('eRegion', ['name'])
				->fields('eAdmin', ['name'])
                ->groupBy('id')
                ->groupBy('name')
                ->groupBy('capacity_class_a')
                ->groupBy('region_edu_admin_id')
                ->groupBy('edu_admin_id')
                ->groupBy('operation_shift')
                ->groupBy('eRegion_name')
                ->groupBy('eAdmin_name');
            $sCon->addExpression('sum(sectors.capacity_class_sector)', 'capacity_class_b');
            if ($regionId != 0) {
				$sCon->condition('eSchool.region_edu_admin_id', $regionId, '=');
            }
            if ($adminId != 0) {
				$sCon->condition('eSchool.edu_admin_id', $adminId, '=');
            }
            if ($schId != 0) {
                $sCon->condition('eSchool.id', $schId, '=');
            }
            $epalSchools = $sCon->execute()->fetchAll(\PDO::FETCH_OBJ);
            foreach ($epalSchools as $epalSchool) {
                //εύρεση ονόματος ΠΔΕ που ανήκει το σχολείο
                $regionColumn = $epalSchool->eRegion_name;
                //εύρεση ονόματος ΔΙΔΕ που ανήκει το σχολείο
                $adminColumn = $epalSchool->eAdmin_name;

                //βρες μέγιστη χωρητικότητα για κάθε τάξη
                $capacity = array();
                //χωρητικότητα για Α' τάξη
                array_push($capacity, $epalSchool->capacity_class_a * $limitUp );

                //χωρητικότητα για Β' τάξη
                array_push($capacity, $epalSchool->capacity_class_b * $limitUp);

                //χωρητικότητα για Γ' τάξη
                $sCon = $this->connection
					->select('eepal_specialties_in_epal_field_data', 'eSchool')
                    ->fields('eSchool', array('id',  'capacity_class_specialty'))
                    ->condition('eSchool.epal_id', $epalSchool->id, '=');
                $specialtiesInEpals = $sCon->execute()->fetchAll(\PDO::FETCH_OBJ);
                $numClassSpecialties = 0;
                foreach ($specialtiesInEpals as $specialtiesInEpal) {
                    $numClassSpecialties += $specialtiesInEpal->capacity_class_specialty;
                }
                array_push($capacity, $numClassSpecialties * $limitUp);

                //χωρητικότητα για Δ' τάξη
                if ($epalSchool->operation_shift === "ΕΣΠΕΡΙΝΟ") {
                    $sCon = $this->connection
                        ->select('eepal_specialties_in_epal_field_data', 'eSchool')
                        ->fields('eSchool', array('id',  'capacity_class_specialty_d'))
                        ->condition('eSchool.epal_id', $epalSchool->id, '=');
                    $specialtiesInEpals = $sCon->execute()->fetchAll(\PDO::FETCH_OBJ);
                    $numClassSpecialtiesNight = 0;
                    foreach ($specialtiesInEpals as $specialtiesInEpal) {
                        $numClassSpecialtiesNight += $specialtiesInEpal->capacity_class_specialty_d;
                    }
					array_push($capacity, $numClassSpecialtiesNight * $limitUp);
                } else {
                    array_push($capacity, -1);
                }

                //χωρητικότητα για όλο το σχολείο
386 387 388
                $capacityTotal = array_reduce($capacity, function ($sum, $v) {
                        return $sum += ($v > 0) ? intval($v) : 0;
                    }, 0);
389 390 391 392 393 394 395 396 397 398

                //βρες αριθμό μαθητών γισ κάθε τάξη
                $num = array();
                $perc = array();
                $stat_complete = true;
                for ($classId = 1; $classId <= 4; $classId++) {
                    $sCon = $this->connection
						->select('epal_student_class', 'eStudent')
                        ->fields('eStudent', array('id', 'epal_id', 'currentclass'))
                        ->condition('eStudent.epal_id', $epalSchool->id, '=')
399
                        ->condition('eStudent.currentclass', $classId, '=');
400 401 402 403
                    array_push( $num, $sCon->countQuery()->execute()->fetchField());
                    //βρες ποσοστά συμπλήρωσης
                    if (isset($capacity[$classId-1]) && $capacity[$classId-1] > 0) {
                        $perc_str = number_format($num[$classId-1] / $capacity[$classId-1] * 100, 2);
404 405
                    } elseif (isset($capacity[$classId-1]) && $capacity[$classId-1] == -1) {
                        $perc_str = '-';
406 407 408 409
                    } else {
                        $perc_str = '-';
                        $stat_complete = false;
                    }
410
                    array_push($perc, $perc_str);
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
                }

                if ($stat_complete === true && $capacityTotal > 0) {
                    $percTotal = number_format(array_sum($num) / $capacityTotal * 100, 2);
                } else {
                    $percTotal = '-';
                }

                //αποστολή αποτελεσμάτων / στατιστικών
				array_push($list, (object) array(
					'name' => $epalSchool->name,
					'region' => $regionColumn,
					'admin' => $adminColumn,
					'percTotal' => $percTotal,
					'percA' => $perc[0],
					'percB' => $perc[1],
					'percC' => $perc[2],
					'percD' => $perc[3]
				));
            }
431

432 433
			return $this->respondWithStatus($list, Response::HTTP_OK);
        } //end try
434

435 436 437
        catch (\Exception $e) {
            $this->logger->warning($e->getMessage());
            return $this->respondWithStatus([
438
                "message" => t("An unexpected problem occured during report")
439 440 441
			], Response::HTTP_INTERNAL_SERVER_ERROR);
        }
    }
442

443

Kostas G's avatar
Kostas G committed
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499

    private function isSmallClass($schoolId, $numStud, $classId, $sectorOrcourseId, $regionId)
    {

        $limitDown = $this->retrieveLimitDown($classId, $regionId);

        if ($limitDown === self::NO_CLASS_LIM_DOWN) {
            return self::NO_CLASS_LIM_DOWN;
        } elseif ($limitDown === self::ERR_DB) {
            return self::ERR_DB;
        }

        $numStudents = (int) $numStud;
        if (($numStudents < $limitDown) /*&& ($numStudents > 0)*/) {
            return self::SMALL_CLS;
        } else {
            return self::NON_SMALL_CLS;
        }
    }


    /**
     * Fetch epal_class_limits data in memory; will save time.
     *
     */
    private function retrieveLimitDown($classId, $regionId)
    {
        static $data = [];

        if (count($data) === 0) {
            try {
                $sCon = $this->connection
                    ->select('epal_class_limits', 'eClassLimit')
                    ->fields('eClassLimit', ['name', 'category', 'limit_down']);
                $classLimits = $sCon->execute()->fetchAll(\PDO::FETCH_OBJ);
                if ($classLimits !== FALSE) {
                    foreach ($classLimits as $limit) {
                        $data["$limit->name"]["$limit->category"] = $limit->limit_down;
                    }
                } else {
                    return self::NO_CLASS_LIM_DOWN;
                }
            } catch (\Exception $e) {
                $this->logger->warning($e->getMessage());
                return self::ERR_DB;
            }
        }

        if (isset($data["$classId"]["$regionId"])) {
            return $data["$classId"]["$regionId"];
        } else {
            return self::NO_CLASS_LIM_DOWN;
        }
    }

    public function retrieveUserRegistryNo(Request $request)
500
    {
Kostas G's avatar
Kostas G committed
501

502 503
        try {
            if (!$request->isMethod('GET')) {
Kostas G's avatar
Kostas G committed
504
                 return $this->respondWithStatus([
505 506 507
					"message" => t("Method Not Allowed")
				], Response::HTTP_METHOD_NOT_ALLOWED);
            }
508

509 510 511 512 513 514 515 516 517 518 519 520 521 522
            //user validation
            $authToken = $request->headers->get('PHP_AUTH_USER');
            $users = $this->entityTypeManager->getStorage('user')->loadByProperties(array('name' => $authToken));
            $user = reset($users);
            if (!$user) {
				return $this->respondWithStatus([
					'message' => t("User not found"),
				], Response::HTTP_FORBIDDEN);
            }

            //user role validation
            $roles = $user->getRoles();
            $validRole = false;
            foreach ($roles as $role) {
Kostas G's avatar
Kostas G committed
523 524
                if ($role === "regioneduadmin" || $role === "eduadmin") {
                    $validRole = true;
525 526 527
                    break;
                }
            }
Kostas G's avatar
Kostas G committed
528
            if (!$validRole) {
529 530 531 532 533
				return $this->respondWithStatus([
					'message' => t("User Invalid Role"),
				], Response::HTTP_FORBIDDEN);
            }

Kostas G's avatar
Kostas G committed
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561
            return $this->respondWithStatus([
				'message' => t("retrieve ID successful"),
				'id' => $user->init->value,
            ], Response::HTTP_OK);

        } catch (\Exception $e) {
            $this->logger->warning($e->getMessage());
            return $this->respondWithStatus([
				"message" => t("An unexpected problem occured in retrievePDEId Method")
			], Response::HTTP_INTERNAL_SERVER_ERROR);
        }
    }

    public function makeReportNoCapacity(Request $request, $capacityEnabled)
    {

        try {
            if (!$request->isMethod('GET')) {
                 return $this->respondWithStatus([
					"message" => t("Method Not Allowed")
				], Response::HTTP_METHOD_NOT_ALLOWED);
            }

            //user validation
            $authToken = $request->headers->get('PHP_AUTH_USER');
            $users = $this->entityTypeManager->getStorage('user')->loadByProperties(array('name' => $authToken));
            $user = reset($users);
            if (!$user) {
562
				return $this->respondWithStatus([
Kostas G's avatar
Kostas G committed
563
					'message' => t("User not found"),
564 565 566
				], Response::HTTP_FORBIDDEN);
            }

Kostas G's avatar
Kostas G committed
567 568 569 570 571 572 573 574 575 576 577 578 579 580
            //user role validation
            $roles = $user->getRoles();
            $validRole = false;
            foreach ($roles as $role) {
                if ($role === "ministry") {
                    $validRole = true;
                    break;
                }
            }
            if (!$validRole) {
				return $this->respondWithStatus([
					'message' => t("User Invalid Role"),
				], Response::HTTP_FORBIDDEN);
            }
581 582 583

            $list = array();

Kostas G's avatar
Kostas G committed
584 585 586 587 588 589 590 591
            //βρες όλα τα σχολεία
            $sCon = $this->connection
				->select('eepal_school_field_data', 'eSchool')
                ->fields('eSchool', array('id', 'name', 'capacity_class_a', 'region_edu_admin_id', 'edu_admin_id','operation_shift'));

            //if ($capacityEnabled === "0")
            //	$sCon->condition('eSchool.capacity_class_a', 0, '=');

592 593
            $epalSchools = $sCon->execute()->fetchAll(\PDO::FETCH_OBJ);

Kostas G's avatar
Kostas G committed
594
            foreach ($epalSchools as $epalSchool) {       //για κάθε σχολείο
595 596 597 598 599 600 601

                $schoolNameColumn = array();
                $regionColumn = array();
                $adminColumn = array();
                $schoolSectionColumn = array();
                $capacityColumn = array();

Kostas G's avatar
Kostas G committed
602 603 604 605 606 607 608
                //εύρεση ονόματος ΠΔΕ που ανήκει το σχολείο
                $sCon = $this->connection
					->select('eepal_region_field_data', 'eRegion')
                    ->fields('eRegion', array('id','name'))
                    ->condition('eRegion.id', $epalSchool->region_edu_admin_id, '=');
                $epalRegions = $sCon->execute()->fetchAll(\PDO::FETCH_OBJ);
                $epalRegion = reset($epalRegions);
609

Kostas G's avatar
Kostas G committed
610 611 612 613 614 615 616
                //εύρεση ονόματος ΔΙΔΕ που ανήκει το σχολείο
                $sCon = $this->connection
					->select('eepal_admin_area_field_data', 'eAdmin')
                    ->fields('eAdmin', array('id','name'))
                    ->condition('eAdmin.id', $epalSchool->edu_admin_id, '=');
                $epalAdmins = $sCon->execute()->fetchAll(\PDO::FETCH_OBJ);
                $epalAdmin = reset($epalAdmins);
617

Kostas G's avatar
Kostas G committed
618 619 620 621 622 623 624 625 626
                //εύρεση αριθμού τμημάτων (χωρητικότητα) για κάθε τμήμα της Α' τάξης
                //$epalSchool->capacity_class_a === "0" ||
                if (($capacityEnabled === '0' && ( !isset($epalSchool->capacity_class_a)) )  ||  ($capacityEnabled === "1")) {
					array_push($regionColumn, $epalRegion->name);
					array_push($adminColumn, $epalAdmin->name);
					array_push($schoolNameColumn, $epalSchool->name);
					array_push($schoolSectionColumn, 'Α\' τάξη');
					array_push($capacityColumn, $epalSchool->capacity_class_a);
                }
627

Kostas G's avatar
Kostas G committed
628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655
                //εύρεση αριθμού τμημάτων (χωρητικότητα) για κάθε τομέα της Β' τάξης
                //ΠΡΟΣΟΧΗ: χειρισμ΄ός τιμών: 0 (ΟΧΙ??) και null

                $sCon = $this->connection
					->select('eepal_sectors_in_epal_field_data', 'eSchool')
                    ->fields('eSchool', array('sector_id','capacity_class_sector'))
                    ->condition('eSchool.epal_id', $epalSchool->id, '=');
                //$db_or = db_or();
                //$db_or->condition('eSchool.capacity_class_sector', 0, '=');
                //$db_or->condition('eSchool.capacity_class_sector', null, 'is');
                //$sCon->condition($db_or) ;
                if ($capacityEnabled === "0") {
                    $sCon->condition( db_or()
						//->condition('eSchool.capacity_class_sector', 0, '=')
						->condition('eSchool.capacity_class_sector', null, 'is')  ) ;
                }
                $sectorsInEpals = $sCon->execute()->fetchAll(\PDO::FETCH_OBJ);

                foreach ($sectorsInEpals as $sectorsInEpal) {
                    $sCon = $this->connection
						->select('eepal_sectors_field_data', 'eSectors')
                        ->fields('eSectors', array('name'))
                        ->condition('eSectors.id', $sectorsInEpal->sector_id, '=');

                    $sectorsNamesInEpals = $sCon->execute()->fetchAll(\PDO::FETCH_OBJ);
                    foreach ($sectorsNamesInEpals as $sectorsNamesInEpal) {
                        array_push($regionColumn, $epalRegion->name);
                        array_push($adminColumn, $epalAdmin->name);
656
                        array_push($schoolNameColumn, $epalSchool->name);
Kostas G's avatar
Kostas G committed
657 658 659 660
                        array_push($schoolSectionColumn, 'Β\' τάξη / ' . $sectorsNamesInEpal->name );
                        array_push($capacityColumn, $sectorsInEpal->capacity_class_sector);
                    }   //end foreach sectorsNamesInEpals
                }   //end foreach sectorsInEpal
661

Kostas G's avatar
Kostas G committed
662 663 664 665 666
                //εύρεση αριθμού τμημάτων (χωρητικότητα) για κάθε ειδικότητα της Γ' τάξης
                $sCon = $this->connection
					->select('eepal_specialties_in_epal_field_data', 'eSchool')
                    ->fields('eSchool', array('specialty_id', 'capacity_class_specialty'))
                    ->condition('eSchool.epal_id', $epalSchool->id, '=');
667

Kostas G's avatar
Kostas G committed
668 669 670 671 672
                if ($capacityEnabled === "0") {
					$sCon->condition( db_or()
						//->condition('eSchool.capacity_class_specialty', 0, '=')
						->condition('eSchool.capacity_class_specialty', null, 'is')  ) ;
                }
673

Kostas G's avatar
Kostas G committed
674
                $specialtiesInEpals = $sCon->execute()->fetchAll(\PDO::FETCH_OBJ);
675

Kostas G's avatar
Kostas G committed
676 677 678 679 680
                foreach ($specialtiesInEpals as $specialtiesInEpal) {
					$sCon = $this->connection
						->select('eepal_specialty_field_data', 'eSpecialties')
                        ->fields('eSpecialties', array('name'))
                        ->condition('eSpecialties.id', $specialtiesInEpal->specialty_id, '=');
681

Kostas G's avatar
Kostas G committed
682 683 684 685 686 687 688 689 690
					$specialtiesNamesInEpals = $sCon->execute()->fetchAll(\PDO::FETCH_OBJ);
                    foreach ($specialtiesNamesInEpals as $specialtiesNamesInEpal) {
						array_push($regionColumn, $epalRegion->name);
						array_push($adminColumn, $epalAdmin->name);
						array_push($schoolNameColumn, $epalSchool->name);
						array_push($schoolSectionColumn, 'Γ\' τάξη / ' . $specialtiesNamesInEpal->name );
						array_push($capacityColumn, $specialtiesInEpal->capacity_class_specialty);
                    }   //end foreach $specialtiesNamesInEpal
                } //end foreach $specialtiesInEpals
691

Kostas G's avatar
Kostas G committed
692 693 694 695 696
                //εύρεση αριθμού τμημάτων (χωρητικότητα) για κάθε ειδικότητα της Δ' τάξης
                $sCon = $this->connection
					->select('eepal_specialties_in_epal_field_data', 'eSchool')
                    ->fields('eSchool', array('specialty_id', 'capacity_class_specialty_d'))
                    ->condition('eSchool.epal_id', $epalSchool->id, '=');
697

Kostas G's avatar
Kostas G committed
698 699 700 701 702
                if ($capacityEnabled === "0") {
					$sCon->condition( db_or()
						//->condition('eSchool.capacity_class_specialty_d', 0, '=')
						->condition('eSchool.capacity_class_specialty_d', null, 'is')  ) ;
                }
703

Kostas G's avatar
Kostas G committed
704
                $specialtiesInEpals = $sCon->execute()->fetchAll(\PDO::FETCH_OBJ);
705

Kostas G's avatar
Kostas G committed
706 707 708 709 710
                foreach ($specialtiesInEpals as $specialtiesInEpal) {
					$sCon = $this->connection
						->select('eepal_specialty_field_data', 'eSpecialties')
                        ->fields('eSpecialties', array('name'))
                        ->condition('eSpecialties.id', $specialtiesInEpal->specialty_id, '=');
711

Kostas G's avatar
Kostas G committed
712 713 714 715 716
					$specialtiesNamesInEpals = $sCon->execute()->fetchAll(\PDO::FETCH_OBJ);
                    foreach ($specialtiesNamesInEpals as $specialtiesNamesInEpal) {
                        if ($epalSchool->operation_shift === "ΕΣΠΕΡΙΝΟ") {
                            array_push($regionColumn, $epalRegion->name);
                            array_push($adminColumn, $epalAdmin->name);
717
                            array_push($schoolNameColumn, $epalSchool->name);
Kostas G's avatar
Kostas G committed
718 719
                            array_push($schoolSectionColumn, 'Δ\' τάξη / ' . $specialtiesNamesInEpal->name );
                            array_push($capacityColumn, $specialtiesInEpal->capacity_class_specialty_d);
720
                        }
Kostas G's avatar
Kostas G committed
721 722
                    }   //end foreach $specialtiesNamesInEpal
                } //end foreach $specialtiesInEpals
723

Kostas G's avatar
Kostas G committed
724
                //εισαγωγή εγγραφών στο tableschema
725
                for ($j = 0; $j < sizeof($schoolNameColumn); $j++) {
Kostas G's avatar
Kostas G committed
726 727 728 729 730 731 732
					array_push($list, (object) array(
						'name' => $schoolNameColumn[$j],
						'region' => $regionColumn[$j],
						'admin' => $adminColumn[$j],
						'section' => $schoolSectionColumn[$j],
						'capacity' => $capacityColumn[$j],
					));
733
                }
Kostas G's avatar
Kostas G committed
734
            } //end foreach school
735

736
            return $this->respondWithStatus($list, Response::HTTP_OK);
Kostas G's avatar
Kostas G committed
737 738
        } //end try

739 740 741
        catch (\Exception $e) {
            $this->logger->warning($e->getMessage());
            return $this->respondWithStatus([
Kostas G's avatar
Kostas G committed
742 743
				"message" => t("An unexpected problem occured during makeReportNoCapacity Method")
			], Response::HTTP_INTERNAL_SERVER_ERROR);
744 745
        }
    }
746

Kostas G's avatar
Kostas G committed
747
    public function retrieveUpLimit()
748
    {
749

Kostas G's avatar
Kostas G committed
750 751 752 753 754 755 756 757 758 759 760 761 762 763 764
        //βρες ανώτατο επιτρεπόμενο όριο μαθητών
        //$limitup = 1;
        try {
            $sCon = $this->connection
				->select('epal_class_limits', 'eSchool')
                ->fields('eSchool', array('name', 'limit_up'))
                ->condition('eSchool.name', '1', '=');
            $epalLimitUps = $sCon->execute()->fetchAll(\PDO::FETCH_OBJ);
            $epalLimitUp = reset($epalLimitUps);
            //$limitup = $epalLimitUp->limit_up;
            //return $limitup;
            return $epalLimitUp->limit_up;
        } catch (\Exception $e) {
            $this->logger->warning($e->getMessage());
            return -1;
765 766
        }
    }
767 768


Kostas G's avatar
Kostas G committed
769
    public function retrieveDownLimit($category,$classId)
770
    {
771

Kostas G's avatar
Kostas G committed
772 773 774 775
        try {
            $sCon = $this->connection->select('epal_class_limits', 'eSchool');
            $sCon->fields('eSchool', array('name', 'limit_down'));
            $sCon->condition('eSchool.name', $classId, '=');
776
            $sCon->condition('eSchool.category', $category, '=');
Kostas G's avatar
Kostas G committed
777 778 779 780 781 782 783
            $epalLimitDowns = $sCon->execute()->fetchAll(\PDO::FETCH_OBJ);
            $epalLimitDown = reset($epalLimitDowns);

            return $epalLimitDown->limit_down;
        } catch (\Exception $e) {
            $this->logger->warning($e->getMessage());
            return -1;
784
        }
Kostas G's avatar
Kostas G committed
785
    }
786

Kostas G's avatar
Kostas G committed
787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807
    /**
     * Check if $user, under $role, can issue the report on the
     * designated region, admin area and school.
     *
     * @return boolean
     */
    protected function canReportOn($user, $role, $regionId, $adminId, $schId)
    {
        if ($role === 'ministry') {
            $can = true;
        } elseif ($role === 'regioneduadmin') {
            $can = (
                ($user->init->value == $regionId)
                && (($adminId == 0) || $this->isAdminUnderRegion($adminId, $regionId))
            );
        } elseif ($role === 'eduadmin') {
            $can = (
                ($user->init->value == $adminId)
                && (($regionId == 0) || $this->isAdminUnderRegion($adminId, $regionId))
                && (($schId == 0) || $this->isSchoolUnderAdmin($schId, $adminId))
            );
808
        } else {
Kostas G's avatar
Kostas G committed
809
            $can = false;
810
        }
Kostas G's avatar
Kostas G committed
811
        return $can;
812
    }
813

Kostas G's avatar
Kostas G committed
814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846
    protected function isSchoolUnderAdmin($schId, $adminId)
    {
        $map = $this->entityTypeManager
            ->getStorage('eepal_school')
            ->loadByProperties([
                'id' => $schId,
                'edu_admin_id' => $adminId,
            ]);
        $existing_map = reset($map);
        if (!$existing_map) {
            return false;
        } else {
            return true;
        }
    }

    protected function isAdminUnderRegion($adminId, $regionId)
    {
        $map = $this->entityTypeManager
            ->getStorage('eepal_admin_area')
            ->loadByProperties([
                'id' => $adminId,
                'region_to_belong' => $regionId,
            ]);
        $existing_map = reset($map);
        if (!$existing_map) {
            return false;
        } else {
            return true;
        }
    }

    private function respondWithStatus($arr, $s)
847
    {
Kostas G's avatar
Kostas G committed
848 849 850 851
        $res = new JsonResponse($arr);
        $res->setStatusCode($s);
        return $res;
    }
852

Kostas G's avatar
Kostas G committed
853 854 855

    public function makeReportMergedClasses(Request $request, $regionId, $adminId, $schId, $classId, $sectorId, $courseId, $finalized)
    {
856
        try {
857 858
            $list = array();

859
            if (!$request->isMethod('GET')) {
Kostas G's avatar
Kostas G committed
860 861 862
                return $this->respondWithStatus([
                    "message" => t("Method Not Allowed")
                ], Response::HTTP_METHOD_NOT_ALLOWED);
863 864 865 866 867 868
            }
            //user validation
            $authToken = $request->headers->get('PHP_AUTH_USER');
            $users = $this->entityTypeManager->getStorage('user')->loadByProperties(array('name' => $authToken));
            $user = reset($users);
            if (!$user) {
Kostas G's avatar
Kostas G committed
869 870 871
                return $this->respondWithStatus([
                    'message' => t("User not found"),
                ], Response::HTTP_FORBIDDEN);
872 873 874 875 876
            }
            //user role validation
            $roles = $user->getRoles();
            $validRole = false;
            foreach ($roles as $role) {
Kostas G's avatar
Kostas G committed
877 878
                if ($role === "ministry" || $role === "regioneduadmin" || $role === "eduadmin") {
                    $validRole = $role;
879 880 881
                    break;
                }
            }
Kostas G's avatar
Kostas G committed
882 883 884 885 886 887 888 889 890
            if ($validRole === false) {
                return $this->respondWithStatus([
                    'message' => t("User Invalid Role"),
                ], Response::HTTP_FORBIDDEN);
            }
            if (!$this->canReportOn($user, $role, $regionId, $adminId, $schId)) {
                return $this->respondWithStatus([
                    'message' => t('User access to area forbidden'),
                ], Response::HTTP_FORBIDDEN);
891
            }
892 893


Kostas G's avatar
Kostas G committed
894 895 896
            if ( ($classId==3 || $classId==4) && $sectorId!=0 && $courseId==0 ){
                $sCon = \Drupal::database()->select('eepal_specialty_field_data', 'eSectors');
                $sCon->fields('eSectors', array('sector_id', 'id', 'name', ));
897
                $sCon->condition('eSectors.sector_id', $sectorId, '=');
Kostas G's avatar
Kostas G committed
898 899 900 901 902 903
                $specialties_in_sector = $sCon->execute()->fetchAll(\PDO::FETCH_OBJ);
            }
            $sector_specialties=array();
            foreach ($specialties_in_sector as $specialty){
                array_push($sector_specialties,$specialty->id);
            }
904 905


906

Kostas G's avatar
Kostas G committed
907
            $sCon = \Drupal::database()->select('epal_student_class', 'eStudent');
908 909 910 911 912 913
            $sCon->leftjoin('eepal_school_field_data','eSchool_initial','eSchool_initial.id=eStudent.initial_epal_id');
            $sCon->join('eepal_region_field_data', 'eRegion_initial', 'eRegion_initial.id = eSchool_initial.region_edu_admin_id');
            $sCon->join('eepal_admin_area_field_data', 'eAdmin_initial', 'eAdmin_initial.id = eSchool_initial.edu_admin_id');
            $sCon->join('eepal_school_field_data','eSchool_epal','eSchool_epal.id=eStudent.epal_id');
            $sCon->join('eepal_region_field_data', 'eRegion_epal', 'eRegion_epal.id = eSchool_epal.region_edu_admin_id');
            $sCon->join('eepal_admin_area_field_data', 'eAdmin_epal', 'eAdmin_epal.id = eSchool_epal.edu_admin_id');
Kostas G's avatar
Kostas G committed
914
            $sCon->fields('eStudent', array('initial_epal_id', 'epal_id', 'currentclass', 'specialization_id'));
915 916 917 918 919 920
            $sCon->addField('eRegion_initial', 'name','regionAName');
            $sCon->addField('eAdmin_initial', 'name','adminAName');
            $sCon->addField('eSchool_initial', 'name','schoolAName');
            $sCon->addField('eRegion_epal', 'name','regionBName');
            $sCon->addField('eAdmin_epal', 'name','adminBName');
            $sCon->addField('eSchool_epal', 'name','schoolBName');
Kostas G's avatar
Kostas G committed
921 922
            if ($classId != 0) {
                $sCon->condition('eStudent.currentclass', $classId, '=');
923
            }
Kostas G's avatar
Kostas G committed
924 925
            if ($sectorId != 0) {
                if ($classId==2){
926
                    $sCon->condition('eStudent.specialization_id', $sectorId, '=');
Kostas G's avatar
Kostas G committed
927 928
                }
                if (($classId==3 || $classId==4) && $courseId==0){
929
                    $sCon->condition('eStudent.specialization_id', $sector_specialties, 'IN');
Kostas G's avatar
Kostas G committed
930
                }
931

Kostas G's avatar
Kostas G committed
932 933 934 935
            }
            if ($courseId!=0){
                if ($classId==3 || $classId==4){
                    $sCon->condition('eStudent.specialization_id', $courseId, '=');
936 937
                }
            }
Kostas G's avatar
Kostas G committed
938 939
            if ($regionId != 0) {
                $sCon->condition('eSchool_initial.region_edu_admin_id', $regionId, '=');
940
            }
Kostas G's avatar
Kostas G committed
941 942 943 944 945 946 947 948 949 950 951
            if ($adminId != 0) {
                $sCon->condition('eSchool_initial.edu_admin_id', $adminId, '=');
            }
            if ($schId != 0) {
                $sCon->condition('eSchool_initial.id', $schId, '=');
            }
            $sCon->condition('eStudent.initial_epal_id', 0, '!=');
            $sCon->groupBy('initial_epal_id');
            $sCon->groupBy('epal_id');
            $sCon->groupBy('currentclass');
            $sCon->groupBy('specialization_id');
952 953 954 955 956 957 958
            $sCon->groupBy('eRegion_initial.name');
            $sCon->groupBy('eAdmin_initial.name');
            $sCon->groupBy('eSchool_initial.name');
            $sCon->groupBy('eRegion_epal.name');
            $sCon->groupBy('eAdmin_epal.name');
            $sCon->groupBy('eSchool_epal.name');
            $sCon->addExpression('count(eStudent.id)', 'eStudent_count');
Kostas G's avatar
Kostas G committed
959
            $mergedSchools = $sCon->execute()->fetchAll(\PDO::FETCH_OBJ);
960 961 962 963




Kostas G's avatar
Kostas G committed
964 965 966 967 968 969 970 971 972
            $schoolANameColumn = array();
            $regionAColumn = array();
            $adminAColumn = array();
            $schoolSectionColumn = array();
            $numAColumn = array();
            $schoolBNameColumn = array();
            $regionBColumn = array();
            $adminBColumn = array();
            $numBColumn = array();
973

974
            foreach ($mergedSchools as $mergedSchool) {
975

Kostas G's avatar
Kostas G committed
976 977 978 979
                array_push($regionAColumn, $mergedSchool->regionAName);
                array_push($adminAColumn, $mergedSchool->adminAName);
                array_push($schoolANameColumn, $mergedSchool->schoolAName);
                if ($mergedSchool->currentclass==1){
980
                    array_push($schoolSectionColumn, 'Α Tάξη');
981
                }
982
                else if ($mergedSchool->currentclass==2){
Kostas G's avatar
Kostas G committed
983 984
                    $sCon = \Drupal::database()->select('eepal_sectors_field_data', 'eSectors');
                    $sCon->addField('eSectors', 'name');
985
                    $sCon->condition('eSectors.id', $mergedSchool->specialization_id, '=');
Kostas G's avatar
Kostas G committed
986 987
                    $sector_name = $sCon->execute()->fetchField();
                    array_push($schoolSectionColumn, 'Β τάξη / ' . $sector_name);
988
                }
Kostas G's avatar
Kostas G committed
989 990
                else{
                    $sCon = \Drupal::database()->select('eepal_specialty_field_data', 'eSpecialties');
991
                    $sCon->join('eepal_sectors_field_data', 'eSectors','eSectors.id=eSpecialties.sector_id');
Kostas G's avatar
Kostas G committed
992
                    $sCon->addField('eSectors', 'name','sectorName');
993 994
                    $sCon->addField('eSpecialties', 'name','specialtyName');
                    $sCon->condition('eSpecialties.id', $mergedSchool->specialization_id, '=');
Kostas G's avatar
Kostas G committed
995 996
                    $sector_specialty = $sCon->execute()->fetchAssoc();
                    if ($mergedSchool->currentclass==3){
997
                        array_push($schoolSectionColumn, 'Γ Tάξη / ' . $sector_specialty['sectorName'].'/'.$sector_specialty['specialtyName']);//->specialization_id);
Kostas G's avatar
Kostas G committed
998 999
                    }
                    else if ($mergedSchool->currentclass==4){
1000
                        array_push($schoolSectionColumn, 'Δ Tάξη / ' . $mergedSchool->specialization_id);
Kostas G's avatar
Kostas G committed
1001
                    }
1002 1003
                }

Kostas G's avatar
Kostas G committed
1004 1005
                array_push($numAColumn, $mergedSchool->eStudent_count);
                array_push($regionBColumn, $mergedSchool->regionBName);
1006 1007
                array_push($adminBColumn, $mergedSchool->adminBName);
                array_push($schoolBNameColumn, $mergedSchool->schoolBName);
1008

Kostas G's avatar
Kostas G committed
1009 1010 1011
                $sCon = \Drupal::database()->select('epal_student_class', 'eStudent');
                $sCon->condition('eStudent.epal_id', $mergedSchool->epal_id, '=');
                $sCon->condition('eStudent.currentclass', $mergedSchool->currentclass, '=');
1012 1013
                $sCon->condition('eStudent.specialization_id', $mergedSchool->specialization_id, '=');
                $sCon->addExpression('count(eStudent.id)', 'eStudent_extra_count');
Kostas G's avatar
Kostas G committed
1014 1015 1016 1017 1018
                $sCon->groupBy('eStudent.epal_id');
                $sCon->groupBy('eStudent.currentclass');
                $sCon->groupBy('eStudent.specialization_id');
                $eStudent_extra_count = $sCon->execute()->fetchAssoc();
                array_push($numBColumn, $eStudent_extra_count['eStudent_extra_count']);
1019

Kostas G's avatar
Kostas G committed
1020
            }
1021

Kostas G's avatar
Kostas G committed
1022
            for ($j = 0; $j < sizeof($schoolANameColumn); $j++) {
1023

Kostas G's avatar
Kostas G committed
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
                array_push($list, (object) array(
                    'nameΑ' => $schoolANameColumn[$j],
                    'regionΑ' => $regionAColumn[$j],
                    'adminΑ' => $adminAColumn[$j],
                    'sectionΑ' => str_replace(",", "", $schoolSectionColumn[$j]),
                    'numΑ' => $numAColumn[$j],
                    'nameΒ' => $schoolBNameColumn[$j],
                    'regionΒ' => $regionBColumn[$j],
                    'adminΒ' => $adminBColumn[$j],
                    'numΒ' => $numBColumn[$j],
                ));
            }
1036 1037 1038

            return $this->respondWithStatus($list, Response::HTTP_OK);

Kostas G's avatar
Kostas G committed
1039
        }
1040 1041 1042
        catch (\Exception $e) {
            $this->logger->warning($e->getMessage());
            return $this->respondWithStatus([
Kostas G's avatar
Kostas G committed
1043 1044
                "message" => t("An unexpected problem occured in makeReportCompleteness Method")
            ], Response::HTTP_INTERNAL_SERVER_ERROR);
1045 1046
        }
    }
1047

Kostas G's avatar
Kostas G committed
1048 1049

    public function makeReportApplications(Request $request, $regionId, $adminId, $schId, $classId, $sectorId, $courseId, $finalized)
1050
    {
1051

1052
        try {
Kostas G's avatar
Kostas G committed
1053 1054 1055 1056 1057
            if (!$request->isMethod('GET')) {
                return $this->respondWithStatus([
                    "message" => t("Method Not Allowed")
                ], Response::HTTP_METHOD_NOT_ALLOWED);
            }
1058

Kostas G's avatar
Kostas G committed
1059 1060 1061 1062 1063 1064 1065 1066 1067
            //user validation
            $authToken = $request->headers->get('PHP_AUTH_USER');
            $users = $this->entityTypeManager->getStorage('user')->loadByProperties(array('name' => $authToken));
            $user = reset($users);
            if (!$user) {
                return $this->respondWithStatus([
                    'message' => t("User not found"),
                ], Response::HTTP_FORBIDDEN);
            }
1068

Kostas G's avatar
Kostas G committed
1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
            //user role validation
            $roles = $user->getRoles();
            $validRole = false;
            foreach ($roles as $role) {
                if ($role === "ministry") {
                    $validRole = true;
                    break;
                }
            }
            if (!$validRole) {
                return $this->respondWithStatus([
                    'message' => t("User Invalid Role"),
                ], Response::HTTP_FORBIDDEN);
            }
1083

Kostas G's avatar
Kostas G committed
1084
            $list = array();
1085

Kostas G's avatar
Kostas G committed
1086 1087 1088
            if ( ($classId==3 || $classId==4) && $sectorId!=0 && $courseId==0 ){
                $sCon = \Drupal::database()->select('eepal_specialty_field_data', 'eSectors');
                $sCon->fields('eSectors', array('sector_id', 'id', 'name', ));
1089
                $sCon->condition('eSectors.sector_id', $sectorId, '=');
Kostas G's avatar
Kostas G committed
1090 1091 1092 1093 1094 1095
                $specialties_in_sector = $sCon->execute()->fetchAll(\PDO::FETCH_OBJ);
            }
            $sector_specialties=array();
            foreach ($specialties_in_sector as $specialty){
                array_push($sector_specialties,$specialty->id);
            }
1096

1097

Kostas G's avatar
Kostas G committed
1098
            $sCon = \Drupal::database()->select('epal_student', 'eStudent');
1099
            $sCon->join('epal_student_epal_chosen','eSchool_chosen','eSchool_chosen.student_id=eStudent.id');
Kostas G's avatar
Kostas G committed
1100
            $sCon->leftjoin('epal_student_sector_field', 'eSector', 'eSector.student_id = eStudent.id AND eStudent.currentclass=2');
1101 1102 1103 1104 1105 1106 1107 1108
            $sCon->leftjoin('epal_student_course_field', 'eCourse', 'eCourse.student_id = eStudent.id  AND eStudent.currentclass>2');
            $sCon->join('eepal_school_field_data','eSchool','eSchool.id=eSchool_chosen.epal_id');
            $sCon->join('eepal_region_field_data', 'eRegion', 'eRegion.id = eSchool.region_edu_admin_id');
            $sCon->join('eepal_admin_area_field_data', 'eAdmin', 'eAdmin.id = eSchool.edu_admin_id');
            $sCon->leftjoin('eepal_sectors_field_data','eSectorTitle','eSectorTitle.id=eSector.sectorfield_id');
            $sCon->leftjoin('eepal_specialty_field_data','eCourseTitle','eCourseTitle.id=eCourse.coursefield_id');
            $sCon->addField('eRegion', 'name','regionName');
            $sCon->addField('eAdmin', 'name','adminName');
Kostas G's avatar
Kostas G committed
1109
            $sCon->addField('eSchool', 'name','schoolName');
1110 1111 1112 1113 1114 1115 1116 1117
            $sCon->addField('eStudent', 'currentclass');
            $sCon->addField('eSchool_chosen','epal_id');
            $sCon->addField('eCourse', 'coursefield_id');
            $sCon->addField('eSector', 'sectorfield_id');
            $sCon->addField('eSectorTitle', 'name','sectorname');
            $sCon->addField('eCourseTitle', 'name','specialtyname');


Kostas G's avatar
Kostas G committed
1118 1119 1120 1121 1122
            if ($classId != 0) {
                $sCon->condition('eStudent.currentclass', $classId, '=');
            }
            if ($sectorId != 0) {
                if ($classId==2){
1123
                    $sCon->condition('eSector.sectorfield_id', $sectorId, '=');
Kostas G's avatar
Kostas G committed
1124 1125
                }
                if (($classId==3 || $classId==4) && $courseId==0){
1126
                    $sCon->condition('eCourse.coursefield_id', $sector_specialties, 'IN');
Kostas G's avatar
Kostas G committed
1127 1128 1129 1130 1131
                }

            }
            if ($courseId!=0){
                if ($classId==3 || $classId==4){
Kostas G's avatar
Kostas G committed
1132
                    $sCon->condition('eCourse.coursefield_id', $courseId, '=');
Kostas G's avatar
Kostas G committed
1133 1134
                }
            }
Kostas G's avatar
Kostas G committed
1135

Kostas G's avatar
Kostas G committed
1136
            if ($regionId != 0) {
Kostas G's avatar
Kostas G committed
1137
                $sCon->condition('eSchool.region_edu_admin_id', $regionId, '=');
Kostas G's avatar
Kostas G committed
1138 1139
            }
            if ($adminId != 0) {
Kostas G's avatar
Kostas G committed
1140
                $sCon->condition('eSchool.edu_admin_id', $adminId, '=');
Kostas G's avatar
Kostas G committed
1141 1142
            }
            if ($schId != 0) {
Kostas G's avatar
Kostas G committed
1143
                $sCon->condition('eSchool_chosen.epal_id', $schId, '=');
Kostas G's avatar
Kostas G committed
1144
            }
Kostas G's avatar
Kostas G committed
1145
            $sCon->condition('eStudent.delapp', 0, '=');
1146
            $sCon->condition('eSchool_chosen.choice_no', 1, '=');
Kostas G's avatar
Kostas G committed
1147 1148
            $sCon->groupBy('eStudent.currentclass');
            $sCon->groupBy('sectorfield_id');
1149 1150 1151
            $sCon->groupBy('coursefield_id');
            $sCon->groupBy('eRegion.name');
            $sCon->groupBy('eAdmin.name');
Kostas G's avatar
Kostas G committed
1152
            $sCon->groupBy('eSchool.name');
1153 1154 1155 1156
            $sCon->groupBy('eSchool_chosen.epal_id');
            $sCon->groupBy('sectorname');
            $sCon->groupBy('specialtyname');
            $sCon->addExpression('count(eStudent.id)', 'eStudent_count');
Kostas G's avatar
Kostas G committed
1157
            $applications = $sCon->execute()->fetchAll(\PDO::FETCH_OBJ);
1158

Kostas G's avatar
Kostas G committed
1159 1160


Kostas G's avatar
Kostas G committed
1161 1162 1163
            $schoolNameColumn = array();
            $regionColumn = array();
            $adminColumn = array();
Kostas G's avatar
Kostas G committed
1164
            $schoolSectionColumn = array();
Kostas G's avatar
Kostas G committed
1165
            $numColumn = array();
Kostas G's avatar
Kostas G committed
1166 1167


1168
            foreach ($applications as $application) {
Kostas G's avatar
Kostas G committed
1169 1170 1171 1172 1173

                array_push($regionColumn, $application->regionName);
                array_push($adminColumn, $application->adminName);
                array_push($schoolNameColumn, $application->schoolName);
                if ($application->currentclass==1){
1174
                    array_push($schoolSectionColumn, 'Α Tάξη');
Kostas G's avatar
Kostas G committed
1175
                }else if($application->currentclass==2){
1176
                    array_push($schoolSectionColumn, 'B Tάξη / '.$application->sectorname);
Kostas G's avatar
Kostas G committed
1177
                }else{
Kostas G's avatar
Kostas G committed
1178
                    $sCon = \Drupal::database()->select('eepal_specialty_field_data', 'eSpecialties');
1179
                    $sCon->join('eepal_sectors_field_data', 'eSectors','eSectors.id=eSpecialties.sector_id');
Kostas G's avatar
Kostas G committed
1180
                    $sCon->addField('eSectors', 'name','sectorName');
1181 1182
                    $sCon->addField('eSpecialties', 'name','specialtyName');
                    $sCon->condition('eSpecialties.id', $application->coursefield_id, '=');
Kostas G's avatar
Kostas G committed
1183
                    $sector_specialty = $sCon->execute()->fetchAssoc();
Kostas G's avatar
Kostas G committed
1184
                    if($application->currentclass==3){
1185
                        array_push($schoolSectionColumn, 'Γ Tάξη / '.$sector_specialty['sectorName'].' / '.$sector_specialty['specialtyName']);
Kostas G's avatar
Kostas G committed
1186
                    }else if($application->currentclass==4){
1187
                        array_push($schoolSectionColumn, 'Δ Tάξη / '.$sector_specialty['sectorName'].' / '.$sector_specialty['specialtyName']);
Kostas G's avatar
Kostas G committed
1188
                    }
1189
                }
Kostas G's avatar
Kostas G committed
1190
                array_push($numColumn,$application->eStudent_count);
Kostas G's avatar
Kostas G committed
1191 1192 1193

            }

Kostas G's avatar
Kostas G committed
1194
            for ($j = 0; $j < sizeof($schoolNameColumn); $j++) {
1195

Kostas G's avatar
Kostas G committed
1196
                array_push($list, (object) array(
Kostas G's avatar
Kostas G committed
1197 1198 1199 1200 1201
                    'name' => $schoolNameColumn[$j],
                    'region' => $regionColumn[$j],
                    'admin' => $adminColumn[$j],
                    'section' => str_replace(",", "", $schoolSectionColumn[$j]),
                    'num' => $numColumn[$j],
Kostas G's avatar
Kostas G committed
1202 1203 1204 1205 1206 1207 1208 1209 1210
                ));
            }

            return $this->respondWithStatus($list, Response::HTTP_OK);

        }
        catch (\Exception $e) {
            $this->logger->warning($e->getMessage());
            return $this->respondWithStatus([
Kostas G's avatar
Kostas G committed
1211
                "message" => t("An unexpected problem occured in makeReportApplications Method")
Kostas G's avatar
Kostas G committed
1212 1213 1214 1215 1216
            ], Response::HTTP_INTERNAL_SERVER_ERROR);
        }
    }


Kostas G's avatar
Kostas G committed
1217
    public function makeReportUserApplications(Request $request)
Kostas G's avatar
Kostas G committed
1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252
    {

        try {
            if (!$request->isMethod('GET')) {
                return $this->respondWithStatus([
                    "message" => t("Method Not Allowed")
                ], Response::HTTP_METHOD_NOT_ALLOWED);
            }

            //user validation
            $authToken = $request->headers->get('PHP_AUTH_USER');
            $users = $this->entityTypeManager->getStorage('user')->loadByProperties(array('name' => $authToken));
            $user = reset($users);
            if (!$user) {
                return $this->respondWithStatus([
                    'message' => t("User not found"),
                ], Response::HTTP_FORBIDDEN);
            }

            //user role validation
            $roles = $user->getRoles();
            $validRole = false;
            foreach ($roles as $role) {
                if ($role === "ministry") {
                    $validRole = true;
                    break;
                }
            }
            if (!$validRole) {
                return $this->respondWithStatus([
                    'message' => t("User Invalid Role"),
                ], Response::HTTP_FORBIDDEN);
            }

            $list = array();
Kostas G's avatar
Kostas G committed
1253 1254
            $studentIdColumn = array();
            $numAppsColumn = array();
Kostas G's avatar
Kostas G committed
1255 1256

            $sCon = \Drupal::database()->select('epal_student', 'eStudent');
1257
            $sCon->addField('eStudent','user_id','studentId');
Kostas G's avatar
Kostas G committed
1258
            $sCon->condition('eStudent.delapp', 0 , '=');
1259
            $sCon->groupBy('eStudent.user_id');
Kostas G's avatar
Kostas G committed
1260 1261
            $sCon->addExpression('count(eStudent.user_id)', 'apps_count');
            $sCon->having('count(eStudent.user_id)>5');                        
1262
            $sCon->orderBy('apps_count', 'DESC');
Kostas G's avatar
Kostas G committed
1263 1264
            $applications = $sCon->execute()->fetchAll(\PDO::FETCH_OBJ);

1265 1266 1267

            foreach ($applications as $application) {

Kostas G's avatar
Kostas G committed
1268
                array_push($studentIdColumn, $application->studentId);
1269
                array_push($numAppsColumn, $application->apps_count);
Kostas G's avatar
Kostas G committed
1270
            }
1271

Kostas G's avatar
Kostas G committed
1272
             for ($j = 0; $j < sizeof($studentIdColumn); $j++) {
1273

Kostas G's avatar
Kostas G committed
1274 1275 1276 1277 1278
                 array_push($list, (object) array(
                    'studentId' => $studentIdColumn[$j],
                    'numapps' => $numAppsColumn[$j],
                ));
            }
1279

Kostas G's avatar
Kostas G committed
1280
            return $this->respondWithStatus($list, Response::HTTP_OK);
1281

Kostas G's avatar
Kostas G committed
1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329
        }
        catch (\Exception $e) {
            $this->logger->warning($e->getMessage());
            return $this->respondWithStatus([
                "message" => t("An unexpected problem occured in makeReportUserApplications Method")
                   ], Response::HTTP_INTERNAL_SERVER_ERROR);
        }
    }

    public function makeReportGelStudents(Request $request,$regionId, $adminId, $schId, $classId, $sectorId, $courseId, $finalized)
    {
        try {
            if (!$request->isMethod('GET')) {
                return $this->respondWithStatus([
                    "message" => t("Method Not Allowed")
                ], Response::HTTP_METHOD_NOT_ALLOWED);
            }

            //user validation
            $authToken = $request->headers->get('PHP_AUTH_USER');
            $users = $this->entityTypeManager->getStorage('user')->loadByProperties(array('name' => $authToken));
            $user = reset($users);
            if (!$user) {
                return $this->respondWithStatus([
                    'message' => t("User not found"),
                ], Response::HTTP_FORBIDDEN);
            }

            //user role validation
            $roles = $user->getRoles();
            $validRole = false;
            foreach ($roles as $role) {
                if ($role === "ministry") {
                    $validRole = true;
                    break;
                }
            }
            if (!$validRole) {
                return $this->respondWithStatus([
                    'message' => t("User Invalid Role"),
                ], Response::HTTP_FORBIDDEN);
            }

            $list = array();

            if ( ($classId==3 || $classId==4) && $sectorId!=0 && $courseId==0 ){
                $sCon = \Drupal::database()->select('eepal_specialty_field_data', 'eSectors');
                $sCon->fields('eSectors', array('sector_id', 'id', 'name', ));
1330
                $sCon->condition('eSectors.sector_id', $sectorId, '=');
Kostas G's avatar
Kostas G committed
1331 1332 1333 1334 1335 1336
                $specialties_in_sector = $sCon->execute()->fetchAll(\PDO::FETCH_OBJ);
            }
            $sector_specialties=array();
            foreach ($specialties_in_sector as $specialty){
                array_push($sector_specialties,$specialty->id);
            }
1337

Kostas G's avatar
Kostas G committed
1338 1339

            $sCon = \Drupal::database()->select('epal_student', 'eStudent');
1340
            $sCon->join('epal_student_epal_chosen','eSchool_chosen','eSchool_chosen.student_id=eStudent.id');
Kostas G's avatar
Kostas G committed
1341
            $sCon->leftjoin('epal_student_sector_field', 'eSector', 'eSector.student_id = eStudent.id AND eStudent.currentclass=2');
1342 1343 1344 1345 1346 1347 1348 1349
            $sCon->leftjoin('epal_student_course_field', 'eCourse', 'eCourse.student_id = eStudent.id  AND eStudent.currentclass>2');
            $sCon->join('eepal_school_field_data','eSchool','eSchool.id=eSchool_chosen.epal_id');
            $sCon->join('eepal_region_field_data', 'eRegion', 'eRegion.id = eSchool.region_edu_admin_id');
            $sCon->join('eepal_admin_area_field_data', 'eAdmin', 'eAdmin.id = eSchool.edu_admin_id');
            $sCon->leftjoin('eepal_sectors_field_data','eSectorTitle','eSectorTitle.id=eSector.sectorfield_id');
            $sCon->leftjoin('eepal_specialty_field_data','eCourseTitle','eCourseTitle.id=eCourse.coursefield_id');
            $sCon->addField('eRegion', 'name','regionName');
            $sCon->addField('eAdmin', 'name','adminName');
Kostas G's avatar
Kostas G committed
1350
            $sCon->addField('eSchool', 'name','schoolName');
1351 1352 1353 1354 1355 1356 1357 1358
            $sCon->addField('eStudent', 'currentclass');
            $sCon->addField('eSchool_chosen','epal_id');
            $sCon->addField('eCourse', 'coursefield_id');
            $sCon->addField('eSector', 'sectorfield_id');
            $sCon->addField('eSectorTitle', 'name','sectorname');
            $sCon->addField('eCourseTitle', 'name','specialtyname');
            $sCon->condition('eStudent.lastschool_unittypeid', 4, '=');

Kostas G's avatar
Kostas G committed
1359 1360 1361 1362 1363
            if ($classId != 0) {
                $sCon->condition('eStudent.currentclass', $classId, '=');
            }
            if ($sectorId != 0) {
                if ($classId==2){
1364
                    $sCon->condition('eSector.sectorfield_id', $sectorId, '=');
Kostas G's avatar
Kostas G committed
1365 1366
                }
                if (($classId==3 || $classId==4) && $courseId==0){
1367
                    $sCon->condition('eCourse.coursefield_id', $sector_specialties, 'IN');
Kostas G's avatar
Kostas G committed
1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386
                }

            }
            if ($courseId!=0){
                if ($classId==3 || $classId==4){
                    $sCon->condition('eCourse.coursefield_id', $courseId, '=');
                }
            }

            if ($regionId != 0) {
                $sCon->condition('eSchool.region_edu_admin_id', $regionId, '=');
            }
            if ($adminId != 0) {
                $sCon->condition('eSchool.edu_admin_id', $adminId, '=');
            }
            if ($schId != 0) {
                $sCon->condition('eSchool_chosen.epal_id', $schId, '=');
            }
            $sCon->condition('eStudent.delapp', 0, '=');
1387
            $sCon->condition('eSchool_chosen.choice_no', 1, '=');
Kostas G's avatar
Kostas G committed
1388 1389
            $sCon->groupBy('eStudent.currentclass');
            $sCon->groupBy('sectorfield_id');
1390 1391 1392
            $sCon->groupBy('coursefield_id');
            $sCon->groupBy('eRegion.name');
            $sCon->groupBy('eAdmin.name');
Kostas G's avatar
Kostas G committed
1393
            $sCon->groupBy('eSchool.name');
1394 1395 1396 1397
            $sCon->groupBy('eSchool_chosen.epal_id');
            $sCon->groupBy('sectorname');
            $sCon->groupBy('specialtyname');
            $sCon->addExpression('count(eStudent.id)', 'eStudent_count');
Kostas G's avatar
Kostas G committed
1398
            $applications = $sCon->execute()->fetchAll(\PDO::FETCH_OBJ);
1399

Kostas G's avatar
Kostas G committed
1400 1401 1402 1403 1404 1405 1406 1407 1408


            $schoolNameColumn = array();
            $regionColumn = array();
            $adminColumn = array();
            $schoolSectionColumn = array();
            $numColumn = array();


1409
            foreach ($applications as $application) {
Kostas G's avatar
Kostas G committed
1410 1411 1412 1413 1414

                array_push($regionColumn, $application->regionName);
                array_push($adminColumn, $application->adminName);
                array_push($schoolNameColumn, $application->schoolName);
                if ($application->currentclass==1){
1415
                    array_push($schoolSectionColumn, 'Α Tάξη');
Kostas G's avatar
Kostas G committed
1416
                }else if($application->currentclass==2){
1417
                    array_push($schoolSectionColumn, 'B Tάξη / '.$application->sectorname);
Kostas G's avatar
Kostas G committed
1418 1419
                }else{
                    $sCon = \Drupal::database()->select('eepal_specialty_field_data', 'eSpecialties');
1420
                    $sCon->join('eepal_sectors_field_data', 'eSectors','eSectors.id=eSpecialties.sector_id');
Kostas G's avatar
Kostas G committed
1421
                    $sCon->addField('eSectors', 'name','sectorName');
1422 1423
                    $sCon->addField('eSpecialties', 'name','specialtyName');
                    $sCon->condition('eSpecialties.id', $application->coursefield_id, '=');
Kostas G's avatar
Kostas G committed
1424 1425
                    $sector_specialty = $sCon->execute()->fetchAssoc();
                    if($application->currentclass==3){
1426
                        array_push($schoolSectionColumn, 'Γ Tάξη / '.$sector_specialty['sectorName'].' / '.$sector_specialty['specialtyName']);
Kostas G's avatar
Kostas G committed
1427
                    }else if($application->currentclass==4){
1428
                        array_push($schoolSectionColumn, 'Δ Tάξη / '.$sector_specialty['sectorName'].' / '.$sector_specialty['specialtyName']);
Kostas G's avatar
Kostas G committed
1429
                    }
1430
                }
Kostas G's avatar
Kostas G committed
1431 1432 1433 1434 1435
                array_push($numColumn,$application->eStudent_count);

            }

            for ($j = 0; $j < sizeof($schoolNameColumn); $j++) {
1436

Kostas G's avatar
Kostas G committed
1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450
                array_push($list, (object) array(
                    'name' => $schoolNameColumn[$j],
                    'region' => $regionColumn[$j],
                    'admin' => $adminColumn[$j],
                    'section' => str_replace(",", "", $schoolSectionColumn[$j]),
                    'num' => $numColumn[$j],
                ));
            }

            return $this->respondWithStatus($list, Response::HTTP_OK);
        }
        catch (\Exception $e) {
            $this->logger->warning($e->getMessage());
            return $this->respondWithStatus([
Kostas G's avatar
Kostas G committed
1451
                "message" => t("An unexpected problem occured in makeReportgelStudents Method")
Kostas G's avatar
Kostas G committed
1452 1453 1454 1455 1456 1457
            ], Response::HTTP_INTERNAL_SERVER_ERROR);
        }
    }



Kostas G's avatar
Kostas G committed
1458 1459
    public function makeReportStudentsNum(Request $request, $regionId, $adminId, $schId, $classId, $sectorId, $courseId, $finalized)
    {
Kostas G's avatar
Kostas G committed
1460 1461
        try {
            if (!$request->isMethod('GET')) {
Kostas G's avatar
Kostas G committed
1462 1463 1464
				return $this->respondWithStatus([
					"message" => t("Method Not Allowed")
				], Response::HTTP_METHOD_NOT_ALLOWED);
Kostas G's avatar
Kostas G committed
1465 1466 1467 1468 1469 1470 1471
            }

            //user validation
            $authToken = $request->headers->get('PHP_AUTH_USER');
            $users = $this->entityTypeManager->getStorage('user')->loadByProperties(array('name' => $authToken));
            $user = reset($users);
            if (!$user) {
Kostas G's avatar
Kostas G committed
1472 1473 1474
				return $this->respondWithStatus([
					'message' => t("User not found"),
				], Response::HTTP_FORBIDDEN);
Kostas G's avatar
Kostas G committed
1475 1476 1477 1478 1479 1480
            }

            //user role validation
            $roles = $user->getRoles();
            $validRole = false;
            foreach ($roles as $role) {
Kostas G's avatar
Kostas G committed
1481 1482
                if ($role === "ministry" || $role === "regioneduadmin" || $role === "eduadmin") {
                    $validRole = $role;
Kostas G's avatar
Kostas G committed
1483 1484 1485
                    break;
                }
            }
Kostas G's avatar
Kostas G committed
1486 1487 1488 1489
            if ($validRole === false) {
				return $this->respondWithStatus([
					'message' => t("User Invalid Role"),
				], Response::HTTP_FORBIDDEN);
Kostas G's avatar
Kostas G committed
1490 1491
            }

Kostas G's avatar
Kostas G committed
1492 1493 1494 1495 1496
            if (!$this->canReportOn($user, $role, $regionId, $adminId, $schId)) {
				return $this->respondWithStatus([
					'message' => t('User access to area forbidden'),
				], Response::HTTP_FORBIDDEN);
            }
Kostas G's avatar
Kostas G committed
1497

1498
            $limitup = $this->retrieveUpLimit();
Kostas G's avatar
Kostas G committed
1499

Kostas G's avatar
Kostas G committed
1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510
            $list = array();

            // βρες όλα τα σχολεία που πληρούν τα κριτήρια / φίλτρα
            $sCon = $this->connection->select('eepal_school_field_data', 'eSchool');
			$sCon->join('eepal_region_field_data', 'eRegion', 'eRegion.id = eSchool.region_edu_admin_id');
			$sCon->join('eepal_admin_area_field_data', 'eAdmin', 'eAdmin.id = eSchool.edu_admin_id');
            $sCon->fields('eSchool', array('id', 'name', 'capacity_class_a', 'region_edu_admin_id', 'edu_admin_id','operation_shift', 'metathesis_region'))
				->fields('eRegion', ['name'])
				->fields('eAdmin', ['name']);
            if ($regionId != 0) {
                $sCon->condition('eSchool.region_edu_admin_id', $regionId, '=');
Kostas G's avatar
Kostas G committed
1511
            }
Kostas G's avatar
Kostas G committed
1512 1513
            if ($adminId != 0) {
                $sCon->condition('eSchool.edu_admin_id', $adminId, '=');
Kostas G's avatar
Kostas G committed
1514
            }
Kostas G's avatar
Kostas G committed
1515 1516
            if ($schId != 0) {
                $sCon->condition('eSchool.id', $schId, '=');
Kostas G's avatar