Distribution.php 17.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
<?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;
16
use Drupal\Core\Database\Database;
17 18 19 20 21
use Drupal\Core\Database\Connection;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;

22 23 24 25 26
//use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\Core\TypedData\Plugin\DataType\TimeStamp;

use Drupal\Core\Language\LanguageManagerInterface;

27 28 29 30 31 32 33 34


class Distribution extends ControllerBase {

	protected $entity_query;
  protected $entityTypeManager;
  protected $logger;
  protected $connection;
35 36
	protected $language;
	protected $currentuser;
37 38 39

	protected $pendingStudents = array();
	protected $choice_id = 1;
40
	protected $globalCounterId = 1;
41 42 43 44 45

	public function __construct(
		EntityTypeManagerInterface $entityTypeManager,
		QueryFactory $entity_query,
		Connection $connection,
46

47 48 49 50
		LoggerChannelFactoryInterface $loggerChannel)
		{
			$this->entityTypeManager = $entityTypeManager;
			$this->entity_query = $entity_query;
51
			$connection = Database::getConnection();
52
			$this->connection = $connection;
53 54 55 56
			$language =  \Drupal::languageManager()->getCurrentLanguage()->getId();
			$this->language = $language;
			$currentuser = \Drupal::currentUser()->id();
			$this->currentuser = $currentuser;
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
			$this->logger = $loggerChannel->get('epal');
    }

	public static function create(ContainerInterface $container)
    {
        return new static(
          $container->get('entity_type.manager'),
          $container->get('entity.query'),
          $container->get('database'),
          $container->get('logger.factory')
      );
    }


