Merge remote-tracking branch 'origin/master' into issue565_document_storedObject

This commit is contained in:
Julien Fastré 2022-04-27 08:43:35 +02:00
commit 452c4b85c6
50 changed files with 1210 additions and 530 deletions

View File

@ -12,10 +12,20 @@ and this project adheres to
<!-- write down unreleased development here --> <!-- write down unreleased development here -->
* [Documents] Validate storedObject and allow for null data (https://gitlab.com/champs-libres/departement-de-la-vendee/chill/-/issues/565) * [Documents] Validate storedObject and allow for null data (https://gitlab.com/champs-libres/departement-de-la-vendee/chill/-/issues/565)
* [Activity form] invert 'incoming' and 'receiving' in Activity form * [Activity form] invert 'incoming' and 'receiving' in Activity form
* [Activity form] keep the same order for 'attendee' field in new and edit form * [Activity form] keep the same order for 'attendee' field in new and edit form
* [list with period] use "sameas" test operator to introduce requestor in list * [list with period] use "sameas" test operator to introduce requestor in list
## Test releases
### 2021-04-26
* [Datepickers] datepickers fixed when using keyboard to enter date (https://gitlab.com/champs-libres/departement-de-la-vendee/chill/-/issues/545)
* [social_action] Display 'agents traitants' in parcours resumé and social action list (https://gitlab.com/champs-libres/departement-de-la-vendee/chill/-/issues/568)
* [Person_search] Closed parcours shown within an accordeon that can be opened/closed (https://gitlab.com/champs-libres/departement-de-la-vendee/chill/-/issues/574)
### 2021-04-24
* [notification email on course designation] allow raw string in email content generation * [notification email on course designation] allow raw string in email content generation
* [Accompanying period work] list evaluations associated to a work by startDate, and then by id, from the most recent to older * [Accompanying period work] list evaluations associated to a work by startDate, and then by id, from the most recent to older
* [Documents] Change wording 'créer' to 'enregistrer' (https://gitlab.com/champs-libres/departement-de-la-vendee/accent-suivi-developpement/-/issues/634) * [Documents] Change wording 'créer' to 'enregistrer' (https://gitlab.com/champs-libres/departement-de-la-vendee/accent-suivi-developpement/-/issues/634)
@ -26,11 +36,16 @@ and this project adheres to
* [Accompanying period work evaluations] list documents associated to a work by creation date, and then by id, from the most recent to older * [Accompanying period work evaluations] list documents associated to a work by creation date, and then by id, from the most recent to older
* [Course comment] add validationConstraint NotNull and NotBlank on comment content, to avoid sql error * [Course comment] add validationConstraint NotNull and NotBlank on comment content, to avoid sql error
* [Notifications] delay the sending of notificaiton to kernel.terminate * [Notifications] delay the sending of notificaiton to kernel.terminate
* [Notifications / Period user change] fix the sending of notification when user changes * [Notifications / Period user change] fix the sending of notification when user changes
* [Activity form] invert 'incoming' and 'receiving' in Activity form
* [Activity form] keep the same order for 'attendee' field in new and edit form
* [list with period] use "sameas" test operator to introduce requestor in list
* [notification email on course designation] allow raw string in email content generation
* [Accompanying period work] list evaluations associated to a work by startDate, and then by id, from the most recent to older
## Test releases
### 2021-04-13 ### 2021-04-13
* [person] household address: add a form for editing the validFrom date (https://gitlab.com/champs-libres/departement-de-la-vendee/chill/-/issues/541) * [person] household address: add a form for editing the validFrom date (https://gitlab.com/champs-libres/departement-de-la-vendee/chill/-/issues/541)
* [person] householdmemberseditor: fix composition type bug in select form (vuejs) (https://gitlab.com/champs-libres/departement-de-la-vendee/chill/-/issues/543) * [person] householdmemberseditor: fix composition type bug in select form (vuejs) (https://gitlab.com/champs-libres/departement-de-la-vendee/chill/-/issues/543)
* [docgen] add more persons choices in docgen for course: amongst requestor (if person), resources of course (if person), and PersonResource (if person); * [docgen] add more persons choices in docgen for course: amongst requestor (if person), resources of course (if person), and PersonResource (if person);
@ -101,6 +116,7 @@ and this project adheres to
* [household] bugfix if position of member is null, renderbox no longer throws an error (https://gitlab.com/champs-libres/departement-de-la-vendee/chill/-/issues/480) * [household] bugfix if position of member is null, renderbox no longer throws an error (https://gitlab.com/champs-libres/departement-de-la-vendee/chill/-/issues/480)
* [parcours] location cannot be removed if linked to a user (https://gitlab.com/champs-libres/departement-de-la-vendee/chill/-/issues/478) * [parcours] location cannot be removed if linked to a user (https://gitlab.com/champs-libres/departement-de-la-vendee/chill/-/issues/478)
* [person] email added to twig personRenderbox (https://gitlab.com/champs-libres/departement-de-la-vendee/chill/-/issues/490) * [person] email added to twig personRenderbox (https://gitlab.com/champs-libres/departement-de-la-vendee/chill/-/issues/490)
* [activity] Only youngest descendant is kept for social issues and actions (https://gitlab.com/champs-libres/departement-de-la-vendee/chill/-/issues/471)
* [person] Add link to current household in person banner (https://gitlab.com/champs-libres/departement-de-la-vendee/chill/-/issues/484) * [person] Add link to current household in person banner (https://gitlab.com/champs-libres/departement-de-la-vendee/chill/-/issues/484)
* [address] person badge in address history changed to open OnTheFly with all person info (https://gitlab.com/champs-libres/departement-de-la-vendee/chill/-/issues/489) * [address] person badge in address history changed to open OnTheFly with all person info (https://gitlab.com/champs-libres/departement-de-la-vendee/chill/-/issues/489)
* [person] Change 'personne' with 'usager' and '&' with 'ET' (https://gitlab.com/champs-libres/departement-de-la-vendee/chill/-/issues/499) * [person] Change 'personne' with 'usager' and '&' with 'ET' (https://gitlab.com/champs-libres/departement-de-la-vendee/chill/-/issues/499)
@ -128,6 +144,9 @@ and this project adheres to
* [notification] Display of social action within workflow notification set to display block (https://gitlab.com/champs-libres/departement-de-la-vendee/chill/-/issues/537) * [notification] Display of social action within workflow notification set to display block (https://gitlab.com/champs-libres/departement-de-la-vendee/chill/-/issues/537)
* [onthefly] trim trailing whitespace in email of person and thirdparty (https://gitlab.com/champs-libres/departement-de-la-vendee/chill/-/issues/542) * [onthefly] trim trailing whitespace in email of person and thirdparty (https://gitlab.com/champs-libres/departement-de-la-vendee/chill/-/issues/542)
* [action] Only youngest descendant is kept for social issues and actions (https://gitlab.com/champs-libres/departement-de-la-vendee/chill/-/issues/471)
## Test releases
### test release 2022-02-21 ### test release 2022-02-21
* [notifications] Word 'un' changed to number '1' for notifications in user menu (https://gitlab.com/champs-libres/departement-de-la-vendee/accent-suivi-developpement/-/issues/483) * [notifications] Word 'un' changed to number '1' for notifications in user menu (https://gitlab.com/champs-libres/departement-de-la-vendee/accent-suivi-developpement/-/issues/483)

View File

@ -21,7 +21,7 @@
"knplabs/knp-time-bundle": "^1.12", "knplabs/knp-time-bundle": "^1.12",
"league/csv": "^9.7.1", "league/csv": "^9.7.1",
"nyholm/psr7": "^1.4", "nyholm/psr7": "^1.4",
"ocramius/package-versions": "^1.10", "ocramius/package-versions": "^1.10 || ^2",
"odolbeau/phone-number-bundle": "^3.6", "odolbeau/phone-number-bundle": "^3.6",
"phpoffice/phpspreadsheet": "^1.16", "phpoffice/phpspreadsheet": "^1.16",
"ramsey/uuid-doctrine": "^1.7", "ramsey/uuid-doctrine": "^1.7",
@ -33,6 +33,7 @@
"symfony/expression-language": "^4.4", "symfony/expression-language": "^4.4",
"symfony/form": "^4.4", "symfony/form": "^4.4",
"symfony/framework-bundle": "^4.4", "symfony/framework-bundle": "^4.4",
"symfony/http-foundation": "^4.4",
"symfony/intl": "^4.4", "symfony/intl": "^4.4",
"symfony/mailer": "^5.4", "symfony/mailer": "^5.4",
"symfony/mime": "^5.4", "symfony/mime": "^5.4",
@ -103,7 +104,8 @@
"ergebnis/composer-normalize": true, "ergebnis/composer-normalize": true,
"ocramius/package-versions": true, "ocramius/package-versions": true,
"phpro/grumphp": true, "phpro/grumphp": true,
"phpstan/extension-installer": true "phpstan/extension-installer": true,
"roave/you-are-using-it-wrong": true
}, },
"bin-dir": "bin", "bin-dir": "bin",
"optimize-autoloader": true, "optimize-autoloader": true,

View File

@ -233,11 +233,22 @@ class Activity implements AccompanyingPeriodLinkedWithSocialIssuesEntityInterfac
{ {
if (!$this->socialActions->contains($socialAction)) { if (!$this->socialActions->contains($socialAction)) {
$this->socialActions[] = $socialAction; $this->socialActions[] = $socialAction;
$this->ensureSocialActionConsistency();
} }
return $this; return $this;
} }
/**
* Add a social issue.
*
* Note: the social issue consistency (the fact that only yougest social issues
* are kept) is processed by an entity listener:
*
* @see{\Chill\PersonBundle\AccompanyingPeriod\SocialIssueConsistency\AccompanyingPeriodSocialIssueConsistencyEntityListener}
*
* @return $this
*/
public function addSocialIssue(SocialIssue $socialIssue): self public function addSocialIssue(SocialIssue $socialIssue): self
{ {
if (!$this->socialIssues->contains($socialIssue)) { if (!$this->socialIssues->contains($socialIssue)) {
@ -633,4 +644,13 @@ class Activity implements AccompanyingPeriodLinkedWithSocialIssuesEntityInterfac
return $this; return $this;
} }
private function ensureSocialActionConsistency(): void
{
$ancestors = SocialAction::findAncestorSocialActions($this->getSocialActions());
foreach ($ancestors as $ancestor) {
$this->removeSocialAction($ancestor);
}
}
} }

View File

@ -54,19 +54,19 @@
{{ $t('activity.select_first_a_social_issue') }} {{ $t('activity.select_first_a_social_issue') }}
</span> </span>
<template v-else-if="socialActionsList.length > 0"> <template v-else-if="socialActionsList.length > 0">
<check-social-action <check-social-action
v-if="socialIssuesSelected.length || socialActionsSelected.length" v-if="socialIssuesSelected.length || socialActionsSelected.length"
v-for="action in socialActionsList" v-for="action in socialActionsList"
:key="action.id" :key="action.id"
:action="action" :action="action"
:selection="socialActionsSelected" :selection="socialActionsSelected"
@updateSelected="updateActionsSelected"> @updateSelected="updateActionsSelected">
</check-social-action> </check-social-action>
</template> </template>
<span v-else-if="actionAreLoaded && socialActionsList.length === 0" class="inline-choice chill-no-data-statement mt-3"> <span v-else-if="actionAreLoaded && socialActionsList.length === 0" class="inline-choice chill-no-data-statement mt-3">
{{ $t('activity.social_action_list_empty') }} {{ $t('activity.social_action_list_empty') }}
</span> </span>
@ -111,7 +111,7 @@ export default {
return this.$store.state.socialIssuesOther; return this.$store.state.socialIssuesOther;
}, },
socialActionsList() { socialActionsList() {
return this.$store.state.socialActionsList; return this.$store.getters.socialActionsListSorted;
}, },
socialActionsSelected() { socialActionsSelected() {
return this.$store.state.activity.socialActions; return this.$store.state.activity.socialActions;

View File

@ -101,6 +101,9 @@ const store = createStore({
state.activity.activityType.thirdPartiesVisible !== 0) state.activity.activityType.thirdPartiesVisible !== 0)
); );
}, },
socialActionsListSorted(state) {
return [ ...state.socialActionsList].sort((a, b) => a.ordering - b.ordering);
},
}, },
mutations: { mutations: {
// SocialIssueAcc // SocialIssueAcc
@ -131,7 +134,6 @@ const store = createStore({
state.socialActionsList = []; state.socialActionsList = [];
}, },
addActionInList(state, action) { addActionInList(state, action) {
//console.log('add action list', action.id);
state.socialActionsList.push(action); state.socialActionsList.push(action);
}, },
updateActionsSelected(state, actions) { updateActionsSelected(state, actions) {

View File

@ -0,0 +1,114 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Chill\ActivityBundle\Tests\Entity;
use Chill\ActivityBundle\Entity\Activity;
use Chill\PersonBundle\AccompanyingPeriod\SocialIssueConsistency\AccompanyingPeriodSocialIssueConsistencyEntityListener;
use Chill\PersonBundle\Entity\AccompanyingPeriod;
use Chill\PersonBundle\Entity\SocialWork\SocialAction;
use Chill\PersonBundle\Entity\SocialWork\SocialIssue;
use Doctrine\ORM\Event\LifecycleEventArgs;
use PHPUnit\Framework\TestCase;
use Prophecy\PhpUnit\ProphecyTrait;
/**
* @internal
* @coversNothing
*/
final class ActivityTest extends TestCase
{
use ProphecyTrait;
public function testHierarchySocialActions(): void
{
$parent = new SocialAction();
$child = new SocialAction();
$parent->addChild($child);
$grandChild = new SocialAction();
$child->addChild($grandChild);
$activity = new Activity();
$activity->addSocialAction($parent);
$this->assertCount(1, $activity->getSocialActions());
$this->assertContains($parent, $activity->getSocialActions());
$activity->addSocialAction($grandChild);
$this->assertCount(1, $activity->getSocialActions());
$this->assertContains($grandChild, $activity->getSocialActions());
$this->assertNotContains($parent, $activity->getSocialActions());
$activity->addSocialAction($child);
$this->assertCount(1, $activity->getSocialActions());
$this->assertContains($grandChild, $activity->getSocialActions());
$this->assertNotContains($parent, $activity->getSocialActions());
$this->assertNotContains($child, $activity->getSocialActions());
$activity->addSocialAction($another = new SocialAction());
$this->assertCount(2, $activity->getSocialActions());
$this->assertContains($grandChild, $activity->getSocialActions());
$this->assertContains($another, $activity->getSocialActions());
$this->assertNotContains($parent, $activity->getSocialActions());
$this->assertNotContains($child, $activity->getSocialActions());
}
public function testHierarchySocialIssues(): void
{
$listener = new AccompanyingPeriodSocialIssueConsistencyEntityListener();
$event = $this->prophesize(LifecycleEventArgs::class)->reveal();
$parent = new SocialIssue();
$child = new SocialIssue();
$parent->addChild($child);
$grandChild = new SocialIssue();
$child->addChild($grandChild);
$activity = new Activity();
$activity->setAccompanyingPeriod(new AccompanyingPeriod());
$activity->addSocialIssue($parent);
$listener->preUpdate($activity, $event);
$this->assertCount(1, $activity->getSocialIssues());
$this->assertContains($parent, $activity->getSocialIssues());
$activity->addSocialIssue($grandChild);
$listener->preUpdate($activity, $event);
$this->assertCount(1, $activity->getSocialIssues());
$this->assertContains($grandChild, $activity->getSocialIssues());
$this->assertNotContains($parent, $activity->getSocialIssues());
$activity->addSocialIssue($child);
$listener->preUpdate($activity, $event);
$this->assertCount(1, $activity->getSocialIssues());
$this->assertContains($grandChild, $activity->getSocialIssues());
$this->assertNotContains($parent, $activity->getSocialIssues());
$this->assertNotContains($child, $activity->getSocialIssues());
$activity->addSocialIssue($another = new SocialIssue());
$listener->preUpdate($activity, $event);
$this->assertCount(2, $activity->getSocialIssues());
$this->assertContains($grandChild, $activity->getSocialIssues());
$this->assertContains($another, $activity->getSocialIssues());
$this->assertNotContains($parent, $activity->getSocialIssues());
$this->assertNotContains($child, $activity->getSocialIssues());
}
}

View File

@ -14,7 +14,7 @@ namespace Chill\DocGeneratorBundle\Context;
use Chill\DocGeneratorBundle\Context\Exception\ContextNotFoundException; use Chill\DocGeneratorBundle\Context\Exception\ContextNotFoundException;
use Chill\DocGeneratorBundle\Entity\DocGeneratorTemplate; use Chill\DocGeneratorBundle\Entity\DocGeneratorTemplate;
class ContextManager final class ContextManager implements ContextManagerInterface
{ {
/** /**
* @var DocGeneratorContextInterface[]|iterable * @var DocGeneratorContextInterface[]|iterable
@ -26,9 +26,6 @@ class ContextManager
$this->contexts = $contexts; $this->contexts = $contexts;
} }
/**
* @throw ContextNotFoundException when the context is not found
*/
public function getContextByDocGeneratorTemplate(DocGeneratorTemplate $docGeneratorTemplate): DocGeneratorContextInterface public function getContextByDocGeneratorTemplate(DocGeneratorTemplate $docGeneratorTemplate): DocGeneratorContextInterface
{ {
foreach ($this->contexts as $key => $context) { foreach ($this->contexts as $key => $context) {

View File

@ -0,0 +1,30 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Chill\DocGeneratorBundle\Context;
use Chill\DocGeneratorBundle\Context\Exception\ContextNotFoundException;
use Chill\DocGeneratorBundle\Entity\DocGeneratorTemplate;
interface ContextManagerInterface
{
/**
* @throws ContextNotFoundException When the context is not found.
*/
public function getContextByDocGeneratorTemplate(DocGeneratorTemplate $docGeneratorTemplate): DocGeneratorContextInterface;
/**
* @throws ContextNotFoundException When the context is not found.
*/
public function getContextByKey(string $searchedKey): DocGeneratorContextInterface;
public function getContexts(): array;
}

View File

@ -11,8 +11,6 @@ declare(strict_types=1);
namespace Chill\DocGeneratorBundle\Controller; namespace Chill\DocGeneratorBundle\Controller;
use Base64Url\Base64Url;
use ChampsLibres\AsyncUploaderBundle\TempUrl\TempUrlGeneratorInterface;
use Chill\DocGeneratorBundle\Context\ContextManager; use Chill\DocGeneratorBundle\Context\ContextManager;
use Chill\DocGeneratorBundle\Context\DocGeneratorContextWithPublicFormInterface; use Chill\DocGeneratorBundle\Context\DocGeneratorContextWithPublicFormInterface;
use Chill\DocGeneratorBundle\Context\Exception\ContextNotFoundException; use Chill\DocGeneratorBundle\Context\Exception\ContextNotFoundException;
@ -21,11 +19,11 @@ use Chill\DocGeneratorBundle\GeneratorDriver\DriverInterface;
use Chill\DocGeneratorBundle\GeneratorDriver\Exception\TemplateException; use Chill\DocGeneratorBundle\GeneratorDriver\Exception\TemplateException;
use Chill\DocGeneratorBundle\Repository\DocGeneratorTemplateRepository; use Chill\DocGeneratorBundle\Repository\DocGeneratorTemplateRepository;
use Chill\DocStoreBundle\Entity\StoredObject; use Chill\DocStoreBundle\Entity\StoredObject;
use Chill\DocStoreBundle\Service\StoredObjectManagerInterface;
use Chill\MainBundle\Pagination\PaginatorFactory; use Chill\MainBundle\Pagination\PaginatorFactory;
use Chill\MainBundle\Serializer\Model\Collection; use Chill\MainBundle\Serializer\Model\Collection;
use Doctrine\ORM\EntityManagerInterface;
use Exception; use Exception;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\TransferException;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType; use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
@ -35,14 +33,14 @@ use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
// TODO à mettre dans services // TODO à mettre dans services
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\Routing\Annotation\Route; use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer; use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Contracts\HttpClient\HttpClientInterface; use Symfony\Contracts\HttpClient\HttpClientInterface;
use Throwable;
use function strlen;
final class DocGeneratorTemplateController extends AbstractController final class DocGeneratorTemplateController extends AbstractController
{ {
@ -54,13 +52,13 @@ final class DocGeneratorTemplateController extends AbstractController
private DriverInterface $driver; private DriverInterface $driver;
private KernelInterface $kernel; private EntityManagerInterface $entityManager;
private LoggerInterface $logger; private LoggerInterface $logger;
private PaginatorFactory $paginatorFactory; private PaginatorFactory $paginatorFactory;
private TempUrlGeneratorInterface $tempUrlGenerator; private StoredObjectManagerInterface $storedObjectManager;
public function __construct( public function __construct(
ContextManager $contextManager, ContextManager $contextManager,
@ -68,18 +66,18 @@ final class DocGeneratorTemplateController extends AbstractController
DriverInterface $driver, DriverInterface $driver,
LoggerInterface $logger, LoggerInterface $logger,
PaginatorFactory $paginatorFactory, PaginatorFactory $paginatorFactory,
TempUrlGeneratorInterface $tempUrlGenerator, HttpClientInterface $client,
KernelInterface $kernel, StoredObjectManagerInterface $storedObjectManager,
HttpClientInterface $client EntityManagerInterface $entityManager
) { ) {
$this->contextManager = $contextManager; $this->contextManager = $contextManager;
$this->docGeneratorTemplateRepository = $docGeneratorTemplateRepository; $this->docGeneratorTemplateRepository = $docGeneratorTemplateRepository;
$this->driver = $driver; $this->driver = $driver;
$this->logger = $logger; $this->logger = $logger;
$this->paginatorFactory = $paginatorFactory; $this->paginatorFactory = $paginatorFactory;
$this->tempUrlGenerator = $tempUrlGenerator;
$this->kernel = $kernel;
$this->client = $client; $this->client = $client;
$this->storedObjectManager = $storedObjectManager;
$this->entityManager = $entityManager;
} }
/** /**
@ -178,8 +176,10 @@ final class DocGeneratorTemplateController extends AbstractController
return $this->redirectToRoute( return $this->redirectToRoute(
'chill_docgenerator_test_generate_from_template', 'chill_docgenerator_test_generate_from_template',
['template' => $template, 'entityClassName' => $entityClassName, 'entityId' => $entityId, [
'returnPath' => $request->query->get('returnPath', '/'), ] 'template' => $template, 'entityClassName' => $entityClassName, 'entityId' => $entityId,
'returnPath' => $request->query->get('returnPath', '/'),
]
); );
} }
@ -193,16 +193,26 @@ final class DocGeneratorTemplateController extends AbstractController
try { try {
$context = $this->contextManager->getContextByDocGeneratorTemplate($template); $context = $this->contextManager->getContextByDocGeneratorTemplate($template);
} catch (ContextNotFoundException $e) { } catch (ContextNotFoundException $e) {
throw new NotFoundHttpException($e->getMessage(), $e); throw new NotFoundHttpException(
'Context not found.',
$e
);
} }
$entity = $this->getDoctrine()->getRepository($context->getEntityClass())->find($entityId); $entity = $this
->entityManager
->getRepository($context->getEntityClass())
->find($entityId);
if (null === $entity) { if (null === $entity) {
throw new NotFoundHttpException("Entity with classname {$entityClassName} and id {$entityId} is not found"); throw new NotFoundHttpException(
sprintf('Entity with classname %s and id %s is not found', $entityClassName, $entityId)
);
} }
$contextGenerationData = []; $contextGenerationData = [
'test_file' => null,
];
if ( if (
$context instanceof DocGeneratorContextWithPublicFormInterface $context instanceof DocGeneratorContextWithPublicFormInterface
@ -240,128 +250,114 @@ final class DocGeneratorTemplateController extends AbstractController
$contextGenerationData = $form->getData(); $contextGenerationData = $form->getData();
} elseif (!$form->isSubmitted() || ($form->isSubmitted() && !$form->isValid())) { } elseif (!$form->isSubmitted() || ($form->isSubmitted() && !$form->isValid())) {
$templatePath = '@ChillDocGenerator/Generator/basic_form.html.twig'; $templatePath = '@ChillDocGenerator/Generator/basic_form.html.twig';
$templateOptions = ['entity' => $entity, 'form' => $form->createView(), $templateOptions = [
'template' => $template, 'context' => $context, ]; 'entity' => $entity, 'form' => $form->createView(),
'template' => $template, 'context' => $context,
];
return $this->render($templatePath, $templateOptions); return $this->render($templatePath, $templateOptions);
} }
} }
if ($isTest && null !== $contextGenerationData['test_file']) { $document = $template->getFile();
/** @var File $file */
$file = $contextGenerationData['test_file']; if ($isTest && ($contextGenerationData['test_file'] instanceof File)) {
$templateResource = fopen($file->getPathname(), 'rb'); $dataDecrypted = file_get_contents($contextGenerationData['test_file']->getPathname());
} else { } else {
$getUrlGen = $this->tempUrlGenerator->generate( try {
'GET', $dataDecrypted = $this->storedObjectManager->read($document);
$template->getFile()->getFilename() } catch (Throwable $exception) {
); throw $exception;
$data = $this->client->request('GET', $getUrlGen->url);
$iv = $template->getFile()->getIv(); // iv as an Array
$ivGoodFormat = pack('C*', ...$iv); // iv as a String (ok for openssl_decrypt)
$method = 'AES-256-CBC';
$key = $template->getFile()->getKeyInfos()['k'];
$keyGoodFormat = Base64Url::decode($key);
$dataDecrypted = openssl_decrypt($data->getContent(), $method, $keyGoodFormat, 1, $ivGoodFormat);
if (false === $dataDecrypted) {
throw new Exception('Error during Decrypt ', 1);
} }
if (false === $templateResource = fopen('php://memory', 'r+b')) {
$this->logger->error('Could not write data to memory');
throw new HttpException(500);
}
fwrite($templateResource, $dataDecrypted);
rewind($templateResource);
} }
$datas = $context->getData($template, $entity, $contextGenerationData);
if ($isTest && isset($form) && $form['show_data']->getData()) { if ($isTest && isset($form) && $form['show_data']->getData()) {
// very ugly hack... // very ugly hack...
dd($datas); dd($context->getData($template, $entity, $contextGenerationData));
} }
try { try {
$generatedResource = $this->driver->generateFromResource($templateResource, $template->getFile()->getType(), $datas, $template->getFile()->getFilename()); $generatedResource = $this
->driver
->generateFromString(
$dataDecrypted,
$template->getFile()->getType(),
$context->getData($template, $entity, $contextGenerationData),
$template->getFile()->getFilename()
);
} catch (TemplateException $e) { } catch (TemplateException $e) {
$msg = implode("\n", $e->getErrors()); return new Response(
implode("\n", $e->getErrors()),
return new Response($msg, 400, [ 400,
'Content-Type' => 'text/plain', [
]); 'Content-Type' => 'text/plain',
]
);
} }
fclose($templateResource);
if ($isTest) { if ($isTest) {
return new StreamedResponse( return new Response(
static function () use ($generatedResource) { $generatedResource,
fpassthru($generatedResource);
fclose($generatedResource);
},
Response::HTTP_OK, Response::HTTP_OK,
[ [
'Content-Transfer-Encoding', 'binary', 'Content-Transfer-Encoding', 'binary',
'Content-Type' => 'application/vnd.oasis.opendocument.text', 'Content-Type' => 'application/vnd.oasis.opendocument.text',
'Content-Disposition' => sprintf('attachment; filename="%s.odt"', 'generated'), 'Content-Disposition' => 'attachment; filename="generated.odt"',
'Content-Length' => fstat($generatedResource)['size'], 'Content-Length' => strlen($generatedResource),
], ],
); );
} }
$genDocName = 'doc_' . sprintf('%010d', mt_rand()) . 'odt'; /** @var StoredObject $storedObject */
$storedObject = (new ObjectNormalizer())
$getUrlGen = $this->tempUrlGenerator->generate( ->denormalize(
'PUT', [
$genDocName 'type' => $template->getFile()->getType(),
); 'filename' => sprintf('%s_odt', uniqid('doc_', true)),
],
$client = new Client(); StoredObject::class
);
try { try {
$putResponse = $client->request('PUT', $getUrlGen->url, [ $this->storedObjectManager->write($storedObject, $generatedResource);
'body' => $generatedResource, } catch (Throwable $exception) {
]); throw $exception;
}
if ($putResponse->getStatusCode() === 201) { $this->entityManager->persist($storedObject);
$em = $this->getDoctrine()->getManager();
$storedObject = new StoredObject();
$storedObject
->setType($template->getFile()->getType())
->setFilename($genDocName);
$em->persist($storedObject); try {
$context
try { ->storeGenerated(
$context->storeGenerated($template, $storedObject, $entity, $contextGenerationData); $template,
} catch (Exception $e) { $storedObject,
$this->logger->error('Could not store the associated document to entity', [ $entity,
$contextGenerationData
);
} catch (Exception $e) {
$this
->logger
->error(
'Unable to store the associated document to entity',
[
'entityClassName' => $entityClassName, 'entityClassName' => $entityClassName,
'entityId' => $entityId, 'entityId' => $entityId,
'contextKey' => $context->getName(), 'contextKey' => $context->getName(),
]); ]
);
throw $e;
}
$em->flush();
return $this->redirectToRoute('chill_wopi_file_edit', [
'fileId' => $storedObject->getUuid(),
'returnPath' => $request->query->get('returnPath', '/'),
]);
}
} catch (TransferException $e) {
throw $e; throw $e;
} }
throw new Exception('Unable to generate document.'); $this->entityManager->flush();
return $this
->redirectToRoute(
'chill_wopi_file_edit',
[
'fileId' => $storedObject->getUuid(),
'returnPath' => $request->query->get('returnPath', '/'),
]
);
} }
} }

View File

@ -13,10 +13,5 @@ namespace Chill\DocGeneratorBundle\GeneratorDriver;
interface DriverInterface interface DriverInterface
{ {
/** public function generateFromString(string $template, string $resourceType, array $data, ?string $templateName = null): string;
* @param resource $template
*
* @return resource
*/
public function generateFromResource($template, string $resourceType, array $data, ?string $templateName = null);
} }

View File

@ -16,45 +16,47 @@ use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface; use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\Mime\Part\DataPart; use Symfony\Component\Mime\Part\DataPart;
use Symfony\Component\Mime\Part\Multipart\FormDataPart; use Symfony\Component\Mime\Part\Multipart\FormDataPart;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\DecodingExceptionInterface; use Symfony\Contracts\HttpClient\Exception\DecodingExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\HttpExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface; use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface; use Symfony\Contracts\HttpClient\HttpClientInterface;
use Throwable;
class RelatorioDriver implements DriverInterface final class RelatorioDriver implements DriverInterface
{ {
private LoggerInterface $logger; private HttpClientInterface $client;
private HttpClientInterface $relatorioClient; private LoggerInterface $logger;
private string $url; private string $url;
public function __construct( public function __construct(
HttpClientInterface $relatorioClient, HttpClientInterface $client,
ParameterBagInterface $parameterBag, ParameterBagInterface $parameterBag,
LoggerInterface $logger LoggerInterface $logger
) { ) {
$this->relatorioClient = $relatorioClient; $this->client = $client;
$this->logger = $logger; $this->logger = $logger;
$this->url = $parameterBag->get('chill_doc_generator')['driver']['relatorio']['url']; $this->url = $parameterBag->get('chill_doc_generator')['driver']['relatorio']['url'];
} }
public function generateFromResource($template, string $resourceType, array $data, ?string $templateName = null) public function generateFromString(string $template, string $resourceType, array $data, ?string $templateName = null): string
{ {
$formFields = [ $form = new FormDataPart(
'variables' => json_encode($data), [
'template' => new DataPart($template, $templateName ?? uniqid('template_'), $resourceType), 'variables' => json_encode($data),
]; 'template' => new DataPart($template, $templateName ?? uniqid('template_'), $resourceType),
$form = new FormDataPart($formFields); ]
);
try { try {
$response = $this->relatorioClient->request('POST', $this->url, [ $response = $this->client->request('POST', $this->url, [
'headers' => $form->getPreparedHeaders()->toArray(), 'headers' => $form->getPreparedHeaders()->toArray(),
'body' => $form->bodyToIterable(), 'body' => $form->bodyToIterable(),
]); ]);
return $response->toStream(); return $response->getContent();
} catch (HttpExceptionInterface $e) { } catch (ClientExceptionInterface $e) {
$content = $e->getResponse()->getContent(false); $content = $e->getResponse()->getContent(false);
if (400 === $e->getResponse()->getStatusCode()) { if (400 === $e->getResponse()->getStatusCode()) {
@ -87,6 +89,18 @@ class RelatorioDriver implements DriverInterface
]); ]);
throw $e; throw $e;
} catch (Throwable $exception) {
$this
->logger
->error(
'relatorio: Unable to get content from response.',
[
'msg' => $exception->getMessage(),
'e' => $exception->getTraceAsString(),
]
);
throw $exception;
} }
} }
} }

View File

@ -18,6 +18,7 @@
} }
], ],
"require": { "require": {
"spomky-labs/base64url": "^2"
}, },
"require-dev": { "require-dev": {
}, },

View File

@ -109,12 +109,12 @@ class StoredObject implements AsyncFileInterface, Document
return $this->id; return $this->id;
} }
public function getIv() public function getIv(): array
{ {
return $this->iv; return $this->iv;
} }
public function getKeyInfos() public function getKeyInfos(): array
{ {
return $this->keyInfos; return $this->keyInfos;
} }

View File

@ -0,0 +1,40 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Chill\DocStoreBundle\Exception;
use Exception;
use Throwable;
final class StoredObjectManagerException extends Exception
{
public static function errorDuringHttpRequest(Throwable $exception): self
{
return new self('Error during HTTP request.', 500, $exception);
}
public static function invalidStatusCode(int $code): self
{
return new self(
sprintf('Invalid status code received (%s).', $code)
);
}
public static function unableToDecrypt(string $message): self
{
return new self(sprintf('Unable to decrypt content (reason: %s).', $message));
}
public static function unableToGetResponseContent(Throwable $exception): self
{
return new self('Unable to get content from response.', 500, $exception);
}
}

View File

@ -1,7 +1,3 @@
{# Twig way
TODO: une route, un template avec un header CHILL et un iframe
#}
<a href="{{ chill_path_add_return_path('chill_wopi_file_edit', {'fileId': document.uuid}) }}" <a href="{{ chill_path_add_return_path('chill_wopi_file_edit', {'fileId': document.uuid}) }}"
class="btn btn-wopilink"> class="btn btn-wopilink">
{{ 'online_edit_document'|trans }} {{ 'online_edit_document'|trans }}

View File

@ -53,6 +53,11 @@
<li> <li>
<a href="{{ path('accompanying_course_document_edit', {'course': accompanyingCourse.id, 'id': document.id }) }}" class="btn btn-update"></a> <a href="{{ path('accompanying_course_document_edit', {'course': accompanyingCourse.id, 'id': document.id }) }}" class="btn btn-update"></a>
</li> </li>
{% if chill_document_is_editable(document.object) %}
<li>
{{ document.object|chill_document_edit_button }}
</li>
{% endif %}
{% endif %} {% endif %}
{% if is_granted('CHILL_ACCOMPANYING_COURSE_DOCUMENT_SEE_DETAILS', document) %} {% if is_granted('CHILL_ACCOMPANYING_COURSE_DOCUMENT_SEE_DETAILS', document) %}
<li> <li>
@ -75,6 +80,11 @@
<li> <li>
<a href="{{ path('person_document_edit', {'person': person.id, 'id': document.id}) }}" class="btn btn-update"></a> <a href="{{ path('person_document_edit', {'person': person.id, 'id': document.id}) }}" class="btn btn-update"></a>
</li> </li>
{% if chill_document_is_editable(document.object) %}
<li>
{{ document.object|chill_document_edit_button }}
</li>
{% endif %}
{% endif %} {% endif %}
{% if is_granted('CHILL_PERSON_DOCUMENT_SEE_DETAILS', document) %} {% if is_granted('CHILL_PERSON_DOCUMENT_SEE_DETAILS', document) %}
<li> <li>

View File

@ -0,0 +1,133 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Chill\DocStoreBundle\Service;
use Base64Url\Base64Url;
use ChampsLibres\AsyncUploaderBundle\TempUrl\TempUrlGeneratorInterface;
use Chill\DocStoreBundle\Entity\StoredObject;
use Chill\DocStoreBundle\Exception\StoredObjectManagerException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Throwable;
use const OPENSSL_RAW_DATA;
final class StoredObjectManager implements StoredObjectManagerInterface
{
private const ALGORITHM = 'AES-256-CBC';
private HttpClientInterface $client;
private TempUrlGeneratorInterface $tempUrlGenerator;
public function __construct(
HttpClientInterface $client,
TempUrlGeneratorInterface $tempUrlGenerator
) {
$this->client = $client;
$this->tempUrlGenerator = $tempUrlGenerator;
}
public function read(StoredObject $document): string
{
try {
$response = $this
->client
->request(
Request::METHOD_GET,
$this
->tempUrlGenerator
->generate(
Request::METHOD_GET,
$document->getFilename()
)
->url
);
} catch (Throwable $e) {
throw StoredObjectManagerException::errorDuringHttpRequest($e);
}
if ($response->getStatusCode() !== Response::HTTP_OK) {
throw StoredObjectManagerException::invalidStatusCode($response->getStatusCode());
}
try {
$data = $response->getContent();
} catch (Throwable $e) {
throw StoredObjectManagerException::unableToGetResponseContent($e);
}
if (false === $this->hasKeysAndIv($document)) {
return $data;
}
$clearData = openssl_decrypt(
$data,
self::ALGORITHM,
// TODO: Why using this library and not use base64_decode() ?
Base64Url::decode($document->getKeyInfos()['k']),
OPENSSL_RAW_DATA,
pack('C*', ...$document->getIv())
);
if (false === $clearData) {
throw StoredObjectManagerException::unableToDecrypt(openssl_error_string());
}
return $clearData;
}
public function write(StoredObject $document, string $clearContent): void
{
$encryptedContent = $this->hasKeysAndIv($document)
? openssl_encrypt(
$clearContent,
self::ALGORITHM,
// TODO: Why using this library and not use base64_decode() ?
Base64Url::decode($document->getKeyInfos()['k']),
OPENSSL_RAW_DATA,
pack('C*', ...$document->getIv())
)
: $clearContent;
try {
$response = $this
->client
->request(
Request::METHOD_PUT,
$this
->tempUrlGenerator
->generate(
Request::METHOD_PUT,
$document->getFilename()
)
->url,
[
'body' => $encryptedContent,
]
);
} catch (TransportExceptionInterface $exception) {
throw StoredObjectManagerException::errorDuringHttpRequest($exception);
}
if ($response->getStatusCode() !== Response::HTTP_CREATED) {
throw StoredObjectManagerException::invalidStatusCode($response->getStatusCode());
}
}
private function hasKeysAndIv(StoredObject $storedObject): bool
{
return ([] !== $storedObject->getKeyInfos()) && ([] !== $storedObject->getIv());
}
}

View File

@ -0,0 +1,34 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Chill\DocStoreBundle\Service;
use Chill\DocStoreBundle\Entity\StoredObject;
interface StoredObjectManagerInterface
{
/**
* Get the content of a StoredObject.
*
* @param StoredObject $document The document.
*
* @return string The retrieved content in clear.
*/
public function read(StoredObject $document): string;
/**
* Set the content of a StoredObject.
*
* @param StoredObject $document The document.
* @param $clearContent The content to store in clear.
*/
public function write(StoredObject $document, string $clearContent): void;
}

View File

@ -0,0 +1,183 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Chill\DocStoreBundle\Tests;
use ChampsLibres\AsyncUploaderBundle\TempUrl\TempUrlGeneratorInterface;
use Chill\DocStoreBundle\Entity\StoredObject;
use Chill\DocStoreBundle\Exception\StoredObjectManagerException;
use Chill\DocStoreBundle\Service\StoredObjectManager;
use Chill\DocStoreBundle\Service\StoredObjectManagerInterface;
use Generator;
use PHPUnit\Framework\TestCase;
use stdClass;
use Symfony\Component\HttpClient\Exception\TransportException;
use Symfony\Component\HttpClient\MockHttpClient;
use Symfony\Component\HttpClient\Response\MockResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Contracts\HttpClient\HttpClientInterface;
/**
* @internal
*
* @covers \Chill\DocStoreBundle\Service\StoredObjectManager
*/
final class StoredObjectManagerTest extends TestCase
{
public function getDataProvider(): Generator
{
/* HAPPY SCENARIO */
// Encrypted object
yield [
(new StoredObject())
->setFilename('encrypted.txt')
->setKeyInfos(['k' => base64_encode('S9NIHMaFHOWzLPez3jZOIHBaNfBrMQUR5zvqBz6kme8')])
->setIv(unpack('C*', 'abcdefghijklmnop')),
hex2bin('741237d255fd4f7eddaaa9058912a84caae28a41b10b34d4e3e3abe41d3b9b47cb0dd8f22c3c883d4f0e9defa75ff662'), // Binary encoded string
'The quick brown fox jumps over the lazy dog', // clear
];
// Non-encrypted object
yield [
(new StoredObject())->setFilename('non-encrypted.txt'), // The StoredObject
'The quick brown fox jumps over the lazy dog', // Encrypted
'The quick brown fox jumps over the lazy dog', // Clear
];
/* UNHAPPY SCENARIO */
// Encrypted object with issue during HTTP communication
yield [
(new StoredObject())
->setFilename('error_during_http_request.txt')
->setKeyInfos(['k' => base64_encode('S9NIHMaFHOWzLPez3jZOIHBaNfBrMQUR5zvqBz6kme8')])
->setIv(unpack('C*', 'abcdefghijklmnop')),
hex2bin('741237d255fd4f7eddaaa9058912a84caae28a41b10b34d4e3e3abe41d3b9b47cb0dd8f22c3c883d4f0e9defa75ff662'), // Binary encoded string
'The quick brown fox jumps over the lazy dog', // clear
StoredObjectManagerException::class,
];
// Encrypted object with issue during HTTP communication: Invalid status code
yield [
(new StoredObject())
->setFilename('invalid_statuscode.txt')
->setKeyInfos(['k' => base64_encode('S9NIHMaFHOWzLPez3jZOIHBaNfBrMQUR5zvqBz6kme8')])
->setIv(unpack('C*', 'abcdefghijklmnop')),
hex2bin('741237d255fd4f7eddaaa9058912a84caae28a41b10b34d4e3e3abe41d3b9b47cb0dd8f22c3c883d4f0e9defa75ff662'), // Binary encoded string
'The quick brown fox jumps over the lazy dog', // clear
StoredObjectManagerException::class,
];
// Erroneous encrypted: Unable to decrypt exception.
yield [
(new StoredObject())
->setFilename('unable_to_decrypt.txt')
->setKeyInfos(['k' => base64_encode('WRONG_PASS_PHRASE')])
->setIv(unpack('C*', 'abcdefghijklmnop')),
'WRONG_ENCODED_VALUE', // Binary encoded string
'The quick brown fox jumps over the lazy dog', // clear
StoredObjectManagerException::class,
];
}
/**
* @dataProvider getDataProvider
*/
public function testRead(StoredObject $storedObject, string $encodedContent, string $clearContent, ?string $exceptionClass = null)
{
if (null !== $exceptionClass) {
$this->expectException($exceptionClass);
}
$storedObjectManager = $this->getSubject($storedObject, $encodedContent);
self::assertEquals($clearContent, $storedObjectManager->read($storedObject));
}
/**
* @dataProvider getDataProvider
*/
public function testWrite(StoredObject $storedObject, string $encodedContent, string $clearContent, ?string $exceptionClass = null)
{
if (null !== $exceptionClass) {
$this->expectException($exceptionClass);
}
$storedObjectManager = $this->getSubject($storedObject, $encodedContent);
$storedObjectManager->write($storedObject, $clearContent);
self::assertEquals($clearContent, $storedObjectManager->read($storedObject));
}
private function getHttpClient(string $encodedContent): HttpClientInterface
{
$callback = static function ($method, $url, $options) use ($encodedContent) {
if (Request::METHOD_GET === $method) {
switch ($url) {
case 'https://example.com/non-encrypted.txt':
case 'https://example.com/encrypted.txt':
return new MockResponse($encodedContent, ['http_code' => 200]);
case 'https://example.com/error_during_http_request.txt':
return new TransportException('error_during_http_request.txt');
case 'https://example.com/invalid_statuscode.txt':
return new MockResponse($encodedContent, ['http_code' => 404]);
}
}
if (Request::METHOD_PUT === $method) {
switch ($url) {
case 'https://example.com/non-encrypted.txt':
case 'https://example.com/encrypted.txt':
return new MockResponse($encodedContent, ['http_code' => 201]);
case 'https://example.com/error_during_http_request.txt':
throw new TransportException('error_during_http_request.txt');
case 'https://example.com/invalid_statuscode.txt':
return new MockResponse($encodedContent, ['http_code' => 404]);
}
}
return new MockResponse('Not found');
};
return new MockHttpClient($callback);
}
private function getSubject(StoredObject $storedObject, string $encodedContent): StoredObjectManagerInterface
{
return new StoredObjectManager(
$this->getHttpClient($encodedContent),
$this->getTempUrlGenerator($storedObject)
);
}
private function getTempUrlGenerator(StoredObject $storedObject): TempUrlGeneratorInterface
{
$response = new stdClass();
$response->url = $storedObject->getFilename();
$tempUrlGenerator = $this
->getMockBuilder(TempUrlGeneratorInterface::class)
->getMock();
$tempUrlGenerator
->method('generate')
->withAnyParameters()
->willReturn($response);
return $tempUrlGenerator;
}
}

View File

@ -8,7 +8,8 @@
} }
}, },
"require": { "require": {
"symfony/mime": "^4 || ^5" "symfony/mime": "^4 || ^5",
"symfony/http-foundation": "^4"
}, },
"license": "AGPL-3.0" "license": "AGPL-3.0"
} }

View File

@ -40,3 +40,8 @@ services:
tags: tags:
- { name: 'serializer.normalizer', priority: 16 } - { name: 'serializer.normalizer', priority: 16 }
Chill\DocStoreBundle\Service\:
autowire: true
autoconfigure: true
resource: '../Service/'

View File

@ -56,7 +56,7 @@ final class NotificationRepository implements ObjectRepository
if (null === $this->notificationByRelatedEntityAndUserAssociatedStatement) { if (null === $this->notificationByRelatedEntityAndUserAssociatedStatement) {
$sql = $sql =
'SELECT 'SELECT
SUM((EXISTS (SELECT 1 AS c FROM chill_main_notification_addresses_unread cmnau JOIN chill_main_notification cmn ON cmnau.notification_id = cmn.id WHERE user_id = :userid and cmnau.notification_id = cmn.id and cmn.sender_id IS NOT NULL))::int) AS unread, SUM((EXISTS (SELECT 1 AS c FROM chill_main_notification_addresses_unread cmnau WHERE user_id = :userid and cmnau.notification_id = cmn.id))::int) AS unread,
SUM((cmn.sender_id = :userid)::int) AS sent, SUM((cmn.sender_id = :userid)::int) AS sent,
COUNT(cmn.*) AS total COUNT(cmn.*) AS total
FROM chill_main_notification cmn FROM chill_main_notification cmn

View File

@ -16,6 +16,9 @@
// Chill forms // Chill forms
@import './scss/forms'; @import './scss/forms';
// Extend bootstrap accordion
@import './scss/accordion';
// Chill record_actions // Chill record_actions
@import './scss/record_actions'; @import './scss/record_actions';

View File

@ -0,0 +1,11 @@
.accordion {
// show a folded / label on accordion
button[aria-expanded="true"] > span.folded,
button[aria-expanded="false"] > span.unfolded { display: none; }
button[aria-expanded="false"] > span.folded,
button[aria-expanded="true"] > span.unfolded { display: inline; }
.accordion-item {
margin-bottom: 1rem;
}
}

View File

@ -128,6 +128,44 @@ class SocialAction
return $this; return $this;
} }
/**
* In a SocialIssues's collection, find the elements which are an ancestor of
* other elements.
*
* The difference of the given list (thus, the elements which are **not** kept
* in the returned collection) are the most-grand-child elements of the list.
*
* Removing those elements of the Collection (which is not done by this method)
* will ensure that only the most descendent elements are present in the collection,
* (any ancestor of another element are present).
*
* @param Collection|SocialAction[] $socialActions
*
* @return Collection|SocialAction[] a list with the elements of the given list which are parent of other elements in the given list
*/
public static function findAncestorSocialActions(Collection $socialActions): Collection
{
$ancestors = new ArrayCollection();
foreach ($socialActions as $candidateChild) {
if ($ancestors->contains($candidateChild)) {
continue;
}
foreach ($socialActions as $candidateParent) {
if ($ancestors->contains($candidateParent)) {
continue;
}
if ($candidateChild->isDescendantOf($candidateParent)) {
$ancestors->add($candidateParent);
}
}
}
return $ancestors;
}
/** /**
* @return Collection|self[] * @return Collection|self[]
*/ */
@ -169,7 +207,7 @@ class SocialAction
} }
/** /**
* @return Collection|self[] All the descendants with the current entity (this) * @return Collection|self[] All the descendants including the current entity (this)
*/ */
public function getDescendantsWithThis(): Collection public function getDescendantsWithThis(): Collection
{ {
@ -233,6 +271,23 @@ class SocialAction
return $this->getParent() instanceof self; return $this->getParent() instanceof self;
} }
/**
* Recursive method which return true if the current $action
* is a descendant of the $action given in parameter.
*/
public function isDescendantOf(SocialAction $action): bool
{
if (!$this->hasParent()) {
return false;
}
if ($this->getParent() === $action) {
return true;
}
return $this->getParent()->isDescendantOf($action);
}
public function removeChild(self $child): self public function removeChild(self $child): self
{ {
if ($this->children->removeElement($child)) { if ($this->children->removeElement($child)) {

View File

@ -202,7 +202,7 @@ class SocialIssue
} }
/** /**
* @return Collection|self[] All the descendants with the current entity (this) * @return Collection|self[] All the descendants including the current entity (this)
*/ */
public function getDescendantsWithThis(): Collection public function getDescendantsWithThis(): Collection
{ {

View File

@ -30,6 +30,7 @@ div.list-with-period {
// override wrap-list // override wrap-list
div.wrap-list.periods-list { div.wrap-list.periods-list {
padding-right: 1rem;
div.wl-row { div.wl-row {
flex-wrap: nowrap; flex-wrap: nowrap;
div.wl-col { div.wl-col {
@ -63,6 +64,7 @@ div.list-with-period {
} }
div.periods-list { div.periods-list {
padding-right: 1rem;
div.title { div.title {
text-align: right; text-align: right;
div.date {} div.date {}

View File

@ -5,9 +5,8 @@
</h2> </h2>
<div> <div>
<div class="mb-3 row"> <div class="mb-3 row">
<label class="col-form-label col-sm-4">{{ $t('startdate.date') }}</label> <div class="col-sm-12 date-update">
<div class="col-sm-8"> <input class="form-control" type="date" id="startDate" v-model="startDateInput">
<input class="form-control" type="date" v-model="startDate" @change="updateStartDate" />
</div> </div>
</div> </div>
</div> </div>
@ -17,30 +16,54 @@
<script> <script>
import { datetimeToISO, dateToISO, ISOToDate, ISOToDatetime} from 'ChillMainAssets/chill/js/date.js'; import { dateToISO, ISOToDatetime} from 'ChillMainAssets/chill/js/date.js';
import { mapState, mapGetters } from 'vuex'; import { mapState } from 'vuex';
export default { export default {
name: 'startDate', name: 'startDate',
methods: { data() {
updateStartDate(event) { return {
const date = event.target.value; lastRecordedDate: null
// console.log(date) }
this.$store.dispatch('updateStartDate', date)
.catch(({name, violations}) => {
if (name === 'ValidationException' || name === 'AccessException') {
violations.forEach((violation) => this.$toast.open({message: violation}));
} else {
this.$toast.open({message: 'An error occurred'})
}
});
},
}, },
computed: { computed: {
...mapState({ ...mapState({
startDate: state => dateToISO(ISOToDatetime(state.accompanyingCourse.openingDate.datetime)) startDate: state => dateToISO(ISOToDatetime(state.accompanyingCourse.openingDate.datetime))
}) }),
startDateInput: {
get() {
return this.startDate;
},
set(value) {
this.lastRecordedDate = value;
setTimeout(() => {
console.log('timeout finished')
if (this.lastRecordedDate === value) {
console.log('last recorded', this.lastRecordedDate, 'value', value)
this.$store.dispatch('updateStartDate', 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'})
}
})
}
}, 3000)
}
}
} }
} }
</script> </script>
<style lang="scss" scoped>
.date-update {
display: flex;
justify-content: space-between;
&-btn {
margin-left: 1rem;
}
}
</style>

View File

@ -153,7 +153,7 @@ const appMessages = {
}, },
startdate: { startdate: {
change: "Date d'ouverture", change: "Date d'ouverture",
date: "Date d'ouverture", // update: "La nouvelle date d'ouverture a été enregistrée"
}, },
// catch errors // catch errors
'Error while updating AccompanyingPeriod Course.': "Erreur du serveur lors de la mise à jour du parcours d'accompagnement.", 'Error while updating AccompanyingPeriod Course.': "Erreur du serveur lors de la mise à jour du parcours d'accompagnement.",

View File

@ -322,7 +322,6 @@ let initPromise = (root) => Promise.all([getScopesPromise(root), accompanyingCou
} }
}, },
updateStartDate(state, date) { updateStartDate(state, date) {
console.log('new state date', date)
state.accompanyingCourse.openingDate = date; state.accompanyingCourse.openingDate = date;
} }
}, },
@ -814,11 +813,9 @@ let initPromise = (root) => Promise.all([getScopesPromise(root), accompanyingCou
}) })
}, },
updateStartDate({commit}, payload) { updateStartDate({commit}, payload) {
console.log('payload', payload)
const date = ISOToDate(payload);
const url = `/api/1.0/person/accompanying-course/${id}.json`; const url = `/api/1.0/person/accompanying-course/${id}.json`;
const body = { type: "accompanying_period", openingDate: { datetime: datetimeToISO(date) }}; const date = payload === null || payload === '' ? null : { datetime: datetimeToISO(ISOToDate(payload)) }
console.log('body', body) const body = { type: "accompanying_period", openingDate: date};
return makeFetch('PATCH', url, body) return makeFetch('PATCH', url, body)
.then((response) => { .then((response) => {
commit('updateStartDate', response.openingDate); commit('updateStartDate', response.openingDate);

View File

@ -227,19 +227,18 @@ export default {
}, },
startDate: { startDate: {
get() { get() {
let d = this.$store.state.startDate; return this.$store.state.startDate;
return dateToISO(d);
}, },
set(value) { set(value) {
this.$store.commit('setStartDate', ISOToDate(value)); this.$store.commit('setStartDate', value);
} }
}, },
endDate: { endDate: {
get() { get() {
return dateToISO(this.$store.state.endDate); return this.$store.state.endDate;
}, },
set(value) { set(value) {
this.$store.commit('setEndDate', ISOToDate(value)); this.$store.commit('setEndDate', value);
} }
}, },
setSocialIssue: { setSocialIssue: {

View File

@ -1,6 +1,6 @@
import { createStore } from 'vuex'; import { createStore } from 'vuex';
import { datetimeToISO } from 'ChillMainAssets/chill/js/date.js'; import { datetimeToISO, dateToISO, ISOToDate, ISOToDatetime } from 'ChillMainAssets/chill/js/date.js';
import { findSocialActionsBySocialIssue } from 'ChillPersonAssets/vuejs/_api/SocialWorkSocialAction.js'; import { findSocialActionsBySocialIssue } from 'ChillPersonAssets/vuejs/_api/SocialWorkSocialAction.js';
// import { create } from 'ChillPersonAssets/vuejs/_api/AccompanyingCourseWork.js'; // import { create } from 'ChillPersonAssets/vuejs/_api/AccompanyingCourseWork.js';
import { makeFetch } from 'ChillMainAssets/lib/api/apiMethods'; import { makeFetch } from 'ChillMainAssets/lib/api/apiMethods';
@ -20,7 +20,7 @@ const store = createStore({
.map(p => p.person), .map(p => p.person),
personsReachables: window.accompanyingCourse.participations.filter(p => p.endDate == null) personsReachables: window.accompanyingCourse.participations.filter(p => p.endDate == null)
.map(p => p.person), .map(p => p.person),
startDate: new Date(), startDate: dateToISO(new Date()),
endDate: null, endDate: null,
isLoadingSocialActions: false, isLoadingSocialActions: false,
isPostingWork: false, isPostingWork: false,
@ -47,7 +47,7 @@ const store = createStore({
id: state.socialActionPicked.id id: state.socialActionPicked.id
}, },
startDate: { startDate: {
datetime: datetimeToISO(state.startDate) datetime: datetimeToISO(ISOToDate(state.startDate))
}, },
persons: [] persons: []
}; };
@ -61,7 +61,7 @@ const store = createStore({
if (null !== state.endDate) { if (null !== state.endDate) {
payload.endDate = { payload.endDate = {
datetime: datetimeToISO(state.endDate) datetime: datetimeToISO(ISOToDate(state.endDate))
}; };
} }
@ -111,6 +111,7 @@ const store = createStore({
state.startDate = date; state.startDate = date;
}, },
setEndDate(state, date) { setEndDate(state, date) {
console.log(date)
state.endDate = date; state.endDate = date;
}, },
setPersonsPickedIds(state, ids) { setPersonsPickedIds(state, ids) {

View File

@ -439,18 +439,18 @@ export default {
]), ]),
startDate: { startDate: {
get() { get() {
return dateToISO(this.$store.state.startDate); return this.$store.state.startDate;
}, },
set(v) { set(v) {
this.$store.commit('setStartDate', ISOToDate(v)); this.$store.commit('setStartDate', v);
} }
}, },
endDate: { endDate: {
get() { get() {
return dateToISO(this.$store.state.endDate); return this.$store.state.endDate;
}, },
set(v) { set(v) {
this.$store.commit('setEndDate', ISOToDate(v)); this.$store.commit('setEndDate', v);
} }
}, },
note: { note: {
@ -521,12 +521,12 @@ export default {
this.$store.commit('removeReferrer', u); this.$store.commit('removeReferrer', u);
}, },
goToGenerateWorkflow({link}) { goToGenerateWorkflow({link}) {
console.log('save before leave to generate workflow') // console.log('save before leave to generate workflow')
const callback = (data) => { const callback = (data) => {
window.location.assign(link); window.location.assign(link);
}; };
return this.$store.dispatch('submit', callback) return this.$store.dispatch('submit', callback)
.catch(e => { console.log(e); throw e; }); .catch(e => { console.log(e); throw e; });
}, },
submit() { submit() {

View File

@ -298,38 +298,39 @@ export default {
} }
}, },
computed: { computed: {
...mapState([ ...mapState([
'isPosting' 'isPosting'
]), ]),
getTemplatesAvailables() { getTemplatesAvailables() {
return this.$store.getters.getTemplatesAvailablesForEvaluation(this.evaluation.evaluation); return this.$store.getters.getTemplatesAvailablesForEvaluation(this.evaluation.evaluation);
}, },
canGenerate() { canGenerate() {
return !this.$store.state.isPosting && this.template !== null; return !this.$store.state.isPosting && this.template !== null;
}, },
startDate: { startDate: {
get() { get() {
return dateToISO(this.evaluation.startDate); console.log('evaluation', this.evaluation);
}, return this.evaluation.startDate;
set(v) { },
this.$store.commit('setEvaluationStartDate', { key: this.evaluation.key, date: ISOToDate(v) }); set(v) {
} this.$store.commit('setEvaluationStartDate', { key: this.evaluation.key, date: v });
}
}, },
endDate: { endDate: {
get() { get() {
return dateToISO(this.evaluation.endDate); return this.evaluation.endDate;
}, },
set(v) { set(v) {
this.$store.commit('setEvaluationEndDate', { key: this.evaluation.key, date: ISOToDate(v) }); this.$store.commit('setEvaluationEndDate', { key: this.evaluation.key, date: v });
} }
}, },
maxDate: { maxDate: {
get() { get() {
return dateToISO(this.evaluation.maxDate); return this.evaluation.maxDate;
}, },
set(v) { set(v) {
this.$store.commit('setEvaluationMaxDate', { key: this.evaluation.key, date: ISOToDate(v) }); this.$store.commit('setEvaluationMaxDate', { key: this.evaluation.key, date: v });
} }
}, },
warningInterval: { warningInterval: {
get() { return this.evaluation.warningInterval; }, get() { return this.evaluation.warningInterval; },
@ -344,7 +345,7 @@ export default {
ISOToDatetime, ISOToDatetime,
canEditDocument(document) { canEditDocument(document) {
return 'storedObject' in document ? return 'storedObject' in document ?
this.mime.includes(document.storedObject.type) && document.storedObject.keyInfos.length === 0 : false; this.mime.includes(document.storedObject.type) : false;
}, },
listAllStatus() { listAllStatus() {
console.log('load all status'); console.log('load all status');
@ -360,16 +361,16 @@ export default {
}, },
buildEditLink(storedObject) { buildEditLink(storedObject) {
return `/wopi/edit/${storedObject.uuid}?returnPath=` + encodeURIComponent( return `/wopi/edit/${storedObject.uuid}?returnPath=` + encodeURIComponent(
window.location.pathname + window.location.search + window.location.hash); window.location.pathname + window.location.search + window.location.hash);
}, },
submitBeforeGenerate({template}) { submitBeforeGenerate({template}) {
const callback = (data) => { const callback = (data) => {
let evaluationId = data.accompanyingPeriodWorkEvaluations.find(e => e.key === this.evaluation.key).id; let evaluationId = data.accompanyingPeriodWorkEvaluations.find(e => e.key === this.evaluation.key).id;
window.location.assign(buildLink(template, evaluationId, 'Chill\\PersonBundle\\Entity\\AccompanyingPeriod\\AccompanyingPeriodWorkEvaluation')); window.location.assign(buildLink(template, evaluationId, 'Chill\\PersonBundle\\Entity\\AccompanyingPeriod\\AccompanyingPeriodWorkEvaluation'));
}; };
return this.$store.dispatch('submit', callback).catch(e => { console.log(e); throw e; }); return this.$store.dispatch('submit', callback).catch(e => { console.log(e); throw e; });
}, },
onInputDocumentTitle(event) { onInputDocumentTitle(event) {
const id = Number(event.target.id); const id = Number(event.target.id);
@ -395,20 +396,20 @@ export default {
}, },
removeDocument(document) { removeDocument(document) {
if (window.confirm("Êtes-vous sûr·e de vouloir supprimer le document qui a pour titre \"" + document.title +"\" ?")) { if (window.confirm("Êtes-vous sûr·e de vouloir supprimer le document qui a pour titre \"" + document.title +"\" ?")) {
this.$store.commit('removeDocument', {key: this.evaluation.key, document: document}); this.$store.commit('removeDocument', {key: this.evaluation.key, document: document});
} }
}, },
goToGenerateWorkflowEvaluationDocument({event, link, workflowName, payload}) { goToGenerateWorkflowEvaluationDocument({event, link, workflowName, payload}) {
const callback = (data) => { const callback = (data) => {
let evaluation = data.accompanyingPeriodWorkEvaluations.find(e => e.key === this.evaluation.key); let evaluation = data.accompanyingPeriodWorkEvaluations.find(e => e.key === this.evaluation.key);
let updatedDocument = evaluation.documents.find(d => d.key === payload.doc.key); let updatedDocument = evaluation.documents.find(d => d.key === payload.doc.key);
window.location.assign(buildLinkCreate(workflowName, window.location.assign(buildLinkCreate(workflowName,
'Chill\\PersonBundle\\Entity\\AccompanyingPeriod\\AccompanyingPeriodWorkEvaluationDocument', updatedDocument.id)); 'Chill\\PersonBundle\\Entity\\AccompanyingPeriod\\AccompanyingPeriodWorkEvaluationDocument', updatedDocument.id));
}; };
return this.$store.dispatch('submit', callback) return this.$store.dispatch('submit', callback)
.catch(e => { console.log(e); throw e; }); .catch(e => { console.log(e); throw e; });
}, },
}, },
} }
</script> </script>

View File

@ -1,5 +1,5 @@
import { createStore } from 'vuex'; import { createStore } from 'vuex';
import { datetimeToISO, ISOToDatetime, intervalDaysToISO, intervalISOToDays } from 'ChillMainAssets/chill/js/date.js'; import { dateToISO, ISOToDate, datetimeToISO, ISOToDatetime, intervalDaysToISO, intervalISOToDays } from 'ChillMainAssets/chill/js/date.js';
import { findSocialActionsBySocialIssue } from 'ChillPersonAssets/vuejs/_api/SocialWorkSocialAction.js'; import { findSocialActionsBySocialIssue } from 'ChillPersonAssets/vuejs/_api/SocialWorkSocialAction.js';
import { create } from 'ChillPersonAssets/vuejs/_api/AccompanyingCourseWork.js'; import { create } from 'ChillPersonAssets/vuejs/_api/AccompanyingCourseWork.js';
import { fetchResults, makeFetch } from 'ChillMainAssets/lib/api/apiMethods.js'; import { fetchResults, makeFetch } from 'ChillMainAssets/lib/api/apiMethods.js';
@ -13,9 +13,9 @@ const store = createStore({
state: { state: {
work: window.accompanyingCourseWork, work: window.accompanyingCourseWork,
startDate: window.accompanyingCourseWork.startDate !== null ? startDate: window.accompanyingCourseWork.startDate !== null ?
ISOToDatetime(window.accompanyingCourseWork.startDate.datetime) : null, dateToISO(new Date(window.accompanyingCourseWork.startDate.datetime)) : null,
endDate: window.accompanyingCourseWork.endDate !== null ? endDate: window.accompanyingCourseWork.endDate !== null ?
ISOToDatetime(window.accompanyingCourseWork.endDate.datetime) : null, dateToISO(new Date(window.accompanyingCourseWork.endDate.datetime)) : null,
note: window.accompanyingCourseWork.note, note: window.accompanyingCourseWork.note,
goalsPicked: window.accompanyingCourseWork.goals, goalsPicked: window.accompanyingCourseWork.goals,
goalsForAction: [], goalsForAction: [],
@ -72,11 +72,11 @@ const store = createStore({
return { return {
type: 'accompanying_period_work', type: 'accompanying_period_work',
id: state.work.id, id: state.work.id,
startDate: state.startDate === null ? null : { startDate: state.startDate === null || state.startDate === '' ? null : {
datetime: datetimeToISO(state.startDate) datetime: datetimeToISO(ISOToDate(state.startDate))
}, },
endDate: state.endDate === null ? null : { endDate: state.endDate === null || state.endDate === '' ? null : {
datetime: datetimeToISO(state.endDate) datetime: datetimeToISO(ISOToDate(state.endDate))
}, },
note: state.note, note: state.note,
persons: state.personsPicked.map(p => ({id: p.id, type: p.type})), persons: state.personsPicked.map(p => ({id: p.id, type: p.type})),
@ -110,9 +110,9 @@ const store = createStore({
id: e.evaluation.id, id: e.evaluation.id,
type: e.evaluation.type type: e.evaluation.type
}, },
startDate: e.startDate !== null ? { datetime: datetimeToISO(e.startDate) } : null, startDate: e.startDate === null || e.startDate === '' ? null : { datetime: datetimeToISO(ISOToDate(e.startDate)) },
endDate: e.endDate !== null ? { datetime: datetimeToISO(e.endDate) } : null, endDate: e.endDate === null || e.endDate === '' ? null : { datetime: datetimeToISO(ISOToDate(e.endDate)) },
maxDate: e.maxDate !== null ? { datetime: datetimeToISO(e.maxDate) } : null, maxDate: e.maxDate === null || e.maxDate === '' ? null : { datetime: datetimeToISO(ISOToDate(e.maxDate)) },
warningInterval: intervalDaysToISO(e.warningInterval), warningInterval: intervalDaysToISO(e.warningInterval),
comment: e.comment, comment: e.comment,
documents: e.documents documents: e.documents
@ -132,9 +132,9 @@ const store = createStore({
var k = Object.assign(e, { var k = Object.assign(e, {
key: index, key: index,
editEvaluation: false, editEvaluation: false,
startDate: e.startDate !== null ? ISOToDatetime(e.startDate.datetime) : null, startDate: e.startDate !== null ? dateToISO(new Date(e.startDate.datetime)) : null,
endDate: e.endDate !== null ? ISOToDatetime(e.endDate.datetime) : null, endDate: e.endDate !== null ? dateToISO(new Date(e.endDate.datetime)) : null,
maxDate: e.maxDate !== null ? ISOToDatetime(e.maxDate.datetime) : null, maxDate: e.maxDate !== null ? dateToISO(new Date(e.maxDate.datetime)) : null,
warningInterval: e.warningInterval !== null ? intervalISOToDays(e.warningInterval) : null, warningInterval: e.warningInterval !== null ? intervalISOToDays(e.warningInterval) : null,
documents: e.documents.map((d, docIndex) => { documents: e.documents.map((d, docIndex) => {
return Object.assign(d, { return Object.assign(d, {
@ -244,7 +244,7 @@ const store = createStore({
type: "accompanying_period_work_evaluation", type: "accompanying_period_work_evaluation",
key: state.evaluationsPicked.length + 1, key: state.evaluationsPicked.length + 1,
evaluation: evaluation, evaluation: evaluation,
startDate: new Date(), startDate: dateToISO(new Date()),
endDate: null, endDate: null,
maxDate: null, maxDate: null,
warningInterval: null, warningInterval: null,
@ -264,6 +264,7 @@ const store = createStore({
.startDate = date; .startDate = date;
}, },
setEvaluationEndDate(state, {key, date}) { setEvaluationEndDate(state, {key, date}) {
console.log('commit date', date)
state.evaluationsPicked.find(e => e.key === key) state.evaluationsPicked.find(e => e.key === key)
.endDate = date; .endDate = date;
}, },

View File

@ -66,18 +66,19 @@ export default {
}, },
startDate: { startDate: {
get() { get() {
return [ return this.$store.state.startDate;
this.$store.state.startDate.getFullYear(), // return [
(this.$store.state.startDate.getMonth() + 1).toString().padStart(2, '0'), // this.$store.state.startDate.getFullYear(),
this.$store.state.startDate.getDate().toString().padStart(2, '0') // (this.$store.state.startDate.getMonth() + 1).toString().padStart(2, '0'),
].join('-'); // this.$store.state.startDate.getDate().toString().padStart(2, '0')
// ].join('-');
}, },
set(value) { set(value) {
let // let
[year, month, day] = value.split('-'), // [year, month, day] = value.split('-'),
dValue = new Date(year, month-1, day); // dValue = new Date(year, month-1, day);
this.$store.dispatch('setStartDate', dValue); this.$store.dispatch('setStartDate', value);
} }
} }
} }

View File

@ -2,7 +2,7 @@ import { createStore } from 'vuex';
import { householdMove, fetchHouseholdSuggestionByAccompanyingPeriod, fetchAddressSuggestionByPerson} from './../api.js'; import { householdMove, fetchHouseholdSuggestionByAccompanyingPeriod, fetchAddressSuggestionByPerson} from './../api.js';
import { fetchResults } from 'ChillMainAssets/lib/api/apiMethods.js' import { fetchResults } from 'ChillMainAssets/lib/api/apiMethods.js'
import { fetchHouseholdByAddressReference } from 'ChillPersonAssets/lib/household.js'; import { fetchHouseholdByAddressReference } from 'ChillPersonAssets/lib/household.js';
import { datetimeToISO } from 'ChillMainAssets/chill/js/date.js'; import { datetimeToISO, dateToISO, ISOToDate } from 'ChillMainAssets/chill/js/date.js';
const debug = process.env.NODE_ENV !== 'production'; const debug = process.env.NODE_ENV !== 'production';
@ -30,7 +30,7 @@ const store = createStore({
} }
return 0; return 0;
}), }),
startDate: new Date(), startDate: dateToISO(new Date()),
/** /**
* Indicates if the destination is: * Indicates if the destination is:
* *
@ -278,7 +278,7 @@ const store = createStore({
type: conc.person.type type: conc.person.type
}, },
start_date: { start_date: {
datetime: datetimeToISO(state.startDate) datetime: state.startDate === null || state.startDate === '' ? null : datetimeToISO(ISOToDate(state.startDate))
} }
}; };
@ -302,7 +302,7 @@ const store = createStore({
}, },
number_of_children: state.numberOfChildren, number_of_children: state.numberOfChildren,
start_date: { start_date: {
datetime: datetimeToISO(state.startDate), datetime: datetimeToISO(ISOToDate(state.startDate)),
}, },
}; };
} }

View File

@ -25,22 +25,6 @@
<div class="item-row separator"> <div class="item-row separator">
<div class="wrap-list"> <div class="wrap-list">
{% if w.createdBy %}
<div class="wl-row">
<div class="wl-col title">
<h3>{{ 'Referrers'|trans }}</h3>
</div>
<div class="wl-col list">
<p class="wl-item">
{% for u in w.referrers %}
{{ u|chill_entity_render_box }}
{% if not loop.last %}, {% endif %}
{% endfor %}
</p>
</div>
</div>
{% endif %}
{%- if w.persons -%} {%- if w.persons -%}
<div class="wl-row"> <div class="wl-row">
<div class="wl-col title"> <div class="wl-col title">
@ -78,6 +62,22 @@
</div> </div>
{% endif %} {% endif %}
{%- if w.referrers -%}
<div class="wl-row">
<div class="wl-col title">
<h3>{{ 'Referrers'|trans }}</h3>
</div>
<div class="wl-col list">
{% for u in w.referrers %}
<span class="wl-item">
{{ u|chill_entity_render_box }}
{% if not loop.last %}, {% endif %}
</span>
{% endfor %}
</div>
</div>
{% endif %}
{%- if w.socialAction.issue -%} {%- if w.socialAction.issue -%}
<div class="wl-row"> <div class="wl-row">
<div class="wl-col title"> <div class="wl-col title">

View File

@ -28,6 +28,15 @@
<span class="badge-thirdparty">{{ w.handlingThierParty|chill_entity_render_box }}</span> <span class="badge-thirdparty">{{ w.handlingThierParty|chill_entity_render_box }}</span>
</li> </li>
{% endif %} {% endif %}
{% if w.referrers %}
<li>
<span class="item-key">{{ 'Referrers'|trans ~ ' : ' }}</span>
{% for u in w.referrers %}
<span class="badge-user">{{ u|chill_entity_render_box }}</span>
{% if not loop.last %}, {% endif %}
{% endfor %}
</li>
{% endif %}
<li class="associated-persons"> <li class="associated-persons">
<span class="item-key">{{ 'Participants'|trans ~ ' : ' }}</span> <span class="item-key">{{ 'Participants'|trans ~ ' : ' }}</span>
{% for p in w.persons %} {% for p in w.persons %}

View File

@ -20,7 +20,7 @@
{% elseif period.step == 'CONFIRMED' %} {% elseif period.step == 'CONFIRMED' %}
<span class="badge bg-primary">{{- 'Confirmed'|trans|upper -}}</span> <span class="badge bg-primary">{{- 'Confirmed'|trans|upper -}}</span>
{% else %} {% else %}
<span class="badge bg-primary">{{- 'Closed'|trans|upper -}}</span> <span class="badge bg-danger">{{- 'Closed'|trans|upper -}}</span>
{% endif %} {% endif %}
</div> </div>
</div> </div>

View File

@ -10,12 +10,6 @@
{% include 'ChillPersonBundle:AccompanyingPeriod:_list.html.twig' %} {% include 'ChillPersonBundle:AccompanyingPeriod:_list.html.twig' %}
{% if accompanying_periods_old|length > 0 %} {% if accompanying_periods_old|length > 0 %}
<style>
button[aria-expanded="true"] > span.folded,
button[aria-expanded="false"] > span.unfolded { display: none; }
button[aria-expanded="false"] > span.folded,
button[aria-expanded="true"] > span.unfolded { display: inline; }
</style>
<div class="accordion" id="nonCurrent"> <div class="accordion" id="nonCurrent">
<div class="accordion-item"> <div class="accordion-item">
<h2 class="accordion-header" id="heading_{{ household.id }}"> <h2 class="accordion-header" id="heading_{{ household.id }}">

View File

@ -191,12 +191,6 @@
{% endif %} {% endif %}
{% if old_members|length > 0 %} {% if old_members|length > 0 %}
<style>
button[aria-expanded="true"] > span.folded,
button[aria-expanded="false"] > span.unfolded { display: none; }
button[aria-expanded="false"] > span.folded,
button[aria-expanded="true"] > span.unfolded { display: inline; }
</style>
<div class="accordion" id="nonCurrent"> <div class="accordion" id="nonCurrent">
<div class="accordion-item"> <div class="accordion-item">
<h2 class="accordion-header" id="heading_{{ p == '_none' ? '_none' : p.id }}"> <h2 class="accordion-header" id="heading_{{ p == '_none' ? '_none' : p.id }}">

View File

@ -10,6 +10,157 @@
</li> </li>
{% endmacro %} {% endmacro %}
{% macro accompanying_period(acp, person) %}
{% set app = person.findParticipationForPeriod(acp) %}
<div class="item-row separator">
<div class="wrap-list periods-list">
<div class="wl-row">
<div class="wl-col title">
<h3 class="courseid mb-2">
<i class="fa fa-random fa-fw"></i>
{{ 'Course number'|trans }} {{ acp.id }}
</h3>
</div>
<div class="wl-col list">
<div class="d-flex flex-column justify-content-center">
{% if app != null %}
<div class="date">
{{ 'Since %date%'|trans({'%date%': app.startDate|format_date('medium') }) }}
</div>
{% endif %}
{% set notif_counter = chill_count_notifications('Chill\\PersonBundle\\Entity\\AccompanyingPeriod', acp.id) %}
{% if notif_counter.total > 0 %}
{{ chill_counter_notifications('Chill\\PersonBundle\\Entity\\AccompanyingPeriod', acp.id) }}
{% endif %}
</div>
<div class="ms-auto">
{% if acp.requestoranonymous == false and acp.requestorPerson is same as(person) %}
<span class="as-requestor badge bg-info" title="{{ 'Requestor'|trans|e('html_attr') }}">
{{ 'Requestor'|trans({'gender': person.gender}) }}
</span>
{% endif %}
{% if acp.emergency %}
<span class="badge rounded-pill bg-danger">{{- 'Emergency'|trans|upper -}}</span>
{% endif %}
{% if acp.confidential %}
<span class="badge rounded-pill bg-confidential">{{- 'Confidential'|trans|upper -}}</span>
{% endif %}
{% if acp.step == 'DRAFT' %}
<span class="badge bg-secondary" style="font-size: 85%;" title="{{ 'course.draft'|trans }}">{{ 'course.draft'|trans }}</span>
{% endif %}
{% if acp.step == 'CLOSED' %}
<span class="badge bg-danger" style="font-size: 85%;" title="{{ 'course.closed'|trans }}">{{ 'course.closed'|trans }}</span>
{% endif %}
</div>
</div>
</div>
{% if acp.user is not null %}
<div class="wl-row">
<div class="wl-col title">
<h3 class="referrer">{{ 'Referrer'|trans }}</h3>
</div>
<div class="wl-col list">
<div class="user">
{{ acp.user|chill_entity_render_box }}
</div>
</div>
</div>
{% endif %}
{% if acp.socialIssues|length > 0 %}
<div class="wl-row">
<div class="wl-col title">
<h3>{{ 'Social issues'|trans }}</h3>
</div>
<div class="wl-col list">
{% for issue in acp.socialIssues %}
{{ issue|chill_entity_render_box }}
{% endfor %}
</div>
</div>
{% endif %}
{% if acp.currentParticipations|length > 1 %}
<div class="wl-row">
<div class="wl-col title">
<h3 class="participants">
{{ 'Participants'|trans }}
</h3>
</div>
<div class="wl-col list">
{% set participating = false %}
{% for part in acp.currentParticipations %}
{% if part.person.id != person.id %}
{% include '@ChillMain/OnTheFly/_insert_vue_onthefly.html.twig' with {
targetEntity: { name: 'person', id: part.person.id },
action: 'show',
displayBadge: true,
buttonText: part.person|chill_entity_render_string,
isDead: part.person.deathdate is not null
} %}
{% else %}
{% set participating = true %}
{% endif %}
{% endfor %}
{% if participating %}
{{ 'person.and_himself'|trans({'gender': person.gender}) }}
{% endif %}
</div>
</div>
{% endif %}
{% if acp.requestoranonymous == false %}
{% if (acp.requestorPerson is not null and acp.requestorPerson.id != person.id) or acp.requestorThirdParty is not null %}
<div class="wl-row">
<div class="wl-col title">
<h3>
{% if acp.requestorPerson is not null %}
{{ 'Requestor'|trans({'gender': acp.requestorPerson.gender}) }}
{% else %}
{{ 'Requestor'|trans({'gender': 'other'})}}
{% endif %}
</h3>
</div>
<div class="wl-col list">
{% if acp.requestorThirdParty is not null %}
{% include '@ChillMain/OnTheFly/_insert_vue_onthefly.html.twig' with {
targetEntity: { name: 'thirdparty', id: acp.requestorThirdParty.id },
action: 'show',
displayBadge: true,
buttonText: acp.requestorThirdParty|chill_entity_render_string
} %}
{% else %}
{% include '@ChillMain/OnTheFly/_insert_vue_onthefly.html.twig' with {
targetEntity: { name: 'person', id: acp.requestorPerson.id },
action: 'show',
displayBadge: true,
buttonText: acp.requestorPerson|chill_entity_render_string,
isDead: acp.requestorPerson.deathdate is not null
} %}
{% endif %}
</div>
</div>
{% endif %}
{% endif %}
<ul class="record_actions record_actions_column">
<li>
<a href="{{ path('chill_person_accompanying_course_index', { 'accompanying_period_id': acp.id }) }}"
class="btn btn-sm btn-outline-primary" title="{{ 'See accompanying period'|trans }}">
<i class="fa fa-random fa-fw"></i>
</a>
</li>
</ul>
</div>
</div>
{% endmacro %}
<div class="list-with-period"> <div class="list-with-period">
<h2>{{ title|default('Person search results')|trans }}</h2> <h2>{{ title|default('Person search results')|trans }}</h2>
@ -66,167 +217,53 @@
{#- 'acps' is for AcCompanyingPeriodS #} {#- 'acps' is for AcCompanyingPeriodS #}
{%- set acps = [] %} {%- set acps = [] %}
{%- set acpsClosed = [] %}
{%- for acp in person.accompanyingPeriodInvolved %} {%- for acp in person.accompanyingPeriodInvolved %}
{%- if is_granted('CHILL_PERSON_ACCOMPANYING_PERIOD_SEE', acp) %} {%- if is_granted('CHILL_PERSON_ACCOMPANYING_PERIOD_SEE', acp) %}
{%- set acps = acps|merge([acp]) %} {% if acp.step == 'CLOSED' %}
{%- set acpsClosed = acpsClosed|merge([acp]) %}
{% else %}
{%- set acps = acps|merge([acp]) %}
{% endif %}
{%- endif %} {%- endif %}
{%- endfor %} {%- endfor %}
{# add as requestor #} {# add as requestor #}
{% if acps|length > 0 %} {% if acps|length > 0 %}
{% for acp in acps %} {% for acp in acps %}
{% set app = person.findParticipationForPeriod(acp) %} {{ _self.accompanying_period(acp, person) }}
<div class="item-row separator">
<div class="wrap-list periods-list">
<div class="wl-row">
<div class="wl-col title">
<h3 class="courseid mb-2">
<i class="fa fa-random fa-fw"></i>
{{ 'Course number'|trans }} {{ acp.id }}
</h3>
</div>
<div class="wl-col list">
<div class="d-flex flex-column justify-content-center">
{% if app != null %}
<div class="date">
{{ 'Since %date%'|trans({'%date%': app.startDate|format_date('medium') }) }}
</div>
{% endif %}
{% set notif_counter = chill_count_notifications('Chill\\PersonBundle\\Entity\\AccompanyingPeriod', acp.id) %}
{% if notif_counter.total > 0 %}
{{ chill_counter_notifications('Chill\\PersonBundle\\Entity\\AccompanyingPeriod', acp.id) }}
{% endif %}
</div>
<div class="ms-auto">
{% if acp.requestoranonymous == false and acp.requestorPerson is same as(person) %}
<span class="as-requestor badge bg-info" title="{{ 'Requestor'|trans|e('html_attr') }}">
{{ 'Requestor'|trans({'gender': person.gender}) }}
</span>
{% endif %}
{% if acp.emergency %}
<span class="badge rounded-pill bg-danger">{{- 'Emergency'|trans|upper -}}</span>
{% endif %}
{% if acp.confidential %}
<span class="badge rounded-pill bg-confidential">{{- 'Confidential'|trans|upper -}}</span>
{% endif %}
{% if acp.step == 'DRAFT' %}
<span class="badge bg-secondary" style="font-size: 85%;" title="{{ 'course.draft'|trans }}">{{ 'course.draft'|trans }}</span>
{% endif %}
{% if acp.step == 'CLOSED' %}
<span class="badge bg-secondary" style="font-size: 85%;" title="{{ 'course.closed'|trans }}">{{ 'course.closed'|trans }}</span>
{% endif %}
</div>
</div>
</div>
{% if acp.user is not null %}
<div class="wl-row">
<div class="wl-col title">
<h3 class="referrer">{{ 'Referrer'|trans }}</h3>
</div>
<div class="wl-col list">
<div class="user">
{{ acp.user|chill_entity_render_box }}
</div>
</div>
</div>
{% endif %}
{% if acp.socialIssues|length > 0 %}
<div class="wl-row">
<div class="wl-col title">
<h3>{{ 'Social issues'|trans }}</h3>
</div>
<div class="wl-col list">
{% for issue in acp.socialIssues %}
{{ issue|chill_entity_render_box }}
{% endfor %}
</div>
</div>
{% endif %}
{% if acp.currentParticipations|length > 1 %}
<div class="wl-row">
<div class="wl-col title">
<h3 class="participants">
{{ 'Participants'|trans }}
</h3>
</div>
<div class="wl-col list">
{% set participating = false %}
{% for part in acp.currentParticipations %}
{% if part.person.id != person.id %}
{% include '@ChillMain/OnTheFly/_insert_vue_onthefly.html.twig' with {
targetEntity: { name: 'person', id: part.person.id },
action: 'show',
displayBadge: true,
buttonText: part.person|chill_entity_render_string,
isDead: part.person.deathdate is not null
} %}
{% else %}
{% set participating = true %}
{% endif %}
{% endfor %}
{% if participating %}
{{ 'person.and_himself'|trans({'gender': person.gender}) }}
{% endif %}
</div>
</div>
{% endif %}
{% if acp.requestoranonymous == false %}
{% if (acp.requestorPerson is not null and acp.requestorPerson.id != person.id) or acp.requestorThirdParty is not null %}
<div class="wl-row">
<div class="wl-col title">
<h3>
{% if acp.requestorPerson is not null %}
{{ 'Requestor'|trans({'gender': acp.requestorPerson.gender}) }}
{% else %}
{{ 'Requestor'|trans({'gender': 'other'})}}
{% endif %}
</h3>
</div>
<div class="wl-col list">
{% if acp.requestorThirdParty is not null %}
{% include '@ChillMain/OnTheFly/_insert_vue_onthefly.html.twig' with {
targetEntity: { name: 'thirdparty', id: acp.requestorThirdParty.id },
action: 'show',
displayBadge: true,
buttonText: acp.requestorThirdParty|chill_entity_render_string
} %}
{% else %}
{% include '@ChillMain/OnTheFly/_insert_vue_onthefly.html.twig' with {
targetEntity: { name: 'person', id: acp.requestorPerson.id },
action: 'show',
displayBadge: true,
buttonText: acp.requestorPerson|chill_entity_render_string,
isDead: acp.requestorPerson.deathdate is not null
} %}
{% endif %}
</div>
</div>
{% endif %}
{% endif %}
<ul class="record_actions record_actions_column">
<li>
<a href="{{ path('chill_person_accompanying_course_index', { 'accompanying_period_id': acp.id }) }}"
class="btn btn-sm btn-outline-primary" title="{{ 'See accompanying period'|trans }}">
<i class="fa fa-random fa-fw"></i>
</a>
</li>
</ul>
</div>
</div>
{% endfor %} {% endfor %}
{% endif %} {% endif %}
{% if acpsClosed|length > 0 %}
<div class="accordion" id="member_{{ person.id }}">
<div class="accordion-item">
<h2 class="accordion-header" id="heading_{{ person.id }}">
<button
class="accordion-button collapsed"
type="button"
data-bs-toggle="collapse"
data-bs-target="#collapse_{{ person.id }}"
aria-expanded="false"
aria-controls="collapse_{{ person.id }}">
<span class="folded">{{ 'periods.show closed periods'|trans({ 'nb_items': acpsClosed|length }) }}</span>
<span class="unfolded text-secondary">{{ 'periods.hide closed periods'|trans({ 'nb_items': acpsClosed|length }) }}</span>
</button>
</h2>
<div id="collapse_{{ person.id }}"
class="accordion-collapse collapse"
aria-labelledby="heading_{{ person.id }}"
data-bs-parent="#nonCurrent">
{% for acp in acpsClosed %}
{{ _self.accompanying_period(acp, person) }}
{% endfor %}
</div>
</div>
</div>
{% endif %}
</div> </div>
{% endfor %} {% endfor %}
</div> </div>

View File

@ -40,6 +40,7 @@ class SocialActionNormalizer implements NormalizerAwareInterface, NormalizerInte
'desactivationDate' => $this->normalizer->normalize($socialAction->getDesactivationDate(), $format, $context), 'desactivationDate' => $this->normalizer->normalize($socialAction->getDesactivationDate(), $format, $context),
'title' => $socialAction->getTitle(), 'title' => $socialAction->getTitle(),
'issue' => $this->normalizer->normalize($socialAction->getIssue(), $format, $context), 'issue' => $this->normalizer->normalize($socialAction->getIssue(), $format, $context),
'ordering' => $socialAction->getOrdering(),
]; ];
case 'docgen': case 'docgen':

View File

@ -114,3 +114,19 @@ household_composition:
few {# enfants dans le ménage} few {# enfants dans le ménage}
other {# enfants dans le ménage} other {# enfants dans le ménage}
} }
periods:
show closed periods: >-
{nb_items, plural,
=0 {Aucun parcours clôturé}
one {Montrer un parcours clôturé}
many {Montrer # parcours clôturés}
other {Montrer # parcours clôturés}
}
hide closed periods: >-
{nb_items, plural,
=0 {Aucun parcours clôturé}
one {Masquer un parcours clôturé}
many {Masquer # parcours clôturés}
other {Masquer # parcours clôturés}
}

View File

@ -214,7 +214,7 @@ No requestor: Pas de demandeur
No resources: "Pas d'interlocuteurs privilégiés" No resources: "Pas d'interlocuteurs privilégiés"
Persons associated: Usagers concernés Persons associated: Usagers concernés
Referrer: Référent Referrer: Référent
Referrers: Référents Referrers: Agents traitants
Some peoples does not belong to any household currently. Add them to an household soon: Certaines personnes n'appartiennent à aucun ménage actuellement. Renseignez leur ménage dès que possible. Some peoples does not belong to any household currently. Add them to an household soon: Certaines personnes n'appartiennent à aucun ménage actuellement. Renseignez leur ménage dès que possible.
Add to household now: Ajouter à un ménage Add to household now: Ajouter à un ménage
Any resource for this accompanying course: Aucun interlocuteur privilégié pour ce parcours Any resource for this accompanying course: Aucun interlocuteur privilégié pour ce parcours
@ -465,6 +465,9 @@ fix it: Compléter
accompanying_course: accompanying_course:
administrative_location: Localisation administrative administrative_location: Localisation administrative
comment is pinned: Le commentaire est épinglé comment is pinned: Le commentaire est épinglé
show: Montrer
hide: Masquer
closed periods: parcours clôturer
# Accompanying Course comments # Accompanying Course comments
Accompanying Course Comment: Commentaire Accompanying Course Comment: Commentaire

View File

@ -11,14 +11,12 @@ declare(strict_types=1);
namespace Chill\WopiBundle\DependencyInjection; namespace Chill\WopiBundle\DependencyInjection;
use Ramsey\Uuid\Doctrine\UuidType;
use Symfony\Component\Config\FileLocator; use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
use Symfony\Component\DependencyInjection\Loader\PhpFileLoader; use Symfony\Component\DependencyInjection\Loader\PhpFileLoader;
use Symfony\Component\HttpKernel\DependencyInjection\Extension; use Symfony\Component\HttpKernel\DependencyInjection\Extension;
final class ChillWopiExtension extends Extension implements PrependExtensionInterface final class ChillWopiExtension extends Extension
{ {
public function load(array $configs, ContainerBuilder $container) public function load(array $configs, ContainerBuilder $container)
{ {
@ -33,18 +31,4 @@ final class ChillWopiExtension extends Extension implements PrependExtensionInte
$loader = new PhpFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config')); $loader = new PhpFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
$loader->load('services.php'); $loader->load('services.php');
} }
public function prepend(ContainerBuilder $container)
{
$container->prependExtensionConfig(
'doctrine',
[
'dbal' => [
'types' => [
'uuid' => UuidType::class,
],
],
]
);
}
} }

View File

@ -9,11 +9,11 @@
declare(strict_types=1); declare(strict_types=1);
use Chill\WopiBundle\Controller\Test; use Chill\WopiBundle\Controller\Editor;
use Symfony\Component\Routing\Loader\Configurator\RoutingConfigurator; use Symfony\Component\Routing\Loader\Configurator\RoutingConfigurator;
return static function (RoutingConfigurator $routes) { return static function (RoutingConfigurator $routes) {
$routes $routes
->add('chill_wopi_file_edit', '/edit/{fileId}') ->add('chill_wopi_file_edit', '/edit/{fileId}')
->controller(Test::class); ->controller(Editor::class);
}; };

View File

@ -14,11 +14,13 @@ window.addEventListener('DOMContentLoaded', function(e) {
office_frame.setAttribute('allowfullscreen', 'true'); office_frame.setAttribute('allowfullscreen', 'true');
// The sandbox attribute is needed to allow automatic redirection to the O365 sign-in page in the business user flow // The sandbox attribute is needed to allow automatic redirection to the O365 sign-in page in the business user flow
office_frame.setAttribute('sandbox', 'allow-downloads allow-scripts allow-same-origin allow-forms allow-popups allow-top-navigation allow-popups-to-escape-sandbox'); office_frame.setAttribute(
'sandbox',
'allow-downloads allow-scripts allow-same-origin allow-forms allow-modals allow-popups allow-top-navigation allow-popups-to-escape-sandbox'
);
frameholder.appendChild(office_frame); frameholder.appendChild(office_frame);
document.getElementById('office_form').submit(); document.getElementById('office_form').submit();
console.log(office_frame);
const url = new URL(editor_url); const url = new URL(editor_url);
const editor_domain = url.origin; const editor_domain = url.origin;

View File

@ -11,12 +11,12 @@ declare(strict_types=1);
namespace Chill\WopiBundle\Service\Wopi; namespace Chill\WopiBundle\Service\Wopi;
use ChampsLibres\AsyncUploaderBundle\TempUrl\TempUrlGeneratorInterface;
use ChampsLibres\WopiLib\Contract\Entity\Document; use ChampsLibres\WopiLib\Contract\Entity\Document;
use ChampsLibres\WopiLib\Contract\Service\DocumentLockManagerInterface; use ChampsLibres\WopiLib\Contract\Service\DocumentLockManagerInterface;
use ChampsLibres\WopiLib\Contract\Service\DocumentManagerInterface; use ChampsLibres\WopiLib\Contract\Service\DocumentManagerInterface;
use Chill\DocStoreBundle\Entity\StoredObject; use Chill\DocStoreBundle\Entity\StoredObject;
use Chill\DocStoreBundle\Repository\StoredObjectRepository; use Chill\DocStoreBundle\Repository\StoredObjectRepository;
use Chill\DocStoreBundle\Service\StoredObjectManagerInterface;
use DateTimeInterface; use DateTimeInterface;
use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\EntityManagerInterface;
use Error; use Error;
@ -28,8 +28,6 @@ use Symfony\Bridge\PsrHttpMessage\HttpMessageFactoryInterface;
use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Mime\MimeTypes; use Symfony\Component\Mime\MimeTypes;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Throwable;
use function strlen; use function strlen;
@ -39,33 +37,29 @@ final class ChillDocumentManager implements DocumentManagerInterface
private EntityManagerInterface $entityManager; private EntityManagerInterface $entityManager;
private HttpClientInterface $httpClient;
private Psr17Interface $psr17; private Psr17Interface $psr17;
private RequestInterface $request; private RequestInterface $request;
private StoredObjectRepository $storedObjectRepository; private StoredObjectManagerInterface $storedObjectManager;
private TempUrlGeneratorInterface $tempUrlGenerator; private StoredObjectRepository $storedObjectRepository;
public function __construct( public function __construct(
DocumentLockManagerInterface $documentLockManager, DocumentLockManagerInterface $documentLockManager,
EntityManagerInterface $entityManager, EntityManagerInterface $entityManager,
HttpClientInterface $httpClient,
Psr17Interface $psr17,
StoredObjectRepository $storedObjectRepository,
TempUrlGeneratorInterface $tempUrlGenerator,
HttpMessageFactoryInterface $httpMessageFactory, HttpMessageFactoryInterface $httpMessageFactory,
RequestStack $requestStack Psr17Interface $psr17,
RequestStack $requestStack,
StoredObjectManagerInterface $storedObjectManager,
StoredObjectRepository $storedObjectRepository
) { ) {
$this->documentLockManager = $documentLockManager;
$this->entityManager = $entityManager; $this->entityManager = $entityManager;
$this->psr17 = $psr17; $this->psr17 = $psr17;
$this->storedObjectRepository = $storedObjectRepository;
$this->documentLockManager = $documentLockManager;
$this->tempUrlGenerator = $tempUrlGenerator;
$this->httpClient = $httpClient;
$this->request = $httpMessageFactory->createRequest($requestStack->getCurrentRequest()); $this->request = $httpMessageFactory->createRequest($requestStack->getCurrentRequest());
$this->storedObjectManager = $storedObjectManager;
$this->storedObjectRepository = $storedObjectRepository;
} }
public function create(array $data): Document public function create(array $data): Document
@ -197,18 +191,7 @@ final class ChillDocumentManager implements DocumentManagerInterface
public function remove(Document $document): void public function remove(Document $document): void
{ {
$entityIsDeleted = false; // TODO: To implement when we have a clearer view and API.
try {
$this->entityManager->remove($document);
$entityIsDeleted = true;
} catch (Throwable $e) {
$entityIsDeleted = false;
}
if (true === $entityIsDeleted) {
$this->deleteContent($document);
}
} }
public function write(Document $document, array $properties = []): void public function write(Document $document, array $properties = []): void
@ -216,42 +199,13 @@ final class ChillDocumentManager implements DocumentManagerInterface
$this->setContent($document, $properties['content']); $this->setContent($document, $properties['content']);
} }
private function deleteContent(StoredObject $storedObject): void
{
/** @var StdClass $object */
$object = $this->tempUrlGenerator->generate('DELETE', $storedObject->getFilename());
$response = $this->httpClient->request('DELETE', $object->url);
if (200 !== $response->getStatusCode()) {
throw new Error('Unable to delete stored object.');
}
}
private function getContent(StoredObject $storedObject): string private function getContent(StoredObject $storedObject): string
{ {
/** @var StdClass $object */ return $this->storedObjectManager->read($storedObject);
$object = $this->tempUrlGenerator->generate('GET', $storedObject->getFilename());
$response = $this->httpClient->request('GET', $object->url);
if (200 !== $response->getStatusCode()) {
throw new Error('Unable to retrieve stored object.');
}
return $response->getContent();
} }
private function setContent(StoredObject $storedObject, string $content): void private function setContent(StoredObject $storedObject, string $content): void
{ {
// TODO: Add strict typing in champs-libres/async-uploader-bundle $this->storedObjectManager->write($storedObject, $content);
/** @var StdClass $object */
$object = $this->tempUrlGenerator->generate('PUT', $storedObject->getFilename());
$response = $this->httpClient->request('PUT', $object->url, ['body' => $content]);
if (201 !== $response->getStatusCode()) {
throw new Error('Unable to save stored object.');
}
} }
} }