X-Git-Url: https://git.rapsys.eu/airbundle/blobdiff_plain/d0d8de5a7844aacda1fa790267fd648fe59b5b2d..c6c9f15189b82a9257a382cf9b68ab8041a187f8:/Controller/SessionController.php?ds=sidebyside diff --git a/Controller/SessionController.php b/Controller/SessionController.php index a8cdfd9..b30d79e 100644 --- a/Controller/SessionController.php +++ b/Controller/SessionController.php @@ -1,929 +1,757 @@ - + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ namespace Rapsys\AirBundle\Controller; +use Symfony\Component\Asset\Packages; +use Symfony\Component\Filesystem\Exception\IOExceptionInterface; +use Symfony\Component\Filesystem\Filesystem; +use Symfony\Component\HttpFoundation\BinaryFileResponse; use Symfony\Component\HttpFoundation\Request; -use Symfony\Component\Routing\RequestContext; +use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Exception\MethodNotAllowedException; use Symfony\Component\Routing\Exception\ResourceNotFoundException; +use Symfony\Component\Routing\Generator\UrlGeneratorInterface; +use Symfony\Component\Routing\RequestContext; + use Rapsys\AirBundle\Entity\Application; +use Rapsys\AirBundle\Entity\Dance; use Rapsys\AirBundle\Entity\User; use Rapsys\AirBundle\Entity\Slot; use Rapsys\AirBundle\Entity\Session; use Rapsys\AirBundle\Entity\Location; -class SessionController extends DefaultController { +class SessionController extends AbstractController { /** - * Edit session + * List all sessions * - * @desc Persist session and all required dependencies in database + * @desc Display all sessions with an application or login form * * @param Request $request The request instance * - * @return Response The rendered view or redirection - * - * @throws \RuntimeException When user has not at least guest role + * @return Response The rendered view */ - public function edit(Request $request, $id) { - //Prevent non-guest to access here - $this->denyAccessUnlessGranted('ROLE_GUEST', null, $this->translator->trans('Unable to access this page without role %role%!', ['%role%' => $this->translator->trans('Guest')])); + public function index(Request $request): Response { + //Get locations + $this->context['locations'] = $this->doctrine->getRepository(Location::class)->findAllAsArray($this->period); - //Reject non post requests - if (!$request->isMethod('POST')) { - throw new \RuntimeException('Request method MUST be POST'); - } + //Add cities + $this->context['cities'] = $this->doctrine->getRepository(Location::class)->findCitiesAsArray($this->period); - //Get doctrine - $doctrine = $this->getDoctrine(); + //Add calendar + $this->context['calendar'] = $this->doctrine->getRepository(Session::class)->findAllByPeriodAsCalendarArray($this->period, !$this->checker->isGranted('IS_AUTHENTICATED_REMEMBERED'), null, null, 1); - //Fetch session - $session = $doctrine->getRepository(Session::class)->fetchOneById($id); - - //Check if - if ( - //we are admin - !$this->isGranted('ROLE_ADMIN') && - //or attributed user - $this->getUser()->getId() != $session['au_id'] && - //or application without attributed user - $session['au_id'] !== null && !in_array($this->getUser()->getId(), explode("\n", $session['sau_id'])) - ) { - //Prevent non admin and non attributed user access - throw $this->createAccessDeniedException(); - } + //Add dances + $this->context['dances'] = $this->doctrine->getRepository(Dance::class)->findNamesAsArray(); - //Set now - $now = new \DateTime('now'); - - //Create SessionEditType form - $form = $this->createForm('Rapsys\AirBundle\Form\SessionEditType', null, [ - //Set the action - 'action' => $this->generateUrl('rapsys_air_session_edit', [ 'id' => $id ]), - //Set the form attribute - 'attr' => [], - //Set admin - 'admin' => $this->isGranted('ROLE_ADMIN'), - //Set default user to current - 'user' => $this->getUser()->getId(), - //Set begin - 'begin' => $session['begin'], - //Set length - 'length' => $session['length'], - //Set raincancel - 'raincancel' => $this->isGranted('ROLE_ADMIN') || $this->getUser()->getId() == $session['au_id'] && $session['rainfall'] >= 2, - //Set cancel - 'cancel' => $this->isGranted('ROLE_ADMIN') || in_array($this->getUser()->getId(), explode("\n", $session['sau_id'])), - //Set modify - 'modify' => $this->isGranted('ROLE_ADMIN') || $this->getUser()->getId() == $session['au_id'] && $session['stop'] >= $now && $this->isGranted('ROLE_REGULAR'), - //Set move - 'move' => $this->isGranted('ROLE_ADMIN') || $this->getUser()->getId() == $session['au_id'] && $session['stop'] >= $now && $this->isGranted('ROLE_SENIOR'), - //Set session - 'session' => $session['id'] - ]); - - //Refill the fields in case of invalid form - $form->handleRequest($request); - - //Handle invalid data - #if (true) { $form->isValid(); - //TODO: mettre une contrainte sur un des boutons submit, je sais pas encore comment - if (!$form->isValid()) { - //Set section - $section = $this->translator->trans('Session %id%', ['%id%' => $id]); + //Set modified + $this->modified = max(array_map(function ($v) { return $v['modified']; }, array_merge($this->context['calendar'], $this->context['cities'], $this->context['dances']))); - //Set title - $title = $section.' - '.$this->translator->trans($this->config['site']['title']); - - //Add session in context - $context['session'] = [ - 'id' => $id, - 'title' => $this->translator->trans('Session %id%', ['%id%' => $id]), - 'location' => [ - 'id' => $session['l_id'], - 'at' => $this->translator->trans('at '.$session['l_title']) - ] - ]; - //Render the view - return $this->render('@RapsysAir/session/edit.html.twig', ['title' => $title, 'section' => $section, 'form' => $form->createView()]+$context+$this->context); - } + //Create response + $response = new Response(); - //Get manager - $manager = $doctrine->getManager(); + //With logged user + if ($this->checker->isGranted('IS_AUTHENTICATED_REMEMBERED')) { + //Set last modified + $response->setLastModified(new \DateTime('-1 year')); - //Get data - $data = $form->getData(); + //Set as private + $response->setPrivate(); + //Without logged user + } else { + //Set etag + //XXX: only for public to force revalidation by last modified + $response->setEtag(md5(serialize(array_merge($this->context['calendar'], $this->context['cities'], $this->context['dances'])))); - //Fetch session - $session = $doctrine->getRepository(Session::class)->findOneById($id); + //Set last modified + $response->setLastModified($this->modified); - //Set user - $user = $this->getUser(); + //Set as public + $response->setPublic(); - //Replace with requested user for admin - if ($this->isGranted('ROLE_ADMIN') && !empty($data['user'])) { - $user = $doctrine->getRepository(User::class)->findOneById($data['user']); + //Without role and modification + if ($response->isNotModified($request)) { + //Return 304 response + return $response; + } } - //Set datetime - $datetime = new \DateTime('now'); - - //With raincancel - if ($form->has('raincancel') && $form->get('raincancel')->isClicked()) { - //Check rainfall - if ($this->isGranted('ROLE_ADMIN') || $session->getRainfall() >= 2) { - //Check that application is attributed - if (!empty($application = $session->getApplication())) { - //Get application - $application = $doctrine->getRepository(Application::class)->findOneBySessionUser($session, $application->getUser()); - - //Set canceled time at start minus one day - $canceled = (clone $session->getStart())->sub(new \DateInterval('P1D')); - - //Cancel application - $application->setCanceled($canceled); - - //Update time - $application->setUpdated($datetime); - - //Queue application save - $manager->persist($application); - - //Add notice in flash message - $this->addFlash('notice', $this->translator->trans('Application %id% updated', ['%id%' => $application->getId()])); - //Update time - $session->setUpdated($datetime); - - //Queue session save - $manager->persist($session); - - //Add notice in flash message - $this->addFlash('notice', $this->translator->trans('Session %id% updated', ['%id%' => $id])); - //Not attributed - } else { - //Add notice in flash message - $this->addFlash('warning', $this->translator->trans('Session %id% not updated', ['%id%' => $id])); + //With cities + if (!empty($this->context['cities'])) { + //Set locations + $locations = []; + + //Iterate on each cities + foreach($this->context['cities'] as $city) { + //Iterate on each locations + foreach($city['locations'] as $location) { + //Add location + $locations[$location['id']] = $location; } - //Not enough rainfall - } else { - //Add notice in flash message - $this->addFlash('warning', $this->translator->trans('Session %id% not updated', ['%id%' => $id])); } - //With modify - } elseif ($form->has('modify') && $form->get('modify')->isClicked()) { - //Set begin - $session->setBegin($data['begin']); - - //Set length - $session->setLength($data['length']); - - //Update time - $session->setUpdated($datetime); - - //Queue session save - $manager->persist($session); - - //Add notice in flash message - $this->addFlash('notice', $this->translator->trans('Session %id% updated', ['%id%' => $id])); - //With move - } elseif ($form->has('move') && $form->get('move')->isClicked()) { - //Set location - $session->setLocation($doctrine->getRepository(Location::class)->findOneById($data['location'])); - //Update time - $session->setUpdated($datetime); + //Add multi + $this->context['multimap'] = $this->map->getMultiMap($this->translator->trans('Libre Air cities sector map'), $this->modified->getTimestamp(), $locations); - //Queue session save - $manager->persist($session); + //Set cities + $cities = array_map(function ($v) { return $v['in']; }, $this->context['cities']); - //Add notice in flash message - $this->addFlash('notice', $this->translator->trans('Session %id% updated', ['%id%' => $id])); - //With cancel - } elseif ($form->has('cancel') && $form->get('cancel')->isClicked()) { - //Get application - $application = $doctrine->getRepository(Application::class)->findOneBySessionUser($session, $user); + //Set dances + $dances = array_map(function ($v) { return $v['name']; }, $this->context['dances']); + } else { + //Set cities + $cities = []; - //Not already canceled - if ($application->getCanceled() === null) { - //Cancel application - $application->setCanceled($datetime); - - //Check if application is session application - if ($session->getApplication() == $application) { - //Unattribute session - $session->setApplication(null); - - //Update time - $session->setUpdated($datetime); + //Set dances + $dances = []; + } - //Queue session save - $manager->persist($session); + //Set keywords + //TODO: use splice instead of that shit !!! + //TODO: handle smartly indoor and outdoor !!! + $this->context['keywords'] = array_values( + array_merge( + $dances, + $cities, + [ + $this->translator->trans('indoor'), + $this->translator->trans('outdoor'), + $this->translator->trans('sessions'), + $this->translator->trans('session list'), + $this->translator->trans('listing'), + $this->translator->trans('Libre Air') + ] + ) + ); - //Add notice in flash message - $this->addFlash('notice', $this->translator->trans('Session %id% updated', ['%id%' => $id])); - } - //Already canceled - } else { - //Uncancel application - $application->setCanceled(null); - } + //Get textual cities + $cities = implode($this->translator->trans(' and '), array_filter(array_merge([implode(', ', array_slice($cities, 0, -1))], array_slice($cities, -1)), 'strlen')); - //Update time - $application->setUpdated($datetime); + //Get textual dances + $dances = implode($this->translator->trans(' and '), array_filter(array_merge([implode(', ', array_slice($dances, 0, -1))], array_slice($dances, -1)), 'strlen')); - //Queue application save - $manager->persist($application); + //Set title + $this->context['title'] = $this->translator->trans('%dances% %cities% sessions', ['%dances%' => $dances, '%cities%' => $cities]); - //Add notice in flash message - $this->addFlash('notice', $this->translator->trans('Application %id% updated', ['%id%' => $application->getId()])); - //With attribute - } elseif ($form->has('attribute') && $form->get('attribute')->isClicked()) { - //Get application - $application = $doctrine->getRepository(Application::class)->findOneBySessionUser($session, $user); + //Set description + $this->context['description'] = $this->translator->trans('%dances% indoor and outdoor session calendar %cities%', ['%dances%' => $dances, '%cities%' => $cities]); - //Already canceled - if ($application->getCanceled() !== null) { - //Uncancel application - $application->setCanceled(null); - } + //Render the view + return $this->render('@RapsysAir/session/index.html.twig', $this->context); + } - //Set score - //XXX: magic cheat score 42 - $application->setScore(42); + /** + * List all sessions for tango argentin + * + * @desc Display all sessions in tango argentin json format + * + * @todo Drop it if unused by tangoargentin ??? + * + * @param Request $request The request instance + * + * @return Response The rendered view or redirection + */ + public function tangoargentin(Request $request): Response { + //Retrieve events to update + $sessions = $this->doctrine->getRepository(Session::class)->findAllByPeriodAsCalendarArray($this->period); + + //Init return array + $ret = []; + + //Flatten sessions tree + $sessions = array_reduce($sessions, function ($c, $v) { return array_merge($c, $v['sessions']); }, []); + + //Iterate on sessions + foreach($sessions as $sessionId => $session) { + //Set route params + $routeParams = $this->router->match($session['link']); + + //Set route + $route = $routeParams['_route']; + + //Drop _route from route params + unset($routeParams['_route']); + + //Add session + $ret[$session['id']] = [ + 'start' => $session['start']->format(\DateTime::ISO8601), + 'stop' => $session['start']->format(\DateTime::ISO8601), + 'fromto' => $this->translator->trans('from %start% to %stop%', ['%start%' => $session['start']->format('H\hi'), '%stop%' => $session['stop']->format('H\hi')]), + 'title' => $this->slugger->latin($session['application']['user']['title'])/*.' '.$this->translator->trans('at '.$session['location']['title'])*/, + 'short' => $session['rate']['short'], + 'rate' => $session['rate']['title'], + 'location' => implode(' ', [$session['location']['address'], $session['location']['zipcode'], $session['location']['city']]), + 'status' => in_array('canceled', $session['class'])?'annulé':'confirmé', + 'modified' => $session['modified']->format(\DateTime::ISO8601), + #'organizer' => $session['application']['user']['title'], + #'source' => $this->router->generate('rapsys_air_session_view', ['id' => $sessionId, 'location' => $this->translator->trans($session['l_title'])], UrlGeneratorInterface::ABSOLUTE_URL) + 'source' => $this->router->generate($route, $routeParams, UrlGeneratorInterface::ABSOLUTE_URL) + ]; + } - //Update time - $application->setUpdated($datetime); + //Set response + $response = new Response(json_encode($ret)); - //Queue application save - $manager->persist($application); + //Set header + $response->headers->set('Content-Type', 'application/json'); - //Add notice in flash message - $this->addFlash('notice', $this->translator->trans('Application %id% updated', ['%id%' => $application->getId()])); + //Send response + return $response; + } - //Unattribute session - $session->setApplication($application); + /** + * Display session + * + * @todo XXX: TODO: add + * @todo XXX: TODO: like described in: https://www.alsacreations.com/article/lire/1400-attribut-rel-relations.html#xnf-rel-attribute + * @todo XXX: TODO: or here: http://microformats.org/wiki/existing-rel-values#HTML5_link_type_extensions + * + * @todo: generate a background from @RapsysAir/Resources/public/location/.png or @RapsysAir/Resources/public/location//.png when available + * + * @todo: generate a share picture @RapsysAir/seance/363/place-saint-sulpice/bal-et-cours-de-tango-argentin/milonga-raphael/share.jpeg ? + * (with date, organiser, type, location, times and logo ?) + * + * @todo: add picture stuff about location ??? + * + * @param Request $request The request instance + * @param int $id The session id + * + * @return Response The rendered view + * + * @throws NotFoundHttpException When session is not found + */ + public function view(Request $request, int $id): Response { + //Fetch session + if (empty($this->context['session'] = $this->doctrine->getRepository(Session::class)->findOneByIdAsArray($id))) { + //Session not found + throw $this->createNotFoundException($this->translator->trans('Unable to find session: %id%', ['%id%' => $id])); + } - //Update time - $session->setUpdated($datetime); + //Get locations at less than 1 km + $this->context['locations'] = $this->doctrine->getRepository(Location::class)->findAllByLatitudeLongitudeAsArray($this->context['session']['location']['latitude'], $this->context['session']['location']['longitude'], $this->period, 2); - //Queue session save - $manager->persist($session); + //Set modified + //XXX: dance modified is already computed inside calendar modified + $this->modified = max(array_merge([$this->context['session']['modified']], array_map(function ($v) { return $v['modified']; }, $this->context['locations']))); - //Add notice in flash message - $this->addFlash('notice', $this->translator->trans('Session %id% updated', ['%id%' => $id])); - //With autoattribute - } elseif ($form->has('autoattribute') && $form->get('autoattribute')->isClicked()) { - //Get best application - //XXX: best application may not issue result while grace time or bad behaviour - if (!empty($application = $doctrine->getRepository(Session::class)->findBestApplicationById($id))) { - //Attribute session - $session->setApplication($application); + //Create response + $response = new Response(); - //Update time - $session->setUpdated($datetime); + //With logged user + if ($this->checker->isGranted('IS_AUTHENTICATED_REMEMBERED')) { + //Set last modified + $response->setLastModified(new \DateTime('-1 year')); - //Queue session save - $manager->persist($session); + //Set as private + $response->setPrivate(); + //Without logged user + } else { + //Set etag + //XXX: only for public to force revalidation by last modified + $response->setEtag(md5(serialize(array_merge($this->context['session'], $this->context['locations'])))); - //Add notice in flash message - $this->addFlash('notice', $this->translator->trans('Session %id% updated', ['%id%' => $id])); - //No application - } else { - //Add notice in flash message - $this->addFlash('warning', $this->translator->trans('Session %id% not updated', ['%id%' => $id])); - } - //With lock - } elseif ($form->has('lock') && $form->get('lock')->isClicked()) { - //Already locked - if ($session->getLocked() !== null) { - //Set uncanceled - $canceled = null; - - //Unlock session - $session->setLocked(null); - //Not locked - } else { - //Set canceled time at start minus one day - $canceled = (clone $session->getStart())->sub(new \DateInterval('P1D')); + //Set last modified + $response->setLastModified($this->modified); - //Unattribute session - $session->setApplication(null); + //Set as public + $response->setPublic(); - //Lock session - $session->setLocked($datetime); + //Without role and modification + if ($response->isNotModified($request)) { + //Return 304 response + return $response; } + } - //Get applications - $applications = $doctrine->getRepository(Application::class)->findBySession($session); + //Get route + $route = $request->attributes->get('_route'); - //Not empty - if (!empty($applications)) { - //Iterate on each applications - foreach($applications as $application) { - //Cancel application - $application->setCanceled($canceled); + //Get route params + $routeParams = $request->attributes->get('_route_params'); - //Update time - $application->setUpdated($datetime); + //Disable redirect + $redirect = false; - //Queue application save - $manager->persist($application); + //Without location or invalid location + if (empty($routeParams['location']) || $this->context['session']['location']['slug'] !== $routeParams['location']) { + //Set location + $routeParams['location'] = $this->context['session']['location']['slug']; - //Add notice in flash message - $this->addFlash('notice', $this->translator->trans('Application %id% updated', ['%id%' => $application->getId()])); - } - } + //Enable redirect + $redirect = true; + } - //Update time - $session->setUpdated($datetime); + //With dance slug without dance or invalid dance + if (!empty($this->context['session']['application']['dance']['slug']) && (empty($routeParams['dance']) || $this->context['session']['application']['dance']['slug'] !== $routeParams['dance'])) { + //Set dance + $routeParams['dance'] = $this->context['session']['application']['dance']['slug']; - //Queue session save - $manager->persist($session); + //Enable redirect + $redirect = true; + //Without dance slug with dance + } elseif (empty($this->context['session']['application']['dance']['slug']) && !empty($routeParams['dance'])) { + //Set dance + unset($routeParams['dance']); - //Add notice in flash message - $this->addFlash('notice', $this->translator->trans('Session %id% updated', ['%id%' => $id])); + //Enable redirect + $redirect = true; } - //Flush to get the ids - $manager->flush(); - - //Extract and process referer - if ($referer = $request->headers->get('referer')) { - //Create referer request instance - $req = Request::create($referer); - - //Get referer path - $path = $req->getPathInfo(); + //With user slug without user or invalid user + if (!empty($this->context['session']['application']['user']['slug']) && (empty($routeParams['user']) || $this->context['session']['application']['user']['slug'] !== $routeParams['user'])) { + //Set user + $routeParams['user'] = $this->context['session']['application']['user']['slug']; - //Get referer query string - $query = $req->getQueryString(); + //Enable redirect + $redirect = true; + //Without user slug with user + } elseif (empty($this->context['session']['application']['user']['slug']) && !empty($routeParams['user'])) { + //Set user + unset($routeParams['user']); - //Remove script name - $path = str_replace($request->getScriptName(), '', $path); + //Enable redirect + $redirect = true; + } - //Try with referer path - try { - //Save old context - $oldContext = $this->router->getContext(); + //With redirect + if ($redirect) { + //Redirect to route + return $this->redirectToRoute($route, $routeParams, $this->context['session']['stop'] <= new \DateTime('now') ? Response::HTTP_MOVED_PERMANENTLY : Response::HTTP_FOUND); + } - //Force clean context - //XXX: prevent MethodNotAllowedException because current context method is POST in onevendor/symfony/routing/Matcher/Dumper/CompiledUrlMatcherTrait.php+42 - $this->router->setContext(new RequestContext()); + //Add map + $this->context['map'] = $this->map->getMap($this->context['session']['location']['map'], $this->modified->getTimestamp(), $this->context['session']['location']['latitude'], $this->context['session']['location']['longitude']); - //Retrieve route matching path - $route = $this->router->match($path); + //Add multi map + $this->context['multimap'] = $this->map->getMultiMap($this->context['session']['location']['multimap'], $this->modified->getTimestamp(), $this->context['locations']); - //Reset context - $this->router->setContext($oldContext); + //Set canonical + $this->context['canonical'] = $this->context['session']['canonical']; - //Clear old context - unset($oldContext); + //Set alternates + $this->context['alternates'] = $this->context['session']['alternates']; - //Extract name - $name = $route['_route']; + //Set localization date formater + $intlDate = new \IntlDateFormatter($this->locale, \IntlDateFormatter::TRADITIONAL, \IntlDateFormatter::NONE); - //Remove route and controller from route defaults - unset($route['_route'], $route['_controller']); + //Set localization time formater + $intlTime = new \IntlDateFormatter($this->locale, \IntlDateFormatter::NONE, \IntlDateFormatter::SHORT); - //Generate url - return $this->redirectToRoute($name, ['session' => $id]+$route); - //No route matched - } catch(MethodNotAllowedException|ResourceNotFoundException $e) { - //Unset referer to fallback to default route - unset($referer); - } + //With application + if (!empty($this->context['session']['application'])) { + //Set title + $this->context['title'] = $this->translator->trans('%dance% %id% by %pseudonym%', ['%id%' => $id, '%dance%' => $this->context['session']['application']['dance']['title'], '%pseudonym%' => $this->context['session']['application']['user']['title']]); + + //Set description + $this->context['description'] = ucfirst($this->translator->trans('%dance% %location% %city% %slot% on %date% at %time%', [ + '%dance%' => $this->context['session']['application']['dance']['title'], + '%location%' => $this->context['session']['location']['at'], + '%city%' => $this->context['session']['location']['in'], + '%slot%' => $this->context['session']['slot']['the'], + '%date%' => $intlDate->format($this->context['session']['start']), + '%time%' => $intlTime->format($this->context['session']['start']), + ])); + + //Set keywords + //TODO: readd outdoor ??? + $this->context['keywords'] = [ + $this->context['session']['application']['dance']['type'], + $this->context['session']['application']['dance']['name'], + $this->context['session']['location']['title'], + $this->context['session']['application']['user']['title'], + $this->translator->trans($this->context['session']['location']['indoor']?'indoor':'outdoor') + ]; + //Without application + } else { + //Set title + $this->context['title'] = $this->translator->trans('Session %id%', ['%id%' => $id]); + + //Set description + $this->context['description'] = ucfirst($this->translator->trans('%location% %city% %slot% on %date% at %time%', [ + '%city%' => ucfirst($this->context['session']['location']['in']), + '%location%' => $this->context['session']['location']['at'], + '%slot%' => $this->context['session']['slot']['the'], + '%date%' => $intlDate->format($this->context['session']['start']), + '%time%' => $intlTime->format($this->context['session']['start']) + ])); + + //Add dance type + //TODO: readd outdoor ??? + $this->context['keywords'] = [ + $this->context['session']['location']['title'], + $this->translator->trans($this->context['session']['location']['indoor']?'indoor':'outdoor') + ]; } - //Redirect to cleanup the form - return $this->redirectToRoute('rapsys_air_session_view', ['id' => $id]); - - //Protect session fetching - try { - //Fetch session - $session = $doctrine->getRepository(Session::class)->findOneById($id); - - //Fetch session - $session = $doctrine->getRepository(Session::class)->findOneByLocationSlotDate($data['location'], $data['slot'], $data['date']); - //Catch no session case - } catch (\Doctrine\ORM\NoResultException $e) { - //Create the session - $session = new Session(); - $session->setLocation($data['location']); - $session->setDate($data['date']); - $session->setSlot($data['slot']); - $session->setCreated(new \DateTime('now')); - $session->setUpdated(new \DateTime('now')); - - //Get short location - $short = $data['location']->getShort(); - - //Get slot - $slot = $data['slot']->getTitle(); - - //Set premium - $session->setPremium($premium = false); - - //Check if slot is afternoon - //XXX: premium is stored only for Afternoon and Evening - if ($slot == 'Afternoon') { - //Compute premium - //XXX: a session is considered premium a day off - $session->setPremium($premium = $this->isPremium($data['date'])); - //Check if slot is evening - //XXX: premium is stored only for Afternoon and Evening - } elseif ($slot == 'Evening') { - //Compute premium - //XXX: a session is considered premium the eve of a day off - $session->setPremium($premium = $this->isPremium((clone $data['date'])->add(new \DateInterval('P1D')))); - //Check if slot is after - } elseif ($slot == 'After') { - //Compute premium - //XXX: a session is considered premium the eve of a day off - $premium = $this->isPremium((clone $data['date'])->add(new \DateInterval('P1D'))); - } + //Set section + $this->context['section'] = $this->context['session']['location']['title']; - //Set default length at 6h - //XXX: date part will be truncated on save - $session->setLength(new \DateTime('06:00:00')); - - //Check if admin - if ($this->isGranted('ROLE_ADMIN')) { - //Check if morning - if ($slot == 'Morning') { - //Set begin at 9h - $session->setBegin(new \DateTime('09:00:00')); - - //Set length at 5h - $session->setLength(new \DateTime('05:00:00')); - //Check if afternoon - } elseif ($slot == 'Afternoon') { - //Set begin at 14h - $session->setBegin(new \DateTime('14:00:00')); - - //Set length at 5h - $session->setLength(new \DateTime('05:00:00')); - //Check if evening - } elseif ($slot == 'Evening') { - //Set begin at 19h - $session->setBegin(new \DateTime('19:00:00')); - - //Check if next day is premium - if ($premium) { - //Set length at 7h - $session->setLength(new \DateTime('07:00:00')); - } - //Check if after - } else { - //Set begin at 1h - $session->setBegin(new \DateTime('01:00:00')); + //Set facebook title + $this->context['facebook']['metas']['og:title'] = $this->context['title'].' '.$this->context['session']['location']['at']; - //Set length at 4h - $session->setLength(new \DateTime('04:00:00')); + //Set facebook image + $this->context['facebook'] = [ + 'texts' => [ + $this->context['session']['application']['user']['title']??$this->context['title'] => [ + 'font' => 'irishgrover', + 'size' => 110 + ], + ucfirst($intlDate->format($this->context['session']['start']))."\n".$this->translator->trans('Around %start% until %stop%', ['%start%' => $intlTime->format($this->context['session']['start']), '%stop%' => $intlTime->format($this->context['session']['stop'])]) => [ + 'font' => 'irishgrover', + 'align' => 'left' + ], + $this->context['session']['location']['at'] => [ + 'align' => 'right', + 'font' => 'labelleaurore', + 'size' => 75 + ] + ], + 'updated' => $this->context['session']['updated']->format('U') + ]+$this->context['facebook']; - //Check if next day is premium - if ($premium) { - //Set begin at 2h - $session->setBegin(new \DateTime('02:00:00')); + //Create application form for role_guest + if ($this->checker->isGranted('ROLE_GUEST')) { + //Set now + $now = new \DateTime('now'); - //Set length at 3h - $session->setLength(new \DateTime('03:00:00')); - } - } - //Docks => 14h -> 19h | 19h -> 01/02h - //XXX: remove Garnier from here to switch back to 21h - } elseif (in_array($short, ['Docks', 'Garnier']) && in_array($slot, ['Afternoon', 'Evening', 'After'])) { - //Check if afternoon - if ($slot == 'Afternoon') { - //Set begin at 14h - $session->setBegin(new \DateTime('14:00:00')); - - //Set length at 5h - $session->setLength(new \DateTime('05:00:00')); - //Check if evening - } elseif ($slot == 'Evening') { - //Set begin at 19h - $session->setBegin(new \DateTime('19:00:00')); - - //Check if next day is premium - if ($premium) { - //Set length at 7h - $session->setLength(new \DateTime('07:00:00')); - } - //Check if after - } else { - //Set begin at 1h - $session->setBegin(new \DateTime('01:00:00')); + //Default favorites and dances + $danceFavorites = $dances = []; + //Default dance + $danceDefault = null; - //Set length at 4h - $session->setLength(new \DateTime('04:00:00')); + //With admin + if ($this->checker->isGranted('ROLE_ADMIN')) { + //Get favorites dances + $danceFavorites = $this->doctrine->getRepository(Dance::class)->findByUserId($this->getUser()->getId()); - //Check if next day is premium - if ($premium) { - //Set begin at 2h - $session->setBegin(new \DateTime('02:00:00')); + //Get dances + $dances = $this->doctrine->getRepository(Dance::class)->findAllIndexed(); - //Set length at 3h - $session->setLength(new \DateTime('03:00:00')); - } - } - //Garnier => 21h -> 01/02h - } elseif ($short == 'Garnier' && in_array($slot, ['Evening', 'After'])) { - //Check if evening - if ($slot == 'Evening') { - //Set begin at 21h - $session->setBegin(new \DateTime('21:00:00')); - - //Set length at 5h - $session->setLength(new \DateTime('05:00:00')); - - //Check if next day is premium - if ($premium) { - //Set length at 6h - $session->setLength(new \DateTime('06:00:00')); - } - //Check if after - } else { - //Set begin at 1h - $session->setBegin(new \DateTime('01:00:00')); + //Set dance default + $danceDefault = !empty($this->context['session']['application'])?$dances[$this->context['session']['application']['dance']['id']]:null; + } - //Set length at 4h - $session->setLength(new \DateTime('04:00:00')); + //Create SessionType form + //TODO: move to named form ??? + $sessionForm = $this->createForm('Rapsys\AirBundle\Form\SessionType', null, [ + //Set the action + 'action' => $this->generateUrl('rapsys_air_session_view', ['id' => $id, 'location' => $this->context['session']['location']['slug'], 'dance' => $this->context['session']['application']['dance']['slug']??null, 'user' => $this->context['session']['application']['user']['slug']??null]), + //Set the form attribute + 'attr' => [ 'class' => 'col' ], + //Set admin + 'admin' => $this->checker->isGranted('ROLE_ADMIN'), + //Set dance choices + 'dance_choices' => $dances, + //Set dance default + 'dance_default' => $danceDefault, + //Set dance favorites + 'dance_favorites' => $danceFavorites, + //Set to session slot or evening by default + //XXX: default to Evening (3) + 'slot_default' => $this->doctrine->getRepository(Slot::class)->findOneById($this->context['session']['slot']['id']??3), + //Set default user to current + 'user' => $this->getUser()->getId(), + //Set date + 'date' => $this->context['session']['date'], + //Set begin + 'begin' => $this->context['session']['begin'], + //Set length + 'length' => $this->context['session']['length'], + //Set raincancel + 'raincancel' => ($this->checker->isGranted('ROLE_ADMIN') || !empty($this->context['session']['application']['user']['id']) && $this->getUser()->getId() == $this->context['session']['application']['user']['id']) && $this->context['session']['rainfall'] >= 2, + //Set cancel + 'cancel' => $this->checker->isGranted('ROLE_ADMIN') || in_array($this->getUser()->getId(), explode("\n", $this->context['session']['sau_id'])), + //Set modify + 'modify' => $this->checker->isGranted('ROLE_ADMIN') || !empty($this->context['session']['application']['user']['id']) && $this->getUser()->getId() == $this->context['session']['application']['user']['id'] && $this->context['session']['stop'] >= $now && $this->checker->isGranted('ROLE_REGULAR'), + //Set move + 'move' => $this->checker->isGranted('ROLE_ADMIN') || !empty($this->context['session']['application']['user']['id']) && $this->getUser()->getId() == $this->context['session']['application']['user']['id'] && $this->context['session']['stop'] >= $now && $this->checker->isGranted('ROLE_SENIOR'), + //Set attribute + 'attribute' => $this->checker->isGranted('ROLE_ADMIN') && $this->context['session']['locked'] === null, + //Set session + 'session' => $this->context['session']['id'] + ]); - //Check if next day is premium - if ($premium) { - //Set begin at 2h - $session->setBegin(new \DateTime('02:00:00')); + //Refill the fields in case of invalid form + $sessionForm->handleRequest($request); - //Set length at 3h - $session->setLength(new \DateTime('03:00:00')); - } - } - //Trocadero|Tokyo|Swan|Honore|Orsay => 19h -> 01/02h - } elseif (in_array($short, ['Trocadero', 'Tokyo', 'Swan', 'Honore', 'Orsay']) && in_array($slot, ['Evening', 'After'])) { - //Check if evening - if ($slot == 'Evening') { - //Set begin at 19h - $session->setBegin(new \DateTime('19:00:00')); - - //Check if next day is premium - if ($premium) { - //Set length at 7h - $session->setLength(new \DateTime('07:00:00')); - } - //Check if after - } else { - //Set begin at 1h - $session->setBegin(new \DateTime('01:00:00')); + //With submitted form + if ($sessionForm->isSubmitted() && $sessionForm->isValid()) { + //Get data + $data = $sessionForm->getData(); - //Set length at 4h - $session->setLength(new \DateTime('04:00:00')); + //Fetch session + $sessionObject = $this->doctrine->getRepository(Session::class)->findOneById($id); - //Check if next day is premium - if ($premium) { - //Set begin at 2h - $session->setBegin(new \DateTime('02:00:00')); + //Set user + $userObject = $this->getUser(); - //Set length at 3h - $session->setLength(new \DateTime('03:00:00')); - } + //Replace with requested user for admin + if ($this->checker->isGranted('ROLE_ADMIN') && !empty($data['user'])) { + $userObject = $this->doctrine->getRepository(User::class)->findOneById($data['user']); } - //La Villette => 14h -> 19h - } elseif ($short == 'Villette' && $slot == 'Afternoon') { - //Set begin at 14h - $session->setBegin(new \DateTime('14:00:00')); - - //Set length at 5h - $session->setLength(new \DateTime('05:00:00')); - //Place Colette => 14h -> 21h - //TODO: add check here that it's a millegaux account ? - } elseif ($short == 'Colette' && $slot == 'Afternoon') { - //Set begin at 14h - $session->setBegin(new \DateTime('14:00:00')); - - //Set length at 7h - $session->setLength(new \DateTime('07:00:00')); - //Galerie d'Orléans => 14h -> 18h - } elseif ($short == 'Orleans' && $slot == 'Afternoon') { - //Set begin at 14h - $session->setBegin(new \DateTime('14:00:00')); - - //Set length at 4h - $session->setLength(new \DateTime('04:00:00')); - //Combination not supported - } else { - //Add error in flash message - $this->addFlash('error', $this->translator->trans('Session on %date% %location% %slot% not yet supported', ['%location%' => $this->translator->trans('at '.$data['location']), '%slot%' => $this->translator->trans('the '.strtolower($data['slot'])), '%date%' => $data['date']->format('Y-m-d')])); - } - //Queue session save - $manager->persist($session); + //Set datetime + $datetime = new \DateTime('now'); - //Flush to get the ids - #$manager->flush(); + //Set canceled time at start minus one day + $canceled = (clone $sessionObject->getStart())->sub(new \DateInterval('P1D')); + + //Set action + $action = [ + 'raincancel' => $sessionForm->has('raincancel') && $sessionForm->get('raincancel')->isClicked(), + 'modify' => $sessionForm->has('modify') && $sessionForm->get('modify')->isClicked(), + 'move' => $sessionForm->has('move') && $sessionForm->get('move')->isClicked(), + 'cancel' => $sessionForm->has('cancel') && $sessionForm->get('cancel')->isClicked(), + 'forcecancel' => $sessionForm->has('forcecancel') && $sessionForm->get('forcecancel')->isClicked(), + 'attribute' => $sessionForm->has('attribute') && $sessionForm->get('attribute')->isClicked(), + 'autoattribute' => $sessionForm->has('autoattribute') && $sessionForm->get('autoattribute')->isClicked(), + 'lock' => $sessionForm->has('lock') && $sessionForm->get('lock')->isClicked(), + ]; - $this->addFlash('notice', $this->translator->trans('Session on %date% %location% %slot% created', ['%location%' => $this->translator->trans('at '.$data['location']), '%slot%' => $this->translator->trans('the '.strtolower($data['slot'])), '%date%' => $data['date']->format('Y-m-d')])); - } + //With raincancel and application and (rainfall or admin) + if ($action['raincancel'] && ($application = $sessionObject->getApplication()) && ($sessionObject->getRainfall() >= 2 || $this->checker->isGranted('ROLE_ADMIN'))) { + //Cancel application at start minus one day + $application->setCanceled($canceled); - //Set user - $user = $this->getUser(); + //Update time + $application->setUpdated($datetime); - //Replace with requested user for admin - if ($this->isGranted('ROLE_ADMIN') && !empty($data['user'])) { - $user = $this->getDoctrine()->getRepository(User::class)->findOneById($data['user']); - } + //Insufficient rainfall + //XXX: is admin + if ($sessionObject->getRainfall() < 2) { + //Set score + //XXX: magic cheat score 42 + $application->setScore(42); + } - //Protect application fetching - try { - //Retrieve application - $application = $doctrine->getRepository(Application::class)->findOneBySessionUser($session, $user); + //Queue application save + $this->manager->persist($application); - //Add warning in flash message - $this->addFlash('warning', $this->translator->trans('Application on %date% %location% %slot% already exists', ['%location%' => $this->translator->trans('at '.$data['location']), '%slot%' => $this->translator->trans('the '.strtolower($data['slot'])), '%date%' => $data['date']->format('Y-m-d')])); - //Catch no application and session without identifier (not persisted&flushed) cases - } catch (\Doctrine\ORM\NoResultException|\Doctrine\ORM\ORMInvalidArgumentException $e) { - //Create the application - $application = new Application(); - $application->setSession($session); - $application->setUser($user); - $application->setCreated(new \DateTime('now')); - $application->setUpdated(new \DateTime('now')); + //Add notice in flash message + $this->addFlash('notice', $this->translator->trans('Application %id% updated', ['%id%' => $application->getId()])); - //Refresh session updated field - $session->setUpdated(new \DateTime('now')); + //Update time + $sessionObject->setUpdated($datetime); - //Queue session save - $manager->persist($session); + //Queue session save + $this->manager->persist($sessionObject); - //Queue application save - $manager->persist($application); + //Add notice in flash message + $this->addFlash('notice', $this->translator->trans('Session %id% updated', ['%id%' => $id])); + //With modify + } elseif ($action['modify']) { + //With admin + if ($this->checker->isGranted('ROLE_ADMIN')) { + //Get application + $application = $this->doctrine->getRepository(Application::class)->findOneBySessionUser($sessionObject, $userObject); - //Flush to get the ids - $manager->flush(); + //Set dance + $application->setDance($data['dance']); - //Add notice in flash message - $this->addFlash('notice', $this->translator->trans('Application on %date% %location% %slot% created', ['%location%' => $this->translator->trans('at '.$data['location']), '%slot%' => $this->translator->trans('the '.strtolower($data['slot'])), '%date%' => $data['date']->format('Y-m-d')])); - } - } + //Queue session save + $this->manager->persist($application); - /** - * List all sessions - * - * @desc Display all sessions with an application or login form - * - * @param Request $request The request instance - * - * @return Response The rendered view - */ - public function index(Request $request = null) { - //Fetch doctrine - $doctrine = $this->getDoctrine(); + //Set slot + $sessionObject->setSlot($data['slot']); - //Set section - $section = $this->translator->trans('Sessions'); + //Set date + $sessionObject->setDate($data['date']); + } - //Set title - $title = $section.' - '.$this->translator->trans($this->config['site']['title']); + //Set begin + $sessionObject->setBegin($data['begin']); - //Init context - $context = []; + //Set length + $sessionObject->setLength($data['length']); - //Create application form for role_guest - if ($this->isGranted('ROLE_GUEST')) { - //Create ApplicationType form - $application = $this->createForm('Rapsys\AirBundle\Form\ApplicationType', null, [ - //Set the action - 'action' => $this->generateUrl('rapsys_air_application_add'), - //Set the form attribute - 'attr' => [ 'class' => 'col' ], - //Set admin - 'admin' => $this->isGranted('ROLE_ADMIN'), - //Set default user to current - 'user' => $this->getUser()->getId(), - //Set default slot to evening - //XXX: default to Evening (3) - 'slot' => $doctrine->getRepository(Slot::class)->findOneById(3) - ]); + //Update time + $sessionObject->setUpdated($datetime); - //Add form to context - $context['application'] = $application->createView(); - //Create login form for anonymous - } elseif (!$this->isGranted('IS_AUTHENTICATED_REMEMBERED')) { - //Create ApplicationType form - $login = $this->createForm('Rapsys\UserBundle\Form\LoginType', null, [ - //Set the action - 'action' => $this->generateUrl('rapsys_user_login'), - //Set the form attribute - 'attr' => [ 'class' => 'col' ] - ]); + //Queue session save + $this->manager->persist($sessionObject); - //Add form to context - $context['login'] = $login->createView(); - } + //Add notice in flash message + $this->addFlash('notice', $this->translator->trans('Session %id% updated', ['%id%' => $id])); + //With move + } elseif ($action['move']) { + //Set location + $sessionObject->setLocation($this->doctrine->getRepository(Location::class)->findOneById($data['location'])); - //Compute period - $period = new \DatePeriod( - //Start from first monday of week - new \DateTime('Monday this week'), - //Iterate on each day - new \DateInterval('P1D'), - //End with next sunday and 4 weeks - new \DateTime('Monday this week + 5 week') - ); + //Update time + $sessionObject->setUpdated($datetime); - //Fetch calendar - //TODO: highlight with current session route parameter - $calendar = $doctrine->getRepository(Session::class)->fetchCalendarByDatePeriod($this->translator, $period, null, $request->get('session'), !$this->isGranted('IS_AUTHENTICATED_REMEMBERED')); + //Queue session save + $this->manager->persist($sessionObject); - //Fetch locations - //XXX: we want to display all active locations anyway - $locations = $doctrine->getRepository(Location::class)->fetchTranslatedLocationByDatePeriod($this->translator, $period/*, !$this->isGranted('IS_AUTHENTICATED_REMEMBERED')*/); + //Add notice in flash message + $this->addFlash('notice', $this->translator->trans('Session %id% updated', ['%id%' => $id])); + //With cancel or forcecancel + } elseif ($action['cancel'] || $action['forcecancel']) { + //Get application + $application = $this->doctrine->getRepository(Application::class)->findOneBySessionUser($sessionObject, $userObject); + + //Not already canceled + if ($application->getCanceled() === null) { + //Cancel application + $application->setCanceled($datetime); + + //Check if application is session application and (canceled 24h before start or forcecancel (as admin)) + #if ($sessionObject->getApplication() == $application && ($datetime < $canceled || $action['forcecancel'])) { + if ($sessionObject->getApplication() == $application && $action['forcecancel']) { + //Set score + //XXX: magic cheat score 42 + $application->setScore(42); + + //Unattribute session + $sessionObject->setApplication(null); + + //Update time + $sessionObject->setUpdated($datetime); + + //Queue session save + $this->manager->persist($sessionObject); + + //Add notice in flash message + $this->addFlash('notice', $this->translator->trans('Session %id% updated', ['%id%' => $id])); + } + //Already canceled + } else { + //Uncancel application + $application->setCanceled(null); + } - //Render the view - return $this->render('@RapsysAir/session/index.html.twig', ['title' => $title, 'section' => $section, 'calendar' => $calendar, 'locations' => $locations]+$context+$this->context); - } + //Update time + $application->setUpdated($datetime); - /** - * Display session - * - * @desc Display session by id with an application or login form - * - * @param Request $request The request instance - * @param int $id The session id - * - * @return Response The rendered view - */ - public function view(Request $request, $id) { - //Fetch doctrine - $doctrine = $this->getDoctrine(); + //Queue application save + $this->manager->persist($application); - //Fetch session - $session = $doctrine->getRepository(Session::class)->fetchOneById($id); + //Add notice in flash message + $this->addFlash('notice', $this->translator->trans('Application %id% updated', ['%id%' => $application->getId()])); + //With attribute + } elseif ($action['attribute']) { + //Get application + $application = $this->doctrine->getRepository(Application::class)->findOneBySessionUser($sessionObject, $userObject); - //Set section - $section = $this->translator->trans($session['l_title']); + //Already canceled + if ($application->getCanceled() !== null) { + //Uncancel application + $application->setCanceled(null); + } - //Set title - $title = $this->translator->trans('Session %id%', ['%id%' => $id]).' - '.$section.' - '.$this->translator->trans($this->config['site']['title']); + //Set score + //XXX: magic cheat score 42 + $application->setScore(42); - //Init context - $context = []; + //Update time + $application->setUpdated($datetime); - //Create application form for role_guest - if ($this->isGranted('ROLE_GUEST')) { - //Create ApplicationType form - $application = $this->createForm('Rapsys\AirBundle\Form\ApplicationType', null, [ - //Set the action - 'action' => $this->generateUrl('rapsys_air_application_add'), - //Set the form attribute - 'attr' => [ 'class' => 'col' ], - //Set admin - 'admin' => $this->isGranted('ROLE_ADMIN'), - //Set default user to current - 'user' => $this->getUser()->getId(), - //Set default slot to current - 'slot' => $this->getDoctrine()->getRepository(Slot::class)->findOneById($session['t_id']), - //Set default location to current - 'location' => $this->getDoctrine()->getRepository(Location::class)->findOneById($session['l_id']), - ]); + //Queue application save + $this->manager->persist($application); - //Add form to context - $context['application'] = $application->createView(); + //Add notice in flash message + $this->addFlash('notice', $this->translator->trans('Application %id% updated', ['%id%' => $application->getId()])); - //Set now - $now = new \DateTime('now'); + //Unattribute session + $sessionObject->setApplication($application); - //Create SessionEditType form - $session_edit = $this->createForm('Rapsys\AirBundle\Form\SessionEditType', null, [ - //Set the action - 'action' => $this->generateUrl('rapsys_air_session_edit', [ 'id' => $id ]), - //Set the form attribute - 'attr' => [ 'class' => 'col' ], - //Set admin - 'admin' => $this->isGranted('ROLE_ADMIN'), - //Set default user to current - 'user' => $this->getUser()->getId(), - //Set begin - 'begin' => $session['begin'], - //Set length - 'length' => $session['length'], - //Set raincancel - 'raincancel' => $this->isGranted('ROLE_ADMIN') || $this->getUser()->getId() == $session['au_id'] && $session['rainfall'] >= 2, - //Set cancel - 'cancel' => $this->isGranted('ROLE_ADMIN') || in_array($this->getUser()->getId(), explode("\n", $session['sau_id'])), - //Set modify - 'modify' => $this->isGranted('ROLE_ADMIN') || $this->getUser()->getId() == $session['au_id'] && $session['stop'] >= $now && $this->isGranted('ROLE_REGULAR'), - //Set move - 'move' => $this->isGranted('ROLE_ADMIN') || $this->getUser()->getId() == $session['au_id'] && $session['stop'] >= $now && $this->isGranted('ROLE_SENIOR'), - //Set session - 'session' => $session['id'] - ]); + //Update time + $sessionObject->setUpdated($datetime); - //Add form to context - $context['session_edit'] = $session_edit->createView(); - //Create login form for anonymous - } elseif (!$this->isGranted('IS_AUTHENTICATED_REMEMBERED')) { - //Create ApplicationType form - $login = $this->createForm('Rapsys\UserBundle\Form\LoginType', null, [ - //Set the action - 'action' => $this->generateUrl('rapsys_user_login'), - //Set the form attribute - 'attr' => [ 'class' => 'col' ] - ]); + //Queue session save + $this->manager->persist($sessionObject); - //Add form to context - $context['login'] = $login->createView(); - } + //Add notice in flash message + $this->addFlash('notice', $this->translator->trans('Session %id% updated', ['%id%' => $id])); + //With autoattribute + } elseif ($action['autoattribute']) { + //Get best application + //XXX: best application may not issue result while grace time or bad behaviour + if (!empty($application = $this->doctrine->getRepository(Session::class)->findBestApplicationById($id))) { + //Attribute session + $sessionObject->setApplication($application); + + //Update time + $sessionObject->setUpdated($datetime); + + //Queue session save + $this->manager->persist($sessionObject); + + //Add notice in flash message + $this->addFlash('notice', $this->translator->trans('Session %id% auto attributed', ['%id%' => $id])); + //No application + } else { + //Add warning in flash message + $this->addFlash('warning', $this->translator->trans('Session %id% not auto attributed', ['%id%' => $id])); + } + //With lock + } elseif ($action['lock']) { + //Already locked + if ($sessionObject->getLocked() !== null) { + //Set uncanceled + $canceled = null; + + //Unlock session + $sessionObject->setLocked(null); + //Not locked + } else { + //Get application + if ($application = $sessionObject->getApplication()) { + //Set score + //XXX: magic cheat score 42 + $application->setScore(42); + + //Update time + $application->setUpdated($datetime); + + //Queue application save + $this->manager->persist($application); + + //Add notice in flash message + $this->addFlash('notice', $this->translator->trans('Application %id% updated', ['%id%' => $application->getId()])); + } + + //Unattribute session + $sessionObject->setApplication(null); + + //Lock session + $sessionObject->setLocked($datetime); + } - //Add session in context - $context['session'] = [ - 'id' => $id, - 'date' => $session['date'], - 'begin' => $session['begin'], - 'start' => $session['start'], - 'length' => $session['length'], - 'stop' => $session['stop'], - 'rainfall' => $session['rainfall'] !== null ? $session['rainfall'].' mm' : $session['rainfall'], - 'rainrisk' => $session['rainrisk'] !== null ? ($session['rainrisk']*100).' %' : $session['rainrisk'], - 'realfeel' => $session['realfeel'] !== null ? $session['realfeel'].' °C' : $session['realfeel'], - 'realfeelmin' => $session['realfeelmin'] !== null ? $session['realfeelmin'].' °C' : $session['realfeelmin'], - 'realfeelmax' => $session['realfeelmax'] !== null ? $session['realfeelmax'].' °C' : $session['realfeelmax'], - 'temperature' => $session['temperature'] !== null ? $session['temperature'].' °C' : $session['temperature'], - 'temperaturemin' => $session['temperaturemin'] !== null ? $session['temperaturemin'].' °C' : $session['temperaturemin'], - 'temperaturemax' => $session['temperaturemax'] !== null ? $session['temperaturemax'].' °C' : $session['temperaturemax'], - 'locked' => $session['locked'], - 'created' => $session['created'], - 'updated' => $session['updated'], - 'title' => $this->translator->trans('Session %id%', ['%id%' => $id]), - 'application' => null, - 'location' => [ - 'id' => $session['l_id'], - 'at' => $this->translator->trans('at '.$session['l_title']), - 'short' => $this->translator->trans($session['l_short']), - 'title' => $this->translator->trans($session['l_title']), - 'address' => $session['l_address'], - 'zipcode' => $session['l_zipcode'], - 'city' => $session['l_city'], - 'latitude' => $session['l_latitude'], - 'longitude' => $session['l_longitude'] - ], - 'slot' => [ - 'id' => $session['t_id'], - 'title' => $this->translator->trans($session['t_title']) - ], - 'applications' => null - ]; + //Update time + $sessionObject->setUpdated($datetime); - //With application - if (!empty($session['a_id'])) { - $context['session']['application'] = [ - 'user' => [ - 'id' => $session['au_id'], - 'title' => $session['au_pseudonym'] - ], - 'id' => $session['a_id'], - 'title' => $this->translator->trans('Application %id%', [ '%id%' => $session['a_id'] ]), - ]; - } + //Queue session save + $this->manager->persist($sessionObject); - //With applications - if (!empty($session['sa_id'])) { - //Extract applications id - $session['sa_id'] = explode("\n", $session['sa_id']); - //Extract applications score - //XXX: score may be null before grant or for bad behaviour, replace NULL with 'NULL' to avoid silent drop in mysql - $session['sa_score'] = array_map(function($v){return $v==='NULL'?null:$v;}, explode("\n", $session['sa_score'])); - //Extract applications created - $session['sa_created'] = array_map(function($v){return new \DateTime($v);}, explode("\n", $session['sa_created'])); - //Extract applications updated - $session['sa_updated'] = array_map(function($v){return new \DateTime($v);}, explode("\n", $session['sa_updated'])); - //Extract applications canceled - //XXX: canceled is null before cancelation, replace NULL with 'NULL' to avoid silent drop in mysql - $session['sa_canceled'] = array_map(function($v){return $v==='NULL'?null:new \DateTime($v);}, explode("\n", $session['sa_canceled'])); - - //Extract applications user id - $session['sau_id'] = explode("\n", $session['sau_id']); - //Extract applications user pseudonym - $session['sau_pseudonym'] = explode("\n", $session['sau_pseudonym']); - - //Init applications - $context['session']['applications'] = []; - foreach($session['sa_id'] as $i => $sa_id) { - $context['session']['applications'][$sa_id] = [ - 'user' => null, - 'score' => $session['sa_score'][$i], - 'created' => $session['sa_created'][$i], - 'updated' => $session['sa_updated'][$i], - 'canceled' => $session['sa_canceled'][$i] - ]; - if (!empty($session['sau_id'][$i])) { - $context['session']['applications'][$sa_id]['user'] = [ - 'id' => $session['sau_id'][$i], - 'title' => $session['sau_pseudonym'][$i] - ]; + //Add notice in flash message + $this->addFlash('notice', $this->translator->trans('Session %id% updated', ['%id%' => $id])); + //Unknown action + } else { + //Add warning in flash message + $this->addFlash('warning', $this->translator->trans('Session %id% not updated', ['%id%' => $id])); } + + //Flush to get the ids + $this->manager->flush(); + + //Redirect to cleanup the form + return $this->redirectToRoute('rapsys_air_session_view', ['id' => $id, 'location' => $this->context['session']['location']['slug'], 'dance' => $this->context['session']['application']['dance']['slug']??null, 'user' => $this->context['session']['application']['user']['slug']??null]); } + + //Add form to context + $this->context['forms']['session'] = $sessionForm->createView(); } //Render the view - return $this->render('@RapsysAir/session/view.html.twig', ['title' => $title, 'section' => $section]+$context+$this->context); + return $this->render('@RapsysAir/session/view.html.twig', $this->context, $response); } }