OrganizationFactory.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753
  1. <?php
  2. namespace App\Service\Organization;
  3. use App\ApiResources\Organization\OrganizationCreationRequest;
  4. use App\ApiResources\Organization\OrganizationDeletionRequest;
  5. use App\ApiResources\Organization\OrganizationMemberCreationRequest;
  6. use App\Entity\Access\Access;
  7. use App\Entity\Billing\BillingSetting;
  8. use App\Entity\Core\AddressPostal;
  9. use App\Entity\Core\ContactPoint;
  10. use App\Entity\Education\CriteriaNotation;
  11. use App\Entity\Education\Cycle;
  12. use App\Entity\Network\NetworkOrganization;
  13. use App\Entity\Organization\Organization;
  14. use App\Entity\Organization\OrganizationAddressPostal;
  15. use App\Entity\Organization\Parameters;
  16. use App\Entity\Organization\Settings;
  17. use App\Entity\Organization\Subdomain;
  18. use App\Entity\Person\Person;
  19. use App\Entity\Person\PersonAddressPostal;
  20. use App\Enum\Core\ContactPointTypeEnum;
  21. use App\Enum\Education\CycleEnum;
  22. use App\Enum\Network\NetworkEnum;
  23. use App\Enum\Organization\AddressPostalOrganizationTypeEnum;
  24. use App\Enum\Person\AddressPostalPersonTypeEnum;
  25. use App\Repository\Core\CountryRepository;
  26. use App\Repository\Organization\OrganizationRepository;
  27. use App\Repository\Person\PersonRepository;
  28. use App\Service\Dolibarr\DolibarrApiService;
  29. use App\Service\Typo3\BindFileService;
  30. use App\Service\Typo3\SubdomainService;
  31. use App\Service\Typo3\Typo3Service;
  32. use App\Service\Utils\DatesUtils;
  33. use App\Service\Utils\SecurityUtils;
  34. use Doctrine\Common\Collections\Collection;
  35. use Doctrine\ORM\EntityManagerInterface;
  36. use Elastica\Param;
  37. use Exception;
  38. use libphonenumber\NumberParseException;
  39. use libphonenumber\PhoneNumberUtil;
  40. use Psr\Log\LoggerInterface;
  41. use SebastianBergmann\Type\RuntimeException;
  42. use Symfony\Component\HttpFoundation\Response;
  43. use Symfony\Component\String\ByteString;
  44. use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
  45. use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
  46. use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
  47. use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
  48. use Symfony\Contracts\Service\Attribute\Required;
  49. use Throwable;
  50. use App\Service\Organization\Utils as OrganizationUtils;
  51. class OrganizationFactory
  52. {
  53. private LoggerInterface $logger;
  54. public function __construct(
  55. private readonly SubdomainService $subdomainService,
  56. private readonly OrganizationRepository $organizationRepository,
  57. private readonly CountryRepository $countryRepository,
  58. private readonly OrganizationUtils $organizationUtils,
  59. private readonly Typo3Service $typo3Service,
  60. private readonly DolibarrApiService $dolibarrApiService,
  61. private readonly EntityManagerInterface $entityManager,
  62. private readonly PersonRepository $personRepository,
  63. private readonly BindFileService $bindFileService,
  64. ) {}
  65. #[Required]
  66. /** @see https://symfony.com/doc/current/logging/channels_handlers.html#how-to-autowire-logger-channels */
  67. public function setLoggerInterface(LoggerInterface $adminLogger): void
  68. {
  69. $this->logger = $adminLogger;
  70. }
  71. /**
  72. * Créé une nouvelle organisation à partir des données contenues dans une OrganizationCreationRequest
  73. *
  74. * @param OrganizationCreationRequest $organizationCreationRequest
  75. * @return Organization
  76. * @throws TransportExceptionInterface
  77. * @throws Throwable
  78. */
  79. public function create(OrganizationCreationRequest $organizationCreationRequest): Organization
  80. {
  81. $this->logger->info(
  82. "Start the creation of a new organization named '" . $organizationCreationRequest->getName() . "'"
  83. );
  84. $this->entityManager->beginTransaction();
  85. try {
  86. // On vérifie si cette organisation n'existe pas déjà
  87. if ($this->isExistingOrganization($organizationCreationRequest)) {
  88. throw new \RuntimeException('An organization named ' . $organizationCreationRequest->getName() . ' already exists');
  89. }
  90. // On vérifie la validité et la disponibilité du sous domaine
  91. $this->validateSubdomain($organizationCreationRequest->getSubdomain());
  92. $this->logger->info("Subdomain is valid and available : '" . $organizationCreationRequest->getSubdomain() . "'");
  93. // On construit l'organisation et ses relations
  94. $organization = $this->makeOrganizationWithRelations($organizationCreationRequest);
  95. $this->logger->info("Organization created with all its relations");
  96. // On persiste et on commit
  97. $this->entityManager->persist($organization);
  98. $this->entityManager->flush();
  99. // Création de la société Dolibarr
  100. $dolibarrId = $this->dolibarrApiService->createSociety(
  101. $organization,
  102. $organizationCreationRequest->isClient()
  103. );
  104. $this->logger->info("New dolibarr structure created (uid : " . $dolibarrId . ")");
  105. $this->entityManager->commit();
  106. $this->logger->debug(" - New entities committed in DB");
  107. $this->logger->info("Organization persisted in the DB");
  108. } catch (\Exception $e) {
  109. $this->logger->critical("An error happened, operation cancelled\n" . $e);
  110. $this->entityManager->rollback();
  111. throw $e;
  112. }
  113. // Register the subdomain into the BindFile (takes up to 5min to take effect)
  114. $this->bindFileService->registerSubdomain($organizationCreationRequest->getSubdomain());
  115. $this->logger->info("Subdomain registered");
  116. // Création du site typo3 (on est obligé d'attendre que l'organisation soit persistée en base)
  117. if ($organizationCreationRequest->getCreateWebsite()) {
  118. $this->createTypo3Website($organization);
  119. } else {
  120. $this->logger->warning("Typo3 website creation was not required");
  121. }
  122. return $organization;
  123. }
  124. /**
  125. * Une organisation du même nom existe-t-elle déjà à la même adresse ?
  126. *
  127. * @param OrganizationCreationRequest $organizationCreationRequest
  128. * @return bool
  129. */
  130. protected function isExistingOrganization(OrganizationCreationRequest $organizationCreationRequest): bool
  131. {
  132. return $this
  133. ->organizationRepository
  134. ->count(
  135. [
  136. 'name' => $organizationCreationRequest->getName(),
  137. ]
  138. ) > 0;
  139. }
  140. /**
  141. * Vérifie la disponibilité et la validité d'un sous domaine
  142. *
  143. * @param string $subdomainValue
  144. * @return void
  145. * @throws \Exception
  146. */
  147. protected function validateSubdomain(string $subdomainValue): void
  148. {
  149. if (!$this->subdomainService->isValidSubdomain($subdomainValue)) {
  150. throw new \RuntimeException("Not a valid subdomain : " . $subdomainValue);
  151. }
  152. if ($this->subdomainService->isReservedSubdomain($subdomainValue)) {
  153. throw new \RuntimeException("This subdomain is not available : " . $subdomainValue);
  154. }
  155. if ($this->subdomainService->isRegistered($subdomainValue)) {
  156. throw new \RuntimeException("This subdomain is already registered : " . $subdomainValue);
  157. }
  158. }
  159. /**
  160. * Créé une nouvelle instance d'organisation, et toutes les instances liées (paramètres, contact, adresses, ...),
  161. * selon le contenu de la requête de création.
  162. *
  163. * @param OrganizationCreationRequest $organizationCreationRequest
  164. * @return Organization
  165. * @throws Throwable
  166. */
  167. protected function makeOrganizationWithRelations(
  168. OrganizationCreationRequest $organizationCreationRequest
  169. ): Organization
  170. {
  171. // Création de l'organisation
  172. $organization = $this->makeOrganization($organizationCreationRequest);
  173. $this->logger->debug(" - Organization created");
  174. // Création des Parameters
  175. $parameters = $this->makeParameters($organizationCreationRequest);
  176. $organization->setParameters($parameters);
  177. $this->logger->debug(" - Parameters created");
  178. // Création des Settings
  179. $settings = $this->makeSettings($organizationCreationRequest);
  180. $organization->setSettings($settings);
  181. $this->logger->debug(" - Settings created");
  182. // Création de l'adresse postale
  183. $organizationAddressPostal = $this->makePostalAddress($organizationCreationRequest);
  184. $organization->addOrganizationAddressPostal($organizationAddressPostal);
  185. $this->logger->debug(" - OrganizationAddressPostal created");
  186. // Création du point de contact
  187. $contactPoint = $this->makeContactPoint($organizationCreationRequest);
  188. $organization->addContactPoint($contactPoint);
  189. $this->logger->debug(" - ContactPoint created");
  190. // Rattachement au réseau
  191. $networkOrganization = $this->makeNetworkOrganization($organizationCreationRequest);
  192. $organization->addNetworkOrganization($networkOrganization);
  193. $this->logger->debug(" - NetworkOrganization created");
  194. // Créé l'admin
  195. $adminAccess = $this->makeAdminAccess($organizationCreationRequest);
  196. $organization->addAccess($adminAccess);
  197. $this->logger->debug(" - Admin access created");
  198. // Création des cycles
  199. foreach ($this->makeCycles() as $cycle) {
  200. $organization->addCycle($cycle);
  201. }
  202. $this->logger->debug(" - Cycles created");
  203. // Création du président (si renseigné)
  204. $presidentCreationRequest = $organizationCreationRequest->getPresident();
  205. if ($presidentCreationRequest !== null) {
  206. $presidentAccess = $this->makeAccess($presidentCreationRequest);
  207. $organization->addAccess($presidentAccess);
  208. $this->logger->debug(" - President access created");
  209. }
  210. // Création du directeur (si renseigné)
  211. $directorCreationRequest = $organizationCreationRequest->getDirector();
  212. if ($directorCreationRequest !== null) {
  213. $directorAccess = $this->makeAccess($directorCreationRequest);
  214. $organization->addAccess($directorAccess);
  215. $this->logger->debug(" - Director access created");
  216. }
  217. // Création du sous-domaine
  218. $subdomain = $this->makeSubdomain($organizationCreationRequest);
  219. $subdomain->setOrganization($organization);
  220. // <--- Pour la rétrocompatibilité avec la v1 ; pourra être supprimé lorsque la migration sera achevée
  221. $parameters = $organization->getParameters();
  222. $parameters->setSubDomain($organizationCreationRequest->getSubdomain());
  223. $parameters->setOtherWebsite('https://' . $organizationCreationRequest->getSubdomain() . '.opentalent.fr');
  224. $this->entityManager->persist($parameters);
  225. // --->
  226. $this->logger->debug(" - Subdomain created");
  227. return $organization;
  228. }
  229. /**
  230. * Créé une nouvelle instance d'organisation
  231. *
  232. * @param OrganizationCreationRequest $organizationCreationRequest
  233. * @return Organization
  234. */
  235. protected function makeOrganization(OrganizationCreationRequest $organizationCreationRequest): Organization
  236. {
  237. // Création de l'organisation
  238. $organization = new Organization();
  239. $organization->setName($organizationCreationRequest->getName());
  240. $organization->setLegalStatus($organizationCreationRequest->getLegalStatus());
  241. $organization->setPrincipalType($organizationCreationRequest->getPrincipalType());
  242. $organization->setIdentifier($organizationCreationRequest->getIdentifier());
  243. $this->entityManager->persist($organization);
  244. return $organization;
  245. }
  246. /**
  247. * Create a new Parameters object from the data in an OrganizationCreationRequest
  248. *
  249. * @param OrganizationCreationRequest $organizationCreationRequest The organization creation request
  250. * @return Parameters The created Parameters object
  251. * @throws Throwable If there is an error
  252. */
  253. protected function makeParameters(OrganizationCreationRequest $organizationCreationRequest): Parameters
  254. {
  255. $parameters = new Parameters();
  256. $this->entityManager->persist($parameters);
  257. return $parameters;
  258. }
  259. /**
  260. * Creates a new instance of the Settings class based on the given OrganizationCreationRequest object.
  261. *
  262. * @param OrganizationCreationRequest $organizationCreationRequest The OrganizationCreationRequest object containing the required data.
  263. *
  264. * @return Settings The newly created instance of the Settings class.
  265. */
  266. protected function makeSettings(OrganizationCreationRequest $organizationCreationRequest): Settings
  267. {
  268. $settings = new Settings();
  269. $settings->setProduct($organizationCreationRequest->getProduct());
  270. $this->entityManager->persist($settings);
  271. return $settings;
  272. }
  273. /**
  274. * Creates a new instance of the OrganizationAddressPostal class based on the given OrganizationCreationRequest object.
  275. *
  276. * @param OrganizationCreationRequest $organizationCreationRequest The OrganizationCreationRequest object containing the required data.
  277. *
  278. * @return OrganizationAddressPostal The newly created instance of the OrganizationAddressPostal class.
  279. */
  280. protected function makePostalAddress(OrganizationCreationRequest $organizationCreationRequest): OrganizationAddressPostal
  281. {
  282. $addressPostal = new AddressPostal();
  283. $addressPostal->setStreetAddress($organizationCreationRequest->getStreetAddress1());
  284. $addressPostal->setStreetAddressSecond($organizationCreationRequest->getStreetAddress2());
  285. $addressPostal->setStreetAddressThird($organizationCreationRequest->getStreetAddress3());
  286. $addressPostal->setPostalCode($organizationCreationRequest->getPostalCode());
  287. $addressPostal->setAddressCity($organizationCreationRequest->getCity());
  288. $country = $this->countryRepository->find($organizationCreationRequest->getCountryId());
  289. $addressPostal->setAddressCountry($country);
  290. $this->entityManager->persist($addressPostal);
  291. $organizationAddressPostal = new OrganizationAddressPostal();
  292. $organizationAddressPostal->setAddressPostal($addressPostal);
  293. $organizationAddressPostal->setType(AddressPostalOrganizationTypeEnum::ADDRESS_HEAD_OFFICE);
  294. $this->entityManager->persist($organizationAddressPostal);
  295. return $organizationAddressPostal;
  296. }
  297. /**
  298. * Creates a new instance of the ContactPoint class based on the given OrganizationCreationRequest object.
  299. *
  300. * @param OrganizationCreationRequest $organizationCreationRequest The OrganizationCreationRequest object containing the required data.
  301. *
  302. * @return ContactPoint The newly created instance of the ContactPoint class.
  303. * @throws NumberParseException
  304. */
  305. protected function makeContactPoint(OrganizationCreationRequest $organizationCreationRequest): ContactPoint
  306. {
  307. $phoneUtil = PhoneNumberUtil::getInstance();
  308. $phoneNumber = $phoneUtil->parse($organizationCreationRequest->getPhoneNumber());
  309. $contactPoint = new ContactPoint();
  310. $contactPoint->setContactType(ContactPointTypeEnum::PRINCIPAL);
  311. $contactPoint->setEmail($organizationCreationRequest->getEmail());
  312. $contactPoint->setTelphone($phoneNumber);
  313. $this->entityManager->persist($contactPoint);
  314. return $contactPoint;
  315. }
  316. /**
  317. * Creates a new instance of the NetworkOrganization class based on the given OrganizationCreationRequest object.
  318. *
  319. * @param OrganizationCreationRequest $organizationCreationRequest The OrganizationCreationRequest object containing the required data.
  320. *
  321. * @return NetworkOrganization The newly created instance of the NetworkOrganization class.
  322. *
  323. * @throws \RuntimeException|\Exception if no parent organization is found for the given parent ID or if no network is found for the given network ID.
  324. */
  325. protected function makeNetworkOrganization(OrganizationCreationRequest $organizationCreationRequest): NetworkOrganization
  326. {
  327. $parent = $this->organizationRepository->find($organizationCreationRequest->getParentId());
  328. if (!$parent) {
  329. throw new \RuntimeException('No parent organization found for id ' . $organizationCreationRequest->getParentId());
  330. }
  331. $networkOrganization = $this->organizationUtils->getActiveNetworkOrganization($parent);
  332. if (!$networkOrganization) {
  333. throw new \RuntimeException('No network found for parent ' . $organizationCreationRequest->getParentId());
  334. }
  335. $network = $networkOrganization->getNetwork();
  336. // Si réseau CMF, on vérifie que le matricule est valide
  337. if ($network->getId() === NetworkEnum::CMF->value) {
  338. if (!preg_match("/FR\d{12}/", $organizationCreationRequest->getIdentifier())) {
  339. throw new \RuntimeException("CMF identifier is missing or invalid.");
  340. }
  341. }
  342. $networkOrganization = new NetworkOrganization();
  343. $networkOrganization->setParent($parent);
  344. $networkOrganization->setNetwork($network);
  345. $networkOrganization->setStartDate(DatesUtils::new());
  346. $this->entityManager->persist($networkOrganization);
  347. return $networkOrganization;
  348. }
  349. /**
  350. * Creates a new instance of the Access class with admin access based on the given OrganizationCreationRequest object.
  351. *
  352. * @param OrganizationCreationRequest $organizationCreationRequest The OrganizationCreationRequest object containing the required data.
  353. *
  354. * @return Access The newly created instance of the Access class with admin access.
  355. */
  356. protected function makeAdminAccess(OrganizationCreationRequest $organizationCreationRequest): Access
  357. {
  358. $admin = new Person();
  359. $admin->setUsername('admin' . strtolower($organizationCreationRequest->getSubdomain()));
  360. $randomString = ByteString::fromRandom(32)->toString();
  361. $admin->setPassword($randomString);
  362. $this->entityManager->persist($admin);
  363. $adminAccess = new Access();
  364. $adminAccess->setAdminAccess(true);
  365. $adminAccess->setPerson($admin);
  366. $this->entityManager->persist($adminAccess);
  367. return $adminAccess;
  368. }
  369. /**
  370. * Creates an array of Cycle objects based on a predefined set of data.
  371. *
  372. * @return Cycle[] An array of Cycle objects.
  373. */
  374. protected function makeCycles(): array
  375. {
  376. $cyclesData = [
  377. ['Cycle initiation', 10, CycleEnum::INITIATION_CYCLE],
  378. ['Cycle 1', 20, CycleEnum::CYCLE_1],
  379. ['Cycle 2', 30, CycleEnum::CYCLE_2],
  380. ['Cycle 3', 40, CycleEnum::CYCLE_3],
  381. ['Cycle 4', 50, CycleEnum::CYCLE_4],
  382. ['Hors cycle', 60, CycleEnum::OUT_CYCLE],
  383. ];
  384. $cycles = [];
  385. foreach ($cyclesData as $cycleData) {
  386. $cycle = new Cycle();
  387. $cycle->setLabel($cycleData[0]);
  388. $cycle->setOrder($cycleData[1]);
  389. $cycle->setCycleEnum($cycleData[2]);
  390. $cycle->setIsSystem(false);
  391. $this->entityManager->persist($cycle);
  392. $cycles[] = $cycle;
  393. }
  394. return $cycles;
  395. }
  396. /**
  397. * Creates an Access object based on the given OrganizationMemberCreationRequest.
  398. *
  399. * @param int|OrganizationMemberCreationRequest $creationRequestData The request object containing the
  400. * necessary data for creating a Person object,
  401. * or the id of an existing one.
  402. * @return Access The created Access object.
  403. * @throws NumberParseException
  404. */
  405. protected function makeAccess(
  406. int | OrganizationMemberCreationRequest $creationRequestData
  407. ): Access
  408. {
  409. if (is_int($creationRequestData)) {
  410. $person = $this->personRepository->find($creationRequestData);
  411. } else {
  412. $person = new Person();
  413. $person->setUsername($creationRequestData->getUsername());
  414. $person->setPassword(ByteString::fromRandom(32)->toString());
  415. $person->setGender($creationRequestData->getGender());
  416. $person->setName(
  417. ucfirst(strtolower($creationRequestData->getName()))
  418. );
  419. $person->setGivenName(
  420. ucfirst(strtolower($creationRequestData->getGivenName()))
  421. );
  422. $personPostalAddress = $this->makePersonPostalAddress($creationRequestData);
  423. $person->addPersonAddressPostal($personPostalAddress);
  424. $contactPoint = $this->makePersonContactPoint($creationRequestData);
  425. $person->addContactPoint($contactPoint);
  426. $this->entityManager->persist($person);
  427. }
  428. $access = new Access();
  429. $access->setPerson($person);
  430. $this->entityManager->persist($access);
  431. return $access;
  432. }
  433. /**
  434. * Creates a PersonAddressPostal object based on the given OrganizationMemberCreationRequest.
  435. *
  436. * @param OrganizationMemberCreationRequest $organizationMemberCreationRequest The request object containing the
  437. * necessary data for creating a
  438. * PersonAddressPostal object.
  439. * @return PersonAddressPostal The created PersonAddressPostal object.
  440. */
  441. protected function makePersonPostalAddress(OrganizationMemberCreationRequest $organizationMemberCreationRequest): PersonAddressPostal
  442. {
  443. $addressPostal = new AddressPostal();
  444. $addressPostal->setStreetAddress($organizationMemberCreationRequest->getStreetAddress1());
  445. $addressPostal->setStreetAddressSecond($organizationMemberCreationRequest->getStreetAddress2());
  446. $addressPostal->setStreetAddressThird($organizationMemberCreationRequest->getStreetAddress3());
  447. $addressPostal->setPostalCode($organizationMemberCreationRequest->getPostalCode());
  448. $addressPostal->setAddressCity($organizationMemberCreationRequest->getCity());
  449. $country = $this->countryRepository->find($organizationMemberCreationRequest->getCountryId());
  450. $addressPostal->setAddressCountry($country);
  451. $this->entityManager->persist($addressPostal);
  452. $personAddressPostal = new PersonAddressPostal();
  453. $personAddressPostal->setAddressPostal($addressPostal);
  454. $personAddressPostal->setType(AddressPostalPersonTypeEnum::ADDRESS_PRINCIPAL);
  455. $this->entityManager->persist($personAddressPostal);
  456. return $personAddressPostal;
  457. }
  458. /**
  459. * Creates a new instance of the ContactPoint class based on the given OrganizationCreationRequest object.
  460. *
  461. * @param OrganizationMemberCreationRequest $organizationMemberCreationRequest The OrganizationMemberCreationRequest object containing the required data.
  462. *
  463. * @return ContactPoint The newly created instance of the ContactPoint class.
  464. * @throws NumberParseException
  465. */
  466. protected function makePersonContactPoint(OrganizationMemberCreationRequest $organizationMemberCreationRequest): ContactPoint
  467. {
  468. $phoneUtil = PhoneNumberUtil::getInstance();
  469. $phoneNumber = $phoneUtil->parse($organizationMemberCreationRequest->getPhone());
  470. $contactPoint = new ContactPoint();
  471. $contactPoint->setContactType(ContactPointTypeEnum::PRINCIPAL);
  472. $contactPoint->setEmail($organizationMemberCreationRequest->getEmail());
  473. $contactPoint->setTelphone($phoneNumber);
  474. if ($organizationMemberCreationRequest->getMobile() !== null) {
  475. $mobileNumber = $phoneUtil->parse($organizationMemberCreationRequest->getMobile());
  476. $contactPoint->setMobilPhone($mobileNumber);
  477. }
  478. $this->entityManager->persist($contactPoint);
  479. return $contactPoint;
  480. }
  481. protected function makeSubdomain(OrganizationCreationRequest $organizationCreationRequest): Subdomain
  482. {
  483. $subdomain = new Subdomain();
  484. $subdomain->setSubdomain($organizationCreationRequest->getSubdomain());
  485. $subdomain->setActive(true);
  486. $this->entityManager->persist($subdomain);
  487. return $subdomain;
  488. }
  489. /**
  490. * Créé le site Typo3 et retourne l'id de la page racine du site nouvellement créé, ou null en cas d'erreur
  491. *
  492. * @throws RedirectionExceptionInterface
  493. * @throws ClientExceptionInterface
  494. * @throws TransportExceptionInterface
  495. * @throws ServerExceptionInterface
  496. */
  497. protected function createTypo3Website(Organization $organization): ?int {
  498. $response = $this->typo3Service->createSite($organization->getId());
  499. $rootPageUid = json_decode($response->getContent(), true);
  500. if ($response->getStatusCode() === Response::HTTP_OK && $rootPageUid > 0) {
  501. // TODO: revoir l'utilité du champs cmsId
  502. $organization->setCmsId($rootPageUid);
  503. $this->entityManager->persist($organization);
  504. $this->entityManager->flush();
  505. return $rootPageUid;
  506. } else {
  507. $this->logger->critical("/!\ A critical error happened while creating the Typo3 website");
  508. $this->logger->debug($response->getContent());
  509. }
  510. return null;
  511. }
  512. /**
  513. * /!\ Danger zone /!\
  514. *
  515. * Supprime définitivement une organisation, ses données, ses fichiers, son site internet, et son profil Dolibarr.
  516. *
  517. * Pour éviter une suppression accidentelle, cette méthode ne doit pouvoir être exécutée que si la requête a été
  518. * envoyée depuis le localhost.
  519. *
  520. * @param OrganizationDeletionRequest $organizationDeletionRequest
  521. * @return OrganizationDeletionRequest
  522. * @throws Exception
  523. */
  524. public function delete(OrganizationDeletionRequest $organizationDeletionRequest): OrganizationDeletionRequest
  525. {
  526. SecurityUtils::preventIfNotLocalhost();
  527. $organization = $this->organizationRepository->find($organizationDeletionRequest->getOrganizationId());
  528. $this->logger->info(
  529. "Start the deletion of organization '" . $organization->getName() . "' [" . $organization->getId() . "]"
  530. );
  531. $this->entityManager->beginTransaction();
  532. $withError = false;
  533. try {
  534. // On doit gérer à part la suppression des Access afin de supprimer au passage les Person devenues 'orphelines'
  535. $this->deleteOrganizationAccesses($organization);
  536. // On est obligé de supprimer manuellement les paramètres, car c'est l'entité Parameters qui est
  537. // propriétaire de la relation Organization ↔ Parameters.
  538. $this->entityManager->remove($organization->getParameters());
  539. // Toutes les autres entités liées seront supprimées en cascade
  540. $this->entityManager->remove($organization);
  541. $this->entityManager->flush();
  542. $this->entityManager->commit();
  543. } catch (\Exception $e) {
  544. $this->logger->critical("An error happened, operation cancelled\n" . $e);
  545. $this->entityManager->rollback();
  546. throw $e;
  547. }
  548. try {
  549. $this->deleteTypo3Website($organization);
  550. } catch (\Exception $e) {
  551. $this->logger->critical("An error happened while deleting the Typo3 website, please proceed manually.");
  552. $this->logger->debug($e);
  553. $withError = true;
  554. }
  555. try {
  556. $this->switchDolibarrSocietyToProspect($organization);
  557. } catch (\Exception $e) {
  558. $this->logger->critical("An error happened while updating the Dolibarr society, please proceed manually.");
  559. $this->logger->debug($e);
  560. $withError = true;
  561. }
  562. try {
  563. $this->deleteLocalDirectories($organization);
  564. } catch (\Exception $e) {
  565. $this->logger->critical("An error happened while deleting the local directories, please proceed manually.");
  566. $this->logger->debug($e);
  567. $withError = true;
  568. }
  569. try {
  570. $this->deleteDirectoriesV1($organization);
  571. } catch (\Exception $e) {
  572. $this->logger->critical("An error happened while deleting the V1 directories, please proceed manually.");
  573. $this->logger->debug($e);
  574. $withError = true;
  575. }
  576. try {
  577. $this->deleteDirectories59($organization);
  578. } catch (\Exception $e) {
  579. $this->logger->critical("An error happened while deleting the 5.9 directories, please proceed manually.");
  580. $this->logger->debug($e);
  581. $withError = true;
  582. }
  583. if ($withError) {
  584. $organizationDeletionRequest->setStatus(OrganizationDeletionRequest::STATUS_OK_WITH_ERRORS);
  585. $this->logger->warning("-- Operation ended with errors, check the logs for more information --");
  586. } else {
  587. $organizationDeletionRequest->setStatus(OrganizationDeletionRequest::STATUS_OK);
  588. }
  589. return $organizationDeletionRequest;
  590. }
  591. /**
  592. * Supprime tous les Access d'une organisation, ainsi que la Person
  593. * rattachée (si celle-ci n'est pas liée à d'autres Access)
  594. *
  595. * @param Organization $organization
  596. * @return void
  597. */
  598. protected function deleteOrganizationAccesses(Organization $organization): void
  599. {
  600. foreach ($organization->getAccesses() as $access) {
  601. $person = $access->getPerson();
  602. if ($person->getAccesses()->count() === 1) {
  603. $this->entityManager->remove($person);
  604. }
  605. $this->entityManager->remove($access);
  606. }
  607. }
  608. // TODO: à revoir, c'est du many to many
  609. // protected function removeTypeOfPractices(Organization $organization): void {
  610. // foreach ($organization->getTypeOfPractices() as $typeOfPractice) {
  611. // $organization->removeTypeOfPractice($typeOfPractice);
  612. // }
  613. // }
  614. // TODO: à revoir, c'est du many to many
  615. // protected function deleteContactPoints(Organization $organization): void
  616. // {
  617. // foreach ($organization->getContactPoints() as $contactPoint) {
  618. // $this->entityManager->remove($contactPoint);
  619. // }
  620. // }
  621. // TODO: à revoir, c'est du many to many
  622. // protected function deleteBankAccounts(Organization $organization): void {
  623. // foreach ($organization->getBankAccounts() as $bankAccount) {
  624. // $this->entityManager->remove($bankAccount);
  625. // }
  626. // }
  627. protected function deleteTypo3Website(Organization $organization): void
  628. {
  629. // TODO: implement
  630. // $this->typo3Service->deleteSite($organization->getId());
  631. }
  632. protected function switchDolibarrSocietyToProspect(Organization $organization): void
  633. {
  634. $this->dolibarrApiService->switchSocietyToProspect($organization->getId());
  635. }
  636. protected function deleteLocalDirectories(Organization $organization): void
  637. {
  638. // TODO: implement
  639. }
  640. protected function deleteDirectoriesV1(Organization $organization): void
  641. {
  642. // TODO: implement
  643. }
  644. protected function deleteDirectories59(Organization $organization): void
  645. {
  646. // TODO: implement
  647. }
  648. }