ApplicationSubmit.php 20 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
<?php

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 Drupal\Core\Database\Connection;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;

16 17
use Drupal\epal\Crypt;

18 19 20 21 22 23 24 25 26 27 28 29 30
use Drupal\epal\ClientConsumer;

class ApplicationSubmit extends ControllerBase
{

    const UNIT_TYPE_NIP = 1;
    const UNIT_TYPE_DIM = 2;
    const UNIT_TYPE_GYM = 3;
    const UNIT_TYPE_LYK = 4;
    const UNIT_TYPE_EPAL = 5;

    const CERT_GYM = 'Απολυτήριο Γυμνασίου';
    const CERT_LYK = 'Απολυτήριο Λυκείου';
31

32 33 34 35 36 37 38 39 40
    const VALID_NAMES_PATTERN = '/^[A-Za-zΑ-ΩΆΈΉΊΙΎΌΏα-ωάέήίΐύόώ \-]*$/mu';
    const VALID_UCASE_NAMES_PATTERN = '/^[A-ZΑ-Ω]{3,}[A-ZΑ-Ω \-]*$/mu';
    const VALID_ADDRESS_PATTERN = '/^[0-9A-Za-zΑ-ΩΆΈΉΊΎΌΏα-ωάέήίύόώ\/\. \-]*$/mu';
    const VALID_ADDRESSTK_PATTERN = '/^[0-9]{5}$/';
    const VALID_DIGITS_PATTERN = '/^[0-9]*$/';
    const VALID_TELEPHONE_PATTERN = '/^2[0-9]{9}$/';
    const VALID_YEAR_PATTERN = '/^(19[6789][0-9]|20[0-1][0-9])$/';
    const VALID_CAPACITY_PATTERN = '/[0-9]*$/';

41 42 43
    protected $entityTypeManager;
    protected $logger;
    protected $connection;
44
    protected $client; // client consumer
45

46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
    public function __construct(
        EntityTypeManagerInterface $entityTypeManager,
        Connection $connection,
        LoggerChannelFactoryInterface $loggerChannel
    ) {
        $this->entityTypeManager = $entityTypeManager;
        $this->connection = $connection;
        $this->logger = $loggerChannel->get('epal');

        $config = $this->config('epal.settings');
        $settings = [];
        foreach (['ws_endpoint', 'ws_username', 'ws_password', 'verbose', 'NO_SAFE_CURL'] as $setting) {
            $settings[$setting] = $config->get($setting);
        }
        $this->client = new ClientConsumer($settings, $entityTypeManager, $loggerChannel);
61
    }
62

63
    public static function create(ContainerInterface $container)
64 65
    {
        return new static(
66 67 68 69
            $container->get('entity_type.manager'),
            $container->get('database'),
            $container->get('logger.factory')
        );
70 71
    }

72 73 74 75 76 77 78 79
    public function appSubmit(Request $request)
    {
        if (!$request->isMethod('POST')) {
            return $this->respondWithStatus([
                "error_code" => 2001
            ], Response::HTTP_METHOD_NOT_ALLOWED);
        }
        $applicationForm = array();
80

81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
        $content = $request->getContent();
        if (!empty($content)) {
            $applicationForm = json_decode($content, true);
        } else {
            return $this->respondWithStatus([
                "error_code" => 5002
            ], Response::HTTP_BAD_REQUEST);
        }

        $epalConfigs = $this->entityTypeManager->getStorage('epal_config')->loadByProperties(array('name' => 'epal_config'));
        $epalConfig = reset($epalConfigs);
        if (!$epalConfig) {
            return $this->respondWithStatus([
                "error_code" => 3001
            ], Response::HTTP_FORBIDDEN);
        }
        if ($epalConfig->lock_application->value) {
            return $this->respondWithStatus([
                "error_code" => 3002
            ], Response::HTTP_FORBIDDEN);
101
        }
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119

        $crypt = new Crypt();
        try {
            $name_encoded = $crypt->encrypt($applicationForm[0]['name']);
            $studentsurname_encoded = $crypt->encrypt($applicationForm[0]['studentsurname']);
            $fatherfirstname_encoded = $crypt->encrypt($applicationForm[0]['fatherfirstname']);
            $motherfirstname_encoded = $crypt->encrypt($applicationForm[0]['motherfirstname']);
            $regionaddress_encoded = $crypt->encrypt($applicationForm[0]['regionaddress']);
            $regiontk_encoded = $crypt->encrypt($applicationForm[0]['regiontk']);
            $regionarea_encoded = $crypt->encrypt($applicationForm[0]['regionarea']);
            // $certificatetype_encoded = $crypt->encrypt($applicationForm[0]['certificatetype']);
            $relationtostudent_encoded = $crypt->encrypt($applicationForm[0]['relationtostudent']);
            $telnum_encoded = $crypt->encrypt($applicationForm[0]['telnum']);
            $guardian_name_encoded = $crypt->encrypt($applicationForm[0]['cu_name']);
            $guardian_surname_encoded = $crypt->encrypt($applicationForm[0]['cu_surname']);
            $guardian_fathername_encoded = $crypt->encrypt($applicationForm[0]['cu_fathername']);
            $guardian_mothername_encoded = $crypt->encrypt($applicationForm[0]['cu_mothername']);
        } catch (\Exception $e) {
120
            $this->logger->error($e->getMessage());
121 122 123
            return $this->respondWithStatus([
                "error_code" => 5001
            ], Response::HTTP_INTERNAL_SERVER_ERROR);
124
        }
125
        unset($crypt);
126

127
        $transaction = $this->connection->startTransaction();
128 129 130 131 132 133 134 135 136 137 138
        try {
            //insert records in entity: epal_student
            $authToken = $request->headers->get('PHP_AUTH_USER');
            $epalUsers = $this->entityTypeManager->getStorage('epal_users')->loadByProperties(array('authtoken' => $authToken));
            $epalUser = reset($epalUsers);
            if (!$epalUser) {
                return $this->respondWithStatus([
                    "error_code" => 4003
                ], Response::HTTP_FORBIDDEN);
            }

139
            $second_period = $epalConfig->activate_second_period->value;
140 141

            $student = array(
142 143 144 145 146 147 148 149 150 151 152 153 154 155
                'langcode' => 'el',
                'student_record_id' => 0,
                'sex' => 0,
                'fathersurname' => '',
                'mothersurname' => '',
                'studentamka' => '',
                'lastam' => '',
                'graduate_school' => 0,
                'apolytirio_id' => '',
                'currentsector' => '',
                'currentcourse' => '',
                'points' => 0,
                'user_id' => $epalUser->user_id->target_id,
                'epaluser_id' => $epalUser->id(),
156 157
                'name' => $name_encoded,
                'studentsurname' => $studentsurname_encoded,
158
                'birthdate' => $applicationForm[0]['studentbirthdate'],
159 160 161 162 163
                'fatherfirstname' => $fatherfirstname_encoded,
                'motherfirstname' => $motherfirstname_encoded,
                'regionaddress' => $regionaddress_encoded,
                'regionarea' => $regionarea_encoded,
                'regiontk' => $regiontk_encoded,
164 165
                // 'certificatetype' => $certificatetype_encoded,
                // 'graduation_year' => $applicationForm[0]['graduation_year'],
166
                'lastschool_registrynumber' => $applicationForm[0]['lastschool_registrynumber'],
167 168
                'lastschool_unittypeid' => $applicationForm[0]['lastschool_unittypeid'],
                'lastschool_schoolname' => $applicationForm[0]['lastschool_schoolname'],
169 170
                'lastschool_schoolyear' => $applicationForm[0]['lastschool_schoolyear'],
                'lastschool_class' => $applicationForm[0]['lastschool_class'],
171
                'currentclass' => $applicationForm[0]['currentclass'],
172 173 174 175
                'guardian_name' => $guardian_name_encoded,
                'guardian_surname' => $guardian_surname_encoded,
                'guardian_fathername' => $guardian_fathername_encoded,
                'guardian_mothername' => $guardian_mothername_encoded,
176
                'agreement' => $applicationForm[0]['disclaimer_checked'],
177
                'relationtostudent' => $relationtostudent_encoded,
178 179
                'telnum' => $telnum_encoded,
                'second_period' => $second_period,
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
            );

            if (($errorCode = $this->validateStudent(array_merge(
                    $student, [
                        'name' => $applicationForm[0]['name'],
                        'studentsurname' => $applicationForm[0]['studentsurname'],
                        'fatherfirstname' => $applicationForm[0]['fatherfirstname'],
                        'motherfirstname' => $applicationForm[0]['motherfirstname'],
                        'regionaddress' => $applicationForm[0]['regionaddress'],
                        'regiontk' => $applicationForm[0]['regiontk'],
                        'regionarea' => $applicationForm[0]['regionarea'],
                        'relationtostudent' => $applicationForm[0]['relationtostudent'],
                        'telnum' => $applicationForm[0]['telnum'],
                        'guardian_name' => $applicationForm[0]['cu_name'],
                        'guardian_surname' => $applicationForm[0]['cu_surname'],
                        'guardian_fathername' => $applicationForm[0]['cu_fathername'],
                        'guardian_mothername' => $applicationForm[0]['cu_mothername']
197 198
                    ]), sizeof($applicationForm[1]), $applicationForm[0]['currentclass'],
                    $applicationForm[3]['sectorfield_id'],
199 200
                    $applicationForm[3]['coursefield_id'],
                    $epalUser)) > 0) {
201
                return $this->respondWithStatus([
202 203
                    "error_code" => $errorCode
                ], Response::HTTP_OK);
204
            }
205

206 207 208 209
            $lastSchoolRegistryNumber = $student['lastschool_registrynumber'];
            $lastSchoolYear = (int)(substr($student['lastschool_schoolyear'], -4));
            if ((int)date("Y") === $lastSchoolYear && (int)$student['lastschool_unittypeid'] === 5) {
                $epalSchools = $this->entityTypeManager->getStorage('eepal_school')->loadByProperties(array('registry_no' => $lastSchoolRegistryNumber));
210
                $epalSchool = reset($epalSchools);
211 212 213 214 215
                /*  if (!$epalSchool){
                return $this->respondWithStatus([
                        "error_code" => 4004
                    ], Response::HTTP_FORBIDDEN);
                } else { */
216
                if ($epalSchool) {
217
                    $student['currentepal'] = $epalSchool->id();
218 219
                } else {
                    $student['currentepal'] = 0;
220 221 222 223 224
                }
            } else {
                $student['currentepal'] = 0;
            }

225 226 227 228 229 230 231 232 233 234 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 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
            $entity_storage_student = $this->entityTypeManager->getStorage('epal_student');
            $entity_object = $entity_storage_student->create($student);
            $entity_storage_student->save($entity_object);

            $created_student_id = $entity_object->id();

            for ($i = 0; $i < sizeof($applicationForm[1]); $i++) {
                $epalchosen = array(
                    'student_id' => $created_student_id,
                    'epal_id' => $applicationForm[1][$i]['epal_id'],
                    'choice_no' => $applicationForm[1][$i]['choice_no']
                );
                $entity_storage_epalchosen = $this->entityTypeManager->getStorage('epal_student_epal_chosen');
                $entity_object = $entity_storage_epalchosen->create($epalchosen);
                $entity_storage_epalchosen->save($entity_object);
            }

            if ($applicationForm[0]['currentclass'] === "3" || $applicationForm[0]['currentclass'] === "4") {
                $course = array(
                    'student_id' => $created_student_id,
                    'coursefield_id' => $applicationForm[3]['coursefield_id']
                );
                $entity_storage_course = $this->entityTypeManager->getStorage('epal_student_course_field');
                $entity_object = $entity_storage_course->create($course);
                $entity_storage_course->save($entity_object);
            } elseif ($applicationForm[0]['currentclass'] === "2") {
                $sector = array(
                    'student_id' => $created_student_id,
                    'sectorfield_id' => $applicationForm[3]['sectorfield_id']
                );
                $entity_storage_sector = $this->entityTypeManager->getStorage('epal_student_sector_field');
                $entity_object = $entity_storage_sector->create($sector);
                $entity_storage_sector->save($entity_object);
            }
            return $this->respondWithStatus([
                "error_code" => 0
            ], Response::HTTP_OK);
        } catch (\Exception $e) {
            $this->logger->warning($e->getMessage());
            $transaction->rollback();

            return $this->respondWithStatus([
                "error_code" => 5001
            ], Response::HTTP_INTERNAL_SERVER_ERROR);
        }
    }