	public function createDistribution(Request $request) {

73 74 75
		$numDistributions = 3;
		$sizeOfBlock = 100000;

76 77 78 79 80 81 82 83
		/*
		if (!$request->isMethod('POST')) {
			return $this->respondWithStatus([
					"message" => t("Method Not Allowed")
				], Response::HTTP_METHOD_NOT_ALLOWED);
    	}
		*/

84
		//clearDistributionResults();
85

86 87 88
		$transaction = $this->connection->startTransaction();

		try {
89

90 91
			//initialize/empty epal_student_class if there are already data in it!
			$this->connection->delete('epal_student_class')->execute();
92

93 94
			$limitUp_class = $this->retrieveCapacityLimitUp("Α");
			print_r("<br> ΑΝΩΤΑΤΟ ΟΡΙΟ ΜΑΘΗΤΩΝ: " . $limitUp_class);
95

96 97 98
			while ($this->choice_id <= $numDistributions)	 {

				print_r("<br>ΠΕΡΑΣΜΑ: " . $this->choice_id);
99 100 101

				//υπολογισμός πλήθους non-finalized αιτήσεων για να καθοριστεί ο αριθμός των fetches που θα κάνουμε με συγκεκριμένο sizeOfBlock
				if ($this->choice_id === 1)	{
102 103 104 105
					$sCon = $this->connection->select('epal_student', 'eStudent')
																		->fields('eStudent', array('id'));
			 	  $numData = $sCon->countQuery()->execute()->fetchField();
					print_r("<br>numData: " .  $numData);
106 107 108 109 110 111
				}

				$j = 1;
				$num = 1;
				if ($this->choice_id === 1) {
							while ($num <= $numData)	{
112

113
								print_r("<br>FETCH: " .  $j);
114 115 116 117 118 119
								$sCon = $this->connection->select('epal_student', 'eStudent')
																					->fields('eStudent', array('id', 'name', 'currentclass', 'currentepal', 'points'))
																			    ->condition('eStudent.id', 1+ $sizeOfBlock*($j-1), '>=')
																					->condition('eStudent.id', $j*$sizeOfBlock, '<=');
								$epalStudents = $sCon->execute()->fetchAll(\PDO::FETCH_OBJ);

120 121
								$this->locateStudent($this->choice_id, $epalStudents);

122
								$num = $num + sizeof($epalStudents);
123 124 125 126
								$j = $j + 1;
							}
						}
				else {
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141

								if (sizeof($this->pendingStudents) != 0)	{
									$sCon = $this->connection->select('epal_student', 'eStudent')
																						->fields('eStudent', array('id', 'name', 'currentclass', 'currentepal', 'points'))
																						->condition('eStudent.id', $this->pendingStudents, 'IN');
									$epalStudents = $sCon->execute()->fetchAll(\PDO::FETCH_OBJ);

									//foreach ($epalStudents as $x)
									//	print_r("<br> TEST:" .  $x->id . "  ");

									$this->locateStudent($this->choice_id, $epalStudents);
								}
								else {	//αν δεν υπάρχουν εκκρεμότητες, μην συνεχίζεις με άλλο πέρασμα
									break;
								}
142 143 144 145 146 147
						}

				//Για κάθε σχολείο βρες τα τμήματα
				//Για κάθε τμήμα βρες αν χωράνε και διευθέτησε (checkCapacityAndArrange)
				//checkCapacityAndArrange (school_id, class_id, sectorORcourse_id, limitUp, schoolCapacity)

148 149 150 151 152
				$sCon = $this->connection->select('eepal_school_field_data', 'eSchool')
																	->fields('eSchool', array('id', 'capacity_class_a'));
																	//->condition('eSchool.id', 151, '>=')
																	//->condition('eSchool.id', 153, '<=');	//προσαρμοσμένο για τα demo data --> να αλλάξει
				$eepalSchools = $sCon->execute()->fetchAll(\PDO::FETCH_OBJ);
153 154 155

				foreach ($eepalSchools as $eepalSchool)	{

156
						$this->checkCapacityAndArrange($eepalSchool->id, "1", "-1", $limitUp_class, $eepalSchool->capacity_class_a);
157

158 159 160 161
						$sCon = $this->connection->select('eepal_sectors_in_epal_field_data', 'eSchool')
																			->fields('eSchool', array('epal_id', 'sector_id', 'capacity_class_sector'))
																			->condition('eSchool.epal_id', $eepalSchool->id, '=');
						$eepalSectorsInEpal = $sCon->execute()->fetchAll(\PDO::FETCH_OBJ);
162
						foreach ($eepalSectorsInEpal as $eepalSecInEp)	{
163
							$this->checkCapacityAndArrange($eepalSchool->id, "2", $eepalSecInEp->sector_id, $limitUp_class, $eepalSecInEp->capacity_class_sector);
164 165
					  }

166 167 168 169
						$sCon = $this->connection->select('eepal_specialties_in_epal_field_data', 'eSchool')
																			->fields('eSchool', array('epal_id', 'specialty_id', 'capacity_class_specialty'))
																			->condition('eSchool.epal_id', $eepalSchool->id, '=');
						$eepalSpecialtiesInEpal = $sCon->execute()->fetchAll(\PDO::FETCH_OBJ);
170
						foreach ($eepalSpecialtiesInEpal as $eepalSpecialInEp)	{
171
							$this->checkCapacityAndArrange($eepalSchool->id, "3", $eepalSpecialInEp->specialty_id, $limitUp_class, $eepalSpecialInEp->capacity_class_specialty);
172 173 174 175 176 177 178 179
						}

					} //end for each school/department

					$this->choice_id++;

	  	} //end while

180 181 182 183 184
		}	//end try

		catch (\Exception $e) {
			$this->logger->warning($e->getMessage());
			$transaction->rollback();
185
			return $this->respondWithStatus([
186 187 188 189 190
					"message" => t("An unexpected problem occured")
				], Response::HTTP_INTERNAL_SERVER_ERROR);
		}

		return $this->respondWithStatus([
191 192 193 194 195 196 197 198 199 200 201
					"message" => t("Distribution has made successfully")
				], Response::HTTP_OK);

	}


