+
+ /**
+ * Find every session pending application
+ *
+ * @return array<Session> The sessions to update
+ */
+ public function findAllPendingApplication() {
+ //Get entity manager
+ $em = $this->getEntityManager();
+
+ //Get quote strategy
+ $qs = $em->getConfiguration()->getQuoteStrategy();
+ $dp = $em->getConnection()->getDatabasePlatform();
+
+ //Get quoted table names
+ //XXX: this allow to make this code table name independent
+ $tables = [
+ 'RapsysAirBundle:Session' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Session'), $dp),
+ "\t" => '',
+ "\n" => ' '
+ ];
+
+ //Select all sessions without application attributed with diff(start, now) <= if(diff(start, created) <= GOOD_DELAY day, diff(start, created)*3/4, GOOD_DELAY day)
+ //XXX: consider only unfinished sessions with stop > now
+ //XXX: consider as grace time first quarter (1/4) between creation and start time when below gooddelay
+ //XXX: we may remove ADDDATE(start, INTERVAL IF(s.slot_id = 4, 1, 0) DAY) used for after specificity
+ $req =<<<SQL
+SELECT s.id
+FROM RapsysAirBundle:Session AS s
+WHERE
+ s.application_id IS NULL AND
+ ADDDATE(ADDTIME(ADDTIME(s.date, s.begin), s.length), INTERVAL IF(s.slot_id = 4, 1, 0) DAY) > NOW() AND
+ TIMEDIFF(ADDDATE(ADDTIME(s.date, s.begin), INTERVAL IF(s.slot_id = 4, 1, 0) DAY), NOW()) <= IF(DATEDIFF(ADDDATE(ADDTIME(s.date, s.begin), INTERVAL IF(s.slot_id = 4, 1, 0) DAY), s.created) <= :gooddelay, SEC_TO_TIME(TIME_TO_SEC(TIMEDIFF(ADDDATE(ADDTIME(s.date, s.begin), INTERVAL IF(s.slot_id = 4, 1, 0) DAY), s.created))*3/4), SEC_TO_TIME(:gooddelay*24*3600))
+ORDER BY ADDDATE(ADDTIME(s.date, s.begin), INTERVAL IF(s.slot_id = 4, 1, 0) DAY) ASC, s.created ASC
+SQL;
+
+ //Replace bundle entity name by table name
+ $req = str_replace(array_keys($tables), array_values($tables), $req);
+
+ //Get result set mapping instance
+ $rsm = new ResultSetMapping();
+
+ //Declare all fields
+ $rsm
+ ->addEntityResult('RapsysAirBundle:Session', 's')
+ ->addFieldResult('s', 'id', 'id')
+ ->addIndexBy('s', 'id');
+
+ //Send result
+ return $em
+ ->createNativeQuery($req, $rsm)
+ ->setParameter('limit', PHP_INT_MAX)
+ ->setParameter('gooddelay', self::GOOD_DELAY)
+ ->getResult();
+ }
+
+ /**
+ * Find all session pending hourly weather
+ *
+ * @return array<Session> The sessions to update
+ */
+ public function findAllPendingHourlyWeather() {
+ //Get entity manager
+ $em = $this->getEntityManager();
+
+ //Get quote strategy
+ $qs = $em->getConfiguration()->getQuoteStrategy();
+ $dp = $em->getConnection()->getDatabasePlatform();
+
+ //Get quoted table names
+ //XXX: this allow to make this code table name independent
+ $tables = [
+ 'RapsysAirBundle:Session' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Session'), $dp),
+ 'RapsysAirBundle:Slot' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Slot'), $dp),
+ 'RapsysAirBundle:Location' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Location'), $dp),
+ "\t" => '',
+ "\n" => ' '
+ ];
+
+ //Select all sessions starting and stopping in the next 3 days
+ //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)
+ //XXX: we may remove ADDDATE(start, INTERVAL IF(s.slot_id = 4, 1, 0) DAY) used for after specificity
+ $req = <<<SQL
+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, o.title
+FROM RapsysAirBundle:Session AS s
+JOIN RapsysAirBundle:Slot AS o ON (o.id = s.slot_id)
+JOIN RapsysAirBundle:Location AS l ON (l.id = s.location_id)
+WHERE ADDDATE(ADDTIME(s.date, s.begin), INTERVAL IF(s.slot_id = 4, 1, 0) DAY) >= NOW() AND ADDDATE(ADDTIME(ADDTIME(s.date, s.begin), s.length), INTERVAL IF(s.slot_id = 4, 1, 0) DAY) < DATE(ADDDATE(NOW(), INTERVAL :accuhourly DAY))
+SQL;
+
+ //Replace bundle entity name by table name
+ $req = str_replace(array_keys($tables), array_values($tables), $req);
+
+ //Get result set mapping instance
+ $rsm = new ResultSetMapping();
+
+ //Declare all fields
+ $rsm
+ ->addEntityResult('RapsysAirBundle:Session', 's')
+ ->addFieldResult('s', 'id', 'id')
+ ->addFieldResult('s', 'date', 'date')
+ ->addFieldResult('s', 'begin', 'begin')
+ ->addFieldResult('s', 'length', 'length')
+ ->addFieldResult('s', 'rainfall', 'rainfall')
+ ->addFieldResult('s', 'rainrisk', 'rainrisk')
+ ->addFieldResult('s', 'realfeel', 'realfeel')
+ ->addFieldResult('s', 'realfeelmin', 'realfeelmin')
+ ->addFieldResult('s', 'realfeelmax', 'realfeelmax')
+ ->addFieldResult('s', 'temperature', 'temperature')
+ ->addFieldResult('s', 'temperaturemin', 'temperaturemin')
+ ->addFieldResult('s', 'temperaturemax', 'temperaturemax')
+ ->addJoinedEntityResult('RapsysAirBundle:Slot', 'o', 's', 'slot')
+ ->addFieldResult('o', 'slot_id', 'id')
+ ->addFieldResult('o', 'title', 'title')
+ ->addJoinedEntityResult('RapsysAirBundle:Location', 'l', 's', 'location')
+ ->addFieldResult('l', 'location_id', 'id')
+ ->addFieldResult('l', 'zipcode', 'zipcode')
+ ->addIndexBy('s', 'id');
+
+ //Send result
+ return $em
+ ->createNativeQuery($req, $rsm)
+ ->setParameter('accuhourly', self::ACCUWEATHER_HOURLY)
+ ->getResult();
+ }
+
+ /**
+ * Find all session pending daily weather
+ *
+ * @return array<Session> The sessions to update
+ */
+ public function findAllPendingDailyWeather() {
+ //Get entity manager
+ $em = $this->getEntityManager();
+
+ //Get quote strategy
+ $qs = $em->getConfiguration()->getQuoteStrategy();
+ $dp = $em->getConnection()->getDatabasePlatform();
+
+ //Get quoted table names
+ //XXX: this allow to make this code table name independent
+ $tables = [
+ 'RapsysAirBundle:Session' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Session'), $dp),
+ 'RapsysAirBundle:Slot' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Slot'), $dp),
+ 'RapsysAirBundle:Location' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Location'), $dp),
+ "\t" => '',
+ "\n" => ' '
+ ];
+
+ //Select all sessions stopping after next 3 days
+ //XXX: select session stopping after or equal date(now)+3d as accuweather only provide hourly data for the next 3 days (INTERVAL 3 DAY)
+ //XXX: we may remove ADDDATE(start, INTERVAL IF(s.slot_id = 4, 1, 0) DAY) used for after specificity
+ $req = <<<SQL
+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, o.title
+FROM RapsysAirBundle:Session AS s
+JOIN RapsysAirBundle:Slot AS o ON (o.id = s.slot_id)
+JOIN RapsysAirBundle:Location AS l ON (l.id = s.location_id)
+WHERE ADDDATE(ADDTIME(ADDTIME(s.date, s.begin), s.length), INTERVAL IF(s.slot_id = 4, 1, 0) DAY) >= DATE(ADDDATE(NOW(), INTERVAL :accuhourly DAY)) AND ADDDATE(ADDTIME(ADDTIME(s.date, s.begin), s.length), INTERVAL IF(s.slot_id = 4, 1, 0) DAY) < DATE(ADDDATE(NOW(), INTERVAL :accudaily DAY))
+SQL;
+
+ //Replace bundle entity name by table name
+ $req = str_replace(array_keys($tables), array_values($tables), $req);
+
+ //Get result set mapping instance
+ $rsm = new ResultSetMapping();
+
+ //Declare all fields
+ $rsm
+ ->addEntityResult('RapsysAirBundle:Session', 's')
+ ->addFieldResult('s', 'id', 'id')
+ ->addFieldResult('s', 'date', 'date')
+ ->addFieldResult('s', 'begin', 'begin')
+ ->addFieldResult('s', 'length', 'length')
+ ->addFieldResult('s', 'rainfall', 'rainfall')
+ ->addFieldResult('s', 'rainrisk', 'rainrisk')
+ ->addFieldResult('s', 'realfeel', 'realfeel')
+ ->addFieldResult('s', 'realfeelmin', 'realfeelmin')
+ ->addFieldResult('s', 'realfeelmax', 'realfeelmax')
+ ->addFieldResult('s', 'temperature', 'temperature')
+ ->addFieldResult('s', 'temperaturemin', 'temperaturemin')
+ ->addFieldResult('s', 'temperaturemax', 'temperaturemax')
+ ->addJoinedEntityResult('RapsysAirBundle:Slot', 'o', 's', 'slot')
+ ->addFieldResult('o', 'slot_id', 'id')
+ ->addFieldResult('o', 'title', 'title')
+ ->addJoinedEntityResult('RapsysAirBundle:Location', 'l', 's', 'location')
+ ->addFieldResult('l', 'location_id', 'id')
+ ->addFieldResult('l', 'zipcode', 'zipcode')
+ ->addIndexBy('s', 'id');
+
+ //Send result
+ return $em
+ ->createNativeQuery($req, $rsm)
+ ->setParameter('accudaily', self::ACCUWEATHER_DAILY)
+ ->setParameter('accuhourly', self::ACCUWEATHER_HOURLY)
+ ->getResult();
+ }
+
+ /**
+ * Fetch session best application by session id
+ *
+ * @param int $id The session id
+ * @return Application|null The application or null
+ */
+ public function findBestApplicationById($id) {
+ //Get entity manager
+ $em = $this->getEntityManager();
+
+ //Get quote strategy
+ $qs = $em->getConfiguration()->getQuoteStrategy();
+ $dp = $em->getConnection()->getDatabasePlatform();
+
+ //Get quoted table names
+ //XXX: this allow to make this code table name independent
+ $tables = [
+ 'RapsysAirBundle:Application' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Application'), $dp),
+ 'RapsysAirBundle:Session' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Session'), $dp),
+ "\t" => '',
+ "\n" => ' '
+ ];
+
+ /**
+ * Query session applications ranked by score, created and user_id
+ *
+ * @xxx User with bad behaviour application are excluded until remaining <= baddelay:
+ * - with (count(premium = 1)+1)/(count(premium = 0)+1) >= 1
+ * - with count(sessions) <= 5
+ * - with average(temperature) >= average(temperature other) + 10
+ *
+ * @xxx Magic happen on this line:
+ * WHERE IF(d.pnp_rate >= 1, d.remaining <= SEC_TO_TIME(:baddelay), 1) AND IF(d.s_count <= 5, d.remaining <= SEC_TO_TIME(:baddelay), 1) AND IF(d.tr_rate >= (d.otr_rate + 10), d.remaining <= SEC_TO_TIME(:baddelay), 1)
+ *
+ * @todo Limit score on last year only ???
+ * AND DATEDIFF(s.date, NOW()) <= 365
+ *
+ * TODO: we may add ADDDATE(start, INTERVAL IF(s.slot_id = 4, 1, 0) DAY) used for after specificity
+ */
+ $req = <<<SQL
+SELECT d.id, d.score
+FROM (
+ SELECT
+ c.id,
+ c.session_id,
+ c.user_id,
+ c.score,
+ c.remaining,
+ c.created,
+ c.s_count,
+ c.tr_rate,
+ AVG(IF(a4.id IS NOT NULL, s4.temperature/(1+s4.rainfall), NULL)) AS otr_rate,
+ c.pnp_rate
+ FROM (
+ SELECT
+ b.id,
+ b.session_id,
+ b.user_id,
+ b.score,
+ b.remaining,
+ b.created,
+ COUNT(a3.id) AS s_count,
+ AVG(IF(a3.id IS NOT NULL AND s3.temperature IS NOT NULL AND s3.rainfall IS NOT NULL, s3.temperature/(1+s3.rainfall), NULL)) AS tr_rate,
+ (SUM(IF(a3.id IS NOT NULL AND s3.premium = 1, 1, 0))+1)/(SUM(IF(a3.id IS NOT NULL AND s3.premium = 0, 1, 0))+1) AS pnp_rate
+ FROM (
+ SELECT
+ a.id,
+ s.id AS session_id,
+ a.user_id,
+ SUM(IF(a2.id IS NOT NULL, 1/ABS(DATEDIFF(s.date, s2.date)), 0)) AS score,
+ TIMEDIFF(ADDTIME(s.date, s.begin), NOW()) AS remaining,
+ a.created
+ FROM sessions AS s
+ JOIN applications AS a ON (a.session_id = s.id AND a.canceled IS NULL)
+ LEFT JOIN sessions AS s2 ON (s2.id != s.id AND s2.location_id = s.location_id AND s2.slot_id = s.slot_id AND s2.application_id IS NOT NULL)
+ LEFT JOIN applications 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, ADDTIME(s2.date, s2.begin)) < 1))
+ WHERE s.id = :sid
+ GROUP BY a.id
+ ORDER BY NULL
+ LIMIT 0, :limit
+ ) AS b
+ LEFT JOIN sessions AS s3 ON (s3.id != b.session_id AND s3.application_id IS NOT NULL)
+ LEFT JOIN applications 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, ADDTIME(s3.date, s3.begin)) < 1))
+ GROUP BY b.id
+ ORDER BY NULL
+ LIMIT 0, :limit
+ ) AS c
+ LEFT JOIN sessions AS s4 ON (s4.id != c.session_id AND s4.application_id IS NOT NULL AND s4.temperature IS NOT NULL AND s4.rainfall IS NOT NULL)
+ LEFT JOIN applications 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, ADDTIME(s4.date, s4.begin)) < 1))
+ GROUP BY c.id
+ ORDER BY NULL
+ LIMIT 0, :limit
+) AS d
+WHERE IF(d.pnp_rate >= 1, d.remaining <= SEC_TO_TIME(:baddelay), 1) AND IF(d.s_count <= 5, d.remaining <= SEC_TO_TIME(:baddelay), 1) AND IF(d.tr_rate >= (d.otr_rate + 10), d.remaining <= SEC_TO_TIME(:baddelay), 1)
+ORDER BY d.score ASC, d.created ASC, d.user_id ASC
+SQL;
+
+ //Replace bundle entity name by table name
+ $req = str_replace(array_keys($tables), array_values($tables), $req);
+
+ //Set update request
+ $upreq = 'UPDATE RapsysAirBundle:Application SET score = :score, updated = NOW() WHERE id = :id';
+
+ //Replace bundle entity name by table name
+ $upreq = str_replace(array_keys($tables), array_values($tables), $upreq);
+
+ //Get result set mapping instance
+ $rsm = new ResultSetMapping();
+
+ //Declare all fields
+ $rsm
+ ->addEntityResult('RapsysAirBundle:Application', 'a')
+ ->addFieldResult('a', 'id', 'id')
+ ->addFieldResult('a', 'score', 'score')
+ ->addIndexBy('a', 'id');
+
+ //Get result
+ //XXX: setting limit in subqueries is required to prevent mariadb optimisation
+ $applications = $em
+ ->createNativeQuery($req, $rsm)
+ ->setParameter('sid', $id)
+ ->setParameter('baddelay', self::BAD_DELAY*24*3600)
+ ->setParameter('limit', PHP_INT_MAX)
+ //XXX: removed, we update score before returning best candidate
+ //->getOneOrNullResult(Query::HYDRATE_SINGLE_SCALAR);
+ ->getResult();
+
+ //Init ret
+ $ret = null;
+
+ //Update score
+ foreach($applications as $application) {
+ //Check if we already saved best candidate
+ if ($ret === null) {
+ //Return first application
+ $ret = $application;
+ }
+
+ //Update application updated field
+ //XXX: updated field is not modified for user with bad behaviour as application is not retrieved until delay is reached
+ $em->getConnection()->executeUpdate($upreq, ['id' => $application->getId(), 'score' => $application->getScore()], ['id' => Type::INTEGER, 'score' => Type::FLOAT]);
+ }
+
+ //Return best ranked application
+ return $ret;
+ }