Allow to add multiple participation

The participationController accept a new parameter : `persons_ids`,
which must receive a comma-separated list of person ids. A participation
will be create for all those peoples.

The `new` and `create` actions does not allow to receive both
`person_id` and `persons_ids`.

Tests are added.

ref #6
This commit is contained in:
Julien Fastré 2016-04-09 23:45:07 +02:00
parent bcfa2c2131
commit 9459d7a287
9 changed files with 626 additions and 31 deletions

View File

@ -26,6 +26,7 @@ use Chill\EventBundle\Entity\Participation;
use Chill\EventBundle\Form\ParticipationType; use Chill\EventBundle\Form\ParticipationType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType; use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Chill\EventBundle\Security\Authorization\ParticipationVoter; use Chill\EventBundle\Security\Authorization\ParticipationVoter;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
/** /**
* *
@ -44,23 +45,65 @@ class ParticipationController extends Controller
*/ */
public function newAction(Request $request) public function newAction(Request $request)
{ {
$single = $request->query->getInt('person_id', null); // test the request is correct
$multiple = $request->query->get('persons_ids', null); try {
$this->testRequest($request);
if ($single !== NULL AND $multiple !== NULL) { } catch (\RuntimeException $ex) {
// we are not allowed to have both person_id and persons_ids $this->get('logger')->warning($ex->getMessage());
return (new Response()) return (new Response())
->setStatusCode(Response::HTTP_BAD_REQUEST) ->setStatusCode(Response::HTTP_BAD_REQUEST)
->setContent("You are not allow to provide both 'person_id' and " ->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");
}
protected function testRequest($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"); . "'persons_ids' simulaneously");
} }
if ($single !== NULL) { if ($multiple === true) {
return $this->newSingleAction($request); $persons_ids = $request->query->get('persons_ids');
if (!preg_match('/^([0-9]{1,},){1,}[0-9]{1,}$/', $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");
}
} }
protected function newSingleAction(Request $request) protected function newSingle(Request $request)
{ {
$participation = $this->handleRequest($request, new Participation()); $participation = $this->handleRequest($request, new Participation());
@ -75,7 +118,57 @@ class ParticipationController extends Controller
)); ));
} }
protected function newMultiple(Request $request)
{
$participations = $this->handleRequest($request, new Participation());
foreach ($participations as $participation) {
$this->denyAccessUnlessGranted(ParticipationVoter::CREATE,
$participation, 'The user is not allowed to create this participation');
}
$form = $this->createCreateFormMultiple($participations);
return $this->render('ChillEventBundle:Participation:new-multiple.html.twig', array(
'form' => $form->createView(),
'participations' => $participations
));
}
public function createAction(Request $request) public function createAction(Request $request)
{
// test the request is correct
try {
$this->testRequest($request);
} catch (\RuntimeException $ex) {
$this->get('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");
}
public function createSingle(Request $request)
{ {
$participation = $this->handleRequest($request, new Participation()); $participation = $this->handleRequest($request, new Participation());
@ -106,7 +199,49 @@ class ParticipationController extends Controller
)); ));
} }
public function createMultiple(Request $request)
{
$participations = $this->handleRequest($request, new Participation());
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 Request $request
* @param Participation $participation * @param Participation $participation
@ -117,6 +252,10 @@ class ParticipationController extends Controller
protected function handleRequest(Request $request, Participation $participation) protected function handleRequest(Request $request, Participation $participation)
{ {
$em = $this->getDoctrine()->getManager(); $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', null); $event_id = $request->query->getInt('event_id', null);
@ -134,23 +273,37 @@ class ParticipationController extends Controller
$participation->setEvent($event); $participation->setEvent($event);
} }
$person_id = $request->query->getInt('person_id', null); // this script should be able to handle multiple, so we translate
// single person_id in an array
$persons_ids = $request->query->has('person_id') ?
array($request->query->getInt('person_id', null)):
explode(',', $request->query->get('persons_ids'))
;
$participations = array();
if ($person_id !== NULL) { foreach($persons_ids as $person_id) {
$person = $em->getRepository('ChillPersonBundle:Person')
->find($person_id);
if ($person === NULL) { // clone if we have to reuse the $participation
throw $this->createNotFoundException('The person with id '.$person_id.' is not found'); $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);
} }
$this->denyAccessUnlessGranted('CHILL_PERSON_SEE', $person, $participations[] = $participation;
'The user is not allowed to see the person');
$participation->setPerson($person);
} }
return $participation; return count($participations) > 1 ? $participations : $participations[0];
} }
/** /**
@ -175,6 +328,37 @@ class ParticipationController extends Controller
return $form; return $form;
} }
/**
*
* @param array $participations
* @return type
*/
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' => $participations[0]->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' => $participations[0]->getEvent()->getType()
),
)
);
$form->add('submit', SubmitType::class, array(
'label' => 'Create'
));
return $form;
}
/** /**
* show an edit form for the participation with the given id. * show an edit form for the participation with the given id.
* *

View File

@ -9,7 +9,7 @@ use Symfony\Component\Validator\Context\ExecutionContextInterface;
/** /**
* Participation * Participation
*/ */
class Participation implements HasCenterInterface, HasScopeInterface class Participation implements HasCenterInterface, HasScopeInterface, \ArrayAccess
{ {
/** /**
* @var integer * @var integer
@ -218,6 +218,11 @@ class Participation implements HasCenterInterface, HasScopeInterface
*/ */
public function isConsistent(ExecutionContextInterface $context) public function isConsistent(ExecutionContextInterface $context)
{ {
if ($this->getEvent() === NULL || $this->getRole() === NULL || $this->getStatus() === NULL) {
return;
}
if ($this->getRole()->getType()->getId() !== if ($this->getRole()->getType()->getId() !==
$this->getEvent()->getType()->getId()) { $this->getEvent()->getType()->getId()) {
$context->buildViolation('The role is not allowed with this event type') $context->buildViolation('The role is not allowed with this event type')
@ -233,4 +238,52 @@ class Participation implements HasCenterInterface, HasScopeInterface
} }
} }
public function offsetExists($offset)
{
return in_array($offset, array(
'person', 'role', 'status', 'event'
));
}
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;
}
}
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;
}
}
public function offsetUnset($offset)
{
$this->offsetSet($offset, null);
}
} }

