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 * @param $locale The locale
150 * @return array The session data
152 public function fetchOneById($id, $locale = null) {
154 $em = $this->getEntityManager();
157 $qs = $em->getConfiguration()->getQuoteStrategy();
158 $dp = $em->getConnection()->getDatabasePlatform();
160 //Get quoted table names
161 //XXX: this allow to make this code table name independent
163 'RapsysAirBundle:Application' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Application'), $dp),
164 'RapsysAirBundle:Group' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Group'), $dp),
165 'RapsysAirBundle:GroupUser' => $qs->getJoinTableName($em->getClassMetadata('RapsysAirBundle:User')->getAssociationMapping('groups'), $em->getClassMetadata('RapsysAirBundle:User'), $dp),
166 'RapsysAirBundle:Location' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Location'), $dp),
167 'RapsysAirBundle:Session' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Session'), $dp),
168 'RapsysAirBundle:Snippet' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Snippet'), $dp),
169 'RapsysAirBundle:Slot' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Slot'), $dp),
170 'RapsysAirBundle:User' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:User'), $dp),
177 //TODO: compute scores ?
178 //TODO: compute delivery date ? (J-3/J-4 ?)
184 ADDDATE(ADDTIME(s.date, s.begin), INTERVAL IF(s.slot_id = :afterid, 1, 0) DAY) AS start,
186 ADDDATE(ADDTIME(ADDTIME(s.date, s.begin), s.length), INTERVAL IF(s.slot_id = :afterid, 1, 0) DAY) AS stop,
198 s.location_id AS l_id,
201 l.address AS l_address,
202 l.zipcode AS l_zipcode,
204 l.latitude AS l_latitude,
205 l.longitude AS l_longitude,
208 s.application_id AS a_id,
209 a.canceled AS a_canceled,
211 au.pseudonym AS au_pseudonym,
213 p.description AS p_description,
215 p.contact AS p_contact,
216 p.donate AS p_donate,
218 p.profile AS p_profile,
219 GROUP_CONCAT(sa.id ORDER BY sa.user_id SEPARATOR "\\n") AS sa_id,
220 GROUP_CONCAT(IFNULL(sa.score, 'NULL') ORDER BY sa.user_id SEPARATOR "\\n") AS sa_score,
221 GROUP_CONCAT(sa.created ORDER BY sa.user_id SEPARATOR "\\n") AS sa_created,
222 GROUP_CONCAT(sa.updated ORDER BY sa.user_id SEPARATOR "\\n") AS sa_updated,
223 GROUP_CONCAT(IFNULL(sa.canceled, 'NULL') ORDER BY sa.user_id SEPARATOR "\\n") AS sa_canceled,
224 GROUP_CONCAT(sa.user_id ORDER BY sa.user_id SEPARATOR "\\n") AS sau_id,
225 GROUP_CONCAT(sau.pseudonym ORDER BY sa.user_id SEPARATOR "\\n") AS sau_pseudonym
226 FROM RapsysAirBundle:Session AS s
227 JOIN RapsysAirBundle:Location AS l ON (l.id = s.location_id)
228 JOIN RapsysAirBundle:Slot AS t ON (t.id = s.slot_id)
229 LEFT JOIN RapsysAirBundle:Application AS a ON (a.id = s.application_id)
230 LEFT JOIN RapsysAirBundle:User AS au ON (au.id = a.user_id)
231 LEFT JOIN RapsysAirBundle:Snippet AS p ON (p.location_id = s.location_id AND p.user_id = a.user_id AND p.locale = :locale)
232 LEFT JOIN RapsysAirBundle:Application AS sa ON (sa.session_id = s.id)
233 LEFT JOIN RapsysAirBundle:User AS sau ON (sau.id = sa.user_id)
239 //Replace bundle entity name by table name
240 $req = str_replace(array_keys($tables), array_values($tables), $req);
242 //Get result set mapping instance
243 //XXX: DEBUG: see ../blog.orig/src/Rapsys/BlogBundle/Repository/ArticleRepository.php
244 $rsm = new ResultSetMapping();
247 //XXX: see vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/Types.php
248 $rsm->addScalarResult('id', 'id', 'integer')
249 ->addScalarResult('date', 'date', 'date')
250 ->addScalarResult('begin', 'begin', 'time')
251 ->addScalarResult('start', 'start', 'datetime')
252 ->addScalarResult('length', 'length', 'time')
253 ->addScalarResult('stop', 'stop', 'datetime')
254 ->addScalarResult('rainfall', 'rainfall', 'float')
255 ->addScalarResult('rainrisk', 'rainrisk', 'float')
256 ->addScalarResult('realfeel', 'realfeel', 'float')
257 ->addScalarResult('realfeelmin', 'realfeelmin', 'float')
258 ->addScalarResult('realfeelmax', 'realfeelmax', 'float')
259 ->addScalarResult('temperature', 'temperature', 'float')
260 ->addScalarResult('temperaturemin', 'temperaturemin', 'float')
261 ->addScalarResult('temperaturemax', 'temperaturemax', 'float')
262 ->addScalarResult('locked', 'locked', 'datetime')
263 ->addScalarResult('created', 'created', 'datetime')
264 ->addScalarResult('updated', 'updated', 'datetime')
265 ->addScalarResult('l_id', 'l_id', 'integer')
266 ->addScalarResult('l_short', 'l_short', 'string')
267 ->addScalarResult('l_title', 'l_title', 'string')
268 ->addScalarResult('l_address', 'l_address', 'string')
269 ->addScalarResult('l_zipcode', 'l_zipcode', 'string')
270 ->addScalarResult('l_city', 'l_city', 'string')
271 ->addScalarResult('l_latitude', 'l_latitude', 'float')
272 ->addScalarResult('l_longitude', 'l_longitude', 'float')
273 ->addScalarResult('t_id', 't_id', 'integer')
274 ->addScalarResult('t_title', 't_title', 'string')
275 ->addScalarResult('a_id', 'a_id', 'integer')
276 ->addScalarResult('a_canceled', 'a_canceled', 'datetime')
277 ->addScalarResult('au_id', 'au_id', 'integer')
278 ->addScalarResult('au_pseudonym', 'au_pseudonym', 'string')
279 ->addScalarResult('p_id', 'p_id', 'integer')
280 ->addScalarResult('p_description', 'p_description', 'text')
281 ->addScalarResult('p_class', 'p_class', 'text')
282 ->addScalarResult('p_contact', 'p_contact', 'text')
283 ->addScalarResult('p_donate', 'p_donate', 'text')
284 ->addScalarResult('p_link', 'p_link', 'text')
285 ->addScalarResult('p_profile', 'p_profile', 'text')
286 //XXX: is a string because of \n separator
287 ->addScalarResult('sa_id', 'sa_id', 'string')
288 //XXX: is a string because of \n separator
289 ->addScalarResult('sa_score', 'sa_score', 'string')
290 //XXX: is a string because of \n separator
291 ->addScalarResult('sa_created', 'sa_created', 'string')
292 //XXX: is a string because of \n separator
293 ->addScalarResult('sa_updated', 'sa_updated', 'string')
294 //XXX: is a string because of \n separator
295 ->addScalarResult('sa_canceled', 'sa_canceled', 'string')
296 //XXX: is a string because of \n separator
297 ->addScalarResult('sau_id', 'sau_id', 'string')
298 //XXX: is a string because of \n separator
299 ->addScalarResult('sau_pseudonym', 'sau_pseudonym', 'string')
300 ->addIndexByScalar('id');
304 ->createNativeQuery($req, $rsm)
305 ->setParameter('sid', $id)
306 ->setParameter('locale', $locale)
307 ->getOneOrNullResult();
311 * Fetch sessions calendar with translated location by date period
313 * @param $translator The TranslatorInterface instance
314 * @param $period The date period
315 * @param $locationId The location id
316 * @param $sessionId The session id
317 * @param $granted The session is granted
319 public function fetchCalendarByDatePeriod(TranslatorInterface
$translator, $period, $locationId = null, $sessionId = null, $granted = false) {
321 $em = $this->getEntityManager();
324 $qs = $em->getConfiguration()->getQuoteStrategy();
325 $dp = $em->getConnection()->getDatabasePlatform();
327 //Get quoted table names
328 //XXX: this allow to make this code table name independent
330 'RapsysAirBundle:GroupUser' => $qs->getJoinTableName($em->getClassMetadata('RapsysAirBundle:User')->getAssociationMapping('groups'), $em->getClassMetadata('RapsysAirBundle:User'), $dp),
331 'RapsysAirBundle:Session' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Session'), $dp),
332 'RapsysAirBundle:Application' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Application'), $dp),
333 'RapsysAirBundle:Group' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Group'), $dp),
334 'RapsysAirBundle:Location' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Location'), $dp),
335 'RapsysAirBundle:Slot' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Slot'), $dp),
336 'RapsysAirBundle:User' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:User'), $dp),
345 //When granted is set
346 if (empty($granted)) {
347 //Set application and user as optional
354 //When location id is set
355 if (!empty($locationId)) {
356 //Add location id clause
357 $locationSql = "\n\t".'AND s.location_id = :lid';
370 ADDDATE(ADDTIME(s.date, s.begin), INTERVAL IF(s.slot_id = :afterid, 1, 0) DAY) AS start,
371 ADDDATE(ADDTIME(ADDTIME(s.date, s.begin), s.length), INTERVAL IF(s.slot_id = :afterid, 1, 0) DAY) AS stop,
372 s.location_id AS l_id,
377 s.application_id AS a_id,
378 a.canceled AS a_canceled,
380 au.pseudonym AS au_pseudonym,
381 GROUP_CONCAT(sa.user_id ORDER BY sa.user_id SEPARATOR "\\n") AS sau_id,
382 GROUP_CONCAT(sau.pseudonym ORDER BY sa.user_id SEPARATOR "\\n") AS sau_pseudonym
383 FROM RapsysAirBundle:Session AS s
384 JOIN RapsysAirBundle:Location AS l ON (l.id = s.location_id)
385 JOIN RapsysAirBundle:Slot AS t ON (t.id = s.slot_id)
386 ${grantSql}JOIN RapsysAirBundle:Application AS a ON (a.id = s.application_id)
387 ${grantSql}JOIN RapsysAirBundle:User AS au ON (au.id = a.user_id)
388 LEFT JOIN RapsysAirBundle:Application AS sa ON (sa.session_id = s.id)
389 LEFT JOIN RapsysAirBundle:User AS sau ON (sau.id = sa.user_id)
390 WHERE s.date BETWEEN :begin AND :end${locationSql}
395 //Replace bundle entity name by table name
396 $req = str_replace(array_keys($tables), array_values($tables), $req);
398 //Get result set mapping instance
399 //XXX: DEBUG: see ../blog.orig/src/Rapsys/BlogBundle/Repository/ArticleRepository.php
400 $rsm = new ResultSetMapping();
403 //XXX: see vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/Types.php
404 //addScalarResult($sqlColName, $resColName, $type = 'string');
405 $rsm->addScalarResult('id', 'id', 'integer')
406 ->addScalarResult('date', 'date', 'date')
407 ->addScalarResult('rainrisk', 'rainrisk', 'float')
408 ->addScalarResult('rainfall', 'rainfall', 'float')
409 ->addScalarResult('realfeel', 'realfeel', 'float')
410 ->addScalarResult('temperature', 'temperature', 'float')
411 ->addScalarResult('locked', 'locked', 'datetime')
412 ->addScalarResult('start', 'start', 'datetime')
413 ->addScalarResult('stop', 'stop', 'datetime')
414 ->addScalarResult('t_id', 't_id', 'integer')
415 ->addScalarResult('t_title', 't_title', 'string')
416 ->addScalarResult('l_id', 'l_id', 'integer')
417 ->addScalarResult('l_short', 'l_short', 'string')
418 ->addScalarResult('l_title', 'l_title', 'string')
419 ->addScalarResult('a_id', 'a_id', 'integer')
420 ->addScalarResult('a_canceled', 'a_canceled', 'datetime')
421 ->addScalarResult('au_id', 'au_id', 'integer')
422 ->addScalarResult('au_pseudonym', 'au_pseudonym', 'string')
423 //XXX: is a string because of \n separator
424 ->addScalarResult('sau_id', 'sau_id', 'string')
425 //XXX: is a string because of \n separator
426 ->addScalarResult('sau_pseudonym', 'sau_pseudonym', 'string')
427 ->addIndexByScalar('id');
431 ->createNativeQuery($req, $rsm)
432 ->setParameter('begin', $period->getStartDate())
433 ->setParameter('end', $period->getEndDate());
435 //Add optional location id
436 if (!empty($locationId)) {
437 $res->setParameter('lid', $locationId);
441 $res = $res->getResult();
449 //Iterate on each day
450 foreach($period as $date) {
451 //Init day in calendar
452 $calendar[$Ymd = $date->format('Ymd')] = [
453 'title' => $translator->trans($date->format('l')).' '.$date->format('d'),
458 //Detect month change
459 if ($month != $date->format('m')) {
460 $month = $date->format('m');
461 //Append month for first day of month
462 //XXX: except if today to avoid double add
463 if ($date->format('U') != strtotime('today')) {
464 $calendar[$Ymd]['title'] .= '/'.$month;
468 if ($date->format('U') == ($today = strtotime('today'))) {
469 $calendar[$Ymd]['title'] .= '/'.$month;
470 $calendar[$Ymd]['current'] = true;
471 $calendar[$Ymd]['class'][] = 'current';
473 //Disable passed days
474 if ($date->format('U') < $today) {
475 $calendar[$Ymd]['disabled'] = true;
476 $calendar[$Ymd]['class'][] = 'disabled';
478 //Set next month days
479 if ($date->format('m') > date('m')) {
480 $calendar[$Ymd]['next'] = true;
481 #$calendar[$Ymd]['class'][] = 'next';
485 if ($date->format('w') == 0) {
486 $calendar[$Ymd]['class'][] = 'sunday';
489 //Iterate on each session to find the one of the day
490 foreach($res as $session) {
491 if (($sessionYmd = $session['date']->format('Ymd')) == $Ymd) {
492 //Count number of application
493 $count = count(explode("\n", $session['sau_id']));
497 if (!empty($session['a_id'])) {
498 $applications = [ $session['au_id'] => $session['au_pseudonym'] ];
499 if (!empty($session['a_canceled'])) {
500 $class[] = 'canceled';
502 $class[] = 'granted';
504 } elseif ($count > 1) {
505 $class[] = 'disputed';
506 } elseif (!empty($session['locked'])) {
509 $class[] = 'pending';
512 if ($sessionId == $session['id']) {
513 $class[] = 'highlight';
517 //XXX: realfeel may be null, temperature should not
518 $temperature = $session['realfeel'] !== null ? $session['realfeel'] : $session['temperature'];
521 //XXX: rainfall may be null
522 if ($session['rainrisk'] > 0.50 || $session['rainfall'] > 2) {
523 $weather = self
::GLYPHS
['Stormy'];
524 } elseif ($session['rainrisk'] > 0.40 || $session['rainfall'] > 1) {
525 $weather = self
::GLYPHS
['Rainy'];
526 } elseif ($temperature > 24) {
527 $weather = self
::GLYPHS
['Cleary'];
528 } elseif ($temperature > 17) {
529 $weather = self
::GLYPHS
['Sunny'];
530 } elseif ($temperature > 10) {
531 $weather = self
::GLYPHS
['Cloudy'];
532 } elseif ($temperature !== null) {
533 $weather = self
::GLYPHS
['Winty'];
541 //Check if realfeel is available
542 if ($session['realfeel'] !== null) {
543 $weathertitle[] = $session['realfeel'].'Β°R';
546 //Check if temperature is available
547 if ($session['temperature'] !== null) {
548 $weathertitle[] = $session['temperature'].'Β°C';
551 //Check if rainrisk is available
552 if ($session['rainrisk'] !== null) {
553 $weathertitle[] = ($session['rainrisk']*100).'%';
556 //Check if rainfall is available
557 if ($session['rainfall'] !== null) {
558 $weathertitle[] = $session['rainfall'].'mm';
563 0 => $translator->trans($session['t_title']).' '.$translator->trans('at '.$session['l_title']).$translator->trans(':')
566 //Fetch pseudonyms from session applications
567 $applications +
= array_combine(explode("\n", $session['sau_id']), array_map(function ($v) {return '- '.$v
;}, explode("\n", $session['sau_pseudonym'])));
572 //Check that session is not granted
573 if (empty($session['a_id'])) {
574 //With location id and unique application
576 //Set unique application pseudonym
577 $pseudonym = $session['sau_pseudonym'];
581 //Replace granted application
582 $applications[$session['au_id']] = '* '.$session['au_pseudonym'];
585 $pseudonym = $session['au_pseudonym'].($count > 1 ? ' ['.$count.']':'');
589 $calendar[$Ymd]['sessions'][$session['t_id'].sprintf('%05d', $session['id'])] = [
590 'id' => $session['id'],
591 'start' => $session['start'],
592 'stop' => $session['stop'],
593 'location' => $translator->trans($session['l_short']),
594 'pseudonym' => $pseudonym,
596 'slot' => self
::GLYPHS
[$session['t_title']],
597 'slottitle' => $translator->trans($session['t_title']),
598 'weather' => $weather,
599 'weathertitle' => implode(' ', $weathertitle),
600 'applications' => $applications
606 ksort($calendar[$Ymd]['sessions']);
614 * Fetch sessions calendar with translated location by date period and user
616 * @param $translator The TranslatorInterface instance
617 * @param $period The date period
618 * @param $userId The user id
619 * @param $sessionId The session id
621 public function fetchUserCalendarByDatePeriod(TranslatorInterface
$translator, $period, $userId = null, $sessionId = null) {
623 $em = $this->getEntityManager();
626 $qs = $em->getConfiguration()->getQuoteStrategy();
627 $dp = $em->getConnection()->getDatabasePlatform();
629 //Get quoted table names
630 //XXX: this allow to make this code table name independent
632 'RapsysAirBundle:GroupUser' => $qs->getJoinTableName($em->getClassMetadata('RapsysAirBundle:User')->getAssociationMapping('groups'), $em->getClassMetadata('RapsysAirBundle:User'), $dp),
633 'RapsysAirBundle:Session' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Session'), $dp),
634 'RapsysAirBundle:Application' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Application'), $dp),
635 'RapsysAirBundle:Group' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Group'), $dp),
636 'RapsysAirBundle:Location' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Location'), $dp),
637 'RapsysAirBundle:Slot' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Slot'), $dp),
638 'RapsysAirBundle:User' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:User'), $dp),
645 $userJoinSql = $userWhereSql = '';
647 //When user id is set
648 if (!empty($userId)) {
650 $userJoinSql = 'JOIN RapsysAirBundle:Application AS sua ON (sua.session_id = s.id)'."\n";
652 $userWhereSql = "\n\t".'AND sua.user_id = :uid';
656 //TODO: change as_u_* in sau_*, a_u_* in au_*, etc, see request up
666 ADDDATE(ADDTIME(s.date, s.begin), INTERVAL IF(s.slot_id = :afterid, 1, 0) DAY) AS start,
667 ADDDATE(ADDTIME(ADDTIME(s.date, s.begin), s.length), INTERVAL IF(s.slot_id = :afterid, 1, 0) DAY) AS stop,
668 s.location_id AS l_id,
673 s.application_id AS a_id,
675 au.pseudonym AS au_pseudonym,
676 GROUP_CONCAT(sa.user_id ORDER BY sa.user_id SEPARATOR "\\n") AS sau_id,
677 GROUP_CONCAT(CONCAT("- ", sau.pseudonym) ORDER BY sa.user_id SEPARATOR "\\n") AS sau_pseudonym
678 FROM RapsysAirBundle:Session AS s
679 JOIN RapsysAirBundle:Location AS l ON (l.id = s.location_id)
680 JOIN RapsysAirBundle:Slot AS t ON (t.id = s.slot_id)
681 ${userJoinSql}LEFT JOIN RapsysAirBundle:Application AS a ON (a.id = s.application_id)
682 LEFT JOIN RapsysAirBundle:User AS au ON (au.id = a.user_id)
683 LEFT JOIN RapsysAirBundle:Application AS sa ON (sa.session_id = s.id)
684 LEFT JOIN RapsysAirBundle:User AS sau ON (sau.id = sa.user_id)
685 WHERE s.date BETWEEN :begin AND :end${userWhereSql}
690 //Replace bundle entity name by table name
691 $req = str_replace(array_keys($tables), array_values($tables), $req);
693 //Get result set mapping instance
694 //XXX: DEBUG: see ../blog.orig/src/Rapsys/BlogBundle/Repository/ArticleRepository.php
695 $rsm = new ResultSetMapping();
698 //XXX: see vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/Types.php
699 //addScalarResult($sqlColName, $resColName, $type = 'string');
700 $rsm->addScalarResult('id', 'id', 'integer')
701 ->addScalarResult('date', 'date', 'date')
702 ->addScalarResult('rainrisk', 'rainrisk', 'float')
703 ->addScalarResult('rainfall', 'rainfall', 'float')
704 ->addScalarResult('realfeel', 'realfeel', 'float')
705 ->addScalarResult('temperature', 'temperature', 'float')
706 ->addScalarResult('locked', 'locked', 'datetime')
707 ->addScalarResult('start', 'start', 'datetime')
708 ->addScalarResult('stop', 'stop', 'datetime')
709 ->addScalarResult('t_id', 't_id', 'integer')
710 ->addScalarResult('t_title', 't_title', 'string')
711 ->addScalarResult('l_id', 'l_id', 'integer')
712 ->addScalarResult('l_short', 'l_short', 'string')
713 ->addScalarResult('l_title', 'l_title', 'string')
714 ->addScalarResult('a_id', 'a_id', 'integer')
715 ->addScalarResult('au_id', 'au_id', 'integer')
716 ->addScalarResult('au_pseudonym', 'au_pseudonym', 'string')
717 //XXX: is a string because of \n separator
718 ->addScalarResult('sau_id', 'sau_id', 'string')
719 //XXX: is a string because of \n separator
720 ->addScalarResult('sau_pseudonym', 'sau_pseudonym', 'string')
721 ->addIndexByScalar('id');
725 ->createNativeQuery($req, $rsm)
726 ->setParameter('begin', $period->getStartDate())
727 ->setParameter('end', $period->getEndDate())
728 ->setParameter('uid', $userId)
737 //Iterate on each day
738 foreach($period as $date) {
739 //Init day in calendar
740 $calendar[$Ymd = $date->format('Ymd')] = [
741 'title' => $translator->trans($date->format('l')).' '.$date->format('d'),
746 //Detect month change
747 if ($month != $date->format('m')) {
748 $month = $date->format('m');
749 //Append month for first day of month
750 //XXX: except if today to avoid double add
751 if ($date->format('U') != strtotime('today')) {
752 $calendar[$Ymd]['title'] .= '/'.$month;
756 if ($date->format('U') == ($today = strtotime('today'))) {
757 $calendar[$Ymd]['title'] .= '/'.$month;
758 $calendar[$Ymd]['current'] = true;
759 $calendar[$Ymd]['class'][] = 'current';
761 //Disable passed days
762 if ($date->format('U') < $today) {
763 $calendar[$Ymd]['disabled'] = true;
764 $calendar[$Ymd]['class'][] = 'disabled';
766 //Set next month days
767 if ($date->format('m') > date('m')) {
768 $calendar[$Ymd]['next'] = true;
769 #$calendar[$Ymd]['class'][] = 'next';
773 if ($date->format('w') == 0) {
774 $calendar[$Ymd]['class'][] = 'sunday';
777 //Iterate on each session to find the one of the day
778 foreach($res as $session) {
779 if (($sessionYmd = $session['date']->format('Ymd')) == $Ymd) {
780 //Count number of application
781 $count = count(explode("\n", $session['sau_id']));
785 if (!empty($session['a_id'])) {
786 $applications = [ $session['au_id'] => $session['au_pseudonym'] ];
787 if ($session['au_id'] == $userId) {
788 $class[] = 'granted';
790 $class[] = 'disputed';
792 } elseif ($count > 1) {
793 $class[] = 'disputed';
794 } elseif (!empty($session['locked'])) {
797 $class[] = 'pending';
800 if ($sessionId == $session['id']) {
801 $class[] = 'highlight';
805 //XXX: realfeel may be null, temperature should not
806 $temperature = $session['realfeel'] !== null ? $session['realfeel'] : $session['temperature'];
809 //XXX: rainfall may be null
810 if ($session['rainrisk'] > 0.50 || $session['rainfall'] > 2) {
811 $weather = self
::GLYPHS
['Stormy'];
812 } elseif ($session['rainrisk'] > 0.40 || $session['rainfall'] > 1) {
813 $weather = self
::GLYPHS
['Rainy'];
814 } elseif ($temperature > 24) {
815 $weather = self
::GLYPHS
['Cleary'];
816 } elseif ($temperature > 17) {
817 $weather = self
::GLYPHS
['Sunny'];
818 } elseif ($temperature > 10) {
819 $weather = self
::GLYPHS
['Cloudy'];
820 } elseif ($temperature !== null) {
821 $weather = self
::GLYPHS
['Winty'];
829 //Check if realfeel is available
830 if ($session['realfeel'] !== null) {
831 $weathertitle[] = $session['realfeel'].'Β°R';
834 //Check if temperature is available
835 if ($session['temperature'] !== null) {
836 $weathertitle[] = $session['temperature'].'Β°C';
839 //Check if rainrisk is available
840 if ($session['rainrisk'] !== null) {
841 $weathertitle[] = ($session['rainrisk']*100).'%';
844 //Check if rainfall is available
845 if ($session['rainfall'] !== null) {
846 $weathertitle[] = $session['rainfall'].'mm';
851 0 => $translator->trans($session['t_title']).' '.$translator->trans('at '.$session['l_title']).$translator->trans(':')
854 //Fetch pseudonyms from session applications
855 $applications +
= array_combine(explode("\n", $session['sau_id']), array_map(function ($v) {return '- '.$v
;}, explode("\n", $session['sau_pseudonym'])));
860 //Check that session is not granted
861 if (empty($session['a_id'])) {
862 //With location id and unique application
864 //Set unique application pseudonym
865 $pseudonym = $session['sau_pseudonym'];
869 //Replace granted application
870 $applications[$session['au_id']] = '* '.$session['au_pseudonym'];
873 $pseudonym = $session['au_pseudonym'].($count > 1 ? ' ['.$count.']':'');
877 $title = $translator->trans($session['l_title']).($count > 1 ? ' ['.$count.']':'');
880 $calendar[$Ymd]['sessions'][$session['t_id'].sprintf('%02d', $session['l_id'])] = [
881 'id' => $session['id'],
882 'start' => $session['start'],
883 'stop' => $session['stop'],
884 'location' => $translator->trans($session['l_short']),
885 'pseudonym' => $pseudonym,
887 'slot' => self
::GLYPHS
[$session['t_title']],
888 'slottitle' => $translator->trans($session['t_title']),
889 'weather' => $weather,
890 'weathertitle' => implode(' ', $weathertitle),
891 'applications' => $applications
897 ksort($calendar[$Ymd]['sessions']);
905 * Find all session pending hourly weather
907 * @return array<Session> The sessions to update
909 public function findAllPendingHourlyWeather() {
911 $em = $this->getEntityManager();
914 $qs = $em->getConfiguration()->getQuoteStrategy();
915 $dp = $em->getConnection()->getDatabasePlatform();
917 //Get quoted table names
918 //XXX: this allow to make this code table name independent
920 'RapsysAirBundle:Session' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Session'), $dp),
921 'RapsysAirBundle:Location' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Location'), $dp),
923 ':accuhourly' => self
::ACCUWEATHER_HOURLY
,
930 //Select all sessions starting and stopping in the next 3 days
931 //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)
933 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
934 FROM RapsysAirBundle:Session AS s
935 JOIN RapsysAirBundle:Location AS l ON (l.id = s.location_id)
936 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))
939 //Replace bundle entity name by table name
940 $req = str_replace(array_keys($tables), array_values($tables), $req);
942 //Get result set mapping instance
943 $rsm = new ResultSetMapping();
947 ->addEntityResult('RapsysAirBundle:Session', 's')
948 ->addFieldResult('s', 'id', 'id')
949 ->addFieldResult('s', 'date', 'date')
950 ->addFieldResult('s', 'begin', 'begin')
951 ->addFieldResult('s', 'length', 'length')
952 ->addFieldResult('s', 'rainfall', 'rainfall')
953 ->addFieldResult('s', 'rainrisk', 'rainrisk')
954 ->addFieldResult('s', 'realfeel', 'realfeel')
955 ->addFieldResult('s', 'realfeelmin', 'realfeelmin')
956 ->addFieldResult('s', 'realfeelmax', 'realfeelmax')
957 ->addFieldResult('s', 'temperature', 'temperature')
958 ->addFieldResult('s', 'temperaturemin', 'temperaturemin')
959 ->addFieldResult('s', 'temperaturemax', 'temperaturemax')
960 ->addJoinedEntityResult('RapsysAirBundle:Slot', 'o', 's', 'slot')
961 ->addFieldResult('o', 'slot_id', 'id')
962 ->addJoinedEntityResult('RapsysAirBundle:Location', 'l', 's', 'location')
963 ->addFieldResult('l', 'location_id', 'id')
964 ->addFieldResult('l', 'zipcode', 'zipcode')
965 ->addIndexBy('s', 'id');
969 ->createNativeQuery($req, $rsm)
974 * Find all session pending daily weather
976 * @return array<Session> The sessions to update
978 public function findAllPendingDailyWeather() {
980 $em = $this->getEntityManager();
983 $qs = $em->getConfiguration()->getQuoteStrategy();
984 $dp = $em->getConnection()->getDatabasePlatform();
986 //Get quoted table names
987 //XXX: this allow to make this code table name independent
989 'RapsysAirBundle:Session' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Session'), $dp),
990 'RapsysAirBundle:Location' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Location'), $dp),
992 ':accudaily' => self
::ACCUWEATHER_DAILY
,
993 ':accuhourly' => self
::ACCUWEATHER_HOURLY
,
1000 //Select all sessions stopping after next 3 days
1001 //XXX: select session stopping after or equal date(now)+3d as accuweather only provide hourly data for the next 3 days (INTERVAL 3 DAY)
1003 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
1004 FROM RapsysAirBundle:Session AS s
1005 JOIN RapsysAirBundle:Location AS l ON (l.id = s.location_id)
1006 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))
1009 //Replace bundle entity name by table name
1010 $req = str_replace(array_keys($tables), array_values($tables), $req);
1012 //Get result set mapping instance
1013 $rsm = new ResultSetMapping();
1015 //Declare all fields
1017 ->addEntityResult('RapsysAirBundle:Session', 's')
1018 ->addFieldResult('s', 'id', 'id')
1019 ->addFieldResult('s', 'date', 'date')
1020 ->addFieldResult('s', 'begin', 'begin')
1021 ->addFieldResult('s', 'length', 'length')
1022 ->addFieldResult('s', 'rainfall', 'rainfall')
1023 ->addFieldResult('s', 'rainrisk', 'rainrisk')
1024 ->addFieldResult('s', 'realfeel', 'realfeel')
1025 ->addFieldResult('s', 'realfeelmin', 'realfeelmin')
1026 ->addFieldResult('s', 'realfeelmax', 'realfeelmax')
1027 ->addFieldResult('s', 'temperature', 'temperature')
1028 ->addFieldResult('s', 'temperaturemin', 'temperaturemin')
1029 ->addFieldResult('s', 'temperaturemax', 'temperaturemax')
1030 ->addJoinedEntityResult('RapsysAirBundle:Slot', 'o', 's', 'slot')
1031 ->addFieldResult('o', 'slot_id', 'id')
1032 ->addJoinedEntityResult('RapsysAirBundle:Location', 'l', 's', 'location')
1033 ->addFieldResult('l', 'location_id', 'id')
1034 ->addFieldResult('l', 'zipcode', 'zipcode')
1035 ->addIndexBy('s', 'id');
1039 ->createNativeQuery($req, $rsm)
1044 * Find every session pending application
1046 * @return array<Session> The sessions to update
1048 public function findAllPendingApplication() {
1049 //Get entity manager
1050 $em = $this->getEntityManager();
1052 //Get quote strategy
1053 $qs = $em->getConfiguration()->getQuoteStrategy();
1054 $dp = $em->getConnection()->getDatabasePlatform();
1056 //Get quoted table names
1057 //XXX: this allow to make this code table name independent
1059 'RapsysAirBundle:Application' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Application'), $dp),
1060 'RapsysAirBundle:Session' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Session'), $dp),
1062 ':regulardelay' => self
::REGULAR_DELAY
* 24 * 3600,
1063 ':seniordelay' => self
::SENIOR_DELAY
* 24 * 3600,
1070 //Select all sessions not locked without application or canceled application within attribution period
1071 //XXX: DIFF(start, now) <= IF(DIFF(start, created) <= SENIOR_DELAY in DAY, DIFF(start, created) * 3 / 4, SENIOR_DELAY)
1072 //TODO: remonter les donnΓ©es pour le mail ?
1075 FROM RapsysAirBundle:Session as s
1076 LEFT JOIN RapsysAirBundle:Application AS a ON (a.id = s.application_id AND a.canceled IS NULL)
1077 JOIN RapsysAirBundle:Application AS a2 ON (a2.session_id = s.id AND a2.canceled IS NULL)
1078 WHERE s.locked IS NULL AND a.id IS NULL AND
1079 TIME_TO_SEC(TIMEDIFF(@dt_start := ADDDATE(ADDTIME(s.date, s.begin), INTERVAL IF(s.slot_id = :afterid, 1, 0) DAY), NOW())) <= IF(
1080 TIME_TO_SEC(@td_sc := TIMEDIFF(@dt_start, s.created)) <= :seniordelay,
1081 ROUND(TIME_TO_SEC(@td_sc) * :regulardelay / :seniordelay),
1085 ORDER BY @dt_start ASC, s.created ASC
1089 //Replace bundle entity name by table name
1090 $req = str_replace(array_keys($tables), array_values($tables), $req);
1092 //Get result set mapping instance
1093 $rsm = new ResultSetMapping();
1095 //Declare all fields
1097 ->addEntityResult('RapsysAirBundle:Session', 's')
1098 ->addFieldResult('s', 'id', 'id')
1099 ->addIndexBy('s', 'id');
1103 ->createNativeQuery($req, $rsm)
1108 * Fetch session best application by session id
1110 * @param int $id The session id
1111 * @return Application|null The application or null
1113 public function findBestApplicationById($id) {
1114 //Get entity manager
1115 $em = $this->getEntityManager();
1117 //Get quote strategy
1118 $qs = $em->getConfiguration()->getQuoteStrategy();
1119 $dp = $em->getConnection()->getDatabasePlatform();
1121 //Get quoted table names
1122 //XXX: this allow to make this code table name independent
1124 'RapsysAirBundle:Application' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Application'), $dp),
1125 'RapsysAirBundle:GroupUser' => $qs->getJoinTableName($em->getClassMetadata('RapsysAirBundle:User')->getAssociationMapping('groups'), $em->getClassMetadata('RapsysAirBundle:User'), $dp),
1126 'RapsysAirBundle:Location' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Location'), $dp),
1127 'RapsysAirBundle:Session' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Session'), $dp),
1128 //XXX: Set limit used to workaround mariadb subselect optimization
1129 ':limit' => PHP_INT_MAX
,
1131 ':guestdelay' => self
::GUEST_DELAY
* 24 * 3600,
1132 ':regulardelay' => self
::REGULAR_DELAY
* 24 * 3600,
1133 ':seniordelay' => self
::SENIOR_DELAY
* 24 * 3600,
1139 ':afternoonid' => 2,
1142 //XXX: days since last session after which guest regain normal priority
1144 //XXX: session count until considered at regular delay
1146 //XXX: pn_ratio over which considered at regular delay
1148 //XXX: tr_ratio diff over which considered at regular delay
1155 * Query session applications ranked by location score, global score, created and user_id
1157 * @xxx guest (or less) with application on location within 30 day are only considered within guestdelay
1159 * @xxx regular (or less) premium application on hotspot are only considered within regulardelay
1161 * @xxx senior (or less) with 5 or less session on location are only considered within seniordelay
1163 * @xxx senior (or less) with l_pn_ratio >= 1 are only considered within seniordelay
1165 * @xxx senior (or less) with l_tr_ratio >= (o_tr_ratio + 5) are only considered within seniordelay
1167 * @xxx only consider session within one year (may be unaccurate by the day with after session)
1169 * @xxx rainfall may not be accessible for previous session and other session at d-4 (only at d-2)
1171 * @todo ??? feedback the data to inform the rejected users ???
1174 SELECT e.id, e.l_score AS score
1186 MAX(gu.group_id) AS group_id,
1201 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,
1218 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,
1231 COUNT(a2.id) AS l_count,
1232 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,
1233 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,
1234 (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,
1235 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,
1236 TIME_TO_SEC(TIMEDIFF(ADDDATE(ADDTIME(s.date, s.begin), INTERVAL IF(s.slot_id = :afterid, 1, 0) DAY), NOW())) AS remaining,
1240 FROM RapsysAirBundle:Session AS s
1241 JOIN RapsysAirBundle:Location AS l ON (l.id = s.location_id)
1242 JOIN RapsysAirBundle:Application AS a ON (a.session_id = s.id AND a.canceled IS NULL)
1243 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)
1244 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))
1250 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)
1251 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))
1256 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)
1257 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))
1262 LEFT JOIN RapsysAirBundle:GroupUser AS gu ON (gu.user_id = d.user_id)
1267 IF(e.group_id <= :guestid AND e.l_previous <= :guestwait, e.remaining <= :guestdelay, 1) AND
1268 IF(e.group_id <= :regularid AND e.premium = 1 AND e.hotspot = 1, e.remaining <= :regulardelay, 1) AND
1269 IF(e.group_id <= :seniorid AND e.l_count <= :scount, e.remaining <= :regulardelay, 1) AND
1270 IF(e.group_id <= :seniorid AND e.l_pn_ratio >= :pnratio, e.remaining <= :regulardelay, 1) AND
1271 IF(e.group_id <= :seniorid AND e.l_tr_ratio >= (e.o_tr_ratio + :trdiff), e.remaining <= :regulardelay, 1)
1272 ORDER BY e.l_score ASC, e.g_score ASC, e.created ASC, e.user_id ASC
1275 //Replace bundle entity name by table name
1276 $req = str_replace(array_keys($tables), array_values($tables), $req);
1278 //Set update request
1279 $upreq = 'UPDATE RapsysAirBundle:Application SET score = :score, updated = NOW() WHERE id = :id';
1281 //Replace bundle entity name by table name
1282 $upreq = str_replace(array_keys($tables), array_values($tables), $upreq);
1284 //Get result set mapping instance
1285 $rsm = new ResultSetMapping();
1287 //Declare all fields
1289 ->addEntityResult('RapsysAirBundle:Application', 'a')
1290 ->addFieldResult('a', 'id', 'id')
1291 ->addFieldResult('a', 'score', 'score')
1292 ->addIndexBy('a', 'id');
1295 //XXX: setting limit in subqueries is required to prevent mariadb optimisation
1297 ->createNativeQuery($req, $rsm)
1298 ->setParameter('sid', $id)
1299 //XXX: removed, we update score before returning best candidate
1300 //->getOneOrNullResult(Query::HYDRATE_SINGLE_SCALAR);
1307 foreach($applications as $application) {
1308 //Check if we already saved best candidate
1309 if ($ret === null) {
1310 //Return first application
1311 $ret = $application;
1314 //Update application updated field
1315 //XXX: updated field is not modified for user with bad behaviour as application is not retrieved until delay is reached
1316 $em->getConnection()->executeUpdate($upreq, ['id' => $application->getId(), 'score' => $application->getScore()], ['id' => Type
::INTEGER, 'score' => Type
::FLOAT]);
1319 //Return best ranked application