	public function locateStudent($choice_id, &$epalStudents)	{

		$epal_dist_id = -1;
		$specialization_id = -1;

202
		$transaction = $this->connection->startTransaction();
203

204
		try {
205 206 207

			foreach ($epalStudents as $epalStudent)	{
				print_r("<br>ΚΑΤΑΝΟΜΗ ΜΑΘΗΤΩΝ ΝΟ: " . $choice_id);
208 209 210 211 212 213 214
				print_r("<br>ΜΑΘΗΤΗΣ: " .  $epalStudent->id);

				$clCon = $this->connection->select('epal_student_epal_chosen', 'epals')
					->fields('epals', array('student_id', 'epal_id', 'choice_no'))
					->condition('epals.student_id', $epalStudent->id , '=')
					->condition('epals.choice_no', $choice_id , '=');
				$epalSchoolsChosen = $clCon->execute()->fetchAll(\PDO::FETCH_OBJ);
215 216 217

				if (sizeof($epalSchoolsChosen) !==  0)	{
					$epalSchoolChos = reset($epalSchoolsChosen);
218 219 220 221 222 223 224 225
					print_r(" SCHOOL_ID:" . $epalSchoolChos->epal_id . " STUDENT_ID " . $epalStudent->id);
					$epal_dist_id = $epalSchoolChos->epal_id;

					if ($epalStudent->currentclass === "2")	{
						$clCon = $this->connection->select('epal_student_sector_field', 'sectors')
							->fields('sectors', array('student_id', 'sectorfield_id'))
							->condition('sectors.student_id', $epalStudent->id , '=');
						$epalSectorChosen = $clCon->execute()->fetchAll(\PDO::FETCH_OBJ);
226 227
						$epalSecChos = reset($epalSectorChosen);
					}
228 229 230 231 232
					elseif ($epalStudent->currentclass === "3")	{
						$clCon = $this->connection->select('epal_student_course_field', 'courses')
							->fields('courses', array('student_id', 'coursefield_id'))
							->condition('courses.student_id', $epalStudent->id , '=');
						$epalCourseChosen = $clCon->execute()->fetchAll(\PDO::FETCH_OBJ);
233 234 235
						$epalCourChos = reset($epalCourseChosen);
					}

236 237 238 239
					if ($epalStudent->currentclass === "2")
						$specialization_id = $epalSecChos->sectorfield_id;
					elseif ($epalStudent->currentclass === "3")
						$specialization_id = $epalCourChos->coursefield_id;
240 241 242
					else
						$specialization_id = -1;

243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261

				 //$currentTime = \Drupal\Core\TypedData\Plugin\DataType\TimeStamp::getDateTime();
					$timestamp = strtotime(date("Y-m-d"));
					$this->connection->insert('epal_student_class')->fields(
						array('id' => $this->globalCounterId++,
							'uuid' => \Drupal::service('uuid')->generate(),
							'langcode' => $this->language,
							'user_id' => $this->currentuser,
							'student_id'=> $epalStudent->id,
							'epal_id'=> $epal_dist_id,
							'currentclass' => $epalStudent->currentclass,
							'currentepal' => $epalStudent->currentepal,
							'specialization_id' => $specialization_id,
							'points' => $epalStudent->points,
							'distribution_id' => $choice_id,
							'status' => 1,
							'created' => $timestamp,
							'changed' => $timestamp,)
					)->execute();
262 263 264 265 266 267 268 269 270

			} //end if

		}	//foreach

	}

	catch (\Exception $e) {
		$this->logger->warning($e->getMessage());
271
		$transaction->rollback();
272 273 274 275 276 277 278 279 280 281 282 283 284 285
		return $this->respondWithStatus([
					"message" => t("An unexpected problem occured during locateStudent Method of Distribution")
				], Response::HTTP_INTERNAL_SERVER_ERROR);
	}

	return $this->respondWithStatus([
			"message" => t("locateStudent Method of Distribution has made successfully")
		], Response::HTTP_OK);

	}


 public function retrieveCapacityLimitUp($className) {

286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
	 $transaction = $this->connection->startTransaction();

	 try {
		 $clCon = $this->connection->select('epal_class_limits', 'classLimits')
			 ->fields('classLimits', array('limit_up'))
			 ->condition('classLimits.name', $className, '=');
		 $results = $clCon->execute()->fetchAll(\PDO::FETCH_OBJ);
		 $row = reset($results);
 	}
	catch (\Exception $e) {
		$this->logger->warning($e->getMessage());
		$transaction->rollback();
		return $this->respondWithStatus([
					"message" => t("An unexpected problem occured during retrieveCapacityLimitUp Method of Distribution")
				], Response::HTTP_INTERNAL_SERVER_ERROR);
	}

	return $row->limit_up;
304 305 306 307
 }

