Merge branch 'calendar/synchro-msgraph' into calendar/finalization

This commit is contained in:
2022-06-17 16:52:52 +02:00
389 changed files with 10282 additions and 2770 deletions

View File

@@ -0,0 +1,28 @@
<?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\CalendarBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
class AdminController extends AbstractController
{
/**
* Calendar admin.
*
* @Route("/{_locale}/admin/calendar", name="chill_calendar_admin_index")
*/
public function indexAdminAction()
{
return $this->render('ChillCalendarBundle:Admin:index.html.twig');
}
}

View File

@@ -13,9 +13,11 @@ namespace Chill\CalendarBundle\Controller;
use Chill\CalendarBundle\Entity\Calendar;
use Chill\CalendarBundle\Form\CalendarType;
use Chill\CalendarBundle\RemoteCalendar\Connector\RemoteCalendarConnectorInterface;
use Chill\CalendarBundle\Repository\CalendarRepository;
use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Pagination\PaginatorFactory;
use Chill\MainBundle\Repository\UserRepository;
use Chill\MainBundle\Security\Authorization\AuthorizationHelper;
use Chill\PersonBundle\Entity\AccompanyingPeriod;
use Chill\PersonBundle\Entity\Person;
@@ -35,32 +37,40 @@ use Symfony\Component\Serializer\SerializerInterface;
class CalendarController extends AbstractController
{
protected AuthorizationHelper $authorizationHelper;
protected EventDispatcherInterface $eventDispatcher;
protected LoggerInterface $logger;
protected PaginatorFactory $paginator;
protected SerializerInterface $serializer;
private AuthorizationHelper $authorizationHelper;
private CalendarRepository $calendarRepository;
private EventDispatcherInterface $eventDispatcher;
private LoggerInterface $logger;
private PaginatorFactory $paginator;
private RemoteCalendarConnectorInterface $remoteCalendarConnector;
private SerializerInterface $serializer;
private UserRepository $userRepository;
public function __construct(
EventDispatcherInterface $eventDispatcher,
AuthorizationHelper $authorizationHelper,
CalendarRepository $calendarRepository,
EventDispatcherInterface $eventDispatcher,
LoggerInterface $logger,
SerializerInterface $serializer,
PaginatorFactory $paginator,
CalendarRepository $calendarRepository
RemoteCalendarConnectorInterface $remoteCalendarConnector,
SerializerInterface $serializer,
UserRepository $userRepository
) {
$this->eventDispatcher = $eventDispatcher;
$this->authorizationHelper = $authorizationHelper;
$this->logger = $logger;
$this->serializer = $serializer;
$this->paginator = $paginator;
$this->calendarRepository = $calendarRepository;
$this->eventDispatcher = $eventDispatcher;
$this->logger = $logger;
$this->paginator = $paginator;
$this->remoteCalendarConnector = $remoteCalendarConnector;
$this->serializer = $serializer;
$this->userRepository = $userRepository;
}
/**
@@ -127,8 +137,12 @@ class CalendarController extends AbstractController
*
* @Route("/{_locale}/calendar/calendar/{id}/edit", name="chill_calendar_calendar_edit")
*/
public function editAction(int $id, Request $request): Response
public function editAction(Calendar $entity, Request $request): Response
{
if (!$this->remoteCalendarConnector->isReady()) {
return $this->remoteCalendarConnector->getMakeReadyResponse($request->getUri());
}
$view = null;
$em = $this->getDoctrine()->getManager();
@@ -137,21 +151,14 @@ class CalendarController extends AbstractController
if ($accompanyingPeriod instanceof AccompanyingPeriod) {
$view = '@ChillCalendar/Calendar/editByAccompanyingCourse.html.twig';
} elseif ($user instanceof User) {
throw new Exception('to analyze');
$view = '@ChillCalendar/Calendar/editByUser.html.twig';
}
$entity = $em->getRepository(\Chill\CalendarBundle\Entity\Calendar::class)->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Calendar entity.');
}
$form = $this->createForm(CalendarType::class, $entity, [
'accompanyingPeriod' => $accompanyingPeriod,
])->handleRequest($request);
$form = $this->createForm(CalendarType::class, $entity);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em->persist($entity);
$em->flush();
$this->addFlash('success', $this->get('translator')->trans('Success : calendar item updated!'));
@@ -165,7 +172,7 @@ class CalendarController extends AbstractController
$this->addFlash('error', $this->get('translator')->trans('This form contains errors'));
}
$deleteForm = $this->createDeleteForm($id, $user, $accompanyingPeriod);
$deleteForm = $this->createDeleteForm($entity->getId(), $user, $accompanyingPeriod);
if (null === $view) {
throw $this->createNotFoundException('Template not found');
@@ -178,7 +185,7 @@ class CalendarController extends AbstractController
'form' => $form->createView(),
'delete_form' => $deleteForm->createView(),
'accompanyingCourse' => $accompanyingPeriod,
'user' => $user,
// 'user' => $user,
'entity_json' => $entity_array,
]);
}
@@ -251,6 +258,28 @@ class CalendarController extends AbstractController
throw new Exception('Unable to list actions.');
}
/**
* @Route("/{_locale}/calendar/calendar/my", name="chill_calendar_calendar_list_my")
*/
public function myCalendar(Request $request): Response
{
$this->denyAccessUnlessGranted('ROLE_USER');
if (!$this->getUser() instanceof User) {
throw new UnauthorizedHttpException('you are not an user');
}
if (!$this->remoteCalendarConnector->isReady()) {
return $this->remoteCalendarConnector->getMakeReadyResponse($request->getUri());
}
$view = '@ChillCalendar/Calendar/listByUser.html.twig';
return $this->render($view, [
'user' => $this->getUser(),
]);
}
/**
* Create a new calendar item.
*
@@ -258,6 +287,10 @@ class CalendarController extends AbstractController
*/
public function newAction(Request $request): Response
{
if (!$this->remoteCalendarConnector->isReady()) {
return $this->remoteCalendarConnector->getMakeReadyResponse($request->getUri());
}
$view = null;
$em = $this->getDoctrine()->getManager();
@@ -271,8 +304,10 @@ class CalendarController extends AbstractController
// }
$entity = new Calendar();
$entity->setUser($this->getUser());
$entity->setStatus($entity::STATUS_VALID);
if ($request->query->has('mainUser')) {
$entity->setMainUser($this->userRepository->find($request->query->getInt('mainUser')));
}
// if ($user instanceof User) {
// $entity->setPerson($user);
@@ -282,9 +317,8 @@ class CalendarController extends AbstractController
$entity->setAccompanyingPeriod($accompanyingPeriod);
}
$form = $this->createForm(CalendarType::class, $entity, [
'accompanyingPeriod' => $accompanyingPeriod,
])->handleRequest($request);
$form = $this->createForm(CalendarType::class, $entity);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em->persist($entity);

