ReportsCreator.php 49.6 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
46
47
48
49
50
51
    protected $entity_query;
    protected $entityTypeManager;
    protected $logger;
    protected $connection;

    public function __construct(
        EntityTypeManagerInterface $entityTypeManager,
        QueryFactory $entity_query,
        Connection $connection,
        LoggerChannelFactoryInterface $loggerChannel
    ) {
    
            $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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
        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')
                ->fields('eStudent', array('id'));
            $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'))
                    ->condition('eStudent.currentclass', strval($i), '=');
                $numApplications = $sCon->countQuery()->execute()->fetchField();
                array_push($list, (object) array('name' => "Αριθμός Αιτήσεων για {$label} Τάξη", 'numStudents' => $numApplications));
            }

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

            //υπολογισμός αριθμού χρηστών
            $sCon = $this->connection
                ->select('epal_users', 'eUser')
                ->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);
        }
    }
144
145
146



147
148
    public function makeGeneralReport(Request $request)
    {
149

150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
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
        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')
                ->fields('eStudent', array('id'));
            $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());
            }

            // υπολογισμός αριθμού δηλώσεων που ΔΕΝ ικανοποιήθηκαν
            /*
201
202
203
204
205
206
207
208
209
210
211
212
213
			$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();
			*/
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
            $sCon = $this->connection->select('epal_student', 'epalStudent');
            $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);
        }
    }
248
249


250
251
    public function makeReportCompleteness(Request $request, $regionId, $adminId, $schId)
    {
252

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

260
261
262
263
264
            //user validation
            $authToken = $request->headers->get('PHP_AUTH_USER');
            $users = $this->entityTypeManager->getStorage('user')->loadByProperties(array('name' => $authToken));
            $user = reset($users);
            if (!$user) {
265
				return $this->respondWithStatus([
266
267
268
269
270
271
272
273
274
					'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") {
275
                    $validRole = $role;
276
277
278
                    break;
                }
            }
279
            if ($validRole === false) {
280
281
282
283
284
				return $this->respondWithStatus([
					'message' => t("User Invalid Role"),
				], Response::HTTP_FORBIDDEN);
            }

285
286
287
288
289
290
            if (!$this->canReportOn($user, $role, $regionId, $adminId, $schId)) {
				return $this->respondWithStatus([
					'message' => t('User access to area forbidden'),
				], Response::HTTP_FORBIDDEN);
            }

291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
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
            $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);
                }

                //χωρητικότητα για όλο το σχολείο
366
367
368
                $capacityTotal = array_reduce($capacity, function ($sum, $v) {
                        return $sum += ($v > 0) ? intval($v) : 0;
                    }, 0);
369
370
371
372
373
374
375
376
377
378

                //βρες αριθμό μαθητών γισ κάθε τάξη
                $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, '=')
379
                        ->condition('eStudent.currentclass', $classId, '=');
380
381
382
383
                    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);
384
385
                    } elseif (isset($capacity[$classId-1]) && $capacity[$classId-1] == -1) {
                        $perc_str = '-';
386
387
388
389
                    } else {
                        $perc_str = '-';
                        $stat_complete = false;
                    }
390
                    array_push($perc, $perc_str);
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
                }

                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]
				));
            }
411

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

415
416
417
        catch (\Exception $e) {
            $this->logger->warning($e->getMessage());
            return $this->respondWithStatus([
418
                "message" => t("An unexpected problem occured during report")
419
420
421
			], Response::HTTP_INTERNAL_SERVER_ERROR);
        }
    }
422

423
424
425
426
427
428
429
430
    public function makeReportAllStat(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);
            }
431

432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
            //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" || $role === "regioneduadmin" || $role === "eduadmin") {
447
                    $validRole = $role;
448
449
450
                    break;
                }
            }
451
            if ($validRole === false) {
452
453
454
455
456
				return $this->respondWithStatus([
					'message' => t("User Invalid Role"),
				], Response::HTTP_FORBIDDEN);
            }