	public function checkCapacityAndArrange($epalId, $classId, $secCourId, $limitup, $capacity)	{

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
		$transaction = $this->connection->startTransaction();

		try {

			$clCon = $this->connection->select('epal_student_class', 'studentClass')
				->fields('studentClass', array('epal_id', 'student_id', 'points', 'currentepal', 'currentclass', 'specialization_id'))
				->condition('studentClass.epal_id', $epalId, '=')
				->condition('studentClass.currentclass', $classId, '=')
				->condition('studentClass.specialization_id', $secCourId, '=');
			$epalStudentClass = $clCon->execute()->fetchAll(\PDO::FETCH_OBJ);

			print_r("<br> ΣΧΟΛΕΙΟ: " .  $epalId . " ΤΑΞΗ: "  . $classId . " ΤΟΜΕΑΣ/ΕΙΔΙΚΟΤΗΤΑ: " . $secCourId .  " ΧΩΡΗΤΙΚΟΤΗΤΑ: " . sizeof($epalStudentClass));

			//ΕΠΙΠΛΕΟΝ ΕΠΙΠΕΔΟ ΑΣΦΑΛΕΙΑΣ: αν δεν υπάρχει ο συγκεκριμένος τομέας/ειδικότητα στο σχολείο
			//ο μαθητής που τοποθετήθηκε με την locateStudent να διαγραφεί
			//Σημείωση: κανονικά κάτι τέτοιο δεν μπορεί να συμβεί από το front-end (δηλ. μαθητής να δηλώσει τομέα/ειδικότητα που δεν προσφέρεται..)
			//ΑΝ ΜΠΕΙ ΠΡΕΠΕΙ ΝΑ ΕΝΣΩΜΑΤΩΘΕΙ ΣΤΗΝ LOCATESTUDENT..
			/*
			if (sizeof($epalStudentClass) === 0)	{
				//print_r("<br>ΜΠΗΚΑ! ");
				foreach ($epalStudentClass as $epalStudCl)	{
					//print_r("<br>ΜΠΗΚΑ! ΜΑΘΗΤΗΣ: " .  $epalStudCl->student_id);
					$query = $this->connection->delete('epal_student_class')
													->condition('student_id', $epalStudCl->student_id)
													->execute();
					}
			}
			*/
			//ΤΕΛΟΣ

			$limit = $limitup * $capacity;
			if (sizeof($epalStudentClass) > $limit)	{
				print_r("<br>ΥΠΕΡΧΕΙΛΙΣΗ!");
				foreach ($epalStudentClass as $epalStudCl)	{
					//Υπολογισμός μορίων του μαθητή και (πιθανή) αποθήκευσή τους
					//ΣΗΜΕΙΩΣΗ: Ο υπoλογισμός γίνεται στο front-end

					//$points = $this->calculatePoints();
					/*
					$query = $this->connection->update('epal_student');
					$query->fields([
						'points' =>$points,
					]);
					$query->condition('id',$epalStudCl->student_id);
					$query->execute();
					*/

				}
				$this->makeSelectionOfStudents($epalStudentClass,$limit);
357
			}
358 359 360 361 362 363
			else { //αφαίρεσε όσους μαθητές βρίσκονται στον πίνακα εκκρεμοτήτων
				foreach ($epalStudentClass as $epalStudCl) {
					if ($this->choice_id !== 1)
						////διέγραψε τον μαθητή από τον πίνακα εκκρεμοτήτων (αν βρίσκεται εκεί)
						$this->removeFromPendingStudents($epalStudCl->student_id);
				}
364 365
			}

366
	}	//end try
367

368 369 370
	catch (\Exception $e) {
		$this->logger->warning($e->getMessage());
		$transaction->rollback();
371
		return $this->respondWithStatus([
372 373 374 375 376
					"message" => t("An unexpected problem occured during checkCapacityAndArrange Method of Distribution")
				], Response::HTTP_INTERNAL_SERVER_ERROR);
	}

	return $this->respondWithStatus([
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
				"message" => t("checkCapacityAndArrange Method of Distribution has made successfully")
			], Response::HTTP_OK);

	}


	public function removeFromPendingStudents($val)	{
		if(($key = array_search($val, $this->pendingStudents)) !== false) {
		   unset($this->pendingStudents[$key]);
		}
		//$this->pendingStudents = array_diff($this->pendingStudents, array($val));
	}

