ApplicationSubmit.php 14.4 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
    protected $entityTypeManager;
    protected $logger;
    protected $connection;
35
    protected $client; // client consumer
36

37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
    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);
52
    }
53

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

63
64
65
66
67
68
69
    public function appSubmit(Request $request) {
    		if (!$request->isMethod('POST')) {
    			return $this->respondWithStatus([
    					"error_code" => 2001
    				], Response::HTTP_METHOD_NOT_ALLOWED);
        	}
    		$applicationForm = array();
70

71
    		$content = $request->getContent();
72

73
74
75
76
    		if (!empty($content)) {
    			$applicationForm = json_decode($content, TRUE);
    		}
    		else {
77
    			return $this->respondWithStatus([
78
79
    					"error_code" => 5002
    				], Response::HTTP_BAD_REQUEST);
80
    		}
81

82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
        $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']);
98
        }
99
100
101
102
103
104
105
        catch (\Exception $e) {
            print_r($e->getMessage());
            unset($crypt);
      			$this->logger->warning($e->getMessage());
      			return $this->respondWithStatus([
      					"error_code" => 5001
      				], Response::HTTP_INTERNAL_SERVER_ERROR);
106
        }
107
        unset($crypt);
108

109
        $transaction = $this->connection->startTransaction();
110
111
112
113
114
115
116
117
118
119
    		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);
        		}
120

121
122

			    $student = array(
123
124
125
126
127
128
129
130
131
132
133
134
135
136
                '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(),
137
138
139
140
141
142
143
144
145
146
147

                'name' => $name_encoded,
                'studentsurname' => $studentsurname_encoded,
        				'birthdate' => $applicationForm[0]['studentbirthdate'],
                'fatherfirstname' => $fatherfirstname_encoded,
                'motherfirstname' => $motherfirstname_encoded,
                'regionaddress' => $regionaddress_encoded,
                'regionarea' => $regionarea_encoded,
                'regiontk' => $regiontk_encoded,
                'certificatetype' => $certificatetype_encoded,
        				'graduation_year' => $applicationForm[0]['graduation_year'],
148
                'lastschool_registrynumber' => $applicationForm[0]['lastschool_registrynumber'],
149
150
                'lastschool_unittypeid' => $applicationForm[0]['lastschool_unittypeid'],
                'lastschool_schoolname' => $applicationForm[0]['lastschool_schoolname'],
151
152
                'lastschool_schoolyear' => $applicationForm[0]['lastschool_schoolyear'],
                'lastschool_class' => $applicationForm[0]['lastschool_class'],
153
154
155
156
157
        				'currentclass' => $applicationForm[0]['currentclass'],
                'guardian_name' => $guardian_name_encoded,
                'guardian_surname' => $guardian_surname_encoded,
                'guardian_fathername' => $guardian_fathername_encoded,
                'guardian_mothername' => $guardian_mothername_encoded,
158
                'agreement' => $applicationForm[0]['disclaimer_checked'],
159
160
161
                'relationtostudent' => $relationtostudent_encoded,
                'telnum' => $telnum_encoded
                    );
162

163
164
            if (($errorCode = $this->validateStudent($student)) > 0) {
                return $this->respondWithStatus([
165
166
                    "error_code" => $errorCode
                ], Response::HTTP_OK);
167
            }
168

169
170
171
172
            $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));
173
                $epalSchool = reset($epalSchools);
174
            /*  if (!$epalSchool){
175
176
177
        			return $this->respondWithStatus([
        					"error_code" => 4004
        				], Response::HTTP_FORBIDDEN);
178
179
        		} else { */
                if ($epalSchool) {
180
                    $student['currentepal'] = $epalSchool->id();
181
182
                } else {
                    $student['currentepal'] = 0;
183
184
185
186
187
                }
            } else {
                $student['currentepal'] = 0;
            }

188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
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
            $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 δεν επιλέχθηκε το πλαίσιο συμφωνης γνώμης
247
248
249
250
     *  1002 λανθασμένο τελευταίο έτος φοίτησης
     *  1003 λανθασμένη ημερομηνία
     *  8000 μη αναμενόμενο λάθος
     *  8001 δικτυακό λάθος κλήσης υπηρεσίας επιβεβαίωσης στοιχείων
251
252
253
254
255
256
257
258
259
260
261
262
263
264
     *  8002 τα στοιχεία φοίτησης δεν επικυρώθηκαν
     *  8003 τα στοιχεία φοίτησης δεν είναι έγκυρα
     */
    private function validateStudent($student)
    {
        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);
265
        if ((count($date_parts) !== 3) ||
266
267
268
            (checkdate($date_parts[1], $date_parts[2], $date_parts[0]) !== true)) {
            return 1003;
        }
269
/*        $birthdate = "{$date_parts[2]}-{$date_parts[1]}-{$date_parts[0]}";
270

271
        // check as per specs:
272
273
        // - can't check certification prior to 2014, pass through
        // - check certification if last passed class is gym
274
        // - check promotion if last passed class is not gym
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289

        $check_certification = true;
        $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;
290
        if (($check_certification === true) ||
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
            ($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
                );
                $pass = ($service_rv === true);
                if ($service_rv === true) {
                    $error_code = 0;
                } elseif ($service_rv === false) {
                    $error_code = 8002;
                } elseif ($service_rv === null) {
                    $error_code = 8003;
                } else {
                    // -1 is an exception and data is already validated
                    $error_code = 8001;
                }
            } catch (\Exception $e) {
                $pass = false;
                $error_code = 8000;
            }
        }

        // TODO REMOVE
        $this->logger->info(
            'check certification: [' . var_export($check_certification, true) . '] ' .
            'check promotion: [' . var_export($check_promotion, true) . '] ' .
331
            'pass: [' . var_export($pass, true) . '] ' .
332
333
334
335
336
337
338
339
340
341
342
343
            'check: ' . print_r([
                    $didactic_year_id,
                    $student['studentsurname'],
                    $student['name'],
                    $student['fatherfirstname'],
                    $student['motherfirstname'],
                    $birthdate,
                    $student['lastschool_registrynumber'],
                    $level_name
            ], true));
        // return 1000; // TODO stop here until all checks are finished

344
        return $error_code; */
345
    }
346
}