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->createNotFoundException('Unable to find Structure entity');
  129. }
  130. $structure = $this->getUser()->getStructure();
  131. if (is_null($structure)) {
  132. throw $this->createNotFoundException('Unable to find Structure entity');
  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. 'structuresArray' => $structuresArray,
  188. 'name' => $filter_name,
  189. 'ville' => $filter_ville,
  190. 'filter_departement' => $filter_departement,
  191. 'filter_region' => $filter_region,
  192. 'filter_structureTypes' => $filter_structureTypes,
  193. 'departements' => $departements,
  194. 'regions' => $regions,
  195. 'typesAuth' => $typesAuth,
  196. ]);
  197. }
  198. /**
  199. * Displays a form to edit an existing entity.
  200. */
  201. #[Route(path: '/{id}/edit', name: 'structure_edit', methods: ['GET', 'POST'])]
  202. public function edit(Request $request, StructureRepository $structureRepository, Structure $structure): Response
  203. {
  204. if (false === $this->isGranted('IS_AUTHENTICATED_FULLY')) {
  205. throw new AccessDeniedException();
  206. }
  207. $structure_id = $this->getUser()->getStructure()->getId();
  208. if (!$this->isGranted('ROLE_ADMIN') && $structure_id != $structure->getId()) {
  209. throw new AccessDeniedException('This user does not have access to this section.');
  210. }
  211. if (0 !== substr_count($structure->getEmail(), 'no_email-')) {
  212. $structure->setEmail('');
  213. }
  214. $editForm = $this->createEditForm($structure);
  215. if ('CSO' != $structure->getTypeStructure() && 'EVS' != $structure->getTypeStructure()) {
  216. $editForm = $this->createForm(SimpleStructureType::class, $structure);
  217. $editForm->remove('password');
  218. $editForm->handleRequest($request);
  219. if ($editForm->isSubmitted() && $editForm->isValid()) {
  220. $structureRepository->add($structure);
  221. if ($structure && $structure->getTypeStructure()) {
  222. $user = $structure->getUser();
  223. // recupration des rôles existants
  224. $roles = $user->getRoles();
  225. switch ($structure->getTypeStructure()) {
  226. case 'EVS':
  227. case 'CSO':
  228. case 'FDD':
  229. case 'CAF':
  230. case 'RR':
  231. case 'RGR':
  232. case 'RN':
  233. case 'DEP_LIGHT':
  234. case 'REG_LIGHT':
  235. $role = 'ROLE_'.$structure->getTypeStructure()->getNom();
  236. break;
  237. case 'RN_LIGHT':
  238. $role = 'ROLE_DEP_LIGHT';
  239. break;
  240. default:
  241. $role = 'ROLE_CSO';
  242. break;
  243. }
  244. if (!in_array($role, $roles)) {
  245. $user->setRoles([$role]);
  246. $this->em->persist($user);
  247. }
  248. }
  249. $this->em->flush();
  250. }
  251. }
  252. return $this->render('Structure/edit.html.twig', [
  253. 'entity' => $structure,
  254. 'edit_form' => $editForm->createView(),
  255. ]);
  256. }
  257. /**
  258. * Creates a form to edit a structure entity.
  259. *
  260. * @param Structure $entity The entity
  261. *
  262. * @return Form The form
  263. */
  264. private function createEditForm(Structure $entity)
  265. {
  266. $form = $this->createForm(StructureType::class, $entity, [
  267. 'action' => $this->generateUrl(
  268. 'structure_update',
  269. ['id' => $entity->getId()]
  270. ),
  271. 'method' => 'POST',
  272. 'currentUser' => $this->getUser(),
  273. ]);
  274. $form->add('submit', SubmitType::class, ['label' => 'Update']);
  275. return $form;
  276. }
  277. /**
  278. * Edits an existing ModeGestion entity.
  279. */
  280. #[Route(path: '/{id}', name: 'structure_update', methods: ['POST'])]
  281. public function update(Request $request, Structure $structure): RedirectResponse|Response
  282. {
  283. if (false === $this->isGranted('IS_AUTHENTICATED_FULLY')) {
  284. throw new AccessDeniedException();
  285. }
  286. $structure_id = $this->getUser()->getStructure()->getId();
  287. if (!$this->isGranted('ROLE_ADMIN') && $structure_id != $structure->getId()) {
  288. throw new AccessDeniedException('This user does not have access to this section.');
  289. }
  290. $editForm = $this->createEditForm($structure);
  291. $editForm->handleRequest($request);
  292. $structureUser = $structure->getUser();
  293. if ($editForm->isSubmitted() && $editForm->isValid()) {
  294. if ($this->isGranted('ROLE_ADMIN') && ($structure && $structure->getTypeStructure())) {
  295. $roles = $structureUser->getRoles();
  296. switch ($structure->getTypeStructure()) {
  297. case 'EVS':
  298. case 'CSO':
  299. case 'FDD':
  300. case 'CAF':
  301. case 'RR':
  302. case 'RGR':
  303. case 'RN':
  304. case 'DEP_LIGHT':
  305. case 'REG_LIGHT':
  306. $role = 'ROLE_'.$structure->getTypeStructure()->getNom();
  307. break;
  308. case 'RN_LIGHT':
  309. $role = 'ROLE_DEP_LIGHT';
  310. break;
  311. default:
  312. $role = 'ROLE_CSO';
  313. break;
  314. }
  315. if (!in_array($role, $roles)) {
  316. $structureUser->setRoles([$role]);
  317. $this->em->persist($structureUser);
  318. }
  319. }
  320. $this->em->persist($structure);
  321. $this->em->flush();
  322. // test si email structure differente de mail user associé
  323. if ($structureUser->getEmail() != $structure->getEmail()) {
  324. // verification que l'adresse email n'est pas déjà utilisée dans la table fos_user
  325. $findExistingEmail = $this->em->getRepository(User::class)->findOneBy(['email' => $structure->getEmail()]);
  326. if (!$findExistingEmail) {
  327. $structureUser->setEmail($structure->getEmail());
  328. $this->em->persist($structureUser);
  329. $this->em->flush();
  330. }
  331. }
  332. // mise a jour des coordonnées geoloc eventuelles
  333. $this->updateGeolocInfos($structure);
  334. $this->affectCorrectDepartmentAndRegion($structure);
  335. $this->get('session')->getFlashBag()->add('success', 'La fiche structure a été mise à jour avec succès');
  336. return $this->redirectToRoute('show_structure', ['id' => $structure->getId()]);
  337. }
  338. return $this->render('Structure/edit.html.twig', [
  339. 'entity' => $structure,
  340. 'edit_form' => $editForm->createView(),
  341. ]);
  342. }
  343. private function updateGeolocInfos(Structure $structure): void
  344. {
  345. $geocoder = 'https://nominatim.openstreetmap.org/search.php?q=%s&format=json&addressdetails=1&limit=1&polygon_svg=1&email=contact@senacs.fr';
  346. if ($structure->getCommuneImplementation()) {
  347. $adresse = '';
  348. if ($structure->getAdresse()) {
  349. $adresse .= $structure->getAdresse().'+';
  350. }
  351. if ($structure->getCodePostal()) {
  352. $adresse .= $structure->getCodePostal().'+';
  353. }
  354. $adresse .= $structure->getCommuneImplementation()->getNom().'+FRANCE';
  355. // $url = sprintf($geocoder, urlencode($adresse));
  356. $url = sprintf($geocoder, str_replace(' ', '+', $adresse));
  357. $ch = curl_init();
  358. curl_setopt($ch, CURLOPT_URL, $url);
  359. curl_setopt($ch, CURLOPT_HEADER, 0);
  360. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  361. $tmp = curl_exec($ch);
  362. $result = json_decode($tmp, true);
  363. $lat = null;
  364. $lng = null;
  365. /* if ($result['status'] === "OK") {
  366. $lat = $result['results']['0']['geometry']['location']['lat'];
  367. $lng = $result['results']['0']['geometry']['location']['lng'];
  368. } */
  369. if (is_array($result) && count($result)) {
  370. $lat = $result['0']['lat'];
  371. $lng = $result['0']['lon'];
  372. }
  373. if ($lat && $lng) {
  374. $structure->setLatitude($lat);
  375. $structure->setLongitude($lng);
  376. $this->em->persist($structure);
  377. $this->em->flush();
  378. }
  379. }
  380. }
  381. private function affectCorrectDepartmentAndRegion(Structure $structure): void
  382. {
  383. $commune = $structure->getCommuneImplementation();
  384. if ($commune && $commune->getDepartement() && (($structure->getDepartement() && $commune->getDepartement()->getId() != $structure->getDepartement()->getId()) || !$structure->getDepartement())) {
  385. $structure->setDepartement($commune->getDepartement());
  386. if ($commune->getDepartement()->getRegion()) {
  387. $structure->setRegion($commune->getDepartement()->getRegion());
  388. $structure->setGrandeRegion($commune->getDepartement()->getRegion()->getGrandeRegion());
  389. }
  390. $this->em->persist($structure);
  391. $this->em->flush();
  392. }
  393. }
  394. }