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 sessions by date period
148 * @param $period The date period
149 * @param $locale The locale
151 public function fetchAllByDatePeriod($period, $locale = null) {
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:Application' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Application'), $dp),
163 'RapsysAirBundle:Location' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Location'), $dp),
164 'RapsysAirBundle:Session' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Session'), $dp),
165 'RapsysAirBundle:Snippet' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Snippet'), $dp),
166 'RapsysAirBundle:User' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:User'), $dp),
173 //TODO: exclude opera and others ?
180 ADDDATE(ADDTIME(s.date, s.begin), INTERVAL IF(s.slot_id = :afterid, 1, 0) DAY) AS start,
181 ADDDATE(ADDTIME(ADDTIME(s.date, s.begin), s.length), INTERVAL IF(s.slot_id = :afterid, 1, 0) DAY) AS stop,
182 s.location_id AS l_id,
183 l.address AS l_address,
184 l.zipcode AS l_zipcode,
187 l.latitude AS l_latitude,
188 l.longitude AS l_longitude,
189 s.application_id AS a_id,
190 a.canceled AS a_canceled,
192 au.forename AS au_forename,
193 au.pseudonym AS au_pseudonym,
195 p.description AS p_description,
200 p.contact AS p_contact,
201 p.donate AS p_donate,
203 p.profile AS p_profile
204 FROM RapsysAirBundle:Session AS s
205 JOIN RapsysAirBundle:Location AS l ON (l.id = s.location_id)
206 JOIN RapsysAirBundle:Application AS a ON (a.id = s.application_id)
207 JOIN RapsysAirBundle:User AS au ON (au.id = a.user_id)
208 LEFT JOIN RapsysAirBundle:Snippet AS p ON (p.location_id = s.location_id AND p.user_id = a.user_id AND p.locale = :locale)
209 WHERE s.date BETWEEN :begin AND :end
213 //Replace bundle entity name by table name
214 $req = str_replace(array_keys($tables), array_values($tables), $req);
216 //Get result set mapping instance
217 //XXX: DEBUG: see ../blog.orig/src/Rapsys/BlogBundle/Repository/ArticleRepository.php
218 $rsm = new ResultSetMapping();
221 //XXX: see vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/Types.php
222 //addScalarResult($sqlColName, $resColName, $type = 'string');
223 $rsm->addScalarResult('id', 'id', 'integer')
224 ->addScalarResult('date', 'date', 'date')
225 ->addScalarResult('locked', 'locked', 'datetime')
226 ->addScalarResult('updated', 'updated', 'datetime')
227 ->addScalarResult('start', 'start', 'datetime')
228 ->addScalarResult('stop', 'stop', 'datetime')
229 ->addScalarResult('l_id', 'l_id', 'integer')
230 ->addScalarResult('l_address', 'l_address', 'string')
231 ->addScalarResult('l_zipcode', 'l_zipcode', 'string')
232 ->addScalarResult('l_city', 'l_city', 'string')
233 ->addScalarResult('l_latitude', 'l_latitude', 'float')
234 ->addScalarResult('l_longitude', 'l_longitude', 'float')
235 ->addScalarResult('l_title', 'l_title', 'string')
236 ->addScalarResult('t_id', 't_id', 'integer')
237 ->addScalarResult('t_title', 't_title', 'string')
238 ->addScalarResult('a_id', 'a_id', 'integer')
239 ->addScalarResult('a_canceled', 'a_canceled', 'datetime')
240 ->addScalarResult('au_id', 'au_id', 'integer')
241 ->addScalarResult('au_forename', 'au_forename', 'string')
242 ->addScalarResult('au_pseudonym', 'au_pseudonym', 'string')
243 ->addScalarResult('p_id', 'p_id', 'integer')
244 ->addScalarResult('p_description', 'p_description', 'string')
245 ->addScalarResult('p_class', 'p_class', 'string')
246 ->addScalarResult('p_short', 'p_short', 'string')
247 ->addScalarResult('p_hat', 'p_hat', 'integer')
248 ->addScalarResult('p_rate', 'p_rate', 'integer')
249 ->addScalarResult('p_contact', 'p_contact', 'string')
250 ->addScalarResult('p_donate', 'p_donate', 'string')
251 ->addScalarResult('p_link', 'p_link', 'string')
252 ->addScalarResult('p_profile', 'p_profile', 'string')
253 ->addIndexByScalar('id');
257 ->createNativeQuery($req, $rsm)
258 ->setParameter('begin', $period->getStartDate())
259 ->setParameter('end', $period->getEndDate())
260 ->setParameter('locale', $locale);
263 return $res->getResult();
267 * Fetch session by id
269 * @param $id The session id
270 * @param $locale The locale
271 * @return array The session data
273 public function fetchOneById($id, $locale = null) {
275 $em = $this->getEntityManager();
278 $qs = $em->getConfiguration()->getQuoteStrategy();
279 $dp = $em->getConnection()->getDatabasePlatform();
281 //Get quoted table names
282 //XXX: this allow to make this code table name independent
284 'RapsysAirBundle:Application' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Application'), $dp),
285 'RapsysAirBundle:Group' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Group'), $dp),
286 'RapsysAirBundle:GroupUser' => $qs->getJoinTableName($em->getClassMetadata('RapsysAirBundle:User')->getAssociationMapping('groups'), $em->getClassMetadata('RapsysAirBundle:User'), $dp),
287 'RapsysAirBundle:Location' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Location'), $dp),
288 'RapsysAirBundle:Session' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Session'), $dp),
289 'RapsysAirBundle:Snippet' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Snippet'), $dp),
290 'RapsysAirBundle:Slot' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Slot'), $dp),
291 'RapsysAirBundle:User' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:User'), $dp),
298 //TODO: compute scores ?
299 //TODO: compute delivery date ? (J-3/J-4 ?)
305 ADDDATE(ADDTIME(s.date, s.begin), INTERVAL IF(s.slot_id = :afterid, 1, 0) DAY) AS start,
307 ADDDATE(ADDTIME(ADDTIME(s.date, s.begin), s.length), INTERVAL IF(s.slot_id = :afterid, 1, 0) DAY) AS stop,
319 s.location_id AS l_id,
321 l.address AS l_address,
322 l.zipcode AS l_zipcode,
324 l.latitude AS l_latitude,
325 l.longitude AS l_longitude,
326 l.updated AS l_updated,
329 t.updated AS t_updated,
330 s.application_id AS a_id,
331 a.canceled AS a_canceled,
333 au.pseudonym AS au_pseudonym,
335 p.description AS p_description,
337 p.contact AS p_contact,
338 p.donate AS p_donate,
340 p.profile AS p_profile,
343 p.updated AS p_updated,
344 GROUP_CONCAT(sa.id ORDER BY sa.user_id SEPARATOR "\\n") AS sa_id,
345 GROUP_CONCAT(IFNULL(sa.score, 'NULL') ORDER BY sa.user_id SEPARATOR "\\n") AS sa_score,
346 GROUP_CONCAT(sa.created ORDER BY sa.user_id SEPARATOR "\\n") AS sa_created,
347 GROUP_CONCAT(sa.updated ORDER BY sa.user_id SEPARATOR "\\n") AS sa_updated,
348 GROUP_CONCAT(IFNULL(sa.canceled, 'NULL') ORDER BY sa.user_id SEPARATOR "\\n") AS sa_canceled,
349 GROUP_CONCAT(sa.user_id ORDER BY sa.user_id SEPARATOR "\\n") AS sau_id,
350 GROUP_CONCAT(sau.pseudonym ORDER BY sa.user_id SEPARATOR "\\n") AS sau_pseudonym
351 FROM RapsysAirBundle:Session AS s
352 JOIN RapsysAirBundle:Location AS l ON (l.id = s.location_id)
353 JOIN RapsysAirBundle:Slot AS t ON (t.id = s.slot_id)
354 LEFT JOIN RapsysAirBundle:Application AS a ON (a.id = s.application_id)
355 LEFT JOIN RapsysAirBundle:User AS au ON (au.id = a.user_id)
356 LEFT JOIN RapsysAirBundle:Snippet AS p ON (p.location_id = s.location_id AND p.user_id = a.user_id AND p.locale = :locale)
357 LEFT JOIN RapsysAirBundle:Application AS sa ON (sa.session_id = s.id)
358 LEFT JOIN RapsysAirBundle:User AS sau ON (sau.id = sa.user_id)
364 //Replace bundle entity name by table name
365 $req = str_replace(array_keys($tables), array_values($tables), $req);
367 //Get result set mapping instance
368 //XXX: DEBUG: see ../blog.orig/src/Rapsys/BlogBundle/Repository/ArticleRepository.php
369 $rsm = new ResultSetMapping();
372 //XXX: see vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/Types.php
373 $rsm->addScalarResult('id', 'id', 'integer')
374 ->addScalarResult('date', 'date', 'date')
375 ->addScalarResult('begin', 'begin', 'time')
376 ->addScalarResult('start', 'start', 'datetime')
377 ->addScalarResult('length', 'length', 'time')
378 ->addScalarResult('stop', 'stop', 'datetime')
379 ->addScalarResult('rainfall', 'rainfall', 'float')
380 ->addScalarResult('rainrisk', 'rainrisk', 'float')
381 ->addScalarResult('realfeel', 'realfeel', 'float')
382 ->addScalarResult('realfeelmin', 'realfeelmin', 'float')
383 ->addScalarResult('realfeelmax', 'realfeelmax', 'float')
384 ->addScalarResult('temperature', 'temperature', 'float')
385 ->addScalarResult('temperaturemin', 'temperaturemin', 'float')
386 ->addScalarResult('temperaturemax', 'temperaturemax', 'float')
387 ->addScalarResult('locked', 'locked', 'datetime')
388 ->addScalarResult('created', 'created', 'datetime')
389 ->addScalarResult('updated', 'updated', 'datetime')
390 ->addScalarResult('l_id', 'l_id', 'integer')
391 ->addScalarResult('l_title', 'l_title', 'string')
392 ->addScalarResult('l_address', 'l_address', 'string')
393 ->addScalarResult('l_zipcode', 'l_zipcode', 'string')
394 ->addScalarResult('l_city', 'l_city', 'string')
395 ->addScalarResult('l_latitude', 'l_latitude', 'float')
396 ->addScalarResult('l_longitude', 'l_longitude', 'float')
397 ->addScalarResult('l_updated', 'l_updated', 'datetime')
398 ->addScalarResult('t_id', 't_id', 'integer')
399 ->addScalarResult('t_title', 't_title', 'string')
400 ->addScalarResult('t_updated', 't_updated', 'datetime')
401 ->addScalarResult('a_id', 'a_id', 'integer')
402 ->addScalarResult('a_canceled', 'a_canceled', 'datetime')
403 ->addScalarResult('au_id', 'au_id', 'integer')
404 ->addScalarResult('au_pseudonym', 'au_pseudonym', 'string')
405 ->addScalarResult('p_id', 'p_id', 'integer')
406 ->addScalarResult('p_description', 'p_description', 'text')
407 ->addScalarResult('p_class', 'p_class', 'text')
408 ->addScalarResult('p_contact', 'p_contact', 'text')
409 ->addScalarResult('p_donate', 'p_donate', 'text')
410 ->addScalarResult('p_link', 'p_link', 'text')
411 ->addScalarResult('p_profile', 'p_profile', 'text')
412 ->addScalarResult('p_rate', 'p_rate', 'integer')
413 ->addScalarResult('p_hat', 'p_hat', 'boolean')
414 ->addScalarResult('p_updated', 'p_updated', 'datetime')
415 //XXX: is a string because of \n separator
416 ->addScalarResult('sa_id', 'sa_id', 'string')
417 //XXX: is a string because of \n separator
418 ->addScalarResult('sa_score', 'sa_score', 'string')
419 //XXX: is a string because of \n separator
420 ->addScalarResult('sa_created', 'sa_created', 'string')
421 //XXX: is a string because of \n separator
422 ->addScalarResult('sa_updated', 'sa_updated', 'string')
423 //XXX: is a string because of \n separator
424 ->addScalarResult('sa_canceled', 'sa_canceled', 'string')
425 //XXX: is a string because of \n separator
426 ->addScalarResult('sau_id', 'sau_id', 'string')
427 //XXX: is a string because of \n separator
428 ->addScalarResult('sau_pseudonym', 'sau_pseudonym', 'string')
429 ->addIndexByScalar('id');
433 ->createNativeQuery($req, $rsm)
434 ->setParameter('sid', $id)
435 ->setParameter('locale', $locale)
436 ->getOneOrNullResult();
440 * Fetch sessions calendar with translated location by date period
442 * @param $translator The TranslatorInterface instance
443 * @param $period The date period
444 * @param $locationId The location id
445 * @param $sessionId The session id
446 * @param $granted The session is granted
448 public function fetchCalendarByDatePeriod(TranslatorInterface
$translator, $period, $locationId = null, $sessionId = null, $granted = false, $locale = null) {
450 $em = $this->getEntityManager();
453 $qs = $em->getConfiguration()->getQuoteStrategy();
454 $dp = $em->getConnection()->getDatabasePlatform();
456 //Get quoted table names
457 //XXX: this allow to make this code table name independent
459 'RapsysAirBundle:GroupUser' => $qs->getJoinTableName($em->getClassMetadata('RapsysAirBundle:User')->getAssociationMapping('groups'), $em->getClassMetadata('RapsysAirBundle:User'), $dp),
460 'RapsysAirBundle:Session' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Session'), $dp),
461 'RapsysAirBundle:Application' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Application'), $dp),
462 'RapsysAirBundle:Group' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Group'), $dp),
463 'RapsysAirBundle:Location' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Location'), $dp),
464 'RapsysAirBundle:Slot' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Slot'), $dp),
465 'RapsysAirBundle:Snippet' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Snippet'), $dp),
466 'RapsysAirBundle:User' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:User'), $dp),
475 //When granted is set
476 if (empty($granted)) {
477 //Set application and user as optional
484 //When location id is set
485 if (!empty($locationId)) {
486 //Add location id clause
487 $locationSql = "\n\t".'AND s.location_id = :lid';
501 ADDDATE(ADDTIME(s.date, s.begin), INTERVAL IF(s.slot_id = :afterid, 1, 0) DAY) AS start,
502 ADDDATE(ADDTIME(ADDTIME(s.date, s.begin), s.length), INTERVAL IF(s.slot_id = :afterid, 1, 0) DAY) AS stop,
503 s.location_id AS l_id,
507 s.application_id AS a_id,
508 a.canceled AS a_canceled,
510 au.pseudonym AS au_pseudonym,
513 GROUP_CONCAT(sa.user_id ORDER BY sa.user_id SEPARATOR "\\n") AS sau_id,
514 GROUP_CONCAT(sau.pseudonym ORDER BY sa.user_id SEPARATOR "\\n") AS sau_pseudonym
515 FROM RapsysAirBundle:Session AS s
516 JOIN RapsysAirBundle:Location AS l ON (l.id = s.location_id)
517 JOIN RapsysAirBundle:Slot AS t ON (t.id = s.slot_id)
518 ${grantSql}JOIN RapsysAirBundle:Application AS a ON (a.id = s.application_id)
519 ${grantSql}JOIN RapsysAirBundle:User AS au ON (au.id = a.user_id)
520 LEFT JOIN RapsysAirBundle:Application AS sa ON (sa.session_id = s.id)
521 LEFT JOIN RapsysAirBundle:Snippet AS p ON (p.location_id = s.location_id AND p.user_id = a.user_id AND p.locale = :locale)
522 LEFT JOIN RapsysAirBundle:User AS sau ON (sau.id = sa.user_id)
523 WHERE s.date BETWEEN :begin AND :end${locationSql}
528 //Replace bundle entity name by table name
529 $req = str_replace(array_keys($tables), array_values($tables), $req);
531 //Get result set mapping instance
532 //XXX: DEBUG: see ../blog.orig/src/Rapsys/BlogBundle/Repository/ArticleRepository.php
533 $rsm = new ResultSetMapping();
536 //XXX: see vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/Types.php
537 //addScalarResult($sqlColName, $resColName, $type = 'string');
538 $rsm->addScalarResult('id', 'id', 'integer')
539 ->addScalarResult('date', 'date', 'date')
540 ->addScalarResult('rainrisk', 'rainrisk', 'float')
541 ->addScalarResult('rainfall', 'rainfall', 'float')
542 ->addScalarResult('realfeel', 'realfeel', 'float')
543 ->addScalarResult('temperature', 'temperature', 'float')
544 ->addScalarResult('locked', 'locked', 'datetime')
545 ->addScalarResult('start', 'start', 'datetime')
546 ->addScalarResult('stop', 'stop', 'datetime')
547 ->addScalarResult('t_id', 't_id', 'integer')
548 ->addScalarResult('t_title', 't_title', 'string')
549 ->addScalarResult('l_id', 'l_id', 'integer')
550 ->addScalarResult('l_title', 'l_title', 'string')
551 ->addScalarResult('a_id', 'a_id', 'integer')
552 ->addScalarResult('a_canceled', 'a_canceled', 'datetime')
553 ->addScalarResult('au_id', 'au_id', 'integer')
554 ->addScalarResult('au_pseudonym', 'au_pseudonym', 'string')
555 ->addScalarResult('p_rate', 'p_rate', 'integer')
556 ->addScalarResult('p_hat', 'p_hat', 'boolean')
557 //XXX: is a string because of \n separator
558 ->addScalarResult('sau_id', 'sau_id', 'string')
559 //XXX: is a string because of \n separator
560 ->addScalarResult('sau_pseudonym', 'sau_pseudonym', 'string')
561 ->addIndexByScalar('id');
565 ->createNativeQuery($req, $rsm)
566 ->setParameter('begin', $period->getStartDate())
567 ->setParameter('end', $period->getEndDate())
568 ->setParameter('locale', $locale);
570 //Add optional location id
571 if (!empty($locationId)) {
572 $res->setParameter('lid', $locationId);
576 $res = $res->getResult();
584 //Iterate on each day
585 foreach($period as $date) {
586 //Init day in calendar
587 $calendar[$Ymd = $date->format('Ymd')] = [
588 'title' => $translator->trans($date->format('l')).' '.$date->format('d'),
593 //Detect month change
594 if ($month != $date->format('m')) {
595 $month = $date->format('m');
596 //Append month for first day of month
597 //XXX: except if today to avoid double add
598 if ($date->format('U') != strtotime('today')) {
599 $calendar[$Ymd]['title'] .= '/'.$month;
603 if ($date->format('U') == ($today = strtotime('today'))) {
604 $calendar[$Ymd]['title'] .= '/'.$month;
605 $calendar[$Ymd]['current'] = true;
606 $calendar[$Ymd]['class'][] = 'current';
608 //Disable passed days
609 if ($date->format('U') < $today) {
610 $calendar[$Ymd]['disabled'] = true;
611 $calendar[$Ymd]['class'][] = 'disabled';
613 //Set next month days
614 if ($date->format('m') > date('m')) {
615 $calendar[$Ymd]['next'] = true;
616 #$calendar[$Ymd]['class'][] = 'next';
620 if ($date->format('w') == 0) {
621 $calendar[$Ymd]['class'][] = 'sunday';
624 //Iterate on each session to find the one of the day
625 foreach($res as $session) {
626 if (($sessionYmd = $session['date']->format('Ymd')) == $Ymd) {
627 //Count number of application
628 $count = count(explode("\n", $session['sau_id']));
632 if (!empty($session['a_id'])) {
633 $applications = [ $session['au_id'] => $session['au_pseudonym'] ];
634 if (!empty($session['a_canceled'])) {
635 $class[] = 'canceled';
637 $class[] = 'granted';
639 } elseif ($count > 1) {
640 $class[] = 'disputed';
641 } elseif (!empty($session['locked'])) {
644 $class[] = 'pending';
647 if ($sessionId == $session['id']) {
648 $class[] = 'highlight';
652 //XXX: realfeel may be null, temperature should not
653 $temperature = $session['realfeel'] !== null ? $session['realfeel'] : $session['temperature'];
656 //XXX: rainfall may be null
657 if ($session['rainrisk'] > 0.50 || $session['rainfall'] > 2) {
658 $weather = self
::GLYPHS
['Stormy'];
659 } elseif ($session['rainrisk'] > 0.40 || $session['rainfall'] > 1) {
660 $weather = self
::GLYPHS
['Rainy'];
661 } elseif ($temperature > 24) {
662 $weather = self
::GLYPHS
['Cleary'];
663 } elseif ($temperature > 17) {
664 $weather = self
::GLYPHS
['Sunny'];
665 } elseif ($temperature > 10) {
666 $weather = self
::GLYPHS
['Cloudy'];
667 } elseif ($temperature !== null) {
668 $weather = self
::GLYPHS
['Winty'];
676 //Check if realfeel is available
677 if ($session['realfeel'] !== null) {
678 $weathertitle[] = $session['realfeel'].'Β°R';
681 //Check if temperature is available
682 if ($session['temperature'] !== null) {
683 $weathertitle[] = $session['temperature'].'Β°C';
686 //Check if rainrisk is available
687 if ($session['rainrisk'] !== null) {
688 $weathertitle[] = ($session['rainrisk']*100).'%';
691 //Check if rainfall is available
692 if ($session['rainfall'] !== null) {
693 $weathertitle[] = $session['rainfall'].'mm';
698 0 => $translator->trans($session['t_title']).' '.$translator->trans('at '.$session['l_title']).$translator->trans(':')
701 //Fetch pseudonyms from session applications
702 $applications +
= array_combine(explode("\n", $session['sau_id']), array_map(function ($v) {return '- '.$v
;}, explode("\n", $session['sau_pseudonym'])));
707 //Check that session is not granted
708 if (empty($session['a_id'])) {
709 //With location id and unique application
711 //Set unique application pseudonym
712 $pseudonym = $session['sau_pseudonym'];
716 //Replace granted application
717 $applications[$session['au_id']] = '* '.$session['au_pseudonym'];
720 $pseudonym = $session['au_pseudonym'].($count > 1 ? ' ['.$count.']':'');
724 $calendar[$Ymd]['sessions'][$session['t_id'].sprintf('%05d', $session['id'])] = [
725 'id' => $session['id'],
726 'start' => $session['start'],
727 'stop' => $session['stop'],
728 'location' => $translator->trans($session['l_title']),
729 'pseudonym' => $pseudonym,
731 'slot' => self
::GLYPHS
[$session['t_title']],
732 'slottitle' => $translator->trans($session['t_title']),
733 'weather' => $weather,
734 'weathertitle' => implode(' ', $weathertitle),
735 'applications' => $applications,
736 'rate' => $session['p_rate'],
737 'hat' => $session['p_hat']
743 ksort($calendar[$Ymd]['sessions']);
751 * Fetch sessions calendar with translated location by date period and user
753 * @param $translator The TranslatorInterface instance
754 * @param $period The date period
755 * @param $userId The user id
756 * @param $sessionId The session id
758 public function fetchUserCalendarByDatePeriod(TranslatorInterface
$translator, $period, $userId = null, $sessionId = null, $locale = null) {
760 $em = $this->getEntityManager();
763 $qs = $em->getConfiguration()->getQuoteStrategy();
764 $dp = $em->getConnection()->getDatabasePlatform();
766 //Get quoted table names
767 //XXX: this allow to make this code table name independent
769 'RapsysAirBundle:GroupUser' => $qs->getJoinTableName($em->getClassMetadata('RapsysAirBundle:User')->getAssociationMapping('groups'), $em->getClassMetadata('RapsysAirBundle:User'), $dp),
770 'RapsysAirBundle:Session' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Session'), $dp),
771 'RapsysAirBundle:Application' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Application'), $dp),
772 'RapsysAirBundle:Group' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Group'), $dp),
773 'RapsysAirBundle:Location' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Location'), $dp),
774 'RapsysAirBundle:Slot' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Slot'), $dp),
775 'RapsysAirBundle:Snippet' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Snippet'), $dp),
776 'RapsysAirBundle:User' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:User'), $dp),
783 $userJoinSql = $userWhereSql = '';
785 //When user id is set
786 if (!empty($userId)) {
788 $userJoinSql = 'JOIN RapsysAirBundle:Application AS sua ON (sua.session_id = s.id)'."\n";
790 $userWhereSql = "\n\t".'AND sua.user_id = :uid';
794 //TODO: change as_u_* in sau_*, a_u_* in au_*, etc, see request up
804 ADDDATE(ADDTIME(s.date, s.begin), INTERVAL IF(s.slot_id = :afterid, 1, 0) DAY) AS start,
805 ADDDATE(ADDTIME(ADDTIME(s.date, s.begin), s.length), INTERVAL IF(s.slot_id = :afterid, 1, 0) DAY) AS stop,
806 s.location_id AS l_id,
810 s.application_id AS a_id,
812 au.pseudonym AS au_pseudonym,
815 GROUP_CONCAT(sa.user_id ORDER BY sa.user_id SEPARATOR "\\n") AS sau_id,
816 GROUP_CONCAT(CONCAT("- ", sau.pseudonym) ORDER BY sa.user_id SEPARATOR "\\n") AS sau_pseudonym
817 FROM RapsysAirBundle:Session AS s
818 JOIN RapsysAirBundle:Location AS l ON (l.id = s.location_id)
819 JOIN RapsysAirBundle:Slot AS t ON (t.id = s.slot_id)
820 ${userJoinSql}LEFT JOIN RapsysAirBundle:Application AS a ON (a.id = s.application_id)
821 LEFT JOIN RapsysAirBundle:Snippet AS p ON (p.location_id = s.location_id AND p.user_id = a.user_id AND p.locale = :locale)
822 LEFT JOIN RapsysAirBundle:User AS au ON (au.id = a.user_id)
823 LEFT JOIN RapsysAirBundle:Application AS sa ON (sa.session_id = s.id)
824 LEFT JOIN RapsysAirBundle:User AS sau ON (sau.id = sa.user_id)
825 WHERE s.date BETWEEN :begin AND :end${userWhereSql}
830 //Replace bundle entity name by table name
831 $req = str_replace(array_keys($tables), array_values($tables), $req);
833 //Get result set mapping instance
834 //XXX: DEBUG: see ../blog.orig/src/Rapsys/BlogBundle/Repository/ArticleRepository.php
835 $rsm = new ResultSetMapping();
838 //XXX: see vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/Types.php
839 //addScalarResult($sqlColName, $resColName, $type = 'string');
840 $rsm->addScalarResult('id', 'id', 'integer')
841 ->addScalarResult('date', 'date', 'date')
842 ->addScalarResult('rainrisk', 'rainrisk', 'float')
843 ->addScalarResult('rainfall', 'rainfall', 'float')
844 ->addScalarResult('realfeel', 'realfeel', 'float')
845 ->addScalarResult('temperature', 'temperature', 'float')
846 ->addScalarResult('locked', 'locked', 'datetime')
847 ->addScalarResult('start', 'start', 'datetime')
848 ->addScalarResult('stop', 'stop', 'datetime')
849 ->addScalarResult('t_id', 't_id', 'integer')
850 ->addScalarResult('t_title', 't_title', 'string')
851 ->addScalarResult('l_id', 'l_id', 'integer')
852 ->addScalarResult('l_title', 'l_title', 'string')
853 ->addScalarResult('a_id', 'a_id', 'integer')
854 ->addScalarResult('au_id', 'au_id', 'integer')
855 ->addScalarResult('au_pseudonym', 'au_pseudonym', 'string')
856 ->addScalarResult('p_rate', 'p_rate', 'integer')
857 ->addScalarResult('p_hat', 'p_hat', 'boolean')
858 //XXX: is a string because of \n separator
859 ->addScalarResult('sau_id', 'sau_id', 'string')
860 //XXX: is a string because of \n separator
861 ->addScalarResult('sau_pseudonym', 'sau_pseudonym', 'string')
862 ->addIndexByScalar('id');
866 ->createNativeQuery($req, $rsm)
867 ->setParameter('begin', $period->getStartDate())
868 ->setParameter('end', $period->getEndDate())
869 ->setParameter('uid', $userId)
870 ->setParameter('locale', $locale)
879 //Iterate on each day
880 foreach($period as $date) {
881 //Init day in calendar
882 $calendar[$Ymd = $date->format('Ymd')] = [
883 'title' => $translator->trans($date->format('l')).' '.$date->format('d'),
888 //Detect month change
889 if ($month != $date->format('m')) {
890 $month = $date->format('m');
891 //Append month for first day of month
892 //XXX: except if today to avoid double add
893 if ($date->format('U') != strtotime('today')) {
894 $calendar[$Ymd]['title'] .= '/'.$month;
898 if ($date->format('U') == ($today = strtotime('today'))) {
899 $calendar[$Ymd]['title'] .= '/'.$month;
900 $calendar[$Ymd]['current'] = true;
901 $calendar[$Ymd]['class'][] = 'current';
903 //Disable passed days
904 if ($date->format('U') < $today) {
905 $calendar[$Ymd]['disabled'] = true;
906 $calendar[$Ymd]['class'][] = 'disabled';
908 //Set next month days
909 if ($date->format('m') > date('m')) {
910 $calendar[$Ymd]['next'] = true;
911 #$calendar[$Ymd]['class'][] = 'next';
915 if ($date->format('w') == 0) {
916 $calendar[$Ymd]['class'][] = 'sunday';
919 //Iterate on each session to find the one of the day
920 foreach($res as $session) {
921 if (($sessionYmd = $session['date']->format('Ymd')) == $Ymd) {
922 //Count number of application
923 $count = count(explode("\n", $session['sau_id']));
927 if (!empty($session['a_id'])) {
928 $applications = [ $session['au_id'] => $session['au_pseudonym'] ];
929 if ($session['au_id'] == $userId) {
930 $class[] = 'granted';
932 $class[] = 'disputed';
934 } elseif ($count > 1) {
935 $class[] = 'disputed';
936 } elseif (!empty($session['locked'])) {
939 $class[] = 'pending';
942 if ($sessionId == $session['id']) {
943 $class[] = 'highlight';
947 //XXX: realfeel may be null, temperature should not
948 $temperature = $session['realfeel'] !== null ? $session['realfeel'] : $session['temperature'];
951 //XXX: rainfall may be null
952 if ($session['rainrisk'] > 0.50 || $session['rainfall'] > 2) {
953 $weather = self
::GLYPHS
['Stormy'];
954 } elseif ($session['rainrisk'] > 0.40 || $session['rainfall'] > 1) {
955 $weather = self
::GLYPHS
['Rainy'];
956 } elseif ($temperature > 24) {
957 $weather = self
::GLYPHS
['Cleary'];
958 } elseif ($temperature > 17) {
959 $weather = self
::GLYPHS
['Sunny'];
960 } elseif ($temperature > 10) {
961 $weather = self
::GLYPHS
['Cloudy'];
962 } elseif ($temperature !== null) {
963 $weather = self
::GLYPHS
['Winty'];
971 //Check if realfeel is available
972 if ($session['realfeel'] !== null) {
973 $weathertitle[] = $session['realfeel'].'Β°R';
976 //Check if temperature is available
977 if ($session['temperature'] !== null) {
978 $weathertitle[] = $session['temperature'].'Β°C';
981 //Check if rainrisk is available
982 if ($session['rainrisk'] !== null) {
983 $weathertitle[] = ($session['rainrisk']*100).'%';
986 //Check if rainfall is available
987 if ($session['rainfall'] !== null) {
988 $weathertitle[] = $session['rainfall'].'mm';
993 0 => $translator->trans($session['t_title']).' '.$translator->trans('at '.$session['l_title']).$translator->trans(':')
996 //Fetch pseudonyms from session applications
997 $applications +
= array_combine(explode("\n", $session['sau_id']), array_map(function ($v) {return '- '.$v
;}, explode("\n", $session['sau_pseudonym'])));
1002 //Check that session is not granted
1003 if (empty($session['a_id'])) {
1004 //With location id and unique application
1006 //Set unique application pseudonym
1007 $pseudonym = $session['sau_pseudonym'];
1009 //Session is granted
1011 //Replace granted application
1012 $applications[$session['au_id']] = '* '.$session['au_pseudonym'];
1015 $pseudonym = $session['au_pseudonym'].($count > 1 ? ' ['.$count.']':'');
1019 $title = $translator->trans($session['l_title']).($count > 1 ? ' ['.$count.']':'');
1022 $calendar[$Ymd]['sessions'][$session['t_id'].sprintf('%02d', $session['l_id'])] = [
1023 'id' => $session['id'],
1024 'start' => $session['start'],
1025 'stop' => $session['stop'],
1026 'location' => $translator->trans($session['l_title']),
1027 'pseudonym' => $pseudonym,
1029 'slot' => self
::GLYPHS
[$session['t_title']],
1030 'slottitle' => $translator->trans($session['t_title']),
1031 'weather' => $weather,
1032 'weathertitle' => implode(' ', $weathertitle),
1033 'applications' => $applications,
1034 'rate' => $session['p_rate'],
1035 'hat' => $session['p_hat']
1041 ksort($calendar[$Ymd]['sessions']);
1049 * Find all session pending hourly weather
1051 * @return array<Session> The sessions to update
1053 public function findAllPendingHourlyWeather() {
1054 //Get entity manager
1055 $em = $this->getEntityManager();
1057 //Get quote strategy
1058 $qs = $em->getConfiguration()->getQuoteStrategy();
1059 $dp = $em->getConnection()->getDatabasePlatform();
1061 //Get quoted table names
1062 //XXX: this allow to make this code table name independent
1064 'RapsysAirBundle:Session' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Session'), $dp),
1065 'RapsysAirBundle:Location' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Location'), $dp),
1067 ':accuhourly' => self
::ACCUWEATHER_HOURLY
,
1074 //Select all sessions starting and stopping in the next 3 days
1075 //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)
1077 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
1078 FROM RapsysAirBundle:Session AS s
1079 JOIN RapsysAirBundle:Location AS l ON (l.id = s.location_id)
1080 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))
1083 //Replace bundle entity name by table name
1084 $req = str_replace(array_keys($tables), array_values($tables), $req);
1086 //Get result set mapping instance
1087 $rsm = new ResultSetMapping();
1089 //Declare all fields
1091 ->addEntityResult('RapsysAirBundle:Session', 's')
1092 ->addFieldResult('s', 'id', 'id')
1093 ->addFieldResult('s', 'date', 'date')
1094 ->addFieldResult('s', 'begin', 'begin')
1095 ->addFieldResult('s', 'length', 'length')
1096 ->addFieldResult('s', 'rainfall', 'rainfall')
1097 ->addFieldResult('s', 'rainrisk', 'rainrisk')
1098 ->addFieldResult('s', 'realfeel', 'realfeel')
1099 ->addFieldResult('s', 'realfeelmin', 'realfeelmin')
1100 ->addFieldResult('s', 'realfeelmax', 'realfeelmax')
1101 ->addFieldResult('s', 'temperature', 'temperature')
1102 ->addFieldResult('s', 'temperaturemin', 'temperaturemin')
1103 ->addFieldResult('s', 'temperaturemax', 'temperaturemax')
1104 ->addJoinedEntityResult('RapsysAirBundle:Slot', 'o', 's', 'slot')
1105 ->addFieldResult('o', 'slot_id', 'id')
1106 ->addJoinedEntityResult('RapsysAirBundle:Location', 'l', 's', 'location')
1107 ->addFieldResult('l', 'location_id', 'id')
1108 ->addFieldResult('l', 'zipcode', 'zipcode')
1109 ->addIndexBy('s', 'id');
1113 ->createNativeQuery($req, $rsm)
1118 * Find all session pending daily weather
1120 * @return array<Session> The sessions to update
1122 public function findAllPendingDailyWeather() {
1123 //Get entity manager
1124 $em = $this->getEntityManager();
1126 //Get quote strategy
1127 $qs = $em->getConfiguration()->getQuoteStrategy();
1128 $dp = $em->getConnection()->getDatabasePlatform();
1130 //Get quoted table names
1131 //XXX: this allow to make this code table name independent
1133 'RapsysAirBundle:Session' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Session'), $dp),
1134 'RapsysAirBundle:Location' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Location'), $dp),
1136 ':accudaily' => self
::ACCUWEATHER_DAILY
,
1137 ':accuhourly' => self
::ACCUWEATHER_HOURLY
,
1144 //Select all sessions stopping after next 3 days
1145 //XXX: select session stopping after or equal date(now)+3d as accuweather only provide hourly data for the next 3 days (INTERVAL 3 DAY)
1147 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
1148 FROM RapsysAirBundle:Session AS s
1149 JOIN RapsysAirBundle:Location AS l ON (l.id = s.location_id)
1150 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))
1153 //Replace bundle entity name by table name
1154 $req = str_replace(array_keys($tables), array_values($tables), $req);
1156 //Get result set mapping instance
1157 $rsm = new ResultSetMapping();
1159 //Declare all fields
1161 ->addEntityResult('RapsysAirBundle:Session', 's')
1162 ->addFieldResult('s', 'id', 'id')
1163 ->addFieldResult('s', 'date', 'date')
1164 ->addFieldResult('s', 'begin', 'begin')
1165 ->addFieldResult('s', 'length', 'length')
1166 ->addFieldResult('s', 'rainfall', 'rainfall')
1167 ->addFieldResult('s', 'rainrisk', 'rainrisk')
1168 ->addFieldResult('s', 'realfeel', 'realfeel')
1169 ->addFieldResult('s', 'realfeelmin', 'realfeelmin')
1170 ->addFieldResult('s', 'realfeelmax', 'realfeelmax')
1171 ->addFieldResult('s', 'temperature', 'temperature')
1172 ->addFieldResult('s', 'temperaturemin', 'temperaturemin')
1173 ->addFieldResult('s', 'temperaturemax', 'temperaturemax')
1174 ->addJoinedEntityResult('RapsysAirBundle:Slot', 'o', 's', 'slot')
1175 ->addFieldResult('o', 'slot_id', 'id')
1176 ->addJoinedEntityResult('RapsysAirBundle:Location', 'l', 's', 'location')
1177 ->addFieldResult('l', 'location_id', 'id')
1178 ->addFieldResult('l', 'zipcode', 'zipcode')
1179 ->addIndexBy('s', 'id');
1183 ->createNativeQuery($req, $rsm)
1188 * Find every session pending application
1190 * @return array<Session> The sessions to update
1192 public function findAllPendingApplication() {
1193 //Get entity manager
1194 $em = $this->getEntityManager();
1196 //Get quote strategy
1197 $qs = $em->getConfiguration()->getQuoteStrategy();
1198 $dp = $em->getConnection()->getDatabasePlatform();
1200 //Get quoted table names
1201 //XXX: this allow to make this code table name independent
1203 'RapsysAirBundle:Application' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Application'), $dp),
1204 'RapsysAirBundle:Session' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Session'), $dp),
1206 ':regulardelay' => self
::REGULAR_DELAY
* 24 * 3600,
1207 ':seniordelay' => self
::SENIOR_DELAY
* 24 * 3600,
1214 //Select all sessions not locked without application or canceled application within attribution period
1215 //XXX: DIFF(start, now) <= IF(DIFF(start, created) <= SENIOR_DELAY in DAY, DIFF(start, created) * 3 / 4, SENIOR_DELAY)
1216 //TODO: remonter les donnΓ©es pour le mail ?
1219 FROM RapsysAirBundle:Session as s
1220 LEFT JOIN RapsysAirBundle:Application AS a ON (a.id = s.application_id AND a.canceled IS NULL)
1221 JOIN RapsysAirBundle:Application AS a2 ON (a2.session_id = s.id AND a2.canceled IS NULL)
1222 WHERE s.locked IS NULL AND a.id IS NULL AND
1223 TIME_TO_SEC(TIMEDIFF(@dt_start := ADDDATE(ADDTIME(s.date, s.begin), INTERVAL IF(s.slot_id = :afterid, 1, 0) DAY), NOW())) <= IF(
1224 TIME_TO_SEC(@td_sc := TIMEDIFF(@dt_start, s.created)) <= :seniordelay,
1225 ROUND(TIME_TO_SEC(@td_sc) * :regulardelay / :seniordelay),
1229 ORDER BY @dt_start ASC, s.created ASC
1233 //Replace bundle entity name by table name
1234 $req = str_replace(array_keys($tables), array_values($tables), $req);
1236 //Get result set mapping instance
1237 $rsm = new ResultSetMapping();
1239 //Declare all fields
1241 ->addEntityResult('RapsysAirBundle:Session', 's')
1242 ->addFieldResult('s', 'id', 'id')
1243 ->addIndexBy('s', 'id');
1247 ->createNativeQuery($req, $rsm)
1252 * Fetch session best application by session id
1254 * @param int $id The session id
1255 * @return Application|null The application or null
1257 public function findBestApplicationById($id) {
1258 //Get entity manager
1259 $em = $this->getEntityManager();
1261 //Get quote strategy
1262 $qs = $em->getConfiguration()->getQuoteStrategy();
1263 $dp = $em->getConnection()->getDatabasePlatform();
1265 //Get quoted table names
1266 //XXX: this allow to make this code table name independent
1268 'RapsysAirBundle:Application' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Application'), $dp),
1269 'RapsysAirBundle:GroupUser' => $qs->getJoinTableName($em->getClassMetadata('RapsysAirBundle:User')->getAssociationMapping('groups'), $em->getClassMetadata('RapsysAirBundle:User'), $dp),
1270 'RapsysAirBundle:Location' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Location'), $dp),
1271 'RapsysAirBundle:Session' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Session'), $dp),
1272 //XXX: Set limit used to workaround mariadb subselect optimization
1273 ':limit' => PHP_INT_MAX
,
1275 ':guestdelay' => self
::GUEST_DELAY
* 24 * 3600,
1276 ':regulardelay' => self
::REGULAR_DELAY
* 24 * 3600,
1277 ':seniordelay' => self
::SENIOR_DELAY
* 24 * 3600,
1283 ':afternoonid' => 2,
1286 //XXX: days since last session after which guest regain normal priority
1288 //XXX: session count until considered at regular delay
1290 //XXX: pn_ratio over which considered at regular delay
1292 //XXX: tr_ratio diff over which considered at regular delay
1299 * Query session applications ranked by location score, global score, created and user_id
1301 * @xxx guest (or less) with application on location within 30 day are only considered within guestdelay
1303 * @xxx regular (or less) premium application on hotspot are only considered within regulardelay
1305 * @xxx senior (or less) with 5 or less session on location are only considered within seniordelay
1307 * @xxx senior (or less) with l_pn_ratio >= 1 are only considered within seniordelay
1309 * @xxx senior (or less) with l_tr_ratio >= (o_tr_ratio + 5) are only considered within seniordelay
1311 * @xxx only consider session within one year (may be unaccurate by the day with after session)
1313 * @xxx rainfall may not be accessible for previous session and other session at d-4 (only at d-2)
1315 * @todo ??? feedback the data to inform the rejected users ???
1318 SELECT e.id, e.l_score AS score
1330 MAX(gu.group_id) AS group_id,
1345 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,
1362 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,
1375 COUNT(a2.id) AS l_count,
1376 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,
1377 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,
1378 (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,
1379 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,
1380 TIME_TO_SEC(TIMEDIFF(ADDDATE(ADDTIME(s.date, s.begin), INTERVAL IF(s.slot_id = :afterid, 1, 0) DAY), NOW())) AS remaining,
1384 FROM RapsysAirBundle:Session AS s
1385 JOIN RapsysAirBundle:Location AS l ON (l.id = s.location_id)
1386 JOIN RapsysAirBundle:Application AS a ON (a.session_id = s.id AND a.canceled IS NULL)
1387 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)
1388 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))
1394 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)
1395 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))
1400 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)
1401 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))
1406 LEFT JOIN RapsysAirBundle:GroupUser AS gu ON (gu.user_id = d.user_id)
1411 IF(e.group_id <= :guestid AND e.l_previous <= :guestwait, e.remaining <= :guestdelay, 1) AND
1412 IF(e.group_id <= :regularid AND e.premium = 1 AND e.hotspot = 1, e.remaining <= :regulardelay, 1) AND
1413 IF(e.group_id <= :seniorid AND e.l_count <= :scount, e.remaining <= :regulardelay, 1) AND
1414 IF(e.group_id <= :seniorid AND e.l_pn_ratio >= :pnratio, e.remaining <= :regulardelay, 1) AND
1415 IF(e.group_id <= :seniorid AND e.l_tr_ratio >= (e.o_tr_ratio + :trdiff), e.remaining <= :regulardelay, 1)
1416 ORDER BY e.l_score ASC, e.g_score ASC, e.created ASC, e.user_id ASC
1419 //Replace bundle entity name by table name
1420 $req = str_replace(array_keys($tables), array_values($tables), $req);
1422 //Set update request
1423 $upreq = 'UPDATE RapsysAirBundle:Application SET score = :score, updated = NOW() WHERE id = :id';
1425 //Replace bundle entity name by table name
1426 $upreq = str_replace(array_keys($tables), array_values($tables), $upreq);
1428 //Get result set mapping instance
1429 $rsm = new ResultSetMapping();
1431 //Declare all fields
1433 ->addEntityResult('RapsysAirBundle:Application', 'a')
1434 ->addFieldResult('a', 'id', 'id')
1435 ->addFieldResult('a', 'score', 'score')
1436 ->addIndexBy('a', 'id');
1439 //XXX: setting limit in subqueries is required to prevent mariadb optimisation
1441 ->createNativeQuery($req, $rsm)
1442 ->setParameter('sid', $id)
1443 //XXX: removed, we update score before returning best candidate
1444 //->getOneOrNullResult(Query::HYDRATE_SINGLE_SCALAR);
1451 foreach($applications as $application) {
1452 //Check if we already saved best candidate
1453 if ($ret === null) {
1454 //Return first application
1455 $ret = $application;
1458 //Update application updated field
1459 //XXX: updated field is not modified for user with bad behaviour as application is not retrieved until delay is reached
1460 $em->getConnection()->executeUpdate($upreq, ['id' => $application->getId(), 'score' => $application->getScore()], ['id' => Type
::INTEGER, 'score' => Type
::FLOAT]);
1463 //Return best ranked application
1469 * Rekey sessions and applications by chronological session id
1471 * @return bool The rekey success or failure
1473 function rekey(): bool {
1474 //Get entity manager
1475 $em = $this->getEntityManager();
1478 $cnx = $em->getConnection();
1480 //Get quote strategy
1481 $qs = $em->getConfiguration()->getQuoteStrategy();
1482 $dp = $em->getConnection()->getDatabasePlatform();
1484 //Get quoted table names
1485 //XXX: this allow to make this code table name independent
1487 'RapsysAirBundle:Application' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Application'), $dp),
1488 'RapsysAirBundle:Session' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Session'), $dp),
1505 GROUP_CONCAT(sa.id ORDER BY sa.id SEPARATOR "\\n") AS sa_id
1506 FROM RapsysAirBundle:Session AS s
1507 LEFT JOIN RapsysAirBundle:Application AS sa ON (sa.session_id = s.id)
1511 ORDER BY ADDDATE(ADDTIME(a.date, a.begin), INTERVAL IF(a.slot_id = :afterid, 1, 0) DAY) ASC
1514 //Replace bundle entity name by table name
1515 $req = str_replace(array_keys($tables), array_values($tables), $req);
1517 //Get result set mapping instance
1518 //XXX: DEBUG: see ../blog.orig/src/Rapsys/BlogBundle/Repository/ArticleRepository.php
1519 $rsm = new ResultSetMapping();
1521 //Declare all fields
1522 //XXX: see vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/Types.php
1523 //addScalarResult($sqlColName, $resColName, $type = 'string');
1524 $rsm->addScalarResult('id', 'id', 'integer')
1525 ->addScalarResult('sa_id', 'sa_id', 'string');
1526 #->addIndexByScalar('id');
1529 $rnq = $em->createNativeQuery($req, $rsm);
1532 $res = $rnq->getResult();
1535 $cnx->beginTransaction();
1537 //Set update session request
1539 UPDATE RapsysAirBundle:Session
1540 SET id = :nid, updated = NOW()
1544 //Replace bundle entity name by table name
1545 $sreq = str_replace(array_keys($tables), array_values($tables), $sreq);
1547 //Set update application request
1549 UPDATE RapsysAirBundle:Application
1550 SET session_id = :nid, updated = NOW()
1551 WHERE session_id = :id
1554 //Replace bundle entity name by table name
1555 $areq = str_replace(array_keys($tables), array_values($tables), $areq);
1558 $max = max(array_keys($res));
1561 //Prepare session to update
1562 foreach($res as $id => $data) {
1564 $res[$id]['t_id'] = $max +
$id +
1;
1567 $res[$id]['n_id'] = $id +
1;
1569 //Explode application ids
1570 $res[$id]['sa_id'] = explode("\n", $data['sa_id']);
1573 if ($res[$id]['n_id'] == $res[$id]['id']) {
1574 //Remove unchanged session
1581 //Disable foreign key checks
1582 $cnx->prepare('SET foreign_key_checks = 0')->execute();
1585 foreach($res as $id => $data) {
1586 //Run session update
1587 $cnx->executeUpdate($sreq, ['nid' => $res[$id]['t_id'], 'id' => $res[$id]['id']]);
1589 //Run applications update
1590 $cnx->executeUpdate($areq, ['nid' => $res[$id]['t_id'], 'id' => $res[$id]['id']]);
1594 foreach($res as $id => $data) {
1595 //Run session update
1596 $cnx->executeUpdate($sreq, ['nid' => $res[$id]['n_id'], 'id' => $res[$id]['t_id']]);
1598 //Run applications update
1599 $cnx->executeUpdate($areq, ['nid' => $res[$id]['n_id'], 'id' => $res[$id]['t_id']]);
1602 //Restore foreign key checks
1603 $cnx->prepare('SET foreign_key_checks = 1')->execute();
1605 //Commit transaction
1608 //Set update auto_increment request
1610 ALTER TABLE RapsysAirBundle:Session
1614 //Replace bundle entity name by table name
1615 $ireq = str_replace(array_keys($tables), array_values($tables), $ireq);
1617 //Reset auto_increment
1621 //Rollback transaction
1624 } catch(\Exception
$e) {
1625 //Rollback transaction