InformUnlocatedStudents.php 15.9 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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?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;

class InformUnlocatedStudents extends ControllerBase {

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

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


59
	public function sendMailToUnallocatedStudents(Request $request) {
60
61
62
63
64
65
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

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

92
93
94
				$cnt_success = 0;
				$cnt_fail = 0;

95
96
				// εύρεση μαθητών που η αίτησή τους ΔΕΝ ικανοποιήθηκε,
				//(δεν κατανεμήθηκαν πουθενά)
97
				$sCon = $this->connection->select('epal_student_class', 'eStudent')
98
99
																	->fields('eStudent', array('student_id'));
																	//->condition('eStudent.finalized', 0 , '=');
100
101
				$epalStudents = $sCon->execute()->fetchAll(\PDO::FETCH_OBJ);
				$studentIds = array();
102

103
				array_push($studentIds,-1);
104

105
106
				foreach ($epalStudents as $epalStudent)
					array_push($studentIds, $epalStudent->student_id);
107

108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
				$sCon = $this->connection->select('epal_student', 'eStudent')
																	->fields('eStudent', array('id', 'user_id', 'created'))
																	->condition('eStudent.id', $studentIds, 'NOT IN');
				$epalNonLocatedStudents = $sCon->execute()->fetchAll(\PDO::FETCH_OBJ);

				foreach ($epalNonLocatedStudents as $epalNonLocatedStudent)	{
					$epalUsers = $this->entityTypeManager->getStorage('epal_users')->loadByProperties(array('user_id' => $epalNonLocatedStudent->user_id));
					$epalUser = reset($epalUsers);

					if ($epalUser) {
	            $user = $this->entityTypeManager->getStorage('user')->load($epalUser->user_id->target_id);
							//$users = $this->entityTypeManager->getStorage('user')->loadByProperties(array('uid' => $epalUser->user_id));
							//$user = reset($users);
	            if ($user) {
											$langcode = $user->getPreferredLangcode();
123
											if ($this->sendEmailToUnallocated($user->getEmail(), $epalNonLocatedStudent->id, $epalNonLocatedStudent->created, $langcode))
124
125
126
127
128
129
130
131
132
												$cnt_success++;
	             }
	            else {
	                return $this->respondWithStatus([
	                    'message' => t("user not found"),
	                ], Response::HTTP_INTERNAL_SERVER_ERROR);
	            }

	        } else {
133

134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
						$cnt_fail++;
	        }

				} //end foreach

				return $this->respondWithStatus([
						'message' => t("post successful"),
						'num_success_mail' => $cnt_success,
						'num_fail_mail' => $cnt_fail,
						//'test' => $test,
				], Response::HTTP_OK);


			}	 //end try

			catch (\Exception $e) {
				$this->logger->warning($e->getMessage());
				return $this->respondWithStatus([
							"message" => t("An unexpected problem occured during  sendMailToStudents Method ")
						], Response::HTTP_INTERNAL_SERVER_ERROR);
			}

		}

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
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
247
248
249
250
251
252
253
254
255
256
257

		public function sendMailToUnallocatedStudentsSC(Request $request) {

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

					$cnt_success = 0;
					$cnt_fail = 0;

					// εύρεση μαθητών που η αίτησή τους ΔΕΝ ικανοποιήθηκε,
					//(δεν κατανεμήθηκαν πουθενά)
					$sCon = $this->connection->select('epal_student_class', 'eStudent')
																		->fields('eStudent', array('student_id'))
																		->condition('eStudent.finalized', 0 , '=');
					$epalStudents = $sCon->execute()->fetchAll(\PDO::FETCH_OBJ);
					$studentIds = array();

					array_push($studentIds,-1);

					foreach ($epalStudents as $epalStudent)
						array_push($studentIds, $epalStudent->student_id);

					$sCon = $this->connection->select('epal_student', 'eStudent')
																		->fields('eStudent', array('id', 'user_id', 'created'))
																		->condition('eStudent.id', $studentIds, 'IN');
					$epalNonLocatedStudents = $sCon->execute()->fetchAll(\PDO::FETCH_OBJ);

					foreach ($epalNonLocatedStudents as $epalNonLocatedStudent)	{
						$epalUsers = $this->entityTypeManager->getStorage('epal_users')->loadByProperties(array('user_id' => $epalNonLocatedStudent->user_id));
						$epalUser = reset($epalUsers);

						if ($epalUser) {
		            $user = $this->entityTypeManager->getStorage('user')->load($epalUser->user_id->target_id);
								//$users = $this->entityTypeManager->getStorage('user')->loadByProperties(array('uid' => $epalUser->user_id));
								//$user = reset($users);
		            if ($user) {
												$langcode = $user->getPreferredLangcode();
												if ($this->sendEmailToUnallocated($user->getEmail(), $epalNonLocatedStudent->id, $epalNonLocatedStudent->created, $langcode))
													$cnt_success++;
		             }
		            else {
		                return $this->respondWithStatus([
		                    'message' => t("user not found"),
		                ], Response::HTTP_INTERNAL_SERVER_ERROR);
		            }

		        } else {

							$cnt_fail++;
		        }

					} //end foreach

					return $this->respondWithStatus([
							'message' => t("post successful"),
							'num_success_mail' => $cnt_success,
							'num_fail_mail' => $cnt_fail,
							//'test' => $test,
					], Response::HTTP_OK);


				}	 //end try

				catch (\Exception $e) {
					$this->logger->warning($e->getMessage());
					return $this->respondWithStatus([
								"message" => t("An unexpected problem occured during  sendMailToStudents Method ")
							], Response::HTTP_INTERNAL_SERVER_ERROR);
				}

			}