457
458
459
460
461
462
            if (!$this->canReportOn($user, $role, $regionId, $adminId, $schId)) {
				return $this->respondWithStatus([
					'message' => t('User access to area forbidden'),
				], Response::HTTP_FORBIDDEN);
            }

463
464
465
466
            $limitup = $this->retrieveUpLimit();

            $list = array();

467
468
469
470
471
472
473
            // βρες όλα τα σχολεία που πληρούν τα κριτήρια / φίλτρα
            $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']);
474
475
476
477
478
479
480
481
482
483
484
            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);

485
            foreach ($epalSchools as $epalSchool) { // για κάθε σχολείο
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500

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

                $smallClass = array();

                $numClassSec = 0;
                $numClassCour = 0;
                $numClassCour_D = 0;

501
                // εύρεση αριθμού μαθητών για κάθε τομέα της Β' τάξης
502
                if ($classId === "0" || $classId === "2") {
503
504
505
506
507
508
509
510
511
512
513
                    $sCon = $this->connection->select('eepal_sectors_in_epal_field_data', 'eSchool');
			        $sCon->join('eepal_sectors_field_data', 'eSectors', 'eSectors.id = eSchool.sector_id');
			        $sCon->leftJoin('epal_student_class', 'eStudent', 
                        'eStudent.epal_id = eSchool.epal_id ' .
                        'AND eStudent.specialization_id = eSchool.sector_id ' .
                        'AND eStudent.currentclass = 2');
                    $sCon->fields('eSchool', array('sector_id','capacity_class_sector'))
                        ->fields('eSectors', ['name'])
                        ->groupBy('sector_id')
                        ->groupBy('capacity_class_sector')
                        ->groupBy('eSectors.name')
514
                        ->condition('eSchool.epal_id', $epalSchool->id, '=');
515
                    $sCon->addExpression('count(eStudent.id)', 'eStudent_count');
516
517
518
519
520
521
522
                    if ($sectorId != "0") {
                        $sCon->condition('eSchool.sector_id', $sectorId, '=');
                    }

                    $sectorsInEpals = $sCon->execute()->fetchAll(\PDO::FETCH_OBJ);

                    foreach ($sectorsInEpals as $sectorsInEpal) {
523
524
525
526
                        array_push($regionColumn, $epalSchool->eRegion_name);
                        array_push($adminColumn, $epalSchool->eAdmin_name);
                        array_push($schoolNameColumn, $epalSchool->name);
                        array_push($schoolSectionColumn, 'Β τάξη / ' . $sectorsInEpal->name);
527

528
529
530
                        $numStud = $sectorsInEpal->eStudent_count;
                        $smCl = $this->isSmallClass($epalSchool->id, $numStud, "2", $sectorsInEpal->sector_id, $epalSchool->metathesis_region);
                        array_push($smallClass, $smCl);
531

532
533
534
535
                        array_push($numColumn, $numStud);
                        $capacityColumnValue = $sectorsInEpal->capacity_class_sector * $limitup;
                        array_push($capacityColumn, $capacityColumnValue);
                        array_push($percColumn, $capacityColumnValue > 0 ? number_format($numStud / $capacityColumnValue * 100, 2) : 0);
536

537
538
539
                        $numClassSec += $sectorsInEpal->capacity_class_sector;
                    }
                } // end εύρεση αριθμού μαθητών για κάθε τομέα της Β' τάξης
540

541
                // εύρεση αριθμού μαθητών για κάθε ειδικότητα της Γ' τάξης
542
                if ($classId === "0" || $classId === "3") {
543
544
545
546
547
548
549
550
551
552
553
                    $sCon = $this->connection->select('eepal_specialties_in_epal_field_data', 'eSchool');
			        $sCon->join('eepal_specialty_field_data', 'eSpecialties', 'eSpecialties.id = eSchool.specialty_id');
			        $sCon->leftJoin('epal_student_class', 'eStudent', 
                        'eStudent.epal_id = eSchool.epal_id ' .
                        'AND eStudent.specialization_id = eSchool.specialty_id ' .
                        'AND eStudent.currentclass = 3');
                    $sCon->fields('eSchool', array('specialty_id', 'capacity_class_specialty'))
                        ->fields('eSpecialties', ['name'])
                        ->groupBy('specialty_id')
                        ->groupBy('capacity_class_specialty')
                        ->groupBy('eSpecialties.name')
554
                        ->condition('eSchool.epal_id', $epalSchool->id, '=');
555
                    $sCon->addExpression('count(eStudent.id)', 'eStudent_count');
556
557
                    if ($courseId !== "0") {
                        $sCon->condition('eSchool.specialty_id', $courseId, '=');
558
559
                    } else if ($sectorId !== "0") {
                        $sCon->condition('eSpecialties.sector_id', $sectorId, '=');
560
561
562
563
                    }
                    $specialtiesInEpals = $sCon->execute()->fetchAll(\PDO::FETCH_OBJ);

                    foreach ($specialtiesInEpals as $specialtiesInEpal) {
564
565
566
567
                        array_push($regionColumn, $epalSchool->eRegion_name);
                        array_push($adminColumn, $epalSchool->eAdmin_name);
                        array_push($schoolNameColumn, $epalSchool->name);
                        array_push($schoolSectionColumn, 'Γ τάξη / ' . $specialtiesInEpal->name );
568

569
570
571
                        $numStud = $specialtiesInEpal->eStudent_count;
                        $smCl = $this->isSmallClass($epalSchool->id, $numStud, "3", $specialtiesInEpal->specialty_id, $epalSchool->metathesis_region);
                        array_push($smallClass, $smCl);
572

573
574
575
576
                        array_push($numColumn, $numStud);
                        $capacityColumnValue = $specialtiesInEpal->capacity_class_specialty * $limitup;
                        array_push($capacityColumn, $capacityColumnValue);
                        array_push($percColumn, $capacityColumnValue > 0 ? number_format($numStud / $capacityColumnValue * 100, 2) : 0);
577

578
579
580
                        $numClassCour += $specialtiesInEpal->capacity_class_specialty;
                    }
                } // end εύρεση αριθμού μαθητών για κάθε ειδικότητα της Γ' τάξης
581

582
                // εύρεση αριθμού μαθητών για κάθε ειδικότητα της Δ' τάξης
583
584
                if ($epalSchool->operation_shift === "ΕΣΠΕΡΙΝΟ") {
                    if ($classId === "0" || $classId === "4") {
585
586
587
588
589
590
591
592
593
594
595
                        $sCon = $this->connection->select('eepal_specialties_in_epal_field_data', 'eSchool');
                        $sCon->join('eepal_specialty_field_data', 'eSpecialties', 'eSpecialties.id = eSchool.specialty_id');
                        $sCon->leftJoin('epal_student_class', 'eStudent', 
                            'eStudent.epal_id = eSchool.epal_id ' .
                            'AND eStudent.specialization_id = eSchool.specialty_id ' .
                            'AND eStudent.currentclass = 4');
                        $sCon->fields('eSchool', array('specialty_id', 'capacity_class_specialty_d'))
                            ->fields('eSpecialties', ['name'])
                            ->groupBy('specialty_id')
                            ->groupBy('capacity_class_specialty_d')
                            ->groupBy('eSpecialties.name')
596
                            ->condition('eSchool.epal_id', $epalSchool->id, '=');
597
                        $sCon->addExpression('count(eStudent.id)', 'eStudent_count');
598
599
                        if ($courseId !== "0") {
                            $sCon->condition('eSchool.specialty_id', $courseId, '=');
600
601
                        } else if ($sectorId !== "0") {
                            $sCon->condition('eSpecialties.sector_id', $sectorId, '=');
602
603
604
605
606
                        }

                        $specialtiesInEpals = $sCon->execute()->fetchAll(\PDO::FETCH_OBJ);

                        foreach ($specialtiesInEpals as $specialtiesInEpal) {
607
608
609
610
611
612
613
614
615
616
617
618
619
620
                            array_push($regionColumn, $epalSchool->eRegion_name);
                            array_push($adminColumn, $epalSchool->eAdmin_name);
                            array_push($schoolNameColumn, $epalSchool->name);
                            array_push($schoolSectionColumn, 'Δ τάξη / ' . $specialtiesInEpal->name );

                            $numStud = $specialtiesInEpal->eStudent_count;
                            $smCl = $this->isSmallClass($epalSchool->id, $numStud, "4", $specialtiesInEpal->specialty_id, $epalSchool->metathesis_region);
                            array_push($smallClass, $smCl);

                            array_push($numColumn, $numStud);
                            $capacityColumnValue = $specialtiesInEpal->capacity_class_specialty_d * $limitup;
                            array_push($capacityColumn, $capacityColumnValue);
                            array_push($percColumn, $capacityColumnValue > 0 ? number_format($numStud / $capacityColumnValue * 100, 2) : 0);

621
                            $numClassCour_D += $specialtiesInEpal->capacity_class_specialty_d;
622
623
624
                        }
                    }
                } //end "ΕΣΠΕΡΙΝΟ" εύρεση αριθμού μαθητών για κάθε ειδικότητα της Δ' τάξης
625

626
                // εύρεση αριθμού μαθητών για κάθε τάξη
627
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
656
657
658
659
660
661
662
663
664
665
666
667
                $numClasses = array();
                array_push($numClasses, $epalSchool->capacity_class_a);
                array_push($numClasses, $numClassSec);
                array_push($numClasses, $numClassCour);
                array_push($numClasses, $numClassCour_D);

                if ($sectorId === "0" && $courseId === "0") {
                    $clidstart = 1;
                    $clidend = 4;

                    if ($classId !== "0") {
                        $clidstart = $classId;
                        $clidend = $classId;
                        if ($classId === "1") {
                            array_push($schoolSectionColumn, 'Α τάξη');
                        } elseif ($classId === "2") {
                            array_push($schoolSectionColumn, 'Β τάξη');
                        } elseif ($classId === "3") {
                            array_push($schoolSectionColumn, 'Γ τάξη');
                        } elseif ($classId === "4") {
                            array_push($schoolSectionColumn, 'Δ τάξη');
                        }
                    } else {
                        array_push($schoolSectionColumn, 'Α τάξη');
                        array_push($schoolSectionColumn, 'Β τάξη');
                        array_push($schoolSectionColumn, 'Γ τάξη');
                        array_push($schoolSectionColumn, 'Δ τάξη');
                    }

                    for ($clId = $clidstart; $clId <= $clidend; $clId++) {
                        $sCon = $this->connection
                            ->select('epal_student_class', 'eStudent')
                            ->fields('eStudent', array('id', 'epal_id', 'currentclass'))
                            ->condition('eStudent.epal_id', $epalSchool->id, '=')
                            ->condition('eStudent.currentclass', $clId, '=');
                        $numStud =  $sCon->countQuery()->execute()->fetchField();

                        $smCl = $this->isSmallClass($epalSchool->id, $numStud, "1", "-1", $epalSchool->metathesis_region);
                        array_push($smallClass, $smCl);

                        array_push($schoolNameColumn, $epalSchool->name);
668
669
                        array_push($regionColumn, $epalSchool->eRegion_name);
                        array_push($adminColumn, $epalSchool->eAdmin_name);
670
                        array_push($numColumn, $numStud);
671
672
673
                        $capacityColumnValue = ($numClasses[$clId-1] * $limitup);
                        array_push($capacityColumn, $capacityColumnValue);
                        array_push($percColumn, $capacityColumnValue > 0 ? number_format($numStud / $capacityColumnValue * 100, 2) : 0);
674
                    }
675
                } // end εύρεση αριθμού μαθητών για κάθε τάξη
676
677

                for ($j = 0; $j < sizeof($schoolNameColumn); $j++) {
678
679
                    // αν έγινε αίτημα για εμφάνιση ολιγομελών και είναι το τρέχον τμήμα ολιγομελές
                    if (($finalized === "1") || 
680
                        ($finalized === "0" && $smallClass[$j] === self::SMALL_CLS
681
682
                            && $schoolSectionColumn[$j] !== "Β τάξη" && $schoolSectionColumn[$j] !== "Γ τάξη" 
                            && $schoolSectionColumn[$j] !== "Δ τάξη")) {
683
684
685
686
687
688
689
690
691
692
693
                            array_push($list, (object) array(
                                'name' => $schoolNameColumn[$j],
                                'region' => $regionColumn[$j],
                                'admin' => $adminColumn[$j],
                                'section' => $schoolSectionColumn[$j],
                                'num' => $numColumn[$j],
                                'capacity' => $capacityColumn[$j],
                                'percentage' => $percColumn[$j],
                            ));
                    }
                }
694
            } //end loop για κάθε σχολείο
