3 namespace Rapsys\AirBundle\Repository
;
5 use Symfony\Component\Translation\TranslatorInterface
;
6 use Doctrine\DBAL\Types\Type
;
7 use Doctrine\ORM\Query\ResultSetMapping
;
8 use Doctrine\ORM\Query
;
13 class SessionRepository
extends \Doctrine\ORM\EntityRepository
{
14 ///Set accuweather max number of daily pages
15 const ACCUWEATHER_DAILY
= 12;
17 ///Set accuweather max number of hourly pages
18 const ACCUWEATHER_HOURLY
= 3;
21 const GUEST_DELAY
= 2;
24 const REGULAR_DELAY
= 3;
27 const SENIOR_DELAY
= 4;
30 //TODO: document utf-8 codes ?
33 'Morning' => 'π
', #0001f305
34 'Afternoon' => 'βοΈ', #2600
35 'Evening' => 'π', #0001f307
36 'After' => 'β¨', #2728
38 'Cleary' => 'β', #2600
39 'Sunny' => 'β
', #26c5
40 'Cloudy' => 'β', #2601
41 'Winty' => 'βοΈ', #2744
42 'Rainy' => 'π', #0001f302
43 'Stormy' => 'β' #2614
47 * Find session by location, slot and date
49 * @param $location The location
50 * @param $slot The slot
51 * @param $date The datetime
53 public function findOneByLocationSlotDate($location, $slot, $date) {
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)
64 * Find sessions by date period
66 * @param $period The date period
68 public function findAllByDatePeriod($period) {
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())
78 * Find sessions by location and date period
80 * @param $location The location
81 * @param $period The date period
83 public function findAllByLocationDatePeriod($location, $period) {
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())
94 * Find one session by location and user id within last month
96 * @param $location The location id
97 * @param $user The user id
99 public function findOneWithinLastMonthByLocationUser($location, $user) {
101 $em = $this->getEntityManager();
104 $qs = $em->getConfiguration()->getQuoteStrategy();
105 $dp = $em->getConnection()->getDatabasePlatform();
107 //Get quoted table names
108 //XXX: this allow to make this code table name independent
110 'RapsysAirBundle:Session' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Session'), $dp),
111 'RapsysAirBundle:Application' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Application'), $dp),
117 //XXX: give the gooddelay to guest just in case
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)
125 //Replace bundle entity name by table name
126 $req = str_replace(array_keys($tables), array_values($tables), $req);
128 //Get result set mapping instance
129 $rsm = new ResultSetMapping();
132 //XXX: see vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/Types.php
133 $rsm->addScalarResult('id', 'id', 'integer')
134 ->addIndexByScalar('id');
138 ->createNativeQuery($req, $rsm)
139 ->setParameter('lid', $location)
140 ->setParameter('uid', $user)
141 ->setParameter('gooddelay', self
::SENIOR_DELAY
)
142 ->getOneOrNullResult();
146 * Fetch session by id
148 * @param $id The session id
149 * @return array The session data
151 public function fetchOneById($id) {
153 $em = $this->getEntityManager();
156 $qs = $em->getConfiguration()->getQuoteStrategy();
157 $dp = $em->getConnection()->getDatabasePlatform();
159 //Get quoted table names
160 //XXX: this allow to make this code table name independent
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),
176 //TODO: compute scores ?
177 //TODO: compute delivery date ? (J-3/J-4 ?)
183 ADDDATE(ADDTIME(s.date, s.begin), INTERVAL IF(s.slot_id = :afterid, 1, 0) DAY) AS start,
185 ADDDATE(ADDTIME(ADDTIME(s.date, s.begin), s.length), INTERVAL IF(s.slot_id = :afterid, 1, 0) DAY) AS stop,
197 s.location_id AS l_id,
200 l.address AS l_address,
201 l.zipcode AS l_zipcode,
203 l.latitude AS l_latitude,
204 l.longitude AS l_longitude,
207 s.application_id AS a_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)
229 //Replace bundle entity name by table name
230 $req = str_replace(array_keys($tables), array_values($tables), $req);
232 //Get result set mapping instance
233 //XXX: DEBUG: see ../blog.orig/src/Rapsys/BlogBundle/Repository/ArticleRepository.php
234 $rsm = new ResultSetMapping();
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');
286 ->createNativeQuery($req, $rsm)
287 ->setParameter('sid', $id)
288 ->getOneOrNullResult();
292 * Fetch sessions calendar with translated location by date period
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
300 public function fetchCalendarByDatePeriod(TranslatorInterface
$translator, $period, $locationId = null, $sessionId = null, $granted = false) {
302 $em = $this->getEntityManager();
305 $qs = $em->getConfiguration()->getQuoteStrategy();
306 $dp = $em->getConnection()->getDatabasePlatform();
308 //Get quoted table names
309 //XXX: this allow to make this code table name independent
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),
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':'').'
337 //Replace bundle entity name by table name
338 $req = str_replace(array_keys($tables), array_values($tables), $req);
340 //Get result set mapping instance
341 //XXX: DEBUG: see ../blog.orig/src/Rapsys/BlogBundle/Repository/ArticleRepository.php
342 $rsm = new ResultSetMapping();
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');
369 ->createNativeQuery($req, $rsm)
370 ->setParameter('begin', $period->getStartDate())
371 ->setParameter('end', $period->getEndDate())
372 ->setParameter('lid', $locationId)
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'),
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;
400 if ($date->format('U') == ($today = strtotime('today'))) {
401 $calendar[$Ymd]['title'] .= '/'.$month;
402 $calendar[$Ymd]['current'] = true;
403 $calendar[$Ymd]['class'][] = 'current';
405 //Disable passed days
406 if ($date->format('U') < $today) {
407 $calendar[$Ymd]['disabled'] = true;
408 $calendar[$Ymd]['class'][] = 'disabled';
410 //Set next month days
411 if ($date->format('m') > date('m')) {
412 $calendar[$Ymd]['next'] = true;
413 $calendar[$Ymd]['class'][] = 'next';
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']));
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';
432 $class[] = 'pending';
435 if ($sessionId == $session['id']) {
436 $class[] = 'highlight';
440 //XXX: realfeel may be null, temperature should not
441 $temperature = $session['realfeel'] !== null ? $session['realfeel'] : $session['temperature'];
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'];
464 //Check if realfeel is available
465 if ($session['realfeel'] !== null) {
466 $weathertitle[] = $session['realfeel'].'Β°R';
469 //Check if temperature is available
470 if ($session['temperature'] !== null) {
471 $weathertitle[] = $session['temperature'].'Β°C';
474 //Check if rainrisk is available
475 if ($session['rainrisk'] !== null) {
476 $weathertitle[] = ($session['rainrisk']*100).'%';
479 //Check if rainfall is available
480 if ($session['rainfall'] !== null) {
481 $weathertitle[] = $session['rainfall'].'mm';
486 0 => $translator->trans($session['t_title']).' '.$translator->trans('at '.$session['l_title']).$translator->trans(':')
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'])));
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
500 //Set location title with optional count
501 $title = $translator->trans($session['l_title']).($count > 1 ? ' ['.$count.']':'');
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.']':'');
512 $calendar[$Ymd]['sessions'][$session['t_id'].sprintf('%02d', $session['l_id'])] = [
513 'id' => $session['id'],
516 'slot' => self
::GLYPHS
[$session['t_title']],
517 'slottitle' => $translator->trans($session['t_title']),
518 'weather' => $weather,
519 'weathertitle' => implode(' ', $weathertitle),
520 'applications' => $applications
526 ksort($calendar[$Ymd]['sessions']);
534 * Fetch sessions calendar with translated location by date period and user
536 * @param $translator The TranslatorInterface instance
537 * @param $period The date period
538 * @param $userId The user id
539 * @param $sessionId The session id
541 public function fetchUserCalendarByDatePeriod(TranslatorInterface
$translator, $period, $userId = null, $sessionId = null) {
543 $em = $this->getEntityManager();
546 $qs = $em->getConfiguration()->getQuoteStrategy();
547 $dp = $em->getConnection()->getDatabasePlatform();
549 //Get quoted table names
550 //XXX: this allow to make this code table name independent
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),
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':'').'
578 //Replace bundle entity name by table name
579 $req = str_replace(array_keys($tables), array_values($tables), $req);
581 //Get result set mapping instance
582 //XXX: DEBUG: see ../blog.orig/src/Rapsys/BlogBundle/Repository/ArticleRepository.php
583 $rsm = new ResultSetMapping();
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');
610 ->createNativeQuery($req, $rsm)
611 ->setParameter('begin', $period->getStartDate())
612 ->setParameter('end', $period->getEndDate())
613 ->setParameter('uid', $userId)
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'),
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;
641 if ($date->format('U') == ($today = strtotime('today'))) {
642 $calendar[$Ymd]['title'] .= '/'.$month;
643 $calendar[$Ymd]['current'] = true;
644 $calendar[$Ymd]['class'][] = 'current';
646 //Disable passed days
647 if ($date->format('U') < $today) {
648 $calendar[$Ymd]['disabled'] = true;
649 $calendar[$Ymd]['class'][] = 'disabled';
651 //Set next month days
652 if ($date->format('m') > date('m')) {
653 $calendar[$Ymd]['next'] = true;
654 $calendar[$Ymd]['class'][] = 'next';
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']));
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';
670 $class[] = 'disputed';
672 } elseif ($count == 0) {
673 $class[] = 'orphaned';
674 } elseif ($count > 1) {
675 $class[] = 'disputed';
677 $class[] = 'pending';
680 if ($sessionId == $session['id']) {
681 $class[] = 'highlight';
685 //XXX: realfeel may be null, temperature should not
686 $temperature = $session['realfeel'] !== null ? $session['realfeel'] : $session['temperature'];
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'];
709 //Check if realfeel is available
710 if ($session['realfeel'] !== null) {
711 $weathertitle[] = $session['realfeel'].'Β°R';
714 //Check if temperature is available
715 if ($session['temperature'] !== null) {
716 $weathertitle[] = $session['temperature'].'Β°C';
719 //Check if rainrisk is available
720 if ($session['rainrisk'] !== null) {
721 $weathertitle[] = ($session['rainrisk']*100).'%';
724 //Check if rainfall is available
725 if ($session['rainfall'] !== null) {
726 $weathertitle[] = $session['rainfall'].'mm';
731 0 => $translator->trans($session['t_title']).' '.$translator->trans('at '.$session['l_title']).$translator->trans(':')
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']));
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'];
747 $title = $translator->trans($session['l_title']).($count > 1 ? ' ['.$count.']':'');
750 $calendar[$Ymd]['sessions'][$session['t_id'].sprintf('%02d', $session['l_id'])] = [
751 'id' => $session['id'],
754 'slot' => self
::GLYPHS
[$session['t_title']],
755 'slottitle' => $translator->trans($session['t_title']),
756 'weather' => $weather,
757 'weathertitle' => implode(' ', $weathertitle),
758 'applications' => $applications
764 ksort($calendar[$Ymd]['sessions']);
772 * Find all session pending hourly weather
774 * @return array<Session> The sessions to update
776 public function findAllPendingHourlyWeather() {
778 $em = $this->getEntityManager();
781 $qs = $em->getConfiguration()->getQuoteStrategy();
782 $dp = $em->getConnection()->getDatabasePlatform();
784 //Get quoted table names
785 //XXX: this allow to make this code table name independent
787 'RapsysAirBundle:Session' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Session'), $dp),
788 'RapsysAirBundle:Location' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Location'), $dp),
790 ':accuhourly' => self
::ACCUWEATHER_HOURLY
,
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)
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))
806 //Replace bundle entity name by table name
807 $req = str_replace(array_keys($tables), array_values($tables), $req);
809 //Get result set mapping instance
810 $rsm = new ResultSetMapping();
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');
836 ->createNativeQuery($req, $rsm)
841 * Find all session pending daily weather
843 * @return array<Session> The sessions to update
845 public function findAllPendingDailyWeather() {
847 $em = $this->getEntityManager();
850 $qs = $em->getConfiguration()->getQuoteStrategy();
851 $dp = $em->getConnection()->getDatabasePlatform();
853 //Get quoted table names
854 //XXX: this allow to make this code table name independent
856 'RapsysAirBundle:Session' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Session'), $dp),
857 'RapsysAirBundle:Location' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Location'), $dp),
859 ':accudaily' => self
::ACCUWEATHER_DAILY
,
860 ':accuhourly' => self
::ACCUWEATHER_HOURLY
,
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)
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))
876 //Replace bundle entity name by table name
877 $req = str_replace(array_keys($tables), array_values($tables), $req);
879 //Get result set mapping instance
880 $rsm = new ResultSetMapping();
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');
906 ->createNativeQuery($req, $rsm)
911 * Find every session pending application
913 * @return array<Session> The sessions to update
915 public function findAllPendingApplication() {
917 $em = $this->getEntityManager();
920 $qs = $em->getConfiguration()->getQuoteStrategy();
921 $dp = $em->getConnection()->getDatabasePlatform();
923 //Get quoted table names
924 //XXX: this allow to make this code table name independent
926 'RapsysAirBundle:Application' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Application'), $dp),
927 'RapsysAirBundle:Session' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Session'), $dp),
929 ':regulardelay' => self
::REGULAR_DELAY
* 24 * 3600,
930 ':seniordelay' => self
::SENIOR_DELAY
* 24 * 3600,
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 ?
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),
952 ORDER BY @dt_start ASC, s.created ASC
956 //Replace bundle entity name by table name
957 $req = str_replace(array_keys($tables), array_values($tables), $req);
959 //Get result set mapping instance
960 $rsm = new ResultSetMapping();
964 ->addEntityResult('RapsysAirBundle:Session', 's')
965 ->addFieldResult('s', 'id', 'id')
966 ->addIndexBy('s', 'id');
970 ->createNativeQuery($req, $rsm)
975 * Fetch session best application by session id
977 * @param int $id The session id
978 * @return Application|null The application or null
980 public function findBestApplicationById($id) {
982 $em = $this->getEntityManager();
985 $qs = $em->getConfiguration()->getQuoteStrategy();
986 $dp = $em->getConnection()->getDatabasePlatform();
988 //Get quoted table names
989 //XXX: this allow to make this code table name independent
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
,
998 ':guestdelay' => self
::GUEST_DELAY
* 24 * 3600,
999 ':regulardelay' => self
::REGULAR_DELAY
* 24 * 3600,
1000 ':seniordelay' => self
::SENIOR_DELAY
* 24 * 3600,
1006 ':afternoonid' => 2,
1009 //XXX: days since last session after which guest regain normal priority
1011 //XXX: session count until considered at regular delay
1013 //XXX: pn_ratio over which considered at regular delay
1015 //XXX: tr_ratio diff over which considered at regular delay
1022 * Query session applications ranked by location score, global score, created and user_id
1024 * @xxx guest (or less) with application on location within 30 day are only considered within guestdelay
1026 * @xxx regular (or less) premium application on hotspot are only considered within regulardelay
1028 * @xxx senior (or less) with 5 or less session on location are only considered within seniordelay
1030 * @xxx senior (or less) with l_pn_ratio >= 1 are only considered within seniordelay
1032 * @xxx senior (or less) with l_tr_ratio >= (o_tr_ratio + 5) are only considered within seniordelay
1034 * @xxx only consider session within one year (may be unaccurate by the day with after session)
1036 * @xxx rainfall may not be accessible for previous session and other session at d-4 (only at d-2)
1038 * @todo ??? feedback the data to inform the rejected users ???
1041 SELECT e.id, e.l_score AS score
1053 MAX(gu.group_id) AS group_id,
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,
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,
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,
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))
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))
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))
1129 LEFT JOIN RapsysAirBundle:GroupUser AS gu ON (gu.user_id = d.user_id)
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
1142 //Replace bundle entity name by table name
1143 $req = str_replace(array_keys($tables), array_values($tables), $req);
1145 //Set update request
1146 $upreq = 'UPDATE RapsysAirBundle:Application SET score = :score, updated = NOW() WHERE id = :id';
1148 //Replace bundle entity name by table name
1149 $upreq = str_replace(array_keys($tables), array_values($tables), $upreq);
1151 //Get result set mapping instance
1152 $rsm = new ResultSetMapping();
1154 //Declare all fields
1156 ->addEntityResult('RapsysAirBundle:Application', 'a')
1157 ->addFieldResult('a', 'id', 'id')
1158 ->addFieldResult('a', 'score', 'score')
1159 ->addIndexBy('a', 'id');
1162 //XXX: setting limit in subqueries is required to prevent mariadb optimisation
1164 ->createNativeQuery($req, $rsm)
1165 ->setParameter('sid', $id)
1166 //XXX: removed, we update score before returning best candidate
1167 //->getOneOrNullResult(Query::HYDRATE_SINGLE_SCALAR);
1174 foreach($applications as $application) {
1175 //Check if we already saved best candidate
1176 if ($ret === null) {
1177 //Return first application
1178 $ret = $application;
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]);
1186 //Return best ranked application