View File

@@ -11,38 +11,72 @@ declare(strict_types=1);
namespace Chill\CalendarBundle\Controller;
use Chill\CalendarBundle\Repository\CalendarRangeRepository;
use Chill\MainBundle\CRUD\Controller\ApiController;
use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Serializer\Model\Collection;
use DateTimeImmutable;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use function count;
use Symfony\Component\Routing\Annotation\Route;
class CalendarRangeAPIController extends ApiController
{
/**
* @Route("/api/1.0/calendar/calendar-range-available.{_format}", name="chill_api_single_calendar_range_available")
*/
public function availableRanges(Request $request, string $_format): JsonResponse
private CalendarRangeRepository $calendarRangeRepository;
public function __construct(CalendarRangeRepository $calendarRangeRepository)
{
$em = $this->getDoctrine()->getManager();
$this->calendarRangeRepository = $calendarRangeRepository;
}
$sql = 'SELECT c FROM ChillCalendarBundle:CalendarRange c
WHERE NOT EXISTS (SELECT cal.id FROM ChillCalendarBundle:Calendar cal WHERE cal.calendarRange = c.id)';
/**
* @Route("/api/1.0/calendar/calendar-range-available/{id}.{_format}",
* name="chill_api_single_calendar_range_available",
* requirements={"_format": "json"}
* )
*/
public function availableRanges(User $user, Request $request, string $_format): JsonResponse
{
//return new JsonResponse(['ok' => true], 200, [], false);
$this->denyAccessUnlessGranted('ROLE_USER');
if ($request->query->has('user')) {
$user = $request->query->get('user');
$sql = $sql . ' AND c.user = :user';
$query = $em->createQuery($sql)
->setParameter('user', $user);
} else {
$query = $em->createQuery($sql);
if (!$request->query->has('dateFrom')) {
throw new BadRequestHttpException('You must provide a dateFrom parameter');
}
$results = $query->getResult();
if (false === $dateFrom = DateTimeImmutable::createFromFormat(
DateTimeImmutable::ATOM,
$request->query->get('dateFrom')
)) {
throw new BadRequestHttpException('dateFrom not parsable');
}
return $this->json(['count' => count($results), 'results' => $results], Response::HTTP_OK, [], ['groups' => ['read']]);
//TODO use also the paginator, eg return $this->serializeCollection('get', $request, $_format, $paginator, $results);
if (!$request->query->has('dateTo')) {
throw new BadRequestHttpException('You must provide a dateTo parameter');
}
if (false === $dateTo = DateTimeImmutable::createFromFormat(
DateTimeImmutable::ATOM,
$request->query->get('dateTo')
)) {
throw new BadRequestHttpException('dateTo not parsable');
}
$total = $this->calendarRangeRepository->countByAvailableRangesForUser($user, $dateFrom, $dateTo);
$paginator = $this->getPaginatorFactory()->create($total);
$ranges = $this->calendarRangeRepository->findByAvailableRangesForUser(
$user,
$dateFrom,
$dateTo,
$paginator->getItemsPerPage(),
$paginator->getCurrentPageFirstItemNumber()
);
$collection = new Collection($ranges, $paginator);
return $this->json($collection, Response::HTTP_OK, [], ['groups' => ['read']]);
}
}

View File

@@ -0,0 +1,26 @@
<?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\CalendarBundle\Controller;
use Chill\MainBundle\CRUD\Controller\CRUDController;
use Chill\MainBundle\Pagination\PaginatorInterface;
use Symfony\Component\HttpFoundation\Request;
class CancelReasonController extends CRUDController
{
protected function orderQuery(string $action, $query, Request $request, PaginatorInterface $paginator)
{
$query->addOrderBy('e.id', 'ASC');
return parent::orderQuery($action, $query, $request, $paginator);
}
}

View File

@@ -0,0 +1,69 @@
<?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\CalendarBundle\Controller;
use Chill\CalendarBundle\Entity\Calendar;
use Chill\CalendarBundle\Entity\Invite;
use Chill\CalendarBundle\Security\Voter\InviteVoter;
use Chill\MainBundle\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Security;
use function in_array;
class InviteApiController
{
private EntityManagerInterface $entityManager;
private Security $security;
public function __construct(Security $security, EntityManagerInterface $entityManager)
{
$this->security = $security;
$this->entityManager = $entityManager;
}
/**
* Give an answer to a calendar invite.
*
* @Route("/api/1.0/calendar/calendar/{id}/answer/{answer}.json", methods={"post"})
*/
public function answer(Calendar $calendar, string $answer): Response
{
$user = $this->security->getUser();
if (!$user instanceof User) {
throw new AccessDeniedHttpException('not a regular user');
}
if (null === $invite = $calendar->getInviteForUser($user)) {
throw new AccessDeniedHttpException('not invited to this calendar');
}
if (!$this->security->isGranted(InviteVoter::ANSWER, $invite)) {
throw new AccessDeniedHttpException('not allowed to answer on this invitation');
}
if (!in_array($answer, Invite::STATUSES, true) || Invite::PENDING === $answer) {
throw new BadRequestHttpException('answer not valid');
}
$invite->setStatus($answer);
$this->entityManager->flush();
return new JsonResponse(null, Response::HTTP_ACCEPTED, [], false);
}
}

View File

@@ -0,0 +1,71 @@
<?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\CalendarBundle\Controller;
use Chill\CalendarBundle\RemoteCalendar\Connector\MSGraph\OnBehalfOfUserTokenStorage;
use KnpU\OAuth2ClientBundle\Client\ClientRegistry;
use League\OAuth2\Client\Provider\Exception\IdentityProviderException;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use TheNetworg\OAuth2\Client\Provider\Azure;
use TheNetworg\OAuth2\Client\Token\AccessToken;
class RemoteCalendarConnectAzureController
{
private ClientRegistry $clientRegistry;
private OnBehalfOfUserTokenStorage $MSGraphTokenStorage;
public function __construct(
ClientRegistry $clientRegistry,
OnBehalfOfUserTokenStorage $MSGraphTokenStorage
) {
$this->clientRegistry = $clientRegistry;
$this->MSGraphTokenStorage = $MSGraphTokenStorage;
}
/**
* @Route("/{_locale}/connect/azure", name="chill_calendar_remote_connect_azure")
*/
public function connectAzure(Request $request): Response
{
$request->getSession()->set('azure_return_path', $request->query->get('returnPath', '/'));
return $this->clientRegistry
->getClient('azure') // key used in config/packages/knpu_oauth2_client.yaml
->redirect([
'https://graph.microsoft.com/.default', 'offline_access',
]);
}
/**
* @Route("/connect/azure/check", name="chill_calendar_remote_connect_azure_check")
*/
public function connectAzureCheck(Request $request): Response
{
/** @var Azure $client */
$client = $this->clientRegistry->getClient('azure');
try {
/** @var AccessToken $token */
$token = $client->getAccessToken();
$this->MSGraphTokenStorage->setToken($token);
} catch (IdentityProviderException $e) {
throw $e;
}
return new RedirectResponse($request->getSession()->remove('azure_return_path', '/'));
}
}

View File

@@ -0,0 +1,88 @@
<?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\CalendarBundle\Controller;
use Chill\CalendarBundle\RemoteCalendar\Connector\RemoteCalendarConnectorInterface;
use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Pagination\PaginatorFactory;
use Chill\MainBundle\Serializer\Model\Collection;
use DateTimeImmutable;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Serializer\SerializerInterface;
use function count;
/**
* Contains method to get events (Calendar) from remote calendar.
*/
class RemoteCalendarProxyController
{
private PaginatorFactory $paginatorFactory;
private RemoteCalendarConnectorInterface $remoteCalendarConnector;
private SerializerInterface $serializer;
public function __construct(PaginatorFactory $paginatorFactory, RemoteCalendarConnectorInterface $remoteCalendarConnector, SerializerInterface $serializer)
{
$this->paginatorFactory = $paginatorFactory;
$this->remoteCalendarConnector = $remoteCalendarConnector;
$this->serializer = $serializer;
}
/**
* @Route("api/1.0/calendar/proxy/calendar/by-user/{id}/events")
*/
public function listEventForCalendar(User $user, Request $request): Response
{
if (!$request->query->has('dateFrom')) {
throw new BadRequestHttpException('You must provide a dateFrom parameter');
}
if (false === $dateFrom = DateTimeImmutable::createFromFormat(
DateTimeImmutable::ATOM,
$request->query->get('dateFrom')
)) {
throw new BadRequestHttpException('dateFrom not parsable');
}
if (!$request->query->has('dateTo')) {
throw new BadRequestHttpException('You must provide a dateTo parameter');
}
if (false === $dateTo = DateTimeImmutable::createFromFormat(
DateTimeImmutable::ATOM,
$request->query->get('dateTo')
)) {
throw new BadRequestHttpException('dateTo not parsable');
}
$events = $this->remoteCalendarConnector->listEventsForUser($user, $dateFrom, $dateTo);
$paginator = $this->paginatorFactory->create(count($events));
if (count($events) > 0) {
$paginator->setItemsPerPage($paginator->getTotalItems());
}
$collection = new Collection($events, $paginator);
return new JsonResponse(
$this->serializer->serialize($collection, 'json', ['groups' => ['read']]),
JsonResponse::HTTP_OK,
[],
true
);
}
}