695

696
697
            return $this->respondWithStatus($list, Response::HTTP_OK);
        } 
698
699
700
        catch (\Exception $e) {
            $this->logger->warning($e->getMessage());
            return $this->respondWithStatus([
701
702
                "message" => t("An unexpected problem occured in makeReportCompleteness Method")
            ], Response::HTTP_INTERNAL_SERVER_ERROR);
703
704
        }
    }
705

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

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

711
712
713
714
        if ($limitDown === self::NO_CLASS_LIM_DOWN) {
            return self::NO_CLASS_LIM_DOWN;
        } elseif ($limitDown === self::ERR_DB) {
            return self::ERR_DB;
715
        }
716

717
718
        $numStudents = (int) $numStud;
        if (($numStudents < $limitDown) /*&& ($numStudents > 0)*/) {
719
            return self::SMALL_CLS;
720
        } else {
721
            return self::NON_SMALL_CLS;
722
723
        }
    }
724
725


726
727
728
729
    /**
     * Fetch epal_class_limits data in memory; will save time.
     *
     */
730
731
    private function retrieveLimitDown($classId, $regionId)
    {
732
        static $data = [];
733

734
735
736
737
738
739
740
741
742
743
744
        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 {
745
                    return self::NO_CLASS_LIM_DOWN;                    
746
747
748
                }
            } catch (\Exception $e) {
                $this->logger->warning($e->getMessage());
749
                return self::ERR_DB;
750
751
752
            }
        }

