1 <?php
declare(strict_types
=1);
4 * This file is part of the Rapsys AirBundle package.
6 * (c) RaphaΓ«l Gertz <symfony@rapsys.eu>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Rapsys\AirBundle\Repository
;
14 use Doctrine\DBAL\Types\Types
;
15 use Doctrine\ORM\Query\ResultSetMapping
;
16 use Symfony\Component\Routing\Generator\UrlGeneratorInterface
;
18 use Rapsys\AirBundle\Entity\Application
;
19 use Rapsys\AirBundle\Entity\Location
;
20 use Rapsys\AirBundle\Entity\Session
;
21 use Rapsys\AirBundle\Entity\Slot
;
26 class SessionRepository
extends Repository
{
28 //TODO: document utf-8 codes ?
29 //TODO: use unknown == ? symbol by default ???
30 //π<= dancer #0001f483
31 //π<= tanguera #0001f483
34 'Morning' => 'π
', #0001f305
35 'Afternoon' => 'βοΈ', #2600
36 'Evening' => 'π', #0001f307
37 'After' => 'β¨', #2728
39 'Cleary' => 'β', #2600
40 'Sunny' => 'β
', #26c5
41 'Cloudy' => 'β', #2601
42 'Winty' => 'βοΈ', #2744
43 'Rainy' => 'π', #0001f302
44 'Stormy' => 'β', #2614
46 'Euro' => 'β¬', #20ac
47 'Free' => 'πΊ', #0001f37a
48 'Hat' => 'π©' #0001f3a9
52 * Find session as array by id
54 * @param int $id The session id
55 * @return array The session data
57 public function findOneByIdAsArray(int $id): ?array {
64 ADDDATE(ADDTIME(s.date, s.begin), INTERVAL IF(s.slot_id = :afterid, 1, 0) DAY) AS start,
66 ADDDATE(ADDTIME(ADDTIME(s.date, s.begin), s.length), INTERVAL IF(s.slot_id = :afterid, 1, 0) DAY) AS stop,
78 s.location_id AS l_id,
80 l.description AS l_description,
81 l.address AS l_address,
82 l.zipcode AS l_zipcode,
84 l.latitude AS l_latitude,
85 l.longitude AS l_longitude,
87 l.updated AS l_updated,
90 s.application_id AS a_id,
91 a.canceled AS a_canceled,
96 au.pseudonym AS au_pseudonym,
98 p.description AS p_description,
100 p.contact AS p_contact,
101 p.donate AS p_donate,
103 p.profile AS p_profile,
106 GREATEST(COALESCE(s.updated, 0), COALESCE(l.updated, 0), COALESCE(t.updated, 0), COALESCE(p.updated, 0), COALESCE(MAX(sa.updated), 0), COALESCE(MAX(sau.updated), 0), COALESCE(MAX(sad.updated), 0)) AS modified,
107 GROUP_CONCAT(sa.id ORDER BY sa.user_id SEPARATOR "\\n") AS sa_id,
108 GROUP_CONCAT(IFNULL(sa.score, 'NULL') ORDER BY sa.user_id SEPARATOR "\\n") AS sa_score,
109 GROUP_CONCAT(sa.created ORDER BY sa.user_id SEPARATOR "\\n") AS sa_created,
110 GROUP_CONCAT(sa.updated ORDER BY sa.user_id SEPARATOR "\\n") AS sa_updated,
111 GROUP_CONCAT(IFNULL(sa.canceled, 'NULL') ORDER BY sa.user_id SEPARATOR "\\n") AS sa_canceled,
112 GROUP_CONCAT(sa.user_id ORDER BY sa.user_id SEPARATOR "\\n") AS sau_id,
113 GROUP_CONCAT(sau.pseudonym ORDER BY sa.user_id SEPARATOR "\\n") AS sau_pseudonym
114 FROM RapsysAirBundle:Session AS s
115 JOIN RapsysAirBundle:Location AS l ON (l.id = s.location_id)
116 JOIN RapsysAirBundle:Slot AS t ON (t.id = s.slot_id)
117 LEFT JOIN RapsysAirBundle:Application AS a ON (a.id = s.application_id)
118 LEFT JOIN RapsysAirBundle:Dance AS ad ON (ad.id = a.dance_id)
119 LEFT JOIN RapsysAirBundle:User AS au ON (au.id = a.user_id)
120 LEFT JOIN RapsysAirBundle:Snippet AS p ON (p.location_id = s.location_id AND p.user_id = a.user_id AND p.locale = :locale)
121 LEFT JOIN RapsysAirBundle:Application AS sa ON (sa.session_id = s.id)
122 LEFT JOIN RapsysAirBundle:User AS sau ON (sau.id = sa.user_id)
123 LEFT JOIN RapsysAirBundle:Dance AS sad ON (sad.id = sa.dance_id)
129 //Replace bundle entity name by table name
130 $req = str_replace($this->tableKeys
, $this->tableValues
, $req);
132 //Get result set mapping instance
133 //XXX: DEBUG: see ../blog.orig/src/Rapsys/BlogBundle/Repository/ArticleRepository.php
134 $rsm = new ResultSetMapping();
137 //XXX: see vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/Types.php
138 $rsm->addScalarResult('id', 'id', 'integer')
139 ->addScalarResult('date', 'date', 'date')
140 ->addScalarResult('begin', 'begin', 'time')
141 ->addScalarResult('start', 'start', 'datetime')
142 ->addScalarResult('length', 'length', 'time')
143 ->addScalarResult('stop', 'stop', 'datetime')
144 ->addScalarResult('rainfall', 'rainfall', 'float')
145 ->addScalarResult('rainrisk', 'rainrisk', 'float')
146 ->addScalarResult('realfeel', 'realfeel', 'float')
147 ->addScalarResult('realfeelmin', 'realfeelmin', 'float')
148 ->addScalarResult('realfeelmax', 'realfeelmax', 'float')
149 ->addScalarResult('temperature', 'temperature', 'float')
150 ->addScalarResult('temperaturemin', 'temperaturemin', 'float')
151 ->addScalarResult('temperaturemax', 'temperaturemax', 'float')
152 ->addScalarResult('locked', 'locked', 'datetime')
153 ->addScalarResult('created', 'created', 'datetime')
154 ->addScalarResult('updated', 'updated', 'datetime')
155 ->addScalarResult('l_id', 'l_id', 'integer')
156 ->addScalarResult('l_title', 'l_title', 'string')
157 ->addScalarResult('l_description', 'l_description', 'string')
158 ->addScalarResult('l_address', 'l_address', 'string')
159 ->addScalarResult('l_zipcode', 'l_zipcode', 'string')
160 ->addScalarResult('l_city', 'l_city', 'string')
161 ->addScalarResult('l_latitude', 'l_latitude', 'float')
162 ->addScalarResult('l_longitude', 'l_longitude', 'float')
163 ->addScalarResult('l_indoor', 'l_indoor', 'boolean')
164 ->addScalarResult('l_updated', 'l_updated', 'datetime')
165 ->addScalarResult('t_id', 't_id', 'integer')
166 ->addScalarResult('t_title', 't_title', 'string')
167 ->addScalarResult('a_id', 'a_id', 'integer')
168 ->addScalarResult('a_canceled', 'a_canceled', 'datetime')
169 ->addScalarResult('ad_id', 'ad_id', 'integer')
170 ->addScalarResult('ad_name', 'ad_name', 'string')
171 ->addScalarResult('ad_type', 'ad_type', 'string')
172 ->addScalarResult('au_id', 'au_id', 'integer')
173 ->addScalarResult('au_pseudonym', 'au_pseudonym', 'string')
174 ->addScalarResult('p_id', 'p_id', 'integer')
175 ->addScalarResult('p_description', 'p_description', 'text')
176 ->addScalarResult('p_class', 'p_class', 'text')
177 ->addScalarResult('p_contact', 'p_contact', 'text')
178 ->addScalarResult('p_donate', 'p_donate', 'text')
179 ->addScalarResult('p_link', 'p_link', 'text')
180 ->addScalarResult('p_profile', 'p_profile', 'text')
181 ->addScalarResult('p_rate', 'p_rate', 'integer')
182 ->addScalarResult('p_hat', 'p_hat', 'boolean')
183 ->addScalarResult('modified', 'modified', 'datetime')
184 //XXX: is a string because of \n separator
185 ->addScalarResult('sa_id', 'sa_id', 'string')
186 //XXX: is a string because of \n separator
187 ->addScalarResult('sa_score', 'sa_score', 'string')
188 //XXX: is a string because of \n separator
189 ->addScalarResult('sa_created', 'sa_created', 'string')
190 //XXX: is a string because of \n separator
191 ->addScalarResult('sa_updated', 'sa_updated', 'string')
192 //XXX: is a string because of \n separator
193 ->addScalarResult('sa_canceled', 'sa_canceled', 'string')
194 //XXX: is a string because of \n separator
195 ->addScalarResult('sau_id', 'sau_id', 'string')
196 //XXX: is a string because of \n separator
197 ->addScalarResult('sau_pseudonym', 'sau_pseudonym', 'string')
198 ->addIndexByScalar('id');
202 ->createNativeQuery($req, $rsm)
203 ->setParameter('id', $id)
204 ->getOneOrNullResult();
207 if ($result === null) {
213 $route = 'rapsys_air_session_view';
216 $routeParams = ['id' => $id, 'location' => $this->slugger
->slug($this->translator
->trans($result['l_title']))];
221 'date' => $result['date'],
222 'begin' => $result['begin'],
223 'start' => $result['start'],
224 'length' => $result['length'],
225 'stop' => $result['stop'],
226 'rainfall' => $result['rainfall'] !== null ? $result['rainfall'].' mm' : $result['rainfall'],
227 'rainrisk' => $result['rainrisk'] !== null ? ($result['rainrisk']*100).' %' : $result['rainrisk'],
228 'realfeel' => $result['realfeel'] !== null ? $result['realfeel'].' Β°C' : $result['realfeel'],
229 'realfeelmin' => $result['realfeelmin'] !== null ? $result['realfeelmin'].' Β°C' : $result['realfeelmin'],
230 'realfeelmax' => $result['realfeelmax'] !== null ? $result['realfeelmax'].' Β°C' : $result['realfeelmax'],
231 'temperature' => $result['temperature'] !== null ? $result['temperature'].' Β°C' : $result['temperature'],
232 'temperaturemin' => $result['temperaturemin'] !== null ? $result['temperaturemin'].' Β°C' : $result['temperaturemin'],
233 'temperaturemax' => $result['temperaturemax'] !== null ? $result['temperaturemax'].' Β°C' : $result['temperaturemax'],
234 'locked' => $result['locked'],
235 'created' => $result['created'],
236 'updated' => $result['updated'],
237 'title' => $this->translator
->trans('Session %id%', ['%id%' => $id]),
238 'modified' => $result['modified'],
239 'application' => null,
241 'id' => $result['l_id'],
242 'at' => $this->translator
->trans('at '.$result['l_title']),
243 'title' => $locationTitle = $this->translator
->trans($result['l_title']),
244 'description' => $this->translator
->trans($result['l_description']??'None'),
245 'address' => $result['l_address'],
246 'zipcode' => $result['l_zipcode'],
247 'city' => $result['l_city'],
248 'in' => $this->translator
->trans('in '.$result['l_city']),
249 'map' => $this->translator
->trans($result['l_title'].' access map'),
250 'multimap' => $this->translator
->trans($result['l_title'].' sector map'),
251 'latitude' => $result['l_latitude'],
252 'longitude' => $result['l_longitude'],
253 'indoor' => $result['l_indoor'],
254 'slug' => $routeParams['location'],
255 'link' => $this->router
->generate('rapsys_air_location_view', ['id' => $result['l_id'], 'location' => $routeParams['location']])
258 'id' => $result['t_id'],
259 'the' => $this->translator
->trans('the '.lcfirst($result['t_title'])),
260 'title' => $this->translator
->trans($result['t_title'])
263 'applications' => null
267 if (!empty($result['a_id'])) {
268 $session['application'] = [
270 'id' => $result['ad_id'],
271 'title' => $this->translator
->trans($result['ad_name'].' '.lcfirst($result['ad_type'])),
272 'name' => $this->translator
->trans($result['ad_name']),
273 'type' => $this->translator
->trans($result['ad_type']),
274 'slug' => $routeParams['dance'] = $this->slugger
->slug($this->translator
->trans($result['ad_name'].' '.lcfirst($result['ad_type']))),
275 'link' => $this->router
->generate('rapsys_air_dance_view', ['id' => $result['ad_id'], 'name' => $this->slugger
->slug($this->translator
->trans($result['ad_name'])), 'type' => $this->slugger
->slug($this->translator
->trans($result['ad_type']))])
278 'id' => $result['au_id'],
279 'by' => $this->translator
->trans('by %pseudonym%', [ '%pseudonym%' => $result['au_pseudonym'] ]),
280 'title' => $result['au_pseudonym'],
281 'slug' => $routeParams['user'] = $this->slugger
->slug($result['au_pseudonym']),
282 'link' => $result['au_id'] == 1 && $routeParams['user'] == 'milonga-raphael' ? $this->router
->generate('rapsys_air_user_milongaraphael') : $this->router
->generate('rapsys_air_user_view', ['id' => $result['au_id'], 'user' => $routeParams['user']]),
283 'contact' => $this->router
->generate('rapsys_air_contact', ['id' => $result['au_id'], 'user' => $routeParams['user']])
285 'id' => $result['a_id'],
286 'canceled' => $result['a_canceled']
291 if (!empty($result['p_id'])) {
292 $session['snippet'] = [
293 'id' => $result['p_id'],
294 'description' => $result['p_description'],
295 'class' => $result['p_class'],
296 'contact' => $result['p_contact'],
297 'donate' => $result['p_donate'],
298 'link' => $result['p_link'],
299 'profile' => $result['p_profile'],
300 'rate' => $result['p_rate'],
301 'hat' => $result['p_hat']
306 if (!empty($result['sa_id'])) {
307 //Extract applications id
308 $result['sa_id'] = explode("\n", $result['sa_id']);
309 //Extract applications score
310 //XXX: score may be null before grant or for bad behaviour, replace NULL with 'NULL' to avoid silent drop in mysql
311 $result['sa_score'] = array_map(function($v){return $v
==='NULL'?null:$v
;}, explode("\n", $result['sa_score']));
312 //Extract applications created
313 $result['sa_created'] = array_map(function($v){return new \
DateTime($v
);}, explode("\n", $result['sa_created']));
314 //Extract applications updated
315 $result['sa_updated'] = array_map(function($v){return new \
DateTime($v
);}, explode("\n", $result['sa_updated']));
316 //Extract applications canceled
317 //XXX: canceled is null before cancelation, replace NULL with 'NULL' to avoid silent drop in mysql
318 $result['sa_canceled'] = array_map(function($v){return $v
==='NULL'?null:new \
DateTime($v
);}, explode("\n", $result['sa_canceled']));
320 //Extract applications user id
321 $result['sau_id'] = explode("\n", $result['sau_id']);
322 //Extract applications user pseudonym
323 $result['sau_pseudonym'] = explode("\n", $result['sau_pseudonym']);
326 $session['applications'] = [];
328 //Iterate on each applications id
329 foreach($result['sa_id'] as $i => $sa_id) {
330 $session['applications'][$sa_id] = [
332 'score' => $result['sa_score'][$i],
333 'created' => $result['sa_created'][$i],
334 'updated' => $result['sa_updated'][$i],
335 'canceled' => $result['sa_canceled'][$i]
337 if (!empty($result['sau_id'][$i])) {
338 $session['applications'][$sa_id]['user'] = [
339 'id' => $result['sau_id'][$i],
340 'title' => $result['sau_pseudonym'][$i],
341 'slug' => $this->slugger
->slug($result['sau_pseudonym'][$i])
348 $session['link'] = $this->router
->generate($route, $routeParams);
351 $session['canonical'] = $this->router
->generate($route, $routeParams, UrlGeneratorInterface
::ABSOLUTE_URL
);
354 $session['alternates'] = [];
356 //Iterate on each locales
357 foreach($this->translator
->getFallbackLocales() as $fallback) {
361 //Set route params location
362 $routeParams['location'] = $this->slugger
->slug($this->translator
->trans($result['l_title'], [], null, $fallback));
364 //With route params dance
365 if (!empty($routeParams['dance'])) {
366 $routeParams['dance'] = $this->slugger
->slug($this->translator
->trans($result['ad_name'].' '.lcfirst($result['ad_type']), [], null, $fallback));
369 //With route params user
370 if (!empty($routeParams['user'])) {
371 $routeParams['user'] = $this->slugger
->slug($result['au_pseudonym']);
374 //With current locale
375 if ($fallback === $this->locale
) {
376 //Set current locale title
377 $titles[$this->locale
] = $this->translator
->trans($this->languages
[$this->locale
]);
378 //Without current locale
380 //Iterate on other locales
381 foreach(array_diff($this->translator
->getFallbackLocales(), [$fallback]) as $other) {
382 //Set other locale title
383 $titles[$other] = $this->translator
->trans($this->languages
[$fallback], [], null, $other);
386 //Add alternates locale
387 $session['alternates'][str_replace('_', '-', $fallback)] = [
388 'absolute' => $this->router
->generate($route, ['_locale' => $fallback]+
$routeParams, UrlGeneratorInterface
::ABSOLUTE_URL
),
389 'relative' => $this->router
->generate($route, ['_locale' => $fallback]+
$routeParams),
390 'title' => implode('/', $titles),
391 'translated' => $this->translator
->trans($this->languages
[$fallback], [], null, $fallback)
395 //Add alternates shorter locale
396 if (empty($parameters['alternates'][$shortFallback = substr($fallback, 0, 2)])) {
397 //Set locale locales context
398 $session['alternates'][$shortFallback] = [
399 'absolute' => $this->router
->generate($route, ['_locale' => $fallback]+
$routeParams, UrlGeneratorInterface
::ABSOLUTE_URL
),
400 'relative' => $this->router
->generate($route, ['_locale' => $fallback]+
$routeParams),
401 'title' => implode('/', $titles),
402 'translated' => $this->translator
->trans($this->languages
[$fallback], [], null, $fallback)
412 * Find sessions as calendar array by date period
414 * @param DatePeriod $period The date period
415 * @param ?bool $granted The session is granted
416 * @param ?float $latitude The latitude
417 * @param ?float $longitude The longitude
418 * @param ?int $userId The user id
419 * @return array The session data
421 public function findAllByPeriodAsCalendarArray(\DatePeriod
$period, ?bool $granted = null, ?float $latitude = null, ?float $longitude = null, ?int $userId = null): array {
425 //When granted is set
426 if (empty($granted)) {
427 //Set application and user as optional
434 //When latitude and longitude
435 if ($latitude !== null && $longitude !== null) {
437 //XXX: get every location between 0 and 15 km of latitude and longitude
440 FROM RapsysAirBundle:Location AS l
441 WHERE ACOS(SIN(RADIANS(:latitude))*SIN(RADIANS(l.latitude))+COS(RADIANS(:latitude))*COS(RADIANS(l.latitude))*COS(RADIANS(:longitude - l.longitude)))*40030.17/2/PI() BETWEEN 0 AND 15
444 //Replace bundle entity name by table name
445 $req = str_replace($this->tableKeys
, $this->tableValues
, $req);
447 //Get result set mapping instance
448 //XXX: DEBUG: see ../blog.orig/src/Rapsys/BlogBundle/Repository/ArticleRepository.php
449 $rsm = new ResultSetMapping();
452 //XXX: see vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/Types.php
453 //addScalarResult($sqlColName, $resColName, $type = 'string');
454 $rsm->addScalarResult('id', 'id', 'integer')
455 ->addIndexByScalar('id');
458 //XXX: check that latitude and longitude have not be swapped !!!
459 //XXX: latitude ~= 48.x longitude ~= 2.x
460 $locationIds = array_keys(
462 ->createNativeQuery($req, $rsm)
463 ->setParameter('latitude', $latitude)
464 ->setParameter('longitude', $longitude)
468 //Add location id clause
469 $locationSql = "\n\t".'AND s.location_id IN (:lids)';
471 } elseif ($userId !== null) {
473 //XXX: get every location between 0 and 15 km
477 SELECT l.id, l.latitude, l.longitude
478 FROM RapsysAirBundle:Application AS a
479 JOIN RapsysAirBundle:Session AS s ON (s.id = a.session_id)
480 JOIN RapsysAirBundle:Location AS l ON (l.id = s.location_id)
481 WHERE a.user_id = :id
486 JOIN RapsysAirBundle:Location AS l2
487 WHERE ACOS(SIN(RADIANS(a.latitude))*SIN(RADIANS(l2.latitude))+COS(RADIANS(a.latitude))*COS(RADIANS(l2.latitude))*COS(RADIANS(a.longitude - l2.longitude)))*40030.17/2/PI() BETWEEN 0 AND 15
492 //Replace bundle entity name by table name
493 $req = str_replace($this->tableKeys
, $this->tableValues
, $req);
495 //Get result set mapping instance
496 //XXX: DEBUG: see ../blog.orig/src/Rapsys/BlogBundle/Repository/ArticleRepository.php
497 $rsm = new ResultSetMapping();
500 //XXX: see vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/Types.php
501 //addScalarResult($sqlColName, $resColName, $type = 'string');
502 $rsm->addScalarResult('id', 'id', 'integer')
503 ->addIndexByScalar('id');
506 $locationIds = array_keys(
508 ->createNativeQuery($req, $rsm)
509 ->setParameter('id', $userId)
514 if (!empty($locationIds)) {
515 //Add location id clause
516 $locationSql = "\n\t".'AND s.location_id IN (:lids)';
531 ADDDATE(ADDTIME(s.date, s.begin), INTERVAL IF(s.slot_id = :afterid, 1, 0) DAY) AS start,
532 ADDDATE(ADDTIME(ADDTIME(s.date, s.begin), s.length), INTERVAL IF(s.slot_id = :afterid, 1, 0) DAY) AS stop,
533 s.location_id AS l_id,
535 l.address AS l_address,
536 l.zipcode AS l_zipcode,
538 l.latitude AS l_latitude,
539 l.longitude AS l_longitude,
540 l.indoor AS l_indoor,
543 s.application_id AS a_id,
544 a.canceled AS a_canceled,
549 au.pseudonym AS au_pseudonym,
553 GROUP_CONCAT(sa.user_id ORDER BY sa.user_id SEPARATOR "\\n") AS sau_id,
554 GROUP_CONCAT(sau.pseudonym ORDER BY sa.user_id SEPARATOR "\\n") AS sau_pseudonym,
555 GROUP_CONCAT(sa.dance_id ORDER BY sa.user_id SEPARATOR "\\n") AS sad_id,
556 GROUP_CONCAT(sad.name ORDER BY sa.user_id SEPARATOR "\\n") AS sad_name,
557 GROUP_CONCAT(sad.type ORDER BY sa.user_id SEPARATOR "\\n") AS sad_type,
558 GREATEST(COALESCE(s.updated, 0), COALESCE(l.updated, 0), COALESCE(p.updated, 0), COALESCE(MAX(sa.updated), 0), COALESCE(MAX(sau.updated), 0), COALESCE(MAX(sad.updated), 0)) AS modified
559 FROM RapsysAirBundle:Session AS s
560 JOIN RapsysAirBundle:Location AS l ON (l.id = s.location_id)
561 JOIN RapsysAirBundle:Slot AS t ON (t.id = s.slot_id)
562 {$grantSql}JOIN RapsysAirBundle:Application AS a ON (a.id = s.application_id)
563 {$grantSql}JOIN RapsysAirBundle:Dance AS ad ON (ad.id = a.dance_id)
564 {$grantSql}JOIN RapsysAirBundle:User AS au ON (au.id = a.user_id)
565 LEFT JOIN RapsysAirBundle:Snippet AS p ON (p.location_id = s.location_id AND p.user_id = a.user_id AND p.locale = :locale)
566 LEFT JOIN RapsysAirBundle:Application AS sa ON (sa.session_id = s.id)
567 LEFT JOIN RapsysAirBundle:Dance AS sad ON (sad.id = sa.dance_id)
568 LEFT JOIN RapsysAirBundle:User AS sau ON (sau.id = sa.user_id)
569 WHERE s.date BETWEEN :begin AND :end{$locationSql}
574 //Replace bundle entity name by table name
575 $req = str_replace($this->tableKeys
, $this->tableValues
, $req);
577 //Get result set mapping instance
578 //XXX: DEBUG: see ../blog.orig/src/Rapsys/BlogBundle/Repository/ArticleRepository.php
579 $rsm = new ResultSetMapping();
582 //XXX: see vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/Types.php
583 //addScalarResult($sqlColName, $resColName, $type = 'string');
584 $rsm->addScalarResult('id', 'id', 'integer')
585 ->addScalarResult('date', 'date', 'date')
586 ->addScalarResult('rainrisk', 'rainrisk', 'float')
587 ->addScalarResult('rainfall', 'rainfall', 'float')
588 ->addScalarResult('realfeel', 'realfeel', 'float')
589 ->addScalarResult('temperature', 'temperature', 'float')
590 ->addScalarResult('locked', 'locked', 'datetime')
591 ->addScalarResult('start', 'start', 'datetime')
592 ->addScalarResult('stop', 'stop', 'datetime')
593 ->addScalarResult('modified', 'modified', 'datetime')
594 ->addScalarResult('t_id', 't_id', 'integer')
595 ->addScalarResult('t_title', 't_title', 'string')
596 ->addScalarResult('l_id', 'l_id', 'integer')
597 ->addScalarResult('l_title', 'l_title', 'string')
598 ->addScalarResult('l_address', 'l_address', 'string')
599 ->addScalarResult('l_zipcode', 'l_zipcode', 'string')
600 ->addScalarResult('l_city', 'l_city', 'string')
601 ->addScalarResult('l_latitude', 'l_latitude', 'float')
602 ->addScalarResult('l_longitude', 'l_longitude', 'float')
603 ->addScalarResult('l_indoor', 'l_indoor', 'boolean')
604 ->addScalarResult('a_id', 'a_id', 'integer')
605 ->addScalarResult('a_canceled', 'a_canceled', 'datetime')
606 ->addScalarResult('ad_id', 'ad_id', 'string')
607 ->addScalarResult('ad_name', 'ad_name', 'string')
608 ->addScalarResult('ad_type', 'ad_type', 'string')
609 ->addScalarResult('au_id', 'au_id', 'integer')
610 ->addScalarResult('au_pseudonym', 'au_pseudonym', 'string')
611 ->addScalarResult('p_hat', 'p_hat', 'boolean')
612 ->addScalarResult('p_rate', 'p_rate', 'integer')
613 ->addScalarResult('p_short', 'p_short', 'string')
614 //XXX: is a string because of \n separator
615 ->addScalarResult('sau_id', 'sau_id', 'string')
616 //XXX: is a string because of \n separator
617 ->addScalarResult('sau_pseudonym', 'sau_pseudonym', 'string')
618 //XXX: is a string because of \n separator
619 ->addScalarResult('sad_id', 'sad_id', 'string')
620 //XXX: is a string because of \n separator
621 ->addScalarResult('sad_name', 'sad_name', 'string')
622 //XXX: is a string because of \n separator
623 ->addScalarResult('sad_type', 'sad_type', 'string')
624 ->addIndexByScalar('id');
628 ->createNativeQuery($req, $rsm)
629 ->setParameter('begin', $period->getStartDate())
630 ->setParameter('end', $period->getEndDate());
632 //Add optional location ids
633 if (!empty($locationIds)) {
634 $res->setParameter('lids', $locationIds);
638 $result = $res->getResult();
647 $route = 'rapsys_air_session_view';
649 //Iterate on each day
650 foreach($period as $date) {
651 //Init day in calendar
652 $calendar[$Ymd = $date->format('Ymd')] = [
653 'title' => $this->translator
->trans($date->format('l')).' '.$date->format('d'),
659 //Detect month change
660 if ($month != $date->format('m')) {
661 $month = $date->format('m');
662 //Append month for first day of month
663 //XXX: except if today to avoid double add
664 if ($date->format('U') != strtotime('today')) {
665 $calendar[$Ymd]['title'] .= '/'.$month;
669 if ($date->format('U') == ($today = strtotime('today'))) {
670 $calendar[$Ymd]['title'] .= '/'.$month;
671 $calendar[$Ymd]['current'] = true;
672 $calendar[$Ymd]['class'][] = 'current';
674 //Disable passed days
675 if ($date->format('U') < $today) {
676 $calendar[$Ymd]['disabled'] = true;
677 $calendar[$Ymd]['class'][] = 'disabled';
679 //Set next month days
680 if ($date->format('m') > date('m')) {
681 $calendar[$Ymd]['next'] = true;
682 #$calendar[$Ymd]['class'][] = 'next';
686 if ($date->format('w') == 0) {
687 $calendar[$Ymd]['class'][] = 'sunday';
690 //Iterate on each session to find the one of the day
691 foreach($result as $session) {
692 if (($sessionYmd = $session['date']->format('Ymd')) == $Ymd) {
693 //With empty or greatest modified
694 if ($calendar[$Ymd]['modified'] === null || $session['modified'] >= $calendar[$Ymd]['modified']) {
696 $calendar[$Ymd]['modified'] = $session['modified'];
700 $applications = array_combine($candidates = explode("\n", $session['sau_id']), explode("\n", $session['sau_pseudonym']));
706 if (!empty($session['locked'])) {
711 if (!empty($session['a_id'])) {
712 //With canceled session
713 if (!empty($session['a_canceled'])) {
714 $class[] = 'canceled';
715 //With disputed session
716 } elseif ($userId !== null && $session['au_id'] != $userId && !empty($candidates[$userId])) {
717 $class[] = 'disputed';
720 $class[] = 'granted';
724 if ($userId !== null && $session['au_id'] == $userId) {
725 $class[] = 'highlight';
728 $class[] = 'pending';
731 //With latitude and longitude
732 if ($latitude !== null && $longitude !== null && $session['l_latitude'] == $latitude && $session['l_longitude'] == $longitude) {
733 $class[] = 'highlight';
739 'glyph' => self
::GLYPHS
['Cleary'],
743 //Compute temperature glyph
744 //XXX: temperature may be null
745 if ($session['temperature'] >= 17 && $session['temperature'] < 24) {
746 $temperature['glyph'] = self
::GLYPHS
['Sunny'];
747 } elseif ($session['temperature'] >= 10 && $session['temperature'] < 17) {
748 $temperature['glyph'] = self
::GLYPHS
['Cloudy'];
749 } elseif ($session['temperature'] !== null && $session['temperature'] < 10) {
750 $temperature['glyph'] = self
::GLYPHS
['Winty'];
753 //Check if temperature is available
754 if ($session['temperature'] !== null) {
755 $temperature['title'][] = $session['temperature'].'Β°C';
758 //Check if realfeel is available
759 if ($session['realfeel'] !== null) {
760 $temperature['title'][] = $session['realfeel'].'Β°R';
763 //Compute temperature title
764 $temperature['title'] = implode(' ', $temperature['title']);
768 'glyph' => self
::GLYPHS
['Cleary'],
773 //XXX: rainfall and rainrisk may be null
774 if ($session['rainrisk'] > 0.50 || $session['rainfall'] > 2) {
775 $rain['glyph'] = self
::GLYPHS
['Stormy'];
776 } elseif ($session['rainrisk'] > 0.40 || $session['rainfall'] > 1) {
777 $rain['glyph'] = self
::GLYPHS
['Rainy'];
780 //Check if rainrisk is available
781 if ($session['rainrisk'] !== null) {
782 $rain['title'][] = ($session['rainrisk']*100).'%';
785 //Check if rainfall is available
786 if ($session['rainfall'] !== null) {
787 $rain['title'][] = $session['rainfall'].'mm';
791 $rain['title'] = implode(' ', $rain['title']);
800 $routeParams = ['id' => $session['id'], 'location' => $this->slugger
->slug($this->translator
->trans($session['l_title']))];
803 if (!empty($session['a_id'])) {
805 $routeParams['dance'] = $this->slugger
->slug($dance = $this->translator
->trans($session['ad_name'].' '.lcfirst($session['ad_type'])));
808 $routeParams['user'] = $this->slugger
->slug($session['au_pseudonym']);
811 $title = $this->translator
->trans('%dance% %id% by %pseudonym% %location% %city%', ['%dance%' => $dance, '%id%' => $session['id'], '%pseudonym%' => $session['au_pseudonym'], '%location%' => $this->translator
->trans('at '.$session['l_title']), '%city%' => $this->translator
->trans('in '.$session['l_city'])]);
816 'id' => $session['ad_id'],
817 'name' => $this->translator
->trans($session['ad_name']),
818 'type' => $this->translator
->trans($session['ad_type']),
822 'id' => $session['au_id'],
823 'title' => $session['au_pseudonym']
829 'glyph' => self
::GLYPHS
['Free'],
831 'short' => $session['p_short'],
832 'title' => $this->translator
->trans('Free')
836 if (!empty($session['p_hat'])) {
838 $rate['glyph'] = self
::GLYPHS
['Hat'];
841 if (!empty($session['p_rate'])) {
843 $rate['rate'] = $session['p_rate'];
846 $rate['title'] = $this->translator
->trans('%rate%β¬ to the hat', ['%rate%' => $session['p_rate']]);
850 $rate['title'] = $this->translator
->trans('To the hat');
853 } elseif (!empty($session['p_rate'])) {
855 $rate['glyph'] = self
::GLYPHS
['Euro'];
858 $rate['rate'] = $session['p_rate'];
861 $rate['title'] = $session['p_rate'].' β¬';
863 //With unique application
864 } elseif (count($applications) == 1) {
866 $dance = $this->translator
->trans($session['sad_name'].' '.lcfirst($session['sad_type']));
869 $title = $this->translator
->trans('%dance% %id% by %pseudonym% %location% %city%', ['%dance%' => $dance, '%id%' => $session['id'], '%pseudonym%' => $session['sau_pseudonym'], '%location%' => $this->translator
->trans('at '.$session['l_title']), '%city%' => $this->translator
->trans('in '.$session['l_city'])]);
874 'id' => $session['sad_id'],
875 'name' => $this->translator
->trans($session['sad_name']),
876 'type' => $this->translator
->trans($session['sad_type']),
880 'id' => $session['sau_id'],
881 'title' => $session['sau_pseudonym']
885 //TODO: glyph stuff ???
886 //Without application
889 $title = $this->translator
->trans('%slot% %id% %location%', ['%slot%' => $this->translator
->trans($session['t_title']), '%id%' => $session['id'], '%location%' => $this->translator
->trans('at '.$session['l_title'])]);
893 $calendar[$Ymd]['sessions'][$session['t_id'].sprintf('%05d', $session['id'])] = [
894 'id' => $session['id'],
895 'start' => $session['start'],
896 'stop' => $session['stop'],
898 'temperature' => $temperature,
901 'link' => $this->router
->generate($route, $routeParams),
903 'id' => $session['l_id'],
904 'title' => $this->translator
->trans($session['l_title']),
905 'address' => $session['l_address'],
906 'latitude' => $session['l_latitude'],
907 'longitude' => $session['l_longitude'],
908 'indoor' => $session['l_indoor'],
909 'at' => $at = $this->translator
->trans('at '.$session['l_title']),
910 'in' => $in = $this->translator
->trans('in '.$session['l_city']),
911 'atin' => $at.' '.$in,
912 'city' => $session['l_city'],
913 'zipcode' => $session['l_zipcode']
915 'application' => $application,
917 'glyph' => self
::GLYPHS
[$session['t_title']],
918 'title' => $this->translator
->trans($session['t_title'])
921 'modified' => $session['modified'],
922 'applications' => $applications
928 ksort($calendar[$Ymd]['sessions']);
936 * Find session by location, slot and date
938 * @param Location $location The location
939 * @param Slot $slot The slot
940 * @param DateTime $date The datetime
941 * @return ?Session The found session
943 public function findOneByLocationSlotDate(Location
$location, Slot
$slot, \DateTime
$date): ?Session
{
945 return $this->getEntityManager()
946 ->createQuery('SELECT s FROM RapsysAirBundle:Session s WHERE (s.location = :location AND s.slot = :slot AND s.date = :date)')
947 ->setParameter('location', $location)
948 ->setParameter('slot', $slot)
949 ->setParameter('date', $date)
954 * Fetch sessions by date period
956 * @XXX: used in calendar command
958 * @param DatePeriod $period The date period
959 * @return array The session array
961 public function fetchAllByDatePeriod(\DatePeriod
$period): array {
963 //TODO: exclude opera and others ?
970 ADDDATE(ADDTIME(s.date, s.begin), INTERVAL IF(s.slot_id = :afterid, 1, 0) DAY) AS start,
971 ADDDATE(ADDTIME(ADDTIME(s.date, s.begin), s.length), INTERVAL IF(s.slot_id = :afterid, 1, 0) DAY) AS stop,
972 s.location_id AS l_id,
973 l.address AS l_address,
974 l.zipcode AS l_zipcode,
977 l.description AS l_description,
978 l.latitude AS l_latitude,
979 l.longitude AS l_longitude,
980 s.application_id AS a_id,
981 a.canceled AS a_canceled,
985 au.forename AS au_forename,
986 au.pseudonym AS au_pseudonym,
988 p.description AS p_description,
993 p.contact AS p_contact,
994 p.donate AS p_donate,
996 p.profile AS p_profile
997 FROM RapsysAirBundle:Session AS s
998 JOIN RapsysAirBundle:Location AS l ON (l.id = s.location_id)
999 JOIN RapsysAirBundle:Application AS a ON (a.id = s.application_id)
1000 JOIN RapsysAirBundle:Dance AS ad ON (ad.id = a.dance_id)
1001 JOIN RapsysAirBundle:User AS au ON (au.id = a.user_id)
1002 LEFT JOIN RapsysAirBundle:Snippet AS p ON (p.location_id = s.location_id AND p.user_id = a.user_id AND p.locale = :locale)
1003 WHERE s.date BETWEEN :begin AND :end
1007 //Replace bundle entity name by table name
1008 $req = str_replace($this->tableKeys
, $this->tableValues
, $req);
1010 //Get result set mapping instance
1011 //XXX: DEBUG: see ../blog.orig/src/Rapsys/BlogBundle/Repository/ArticleRepository.php
1012 $rsm = new ResultSetMapping();
1014 //Declare all fields
1015 //XXX: see vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/Types.php
1016 //addScalarResult($sqlColName, $resColName, $type = 'string');
1017 $rsm->addScalarResult('id', 'id', 'integer')
1018 ->addScalarResult('date', 'date', 'date')
1019 ->addScalarResult('locked', 'locked', 'datetime')
1020 ->addScalarResult('updated', 'updated', 'datetime')
1021 ->addScalarResult('start', 'start', 'datetime')
1022 ->addScalarResult('stop', 'stop', 'datetime')
1023 ->addScalarResult('l_id', 'l_id', 'integer')
1024 ->addScalarResult('l_address', 'l_address', 'string')
1025 ->addScalarResult('l_zipcode', 'l_zipcode', 'string')
1026 ->addScalarResult('l_city', 'l_city', 'string')
1027 ->addScalarResult('l_latitude', 'l_latitude', 'float')
1028 ->addScalarResult('l_longitude', 'l_longitude', 'float')
1029 ->addScalarResult('l_title', 'l_title', 'string')
1030 ->addScalarResult('l_description', 'l_description', 'string')
1031 ->addScalarResult('t_id', 't_id', 'integer')
1032 ->addScalarResult('t_title', 't_title', 'string')
1033 ->addScalarResult('a_id', 'a_id', 'integer')
1034 ->addScalarResult('a_canceled', 'a_canceled', 'datetime')
1035 ->addScalarResult('ad_name', 'ad_name', 'string')
1036 ->addScalarResult('ad_type', 'ad_type', 'string')
1037 ->addScalarResult('au_id', 'au_id', 'integer')
1038 ->addScalarResult('au_forename', 'au_forename', 'string')
1039 ->addScalarResult('au_pseudonym', 'au_pseudonym', 'string')
1040 ->addScalarResult('p_id', 'p_id', 'integer')
1041 ->addScalarResult('p_description', 'p_description', 'string')
1042 ->addScalarResult('p_class', 'p_class', 'string')
1043 ->addScalarResult('p_short', 'p_short', 'string')
1044 ->addScalarResult('p_hat', 'p_hat', 'integer')
1045 ->addScalarResult('p_rate', 'p_rate', 'integer')
1046 ->addScalarResult('p_contact', 'p_contact', 'string')
1047 ->addScalarResult('p_donate', 'p_donate', 'string')
1048 ->addScalarResult('p_link', 'p_link', 'string')
1049 ->addScalarResult('p_profile', 'p_profile', 'string')
1050 ->addIndexByScalar('id');
1054 ->createNativeQuery($req, $rsm)
1055 ->setParameter('begin', $period->getStartDate())
1056 ->setParameter('end', $period->getEndDate());
1059 return $res->getResult();
1063 * Fetch sessions calendar with translated location by date period and user
1065 * @param DatePeriod $period The date period
1066 * @param ?int $userId The user id
1067 * @param ?int $sessionId The session id
1069 public function fetchUserCalendarByDatePeriod(\DatePeriod
$period, ?int $userId = null, ?int $sessionId = null): array {
1071 $userJoinSql = $userWhereSql = '';
1073 //When user id is set
1074 if (!empty($userId)) {
1076 $userJoinSql = 'JOIN RapsysAirBundle:Application AS sua ON (sua.session_id = s.id)'."\n";
1077 //Add user id clause
1078 $userWhereSql = "\n\t".'AND sua.user_id = :uid';
1082 //TODO: change as_u_* in sau_*, a_u_* in au_*, etc, see request up
1092 ADDDATE(ADDTIME(s.date, s.begin), INTERVAL IF(s.slot_id = :afterid, 1, 0) DAY) AS start,
1093 ADDDATE(ADDTIME(ADDTIME(s.date, s.begin), s.length), INTERVAL IF(s.slot_id = :afterid, 1, 0) DAY) AS stop,
1094 s.location_id AS l_id,
1098 s.application_id AS a_id,
1102 au.pseudonym AS au_pseudonym,
1105 GROUP_CONCAT(sa.user_id ORDER BY sa.user_id SEPARATOR "\\n") AS sau_id,
1106 GROUP_CONCAT(CONCAT("- ", sau.pseudonym) ORDER BY sa.user_id SEPARATOR "\\n") AS sau_pseudonym
1107 FROM RapsysAirBundle:Session AS s
1108 JOIN RapsysAirBundle:Location AS l ON (l.id = s.location_id)
1109 JOIN RapsysAirBundle:Slot AS t ON (t.id = s.slot_id)
1110 {$userJoinSql}LEFT JOIN RapsysAirBundle:Application AS a ON (a.id = s.application_id)
1111 LEFT JOIN RapsysAirBundle:Snippet AS p ON (p.location_id = s.location_id AND p.user_id = a.user_id AND p.locale = :locale)
1112 LEFT JOIN RapsysAirBundle:Dance AS ad ON (ad.id = a.dance_id)
1113 LEFT JOIN RapsysAirBundle:User AS au ON (au.id = a.user_id)
1114 LEFT JOIN RapsysAirBundle:Application AS sa ON (sa.session_id = s.id)
1115 LEFT JOIN RapsysAirBundle:User AS sau ON (sau.id = sa.user_id)
1116 WHERE s.date BETWEEN :begin AND :end{$userWhereSql}
1121 //Replace bundle entity name by table name
1122 $req = str_replace($this->tableKeys
, $this->tableValues
, $req);
1124 //Get result set mapping instance
1125 //XXX: DEBUG: see ../blog.orig/src/Rapsys/BlogBundle/Repository/ArticleRepository.php
1126 $rsm = new ResultSetMapping();
1128 //Declare all fields
1129 //XXX: see vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/Types.php
1130 //addScalarResult($sqlColName, $resColName, $type = 'string');
1131 $rsm->addScalarResult('id', 'id', 'integer')
1132 ->addScalarResult('date', 'date', 'date')
1133 ->addScalarResult('rainrisk', 'rainrisk', 'float')
1134 ->addScalarResult('rainfall', 'rainfall', 'float')
1135 ->addScalarResult('realfeel', 'realfeel', 'float')
1136 ->addScalarResult('temperature', 'temperature', 'float')
1137 ->addScalarResult('locked', 'locked', 'datetime')
1138 ->addScalarResult('start', 'start', 'datetime')
1139 ->addScalarResult('stop', 'stop', 'datetime')
1140 ->addScalarResult('t_id', 't_id', 'integer')
1141 ->addScalarResult('t_title', 't_title', 'string')
1142 ->addScalarResult('l_id', 'l_id', 'integer')
1143 ->addScalarResult('l_title', 'l_title', 'string')
1144 ->addScalarResult('a_id', 'a_id', 'integer')
1145 ->addScalarResult('ad_name', 'ad_name', 'string')
1146 ->addScalarResult('ad_type', 'ad_type', 'string')
1147 ->addScalarResult('au_id', 'au_id', 'integer')
1148 ->addScalarResult('au_pseudonym', 'au_pseudonym', 'string')
1149 ->addScalarResult('p_rate', 'p_rate', 'integer')
1150 ->addScalarResult('p_hat', 'p_hat', 'boolean')
1151 //XXX: is a string because of \n separator
1152 ->addScalarResult('sau_id', 'sau_id', 'string')
1153 //XXX: is a string because of \n separator
1154 ->addScalarResult('sau_pseudonym', 'sau_pseudonym', 'string')
1155 ->addIndexByScalar('id');
1159 ->createNativeQuery($req, $rsm)
1160 ->setParameter('begin', $period->getStartDate())
1161 ->setParameter('end', $period->getEndDate())
1162 ->setParameter('uid', $userId)
1171 //Iterate on each day
1172 foreach($period as $date) {
1173 //Init day in calendar
1174 $calendar[$Ymd = $date->format('Ymd')] = [
1175 'title' => $this->translator
->trans($date->format('l')).' '.$date->format('d'),
1180 //Detect month change
1181 if ($month != $date->format('m')) {
1182 $month = $date->format('m');
1183 //Append month for first day of month
1184 //XXX: except if today to avoid double add
1185 if ($date->format('U') != strtotime('today')) {
1186 $calendar[$Ymd]['title'] .= '/'.$month;
1190 if ($date->format('U') == ($today = strtotime('today'))) {
1191 $calendar[$Ymd]['title'] .= '/'.$month;
1192 $calendar[$Ymd]['current'] = true;
1193 $calendar[$Ymd]['class'][] = 'current';
1195 //Disable passed days
1196 if ($date->format('U') < $today) {
1197 $calendar[$Ymd]['disabled'] = true;
1198 $calendar[$Ymd]['class'][] = 'disabled';
1200 //Set next month days
1201 if ($date->format('m') > date('m')) {
1202 $calendar[$Ymd]['next'] = true;
1203 #$calendar[$Ymd]['class'][] = 'next';
1207 if ($date->format('w') == 0) {
1208 $calendar[$Ymd]['class'][] = 'sunday';
1211 //Iterate on each session to find the one of the day
1212 foreach($res as $session) {
1213 if (($sessionYmd = $session['date']->format('Ymd')) == $Ymd) {
1214 //Count number of application
1215 $count = count(explode("\n", $session['sau_id']));
1219 if (!empty($session['a_id'])) {
1220 $applications = [ $session['au_id'] => $session['au_pseudonym'] ];
1221 if ($session['au_id'] == $userId) {
1222 $class[] = 'granted';
1224 $class[] = 'disputed';
1226 } elseif ($count > 1) {
1227 $class[] = 'disputed';
1228 } elseif (!empty($session['locked'])) {
1229 $class[] = 'locked';
1231 $class[] = 'pending';
1234 if ($sessionId == $session['id']) {
1235 $class[] = 'highlight';
1239 //XXX: realfeel may be null, temperature should not
1240 $temperature = $session['realfeel'] !== null ? $session['realfeel'] : $session['temperature'];
1243 //XXX: rainfall may be null
1244 if ($session['rainrisk'] > 0.50 || $session['rainfall'] > 2) {
1245 $weather = self
::GLYPHS
['Stormy'];
1246 } elseif ($session['rainrisk'] > 0.40 || $session['rainfall'] > 1) {
1247 $weather = self
::GLYPHS
['Rainy'];
1248 } elseif ($temperature > 24) {
1249 $weather = self
::GLYPHS
['Cleary'];
1250 } elseif ($temperature > 17) {
1251 $weather = self
::GLYPHS
['Sunny'];
1252 } elseif ($temperature > 10) {
1253 $weather = self
::GLYPHS
['Cloudy'];
1254 } elseif ($temperature !== null) {
1255 $weather = self
::GLYPHS
['Winty'];
1263 //Check if realfeel is available
1264 if ($session['realfeel'] !== null) {
1265 $weathertitle[] = $session['realfeel'].'Β°R';
1268 //Check if temperature is available
1269 if ($session['temperature'] !== null) {
1270 $weathertitle[] = $session['temperature'].'Β°C';
1273 //Check if rainrisk is available
1274 if ($session['rainrisk'] !== null) {
1275 $weathertitle[] = ($session['rainrisk']*100).'%';
1278 //Check if rainfall is available
1279 if ($session['rainfall'] !== null) {
1280 $weathertitle[] = $session['rainfall'].'mm';
1285 0 => $this->translator
->trans($session['t_title']).' '.$this->translator
->trans('at '.$session['l_title']).$this->translator
->trans(':')
1288 //Fetch pseudonyms from session applications
1289 $applications +
= array_combine(explode("\n", $session['sau_id']), array_map(function ($v) {return '- '.$v
;}, explode("\n", $session['sau_pseudonym'])));
1297 //Check that session is not granted
1298 if (empty($session['a_id'])) {
1299 //With location id and unique application
1301 //Set unique application pseudonym
1302 $pseudonym = $session['sau_pseudonym'];
1304 //Session is granted
1306 //Replace granted application
1307 $applications[$session['au_id']] = '* '.$session['au_pseudonym'];
1310 $dance = $this->translator
->trans($session['ad_name'].' '.lcfirst($session['ad_type']));
1313 $pseudonym = $session['au_pseudonym'].($count > 1 ? ' ['.$count.']':'');
1317 $title = $this->translator
->trans($session['l_title']).($count > 1 ? ' ['.$count.']':'');
1320 $calendar[$Ymd]['sessions'][$session['t_id'].sprintf('%02d', $session['l_id'])] = [
1321 'id' => $session['id'],
1322 'start' => $session['start'],
1323 'stop' => $session['stop'],
1324 'location' => $this->translator
->trans($session['l_title']),
1326 'pseudonym' => $pseudonym,
1328 'slot' => self
::GLYPHS
[$session['t_title']],
1329 'slottitle' => $this->translator
->trans($session['t_title']),
1330 'weather' => $weather,
1331 'weathertitle' => implode(' ', $weathertitle),
1332 'applications' => $applications,
1333 'rate' => $session['p_rate'],
1334 'hat' => $session['p_hat']
1340 ksort($calendar[$Ymd]['sessions']);
1348 * Find all session pending hourly weather
1350 * @return array The sessions to update
1352 public function findAllPendingHourlyWeather(): array {
1353 //Select all sessions starting and stopping in the next 3 days
1354 //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)
1356 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
1357 FROM RapsysAirBundle:Session AS s
1358 JOIN RapsysAirBundle:Location AS l ON (l.id = s.location_id)
1359 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))
1362 //Replace bundle entity name by table name
1363 $req = str_replace($this->tableKeys
, $this->tableValues
, $req);
1365 //Get result set mapping instance
1366 $rsm = new ResultSetMapping();
1368 //Declare all fields
1370 ->addEntityResult('RapsysAirBundle:Session', 's')
1371 ->addFieldResult('s', 'id', 'id')
1372 ->addFieldResult('s', 'date', 'date')
1373 ->addFieldResult('s', 'begin', 'begin')
1374 ->addFieldResult('s', 'length', 'length')
1375 ->addFieldResult('s', 'rainfall', 'rainfall')
1376 ->addFieldResult('s', 'rainrisk', 'rainrisk')
1377 ->addFieldResult('s', 'realfeel', 'realfeel')
1378 ->addFieldResult('s', 'realfeelmin', 'realfeelmin')
1379 ->addFieldResult('s', 'realfeelmax', 'realfeelmax')
1380 ->addFieldResult('s', 'temperature', 'temperature')
1381 ->addFieldResult('s', 'temperaturemin', 'temperaturemin')
1382 ->addFieldResult('s', 'temperaturemax', 'temperaturemax')
1383 ->addJoinedEntityResult('RapsysAirBundle:Slot', 'o', 's', 'slot')
1384 ->addFieldResult('o', 'slot_id', 'id')
1385 ->addJoinedEntityResult('RapsysAirBundle:Location', 'l', 's', 'location')
1386 ->addFieldResult('l', 'location_id', 'id')
1387 ->addFieldResult('l', 'zipcode', 'zipcode')
1388 ->addIndexBy('s', 'id');
1392 ->createNativeQuery($req, $rsm)
1397 * Find all session pending daily weather
1399 * @return array The sessions to update
1401 public function findAllPendingDailyWeather(): array {
1402 //Select all sessions stopping after next 3 days
1403 //XXX: select session stopping after or equal date(now)+3d as accuweather only provide hourly data for the next 3 days (INTERVAL 3 DAY)
1405 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
1406 FROM RapsysAirBundle:Session AS s
1407 JOIN RapsysAirBundle:Location AS l ON (l.id = s.location_id)
1408 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))
1411 //Replace bundle entity name by table name
1412 $req = str_replace($this->tableKeys
, $this->tableValues
, $req);
1414 //Get result set mapping instance
1415 $rsm = new ResultSetMapping();
1417 //Declare all fields
1419 ->addEntityResult('RapsysAirBundle:Session', 's')
1420 ->addFieldResult('s', 'id', 'id')
1421 ->addFieldResult('s', 'date', 'date')
1422 ->addFieldResult('s', 'begin', 'begin')
1423 ->addFieldResult('s', 'length', 'length')
1424 ->addFieldResult('s', 'rainfall', 'rainfall')
1425 ->addFieldResult('s', 'rainrisk', 'rainrisk')
1426 ->addFieldResult('s', 'realfeel', 'realfeel')
1427 ->addFieldResult('s', 'realfeelmin', 'realfeelmin')
1428 ->addFieldResult('s', 'realfeelmax', 'realfeelmax')
1429 ->addFieldResult('s', 'temperature', 'temperature')
1430 ->addFieldResult('s', 'temperaturemin', 'temperaturemin')
1431 ->addFieldResult('s', 'temperaturemax', 'temperaturemax')
1432 ->addJoinedEntityResult('RapsysAirBundle:Slot', 'o', 's', 'slot')
1433 ->addFieldResult('o', 'slot_id', 'id')
1434 ->addJoinedEntityResult('RapsysAirBundle:Location', 'l', 's', 'location')
1435 ->addFieldResult('l', 'location_id', 'id')
1436 ->addFieldResult('l', 'zipcode', 'zipcode')
1437 ->addIndexBy('s', 'id');
1441 ->createNativeQuery($req, $rsm)
1446 * Find every session pending application
1448 * @return array The sessions to update
1450 public function findAllPendingApplication(): array {
1451 //Select all sessions not locked without application or canceled application within attribution period
1452 //XXX: DIFF(start, now) <= IF(DIFF(start, created) <= SENIOR_DELAY in DAY, DIFF(start, created) * 3 / 4, SENIOR_DELAY)
1453 //TODO: remonter les donnΓ©es pour le mail ?
1456 FROM RapsysAirBundle:Session as s
1457 LEFT JOIN RapsysAirBundle:Application AS a ON (a.id = s.application_id AND a.canceled IS NULL)
1458 JOIN RapsysAirBundle:Application AS a2 ON (a2.session_id = s.id AND a2.canceled IS NULL)
1459 WHERE s.locked IS NULL AND s.application_id IS NULL AND
1460 (UNIX_TIMESTAMP(@dt_start := ADDDATE(ADDTIME(s.date, s.begin), INTERVAL IF(s.slot_id = :afterid, 1, 0) DAY)) - UNIX_TIMESTAMP()) <= IF(
1461 (@td_sc := UNIX_TIMESTAMP(@dt_start) - UNIX_TIMESTAMP(s.created)) <= :seniordelay,
1462 ROUND(@td_sc * :regulardelay / :seniordelay),
1466 ORDER BY @dt_start ASC, s.created ASC
1469 //Replace bundle entity name by table name
1470 $req = str_replace($this->tableKeys
, $this->tableValues
, $req);
1472 //Get result set mapping instance
1473 $rsm = new ResultSetMapping();
1475 //Declare all fields
1477 ->addEntityResult('RapsysAirBundle:Session', 's')
1478 ->addFieldResult('s', 'id', 'id')
1479 ->addIndexBy('s', 'id');
1483 ->createNativeQuery($req, $rsm)
1488 * Fetch session best application by session id
1490 * @param int $id The session id
1491 * @return ?Application The application or null
1493 public function findBestApplicationById(int $id): ?Application
{
1495 * Query session applications ranked by location score, global score, created and user_id
1497 * @xxx guest (or less) with application on location within 30 day are only considered within guestdelay
1499 * @xxx regular (or less) premium application on hotspot are only considered within regulardelay
1501 * @xxx senior (or less) with 5 or less session on location are only considered within seniordelay
1503 * @xxx senior (or less) with l_pn_ratio >= 1 are only considered within seniordelay
1505 * @xxx senior (or less) with l_tr_ratio >= (o_tr_ratio + 5) are only considered within seniordelay
1507 * @xxx only consider session within one year (may be unaccurate by the day with after session)
1509 * @xxx rainfall may not be accessible for previous session and other session at d-4 (only at d-2)
1511 * @todo ??? feedback the data to inform the rejected users ???
1514 SELECT e.id, e.l_score AS score
1526 MAX(ug.group_id) AS group_id,
1541 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,
1558 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,
1571 COUNT(a2.id) AS l_count,
1572 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,
1573 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,
1574 (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,
1575 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,
1576 UNIX_TIMESTAMP(ADDDATE(ADDTIME(s.date, s.begin), INTERVAL IF(s.slot_id = :afterid, 1, 0) DAY)) - UNIX_TIMESTAMP() AS remaining,
1580 FROM RapsysAirBundle:Session AS s
1581 JOIN RapsysAirBundle:Location AS l ON (l.id = s.location_id)
1582 JOIN RapsysAirBundle:Application AS a ON (a.session_id = s.id AND a.canceled IS NULL)
1583 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)
1584 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))
1590 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)
1591 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))
1596 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)
1597 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))
1602 LEFT JOIN RapsysAirBundle:UserGroup AS ug ON (ug.user_id = d.user_id)
1607 IF(e.group_id <= :guestid AND e.l_previous <= :guestwait, e.remaining <= :guestdelay, 1) AND
1608 IF(e.group_id <= :regularid AND e.premium = 1 AND e.hotspot = 1, e.remaining <= :regulardelay, 1) AND
1609 IF(e.group_id <= :seniorid AND e.l_count <= :scount, e.remaining <= :regulardelay, 1) AND
1610 IF(e.group_id <= :seniorid AND e.l_pn_ratio >= :pnratio, e.remaining <= :regulardelay, 1) AND
1611 IF(e.group_id <= :seniorid AND e.l_tr_ratio >= (e.o_tr_ratio + :trdiff), e.remaining <= :regulardelay, 1)
1612 ORDER BY e.l_score ASC, e.g_score ASC, e.created ASC, e.user_id ASC
1615 //Replace bundle entity name by table name
1616 $req = str_replace($this->tableKeys
, $this->tableValues
, $req);
1618 //Set update request
1619 $upreq = 'UPDATE RapsysAirBundle:Application SET score = :score, updated = NOW() WHERE id = :id';
1621 //Replace bundle entity name by table name
1622 $upreq = str_replace($this->tableKeys
, $this->tableValues
, $upreq);
1624 //Get result set mapping instance
1625 $rsm = new ResultSetMapping();
1627 //Declare all fields
1629 ->addEntityResult('RapsysAirBundle:Application', 'a')
1630 ->addFieldResult('a', 'id', 'id')
1631 ->addFieldResult('a', 'score', 'score')
1632 ->addIndexBy('a', 'id');
1635 //XXX: setting limit in subqueries is required to prevent mariadb optimisation
1636 $applications = $this->_em
1637 ->createNativeQuery($req, $rsm)
1638 ->setParameter('sid', $id)
1645 foreach($applications as $application) {
1646 //Check if we already saved best candidate
1647 if ($ret === null) {
1648 //Return first application
1649 $ret = $application;
1652 //Update application updated field
1653 //XXX: updated field is not modified for user with bad behaviour as application is not retrieved until delay is reached
1654 $this->_em
->getConnection()->executeUpdate($upreq, ['id' => $application->getId(), 'score' => $application->getScore()], ['id' => Types
::INTEGER, 'score' => Types
::FLOAT]);
1657 //Return best ranked application
1662 * Rekey sessions and applications by chronological session id
1664 * @return bool The rekey success or failure
1666 function rekey(): bool {
1668 $cnx = $this->_em
->getConnection();
1681 GROUP_CONCAT(sa.id ORDER BY sa.id SEPARATOR "\\n") AS sa_id
1682 FROM RapsysAirBundle:Session AS s
1683 LEFT JOIN RapsysAirBundle:Application AS sa ON (sa.session_id = s.id)
1687 ORDER BY ADDDATE(ADDTIME(a.date, a.begin), INTERVAL IF(a.slot_id = :afterid, 1, 0) DAY) ASC
1690 //Replace bundle entity name by table name
1691 $req = str_replace($this->tableKeys
, $this->tableValues
, $req);
1693 //Get result set mapping instance
1694 //XXX: DEBUG: see ../blog.orig/src/Rapsys/BlogBundle/Repository/ArticleRepository.php
1695 $rsm = new ResultSetMapping();
1697 //Declare all fields
1698 //XXX: see vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/Types.php
1699 //addScalarResult($sqlColName, $resColName, $type = 'string');
1700 $rsm->addScalarResult('id', 'id', 'integer')
1701 ->addScalarResult('sa_id', 'sa_id', 'string');
1702 #->addIndexByScalar('id');
1705 $rnq = $this->_em
->createNativeQuery($req, $rsm);
1708 $res = $rnq->getResult();
1711 $cnx->beginTransaction();
1713 //Set update session request
1715 UPDATE RapsysAirBundle:Session
1716 SET id = :nid, updated = NOW()
1720 //Replace bundle entity name by table name
1721 $sreq = str_replace($this->tableKeys
, $this->tableValues
, $sreq);
1723 //Set update application request
1725 UPDATE RapsysAirBundle:Application
1726 SET session_id = :nid, updated = NOW()
1727 WHERE session_id = :id
1730 //Replace bundle entity name by table name
1731 $areq = str_replace($this->tableKeys
, $this->tableValues
, $areq);
1734 $max = max(array_keys($res));
1737 //Prepare session to update
1738 foreach($res as $id => $data) {
1740 $res[$id]['t_id'] = $max +
$id +
1;
1743 $res[$id]['n_id'] = $id +
1;
1745 //Explode application ids
1746 $res[$id]['sa_id'] = explode("\n", $data['sa_id']);
1749 if ($res[$id]['n_id'] == $res[$id]['id']) {
1750 //Remove unchanged session
1757 //Disable foreign key checks
1758 $cnx->prepare('SET foreign_key_checks = 0')->execute();
1761 foreach($res as $id => $data) {
1762 //Run session update
1763 $cnx->executeUpdate($sreq, ['nid' => $res[$id]['t_id'], 'id' => $res[$id]['id']]);
1765 //Run applications update
1766 $cnx->executeUpdate($areq, ['nid' => $res[$id]['t_id'], 'id' => $res[$id]['id']]);
1770 foreach($res as $id => $data) {
1771 //Run session update
1772 $cnx->executeUpdate($sreq, ['nid' => $res[$id]['n_id'], 'id' => $res[$id]['t_id']]);
1774 //Run applications update
1775 $cnx->executeUpdate($areq, ['nid' => $res[$id]['n_id'], 'id' => $res[$id]['t_id']]);
1778 //Restore foreign key checks
1779 $cnx->prepare('SET foreign_key_checks = 1')->execute();
1781 //Commit transaction
1784 //Set update auto_increment request
1786 ALTER TABLE RapsysAirBundle:Session
1790 //Replace bundle entity name by table name
1791 $ireq = str_replace($this->tableKeys
, $this->tableValues
, $ireq);
1793 //Reset auto_increment
1797 //Rollback transaction
1800 } catch(\Exception
$e) {
1801 //Rollback transaction