	public function makeSelectionOfStudents(&$students, $limit)	{
		//συνάρτηση επιλογής μαθητών σε περίπτωση υπερχείλισης
		// (1) έχουν απόλυτη προτεραιότητα όσοι ήδη φοιτούσαν στο σχολείο (σε περίπτωση που φοιτούσαν περισσότεροι από την χωρητικότητα, τους δεχόμαστε όλους)
		// (2) αν απομένουν κενές θέσεις, επέλεξε από τους εναπομείναντες μαθητές αυτούς με τα περισσότερα μόρια. Σε περίπτωση ισοβαθμίας δεχόμαστε όλους όσους ισοβαθμούν.
		//αυτοδίκαια έχουν προτεραιότητα όσοι ήδη φοιτούσαν στο σχολείο

		foreach($students as $student)	{
397 398
			$student->student_id;
			print_r("<br>STUDENT_ID:" . $student->student_id);
399 400 401 402 403
		}

		//εύρεση αριθμού μαθητών που ήδη φοιτούσαν στο σχολείο
		$cnt = 0;
		foreach($students as $student)	{
404
			if ($student->currentepal === $student->epal_id) {
405 406 407
				$cnt++;
				if ($this->choice_id !== 1)
					////διέγραψε τον μαθητή από τον πίνακα εκκρεμοτήτων (αν βρίσκεται εκεί)
408
					$this->removeFromPendingStudents($student->student_id);
409 410 411 412 413 414 415 416 417 418
			}
		}
		print_r("<br>#ΕΓΓΡΑΦΩΝ ΠΟΥ ΟΙ ΜΑΘΗΤΕΣ ΦΟΙΤΟΥΣΑΝ ΗΔΗ:" . $cnt);

		$newlimit = $limit - $cnt;
		print_r("<br>ΑΝΩΤΑΤΟ ΟΡΙΟ ΜΑΘΗΤΩΝ:" . $limit);
		print_r("<br>#ΜΑΘΗΤΩΝ ΓΙΑ ΝΑ ΕΠΙΛΕΓΟΥΝ ΜΕ ΜΟΡΙΑ:" . $newlimit);

		$points_arr = [];
		foreach($students as $student)	{
419 420
			if ($student->currentepal !== $student->epal_id)
				$points_arr[] = $student->points;
421
		}
422

423 424 425 426 427 428
		rsort($points_arr);
		for ($i=0; $i < sizeof($points_arr); $i++)
			print_r("<br>ΜΟΡΙΑ ΜΕΤΑ ΤΗΝ ΤΑΞΙΝΟΜΙΣΗ: " . $points_arr[$i]);

		print_r("<br>ΟΡΙΟ ΜΟΡΙΩΝ: " . $points_arr[$newlimit-1]);

429 430
		$transaction = $this->connection->startTransaction();

431
		foreach($students as $student)	{
432 433 434
			if ($student->currentepal !== $student->epal_id)	{
				if ($student->points < $points_arr[$newlimit-1]) {
					print_r("<br>ΣΕ ΕΚΚΡΕΜΟΤΗΤΑ - ΔΙΑΓΡΑΦΗ: " . $student->student_id);
435
					//βάλε τον μαθητή στον πίνακα εκκρεμοτήτων και διέγραψέ τον από τον προσωρινό πίνακα αποτελεσμάτων
436 437 438 439 440 441 442 443 444 445 446 447 448 449
					array_push($this->pendingStudents, $student->student_id);
					try {
						$this->connection->delete('epal_student_class')
													->condition('student_id', $student->student_id)
													->execute();
					}
					catch (\Exception $e) {
						$this->logger->warning($e->getMessage());
						$transaction->rollback();
						return $this->respondWithStatus([
									"message" => t("An unexpected problem occured during DELETE proccess in makeSelectionOfStudents Method of Distribution")
								], Response::HTTP_INTERNAL_SERVER_ERROR);
					}

450 451 452 453
				}
				else {
					if ($this->choice_id !== 1)
						//διέγραψε τον μαθητή από τον πίνακα εκκρεμοτήτων (αν βρίσκεται εκεί)
454
						$this->removeFromPendingStudents($student->student_id);
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
				}
			}
		}

		return $this->respondWithStatus([
				"message" => t("makeSelectionOfStudents Method of Distribution has made successfully")
			], Response::HTTP_OK);
	}

	public function calculatePoints()	{

			return rand(0,20);

	}

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




}