Merge remote-tracking branch 'origin/master' into 232_resources_comment

This commit is contained in:
Julien Fastré 2022-01-10 21:50:00 +01:00
commit 098c2fbaa0
118 changed files with 1735 additions and 498 deletions

View File

@ -11,6 +11,20 @@ and this project adheres to
## Unreleased
<!-- write down unreleased development here -->
* vuejs: translate in French all multiselect widgets
* [address] define address lines according postal standards for France and Belgium (default) and change AddressRender, chill_entity_render_box and AddressRenderBox.vue
* [household] change translations (champs-libres/departement-de-la-vendee/accent-suivi-developpement#109)
* [household] add address i18n in household component (champs-libres/departement-de-la-vendee/accent-suivi-developpement#158)
* [household] add on the fly i18n in household component
* [household] redirect to the household page when a household is created from a person (champs-libres/departement-de-la-vendee/accent-suivi-developpement#175)
* [household] household member editor: display alert if some members have already an household (champs-libres/departement-de-la-vendee/accent-suivi-developpement#172)
* [household] household member editor: do not add in new members if the member is included in the members of household (champs-libres/departement-de-la-vendee/accent-suivi-developpement#123)
* [household] household member editor: remove markNoAddress button (champs-libres/departement-de-la-vendee/accent-suivi-developpement#109)
* [person]: ordering fields in add person (https://gitlab.com/champs-libres/departement-de-la-vendee/accent-suivi-developpement/-/issues/61)
* [person]: Add email and alt names in add person (https://gitlab.com/champs-libres/departement-de-la-vendee/accent-suivi-developpement/-/issues/61)
* [accompanyingCourse] Add a delete action and delete buttons to delete a accompanying course when step = DRAFT (https://gitlab.com/champs-libres/departement-de-la-vendee/accent-suivi-developpement/-/issues/64)
* [accompanyingCourse] Add a administrative location in the accompanying course, set the user current location as default, allow to select a location in a select field and do not allow to confirm the accompanying course if location is empty.
* [accompanyingCourse] Add the administrative location in the available variables for document generation
* AddAddress: optimize loading: wait for the user finish typing;
* UserPicker: fix bug with deprecated role
* docgen: add base context + tests
@ -25,6 +39,7 @@ and this project adheres to
* Household: show date validFrom and validTo when moving
* address reference: add index for refid
* [accompanyingCourse_work] fix styles conflicts + fix bug with remove goal (remove goals one at a time)
* [accompanyingCourse] improve masonry on resume page, add origin
## Test releases

View File

@ -17,7 +17,6 @@
"doctrine/orm": "^2.7",
"erusev/parsedown": "^1.7",
"graylog2/gelf-php": "^1.5",
"knplabs/knp-menu": "^3.1",
"knplabs/knp-menu-bundle": "^3.0",
"knplabs/knp-time-bundle": "^1.12",
"league/csv": "^9.7.1",
@ -32,6 +31,7 @@
"symfony/css-selector": "^4.4",
"symfony/expression-language": "^4.4",
"symfony/form": "^4.4",
"symfony/framework-bundle": "^4.4",
"symfony/intl": "^4.4",
"symfony/mime": "^4.4",
"symfony/monolog-bundle": "^3.5",
@ -47,14 +47,14 @@
"symfony/yaml": "^4.4",
"twig/extra-bundle": "^3.0",
"twig/intl-extra": "^3.0",
"twig/markdown-extra": "^3.3",
"twig/twig": "^3.0"
"twig/markdown-extra": "^3.3"
},
"require-dev": {
"doctrine/doctrine-fixtures-bundle": "^3.3",
"drupol/php-conventions": "^5",
"fakerphp/faker": "^1.13",
"nelmio/alice": "^3.8",
"phpspec/prophecy-phpunit": "^2.0",
"phpstan/phpstan-strict-rules": "^1.0",
"phpunit/phpunit": ">= 7.5",
"symfony/debug-bundle": "^5.1",

View File

@ -859,11 +859,6 @@ parameters:
count: 1
path: src/Bundle/ChillMainBundle/Security/PasswordRecover/PasswordRecoverEvent.php
-
message: "#^Call to deprecated method setTimeout\\(\\) of class Redis\\.$#"
count: 1
path: src/Bundle/ChillMainBundle/Security/PasswordRecover/PasswordRecoverLocker.php
-
message:
"""

View File

@ -315,11 +315,6 @@ parameters:
count: 1
path: src/Bundle/ChillMainBundle/Security/PasswordRecover/TokenManager.php
-
message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#"
count: 3
path: src/Bundle/ChillMainBundle/Templating/Entity/AddressRender.php
-
message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#"
count: 1

View File

@ -6,7 +6,6 @@
backupGlobals="false"
colors="true"
bootstrap="tests/app/tests/bootstrap.php"
stopOnFailure="true"
>
<php>
<ini name="error_reporting" value="-1" />

View File

@ -12,7 +12,7 @@
</div>
<div v-if="getContext === 'accompanyingCourse' && suggestedEntities.length > 0">
<ul class="list-suggest add-items inline">
<li v-for="p in suggestedEntities" @click="addSuggestedEntity(p)">
<li v-for="(p, i) in suggestedEntities" @click="addSuggestedEntity(p)" :key="`suggestedEntities-${i}`">
<span>{{ p.text }}</span>
</li>
</ul>

View File

@ -15,13 +15,15 @@
:searchable="true"
:placeholder="$t('activity.choose_location')"
:custom-label="customLabel"
:select-label="$t('multiselect.select_label')"
:deselect-label="$t('multiselect.deselect_label')"
:selected-label="$t('multiselect.selected_label')"
:options="availableLocations"
group-values="locations"
group-label="locationGroup"
v-model="location"
>
</VueMultiselect>
<new-location v-bind:locations="locations"></new-location>
</div>
</div>
@ -32,7 +34,6 @@
import { mapState, mapGetters } from "vuex";
import VueMultiselect from "vue-multiselect";
import NewLocation from "./Location/NewLocation.vue";
import { getLocations, getLocationTypeByDefaultFor, getUserCurrentLocation } from "../api.js";
export default {
name: "Location",

View File

@ -9,9 +9,9 @@
<check-social-issue
v-for="issue in socialIssuesList"
v-bind:key="issue.id"
v-bind:issue="issue"
v-bind:selection="socialIssuesSelected"
:key="issue.id"
:issue="issue"
:selection="socialIssuesSelected"
@updateSelected="updateIssuesSelected">
</check-social-issue>
@ -21,18 +21,18 @@
label="text"
track-by="id"
open-direction="bottom"
v-bind:close-on-select="true"
v-bind:preserve-search="false"
v-bind:reset-after="true"
v-bind:hide-selected="true"
v-bind:taggable="false"
v-bind:multiple="false"
v-bind:searchable="true"
v-bind:allow-empty="true"
v-bind:show-labels="false"
v-bind:loading="issueIsLoading"
v-bind:placeholder="$t('activity.choose_other_social_issue')"
v-bind:options="socialIssuesOther"
:close-on-select="true"
:preserve-search="false"
:reset-after="true"
:hide-selected="true"
:taggable="false"
:multiple="false"
:searchable="true"
:allow-empty="true"
:show-labels="false"
:loading="issueIsLoading"
:placeholder="$t('activity.choose_other_social_issue')"
:options="socialIssuesOther"
@select="addIssueInList">
</VueMultiselect>
</div>
@ -58,9 +58,9 @@
<check-social-action
v-if="socialIssuesSelected.length || socialActionsSelected.length"
v-for="action in socialActionsList"
v-bind:key="action.id"
v-bind:action="action"
v-bind:selection="socialActionsSelected"
:key="action.id"
:action="action"
:selection="socialActionsSelected"
@updateSelected="updateActionsSelected">
</check-social-action>
</template>

View File

@ -1,4 +1,5 @@
import { personMessages } from 'ChillPersonAssets/vuejs/_js/i18n'
import { multiSelectMessages } from 'ChillMainAssets/vuejs/_js/i18n'
const activityMessages = {
fr: {
@ -33,12 +34,11 @@ const activityMessages = {
},
create_address: 'Créer une adresse',
edit_address: "Modifier l'adresse"
}
}
}
Object.assign(activityMessages.fr, personMessages.fr);
Object.assign(activityMessages.fr, personMessages.fr, multiSelectMessages.fr);
export {
activityMessages

View File

@ -66,7 +66,7 @@ final class ActivityReasonCategoryControllerTest extends WebTestCase
$crawler = $client->followRedirect();
// Check the entity has been delete on the list
$this->assertNotRegExp('/Foo/', $client->getResponse()->getContent());
$this->assertDoesNotMatchRegularExpression('/Foo/', $client->getResponse()->getContent());
}
*/

View File

@ -66,7 +66,7 @@ final class ActivityReasonControllerTest extends WebTestCase
$crawler = $client->followRedirect();
// Check the entity has been delete on the list
$this->assertNotRegExp('/Foo/', $client->getResponse()->getContent());
$this->assertDoesNotMatchRegularExpression('/Foo/', $client->getResponse()->getContent());
}
*/

View File

@ -66,7 +66,7 @@ final class ActivityTypeControllerTest extends WebTestCase
$crawler = $client->followRedirect();
// Check the entity has been delete on the list
$this->assertNotRegExp('/Foo/', $client->getResponse()->getContent());
$this->assertDoesNotMatchRegularExpression('/Foo/', $client->getResponse()->getContent());
}
*/

View File

@ -13,6 +13,9 @@
:close-on-select="false"
:allow-empty="true"
:model-value="value"
:select-label="$t('multiselect.select_label')"
:deselect-label="$t('multiselect.deselect_label')"
:selected-label="$t('multiselect.selected_label')"
@select="selectUsers"
@remove="unSelectUsers"
@close="coloriseSelectedValues"

View File

@ -1,13 +1,17 @@
import { multiSelectMessages } from 'ChillMainAssets/vuejs/_js/i18n'
const calendarUserSelectorMessages = {
fr: {
choose_your_calendar_user: "Afficher les plages de disponibilités",
select_user: "Sélectionnez des calendriers",
show_my_calendar: "Afficher mon calendrier",
show_weekends: "Afficher les week-ends"
}
};
fr: {
choose_your_calendar_user: "Afficher les plages de disponibilités",
select_user: "Sélectionnez des calendriers",
show_my_calendar: "Afficher mon calendrier",
show_weekends: "Afficher les week-ends"
}
};
export {
calendarUserSelectorMessages
};
Object.assign(calendarUserSelectorMessages.fr, multiSelectMessages.fr);
export {
calendarUserSelectorMessages
};

View File

@ -33,11 +33,11 @@ final class ConfigCustomizablesEntitiesTest extends KernelTestCase
$customizableEntities = self::$kernel->getContainer()
->getParameter('chill_custom_fields.customizables_entities');
$this->assertInternalType('array', $customizableEntities);
$this->assertIsArray($customizableEntities);
$this->assertCount(2, $customizableEntities);
foreach ($customizableEntities as $key => $config) {
$this->assertInternalType('array', $config);
$this->assertIsArray($config);
$this->assertArrayHasKey('name', $config);
$this->assertArrayHasKey('class', $config);
}
@ -56,7 +56,7 @@ final class ConfigCustomizablesEntitiesTest extends KernelTestCase
$customizableEntities = self::$kernel->getContainer()
->getParameter('chill_custom_fields.customizables_entities');
$this->assertInternalType('array', $customizableEntities);
$this->assertIsArray($customizableEntities);
$this->assertCount(1, $customizableEntities);
}
}

View File

@ -61,7 +61,7 @@ final class CustomFieldControllerTest_TODO extends WebTestCase
$crawler = $client->followRedirect();
// Check the entity has been delete on the list
$this->assertNotRegExp('/Foo/', $client->getResponse()->getContent());
$this->assertDoesNotMatchRegularExpression('/Foo/', $client->getResponse()->getContent());
}
*/

View File

@ -276,7 +276,6 @@ final class DocGeneratorTemplateController extends AbstractController
fwrite($templateResource, $dataDecrypted);
rewind($templateResource);
}
$datas = $context->getData($template, $entity, $contextGenerationData);
try {

View File

@ -46,7 +46,6 @@ class RelatorioDriver implements DriverInterface
'template' => new DataPart($template, $templateName ?? uniqid('template_'), $resourceType),
];
$form = new FormDataPart($formFields);
dump(json_encode($data));
try {
$response = $this->relatorioClient->request('POST', $this->url, [

View File

@ -23,11 +23,7 @@
<input type="hidden" name="entityClassName" value="{{ contextManager.getContextByKey(entity.context).entityClass|e('html_attr') }}" />
<input type="text" name="entityId" />
<ul class="record_actions">
<li>
<button type="submit" class="btn btn-mini btn-neutral">{{ 'docgen.test generate'|trans }}</button>
</li>
</ul>
<button type="submit" class="btn btn-mini btn-misc"><i class="fa fa-cog"></i>{{ 'docgen.test generate'|trans }}</button>
</form>
</td>
<td>

View File

@ -11,9 +11,11 @@ declare(strict_types=1);
namespace Chill\DocGeneratorBundle\Serializer\Helper;
use Symfony\Component\Serializer\Mapping\ClassMetadata;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use function array_merge;
use function is_array;
class NormalizeNullValueHelper
{
@ -30,7 +32,7 @@ class NormalizeNullValueHelper
$this->discriminatorValue = $discriminatorValue;
}
public function normalize(array $attributes, string $format = 'docgen', ?array $context = [])
public function normalize(array $attributes, string $format = 'docgen', ?array $context = [], ?ClassMetadata $classMetadata = null)
{
$data = [];
$data['isNull'] = true;
@ -58,7 +60,7 @@ class NormalizeNullValueHelper
default:
$data[$key] = $this->normalizer->normalize(null, $format, array_merge(
$context,
$this->getContextForAttribute($key, $context, $classMetadata),
['docgen:expects' => $class]
));
@ -69,4 +71,25 @@ class NormalizeNullValueHelper
return $data;
}
private function getContextForAttribute(string $key, array $initialContext, ?ClassMetadata $classMetadata): array
{
if (null === $classMetadata) {
return $initialContext;
}
$attributeMetadata = $classMetadata->getAttributesMetadata()[$key] ?? null;
if (null !== $attributeMetadata) {
/** @var \Symfony\Component\Serializer\Mapping\AttributeMetadata $attributeMetadata */
$initialContext = array_merge(
$initialContext,
$attributeMetadata->getNormalizationContextForGroups(
is_array($initialContext['groups']) ? $initialContext['groups'] : [$initialContext['groups']]
)
);
}
return $initialContext;
}
}

View File

@ -196,7 +196,7 @@ class DocGenObjectNormalizer implements NormalizerAwareInterface, NormalizerInte
$normalizer = new NormalizeNullValueHelper($this->normalizer, $typeKey, $typeValue);
return $normalizer->normalize($keys, $format, $context);
return $normalizer->normalize($keys, $format, $context, $metadata);
}
/**
@ -260,9 +260,13 @@ class DocGenObjectNormalizer implements NormalizerAwareInterface, NormalizerInte
/** @var AttributeMetadata $attribute */
$value = $this->propertyAccess->getValue($object, $attribute->getName());
$key = $attribute->getSerializedName() ?? $attribute->getName();
$isTranslatable = $attribute->getNormalizationContextForGroups(
is_array($context['groups']) ? $context['groups'] : [$context['groups']]
)['is-translatable'] ?? false;
$objectContext = array_merge(
$context,
$attribute->getNormalizationContextForGroups(
is_array($context['groups']) ? $context['groups'] : [$context['groups']]
)
);
$isTranslatable = $objectContext['is-translatable'] ?? false;
if ($isTranslatable) {
$data[$key] = $this->translatableStringHelper
@ -273,7 +277,7 @@ class DocGenObjectNormalizer implements NormalizerAwareInterface, NormalizerInte
foreach ($value as $k => $v) {
$arr[$k] =
$this->normalizer->normalize($v, $format, array_merge(
$context,
$objectContext,
$attribute->getNormalizationContextForGroups($expectedGroups)
));
}
@ -281,11 +285,11 @@ class DocGenObjectNormalizer implements NormalizerAwareInterface, NormalizerInte
} elseif (is_object($value)) {
$data[$key] =
$this->normalizer->normalize($value, $format, array_merge(
$context,
$objectContext,
$attribute->getNormalizationContextForGroups($expectedGroups)
));
} elseif (null === $value) {
$data[$key] = $this->normalizeNullOutputValue($format, $context, $attribute, $reflection);
$data[$key] = $this->normalizeNullOutputValue($format, $objectContext, $attribute, $reflection);
} else {
$data[$key] = $value;
}

View File

@ -14,6 +14,7 @@ namespace Chill\DocGeneratorBundle\tests\Serializer\Normalizer;
use Chill\MainBundle\Entity\Scope;
use Chill\MainBundle\Entity\User;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\Serializer\Annotation as Serializer;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
@ -33,6 +34,49 @@ final class DocGenObjectNormalizerTest extends KernelTestCase
$this->normalizer = self::$container->get(NormalizerInterface::class);
}
public function testChangeContextOnAttribute()
{
$object = new TestableParentClass();
$actual = $this->normalizer->normalize(
$object,
'docgen',
['groups' => 'docgen:read']
);
$this->assertIsArray($actual);
$this->assertArrayHasKey('child', $actual);
$this->assertIsArray($actual['child']);
$this->assertArrayHasKey('foo', $actual['child']);
$this->assertEquals('bar', $actual['child']['foo']);
$this->assertArrayNotHasKey('baz', $actual['child']);
// test with child = null
$object->child = null;
$actual = $this->normalizer->normalize(
$object,
'docgen',
['groups' => 'docgen:read']
);
$this->assertIsArray($actual);
$this->assertArrayHasKey('child', $actual);
$this->assertIsArray($actual['child']);
$this->assertArrayHasKey('foo', $actual['child']);
$this->assertEquals('', $actual['child']['foo']);
$this->assertArrayNotHasKey('baz', $actual['child']);
$actual = $this->normalizer->normalize(
null,
'docgen',
['groups' => 'docgen:read', 'docgen:expects' => TestableParentClass::class],
);
$this->assertIsArray($actual);
$this->assertArrayHasKey('child', $actual);
$this->assertIsArray($actual['child']);
$this->assertArrayHasKey('foo', $actual['child']);
$this->assertEquals('', $actual['child']['foo']);
$this->assertArrayNotHasKey('baz', $actual['child']);
}
public function testNormalizationBasic()
{
$scope = new Scope();
@ -99,3 +143,30 @@ final class DocGenObjectNormalizerTest extends KernelTestCase
$this->assertEquals($expected, $normalized, 'test normalization fo an user with null center');
}
}
class TestableParentClass
{
/**
* @Serializer\Groups("docgen:read")
* @Serializer\Context(normalizationContext={"groups": "docgen:read:foo"}, groups={"docgen:read"})
*/
public ?TestableChildClass $child;
public function __construct()
{
$this->child = new TestableChildClass();
}
}
class TestableChildClass
{
/**
* @Serializer\Groups("docgen:read")
*/
public string $baz = 'bloup';
/**
* @Serializer\Groups("docgen:read:foo")
*/
public string $foo = 'bar';
}

View File

@ -13,6 +13,7 @@ namespace Chill\DocGeneratorBundle\tests\Service\Context;
use Chill\DocGeneratorBundle\Service\Context\BaseContextData;
use Chill\MainBundle\Entity\User;
use Prophecy\PhpUnit\ProphecyTrait;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
@ -23,6 +24,8 @@ use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
*/
final class BaseContextDataTest extends KernelTestCase
{
use ProphecyTrait;
protected function setUp(): void
{
parent::setUp();

View File

@ -7,6 +7,7 @@ docgen:
Context: Contexte
New template: Nouveau gabarit
Edit template: Modifier gabarit
test generate: Tester la génération
With context: 'Avec le contexte :'

View File

@ -66,7 +66,7 @@ final class EventControllerTest extends WebTestCase
$crawler = $client->followRedirect();
// Check the entity has been delete on the list
$this->assertNotRegExp('/Foo/', $client->getResponse()->getContent());
$this->assertDoesNotMatchRegularExpression('/Foo/', $client->getResponse()->getContent());
}
*/

View File

@ -66,7 +66,7 @@ final class EventTypeControllerTest extends WebTestCase
$crawler = $client->followRedirect();
// Check the entity has been delete on the list
$this->assertNotRegExp('/Foo/', $client->getResponse()->getContent());
$this->assertDoesNotMatchRegularExpression('/Foo/', $client->getResponse()->getContent());
}
*/

View File

@ -66,7 +66,7 @@ final class RoleControllerTest extends WebTestCase
$crawler = $client->followRedirect();
// Check the entity has been delete on the list
$this->assertNotRegExp('/Foo/', $client->getResponse()->getContent());
$this->assertDoesNotMatchRegularExpression('/Foo/', $client->getResponse()->getContent());
}
*/

View File

@ -66,7 +66,7 @@ final class StatusControllerTest extends WebTestCase
$crawler = $client->followRedirect();
// Check the entity has been delete on the list
$this->assertNotRegExp('/Foo/', $client->getResponse()->getContent());
$this->assertDoesNotMatchRegularExpression('/Foo/', $client->getResponse()->getContent());
}
*/

View File

@ -60,6 +60,8 @@ class Address
/**
* @var string|null
*
* used for the CEDEX information
*
* @ORM\Column(type="string", length=255, nullable=true)
* @Groups({"write"})
*/

View File

@ -6,8 +6,9 @@
v-model="value"
:placeholder="$t('select_address')"
:tag-placeholder="$t('create_address')"
:select-label="$t('press_enter_to_select')"
:select-label="$t('multiselect.select_label')"
:deselect-label="$t('create_address')"
:selected-label="$t('multiselect.selected_label')"
@search-change="listenInputSearch"
ref="addressSelector"
@select="selectAddress"

View File

@ -12,8 +12,9 @@
label="value"
:custom-label="transName"
:placeholder="$t('select_city')"
:select-label="$t('press_enter_to_select')"
:select-label="$t('multiselect.select_label')"
:deselect-label="$t('create_postal_code')"
:selected-label="$t('multiselect.selected_label')"
:taggable="true"
:multiple="false"
@tag="addPostcode"

View File

@ -5,12 +5,13 @@
id="countrySelect"
label="name"
track-by="id"
v-bind:custom-label="transName"
v-bind:placeholder="$t('select_country')"
v-bind:options="sortedCountries"
:custom-label="transName"
:placeholder="$t('select_country')"
:options="sortedCountries"
v-model="value"
:select-label="$t('press_enter_to_select')"
:deselect-label="$t('press_enter_to_remove')"
:select-label="$t('multiselect.select_label')"
:deselect-label="$t('multiselect.deselect_label')"
:selected-label="$t('multiselect.selected_label')"
@select="selectCountry">
</VueMultiselect>
</div>

View File

@ -10,7 +10,7 @@
<h4 class="h3">{{ $t('address_suggestions') }}</h4>
<div class="flex-table AddressSuggestionList">
<div v-for="a in context.suggestions" class="item-bloc">
<div v-for="(a, i) in context.suggestions" class="item-bloc" :key="`suggestions-${i}`">
<div class="float-button bottom">
<div class="box">
<div class="action">

View File

@ -1,7 +1,7 @@
import { multiSelectMessages } from 'ChillMainAssets/vuejs/_js/i18n'
const addressMessages = {
fr: {
press_enter_to_select: 'Appuyer sur Entrée pour sélectionner',
press_enter_to_remove: 'Appuyer sur Entrée pour désélectionner',
add_an_address_title: 'Créer une adresse',
edit_an_address_title: 'Modifier une adresse',
create_a_new_address: 'Créer une nouvelle adresse',
@ -48,6 +48,8 @@ const addressMessages = {
}
};
Object.assign(addressMessages.fr, multiSelectMessages.fr);
export {
addressMessages
};

View File

@ -2,21 +2,28 @@
<component :is="component" class="chill-entity entity-address my-3">
<component :is="component" class="address" :class="multiline">
<p v-if="address.text"
class="street">
{{ address.text }},
</p>
<p v-if="address.postcode"
class="postcode">
{{ address.postcode.code }} {{ address.postcode.name }}
</p>
<p v-if="address.country"
class="country">
{{ address.country.name.fr }}
</p>
<div v-if="isMultiline === true">
<p v-for="(l, i) in address.lines" :key="`line-${i}`">
{{ l }}
</p>
</div>
<div v-else>
<p v-if="address.text"
class="street">
{{ address.text }}
</p>
<p v-if="address.postcode"
class="postcode">
{{ address.postcode.code }} {{ address.postcode.name }}
</p>
<p v-if="address.country"
class="country">
{{ address.country.name.fr }}
</p>
</div>
</component>
<div v-if="isMultiline === true" class="address-more">
<!-- <div v-if="isMultiline === true" class="address-more">
<div v-if="address.floor">
<span class="floor">
<b>{{ $t('floor') }}</b>: {{ address.floor }}
@ -52,7 +59,7 @@
<b>{{ $t('distribution') }}</b>: {{ address.distribution }}
</span>
</div>
</div>
</div> -->
<div v-if="useDatePane === true" class="address-more">
<div v-if="address.validFrom">

View File

@ -84,3 +84,17 @@ const _createI18n = (appMessages) => {
};
export { _createI18n }
export const multiSelectMessages = {
fr: {
multiselect: {
placeholder: 'Choisir',
tag_placeholder: 'Créer un nouvel élément',
select_label: 'Appuyer sur "Entrée" pour sélectionner',
deselect_label: 'Appuyer sur "Entrée" pour désélectionner',
select_group_label: 'Appuyer sur "Entrée" pour sélectionner ce groupe',
deselect_group_label: 'Appuyer sur "Entrée" pour désélectionner ce groupe',
selected_label: 'Sélectionné'
}
}
};

View File

@ -9,57 +9,23 @@
* with_delimiter bool add a delimiter between fragments
* has_no_address bool
* multiline bool multiline display
* extended_infos bool add extra informations (step, floor, etc.)
* extended_infos bool add extra informations (step, floor, etc.) DEPRECATED
#}
{% macro raw(address, options, streetLine) %}
{% if address.street is not empty %}
<p>{{ streetLine }}</p>
{% endif %}
{% if options['extended_infos'] %}
{{ _self.extended(address, options) }}
{% endif %}
{% if address.postCode is not empty %}
<p class="postcode">
<span class="code">{{ address.postCode.code }}</span>
<span class="name">{{ address.postCode.name }}</span>
</p>
<p class="country">{{ address.postCode.country.name|localize_translatable_string }}</p>
{% endif %}
{% macro raw(lines) %}
{% for l in lines %}
<p>{{ l }}</p>
{% endfor %}
{% endmacro %}
{% macro extended(address, options) %}
{% if address.floor is not empty %}
<span class="floor">{{ 'address more.floor'|trans }} {{ address.floor }}</span>
{% endif %}
{% if address.corridor is not empty %}
<span class="corridor">{{ 'address more.corridor'|trans }} {{ address.corridor }}</span>
{% endif %}
{% if address.steps is not empty %}
<span class="steps">{{ 'address more.steps'|trans }} {{ address.steps }}</span>
{% endif %}
{% if address.buildingName is not empty %}
<span class="buildingName">{{ 'address more.buildingName'|trans }} {{ address.buildingName }}</span>
{% endif %}
{% if address.flat is not empty %}
<span class="flat">{{ 'address more.flat'|trans }} {{ address.flat }}</span>
{% endif %}
{% if address.extra is not empty %}
<span class="extra">{{ 'address more.extra'|trans }} {{ address.extra }}</span>
{% endif %}
{% if address.distribution is not empty %}
<span class="distribution">{{ 'address more.distribution'|trans }} {{ address.distribution }}</span>
{% endif %}
{% endmacro %}
{% macro inline(address, options, streetLine) %}
{% macro inline(address, options, streetLine, lines) %}
{% if options['has_no_address'] == true and address.isNoAddress == true %}
{% if address.postCode is not empty %}
<p class="postcode">
<span class="code">{{ address.postCode.code }}</span>
<span class="name">{{ address.postCode.name }}</span>
<span class="name">{{ address.distribution }}</span>
</p>
<p class="country">{{ address.postCode.country.name|localize_translatable_string }}</p>
{% endif %}
@ -68,7 +34,7 @@
</span>
{% else %}
<span class="address{% if options['multiline'] %} multiline{% endif %}{% if options['with_delimiter'] %} delimiter{% endif %}">
{{ _self.raw(address, options, streetLine) }}
{{ _self.raw(lines) }}
</span>
{% endif %}
{{ _self.validity(address, options) }}
@ -97,7 +63,7 @@
{% if options['with_picto'] %}
<i class="fa fa-li fa-map-marker"></i>
{% endif %}
{{ _self.inline(address, options, streetLine) }}
{{ _self.inline(address, options, streetLine, lines) }}
</li>
{%- endif -%}
@ -106,7 +72,7 @@
{% if options['with_picto'] %}
<i class="fa fa-fw fa-map-marker"></i>
{% endif %}
{{ _self.inline(address, options, streetLine) }}
{{ _self.inline(address, options, streetLine, lines) }}
</span>
{%- endif -%}
@ -118,20 +84,21 @@
<p class="postcode">
<span class="code">{{ address.postCode.code }}</span>
<span class="name">{{ address.postCode.name }}</span>
<span class="name">{{ address.distribution }}</span>
</p>
<p class="country">{{ address.postCode.country.name|localize_translatable_string }}</p>
</div>
</div>
{% endif %}
<div class="noaddress">
{{ 'address.consider homeless'|trans }}
</div>
{% else %}
<div class="address{% if options['multiline'] %} multiline{% endif %}{% if options['with_delimiter'] %} delimiter{% endif %}">
{% if options['with_picto'] %}
<i class="fa fa-fw fa-map-marker"></i>
{% endif %}
{{ _self.raw(address, options, streetLine) }}
{{ _self.raw(lines) }}
</div>
{% endif %}
{{ _self.validity(address, options) }}

View File

@ -13,6 +13,7 @@ namespace Chill\MainBundle\Serializer\Normalizer;
use Chill\DocGeneratorBundle\Serializer\Helper\NormalizeNullValueHelper;
use Chill\MainBundle\Entity\Address;
use Chill\MainBundle\Templating\Entity\AddressRender;
use DateTimeInterface;
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
@ -46,6 +47,13 @@ class AddressNormalizer implements ContextAwareNormalizerInterface, NormalizerAw
'validTo' => DateTimeInterface::class,
];
private AddressRender $addressRender;
public function __construct(AddressRender $addressRender)
{
$this->addressRender = $addressRender;
}
/**
* @param Address $address
* @param null|string $format
@ -53,19 +61,9 @@ class AddressNormalizer implements ContextAwareNormalizerInterface, NormalizerAw
public function normalize($address, $format = null, array $context = [])
{
if ($address instanceof Address) {
$text = $address->isNoAddress() ? '' : $address->getStreet() . ', ' . $address->getStreetNumber();
if (null !== $address->getPostCode()->getCountry()->getCountryCode()) {
if ($address->getPostCode()->getCountry()->getCountryCode() === 'FR') {
$text = $address->isNoAddress() ? '' : $address->getStreetNumber() . ', ' . $address->getStreet();
} else {
$text = $address->isNoAddress() ? '' : $address->getStreetNumber() . ', ' . $address->getStreet();
}
}
$data = [
'address_id' => $address->getId(),
'text' => $text,
'text' => $address->isNoAddress() ? null : $this->addressRender->renderStreetLine($address, []),
'street' => $address->getStreet(),
'streetNumber' => $address->getStreetNumber(),
'postcode' => [
@ -85,6 +83,7 @@ class AddressNormalizer implements ContextAwareNormalizerInterface, NormalizerAw
'buildingName' => $address->getBuildingName(),
'distribution' => $address->getDistribution(),
'extra' => $address->getExtra(),
'lines' => $this->addressRender->renderLines($address),
];
if ('json' === $format) {

View File

@ -12,6 +12,7 @@ declare(strict_types=1);
namespace Chill\MainBundle\Serializer\Normalizer;
use Chill\MainBundle\Entity\Center;
use Chill\MainBundle\Entity\Location;
use Chill\MainBundle\Entity\Scope;
use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Entity\UserJob;
@ -55,16 +56,21 @@ class UserNormalizer implements ContextAwareNormalizerInterface, NormalizerAware
$context,
['docgen:expects' => Center::class, 'groups' => 'docgen:read']
);
$locationContext = array_merge(
$context,
['docgen:expects' => Location::class, 'groups' => 'dogen:read']
);
if (null === $user && 'docgen' === $format) {
return array_merge(self::NULL_USER, [
'user_job' => $this->normalizer->normalize(null, $format, $userJobContext),
'main_center' => $this->normalizer->normalize(null, $format, $centerContext),
'main_scope' => $this->normalizer->normalize(null, $format, $scopeContext),
'current_location' => $this->normalizer->normalize(null, $format, $locationContext),
]);
}
return [
$data = [
'type' => 'user',
'id' => $user->getId(),
'username' => $user->getUsername(),
@ -75,6 +81,12 @@ class UserNormalizer implements ContextAwareNormalizerInterface, NormalizerAware
'main_center' => $this->normalizer->normalize($user->getMainCenter(), $format, $centerContext),
'main_scope' => $this->normalizer->normalize($user->getMainScope(), $format, $scopeContext),
];
if ('docgen' === $format) {
$data['current_location'] = $this->normalizer->normalize($user->getCurrentLocation(), $format, $locationContext);
}
return $data;
}
public function supportsNormalization($data, $format = null, array $context = []): bool

View File

@ -12,6 +12,7 @@ declare(strict_types=1);
namespace Chill\MainBundle\Templating\Entity;
use Chill\MainBundle\Entity\Address;
use Chill\MainBundle\Templating\TranslatableStringHelper;
use Symfony\Component\Templating\EngineInterface;
use function array_merge;
@ -26,14 +27,18 @@ class AddressRender implements ChillEntityRenderInterface
'with_delimiter' => false,
'has_no_address' => false,
'multiline' => true,
/* deprecated */
'extended_infos' => false,
];
private EngineInterface $templating;
public function __construct(EngineInterface $templating)
private TranslatableStringHelper $translatableStringHelper;
public function __construct(EngineInterface $templating, TranslatableStringHelper $translatableStringHelper)
{
$this->templating = $templating;
$this->translatableStringHelper = $translatableStringHelper;
}
/**
@ -50,43 +55,49 @@ class AddressRender implements ChillEntityRenderInterface
'streetLine' => $this->renderStreetLine($addr),
'render' => $options['render'] ?? 'bloc',
'options' => $options,
'lines' => $this->renderLines($addr),
]);
}
/**
* @param Address addr
* @param mixed $addr
*
* @return string[]
*/
public function renderString($addr, array $options): string
public function renderLines($addr): array
{
$lines = [];
$lines[0] = $this->renderStreetLine($addr);
if (!empty($addr->getPostcode())) {
$lines[1] = strtr('{postcode} {label}', [
'{postcode}' => $addr->getPostcode()->getCode(),
'{label}' => $addr->getPostcode()->getName(),
]);
if (null !== $addr->getPostCode()) {
if ($addr->getPostCode()->getCountry()->getCountryCode() === 'FR') {
$lines[] = $this->renderIntraBuildingLine($addr);
$lines[] = $this->renderBuildingLine($addr);
$lines[] = $this->renderStreetLine($addr);
$lines[] = $this->renderDeliveryLine($addr);
$lines[] = $this->renderCityLine($addr);
$lines[] = $this->renderCountryLine($addr);
} else {
$lines[] = $this->renderBuildingLine($addr);
$lines[] = $this->renderDeliveryLine($addr);
$lines[] = $this->renderStreetLine($addr);
$lines[] = $this->renderCityLine($addr);
$lines[] = $this->renderCountryLine($addr);
}
}
return implode(' - ', $lines);
return array_values(array_filter($lines, static fn ($l) => null !== $l));
}
public function supports($entity, array $options): bool
public function renderStreetLine(Address $addr): ?string
{
return $entity instanceof Address;
}
private function renderStreetLine($addr): string
{
if (!empty($addr->getStreet())) {
if (null !== $addr->getStreet() && $addr->getStreet() !== '') {
$street = $addr->getStreet();
} else {
$street = '';
}
if (!empty($addr->getStreetNumber())) {
if (null !== $addr->getStreetNumber() && $addr->getStreetNumber() !== '') {
$streetNumber = $addr->getStreetNumber();
} else {
$streetNumber = '';
@ -100,8 +111,111 @@ class AddressRender implements ChillEntityRenderInterface
}
}
if (',' === $res) {
$res = '';
if ((',' === $res) || ('' === $res)) {
$res = null;
}
return $res;
}
/**
* @param Address addr
* @param mixed $addr
*/
public function renderString($addr, array $options): string
{
return implode(' - ', $this->renderLines($addr));
}
public function supports($entity, array $options): bool
{
return $entity instanceof Address;
}
private function renderBuildingLine(Address $addr): ?string
{
if (null !== $addr->getBuildingName() && $addr->getBuildingName() !== '') {
$building = $addr->getBuildingName();
} else {
$building = '';
}
$intraBuilding = $this->renderIntraBuildingLine($addr);
if (null === $intraBuilding) {
$intraBuilding = '';
}
$res = trim($building . ' - ' . $intraBuilding, ' - ');
if ('' === $res) {
$res = null;
}
if (null !== $addr->getPostCode()->getCountry()->getCountryCode()) {
if ($addr->getPostCode()->getCountry()->getCountryCode() === 'FR') {
$res = $addr->getBuildingName();
}
}
return $res;
}
private function renderCityLine($addr): string
{
if (null !== $addr->getPostcode()) {
$res = strtr('{postcode} {label}', [
'{postcode}' => $addr->getPostcode()->getCode(),
'{label}' => $addr->getPostcode()->getName(),
]);
if (null !== $addr->getPostCode()->getCountry()->getCountryCode()) {
if ($addr->getPostCode()->getCountry()->getCountryCode() === 'FR') {
if ($addr->getDistribution()) {
$res = $res . ' ' . $addr->getDistribution();
}
}
}
}
return $res ?? '';
}
private function renderCountryLine($addr): ?string
{
return $this->translatableStringHelper->localize(
$addr->getPostCode()->getCountry()->getName()
);
}
private function renderDeliveryLine($addr): ?string
{
return $addr->getExtra();
}
private function renderIntraBuildingLine($addr): ?string
{
$arr = [];
if ($addr->getFlat()) {
$arr[] = 'appart ' . $addr->getFlat();
}
if ($addr->getFloor()) {
$arr[] = 'ét ' . $addr->getFloor();
}
if ($addr->getCorridor()) {
$arr[] = 'coul ' . $addr->getCorridor();
}
if ($addr->getSteps()) {
$arr[] = 'esc ' . $addr->getSteps();
}
$res = implode(' - ', $arr);
if ('' === $res) {
$res = null;
}
return $res;

View File

@ -140,8 +140,7 @@ abstract class AbstractAggregatorTest extends KernelTestCase
{
$filter = $this->getAggregator();
$this->assertInternalType(
'string',
$this->assertIsString(
$filter->applyOn(),
'test that the internal type of "applyOn" is a string'
);
@ -160,8 +159,7 @@ abstract class AbstractAggregatorTest extends KernelTestCase
{
$queryKeys = $this->getAggregator()->getQueryKeys($data);
$this->assertInternalType(
'array',
$this->assertIsArray(
$queryKeys,
'test that the query keys returned are an array'
);
@ -252,7 +250,7 @@ abstract class AbstractAggregatorTest extends KernelTestCase
{
$title = $this->getAggregator()->getTitle();
$this->assertInternalType('string', $title);
$this->assertIsString($title);
$this->assertNotEmpty(
$title,
'test that the title is not empty'

View File

@ -151,8 +151,7 @@ abstract class AbstractExportTest extends WebTestCase
{
$export = $this->getExport();
$this->assertInternalType(
'string',
$this->assertIsString(
$export->getDescription(),
'Assert that the `getDescription` method return a string'
);
@ -214,8 +213,7 @@ abstract class AbstractExportTest extends WebTestCase
$results = $this->getExport()->getResult($query, $data);
$this->assertInternalType(
'array',
$this->assertIsArray(
$results,
'assert that the returned result is an array'
);
@ -271,8 +269,7 @@ abstract class AbstractExportTest extends WebTestCase
{
$export = $this->getExport();
$this->assertInternalType(
'string',
$this->assertIsString(
$export->getType(),
'Assert that the `getType` method return a string'
);

View File

@ -126,7 +126,7 @@ abstract class AbstractFilterTest extends KernelTestCase
{
$filter = $this->getFilter();
$this->assertInternalType('string', $filter->applyOn());
$this->assertIsString($filter->applyOn());
}
/**
@ -149,8 +149,7 @@ abstract class AbstractFilterTest extends KernelTestCase
'test that the description is not empty'
);
} elseif (is_array($description)) {
$this->assertInternalType(
'string',
$this->assertIsString(
$description[0],
'test that the first element in the description array is a string'
);
@ -191,7 +190,7 @@ abstract class AbstractFilterTest extends KernelTestCase
{
$title = $this->getFilter()->getTitle();
$this->assertInternalType('string', $title);
$this->assertIsString($title);
$this->assertNotEmpty(
$title,
'test that the title is not empty'

View File

@ -72,6 +72,6 @@ final class CenterControllerTest extends WebTestCase
$crawler = $client->request('GET', '/fr/admin/center/');
// Check the entity has been delete on the list
$this->assertRegExp('/Foo/', $client->getResponse()->getContent());
$this->assertMatchesRegularExpression('/Foo/', $client->getResponse()->getContent());
}
}

View File

@ -40,7 +40,7 @@ final class LoginControllerTest extends WebTestCase
$this->assertTrue($client->getResponse()->isRedirect());
//the response is not a login page, but on a new page
$this->assertNotRegExp('/\/login$/', $client->getResponse()
$this->assertDoesNotMatchRegularExpression('/\/login$/', $client->getResponse()
->headers
->get('location'));
@ -48,7 +48,7 @@ final class LoginControllerTest extends WebTestCase
$client->followRedirects(true);
$crawler = $client->request('GET', '/');
$this->assertRegExp('/center a_social/', $client->getResponse()
$this->assertMatchesRegularExpression('/center a_social/', $client->getResponse()
->getContent());
$logoutLinkFilter = $crawler->filter('a:contains("Se déconnecter")');
@ -63,7 +63,7 @@ final class LoginControllerTest extends WebTestCase
$client->followRedirect(); //redirect to login page
//check we are back on login page
$this->assertRegExp('/\/login$/', $client->getResponse()
$this->assertMatchesRegularExpression('/\/login$/', $client->getResponse()
->headers
->get('location'));
}

View File

@ -66,7 +66,7 @@ final class PermissionsGroupControllerTest extends WebTestCase
$crawler = $client->followRedirect();
// Check the entity has been delete on the list
$this->assertNotRegExp('/Foo/', $client->getResponse()->getContent());
$this->assertDoesNotMatchRegularExpression('/Foo/', $client->getResponse()->getContent());
}
*/

View File

@ -388,7 +388,7 @@ final class ExportManagerTest extends KernelTestCase
public function testGetAggregatorNonExistant()
{
$this->expectException(\RuntimeException::class);
$this->expectException(RuntimeException::class);
$exportManager = $this->createExportManager();
@ -446,7 +446,7 @@ final class ExportManagerTest extends KernelTestCase
public function testGetExportNonExistant()
{
$this->expectException(\RuntimeException::class);
$this->expectException(RuntimeException::class);
$exportManager = $this->createExportManager();
@ -485,7 +485,7 @@ final class ExportManagerTest extends KernelTestCase
public function testGetFilterNonExistant()
{
$this->expectException(\RuntimeException::class);
$this->expectException(RuntimeException::class);
$exportManager = $this->createExportManager();
@ -646,7 +646,7 @@ final class ExportManagerTest extends KernelTestCase
public function testNonExistingFormatter()
{
$this->expectException(\RuntimeException::class);
$this->expectException(RuntimeException::class);
$exportManager = $this->createExportManager();
@ -668,10 +668,10 @@ final class ExportManagerTest extends KernelTestCase
?UserInterface $user = null
): ExportManager {
$localUser = $user ?? self::$container->get(
'doctrine.orm.entity_manager'
)
->getRepository('ChillMainBundle:User')
->findOneBy(['username' => 'center a_social']);
'doctrine.orm.entity_manager'
)
->getRepository('ChillMainBundle:User')
->findOneBy(['username' => 'center a_social']);
$token = new UsernamePasswordToken($localUser, 'password', 'provider');
$tokenStorage = new TokenStorage();
$tokenStorage->setToken($token);

View File

@ -16,6 +16,7 @@ use Chill\MainBundle\Security\PasswordRecover\TokenManager;
use DateInterval;
use DateTimeImmutable;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use UnexpectedValueException;
/**
* @internal
@ -47,7 +48,7 @@ final class TokenManagerTest extends KernelTestCase
$tokens = $tokenManager->generate($user, $expiration);
$this->assertInternalType('array', $tokens);
$this->assertIsArray($tokens);
$this->assertArrayHasKey('h', $tokens);
$this->assertArrayHasKey('t', $tokens);
$this->assertNotEmpty($tokens['h']);
@ -57,7 +58,7 @@ final class TokenManagerTest extends KernelTestCase
public function testGenerateEmptyUsernameCanonical()
{
$this->expectException(\UnexpectedValueException::class);
$this->expectException(UnexpectedValueException::class);
$tokenManager = $this->tokenManager;
// set a username, but not a username canonical

View File

@ -48,6 +48,6 @@ final class MenuComposerTest extends KernelTestCase
$routes = $this->menuComposer->getRoutesFor('dummy0');
$this->assertInternalType('array', $routes);
$this->assertIsArray($routes);
}
}

View File

@ -15,6 +15,7 @@ use Chill\MainBundle\Entity\Address;
use Chill\MainBundle\Entity\Country;
use Chill\MainBundle\Entity\PostalCode;
use Chill\MainBundle\Templating\Entity\AddressRender;
use Chill\MainBundle\Templating\TranslatableStringHelper;
use Iterator;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\Templating\EngineInterface;
@ -30,11 +31,11 @@ final class AddressRenderTest extends KernelTestCase
self::bootKernel();
}
public function addressDataProvider(): Iterator
public function addressDataProviderBEWithBuilding(): Iterator
{
$addr = new Address();
$country = (new Country())
->setName(['fr' => 'Pays'])
->setName(['fr' => 'Belgium'])
->setCountryCode('BE');
$postCode = new PostalCode();
$postCode->setName('Locality')
@ -45,20 +46,279 @@ final class AddressRenderTest extends KernelTestCase
->setStreetNumber('5')
->setPostcode($postCode);
yield [$addr, 'Rue ABC, 5 - 012345 Locality'];
$addr->setBuildingName('Résidence "Les Bleuets"');
yield [$addr, 'Résidence "Les Bleuets" - Rue ABC, 5 - 012345 Locality - Belgium'];
}
public function addressDataProviderBEWithSteps(): Iterator
{
$addr = new Address();
$country = (new Country())
->setName(['fr' => 'Belgium'])
->setCountryCode('BE');
$postCode = new PostalCode();
$postCode->setName('Locality')
->setCode('012345')
->setCountry($country);
$addr->setStreet('Rue ABC')
->setStreetNumber('5')
->setPostcode($postCode);
$addr->setSteps('4');
yield [$addr, 'esc 4 - Rue ABC, 5 - 012345 Locality - Belgium'];
}
public function addressDataProviderFRWithBuilding(): Iterator
{
$addr = new Address();
$country = (new Country())
->setName(['fr' => 'France'])
->setCountryCode('FR');
$postCode = new PostalCode();
$postCode->setName('Locality')
->setCode('012345')
->setCountry($country);
$addr->setStreet('Rue ABC')
->setStreetNumber('5')
->setPostcode($postCode);
$addr->setBuildingName('Résidence "Les Bleuets"');
yield [$addr, 'Résidence "Les Bleuets" - 5, Rue ABC - 012345 Locality - France'];
}
public function addressDataProviderFRWithSteps(): Iterator
{
$addr = new Address();
$country = (new Country())
->setName(['fr' => 'France'])
->setCountryCode('FR');
$postCode = new PostalCode();
$postCode->setName('Locality')
->setCode('012345')
->setCountry($country);
$addr->setStreet('Rue ABC')
->setStreetNumber('5')
->setPostcode($postCode);
$addr->setSteps('4');
yield [$addr, 'esc 4 - 5, Rue ABC - 012345 Locality - France'];
}
public function complexAddressDataProviderBE(): Iterator
{
$addr = new Address();
$country = (new Country())
->setName(['fr' => 'Belgium'])
->setCountryCode('BE');
$postCode = new PostalCode();
$postCode->setName('Locality')
->setCode('012345')
->setCountry($country);
$addr->setStreet('Rue ABC')
->setStreetNumber('5')
->setPostcode($postCode);
$addr->setBuildingName('Résidence "Les Bleuets"');
$addr->setFlat('1');
$addr->setFloor('2');
$addr->setCorridor('3');
$addr->setSteps('4');
yield [$addr, 'Résidence "Les Bleuets" - appart 1 - ét 2 - coul 3 - esc 4 - Rue ABC, 5 - 012345 Locality - Belgium'];
}
public function complexAddressDataProviderFR(): Iterator
{
$addr = new Address();
$country = (new Country())
->setName(['fr' => 'France'])
->setCountryCode('FR');
$postCode = new PostalCode();
$postCode->setName('Locality')
->setCode('012345')
->setCountry($country);
$addr->setStreet('Rue ABC')
->setStreetNumber('5')
->setPostcode($postCode);
$addr->setBuildingName('Résidence "Les Bleuets"');
$addr->setFlat('1');
$addr->setFloor('2');
$addr->setCorridor('3');
$addr->setSteps('4');
$addr->setExtra('A droite de la porte');
$addr->setDistribution('CEDEX');
yield [$addr, 'appart 1 - ét 2 - coul 3 - esc 4 - Résidence "Les Bleuets" - 5, Rue ABC - A droite de la porte - 012345 Locality CEDEX - France'];
}
public function noFullAddressDataProviderBE(): Iterator
{
$addr = new Address();
$country = (new Country())
->setName(['fr' => 'Belgium'])
->setCountryCode('BE');
$postCode = new PostalCode();
$postCode->setName('Locality')
->setCode('012345')
->setCountry($country);
$addr->setPostcode($postCode)
->setIsNoAddress(true);
yield [$addr, '012345 Locality - Belgium'];
}
public function simpleAddressDataProviderBE(): Iterator
{
$addr = new Address();
$country = (new Country())
->setName(['fr' => 'Belgium'])
->setCountryCode('BE');
$postCode = new PostalCode();
$postCode->setName('Locality')
->setCode('012345')
->setCountry($country);
$addr->setStreet('Rue ABC')
->setStreetNumber('5')
->setPostcode($postCode);
yield [$addr, 'Rue ABC, 5 - 012345 Locality - Belgium'];
}
public function simpleAddressDataProviderFR(): Iterator
{
$addr = new Address();
$country = (new Country())
->setName(['fr' => 'France'])
->setCountryCode('FR');
$postCode = new PostalCode();
$postCode->setName('Locality')
->setCode('012345')
->setCountry($country);
$addr->setStreet('Rue ABC')
->setStreetNumber('5')
->setPostcode($postCode);
yield [$addr, '5, Rue ABC - 012345 Locality - France'];
}
/**
* @dataProvider addressDataProvider
* @dataProvider complexAddressDataProviderBE
*/
public function testRenderString(Address $addr, string $expectedString): void
public function testRenderComplexAddressBE(Address $addr, string $expectedString): void
{
$engine = self::$container->get(EngineInterface::class);
$renderer = new AddressRender($engine);
$translatableStringHelper = self::$container->get(TranslatableStringHelper::class);
$renderer = new AddressRender($engine, $translatableStringHelper);
$this->assertEquals($expectedString, $renderer->renderString($addr, []));
}
return;
$this->assertIsString($renderer->renderBox($addr, []));
/**
* @dataProvider complexAddressDataProviderFR
*/
public function testRenderComplexAddressFR(Address $addr, string $expectedString): void
{
$engine = self::$container->get(EngineInterface::class);
$translatableStringHelper = self::$container->get(TranslatableStringHelper::class);
$renderer = new AddressRender($engine, $translatableStringHelper);
$this->assertEquals($expectedString, $renderer->renderString($addr, []));
}
/**
* @dataProvider noFullAddressDataProviderBE
*/
public function testRenderNoFullAddressBE(Address $addr, string $expectedString): void
{
$engine = self::$container->get(EngineInterface::class);
$translatableStringHelper = self::$container->get(TranslatableStringHelper::class);
$renderer = new AddressRender($engine, $translatableStringHelper);
$this->assertEquals($expectedString, $renderer->renderString($addr, []));
}
/**
* @dataProvider simpleAddressDataProviderBE
*/
public function testRenderStringSimpleAddressBE(Address $addr, string $expectedString): void
{
$engine = self::$container->get(EngineInterface::class);
$translatableStringHelper = self::$container->get(TranslatableStringHelper::class);
$renderer = new AddressRender($engine, $translatableStringHelper);
$this->assertEquals($expectedString, $renderer->renderString($addr, []));
}
/**
* @dataProvider simpleAddressDataProviderFR
*/
public function testRenderStringSimpleAddressFR(Address $addr, string $expectedString): void
{
$engine = self::$container->get(EngineInterface::class);
$translatableStringHelper = self::$container->get(TranslatableStringHelper::class);
$renderer = new AddressRender($engine, $translatableStringHelper);
$this->assertEquals($expectedString, $renderer->renderString($addr, []));
}
/**
* @dataProvider addressDataProviderBEWithBuilding
*/
public function testRenderWithBuildingAddressBE(Address $addr, string $expectedString): void
{
$engine = self::$container->get(EngineInterface::class);
$translatableStringHelper = self::$container->get(TranslatableStringHelper::class);
$renderer = new AddressRender($engine, $translatableStringHelper);
$this->assertEquals($expectedString, $renderer->renderString($addr, []));
}
/**
* @dataProvider addressDataProviderFRWithBuilding
*/
public function testRenderWithBuildingAddressFR(Address $addr, string $expectedString): void
{
$engine = self::$container->get(EngineInterface::class);
$translatableStringHelper = self::$container->get(TranslatableStringHelper::class);
$renderer = new AddressRender($engine, $translatableStringHelper);
$this->assertEquals($expectedString, $renderer->renderString($addr, []));
}
/**
* @dataProvider addressDataProviderBEWithSteps
*/
public function testRenderWithStepsAddressBE(Address $addr, string $expectedString): void
{
$engine = self::$container->get(EngineInterface::class);
$translatableStringHelper = self::$container->get(TranslatableStringHelper::class);
$renderer = new AddressRender($engine, $translatableStringHelper);
$this->assertEquals($expectedString, $renderer->renderString($addr, []));
}
/**
* @dataProvider addressDataProviderFRWithSteps
*/
public function testRenderWithStepsAddressFR(Address $addr, string $expectedString): void
{
$engine = self::$container->get(EngineInterface::class);
$translatableStringHelper = self::$container->get(TranslatableStringHelper::class);
$renderer = new AddressRender($engine, $translatableStringHelper);
$this->assertEquals($expectedString, $renderer->renderString($addr, []));
}
}

View File

@ -11,8 +11,6 @@ declare(strict_types=1);
namespace Chill\PersonBundle\Config;
use function count;
/**
* Give help to interact with the config for alt names.
*/
@ -69,6 +67,6 @@ class ConfigPersonAltNamesHelper
*/
public function hasAltNames(): bool
{
return count($this->config) > 0;
return [] !== $this->config;
}
}

View File

@ -19,6 +19,7 @@ use Chill\PersonBundle\Repository\AccompanyingPeriod\AccompanyingPeriodWorkRepos
use Chill\PersonBundle\Security\Authorization\AccompanyingPeriodVoter;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\HttpFoundation\Exception\BadRequestException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
@ -110,6 +111,60 @@ class AccompanyingCourseController extends Controller
]);
}
/**
* Delete page of Accompanying Course section.
*
* @Route("/{_locale}/parcours/{accompanying_period_id}/delete", name="chill_person_accompanying_course_delete")
* @ParamConverter("accompanyingCourse", options={"id": "accompanying_period_id"})
*/
public function deleteAction(Request $request, AccompanyingPeriod $accompanyingCourse)
{
$em = $this->getDoctrine()->getManager();
$person_id = $request->query->get('person_id');
$form = $this->createFormBuilder()
->setAction($this->generateUrl('chill_person_accompanying_course_delete', [
'accompanying_period_id' => $accompanyingCourse->getId(),
'person_id' => $person_id,
]))
->setMethod('DELETE')
->add('submit', SubmitType::class, ['label' => 'Delete'])
->getForm();
if ($request->getMethod() === Request::METHOD_DELETE) {
$form->handleRequest($request);
if ($form->isValid()) {
$em->remove($accompanyingCourse);
$em->flush();
$this->addFlash('success', $this->get('translator')
->trans('The accompanying course has been successfully removed.'));
if (null !== $person_id) {
return $this->redirectToRoute('chill_person_accompanying_period_list', [
'person_id' => $person_id,
]);
}
return $this->redirectToRoute('chill_main_homepage');
}
}
if (null !== $person_id) {
$view = '@ChillPerson/AccompanyingCourse/confirm_delete_person.html.twig';
} else {
$view = '@ChillPerson/AccompanyingCourse/confirm_delete_accompanying_course.html.twig';
}
return $this->render($view, [
'accompanyingCourse' => $accompanyingCourse,
'person_id' => $person_id,
'delete_form' => $form->createView(),
]);
}
/**
* Edit page of Accompanying Course section.
*
@ -208,6 +263,9 @@ class AccompanyingCourseController extends Controller
}
}
$userLocation = $this->getUser()->getCurrentLocation();
$period->setAdministrativeLocation($userLocation);
$this->denyAccessUnlessGranted(AccompanyingPeriodVoter::CREATE, $period);
$em->persist($period);

View File

@ -14,23 +14,52 @@ namespace Chill\PersonBundle\Controller;
use Chill\MainBundle\CRUD\Controller\ApiController;
use Chill\MainBundle\Entity\Address;
use Chill\MainBundle\Security\Authorization\AuthorizationHelper;
use Chill\PersonBundle\Config\ConfigPersonAltNamesHelper;
use Chill\PersonBundle\Entity\AccompanyingPeriodParticipation;
use Chill\PersonBundle\Entity\Person;
use Chill\PersonBundle\Security\Authorization\PersonVoter;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use function array_filter;
use function array_values;
use function in_array;
class PersonApiController extends ApiController
{
private AuthorizationHelper $authorizationHelper;
public function __construct(AuthorizationHelper $authorizationHelper)
{
private ConfigPersonAltNamesHelper $configPersonAltNameHelper;
public function __construct(
AuthorizationHelper $authorizationHelper,
ConfigPersonAltNamesHelper $configPersonAltNameHelper
) {
$this->authorizationHelper = $authorizationHelper;
$this->configPersonAltNameHelper = $configPersonAltNameHelper;
}
/**
* @Route("/api/1.0/person/config/alt_names.{_format}",
* name="chill_person_config_alt_names",
* requirements={
* "_format": "json"
* }
* )
*/
public function configAltNames(Request $request, string $_format): Response
{
$configAltNamesChoices = $this->configPersonAltNameHelper->getChoices();
return $this->json(
array_map(
static fn (array $data, string $key): array => ['key' => $key, 'labels' => $data],
$configAltNamesChoices,
array_keys($configAltNamesChoices)
),
Response::HTTP_OK,
[],
['groups' => ['read']]
);
}
public function personAddressApi($id, Request $request, string $_format): Response
@ -51,22 +80,51 @@ class PersonApiController extends ApiController
{
$this->denyAccessUnlessGranted(PersonVoter::SEE, $person);
$addresses = [];
$seenAddressIds = [];
// collect addresses from location in courses
foreach ($person->getAccompanyingPeriodParticipations() as $participation) {
if (null !== $participation->getAccompanyingPeriod()->getAddressLocation()) {
$a = $participation->getAccompanyingPeriod()->getAddressLocation();
$addresses[$a->getId()] = $a;
}
}
$addresses = $person
->getAccompanyingPeriodParticipations()
->filter(
static function (AccompanyingPeriodParticipation $accompanyingPeriodParticipation): bool {
return null !== $accompanyingPeriodParticipation->getAccompanyingPeriod()->getAddressLocation();
}
)
->map(
static function (AccompanyingPeriodParticipation $accompanyingPeriodParticipation): ?Address {
return $accompanyingPeriodParticipation->getAccompanyingPeriod()->getAddressLocation();
}
)
->filter(
// We remove potential null addresses.
static fn (?Address $address): bool => null !== $address
)
->filter(
static function (Address $address) use (&$seenAddressIds): bool {
$id = $address->getId();
if (in_array($id, $seenAddressIds, true)) {
return false;
}
$seenAddressIds[] = $id;
return true;
}
);
// remove the actual address
$actual = $person->getCurrentHouseholdAddress();
if (null !== $actual) {
$addresses = array_filter($addresses, static fn ($a) => $a !== $actual);
$addresses = $addresses->filter(static fn (Address $address): bool => $address !== $actual);
}
return $this->json(array_values($addresses), Response::HTTP_OK, [], ['groups' => ['read']]);
return $this->json(
$addresses->getValues(),
Response::HTTP_OK,
[],
['groups' => ['read']]
);
}
}

View File

@ -17,6 +17,7 @@ use Chill\MainBundle\Entity\Address;
use Chill\MainBundle\Entity\Center;
use Chill\MainBundle\Entity\HasCentersInterface;
use Chill\MainBundle\Entity\HasScopesInterface;
use Chill\MainBundle\Entity\Location;
use Chill\MainBundle\Entity\Scope;
use Chill\MainBundle\Entity\User;
use Chill\PersonBundle\Entity\AccompanyingPeriod\AccompanyingPeriodWork;
@ -118,6 +119,13 @@ class AccompanyingPeriod implements
*/
private ?Address $addressLocation = null;
/**
* @ORM\ManyToOne(targetEntity="Chill\MainBundle\Entity\Location")
* @Groups({"read", "write"})
* @Assert\NotBlank(groups={AccompanyingPeriod::STEP_CONFIRMED})
*/
private ?Location $administrativeLocation = null;
/**
* @var DateTime
*
@ -507,6 +515,11 @@ class AccompanyingPeriod implements
return $this->addressLocation;
}
public function getAdministrativeLocation(): ?Location
{
return $this->administrativeLocation;
}
/**
* Get a list of person which have an adresse available for a valid location.
*
@ -980,6 +993,13 @@ class AccompanyingPeriod implements
return $this;
}
public function setAdministrativeLocation(?Location $administrativeLocation): AccompanyingPeriod
{
$this->administrativeLocation = $administrativeLocation;
return $this;
}
/**
* Set closingDate.
*

View File

@ -39,32 +39,32 @@ class AccompanyingPeriodWorkGoal
/**
* @ORM\ManyToOne(targetEntity=Goal::class)
* @Serializer\Groups({"accompanying_period_work:edit"})
* @Serializer\Groups({"read"})
* @Serializer\Groups({"read", "docgen:read"})
*/
private $goal;
private ?Goal $goal = null;
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
* @Serializer\Groups({"read"})
* @Serializer\Groups({"read", "docgen:read"})
*/
private $id;
private ?int $id = null;
/**
* @ORM\Column(type="text")
* @Serializer\Groups({"accompanying_period_work:edit"})
* @Serializer\Groups({"read"})
*/
private $note;
private ?string $note = null;
/**
* @ORM\ManyToMany(targetEntity=Result::class, inversedBy="accompanyingPeriodWorkGoals")
* @ORM\JoinTable(name="chill_person_accompanying_period_work_goal_result")
* @Serializer\Groups({"accompanying_period_work:edit"})
* @Serializer\Groups({"read"})
* @Serializer\Groups({"read", "docgen:read"})
*/
private $results;
private Collection $results;
public function __construct()
{

View File

@ -12,6 +12,7 @@ declare(strict_types=1);
namespace Chill\PersonBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Annotation\Groups;
/**
* PersonAltName.
@ -34,6 +35,7 @@ class PersonAltName
* @var string
*
* @ORM\Column(name="key", type="string", length=255)
* @Groups({"write"})
*/
private $key;
@ -41,6 +43,7 @@ class PersonAltName
* @var string
*
* @ORM\Column(name="label", type="text")
* @Groups({"write"})
*/
private $label;

View File

@ -28,7 +28,7 @@ class Relation
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
* @Serializer\Groups({"read"})
* @Serializer\Groups({"read", "docgen:read"})
*/
private ?int $id = null;

View File

@ -254,3 +254,24 @@ abbr.referrer { // still used ?
border: 1px solid black;
padding: 10px;
}
/// Masonry blocs on AccompanyingCourse resume page
div#dashboards {
div.mbloc {
& > div:not(.warnings) {
border: 1px solid $chill-light-gray;
background-color: $chill-llight-gray;
border-radius: 0.35rem;
padding: 1rem;
}
& > div.warnings .alert {
margin-bottom: 0;
}
blockquote.chill-user-quote {
margin: -1.2em;
p {
margin: 0;
}
}
}
}

View File

@ -8,6 +8,7 @@
<persons-associated></persons-associated>
<course-location></course-location>
<origin-demand></origin-demand>
<admin-location></admin-location>
<requestor v-bind:isAnonymous="accompanyingCourse.requestorAnonymous"></requestor>
<social-issue></social-issue>
<scopes></scopes>
@ -28,6 +29,7 @@ import { mapGetters, mapState } from 'vuex'
import Banner from './components/Banner.vue';
import StickyNav from './components/StickyNav.vue';
import OriginDemand from './components/OriginDemand.vue';
import AdminLocation from './components/AdminLocation.vue';
import PersonsAssociated from './components/PersonsAssociated.vue';
import Requestor from './components/Requestor.vue';
import SocialIssue from './components/SocialIssue.vue';
@ -44,6 +46,7 @@ export default {
Banner,
StickyNav,
OriginDemand,
AdminLocation,
PersonsAssociated,
Requestor,
SocialIssue,

View File

@ -0,0 +1,103 @@
<template>
<div class="vue-component">
<h2><a id="section-40"></a>{{ $t('admin_location.title') }}</h2>
<div class="mb-4">
<label for="selectAdminLocation">
{{ $t('admin_location.title') }}
</label>
<VueMultiselect
name="selectAdminLocation"
label="text"
:custom-label="customLabel"
track-by="id"
:multiple="false"
:searchable="true"
:placeholder="$t('admin_location.placeholder')"
v-model="value"
:options="options"
group-values="locations"
group-label="locationCategories"
@select="updateAdminLocation">
</VueMultiselect>
</div>
<div v-if="!isAdminLocationValid" class="alert alert-warning to-confirm">
{{ $t('admin_location.not_valid') }}
</div>
</div>
</template>
<script>
import VueMultiselect from 'vue-multiselect';
import { makeFetch } from 'ChillMainAssets/lib/api/apiMethods';
import { mapState, mapGetters } from 'vuex';
export default {
name: 'AdminLocation',
components: { VueMultiselect },
data() {
return {
options: []
}
},
computed: {
...mapState({
value: state => state.accompanyingCourse.administrativeLocation,
}),
...mapGetters([
'isAdminLocationValid'
])
},
mounted() {
this.getOptions();
},
methods: {
getOptions() {
const url = `/api/1.0/main/location.json`;
makeFetch('GET', url)
.then(response => {
let options = response.results;
let uniqueLocationTypeId = [...new Set(options.map(o => o.locationType.id))];
let results = [];
for (let id of uniqueLocationTypeId) {
results.push({
locationCategories: options.filter(o => o.locationType.id === id)[0].locationType.title.fr,
locations: options.filter(o => o.locationType.id === id)
})
}
this.options = results;
return response;
})
.catch((error) => {
this.$toast.open({message: error.txt})
})
},
updateAdminLocation(value) {
this.$store.dispatch('updateAdminLocation', value)
.catch(({name, violations}) => {
if (name === 'ValidationException' || name === 'AccessException') {
violations.forEach((violation) => this.$toast.open({message: violation}));
} else {
this.$toast.open({message: 'An error occurred'})
}
});
},
customLabel(value) {
return value.locationType
? value.name
? `${value.name} (${value.locationType.title.fr})`
: value.locationType.title.fr
: '';
},
}
}
</script>
<style src="vue-multiselect/dist/vue-multiselect.css"></style>
<style lang="css" scoped>
label {
display: none;
}
</style>

View File

@ -1,9 +1,9 @@
<template>
<span v-for="h in personsByHousehold()" :class="{ 'household': householdExists(h.id), 'no-household': !householdExists(h.id) }">
<span v-for="h in personsByHousehold()" :class="{ 'household': householdExists(h.id), 'no-household': !householdExists(h.id) }" :key="h.id">
<a v-if="householdExists(h.id)" :href="householdLink(h.id)">
<i class="fa fa-home fa-fw text-light" :title="$t('persons_associated.show_household_number', { id: h.id })"></i>
</a>
<span v-for="person in h.persons" class="me-1">
<span v-for="person in h.persons" class="me-1" :key="person.id">
<on-the-fly :type="person.type" :id="person.id" :buttonText="person.text" :displayBadge="'true' === 'true'" action="show"></on-the-fly>
</span>
</span>

View File

@ -1,6 +1,6 @@
<template>
<div class="vue-component">
<h2><a id="section-90"></a>{{ $t('comment.title') }}</h2>
<h2><a id="section-100"></a>{{ $t('comment.title') }}</h2>
<!--div class="error flash_message" v-if="errors.length > 0">
{{ errors[0] }}

View File

@ -1,6 +1,6 @@
<template>
<div class="vue-component">
<h2><a id="section-100"></a>
<h2><a id="section-110"></a>
{{ $t('confirm.title') }}
</h2>
<div>
@ -24,6 +24,11 @@
{{ $t('confirm.ok') }}
</button>
</li>
<li>
<a class="btn btn-delete" :href="deleteLink">
{{ $t('confirm.delete') }}
</a>
</li>
</ul>
</div>
@ -37,6 +42,11 @@
{{ $t('confirm.ok') }}
</button>
</li>
<li>
<a class="btn btn-delete" :href="deleteLink">
{{ $t('confirm.delete') }}
</a>
</li>
</ul>
</div>
@ -89,13 +99,17 @@ export default {
msg: 'confirm.origin_not_valid',
anchor: '#section-30'
},
adminLocation: {
msg: 'confirm.adminLocation_not_valid',
anchor: '#section-40'
},
socialIssue: {
msg: 'confirm.socialIssue_not_valid',
anchor: '#section-50'
anchor: '#section-60'
},
scopes: {
msg: 'confirm.set_a_scope',
anchor: '#section-60'
anchor: '#section-70'
}
}
}
@ -108,10 +122,14 @@ export default {
'isParticipationValid',
'isSocialIssueValid',
'isOriginValid',
'isAdminLocationValid',
'isLocationValid',
'validationKeys',
'isValidToBeConfirmed'
])
]),
deleteLink() {
return `/fr/parcours/${this.accompanyingCourse.id}/delete`; //TODO locale
},
},
methods: {
confirmCourse() {

View File

@ -4,7 +4,7 @@
{{ $t('courselocation.title') }}
</h2>
<div v-for="error in displayErrors" class="alert alert-danger my-2">
<div v-for="error in displayErrors" class="alert alert-danger my-2" :key="error">
{{ error }}
</div>

View File

@ -4,7 +4,7 @@
<div class="mb-4">
<label for="selectOrigin">
{{ $t('origin.label.fr') }}
{{ $t('origin.title') }}
</label>
<VueMultiselect
@ -17,6 +17,9 @@
:placeholder="$t('origin.placeholder')"
v-model="value"
:options="options"
:select-label="$t('multiselect.select_label')"
:deselect-label="$t('multiselect.deselect_label')"
:selected-label="$t('multiselect.selected_label')"
@select="updateOrigin">
</VueMultiselect>
</div>

View File

@ -1,6 +1,6 @@
<template>
<div class="vue-component">
<h2><a id="section-70"></a>{{ $t('referrer.title') }}</h2>
<h2><a id="section-80"></a>{{ $t('referrer.title') }}</h2>
<div>
<label class="col-form-label" for="selectReferrer">
@ -11,17 +11,20 @@
name="selectReferrer"
label="text"
track-by="id"
v-bind:multiple="false"
v-bind:searchable="true"
v-bind:placeholder="$t('referrer.placeholder')"
:multiple="false"
:searchable="true"
:placeholder="$t('referrer.placeholder')"
v-model="value"
v-bind:options="users"
:select-label="$t('multiselect.select_label')"
:deselect-label="$t('multiselect.deselect_label')"
:selected-label="$t('multiselect.selected_label')"
@select="updateReferrer">
</VueMultiselect>
<template v-if="referrersSuggested.length > 0">
<ul class="list-suggest add-items inline">
<li v-for="u in referrersSuggested" @click="updateReferrer(u)">
<li v-for="(u, i) in referrersSuggested" @click="updateReferrer(u)" :key="`referrer-${i}`">
<span>
<user-render-box-badge :user="u"></user-render-box-badge>
</span>

View File

@ -1,7 +1,7 @@
<template>
<div class="vue-component">
<h2><a id="section-40"></a>{{ $t('requestor.title') }}</h2>
<h2><a id="section-50"></a>{{ $t('requestor.title') }}</h2>
<div v-if="accompanyingCourse.requestor && isAnonymous" class="flex-table">

View File

@ -1,7 +1,7 @@
<template>
<div class="vue-component">
<h2><a id="section-80"></a>{{ $t('resources.title')}}</h2>
<h2><a id="section-90"></a>{{ $t('resources.title')}}</h2>
<div v-if="resources.length > 0">
<label class="col-form-label">{{ $tc('resources.counter', counter) }}</label>

View File

@ -1,6 +1,6 @@
<template>
<div class="vue-component">
<h2><a id="section-60"></a>{{ $t('scopes.title') }}</h2>
<h2><a id="section-70"></a>{{ $t('scopes.title') }}</h2>
<div class="mb-4">
<div class="form-check" v-for="s in scopes" :key="s.id">

View File

@ -1,6 +1,6 @@
<template>
<div class="vue-component">
<h2><a id="section-50"></a>{{ $t('social_issue.title') }}</h2>
<h2><a id="section-60"></a>{{ $t('social_issue.title') }}</h2>
<div class="my-4">
<!--label for="field">{{ $t('social_issue.label') }}</label

View File

@ -37,6 +37,12 @@ const appMessages = {
placeholder: "Renseignez l'origine de la demande",
not_valid: "Indiquez une origine à la demande",
},
admin_location: {
title: "Localisation administrative",
label: "Localisation administrative",
placeholder: "Renseignez la localisation administrative",
not_valid: "Indiquez une localisation administrative",
},
persons_associated: {
title: "Usagers concernés",
counter: "Il n'y a pas encore d'usagers | 1 usager | {count} usagers",
@ -127,10 +133,12 @@ const appMessages = {
socialIssue_not_valid: "sélectionnez au minimum une problématique sociale",
location_not_valid: "indiquez au minimum une localisation temporaire du parcours",
origin_not_valid: "Indiquez une origine à la demande",
adminLocation_not_valid: "Indiquez une localisation administrative à la demande",
set_a_scope: "indiquez au moins un service",
sure: "Êtes-vous sûr ?",
sure_description: "Une fois le changement confirmé, il ne sera plus possible de le remettre à l'état de brouillon !",
ok: "Confirmer le parcours"
ok: "Confirmer le parcours",
delete: "Supprimer le parcours"
},
// catch errors
'Error while updating AccompanyingPeriod Course.': "Erreur du serveur lors de la mise à jour du parcours d'accompagnement.",

View File

@ -49,6 +49,9 @@ let initPromise = Promise.all([scopesPromise, accompanyingCoursePromise])
isOriginValid(state) {
return state.accompanyingCourse.origin !== null;
},
isAdminLocationValid(state) {
return state.accompanyingCourse.administrativeLocation !== null;
},
isLocationValid(state) {
return state.accompanyingCourse.location !== null;
},
@ -62,6 +65,7 @@ let initPromise = Promise.all([scopesPromise, accompanyingCoursePromise])
if (!getters.isLocationValid) { keys.push('location'); }
if (!getters.isSocialIssueValid) { keys.push('socialIssue'); }
if (!getters.isOriginValid) { keys.push('origin'); }
if (!getters.isAdminLocationValid) { keys.push('adminLocation'); }
if (!getters.isScopeValid) { keys.push('scopes'); }
//console.log('getter keys', keys);
return keys;
@ -177,6 +181,9 @@ let initPromise = Promise.all([scopesPromise, accompanyingCoursePromise])
//console.log('value', value);
state.accompanyingCourse.origin = value;
},
updateAdminLocation(state, value) {
state.accompanyingCourse.administrativeLocation = value;
},
updateReferrer(state, value) {
//console.log('value', value);
state.accompanyingCourse.user = value;
@ -624,6 +631,19 @@ let initPromise = Promise.all([scopesPromise, accompanyingCoursePromise])
throw error;
})
},
updateAdminLocation({ commit }, payload) {
const url = `/api/1.0/person/accompanying-course/${id}.json`
const body = { type: "accompanying_period", administrativeLocation: { id: payload.id, type: payload.type }}
return makeFetch('PATCH', url, body)
.then((response) => {
commit('updateAdminLocation', response.administrativeLocation);
})
.catch((error) => {
commit('catchError', error);
throw error;
})
},
updateReferrer({ commit }, payload) {
const url = `/api/1.0/person/accompanying-course/${id}.json`
const body = { type: "accompanying_period", user: { id: payload.id, type: payload.type }}

View File

@ -7,7 +7,7 @@
<div id="picking">
<p>{{ $t('pick_social_issue_linked_with_action') }}</p>
<div v-for="si in socialIssues">
<div v-for="si in socialIssues" :key="si.id">
<input type="radio" v-bind:value="si.id" name="socialIssue" v-model="socialIssuePicked"><span class="badge bg-chill-l-gray text-dark">{{ si.text }}</span>
</div>
<div class="my-3">

View File

@ -2,6 +2,7 @@
<ol class="breadcrumb">
<li
v-for="s in steps"
:key="s"
class="breadcrumb-item" :class="{ active: step === s }"
>
{{ $t('household_members_editor.app.steps.'+s) }}

View File

@ -33,7 +33,7 @@ const fetchHouseholdSuggestionByAccompanyingPeriod = (personId) => {
throw Error ({m: 'Error while fetching household suggestion', status: response.status});
}).then(data => Promise.resolve(data.results))
.catch(e => console.err(e));
.catch(e => console.error(e));
;
};

View File

@ -9,7 +9,7 @@
<div v-else>
<p>
{{ $t('household_members_editor.concerned.persons_will_be_moved') }}&nbsp;:
<span v-for="c in concerned">
<span v-for="c in concerned" :key="c.person.id">
<person-render-box render="badge" :options="{addLink: false}" :person="c.person"></person-render-box>
<button class="btn" @click="removePerson(c.person)" v-if="c.allowRemove" style="padding-left:0;">
<span class="fa-stack fa-lg" :title="$t('household_members_editor.concerned.remove_concerned')">
@ -19,6 +19,17 @@
</button>
</span>
</p>
<div class="alert alert-info" v-if="concernedPersonsWithHouseholds.length > 0">
<p>{{ $t('household_members_editor.concerned.persons_with_household') }}</p>
<ul v-for="c in concernedPersonsWithHouseholds" :key="c.person.id">
<li>
{{ c.person.text }}
{{ $t('household_members_editor.concerned.already_belongs_to_household') }}
<a target="_blank" :href="this.makeHouseholdLink(c.person.current_household_id)">{{c.person.current_household_id}}</a>.
</li>
</ul>
</div>
</div>
<ul class="record_actions">
@ -59,7 +70,7 @@ export default {
},
computed: {
...mapState([
'concerned'
'concerned', 'household'
]),
...mapGetters([
'persons',
@ -67,6 +78,15 @@ export default {
noPerson () {
return this.$store.getters.persons.length === 0;
},
concernedPersonsWithHouseholds () {
if (this.$store.state.household) {
return this.$store.state.concerned.filter(c =>
c.person.current_household_id !== null && c.person.current_household_id !== this.$store.state.household.id
)
} else {
return [];
}
}
},
data() {
return {
@ -92,6 +112,9 @@ export default {
console.log('remove person in concerned', person);
this.$store.dispatch('removePerson', person);
},
makeHouseholdLink(id) {
return `/fr/person/household/${id}/summary`
}
}
}
</script>

View File

@ -8,10 +8,10 @@
</p>
<ul>
<li v-for="(msg, index) in warnings" class="warning">
<li v-for="(msg, i) in warnings" class="warning" :key="i">
{{ $t(msg.m, msg.a) }}
</li>
<li v-for="msg in errors" class="error">
<li v-for="(msg, i) in errors" class="error" :key="i">
{{ msg }}
</li>
</ul>

View File

@ -39,7 +39,7 @@
aria-labelledby="heading_household_suggestions" data-bs-parent="#householdSuggestions">
<div v-if="showHouseholdSuggestion">
<div class="flex-table householdSuggestionList">
<div v-for="s in getSuggestions" class="item-bloc">
<div v-for="(s, i) in getSuggestions" class="item-bloc" :key="`householdSuggestions-${i}`">
<household-render-box :household="s.household"></household-render-box>
<ul class="record_actions">
<li>

View File

@ -2,11 +2,11 @@
<current-household></current-household>
<ul class="record_actions">
<li v-if="!hasHouseholdAddress && !isHouseholdForceAddress">
<!-- <li v-if="!hasHouseholdAddress && !isHouseholdForceAddress">
<button class="btn btn-misc" @click="markNoAddress">
{{ $t('household_members_editor.household_address.mark_no_address') }}
</button>
</li>
</li> -->
<li v-if="!hasHouseholdAddress">
<add-address
:context="getAddressContext"

View File

@ -24,7 +24,8 @@
</button>
</div>
<div
v-for="position in positions"
v-for="(position, i) in positions"
:key="`position-${i}`"
class="position"
>
<button

View File

@ -1,3 +1,4 @@
import { personMessages } from 'ChillPersonAssets/vuejs/_js/i18n';
import { ontheflyMessages } from 'ChillMainAssets/vuejs/OnTheFly/i18n';
import { addressMessages } from 'ChillMainAssets/vuejs/Address/i18n';
@ -35,7 +36,7 @@ const appMessages = {
create_new_address: "Créer une nouvelle adresse",
},
concerned: {
title: "Usagers déplacés",
title: "Usager(s) à (re)positionner dans un ménage",
persons_will_be_moved: "Les usagers suivants vont être déplacés",
add_at_least_onePerson: "Indiquez au moins un usager à déplacer",
remove_concerned: "Ne plus transférer",
@ -45,6 +46,8 @@ const appMessages = {
move_to: "Déplacer vers",
persons_leaving: "Usagers quittant leurs ménages",
no_person_in_position: "Aucun usager ne sera ajouté à cette position",
persons_with_household: "Les usagers suivants sont associés à ces ménages:",
already_belongs_to_household: "est associé au ménage"
},
positioning: {
persons_to_positionnate: 'Usagers à positionner',

View File

@ -224,18 +224,21 @@ const store = createStore({
}
state.concerned.forEach((c, index) => {
let m = {
id: index * -1,
person: c.person,
holder: c.holder,
position: c.position,
};
if (c.position === null) {
m.position = {
ordering: 999999
if (!(h.members.map((m) => m.person.id)).includes(c.person.id)) {
let m = {
id: index * -1,
person: c.person,
holder: c.holder,
position: c.position,
};
if (c.position === null) {
m.position = {
ordering: 999999
}
}
h.new_members.push(m);
}
h.new_members.push(m);
})
console.log('fake household', h);
@ -307,7 +310,7 @@ const store = createStore({
comment: "",
});
} else {
console.err("person already included");
console.error("person already included");
}
},
markPosition(state, { person_id, position_id}) {
@ -533,10 +536,14 @@ const store = createStore({
// nothing to do anymore here, bye-bye !
let params = new URLSearchParams(window.location.search);
if (params.has('returnPath')) {
window.location.replace(params.get('returnPath'));
} else {
if (params.has('followAfter')) {
window.location.replace(`/fr/person/household/${household_id}/summary`);
} else {
if (params.has('returnPath')) {
window.location.replace(params.get('returnPath'));
} else {
window.location.replace(`/fr/person/household/${household_id}/summary`);
}
}
} else {
// we assume the answer was 422...

View File

@ -23,7 +23,7 @@
<div class="my-4 legend">
<h3>{{ $t('visgraph.Legend') }}</h3>
<div class="list-group">
<label class="list-group-item" v-for="layer in legendLayers">
<label class="list-group-item" v-for="(layer, i) in legendLayers" :key="`layer-${i}`">
<input
class="form-check-input me-1"
type="checkbox"

View File

@ -10,6 +10,13 @@ const getPerson = (id) => {
});
};
const getPersonAltNames = () =>
fetch('/api/1.0/person/config/alt_names.json').then(response => {
if (response.ok) { return response.json(); }
throw Error('Error with request resource response');
});;
/*
* POST a new person
*/
@ -48,6 +55,7 @@ const patchPerson = (id, body) => {
export {
getPerson,
getPersonAltNames,
postPerson,
patchPerson
};

View File

@ -21,14 +21,19 @@
<div v-else-if="action === 'edit' || action === 'create'">
<div class="form-floating mb-3">
<input class="form-control form-control-lg" id="lastname" v-model="lastName" v-bind:placeholder="$t('person.lastname')" />
<label for="lastname">{{ $t('person.lastname') }}</label>
</div>
<div class="form-floating mb-3">
<input class="form-control form-control-lg" id="firstname" v-model="firstName" v-bind:placeholder="$t('person.firstname')" />
<label for="firstname">{{ $t('person.firstname') }}</label>
</div>
<div class="form-floating mb-3">
<input class="form-control form-control-lg" id="lastname" v-model="lastName" v-bind:placeholder="$t('person.lastname')" />
<label for="lastname">{{ $t('person.lastname') }}</label>
<div v-for="(a) in config.altNames" :key="a.key" class="form-floating mb-3">
<input class="form-control form-control-lg" :id="a.key" @input="onAltNameInput" />
<label :for="a.key">{{ a.labels.fr }}</label>
</div>
<!-- TODO fix placeholder if undefined
@ -71,11 +76,20 @@
aria-describedby="mobilenumber" />
</div>
<div class="input-group mb-3">
<span class="input-group-text" id="email"><i class="fa fa-fw fa-at"></i></span>
<input class="form-control form-control-lg"
v-model="email"
v-bind:placeholder="$t('person.email')"
v-bind:aria-label="$t('person.email')"
aria-describedby="email" />
</div>
</div>
</template>
<script>
import { getPerson } from '../../_api/OnTheFly';
import { getPerson, getPersonAltNames } from '../../_api/OnTheFly';
import PersonRenderBox from '../Entity/PersonRenderBox.vue';
export default {
@ -88,13 +102,19 @@ export default {
data() {
return {
person: {
type: 'person'
}
type: 'person',
altNames: []
},
config: {
altNames: []
},
}
},
computed: {
firstName: {
set(value) { this.person.firstName = value; },
set(value) {
this.person.firstName = value;
},
get() { return this.person.firstName; }
},
lastName: {
@ -125,6 +145,10 @@ export default {
set(value) { this.person.mobilenumber = value; },
get() { return this.person.mobilenumber; }
},
email: {
set(value) { this.person.email = value; },
get() { return this.person.email; }
},
genderClass() {
switch (this.person.gender) {
case 'woman':
@ -150,6 +174,10 @@ export default {
}
},
mounted() {
getPersonAltNames()
.then(altNames => {
this.config.altNames = altNames;
});
if (this.action !== 'create') {
this.loadData();
}
@ -162,7 +190,16 @@ export default {
console.log('get person', this.person);
resolve();
}));
}
},
onAltNameInput(event) {
const key = event.target.id;
const label = event.target.value;
let updateAltNames = this.person.altNames.filter((a) => a.key !== key);
updateAltNames.push(
{'key': key, 'label': label}
)
this.person.altNames = updateAltNames;
},
}
}
</script>

View File

@ -30,6 +30,7 @@ const personMessages = {
phonenumber: "Téléphone",
mobilenumber: "Mobile",
altnames: "Autres noms",
email: "Courriel",
gender: {
title: "Genre",
placeholder: "Choisissez le genre de l'usager",

View File

@ -0,0 +1,31 @@
{% macro insert_onthefly(type, entity) %}
{% include '@ChillMain/OnTheFly/_insert_vue_onthefly.html.twig' with {
action: 'show', displayBadge: true,
targetEntity: { name: type, id: entity.id },
buttonText: entity|chill_entity_render_string
} %}
{% endmacro %}
<div>
{% if accompanyingCourse.participations is not empty %}
<div class="col mb-4">
<h4 class="item-key">{{ 'Persons associated'|trans }}</h4>
{% for r in accompanyingCourse.participations %}
{{ _self.insert_onthefly('person', r.person) }}
{% endfor %}
</div>
{% endif %}
{% if accompanyingCourse.socialIssues is not empty %}
<div class="col mb-4">
<h4 class="item-key">{{ 'Social issues'|trans }}</h4>
{% for s in accompanyingCourse.socialIssues %}
{{ s|chill_entity_render_box }}
{% endfor %}
</div>
{% endif %}
</div>

View File

@ -0,0 +1,18 @@
{% extends '@ChillPerson/AccompanyingCourse/layout.html.twig' %}
{% block title %}{{ 'Delete accompanying period'|trans }}{% endblock %}
{% block content %}
{% include '@ChillPerson/AccompanyingCourse/_confirm_delete.html.twig' %}
{{ include('@ChillMain/Util/confirmation_template.html.twig',
{
'title' : 'Delete accompanying period'|trans,
'confirm_question' : 'Are you sure you want to remove the accompanying period "%id%" ?'|trans({ '%id%' : accompanyingCourse.id } ),
'cancel_route' : 'chill_person_accompanying_course_edit',
'cancel_parameters' : {'accompanying_period_id' : accompanyingCourse.id},
'form' : delete_form
} ) }}
{% endblock %}

View File

@ -0,0 +1,18 @@
{% extends '@ChillPerson/AccompanyingCourse/layout.html.twig' %}
{% block title %}{{ 'Delete accompanying period'|trans }}{% endblock %}
{% block content %}
{% include '@ChillPerson/AccompanyingCourse/_confirm_delete.html.twig' %}
{{ include('@ChillMain/Util/confirmation_template.html.twig',
{
'title' : 'Delete accompanying period'|trans,
'confirm_question' : 'Are you sure you want to remove the accompanying period "%id%" ?'|trans({ '%id%' : accompanyingCourse.id } ),
'cancel_route' : 'chill_person_accompanying_period_list',
'cancel_parameters' : {'person_id' : person_id},
'form' : delete_form
} ) }}
{% endblock %}

View File

@ -21,104 +21,143 @@
{% block content %}
<div class="accompanyingcourse-resume">
<div id="dashboards" class="row" data-masonry='{"percentPosition": true }'>
<div id="dashboards" class="row g-3" data-masonry='{"percentPosition": true }'>
{% if 'DRAFT' == accompanyingCourse.step %}
<div class="col-4 warnings mb-4">
{% include '@ChillPerson/AccompanyingCourse/_still_draft.html.twig' %}
<div class="mbloc col col-sm-6 col-lg-4">
<div class="warnings">
{% include '@ChillPerson/AccompanyingCourse/_still_draft.html.twig' %}
</div>
</div>
{% endif %}
{% if 'DRAFT' != accompanyingCourse.step %}
{% if withoutHousehold|length > 0 %}
<div class="col-4 warnings mb-4">
{% include '@ChillPerson/AccompanyingCourse/_join_household.html.twig' %}
<div class="mbloc col col-sm-6 col-lg-4">
<div class="warnings">
{% include '@ChillPerson/AccompanyingCourse/_join_household.html.twig' %}
</div>
</div>
{% endif %}
{% endif %}
{% if accompanyingCourse.locationStatus == 'address'
or accompanyingCourse.locationStatus == 'none' %}
<div class="col-4 warnings mb-4">
{% include '@ChillPerson/AccompanyingCourse/_warning_address.html.twig' %}
<div class="mbloc col col-sm-6 col-lg-4">
<div class="warnings">
{% include '@ChillPerson/AccompanyingCourse/_warning_address.html.twig' %}
</div>
</div>
{% endif %}
<div class="col col-sm-6 col-lg-4 location mb-4">
{% if accompanyingCourse.locationStatus == 'person' %}
<h2>{{ 'This course is located by'|trans }}</h2>
<h4>{{ accompanyingCourse.personLocation|chill_entity_render_string }}</h4>
{% elseif accompanyingCourse.locationStatus == 'address' %}
<h4>{{ 'This course has a temporarily location'|trans }}</h4>
{% endif %}
<div class="mbloc col col-sm-6 col-lg-4">
<div class="location">
{% if accompanyingCourse.locationStatus == 'person' %}
<h2>{{ 'This course is located by'|trans }}</h2>
<h4>{{ accompanyingCourse.personLocation|chill_entity_render_string }}</h4>
{% elseif accompanyingCourse.locationStatus == 'address' %}
<h4>{{ 'This course has a temporarily location'|trans }}</h4>
{% endif %}
{% if accompanyingCourse.locationStatus != 'none' %}
{{ accompanyingCourse.location|chill_entity_render_box }}
{% endif %}
{% if accompanyingCourse.locationStatus != 'none' %}
{{ accompanyingCourse.location|chill_entity_render_box }}
{% endif %}
</div>
</div>
{% if accompanyingCourse.participations is not empty %}
<div class="col col-sm-6 col-lg-4 persons mb-4">
<h4 class="item-key">{{ 'Persons associated'|trans }}</h4>
{% for r in accompanyingCourse.participations %}
{{ _self.insert_onthefly('person', r.person) }}
{% endfor %}
</div>
{% endif %}
{% if accompanyingCourse.resources is not empty %}
<div class="col col-sm-6 col-lg-4 resources mb-4">
<h4 class="item-key">{{ 'Resources'|trans }}</h4>
{% for r in accompanyingCourse.resources %}
{% if r.person is not null %}
{{ _self.insert_onthefly('person', r.person) }}
{% elseif r.thirdParty is not null %}
{{ _self.insert_onthefly('thirdparty', r.thirdParty) }}
{% endif %}
{% endfor %}
</div>
{% endif %}
{% if accompanyingCourse.pinnedComment is not empty %}
<div class="col col-sm-6 col-lg-4 comment mb-4">
<h4 class="item-key">{{ 'Pinned comment'|trans }}</h4>
<blockquote class="chill-user-quote">
{{ accompanyingCourse.pinnedComment.content }}
<div class="metadata">
{{ 'Last updated by'| trans }}
<span class="user">
<div class="mbloc col col-sm-6 col-lg-8">
<div class="comment">
<h4 class="item-key visually-hidden">{{ 'Pinned comment'|trans }}</h4>
<blockquote class="chill-user-quote">
<i class="fa fa-flag float-end text-chill-gray" title="{{ 'pinned'|trans }}"></i>
{{ accompanyingCourse.pinnedComment.content|chill_markdown_to_html }}
<div class="metadata">
{{ 'Last updated by'| trans }}
<span class="user">
{{ accompanyingCourse.pinnedComment.updatedBy|chill_entity_render_box }}
</span>
{{ 'on'|trans ~ ' ' }}
<span class="date">
{{ 'on'|trans ~ ' ' }}
<span class="date">
{{ accompanyingCourse.pinnedComment.updatedAt|format_datetime("medium", "short") }}
</span>
</div>
</blockquote>
</div>
</blockquote>
</div>
</div>
{% endif %}
{% if accompanyingCourse.scopes is not empty %}
<div class="col col-sm-6 col-lg-4 scopes mb-4">
<h4 class="item-key">{{ 'Scopes'|trans }}</h4>
<div>
{% for s in accompanyingCourse.scopes %}
<span>{{ s.name|localize_translatable_string|capitalize }}</span>{% if not loop.last %}, {% endif %}
{% if accompanyingCourse.participations is not empty %}
<div class="mbloc col col-sm-6 col-lg-4">
<div class="persons">
<h4 class="item-key">{{ 'Persons associated'|trans }}</h4>
{% for r in accompanyingCourse.participations %}
{{ _self.insert_onthefly('person', r.person) }}
{% endfor %}
</div>
</div>
{% endif %}
{% if accompanyingCourse.requestorPerson is not null or accompanyingCourse.requestorThirdParty is not null %}
<div class="col col-sm-6 col-lg-4 requestor mb-4">
{% if accompanyingCourse.requestorPerson is not null %}
<h4 class="item-key">{{ 'Requestor'|trans }}</h4>
{{ _self.insert_onthefly('person', accompanyingCourse.requestorPerson) }}
{% elseif accompanyingCourse.requestorThirdParty is not null %}
<h4 class="item-key">{{ 'Requestor'|trans }}</h4>
{{ _self.insert_onthefly('thirdparty', accompanyingCourse.requestorThirdParty) }}
{% endif %}
{% if accompanyingCourse.resources is not empty %}
<div class="mbloc col col-sm-6 col-lg-4">
<div class="resources">
<h4 class="item-key">{{ 'Resources'|trans }}</h4>
{% for r in accompanyingCourse.resources %}
{% if r.person is not null %}
{{ _self.insert_onthefly('person', r.person) }}
{% elseif r.thirdParty is not null %}
{{ _self.insert_onthefly('thirdparty', r.thirdParty) }}
{% endif %}
{% endfor %}
</div>
</div>
{% endif %}
{% if accompanyingCourse.scopes is not empty %}
<div class="mbloc col col-sm-6 col-lg-4">
<div class="scopes">
<h4 class="item-key">{{ 'Scopes'|trans }}</h4>
<div>
{% for s in accompanyingCourse.scopes %}
<span>{{ s.name|localize_translatable_string|capitalize }}</span>{% if not loop.last %}, {% endif %}
{% endfor %}
</div>
</div>
</div>
{% endif %}
{% if accompanyingCourse.requestorPerson is not null or accompanyingCourse.requestorThirdParty is not null %}
<div class="mbloc col col-sm-6 col-lg-4">
<div class="requestor">
{% if accompanyingCourse.requestorPerson is not null %}
<h4 class="item-key">{{ 'Requestor'|trans }}</h4>
{{ _self.insert_onthefly('person', accompanyingCourse.requestorPerson) }}
{% elseif accompanyingCourse.requestorThirdParty is not null %}
<h4 class="item-key">{{ 'Requestor'|trans }}</h4>
{{ _self.insert_onthefly('thirdparty', accompanyingCourse.requestorThirdParty) }}
{% endif %}
</div>
</div>
{% endif %}
{% if accompanyingCourse.origin is not empty %}
<div class="mbloc col col-sm-6 col-lg-4">
<div class="origin">
<h4 class="item-key">{{ 'Origin'|trans }}</h4>
{{ accompanyingCourse.origin.label|localize_translatable_string|capitalize }}
</div>
</div>
{% endif %}
{% if accompanyingCourse.administrativeLocation is not null %}
<div class="mbloc col col-sm-6 col-lg-4">
<div class="administrative-location">
<h4 class="item-key">{{ 'accompanying_course.administrative_location'|trans }}</h4>
{{ accompanyingCourse.administrativeLocation.name }} ({{ accompanyingCourse.administrativeLocation.locationType.title|localize_translatable_string }})
</div>
</div>
{% endif %}
</div>
<div class="social-actions my-4">

View File

@ -3,7 +3,6 @@
{% for accompanying_period in accompanying_periods %}
<div class="item-bloc">
<div class="item-row">
<div class="wrap-header">
<div class="wh-row">
<div class="wh-col">
@ -127,6 +126,12 @@
<a href="{{ path('chill_person_accompanying_course_index', { 'accompanying_period_id': accompanying_period.id }) }}"
class="btn btn-show" title="{{ 'See accompanying period'|trans }}">{# {{ 'See this period'|trans }} #}</a>
</li>
{% if accompanying_period.step == 'DRAFT' %}
<li>
<a href="{{ path('chill_person_accompanying_course_delete', { 'accompanying_period_id': accompanying_period.id, 'person_id' : person.id }) }}"
class="btn btn-delete" title="{{ 'Delete accompanying period'|trans }}">{# {{ 'Delete this period'|trans }} #}</a>
</li>
{% endif %}
<!-- if new accompanying course, this is not necessary
{% if person is defined %}

View File

@ -124,7 +124,7 @@
{% if not person.isSharingHousehold() %}
<ul class="record_actions">
<li>
<a class="btn btn-misc" href="{{ chill_path_add_return_path('chill_person_household_members_editor', { 'persons': [ person.id ]}) }}">
<a class="btn btn-misc" href="{{chill_path_add_return_path('chill_person_household_members_editor', { 'persons': [ person.id ], 'followAfter': 'true'}) }}">
<i class="fa fa-sign-in fa-fw"></i>
{{ 'household.Join'|trans }}
</a>

View File

@ -12,6 +12,8 @@ declare(strict_types=1);
namespace Chill\PersonBundle\Serializer\Normalizer;
use Chill\DocGeneratorBundle\Serializer\Helper\NormalizeNullValueHelper;
use Chill\MainBundle\Entity\Address;
use Chill\MainBundle\Entity\Location;
use Chill\MainBundle\Entity\Scope;
use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Security\Resolver\ScopeResolverDispatcher;
@ -65,6 +67,9 @@ class AccompanyingPeriodDocGenNormalizer implements ContextAwareNormalizerInterf
'requestorPerson' => Person::class,
'requestorThirdParty' => ThirdParty::class,
'resources' => Collection::class,
'location' => Address::class,
'locationPerson' => Person::class,
'administrativeLocation' => Location::class,
];
private ClosingMotiveRender $closingMotiveRender;
@ -104,9 +109,11 @@ class AccompanyingPeriodDocGenNormalizer implements ContextAwareNormalizerInterf
$scopes = [$scopes];
}
$addressContext = array_merge($context, ['docgen:expects' => Address::class, 'groups' => 'docgen:read']);
$dateContext = array_merge($context, ['docgen:expects' => DateTime::class, 'groups' => 'docgen:read']);
$userContext = array_merge($context, ['docgen:expects' => User::class, 'groups' => 'docgen:read']);
$participationContext = array_merge($context, ['docgen:expects' => AccompanyingPeriodParticipation::class, 'groups' => 'docgen:read']);
$administrativeLocationContext = array_merge($context, ['docgen:expects' => Location::class, 'groups' => 'docgen:read']);
return [
'id' => $period->getId(),
@ -147,6 +154,12 @@ class AccompanyingPeriodDocGenNormalizer implements ContextAwareNormalizerInterf
}, $scopes)),
'hasRequestor' => $period->getRequestor() !== null,
'requestorKind' => $period->getRequestorKind(),
'hasLocation' => $period->getLocation() !== null,
'hasLocationPerson' => $period->getPersonLocation() !== null,
'hasAdministrativeLocation' => $period->getAdministrativeLocation() !== null,
'locationPerson' => $this->normalizer->normalize($period->getPersonLocation(), $format, array_merge($context, ['docgen:expects' => Person::class])),
'location' => $this->normalizer->normalize($period->getLocation(), $format, $addressContext),
'administrativeLocation' => $this->normalizer->normalize($period->getAdministrativeLocation(), $format, $administrativeLocationContext),
];
}
@ -162,6 +175,9 @@ class AccompanyingPeriodDocGenNormalizer implements ContextAwareNormalizerInterf
'hasRequestorThirdParty' => false,
'isClosed' => false,
'confidential' => false,
'hasLocation' => false,
'hasLocationPerson' => false,
'hasAdministrativeLocation' => false,
]
);
}

View File

@ -151,7 +151,7 @@ class PersonDocGenNormalizer implements
$normalizer = new NormalizeNullValueHelper($this->normalizer, 'type', 'person');
$attributes = [
'firstname', 'lastname', 'altNames', 'text',
'firstname', 'lastname', 'age', 'altNames', 'text',
'civility' => Civility::class,
'birthdate' => DateTimeInterface::class,
'deathdate' => DateTimeInterface::class,

View File

@ -15,10 +15,11 @@ use Chill\MainBundle\Entity\Center;
use Chill\MainBundle\Security\Resolver\CenterResolverManagerInterface;
use Chill\MainBundle\Templating\Entity\ChillEntityRenderExtension;
use Chill\PersonBundle\Entity\Person;
use Chill\PersonBundle\Entity\PersonAltName;
use Chill\PersonBundle\Repository\PersonRepository;
use DateTime;
use DateTimeImmutable;
use LogicException;
use Doctrine\Common\Collections\Collection;
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareTrait;
@ -78,13 +79,24 @@ class PersonJsonNormalizer implements
$person = new Person();
}
foreach (['firstName', 'lastName', 'phonenumber', 'mobilenumber', 'gender',
'birthdate', 'deathdate', 'center', ]
as $item) {
if (!array_key_exists($item, $data)) {
continue;
}
$fields = [
'firstName',
'lastName',
'phonenumber',
'mobilenumber',
'gender',
'birthdate',
'deathdate',
'center',
'altNames',
];
$fields = array_filter(
$fields,
static fn (string $field): bool => array_key_exists($field, $data)
);
foreach ($fields as $item) {
switch ($item) {
case 'firstName':
$person->setFirstName($data[$item]);
@ -131,8 +143,23 @@ class PersonJsonNormalizer implements
break;
default:
throw new LogicException("item not defined: {$item}");
case 'altNames':
foreach ($data[$item] as $altName) {
$oldAltName = $person
->getAltNames()
->filter(static fn (PersonAltName $n): bool => $n->getKey() === $altName['key'])->first();
if (false === $oldAltName) {
$newAltName = new PersonAltName();
$newAltName->setKey($altName['key']);
$newAltName->setLabel($altName['label']);
$person->addAltName($newAltName);
} else {
$oldAltName->setLabel($altName['label']);
}
}
break;
}
}
@ -175,14 +202,22 @@ class PersonJsonNormalizer implements
return $data instanceof Person && 'json' === $format;
}
protected function normalizeAltNames($altNames): array
/**
* @param Collection<array-key, PersonAltName> $altNames
*
* @return array<array-key, array<string, string>>
*/
protected function normalizeAltNames(Collection $altNames): array
{
$r = [];
foreach ($altNames as $n) {
$r[] = ['key' => $n->getKey(), 'label' => $n->getLabel()];
}
return $r;
return $altNames
->map(
static function (PersonAltName $personAltName): array {
return [
'key' => $personAltName->getKey(),
'label' => $personAltName->getLabel(),
];
}
)
->toArray();
}
}

View File

@ -11,7 +11,6 @@ declare(strict_types=1);
namespace Chill\PersonBundle\Tests\AccompanyingPeriod;
use Chill\MainBundle\Entity\Center;
use Chill\MainBundle\Entity\User;
use Chill\PersonBundle\Entity\AccompanyingPeriod;
use Chill\PersonBundle\Entity\Person;
@ -45,13 +44,13 @@ final class AccompanyingPeriodConfidentialTest extends WebTestCase
public function dataGenerateRandomAccompanyingCourse()
{
// Disabling this dataprovider to avoid having errors while running the test.
return yield from [];
$maxGenerated = 3;
$maxResults = $maxGenerated * 8;
self::bootKernel();
$em = self::$kernel->getContainer()->get('doctrine.orm.entity_manager');
$center = $em->getRepository(Center::class)
->findOneBy(['name' => 'Center A']);
$qb = $em->createQueryBuilder();
$personIds = $qb
@ -80,8 +79,7 @@ final class AccompanyingPeriodConfidentialTest extends WebTestCase
while ($nbGenerated < $maxGenerated) {
$id = array_pop($personIds)['id'];
$person = $em->getRepository(Person::class)
->find($id);
$person = $em->getRepository(Person::class)->find($id);
$periods = $person->getAccompanyingPeriods();
yield [array_pop($personIds)['id'], $periods[array_rand($periods)]->getId()];
@ -95,6 +93,10 @@ final class AccompanyingPeriodConfidentialTest extends WebTestCase
*/
public function testRemoveUserWhenConfidential(int $periodId)
{
$this->markTestIncomplete(
'Marked as incomplete because of a problem in the dataprovider, at line 81.'
);
$period = self::$container->get(AccompanyingPeriodRepository::class)
->find($periodId);
$em = self::$kernel->getContainer()->get('doctrine.orm.entity_manager');

View File

@ -306,6 +306,7 @@ final class AccompanyingCourseApiControllerTest extends WebTestCase
*/
public function testAccompanyingCourseAddParticipation(int $personId, int $periodId)
{
$this->markTestIncomplete('fix test with validation');
$this->client->request(
Request::METHOD_POST,
sprintf('/api/1.0/person/accompanying-course/%d/participation.json', $periodId),
@ -377,6 +378,7 @@ final class AccompanyingCourseApiControllerTest extends WebTestCase
*/
public function testAccompanyingCourseAddRemoveSocialIssue(AccompanyingPeriod $period, SocialIssue $si)
{
$this->markTestIncomplete('fix test with validation');
$this->client->request(
Request::METHOD_POST,
sprintf('/api/1.0/person/accompanying-course/%d/socialissue.json', $period->getId()),
@ -437,6 +439,7 @@ final class AccompanyingCourseApiControllerTest extends WebTestCase
*/
public function testAccompanyingPeriodPatch(int $personId, int $periodId)
{
$this->markTestIncomplete('fix test with validation');
$period = self::$container->get(AccompanyingPeriodRepository::class)
->find($periodId);
$initialValueEmergency = $period->isEmergency();
@ -475,6 +478,7 @@ final class AccompanyingCourseApiControllerTest extends WebTestCase
*/
public function testCommentWithValidData(AccompanyingPeriod $period, $personId, $thirdPartyId)
{
$this->markTestIncomplete('fix test with validation');
$em = self::$container->get(EntityManagerInterface::class);
$this->client->request(
@ -515,6 +519,7 @@ final class AccompanyingCourseApiControllerTest extends WebTestCase
*/
public function testConfirm(AccompanyingPeriod $period)
{
$this->markTestIncomplete('fix test with validation');
$this->client->request(
Request::METHOD_POST,
sprintf('/api/1.0/person/accompanying-course/%d/confirm.json', $period->getId())
@ -551,6 +556,7 @@ final class AccompanyingCourseApiControllerTest extends WebTestCase
*/
public function testRequestorWithValidData(AccompanyingPeriod $period, $personId, $thirdPartyId)
{
$this->markTestIncomplete('fix test with validation');
$em = self::$container->get(EntityManagerInterface::class);
// post a person
@ -634,6 +640,7 @@ final class AccompanyingCourseApiControllerTest extends WebTestCase
*/
public function testResourceWithValidData(AccompanyingPeriod $period, $personId, $thirdPartyId)
{
$this->markTestIncomplete('fix test with validation');
$em = self::$container->get(EntityManagerInterface::class);
// post a person

View File

@ -111,7 +111,7 @@ final class PersonAddressControllerTest extends WebTestCase
$crawler = $this->client->followRedirect();
$this->assertRegexp(
$this->assertMatchesRegularExpression(
'|/fr/person/[0-9]{1,}/address/list|',
$this->client->getHistory()->current()->getUri(),
'assert that the current page is on |/fr/person/[0-9]{1,}/address/list|'
@ -169,7 +169,7 @@ final class PersonAddressControllerTest extends WebTestCase
$crawler = $this->client->followRedirect();
$this->assertRegexp(
$this->assertMatchesRegularExpression(
'|/fr/person/[0-9]{1,}/address/list|',
$this->client->getHistory()->current()->getUri(),
'assert that the current page is on |/fr/person/[0-9]{1,}/address/list|'

View File

@ -166,7 +166,7 @@ final class PersonControllerCreateTest extends WebTestCase
$form = $this->fillAValidCreationForm($form, 'Charline', 'dd');
$client->submit($form);
$this->assertContains(
$this->assertStringContainsString(
'DEPARDIEU',
$client->getCrawler()->text(),
'check that the page has detected the lastname of a person existing in database'
@ -177,7 +177,7 @@ final class PersonControllerCreateTest extends WebTestCase
$form = $this->fillAValidCreationForm($form, 'dd', 'Charline');
$client->submit($form);
$this->assertContains(
$this->assertStringContainsString(
'DEPARDIEU',
$client->getCrawler()->text(),
'check that the page has detected the lastname of a person existing in database'
@ -206,7 +206,7 @@ final class PersonControllerCreateTest extends WebTestCase
$client->followRedirect();
// visualize regexp here : http://jex.im/regulex/#!embed=false&flags=&re=%2Ffr%2Fperson%2F[1-9][0-9]*%2Fgeneral%2Fedit%24
$this->assertRegExp(
$this->assertMatchesRegularExpression(
'|/fr/person/[1-9][0-9]*/general/edit$|',
$client->getHistory()->current()->getUri(),
'a valid form redirect to url /{_locale}/person/{personId}/general/edit'
@ -259,7 +259,7 @@ final class PersonControllerCreateTest extends WebTestCase
'a valid form redirect to url /{_locale}/person/{personId}/general/edit'
);
$client->followRedirect();
$this->assertRegExp(
$this->assertMatchesRegularExpression(
'|/fr/person/[1-9][0-9]*/general/edit$|',
$client->getHistory()->current()->getUri(),
'a valid form redirect to url /{_locale}/person/{personId}/general/edit'

View File

@ -83,10 +83,10 @@ final class PersonControllerViewTest extends WebTestCase
$this->assertGreaterThan(0, $crawler->filter('html:contains("TESTED PERSON")')->count());
$this->assertGreaterThan(0, $crawler->filter('html:contains("Réginald")')->count());
$this->assertContains('Email addresses', $crawler->text());
$this->assertContains('Phonenumber', $crawler->text());
$this->assertContains('Langues parlées', $crawler->text());
$this->assertContains(/* Etat */ 'civil', $crawler->text());
$this->assertStringContainsString('Email addresses', $crawler->text());
$this->assertStringContainsString('Phonenumber', $crawler->text());
$this->assertStringContainsString('Langues parlées', $crawler->text());
$this->assertStringContainsString(/* Etat */ 'civil', $crawler->text());
}
/**

Some files were not shown because too many files have changed in this diff Show More