diff --git a/src/Bundle/ChillEvent/.gitignore b/src/Bundle/ChillEvent/.gitignore new file mode 100644 index 000000000..093d23fa5 --- /dev/null +++ b/src/Bundle/ChillEvent/.gitignore @@ -0,0 +1,24 @@ +*~ +# MacOS +.DS_Store + +# Bootstrap +app/bootstrap* + +# Symfony directories +vendor/* +*/logs/* +*/cache/* +web/uploads/* +web/bundles/* + +# Configuration files +app/config/parameters.ini +app/config/parameters.yml +Tests/Fixtures/App/config/parameters.yml + +# fixtures +Resources/test/Fixtures/App/DoctrineMigrations/ + +#composer +composer.lock diff --git a/src/Bundle/ChillEvent/.gitlab-ci.yml b/src/Bundle/ChillEvent/.gitlab-ci.yml new file mode 100644 index 000000000..ffd3e3a9f --- /dev/null +++ b/src/Bundle/ChillEvent/.gitlab-ci.yml @@ -0,0 +1,75 @@ +.test_definition: &test_definition + services: + - chill/database:latest + before_script: + - composer config github-oauth.github.com $GITHUB_TOKEN + - php -d memory_limit=-1 /usr/local/bin/composer install + - cp Resources/test/Fixtures/App/config/parameters.gitlab-ci.yml Resources/test/Fixtures/App/config/parameters.yml + - php Resources/test/Fixtures/App/console --env=test cache:warmup + - php Resources/test/Fixtures/App/console doctrine:migrations:migrate --env=test --no-interaction + - php Resources/test/Fixtures/App/console doctrine:fixtures:load --env=test --no-interaction + + +stages: + - test + - deploy + - build-doc + - deploy-doc + + + + +test:php-5.6: + stage: test + <<: *test_definition + image: chill/ci-image:php-5.6 + script: phpunit + +test:php-7: + stage: test + <<: *test_definition + image: chill/ci-image:php-7 + script: phpunit + + +deploy-packagist: + stage: deploy + image: chill/ci-image:php-7 + before_script: + # test that PACKAGIST USERNAME and PACKAGIST_TOKEN variable are set + - if [ -z ${PACKAGIST_USERNAME+x} ]; then echo "Please set PACKAGIST_USERNAME variable"; exit -1; fi + - if [ -z ${PACKAGIST_TOKEN+x} ]; then echo "Please set PACKAGIST_TOKEN variable"; exit -1; fi + script: + - STATUSCODE=$(curl -XPOST -H'content-type:application/json' "https://packagist.org/api/update-package?username=$PACKAGIST_USERNAME&apiToken=$PACKAGIST_TOKEN" -d"{\"repository\":{\"url\":\"$CI_PROJECT_URL.git\"}}" --silent --output /dev/stderr --write-out "%{http_code}") + - if [ $STATUSCODE = "202" ]; then exit 0; else exit $STATUSCODE; fi + +# deploy documentation +api-doc-build: + stage: build-doc + environment: api-doc + image: chill/ci-image:php-7 + before_script: + - mkdir api-doc + script: apigen generate --destination api-doc/$CI_BUILD_REF_NAME/$CI_PROJECT_NAME + artifacts: + paths: + - "api-doc/" + name: api + expire_in: '2h' + only: + - master + - tags + +api-doc-deploy: + stage: deploy-doc + image: pallet/swiftclient:latest + before_script: + # test that CONTAINER_API variable is set + - if [ -z ${CONTAINER_API+x} ]; then echo "Please set CONTAINER_API variable"; exit -1; fi + # go to api-doc to have and url with PROJECT/BUILD + - cd api-doc + # upload, and keep files during 1 year + script: "swift upload --header \"X-Delete-After: 31536000\" $CONTAINER_API $CI_BUILD_REF_NAME/$CI_PROJECT_NAME" + only: + - master + - tags diff --git a/src/Bundle/ChillEvent/CHANGELOG.md b/src/Bundle/ChillEvent/CHANGELOG.md new file mode 100644 index 000000000..66a6d4c33 --- /dev/null +++ b/src/Bundle/ChillEvent/CHANGELOG.md @@ -0,0 +1,25 @@ + +Branch sf3 +========== + +- fix symfony3 php depreciations ; +- add time to event dates ; +- add new moderator field on events ; +- misc improvements form styles ; +- adapt webpack config for styles sheets ; +- add a new page 'events participation' in menu person, that list all events participation for a person ; +- subscribe a person to an event from person context ; +- improve message translation ; +- add a first step to pick center in new event form ; +- add events in history timeline ; +- export participations list for an event ; +- add event administration pages ; +- add remove participation and remove event feature ; +- fix the way the bundle compile assets ; + This modification will require to update Chill-Standard to the latest version. + At least, the file `webpack.config.js` should be upgrade [to the last + version](https://framagit.org/Chill-project/Chill-Standard/-/blob/c7a7de68ec49d97c9e1481b72c1f848f9b5cb2d7/webpack.config.js) +- fix redirection when only one participation edit ; + + + diff --git a/src/Bundle/ChillEvent/ChillEventBundle.php b/src/Bundle/ChillEvent/ChillEventBundle.php new file mode 100644 index 000000000..dc040dac6 --- /dev/null +++ b/src/Bundle/ChillEvent/ChillEventBundle.php @@ -0,0 +1,9 @@ + + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +namespace Chill\EventBundle\Controller; + +use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; + +/** + * Class AdminController + * Controller for the event configuration section (in admin section) + * + * @package Chill\EventBundle\Controller + */ +class AdminController extends AbstractController +{ + /** + * @return \Symfony\Component\HttpFoundation\Response + */ + public function indexAction() + { + return $this->render('ChillEventBundle:Admin:layout.html.twig'); + } + + /** + * @return \Symfony\Component\HttpFoundation\RedirectResponse + */ + public function redirectToAdminIndexAction() + { + return $this->redirectToRoute('chill_main_admin_central'); + } +} \ No newline at end of file diff --git a/src/Bundle/ChillEvent/Controller/EventController.php b/src/Bundle/ChillEvent/Controller/EventController.php new file mode 100644 index 000000000..9f4d242d1 --- /dev/null +++ b/src/Bundle/ChillEvent/Controller/EventController.php @@ -0,0 +1,678 @@ +, + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +namespace Chill\EventBundle\Controller; + +use Chill\EventBundle\Entity\Participation; +use Chill\EventBundle\Form\Type\PickEventType; +use Chill\MainBundle\Pagination\PaginatorFactory; +use PhpOffice\PhpSpreadsheet\Spreadsheet; +use PhpOffice\PhpSpreadsheet\Writer\Csv; +use PhpOffice\PhpSpreadsheet\Writer\Ods; +use PhpOffice\PhpSpreadsheet\Writer\Xlsx; +use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; +use Symfony\Component\Form\Extension\Core\Type\ChoiceType; +use Symfony\Component\HttpFoundation\StreamedResponse; +use Chill\EventBundle\Security\Authorization\EventVoter; +use Chill\MainBundle\Security\Authorization\AuthorizationHelper; +use Chill\PersonBundle\Entity\Person; +use Chill\PersonBundle\Privacy\PrivacyEvent; +use Symfony\Component\EventDispatcher\EventDispatcherInterface; +use Symfony\Component\HttpFoundation\Request; +use Chill\PersonBundle\Form\Type\PickPersonType; +use Chill\EventBundle\Entity\Event; +use Chill\EventBundle\Form\EventType; +use Symfony\Component\Security\Core\Role\Role; +use Symfony\Component\Form\Extension\Core\Type\FormType; +use Symfony\Component\Form\Extension\Core\Type\SubmitType; +use Symfony\Component\Form\Extension\Core\Type\HiddenType; +use Chill\MainBundle\Entity\Center; +use Symfony\Bridge\Doctrine\Form\Type\EntityType; +use Symfony\Component\Form\FormFactoryInterface; +use Symfony\Component\Translation\TranslatorInterface; +use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter; + + +/** + * Class EventController + * + * @package Chill\EventBundle\Controller + */ +class EventController extends AbstractController +{ + /** + * @var EventDispatcherInterface + */ + protected $eventDispatcher; + + /** + * @var AuthorizationHelper + */ + protected $authorizationHelper; + + /** + * @var FormFactoryInterface + */ + protected $formFactoryInterface; + + /** + * @var TranslatorInterface + */ + protected $translator; + + /** + * @var PaginatorFactory + */ + protected $paginator; + + /** + * EventController constructor. + * + * @param EventDispatcherInterface $eventDispatcher + * @param AuthorizationHelper $authorizationHelper + * @param FormFactoryInterface $formFactoryInterface + * @param TranslatorInterface $translator + * @param PaginatorFactory $paginator + */ + public function __construct( + EventDispatcherInterface $eventDispatcher, + AuthorizationHelper $authorizationHelper, + FormFactoryInterface $formFactoryInterface, + TranslatorInterface $translator, + PaginatorFactory $paginator + ) + { + $this->eventDispatcher = $eventDispatcher; + $this->authorizationHelper = $authorizationHelper; + $this->formFactoryInterface = $formFactoryInterface; + $this->translator = $translator; + $this->paginator = $paginator; + } + + + public function mostRecentIndexAction() + { + return $this->redirectToRoute('chill_main_search', array( + 'q' => '@event' + )); + } + + + /** + * First step of new Event form + */ + public function newPickCenterAction() + { + $role = new Role('CHILL_EVENT_CREATE'); + + /** + * @var Center $centers + */ + $centers = $this->authorizationHelper->getReachableCenters($this->getUser(), $role); + + if (count($centers) === 1) + { + return $this->redirectToRoute('chill_event__event_new', array( + 'center_id' => $centers[0]->getId() + )); + } + + $form = $this->formFactoryInterface + ->createNamedBuilder(null, FormType::class, null, array( + 'csrf_protection' => false + )) + ->setMethod('GET') + ->setAction( + $this->generateUrl('chill_event__event_new')) + ->add('center_id', EntityType::class, array( + 'class' => Center::class, + 'choices' => $centers, + 'placeholder' => '', + 'label' => 'To which centre should the event be associated ?' + )) + ->add('submit', SubmitType::class, array( + 'label' => 'Next step' + )) + ->getForm(); + + return $this->render('ChillEventBundle:Event:newPickCenter.html.twig', array( + 'form' => $form->createView() + )); + + } + + /** + * Creates a form to create a Event entity. + * + * @param Event $entity The entity + * @return \Symfony\Component\Form\FormInterface + */ + private function createCreateForm(Event $entity) + { + $form = $this->createForm(EventType::class, $entity, array( + 'method' => 'POST', + 'center' => $entity->getCenter(), + 'role' => new Role('CHILL_EVENT_CREATE') + )); + + $form->add('submit', SubmitType::class, array('label' => 'Create')); + + return $form; + } + + /** + * Displays a form to create a new Event entity. + * @param Center $center + * @param Request $request + * @return \Symfony\Component\HttpFoundation\Response + */ + public function newAction(Center $center = null, Request $request) + { + if ($center === null) + { + $center_id = $request->query->get('center_id'); + $center = $this->getDoctrine()->getRepository(Center::class)->find($center_id); + } + + $entity = new Event(); + $entity->setCenter($center); + + $form = $this->createCreateForm($entity); + $form->handleRequest($request); + + if ($form->isSubmitted() && $form->isValid()) + { + $em = $this->getDoctrine()->getManager(); + $em->persist($entity); + $em->flush(); + + $this->addFlash('success', $this->get('translator') + ->trans('The event was created')); + + return $this->redirect($this->generateUrl('chill_event__event_show', array('event_id' => $entity->getId()))); + } + + return $this->render('ChillEventBundle:Event:new.html.twig', array( + 'entity' => $entity, + 'form' => $form->createView(), + )); + } + + /** + * Finds and displays a Event entity. + * + * @ParamConverter("event", options={"id" = "event_id"}) + * @param Event $event + * @param Request $request + * @return \Symfony\Component\HttpFoundation\Response + * @throws \PhpOffice\PhpSpreadsheet\Exception + */ + public function showAction(Event $event, Request $request) + { + if (!$event) { + throw $this->createNotFoundException('Unable to find Event entity.'); + } + + $this->denyAccessUnlessGranted('CHILL_EVENT_SEE_DETAILS', $event, + "You are not allowed to see details on this event"); + + $addParticipationByPersonForm = $this->createAddParticipationByPersonForm($event); + + $exportParticipationsList = $this->exportParticipationsList($event, $request); + + if ($exportParticipationsList['response']) { + return $exportParticipationsList['response']; + } + + return $this->render('ChillEventBundle:Event:show.html.twig', array( + 'event' => $event, + 'form_add_participation_by_person' => $addParticipationByPersonForm->createView(), + 'form_export' => $exportParticipationsList['form']->createView() + )); + } + + /** + * create a form to add a participation with a person + * + * @param Event $event + * @return \Symfony\Component\Form\FormInterface + */ + protected function createAddParticipationByPersonForm(Event $event) + { + /* @var $builder \Symfony\Component\Form\FormBuilderInterface */ + $builder = $this + ->get('form.factory') + ->createNamedBuilder( + null, + FormType::class, + null, + array( + 'method' => 'GET', + 'action' => $this->generateUrl('chill_event_participation_new'), + 'csrf_protection' => false + )) + ; + + $builder->add('person_id', PickPersonType::class, array( + 'role' => new Role('CHILL_EVENT_CREATE'), + 'centers' => $event->getCenter() + )); + + $builder->add('event_id', HiddenType::class, array( + 'data' => $event->getId() + )); + + $builder->add('submit', SubmitType::class, + array( + 'label' => 'Add a participation' + )); + + return $builder->getForm(); + } + + /** + * Displays a form to edit an existing Event entity. + * + * @param $event_id + * @return \Symfony\Component\HttpFoundation\Response + */ + public function editAction($event_id) + { + $em = $this->getDoctrine()->getManager(); + + $entity = $em->getRepository('ChillEventBundle:Event')->find($event_id); + + if (!$entity) { + throw $this->createNotFoundException('Unable to find Event entity.'); + } + + $editForm = $this->createEditForm($entity); + + return $this->render('ChillEventBundle:Event:edit.html.twig', array( + 'entity' => $entity, + 'edit_form' => $editForm->createView(), + )); + } + + /** + * Creates a form to edit a Event entity. + * + * @param Event $entity + * @return \Symfony\Component\Form\FormInterface + */ + private function createEditForm(Event $entity) + { + $form = $this->createForm(EventType::class, $entity, array( + 'action' => $this->generateUrl('chill_event__event_update', array('event_id' => $entity->getId())), + 'method' => 'PUT', + 'center' => $entity->getCenter(), + 'role' => new Role('CHILL_EVENT_CREATE') + )); + + $form->remove('center'); + + $form->add('submit', SubmitType::class, array('label' => 'Update')); + + return $form; + } + + /** + * Edits an existing Event entity. + * + * @param Request $request + * @param $event_id + * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response + */ + public function updateAction(Request $request, $event_id) + { + $em = $this->getDoctrine()->getManager(); + + $entity = $em->getRepository('ChillEventBundle:Event')->find($event_id); + + if (!$entity) { + throw $this->createNotFoundException('Unable to find Event entity.'); + } + + $editForm = $this->createEditForm($entity); + $editForm->handleRequest($request); + + if ($editForm->isValid()) { + $em->flush(); + + $this->addFlash('success', $this->get('translator') + ->trans('The event was updated')); + + return $this->redirect($this->generateUrl('chill_event__event_edit', array('event_id' => $event_id))); + } + + return $this->render('ChillEventBundle:Event:edit.html.twig', array( + 'entity' => $entity, + 'edit_form' => $editForm->createView(), + )); + } + + /** + * List events subscriptions for a person + * + * @param $person_id + * @return \Symfony\Component\HttpFoundation\Response + * @throws \Doctrine\ORM\NonUniqueResultException + */ + public function listByPersonAction($person_id) + { + + $em = $this->getDoctrine()->getManager(); + + $person = $em->getRepository('ChillPersonBundle:Person')->find($person_id); + + if ($person === NULL) { + throw $this->createNotFoundException('Person not found'); + } + + $this->denyAccessUnlessGranted('CHILL_PERSON_SEE', $person); + + $reachablesCircles = $this->authorizationHelper->getReachableCircles( + $this->getUser(), + new Role(EventVoter::SEE), + $person->getCenter() + ); + + $total = $em->getRepository('ChillEventBundle:Participation')->countByPerson($person_id); + + $paginator = $this->paginator->create($total); + + $participations = $em->getRepository('ChillEventBundle:Participation')->findByPersonInCircle( + $person_id, + $reachablesCircles, + $paginator->getCurrentPage()->getFirstItemNumber(), + $paginator->getItemsPerPage() + ); + + $privacyEvent = new PrivacyEvent($person, array( + 'element_class' => Participation::class, + 'action' => 'list' + )); + $this->eventDispatcher->dispatch(PrivacyEvent::PERSON_PRIVACY_EVENT, $privacyEvent); + + $addEventParticipationByPersonForm = $this->createAddEventParticipationByPersonForm($person); + + return $this->render('ChillEventBundle:Event:listByPerson.html.twig', array( + 'participations' => $participations, + 'person' => $person, + 'paginator' => $paginator, + 'form_add_event_participation_by_person' => $addEventParticipationByPersonForm->createView() + )); + } + + /** + * create a form to add a participation with an event + * + * @param Person $person + * @return \Symfony\Component\Form\FormInterface + */ + protected function createAddEventParticipationByPersonForm(Person $person) + { + /* @var $builder \Symfony\Component\Form\FormBuilderInterface */ + $builder = $this + ->get('form.factory') + ->createNamedBuilder( + null, + FormType::class, + null, + array( + 'method' => 'GET', + 'action' => $this->generateUrl('chill_event_participation_new'), + 'csrf_protection' => false + )) + ; + + $builder->add('event_id', PickEventType::class, array( + 'role' => new Role('CHILL_EVENT_CREATE'), + 'centers' => $person->getCenter() + )); + + $builder->add('person_id', HiddenType::class, array( + 'data' => $person->getId() + )); + + $builder->add('return_path', HiddenType::class, array( + 'data' => $this->generateUrl('chill_event__list_by_person', array( + 'person_id' => $person->getId() + )) + )); + + + $builder->add('submit', SubmitType::class, + array( + 'label' => 'Subscribe an event' + )); + + return $builder->getForm(); + } + + + /** + * @param Event $event + * @param Request $request + * @return array + * @throws \PhpOffice\PhpSpreadsheet\Exception + */ + protected function exportParticipationsList(Event $event, Request $request) + { + $form = $this->createExportByFormatForm(); + $form->handleRequest($request); + + if ($form->isSubmitted() && $form->isValid()) + { + $data = $form->getData(); + $format = $data['format']; + $filename = 'export_event'. $event->getId() .'_participations.' .$format; + + $spreadsheet = $this->createExportSpreadsheet($event); + + switch ($format) { + case 'ods': + $contentType = 'application/vnd.oasis.opendocument.spreadsheet'; + $writer = new Ods($spreadsheet); + break; + case 'xlsx': + $contentType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; + $writer = new Xlsx($spreadsheet); + break; + case 'csv': + $contentType = 'text/csv'; + $writer = new Csv($spreadsheet); + break; + default: + return [ 'form' => $form, 'response' => null ]; + } + + $response = new StreamedResponse(); + $response->headers->set('Content-Type', $contentType); + $response->headers->set('Content-Disposition', 'attachment;filename="'.$filename.'"'); + $response->setPrivate(); + $response->headers->addCacheControlDirective('no-cache', true); + $response->headers->addCacheControlDirective('must-revalidate', true); + $response->setCallback(function() use ($writer) { + $writer->save('php://output'); + }); + + return [ 'form' => $form, 'response' => $response ]; + } + + return [ 'form' => $form, 'response' => null ]; + } + + /** + * @return \Symfony\Component\Form\FormInterface + */ + protected function createExportByFormatForm() + { + $builder = $this->createFormBuilder() + ->add('format', ChoiceType::class, [ + 'choices' => [ + 'xlsx' => 'xlsx', + 'ods' => 'ods', + 'csv' => 'csv' + ], + 'label' => false, + 'placeholder' => 'Select a format' + ]) + ->add('submit', SubmitType::class, [ + 'label' => 'Export' + ]); + + return $builder->getForm(); + } + + /** + * @param Event $event + * @return Spreadsheet + * @throws \PhpOffice\PhpSpreadsheet\Exception + */ + protected function createExportSpreadsheet(Event $event) + { + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + + $trans = $this->translator->getLocale(); + + $headerValues = [ + 'A1' => 'Event', + 'B1' => $event->getId(), + 'A2' => 'Date', + 'B2' => $event->getDate()->format('d-m-Y H:i'), + 'A3' => 'Name', + 'B3' => $event->getName(), + 'A4' => 'Type', + 'B4' => $event->getType()->getName()[$trans], + 'A5' => 'Circle', + 'B5' => $event->getCircle()->getName()[$trans], + 'A6' => 'Moderator', + 'B6' => $event->getModerator() ? $event->getModerator()->getUsernameCanonical() : null, + ]; + foreach ($headerValues as $k => $value) { + $sheet->setCellValue($k, $value); + } + + $columnNames = [ 'id', 'firstname', 'lastname', 'role', 'status', 'email', 'phone', 'mobile' ]; + $columnLetter = 'A'; + foreach ($columnNames as $columnName) { + $sheet->setCellValue($columnLetter.'8', $columnName); + $columnLetter++; + } + + $columnValues = []; + foreach ($event->getParticipations() as $participation) + { + /** @var Participation $participation */ + $columnValues[] = [ + $participation->getPerson()->getId(), + $participation->getPerson()->getFirstname(), + $participation->getPerson()->getLastname(), + $participation->getRole()->getName()[$trans], + $participation->getStatus()->getName()[$trans], + $participation->getPerson()->getEmail(), + $participation->getPerson()->getPhoneNumber(), + $participation->getPerson()->getMobileNumber(), + ]; + } + + $i = 9; + foreach ($columnValues as $columnValue) { + $columnLetter = 'A'; + foreach ($columnValue as $value) { + $sheet->setCellValue($columnLetter.$i, $value); + $columnLetter++; + } + $i++; + } + + return $spreadsheet; + } + + /** + * @param $event_id + * @param Request $request + * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response + */ + public function deleteAction($event_id, Request $request) + { + $em = $this->getDoctrine()->getManager(); + $event = $em->getRepository('ChillEventBundle:Event')->findOneBy([ + 'id' => $event_id + ]); + + if (! $event) { + throw $this->createNotFoundException('Unable to find this event.'); + } + + /** @var array $participations */ + $participations = $event->getParticipations(); + + $form = $this->createDeleteForm($event_id); + + if ($request->getMethod() === Request::METHOD_DELETE) { + $form->handleRequest($request); + + if ($form->isValid()) { + + foreach ($participations as $participation) { + $em->remove($participation); + } + + $em->remove($event); + $em->flush(); + + $this->addFlash('success', $this->get('translator') + ->trans("The event has been sucessfully removed") + ); + + return $this->redirectToRoute('chill_main_search', [ + 'name' => 'event_regular', + 'q' => '@event' + ]); + } + } + return $this->render('ChillEventBundle:Event:confirm_delete.html.twig', [ + 'event_id' => $event->getId(), + 'delete_form' => $form->createView() + ]); + } + + /** + * @param $event_id + * @return \Symfony\Component\Form\FormInterface + */ + private function createDeleteForm($event_id) + { + return $this->createFormBuilder() + ->setAction($this->generateUrl('chill_event__event_delete', [ + 'event_id' => $event_id + ])) + ->setMethod('DELETE') + ->add('submit', SubmitType::class, ['label' => 'Delete']) + ->getForm() + ; + } + +} diff --git a/src/Bundle/ChillEvent/Controller/EventTypeController.php b/src/Bundle/ChillEvent/Controller/EventTypeController.php new file mode 100644 index 000000000..e151f04cb --- /dev/null +++ b/src/Bundle/ChillEvent/Controller/EventTypeController.php @@ -0,0 +1,230 @@ +getDoctrine()->getManager(); + + $entities = $em->getRepository('ChillEventBundle:EventType')->findAll(); + + return $this->render('ChillEventBundle:EventType:index.html.twig', array( + 'entities' => $entities, + )); + } + /** + * Creates a new EventType entity. + * + */ + public function createAction(Request $request) + { + $entity = new EventType(); + $form = $this->createCreateForm($entity); + $form->handleRequest($request); + + if ($form->isValid()) { + $em = $this->getDoctrine()->getManager(); + $em->persist($entity); + $em->flush(); + + return $this->redirect($this->generateUrl('chill_eventtype_admin', + array('id' => $entity->getId()))); + } + + return $this->render('ChillEventBundle:EventType:new.html.twig', array( + 'entity' => $entity, + 'form' => $form->createView(), + )); + } + + /** + * Creates a form to create a EventType entity. + * + * @param EventType $entity The entity + * + * @return \Symfony\Component\Form\Form The form + */ + private function createCreateForm(EventType $entity) + { + $form = $this->createForm(EventTypeType::class, $entity, array( + 'action' => $this->generateUrl('chill_eventtype_admin_create'), + 'method' => 'POST', + )); + + $form->add('submit', SubmitType::class, array('label' => 'Create')); + + return $form; + } + + /** + * Displays a form to create a new EventType entity. + * + */ + public function newAction() + { + $entity = new EventType(); + $form = $this->createCreateForm($entity); + + return $this->render('ChillEventBundle:EventType:new.html.twig', array( + 'entity' => $entity, + 'form' => $form->createView(), + )); + } + + /** + * Finds and displays a EventType entity. + * + */ + public function showAction($id) + { + $em = $this->getDoctrine()->getManager(); + + $entity = $em->getRepository('ChillEventBundle:EventType')->find($id); + + if (!$entity) { + throw $this->createNotFoundException('Unable to find EventType entity.'); + } + + $deleteForm = $this->createDeleteForm($id); + + return $this->render('ChillEventBundle:EventType:show.html.twig', array( + 'entity' => $entity, + 'delete_form' => $deleteForm->createView(), + )); + } + + /** + * Displays a form to edit an existing EventType entity. + * + */ + public function editAction($id) + { + $em = $this->getDoctrine()->getManager(); + + $entity = $em->getRepository('ChillEventBundle:EventType')->find($id); + + if (!$entity) { + throw $this->createNotFoundException('Unable to find EventType entity.'); + } + + $editForm = $this->createEditForm($entity); + $deleteForm = $this->createDeleteForm($id); + + return $this->render('ChillEventBundle:EventType:edit.html.twig', array( + 'entity' => $entity, + 'edit_form' => $editForm->createView(), + 'delete_form' => $deleteForm->createView(), + )); + } + + /** + * Creates a form to edit a EventType entity. + * + * @param EventType $entity The entity + * + * @return \Symfony\Component\Form\Form The form + */ + private function createEditForm(EventType $entity) + { + $form = $this->createForm(EventTypeType::class, $entity, array( + 'action' => $this->generateUrl('chill_eventtype_admin_update', + array('id' => $entity->getId())), + 'method' => 'PUT', + )); + + $form->add('submit', SubmitType::class, array('label' => 'Update')); + + return $form; + } + /** + * Edits an existing EventType entity. + * + */ + public function updateAction(Request $request, $id) + { + $em = $this->getDoctrine()->getManager(); + + $entity = $em->getRepository('ChillEventBundle:EventType')->find($id); + + if (!$entity) { + throw $this->createNotFoundException('Unable to find EventType entity.'); + } + + $deleteForm = $this->createDeleteForm($id); + $editForm = $this->createEditForm($entity); + $editForm->handleRequest($request); + + if ($editForm->isValid()) { + $em->flush(); + + return $this->redirect($this->generateUrl('chill_eventtype_admin', + array('id' => $id))); + } + + return $this->render('ChillEventBundle:EventType:edit.html.twig', array( + 'entity' => $entity, + 'edit_form' => $editForm->createView(), + 'delete_form' => $deleteForm->createView(), + )); + } + /** + * Deletes a EventType entity. + * + */ + public function deleteAction(Request $request, $id) + { + $form = $this->createDeleteForm($id); + $form->handleRequest($request); + + if ($form->isValid()) { + $em = $this->getDoctrine()->getManager(); + $entity = $em->getRepository('ChillEventBundle:EventType')->find($id); + + if (!$entity) { + throw $this->createNotFoundException('Unable to find EventType entity.'); + } + + $em->remove($entity); + $em->flush(); + } + + return $this->redirect($this->generateUrl('chill_eventtype_admin')); + } + + /** + * Creates a form to delete a EventType entity by id. + * + * @param mixed $id The entity id + * + * @return \Symfony\Component\Form\Form The form + */ + private function createDeleteForm($id) + { + return $this->createFormBuilder() + ->setAction($this->generateUrl('chill_eventtype_admin_delete', + array('id' => $id))) + ->setMethod('DELETE') + ->add('submit', SubmitType::class, array('label' => 'Delete')) + ->getForm() + ; + } +} diff --git a/src/Bundle/ChillEvent/Controller/ParticipationController.php b/src/Bundle/ChillEvent/Controller/ParticipationController.php new file mode 100644 index 000000000..4242eb784 --- /dev/null +++ b/src/Bundle/ChillEvent/Controller/ParticipationController.php @@ -0,0 +1,766 @@ + + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +namespace Chill\EventBundle\Controller; + +use ArrayIterator; +use Chill\EventBundle\Entity\Event; +use Psr\Log\LoggerInterface; +use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\Response; +use Chill\EventBundle\Entity\Participation; +use Chill\EventBundle\Form\ParticipationType; +use Symfony\Component\Form\Extension\Core\Type\SubmitType; +use Chill\EventBundle\Security\Authorization\ParticipationVoter; +use Symfony\Component\Form\Extension\Core\Type\CollectionType; + +/** + * Class ParticipationController + * + * @package Chill\EventBundle\Controller + * @author Julien Fastré + */ +class ParticipationController extends AbstractController +{ + + /** + * @var \Psr\Log\LoggerInterface + */ + private $logger; + + /** + * ParticipationController constructor. + * + * @param LoggerInterface $logger + */ + public function __construct(LoggerInterface $logger) + { + $this->logger = $logger; + } + + /** + * Show a form to add a participation + * + * This function parse the person_id / persons_ids query argument + * and decide if it should process a single or multiple participation. Depending + * on this, the appropriate layout and form. + * + * @param Request $request + * @return \Symfony\Component\HttpFoundation\RedirectResponse|Response + */ + public function newAction(Request $request) + { + + // test the request is correct + try { + $this->testRequest($request); + } catch (\RuntimeException $ex) { + $this->logger->warning($ex->getMessage()); + + return (new Response()) + ->setStatusCode(Response::HTTP_BAD_REQUEST) + ->setContent($ex->getMessage()); + } + + // forward to other action + $single = $request->query->has('person_id'); + $multiple = $request->query->has('persons_ids'); + + if ($single === true) { + return $this->newSingle($request); + } + + if ($multiple === true) { + + return $this->newMultiple($request); + } + + // at this point, we miss the required fields. Throw an error + return (new Response()) + ->setStatusCode(Response::HTTP_BAD_REQUEST) + ->setContent("You must provide either 'person_id' or " + . "'persons_ids' argument in query"); + } + + /** + * + * Test that the query parameters are valid : + * + * - an `event_id` is existing ; + * - `person_id` and `persons_ids` are **not** both present ; + * - `persons_id` is correct (contains only numbers and a ','. + * + * @param Request $request + * @throws \RuntimeException if an error is detected + */ + protected function testRequest(Request $request) + { + $single = $request->query->has('person_id'); + $multiple = $request->query->has('persons_ids'); + + if ($single === true AND $multiple === true) { + // we are not allowed to have both person_id and persons_ids + throw new \RuntimeException("You are not allow to provide both 'person_id' and " + . "'persons_ids' simulaneously"); + } + + if ($multiple === true) { + $persons_ids = $request->query->get('persons_ids'); + + if (!preg_match('/^([0-9]{1,},{0,1}){1,}[0-9]{0,}$/', $persons_ids)) { + throw new \RuntimeException("The persons_ids value should " + . "contains int separated by ','"); + } + } + + // check for event_id - this could be removed later + if ($request->query->has('event_id') === FALSE) { + throw new \RuntimeException("You must provide an event_id"); + } + + } + + /** + * Show a form with single participation. + * + * @param Request $request + * @return Response + */ + protected function newSingle(Request $request) + { + + $returnPath = $request->query->get('return_path') ? + $request->query->get('return_path') : null; + + $participation = $this->handleRequest($request, new Participation(), false); + + $this->denyAccessUnlessGranted(ParticipationVoter::CREATE, + $participation, 'The user is not allowed to create this participation'); + + $form = $this->createCreateForm($participation, $returnPath); + + return $this->render('ChillEventBundle:Participation:new.html.twig', array( + 'form' => $form->createView(), + 'participation' => $participation, + 'ignored_participations' => array() // this is required, see self::newMultiple + )); + } + + /** + * Show a form with multiple participation. + * + * If a person is already participating on the event (if a participation with + * the same person is associated with the event), the participation is ignored. + * + * If all but one participation is ignored, the page show the same response + * than the newSingle function. + * + * If all participations must be ignored, an error is shown and the method redirects + * to the event 'show' view with an appropriate flash message. + * + * @param Request $request + * @return \Symfony\Component\HttpFoundation\RedirectResponse|Response + */ + protected function newMultiple(Request $request) + { + $participations = $this->handleRequest($request, new Participation(), true); + + + foreach ($participations as $i => $participation) { + // check for authorization + $this->denyAccessUnlessGranted(ParticipationVoter::CREATE, + $participation, 'The user is not allowed to create this participation'); + + // create a collection of person's id participating to the event + /* @var $peopleParticipating \Doctrine\Common\Collections\ArrayCollection */ + $peopleParticipating = isset($peopleParticipating) ? $peopleParticipating : + $participation->getEvent()->getParticipations()->map( + function(Participation $p) { return $p->getPerson()->getId(); } + ); + // check that the user is not already in the event + if ($peopleParticipating->contains($participation->getPerson()->getId())) { + $ignoredParticipations[] = $participation + ->getEvent()->getParticipations()->filter( + function (Participation $p) use ($participation) { + return $p->getPerson()->getId() === $participation->getPerson()->getId(); + } + )->first(); + } else { + $newParticipations[] = $participation; + } + } + + // this is where the function redirect depending on valid participation + + if (!isset($newParticipations)) { + // if we do not have nay participants, redirect to event view + $this->addFlash('error', $this->get('translator')->trans( + 'None of the requested people may participate ' + . 'the event: they are maybe already participating.')); + + return $this->redirectToRoute('chill_event__event_show', array( + 'event_id' => $request->query->getInt('event_id', 0) + )); + } elseif (count($newParticipations) > 1) { + // if we have multiple participations, show a form with multiple participations + $form = $this->createCreateFormMultiple($newParticipations); + + return $this->render('ChillEventBundle:Participation:new-multiple.html.twig', array( + 'form' => $form->createView(), + 'participations' => $newParticipations, + 'ignored_participations' => isset($ignoredParticipations) ? $ignoredParticipations : array() + )); + } else { + // if we have only one participation, show the same form than for single participation + $form = $this->createCreateForm($participation); + + return $this->render('ChillEventBundle:Participation:new.html.twig', array( + 'form' => $form->createView(), + 'participation' => $participation, + 'ignored_participations' => isset($ignoredParticipations) ? $ignoredParticipations : array() + )); + + } + } + + /** + * @param Request $request + * @return \Symfony\Component\HttpFoundation\RedirectResponse|Response + */ + public function createAction(Request $request) + { + // test the request is correct + try { + $this->testRequest($request); + } catch (\RuntimeException $ex) { + $this->logger->warning($ex->getMessage()); + + return (new Response()) + ->setStatusCode(Response::HTTP_BAD_REQUEST) + ->setContent($ex->getMessage()); + } + + // forward to other action + $single = $request->query->has('person_id'); + $multiple = $request->query->has('persons_ids'); + + if ($single === true) { + return $this->createSingle($request); + } + + if ($multiple === true) { + + return $this->createMultiple($request); + } + + // at this point, we miss the required fields. Throw an error + return (new Response()) + ->setStatusCode(Response::HTTP_BAD_REQUEST) + ->setContent("You must provide either 'person_id' or " + . "'persons_ids' argument in query"); + } + + /** + * @param Request $request + * @return \Symfony\Component\HttpFoundation\RedirectResponse|Response + */ + public function createSingle(Request $request) + { + $participation = $this->handleRequest($request, new Participation(), false); + + $this->denyAccessUnlessGranted(ParticipationVoter::CREATE, + $participation, 'The user is not allowed to create this participation'); + + $form = $this->createCreateForm($participation); + $form->handleRequest($request); + + if ($form->isSubmitted() && $form->isValid()) { + $em = $this->getDoctrine()->getManager(); + + $em->persist($participation); + $em->flush(); + + $this->addFlash('success', $this->get('translator')->trans( + 'The participation was created' + )); + + if ($request->query->get('return_path')) + { + return $this->redirect($request->query->get('return_path')); + + } else { + return $this->redirectToRoute('chill_event__event_show', array( + 'event_id' => $participation->getEvent()->getId() + )); + } + + } + + return $this->render('ChillEventBundle:Participation:new.html.twig', array( + 'form' => $form->createView(), + 'participation' => $participation + )); + } + + /** + * @param Request $request + * @return \Symfony\Component\HttpFoundation\RedirectResponse|Response + */ + public function createMultiple(Request $request) + { + $participations = $this->handleRequest($request, new Participation(), true); + + foreach($participations as $participation) { + $this->denyAccessUnlessGranted(ParticipationVoter::CREATE, + $participation, 'The user is not allowed to create this participation'); + } + + $form = $this->createCreateFormMultiple($participations); + $form->handleRequest($request); + + if ($form->isSubmitted() && $form->isValid()) { + $em = $this->getDoctrine()->getManager(); + $data = $form->getData(); + + foreach($data['participations'] as $participation) { + $em->persist($participation); + } + + $em->flush(); + + $this->addFlash('success', $this->get('translator')->trans( + 'The participations were created' + )); + + return $this->redirectToRoute('chill_event__event_show', array( + 'event_id' => $participations[0]->getEvent()->getId() + )); + } + + return $this->render('ChillEventBundle:Participation:new.html.twig', array( + 'form' => $form->createView(), + 'participation' => $participation + )); + } + + /** + * + * Handle the request to adapt $participation. + * + * If the request is multiple, the $participation object is cloned. + * Limitations: the $participation should not be persisted. + * + * @param Request $request + * @param Participation $participation + * @param boolean $multiple (default false) + * @return Participation|Participations[] return one single participation if $multiple == false + * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException if the event/person is not found + * @throws \Symfony\Component\Security\Core\Exception\AccessDeniedException if the user does not have access to event/person + */ + protected function handleRequest( + Request $request, + Participation $participation, + $multiple = false) + { + $em = $this->getDoctrine()->getManager(); + if ($em->contains($participation)) { + throw new \LogicException("The participation object should not be managed by " + . "the object manager using the method ".__METHOD__); + } + + $event_id = $request->query->getInt('event_id', 0); // sf4 check: + // prevent error: `Argument 2 passed to ::getInt() must be of the type int, null given` + + if ($event_id !== NULL) { + $event = $em->getRepository('ChillEventBundle:Event') + ->find($event_id); + + if ($event === NULL) { + throw $this->createNotFoundException('The event with id '.$event_id.' is not found'); + } + + $this->denyAccessUnlessGranted('CHILL_EVENT_SEE', $event, + 'The user is not allowed to see the event'); + + $participation->setEvent($event); + } + + // this script should be able to handle multiple, so we translate + // single person_id in an array + $persons_ids = $request->query->has('person_id') ? + [$request->query->getInt('person_id', 0)] // sf4 check: + // prevent error: `Argument 2 passed to ::getInt() must be of the type int, null given` + : explode(',', $request->query->get('persons_ids')); + $participations = array(); + + foreach($persons_ids as $person_id) { + + // clone if we have to reuse the $participation + $participation = count($persons_ids) > 1 ? clone $participation : $participation; + + if ($person_id !== NULL) { + $person = $em->getRepository('ChillPersonBundle:Person') + ->find($person_id); + + if ($person === NULL) { + throw $this->createNotFoundException('The person with id '.$person_id.' is not found'); + } + + $this->denyAccessUnlessGranted('CHILL_PERSON_SEE', $person, + 'The user is not allowed to see the person'); + + $participation->setPerson($person); + } + + $participations[] = $participation; + } + + return $multiple ? $participations : $participations[0]; + } + + /** + * @param Participation $participation + * @param null $return_path + * @return \Symfony\Component\Form\FormInterface + */ + public function createCreateForm(Participation $participation, $return_path = null) + { + + $form = $this->createForm(ParticipationType::class, $participation, array( + 'event_type' => $participation->getEvent()->getType(), + 'action' => $this->generateUrl('chill_event_participation_create', array( + 'return_path' => $return_path, + 'event_id' => $participation->getEvent()->getId(), + 'person_id' => $participation->getPerson()->getId() + )) + )); + + $form->add('submit', SubmitType::class, array( + 'label' => 'Create' + )); + + return $form; + } + + /** + * @param array $participations + * @return \Symfony\Component\Form\FormInterface + */ + public function createCreateFormMultiple(array $participations) + { + $form = $this->createForm(\Symfony\Component\Form\Extension\Core\Type\FormType::class, + array('participations' => $participations), array( + 'action' => $this->generateUrl('chill_event_participation_create', array( + 'event_id' => current($participations)->getEvent()->getId(), + 'persons_ids' => implode(',', array_map( + function(Participation $p) { return $p->getPerson()->getId(); }, + $participations)) + ) + ))); + $form->add('participations', CollectionType::class, array( + 'entry_type' => ParticipationType::class, + 'entry_options' => array( + 'event_type' => current($participations)->getEvent()->getType() + ), + ) + ); + + $form->add('submit', SubmitType::class, array( + 'label' => 'Create' + )); + + return $form; + } + + /** + * show an edit form for the participation with the given id. + * + * @param int $participation_id + * @return \Symfony\Component\HttpFoundation\Response + * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException if the participation is not found + * @throws \Symfony\Component\HttpFoundation\File\Exception\AccessDeniedException if the user is not allowed to edit the participation + */ + public function editAction($participation_id) + { + /* @var $participation Participation */ + $participation = $this->getDoctrine()->getManager() + ->getRepository('ChillEventBundle:Participation') + ->find($participation_id); + + if ($participation === NULL) { + throw $this->createNotFoundException('The participation is not found'); + } + + $this->denyAccessUnlessGranted(ParticipationVoter::UPDATE, $participation, + 'You are not allowed to edit this participation'); + + $form = $this->createEditForm($participation); + + return $this->render('ChillEventBundle:Participation:edit.html.twig', array( + 'form' => $form->createView(), + 'participation' => $participation + )); + } + + /** + * @param $participation_id + * @param Request $request + * @return \Symfony\Component\HttpFoundation\RedirectResponse|Response + */ + public function updateAction($participation_id, Request $request) + { + /* @var $participation Participation */ + $participation = $this->getDoctrine()->getManager() + ->getRepository('ChillEventBundle:Participation') + ->find($participation_id); + + if ($participation === NULL) { + throw $this->createNotFoundException('The participation is not found'); + } + + $this->denyAccessUnlessGranted(ParticipationVoter::UPDATE, $participation, + 'You are not allowed to edit this participation'); + + $form = $this->createEditForm($participation); + + $form->handleRequest($request); + + if ($form->isSubmitted() && $form->isValid()) { + $em = $this->getDoctrine()->getManager(); + + $em->flush(); + + $this->addFlash('success', $this->get('translator')->trans( + 'The participation was updated' + )); + + return $this->redirectToRoute('chill_event__event_show', array( + 'event_id' => $participation->getEvent()->getId() + )); + + } + + return $this->render('ChillEventBundle:Participation:edit.html.twig', array( + 'form' => $form->createView(), + 'participation' => $participation + )); + } + + /** + * + * @param Participation $participation + * @return \Symfony\Component\Form\FormInterface + */ + public function createEditForm(Participation $participation) + { + $form = $this->createForm(ParticipationType::class, $participation, array( + 'event_type' => $participation->getEvent()->getType(), + 'action' => $this->generateUrl('chill_event_participation_update', array( + 'participation_id' => $participation->getId() + )) + )); + + $form->add('submit', SubmitType::class, array( + 'label' => 'Edit' + )); + + return $form; + } + + /** + * show a form to edit multiple participation for the same event. + * + * @param int $event_id + * @return \Symfony\Component\HttpFoundation\RedirectResponse|Response + */ + public function editMultipleAction($event_id) + { + $event = $this->getDoctrine()->getRepository('ChillEventBundle:Event') + ->find($event_id); + + if ($event === null) { + throw $this->createNotFoundException("The event with id $event_id is not found"); + } + + // check for ACL, on Event level and on Participation Level + $this->denyAccessUnlessGranted('CHILL_EVENT_SEE', $event, "You are not allowed " + . "to see this event"); + foreach ($event->getParticipations() as $participation) { + $this->denyAccessUnlessGranted(ParticipationVoter::UPDATE, $participation, + "You are not allowed to update participation with id ".$participation->getId()); + } + + + switch ($event->getParticipations()->count()) { + + case 0: + // if there aren't any participation, redirect to the 'show' view with an add flash + $this->addFlash('warning', $this->get('translator') + ->trans( "There are no participation to edit for this event")); + + return $this->redirectToRoute('chill_event__event_show', + array('event_id' => $event->getId())); + + case 1: + // redirect to the form for a single participation + return $this->redirectToRoute('chill_event_participation_edit', array( + 'participation_id' => $event->getParticipations()->current()->getId() + )); + } + + $form = $this->createEditFormMultiple($event->getParticipations(), $event); + + return $this->render('ChillEventBundle:Participation:edit-multiple.html.twig', array( + 'event' => $event, + 'participations' => $event->getParticipations(), + 'form' => $form->createView() + )); + } + + public function updateMultipleAction($event_id, Request $request) + { + /* @var $event \Chill\EventBundle\Entity\Event */ + $event = $this->getDoctrine()->getRepository('ChillEventBundle:Event') + ->find($event_id); + + if ($event === null) { + throw $this->createNotFoundException("The event with id $event_id is not found"); + } + + $this->denyAccessUnlessGranted('CHILL_EVENT_SEE', $event, "You are not allowed " + . "to see this event"); + foreach ($event->getParticipations() as $participation) { + $this->denyAccessUnlessGranted(ParticipationVoter::UPDATE, $participation, + "You are not allowed to update participation with id ".$participation->getId()); + } + + $form = $this->createEditFormMultiple($event->getParticipations(), $event); + + $form->handleRequest($request); + + if ($form->isSubmitted() && $form->isValid()) { + $this->getDoctrine()->getManager()->flush(); + + $this->addFlash('success', $this->get('translator')->trans("The participations " + . "have been successfully updated.")); + + return $this->redirectToRoute('chill_event__event_show', + array('event_id' => $event->getId())); + } + + return $this->render('ChillEventBundle:Participation:edit-multiple.html.twig', array( + 'event' => $event, + 'participations' => $event->getParticipations(), + 'form' => $form->createView() + )); + } + + /** + * @param ArrayIterator $participations + * @param Event $event + * @return \Symfony\Component\Form\FormInterface + */ + protected function createEditFormMultiple(ArrayIterator $participations, Event $event) + { + $form = $this->createForm(\Symfony\Component\Form\Extension\Core\Type\FormType::class, + array('participations' => $participations), array( + 'method' => 'POST', + 'action' => $this->generateUrl('chill_event_participation_update_multiple', array( + 'event_id' => $event->getId() + )) + )); + + $form->add('participations', CollectionType::class, array( + 'entry_type' => ParticipationType::class, + 'entry_options' => array( + 'event_type' => $event->getType() + ), + ) + ); + + $form->add('submit', SubmitType::class, array( + 'label' => 'Update' + )); + + return $form; + } + + /** + * @param integer $participation_id + * @param Request $request + * @return \Symfony\Component\HttpFoundation\RedirectResponse|Response + */ + public function deleteAction($participation_id, Request $request) + { + $em = $this->getDoctrine()->getManager(); + $participation = $em->getRepository('ChillEventBundle:Participation')->findOneBy([ + 'id' => $participation_id + ]); + + if (! $participation) { + throw $this->createNotFoundException('Unable to find participation.'); + } + + /** @var Event $event */ + $event = $participation->getEvent(); + + $form = $this->createDeleteForm($participation_id); + + if ($request->getMethod() === Request::METHOD_DELETE) { + $form->handleRequest($request); + + if ($form->isValid()) { + + $em->remove($participation); + $em->flush(); + + $this->addFlash('success', $this->get('translator') + ->trans("The participation has been sucessfully removed") + ); + + return $this->redirectToRoute('chill_event__event_show', [ + 'event_id' => $event->getId() + ]); + } + } + return $this->render('ChillEventBundle:Participation:confirm_delete.html.twig', [ + 'event_id' => $event->getId(), + 'delete_form' => $form->createView() + ]); + + } + + /** + * @param $participation_id + * @return \Symfony\Component\Form\FormInterface + */ + private function createDeleteForm($participation_id) + { + return $this->createFormBuilder() + ->setAction($this->generateUrl('chill_event_participation_delete', [ + 'participation_id' => $participation_id + ])) + ->setMethod('DELETE') + ->add('submit', SubmitType::class, ['label' => 'Delete']) + ->getForm() + ; + } + +} diff --git a/src/Bundle/ChillEvent/Controller/RoleController.php b/src/Bundle/ChillEvent/Controller/RoleController.php new file mode 100644 index 000000000..103729934 --- /dev/null +++ b/src/Bundle/ChillEvent/Controller/RoleController.php @@ -0,0 +1,228 @@ +getDoctrine()->getManager(); + + $entities = $em->getRepository('ChillEventBundle:Role')->findAll(); + + return $this->render('ChillEventBundle:Role:index.html.twig', array( + 'entities' => $entities, + )); + } + /** + * Creates a new Role entity. + * + */ + public function createAction(Request $request) + { + $entity = new Role(); + $form = $this->createCreateForm($entity); + $form->handleRequest($request); + + if ($form->isValid()) { + $em = $this->getDoctrine()->getManager(); + $em->persist($entity); + $em->flush(); + + return $this->redirect($this->generateUrl('chill_event_admin_role', + array('id' => $entity->getId()))); + } + + return $this->render('ChillEventBundle:Role:new.html.twig', array( + 'entity' => $entity, + 'form' => $form->createView(), + )); + } + + /** + * Creates a form to create a Role entity. + * + * @param Role $entity The entity + * + * @return \Symfony\Component\Form\Form The form + */ + private function createCreateForm(Role $entity) + { + $form = $this->createForm(RoleType::class, $entity, array( + 'action' => $this->generateUrl('chill_event_admin_role_create'), + 'method' => 'POST', + )); + + $form->add('submit', SubmitType::class, array('label' => 'Create')); + + return $form; + } + + /** + * Displays a form to create a new Role entity. + * + */ + public function newAction() + { + $entity = new Role(); + $form = $this->createCreateForm($entity); + + return $this->render('ChillEventBundle:Role:new.html.twig', array( + 'entity' => $entity, + 'form' => $form->createView(), + )); + } + + /** + * Finds and displays a Role entity. + * + */ + public function showAction($id) + { + $em = $this->getDoctrine()->getManager(); + + $entity = $em->getRepository('ChillEventBundle:Role')->find($id); + + if (!$entity) { + throw $this->createNotFoundException('Unable to find Role entity.'); + } + + $deleteForm = $this->createDeleteForm($id); + + return $this->render('ChillEventBundle:Role:show.html.twig', array( + 'entity' => $entity, + 'delete_form' => $deleteForm->createView(), + )); + } + + /** + * Displays a form to edit an existing Role entity. + * + */ + public function editAction($id) + { + $em = $this->getDoctrine()->getManager(); + + $entity = $em->getRepository('ChillEventBundle:Role')->find($id); + + if (!$entity) { + throw $this->createNotFoundException('Unable to find Role entity.'); + } + + $editForm = $this->createEditForm($entity); + $deleteForm = $this->createDeleteForm($id); + + return $this->render('ChillEventBundle:Role:edit.html.twig', array( + 'entity' => $entity, + 'edit_form' => $editForm->createView(), + 'delete_form' => $deleteForm->createView(), + )); + } + + /** + * Creates a form to edit a Role entity. + * + * @param Role $entity The entity + * + * @return \Symfony\Component\Form\Form The form + */ + private function createEditForm(Role $entity) + { + $form = $this->createForm(RoleType::class, $entity, array( + 'action' => $this->generateUrl('chill_event_admin_role_update', + array('id' => $entity->getId())), + 'method' => 'PUT', + )); + + $form->add('submit', SubmitType::class, array('label' => 'Update')); + + return $form; + } + /** + * Edits an existing Role entity. + * + */ + public function updateAction(Request $request, $id) + { + $em = $this->getDoctrine()->getManager(); + + $entity = $em->getRepository('ChillEventBundle:Role')->find($id); + + if (!$entity) { + throw $this->createNotFoundException('Unable to find Role entity.'); + } + + $deleteForm = $this->createDeleteForm($id); + $editForm = $this->createEditForm($entity); + $editForm->handleRequest($request); + + if ($editForm->isValid()) { + $em->flush(); + + return $this->redirect($this->generateUrl('chill_event_admin_role', + array('id' => $id))); + } + + return $this->render('ChillEventBundle:Role:edit.html.twig', array( + 'entity' => $entity, + 'edit_form' => $editForm->createView(), + 'delete_form' => $deleteForm->createView(), + )); + } + /** + * Deletes a Role entity. + * + */ + public function deleteAction(Request $request, $id) + { + $form = $this->createDeleteForm($id); + $form->handleRequest($request); + + if ($form->isValid()) { + $em = $this->getDoctrine()->getManager(); + $entity = $em->getRepository('ChillEventBundle:Role')->find($id); + + if (!$entity) { + throw $this->createNotFoundException('Unable to find Role entity.'); + } + + $em->remove($entity); + $em->flush(); + } + + return $this->redirect($this->generateUrl('chill_event_admin_role')); + } + + /** + * Creates a form to delete a Role entity by id. + * + * @param mixed $id The entity id + * + * @return \Symfony\Component\Form\Form The form + */ + private function createDeleteForm($id) + { + return $this->createFormBuilder() + ->setAction($this->generateUrl('chill_event_admin_role_delete', array('id' => $id))) + ->setMethod('DELETE') + ->add('submit', SubmitType::class, array('label' => 'Delete')) + ->getForm() + ; + } +} diff --git a/src/Bundle/ChillEvent/Controller/StatusController.php b/src/Bundle/ChillEvent/Controller/StatusController.php new file mode 100644 index 000000000..e5861aa80 --- /dev/null +++ b/src/Bundle/ChillEvent/Controller/StatusController.php @@ -0,0 +1,226 @@ +getDoctrine()->getManager(); + + $entities = $em->getRepository('ChillEventBundle:Status')->findAll(); + + return $this->render('ChillEventBundle:Status:index.html.twig', array( + 'entities' => $entities, + )); + } + /** + * Creates a new Status entity. + * + */ + public function createAction(Request $request) + { + $entity = new Status(); + $form = $this->createCreateForm($entity); + $form->handleRequest($request); + + if ($form->isValid()) { + $em = $this->getDoctrine()->getManager(); + $em->persist($entity); + $em->flush(); + + return $this->redirect($this->generateUrl('chill_event_admin_status', array('id' => $entity->getId()))); + } + + return $this->render('ChillEventBundle:Status:new.html.twig', array( + 'entity' => $entity, + 'form' => $form->createView(), + )); + } + + /** + * Creates a form to create a Status entity. + * + * @param Status $entity The entity + * + * @return \Symfony\Component\Form\Form The form + */ + private function createCreateForm(Status $entity) + { + $form = $this->createForm(StatusType::class, $entity, array( + 'action' => $this->generateUrl('chill_event_admin_status_create'), + 'method' => 'POST', + )); + + $form->add('submit', SubmitType::class, array('label' => 'Create')); + + return $form; + } + + /** + * Displays a form to create a new Status entity. + * + */ + public function newAction() + { + $entity = new Status(); + $form = $this->createCreateForm($entity); + + return $this->render('ChillEventBundle:Status:new.html.twig', array( + 'entity' => $entity, + 'form' => $form->createView(), + )); + } + + /** + * Finds and displays a Status entity. + * + */ + public function showAction($id) + { + $em = $this->getDoctrine()->getManager(); + + $entity = $em->getRepository('ChillEventBundle:Status')->find($id); + + if (!$entity) { + throw $this->createNotFoundException('Unable to find Status entity.'); + } + + $deleteForm = $this->createDeleteForm($id); + + return $this->render('ChillEventBundle:Status:show.html.twig', array( + 'entity' => $entity, + 'delete_form' => $deleteForm->createView(), + )); + } + + /** + * Displays a form to edit an existing Status entity. + * + */ + public function editAction($id) + { + $em = $this->getDoctrine()->getManager(); + + $entity = $em->getRepository('ChillEventBundle:Status')->find($id); + + if (!$entity) { + throw $this->createNotFoundException('Unable to find Status entity.'); + } + + $editForm = $this->createEditForm($entity); + $deleteForm = $this->createDeleteForm($id); + + return $this->render('ChillEventBundle:Status:edit.html.twig', array( + 'entity' => $entity, + 'edit_form' => $editForm->createView(), + 'delete_form' => $deleteForm->createView(), + )); + } + + /** + * Creates a form to edit a Status entity. + * + * @param Status $entity The entity + * + * @return \Symfony\Component\Form\Form The form + */ + private function createEditForm(Status $entity) + { + $form = $this->createForm(StatusType::class, $entity, array( + 'action' => $this->generateUrl('chill_event_admin_status_update', array('id' => $entity->getId())), + 'method' => 'PUT', + )); + + $form->add('submit', SubmitType::class, array('label' => 'Update')); + + return $form; + } + /** + * Edits an existing Status entity. + * + */ + public function updateAction(Request $request, $id) + { + $em = $this->getDoctrine()->getManager(); + + $entity = $em->getRepository('ChillEventBundle:Status')->find($id); + + if (!$entity) { + throw $this->createNotFoundException('Unable to find Status entity.'); + } + + $deleteForm = $this->createDeleteForm($id); + $editForm = $this->createEditForm($entity); + $editForm->handleRequest($request); + + if ($editForm->isValid()) { + $em->flush(); + + return $this->redirect($this->generateUrl('chill_event_admin_status', array('id' => $id))); + } + + return $this->render('ChillEventBundle:Status:edit.html.twig', array( + 'entity' => $entity, + 'edit_form' => $editForm->createView(), + 'delete_form' => $deleteForm->createView(), + )); + } + /** + * Deletes a Status entity. + * + */ + public function deleteAction(Request $request, $id) + { + $form = $this->createDeleteForm($id); + $form->handleRequest($request); + + if ($form->isValid()) { + $em = $this->getDoctrine()->getManager(); + $entity = $em->getRepository('ChillEventBundle:Status')->find($id); + + if (!$entity) { + throw $this->createNotFoundException('Unable to find Status entity.'); + } + + $em->remove($entity); + $em->flush(); + } + + return $this->redirect($this->generateUrl('chill_event_admin_status')); + } + + /** + * Creates a form to delete a Status entity by id. + * + * @param mixed $id The entity id + * + * @return \Symfony\Component\Form\Form The form + */ + private function createDeleteForm($id) + { + return $this->createFormBuilder() + ->setAction($this->generateUrl('chill_event_admin_status_delete', array('id' => $id))) + ->setMethod('DELETE') + ->add('submit', SubmitType::class, array('label' => 'Delete')) + ->getForm() + ; + } +} diff --git a/src/Bundle/ChillEvent/DataFixtures/ORM/LoadEventTypes.php b/src/Bundle/ChillEvent/DataFixtures/ORM/LoadEventTypes.php new file mode 100644 index 000000000..148582ca3 --- /dev/null +++ b/src/Bundle/ChillEvent/DataFixtures/ORM/LoadEventTypes.php @@ -0,0 +1,286 @@ + + * @author Champs Libres + */ +class LoadEventTypes extends AbstractFixture implements OrderedFixtureInterface +{ + public static $refs = array(); + + public function getOrder() + { + return 30000; + } + + public function load(ObjectManager $manager) + { + /* + * Echange de savoirs + */ + $type = (new EventType()) + ->setActive(true) + ->setName(array('fr' => 'Échange de savoirs', 'en' => 'Exchange of knowledge')) + ; + $manager->persist($type); + + $this->addReference('event_type_knowledge', $type); + self::$refs[] = 'event_type_knowledge'; + + $role = (new Role()) + ->setActive(true) + ->setName(array('fr' => 'Participant', 'nl' => 'Deelneemer', 'en' => 'Participant')) + ->setType($type) + ; + $manager->persist($role); + + $role = (new Role()) + ->setActive(true) + ->setName(array('fr' => 'Animateur')) + ->setType($type); + $manager->persist($role); + + $status = (new Status()) + ->setActive(true) + ->setName(array('fr' => 'Inscrit')) + ->setType($type); + $manager->persist($status); + + $status = (new Status()) + ->setActive(true) + ->setName(array('fr' => 'Présent')) + ->setType($type) + ; + $manager->persist($status); + + /* + * Formation + */ + $type = (new EventType()) + ->setActive(true) + ->setName(array('fr' => 'Formation', 'en' => 'Course', 'nl' => 'Opleiding')) + ; + $manager->persist($type); + + $this->addReference('event_type_course', $type); + self::$refs[] = 'event_type_course'; + + $role = (new Role()) + ->setActive(true) + ->setName(array('fr' => 'Participant', 'nl' => 'Deelneemer', 'en' => 'Participant')) + ->setType($type) + ; + $manager->persist($role); + + $status = (new Status()) + ->setActive(true) + ->setName(array('fr' => 'Inscrit')) + ->setType($type) + ; + $manager->persist($status); + + $status = (new Status()) + ->setActive(true) + ->setName(array('fr' => 'En liste d\'attente')) + ->setType($type) + ; + $manager->persist($status); + + /* + * Visite + */ + $type = (new EventType()) + ->setActive(true) + ->setName(array('fr' => 'Visite', 'en' => 'Visit')) + ; + $manager->persist($type); + + $this->addReference('event_type_visit', $type); + self::$refs[] = 'event_type_visit'; + + $role = (new Role()) + ->setActive(true) + ->setName(array('fr' => 'Participant', 'nl' => 'Deelneemer', 'en' => 'Participant')) + ->setType($type) + ; + $manager->persist($role); + + $status = (new Status()) + ->setActive(true) + ->setName(array('fr' => 'Présent')) + ->setType($type) + ; + $manager->persist($status); + + $status = (new Status()) + ->setActive(true) + ->setName(array('fr' => 'Absent')) + ->setType($type) + ; + $manager->persist($status); + + $status = (new Status()) + ->setActive(true) + ->setName(array('fr' => 'Excusé')) + ->setType($type) + ; + $manager->persist($status); + + $status = (new Status()) + ->setActive(true) + ->setName(array('fr' => 'Inscrit')) + ->setType($type) + ; + $manager->persist($status); + + /* + * Réunion + */ + $type = (new EventType()) + ->setActive(true) + ->setName(array('fr' => 'Réunion', 'en' => 'Meeting')) + ; + $manager->persist($type); + + $this->addReference('event_type_meeting', $type); + self::$refs[] = 'event_type_meeting'; + + $role = (new Role()) + ->setActive(true) + ->setName(array('fr' => 'Participant', 'nl' => 'Deelneemer', 'en' => 'Participant')) + ->setType($type) + ; + $manager->persist($role); + + $status = (new Status()) + ->setActive(true) + ->setName(array('fr' => 'Présent')) + ->setType($type) + ; + $manager->persist($status); + + $status = (new Status()) + ->setActive(true) + ->setName(array('fr' => 'Absent')) + ->setType($type) + ; + $manager->persist($status); + + $status = (new Status()) + ->setActive(true) + ->setName(array('fr' => 'Excusé')) + ->setType($type) + ; + $manager->persist($status); + + /* + * Atelier + */ + $type = (new EventType()) + ->setActive(true) + ->setName(array('fr' => 'Atelier', 'en' => 'Workshop')) + ; + $manager->persist($type); + + $this->addReference('event_type_workshop', $type); + self::$refs[] = 'event_type_workshop'; + + $role = (new Role()) + ->setActive(true) + ->setName(array('fr' => 'Participant', 'nl' => 'Deelneemer', 'en' => 'Participant')) + ->setType($type) + ; + $manager->persist($role); + + $status = (new Status()) + ->setActive(true) + ->setName(array('fr' => 'Présent')) + ->setType($type) + ; + $manager->persist($status); + + $status = (new Status()) + ->setActive(true) + ->setName(array('fr' => 'Absent')) + ->setType($type) + ; + $manager->persist($status); + + $status = (new Status()) + ->setActive(true) + ->setName(array('fr' => 'Excusé')) + ->setType($type) + ; + $manager->persist($status); + + $status = (new Status()) + ->setActive(true) + ->setName(array('fr' => 'Inscrit')) + ->setType($type) + ; + $manager->persist($status); + + + /* + * Séance d'info + */ + $type = (new EventType()) + ->setActive(true) + ->setName(array('fr' => "Séance d'info", 'en' => 'Info')) + ; + $manager->persist($type); + + $this->addReference('event_type_info', $type); + self::$refs[] = 'event_type_info'; + + $role = (new Role()) + ->setActive(true) + ->setName(array('fr' => 'Participant', 'nl' => 'Deelneemer', 'en' => 'Participant')) + ->setType($type) + ; + $manager->persist($role); + + $status = (new Status()) + ->setActive(true) + ->setName(array('fr' => 'Présent')) + ->setType($type) + ; + $manager->persist($status); + + $status = (new Status()) + ->setActive(true) + ->setName(array('fr' => 'Absent')) + ->setType($type) + ; + $manager->persist($status); + + $status = (new Status()) + ->setActive(true) + ->setName(array('fr' => 'Excusé')) + ->setType($type) + ; + $manager->persist($status); + + $status = (new Status()) + ->setActive(true) + ->setName(array('fr' => 'Inscrit')) + ->setType($type) + ; + $manager->persist($status); + + + $manager->flush(); + } +} diff --git a/src/Bundle/ChillEvent/DataFixtures/ORM/LoadParticipation.php b/src/Bundle/ChillEvent/DataFixtures/ORM/LoadParticipation.php new file mode 100644 index 000000000..b89937abe --- /dev/null +++ b/src/Bundle/ChillEvent/DataFixtures/ORM/LoadParticipation.php @@ -0,0 +1,98 @@ + + * @author Champs Libres + */ +class LoadParticipation extends AbstractFixture implements OrderedFixtureInterface +{ + /** + * + * @var \Faker\Generator + */ + protected $faker; + + public function __construct() + { + $this->faker = \Faker\Factory::create('fr_FR'); + } + + public function getOrder() + { + return 30010; + } + + public function load(ObjectManager $manager) + { + $centers = $manager->getRepository('ChillMainBundle:Center') + ->findAll(); + + foreach($centers as $center) { + + $people = $manager->getRepository('ChillPersonBundle:Person') + ->findBy(array('center' => $center)); + $events = $this->createEvents($center, $manager); + + /* @var $person \Chill\PersonBundle\Entity\Person */ + foreach ($people as $person) { + $nb = rand(0,3); + + for ($i=0; $i<$nb; $i++) { + $event = $events[array_rand($events)]; + $role = $event->getType()->getRoles()->get( + array_rand($event->getType()->getRoles()->toArray())); + $status = $event->getType()->getStatuses()->get( + array_rand($event->getType()->getStatuses()->toArray())); + + $participation = (new Participation()) + ->setPerson($person) + ->setRole($role) + ->setStatus($status) + ->setEvent($event) + ; + $manager->persist($participation); + } + } + } + + $manager->flush(); + + + } + + public function createEvents(Center $center, ObjectManager $manager) + { + $expectedNumber = 20; + $events = array(); + + for($i=0; $i<$expectedNumber; $i++) { + $event = (new Event()) + ->setDate($this->faker->dateTimeBetween('-2 years', '+6 months')) + ->setName($this->faker->words(rand(2,4), true)) + ->setType($this->getReference(LoadEventTypes::$refs[array_rand(LoadEventTypes::$refs)])) + ->setCenter($center) + ->setCircle( + $this->getReference( + LoadScopes::$references[array_rand(LoadScopes::$references)] + ) + ) + ; + $manager->persist($event); + $events[] = $event; + } + + return $events; + } +} diff --git a/src/Bundle/ChillEvent/DataFixtures/ORM/LoadRolesACL.php b/src/Bundle/ChillEvent/DataFixtures/ORM/LoadRolesACL.php new file mode 100644 index 000000000..7ef753e52 --- /dev/null +++ b/src/Bundle/ChillEvent/DataFixtures/ORM/LoadRolesACL.php @@ -0,0 +1,111 @@ + + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + + +namespace Chill\EventBundle\DataFixtures\ORM; + +use Doctrine\Common\DataFixtures\AbstractFixture; +use Doctrine\Common\DataFixtures\OrderedFixtureInterface; +use Chill\MainBundle\DataFixtures\ORM\LoadPermissionsGroup; +use Chill\MainBundle\Entity\RoleScope; +use Chill\MainBundle\DataFixtures\ORM\LoadScopes; +use Doctrine\Persistence\ObjectManager; + +/** + * Add roles to existing groups + * + * @author Julien Fastré + * @author Champs Libres + */ +class LoadRolesACL extends AbstractFixture implements OrderedFixtureInterface +{ + public function load(ObjectManager $manager) + { + foreach (LoadPermissionsGroup::$refs as $permissionsGroupRef) { + $permissionsGroup = $this->getReference($permissionsGroupRef); + foreach (LoadScopes::$references as $scopeRef){ + $scope = $this->getReference($scopeRef); + //create permission group + switch ($permissionsGroup->getName()) { + case 'social': + if ($scope->getName()['en'] === 'administrative') { + break 2; // we do not want any power on administrative + } + break; + case 'administrative': + case 'direction': + if (in_array($scope->getName()['en'], array('administrative', 'social'))) { + break 2; // we do not want any power on social or administrative + } + break; + } + + printf("Adding CHILL_EVENT_UPDATE & CHILL_EVENT_CREATE " + . "& CHILL_EVENT_PARTICIPATION_UPDATE & CHILL_EVENT_PARTICIPATION_CREATE " + . "& CHILL_EVENT_SEE & CHILL_EVENT_SEE_DETAILS " + . "to %s " + . "permission group, scope '%s' \n", + $permissionsGroup->getName(), $scope->getName()['en']); + + $roleScopeUpdate = (new RoleScope()) + ->setRole('CHILL_EVENT_UPDATE') + ->setScope($scope); + $roleScopeUpdate2 = (new RoleScope()) + ->setRole('CHILL_EVENT_PARTICIPATION_UPDATE') + ->setScope($scope); + $permissionsGroup->addRoleScope($roleScopeUpdate); + $permissionsGroup->addRoleScope($roleScopeUpdate2); + + $roleScopeCreate = (new RoleScope()) + ->setRole('CHILL_EVENT_CREATE') + ->setScope($scope); + $roleScopeCreate2 = (new RoleScope()) + ->setRole('CHILL_EVENT_PARTICIPATION_CREATE') + ->setScope($scope); + $permissionsGroup->addRoleScope($roleScopeCreate); + $permissionsGroup->addRoleScope($roleScopeCreate2); + + $roleScopeSee = (new RoleScope()) + ->setRole('CHILL_EVENT_SEE') + ->setScope($scope); + $roleScopeSee2 = (new RoleScope()) + ->setRole('CHILL_EVENT_SEE_DETAILS') + ->setScope($scope); + $permissionsGroup->addRoleScope($roleScopeSee); + $permissionsGroup->addRoleScope($roleScopeSee2); + + $manager->persist($roleScopeUpdate); + $manager->persist($roleScopeUpdate2); + $manager->persist($roleScopeCreate); + $manager->persist($roleScopeCreate2); + $manager->persist($roleScopeSee); + $manager->persist($roleScopeSee2); + } + + } + + $manager->flush(); + } + + public function getOrder() + { + return 30011; + } + +} diff --git a/src/Bundle/ChillEvent/DependencyInjection/ChillEventExtension.php b/src/Bundle/ChillEvent/DependencyInjection/ChillEventExtension.php new file mode 100644 index 000000000..639d3068d --- /dev/null +++ b/src/Bundle/ChillEvent/DependencyInjection/ChillEventExtension.php @@ -0,0 +1,80 @@ +processConfiguration($configuration, $configs); + + $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../config')); + $loader->load('services.yaml'); + $loader->load('services/authorization.yaml'); + $loader->load('services/controller.yaml'); + $loader->load('services/fixtures.yaml'); + $loader->load('services/forms.yaml'); + $loader->load('services/menu.yaml'); + $loader->load('services/repositories.yaml'); + $loader->load('services/search.yaml'); + $loader->load('services/timeline.yaml'); + } + + /* (non-PHPdoc) + * @see \Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface::prepend() + */ + public function prepend(ContainerBuilder $container) + { + $this->prependAuthorization($container); + $this->prependRoute($container); + } + + /** + * add route to route loader for chill + * + * @param ContainerBuilder $container + */ + protected function prependRoute(ContainerBuilder $container) + { + //add routes for custom bundle + $container->prependExtensionConfig('chill_main', array( + 'routing' => array( + 'resources' => array( + '@ChillEventBundle/config/routes.yaml' + ) + ) + )); + } + + /** + * add authorization hierarchy + * + * @param ContainerBuilder $container + */ + protected function prependAuthorization(ContainerBuilder $container) + { + $container->prependExtensionConfig('security', array( + 'role_hierarchy' => array( + EventVoter::SEE_DETAILS => array(EventVoter::SEE), + EventVoter::UPDATE => array(EventVoter::SEE_DETAILS), + EventVoter::CREATE => array(EventVoter::SEE_DETAILS) + ) + )); + } +} diff --git a/src/Bundle/ChillEvent/DependencyInjection/Configuration.php b/src/Bundle/ChillEvent/DependencyInjection/Configuration.php new file mode 100644 index 000000000..14cbddafe --- /dev/null +++ b/src/Bundle/ChillEvent/DependencyInjection/Configuration.php @@ -0,0 +1,29 @@ +getRootNode('chill_event'); + + // Here you should define the parameters that are allowed to + // configure your bundle. See the documentation linked above for + // more information on that topic. + + return $treeBuilder; + } +} diff --git a/src/Bundle/ChillEvent/Entity/Event.php b/src/Bundle/ChillEvent/Entity/Event.php new file mode 100644 index 000000000..a92bf8b26 --- /dev/null +++ b/src/Bundle/ChillEvent/Entity/Event.php @@ -0,0 +1,295 @@ + + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +namespace Chill\EventBundle\Entity; + +use Doctrine\ORM\Mapping as ORM; +use Chill\MainBundle\Entity\User; +use Chill\MainBundle\Entity\Center; +use Chill\MainBundle\Entity\Scope; +use Doctrine\Common\Collections\Collection; +use Doctrine\Common\Collections\ArrayCollection; +use Chill\MainBundle\Entity\HasCenterInterface; +use Chill\MainBundle\Entity\HasScopeInterface; + +/** + * Class Event + * + * @package Chill\EventBundle\Entity + * @ORM\Entity(repositoryClass="Chill\EventBundle\Repository\EventRepository") + * @ORM\Table(name="chill_event_event") + * @ORM\HasLifecycleCallbacks() + */ +class Event implements HasCenterInterface, HasScopeInterface +{ + /** + * @var integer + * + * @ORM\Id + * @ORM\Column(name="id", type="integer") + * @ORM\GeneratedValue(strategy="AUTO") + */ + private $id; + + /** + * @var string + * @ORM\Column(type="string", length=150) + */ + private $name; + + /** + * @var \DateTime + * @ORM\Column(type="datetime") + */ + private $date; + + /** + * + * @var Center + * @ORM\ManyToOne(targetEntity="Chill\MainBundle\Entity\Center") + */ + private $center; + + /** + * + * @var EventType + * @ORM\ManyToOne(targetEntity="Chill\EventBundle\Entity\EventType") + */ + private $type; + + /** + * + * @var Scope + * @ORM\ManyToOne(targetEntity="Chill\MainBundle\Entity\Scope") + */ + private $circle; + + /** + * @var Participation + * @ORM\OneToMany( + * targetEntity="Chill\EventBundle\Entity\Participation", + * mappedBy="event") + */ + private $participations; + + /** + * + * @var User + * @ORM\ManyToOne(targetEntity="Chill\MainBundle\Entity\User") + */ + private $moderator; + + + /** + * Event constructor. + */ + public function __construct() + { + $this->participations = new ArrayCollection(); + } + + /** + * Get id + * + * @return integer + */ + public function getId() + { + return $this->id; + } + + /** + * Set label + * + * @param string $label + * @return Event + */ + public function setName($label) + { + $this->name = $label; + + return $this; + } + + /** + * Get label + * + * @return string + */ + public function getName() + { + return $this->name; + } + + /** + * Set date + * + * @param \DateTime $date + * @return Event + */ + public function setDate(\DateTime $date) + { + $this->date = $date; + + return $this; + } + + /** + * Get date + * + * @return \DateTime + */ + public function getDate() + { + return $this->date; + } + + /** + * @param Center $center + * @return $this + */ + public function setCenter(Center $center) + { + $this->center = $center; + + return $this; + } + + /** + * @return EventType + */ + public function getType() + { + return $this->type; + } + + /** + * @param EventType $type + * @return $this + */ + public function setType(EventType $type) + { + $this->type = $type; + return $this; + } + + /** + * @return Center + */ + public function getCenter() + { + return $this->center; + } + + /** + * @return Scope + */ + public function getCircle() + { + return $this->circle; + } + + /** + * @param Scope $circle + * @return $this + */ + public function setCircle(\Chill\MainBundle\Entity\Scope $circle) + { + $this->circle = $circle; + return $this; + } + + /** + * @deprecated + * @return Scope + */ + public function getScope() + { + return $this->getCircle(); + } + + + /** + * Add participation + * + * @param Participation $participation + * @return Event + */ + public function addParticipation(Participation $participation) + { + $this->participations[] = $participation; + + return $this; + } + + /** + * Remove participation + * + * @param Participation $participation + */ + public function removeParticipation(Participation $participation) + { + $this->participations->removeElement($participation); + } + + /** + * @return \ArrayIterator|\Traversable|Collection + */ + public function getParticipations() + { + return $this->getParticipationsOrdered(); + } + + /** + * Sort Collection of Participations + * + * @return \ArrayIterator|\Traversable + */ + public function getParticipationsOrdered() { + + $iterator = $this->participations->getIterator(); + + $iterator->uasort(function($first, $second) + { + return strnatcasecmp($first->getPerson()->getFirstName(), $second->getPerson()->getFirstName()); + }); + + return $iterator; + } + + /** + * @return int + */ + public function getModerator() + { + return $this->moderator; + } + + /** + * @param int $moderator + * @return Event + */ + public function setModerator($moderator) + { + $this->moderator = $moderator; + return $this; + } +} diff --git a/src/Bundle/ChillEvent/Entity/EventType.php b/src/Bundle/ChillEvent/Entity/EventType.php new file mode 100644 index 000000000..8c67d8c81 --- /dev/null +++ b/src/Bundle/ChillEvent/Entity/EventType.php @@ -0,0 +1,205 @@ + + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +namespace Chill\EventBundle\Entity; + +use Doctrine\ORM\Mapping as ORM; +use Doctrine\Common\Collections\Collection; +use Doctrine\Common\Collections\ArrayCollection; + +/** + * Class EventType + * + * @package Chill\EventBundle\Entity + * @ORM\Entity() + * @ORM\Table(name="chill_event_event_type") + * @ORM\HasLifecycleCallbacks() + */ +class EventType +{ + /** + * @var integer + * + * @ORM\Id + * @ORM\Column(name="id", type="integer") + * @ORM\GeneratedValue(strategy="AUTO") + */ + private $id; + + /** + * @var array + * @ORM\Column(type="json_array") + */ + private $name; + + /** + * @var boolean + * @ORM\Column(type="boolean") + */ + private $active; + + /** + * @var Collection + * @ORM\OneToMany( + * targetEntity="Chill\EventBundle\Entity\Role", + * mappedBy="type") + */ + private $roles; + + /** + * @var Collection + * @ORM\OneToMany( + * targetEntity="Chill\EventBundle\Entity\Status", + * mappedBy="type") + */ + private $statuses; + + /** + * Constructor + */ + public function __construct() + { + $this->roles = new ArrayCollection(); + $this->statuses = new ArrayCollection(); + } + + /** + * Get id + * + * @return integer + */ + public function getId() + { + return $this->id; + } + + /** + * Set label + * + * @param array $label + * @return EventType + */ + public function setName($label) + { + $this->name = $label; + + return $this; + } + + /** + * Get label + * + * @return array + */ + public function getName() + { + return $this->name; + } + + /** + * Set active + * + * @param boolean $active + * @return EventType + */ + public function setActive($active) + { + $this->active = $active; + + return $this; + } + + /** + * Get active + * + * @return boolean + */ + public function getActive() + { + return $this->active; + } + + /** + * Add role + * + * @param Role $role + * @return EventType + */ + public function addRole(Role $role) + { + $this->roles[] = $role; + + return $this; + } + + /** + * Remove role + * + * @param Role $role + */ + public function removeRole(Role $role) + { + $this->roles->removeElement($role); + } + + /** + * Get roles + * + * @return Collection + */ + public function getRoles() + { + return $this->roles; + } + + /** + * Add status + * + * @param Status $status + * @return EventType + */ + public function addStatus(Status $status) + { + $this->statuses[] = $status; + + return $this; + } + + /** + * Remove status + * + * @param Status $status + */ + public function removeStatus(Status $status) + { + $this->statuses->removeElement($status); + } + + /** + * Get statuses + * + * @return Collection + */ + public function getStatuses() + { + return $this->statuses; + } +} diff --git a/src/Bundle/ChillEvent/Entity/Participation.php b/src/Bundle/ChillEvent/Entity/Participation.php new file mode 100644 index 000000000..d578db863 --- /dev/null +++ b/src/Bundle/ChillEvent/Entity/Participation.php @@ -0,0 +1,346 @@ + + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +namespace Chill\EventBundle\Entity; + +use Doctrine\ORM\Mapping as ORM; +use Chill\MainBundle\Entity\Center; +use Chill\MainBundle\Entity\Scope; +use Chill\PersonBundle\Entity\Person; +use Chill\MainBundle\Entity\HasScopeInterface; +use Chill\MainBundle\Entity\HasCenterInterface; +use Symfony\Component\Validator\Context\ExecutionContextInterface; + +/** + * Class Participation + * + * @package Chill\EventBundle\Entity + * @ORM\Entity( + * repositoryClass="Chill\EventBundle\Repository\ParticipationRepository") + * @ORM\Table(name="chill_event_participation") + * @ORM\HasLifecycleCallbacks() + */ +class Participation implements HasCenterInterface, HasScopeInterface, \ArrayAccess +{ + /** + * @var integer + * + * @ORM\Id + * @ORM\Column(name="id", type="integer") + * @ORM\GeneratedValue(strategy="AUTO") + */ + private $id; + + /** + * @var \DateTime + * @ORM\Column(type="datetime") + */ + private $lastUpdate; + + /** + * @var Event + * @ORM\ManyToOne( + * targetEntity="Chill\EventBundle\Entity\Event", + * inversedBy="participations") + */ + private $event; + + /** + * @var Person + * @ORM\ManyToOne(targetEntity="Chill\PersonBundle\Entity\Person") + */ + private $person; + + /** + * @var Role + * @ORM\ManyToOne(targetEntity="Chill\EventBundle\Entity\Role") + */ + private $role; + + /** + * @var Status + * @ORM\ManyToOne(targetEntity="Chill\EventBundle\Entity\Status") + */ + private $status; + + + /** + * Get id + * + * @return integer + */ + public function getId() + { + return $this->id; + } + + /** + * Set lastUpdate + * + * @param \DateTime $lastUpdate + * @return Participation + */ + protected function update() + { + $this->lastUpdate = new \DateTime('now'); + + return $this; + } + + /** + * Get lastUpdate + * + * @return \DateTime + */ + public function getLastUpdate() + { + return $this->lastUpdate; + } + + + /** + * Set event + * + * @param Event $event + * @return Participation + */ + public function setEvent(Event $event = null) + { + if ($this->event !== $event) { + $this->update(); + } + + $this->event = $event; + + return $this; + } + + /** + * Get event + * + * @return Event + */ + public function getEvent() + { + return $this->event; + } + + /** + * Set person + * + * @param Person $person + * @return Participation + */ + public function setPerson(Person $person = null) + { + if ($person !== $this->person) { + $this->update(); + } + + $this->person = $person; + + return $this; + } + + /** + * Get person + * + * @return Person + */ + public function getPerson() + { + return $this->person; + } + + /** + * Set role + * + * @param Role $role + * @return Participation + */ + public function setRole(Role $role = null) + { + if ($role !== $this->role) { + $this->update(); + } + $this->role = $role; + + return $this; + } + + /** + * Get role + * + * @return Role + */ + public function getRole() + { + return $this->role; + } + + /** + * Set status + * + * @param Status $status + * @return Participation + */ + public function setStatus(Status $status = null) + { + if ($this->status !== $status) { + $this->update(); + } + + $this->status = $status; + + return $this; + } + + /** + * Get status + * + * @return Status + */ + public function getStatus() + { + return $this->status; + } + + /** + * @return Center + */ + public function getCenter() + { + if ($this->getEvent() === NULL) { + throw new \RuntimeException('The event is not linked with this instance. ' + . 'You should initialize the event with a valid center before.'); + } + + return $this->getEvent()->getCenter(); + } + + /** + * @return Scope + */ + public function getScope() + { + if ($this->getEvent() === NULL) { + throw new \RuntimeException('The event is not linked with this instance. ' + . 'You should initialize the event with a valid center before.'); + } + + return $this->getEvent()->getCircle(); + } + + /** + * Check that : + * + * - the role can be associated with this event type + * - the status can be associated with this event type + * + * @param ExecutionContextInterface $context + */ + public function isConsistent(ExecutionContextInterface $context) + { + + if ($this->getEvent() === NULL || $this->getRole() === NULL || $this->getStatus() === NULL) { + return; + } + + if ($this->getRole()->getType()->getId() !== + $this->getEvent()->getType()->getId()) { + $context->buildViolation('The role is not allowed with this event type') + ->atPath('role') + ->addViolation(); + } + + if ($this->getStatus()->getType()->getId() !== + $this->getEvent()->getType()->getId()) { + $context->buildViolation('The status is not allowed with this event type') + ->atPath('status') + ->addViolation(); + } + } + + /** + * @param mixed $offset + * @return bool + */ + public function offsetExists($offset) + { + return in_array($offset, array( + 'person', 'role', 'status', 'event' + )); + } + + /** + * @param mixed $offset + * @return Event|Role|Status|Person|mixed + */ + public function offsetGet($offset) + { + switch ($offset) { + case 'person': + return $this->getPerson(); + break; + case 'role': + return $this->getRole(); + break; + case 'status': + return $this->getStatus(); + break; + case 'event': + return $this->getEvent(); + break; + } + } + + /** + * @param mixed $offset + * @param mixed $value + * @return Participation|void + */ + public function offsetSet($offset, $value) + { + switch($offset) { + case 'person': + return $this->setPerson($value); + break; + case 'role': + return $this->setRole($value); + break; + case 'status': + return $this->setStatus($value); + break; + case 'event': + return $this->setEvent($value); + break; + } + } + + /** + * @param mixed $offset + */ + public function offsetUnset($offset) + { + $this->offsetSet($offset, null); + } + +} diff --git a/src/Bundle/ChillEvent/Entity/Role.php b/src/Bundle/ChillEvent/Entity/Role.php new file mode 100644 index 000000000..cf7d3a243 --- /dev/null +++ b/src/Bundle/ChillEvent/Entity/Role.php @@ -0,0 +1,145 @@ + + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +namespace Chill\EventBundle\Entity; + +use Doctrine\ORM\Mapping as ORM; + +/** + * Class Role + * + * @package Chill\EventBundle\Entity + * @ORM\Entity() + * @ORM\Table(name="chill_event_role") + * @ORM\HasLifecycleCallbacks() + */ +class Role +{ + /** + * @var integer + * + * @ORM\Id + * @ORM\Column(name="id", type="integer") + * @ORM\GeneratedValue(strategy="AUTO") + */ + private $id; + + /** + * @var array + * @ORM\Column(type="json_array") + */ + private $name; + + /** + * @var boolean + * @ORM\Column(type="boolean") + */ + private $active; + + /** + * @var EventType + * @ORM\ManyToOne( + * targetEntity="Chill\EventBundle\Entity\EventType", + * inversedBy="roles") + */ + private $type; + + + /** + * Get id + * + * @return integer + */ + public function getId() + { + return $this->id; + } + + /** + * Set label + * + * @param array $label + * @return Role + */ + public function setName($label) + { + $this->name = $label; + + return $this; + } + + /** + * Get label + * + * @return array + */ + public function getName() + { + return $this->name; + } + + /** + * Set active + * + * @param boolean $active + * @return Role + */ + public function setActive($active) + { + $this->active = $active; + + return $this; + } + + /** + * Get active + * + * @return boolean + */ + public function getActive() + { + return $this->active; + } + + + /** + * Set type + * + * @param EventType $type + * @return Role + */ + public function setType(EventType $type = null) + { + $this->type = $type; + + return $this; + } + + /** + * Get type + * + * @return EventType + */ + public function getType() + { + return $this->type; + } +} diff --git a/src/Bundle/ChillEvent/Entity/Status.php b/src/Bundle/ChillEvent/Entity/Status.php new file mode 100644 index 000000000..a88bff5c4 --- /dev/null +++ b/src/Bundle/ChillEvent/Entity/Status.php @@ -0,0 +1,146 @@ + + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +namespace Chill\EventBundle\Entity; + +use Doctrine\ORM\Mapping as ORM; + +/** + * Class Status + * + * @package Chill\EventBundle\Entity + * @ORM\Entity() + * @ORM\Table(name="chill_event_status") + * @ORM\HasLifecycleCallbacks() + */ +class Status +{ + /** + * @var integer + * + * @ORM\Id + * @ORM\Column(name="id", type="integer") + * @ORM\GeneratedValue(strategy="AUTO") + */ + private $id; + + /** + * @var array + * @ORM\Column(type="json_array") + */ + private $name; + + /** + * @var boolean + * @ORM\Column(type="boolean") + */ + private $active; + + /** + * @var EventType + * @ORM\ManyToOne( + * targetEntity="Chill\EventBundle\Entity\EventType", + * inversedBy="statuses") + */ + private $type; + + + /** + * Get id + * + * @return integer + */ + public function getId() + { + return $this->id; + } + + /** + * Set label + * + * @param array $name + * @return Status + */ + public function setName($name) + { + $this->name = $name; + + return $this; + } + + /** + * Get label + * + * @return array + */ + public function getName() + { + return $this->name; + } + + + /** + * Set active + * + * @param boolean $active + * @return Status + */ + public function setActive($active) + { + $this->active = $active; + + return $this; + } + + /** + * Get active + * + * @return boolean + */ + public function getActive() + { + return $this->active; + } + + + /** + * Set type + * + * @param EventType $type + * @return Status + */ + public function setType(EventType $type = null) + { + $this->type = $type; + + return $this; + } + + /** + * Get type + * + * @return EventType + */ + public function getType() + { + return $this->type; + } +} diff --git a/src/Bundle/ChillEvent/Form/ChoiceLoader/EventChoiceLoader.php b/src/Bundle/ChillEvent/Form/ChoiceLoader/EventChoiceLoader.php new file mode 100644 index 000000000..c96e541f7 --- /dev/null +++ b/src/Bundle/ChillEvent/Form/ChoiceLoader/EventChoiceLoader.php @@ -0,0 +1,138 @@ + + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +namespace Chill\EventBundle\Form\ChoiceLoader; + +use Symfony\Component\Form\ChoiceList\Loader\ChoiceLoaderInterface; +use Symfony\Component\Form\ChoiceList\ChoiceListInterface; +use Doctrine\ORM\EntityRepository; +use Chill\EventBundle\Entity\Event; + +/*** + * Class EventChoiceLoader + * + * @package Chill\EventBundle\Form\ChoiceLoader + * @author Mathieu Jaumotte jaum_mathieu@collectifs.net + */ +class EventChoiceLoader implements ChoiceLoaderInterface +{ + + /** + * @var EntityRepository + */ + protected $eventRepository; + + /** + * @var array + */ + protected $lazyLoadedEvents = []; + + /** + * @var array + */ + protected $centers = []; + + /** + * EventChoiceLoader constructor. + * + * @param EntityRepository $eventRepository + * @param array|null $centers + */ + public function __construct( + EntityRepository $eventRepository, + array $centers = null + ) { + $this->eventRepository = $eventRepository; + if (NULL !== $centers) { + $this->centers = $centers; + } + } + + /** + * @return bool + */ + protected function hasCenterFilter() + { + return count($this->centers) > 0; + } + + /** + * @param null $value + * @return ChoiceListInterface + */ + public function loadChoiceList($value = null): ChoiceListInterface + { + $list = new \Symfony\Component\Form\ChoiceList\ArrayChoiceList( + $this->lazyLoadedEvents, + function(Event $p) use ($value) { + return \call_user_func($value, $p); + }); + + return $list; + } + + /** + * @param array $values + * @param null $value + * @return array + */ + public function loadChoicesForValues(array $values, $value = null) + { + $choices = []; + + foreach($values as $value) { + if (empty($value)) { + continue; + } + + $event = $this->eventRepository->find($value); + + if ($this->hasCenterFilter() && + !\in_array($event->getCenter(), $this->centers)) { + throw new \RuntimeException("chosen an event not in correct center"); + } + + $choices[] = $event; + } + + return $choices; + } + + /** + * @param array $choices + * @param null $value + * @return array|string[] + */ + public function loadValuesForChoices(array $choices, $value = null) + { + $values = []; + + foreach ($choices as $choice) { + if (NULL === $choice) { + $values[] = null; + continue; + } + + $id = \call_user_func($value, $choice); + $values[] = $id; + $this->lazyLoadedEvents[$id] = $choice; + } + return $values; + } + +} diff --git a/src/Bundle/ChillEvent/Form/EventType.php b/src/Bundle/ChillEvent/Form/EventType.php new file mode 100644 index 000000000..ed1265620 --- /dev/null +++ b/src/Bundle/ChillEvent/Form/EventType.php @@ -0,0 +1,98 @@ +, + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +namespace Chill\EventBundle\Form; + +use Chill\EventBundle\Form\Type\PickEventTypeType; +use Chill\MainBundle\Form\Type\ScopePickerType; +use Chill\MainBundle\Templating\TranslatableStringHelper; +use Chill\MainBundle\Entity\User; +use Chill\MainBundle\Entity\Center; +use Chill\MainBundle\Entity\Scope; +use Chill\MainBundle\Form\Type\ChillDateTimeType; +use Chill\MainBundle\Form\Type\UserPickerType; +use Chill\MainBundle\Security\Authorization\AuthorizationHelper; +use Symfony\Bridge\Doctrine\Form\Type\EntityType; +use Symfony\Component\Form\AbstractType; +use Symfony\Component\Form\FormBuilderInterface; +use Symfony\Component\OptionsResolver\OptionsResolver; +use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; +use Symfony\Component\Security\Core\Role\Role; + +class EventType extends AbstractType +{ + /** + * @param FormBuilderInterface $builder + * @param array $options + */ + public function buildForm(FormBuilderInterface $builder, array $options) + { + $builder + ->add('name') + ->add('date', ChillDateTimeType::class, array( + 'required' => true + )) + ->add('circle', ScopePickerType::class, [ + 'center' => $options['center'], + 'role' => $options['role'] + ]) + ->add('type', PickEventTypeType::class, array( + 'placeholder' => 'Pick a type of event', + 'attr' => array( + 'class' => '' + ) + )) + ->add('moderator', UserPickerType::class, array( + 'center' => $options['center'], + 'role' => $options['role'], + 'placeholder' => 'Pick a moderator', + 'attr' => array( + 'class' => '' + ), + 'required' => false + )) + ; + } + + /** + * @param OptionsResolver $resolver + */ + public function configureOptions(OptionsResolver $resolver) + { + $resolver->setDefaults(array( + 'data_class' => 'Chill\EventBundle\Entity\Event' + )); + $resolver + ->setRequired(array('center', 'role')) + ->setAllowedTypes('center', Center::class) + ->setAllowedTypes('role', Role::class) + ; + } + + /** + * @return string + */ + public function getName() + { + return 'chill_eventbundle_event'; + } +} diff --git a/src/Bundle/ChillEvent/Form/EventTypeType.php b/src/Bundle/ChillEvent/Form/EventTypeType.php new file mode 100644 index 000000000..b72a9f186 --- /dev/null +++ b/src/Bundle/ChillEvent/Form/EventTypeType.php @@ -0,0 +1,41 @@ +add('name', TranslatableStringFormType::class) + ->add('active') + ; + } + + /** + * @param OptionsResolverInterface $resolver + */ + public function setDefaultOptions(OptionsResolverInterface $resolver) + { + $resolver->setDefaults(array( + 'data_class' => 'Chill\EventBundle\Entity\EventType' + )); + } + + /** + * @return string + */ + public function getName() + { + return 'chill_eventbundle_eventtype'; + } +} diff --git a/src/Bundle/ChillEvent/Form/ParticipationType.php b/src/Bundle/ChillEvent/Form/ParticipationType.php new file mode 100644 index 000000000..d7186ac91 --- /dev/null +++ b/src/Bundle/ChillEvent/Form/ParticipationType.php @@ -0,0 +1,76 @@ + + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +namespace Chill\EventBundle\Form; + +use Symfony\Component\Form\AbstractType; +use Symfony\Component\Form\FormBuilderInterface; +use Symfony\Component\OptionsResolver\OptionsResolver; +use Chill\EventBundle\Entity\EventType; +use Chill\EventBundle\Entity\Status; +use Symfony\Bridge\Doctrine\Form\Type\EntityType; +use Doctrine\ORM\EntityRepository; +use Chill\MainBundle\Templating\TranslatableStringHelper; +use Chill\EventBundle\Form\Type\PickRoleType; +use Chill\EventBundle\Form\Type\PickStatusType; + +/** + * A type to create a participation + * + * If the `event` option is defined, the role will be restricted + * + * @author Julien Fastré + */ +class ParticipationType extends AbstractType +{ + /** + * + * @var TranslatableStringHelper + */ + protected $translatableStringHelper; + + public function __construct(TranslatableStringHelper $translatableStringHelper) + { + $this->translatableStringHelper = $translatableStringHelper; + } + + public function buildForm(FormBuilderInterface $builder, array $options) + { + // local copy of variable for Closure + $translatableStringHelper = $this->translatableStringHelper; + + // add role + $builder->add('role', PickRoleType::class, array( + 'event_type' => $options['event_type'] + )); + + // add a status + $builder->add('status', PickStatusType::class, array( + 'event_type' => $options['event_type'] + )); + + } + + public function configureOptions(OptionsResolver $resolver) + { + $resolver->setDefined('event_type') + ->setAllowedTypes('event_type', array('null', EventType::class)) + ->setDefault('event_type', 'null'); + } +} diff --git a/src/Bundle/ChillEvent/Form/RoleType.php b/src/Bundle/ChillEvent/Form/RoleType.php new file mode 100644 index 000000000..d3483e917 --- /dev/null +++ b/src/Bundle/ChillEvent/Form/RoleType.php @@ -0,0 +1,60 @@ +translatableStringHelper = $translatableStringHelper; + } + + /** + * @param FormBuilderInterface $builder + * @param array $options + */ + public function buildForm(FormBuilderInterface $builder, array $options) + { + $builder + ->add('name', TranslatableStringFormType::class) + ->add('active') + ->add('type', EntityType::class, array( + 'class' => EventType::class, + 'choice_label' => function (EventType $e) { + return $this->translatableStringHelper->localize($e->getName()); + } + )) + ; + } + + /** + * @param OptionsResolverInterface $resolver + */ + public function setDefaultOptions(OptionsResolverInterface $resolver) + { + $resolver->setDefaults(array( + 'data_class' => 'Chill\EventBundle\Entity\Role' + )); + } + + /** + * @return string + */ + public function getName() + { + return 'chill_eventbundle_role'; + } +} diff --git a/src/Bundle/ChillEvent/Form/StatusType.php b/src/Bundle/ChillEvent/Form/StatusType.php new file mode 100644 index 000000000..bee55c8c9 --- /dev/null +++ b/src/Bundle/ChillEvent/Form/StatusType.php @@ -0,0 +1,43 @@ +add('name', TranslatableStringFormType::class) + ->add('active') + ->add('type', PickEventTypeType::class) + ; + } + + /** + * @param OptionsResolverInterface $resolver + */ + public function setDefaultOptions(OptionsResolverInterface $resolver) + { + $resolver->setDefaults(array( + 'data_class' => 'Chill\EventBundle\Entity\Status' + )); + } + + /** + * @return string + */ + public function getName() + { + return 'chill_eventbundle_status'; + } +} diff --git a/src/Bundle/ChillEvent/Form/Type/PickEventType.php b/src/Bundle/ChillEvent/Form/Type/PickEventType.php new file mode 100644 index 000000000..9cf8c3f29 --- /dev/null +++ b/src/Bundle/ChillEvent/Form/Type/PickEventType.php @@ -0,0 +1,214 @@ +, + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +namespace Chill\EventBundle\Form\Type; + +use Chill\EventBundle\Entity\Event; +use Chill\EventBundle\Form\ChoiceLoader\EventChoiceLoader; +use Chill\EventBundle\Repository\EventRepository; +use Chill\EventBundle\Search\EventSearch; +use Chill\MainBundle\Entity\Center; +use Chill\MainBundle\Entity\GroupCenter; +use Chill\MainBundle\Entity\User; +use Chill\MainBundle\Security\Authorization\AuthorizationHelper; +use Symfony\Bridge\Doctrine\Form\Type\EntityType; +use Symfony\Component\Finder\Exception\AccessDeniedException; +use Symfony\Component\Form\AbstractType; +use Symfony\Component\OptionsResolver\Options; +use Symfony\Component\OptionsResolver\OptionsResolver; +use Symfony\Component\Routing\Generator\UrlGeneratorInterface; +use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; +use Symfony\Component\Security\Core\Role\Role; +use Symfony\Component\Translation\TranslatorInterface; + +/** + * Class PickEventType + * + * @package Chill\EventBundle\Form\Type + * @author Mathieu Jaumotte jaum_mathieu@collectifs.net + */ +class PickEventType extends AbstractType +{ + + /** + * @var EventRepository + */ + protected $eventRepository; + + /** + * @var User + */ + protected $user; + + /** + * @var AuthorizationHelper + */ + protected $authorizationHelper; + + /** + * @var UrlGeneratorInterface + */ + protected $urlGenerator; + + /** + * @var TranslatorInterface + */ + protected $translator; + + /** + * PickEventType constructor. + * + * @param EventRepository $eventRepository + * @param TokenStorageInterface $tokenStorage + * @param AuthorizationHelper $authorizationHelper + * @param UrlGeneratorInterface $urlGenerator + * @param TranslatorInterface $translator + */ + public function __construct( + EventRepository $eventRepository, + TokenStorageInterface $tokenStorage, + AuthorizationHelper $authorizationHelper, + UrlGeneratorInterface $urlGenerator, + TranslatorInterface $translator + ) { + $this->eventRepository = $eventRepository; + $this->user = $tokenStorage->getToken()->getUser(); + $this->authorizationHelper = $authorizationHelper; + $this->urlGenerator = $urlGenerator; + $this->translator = $translator; + } + + /** + * @param OptionsResolver $resolver + */ + public function configureOptions(OptionsResolver $resolver) + { + parent::configureOptions($resolver); + + // add the possibles options for this type + $resolver + ->setDefined('centers') + ->addAllowedTypes('centers', array('array', Center::class, 'null')) + ->setDefault('centers', null) + ; + $resolver + ->setDefined('role') + ->addAllowedTypes('role', array(Role::class, 'null')) + ->setDefault('role', null) + ; + + // add the default options + $resolver->setDefaults(array( + 'class' => Event::class, + 'choice_label' => function(Event $e) { + return $e->getDate()->format('d/m/Y, H:i') . ' → ' . + // $e->getType()->getName()['fr'] . ': ' . // display the type of event + $e->getName(); + }, + 'placeholder' => 'Pick an event', + 'attr' => array('class' => 'select2 '), + 'choice_attr' => function(Event $e) { + return array('data-center' => $e->getCenter()->getId()); + }, + 'choiceloader' => function(Options $options) { + $centers = $this->filterCenters($options); + return new EventChoiceLoader($this->eventRepository, $centers); + } + )); + + } + + /** + * @return null|string + */ + public function getParent() + { + return EntityType::class; + } + + /** + * @param \Symfony\Component\Form\FormView $view + * @param \Symfony\Component\Form\FormInterface $form + * @param array $options + */ + public function buildView(\Symfony\Component\Form\FormView $view, \Symfony\Component\Form\FormInterface $form, array $options) + { + $view->vars['attr']['data-person-picker'] = true; + $view->vars['attr']['data-select-interactive-loading'] = true; + $view->vars['attr']['data-search-url'] = $this->urlGenerator + ->generate('chill_main_search', [ 'name' => EventSearch::NAME, '_format' => 'json' ]); + $view->vars['attr']['data-placeholder'] = $this->translator->trans($options['placeholder']); + $view->vars['attr']['data-no-results-label'] = $this->translator->trans('select2.no_results'); + $view->vars['attr']['data-error-load-label'] = $this->translator->trans('select2.error_loading'); + $view->vars['attr']['data-searching-label'] = $this->translator->trans('select2.searching'); + } + + /** + * @param Options $options + * @return array + */ + protected function filterCenters(Options $options) + { + // option role + if ($options['role'] === NULL) { + $centers = array_map( + function (GroupCenter $g) { + return $g->getCenter(); + }, + $this->user->getGroupCenters()->toArray() + ); + } else { + $centers = $this->authorizationHelper->getReachableCenters( + $this->user, + $options['role'] + ); + } + + // option center + if ($options['centers'] === NULL) + { + // we select all selected centers + $selectedCenters = $centers; + + } else { + $selectedCenters = array(); + $optionsCenters = is_array($options['centers']) ? + $options['centers'] : array($options['centers']); + + foreach ($optionsCenters as $c) { + // check that every member of the array is a center + if (!$c instanceof Center) { + throw new \RuntimeException('Every member of the "centers" ' + . 'option must be an instance of '.Center::class); + } + if (!in_array($c->getId(), array_map( + function(Center $c) { return $c->getId();}, + $centers))) { + throw new AccessDeniedException('The given center is not reachable'); + } + $selectedCenters[] = $c; + } + } + return $selectedCenters; + } + +} \ No newline at end of file diff --git a/src/Bundle/ChillEvent/Form/Type/PickEventTypeType.php b/src/Bundle/ChillEvent/Form/Type/PickEventTypeType.php new file mode 100644 index 000000000..4821296ae --- /dev/null +++ b/src/Bundle/ChillEvent/Form/Type/PickEventTypeType.php @@ -0,0 +1,73 @@ +, + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +namespace Chill\EventBundle\Form\Type; + +use Symfony\Component\Form\AbstractType; +use Symfony\Component\OptionsResolver\OptionsResolver; +use Chill\MainBundle\Templating\TranslatableStringHelper; +use Symfony\Bridge\Doctrine\Form\Type\EntityType; +use Doctrine\ORM\EntityRepository; +use Chill\EventBundle\Entity\EventType; + +/** + * Description of TranslatableEventType + * + * @author Champs-Libres Coop + */ +class PickEventTypeType extends AbstractType +{ + /** + * @var TranslatableStringHelper + */ + protected $translatableStringHelper; + + public function __construct(TranslatableStringHelper $helper) + { + $this->translatableStringHelper = $helper; + } + + public function getParent() + { + return EntityType::class; + } + + public function configureOptions(OptionsResolver $resolver) + { + $helper = $this->translatableStringHelper; + $resolver->setDefaults( + array( + 'class' => EventType::class, + 'query_builder' => function (EntityRepository $er) { + return $er->createQueryBuilder('et') + ->where('et.active = true'); + }, + 'choice_label' => function (EventType $t) use ($helper) { + return $helper->localize($t->getName()); + }, + 'choice_attrs' => function (EventType $t) { + return array('data-link-category' => $t->getId()); + } + ) + ); + } +} diff --git a/src/Bundle/ChillEvent/Form/Type/PickRoleType.php b/src/Bundle/ChillEvent/Form/Type/PickRoleType.php new file mode 100644 index 000000000..545892b98 --- /dev/null +++ b/src/Bundle/ChillEvent/Form/Type/PickRoleType.php @@ -0,0 +1,151 @@ +, + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +namespace Chill\EventBundle\Form\Type; + +use Symfony\Component\Form\AbstractType; +use Symfony\Component\Form\FormBuilderInterface; +use Symfony\Component\OptionsResolver\OptionsResolver; +use Chill\EventBundle\Entity\Role; +use Chill\EventBundle\Entity\EventType; +use Chill\MainBundle\Templating\TranslatableStringHelper; +use Symfony\Component\Translation\TranslatorInterface; +use Symfony\Bridge\Doctrine\Form\Type\EntityType; +use Doctrine\ORM\EntityRepository; +use Symfony\Component\Form\FormEvent; +use Symfony\Component\Form\FormEvents; + +/** + * Allow to pick a choice amongst different choices + * + * @author Julien Fastré + * @author Champs Libres + */ +class PickRoleType extends AbstractType +{ + + /** + * + * @var TranslatableStringHelper + */ + protected $translatableStringHelper; + + /** + * + * @var TranslatorInterface + */ + protected $translator; + + /** + * + * @var EntityRepository + */ + protected $roleRepository; + + public function __construct( + TranslatableStringHelper $translatableStringHelper, + TranslatorInterface $translator, + EntityRepository $roleRepository + ) { + $this->translatableStringHelper = $translatableStringHelper; + $this->translator = $translator; + $this->roleRepository = $roleRepository; + } + + public function buildForm(FormBuilderInterface $builder, array $options) + { + // create copy for easier management + $qb = $options['query_builder']; + + if ($options['event_type'] instanceof EventType) { + $options['query_builder']->where($qb->expr()->eq('r.type', ':event_type')) + ->setParameter('event_type', $options['event_type']); + } + + if ($options['active_only'] === true) { + $options['query_builder']->andWhere($qb->expr()->eq('r.active', ':active')) + ->setParameter('active', true); + } + + if ($options['group_by'] === null) { + $builder->addEventListener( + FormEvents::PRE_SET_DATA, + function(FormEvent $event) use ($options) { + if ($options['event_type'] === null) { + $form = $event->getForm(); + $name = $form->getName(); + $config = $form->getConfig(); + $type = $config->getType()->getName(); + $options = $config->getOptions(); + + $form->getParent()->add($name, $type, array_replace($options, array( + 'group_by' => function(Role $r) + { return $this->translatableStringHelper->localize($r->getType()->getName()); } + ))); + } + } + ); + } + } + + public function configureOptions(OptionsResolver $resolver) + { + // create copy for use in Closure + $translatableStringHelper = $this->translatableStringHelper; + $translator = $this->translator; + + $resolver + // add option "event_type" + ->setDefined('event_type') + ->setAllowedTypes('event_type', array('null', EventType::class)) + ->setDefault('event_type', null) + // add option allow unactive + ->setDefault('active_only', true) + ->setAllowedTypes('active_only', array('boolean')) + ; + + $qb = $this->roleRepository->createQueryBuilder('r'); + + $resolver->setDefaults(array( + 'class' => Role::class, + 'query_builder' => $qb, + 'group_by' => null, + 'choice_attr' => function(Role $r) { + return array( + 'data-event-type' => $r->getType()->getId(), + 'data-link-category' => $r->getType()->getId() + ); + }, + 'choice_label' => function(Role $r) + use ($translatableStringHelper, $translator) { + return $translatableStringHelper->localize($r->getName()). + ($r->getActive() === true ? '' : + ' ('.$translator->trans('unactive').')'); + } + )); + } + + public function getParent() + { + return EntityType::class; + } +} diff --git a/src/Bundle/ChillEvent/Form/Type/PickStatusType.php b/src/Bundle/ChillEvent/Form/Type/PickStatusType.php new file mode 100644 index 000000000..b4f40b7be --- /dev/null +++ b/src/Bundle/ChillEvent/Form/Type/PickStatusType.php @@ -0,0 +1,154 @@ +, + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +namespace Chill\EventBundle\Form\Type; + +use Symfony\Component\Form\AbstractType; +use Symfony\Component\Form\FormBuilderInterface; +use Symfony\Component\OptionsResolver\OptionsResolver; +use Chill\EventBundle\Entity\Status; +use Chill\EventBundle\Entity\EventType; +use Chill\MainBundle\Templating\TranslatableStringHelper; +use Symfony\Component\Translation\TranslatorInterface; +use Symfony\Bridge\Doctrine\Form\Type\EntityType; +use Doctrine\ORM\EntityRepository; +use Symfony\Component\Form\FormEvent; +use Symfony\Component\Form\FormEvents; + +/** + * Allow to pick amongst type + * + * parameters : + * + * - event_type : restricts to a certain event type. Default null (= all event types) + * - active_only: restricts to active type only. Default true + * + * @author Julien Fastré + * @author Champs Libres + */ +class PickStatusType extends AbstractType +{ + + /** + * + * @var TranslatableStringHelper + */ + protected $translatableStringHelper; + + /** + * + * @var TranslatorInterface + */ + protected $translator; + + /** + * + * @var EntityRepository + */ + protected $statusRepository; + + public function __construct( + TranslatableStringHelper $translatableStringHelper, + TranslatorInterface $translator, + EntityRepository $statusRepository + ) { + $this->translatableStringHelper = $translatableStringHelper; + $this->translator = $translator; + $this->statusRepository = $statusRepository; + } + + public function buildForm(FormBuilderInterface $builder, array $options) + { + $qb = $options['query_builder']; + + if ($options['event_type'] instanceof EventType) { + $options['query_builder']->where($qb->expr()->eq('r.type', ':event_type')) + ->setParameter('event_type', $options['event_type']); + + } + + if ($options['active_only'] === true) { + $options['query_builder']->andWhere($qb->expr()->eq('r.active', ':active')) + ->setParameter('active', true); + } + + if ($options['group_by'] === null && $options['event_type'] === null) { + $builder->addEventListener( + FormEvents::PRE_SET_DATA, + function(FormEvent $event) { + $form = $event->getForm(); + $name = $form->getName(); + $config = $form->getConfig(); + $type = $config->getType()->getName(); + $options = $config->getOptions(); + $form->getParent()->add($name, $type, array_replace($options, array( + 'group_by' => function(Status $s) + { return $this->translatableStringHelper->localize($s->getType()->getName()); } + ))); + } + ); + } + + } + + public function configureOptions(OptionsResolver $resolver) + { + // create copy for use in Closure + $translatableStringHelper = $this->translatableStringHelper; + $translator = $this->translator; + + $resolver + // add option "event_type" + ->setDefined('event_type') + ->setAllowedTypes('event_type', array('null', EventType::class)) + ->setDefault('event_type', null) + // add option allow unactive + ->setDefault('active_only', true) + ->setAllowedTypes('active_only', array('boolean')) + ; + + $qb = $this->statusRepository->createQueryBuilder('r'); + + $resolver->setDefaults(array( + 'class' => Status::class, + 'query_builder' => $qb, + 'group_by' => null, + 'choice_attr' => function(Status $s) { + return array( + 'data-event-type' => $s->getType()->getId(), + 'data-link-category' => $s->getType()->getId() + ); + }, + 'choice_label' => function(Status $s) + use ($translatableStringHelper, $translator) { + return $translatableStringHelper->localize($s->getName()). + ($s->getActive() === true ? '' : + ' ('.$translator->trans('unactive').')'); + } + )); + } + + public function getParent() + { + return EntityType::class; + } +} diff --git a/src/Bundle/ChillEvent/LICENSE.txt b/src/Bundle/ChillEvent/LICENSE.txt new file mode 100644 index 000000000..dba13ed2d --- /dev/null +++ b/src/Bundle/ChillEvent/LICENSE.txt @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/src/Bundle/ChillEvent/Menu/PersonMenuBuilder.php b/src/Bundle/ChillEvent/Menu/PersonMenuBuilder.php new file mode 100644 index 000000000..0133409b8 --- /dev/null +++ b/src/Bundle/ChillEvent/Menu/PersonMenuBuilder.php @@ -0,0 +1,58 @@ +authorizationChecker = $authorizationChecker; + $this->translator = $translator; + } + + + public function buildMenu($menuId, MenuItem $menu, array $parameters) + { + /* @var $person \Chill\PersonBundle\Entity\Person */ + $person = $parameters['person'] ?? null; + + if ($this->authorizationChecker->isGranted(EventVoter::SEE, $person)) { + + $menu->addChild($this->translator->trans('Events participation'), [ + 'route' => 'chill_event__list_by_person', + 'routeParameters' => [ + 'person_id' => $person->getId() + ] + ]) + ->setExtras([ + 'order' => 500 + ]); + } + } + + public static function getMenuIds(): array + { + return [ 'person' ]; + } +} \ No newline at end of file diff --git a/src/Bundle/ChillEvent/README.md b/src/Bundle/ChillEvent/README.md new file mode 100644 index 000000000..2aad96db5 --- /dev/null +++ b/src/Bundle/ChillEvent/README.md @@ -0,0 +1,16 @@ +Chill Event Bundle +==================== + +This bundle extend [chill software](https://www.chill.social). This bundle allow to define event and participation to those events. + +Documentation & installation +============================ + +This bundle can be installed with the Chill software. + +Read documentation here : http://chill.readthedocs.org + +Issues and bug tracking +======================= + +The issues tracker is here : https://git.framasoft.org/Chill-project/Chill-Event/issues diff --git a/src/Bundle/ChillEvent/Repository/EventRepository.php b/src/Bundle/ChillEvent/Repository/EventRepository.php new file mode 100644 index 000000000..a18e664ba --- /dev/null +++ b/src/Bundle/ChillEvent/Repository/EventRepository.php @@ -0,0 +1,35 @@ +, + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +namespace Chill\EventBundle\Repository; + +use Doctrine\ORM\EntityRepository; + +/** + * Class EventRepository + * + * @package Chill\EventBundle\Repository + * @author Mathieu Jaumotte jaum_mathieu@collectifs.net + */ +class EventRepository extends EntityRepository +{ + +} diff --git a/src/Bundle/ChillEvent/Repository/ParticipationRepository.php b/src/Bundle/ChillEvent/Repository/ParticipationRepository.php new file mode 100644 index 000000000..29bd09e9a --- /dev/null +++ b/src/Bundle/ChillEvent/Repository/ParticipationRepository.php @@ -0,0 +1,83 @@ +, + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +namespace Chill\EventBundle\Repository; + +use Doctrine\ORM\EntityRepository; + +/** + * Class ParticipationRepository + * + * @package Chill\EventBundle\Repository + * @author Mathieu Jaumotte jaum_mathieu@collectifs.net + */ +class ParticipationRepository extends EntityRepository +{ + + /** + * Count number of participations per person + * + * @param $person_id + * @return mixed + * @throws \Doctrine\ORM\NonUniqueResultException + */ + public function countByPerson($person_id) + { + return $this->createQueryBuilder('p') + ->select('COUNT (p.id)') + ->where('p.id = :person_id') + ->setParameter(':person_id', $person_id) + ->getQuery() + ->getSingleScalarResult() + ; + } + + + /** + * Return paginated participations for a person and in reachables circles + * + * @param $person_id + * @param $reachablesCircles + * @param $first + * @param $max + * @return mixed + */ + public function findByPersonInCircle($person_id, $reachablesCircles, $first, $max) + { + return $this->createQueryBuilder('p') + ->join('p.event', 'e') + ->where('p.person = :person_id') + ->andWhere('e.circle IN (:reachable_circles)') + ->orderBy('e.date', 'ASC') + ->setParameters(array( + ':person_id' => $person_id, + ':reachable_circles' => $reachablesCircles + )) + ->setFirstResult($first) + ->setMaxResults($max) + ->getQuery() + ->getResult() + ; + } + + + +} diff --git a/src/Bundle/ChillEvent/Resources/public/css/chillevent.css b/src/Bundle/ChillEvent/Resources/public/css/chillevent.css new file mode 100644 index 000000000..6020d45dc --- /dev/null +++ b/src/Bundle/ChillEvent/Resources/public/css/chillevent.css @@ -0,0 +1,57 @@ +div#event_date { display: flex; flex-direction: row; flex-wrap: nowrap; } +div#event_date input#event_date_date { margin-right: 1em; } +div#event_date div#event_date_time { min-width: 140px; } + + + + +.input-group { + position: relative; + width: 100%; + display: -ms-flexbox; display: flex; + -ms-flex-wrap: wrap; flex-wrap: wrap; + -ms-flex-align: stretch; align-items: stretch; +} + +/* +* form#export_tableur +* design du formulaires dropdown + submit +*/ +form#export_tableur { + width: 19.5em; + margin-right: 0; +} + +.custom-select { + padding: .375rem 1.75rem .375rem .75rem; + background: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 4 5'%3e%3cpath fill='%23343a40' d='M2 0L0 2h4zm0 5L0 3h4z'/%3e%3c/svg%3e") + no-repeat right .75rem center/8px 10px; background-color: white; + border-radius: .25rem; border: 1px solid #ced4da; + -webkit-appearance: none; -moz-appearance: none; appearance: none; +} +.input-group > .custom-select { + position: relative; + width: 1%; + margin-bottom: 0; + -ms-flex: 1 1 auto; flex: 1 1 auto; + color: #999; +} +.input-group > span.select2-container--default > span > span.select2-selection--single, +.input-group > .custom-select:not(:last-child) { border-top-right-radius: 0; border-bottom-right-radius: 0; + height: 38px; padding: 8px; +} +/* override correction style */ +.select2-container--default .select2-selection--single .select2-selection__arrow { height: 38px; } +.select2-container--default .select2-selection--single .select2-selection__rendered { line-height: unset; } + +.input-group > .input-group-append > .sc-button { border-top-left-radius: 0; border-bottom-left-radius: 0; } +.input-group-append { display: -ms-flexbox; display: flex; margin-left: -1px; } +.input-group-append .sc-button { position: relative; z-index: 2; } +.sc-button { + display: inline-block; + text-align: center; vertical-align: middle; + padding: .375rem .75rem; + font-weight: 400; font-size: 1rem; line-height: 1.5; + -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; + transition: color .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out; +} diff --git a/src/Bundle/ChillEvent/Resources/public/index.js b/src/Bundle/ChillEvent/Resources/public/index.js new file mode 100644 index 000000000..697693c59 --- /dev/null +++ b/src/Bundle/ChillEvent/Resources/public/index.js @@ -0,0 +1 @@ +require('./css/chillevent.css'); \ No newline at end of file diff --git a/src/Bundle/ChillEvent/Resources/test/Fixtures/App/AppKernel.php b/src/Bundle/ChillEvent/Resources/test/Fixtures/App/AppKernel.php new file mode 100644 index 000000000..366c1e6a0 --- /dev/null +++ b/src/Bundle/ChillEvent/Resources/test/Fixtures/App/AppKernel.php @@ -0,0 +1,46 @@ +load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml'); + } + + /** + * @return string + */ + public function getCacheDir() + { + return sys_get_temp_dir().'/ChillEventBundle/cache'; + } + + /** + * @return string + */ + public function getLogDir() + { + return sys_get_temp_dir().'/ChillEventBundle/logs'; + } +} diff --git a/src/Bundle/ChillEvent/Resources/test/Fixtures/App/config/config.yml b/src/Bundle/ChillEvent/Resources/test/Fixtures/App/config/config.yml new file mode 100644 index 000000000..cf6bb3108 --- /dev/null +++ b/src/Bundle/ChillEvent/Resources/test/Fixtures/App/config/config.yml @@ -0,0 +1,43 @@ +imports: + - { resource: parameters.yml } + +framework: + secret: Not very secret + router: { resource: "%kernel.root_dir%/config/routing.yml" } + form: true + csrf_protection: true + session: ~ + default_locale: fr + translator: { fallback: fr } + profiler: { only_exceptions: false } + templating: + engines: ['twig'] + +# Doctrine Configuration +doctrine: + dbal: + driver: pdo_pgsql + host: "%database_host%" + port: "%database_port%" + dbname: "%database_name%" + user: "%database_user%" + password: "%database_password%" + charset: UTF8 + mapping_types: + jsonb: json_array + + orm: + auto_generate_proxy_classes: "%kernel.debug%" + auto_mapping: true + +# Assetic Configuration +assetic: + debug: "%kernel.debug%" + use_controller: false + bundles: [ ] + #java: /usr/bin/java + filters: + cssrewrite: ~ + +chill_main: + available_languages: [fr, en] diff --git a/src/Bundle/ChillEvent/Resources/test/Fixtures/App/config/config_test.yml b/src/Bundle/ChillEvent/Resources/test/Fixtures/App/config/config_test.yml new file mode 100644 index 000000000..b4f6d786a --- /dev/null +++ b/src/Bundle/ChillEvent/Resources/test/Fixtures/App/config/config_test.yml @@ -0,0 +1,52 @@ +imports: + - { resource: config.yml } + +framework: + test: ~ + session: + storage_id: session.storage.filesystem + +security: + role_hierarchy: + CHILL_MASTER_ROLE: [CHILL_INHERITED_ROLE_1] + providers: + chain_provider: + chain : + providers: [in_memory, users] + in_memory: + memory: + users: + admin: { password: "password", roles: 'ROLE_ADMIN' } + users: + entity: + class: Chill\MainBundle\Entity\User + property: username + + encoders: + Chill\MainBundle\Entity\User: + algorithm: bcrypt + Symfony\Component\Security\Core\User\User: + algorithm: plaintext + + firewalls: + dev: + pattern: ^/(_(profiler|wdt)|css|images|js)/ + security: false + + + + default: + anonymous: ~ + http_basic: ~ + form_login: + csrf_parameter: _csrf_token + csrf_token_id: authenticate + csrf_provider: form.csrf_provider + + logout: ~ + + + access_control: + - { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY } + - { path: ^/[a-z]*/admin, roles: ROLE_ADMIN } + - { path: ^/, roles: ROLE_USER } \ No newline at end of file diff --git a/src/Bundle/ChillEvent/Resources/test/Fixtures/App/config/parameters.gitlab-ci.yml b/src/Bundle/ChillEvent/Resources/test/Fixtures/App/config/parameters.gitlab-ci.yml new file mode 100644 index 000000000..c4e63ef76 --- /dev/null +++ b/src/Bundle/ChillEvent/Resources/test/Fixtures/App/config/parameters.gitlab-ci.yml @@ -0,0 +1,11 @@ +parameters: + database_host: chill__database + database_port: 5432 + database_name: postgres + database_user: postgres + database_password: postgres + locale: fr + secret: ThisTokenIsNotSoSecretChangeIt + debug_toolbar: true + debug_redirects: false + use_assetic_controller: true \ No newline at end of file diff --git a/src/Bundle/ChillEvent/Resources/test/Fixtures/App/config/parameters.yml b/src/Bundle/ChillEvent/Resources/test/Fixtures/App/config/parameters.yml new file mode 100644 index 000000000..d92cc2318 --- /dev/null +++ b/src/Bundle/ChillEvent/Resources/test/Fixtures/App/config/parameters.yml @@ -0,0 +1,11 @@ +parameters: + database_host: 127.0.0.1 + database_port: 5435 + database_name: postgres + database_user: postgres + database_password: postgres + locale: fr + secret: ThisTokenIsNotSoSecretChangeIt + debug_toolbar: true + debug_redirects: false + use_assetic_controller: true \ No newline at end of file diff --git a/src/Bundle/ChillEvent/Resources/test/Fixtures/App/config/parameters.yml.dist b/src/Bundle/ChillEvent/Resources/test/Fixtures/App/config/parameters.yml.dist new file mode 100644 index 000000000..38fab7fd2 --- /dev/null +++ b/src/Bundle/ChillEvent/Resources/test/Fixtures/App/config/parameters.yml.dist @@ -0,0 +1,11 @@ +parameters: + database_host: 127.0.0.1 + database_port: 5435 + database_name: chill + database_user: chill + database_password: chill + locale: fr + secret: ThisTokenIsNotSoSecretChangeIt + debug_toolbar: true + debug_redirects: false + use_assetic_controller: true \ No newline at end of file diff --git a/src/Bundle/ChillEvent/Resources/test/Fixtures/App/config/routing.yml b/src/Bundle/ChillEvent/Resources/test/Fixtures/App/config/routing.yml new file mode 100644 index 000000000..802d3a1c8 --- /dev/null +++ b/src/Bundle/ChillEvent/Resources/test/Fixtures/App/config/routing.yml @@ -0,0 +1,4 @@ +#load routes for chil bundles +chill_routes: + resource: . + type: chill_routes \ No newline at end of file diff --git a/src/Bundle/ChillEvent/Resources/test/Fixtures/App/console b/src/Bundle/ChillEvent/Resources/test/Fixtures/App/console new file mode 100644 index 000000000..4ee9cfb33 --- /dev/null +++ b/src/Bundle/ChillEvent/Resources/test/Fixtures/App/console @@ -0,0 +1,27 @@ +#!/usr/bin/env php +getParameterOption(array('--env', '-e'), getenv('SYMFONY_ENV') ?: 'test'); +$debug = getenv('SYMFONY_DEBUG') !== '0' && !$input->hasParameterOption(array('--no-debug', '')) && $env !== 'prod'; + +if ($debug) { + Debug::enable(); +} + +$kernel = new AppKernel($env, $debug); +$application = new Application($kernel); +$application->run($input); diff --git a/src/Bundle/ChillEvent/Resources/test/bootstrap.php b/src/Bundle/ChillEvent/Resources/test/bootstrap.php new file mode 100644 index 000000000..0279b4ee6 --- /dev/null +++ b/src/Bundle/ChillEvent/Resources/test/bootstrap.php @@ -0,0 +1,8 @@ + / + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . +#} + +{% extends "@ChillMain/Admin/layoutWithVerticalMenu.html.twig" %} + +{% block vertical_menu_content %} + {{ chill_menu('admin_events', { + 'layout': '@ChillEvent/Admin/menu.html.twig', + }) }} +{% endblock %} + +{% block layout_wvm_content %} + {% block admin_content %} +