258
		//sendEmail(e-mail address, A/A, application Date, lang)
259
		private function sendEmailToUnallocated($email, $appId, $appDate, $langcode) {
260
261
262
				$mailManager = \Drupal::service('plugin.manager.mail');

				$module = 'epal';
263
				$key = 'massive_mail_unallocated';	//to be checked..
264
265
				$to = $email;

266
				$params['message'] = "Σας ενημερώνουμε ότι η αίτησή σας με Α/Α: " . $appId . " / " . date('d-m-y H:i:s', $appDate)
267
														. " είναι σε εκκρεμότητα. Για την τοποθέτησή σας και τις ενέργειες που πρέπει να  κάνετε θα ενημερωθείτε με νέο μήνυμα, με τον ίδιο τρόπο, μετά  τις 8-7-2017."
268
269
 														. "\r\n\r\n Ομάδα Διαχείρισης της εφαρμογής e-epal."
														. "\r\n Προσοχή: το μήνυμα που διαβάζετε είναι αυτοματοποιημένο. Παρακαλώ μην απαντάτε σε αυτό το μήνυμα.." ;//e-mail body" ;//e-mail body
270
271
272
273
274
275
276
277
				$send = true;

				$mail_sent = $mailManager->mail($module, $key, $to, $langcode, $params, NULL, $send);

				if ($mail_sent) {
						return 1;
				}
				else {
278
279
280
281
282
283
284
285
286
287
288
289
290
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
						return 0;
				}
		}

		public function sendMailToLocatedStudents(Request $request) {

			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_class', 'eStudent')
318
319
 																	->fields('eStudent', array('student_id', 'epal_id'))
																	->condition('eStudent.finalized', 1 , '=');
320
321
322
323
 				$epalStudents = $sCon->execute()->fetchAll(\PDO::FETCH_OBJ);
 				$studentIds = array();

				//if sizeof(studentIds = 0..distribution has not been made!)
324
				array_push($studentIds, -1);
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
366
367
368
369
370
371
372
373
374
375
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420

 				foreach ($epalStudents as $epalStudent)
 					array_push($studentIds, $epalStudent->student_id);
 				$sCon = $this->connection->select('epal_student', 'eStudent')
 																	->fields('eStudent', array('id', 'user_id', 'created'))
 																	->condition('eStudent.id', $studentIds, 'IN');

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

 				$cnt_success = 0;
 				$cnt_fail = 0;
 				foreach ($epalLocatedStudents as $epalLocatedStudent)	{

					//test purpose
				  //$epalLocatedStudent = reset($epalLocatedStudents);

 					$epalUsers = $this->entityTypeManager->getStorage('epal_users')->loadByProperties(array('user_id' => $epalLocatedStudent->user_id));
 					$epalUser = reset($epalUsers);

 					if ($epalUser) {
 	            $user = $this->entityTypeManager->getStorage('user')->load($epalUser->user_id->target_id);

 	            if ($user) {
 											$langcode = $user->getPreferredLangcode();

											//εύρεση ονόματος σχολείου
											$sCon = $this->connection->select('eepal_school_field_data', 'eSchool')
											                         ->fields('eSchool', array('id', 'name','street_address','phone_number'))
											                         ->condition('eSchool.id', $epalStudent->epal_id, '=');;
											$epalSchools = $sCon->execute()->fetchAll(\PDO::FETCH_OBJ);
											$epalSchool = reset($epalSchools);

											//$msg = $this->sendEmailToLocated($user->getEmail(), $epalLocatedStudent->id, $epalSchool->name, $epalSchool->street_address, $epalSchool->phone_number, $epalLocatedStudent->created, $langcode);
											if ($this->sendEmailToLocated($user->getEmail(), $epalLocatedStudent->id, $epalSchool->name, $epalSchool->street_address, $epalSchool->phone_number, $epalLocatedStudent->created, $langcode))
											  $cnt_success++;

												/*
											//test purposes
											return $this->respondWithStatus([
													//'message' => $epalLocatedStudent->id . ", " . $epalSchool->name . ", " . $epalSchool->street_address . ", " . $epalSchool->phone_number . ", " .  $epalLocatedStudent->created,
													'message' => $msg,
													'num_success_mail' => $cnt_success,
													'num_fail_mail' => $cnt_fail,
											], Response::HTTP_OK);
											//end test
											*/

 	             }
 	            else {
 	                return $this->respondWithStatus([
 	                    'message' => t("user not found"),
 	                ], Response::HTTP_INTERNAL_SERVER_ERROR);
 	            }

 	        } else {

 						$cnt_fail++;
 	        }


 				} //end foreach



				 return $this->respondWithStatus([
						 'message' => t("post successful"),
						 //'message' => t($msg),
						 'num_success_mail' => $cnt_success,
						 'num_fail_mail' => $cnt_fail,
				 ], Response::HTTP_OK);





			 }	 //end try

			 catch (\Exception $e) {
				 $this->logger->warning($e->getMessage());
				 return $this->respondWithStatus([
							 "message" => t("An unexpected problem occured during  sendMailToStudents Method ")
						 ], Response::HTTP_INTERNAL_SERVER_ERROR);
			 }

		}

		//sendEmail(e-mail address, A/A, application Date, lang)
		private function sendEmailToLocated($email, $appId, $schName, $schStreet, $schTel, $appDate, $langcode) {
				//$this->logger->warning("test");

				$mailManager = \Drupal::service('plugin.manager.mail');

				$module = 'epal';
				$key = 'massive_mail_located';
				$to = $email;

421
				$params['message'] = "Σας ενημερώνουμε ότι η αίτησή σας με Α/Α: " . $appId . " / " . date('d-m-y H:i:s', $appDate)
422
423
424
425
														. " ΙΚΑΝΟΠΟΙΗΘΗΚΕ. Έχετε επιλεγεί για να εγγραφείτε στο  "  . $schName
														. ". Παρακαλώ να προσέλθετε ΑΜΕΣΑ στο σχολείο για να προχωρήσει η διαδικασία εγγραφής σας σε αυτό, "
														. "προσκομίζοντας τα απαραίτητα δικαιολογητικά. Διεύθυνση σχολείου:  " . $schStreet
														. " Τηλέφωνο επικοινωνίας σχολείου: " . $schTel
426
427
														. "\r\n\r\n Ομάδα Διαχείρισης της εφαρμογής e-epal."
														. "\r\n Προσοχή: το μήνυμα που διαβάζετε είναι αυτοματοποιημένο. Παρακαλώ μην απαντάτε σε αυτό το μήνυμα." ;//e-mail body
428
429
430
431
432
433
434
435
436
437
438
439
440
441

				//$this->logger->info($params['message']);

				$send = true;

				$mail_sent = $mailManager->mail($module, $key, $to, $langcode, $params, NULL, $send);

				if ($mail_sent) {

						return 1;
						//return $params['message'];
				}
				else {

442
						return 0;
443
						//return $params['message'];
444
445
446
447
448
449
450
451
452
453
454
455
456
457
				}
		}


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




}