    private function respondWithStatus($arr, $s)
    {
        $res = new JsonResponse($arr);
        $res->setStatusCode($s);
        return $res;
    }

    /**
     *
     * @return int error code ελέγχου; 0 εάν ο έλεγχος επιτύχει, μη μηδενικό εάν αποτύχει:
     *  1001 δεν επιλέχθηκε το πλαίσιο συμφωνης γνώμης
283 284
     *  1002 λανθασμένο τελευταίο έτος φοίτησης
     *  1003 λανθασμένη ημερομηνία
285
     *  1004-> 1023: λανθασμένα πεδία αίτησης
286 287
     *  8000 μη αναμενόμενο λάθος
     *  8001 δικτυακό λάθος κλήσης υπηρεσίας επιβεβαίωσης στοιχείων
288 289 290
     *  8002 τα στοιχεία φοίτησης δεν επικυρώθηκαν
     *  8003 τα στοιχεία φοίτησης δεν είναι έγκυρα
     */
291
    private function validateStudent($student, $numberOfSchools, $chosenClass, $chosenSector, $chosenCourse, $epalUser = null)
292
    {
293
        $error_code = 0;
294 295 296 297 298 299 300 301 302
        if ($numberOfSchools < 1) {
            return 1000;
        }
        if ($chosenClass === "2" && !isset($chosenSector)) {
            return 999;
        }
        if (($chosenClass === "3" || $chosenClass === "4") && !isset($chosenCourse)) {
            return 998;
        }
303 304 305 306 307 308 309 310 311
        if (!$student["agreement"]) {
            return 1001;
        }
        if (!$student["lastschool_schoolyear"] || strlen($student["lastschool_schoolyear"]) !== 9) {
            return 1002;
        }

        // date in YYY-MM-DD, out d-m-Y
        $date_parts = explode('-', $student['birthdate'], 3);
312
        if ((count($date_parts) !== 3) ||
313 314 315
            (checkdate($date_parts[1], $date_parts[2], $date_parts[0]) !== true)) {
            return 1003;
        }
316
        if (intval($date_parts[0]) >= ((int)date("Y") - 13)) {
317
            return 1003;
318
        }
319
        $birthdate = "{$date_parts[2]}-{$date_parts[1]}-{$date_parts[0]}";
320

321
        if (preg_match(self::VALID_UCASE_NAMES_PATTERN, $student["name"]) !== 1) {
322 323
            return 1004;
        }
324
        if (preg_match(self::VALID_UCASE_NAMES_PATTERN, $student["studentsurname"]) !== 1) {
325 326
            return 1005;
        }
327
        if (preg_match(self::VALID_UCASE_NAMES_PATTERN, $student["fatherfirstname"]) !== 1) {
328 329
            return 1006;
        }
330
        if (preg_match(self::VALID_UCASE_NAMES_PATTERN, $student["motherfirstname"]) !== 1) {
331 332
            return 1007;
        }
333
        if (preg_match(self::VALID_ADDRESS_PATTERN, $student["regionaddress"]) !== 1) {
334 335
            return 1008;
        }
336
        if (preg_match(self::VALID_ADDRESSTK_PATTERN, $student["regiontk"]) !== 1) {
337 338
            return 1009;
        }
339
        if (preg_match(self::VALID_NAMES_PATTERN, $student["regionarea"]) !== 1) {
340 341
            return 1010;
        }
342
        if (!$student["currentclass"] || ($student["currentclass"] !== "1" && $student["currentclass"] !== "2" && $student["currentclass"] !== "3" && $student["currentclass"] !== "4")) {
343 344 345 346 347
            return 1013;
        }
        if (!$student["relationtostudent"]) {
            return 1014;
        }
348
        if (preg_match(self::VALID_TELEPHONE_PATTERN, $student["telnum"]) !== 1) {
349 350
            return 1015;
        }
351
        if (preg_match(self::VALID_NAMES_PATTERN, $student["guardian_name"]) !== 1) {
352 353
            return 1016;
        }
354
        if (preg_match(self::VALID_NAMES_PATTERN, $student["guardian_surname"]) !== 1) {
355 356
            return 1017;
        }
357
        if (preg_match(self::VALID_NAMES_PATTERN, $student["guardian_fathername"]) !== 1) {
358 359
            return 1018;
        }
360
        if (preg_match(self::VALID_NAMES_PATTERN, $student["guardian_mothername"]) !== 1) {
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
            return 1019;
        }
        if (!$student["lastschool_registrynumber"]) {
            return 1020;
        }
        if (!$student["lastschool_unittypeid"]) {
            return 1021;
        }
        if (!$student["lastschool_schoolname"]) {
            return 1022;
        }
        if (!$student["lastschool_class"]) {
            return 1023;
        }

376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
        // second period: check if application exists
        if ($student['second_period'] == 1 && $epalUser !== null) {

            $esQuery = $this->connection->select('epal_student', 'es')
                                    ->fields('es',
                                    array('name',
                                            'studentsurname',
                                            'birthdate',
                                        ));
            $esQuery->condition('es.epaluser_id', $epalUser->id(), '=');

            $existing = $esQuery->execute()->fetchAll(\PDO::FETCH_OBJ);

/*            $existing = $this->entityTypeManager->getStorage('epal_student')
                ->loadByProperties(['epaluser_id' => $epalUser->id->value]); */
            if ($existing && sizeof($existing) > 0) {
                $crypt = new Crypt();
                foreach ($existing as $candidate) {
                    if (($crypt->decrypt($candidate->name) == $student['name'])
                        && ($crypt->decrypt($candidate->studentsurname) == $student['studentsurname'])
                        && ($candidate->birthdate == $student['birthdate'])
                        ) {
                        return 8004;
                    }
                }
            }
        }

404
        // check as per specs:
405 406
        // - can't check certification prior to 2014, pass through
        // - check certification if last passed class is gym
407
        // - check promotion if last passed class is not gym
408

409
/*        $check_certification = true;
410 411 412 413 414 415 416 417 418 419 420 421 422
        $check_promotion = true;
        if (intval($student['lastschool_unittypeid']) == self::UNIT_TYPE_GYM) {
            $check_promotion = false;
            $check_certification = true;
        }
        if (intval($student['graduation_year']) < 2014 &&
            intval($student['certificatetype']) == self::CERT_GYM) {
            $check_certification = false;
        }

        // now check service
        $pass = true;
        $error_code = 0;
423
        if (($check_certification === true) ||
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
            ($check_promotion === true)) {
            if ($check_promotion === true) {
                $service = 'getStudentEpalPromotion';
            } else {
                $service = 'getStudentEpalCertification';
            }
            try {
                $didactic_year_id = $this->client->getDidacticYear(substr($student["lastschool_schoolyear"], -4, 4));
                $level_name = $this->client->getLevelName($student['lastschool_class']);
                $service_rv = $this->client->$service(
                    $didactic_year_id,
                    $student['studentsurname'],
                    $student['name'],
                    $student['fatherfirstname'],
                    $student['motherfirstname'],
                    $birthdate,
                    $student['lastschool_registrynumber'],
                    $level_name
                );
443 444
                $pass = ($service_rv == 'true');
                if ($service_rv == 'true') {
445
                    $error_code = 0;
446
                } elseif ($service_rv == 'false') {
447
                    $error_code = 8002;
448
                } elseif ($service_rv == 'null') {
449 450 451 452 453 454 455 456 457
                    $error_code = 8003;
                } else {
                    // -1 is an exception and data is already validated
                    $error_code = 8001;
                }
            } catch (\Exception $e) {
                $pass = false;
                $error_code = 8000;
            }
458
        } */
459

460
        return $error_code;
461
    }
462
}