753
754
755
        if (isset($data["$classId"]["$regionId"])) {
            return $data["$classId"]["$regionId"];
        } else {
756
            return self::NO_CLASS_LIM_DOWN;
757
758
        }
    }
759
760
761

    public function retrieveUserRegistryNo(Request $request)
    {
762

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

770
771
772
773
774
            //user validation
            $authToken = $request->headers->get('PHP_AUTH_USER');
            $users = $this->entityTypeManager->getStorage('user')->loadByProperties(array('name' => $authToken));
            $user = reset($users);
            if (!$user) {
775
				return $this->respondWithStatus([
776
777
778
779
780
781
782
783
784
785
786
787
788
789
					'message' => t("User not found"),
				], Response::HTTP_FORBIDDEN);
            }

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

795
796
797
798
            return $this->respondWithStatus([
				'message' => t("retrieve ID successful"),
				'id' => $user->init->value,
            ], Response::HTTP_OK);
799

800
801
802
803
804
805
806
        } 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);
        }
    }
807

808
809
    public function makeReportNoCapacity(Request $request, $capacityEnabled)
    {
810

811
812
813
814
815
816
        try {
            if (!$request->isMethod('GET')) {
                 return $this->respondWithStatus([
					"message" => t("Method Not Allowed")
				], Response::HTTP_METHOD_NOT_ALLOWED);
            }
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
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
            //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('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, '=');

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

            foreach ($epalSchools as $epalSchool) {       //για κάθε σχολείο

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

                //εύρεση ονόματος ΠΔΕ που ανήκει το σχολείο
                $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);

                //εύρεση ονόματος ΔΙΔΕ που ανήκει το σχολείο
                $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);

                //εύρεση αριθμού τμημάτων (χωρητικότητα) για κάθε τμήμα της Α' τάξης
                //$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);
                }

                //εύρεση αριθμού τμημάτων (χωρητικότητα) για κάθε τομέα της Β' τάξης
                //ΠΡΟΣΟΧΗ: χειρισμ΄ός τιμών: 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);
                        array_push($schoolNameColumn, $epalSchool->name);
                        array_push($schoolSectionColumn, 'Β\' τάξη / ' . $sectorsNamesInEpal->name );
                        array_push($capacityColumn, $sectorsInEpal->capacity_class_sector);
                    }   //end foreach sectorsNamesInEpals
                }   //end foreach sectorsInEpal

                //εύρεση αριθμού τμημάτων (χωρητικότητα) για κάθε ειδικότητα της Γ' τάξης
                $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, '=');

                if ($capacityEnabled === "0") {
					$sCon->condition( db_or()
						//->condition('eSchool.capacity_class_specialty', 0, '=')
						->condition('eSchool.capacity_class_specialty', null, 'is')  ) ;
                }

                $specialtiesInEpals = $sCon->execute()->fetchAll(\PDO::FETCH_OBJ);

                foreach ($specialtiesInEpals as $specialtiesInEpal) {
					$sCon = $this->connection
						->select('eepal_specialty_field_data', 'eSpecialties')
                        ->fields('eSpecialties', array('name'))
                        ->condition('eSpecialties.id', $specialtiesInEpal->specialty_id, '=');

					$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

                //εύρεση αριθμού τμημάτων (χωρητικότητα) για κάθε ειδικότητα της Δ' τάξης
                $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, '=');

                if ($capacityEnabled === "0") {
					$sCon->condition( db_or()
						//->condition('eSchool.capacity_class_specialty_d', 0, '=')
						->condition('eSchool.capacity_class_specialty_d', null, 'is')  ) ;
                }

                $specialtiesInEpals = $sCon->execute()->fetchAll(\PDO::FETCH_OBJ);

                foreach ($specialtiesInEpals as $specialtiesInEpal) {
					$sCon = $this->connection
						->select('eepal_specialty_field_data', 'eSpecialties')
                        ->fields('eSpecialties', array('name'))
                        ->condition('eSpecialties.id', $specialtiesInEpal->specialty_id, '=');

					$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);
                            array_push($schoolNameColumn, $epalSchool->name);
                            array_push($schoolSectionColumn, 'Δ\' τάξη / ' . $specialtiesNamesInEpal->name );
                            array_push($capacityColumn, $specialtiesInEpal->capacity_class_specialty_d);
                        }
                    }   //end foreach $specialtiesNamesInEpal
                } //end foreach $specialtiesInEpals

                //εισαγωγή εγγραφών στο tableschema
                for ($j = 0; $j < sizeof($schoolNameColumn); $j++) {
					array_push($list, (object) array(
						'name' => $schoolNameColumn[$j],
						'region' => $regionColumn[$j],
						'admin' => $adminColumn[$j],
						'section' => $schoolSectionColumn[$j],
						'capacity' => $capacityColumn[$j],
					));
                }
            } //end foreach school

            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 makeReportNoCapacity Method")
			], Response::HTTP_INTERNAL_SERVER_ERROR);
        }
    }
1007

1008
1009
    public function retrieveUpLimit()
    {
1010

1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
        //βρες ανώτατο επιτρεπόμενο όριο μαθητών
        //$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;
        }
    }
1028

1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
    /**
     * 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))
            );
        } else {
            $can = false;
        }
        return $can;
    }

    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;
        }
    }

1088
1089
1090
1091
1092
1093
    private function respondWithStatus($arr, $s)
    {
        $res = new JsonResponse($arr);
        $res->setStatusCode($s);
        return $res;
    }
1094
}