]> RaphaΓ«l G. Git Repositories - airbundle/blob - Repository/SessionRepository.php
Add snippet feature
[airbundle] / Repository / SessionRepository.php
1 <?php
2
3 namespace Rapsys\AirBundle\Repository;
4
5 use Symfony\Component\Translation\TranslatorInterface;
6 use Doctrine\DBAL\Types\Type;
7 use Doctrine\ORM\Query\ResultSetMapping;
8 use Doctrine\ORM\Query;
9
10 /**
11 * SessionRepository
12 */
13 class SessionRepository extends \Doctrine\ORM\EntityRepository {
14 ///Set accuweather max number of daily pages
15 const ACCUWEATHER_DAILY = 12;
16
17 ///Set accuweather max number of hourly pages
18 const ACCUWEATHER_HOURLY = 3;
19
20 ///Set guest delay
21 const GUEST_DELAY = 2;
22
23 ///Set regular delay
24 const REGULAR_DELAY = 3;
25
26 ///Set senior
27 const SENIOR_DELAY = 4;
28
29 ///Set glyphs
30 //TODO: document utf-8 codes ?
31 const GLYPHS = [
32 //Slots
33 'Morning' => 'πŸŒ…', #0001f305
34 'Afternoon' => 'β˜€οΈ', #2600
35 'Evening' => 'πŸŒ‡', #0001f307
36 'After' => '✨', #2728
37 //Weathers
38 'Cleary' => 'β˜€', #2600
39 'Sunny' => 'β›…', #26c5
40 'Cloudy' => '☁', #2601
41 'Winty' => '❄️', #2744
42 'Rainy' => 'πŸŒ‚', #0001f302
43 'Stormy' => 'β˜”' #2614
44 ];
45
46 /**
47 * Find session by location, slot and date
48 *
49 * @param $location The location
50 * @param $slot The slot
51 * @param $date The datetime
52 */
53 public function findOneByLocationSlotDate($location, $slot, $date) {
54 //Return sessions
55 return $this->getEntityManager()
56 ->createQuery('SELECT s FROM RapsysAirBundle:Session s WHERE (s.location = :location AND s.slot = :slot AND s.date = :date)')
57 ->setParameter('location', $location)
58 ->setParameter('slot', $slot)
59 ->setParameter('date', $date)
60 ->getSingleResult();
61 }
62
63 /**
64 * Find sessions by date period
65 *
66 * @param $period The date period
67 */
68 public function findAllByDatePeriod($period) {
69 //Return sessions
70 return $this->getEntityManager()
71 ->createQuery('SELECT s FROM RapsysAirBundle:Session s WHERE s.date BETWEEN :begin AND :end')
72 ->setParameter('begin', $period->getStartDate())
73 ->setParameter('end', $period->getEndDate())
74 ->getResult();
75 }
76
77 /**
78 * Find sessions by location and date period
79 *
80 * @param $location The location
81 * @param $period The date period
82 */
83 public function findAllByLocationDatePeriod($location, $period) {
84 //Return sessions
85 return $this->getEntityManager()
86 ->createQuery('SELECT s FROM RapsysAirBundle:Session s WHERE (s.location = :location AND s.date BETWEEN :begin AND :end)')
87 ->setParameter('location', $location)
88 ->setParameter('begin', $period->getStartDate())
89 ->setParameter('end', $period->getEndDate())
90 ->getResult();
91 }
92
93 /**
94 * Find one session by location and user id within last month
95 *
96 * @param $location The location id
97 * @param $user The user id
98 */
99 public function findOneWithinLastMonthByLocationUser($location, $user) {
100 //Get entity manager
101 $em = $this->getEntityManager();
102
103 //Get quote strategy
104 $qs = $em->getConfiguration()->getQuoteStrategy();
105 $dp = $em->getConnection()->getDatabasePlatform();
106
107 //Get quoted table names
108 //XXX: this allow to make this code table name independent
109 $tables = [
110 'RapsysAirBundle:Session' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Session'), $dp),
111 'RapsysAirBundle:Application' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Application'), $dp),
112 "\t" => '',
113 "\n" => ' '
114 ];
115
116 //Set the request
117 //XXX: give the gooddelay to guest just in case
118 $req =<<<SQL
119 SELECT s.id
120 FROM RapsysAirBundle:Session s
121 JOIN RapsysAirBundle:Application a ON (a.id = s.application_id AND a.user_id = :uid AND (a.canceled IS NULL OR TIMESTAMPDIFF(DAY, a.canceled, ADDTIME(s.date, s.begin)) < 1))
122 WHERE s.location_id = :lid AND s.date >= DATE_ADD(DATE_SUB(NOW(), INTERVAL 1 MONTH), INTERVAL :gooddelay DAY)
123 SQL;
124
125 //Replace bundle entity name by table name
126 $req = str_replace(array_keys($tables), array_values($tables), $req);
127
128 //Get result set mapping instance
129 $rsm = new ResultSetMapping();
130
131 //Declare all fields
132 //XXX: see vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/Types.php
133 $rsm->addScalarResult('id', 'id', 'integer')
134 ->addIndexByScalar('id');
135
136 //Return result
137 return $em
138 ->createNativeQuery($req, $rsm)
139 ->setParameter('lid', $location)
140 ->setParameter('uid', $user)
141 ->setParameter('gooddelay', self::SENIOR_DELAY)
142 ->getOneOrNullResult();
143 }
144
145 /**
146 * Fetch session by id
147 *
148 * @param $id The session id
149 * @return array The session data
150 */
151 public function fetchOneById($id) {
152 //Get entity manager
153 $em = $this->getEntityManager();
154
155 //Get quote strategy
156 $qs = $em->getConfiguration()->getQuoteStrategy();
157 $dp = $em->getConnection()->getDatabasePlatform();
158
159 //Get quoted table names
160 //XXX: this allow to make this code table name independent
161 $tables = [
162 'RapsysAirBundle:GroupUser' => $qs->getJoinTableName($em->getClassMetadata('RapsysAirBundle:User')->getAssociationMapping('groups'), $em->getClassMetadata('RapsysAirBundle:User'), $dp),
163 'RapsysAirBundle:Session' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Session'), $dp),
164 'RapsysAirBundle:Application' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Application'), $dp),
165 'RapsysAirBundle:Group' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Group'), $dp),
166 'RapsysAirBundle:Location' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Location'), $dp),
167 'RapsysAirBundle:Slot' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Slot'), $dp),
168 'RapsysAirBundle:User' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:User'), $dp),
169 //Delay
170 ':afterid' => 4,
171 "\t" => '',
172 "\n" => ' '
173 ];
174
175 //Set the request
176 //TODO: compute scores ?
177 //TODO: compute delivery date ? (J-3/J-4 ?)
178 $req =<<<SQL
179 SELECT
180 s.id,
181 s.date,
182 s.begin,
183 ADDDATE(ADDTIME(s.date, s.begin), INTERVAL IF(s.slot_id = :afterid, 1, 0) DAY) AS start,
184 s.length,
185 ADDDATE(ADDTIME(ADDTIME(s.date, s.begin), s.length), INTERVAL IF(s.slot_id = :afterid, 1, 0) DAY) AS stop,
186 s.rainfall,
187 s.rainrisk,
188 s.realfeel,
189 s.realfeelmin,
190 s.realfeelmax,
191 s.temperature,
192 s.temperaturemin,
193 s.temperaturemax,
194 s.locked,
195 s.created,
196 s.updated,
197 s.location_id AS l_id,
198 l.short AS l_short,
199 l.title AS l_title,
200 l.address AS l_address,
201 l.zipcode AS l_zipcode,
202 l.city AS l_city,
203 l.latitude AS l_latitude,
204 l.longitude AS l_longitude,
205 s.slot_id AS t_id,
206 t.title AS t_title,
207 s.application_id AS a_id,
208 a.user_id AS au_id,
209 au.pseudonym AS au_pseudonym,
210 GROUP_CONCAT(sa.id ORDER BY sa.user_id SEPARATOR "\\n") AS sa_id,
211 GROUP_CONCAT(IFNULL(sa.score, 'NULL') ORDER BY sa.user_id SEPARATOR "\\n") AS sa_score,
212 GROUP_CONCAT(sa.created ORDER BY sa.user_id SEPARATOR "\\n") AS sa_created,
213 GROUP_CONCAT(sa.updated ORDER BY sa.user_id SEPARATOR "\\n") AS sa_updated,
214 GROUP_CONCAT(IFNULL(sa.canceled, 'NULL') ORDER BY sa.user_id SEPARATOR "\\n") AS sa_canceled,
215 GROUP_CONCAT(sa.user_id ORDER BY sa.user_id SEPARATOR "\\n") AS sau_id,
216 GROUP_CONCAT(sau.pseudonym ORDER BY sa.user_id SEPARATOR "\\n") AS sau_pseudonym
217 FROM RapsysAirBundle:Session AS s
218 JOIN RapsysAirBundle:Location AS l ON (l.id = s.location_id)
219 JOIN RapsysAirBundle:Slot AS t ON (t.id = s.slot_id)
220 LEFT JOIN RapsysAirBundle:Application AS a ON (a.id = s.application_id)
221 LEFT JOIN RapsysAirBundle:User AS au ON (au.id = a.user_id)
222 LEFT JOIN RapsysAirBundle:Application AS sa ON (sa.session_id = s.id)
223 LEFT JOIN RapsysAirBundle:User AS sau ON (sau.id = sa.user_id)
224 WHERE s.id = :sid
225 GROUP BY s.id
226 ORDER BY NULL
227 SQL;
228
229 //Replace bundle entity name by table name
230 $req = str_replace(array_keys($tables), array_values($tables), $req);
231
232 //Get result set mapping instance
233 //XXX: DEBUG: see ../blog.orig/src/Rapsys/BlogBundle/Repository/ArticleRepository.php
234 $rsm = new ResultSetMapping();
235
236 //Declare all fields
237 //XXX: see vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/Types.php
238 $rsm->addScalarResult('id', 'id', 'integer')
239 ->addScalarResult('date', 'date', 'date')
240 ->addScalarResult('begin', 'begin', 'time')
241 ->addScalarResult('start', 'start', 'datetime')
242 ->addScalarResult('length', 'length', 'time')
243 ->addScalarResult('stop', 'stop', 'datetime')
244 ->addScalarResult('rainfall', 'rainfall', 'float')
245 ->addScalarResult('rainrisk', 'rainrisk', 'float')
246 ->addScalarResult('realfeel', 'realfeel', 'float')
247 ->addScalarResult('realfeelmin', 'realfeelmin', 'float')
248 ->addScalarResult('realfeelmax', 'realfeelmax', 'float')
249 ->addScalarResult('temperature', 'temperature', 'float')
250 ->addScalarResult('temperaturemin', 'temperaturemin', 'float')
251 ->addScalarResult('temperaturemax', 'temperaturemax', 'float')
252 ->addScalarResult('locked', 'locked', 'datetime')
253 ->addScalarResult('created', 'created', 'datetime')
254 ->addScalarResult('updated', 'updated', 'datetime')
255 ->addScalarResult('l_id', 'l_id', 'integer')
256 ->addScalarResult('l_short', 'l_short', 'string')
257 ->addScalarResult('l_title', 'l_title', 'string')
258 ->addScalarResult('l_address', 'l_address', 'string')
259 ->addScalarResult('l_zipcode', 'l_zipcode', 'string')
260 ->addScalarResult('l_city', 'l_city', 'string')
261 ->addScalarResult('l_latitude', 'l_latitude', 'float')
262 ->addScalarResult('l_longitude', 'l_longitude', 'float')
263 ->addScalarResult('t_id', 't_id', 'integer')
264 ->addScalarResult('t_title', 't_title', 'string')
265 ->addScalarResult('a_id', 'a_id', 'integer')
266 ->addScalarResult('au_id', 'au_id', 'integer')
267 ->addScalarResult('au_pseudonym', 'au_pseudonym', 'string')
268 //XXX: is a string because of \n separator
269 ->addScalarResult('sa_id', 'sa_id', 'string')
270 //XXX: is a string because of \n separator
271 ->addScalarResult('sa_score', 'sa_score', 'string')
272 //XXX: is a string because of \n separator
273 ->addScalarResult('sa_created', 'sa_created', 'string')
274 //XXX: is a string because of \n separator
275 ->addScalarResult('sa_updated', 'sa_updated', 'string')
276 //XXX: is a string because of \n separator
277 ->addScalarResult('sa_canceled', 'sa_canceled', 'string')
278 //XXX: is a string because of \n separator
279 ->addScalarResult('sau_id', 'sau_id', 'string')
280 //XXX: is a string because of \n separator
281 ->addScalarResult('sau_pseudonym', 'sau_pseudonym', 'string')
282 ->addIndexByScalar('id');
283
284 //Return result
285 return $em
286 ->createNativeQuery($req, $rsm)
287 ->setParameter('sid', $id)
288 ->getOneOrNullResult();
289 }
290
291 /**
292 * Fetch sessions calendar with translated location by date period
293 *
294 * @param $translator The TranslatorInterface instance
295 * @param $period The date period
296 * @param $locationId The location id
297 * @param $sessionId The session id
298 * @param $granted The session is granted
299 */
300 public function fetchCalendarByDatePeriod(TranslatorInterface $translator, $period, $locationId = null, $sessionId = null, $granted = false) {
301 //Get entity manager
302 $em = $this->getEntityManager();
303
304 //Get quote strategy
305 $qs = $em->getConfiguration()->getQuoteStrategy();
306 $dp = $em->getConnection()->getDatabasePlatform();
307
308 //Get quoted table names
309 //XXX: this allow to make this code table name independent
310 $tables = [
311 'RapsysAirBundle:GroupUser' => $qs->getJoinTableName($em->getClassMetadata('RapsysAirBundle:User')->getAssociationMapping('groups'), $em->getClassMetadata('RapsysAirBundle:User'), $dp),
312 'RapsysAirBundle:Session' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Session'), $dp),
313 'RapsysAirBundle:Application' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Application'), $dp),
314 'RapsysAirBundle:Group' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Group'), $dp),
315 'RapsysAirBundle:Location' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Location'), $dp),
316 'RapsysAirBundle:Slot' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Slot'), $dp),
317 'RapsysAirBundle:User' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:User'), $dp),
318 "\t" => '',
319 "\n" => ' '
320 ];
321
322 //Set the request
323 //TODO: change as_u_* in sau_*, a_u_* in au_*, etc, see request up
324 $req = 'SELECT s.id, s.date, s.rainrisk, s.rainfall, s.realfeel, s.temperature, s.location_id AS l_id, l.short AS l_short, l.title AS l_title, s.slot_id AS t_id, t.title AS t_title, s.application_id AS a_id, a.user_id AS a_u_id, au.pseudonym AS a_u_pseudonym, GROUP_CONCAT(sa.user_id ORDER BY sa.user_id SEPARATOR "\\n") AS as_u_id, GROUP_CONCAT(sau.pseudonym ORDER BY sa.user_id SEPARATOR "\\n") AS as_u_pseudonym
325 FROM RapsysAirBundle:Session AS s
326 JOIN RapsysAirBundle:Location AS l ON (l.id = s.location_id)
327 JOIN RapsysAirBundle:Slot AS t ON (t.id = s.slot_id)
328 '.($granted?'':'LEFT ').'JOIN RapsysAirBundle:Application AS a ON (a.id = s.application_id)
329 '.($granted?'':'LEFT ').'JOIN RapsysAirBundle:User AS au ON (au.id = a.user_id)
330 LEFT JOIN RapsysAirBundle:Application AS sa ON (sa.session_id = s.id)
331 LEFT JOIN RapsysAirBundle:User AS sau ON (sau.id = sa.user_id)
332 WHERE s.date BETWEEN :begin AND :end
333 '.($locationId?'AND s.location_id = :lid':'').'
334 GROUP BY s.id
335 ORDER BY NULL';
336
337 //Replace bundle entity name by table name
338 $req = str_replace(array_keys($tables), array_values($tables), $req);
339
340 //Get result set mapping instance
341 //XXX: DEBUG: see ../blog.orig/src/Rapsys/BlogBundle/Repository/ArticleRepository.php
342 $rsm = new ResultSetMapping();
343
344 //Declare all fields
345 //XXX: see vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/Types.php
346 //addScalarResult($sqlColName, $resColName, $type = 'string');
347 $rsm->addScalarResult('id', 'id', 'integer')
348 ->addScalarResult('date', 'date', 'date')
349 ->addScalarResult('rainrisk', 'rainrisk', 'float')
350 ->addScalarResult('rainfall', 'rainfall', 'float')
351 ->addScalarResult('realfeel', 'realfeel', 'float')
352 ->addScalarResult('temperature', 'temperature', 'float')
353 ->addScalarResult('t_id', 't_id', 'integer')
354 ->addScalarResult('t_title', 't_title', 'string')
355 ->addScalarResult('l_id', 'l_id', 'integer')
356 ->addScalarResult('l_short', 'l_short', 'string')
357 ->addScalarResult('l_title', 'l_title', 'string')
358 ->addScalarResult('a_id', 'a_id', 'integer')
359 ->addScalarResult('a_u_id', 'a_u_id', 'integer')
360 ->addScalarResult('a_u_pseudonym', 'a_u_pseudonym', 'string')
361 //XXX: is a string because of \n separator
362 ->addScalarResult('as_u_id', 'as_u_id', 'string')
363 //XXX: is a string because of \n separator
364 ->addScalarResult('as_u_pseudonym', 'as_u_pseudonym', 'string')
365 ->addIndexByScalar('id');
366
367 //Fetch result
368 $res = $em
369 ->createNativeQuery($req, $rsm)
370 ->setParameter('begin', $period->getStartDate())
371 ->setParameter('end', $period->getEndDate())
372 ->setParameter('lid', $locationId)
373 ->getResult();
374
375 //Init calendar
376 $calendar = [];
377
378 //Init month
379 $month = null;
380
381 //Iterate on each day
382 foreach($period as $date) {
383 //Init day in calendar
384 $calendar[$Ymd = $date->format('Ymd')] = [
385 'title' => $date->format('d'),
386 'class' => [],
387 'sessions' => []
388 ];
389
390 //Detect month change
391 if ($month != $date->format('m')) {
392 $month = $date->format('m');
393 //Append month for first day of month
394 //XXX: except if today to avoid double add
395 if ($date->format('U') != strtotime('today')) {
396 $calendar[$Ymd]['title'] .= '/'.$month;
397 }
398 }
399 //Deal with today
400 if ($date->format('U') == ($today = strtotime('today'))) {
401 $calendar[$Ymd]['title'] .= '/'.$month;
402 $calendar[$Ymd]['current'] = true;
403 $calendar[$Ymd]['class'][] = 'current';
404 }
405 //Disable passed days
406 if ($date->format('U') < $today) {
407 $calendar[$Ymd]['disabled'] = true;
408 $calendar[$Ymd]['class'][] = 'disabled';
409 }
410 //Set next month days
411 if ($date->format('m') > date('m')) {
412 $calendar[$Ymd]['next'] = true;
413 $calendar[$Ymd]['class'][] = 'next';
414 }
415
416 //Iterate on each session to find the one of the day
417 foreach($res as $session) {
418 if (($sessionYmd = $session['date']->format('Ymd')) == $Ymd) {
419 //Count number of application
420 $count = count(explode("\n", $session['as_u_id']));
421
422 //Compute classes
423 $class = [];
424 if (!empty($session['a_id'])) {
425 $applications = [ $session['a_u_id'] => $session['a_u_pseudonym'] ];
426 $class[] = 'granted';
427 } elseif ($count == 0) {
428 $class[] = 'orphaned';
429 } elseif ($count > 1) {
430 $class[] = 'disputed';
431 } else {
432 $class[] = 'pending';
433 }
434
435 if ($sessionId == $session['id']) {
436 $class[] = 'highlight';
437 }
438
439 //Set temperature
440 //XXX: realfeel may be null, temperature should not
441 $temperature = $session['realfeel'] !== null ? $session['realfeel'] : $session['temperature'];
442
443 //Compute weather
444 //XXX: rainfall may be null
445 if ($session['rainrisk'] > 0.50 || $session['rainfall'] > 2) {
446 $weather = self::GLYPHS['Stormy'];
447 } elseif ($session['rainrisk'] > 0.40 || $session['rainfall'] > 1) {
448 $weather = self::GLYPHS['Rainy'];
449 } elseif ($temperature > 24) {
450 $weather = self::GLYPHS['Cleary'];
451 } elseif ($temperature > 17) {
452 $weather = self::GLYPHS['Sunny'];
453 } elseif ($temperature > 10) {
454 $weather = self::GLYPHS['Cloudy'];
455 } elseif ($temperature !== null) {
456 $weather = self::GLYPHS['Winty'];
457 } else {
458 $weather = null;
459 }
460
461 //Init weathertitle
462 $weathertitle = [];
463
464 //Check if realfeel is available
465 if ($session['realfeel'] !== null) {
466 $weathertitle[] = $session['realfeel'].'Β°R';
467 }
468
469 //Check if temperature is available
470 if ($session['temperature'] !== null) {
471 $weathertitle[] = $session['temperature'].'Β°C';
472 }
473
474 //Check if rainrisk is available
475 if ($session['rainrisk'] !== null) {
476 $weathertitle[] = ($session['rainrisk']*100).'%';
477 }
478
479 //Check if rainfall is available
480 if ($session['rainfall'] !== null) {
481 $weathertitle[] = $session['rainfall'].'mm';
482 }
483
484 //Set applications
485 $applications = [
486 0 => $translator->trans($session['t_title']).' '.$translator->trans('at '.$session['l_title']).$translator->trans(':')
487 ];
488
489 //Fetch pseudonyms from session applications
490 $applications += array_combine(explode("\n", $session['as_u_id']), array_map(function ($v) {return '- '.$v;}, explode("\n", $session['as_u_pseudonym'])));
491
492 //Check that session is not granted
493 if (empty($session['a_id'])) {
494 //With location id and unique application
495 if ($locationId && $count == 1) {
496 //Set unique application pseudonym as title
497 $title = $session['as_u_pseudonym'];
498 //Without location id or multiple application
499 } else {
500 //Set location title with optional count
501 $title = $translator->trans($session['l_title']).($count > 1 ? ' ['.$count.']':'');
502 }
503 //Session is granted
504 } else {
505 //Replace granted application
506 $applications[$session['a_u_id']] = '* '.$session['a_u_pseudonym'];
507 //Set pseudonym with optional location title and count
508 $title = $session['a_u_pseudonym'].($locationId?'':' '.$translator->trans('at '.$session['l_short'])).($count > 1 ? ' ['.$count.']':'');
509 }
510
511 //Add the session
512 $calendar[$Ymd]['sessions'][$session['t_id'].sprintf('%02d', $session['l_id'])] = [
513 'id' => $session['id'],
514 'title' => $title,
515 'class' => $class,
516 'slot' => self::GLYPHS[$session['t_title']],
517 'slottitle' => $translator->trans($session['t_title']),
518 'weather' => $weather,
519 'weathertitle' => implode(' ', $weathertitle),
520 'applications' => $applications
521 ];
522 }
523 }
524
525 //Sort sessions
526 ksort($calendar[$Ymd]['sessions']);
527 }
528
529 //Send result
530 return $calendar;
531 }
532
533 /**
534 * Fetch sessions calendar with translated location by date period and user
535 *
536 * @param $translator The TranslatorInterface instance
537 * @param $period The date period
538 * @param $userId The user id
539 * @param $sessionId The session id
540 */
541 public function fetchUserCalendarByDatePeriod(TranslatorInterface $translator, $period, $userId = null, $sessionId = null) {
542 //Get entity manager
543 $em = $this->getEntityManager();
544
545 //Get quote strategy
546 $qs = $em->getConfiguration()->getQuoteStrategy();
547 $dp = $em->getConnection()->getDatabasePlatform();
548
549 //Get quoted table names
550 //XXX: this allow to make this code table name independent
551 $tables = [
552 'RapsysAirBundle:GroupUser' => $qs->getJoinTableName($em->getClassMetadata('RapsysAirBundle:User')->getAssociationMapping('groups'), $em->getClassMetadata('RapsysAirBundle:User'), $dp),
553 'RapsysAirBundle:Session' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Session'), $dp),
554 'RapsysAirBundle:Application' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Application'), $dp),
555 'RapsysAirBundle:Group' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Group'), $dp),
556 'RapsysAirBundle:Location' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Location'), $dp),
557 'RapsysAirBundle:Slot' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Slot'), $dp),
558 'RapsysAirBundle:User' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:User'), $dp),
559 "\t" => '',
560 "\n" => ' '
561 ];
562
563 //Set the request
564 $req = 'SELECT s.id, s.date, s.rainrisk, s.rainfall, s.realfeel, s.temperature, s.location_id AS l_id, l.short AS l_short, l.title AS l_title, s.slot_id AS t_id, t.title AS t_title, s.application_id AS a_id, a.user_id AS a_u_id, au.pseudonym AS a_u_pseudonym, GROUP_CONCAT(sa.user_id ORDER BY sa.user_id SEPARATOR "\\n") AS as_u_id, GROUP_CONCAT(CONCAT("- ", sau.pseudonym) ORDER BY sa.user_id SEPARATOR "\\n") AS as_u_pseudonym
565 FROM RapsysAirBundle:Session AS s
566 JOIN RapsysAirBundle:Location AS l ON (l.id = s.location_id)
567 JOIN RapsysAirBundle:Slot AS t ON (t.id = s.slot_id)
568 '.($userId?'JOIN RapsysAirBundle:Application AS sua ON (sua.session_id = s.id)':'').'
569 LEFT JOIN RapsysAirBundle:Application AS a ON (a.id = s.application_id)
570 LEFT JOIN RapsysAirBundle:User AS au ON (au.id = a.user_id)
571 LEFT JOIN RapsysAirBundle:Application AS sa ON (sa.session_id = s.id)
572 LEFT JOIN RapsysAirBundle:User AS sau ON (sau.id = sa.user_id)
573 WHERE s.date BETWEEN :begin AND :end
574 '.($userId?'AND sua.user_id = :uid':'').'
575 GROUP BY s.id
576 ORDER BY NULL';
577
578 //Replace bundle entity name by table name
579 $req = str_replace(array_keys($tables), array_values($tables), $req);
580
581 //Get result set mapping instance
582 //XXX: DEBUG: see ../blog.orig/src/Rapsys/BlogBundle/Repository/ArticleRepository.php
583 $rsm = new ResultSetMapping();
584
585 //Declare all fields
586 //XXX: see vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/Types.php
587 //addScalarResult($sqlColName, $resColName, $type = 'string');
588 $rsm->addScalarResult('id', 'id', 'integer')
589 ->addScalarResult('date', 'date', 'date')
590 ->addScalarResult('rainrisk', 'rainrisk', 'float')
591 ->addScalarResult('rainfall', 'rainfall', 'float')
592 ->addScalarResult('realfeel', 'realfeel', 'float')
593 ->addScalarResult('temperature', 'temperature', 'float')
594 ->addScalarResult('t_id', 't_id', 'integer')
595 ->addScalarResult('t_title', 't_title', 'string')
596 ->addScalarResult('l_id', 'l_id', 'integer')
597 ->addScalarResult('l_short', 'l_short', 'string')
598 ->addScalarResult('l_title', 'l_title', 'string')
599 ->addScalarResult('a_id', 'a_id', 'integer')
600 ->addScalarResult('a_u_id', 'a_u_id', 'integer')
601 ->addScalarResult('a_u_pseudonym', 'a_u_pseudonym', 'string')
602 //XXX: is a string because of \n separator
603 ->addScalarResult('as_u_id', 'as_u_id', 'string')
604 //XXX: is a string because of \n separator
605 ->addScalarResult('as_u_pseudonym', 'as_u_pseudonym', 'string')
606 ->addIndexByScalar('id');
607
608 //Fetch result
609 $res = $em
610 ->createNativeQuery($req, $rsm)
611 ->setParameter('begin', $period->getStartDate())
612 ->setParameter('end', $period->getEndDate())
613 ->setParameter('uid', $userId)
614 ->getResult();
615
616 //Init calendar
617 $calendar = [];
618
619 //Init month
620 $month = null;
621
622 //Iterate on each day
623 foreach($period as $date) {
624 //Init day in calendar
625 $calendar[$Ymd = $date->format('Ymd')] = [
626 'title' => $date->format('d'),
627 'class' => [],
628 'sessions' => []
629 ];
630
631 //Detect month change
632 if ($month != $date->format('m')) {
633 $month = $date->format('m');
634 //Append month for first day of month
635 //XXX: except if today to avoid double add
636 if ($date->format('U') != strtotime('today')) {
637 $calendar[$Ymd]['title'] .= '/'.$month;
638 }
639 }
640 //Deal with today
641 if ($date->format('U') == ($today = strtotime('today'))) {
642 $calendar[$Ymd]['title'] .= '/'.$month;
643 $calendar[$Ymd]['current'] = true;
644 $calendar[$Ymd]['class'][] = 'current';
645 }
646 //Disable passed days
647 if ($date->format('U') < $today) {
648 $calendar[$Ymd]['disabled'] = true;
649 $calendar[$Ymd]['class'][] = 'disabled';
650 }
651 //Set next month days
652 if ($date->format('m') > date('m')) {
653 $calendar[$Ymd]['next'] = true;
654 $calendar[$Ymd]['class'][] = 'next';
655 }
656
657 //Iterate on each session to find the one of the day
658 foreach($res as $session) {
659 if (($sessionYmd = $session['date']->format('Ymd')) == $Ymd) {
660 //Count number of application
661 $count = count(explode("\n", $session['as_u_id']));
662
663 //Compute classes
664 $class = [];
665 if (!empty($session['a_id'])) {
666 $applications = [ $session['a_u_id'] => $session['a_u_pseudonym'] ];
667 if ($session['a_u_id'] == $userId) {
668 $class[] = 'granted';
669 } else {
670 $class[] = 'disputed';
671 }
672 } elseif ($count == 0) {
673 $class[] = 'orphaned';
674 } elseif ($count > 1) {
675 $class[] = 'disputed';
676 } else {
677 $class[] = 'pending';
678 }
679
680 if ($sessionId == $session['id']) {
681 $class[] = 'highlight';
682 }
683
684 //Set temperature
685 //XXX: realfeel may be null, temperature should not
686 $temperature = $session['realfeel'] !== null ? $session['realfeel'] : $session['temperature'];
687
688 //Compute weather
689 //XXX: rainfall may be null
690 if ($session['rainrisk'] > 0.50 || $session['rainfall'] > 2) {
691 $weather = self::GLYPHS['Stormy'];
692 } elseif ($session['rainrisk'] > 0.40 || $session['rainfall'] > 1) {
693 $weather = self::GLYPHS['Rainy'];
694 } elseif ($temperature > 24) {
695 $weather = self::GLYPHS['Cleary'];
696 } elseif ($temperature > 17) {
697 $weather = self::GLYPHS['Sunny'];
698 } elseif ($temperature > 10) {
699 $weather = self::GLYPHS['Cloudy'];
700 } elseif ($temperature !== null) {
701 $weather = self::GLYPHS['Winty'];
702 } else {
703 $weather = null;
704 }
705
706 //Init weathertitle
707 $weathertitle = [];
708
709 //Check if realfeel is available
710 if ($session['realfeel'] !== null) {
711 $weathertitle[] = $session['realfeel'].'Β°R';
712 }
713
714 //Check if temperature is available
715 if ($session['temperature'] !== null) {
716 $weathertitle[] = $session['temperature'].'Β°C';
717 }
718
719 //Check if rainrisk is available
720 if ($session['rainrisk'] !== null) {
721 $weathertitle[] = ($session['rainrisk']*100).'%';
722 }
723
724 //Check if rainfall is available
725 if ($session['rainfall'] !== null) {
726 $weathertitle[] = $session['rainfall'].'mm';
727 }
728
729 //Set applications
730 $applications = [
731 0 => $translator->trans($session['t_title']).' '.$translator->trans('at '.$session['l_title']).$translator->trans(':')
732 ];
733
734 //Check that session is not granted
735 if (empty($session['a_id'])) {
736 //Fetch pseudonyms from session applications
737 $applications += array_combine(explode("\n", $session['as_u_id']), explode("\n", $session['as_u_pseudonym']));
738 //Session is granted
739 } else {
740 //Fetch pseudonyms from session applications
741 $applications += array_combine(explode("\n", $session['as_u_id']), explode("\n", $session['as_u_pseudonym']));
742 //Replace granted application
743 $applications[$session['a_u_id']] = '* '.$session['a_u_pseudonym'];
744 }
745
746 //Set title
747 $title = $translator->trans($session['l_title']).($count > 1 ? ' ['.$count.']':'');
748
749 //Add the session
750 $calendar[$Ymd]['sessions'][$session['t_id'].sprintf('%02d', $session['l_id'])] = [
751 'id' => $session['id'],
752 'title' => $title,
753 'class' => $class,
754 'slot' => self::GLYPHS[$session['t_title']],
755 'slottitle' => $translator->trans($session['t_title']),
756 'weather' => $weather,
757 'weathertitle' => implode(' ', $weathertitle),
758 'applications' => $applications
759 ];
760 }
761 }
762
763 //Sort sessions
764 ksort($calendar[$Ymd]['sessions']);
765 }
766
767 //Send result
768 return $calendar;
769 }
770
771 /**
772 * Find all session pending hourly weather
773 *
774 * @return array<Session> The sessions to update
775 */
776 public function findAllPendingHourlyWeather() {
777 //Get entity manager
778 $em = $this->getEntityManager();
779
780 //Get quote strategy
781 $qs = $em->getConfiguration()->getQuoteStrategy();
782 $dp = $em->getConnection()->getDatabasePlatform();
783
784 //Get quoted table names
785 //XXX: this allow to make this code table name independent
786 $tables = [
787 'RapsysAirBundle:Session' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Session'), $dp),
788 'RapsysAirBundle:Location' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Location'), $dp),
789 //Accuweather
790 ':accuhourly' => self::ACCUWEATHER_HOURLY,
791 //Delay
792 ':afterid' => 4,
793 "\t" => '',
794 "\n" => ' '
795 ];
796
797 //Select all sessions starting and stopping in the next 3 days
798 //XXX: select session starting after now and stopping before date(now)+3d as accuweather only provide hourly data for the next 3 days (INTERVAL 3 DAY)
799 $req = <<<SQL
800 SELECT s.id, s.slot_id, s.location_id, s.date, s.begin, s.length, s.rainfall, s.rainrisk, s.realfeel, s.realfeelmin, s.realfeelmax, s.temperature, s.temperaturemin, s.temperaturemax, l.zipcode
801 FROM RapsysAirBundle:Session AS s
802 JOIN RapsysAirBundle:Location AS l ON (l.id = s.location_id)
803 WHERE ADDDATE(ADDTIME(s.date, s.begin), INTERVAL IF(s.slot_id = :afterid, 1, 0) DAY) >= NOW() AND ADDDATE(ADDTIME(ADDTIME(s.date, s.begin), s.length), INTERVAL IF(s.slot_id = :afterid, 1, 0) DAY) < DATE(ADDDATE(NOW(), INTERVAL :accuhourly DAY))
804 SQL;
805
806 //Replace bundle entity name by table name
807 $req = str_replace(array_keys($tables), array_values($tables), $req);
808
809 //Get result set mapping instance
810 $rsm = new ResultSetMapping();
811
812 //Declare all fields
813 $rsm
814 ->addEntityResult('RapsysAirBundle:Session', 's')
815 ->addFieldResult('s', 'id', 'id')
816 ->addFieldResult('s', 'date', 'date')
817 ->addFieldResult('s', 'begin', 'begin')
818 ->addFieldResult('s', 'length', 'length')
819 ->addFieldResult('s', 'rainfall', 'rainfall')
820 ->addFieldResult('s', 'rainrisk', 'rainrisk')
821 ->addFieldResult('s', 'realfeel', 'realfeel')
822 ->addFieldResult('s', 'realfeelmin', 'realfeelmin')
823 ->addFieldResult('s', 'realfeelmax', 'realfeelmax')
824 ->addFieldResult('s', 'temperature', 'temperature')
825 ->addFieldResult('s', 'temperaturemin', 'temperaturemin')
826 ->addFieldResult('s', 'temperaturemax', 'temperaturemax')
827 ->addJoinedEntityResult('RapsysAirBundle:Slot', 'o', 's', 'slot')
828 ->addFieldResult('o', 'slot_id', 'id')
829 ->addJoinedEntityResult('RapsysAirBundle:Location', 'l', 's', 'location')
830 ->addFieldResult('l', 'location_id', 'id')
831 ->addFieldResult('l', 'zipcode', 'zipcode')
832 ->addIndexBy('s', 'id');
833
834 //Send result
835 return $em
836 ->createNativeQuery($req, $rsm)
837 ->getResult();
838 }
839
840 /**
841 * Find all session pending daily weather
842 *
843 * @return array<Session> The sessions to update
844 */
845 public function findAllPendingDailyWeather() {
846 //Get entity manager
847 $em = $this->getEntityManager();
848
849 //Get quote strategy
850 $qs = $em->getConfiguration()->getQuoteStrategy();
851 $dp = $em->getConnection()->getDatabasePlatform();
852
853 //Get quoted table names
854 //XXX: this allow to make this code table name independent
855 $tables = [
856 'RapsysAirBundle:Session' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Session'), $dp),
857 'RapsysAirBundle:Location' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Location'), $dp),
858 //Accuweather
859 ':accudaily' => self::ACCUWEATHER_DAILY,
860 ':accuhourly' => self::ACCUWEATHER_HOURLY,
861 //Delay
862 ':afterid' => 4,
863 "\t" => '',
864 "\n" => ' '
865 ];
866
867 //Select all sessions stopping after next 3 days
868 //XXX: select session stopping after or equal date(now)+3d as accuweather only provide hourly data for the next 3 days (INTERVAL 3 DAY)
869 $req = <<<SQL
870 SELECT s.id, s.slot_id, s.location_id, s.date, s.begin, s.length, s.rainfall, s.rainrisk, s.realfeel, s.realfeelmin, s.realfeelmax, s.temperature, s.temperaturemin, s.temperaturemax, l.zipcode
871 FROM RapsysAirBundle:Session AS s
872 JOIN RapsysAirBundle:Location AS l ON (l.id = s.location_id)
873 WHERE ADDDATE(ADDTIME(ADDTIME(s.date, s.begin), s.length), INTERVAL IF(s.slot_id = :afterid, 1, 0) DAY) >= DATE(ADDDATE(NOW(), INTERVAL :accuhourly DAY)) AND ADDDATE(ADDTIME(ADDTIME(s.date, s.begin), s.length), INTERVAL IF(s.slot_id = :afterid, 1, 0) DAY) < DATE(ADDDATE(NOW(), INTERVAL :accudaily DAY))
874 SQL;
875
876 //Replace bundle entity name by table name
877 $req = str_replace(array_keys($tables), array_values($tables), $req);
878
879 //Get result set mapping instance
880 $rsm = new ResultSetMapping();
881
882 //Declare all fields
883 $rsm
884 ->addEntityResult('RapsysAirBundle:Session', 's')
885 ->addFieldResult('s', 'id', 'id')
886 ->addFieldResult('s', 'date', 'date')
887 ->addFieldResult('s', 'begin', 'begin')
888 ->addFieldResult('s', 'length', 'length')
889 ->addFieldResult('s', 'rainfall', 'rainfall')
890 ->addFieldResult('s', 'rainrisk', 'rainrisk')
891 ->addFieldResult('s', 'realfeel', 'realfeel')
892 ->addFieldResult('s', 'realfeelmin', 'realfeelmin')
893 ->addFieldResult('s', 'realfeelmax', 'realfeelmax')
894 ->addFieldResult('s', 'temperature', 'temperature')
895 ->addFieldResult('s', 'temperaturemin', 'temperaturemin')
896 ->addFieldResult('s', 'temperaturemax', 'temperaturemax')
897 ->addJoinedEntityResult('RapsysAirBundle:Slot', 'o', 's', 'slot')
898 ->addFieldResult('o', 'slot_id', 'id')
899 ->addJoinedEntityResult('RapsysAirBundle:Location', 'l', 's', 'location')
900 ->addFieldResult('l', 'location_id', 'id')
901 ->addFieldResult('l', 'zipcode', 'zipcode')
902 ->addIndexBy('s', 'id');
903
904 //Send result
905 return $em
906 ->createNativeQuery($req, $rsm)
907 ->getResult();
908 }
909
910 /**
911 * Find every session pending application
912 *
913 * @return array<Session> The sessions to update
914 */
915 public function findAllPendingApplication() {
916 //Get entity manager
917 $em = $this->getEntityManager();
918
919 //Get quote strategy
920 $qs = $em->getConfiguration()->getQuoteStrategy();
921 $dp = $em->getConnection()->getDatabasePlatform();
922
923 //Get quoted table names
924 //XXX: this allow to make this code table name independent
925 $tables = [
926 'RapsysAirBundle:Application' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Application'), $dp),
927 'RapsysAirBundle:Session' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Session'), $dp),
928 //Delay
929 ':regulardelay' => self::REGULAR_DELAY * 24 * 3600,
930 ':seniordelay' => self::SENIOR_DELAY * 24 * 3600,
931 //Slot
932 ':afterid' => 4,
933 "\t" => '',
934 "\n" => ' '
935 ];
936
937 //Select all sessions not locked without application or canceled application within attribution period
938 //XXX: DIFF(start, now) <= IF(DIFF(start, created) <= SENIOR_DELAY in DAY, DIFF(start, created) * 3 / 4, SENIOR_DELAY)
939 //TODO: remonter les donnΓ©es pour le mail ?
940 $req =<<<SQL
941 SELECT s.id
942 FROM RapsysAirBundle:Session as s
943 LEFT JOIN RapsysAirBundle:Application AS a ON (a.id = s.application_id AND a.canceled IS NULL)
944 JOIN RapsysAirBundle:Application AS a2 ON (a2.session_id = s.id AND a2.canceled IS NULL)
945 WHERE s.locked IS NULL AND a.id IS NULL AND
946 TIME_TO_SEC(TIMEDIFF(@dt_start := ADDDATE(ADDTIME(s.date, s.begin), INTERVAL IF(s.slot_id = :afterid, 1, 0) DAY), NOW())) <= IF(
947 TIME_TO_SEC(@td_sc := TIMEDIFF(@dt_start, s.created)) <= :seniordelay,
948 ROUND(TIME_TO_SEC(@td_sc) * :regulardelay / :seniordelay),
949 :seniordelay
950 )
951 GROUP BY s.id
952 ORDER BY @dt_start ASC, s.created ASC
953 SQL;
954
955
956 //Replace bundle entity name by table name
957 $req = str_replace(array_keys($tables), array_values($tables), $req);
958
959 //Get result set mapping instance
960 $rsm = new ResultSetMapping();
961
962 //Declare all fields
963 $rsm
964 ->addEntityResult('RapsysAirBundle:Session', 's')
965 ->addFieldResult('s', 'id', 'id')
966 ->addIndexBy('s', 'id');
967
968 //Send result
969 return $em
970 ->createNativeQuery($req, $rsm)
971 ->getResult();
972 }
973
974 /**
975 * Fetch session best application by session id
976 *
977 * @param int $id The session id
978 * @return Application|null The application or null
979 */
980 public function findBestApplicationById($id) {
981 //Get entity manager
982 $em = $this->getEntityManager();
983
984 //Get quote strategy
985 $qs = $em->getConfiguration()->getQuoteStrategy();
986 $dp = $em->getConnection()->getDatabasePlatform();
987
988 //Get quoted table names
989 //XXX: this allow to make this code table name independent
990 $tables = [
991 'RapsysAirBundle:Application' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Application'), $dp),
992 'RapsysAirBundle:GroupUser' => $qs->getJoinTableName($em->getClassMetadata('RapsysAirBundle:User')->getAssociationMapping('groups'), $em->getClassMetadata('RapsysAirBundle:User'), $dp),
993 'RapsysAirBundle:Location' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Location'), $dp),
994 'RapsysAirBundle:Session' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Session'), $dp),
995 //XXX: Set limit used to workaround mariadb subselect optimization
996 ':limit' => PHP_INT_MAX,
997 //Delay
998 ':guestdelay' => self::GUEST_DELAY * 24 * 3600,
999 ':regulardelay' => self::REGULAR_DELAY * 24 * 3600,
1000 ':seniordelay' => self::SENIOR_DELAY * 24 * 3600,
1001 //Group
1002 ':guestid' => 2,
1003 ':regularid' => 3,
1004 ':seniorid' => 4,
1005 //Slot
1006 ':afternoonid' => 2,
1007 ':eveningid' => 3,
1008 ':afterid' => 4,
1009 //XXX: days since last session after which guest regain normal priority
1010 ':guestwait' => 30,
1011 //XXX: session count until considered at regular delay
1012 ':scount' => 5,
1013 //XXX: pn_ratio over which considered at regular delay
1014 ':pnratio' => 1,
1015 //XXX: tr_ratio diff over which considered at regular delay
1016 ':trdiff' => 5,
1017 "\t" => '',
1018 "\n" => ' '
1019 ];
1020
1021 /**
1022 * Query session applications ranked by location score, global score, created and user_id
1023 *
1024 * @xxx guest (or less) with application on location within 30 day are only considered within guestdelay
1025 *
1026 * @xxx regular (or less) premium application on hotspot are only considered within regulardelay
1027 *
1028 * @xxx senior (or less) with 5 or less session on location are only considered within seniordelay
1029 *
1030 * @xxx senior (or less) with l_pn_ratio >= 1 are only considered within seniordelay
1031 *
1032 * @xxx senior (or less) with l_tr_ratio >= (o_tr_ratio + 5) are only considered within seniordelay
1033 *
1034 * @xxx only consider session within one year (may be unaccurate by the day with after session)
1035 *
1036 * @xxx rainfall may not be accessible for previous session and other session at d-4 (only at d-2)
1037 *
1038 * @todo ??? feedback the data to inform the rejected users ???
1039 */
1040 $req = <<<SQL
1041 SELECT e.id, e.l_score AS score
1042 FROM (
1043 SELECT
1044 d.id,
1045 d.user_id,
1046 d.l_count,
1047 d.l_score,
1048 d.l_tr_ratio,
1049 d.l_pn_ratio,
1050 d.l_previous,
1051 d.g_score,
1052 d.o_tr_ratio,
1053 MAX(gu.group_id) AS group_id,
1054 d.remaining,
1055 d.premium,
1056 d.hotspot,
1057 d.created
1058 FROM (
1059 SELECT
1060 c.id,
1061 c.user_id,
1062 c.l_count,
1063 c.l_score,
1064 c.l_tr_ratio,
1065 c.l_pn_ratio,
1066 c.l_previous,
1067 c.g_score,
1068 AVG(IF(a4.id IS NOT NULL AND s4.temperature IS NOT NULL AND s4.rainfall IS NOT NULL, s4.temperature/(1+s4.rainfall), NULL)) AS o_tr_ratio,
1069 c.remaining,
1070 c.premium,
1071 c.hotspot,
1072 c.created
1073 FROM (
1074 SELECT
1075 b.id,
1076 b.user_id,
1077 b.session_id,
1078 b.date,
1079 b.location_id,
1080 b.l_count,
1081 b.l_score,
1082 b.l_tr_ratio,
1083 b.l_pn_ratio,
1084 b.l_previous,
1085 SUM(IF(a3.id IS NOT NULL, 1/ABS(DATEDIFF(ADDDATE(b.date, INTERVAL IF(b.slot_id = :afterid, 1, 0) DAY), ADDDATE(s3.date, INTERVAL IF(s3.slot_id = :afterid, 1, 0) DAY))), 0)) AS g_score,
1086 b.remaining,
1087 b.premium,
1088 b.hotspot,
1089 b.created
1090 FROM (
1091 SELECT
1092 a.id,
1093 a.user_id,
1094 s.id AS session_id,
1095 s.date AS date,
1096 s.slot_id,
1097 s.location_id,
1098 COUNT(a2.id) AS l_count,
1099 SUM(IF(a2.id IS NOT NULL, 1/ABS(DATEDIFF(ADDDATE(s.date, INTERVAL IF(s.slot_id = :afterid, 1, 0) DAY), ADDDATE(s2.date, INTERVAL IF(s2.slot_id = :afterid, 1, 0) DAY))), 0)) AS l_score,
1100 AVG(IF(a2.id IS NOT NULL AND s2.temperature IS NOT NULL AND s2.rainfall IS NOT NULL, s2.temperature/(1+s2.rainfall), NULL)) AS l_tr_ratio,
1101 (SUM(IF(a2.id IS NOT NULL AND s2.premium = 1, 1, 0))+1)/(SUM(IF(a2.id IS NOT NULL AND s2.premium = 0, 1, 0))+1) AS l_pn_ratio,
1102 MIN(IF(a2.id IS NOT NULL, DATEDIFF(ADDDATE(s.date, INTERVAL IF(s.slot_id = :afterid, 1, 0) DAY), ADDDATE(s2.date, INTERVAL IF(s2.slot_id = :afterid, 1, 0) DAY)), NULL)) AS l_previous,
1103 TIME_TO_SEC(TIMEDIFF(ADDDATE(ADDTIME(s.date, s.begin), INTERVAL IF(s.slot_id = :afterid, 1, 0) DAY), NOW())) AS remaining,
1104 s.premium,
1105 l.hotspot,
1106 a.created
1107 FROM RapsysAirBundle:Session AS s
1108 JOIN RapsysAirBundle:Location AS l ON (l.id = s.location_id)
1109 JOIN RapsysAirBundle:Application AS a ON (a.session_id = s.id AND a.canceled IS NULL)
1110 LEFT JOIN RapsysAirBundle:Session AS s2 ON (s2.id != s.id AND s2.location_id = s.location_id AND s2.slot_id IN (:afternoonid, :eveningid) AND s2.application_id IS NOT NULL AND s2.locked IS NULL AND s2.date > s.date - INTERVAL 1 YEAR)
1111 LEFT JOIN RapsysAirBundle:Application AS a2 ON (a2.id = s2.application_id AND a2.user_id = a.user_id AND (a2.canceled IS NULL OR TIMESTAMPDIFF(DAY, a2.canceled, ADDDATE(ADDTIME(s2.date, s2.begin), INTERVAL IF(s2.slot_id = :afterid, 1, 0) DAY)) < 1))
1112 WHERE s.id = :sid
1113 GROUP BY a.id
1114 ORDER BY NULL
1115 LIMIT 0, :limit
1116 ) AS b
1117 LEFT JOIN RapsysAirBundle:Session AS s3 ON (s3.id != b.session_id AND s3.application_id IS NOT NULL AND s3.locked IS NULL AND s3.date > b.date - INTERVAL 1 YEAR)
1118 LEFT JOIN RapsysAirBundle:Application AS a3 ON (a3.id = s3.application_id AND a3.user_id = b.user_id AND (a3.canceled IS NULL OR TIMESTAMPDIFF(DAY, a3.canceled, ADDDATE(ADDTIME(s3.date, s3.begin), INTERVAL IF(s3.slot_id = :afterid, 1, 0) DAY)) < 1))
1119 GROUP BY b.id
1120 ORDER BY NULL
1121 LIMIT 0, :limit
1122 ) AS c
1123 LEFT JOIN RapsysAirBundle:Session AS s4 ON (s4.id != c.session_id AND s4.location_id = c.location_id AND s4.application_id IS NOT NULL AND s4.locked IS NULL AND s4.date > c.date - INTERVAL 1 YEAR)
1124 LEFT JOIN RapsysAirBundle:Application AS a4 ON (a4.id = s4.application_id AND a4.user_id != c.user_id AND (a4.canceled IS NULL OR TIMESTAMPDIFF(DAY, a4.canceled, ADDDATE(ADDTIME(s4.date, s4.begin), INTERVAL IF(s4.slot_id = :afterid, 1, 0) DAY)) < 1))
1125 GROUP BY c.id
1126 ORDER BY NULL
1127 LIMIT 0, :limit
1128 ) AS d
1129 LEFT JOIN RapsysAirBundle:GroupUser AS gu ON (gu.user_id = d.user_id)
1130 GROUP BY d.id
1131 LIMIT 0, :limit
1132 ) AS e
1133 WHERE
1134 IF(e.group_id <= :guestid AND e.l_previous <= :guestwait, e.remaining <= :guestdelay, 1) AND
1135 IF(e.group_id <= :regularid AND e.premium = 1 AND e.hotspot = 1, e.remaining <= :regulardelay, 1) AND
1136 IF(e.group_id <= :seniorid AND e.l_count <= :scount, e.remaining <= :regulardelay, 1) AND
1137 IF(e.group_id <= :seniorid AND e.l_pn_ratio >= :pnratio, e.remaining <= :regulardelay, 1) AND
1138 IF(e.group_id <= :seniorid AND e.l_tr_ratio >= (e.o_tr_ratio + :trdiff), e.remaining <= :regulardelay, 1)
1139 ORDER BY e.l_score ASC, e.g_score ASC, e.created ASC, e.user_id ASC
1140 SQL;
1141
1142 //Replace bundle entity name by table name
1143 $req = str_replace(array_keys($tables), array_values($tables), $req);
1144
1145 //Set update request
1146 $upreq = 'UPDATE RapsysAirBundle:Application SET score = :score, updated = NOW() WHERE id = :id';
1147
1148 //Replace bundle entity name by table name
1149 $upreq = str_replace(array_keys($tables), array_values($tables), $upreq);
1150
1151 //Get result set mapping instance
1152 $rsm = new ResultSetMapping();
1153
1154 //Declare all fields
1155 $rsm
1156 ->addEntityResult('RapsysAirBundle:Application', 'a')
1157 ->addFieldResult('a', 'id', 'id')
1158 ->addFieldResult('a', 'score', 'score')
1159 ->addIndexBy('a', 'id');
1160
1161 //Get result
1162 //XXX: setting limit in subqueries is required to prevent mariadb optimisation
1163 $applications = $em
1164 ->createNativeQuery($req, $rsm)
1165 ->setParameter('sid', $id)
1166 //XXX: removed, we update score before returning best candidate
1167 //->getOneOrNullResult(Query::HYDRATE_SINGLE_SCALAR);
1168 ->getResult();
1169
1170 //Init ret
1171 $ret = null;
1172
1173 //Update score
1174 foreach($applications as $application) {
1175 //Check if we already saved best candidate
1176 if ($ret === null) {
1177 //Return first application
1178 $ret = $application;
1179 }
1180
1181 //Update application updated field
1182 //XXX: updated field is not modified for user with bad behaviour as application is not retrieved until delay is reached
1183 $em->getConnection()->executeUpdate($upreq, ['id' => $application->getId(), 'score' => $application->getScore()], ['id' => Type::INTEGER, 'score' => Type::FLOAT]);
1184 }
1185
1186 //Return best ranked application
1187 return $ret;
1188 }
1189 }