src/Controller/StructureController.php line 45

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Controller;
  4. use App\Entity\Departement;
  5. use App\Entity\Region;
  6. use App\Entity\Structure;
  7. use App\Entity\User;
  8. use App\Form\SimpleStructureType;
  9. use App\Form\StructureType;
  10. use App\Repository\StructureRepository;
  11. use Doctrine\ORM\EntityManagerInterface;
  12. use Knp\Component\Pager\PaginatorInterface;
  13. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  14. use Symfony\Component\Form\Extension\Core\Type\SubmitType;
  15. use Symfony\Component\Form\Form;
  16. use Symfony\Component\HttpFoundation\RedirectResponse;
  17. use Symfony\Component\HttpFoundation\Request;
  18. use Symfony\Component\HttpFoundation\Response;
  19. use Symfony\Component\Routing\Annotation\Route;
  20. use Symfony\Component\Security\Core\Exception\AccessDeniedException;
  21. /**
  22. * Structure controller.
  23. */
  24. #[Route(path: '/structure')]
  25. class StructureController extends AbstractController
  26. {
  27. private EntityManagerInterface $em;
  28. public function __construct(EntityManagerInterface $em)
  29. {
  30. $this->em = $em;
  31. }
  32. /**
  33. * Lists all csx structure.
  34. */
  35. #[Route(path: '/csx', name: 'list_csx')]
  36. #[Route(path: '/evs', name: 'list_evs')]
  37. #[Route(path: '/admin/cafs', name: 'list_caf')]
  38. #[Route(path: '/admin/federations', name: 'list_fdd')]
  39. public function listStructures(Request $request, PaginatorInterface $paginator): Response
  40. {
  41. $routeName = $request->get('_route');
  42. switch ($routeName) {
  43. case 'list_evs':
  44. $title = 'Liste des espaces de vie sociale';
  45. $structure_type_id = '2';
  46. $type_structure = 'EVS';
  47. break;
  48. case 'list_csx':
  49. default:
  50. $title = 'Liste des centres sociaux';
  51. $structure_type_id = '4';
  52. $type_structure = 'CSO';
  53. break;
  54. case 'list_caf':
  55. $title = 'Liste des CAFS';
  56. $structure_type_id = '3';
  57. $type_structure = 'CAF';
  58. break;
  59. case 'list_fdd':
  60. $title = 'Liste des fédérations';
  61. $structure_type_id = '5';
  62. $type_structure = 'FDD';
  63. break;
  64. }
  65. $query = $request->query;
  66. $filter_name = $query->get('name', '');
  67. $filter_ville = $query->get('ville', '');
  68. $filter_departement = $query->get('departement', '');
  69. $filter_region = $query->get('region', '');
  70. // recuperations des départements
  71. $departements = $this->em->getRepository(Departement::class)->getAllByRegion($filter_region);
  72. $regions = $this->em->getRepository(Region::class)->findAll();
  73. $pagination = $paginator->paginate(
  74. $this->em->getRepository(Structure::class)->getListStructure(
  75. $query->get('sort', 'e.id'),
  76. $query->get('direction', 'ASC'),
  77. $structure_type_id,
  78. $filter_name,
  79. $filter_ville,
  80. $filter_departement,
  81. $filter_region
  82. ),
  83. $query->getInt('page', 1), /* page number */
  84. 25 /* limit per page */
  85. );
  86. return $this->render('Structure/index.html.twig', [
  87. 'name' => $filter_name,
  88. 'ville' => $filter_ville,
  89. 'filter_departement' => $filter_departement,
  90. 'filter_region' => $filter_region,
  91. 'pagination' => $pagination,
  92. 'title' => $title,
  93. 'type_structure' => $type_structure,
  94. 'departements' => $departements,
  95. 'regions' => $regions,
  96. ]);
  97. }
  98. /**
  99. * Afficher les infos dans un modal.
  100. */
  101. #[Route(path: '/showModal/{id}', name: 'show_modal_structure', methods: ['GET'])]
  102. #[Route(path: '/showModal', name: 'show_modal_my_structure', methods: ['GET'])] // La variable $idModal permet de spécifier l'id de la class modal
  103. public function showModal(?Structure $structure = null, $idModal = null): Response
  104. {
  105. if (is_null($structure)) {
  106. $structure = $this->getUser()->getStructure();
  107. if (is_null($structure)) {
  108. throw $this->createNotFoundException('Unable to find Structure entity');
  109. }
  110. }
  111. return $this->render('Structure/show_modal_information.html.twig', [
  112. 'idModal' => $idModal,
  113. 'entity' => $structure,
  114. ]);
  115. }
  116. /**
  117. * Afficher les infos dans un modal.
  118. */
  119. #[Route(path: '/show/{id}', name: 'show_structure', methods: ['GET'])]
  120. #[Route(path: '/show', name: 'show_my_structure', methods: ['GET'])]
  121. public function show(?Structure $structure = null): Response
  122. {
  123. if (false === $this->isGranted('ROLE_USER')) {
  124. // throw new AccessDeniedException();
  125. }
  126. if (is_null($structure) || is_null($this->getUser())) {
  127. if (is_null($this->getUser())) {
  128. throw $this->createAccessDeniedException('Accès non autorisé.');
  129. }
  130. $structure = $this->getUser()->getStructure();
  131. if (is_null($structure)) {
  132. throw $this->createNotFoundException('Structure inexistante');
  133. }
  134. }
  135. return $this->render('Structure/show.html.twig', [
  136. 'entity' => $structure,
  137. ]);
  138. }
  139. /**
  140. * Afficher une carte avec les structures auquels le cso a droit.
  141. */
  142. #[Route(path: '/map', name: 'map_structures', methods: ['GET'])]
  143. public function showAuthMapStructure(Request $request): Response
  144. {
  145. $user = $this->getUser();
  146. $structure = $user ? $user->getStructure() : null;
  147. $query = $request->query;
  148. $filter_name = $query->get('name', '');
  149. $filter_ville = $query->get('ville', '');
  150. $filter_departement = $query->get('departement', '');
  151. $filter_region = $query->get('region', '');
  152. $filter_structureTypes = $query->get('structureTypes', $this->getUser() ? ['4'] : ['0']);
  153. if ($this->getUser() && $this->isGranted('ROLE_ADMIN') && !$this->isGranted('ROLE_RN') && '' == $filter_region) {
  154. if (($this->isGranted('ROLE_CAF') || $this->isGranted('ROLE_FDD')) && !$this->isGranted('ROLE_RR') && '' == $filter_departement) {
  155. $filter_departement = $this->getUser()->getStructure()->getDepartement()->getId();
  156. }
  157. $filter_region = $this->getUser()->getStructure()->getRegion()->getId();
  158. }
  159. // recuperations des départements
  160. $departements = $this->em->getRepository(Departement::class)->getAllByRegion($filter_region);
  161. $regions = $this->em->getRepository(Region::class)->findAll();
  162. $typesAuth = [
  163. '2' => 'EVS',
  164. '4' => 'CSO',
  165. ];
  166. if ($this->getUser()) {
  167. $typesAuth = [
  168. '2' => 'EVS',
  169. '4' => 'CSO',
  170. '3' => 'CAF',
  171. '5' => 'FDD',
  172. ];
  173. }
  174. $structuresArray = [];
  175. if (count($filter_structureTypes) > 0) {
  176. // récupération des structures authorisées
  177. $structuresArray = [
  178. 'CSO' => $this->em->getRepository(Structure::class)->getListCoordinateStructureFormMap($structure, '4', $filter_name, $filter_ville, $filter_departement, $filter_region, $filter_structureTypes),
  179. 'EVS' => $this->em->getRepository(Structure::class)->getListCoordinateStructureFormMap($structure, '2', $filter_name, $filter_ville, $filter_departement, $filter_region, $filter_structureTypes),
  180. ];
  181. if ($this->getUser()) {
  182. $structuresArray['CAF'] = $this->em->getRepository(Structure::class)->getListCoordinateStructureFormMap($structure, '3', $filter_name, $filter_ville, $filter_departement, $filter_region, $filter_structureTypes);
  183. $structuresArray['FDD'] = $this->em->getRepository(Structure::class)->getListCoordinateStructureFormMap($structure, '5', $filter_name, $filter_ville, $filter_departement, $filter_region, $filter_structureTypes);
  184. }
  185. }
  186. return $this->render('Structure/map.html.twig', [
  187. 'structuresJson' => json_encode($structuresArray),
  188. 'structuresArray' => $structuresArray,
  189. 'name' => $filter_name,
  190. 'ville' => $filter_ville,
  191. 'filter_departement' => $filter_departement,
  192. 'filter_region' => $filter_region,
  193. 'filter_structureTypes' => $filter_structureTypes,
  194. 'departements' => $departements,
  195. 'regions' => $regions,
  196. 'typesAuth' => $typesAuth,
  197. ]);
  198. }
  199. /**
  200. * Displays a form to edit an existing entity.
  201. */
  202. #[Route(path: '/{id}/edit', name: 'structure_edit', methods: ['GET', 'POST'])]
  203. public function edit(Request $request, StructureRepository $structureRepository, Structure $structure): Response
  204. {
  205. if (false === $this->isGranted('IS_AUTHENTICATED_FULLY')) {
  206. throw new AccessDeniedException();
  207. }
  208. $structure_id = $this->getUser()->getStructure()->getId();
  209. if (!$this->isGranted('ROLE_ADMIN') && $structure_id != $structure->getId()) {
  210. throw new AccessDeniedException('This user does not have access to this section.');
  211. }
  212. if (0 !== substr_count($structure->getEmail()??'', 'no_email-')) {
  213. $structure->setEmail('');
  214. }
  215. $editForm = $this->createEditForm($structure);
  216. if ('CSO' != $structure->getTypeStructure() && 'EVS' != $structure->getTypeStructure()) {
  217. $editForm = $this->createForm(SimpleStructureType::class, $structure);
  218. $editForm->remove('password');
  219. $editForm->handleRequest($request);
  220. if ($editForm->isSubmitted() && $editForm->isValid()) {
  221. $structureRepository->add($structure);
  222. if ($structure && $structure->getTypeStructure()) {
  223. $user = $structure->getUser();
  224. // recupration des rôles existants
  225. $roles = $user->getRoles();
  226. switch ($structure->getTypeStructure()) {
  227. case 'EVS':
  228. case 'CSO':
  229. case 'FDD':
  230. case 'CAF':
  231. case 'RR':
  232. case 'RGR':
  233. case 'RN':
  234. case 'DEP_LIGHT':
  235. case 'REG_LIGHT':
  236. $role = 'ROLE_'.$structure->getTypeStructure()->getNom();
  237. break;
  238. case 'RN_LIGHT':
  239. $role = 'ROLE_DEP_LIGHT';
  240. break;
  241. default:
  242. $role = 'ROLE_CSO';
  243. break;
  244. }
  245. if (!in_array($role, $roles)) {
  246. $user->setRoles([$role]);
  247. $this->em->persist($user);
  248. }
  249. }
  250. $this->em->flush();
  251. }
  252. }
  253. return $this->render('Structure/edit.html.twig', [
  254. 'entity' => $structure,
  255. 'edit_form' => $editForm->createView(),
  256. ]);
  257. }
  258. /**
  259. * Creates a form to edit a structure entity.
  260. *
  261. * @param Structure $entity The entity
  262. *
  263. * @return Form The form
  264. */
  265. private function createEditForm(Structure $entity)
  266. {
  267. $form = $this->createForm(StructureType::class, $entity, [
  268. 'action' => $this->generateUrl(
  269. 'structure_update',
  270. ['id' => $entity->getId()]
  271. ),
  272. 'method' => 'POST',
  273. 'currentUser' => $this->getUser(),
  274. ]);
  275. $form->add('submit', SubmitType::class, ['label' => 'Update']);
  276. return $form;
  277. }
  278. /**
  279. * Edits an existing ModeGestion entity.
  280. */
  281. #[Route(path: '/{id}', name: 'structure_update', methods: ['POST'])]
  282. public function update(Request $request, Structure $structure): RedirectResponse|Response
  283. {
  284. if (false === $this->isGranted('IS_AUTHENTICATED_FULLY')) {
  285. throw new AccessDeniedException();
  286. }
  287. $structure_id = $this->getUser()->getStructure()->getId();
  288. if (!$this->isGranted('ROLE_ADMIN') && $structure_id != $structure->getId()) {
  289. throw new AccessDeniedException('This user does not have access to this section.');
  290. }
  291. $editForm = $this->createEditForm($structure);
  292. $editForm->handleRequest($request);
  293. $structureUser = $structure->getUser();
  294. if ($editForm->isSubmitted() && $editForm->isValid()) {
  295. if ($this->isGranted('ROLE_ADMIN') && ($structure && $structure->getTypeStructure())) {
  296. $roles = $structureUser->getRoles();
  297. switch ($structure->getTypeStructure()) {
  298. case 'EVS':
  299. case 'CSO':
  300. case 'FDD':
  301. case 'CAF':
  302. case 'RR':
  303. case 'RGR':
  304. case 'RN':
  305. case 'DEP_LIGHT':
  306. case 'REG_LIGHT':
  307. $role = 'ROLE_'.$structure->getTypeStructure()->getNom();
  308. break;
  309. case 'RN_LIGHT':
  310. $role = 'ROLE_DEP_LIGHT';
  311. break;
  312. default:
  313. $role = 'ROLE_CSO';
  314. break;
  315. }
  316. if (!in_array($role, $roles)) {
  317. $structureUser->setRoles([$role]);
  318. $this->em->persist($structureUser);
  319. }
  320. }
  321. $this->em->persist($structure);
  322. $this->em->flush();
  323. // test si email structure differente de mail user associé
  324. if ($structureUser->getEmail() != $structure->getEmail()) {
  325. // verification que l'adresse email n'est pas déjà utilisée dans la table fos_user
  326. $findExistingEmail = $this->em->getRepository(User::class)->findOneBy(['email' => $structure->getEmail()]);
  327. if (!$findExistingEmail) {
  328. $structureUser->setEmail($structure->getEmail());
  329. $this->em->persist($structureUser);
  330. $this->em->flush();
  331. }
  332. }
  333. // mise a jour des coordonnées geoloc eventuelles
  334. $this->updateGeolocInfos($structure);
  335. $this->affectCorrectDepartmentAndRegion($structure);
  336. $this->get('session')->getFlashBag()->add('success', 'La fiche structure a été mise à jour avec succès');
  337. return $this->redirectToRoute('show_structure', ['id' => $structure->getId()]);
  338. }
  339. return $this->render('Structure/edit.html.twig', [
  340. 'entity' => $structure,
  341. 'edit_form' => $editForm->createView(),
  342. ]);
  343. }
  344. private function updateGeolocInfos(Structure $structure): void
  345. {
  346. $geocoder = 'https://nominatim.openstreetmap.org/search.php?q=%s&format=json&addressdetails=1&limit=1&polygon_svg=1&email=contact@senacs.fr';
  347. if ($structure->getCommuneImplementation()) {
  348. $adresse = '';
  349. if ($structure->getAdresse()) {
  350. $adresse .= $structure->getAdresse().'+';
  351. }
  352. if ($structure->getCodePostal()) {
  353. $adresse .= $structure->getCodePostal().'+';
  354. }
  355. $adresse .= $structure->getCommuneImplementation()->getNom().'+FRANCE';
  356. // $url = sprintf($geocoder, urlencode($adresse));
  357. $url = sprintf($geocoder, str_replace(' ', '+', $adresse));
  358. $ch = curl_init();
  359. curl_setopt($ch, CURLOPT_URL, $url);
  360. curl_setopt($ch, CURLOPT_HEADER, 0);
  361. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  362. $tmp = curl_exec($ch);
  363. $result = json_decode($tmp, true);
  364. $lat = null;
  365. $lng = null;
  366. /* if ($result['status'] === "OK") {
  367. $lat = $result['results']['0']['geometry']['location']['lat'];
  368. $lng = $result['results']['0']['geometry']['location']['lng'];
  369. } */
  370. if (is_array($result) && count($result)) {
  371. $lat = $result['0']['lat'];
  372. $lng = $result['0']['lon'];
  373. }
  374. if ($lat && $lng) {
  375. $structure->setLatitude($lat);
  376. $structure->setLongitude($lng);
  377. $this->em->persist($structure);
  378. $this->em->flush();
  379. }
  380. }
  381. }
  382. private function affectCorrectDepartmentAndRegion(Structure $structure): void
  383. {
  384. $commune = $structure->getCommuneImplementation();
  385. if ($commune && $commune->getDepartement() && (($structure->getDepartement() && $commune->getDepartement()->getId() != $structure->getDepartement()->getId()) || !$structure->getDepartement())) {
  386. $structure->setDepartement($commune->getDepartement());
  387. if ($commune->getDepartement()->getRegion()) {
  388. $structure->setRegion($commune->getDepartement()->getRegion());
  389. $structure->setGrandeRegion($commune->getDepartement()->getRegion()->getGrandeRegion());
  390. }
  391. $this->em->persist($structure);
  392. $this->em->flush();
  393. }
  394. }
  395. }