{{ 'Events configuration' |trans }}

+ {% endblock %} +{% endblock %} \ No newline at end of file diff --git a/src/Bundle/ChillEvent/Resources/views/Admin/menu.html.twig b/src/Bundle/ChillEvent/Resources/views/Admin/menu.html.twig new file mode 100644 index 000000000..2e804277d --- /dev/null +++ b/src/Bundle/ChillEvent/Resources/views/Admin/menu.html.twig @@ -0,0 +1,21 @@ +{# + * Copyright (C) 2014-2015, Champs Libres Cooperative SCRLFS, + / + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . +#} + +{% extends "@ChillMain/Menu/verticalMenu.html.twig" %} +{% block v_menu_title %}{{ 'Events configuration menu'|trans }}{% endblock %} + diff --git a/src/Bundle/ChillEvent/Resources/views/Event/confirm_delete.html.twig b/src/Bundle/ChillEvent/Resources/views/Event/confirm_delete.html.twig new file mode 100644 index 000000000..86b7c6fd2 --- /dev/null +++ b/src/Bundle/ChillEvent/Resources/views/Event/confirm_delete.html.twig @@ -0,0 +1,20 @@ +{% extends '@ChillEvent/layout.html.twig' %} + +{% set activeRouteKey = 'chill_event__event_show' %} + +{% block title 'Delete event'|trans %} + +{% block event_content %} + + {{ include('@ChillMain/Util/confirmation_template.html.twig', + { + 'title' : 'Delete event'|trans, + 'confirm_question' : 'Are you sure you want to remove that event ?'|trans, + 'cancel_route' : activeRouteKey, + 'cancel_parameters' : { 'event_id' : event_id }, + 'form' : delete_form + } + ) }} + +{% endblock %} + diff --git a/src/Bundle/ChillEvent/Resources/views/Event/edit.html.twig b/src/Bundle/ChillEvent/Resources/views/Event/edit.html.twig new file mode 100644 index 000000000..97b32b328 --- /dev/null +++ b/src/Bundle/ChillEvent/Resources/views/Event/edit.html.twig @@ -0,0 +1,33 @@ +{% extends '@ChillEvent/layout.html.twig' %} + +{% block title 'Event edit'|trans %} + +{% block event_content -%} +

{{ 'Event edit'|trans }}

+ + {{ form_start(edit_form) }} + {{ form_errors(edit_form) }} + {{ form_row(edit_form.circle) }} + {{ form_row(edit_form.name) }} + {{ form_row(edit_form.date) }} + + {{ form_row(edit_form.type, { 'label': 'Event type' }) }} + {{ form_row(edit_form.moderator) }} + + + + {{ form_end(edit_form) }} +{% endblock %} diff --git a/src/Bundle/ChillEvent/Resources/views/Event/index.html.twig b/src/Bundle/ChillEvent/Resources/views/Event/index.html.twig new file mode 100644 index 000000000..442d5ca67 --- /dev/null +++ b/src/Bundle/ChillEvent/Resources/views/Event/index.html.twig @@ -0,0 +1,43 @@ +{% extends '::base.html.twig' %} + +{% block body -%} +

Event list

+ + + + + + + + + + + + {% for entity in entities %} + + + + + + + {% endfor %} + +
IdNameDateActions
{{ entity.id }}{{ entity.name }}{% if entity.date %}{{ entity.date|date('Y-m-d H:i:s') }}{% endif %} + +
+ + + {% endblock %} diff --git a/src/Bundle/ChillEvent/Resources/views/Event/list.html.twig b/src/Bundle/ChillEvent/Resources/views/Event/list.html.twig new file mode 100644 index 000000000..366d0c588 --- /dev/null +++ b/src/Bundle/ChillEvent/Resources/views/Event/list.html.twig @@ -0,0 +1,65 @@ +

{{ 'Event search'|trans }}

+ +

{% transchoice total with { '%pattern%' : pattern } %}%total% events match the search %pattern%{% endtranschoice %}

+ +{% if events|length > 0 %} + +

{{ 'Results %start%-%end% of %total%'|trans({ '%start%' : start, '%end%': start + events|length, '%total%' : total } ) }}

+ + + + + + + + + + + + {% for event in events %} + + + + + + + {% endfor %} + +
{{ 'Name'|trans }}{{ 'Date'|trans }}{{ 'Event type'|trans }} 
{{ event.name }}{{ event.date|format_date('long') }}{{ event.type.name|localize_translatable_string }} + +
+ +{% endif %} + + + +{% if preview == false %} +{{ chill_pagination(paginator) }} +{% endif %} diff --git a/src/Bundle/ChillEvent/Resources/views/Event/listByPerson.html.twig b/src/Bundle/ChillEvent/Resources/views/Event/listByPerson.html.twig new file mode 100644 index 000000000..2cd19d08a --- /dev/null +++ b/src/Bundle/ChillEvent/Resources/views/Event/listByPerson.html.twig @@ -0,0 +1,114 @@ +{# + * Copyright (C) 2014, Champs Libres Cooperative SCRLFS, + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . +#} +{% extends "@ChillPerson/layout.html.twig" %} + +{% set activeRouteKey = 'chill_event__list_by_person' %} +{% set currentPerson = person.firstName ~ ' ' ~ person.lastName %} + +{% block title %}{{ 'Events participation' |trans }}{% endblock title %} + +{% block personcontent %} +

{{ 'Events participation' |trans }}

+ + + + + + + + + + + + + + {% for participation in participations %} + + + + + + + + + {% endfor %} + + +
{{ 'Date'|trans }}{{ 'Name'|trans }}{{ 'Event type'|trans }}{{ 'Role'|trans }}{{ 'Status'|trans }}
{{ participation.event.date|format_date('short') }}{{ participation.event.name }}{{ participation.event.type.name|localize_translatable_string }}{{ participation.role.name|localize_translatable_string }}{{ participation.status.name|localize_translatable_string }} +
    +
  • + + {% set currentPath = path(app.request.attributes.get('_route'), app.request.attributes.get('_route_params')) %} + {% set returnLabel = 'Back to %person% events'|trans({ '%person%' : currentPerson } ) %} + + {% if is_granted('CHILL_EVENT_SEE_DETAILS', participation.event) %} + + {% endif %} + + {% if is_granted('CHILL_EVENT_UPDATE', participation.event) + and is_granted('CHILL_EVENT_PARTICIPATION_UPDATE', participation) %} + + + {% else %} + + {% if is_granted('CHILL_EVENT_UPDATE', participation.event) %} + + {{ 'Edit the event'|trans }} + + {% endif %} + {% if is_granted('CHILL_EVENT_PARTICIPATION_UPDATE', participation) %} + + {{ 'Edit the participation'|trans }} + + {% endif %} + + {% endif %} + +
  • +
+
+ +{% if participations|length < paginator.getTotalItems %} + {{ chill_pagination(paginator) }} +{% endif %} + +
+ {{ form_start(form_add_event_participation_by_person) }} + {{ form_widget(form_add_event_participation_by_person.event_id, { 'attr' : { 'style' : 'width: 25em; display:inline-block; ' } } ) }} + {{ form_widget(form_add_event_participation_by_person.submit, { 'attr' : { 'class' : 'sc-button bt-create' } } ) }} + {{ form_rest(form_add_event_participation_by_person) }} + {{ form_end(form_add_event_participation_by_person) }} +
+ +{% endblock %} \ No newline at end of file diff --git a/src/Bundle/ChillEvent/Resources/views/Event/new.html.twig b/src/Bundle/ChillEvent/Resources/views/Event/new.html.twig new file mode 100644 index 000000000..33a826f85 --- /dev/null +++ b/src/Bundle/ChillEvent/Resources/views/Event/new.html.twig @@ -0,0 +1,29 @@ +{% extends '@ChillEvent/layout.html.twig' %} + +{% block title 'Event creation'|trans %} + +{% block event_content -%} +

{{ 'Event creation'|trans }}

+ + {{ form_start(form) }} + {{ form_errors(form) }} + {{ form_row(form.circle) }} + {{ form_row(form.name) }} + {{ form_row(form.date) }} + + {{ form_row(form.type, { 'label': 'Event type' }) }} + {{ form_row(form.moderator) }} + + + + {{ form_end(form) }} +{% endblock %} diff --git a/src/Bundle/ChillEvent/Resources/views/Event/newPickCenter.html.twig b/src/Bundle/ChillEvent/Resources/views/Event/newPickCenter.html.twig new file mode 100644 index 000000000..06c29a924 --- /dev/null +++ b/src/Bundle/ChillEvent/Resources/views/Event/newPickCenter.html.twig @@ -0,0 +1,26 @@ +{% extends '@ChillEvent/layout.html.twig' %} + +{% block title 'Event creation'|trans %} + +{% block event_content -%} +

{{ 'Event creation'|trans }}

+ + {{ form_start(form) }} + {{ form_errors(form) }} + + {{ form_row(form.center_id) }} + + + + {{ form_end(form) }} + +{% endblock %} diff --git a/src/Bundle/ChillEvent/Resources/views/Event/show.html.twig b/src/Bundle/ChillEvent/Resources/views/Event/show.html.twig new file mode 100644 index 000000000..9e03f7fe6 --- /dev/null +++ b/src/Bundle/ChillEvent/Resources/views/Event/show.html.twig @@ -0,0 +1,154 @@ +{% extends '@ChillEvent/layout.html.twig' %} + +{% block title 'Event : %label%'|trans({ '%label%' : event.name } ) %} + +{% import 'ChillPersonBundle:Person:macro.html.twig' as person_macro %} + +{% block event_content -%} +

{{ 'Details of an event'|trans }}

+ + + + + + + + + + + + + + + + + + + + + + + + + +
{{ 'Name'|trans }}{{ event.name }}
{{ 'Date'|trans }}{{ event.date|format_date('long') }}
{{ 'Event type'|trans }}{{ event.type.name|localize_translatable_string }}
{{ 'Circle'|trans }}{{ event.circle.name|localize_translatable_string }}
{{ 'Moderator'|trans }}{{ event.moderator|trans|default('-') }}
+ + + +

{{ 'Participations'|trans }}

+ {% set count = event.participations|length %} +

{% transchoice count %}%count% participations to this event{% endtranschoice %}

+ + {% if count > 0 %} + + + + + + + + + + + + {% for participation in event.participations %} + + + + + + + + {% endfor %} + +
{{ 'Person'|trans }}{{ 'Role'|trans }}{{ 'Status'|trans }}{{ 'Last update'|trans }} 
{{ person_macro.render(participation.person) }}{{ participation.role.name|localize_translatable_string }}{{ participation.status.name|localize_translatable_string }}{{ participation.lastUpdate|ago }} {# sf4 check: filter 'time_diff' is abandoned, + alternative: knplabs/knp-time-bundle provide filter 'ago' #} + + +
    + {% if is_granted('CHILL_EVENT_PARTICIPATION_UPDATE', participation) %} +
  • + +
  • +
  • + +
  • + {% endif %} +
+
+ + + {% endif %} + + + +
+
+ {{ form_start(form_add_participation_by_person) }} +
+ {{ form_widget(form_add_participation_by_person.person_id, { 'attr' : { + 'class' : 'custom-select', + 'style': 'min-width: 15em; max-width: 18em; display: inline-block;' + }} ) }} +
+ {{ form_widget(form_add_participation_by_person.submit, { 'attr' : { 'class' : 'sc-button bt-create' } } ) }} +
+
+ {{ form_rest(form_add_participation_by_person) }} + {{ form_end(form_add_participation_by_person) }} +
+ +
+ {{ form_start(form_export, {'attr': {'id': 'export_tableur'}}) }} +
+ {{ form_widget(form_export.format, { 'attr' : { 'class': 'custom-select' } }) }} +
+ {{ form_widget(form_export.submit, { 'attr' : { 'class': 'sc-button bt-save' } }) }} +
+ +
+ {{ form_rest(form_export) }} + {{ form_end(form_export) }} +
+
+ +
+ {{ chill_delegated_block('block_footer_show', { 'event': event }) }} +
+ +{% endblock %} diff --git a/src/Bundle/ChillEvent/Resources/views/EventReason/macro.html.twig b/src/Bundle/ChillEvent/Resources/views/EventReason/macro.html.twig new file mode 100644 index 000000000..c9e3e3729 --- /dev/null +++ b/src/Bundle/ChillEvent/Resources/views/EventReason/macro.html.twig @@ -0,0 +1,3 @@ +{%- macro reason(r) -%} +  {{ r.name | localize_translatable_string }} +{%- endmacro -%} \ No newline at end of file diff --git a/src/Bundle/ChillEvent/Resources/views/EventType/edit.html.twig b/src/Bundle/ChillEvent/Resources/views/EventType/edit.html.twig new file mode 100644 index 000000000..2142998f5 --- /dev/null +++ b/src/Bundle/ChillEvent/Resources/views/EventType/edit.html.twig @@ -0,0 +1,21 @@ +{% extends "ChillEventBundle:Admin:layout.html.twig" %} + +{% block admin_content -%} + +

{{ 'EventType edit'|trans }}

+ + {{ form_start(edit_form) }} + {{ form_row(edit_form.name) }} + {{ form_row(edit_form.active) }} + + + + {{ form_end(edit_form) }} +{% endblock %} diff --git a/src/Bundle/ChillEvent/Resources/views/EventType/index.html.twig b/src/Bundle/ChillEvent/Resources/views/EventType/index.html.twig new file mode 100644 index 000000000..f1b2f9acd --- /dev/null +++ b/src/Bundle/ChillEvent/Resources/views/EventType/index.html.twig @@ -0,0 +1,42 @@ +{% extends "ChillEventBundle:Admin:layout.html.twig" %} + +{% block admin_content -%} + +

{{ 'EventType list'|trans }}

+ + + + + + + + + + + + {% for entity in entities %} + + + + + + + {% endfor %} + +
{{ 'Id'|trans }}{{ 'Type'|trans }}{{ 'Active'|trans }}{{ 'Actions'|trans }}
{{ entity.id }}{{ entity.name|localize_translatable_string }}{{ entity.active }} +
    +
  • + +
  • +
  • + +
  • +
+
+ + +{% endblock %} diff --git a/src/Bundle/ChillEvent/Resources/views/EventType/new.html.twig b/src/Bundle/ChillEvent/Resources/views/EventType/new.html.twig new file mode 100644 index 000000000..b4aa07626 --- /dev/null +++ b/src/Bundle/ChillEvent/Resources/views/EventType/new.html.twig @@ -0,0 +1,21 @@ +{% extends "ChillEventBundle:Admin:layout.html.twig" %} + +{% block admin_content -%} + +

{{ 'EventType creation'|trans }}

+ + {{ form_start(form) }} + {{ form_row(form.name) }} + {{ form_row(form.active) }} + + + + {{ form_end(form) }} +{% endblock %} diff --git a/src/Bundle/ChillEvent/Resources/views/EventType/show.html.twig b/src/Bundle/ChillEvent/Resources/views/EventType/show.html.twig new file mode 100644 index 000000000..56edf0a19 --- /dev/null +++ b/src/Bundle/ChillEvent/Resources/views/EventType/show.html.twig @@ -0,0 +1,37 @@ +{% extends "ChillEventBundle:Admin:layout.html.twig" %} + +{% block admin_content -%} + +

{{ 'EventType'|trans }}

+ + + + + + + + + + + + + + + + +
{{ 'Id'|trans }}{{ entity.id }}
{{ 'Name'|trans }}{{ entity.name|localize_translatable_string }}
{{ 'Active'|trans }}{{ entity.active }}
+ + +{% endblock %} diff --git a/src/Bundle/ChillEvent/Resources/views/Participation/_ignored_participations.html.twig b/src/Bundle/ChillEvent/Resources/views/Participation/_ignored_participations.html.twig new file mode 100644 index 000000000..0d54dd624 --- /dev/null +++ b/src/Bundle/ChillEvent/Resources/views/Participation/_ignored_participations.html.twig @@ -0,0 +1,10 @@ +{% import 'ChillPersonBundle:Person:macro.html.twig' as person_macro %} + +{% if ignored_participations|length > 0 %} +

{% transchoice ignored_participations|length %}The following people have been ignored because they are already participating on the event{% endtranschoice %} :

+
    + {% for p in ignored_participations %} +
  • {{ person_macro.render(p.person) }}
  • + {% endfor %} +
+{% endif %} \ No newline at end of file diff --git a/src/Bundle/ChillEvent/Resources/views/Participation/confirm_delete.html.twig b/src/Bundle/ChillEvent/Resources/views/Participation/confirm_delete.html.twig new file mode 100644 index 000000000..9b023a915 --- /dev/null +++ b/src/Bundle/ChillEvent/Resources/views/Participation/confirm_delete.html.twig @@ -0,0 +1,20 @@ +{% extends '@ChillEvent/layout.html.twig' %} + +{% set activeRouteKey = 'chill_event__event_show' %} + +{% block title 'Remove participation'|trans %} + +{% block event_content %} + + {{ include('@ChillMain/Util/confirmation_template.html.twig', + { + 'title' : 'Remove participation'|trans, + 'confirm_question' : 'Are you sure you want to remove that participation ?'|trans, + 'cancel_route' : activeRouteKey, + 'cancel_parameters' : { 'event_id' : event_id }, + 'form' : delete_form + } + ) }} + +{% endblock %} + diff --git a/src/Bundle/ChillEvent/Resources/views/Participation/edit-multiple.html.twig b/src/Bundle/ChillEvent/Resources/views/Participation/edit-multiple.html.twig new file mode 100644 index 000000000..18465d241 --- /dev/null +++ b/src/Bundle/ChillEvent/Resources/views/Participation/edit-multiple.html.twig @@ -0,0 +1,62 @@ +{% extends '@ChillEvent/layout.html.twig' %} + +{% import 'ChillPersonBundle:Person:macro.html.twig' as person_macro %} + +{% block event_content -%} +

{{ 'Participation Edit'|trans }}

+ + + + + + + + + + + + +
{{ 'Associated event'|trans }} {{ event.name }}
{{ 'Date'|trans }} {{ event.date|format_date('long') }}
+ +

{{ 'Participations'|trans }}

+ + {{ form_start(form) }} + + + + + + + + + + + + + {% for participation in form.participations %} + + + + + + + {% endfor %} + +
{{ 'Person'|trans }}{{ 'Role'|trans }}{{ 'Status'|trans }}{{ 'Last update'|trans }} 
{{ person_macro.render(participation.vars.value.person) }}{{ form_widget(participation.role) }}{{ form_widget(participation.status) }}{{ participation.vars.value.lastUpdate|ago }} {# sf4 check: filter 'time_diff' is abandoned, + alternative: knplabs/knp-time-bundle provide filter 'ago' #} + +
+ + + + {{ form_end(form) }} +{% endblock %} diff --git a/src/Bundle/ChillEvent/Resources/views/Participation/edit.html.twig b/src/Bundle/ChillEvent/Resources/views/Participation/edit.html.twig new file mode 100644 index 000000000..93956c5f0 --- /dev/null +++ b/src/Bundle/ChillEvent/Resources/views/Participation/edit.html.twig @@ -0,0 +1,45 @@ +{% extends '@ChillEvent/layout.html.twig' %} + +{% import 'ChillPersonBundle:Person:macro.html.twig' as person_macro %} + +{% block event_content -%} +

{{ 'Participation Edit'|trans }}

+ + + + + + + + + + + + + + + + +
{{ 'Associated person'|trans }}{{ person_macro.render(participation.person) }}
{{ 'Associated event'|trans }} {{ participation.event.name }}
{{ 'Date'|trans }} {{ participation.event.date|format_date('long') }}
+ + {{ form_start(form) }} + {{ form_row(form.role) }} + {{ form_row(form.status) }} + + + + {{ form_end(form) }} +{% endblock %} diff --git a/src/Bundle/ChillEvent/Resources/views/Participation/new-multiple.html.twig b/src/Bundle/ChillEvent/Resources/views/Participation/new-multiple.html.twig new file mode 100644 index 000000000..f73744a59 --- /dev/null +++ b/src/Bundle/ChillEvent/Resources/views/Participation/new-multiple.html.twig @@ -0,0 +1,68 @@ +{% extends '@ChillEvent/layout.html.twig' %} + +{% import 'ChillPersonBundle:Person:macro.html.twig' as person_macro %} + +{% block title 'Participation creation'|trans %} + + {% form_theme form _self %} + + {% block _collection_row %} + + + {{ form_widget(form) }} + + + {# {{ form_row(participationField.status) }} #} + + + {% endblock %} + +{% block event_content -%} +

{{ 'Participation creation'|trans }}

+ + + + + + + + +
{{ 'Associated event'|trans }} {{ participations[0].event.name }}
+ + {% include 'ChillEventBundle:Participation:_ignored_participations.html.twig' with ignored_participations %} + + {{ form_start(form) }} + + + + + + + + + + {% for participationField in form.participations %} + + + + + + {% endfor %} + +
{{ 'Person'|trans }}{{ 'Role'|trans }}{{ 'Status'|trans }}
{{ person_macro.render(participationField.vars.value.person) }}{{ form_widget(participationField.role) }}{{ form_widget(participationField.status) }}
+ + + + {{ form_end(form) }} + +{% endblock %} diff --git a/src/Bundle/ChillEvent/Resources/views/Participation/new.html.twig b/src/Bundle/ChillEvent/Resources/views/Participation/new.html.twig new file mode 100644 index 000000000..514161c35 --- /dev/null +++ b/src/Bundle/ChillEvent/Resources/views/Participation/new.html.twig @@ -0,0 +1,48 @@ +{% extends '@ChillEvent/layout.html.twig' %} + +{% import 'ChillPersonBundle:Person:macro.html.twig' as person_macro %} + +{% block title 'Participation creation'|trans %} + +{% block event_content -%} +

{{ 'Participation creation'|trans }}

+ + + + + + + + + + + + +
{{ 'Associated person'|trans }}{{ person_macro.render(participation.person) }}
{{ 'Associated event'|trans }} {{ participation.event.name }}
+ + {% include 'ChillEventBundle:Participation:_ignored_participations.html.twig' with ignored_participations %} + + {{ form_start(form) }} + + {{ form_errors(form) }} + + {{ form_row(form.role) }} + {{ form_row(form.status) }} + + + + + + {{ form_end(form) }} + +{% endblock %} diff --git a/src/Bundle/ChillEvent/Resources/views/Role/edit.html.twig b/src/Bundle/ChillEvent/Resources/views/Role/edit.html.twig new file mode 100644 index 000000000..0df6e12de --- /dev/null +++ b/src/Bundle/ChillEvent/Resources/views/Role/edit.html.twig @@ -0,0 +1,21 @@ +{% extends "ChillEventBundle:Admin:layout.html.twig" %} + +{% block admin_content -%} +

{{ 'Role edit'|trans }}

+ + {{ form_start(edit_form) }} + {{ form_row(edit_form.name) }} + {{ form_row(edit_form.type) }} + {{ form_row(edit_form.active) }} + + + + {{ form_end(edit_form) }} +{% endblock %} diff --git a/src/Bundle/ChillEvent/Resources/views/Role/index.html.twig b/src/Bundle/ChillEvent/Resources/views/Role/index.html.twig new file mode 100644 index 000000000..f6b071924 --- /dev/null +++ b/src/Bundle/ChillEvent/Resources/views/Role/index.html.twig @@ -0,0 +1,44 @@ +{% extends "ChillEventBundle:Admin:layout.html.twig" %} + +{% block admin_content -%} + +

{{ 'Role list'|trans }}

+ + + + + + + + + + + + + {% for entity in entities %} + + + + + + + + {% endfor %} + +
{{ 'Id'|trans }}{{ 'Role'|trans }}{{ 'Type'|trans }}{{ 'Active'|trans }}{{ 'Actions'|trans }}
{{ entity.id }}{{ entity.name|localize_translatable_string }}{{ entity.type.name|localize_translatable_string }}{{ entity.active }} +
    +
  • + +
  • +
  • + +
  • +
+
+ + + {% endblock %} diff --git a/src/Bundle/ChillEvent/Resources/views/Role/new.html.twig b/src/Bundle/ChillEvent/Resources/views/Role/new.html.twig new file mode 100644 index 000000000..1bc923f09 --- /dev/null +++ b/src/Bundle/ChillEvent/Resources/views/Role/new.html.twig @@ -0,0 +1,22 @@ +{% extends "ChillEventBundle:Admin:layout.html.twig" %} + +{% block admin_content -%} + +

{{ 'Role creation'|trans }}

+ + {{ form_start(form) }} + {{ form_row(form.name) }} + {{ form_row(form.type) }} + {{ form_row(form.active) }} + + + + {{ form_end(form) }} +{% endblock %} diff --git a/src/Bundle/ChillEvent/Resources/views/Role/show.html.twig b/src/Bundle/ChillEvent/Resources/views/Role/show.html.twig new file mode 100644 index 000000000..5d24ef14f --- /dev/null +++ b/src/Bundle/ChillEvent/Resources/views/Role/show.html.twig @@ -0,0 +1,41 @@ +{% extends "ChillEventBundle:Admin:layout.html.twig" %} + +{% block admin_content -%} + +

{{ 'Role'|trans }}

+ + + + + + + + + + + + + + + + + + + + +
{{ 'Id'|trans }}{{ entity.id }}
{{ 'Name'|trans }}{{ entity.name|localize_translatable_string }}
{{ 'Type'|trans }}{{ entity.type.name|localize_translatable_string }}
{{ 'Active'|trans }}{{ entity.active }}
+ + +{% endblock %} diff --git a/src/Bundle/ChillEvent/Resources/views/Status/edit.html.twig b/src/Bundle/ChillEvent/Resources/views/Status/edit.html.twig new file mode 100644 index 000000000..449ddcb1f --- /dev/null +++ b/src/Bundle/ChillEvent/Resources/views/Status/edit.html.twig @@ -0,0 +1,22 @@ +{% extends "ChillEventBundle:Admin:layout.html.twig" %} + +{% block admin_content -%} + +

{{ 'Status edit'|trans }}

+ + {{ form_start(edit_form) }} + {{ form_row(edit_form.name) }} + {{ form_row(edit_form.type) }} + {{ form_row(edit_form.active) }} + + + + {{ form_end(edit_form) }} +{% endblock %} diff --git a/src/Bundle/ChillEvent/Resources/views/Status/index.html.twig b/src/Bundle/ChillEvent/Resources/views/Status/index.html.twig new file mode 100644 index 000000000..8dec02493 --- /dev/null +++ b/src/Bundle/ChillEvent/Resources/views/Status/index.html.twig @@ -0,0 +1,44 @@ +{% extends "ChillEventBundle:Admin:layout.html.twig" %} + +{% block admin_content -%} + +

{{ 'Status list'|trans }}

+ + + + + + + + + + + + + {% for entity in entities %} + + + + + + + + {% endfor %} + +
{{ 'Id'|trans }}{{ 'Statut'|trans }}{{ 'Type'|trans }}{{ 'Active'|trans }}{{ 'Actions'|trans }}
{{ entity.id }}{{ entity.name|localize_translatable_string }}{{ entity.type.name|localize_translatable_string }}{{ entity.active }} +
    +
  • + +
  • +
  • + +
  • +
+
+ + + {% endblock %} diff --git a/src/Bundle/ChillEvent/Resources/views/Status/new.html.twig b/src/Bundle/ChillEvent/Resources/views/Status/new.html.twig new file mode 100644 index 000000000..f88738d23 --- /dev/null +++ b/src/Bundle/ChillEvent/Resources/views/Status/new.html.twig @@ -0,0 +1,22 @@ +{% extends "ChillEventBundle:Admin:layout.html.twig" %} + +{% block admin_content -%} + +

{{ 'Status creation'|trans }}

+ + {{ form_start(form) }} + {{ form_row(form.name) }} + {{ form_row(form.type) }} + {{ form_row(form.active) }} + + + + {{ form_end(form) }} +{% endblock %} diff --git a/src/Bundle/ChillEvent/Resources/views/Status/show.html.twig b/src/Bundle/ChillEvent/Resources/views/Status/show.html.twig new file mode 100644 index 000000000..e79de3b1c --- /dev/null +++ b/src/Bundle/ChillEvent/Resources/views/Status/show.html.twig @@ -0,0 +1,41 @@ +{% extends "ChillEventBundle:Admin:layout.html.twig" %} + +{% block admin_content -%} + +

{{ 'Status'|trans }}

+ + + + + + + + + + + + + + + + + + + + +
{{ 'Id'|trans }}{{ entity.id }}
{{ 'Status'|trans }}{{ entity.name|localize_translatable_string }}
{{ 'Type'|trans }}{{ entity.type.name|localize_translatable_string }}
{{ 'Active'|trans }}{{ entity.active }}
+ + +{% endblock %} diff --git a/src/Bundle/ChillEvent/Resources/views/Timeline/event_person_context.html.twig b/src/Bundle/ChillEvent/Resources/views/Timeline/event_person_context.html.twig new file mode 100644 index 000000000..09c2390c2 --- /dev/null +++ b/src/Bundle/ChillEvent/Resources/views/Timeline/event_person_context.html.twig @@ -0,0 +1,50 @@ +{% import 'ChillEventBundle:EventReason:macro.html.twig' as m %} + +{% if "now"|date('U') > event.date|date('U') %} + {% set boolDate = 'past' %} +{% else %} + {% set boolDate = 'futur' %} +{% endif %} + +
+

{{ event.date|format_date('long') }} + / + {% if boolDate|trans == 'futur' %} + Prochain événement + {% else %} + {{ 'Event'|trans }} passé + {% endif %} + +

+
+
    +
  • {{ event.name }}
  • +
  • {{ 'Type: ' ~ event.type.name|localize_translatable_string }}
  • +
+ + + {% if is_granted(constant('Chill\\ActivityBundle\\Security\\Authorization\\ActivityVoter::SEE_DETAILS'), event) %} +
+
{{ 'Remark'|trans }}
+
{% if event.remark is empty %}{{ 'No remarks'|trans }}{% else %}
{{ event.remark|nl2br }}
{% endif %}
+ +
{{ 'Reasons'|trans }}
+ {%- if event.reasons is empty -%} +
{{ 'No reason associated'|trans }}
+ {%- else -%} +
{% for r in event.reasons %}{{ m.reason(r) }} {% endfor %}
+ {%- endif -%} + +
+ {% endif %} + +
+ + +
diff --git a/src/Bundle/ChillEvent/Resources/views/layout.html.twig b/src/Bundle/ChillEvent/Resources/views/layout.html.twig new file mode 100644 index 000000000..45eb6e481 --- /dev/null +++ b/src/Bundle/ChillEvent/Resources/views/layout.html.twig @@ -0,0 +1,25 @@ +{# + * Copyright (C) 2014-2015, Champs Libres Cooperative SCRLFS, + / + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . +#} + +{% extends "@ChillMain/layoutWithVerticalMenu.html.twig" %} + +{% block layout_wvm_content %} + {% block event_content %} +

{{ 'Event' |trans }}

+ {% endblock %} +{% endblock %} diff --git a/src/Bundle/ChillEvent/Search/EventSearch.php b/src/Bundle/ChillEvent/Search/EventSearch.php new file mode 100644 index 000000000..8833ed702 --- /dev/null +++ b/src/Bundle/ChillEvent/Search/EventSearch.php @@ -0,0 +1,233 @@ + + * @author Champs Libres + */ +class EventSearch extends AbstractSearch +{ + + /** + * + * @var EntityRepository + */ + private $er; + + /** + * + * @var \Chill\MainBundle\Entity\User + */ + private $user; + + /** + * + * @var AuthorizationHelper + */ + private $helper; + + /** + * + * @var TemplatingEngine + */ + private $templating; + + /** + * + * @var PaginatorFactory + */ + private $paginationFactory; + + const NAME = 'event_regular'; + + public function __construct( + TokenStorageInterface $tokenStorage, + EntityRepository $eventRepository, + AuthorizationHelper $authorizationHelper, + TemplatingEngine $templating, + PaginatorFactory $paginatorFactory + ) + { + $this->user = $tokenStorage->getToken()->getUser(); + $this->er = $eventRepository; + $this->helper = $authorizationHelper; + $this->templating = $templating; + $this->paginationFactory = $paginatorFactory; + } + + public function supports($domain, $format) + { + return 'event' === $domain or 'events' === $domain; + } + + public function isActiveByDefault() + { + return true; + } + + public function getOrder() + { + return 3000; + } + + public function renderResult(array $terms, $start = 0, $limit = 50, + array $options = array(), $format = 'html') + { + $total = $this->count($terms); + $paginator = $this->paginationFactory->create($total); + + if ($format === 'html') { + return $this->templating->render('ChillEventBundle:Event:list.html.twig', + array( + 'events' => $this->search($terms, $start, $limit, $options), + 'pattern' => $this->recomposePattern($terms, $this->getAvailableTerms(), $terms['_domain']), + 'total' => $total, + 'start' => $start, + 'preview' => $options[SearchInterface::SEARCH_PREVIEW_OPTION], + 'paginator' => $paginator, + 'search_name' => self::NAME + )); + } + else if ($format === 'json') { + $results = []; + $search = $this->search($terms, $start, $limit, $options); + foreach ($search as $item) { + $results[] = [ + 'id' => $item->getId(), + 'text' => $item->getDate()->format('d/m/Y, H:i') . ' → ' . + // $item->getType()->getName()['fr'] . ': ' . // display the type of event + $item->getName() + ]; + } + return [ + 'results' => $results, + 'pagination' => [ + 'more' => $paginator->hasNextPage() + ] + ]; + } + } + + protected function getAvailableTerms() + { + return array('date-from', 'date-to', 'name', 'date'); + } + + protected function search(array $terms, $start, $limit, $options) + { + $qb = $this->er->createQueryBuilder('e'); + $qb->select('e'); + $this->composeQuery($qb, $terms) + ->setMaxResults($limit) + ->setFirstResult($start) + ->orderBy('e.date', 'DESC') + ; + + return $qb->getQuery()->getResult(); + } + + protected function count(array $terms) + { + $qb = $this->er->createQueryBuilder('e'); + $qb->select('COUNT(e)'); + $this->composeQuery($qb, $terms) + ; + + return $qb->getQuery()->getSingleScalarResult(); + } + + protected function composeQuery(QueryBuilder &$qb, $terms) + { + + // add security clauses + $reachableCenters = $this->helper + ->getReachableCenters($this->user, new Role('CHILL_EVENT_SEE')); + + if (count($reachableCenters) === 0) { + // add a clause to block all events + $where = $qb->expr()->isNull('e.center'); + $qb->andWhere($where); + } else { + + $n = 0; + $orWhere = $qb->expr()->orX(); + foreach ($reachableCenters as $center) { + $circles = $this->helper->getReachableScopes($this->user, + new Role('CHILL_EVENT_SEE'), $center); + $where = $qb->expr()->andX( + $qb->expr()->eq('e.center', ':center_'.$n), + $qb->expr()->in('e.circle', ':circle_'.$n) + ); + $qb->setParameter('center_'.$n, $center); + $qb->setParameter('circle_'.$n, $circles); + $orWhere->add($where); + } + + $qb->andWhere($orWhere); + } + + if ( + (isset($terms['name']) OR isset($terms['_default'])) + AND + (!empty($terms['name']) OR !empty($terms['_default']))) { + // the form with name:"xyz" has precedence + $name = isset($terms['name']) ? $terms['name'] : $terms['_default']; + + $where = $qb->expr()->like('UNACCENT(LOWER(e.name))', ':name'); + $qb->setParameter('name', '%'.$name.'%'); + $qb->andWhere($where); + } + + if (isset($terms['date'])) { + $date = $this->parseDate($terms['date']); + + $where = $qb->expr()->eq('e.date', ':date'); + $qb->setParameter('date', $date); + $qb->andWhere($where); + } + + if (isset($terms['date-from'])) { + $date = $this->parseDate($terms['date-from']); + + $where = $qb->expr()->gte('e.date', ':datefrom'); + $qb->setParameter('datefrom', $date); + $qb->andWhere($where); + } + + if (isset($terms['date-to'])) { + $date = $this->parseDate($terms['date-to']); + + $where = $qb->expr()->lte('e.date', ':dateto'); + $qb->setParameter('dateto', $date); + $qb->andWhere($where); + } + + return $qb; + } +} diff --git a/src/Bundle/ChillEvent/Security/Authorization/EventVoter.php b/src/Bundle/ChillEvent/Security/Authorization/EventVoter.php new file mode 100644 index 000000000..c62767fa9 --- /dev/null +++ b/src/Bundle/ChillEvent/Security/Authorization/EventVoter.php @@ -0,0 +1,149 @@ + + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +namespace Chill\EventBundle\Security\Authorization; + +use Chill\MainBundle\Security\Authorization\AbstractChillVoter; +use Chill\MainBundle\Security\ProvideRoleHierarchyInterface; +use Chill\EventBundle\Entity\Event; +use Chill\MainBundle\Security\Authorization\AuthorizationHelper; +use Chill\MainBundle\Entity\User; +use Chill\PersonBundle\Entity\Person; +use Chill\PersonBundle\Security\Authorization\PersonVoter; +use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; +use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface; +use Symfony\Component\Security\Core\Role\Role; +use Psr\Log\LoggerInterface; + +/** + * Description of EventVoter + * + * @author Mathieu Jaumotte + * @author Champs Libres + */ +class EventVoter extends AbstractChillVoter implements ProvideRoleHierarchyInterface +{ + const SEE = 'CHILL_EVENT_SEE'; + const SEE_DETAILS = 'CHILL_EVENT_SEE_DETAILS'; + const CREATE = 'CHILL_EVENT_CREATE'; + const UPDATE = 'CHILL_EVENT_UPDATE'; + + const ROLES = [ + self::SEE, + self::SEE_DETAILS, + self::CREATE, + self::UPDATE + ]; + + /** + * @var AuthorizationHelper + */ + protected $authorizationHelper; + + /** + * @var AccessDecisionManagerInterface + */ + protected $accessDecisionManager; + + /** + * @var LoggerInterface + */ + protected $logger; + + public function __construct( + AccessDecisionManagerInterface $accessDecisionManager, + AuthorizationHelper $authorizationHelper, + LoggerInterface $logger + ) + { + $this->accessDecisionManager = $accessDecisionManager; + $this->authorizationHelper = $authorizationHelper; + $this->logger = $logger; + } + + public function supports($attribute, $subject) + { + return ($subject instanceof Event && in_array($attribute, self::ROLES)) + || + ($subject instanceof Person && \in_array($attribute, [ self::CREATE, self::SEE ])) + || + (NULL === $subject && $attribute === self::SEE ) + ; + } + + /** + * + * @param string $attribute + * @param Event $subject + * @param TokenInterface $token + * @return boolean + */ + protected function voteOnAttribute($attribute, $subject, TokenInterface $token) + { + $this->logger->debug(sprintf("Voting from %s class", self::class)); + + if (!$token->getUser() instanceof User) { + return false; + } + + if ($subject instanceof Event) { + return $this->authorizationHelper->userHasAccess($token->getUser(), $subject, $attribute); + + } elseif ($subject instanceof Person) { + return $this->authorizationHelper->userHasAccess($token->getUser(), $subject, $attribute); + + } else { + + // subject is null. We check that at least one center is reachable + $centers = $this->authorizationHelper + ->getReachableCenters($token->getUser(), new Role($attribute)); + + return count($centers) > 0; + } + + if (!$this->accessDecisionManager->decide($token, [PersonVoter::SEE], $person)) { + return false; + } + + return $this->authorizationHelper->userHasAccess( + $token->getUser(), + $subject, + $attribute + ); + + } + + + public function getRoles() + { + return self::ROLES; + } + + public function getRolesWithHierarchy() + { + return [ + 'Event' => self::ROLES + ]; + } + + public function getRolesWithoutScope() + { + return []; + } + +} diff --git a/src/Bundle/ChillEvent/Security/Authorization/ParticipationVoter.php b/src/Bundle/ChillEvent/Security/Authorization/ParticipationVoter.php new file mode 100644 index 000000000..50e05e279 --- /dev/null +++ b/src/Bundle/ChillEvent/Security/Authorization/ParticipationVoter.php @@ -0,0 +1,147 @@ + + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +namespace Chill\EventBundle\Security\Authorization; + +use Chill\MainBundle\Security\ProvideRoleHierarchyInterface; +use Chill\MainBundle\Security\Authorization\AbstractChillVoter; +use Chill\MainBundle\Security\Authorization\AuthorizationHelper; +use Chill\EventBundle\Entity\Participation; +use Chill\MainBundle\Entity\User; +use Chill\PersonBundle\Entity\Person; +use Chill\PersonBundle\Security\Authorization\PersonVoter; +use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface; +use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; +use Symfony\Component\Security\Core\Role\Role; +use Psr\Log\LoggerInterface; + +/** + * + * + * @author Julien Fastré + */ +class ParticipationVoter extends AbstractChillVoter implements ProvideRoleHierarchyInterface +{ + const SEE = 'CHILL_EVENT_PARTICIPATION_SEE'; + const SEE_DETAILS = 'CHILL_EVENT_PARTICIPATION_SEE_DETAILS'; + const CREATE = 'CHILL_EVENT_PARTICIPATION_CREATE'; + const UPDATE = 'CHILL_EVENT_PARTICIPATION_UPDATE'; + + const ROLES = [ + self::SEE, + self::SEE_DETAILS, + self::CREATE, + self::UPDATE + ]; + + /** + * @var AuthorizationHelper + */ + protected $authorizationHelper; + + /** + * @var AccessDecisionManagerInterface + */ + protected $accessDecisionManager; + + /** + * @var LoggerInterface + */ + protected $logger; + + public function __construct( + AccessDecisionManagerInterface $accessDecisionManager, + AuthorizationHelper $authorizationHelper, + LoggerInterface $logger + ) + { + $this->accessDecisionManager = $accessDecisionManager; + $this->authorizationHelper = $authorizationHelper; + $this->logger = $logger; + } + + public function supports($attribute, $subject) + { + return ($subject instanceof Participation && in_array($attribute, self::ROLES)) + || + ($subject instanceof Person && \in_array($attribute, [ self::CREATE, self::SEE ])) + || + (NULL === $subject && $attribute === self::SEE ) + ; + } + + /** + * + * @param string $attribute + * @param Participation $subject + * @param TokenInterface $token + * @return boolean + */ + protected function voteOnAttribute($attribute, $subject, TokenInterface $token) + { + $this->logger->debug(sprintf("Voting from %s class", self::class)); + + if (!$token->getUser() instanceof User) { + return false; + } + + if ($subject instanceof Participation) { + return $this->authorizationHelper->userHasAccess($token->getUser(), $subject, $attribute); + + } elseif ($subject instanceof Person) { + return $this->authorizationHelper->userHasAccess($token->getUser(), $subject, $attribute); + + } else { + + // subject is null. We check that at least one center is reachable + $centers = $this->authorizationHelper + ->getReachableCenters($token->getUser(), new Role($attribute)); + + return count($centers) > 0; + } + + if (!$this->accessDecisionManager->decide($token, [PersonVoter::SEE], $person)) { + return false; + } + + return $this->authorizationHelper->userHasAccess( + $token->getUser(), + $subject, + $attribute + ); + + } + + public function getRoles() + { + return self::ROLES; + } + + public function getRolesWithHierarchy() + { + return [ + 'Event' => self::ROLES + ]; + } + + public function getRolesWithoutScope() + { + return []; + } + +} diff --git a/src/Bundle/ChillEvent/Tests/Controller/EventControllerTest.php b/src/Bundle/ChillEvent/Tests/Controller/EventControllerTest.php new file mode 100644 index 000000000..d955d4a56 --- /dev/null +++ b/src/Bundle/ChillEvent/Tests/Controller/EventControllerTest.php @@ -0,0 +1,60 @@ +markTestSkipped(); + } + /* + public function testCompleteScenario() + { + // Create a new client to browse the application + $client = static::createClient(); + + // Create a new entry in the database + $crawler = $client->request('GET', '/event/'); + $this->assertEquals(200, $client->getResponse()->getStatusCode(), "Unexpected HTTP status code for GET /event/"); + $crawler = $client->click($crawler->selectLink('Create a new entry')->link()); + + // Fill in the form and submit it + $form = $crawler->selectButton('Create')->form(array( + 'chill_eventbundle_event[field_name]' => 'Test', + // ... other fields to fill + )); + + $client->submit($form); + $crawler = $client->followRedirect(); + + // Check data in the show view + $this->assertGreaterThan(0, $crawler->filter('td:contains("Test")')->count(), 'Missing element td:contains("Test")'); + + // Edit the entity + $crawler = $client->click($crawler->selectLink('Edit')->link()); + + $form = $crawler->selectButton('Update')->form(array( + 'chill_eventbundle_event[field_name]' => 'Foo', + // ... other fields to fill + )); + + $client->submit($form); + $crawler = $client->followRedirect(); + + // Check the element contains an attribute with value equals "Foo" + $this->assertGreaterThan(0, $crawler->filter('[value="Foo"]')->count(), 'Missing element [value="Foo"]'); + + // Delete the entity + $client->submit($crawler->selectButton('Delete')->form()); + $crawler = $client->followRedirect(); + + // Check the entity has been delete on the list + $this->assertNotRegExp('/Foo/', $client->getResponse()->getContent()); + } + + */ +} diff --git a/src/Bundle/ChillEvent/Tests/Controller/EventTypeControllerTest.php b/src/Bundle/ChillEvent/Tests/Controller/EventTypeControllerTest.php new file mode 100644 index 000000000..57af95de5 --- /dev/null +++ b/src/Bundle/ChillEvent/Tests/Controller/EventTypeControllerTest.php @@ -0,0 +1,59 @@ +markTestSkipped(); + } + /* + public function testCompleteScenario() + { + // Create a new client to browse the application + $client = static::createClient(); + + // Create a new entry in the database + $crawler = $client->request('GET', '/{_locale}/admin/'); + $this->assertEquals(200, $client->getResponse()->getStatusCode(), "Unexpected HTTP status code for GET /{_locale}/admin/"); + $crawler = $client->click($crawler->selectLink('Create a new entry')->link()); + + // Fill in the form and submit it + $form = $crawler->selectButton('Create')->form(array( + 'chill_eventbundle_eventtype[field_name]' => 'Test', + // ... other fields to fill + )); + + $client->submit($form); + $crawler = $client->followRedirect(); + + // Check data in the show view + $this->assertGreaterThan(0, $crawler->filter('td:contains("Test")')->count(), 'Missing element td:contains("Test")'); + + // Edit the entity + $crawler = $client->click($crawler->selectLink('Edit')->link()); + + $form = $crawler->selectButton('Update')->form(array( + 'chill_eventbundle_eventtype[field_name]' => 'Foo', + // ... other fields to fill + )); + + $client->submit($form); + $crawler = $client->followRedirect(); + + // Check the element contains an attribute with value equals "Foo" + $this->assertGreaterThan(0, $crawler->filter('[value="Foo"]')->count(), 'Missing element [value="Foo"]'); + + // Delete the entity + $client->submit($crawler->selectButton('Delete')->form()); + $crawler = $client->followRedirect(); + + // Check the entity has been delete on the list + $this->assertNotRegExp('/Foo/', $client->getResponse()->getContent()); + } + + */ +} diff --git a/src/Bundle/ChillEvent/Tests/Controller/ParticipationControllerTest.php b/src/Bundle/ChillEvent/Tests/Controller/ParticipationControllerTest.php new file mode 100644 index 000000000..a51fae197 --- /dev/null +++ b/src/Bundle/ChillEvent/Tests/Controller/ParticipationControllerTest.php @@ -0,0 +1,448 @@ + + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +namespace Chill\EventBundle\Tests\Controller; + +use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; + +/** + * Test the creation of participation controller + * + * + * @author Julien Fastré + */ +class ParticipationControllerTest extends WebTestCase +{ + /** + * + * @var \Symfony\Component\BrowserKit\Client + */ + protected $client; + + /** + * + * @var \Doctrine\ORM\EntityManagerInterface + */ + protected $em; + + /** + * Keep a cache for each person id given by the function getRandomPerson. + * + * You may ask to ignore some people by adding their id to the array. + * + * This is reset by setUp(). + * + * @var int[] + */ + private $personsIdsCache = array(); + + public function setUp() + { + self::bootKernel(); + + $this->client = static::createClient(array(), array( + 'PHP_AUTH_USER' => 'center a_social', + 'PHP_AUTH_PW' => 'password', + 'HTTP_ACCEPT_LANGUAGE' => 'fr_FR' + )); + + $container = self::$kernel->getContainer(); + + $this->em = $container->get('doctrine.orm.entity_manager') + ; + + $this->personsIdsCache = array(); + } + + /** + * + * + * @return \Chill\EventBundle\Entity\Event + */ + protected function getRandomEvent($centerName = 'Center A', $circleName = 'social') + { + $center = $this->em->getRepository('ChillMainBundle:Center') + ->findByName($centerName); + + $circles = $this->em->getRepository('ChillMainBundle:Scope') + ->findAll(); + array_filter($circles, function($circle) use ($circleName) { + return in_array($circleName, $circle->getName()); + }); + $circle = $circles[0]; + + $events = $this->em->getRepository('ChillEventBundle:Event') + ->findBy(array('center' => $center, 'circle' => $circle)); + + return $events[array_rand($events)]; + } + + /** + * Return a random event only if he has more than one participation. + * + * @param string $centerName + * @param type $circleName + * @return \Chill\EventBundle\Entity\Event + */ + protected function getRandomEventWithMultipleParticipations( + $centerName = 'Center A', + $circleName = 'social') + { + $event = $this->getRandomEvent($centerName, $circleName); + + return $event->getParticipations()->count() > 1 ? + $event : + $this->getRandomEventWithMultipleParticipations($centerName, $circleName); + } + + /** + * Returns a person randomly. + * + * This function does not give the same person twice + * for each test. + * + * You may ask to ignore some people by adding their id to the property + * `$this->personsIdsCache` + * + * @param string $centerName + * @return \Chill\PersonBundle\Entity\Person + */ + protected function getRandomPerson($centerName = 'Center A') + { + $center = $this->em->getRepository('ChillMainBundle:Center') + ->findByName($centerName); + + $persons = $this->em->getRepository('ChillPersonBundle:Person') + ->findBy(array('center' => $center)); + + $person = $persons[array_rand($persons)]; + + if (in_array($person->getId(), $this->personsIdsCache)) { + return $this->getRandomPerson($centerName); // we try another time + } else { + $this->personsIdsCache[] = $person->getId(); + return $person; + } + + } + + public function testNewActionWrongParameters() + { + $event = $this->getRandomEvent(); + $person = $this->getRandomPerson(); + + // missing person_id or persons_ids + $this->client->request('GET', '/fr/event/participation/new', + array( + 'event_id' => $event->getId() + )); + $this->assertEquals(400, $this->client->getResponse()->getStatusCode(), + "Test that /fr/event/participation/new fail if " + . "both person_id and persons_ids are missing"); + + // having both person_id and persons_ids + $this->client->request('GET', '/fr/event/participation/new', + array( + 'event_id' => $event->getId(), + 'persons_ids' => implode(',', array( + $this->getRandomPerson()->getId(), + $this->getRandomPerson()->getId() + )), + 'person_id' => $person->getId() + )); + $this->assertEquals(400, $this->client->getResponse()->getStatusCode(), + "test that /fr/event/participation/new fail if both person_id and " + . "persons_ids are set"); + + // missing event_id + $this->client->request('GET', '/fr/event/participation/new', + array( + 'person_id' => $person->getId() + )); + $this->assertEquals(400, $this->client->getResponse()->getStatusCode(), + "Test that /fr/event/participation/new fails if event_id is missing"); + + // persons_ids with wrong content + $this->client->request('GET', '/fr/event/participation/new', + array( + 'persons_ids' => 'a,b,531', + 'event_id' => $event->getId() + )); + $this->assertEquals(400, $this->client->getResponse()->getStatusCode(), + "Test that /fr/event/participation/new fails if persons_ids has wrong content"); + } + + /** + * This method test participation creation with wrong parameters. + * + * Those request should fail before any processing. + */ + public function testCreateActionWrongParameters() + { + $event = $this->getRandomEvent(); + $person = $this->getRandomPerson(); + + // missing person_id or persons_ids + $this->client->request('GET', '/fr/event/participation/create', + array( + 'event_id' => $event->getId() + )); + $this->assertEquals(400, $this->client->getResponse()->getStatusCode(), + "Test that /fr/event/participation/create fail if " + . "both person_id and persons_ids are missing"); + + // having both person_id and persons_ids + $this->client->request('GET', '/fr/event/participation/create', + array( + 'event_id' => $event->getId(), + 'persons_ids' => implode(',', array( + $this->getRandomPerson()->getId(), + $this->getRandomPerson()->getId() + )), + 'person_id' => $person->getId() + )); + $this->assertEquals(400, $this->client->getResponse()->getStatusCode(), + "test that /fr/event/participation/create fail if both person_id and " + . "persons_ids are set"); + + // missing event_id + $this->client->request('GET', '/fr/event/participation/create', + array( + 'person_id' => $person->getId() + )); + $this->assertEquals(400, $this->client->getResponse()->getStatusCode(), + "Test that /fr/event/participation/create fails if event_id is missing"); + + // persons_ids with wrong content + $this->client->request('GET', '/fr/event/participation/create', + array( + 'persons_ids' => 'a,b,531', + 'event_id' => $event->getId() + )); + $this->assertEquals(400, $this->client->getResponse()->getStatusCode(), + "Test that /fr/event/participation/create fails if persons_ids has wrong content"); + } + + public function testNewSingleAction() + { + $event = $this->getRandomEvent(); + // record the number of participation for the event + $nbParticipations = $event->getParticipations()->count(); + $person = $this->getRandomPerson(); + + $crawler = $this->client->request('GET', '/fr/event/participation/new', + array( + 'person_id' => $person->getId(), + 'event_id' => $event->getId() + )); + + $this->assertEquals(200, $this->client->getResponse()->getStatusCode(), + "test that /fr/event/participation/new is successful"); + + $button = $crawler->selectButton('Créer'); + + $this->assertNotNull($button, "test the form with button 'Créer' exists"); + + $this->client->submit($button->form(), array( + 'participation[role]' => $event->getType()->getRoles()->first()->getId(), + 'participation[status]' => $event->getType()->getStatuses()->first()->getId() + )); + + $this->assertTrue($this->client->getResponse()->isRedirect()); + $crawler = $this->client->followRedirect(); + + $span = $crawler->filter('table td span.entity-person a:contains("' + .$person->getFirstName().'"):contains("'.$person->getLastname().'")'); + + $this->assertGreaterThan(0, count($span)); + + // as the container has reloaded, reload the event + $event = $this->em->getRepository('ChillEventBundle:Event')->find($event->getId()); + $this->em->refresh($event); + + $this->assertEquals($nbParticipations + 1, $event->getParticipations()->count()); + } + + public function testNewMultipleAction() + { + $event = $this->getRandomEvent(); + // record the number of participation for the event (used later in this test) + $nbParticipations = $event->getParticipations()->count(); + // make ignore the people already in the event from the function getRandomPerson + $this->personsIdsCache = array_merge( + $this->personsIdsCache, + $event->getParticipations()->map( + function($p) { return $p->getPerson()->getId(); } + ) + ->toArray() + ); + // get some random people + $person1 = $this->getRandomPerson(); + $person2 = $this->getRandomPerson(); + + $crawler = $this->client->request('GET', '/fr/event/participation/new', + array( + 'persons_ids' => implode(',', array($person1->getId(), $person2->getId())), + 'event_id' => $event->getId() + )); + + $this->assertEquals(200, $this->client->getResponse()->getStatusCode(), + "test that /fr/event/participation/new is successful"); + + $button = $crawler->selectButton('Créer'); + + $this->assertNotNull($button, "test the form with button 'Créer' exists"); + + $this->client->submit($button->form(), array( + 'form' => array( + 'participations' => array( + 0 => array( + 'role' => $event->getType()->getRoles()->first()->getId(), + 'status' => $event->getType()->getStatuses()->first()->getId() + ), + 1 => array( + 'role' => $event->getType()->getRoles()->first()->getId(), + 'status' => $event->getType()->getStatuses()->first()->getId() + ), + ) + ) + )); + + $this->assertTrue($this->client->getResponse()->isRedirect()); + $crawler = $this->client->followRedirect(); + + $span1 = $crawler->filter('table td span.entity-person a:contains("' + .$person1->getFirstName().'"):contains("'.$person1->getLastname().'")'); + $this->assertGreaterThan(0, count($span1)); + $span2 = $crawler->filter('table td span.entity-person a:contains("' + .$person2->getFirstName().'"):contains("'.$person2->getLastname().'")'); + $this->assertGreaterThan(0, count($span2)); + + // as the container has reloaded, reload the event + $event = $this->em->getRepository('ChillEventBundle:Event')->find($event->getId()); + $this->em->refresh($event); + + $this->assertEquals($nbParticipations + 2, $event->getParticipations()->count()); + } + + public function testNewMultipleWithAllPeopleParticipating() + { + $event = $this->getRandomEventWithMultipleParticipations(); + + $persons_id = implode(',', $event->getParticipations()->map( + function($p) { return $p->getPerson()->getId(); } + )->toArray()); + + $crawler = $this->client->request('GET', '/fr/event/participation/new', + array( + 'persons_ids' => $persons_id, + 'event_id' => $event->getId() + )); + + $this->assertEquals(302, $this->client->getResponse()->getStatusCode(), + "test that /fr/event/participation/new is redirecting"); + } + + public function testNewMultipleWithSomePeopleParticipating() + { + $event = $this->getRandomEventWithMultipleParticipations(); + // record the number of participation for the event (used later in this test) + $nbParticipations = $event->getParticipations()->count(); + // get the persons_id participating on this event + $persons_id = $event->getParticipations()->map( + function($p) { return $p->getPerson()->getId(); } + )->toArray(); + // exclude the existing persons_ids from the new person + $this->personsIdsCache = array_merge($this->personsIdsCache, $persons_id); + + // get a random person + $newPerson = $this->getRandomPerson(); + + // build the `persons_ids` parameter + $persons_ids_string = implode(',', array_merge($persons_id, + array($newPerson->getId()))); + + $crawler = $this->client->request('GET', '/fr/event/participation/new', + array( + 'persons_ids' => $persons_ids_string, + 'event_id' => $event->getId() + )); + + $this->assertEquals(200, $this->client->getResponse()->getStatusCode(), + "test that /fr/event/participation/new is successful"); + + // count that the one UL contains the new person string + $firstPerson = $event->getParticipations()->first()->getPerson(); + $ul = $crawler->filter('ul:contains("'.$firstPerson->getLastName().'")' + . ':contains("'.$firstPerson->getFirstName().'")'); + + $this->assertEquals(1, $ul->count(), + "assert an ul containing the name of ignored people is present"); + $this->assertEquals($event->getParticipations()->count(), $ul->children()->count(), + "assert the li listing ignored people has the correct number"); + + // test a form is present on the page + $button = $crawler->selectButton('Créer'); + + $this->assertNotNull($button, "test the form with button 'Créer' exists"); + + // submit the form + $this->client->submit($button->form(), array( + 'participation[role]' => $event->getType()->getRoles()->first()->getId(), + 'participation[status]' => $event->getType()->getStatuses()->first()->getId() + )); + + $this->assertTrue($this->client->getResponse()->isRedirect()); + + // reload the event and test there is a new participation + $event = $this->em->getRepository('ChillEventBundle:Event') + ->find($event->getId()); + $this->em->refresh($event); + + $this->assertEquals($nbParticipations + 1, $event->getParticipations()->count(), + "Test we have persisted a new participation associated to the test"); + } + + public function testEditMultipleAction() + { + /* @var $event \Chill\EventBundle\Entity\Event */ + $event = $this->getRandomEventWithMultipleParticipations(); + + $crawler = $this->client->request('GET', '/fr/event/participation/'.$event->getId(). + '/edit_multiple'); + + $this->assertEquals(200, $this->client->getResponse()->getStatusCode()); + + $button = $crawler->selectButton('Mettre à jour'); + $this->assertEquals(1, $button->count(), "test the form with button 'mettre à jour' exists "); + + + $this->client->submit($button->form(), array( + 'form[participations][0][role]' => $event->getType()->getRoles()->first()->getId(), + 'form[participations][0][status]' => $event->getType()->getStatuses()->first()->getId(), + 'form[participations][1][role]' => $event->getType()->getRoles()->last()->getId(), + 'form[participations][1][status]' => $event->getType()->getStatuses()->last()->getId(), + )); + + $this->assertTrue($this->client->getResponse() + ->isRedirect('/fr/event/event/'.$event->getId().'/show')); + } + + +} diff --git a/src/Bundle/ChillEvent/Tests/Controller/RoleControllerTest.php b/src/Bundle/ChillEvent/Tests/Controller/RoleControllerTest.php new file mode 100644 index 000000000..f2286f208 --- /dev/null +++ b/src/Bundle/ChillEvent/Tests/Controller/RoleControllerTest.php @@ -0,0 +1,59 @@ +markTestSkipped(); + } + /* + public function testCompleteScenario() + { + // Create a new client to browse the application + $client = static::createClient(); + + // Create a new entry in the database + $crawler = $client->request('GET', '/{_locale}/admin/role/'); + $this->assertEquals(200, $client->getResponse()->getStatusCode(), "Unexpected HTTP status code for GET /{_locale}/admin/role/"); + $crawler = $client->click($crawler->selectLink('Create a new entry')->link()); + + // Fill in the form and submit it + $form = $crawler->selectButton('Create')->form(array( + 'chill_eventbundle_role[field_name]' => 'Test', + // ... other fields to fill + )); + + $client->submit($form); + $crawler = $client->followRedirect(); + + // Check data in the show view + $this->assertGreaterThan(0, $crawler->filter('td:contains("Test")')->count(), 'Missing element td:contains("Test")'); + + // Edit the entity + $crawler = $client->click($crawler->selectLink('Edit')->link()); + + $form = $crawler->selectButton('Update')->form(array( + 'chill_eventbundle_role[field_name]' => 'Foo', + // ... other fields to fill + )); + + $client->submit($form); + $crawler = $client->followRedirect(); + + // Check the element contains an attribute with value equals "Foo" + $this->assertGreaterThan(0, $crawler->filter('[value="Foo"]')->count(), 'Missing element [value="Foo"]'); + + // Delete the entity + $client->submit($crawler->selectButton('Delete')->form()); + $crawler = $client->followRedirect(); + + // Check the entity has been delete on the list + $this->assertNotRegExp('/Foo/', $client->getResponse()->getContent()); + } + + */ +} diff --git a/src/Bundle/ChillEvent/Tests/Controller/StatusControllerTest.php b/src/Bundle/ChillEvent/Tests/Controller/StatusControllerTest.php new file mode 100644 index 000000000..99e297575 --- /dev/null +++ b/src/Bundle/ChillEvent/Tests/Controller/StatusControllerTest.php @@ -0,0 +1,59 @@ +markTestSkipped(); + } + /* + public function testCompleteScenario() + { + // Create a new client to browse the application + $client = static::createClient(); + + // Create a new entry in the database + $crawler = $client->request('GET', '/fr/admin/event/status/'); + $this->assertEquals(200, $client->getResponse()->getStatusCode(), "Unexpected HTTP status code for GET /fr/admin/event/status/"); + $crawler = $client->click($crawler->selectLink('Create a new entry')->link()); + + // Fill in the form and submit it + $form = $crawler->selectButton('Create')->form(array( + 'chill_eventbundle_status[field_name]' => 'Test', + // ... other fields to fill + )); + + $client->submit($form); + $crawler = $client->followRedirect(); + + // Check data in the show view + $this->assertGreaterThan(0, $crawler->filter('td:contains("Test")')->count(), 'Missing element td:contains("Test")'); + + // Edit the entity + $crawler = $client->click($crawler->selectLink('Edit')->link()); + + $form = $crawler->selectButton('Update')->form(array( + 'chill_eventbundle_status[field_name]' => 'Foo', + // ... other fields to fill + )); + + $client->submit($form); + $crawler = $client->followRedirect(); + + // Check the element contains an attribute with value equals "Foo" + $this->assertGreaterThan(0, $crawler->filter('[value="Foo"]')->count(), 'Missing element [value="Foo"]'); + + // Delete the entity + $client->submit($crawler->selectButton('Delete')->form()); + $crawler = $client->followRedirect(); + + // Check the entity has been delete on the list + $this->assertNotRegExp('/Foo/', $client->getResponse()->getContent()); + } + + */ +} diff --git a/src/Bundle/ChillEvent/Tests/Search/EventSearchTest.php b/src/Bundle/ChillEvent/Tests/Search/EventSearchTest.php new file mode 100644 index 000000000..bb31a7bfa --- /dev/null +++ b/src/Bundle/ChillEvent/Tests/Search/EventSearchTest.php @@ -0,0 +1,398 @@ + + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +namespace Chill\EventBundle\Tests\Search; + +use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; +use Chill\EventBundle\Entity\Event; +use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; +use Chill\EventBundle\Search\EventSearch; + + +/** + * Test the EventSearch class + * + * @author Julien Fastré + */ +class EventSearchTest extends WebTestCase +{ + /** + * The eventSearch service, which is used to search events + * + * @var \Chill\EventBundle\Search\EventSearch + */ + protected $eventSearch; + + /** + * + * @var \Doctrine\ORM\EntityManagerInterface + */ + protected $entityManager; + + /** + * The center A + * + * @var \Chill\MainBundle\Entity\Center + */ + protected $centerA; + + /** + * a random event type + * + * @var \Chill\EventBundle\Entity\EventType + */ + protected $eventType; + + /** + * Events created during this test + * + * @var Event[] + */ + protected $events = array(); + + /** + * + * @var \Prophecy\Prophet + */ + protected $prophet; + + /** + * + * @var \Symfony\Component\BrowserKit\Client + */ + protected $client; + + public function setUp() + { + self::bootKernel(); + /* @var $kernel \Symfony\Component\HttpKernel\KernelInterface */ + $kernel = self::$kernel; + + $this->client = static::createClient(array(), array( + 'PHP_AUTH_USER' => 'center a_social', + 'PHP_AUTH_PW' => 'password', + 'HTTP_ACCEPT_LANGUAGE' => 'fr_FR' + )); + + $this->prophet = new \Prophecy\Prophet; + + $this->entityManager = self::$kernel->getContainer() + ->get('doctrine.orm.entity_manager') + ; + + $this->centerA = $this->entityManager + ->getRepository('ChillMainBundle:Center') + ->findOneBy(array('name' => 'Center A')); + + $this->eventType = $this->entityManager + ->getRepository('ChillEventBundle:EventType') + ->findAll()[0]; + + $this->createEvents(); + } + + public function tearDown() + { + foreach ($this->events as $event) { + $this->entityManager->createQuery('DELETE FROM ChillEventBundle:Event e WHERE e.id = :event_id') + ->setParameter('event_id', $event->getId()) + ->execute(); + } + + $this->events = array(); + } + + protected function createEvents() + { + $event1 = (new Event()) + ->setCenter($this->centerA) + ->setDate(new \DateTime('2016-05-30')) + ->setName('Printemps européen') + ->setType($this->eventType) + ->setCircle($this->getCircle()) + ; + $this->entityManager->persist($event1); + $this->events[] = $event1; + + $event2 = (new Event()) + ->setCenter($this->centerA) + ->setDate(new \DateTime('2016-06-24')) + ->setName('Hiver de la droite') + ->setType($this->eventType) + ->setCircle($this->getCircle()) + ; + $this->entityManager->persist($event2); + $this->events[] = $event2; + + $this->entityManager->flush(); + } + + /** + * + * @param string $name the name of the circle + * @return \Chill\MainBundle\Entity\Scope + */ + protected function getCircle($name = 'social') + { + $circles = $this->entityManager->getRepository('ChillMainBundle:Scope') + ->findAll(); + + /* @var $circle \Chill\MainBundle\Entity\Scope */ + foreach($circles as $circle) { + if (in_array($name, $circle->getName())) { + return $circle; + } + } + } + + public function testDisplayAll() + { + $crawler = $this->client->request('GET', '/fr/search', array( + 'q' => '@events' + )); + + $this->assertGreaterThanOrEqual(2, $crawler->filter('table.events tr')->count(), + 'assert than more than 2 tr are present'); + } + + public function testSearchByDefault() + { + $crawler = $this->client->request('GET', '/fr/search', array( + 'q' => '@events printemps' + )); + + $this->assertEquals( + 1, + $crawler->filter('table.events tr')->count() - 1 /* as the header is a th */, + 'assert than more than 2 tr are present'); + + $this->assertEquals( + 1, + $crawler->filter('tr:contains("Printemps")')->count(), + 'assert that the word "printemps" is present'); + } + + public function testSearchByName() + { + $crawler = $this->client->request('GET', '/fr/search', array( + 'q' => '@events name:printemps' + )); + + $this->assertEquals( + 1, + $crawler->filter('table.events tr')->count() - 1 /* as the header is a th */, + 'assert than more than 2 tr are present'); + + $this->assertEquals( + 1, + $crawler->filter('tr:contains("Printemps")')->count(), + 'assert that the word "printemps" is present'); + } + + public function testSearchByDateDateFromOnly() + { + // search with date from + $crawler = $this->client->request('GET', '/fr/search', array( + 'q' => '@events date-from:2016-05-30' + )); + /* @var $dateFrom \DateTime the date from in DateTime */ + $dateFrom = \DateTime::createFromFormat("Y-m-d", "2016-05-30"); + + $dates = $this->iterateOnRowsToFindDate($crawler->filter("tr")); + + foreach($dates as $date) { + $this->assertGreaterThanOrEqual($dateFrom, $date); + } + + // click on link "Voir tous les résultats" + $crawlerAllResults = $this->client->click($crawler + ->selectLink("Voir tous les résultats")->link()); + $dates = $this->iterateOnRowsToFindDate($crawlerAllResults->filter("tr")); + + foreach ($dates as $date) { + $this->assertGreaterThanOrEqual($dateFrom, $date); + } + + //iterate on pagination + $crawlerAllResults->filter(".pagination a")->each(function($a, $i) use ($dateFrom) { + $page = $this->client->click($a->link()); + $dates = $this->iterateOnRowsToFindDate($page->filter("tr")); + + foreach($dates as $date) { + $this->assertGreaterThanOrEqual($dateFrom, $date); + } + }); + } + + public function testSearchByDateDateBetween() + { + // serach with date from **and** date-to + $crawler = $this->client->request('GET', '/fr/search', array( + 'q' => '@events date-from:2016-05-30 date-to:2016-06-20' + )); + + /* @var $dateFrom \DateTime the date from in DateTime */ + $dateFrom = \DateTime::createFromFormat("Y-m-d", "2016-05-30"); + $dateTo = \DateTime::createFromFormat("Y-m-d", "2016-06-20"); + + $dates = $this->iterateOnRowsToFindDate($crawler->filter("tr")); + + foreach($dates as $date) { + $this->assertGreaterThanOrEqual($dateFrom, $date); + $this->assertLessThanOrEqual($dateTo, $date); + } + + // there should not have any other results, but if any other bundle + // add some other event, we go on next pages + + if ($crawler->selectLink("Voir tous les résultats")->count() == 0) { + return ; + } + + // click on link "Voir tous les résultats" + $crawlerAllResults = $this->client->click($crawler + ->selectLink("Voir tous les résultats")->link()); + $dates = $this->iterateOnRowsToFindDate($crawlerAllResults->filter("tr")); + + foreach ($dates as $date) { + $this->assertGreaterThanOrEqual($dateFrom, $date); + $this->assertLessThanOrEqual($dateTo, $date); + } + + //iterate on pagination + $crawlerAllResults->filter(".pagination a")->each(function($a, $i) use ($dateFrom) { + $page = $this->client->click($a->link()); + $dates = $this->iterateOnRowsToFindDate($page->filter("tr")); + + foreach($dates as $date) { + $this->assertGreaterThanOrEqual($dateFrom, $date); + $this->assertLessThanOrEqual($dateTo, $date); + } + }); + } + + public function testSearchByDateDateTo() + { + + // serach with date from **and** date-to + $crawler = $this->client->request('GET', '/fr/search', array( + 'q' => '@events date:2016-05-30' + )); + + /* @var $dateFrom \DateTime the date from in DateTime */ + $dateTo = \DateTime::createFromFormat("Y-m-d", "2016-05-30"); + + $dates = $this->iterateOnRowsToFindDate($crawler->filter("tr")); + + foreach($dates as $date) { + $this->assertLessThanOrEqual($dateTo, $date); + } + + if ($crawler->selectLink("Voir tous les résultats")->count() == 0) { + return ; + } + + // click on link "Voir tous les résultats" + $crawlerAllResults = $this->client->click($crawler + ->selectLink("Voir tous les résultats")->link()); + $dates = $this->iterateOnRowsToFindDate($crawlerAllResults->filter("tr")); + + foreach ($dates as $date) { + $this->assertLessThanOrEqual($dateTo, $date); + } + + //iterate on pagination + $crawlerAllResults->filter(".pagination a")->each(function($a, $i) use ($dateFrom) { + $page = $this->client->click($a->link()); + $dates = $this->iterateOnRowsToFindDate($page->filter("tr")); + + foreach($dates as $date) { + $this->assertLessThanOrEqual($dateTo, $date); + } + }); + + } + + /** + * this function iterate on row from results of events and return the content + * of the second column (which should contains the date) in DateTime objects + * + * @param \Symfony\Component\DomCrawler\Crawler $trs + * @return \DateTime[] + */ + private function iterateOnRowsToFindDate(\Symfony\Component\DomCrawler\Crawler $trs) + { + $months = array( + "janvier" => 1, + "février" => 2, + "mars" => 3, + "avril" => 4, + "mai" => 5, + "juin" => 6, + "juillet" => 7, + "août" => 8, + "septembre" => 9, + "octobre" => 10, + "novembre" => 11, + "décembre" => 12 + ); + + + $results = $trs->each(function($tr, $i) use ($months) { + // we skip the first row + if ($i > 0) { + // get the second node, which should contains a date + $tdDate = $tr->filter("td")->eq(1); + // transform the date, which should be in french, into a DateTime object + $parts = explode(" ", $tdDate->text()); + return \DateTime::createFromFormat("Y-m-d", $parts[2]. + "-".$months[$parts[1]]."-".$parts[0]); + } + }); + + // remove the first row + unset($results[0]); + + return $results; + } + + /** + * Test that a user connected with an user with the wrong center does not + * see the events + */ + public function testDisplayAllWrongUser() + { + $client = static::createClient(array(), array( + 'PHP_AUTH_USER' => 'center b_social', + 'PHP_AUTH_PW' => 'password', + 'HTTP_ACCEPT_LANGUAGE' => 'fr_FR' + )); + + $crawler = $client->request('GET', '/fr/search', array( + 'q' => '@events printemps' + )); + + $this->assertEquals(0, $crawler->filter('tr:contains("Printemps")')->count(), + 'assert that the word "printemps" is present'); + + } + + + +} diff --git a/src/Bundle/ChillEvent/Timeline/TimelineEventProvider.php b/src/Bundle/ChillEvent/Timeline/TimelineEventProvider.php new file mode 100644 index 000000000..3e7c67562 --- /dev/null +++ b/src/Bundle/ChillEvent/Timeline/TimelineEventProvider.php @@ -0,0 +1,241 @@ + + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +namespace Chill\EventBundle\Timeline; + +use Chill\EventBundle\Entity\Event; +use Chill\MainBundle\Entity\Scope; +use Chill\MainBundle\Timeline\TimelineProviderInterface; +use Doctrine\ORM\EntityManager; +use Chill\MainBundle\Security\Authorization\AuthorizationHelper; +use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; +use Symfony\Component\Security\Core\Role\Role; +use Doctrine\ORM\Mapping\ClassMetadata; +use Chill\PersonBundle\Entity\Person; +use Chill\MainBundle\Entity\User; + +/** + * Class TimelineEventProvider + * + * @package Chill\EventBundle\Timeline + * @author Mathieu Jaumotte jaum_mathieu@collectifs.net + */ +class TimelineEventProvider implements TimelineProviderInterface +{ + /** + * @var EntityManager + */ + protected $em; + + /** + * @var AuthorizationHelper + */ + protected $helper; + + /** + * @var User + */ + protected $user; + + /** + * TimelineEventProvider constructor. + * + * @param EntityManager $em + * @param AuthorizationHelper $helper + * @param TokenStorageInterface $storage + */ + public function __construct( + EntityManager $em, + AuthorizationHelper $helper, + TokenStorageInterface $storage + ) { + $this->em = $em; + $this->helper = $helper; + if (!$storage->getToken()->getUser() instanceof User) { + throw new \RuntimeException('A user should be authenticated !'); + } + $this->user = $storage->getToken()->getUser(); + } + + /** + * @param string $context + * @param array $args + * @return array|string[] + * @throws \Doctrine\ORM\Mapping\MappingException + */ + public function fetchQuery($context, array $args) + { + $this->checkContext($context); + + $metadataEvent = $this->em->getClassMetadata('ChillEventBundle:Event'); + $metadataParticipation = $this->em->getClassMetadata('ChillEventBundle:Participation'); + $metadataPerson = $this->em->getClassMetadata('ChillPersonBundle:Person'); + + $query = array( + 'id' => $metadataEvent->getTableName().'.'.$metadataEvent->getColumnName('id'), + 'type' => 'event', + 'date' => $metadataEvent->getTableName().'.'.$metadataEvent->getColumnName('date'), + 'FROM' => $this->getFromClause($metadataEvent, $metadataParticipation, $metadataPerson), + 'WHERE' => $this->getWhereClause($metadataEvent, $metadataParticipation, $metadataPerson, $args['person']) + ); + + return $query; + } + + /** + * @param ClassMetadata $metadataEvent + * @param ClassMetadata $metadataParticipation + * @param ClassMetadata $metadataPerson + * @return string + * @throws \Doctrine\ORM\Mapping\MappingException + */ + private function getFromClause( + ClassMetadata $metadataEvent, + ClassMetadata $metadataParticipation, + ClassMetadata $metadataPerson + ) { + $eventParticipationMapping = $metadataParticipation->getAssociationMapping('event'); + $participationPersonMapping = $metadataParticipation->getAssociationMapping('person'); + + return $metadataEvent->getTableName() + + .' JOIN '.$metadataParticipation->getTableName() + .' ON ' .$metadataParticipation->getTableName() + .'.' .$eventParticipationMapping['joinColumns'][0]['name'] + .' = ' .$metadataEvent->getTableName() + .'.' .$eventParticipationMapping['joinColumns'][0]['referencedColumnName'] + + .' JOIN '.$metadataPerson->getTableName() + .' ON ' .$metadataPerson->getTableName() + .'.' .$participationPersonMapping['joinColumns'][0]['referencedColumnName'] + .' = ' .$metadataParticipation->getTableName() + .'.' .$participationPersonMapping['joinColumns'][0]['name'] + ; + } + + /** + * @param ClassMetadata $metadataEvent + * @param ClassMetadata $metadataParticipation + * @param ClassMetadata $metadataPerson + * @param Person $person + * @return string + * @throws \Doctrine\ORM\Mapping\MappingException + */ + private function getWhereClause( + ClassMetadata $metadataEvent, + ClassMetadata $metadataParticipation, + ClassMetadata $metadataPerson, + Person $person + ) { + $role = new Role('CHILL_EVENT_SEE'); + + $reachableCenters = $this->helper->getReachableCenters($this->user, $role); + $associationMapping = $metadataParticipation->getAssociationMapping('person'); + + if (count($reachableCenters) === 0) { + return 'FALSE = TRUE'; + } + + $whereClause = sprintf( '%s = %d', + $associationMapping['joinColumns'][0]['name'], + $person->getId()); + + // and + $centerAndScopeLines = array(); + foreach ($reachableCenters as $center) { + $reachableCircleId = array_map( + function (Scope $scope) { return $scope->getId(); }, + $this->helper->getReachableCircles($this->user, $role, $person->getCenter()) + ); + $centerAndScopeLines[] = sprintf( + '(%s = %d AND %s IN (%s))', + $metadataPerson->getTableName() . '.' . + $metadataPerson->getAssociationMapping('center')['joinColumns'][0]['name'], + $center->getId(), + $metadataEvent->getTableName() . '.' . + $metadataEvent->getAssociationMapping('circle')['joinColumns'][0]['name'], + implode(',', $reachableCircleId) + ); + } + $whereClause .= ' AND ('. implode(' OR ', $centerAndScopeLines) .')'; + + return $whereClause; + } + + /** + * check if the context is supported + * + * @param string $context + * @throws \LogicException if the context is not supported + */ + private function checkContext($context) + { + if ($context !== 'person') { + throw new \LogicException("The context '$context' is not " + . "supported. Currently only 'person' is supported"); + } + } + + /** + * @param string $type + * @return bool + */ + public function supportsType($type) + { + return $type === 'event'; + } + + /** + * @param array $ids + * @return array|mixed[] + */ + public function getEntities(array $ids) { + + $events = $this->em->getRepository(Event::class) + ->findBy(array('id' => $ids)); + + $result = array(); + foreach ($events as $event) { + $result[$event->getId()] = $event; + } + return $result; + } + + /** + * @param Event $entity + * @param string $context + * @param array $args + * @return array|mixed[] + */ + public function getEntityTemplate($entity, $context, array $args) { + + $this->checkContext($context); + + return array( + 'template' => 'ChillEventBundle:Timeline:event_person_context.html.twig', + 'template_data' => array( + 'event' => $entity, + 'person' => $args['person'], + 'user' => $this->user + ) + ); + } + +} \ No newline at end of file diff --git a/src/Bundle/ChillEvent/apigen.neon b/src/Bundle/ChillEvent/apigen.neon new file mode 100644 index 000000000..7b4c4afc0 --- /dev/null +++ b/src/Bundle/ChillEvent/apigen.neon @@ -0,0 +1,12 @@ +# configuration for apigen + + +source: + - . + +exclude: + - vendor/* + - Resources/test/* + +title: Chill EventBundle + diff --git a/src/Bundle/ChillEvent/chill.webpack.config.js b/src/Bundle/ChillEvent/chill.webpack.config.js new file mode 100644 index 000000000..a194522ad --- /dev/null +++ b/src/Bundle/ChillEvent/chill.webpack.config.js @@ -0,0 +1,4 @@ +// this file loads all assets from the Chill Event Bundle +module.exports = function(encore, entries) { + entries.push(__dirname + '/Resources/public/index.js'); +}; \ No newline at end of file diff --git a/src/Bundle/ChillEvent/composer.json b/src/Bundle/ChillEvent/composer.json new file mode 100644 index 000000000..0a10b88f5 --- /dev/null +++ b/src/Bundle/ChillEvent/composer.json @@ -0,0 +1,43 @@ +{ + "name": "chill-project/event", + "description": "This bundle extend chill software. This bundle allow to define event and participation to those events.", + "type": "symfony-bundle", + "license": "AGPL-3.0-only", + "keywords" : ["chill", "social work"], + "homepage" : "https://git.framasoft.org/Chill-project/Chill-Group", + "autoload": { + "psr-4": { "Chill\\EventBundle\\": "" } + }, + "support": { + "issues": "https://git.framasoft.org/Chill-project/Chill-Event/issues", + "source": "https://git.framasoft.org/Chill-project/Chill-Event", + "docs" : "http://docs.chill.social", + "email": "dev@listes.chill.social" + }, + "authors": [ + { + "name": "Champs-Libres", + "email": "info@champs-libres.coop" + } + ], + "require": { + }, + "require-dev": { + }, + "suggest" : { + "chill-project/group": "dev-master@dev" + }, + "scripts": { + "post-install-cmd": [ + "ComposerBundleMigration\\Composer\\Migrations::synchronizeMigrations" + ], + "post-update-cmd": [ + "ComposerBundleMigration\\Composer\\Migrations::synchronizeMigrations" + ] + }, + "extra": { + "app-migrations-dir": "Resources/test/Fixtures/App/DoctrineMigrations" + }, + "minimum-stability": "dev", + "prefer-stable": true +} diff --git a/src/Bundle/ChillEvent/config/routes.yaml b/src/Bundle/ChillEvent/config/routes.yaml new file mode 100644 index 000000000..2abb338bd --- /dev/null +++ b/src/Bundle/ChillEvent/config/routes.yaml @@ -0,0 +1,42 @@ +chill_event_event: + resource: "@ChillEventBundle/config/routes/event.yaml" + prefix: /{_locale}/event/event + +chill_event_participation: + resource: "@ChillEventBundle/config/routes/participation.yaml" + prefix: /{_locale}/event/participation + + +## ADMIN + +chill_event_admin: + path: /{_locale}/admin/event + controller: Chill\EventBundle\Controller\AdminController::indexAction + options: + menus: + admin_section: + order: 2100 + label: "Events" + icons: ['calendar'] + +chill_event_admin_redirect_to_admin_index: + path: /{_locale}/admin/event_redirect_to_main + controller: Chill\EventBundle\Controller\AdminController::redirectToAdminIndexAction + options: + menus: + admin_events: + order: 0 + label: Main admin menu + +chill_event_admin_status: + resource: "@ChillEventBundle/config/routes/status.yaml" + prefix: /{_locale}/admin/event/status + +chill_event_admin_role: + resource: "@ChillEventBundle/config/routes/role.yaml" + prefix: /{_locale}/admin/event/role + +chill_event_admin_event_type: + resource: "@ChillEventBundle/config/routes/eventtype.yaml" + prefix: /{_locale}/admin/event/event_type + diff --git a/src/Bundle/ChillEvent/config/routes/event.yaml b/src/Bundle/ChillEvent/config/routes/event.yaml new file mode 100644 index 000000000..99dd6447c --- /dev/null +++ b/src/Bundle/ChillEvent/config/routes/event.yaml @@ -0,0 +1,49 @@ +chill_event_list_most_recent: + path: most_recent + controller: Chill\EventBundle\Controller\EventController::mostRecentIndexAction + options: + menus: + section: + order: 90 + label: Events + icons: [calendar] + +chill_event__event_show: + path: /{event_id}/show + controller: Chill\EventBundle\Controller\EventController::showAction + +chill_event__event_new_pickcenter: + path: /new/pick-center + controller: Chill\EventBundle\Controller\EventController::newPickCenterAction + options: + menus: + section: + order: 11 + label: Add an event + icons: [plus, calendar-o] + +chill_event__event_new: + path: /new + controller: Chill\EventBundle\Controller\EventController::newAction + methods: [ GET, POST ] + +chill_event__event_edit: + path: /{event_id}/edit + controller: Chill\EventBundle\Controller\EventController::editAction + +chill_event__event_update: + path: /{event_id}/update + controller: Chill\EventBundle\Controller\EventController::updateAction + methods: [POST, PUT] + +chill_event__list_by_person: + path: /{person_id}/list + controller: Chill\EventBundle\Controller\EventController::listByPersonAction + methods: [ GET ] + +chill_event__event_delete: + path: /{event_id}/delete + requirements: + event_id: \d+ + controller: Chill\EventBundle\Controller\EventController::deleteAction + methods: [ GET, DELETE ] \ No newline at end of file diff --git a/src/Bundle/ChillEvent/config/routes/eventtype.yaml b/src/Bundle/ChillEvent/config/routes/eventtype.yaml new file mode 100644 index 000000000..cbde13ce6 --- /dev/null +++ b/src/Bundle/ChillEvent/config/routes/eventtype.yaml @@ -0,0 +1,35 @@ +chill_eventtype_admin: + path: / + controller: Chill\EventBundle\Controller\EventTypeController::indexAction + options: + menus: + admin_events: + order: 90 + label: "Event types" + +chill_eventtype_admin_show: + path: /{id}/show + controller: Chill\EventBundle\Controller\EventTypeController::showAction + +chill_eventtype_admin_new: + path: /new + controller: Chill\EventBundle\Controller\EventTypeController::newAction + +chill_eventtype_admin_create: + path: /create + controller: Chill\EventBundle\Controller\EventTypeController::createAction + methods: POST + +chill_eventtype_admin_edit: + path: /{id}/edit + controller: Chill\EventBundle\Controller\EventTypeController::editAction + +chill_eventtype_admin_update: + path: /{id}/update + controller: Chill\EventBundle\Controller\EventTypeController::updateAction + methods: [POST, PUT] + +chill_eventtype_admin_delete: + path: /{id}/delete + controller: Chill\EventBundle\Controller\EventTypeController::deleteAction + methods: [POST, DELETE] diff --git a/src/Bundle/ChillEvent/config/routes/participation.yaml b/src/Bundle/ChillEvent/config/routes/participation.yaml new file mode 100644 index 000000000..eb11c72a9 --- /dev/null +++ b/src/Bundle/ChillEvent/config/routes/participation.yaml @@ -0,0 +1,33 @@ +chill_event_participation_new: + path: /new + controller: Chill\EventBundle\Controller\ParticipationController::newAction + +chill_event_participation_create: + path: /create + controller: Chill\EventBundle\Controller\ParticipationController::createAction + +chill_event_participation_edit: + path: /{participation_id}/edit + controller: Chill\EventBundle\Controller\ParticipationController::editAction + +chill_event_participation_update: + path: /{participation_id}/update + controller: Chill\EventBundle\Controller\ParticipationController::updateAction + methods: [POST] + +chill_event_participation_edit_multiple: + path: /{event_id}/edit_multiple + controller: Chill\EventBundle\Controller\ParticipationController::editMultipleAction + +chill_event_participation_update_multiple: + path: /{event_id}/update_multiple + controller: Chill\EventBundle\Controller\ParticipationController::updateMultipleAction + methods: [POST] + +chill_event_participation_delete: + path: /{participation_id}/delete + requirements: + participation_id: \d+ + controller: Chill\EventBundle\Controller\ParticipationController::deleteAction + methods: [ GET, DELETE ] + diff --git a/src/Bundle/ChillEvent/config/routes/role.yaml b/src/Bundle/ChillEvent/config/routes/role.yaml new file mode 100644 index 000000000..5da3c9f98 --- /dev/null +++ b/src/Bundle/ChillEvent/config/routes/role.yaml @@ -0,0 +1,35 @@ +chill_event_admin_role: + path: / + controller: Chill\EventBundle\Controller\RoleController::indexAction + options: + menus: + admin_events: + order: 110 + label: "Event roles" + +chill_event_admin_role_show: + path: /{id}/show + controller: Chill\EventBundle\Controller\RoleController::showAction + +chill_event_admin_role_new: + path: /new + controller: Chill\EventBundle\Controller\RoleController::newAction + +chill_event_admin_role_create: + path: /create + controller: Chill\EventBundle\Controller\RoleController::createAction + methods: POST + +chill_event_admin_role_edit: + path: /{id}/edit + controller: Chill\EventBundle\Controller\RoleController::editAction + +chill_event_admin_role_update: + path: /{id}/update + controller: Chill\EventBundle\Controller\RoleController::updateAction + methods: [POST, PUT] + +chill_event_admin_role_delete: + path: /{id}/delete + controller: Chill\EventBundle\Controller\RoleController::deleteAction + methods: [POST, DELETE] diff --git a/src/Bundle/ChillEvent/config/routes/status.yaml b/src/Bundle/ChillEvent/config/routes/status.yaml new file mode 100644 index 000000000..200d79733 --- /dev/null +++ b/src/Bundle/ChillEvent/config/routes/status.yaml @@ -0,0 +1,35 @@ +chill_event_admin_status: + path: / + controller: Chill\EventBundle\Controller\StatusController::indexAction + options: + menus: + admin_events: + order: 100 + label: "Event status" + +chill_event_admin_status_show: + path: /{id}/show + controller: Chill\EventBundle\Controller\StatusController::showAction + +chill_event_admin_status_new: + path: /new + controller: Chill\EventBundle\Controller\StatusController::newAction + +chill_event_admin_status_create: + path: /create + controller: Chill\EventBundle\Controller\StatusController::createAction + methods: POST + +chill_event_admin_status_edit: + path: /{id}/edit + controller: Chill\EventBundle\Controller\StatusController::editAction + +chill_event_admin_status_update: + path: /{id}/update + controller: Chill\EventBundle\Controller\StatusController::updateAction + methods: [POST, PUT] + +chill_event_admin_status_delete: + path: /{id}/delete + controller: Chill\EventBundle\Controller\StatusController::deleteAction + methods: [POST, DELETE] diff --git a/src/Bundle/ChillEvent/config/services.yaml b/src/Bundle/ChillEvent/config/services.yaml new file mode 100644 index 000000000..8287f32b5 --- /dev/null +++ b/src/Bundle/ChillEvent/config/services.yaml @@ -0,0 +1,2 @@ +services: + diff --git a/src/Bundle/ChillEvent/config/services/authorization.yaml b/src/Bundle/ChillEvent/config/services/authorization.yaml new file mode 100644 index 000000000..ca1eb789b --- /dev/null +++ b/src/Bundle/ChillEvent/config/services/authorization.yaml @@ -0,0 +1,20 @@ +services: + chill_event.event_voter: + class: Chill\EventBundle\Security\Authorization\EventVoter + arguments: + - "@security.access.decision_manager" + - "@chill.main.security.authorization.helper" + - "@logger" + tags: + - { name: chill.role } + - { name: security.voter } + + chill_event.event_participation: + class: Chill\EventBundle\Security\Authorization\ParticipationVoter + arguments: + - "@security.access.decision_manager" + - "@chill.main.security.authorization.helper" + - "@logger" + tags: + - { name: chill.role } + - { name: security.voter } diff --git a/src/Bundle/ChillEvent/config/services/controller.yaml b/src/Bundle/ChillEvent/config/services/controller.yaml new file mode 100644 index 000000000..b74764e34 --- /dev/null +++ b/src/Bundle/ChillEvent/config/services/controller.yaml @@ -0,0 +1,16 @@ +services: + + Chill\EventBundle\Controller\EventController: + arguments: + $eventDispatcher: '@Symfony\Component\EventDispatcher\EventDispatcherInterface' + $authorizationHelper: '@Chill\MainBundle\Security\Authorization\AuthorizationHelper' + $formFactoryInterface: '@Symfony\Component\Form\FormFactoryInterface' + $translator: '@Symfony\Component\Translation\TranslatorInterface' + $paginator: '@chill_main.paginator_factory' + public: true + tags: ['controller.service_arguments'] + + Chill\EventBundle\Controller\ParticipationController: + arguments: + $logger: '@Psr\Log\LoggerInterface' + tags: ['controller.service_arguments'] diff --git a/src/Bundle/ChillEvent/config/services/fixtures.yaml b/src/Bundle/ChillEvent/config/services/fixtures.yaml new file mode 100644 index 000000000..c39947899 --- /dev/null +++ b/src/Bundle/ChillEvent/config/services/fixtures.yaml @@ -0,0 +1,4 @@ +services: + Chill\EventBundle\DataFixtures\ORM\: + resource: ../../DataFixtures/ORM + tags: [ 'doctrine.fixture.orm' ] diff --git a/src/Bundle/ChillEvent/config/services/forms.yaml b/src/Bundle/ChillEvent/config/services/forms.yaml new file mode 100644 index 000000000..a1c0d925a --- /dev/null +++ b/src/Bundle/ChillEvent/config/services/forms.yaml @@ -0,0 +1,49 @@ +services: + chill.event.form.type.pick_event_type: + class: Chill\EventBundle\Form\Type\PickEventTypeType + arguments: + - "@chill.main.helper.translatable_string" + tags: + - { name: form.type } + + chill.event.form.participation_type: + class: Chill\EventBundle\Form\ParticipationType + arguments: + - "@chill.main.helper.translatable_string" + tags: + - { name: form.type } + + chill.event.form.pick_role_type: + class: Chill\EventBundle\Form\Type\PickRoleType + arguments: + - "@chill.main.helper.translatable_string" + - "@translator" + - "@chill_event.repository.role" + tags: + - { name: form.type } + + chill.event.form.pick_status_type: + class: Chill\EventBundle\Form\Type\PickStatusType + arguments: + - "@chill.main.helper.translatable_string" + - "@translator" + - "@chill_event.repository.status" + tags: + - { name: form.type } + + chill.event.form.role_type: + class: Chill\EventBundle\Form\RoleType + arguments: + - "@chill.main.helper.translatable_string" + tags: + - { name: form.type } + + Chill\EventBundle\Form\Type\PickEventType: + arguments: + $eventRepository: "@chill_event.repository.event" + $tokenStorage: "@security.token_storage" + $authorizationHelper: "@chill.main.security.authorization.helper" + $urlGenerator: '@Symfony\Component\Routing\Generator\UrlGeneratorInterface' + $translator: '@Symfony\Component\Translation\TranslatorInterface' + tags: + - { name: form.type } diff --git a/src/Bundle/ChillEvent/config/services/menu.yaml b/src/Bundle/ChillEvent/config/services/menu.yaml new file mode 100644 index 000000000..a2451122f --- /dev/null +++ b/src/Bundle/ChillEvent/config/services/menu.yaml @@ -0,0 +1,7 @@ +services: + Chill\EventBundle\Menu\PersonMenuBuilder: + arguments: + $authorizationChecker: '@Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface' + $translator: '@Symfony\Component\Translation\TranslatorInterface' + tags: + - { name: 'chill.menu_builder' } \ No newline at end of file diff --git a/src/Bundle/ChillEvent/config/services/repositories.yaml b/src/Bundle/ChillEvent/config/services/repositories.yaml new file mode 100644 index 000000000..4d627f625 --- /dev/null +++ b/src/Bundle/ChillEvent/config/services/repositories.yaml @@ -0,0 +1,25 @@ +services: + + chill_event.repository.event: + class: Chill\EventBundle\Repository\EventRepository + factory: ['@doctrine.orm.entity_manager', getRepository] + arguments: + - 'Chill\EventBundle\Entity\Event' + + chill_event.repository.participation: + class: Chill\EventBundle\Repository\ParticipationRepository + factory: ['@doctrine.orm.entity_manager', getRepository] + arguments: + - 'Chill\EventBundle\Entity\Participation' + + chill_event.repository.role: + class: Doctrine\ORM\EntityRepository + factory: ['@doctrine.orm.entity_manager', getRepository] + arguments: + - 'Chill\EventBundle\Entity\Role' + + chill_event.repository.status: + class: Doctrine\ORM\EntityRepository + factory: ['@doctrine.orm.entity_manager', getRepository] + arguments: + - 'Chill\EventBundle\Entity\Status' diff --git a/src/Bundle/ChillEvent/config/services/search.yaml b/src/Bundle/ChillEvent/config/services/search.yaml new file mode 100644 index 000000000..2df3db26f --- /dev/null +++ b/src/Bundle/ChillEvent/config/services/search.yaml @@ -0,0 +1,12 @@ +services: + chill_event.search_events: + class: Chill\EventBundle\Search\EventSearch + arguments: + - "@security.token_storage" + - "@chill_event.repository.event" + - "@chill.main.security.authorization.helper" + - "@templating" + - "@chill_main.paginator_factory" + tags: + - { name: chill.search, alias: 'event_regular' } + diff --git a/src/Bundle/ChillEvent/config/services/timeline.yaml b/src/Bundle/ChillEvent/config/services/timeline.yaml new file mode 100644 index 000000000..7a8eb366d --- /dev/null +++ b/src/Bundle/ChillEvent/config/services/timeline.yaml @@ -0,0 +1,10 @@ +services: + chill.event.timeline: + class: Chill\EventBundle\Timeline\TimelineEventProvider + arguments: + - '@doctrine.orm.entity_manager' + - '@chill.main.security.authorization.helper' + - '@security.token_storage' + public: true + tags: + - { name: chill.timeline, context: 'person' } diff --git a/src/Bundle/ChillEvent/config/validation.yaml b/src/Bundle/ChillEvent/config/validation.yaml new file mode 100644 index 000000000..d5c7d2243 --- /dev/null +++ b/src/Bundle/ChillEvent/config/validation.yaml @@ -0,0 +1,26 @@ +Chill\EventBundle\Entity\Participation: + properties: + event: + - NotNull: ~ + status: + - NotNull: ~ + person: + - NotNull: ~ + constraints: + - Callback: isConsistent + + +Chill\EventBundle\Entity\Event: + properties: + name: + - Length: + min: 3 + max: 75 + minMessage: The event name must have at least {{ limit }} characters. + maxMessage: The event name must have maximum {{ limit }} characters. + type: + - NotNull: ~ + circle: + - NotNull: ~ + center: + - NotNull: ~ diff --git a/src/Bundle/ChillEvent/migrations/Version20160318111334.php b/src/Bundle/ChillEvent/migrations/Version20160318111334.php new file mode 100644 index 000000000..50671534e --- /dev/null +++ b/src/Bundle/ChillEvent/migrations/Version20160318111334.php @@ -0,0 +1,141 @@ +abortIf($this->connection->getDatabasePlatform()->getName() != 'postgresql', 'Migration can only be executed safely on \'postgresql\'.'); + + $this->addSql('CREATE SEQUENCE chill_event_event_type_id_seq INCREMENT BY 1 MINVALUE 1 START 1'); + $this->addSql('CREATE SEQUENCE chill_event_role_id_seq INCREMENT BY 1 MINVALUE 1 START 1'); + $this->addSql('CREATE SEQUENCE chill_event_status_id_seq INCREMENT BY 1 MINVALUE 1 START 1'); + $this->addSql('CREATE SEQUENCE chill_event_event_id_seq INCREMENT BY 1 MINVALUE 1 START 1'); + $this->addSql('CREATE SEQUENCE chill_event_participation_id_seq INCREMENT BY 1 MINVALUE 1 START 1'); + $this->addSql('CREATE TABLE chill_event_event_type (' + . 'id INT NOT NULL, name JSON NOT NULL, ' + . 'active BOOLEAN NOT NULL, PRIMARY KEY(id))'); + $this->addSql('CREATE TABLE chill_event_role (' + . 'id INT NOT NULL, ' + . 'type_id INT DEFAULT NULL, ' + . 'name JSON NOT NULL, ' + . 'active BOOLEAN NOT NULL, ' + . 'PRIMARY KEY(id))'); + $this->addSql('CREATE INDEX IDX_AA714E54C54C8C93 ON chill_event_role (type_id)'); + $this->addSql('CREATE TABLE chill_event_status (id INT NOT NULL, ' + . 'type_id INT DEFAULT NULL, ' + . 'name JSON NOT NULL, ' + . 'active BOOLEAN NOT NULL, ' + . 'PRIMARY KEY(id))'); + $this->addSql('CREATE INDEX IDX_A6CC85D0C54C8C93 ON chill_event_status (type_id)'); + $this->addSql('CREATE TABLE chill_event_event (' + . 'id INT NOT NULL, ' + . 'name VARCHAR(150) NOT NULL, ' + . 'date DATE NOT NULL, ' + . 'center_id INT DEFAULT NULL, ' + . 'type_id INT DEFAULT NULL, ' + . 'circle_id INT DEFAULT NULL, ' + . 'PRIMARY KEY(id))'); + $this->addSql('CREATE TABLE chill_event_participation (' + . 'id INT NOT NULL, ' + . 'event_id INT DEFAULT NULL, ' + . 'person_id INT DEFAULT NULL, ' + . 'role_id INT DEFAULT NULL, ' + . 'status_id INT DEFAULT NULL, ' + . 'lastUpdate TIMESTAMP(0) WITHOUT TIME ZONE NOT NULL, ' + . 'PRIMARY KEY(id))'); + $this->addSql('CREATE INDEX IDX_4E7768AC71F7E88B ON chill_event_participation (event_id)'); + $this->addSql('CREATE INDEX IDX_4E7768AC217BBB47 ON chill_event_participation (person_id)'); + $this->addSql('CREATE INDEX IDX_4E7768ACD60322AC ON chill_event_participation (role_id)'); + $this->addSql('CREATE INDEX IDX_4E7768AC6BF700BD ON chill_event_participation (status_id)'); + $this->addSql('CREATE INDEX IDX_FA320FC85932F377 ON chill_event_event (center_id)'); + $this->addSql('CREATE INDEX IDX_FA320FC8C54C8C93 ON chill_event_event (type_id)'); + $this->addSql('CREATE INDEX IDX_FA320FC870EE2FF6 ON chill_event_event (circle_id)'); + + $this->addSql('ALTER TABLE chill_event_event ' + . 'ADD CONSTRAINT FK_FA320FC85932F377 FOREIGN KEY (center_id) ' + . 'REFERENCES centers (id) ' + . 'NOT DEFERRABLE INITIALLY IMMEDIATE'); + $this->addSql('ALTER TABLE chill_event_event ' + . 'ADD CONSTRAINT FK_FA320FC870EE2FF6 FOREIGN KEY (circle_id) ' + . 'REFERENCES scopes (id) NOT DEFERRABLE INITIALLY IMMEDIATE'); + $this->addSql('ALTER TABLE chill_event_event ' + . 'ADD CONSTRAINT FK_FA320FC8C54C8C93 FOREIGN KEY (type_id) ' + . 'REFERENCES chill_event_event_type (id) ' + . 'NOT DEFERRABLE INITIALLY IMMEDIATE'); + $this->addSql('ALTER TABLE chill_event_role ' + . 'ADD CONSTRAINT FK_AA714E54C54C8C93 FOREIGN KEY (type_id) ' + . 'REFERENCES chill_event_event_type (id) ' + . 'NOT DEFERRABLE INITIALLY IMMEDIATE'); + $this->addSql('ALTER TABLE chill_event_status ' + . 'ADD CONSTRAINT FK_A6CC85D0C54C8C93 ' + . 'FOREIGN KEY (type_id) ' + . 'REFERENCES chill_event_event_type (id) ' + . 'NOT DEFERRABLE INITIALLY IMMEDIATE'); + $this->addSql('ALTER TABLE chill_event_participation ' + . 'ADD CONSTRAINT FK_4E7768AC71F7E88B ' + . 'FOREIGN KEY (event_id) ' + . 'REFERENCES chill_event_event (id) ' + . 'NOT DEFERRABLE INITIALLY IMMEDIATE'); + $this->addSql('ALTER TABLE chill_event_participation ' + . 'ADD CONSTRAINT FK_4E7768AC217BBB47 ' + . 'FOREIGN KEY (person_id) ' + . 'REFERENCES Person (id) ' + . 'NOT DEFERRABLE INITIALLY IMMEDIATE'); + $this->addSql('ALTER TABLE chill_event_participation ' + . 'ADD CONSTRAINT FK_4E7768ACD60322AC ' + . 'FOREIGN KEY (role_id) ' + . 'REFERENCES chill_event_role (id) ' + . 'NOT DEFERRABLE INITIALLY IMMEDIATE'); + $this->addSql('ALTER TABLE chill_event_participation ' + . 'ADD CONSTRAINT FK_4E7768AC6BF700BD ' + . 'FOREIGN KEY (status_id) ' + . 'REFERENCES chill_event_status (id) ' + . 'NOT DEFERRABLE INITIALLY IMMEDIATE'); + + } + + /** + * @param Schema $schema + */ + public function down(Schema $schema): void + { + // this down() migration is auto-generated, please modify it to your needs + $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'postgresql', 'Migration can only be executed safely on \'postgresql\'.'); + + $this->addSql('ALTER TABLE chill_event_role DROP CONSTRAINT FK_AA714E54C54C8C93'); + $this->addSql('ALTER TABLE chill_event_status DROP CONSTRAINT FK_A6CC85D0C54C8C93'); + $this->addSql('ALTER TABLE chill_event_participation DROP CONSTRAINT FK_4E7768ACD60322AC'); + $this->addSql('ALTER TABLE chill_event_participation DROP CONSTRAINT FK_4E7768AC6BF700BD'); + $this->addSql('ALTER TABLE chill_event_participation DROP CONSTRAINT FK_4E7768AC71F7E88B'); + // drop center_id constraint + $this->addSql('ALTER TABLE chill_event_event DROP CONSTRAINT FK_FA320FC85932F377'); + // drop type_id constraint + $this->addSql('ALTER TABLE chill_event_event DROP CONSTRAINT FK_FA320FC8C54C8C93'); + // drop circle_id constraint + $this->addSql('ALTER TABLE chill_event_event DROP CONSTRAINT FK_FA320FC870EE2FF6'); + + $this->addSql('DROP SEQUENCE chill_event_event_type_id_seq CASCADE'); + $this->addSql('DROP SEQUENCE chill_event_role_id_seq CASCADE'); + $this->addSql('DROP SEQUENCE chill_event_status_id_seq CASCADE'); + $this->addSql('DROP SEQUENCE chill_event_event_id_seq CASCADE'); + $this->addSql('DROP SEQUENCE chill_event_participation_id_seq CASCADE'); + $this->addSql('DROP TABLE chill_event_event_type'); + $this->addSql('DROP TABLE chill_event_role'); + $this->addSql('DROP TABLE chill_event_status'); + $this->addSql('DROP TABLE chill_event_event'); + $this->addSql('DROP TABLE chill_event_participation'); + + } +} diff --git a/src/Bundle/ChillEvent/migrations/Version20190110140538.php b/src/Bundle/ChillEvent/migrations/Version20190110140538.php new file mode 100644 index 000000000..5018c9f1a --- /dev/null +++ b/src/Bundle/ChillEvent/migrations/Version20190110140538.php @@ -0,0 +1,29 @@ +abortIf($this->connection->getDatabasePlatform()->getName() !== 'postgresql', 'Migration can only be executed safely on \'postgresql\'.'); + + $this->addSql('ALTER TABLE chill_event_event ALTER date TYPE TIMESTAMP(0) WITHOUT TIME ZONE'); + $this->addSql('ALTER TABLE chill_event_event ALTER date DROP DEFAULT'); + + } + + public function down(Schema $schema): void + { + $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'postgresql', 'Migration can only be executed safely on \'postgresql\'.'); + + $this->addSql('ALTER TABLE chill_event_event ALTER date TYPE DATE'); + $this->addSql('ALTER TABLE chill_event_event ALTER date DROP DEFAULT'); + } +} diff --git a/src/Bundle/ChillEvent/migrations/Version20190115140042.php b/src/Bundle/ChillEvent/migrations/Version20190115140042.php new file mode 100644 index 000000000..21e476948 --- /dev/null +++ b/src/Bundle/ChillEvent/migrations/Version20190115140042.php @@ -0,0 +1,32 @@ +abortIf($this->connection->getDatabasePlatform()->getName() !== 'postgresql', 'Migration can only be executed safely on \'postgresql\'.'); + + $this->addSql('ALTER TABLE chill_event_event ADD moderator_id INT DEFAULT NULL'); + $this->addSql('ALTER TABLE chill_event_event ADD CONSTRAINT FK_FA320FC8D0AFA354 FOREIGN KEY (moderator_id) REFERENCES chill_person_person (id) NOT DEFERRABLE INITIALLY IMMEDIATE'); + $this->addSql('CREATE INDEX IDX_FA320FC8D0AFA354 ON chill_event_event (moderator_id)'); + } + + public function down(Schema $schema): void + { + // this down() migration is auto-generated, please modify it to your needs + $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'postgresql', 'Migration can only be executed safely on \'postgresql\'.'); + + $this->addSql('ALTER TABLE chill_event_event DROP CONSTRAINT FK_FA320FC8D0AFA354'); + $this->addSql('DROP INDEX IDX_FA320FC8D0AFA354'); + $this->addSql('ALTER TABLE chill_event_event DROP moderator_id'); + } +} diff --git a/src/Bundle/ChillEvent/migrations/Version20190201143121.php b/src/Bundle/ChillEvent/migrations/Version20190201143121.php new file mode 100644 index 000000000..7edbb4d52 --- /dev/null +++ b/src/Bundle/ChillEvent/migrations/Version20190201143121.php @@ -0,0 +1,31 @@ +abortIf($this->connection->getDatabasePlatform()->getName() !== 'postgresql', 'Migration can only be executed safely on \'postgresql\'.'); + + $this->addSql('ALTER TABLE chill_event_event DROP CONSTRAINT FK_FA320FC8D0AFA354'); + $this->addSql('ALTER TABLE chill_event_event ADD CONSTRAINT FK_FA320FC8D0AFA354 FOREIGN KEY (moderator_id) REFERENCES users (id) NOT DEFERRABLE INITIALLY IMMEDIATE'); + } + + public function down(Schema $schema): void + { + // this down() migration is auto-generated, please modify it to your needs + $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'postgresql', 'Migration can only be executed safely on \'postgresql\'.'); + + $this->addSql('ALTER TABLE chill_event_event DROP CONSTRAINT fk_fa320fc8d0afa354'); + $this->addSql('ALTER TABLE chill_event_event ADD CONSTRAINT fk_fa320fc8d0afa354 FOREIGN KEY (moderator_id) REFERENCES chill_person_person (id) NOT DEFERRABLE INITIALLY IMMEDIATE'); + + } +} diff --git a/src/Bundle/ChillEvent/phpunit.xml.dist b/src/Bundle/ChillEvent/phpunit.xml.dist new file mode 100644 index 000000000..cb1f867cf --- /dev/null +++ b/src/Bundle/ChillEvent/phpunit.xml.dist @@ -0,0 +1,23 @@ + + + + + + ./Tests + + + + + ./ + + ./Resources + ./Tests + ./vendor + + + + + + + + diff --git a/src/Bundle/ChillEvent/translations/messages.fr.yml b/src/Bundle/ChillEvent/translations/messages.fr.yml new file mode 100644 index 000000000..3ca0da260 --- /dev/null +++ b/src/Bundle/ChillEvent/translations/messages.fr.yml @@ -0,0 +1,111 @@ +#events +Name: Nom +Label: Nom +Date: Date +Event type : Type d'événement +See: Voir +Event: Événement +Events: Événements +'Event : %label%': Événement "%label%" +Participation: Participation +Participations: Participations +Status: Statut +Last update: Dernière mise à jour +'%count% participations to this event': '{0} Aucun participant à l''événement | {1} Un participant à l''événement | ]1,Inf] %count% participants à l''événement' +Moderator: Animateur + +#CRUD event +Details of an event: Détails d'un événement +See details of the event: Voir les détails de l'événement +Back to details of the event: Retour aux détails de l'événement +New event: Nouvel événement +Back to the most recent events: Retour aux derniers événements +'Back to %person% events': Retour aux événements de %person% +Event creation: Création d'un événement +Add an event: Ajouter un événement +Event edit: Modifier un événement +Edit the event: Modifier l'événement +The event was updated: L'événement a été modifié +The event was created: L'événement a été créé + +#crud participation +Edit all the participations: Modifier toutes les participations +Edit the participation: Modifier la participation +Participation Edit: Modifier une participation +Add a participation: Ajouter un participant +Participation creation: Ajouter une participation +Associated person: Personne associée +Associated event: Événement associé +Back to the event: Retour à l'événement +The participation was created: La participation a été créée +The participation was updated: La participation a été mise à jour +'None of the requested people may participate the event: they are maybe already participating.': 'Aucune des personnes indiquées ne peut être ajoutée à l''événement: elles sont peut-être déjà inscrites comme participantes.' +'The following people have been ignored because they are already participating on the event': '{1} La personne suivante a été ignorée parce qu''elle participe déjà à l''événement | ]1,Inf] Les personnes suivantes ont été ignorées parce qu''elles participent déjà à l''événement' +There are no participation to edit for this event: Il n'y a pas de participation pour cet événement +The participations have been successfully updated.: Les participations ont été mises à jour. +The participation has been sucessfully removed: La participation a été correctement supprimée. +The event has been sucessfully removed: L'événement et toutes les participations associées ont été correctement supprimées. +The participations were created: Les participations ont été créées +Events participation: Participation aux événements +Remove participation: Supprimer la participation +Delete event: Supprimer l'événement +Are you sure you want to remove that participation ?: Êtes-vous certain de vouloir supprimer cette participation ? +Are you sure you want to remove that event ?: Êtes-vous certain de vouloir supprimer cet événement, ainsi que toutes les participations associées ? + +#search +Event search: Recherche d'événements +'%total% events match the search %pattern%' : '{0} Aucun événement ne correspond aux termes de recherche "%pattern%" | {1} Un événement a été trouvé par la recherche "%pattern%" | ]1,Inf] %total% événements correspondent aux termes de recherche "%pattern%".' + +CHILL_EVENT_UPDATE: Modifier un événement +CHILL_EVENT_CREATE: Créer un événement +CHILL_EVENT_SEE: Voir un événement +CHILL_EVENT_SEE_DETAILS: Voir les détails d'un événement +CHILL_EVENT_PARTICIPATION_CREATE: Créer une participation +CHILL_EVENT_PARTICIPATION_UPDATE: Modifier une participation +CHILL_EVENT_PARTICIPATION_SEE: Voir une participation +CHILL_EVENT_PARTICIPATION_SEE_DETAILS: Voir le détail d'une participation + +# TODO check place to put this +Next step: Étape suivante +To which centre should the event be associated ?: À quel centre doit être associé l'événement ? + +# timeline +past: passé +futur: futur +'subscribed by %user% to event "%event%" (%event_type%)': inscrit par %user% à l'événement "%event%" (%event_type%) +Show the event: Voir l'événement + +Subscribe an event: Ajouter un événement +Pick an event: Choisir un événement +Pick a type of event: Choisir un type d'événement +Pick a moderator: Choisir un animateur + +Select a format: Choisir un format +Export: Exporter + + +Events configuration: Configuration des événements +Events configuration menu: Menu des événements +Event status: Statuts par type d'événement +Event roles: Rôles par type d'événement +Event types: Types d'événements +EventType list: Liste des types d'événements +EventType: Types d'événements +EventType creation: Nouveau type d'événement +EventType edit: Modifier le type d'événement +Status list: Liste des statuts +Status creation: Nouveau statut +Status edit: Modifier un statut +Role list: Liste des rôles +Role: Rôles +Role creation: Nouveau rôle +Role edit: Modifier un rôle + +'': '' +xlsx: xlsx +ods: ods +csv: csv + +Create a new role: Créer un nouveau rôle +Create a new type: Créer un nouveau type +Create a new status: Créer un nouveau statut \ No newline at end of file