View File

@ -3,30 +3,57 @@
{% import 'ChillPersonBundle:Person:macro.html.twig' as person_macro %} {% import 'ChillPersonBundle:Person:macro.html.twig' as person_macro %}
{% block title 'Participation creation'|trans %} {% block title 'Participation creation'|trans %}
{% form_theme form _self %}
{% block _collection_row %}
<tr>
<td>
{{ form_widget(form) }}
</td>
<td>
{# {{ form_row(participationField.status) }} #}
</td>
</tr>
{% endblock %}
{% block event_content -%} {% block event_content -%}
<h1>{{ 'Participation creation'|trans }}</h1> <h1>{{ 'Participation creation'|trans }}</h1>
<table> <table>
<tbody> <tbody>
<tr>
<th>{{ 'Associated person'|trans }}</th>
<td>{{ person_macro.render(participation.person) }}</td>
</tr>
<tr> <tr>
<th>{{ 'Associated event'|trans }} </th> <th>{{ 'Associated event'|trans }} </th>
<td>{{ participation.event.name }}</td> <td>{{ participations[0].event.name }}</td>
</tr> </tr>
</tbody> </tbody>
</table> </table>
{{ form_start(form) }}
{{ form_row(form.role) }}
{{ form_row(form.status) }}
{{ form_start(form) }}
<table>
<thead>
<tr>
<th>{{ 'Person'|trans }}</th>
<th>{{ 'Role'|trans }}</th>
<th>{{ 'Status'|trans }}</th>
</tr>
</thead>
<tbody>
{% for participationField in form.participations %}
<tr>
<td>{{ person_macro.render(participationField.vars.value.person) }}</td>
<td>{{ form_widget(participationField.role) }}</td>
<td>{{ form_widget(participationField.status) }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<ul class="record_actions"> <ul class="record_actions">
<li> <li>
<a href="{{ path('chill_event__event_show', { 'event_id' : participation.event.id } ) }}" class="sc-button btn-cancel"> <a href="{{ path('chill_event__event_show', { 'event_id' : participations[0].event.id } ) }}" class="sc-button btn-cancel">
<i class="fa fa-arrow-left"></i> <i class="fa fa-arrow-left"></i>
{{ 'Back to the event'|trans }} {{ 'Back to the event'|trans }}
</a> </a>

View File

@ -21,6 +21,9 @@
</table> </table>
{{ form_start(form) }} {{ form_start(form) }}
{{ form_errors(form) }}
{{ form_row(form.role) }} {{ form_row(form.role) }}
{{ form_row(form.status) }} {{ form_row(form.status) }}

View File

@ -6,6 +6,11 @@ use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class EventControllerTest extends WebTestCase class EventControllerTest extends WebTestCase
{ {
public function testSkipped()
{
$this->markTestSkipped();
}
/* /*
public function testCompleteScenario() public function testCompleteScenario()
{ {

View File

@ -6,6 +6,10 @@ use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class EventTypeControllerTest extends WebTestCase class EventTypeControllerTest extends WebTestCase
{ {
public function testSkipped()
{
$this->markTestSkipped();
}
/* /*
public function testCompleteScenario() public function testCompleteScenario()
{ {

View File

@ -0,0 +1,311 @@
<?php
/*
* Copyright (C) 2016 Champs-Libres <info@champs-libres.coop>
*
* 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 <http://www.gnu.org/licenses/>.
*/
namespace Chill\EventBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
/**
* Test the creation of participation controller
*
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
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.
*
* 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)];
}
/**
* This function does not give the same person twice
* for each test
*
* @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
$nbParticipations = $event->getParticipations()->count();
$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());
}
}

View File

@ -6,6 +6,10 @@ use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class RoleControllerTest extends WebTestCase class RoleControllerTest extends WebTestCase
{ {
public function testSkipped()
{
$this->markTestSkipped();
}
/* /*
public function testCompleteScenario() public function testCompleteScenario()
{ {

View File

@ -6,6 +6,10 @@ use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class StatusControllerTest extends WebTestCase class StatusControllerTest extends WebTestCase
{ {
public function testSkipped()
{
$this->markTestSkipped();
}
/* /*
public function testCompleteScenario() public function testCompleteScenario()
{ {