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,
199 p.contact AS p_contact,
200 p.donate AS p_donate,
202 p.profile AS p_profile
203 FROM RapsysAirBundle:Session AS s
204 JOIN RapsysAirBundle:Location AS l ON (l.id = s.location_id)
205 JOIN RapsysAirBundle:Application AS a ON (a.id = s.application_id)
206 JOIN RapsysAirBundle:User AS au ON (au.id = a.user_id)
207 LEFT JOIN RapsysAirBundle:Snippet AS p ON (p.location_id = s.location_id AND p.user_id = a.user_id AND p.locale = :locale)
208 WHERE s.date BETWEEN :begin AND :end
212 //Replace bundle entity name by table name
213 $req = str_replace(array_keys($tables), array_values($tables), $req);
215 //Get result set mapping instance
216 //XXX: DEBUG: see ../blog.orig/src/Rapsys/BlogBundle/Repository/ArticleRepository.php
217 $rsm = new ResultSetMapping();
220 //XXX: see vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/Types.php
221 //addScalarResult($sqlColName, $resColName, $type = 'string');
222 $rsm->addScalarResult('id', 'id', 'integer')
223 ->addScalarResult('date', 'date', 'date')
224 ->addScalarResult('locked', 'locked', 'datetime')
225 ->addScalarResult('updated', 'updated', 'datetime')
226 ->addScalarResult('start', 'start', 'datetime')
227 ->addScalarResult('stop', 'stop', 'datetime')
228 ->addScalarResult('l_id', 'l_id', 'integer')
229 ->addScalarResult('l_address', 'l_address', 'string')
230 ->addScalarResult('l_zipcode', 'l_zipcode', 'string')
231 ->addScalarResult('l_city', 'l_city', 'string')
232 ->addScalarResult('l_latitude', 'l_latitude', 'float')
233 ->addScalarResult('l_longitude', 'l_longitude', 'float')
234 ->addScalarResult('l_title', 'l_title', 'string')
235 ->addScalarResult('t_id', 't_id', 'integer')
236 ->addScalarResult('t_title', 't_title', 'string')
237 ->addScalarResult('a_id', 'a_id', 'integer')
238 ->addScalarResult('a_canceled', 'a_canceled', 'datetime')
239 ->addScalarResult('au_id', 'au_id', 'integer')
240 ->addScalarResult('au_forename', 'au_forename', 'string')
241 ->addScalarResult('au_pseudonym', 'au_pseudonym', 'string')
242 ->addScalarResult('p_id', 'p_id', 'integer')
243 ->addScalarResult('p_description', 'p_description', 'string')
244 ->addScalarResult('p_class', 'p_class', 'string')
245 ->addScalarResult('p_short', 'p_short', 'string')
246 ->addScalarResult('p_rate', 'p_rate', 'integer')
247 ->addScalarResult('p_contact', 'p_contact', 'string')
248 ->addScalarResult('p_donate', 'p_donate', 'string')
249 ->addScalarResult('p_link', 'p_link', 'string')
250 ->addScalarResult('p_profile', 'p_profile', 'string')
251 ->addIndexByScalar('id');
255 ->createNativeQuery($req, $rsm)
256 ->setParameter('begin', $period->getStartDate())
257 ->setParameter('end', $period->getEndDate())
258 ->setParameter('locale', $locale);
261 return $res->getResult();
265 * Fetch session by id
267 * @param $id The session id
268 * @param $locale The locale
269 * @return array The session data
271 public function fetchOneById($id, $locale = null) {
273 $em = $this->getEntityManager();
276 $qs = $em->getConfiguration()->getQuoteStrategy();
277 $dp = $em->getConnection()->getDatabasePlatform();
279 //Get quoted table names
280 //XXX: this allow to make this code table name independent
282 'RapsysAirBundle:Application' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Application'), $dp),
283 'RapsysAirBundle:Group' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Group'), $dp),
284 'RapsysAirBundle:GroupUser' => $qs->getJoinTableName($em->getClassMetadata('RapsysAirBundle:User')->getAssociationMapping('groups'), $em->getClassMetadata('RapsysAirBundle:User'), $dp),
285 'RapsysAirBundle:Location' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Location'), $dp),
286 'RapsysAirBundle:Session' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Session'), $dp),
287 'RapsysAirBundle:Snippet' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Snippet'), $dp),
288 'RapsysAirBundle:Slot' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Slot'), $dp),
289 'RapsysAirBundle:User' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:User'), $dp),
296 //TODO: compute scores ?
297 //TODO: compute delivery date ? (J-3/J-4 ?)
303 ADDDATE(ADDTIME(s.date, s.begin), INTERVAL IF(s.slot_id = :afterid, 1, 0) DAY) AS start,
305 ADDDATE(ADDTIME(ADDTIME(s.date, s.begin), s.length), INTERVAL IF(s.slot_id = :afterid, 1, 0) DAY) AS stop,
317 s.location_id AS l_id,
319 l.address AS l_address,
320 l.zipcode AS l_zipcode,
322 l.latitude AS l_latitude,
323 l.longitude AS l_longitude,
324 l.updated AS l_updated,
327 t.updated AS t_updated,
328 s.application_id AS a_id,
329 a.canceled AS a_canceled,
331 au.pseudonym AS au_pseudonym,
333 p.description AS p_description,
335 p.contact AS p_contact,
336 p.donate AS p_donate,
338 p.profile AS p_profile,
341 p.updated AS p_updated,
342 GROUP_CONCAT(sa.id ORDER BY sa.user_id SEPARATOR "\\n") AS sa_id,
343 GROUP_CONCAT(IFNULL(sa.score, 'NULL') ORDER BY sa.user_id SEPARATOR "\\n") AS sa_score,
344 GROUP_CONCAT(sa.created ORDER BY sa.user_id SEPARATOR "\\n") AS sa_created,
345 GROUP_CONCAT(sa.updated ORDER BY sa.user_id SEPARATOR "\\n") AS sa_updated,
346 GROUP_CONCAT(IFNULL(sa.canceled, 'NULL') ORDER BY sa.user_id SEPARATOR "\\n") AS sa_canceled,
347 GROUP_CONCAT(sa.user_id ORDER BY sa.user_id SEPARATOR "\\n") AS sau_id,
348 GROUP_CONCAT(sau.pseudonym ORDER BY sa.user_id SEPARATOR "\\n") AS sau_pseudonym
349 FROM RapsysAirBundle:Session AS s
350 JOIN RapsysAirBundle:Location AS l ON (l.id = s.location_id)
351 JOIN RapsysAirBundle:Slot AS t ON (t.id = s.slot_id)
352 LEFT JOIN RapsysAirBundle:Application AS a ON (a.id = s.application_id)
353 LEFT JOIN RapsysAirBundle:User AS au ON (au.id = a.user_id)
354 LEFT JOIN RapsysAirBundle:Snippet AS p ON (p.location_id = s.location_id AND p.user_id = a.user_id AND p.locale = :locale)
355 LEFT JOIN RapsysAirBundle:Application AS sa ON (sa.session_id = s.id)
356 LEFT JOIN RapsysAirBundle:User AS sau ON (sau.id = sa.user_id)
362 //Replace bundle entity name by table name
363 $req = str_replace(array_keys($tables), array_values($tables), $req);
365 //Get result set mapping instance
366 //XXX: DEBUG: see ../blog.orig/src/Rapsys/BlogBundle/Repository/ArticleRepository.php
367 $rsm = new ResultSetMapping();
370 //XXX: see vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/Types.php
371 $rsm->addScalarResult('id', 'id', 'integer')
372 ->addScalarResult('date', 'date', 'date')
373 ->addScalarResult('begin', 'begin', 'time')
374 ->addScalarResult('start', 'start', 'datetime')
375 ->addScalarResult('length', 'length', 'time')
376 ->addScalarResult('stop', 'stop', 'datetime')
377 ->addScalarResult('rainfall', 'rainfall', 'float')
378 ->addScalarResult('rainrisk', 'rainrisk', 'float')
379 ->addScalarResult('realfeel', 'realfeel', 'float')
380 ->addScalarResult('realfeelmin', 'realfeelmin', 'float')
381 ->addScalarResult('realfeelmax', 'realfeelmax', 'float')
382 ->addScalarResult('temperature', 'temperature', 'float')
383 ->addScalarResult('temperaturemin', 'temperaturemin', 'float')
384 ->addScalarResult('temperaturemax', 'temperaturemax', 'float')
385 ->addScalarResult('locked', 'locked', 'datetime')
386 ->addScalarResult('created', 'created', 'datetime')
387 ->addScalarResult('updated', 'updated', 'datetime')
388 ->addScalarResult('l_id', 'l_id', 'integer')
389 ->addScalarResult('l_title', 'l_title', 'string')
390 ->addScalarResult('l_address', 'l_address', 'string')
391 ->addScalarResult('l_zipcode', 'l_zipcode', 'string')
392 ->addScalarResult('l_city', 'l_city', 'string')
393 ->addScalarResult('l_latitude', 'l_latitude', 'float')
394 ->addScalarResult('l_longitude', 'l_longitude', 'float')
395 ->addScalarResult('l_updated', 'l_updated', 'datetime')
396 ->addScalarResult('t_id', 't_id', 'integer')
397 ->addScalarResult('t_title', 't_title', 'string')
398 ->addScalarResult('t_updated', 't_updated', 'datetime')
399 ->addScalarResult('a_id', 'a_id', 'integer')
400 ->addScalarResult('a_canceled', 'a_canceled', 'datetime')
401 ->addScalarResult('au_id', 'au_id', 'integer')
402 ->addScalarResult('au_pseudonym', 'au_pseudonym', 'string')
403 ->addScalarResult('p_id', 'p_id', 'integer')
404 ->addScalarResult('p_description', 'p_description', 'text')
405 ->addScalarResult('p_class', 'p_class', 'text')
406 ->addScalarResult('p_contact', 'p_contact', 'text')
407 ->addScalarResult('p_donate', 'p_donate', 'text')
408 ->addScalarResult('p_link', 'p_link', 'text')
409 ->addScalarResult('p_profile', 'p_profile', 'text')
410 ->addScalarResult('p_rate', 'p_rate', 'integer')
411 ->addScalarResult('p_hat', 'p_hat', 'boolean')
412 ->addScalarResult('p_updated', 'p_updated', 'datetime')
413 //XXX: is a string because of \n separator
414 ->addScalarResult('sa_id', 'sa_id', 'string')
415 //XXX: is a string because of \n separator
416 ->addScalarResult('sa_score', 'sa_score', 'string')
417 //XXX: is a string because of \n separator
418 ->addScalarResult('sa_created', 'sa_created', 'string')
419 //XXX: is a string because of \n separator
420 ->addScalarResult('sa_updated', 'sa_updated', 'string')
421 //XXX: is a string because of \n separator
422 ->addScalarResult('sa_canceled', 'sa_canceled', '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('sid', $id)
433 ->setParameter('locale', $locale)
434 ->getOneOrNullResult();
438 * Fetch sessions calendar with translated location by date period
440 * @param $translator The TranslatorInterface instance
441 * @param $period The date period
442 * @param $locationId The location id
443 * @param $sessionId The session id
444 * @param $granted The session is granted
446 public function fetchCalendarByDatePeriod(TranslatorInterface
$translator, $period, $locationId = null, $sessionId = null, $granted = false, $locale = null) {
448 $em = $this->getEntityManager();
451 $qs = $em->getConfiguration()->getQuoteStrategy();
452 $dp = $em->getConnection()->getDatabasePlatform();
454 //Get quoted table names
455 //XXX: this allow to make this code table name independent
457 'RapsysAirBundle:GroupUser' => $qs->getJoinTableName($em->getClassMetadata('RapsysAirBundle:User')->getAssociationMapping('groups'), $em->getClassMetadata('RapsysAirBundle:User'), $dp),
458 'RapsysAirBundle:Session' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Session'), $dp),
459 'RapsysAirBundle:Application' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Application'), $dp),
460 'RapsysAirBundle:Group' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Group'), $dp),
461 'RapsysAirBundle:Location' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Location'), $dp),
462 'RapsysAirBundle:Slot' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Slot'), $dp),
463 'RapsysAirBundle:Snippet' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Snippet'), $dp),
464 'RapsysAirBundle:User' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:User'), $dp),
473 //When granted is set
474 if (empty($granted)) {
475 //Set application and user as optional
482 //When location id is set
483 if (!empty($locationId)) {
484 //Add location id clause
485 $locationSql = "\n\t".'AND s.location_id = :lid';
499 ADDDATE(ADDTIME(s.date, s.begin), INTERVAL IF(s.slot_id = :afterid, 1, 0) DAY) AS start,
500 ADDDATE(ADDTIME(ADDTIME(s.date, s.begin), s.length), INTERVAL IF(s.slot_id = :afterid, 1, 0) DAY) AS stop,
501 s.location_id AS l_id,
505 s.application_id AS a_id,
506 a.canceled AS a_canceled,
508 au.pseudonym AS au_pseudonym,
511 GROUP_CONCAT(sa.user_id ORDER BY sa.user_id SEPARATOR "\\n") AS sau_id,
512 GROUP_CONCAT(sau.pseudonym ORDER BY sa.user_id SEPARATOR "\\n") AS sau_pseudonym
513 FROM RapsysAirBundle:Session AS s
514 JOIN RapsysAirBundle:Location AS l ON (l.id = s.location_id)
515 JOIN RapsysAirBundle:Slot AS t ON (t.id = s.slot_id)
516 ${grantSql}JOIN RapsysAirBundle:Application AS a ON (a.id = s.application_id)
517 ${grantSql}JOIN RapsysAirBundle:User AS au ON (au.id = a.user_id)
518 LEFT JOIN RapsysAirBundle:Application AS sa ON (sa.session_id = s.id)
519 LEFT JOIN RapsysAirBundle:Snippet AS p ON (p.location_id = s.location_id AND p.user_id = a.user_id AND p.locale = :locale)
520 LEFT JOIN RapsysAirBundle:User AS sau ON (sau.id = sa.user_id)
521 WHERE s.date BETWEEN :begin AND :end${locationSql}
526 //Replace bundle entity name by table name
527 $req = str_replace(array_keys($tables), array_values($tables), $req);
529 //Get result set mapping instance
530 //XXX: DEBUG: see ../blog.orig/src/Rapsys/BlogBundle/Repository/ArticleRepository.php
531 $rsm = new ResultSetMapping();
534 //XXX: see vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/Types.php
535 //addScalarResult($sqlColName, $resColName, $type = 'string');
536 $rsm->addScalarResult('id', 'id', 'integer')
537 ->addScalarResult('date', 'date', 'date')
538 ->addScalarResult('rainrisk', 'rainrisk', 'float')
539 ->addScalarResult('rainfall', 'rainfall', 'float')
540 ->addScalarResult('realfeel', 'realfeel', 'float')
541 ->addScalarResult('temperature', 'temperature', 'float')
542 ->addScalarResult('locked', 'locked', 'datetime')
543 ->addScalarResult('start', 'start', 'datetime')
544 ->addScalarResult('stop', 'stop', 'datetime')
545 ->addScalarResult('t_id', 't_id', 'integer')
546 ->addScalarResult('t_title', 't_title', 'string')
547 ->addScalarResult('l_id', 'l_id', 'integer')
548 ->addScalarResult('l_title', 'l_title', 'string')
549 ->addScalarResult('a_id', 'a_id', 'integer')
550 ->addScalarResult('a_canceled', 'a_canceled', 'datetime')
551 ->addScalarResult('au_id', 'au_id', 'integer')
552 ->addScalarResult('au_pseudonym', 'au_pseudonym', 'string')
553 ->addScalarResult('p_rate', 'p_rate', 'integer')
554 ->addScalarResult('p_hat', 'p_hat', 'boolean')
555 //XXX: is a string because of \n separator
556 ->addScalarResult('sau_id', 'sau_id', 'string')
557 //XXX: is a string because of \n separator
558 ->addScalarResult('sau_pseudonym', 'sau_pseudonym', 'string')
559 ->addIndexByScalar('id');
563 ->createNativeQuery($req, $rsm)
564 ->setParameter('begin', $period->getStartDate())
565 ->setParameter('end', $period->getEndDate())
566 ->setParameter('locale', $locale);
568 //Add optional location id
569 if (!empty($locationId)) {
570 $res->setParameter('lid', $locationId);
574 $res = $res->getResult();
582 //Iterate on each day
583 foreach($period as $date) {
584 //Init day in calendar
585 $calendar[$Ymd = $date->format('Ymd')] = [
586 'title' => $translator->trans($date->format('l')).' '.$date->format('d'),
591 //Detect month change
592 if ($month != $date->format('m')) {
593 $month = $date->format('m');
594 //Append month for first day of month
595 //XXX: except if today to avoid double add
596 if ($date->format('U') != strtotime('today')) {
597 $calendar[$Ymd]['title'] .= '/'.$month;
601 if ($date->format('U') == ($today = strtotime('today'))) {
602 $calendar[$Ymd]['title'] .= '/'.$month;
603 $calendar[$Ymd]['current'] = true;
604 $calendar[$Ymd]['class'][] = 'current';
606 //Disable passed days
607 if ($date->format('U') < $today) {
608 $calendar[$Ymd]['disabled'] = true;
609 $calendar[$Ymd]['class'][] = 'disabled';
611 //Set next month days
612 if ($date->format('m') > date('m')) {
613 $calendar[$Ymd]['next'] = true;
614 #$calendar[$Ymd]['class'][] = 'next';
618 if ($date->format('w') == 0) {
619 $calendar[$Ymd]['class'][] = 'sunday';
622 //Iterate on each session to find the one of the day
623 foreach($res as $session) {
624 if (($sessionYmd = $session['date']->format('Ymd')) == $Ymd) {
625 //Count number of application
626 $count = count(explode("\n", $session['sau_id']));
630 if (!empty($session['a_id'])) {
631 $applications = [ $session['au_id'] => $session['au_pseudonym'] ];
632 if (!empty($session['a_canceled'])) {
633 $class[] = 'canceled';
635 $class[] = 'granted';
637 } elseif ($count > 1) {
638 $class[] = 'disputed';
639 } elseif (!empty($session['locked'])) {
642 $class[] = 'pending';
645 if ($sessionId == $session['id']) {
646 $class[] = 'highlight';
650 //XXX: realfeel may be null, temperature should not
651 $temperature = $session['realfeel'] !== null ? $session['realfeel'] : $session['temperature'];
654 //XXX: rainfall may be null
655 if ($session['rainrisk'] > 0.50 || $session['rainfall'] > 2) {
656 $weather = self
::GLYPHS
['Stormy'];
657 } elseif ($session['rainrisk'] > 0.40 || $session['rainfall'] > 1) {
658 $weather = self
::GLYPHS
['Rainy'];
659 } elseif ($temperature > 24) {
660 $weather = self
::GLYPHS
['Cleary'];
661 } elseif ($temperature > 17) {
662 $weather = self
::GLYPHS
['Sunny'];
663 } elseif ($temperature > 10) {
664 $weather = self
::GLYPHS
['Cloudy'];
665 } elseif ($temperature !== null) {
666 $weather = self
::GLYPHS
['Winty'];
674 //Check if realfeel is available
675 if ($session['realfeel'] !== null) {
676 $weathertitle[] = $session['realfeel'].'Β°R';
679 //Check if temperature is available
680 if ($session['temperature'] !== null) {
681 $weathertitle[] = $session['temperature'].'Β°C';
684 //Check if rainrisk is available
685 if ($session['rainrisk'] !== null) {
686 $weathertitle[] = ($session['rainrisk']*100).'%';
689 //Check if rainfall is available
690 if ($session['rainfall'] !== null) {
691 $weathertitle[] = $session['rainfall'].'mm';
696 0 => $translator->trans($session['t_title']).' '.$translator->trans('at '.$session['l_title']).$translator->trans(':')
699 //Fetch pseudonyms from session applications
700 $applications +
= array_combine(explode("\n", $session['sau_id']), array_map(function ($v) {return '- '.$v
;}, explode("\n", $session['sau_pseudonym'])));
705 //Check that session is not granted
706 if (empty($session['a_id'])) {
707 //With location id and unique application
709 //Set unique application pseudonym
710 $pseudonym = $session['sau_pseudonym'];
714 //Replace granted application
715 $applications[$session['au_id']] = '* '.$session['au_pseudonym'];
718 $pseudonym = $session['au_pseudonym'].($count > 1 ? ' ['.$count.']':'');
722 $calendar[$Ymd]['sessions'][$session['t_id'].sprintf('%05d', $session['id'])] = [
723 'id' => $session['id'],
724 'start' => $session['start'],
725 'stop' => $session['stop'],
726 'location' => $translator->trans($session['l_title']),
727 'pseudonym' => $pseudonym,
729 'slot' => self
::GLYPHS
[$session['t_title']],
730 'slottitle' => $translator->trans($session['t_title']),
731 'weather' => $weather,
732 'weathertitle' => implode(' ', $weathertitle),
733 'applications' => $applications,
734 'rate' => $session['p_rate'],
735 'hat' => $session['p_hat']
741 ksort($calendar[$Ymd]['sessions']);
749 * Fetch sessions calendar with translated location by date period and user
751 * @param $translator The TranslatorInterface instance
752 * @param $period The date period
753 * @param $userId The user id
754 * @param $sessionId The session id
756 public function fetchUserCalendarByDatePeriod(TranslatorInterface
$translator, $period, $userId = null, $sessionId = null, $locale = null) {
758 $em = $this->getEntityManager();
761 $qs = $em->getConfiguration()->getQuoteStrategy();
762 $dp = $em->getConnection()->getDatabasePlatform();
764 //Get quoted table names
765 //XXX: this allow to make this code table name independent
767 'RapsysAirBundle:GroupUser' => $qs->getJoinTableName($em->getClassMetadata('RapsysAirBundle:User')->getAssociationMapping('groups'), $em->getClassMetadata('RapsysAirBundle:User'), $dp),
768 'RapsysAirBundle:Session' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Session'), $dp),
769 'RapsysAirBundle:Application' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Application'), $dp),
770 'RapsysAirBundle:Group' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Group'), $dp),
771 'RapsysAirBundle:Location' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Location'), $dp),
772 'RapsysAirBundle:Slot' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Slot'), $dp),
773 'RapsysAirBundle:Snippet' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Snippet'), $dp),
774 'RapsysAirBundle:User' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:User'), $dp),
781 $userJoinSql = $userWhereSql = '';
783 //When user id is set
784 if (!empty($userId)) {
786 $userJoinSql = 'JOIN RapsysAirBundle:Application AS sua ON (sua.session_id = s.id)'."\n";
788 $userWhereSql = "\n\t".'AND sua.user_id = :uid';
792 //TODO: change as_u_* in sau_*, a_u_* in au_*, etc, see request up
802 ADDDATE(ADDTIME(s.date, s.begin), INTERVAL IF(s.slot_id = :afterid, 1, 0) DAY) AS start,
803 ADDDATE(ADDTIME(ADDTIME(s.date, s.begin), s.length), INTERVAL IF(s.slot_id = :afterid, 1, 0) DAY) AS stop,
804 s.location_id AS l_id,
808 s.application_id AS a_id,
810 au.pseudonym AS au_pseudonym,
813 GROUP_CONCAT(sa.user_id ORDER BY sa.user_id SEPARATOR "\\n") AS sau_id,
814 GROUP_CONCAT(CONCAT("- ", sau.pseudonym) ORDER BY sa.user_id SEPARATOR "\\n") AS sau_pseudonym
815 FROM RapsysAirBundle:Session AS s
816 JOIN RapsysAirBundle:Location AS l ON (l.id = s.location_id)
817 JOIN RapsysAirBundle:Slot AS t ON (t.id = s.slot_id)
818 ${userJoinSql}LEFT JOIN RapsysAirBundle:Application AS a ON (a.id = s.application_id)
819 LEFT JOIN RapsysAirBundle:Snippet AS p ON (p.location_id = s.location_id AND p.user_id = a.user_id AND p.locale = :locale)
820 LEFT JOIN RapsysAirBundle:User AS au ON (au.id = a.user_id)
821 LEFT JOIN RapsysAirBundle:Application AS sa ON (sa.session_id = s.id)
822 LEFT JOIN RapsysAirBundle:User AS sau ON (sau.id = sa.user_id)
823 WHERE s.date BETWEEN :begin AND :end${userWhereSql}
828 //Replace bundle entity name by table name
829 $req = str_replace(array_keys($tables), array_values($tables), $req);
831 //Get result set mapping instance
832 //XXX: DEBUG: see ../blog.orig/src/Rapsys/BlogBundle/Repository/ArticleRepository.php
833 $rsm = new ResultSetMapping();
836 //XXX: see vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/Types.php
837 //addScalarResult($sqlColName, $resColName, $type = 'string');
838 $rsm->addScalarResult('id', 'id', 'integer')
839 ->addScalarResult('date', 'date', 'date')
840 ->addScalarResult('rainrisk', 'rainrisk', 'float')
841 ->addScalarResult('rainfall', 'rainfall', 'float')
842 ->addScalarResult('realfeel', 'realfeel', 'float')
843 ->addScalarResult('temperature', 'temperature', 'float')
844 ->addScalarResult('locked', 'locked', 'datetime')
845 ->addScalarResult('start', 'start', 'datetime')
846 ->addScalarResult('stop', 'stop', 'datetime')
847 ->addScalarResult('t_id', 't_id', 'integer')
848 ->addScalarResult('t_title', 't_title', 'string')
849 ->addScalarResult('l_id', 'l_id', 'integer')
850 ->addScalarResult('l_title', 'l_title', 'string')
851 ->addScalarResult('a_id', 'a_id', 'integer')
852 ->addScalarResult('au_id', 'au_id', 'integer')
853 ->addScalarResult('au_pseudonym', 'au_pseudonym', 'string')
854 ->addScalarResult('p_rate', 'p_rate', 'integer')
855 ->addScalarResult('p_hat', 'p_hat', 'boolean')
856 //XXX: is a string because of \n separator
857 ->addScalarResult('sau_id', 'sau_id', 'string')
858 //XXX: is a string because of \n separator
859 ->addScalarResult('sau_pseudonym', 'sau_pseudonym', 'string')
860 ->addIndexByScalar('id');
864 ->createNativeQuery($req, $rsm)
865 ->setParameter('begin', $period->getStartDate())
866 ->setParameter('end', $period->getEndDate())
867 ->setParameter('uid', $userId)
868 ->setParameter('locale', $locale)
877 //Iterate on each day
878 foreach($period as $date) {
879 //Init day in calendar
880 $calendar[$Ymd = $date->format('Ymd')] = [
881 'title' => $translator->trans($date->format('l')).' '.$date->format('d'),
886 //Detect month change
887 if ($month != $date->format('m')) {
888 $month = $date->format('m');
889 //Append month for first day of month
890 //XXX: except if today to avoid double add
891 if ($date->format('U') != strtotime('today')) {
892 $calendar[$Ymd]['title'] .= '/'.$month;
896 if ($date->format('U') == ($today = strtotime('today'))) {
897 $calendar[$Ymd]['title'] .= '/'.$month;
898 $calendar[$Ymd]['current'] = true;
899 $calendar[$Ymd]['class'][] = 'current';
901 //Disable passed days
902 if ($date->format('U') < $today) {
903 $calendar[$Ymd]['disabled'] = true;
904 $calendar[$Ymd]['class'][] = 'disabled';
906 //Set next month days
907 if ($date->format('m') > date('m')) {
908 $calendar[$Ymd]['next'] = true;
909 #$calendar[$Ymd]['class'][] = 'next';
913 if ($date->format('w') == 0) {
914 $calendar[$Ymd]['class'][] = 'sunday';
917 //Iterate on each session to find the one of the day
918 foreach($res as $session) {
919 if (($sessionYmd = $session['date']->format('Ymd')) == $Ymd) {
920 //Count number of application
921 $count = count(explode("\n", $session['sau_id']));
925 if (!empty($session['a_id'])) {
926 $applications = [ $session['au_id'] => $session['au_pseudonym'] ];
927 if ($session['au_id'] == $userId) {
928 $class[] = 'granted';
930 $class[] = 'disputed';
932 } elseif ($count > 1) {
933 $class[] = 'disputed';
934 } elseif (!empty($session['locked'])) {
937 $class[] = 'pending';
940 if ($sessionId == $session['id']) {
941 $class[] = 'highlight';
945 //XXX: realfeel may be null, temperature should not
946 $temperature = $session['realfeel'] !== null ? $session['realfeel'] : $session['temperature'];
949 //XXX: rainfall may be null
950 if ($session['rainrisk'] > 0.50 || $session['rainfall'] > 2) {
951 $weather = self
::GLYPHS
['Stormy'];
952 } elseif ($session['rainrisk'] > 0.40 || $session['rainfall'] > 1) {
953 $weather = self
::GLYPHS
['Rainy'];
954 } elseif ($temperature > 24) {
955 $weather = self
::GLYPHS
['Cleary'];
956 } elseif ($temperature > 17) {
957 $weather = self
::GLYPHS
['Sunny'];
958 } elseif ($temperature > 10) {
959 $weather = self
::GLYPHS
['Cloudy'];
960 } elseif ($temperature !== null) {
961 $weather = self
::GLYPHS
['Winty'];
969 //Check if realfeel is available
970 if ($session['realfeel'] !== null) {
971 $weathertitle[] = $session['realfeel'].'Β°R';
974 //Check if temperature is available
975 if ($session['temperature'] !== null) {
976 $weathertitle[] = $session['temperature'].'Β°C';
979 //Check if rainrisk is available
980 if ($session['rainrisk'] !== null) {
981 $weathertitle[] = ($session['rainrisk']*100).'%';
984 //Check if rainfall is available
985 if ($session['rainfall'] !== null) {
986 $weathertitle[] = $session['rainfall'].'mm';
991 0 => $translator->trans($session['t_title']).' '.$translator->trans('at '.$session['l_title']).$translator->trans(':')
994 //Fetch pseudonyms from session applications
995 $applications +
= array_combine(explode("\n", $session['sau_id']), array_map(function ($v) {return '- '.$v
;}, explode("\n", $session['sau_pseudonym'])));
1000 //Check that session is not granted
1001 if (empty($session['a_id'])) {
1002 //With location id and unique application
1004 //Set unique application pseudonym
1005 $pseudonym = $session['sau_pseudonym'];
1007 //Session is granted
1009 //Replace granted application
1010 $applications[$session['au_id']] = '* '.$session['au_pseudonym'];
1013 $pseudonym = $session['au_pseudonym'].($count > 1 ? ' ['.$count.']':'');
1017 $title = $translator->trans($session['l_title']).($count > 1 ? ' ['.$count.']':'');
1020 $calendar[$Ymd]['sessions'][$session['t_id'].sprintf('%02d', $session['l_id'])] = [
1021 'id' => $session['id'],
1022 'start' => $session['start'],
1023 'stop' => $session['stop'],
1024 'location' => $translator->trans($session['l_title']),
1025 'pseudonym' => $pseudonym,
1027 'slot' => self
::GLYPHS
[$session['t_title']],
1028 'slottitle' => $translator->trans($session['t_title']),
1029 'weather' => $weather,
1030 'weathertitle' => implode(' ', $weathertitle),
1031 'applications' => $applications,
1032 'rate' => $session['p_rate'],
1033 'hat' => $session['p_hat']
1039 ksort($calendar[$Ymd]['sessions']);
1047 * Find all session pending hourly weather
1049 * @return array<Session> The sessions to update
1051 public function findAllPendingHourlyWeather() {
1052 //Get entity manager
1053 $em = $this->getEntityManager();
1055 //Get quote strategy
1056 $qs = $em->getConfiguration()->getQuoteStrategy();
1057 $dp = $em->getConnection()->getDatabasePlatform();
1059 //Get quoted table names
1060 //XXX: this allow to make this code table name independent
1062 'RapsysAirBundle:Session' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Session'), $dp),
1063 'RapsysAirBundle:Location' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Location'), $dp),
1065 ':accuhourly' => self
::ACCUWEATHER_HOURLY
,
1072 //Select all sessions starting and stopping in the next 3 days
1073 //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)
1075 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
1076 FROM RapsysAirBundle:Session AS s
1077 JOIN RapsysAirBundle:Location AS l ON (l.id = s.location_id)
1078 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))
1081 //Replace bundle entity name by table name
1082 $req = str_replace(array_keys($tables), array_values($tables), $req);
1084 //Get result set mapping instance
1085 $rsm = new ResultSetMapping();
1087 //Declare all fields
1089 ->addEntityResult('RapsysAirBundle:Session', 's')
1090 ->addFieldResult('s', 'id', 'id')
1091 ->addFieldResult('s', 'date', 'date')
1092 ->addFieldResult('s', 'begin', 'begin')
1093 ->addFieldResult('s', 'length', 'length')
1094 ->addFieldResult('s', 'rainfall', 'rainfall')
1095 ->addFieldResult('s', 'rainrisk', 'rainrisk')
1096 ->addFieldResult('s', 'realfeel', 'realfeel')
1097 ->addFieldResult('s', 'realfeelmin', 'realfeelmin')
1098 ->addFieldResult('s', 'realfeelmax', 'realfeelmax')
1099 ->addFieldResult('s', 'temperature', 'temperature')
1100 ->addFieldResult('s', 'temperaturemin', 'temperaturemin')
1101 ->addFieldResult('s', 'temperaturemax', 'temperaturemax')
1102 ->addJoinedEntityResult('RapsysAirBundle:Slot', 'o', 's', 'slot')
1103 ->addFieldResult('o', 'slot_id', 'id')
1104 ->addJoinedEntityResult('RapsysAirBundle:Location', 'l', 's', 'location')
1105 ->addFieldResult('l', 'location_id', 'id')
1106 ->addFieldResult('l', 'zipcode', 'zipcode')
1107 ->addIndexBy('s', 'id');
1111 ->createNativeQuery($req, $rsm)
1116 * Find all session pending daily weather
1118 * @return array<Session> The sessions to update
1120 public function findAllPendingDailyWeather() {
1121 //Get entity manager
1122 $em = $this->getEntityManager();
1124 //Get quote strategy
1125 $qs = $em->getConfiguration()->getQuoteStrategy();
1126 $dp = $em->getConnection()->getDatabasePlatform();
1128 //Get quoted table names
1129 //XXX: this allow to make this code table name independent
1131 'RapsysAirBundle:Session' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Session'), $dp),
1132 'RapsysAirBundle:Location' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Location'), $dp),
1134 ':accudaily' => self
::ACCUWEATHER_DAILY
,
1135 ':accuhourly' => self
::ACCUWEATHER_HOURLY
,
1142 //Select all sessions stopping after next 3 days
1143 //XXX: select session stopping after or equal date(now)+3d as accuweather only provide hourly data for the next 3 days (INTERVAL 3 DAY)
1145 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
1146 FROM RapsysAirBundle:Session AS s
1147 JOIN RapsysAirBundle:Location AS l ON (l.id = s.location_id)
1148 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))
1151 //Replace bundle entity name by table name
1152 $req = str_replace(array_keys($tables), array_values($tables), $req);
1154 //Get result set mapping instance
1155 $rsm = new ResultSetMapping();
1157 //Declare all fields
1159 ->addEntityResult('RapsysAirBundle:Session', 's')
1160 ->addFieldResult('s', 'id', 'id')
1161 ->addFieldResult('s', 'date', 'date')
1162 ->addFieldResult('s', 'begin', 'begin')
1163 ->addFieldResult('s', 'length', 'length')
1164 ->addFieldResult('s', 'rainfall', 'rainfall')
1165 ->addFieldResult('s', 'rainrisk', 'rainrisk')
1166 ->addFieldResult('s', 'realfeel', 'realfeel')
1167 ->addFieldResult('s', 'realfeelmin', 'realfeelmin')
1168 ->addFieldResult('s', 'realfeelmax', 'realfeelmax')
1169 ->addFieldResult('s', 'temperature', 'temperature')
1170 ->addFieldResult('s', 'temperaturemin', 'temperaturemin')
1171 ->addFieldResult('s', 'temperaturemax', 'temperaturemax')
1172 ->addJoinedEntityResult('RapsysAirBundle:Slot', 'o', 's', 'slot')
1173 ->addFieldResult('o', 'slot_id', 'id')
1174 ->addJoinedEntityResult('RapsysAirBundle:Location', 'l', 's', 'location')
1175 ->addFieldResult('l', 'location_id', 'id')
1176 ->addFieldResult('l', 'zipcode', 'zipcode')
1177 ->addIndexBy('s', 'id');
1181 ->createNativeQuery($req, $rsm)
1186 * Find every session pending application
1188 * @return array<Session> The sessions to update
1190 public function findAllPendingApplication() {
1191 //Get entity manager
1192 $em = $this->getEntityManager();
1194 //Get quote strategy
1195 $qs = $em->getConfiguration()->getQuoteStrategy();
1196 $dp = $em->getConnection()->getDatabasePlatform();
1198 //Get quoted table names
1199 //XXX: this allow to make this code table name independent
1201 'RapsysAirBundle:Application' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Application'), $dp),
1202 'RapsysAirBundle:Session' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Session'), $dp),
1204 ':regulardelay' => self
::REGULAR_DELAY
* 24 * 3600,
1205 ':seniordelay' => self
::SENIOR_DELAY
* 24 * 3600,
1212 //Select all sessions not locked without application or canceled application within attribution period
1213 //XXX: DIFF(start, now) <= IF(DIFF(start, created) <= SENIOR_DELAY in DAY, DIFF(start, created) * 3 / 4, SENIOR_DELAY)
1214 //TODO: remonter les donnΓ©es pour le mail ?
1217 FROM RapsysAirBundle:Session as s
1218 LEFT JOIN RapsysAirBundle:Application AS a ON (a.id = s.application_id AND a.canceled IS NULL)
1219 JOIN RapsysAirBundle:Application AS a2 ON (a2.session_id = s.id AND a2.canceled IS NULL)
1220 WHERE s.locked IS NULL AND a.id IS NULL AND
1221 TIME_TO_SEC(TIMEDIFF(@dt_start := ADDDATE(ADDTIME(s.date, s.begin), INTERVAL IF(s.slot_id = :afterid, 1, 0) DAY), NOW())) <= IF(
1222 TIME_TO_SEC(@td_sc := TIMEDIFF(@dt_start, s.created)) <= :seniordelay,
1223 ROUND(TIME_TO_SEC(@td_sc) * :regulardelay / :seniordelay),
1227 ORDER BY @dt_start ASC, s.created ASC
1231 //Replace bundle entity name by table name
1232 $req = str_replace(array_keys($tables), array_values($tables), $req);
1234 //Get result set mapping instance
1235 $rsm = new ResultSetMapping();
1237 //Declare all fields
1239 ->addEntityResult('RapsysAirBundle:Session', 's')
1240 ->addFieldResult('s', 'id', 'id')
1241 ->addIndexBy('s', 'id');
1245 ->createNativeQuery($req, $rsm)
1250 * Fetch session best application by session id
1252 * @param int $id The session id
1253 * @return Application|null The application or null
1255 public function findBestApplicationById($id) {
1256 //Get entity manager
1257 $em = $this->getEntityManager();
1259 //Get quote strategy
1260 $qs = $em->getConfiguration()->getQuoteStrategy();
1261 $dp = $em->getConnection()->getDatabasePlatform();
1263 //Get quoted table names
1264 //XXX: this allow to make this code table name independent
1266 'RapsysAirBundle:Application' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Application'), $dp),
1267 'RapsysAirBundle:GroupUser' => $qs->getJoinTableName($em->getClassMetadata('RapsysAirBundle:User')->getAssociationMapping('groups'), $em->getClassMetadata('RapsysAirBundle:User'), $dp),
1268 'RapsysAirBundle:Location' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Location'), $dp),
1269 'RapsysAirBundle:Session' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Session'), $dp),
1270 //XXX: Set limit used to workaround mariadb subselect optimization
1271 ':limit' => PHP_INT_MAX
,
1273 ':guestdelay' => self
::GUEST_DELAY
* 24 * 3600,
1274 ':regulardelay' => self
::REGULAR_DELAY
* 24 * 3600,
1275 ':seniordelay' => self
::SENIOR_DELAY
* 24 * 3600,
1281 ':afternoonid' => 2,
1284 //XXX: days since last session after which guest regain normal priority
1286 //XXX: session count until considered at regular delay
1288 //XXX: pn_ratio over which considered at regular delay
1290 //XXX: tr_ratio diff over which considered at regular delay
1297 * Query session applications ranked by location score, global score, created and user_id
1299 * @xxx guest (or less) with application on location within 30 day are only considered within guestdelay
1301 * @xxx regular (or less) premium application on hotspot are only considered within regulardelay
1303 * @xxx senior (or less) with 5 or less session on location are only considered within seniordelay
1305 * @xxx senior (or less) with l_pn_ratio >= 1 are only considered within seniordelay
1307 * @xxx senior (or less) with l_tr_ratio >= (o_tr_ratio + 5) are only considered within seniordelay
1309 * @xxx only consider session within one year (may be unaccurate by the day with after session)
1311 * @xxx rainfall may not be accessible for previous session and other session at d-4 (only at d-2)
1313 * @todo ??? feedback the data to inform the rejected users ???
1316 SELECT e.id, e.l_score AS score
1328 MAX(gu.group_id) AS group_id,
1343 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,
1360 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,
1373 COUNT(a2.id) AS l_count,
1374 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,
1375 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,
1376 (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,
1377 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,
1378 TIME_TO_SEC(TIMEDIFF(ADDDATE(ADDTIME(s.date, s.begin), INTERVAL IF(s.slot_id = :afterid, 1, 0) DAY), NOW())) AS remaining,
1382 FROM RapsysAirBundle:Session AS s
1383 JOIN RapsysAirBundle:Location AS l ON (l.id = s.location_id)
1384 JOIN RapsysAirBundle:Application AS a ON (a.session_id = s.id AND a.canceled IS NULL)
1385 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)
1386 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))
1392 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)
1393 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))
1398 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)
1399 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))
1404 LEFT JOIN RapsysAirBundle:GroupUser AS gu ON (gu.user_id = d.user_id)
1409 IF(e.group_id <= :guestid AND e.l_previous <= :guestwait, e.remaining <= :guestdelay, 1) AND
1410 IF(e.group_id <= :regularid AND e.premium = 1 AND e.hotspot = 1, e.remaining <= :regulardelay, 1) AND
1411 IF(e.group_id <= :seniorid AND e.l_count <= :scount, e.remaining <= :regulardelay, 1) AND
1412 IF(e.group_id <= :seniorid AND e.l_pn_ratio >= :pnratio, e.remaining <= :regulardelay, 1) AND
1413 IF(e.group_id <= :seniorid AND e.l_tr_ratio >= (e.o_tr_ratio + :trdiff), e.remaining <= :regulardelay, 1)
1414 ORDER BY e.l_score ASC, e.g_score ASC, e.created ASC, e.user_id ASC
1417 //Replace bundle entity name by table name
1418 $req = str_replace(array_keys($tables), array_values($tables), $req);
1420 //Set update request
1421 $upreq = 'UPDATE RapsysAirBundle:Application SET score = :score, updated = NOW() WHERE id = :id';
1423 //Replace bundle entity name by table name
1424 $upreq = str_replace(array_keys($tables), array_values($tables), $upreq);
1426 //Get result set mapping instance
1427 $rsm = new ResultSetMapping();
1429 //Declare all fields
1431 ->addEntityResult('RapsysAirBundle:Application', 'a')
1432 ->addFieldResult('a', 'id', 'id')
1433 ->addFieldResult('a', 'score', 'score')
1434 ->addIndexBy('a', 'id');
1437 //XXX: setting limit in subqueries is required to prevent mariadb optimisation
1439 ->createNativeQuery($req, $rsm)
1440 ->setParameter('sid', $id)
1441 //XXX: removed, we update score before returning best candidate
1442 //->getOneOrNullResult(Query::HYDRATE_SINGLE_SCALAR);
1449 foreach($applications as $application) {
1450 //Check if we already saved best candidate
1451 if ($ret === null) {
1452 //Return first application
1453 $ret = $application;
1456 //Update application updated field
1457 //XXX: updated field is not modified for user with bad behaviour as application is not retrieved until delay is reached
1458 $em->getConnection()->executeUpdate($upreq, ['id' => $application->getId(), 'score' => $application->getScore()], ['id' => Type
::INTEGER, 'score' => Type
::FLOAT]);
1461 //Return best ranked application
1467 * Rekey sessions and applications by chronological session id
1469 * @return bool The rekey success or failure
1471 function rekey(): bool {
1472 //Get entity manager
1473 $em = $this->getEntityManager();
1476 $cnx = $em->getConnection();
1478 //Get quote strategy
1479 $qs = $em->getConfiguration()->getQuoteStrategy();
1480 $dp = $em->getConnection()->getDatabasePlatform();
1482 //Get quoted table names
1483 //XXX: this allow to make this code table name independent
1485 'RapsysAirBundle:Application' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Application'), $dp),
1486 'RapsysAirBundle:Session' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Session'), $dp),
1503 GROUP_CONCAT(sa.id ORDER BY sa.id SEPARATOR "\\n") AS sa_id
1504 FROM RapsysAirBundle:Session AS s
1505 LEFT JOIN RapsysAirBundle:Application AS sa ON (sa.session_id = s.id)
1509 ORDER BY ADDDATE(ADDTIME(a.date, a.begin), INTERVAL IF(a.slot_id = :afterid, 1, 0) DAY) ASC
1512 //Replace bundle entity name by table name
1513 $req = str_replace(array_keys($tables), array_values($tables), $req);
1515 //Get result set mapping instance
1516 //XXX: DEBUG: see ../blog.orig/src/Rapsys/BlogBundle/Repository/ArticleRepository.php
1517 $rsm = new ResultSetMapping();
1519 //Declare all fields
1520 //XXX: see vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/Types.php
1521 //addScalarResult($sqlColName, $resColName, $type = 'string');
1522 $rsm->addScalarResult('id', 'id', 'integer')
1523 ->addScalarResult('sa_id', 'sa_id', 'string');
1524 #->addIndexByScalar('id');
1527 $rnq = $em->createNativeQuery($req, $rsm);
1530 $res = $rnq->getResult();
1533 $cnx->beginTransaction();
1535 //Set update session request
1537 UPDATE RapsysAirBundle:Session
1538 SET id = :nid, updated = NOW()
1542 //Replace bundle entity name by table name
1543 $sreq = str_replace(array_keys($tables), array_values($tables), $sreq);
1545 //Set update application request
1547 UPDATE RapsysAirBundle:Application
1548 SET session_id = :nid, updated = NOW()
1549 WHERE session_id = :id
1552 //Replace bundle entity name by table name
1553 $areq = str_replace(array_keys($tables), array_values($tables), $areq);
1556 $max = max(array_keys($res));
1559 //Prepare session to update
1560 foreach($res as $id => $data) {
1562 $res[$id]['t_id'] = $max +
$id +
1;
1565 $res[$id]['n_id'] = $id +
1;
1567 //Explode application ids
1568 $res[$id]['sa_id'] = explode("\n", $data['sa_id']);
1571 if ($res[$id]['n_id'] == $res[$id]['id']) {
1572 //Remove unchanged session
1579 //Disable foreign key checks
1580 $cnx->prepare('SET foreign_key_checks = 0')->execute();
1583 foreach($res as $id => $data) {
1584 //Run session update
1585 $cnx->executeUpdate($sreq, ['nid' => $res[$id]['t_id'], 'id' => $res[$id]['id']]);
1587 //Run applications update
1588 $cnx->executeUpdate($areq, ['nid' => $res[$id]['t_id'], 'id' => $res[$id]['id']]);
1592 foreach($res as $id => $data) {
1593 //Run session update
1594 $cnx->executeUpdate($sreq, ['nid' => $res[$id]['n_id'], 'id' => $res[$id]['t_id']]);
1596 //Run applications update
1597 $cnx->executeUpdate($areq, ['nid' => $res[$id]['n_id'], 'id' => $res[$id]['t_id']]);
1600 //Restore foreign key checks
1601 $cnx->prepare('SET foreign_key_checks = 1')->execute();
1603 //Commit transaction
1606 //Set update auto_increment request
1608 ALTER TABLE RapsysAirBundle:Session
1612 //Replace bundle entity name by table name
1613 $ireq = str_replace(array_keys($tables), array_values($tables), $ireq);
1615 //Reset auto_increment
1619 //Rollback transaction
1622 } catch(\Exception
$e) {
1623 //Rollback transaction