ApplicationSubmit.php 7.47 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?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;

class ApplicationSubmit extends ControllerBase {
17

18
19
20
    protected $entityTypeManager;
    protected $logger;
    protected $connection;
21

22
23
24
25
26
27
28
	public function __construct(
		EntityTypeManagerInterface $entityTypeManager,
		Connection $connection,
		LoggerChannelFactoryInterface $loggerChannel)
		{
			$this->entityTypeManager = $entityTypeManager;
			$this->connection = $connection;
29
			$this->logger = $loggerChannel->get('epal');
30
    }
31

32
33
34
	public static function create(ContainerInterface $container)
    {
        return new static(
35
          $container->get('entity_type.manager'),
36
37
38
39
40
          $container->get('database'),
          $container->get('logger.factory')
      );
    }

41
42
43
 	public function appSubmit(Request $request) {
		if (!$request->isMethod('POST')) {
			return $this->respondWithStatus([
44
					"error_code" => 2001
45
46
47
				], Response::HTTP_METHOD_NOT_ALLOWED);
    	}
		$applicationForm = array();
48

49
		$content = $request->getContent();
50
51

		if (!empty($content)) {
52
53
54
55
			$applicationForm = json_decode($content, TRUE);
		}
		else {
			return $this->respondWithStatus([
56
					"error_code" => 5002
57
				], Response::HTTP_BAD_REQUEST);
58
		}
59
60
		$transaction = $this->connection->startTransaction();
		try {
61
			//insert records in entity: epal_student
62
63
64
			$authToken = $request->headers->get('PHP_AUTH_USER');
	        $epalUsers = $this->entityTypeManager->getStorage('epal_users')->loadByProperties(array('authtoken' => $authToken));
	        $epalUser = reset($epalUsers);
65
66
67
68
69
            if (!$epalUser){
    			return $this->respondWithStatus([
    					"error_code" => 4003
    				], Response::HTTP_FORBIDDEN);
    		}
70

71

72
			$student = array(
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
                '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(),
				'name' => $applicationForm[0]['name'],
				'studentsurname' => $applicationForm[0]['studentsurname'],
				'birthdate' => $applicationForm[0]['studentbirthdate'],
				'fatherfirstname' => $applicationForm[0]['fatherfirstname'],
				'motherfirstname' => $applicationForm[0]['motherfirstname'],
				'regionaddress' => $applicationForm[0]['regionaddress'],
				'regionarea' => $applicationForm[0]['regionarea'],
				'regiontk' => $applicationForm[0]['regiontk'],
                'certificatetype' => $applicationForm[0]['certificatetype'],
				'graduation_year' => $applicationForm[0]['graduation_year'],
                'lastschool_registrynumber' => $applicationForm[0]['lastschool_registrynumber'],
98
99
                'lastschool_unittypeid' => $applicationForm[0]['lastschool_unittypeid'],
                'lastschool_schoolname' => $applicationForm[0]['lastschool_schoolname'],
100
101
102
103
104
105
106
107
108
109
                'lastschool_schoolyear' => $applicationForm[0]['lastschool_schoolyear'],
                'lastschool_class' => $applicationForm[0]['lastschool_class'],
				'currentclass' => $applicationForm[0]['currentclass'],
                'guardian_name' => $applicationForm[0]['cu_name'],
                'guardian_surname' => $applicationForm[0]['cu_surname'],
                'guardian_fathername' => $applicationForm[0]['cu_fathername'],
                'guardian_mothername' => $applicationForm[0]['cu_mothername'],
                'agreement' => $applicationForm[0]['disclaimer_checked'],
				'relationtostudent' => $applicationForm[0]['relationtostudent'],
				'telnum' => $applicationForm[0]['telnum']
110
            );
111

112
113
114
115
            if (($errorCode = $this->validateStudent($student)) > 0) {
                return $this->respondWithStatus([
    					"error_code" => $errorCode ], Response::HTTP_OK);
            }
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
            $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));
    	        $epalSchool = reset($epalSchools);
                if (!$epalSchool){
        			return $this->respondWithStatus([
        					"error_code" => 4004
        				], Response::HTTP_FORBIDDEN);
        		} else {
                    $student['currentepal'] = $epalSchool->id();
                }
            } else {
                $student['currentepal'] = 0;
            }

132
			$entity_storage_student = $this->entityTypeManager->getStorage('epal_student');
133
134
135
136
			$entity_object = $entity_storage_student->create($student);
			$entity_storage_student->save($entity_object);

			$created_student_id = $entity_object->id();
137
138

			for ($i = 0; $i < sizeof($applicationForm[1]); $i++) {
139
140
				$epalchosen = array(
					'student_id' => $created_student_id,
141
142
					'epal_id' => $applicationForm[1][$i]['epal_id'],
					'choice_no' => $applicationForm[1][$i]['choice_no']
143
				);
144
				$entity_storage_epalchosen = $this->entityTypeManager->getStorage('epal_student_epal_chosen');
145
146
147
				$entity_object = $entity_storage_epalchosen->create($epalchosen);
				$entity_storage_epalchosen->save($entity_object);
			}
148
149


150
      if ($applicationForm[0]['currentclass'] === "3" || $applicationForm[0]['currentclass'] === "4" )	{
151
152
				$course = array(
					'student_id' => $created_student_id,
153
					'coursefield_id' => $applicationForm[3]['coursefield_id']
154
				);
155
156

				$entity_storage_course = $this->entityTypeManager->getStorage('epal_student_course_field');
157
158
159
				$entity_object = $entity_storage_course->create($course);
				$entity_storage_course->save($entity_object);
			}
160

161
      else if ($applicationForm[0]['currentclass'] === "2")	{
162
163
				$sector = array(
					'student_id' => $created_student_id,
164
					'sectorfield_id' => $applicationForm[3]['sectorfield_id']
165
				);
166
167

				$entity_storage_sector = $this->entityTypeManager->getStorage('epal_student_sector_field');
168
169
170
				$entity_object = $entity_storage_sector->create($sector);
				$entity_storage_sector->save($entity_object);
			}
171
			return $this->respondWithStatus([
172
					"error_code" => 0
173
				], Response::HTTP_OK);
174
175
176
		}

		catch (\Exception $e) {
177
            print_r($e->getMessage());
178
			$this->logger->warning($e->getMessage());
179

180
			$transaction->rollback();
181
			return $this->respondWithStatus([
182
					"error_code" => 5001
183
				], Response::HTTP_INTERNAL_SERVER_ERROR);
184
185
186
		}
	 }

187
188
189
190
191
	 private function respondWithStatus($arr, $s) {
         $res = new JsonResponse($arr);
         $res->setStatusCode($s);
         return $res;
     }
192
193
194
195
196

     private function validateStudent($student) {
         if(!$student["agreement"]) {
             return 1001;
         }
197
198
199
         if(!$student["lastschool_schoolyear"] || strlen($student["lastschool_schoolyear"]) !== 9) {
             return 1002;
         }
200
201
         return 0;
     }
202
}