OrganizationFactory.php 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909
  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\Access\OrganizationFunction;
  8. use App\Entity\Core\AddressPostal;
  9. use App\Entity\Core\ContactPoint;
  10. use App\Entity\Education\Cycle;
  11. use App\Entity\Network\NetworkOrganization;
  12. use App\Entity\Organization\Organization;
  13. use App\Entity\Organization\OrganizationAddressPostal;
  14. use App\Entity\Organization\Parameters;
  15. use App\Entity\Organization\Settings;
  16. use App\Entity\Organization\Subdomain;
  17. use App\Entity\Person\Person;
  18. use App\Entity\Person\PersonAddressPostal;
  19. use App\Enum\Access\FunctionEnum;
  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\Organization\SettingsProductEnum;
  25. use App\Enum\Person\AddressPostalPersonTypeEnum;
  26. use App\Repository\Access\FunctionTypeRepository;
  27. use App\Repository\Core\CountryRepository;
  28. use App\Repository\Organization\OrganizationIdentificationRepository;
  29. use App\Repository\Organization\OrganizationRepository;
  30. use App\Repository\Person\PersonRepository;
  31. use App\Service\ApiLegacy\ApiLegacyRequestService;
  32. use App\Service\Dolibarr\DolibarrApiService;
  33. use App\Service\File\FileManager;
  34. use App\Service\Organization\Utils as OrganizationUtils;
  35. use App\Service\Typo3\BindFileService;
  36. use App\Service\Typo3\SubdomainService;
  37. use App\Service\Typo3\Typo3Service;
  38. use App\Service\Utils\DatesUtils;
  39. use App\Service\Utils\UrlBuilder;
  40. use App\Service\Utils\SecurityUtils;
  41. use Doctrine\ORM\EntityManagerInterface;
  42. use Elastica\Param;
  43. use libphonenumber\NumberParseException;
  44. use libphonenumber\PhoneNumberUtil;
  45. use Psr\Log\LoggerInterface;
  46. use Symfony\Component\HttpFoundation\Response;
  47. use Symfony\Component\String\ByteString;
  48. use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
  49. use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
  50. use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
  51. use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
  52. use Symfony\Contracts\Service\Attribute\Required;
  53. class OrganizationFactory
  54. {
  55. private LoggerInterface $logger;
  56. protected PhoneNumberUtil $phoneNumberUtil;
  57. public function __construct(
  58. private readonly SubdomainService $subdomainService,
  59. private readonly OrganizationRepository $organizationRepository,
  60. private readonly CountryRepository $countryRepository,
  61. private readonly OrganizationUtils $organizationUtils,
  62. private readonly Typo3Service $typo3Service,
  63. private readonly DolibarrApiService $dolibarrApiService,
  64. private readonly EntityManagerInterface $entityManager,
  65. private readonly PersonRepository $personRepository,
  66. private readonly BindFileService $bindFileService,
  67. private readonly OrganizationIdentificationRepository $organizationIdentificationRepository,
  68. private readonly ApiLegacyRequestService $apiLegacyRequestService,
  69. private readonly FunctionTypeRepository $functionTypeRepository,
  70. ) {
  71. $this->phoneNumberUtil = PhoneNumberUtil::getInstance();
  72. }
  73. #[Required]
  74. /** @see https://symfony.com/doc/current/logging/channels_handlers.html#how-to-autowire-logger-channels */
  75. public function setLoggerInterface(LoggerInterface $adminLogger): void
  76. {
  77. $this->logger = $adminLogger;
  78. }
  79. /**
  80. * Créé une nouvelle organisation à partir des données contenues dans une OrganizationCreationRequest.
  81. *
  82. * @throws TransportExceptionInterface
  83. * @throws \Throwable
  84. */
  85. public function create(OrganizationCreationRequest $organizationCreationRequest): Organization
  86. {
  87. $this->logger->info(
  88. "Start the creation of a new organization named '".$organizationCreationRequest->getName()."'"
  89. );
  90. $this->entityManager->beginTransaction();
  91. try {
  92. // On vérifie si cette organisation n'existe pas déjà
  93. $this->interruptIfOrganizationExists($organizationCreationRequest);
  94. // On vérifie la validité et la disponibilité du sous domaine
  95. $this->validateSubdomain($organizationCreationRequest->getSubdomain());
  96. $this->logger->info("Subdomain is valid and available : '".$organizationCreationRequest->getSubdomain()."'");
  97. // On construit l'organisation et ses relations
  98. $organization = $this->makeOrganizationWithRelations($organizationCreationRequest);
  99. $this->logger->info('Organization created with all its relations');
  100. // On persiste et on commit, les objets liés seront persistés en cascade
  101. $this->entityManager->persist($organization);
  102. $this->entityManager->flush();
  103. $this->entityManager->commit();
  104. $this->logger->debug(' - New entities committed in DB');
  105. $this->logger->info('Organization persisted in the DB');
  106. } catch (\Throwable $e) {
  107. $this->logger->critical("An error happened, operation cancelled\n".$e);
  108. $this->entityManager->rollback();
  109. throw $e;
  110. }
  111. $withError = false;
  112. // Création de la société Dolibarr
  113. try {
  114. $dolibarrId = $this->dolibarrApiService->createSociety(
  115. $organization,
  116. $organizationCreationRequest->isClient()
  117. );
  118. $this->logger->info('New dolibarr structure created (uid : '.$dolibarrId.')');
  119. } catch (\Throwable $e) {
  120. $this->logger->critical('An error happened while creating the dolibarr society, please proceed manually.');
  121. $this->logger->debug($e);
  122. $withError = true;
  123. }
  124. // Register the subdomain into the BindFile (takes up to 5min to take effect)
  125. try {
  126. $this->bindFileService->registerSubdomain($organizationCreationRequest->getSubdomain());
  127. $this->logger->info('Subdomain registered');
  128. } catch (\Throwable $e) {
  129. $this->logger->critical('An error happened while updating the bind file, please proceed manually.');
  130. $this->logger->debug($e);
  131. $withError = true;
  132. }
  133. // Création du site typo3 (on est obligé d'attendre que l'organisation soit persistée en base)
  134. if ($organizationCreationRequest->getCreateWebsite()) {
  135. try {
  136. $rootUid = $this->createTypo3Website($organization);
  137. $this->logger->info('Typo3 website created (root uid: '.$rootUid.')');
  138. } catch (\Throwable $e) {
  139. $this->logger->critical('An error happened while creating the typo3 website, please proceed manually.');
  140. $this->logger->debug($e);
  141. $withError = true;
  142. }
  143. } else {
  144. $this->logger->warning('Typo3 website creation was not required');
  145. }
  146. // Création de l'organisation dans la base adminassos (géré par la V1)
  147. try {
  148. $this->updateAdminassosDb($organization);
  149. $this->logger->info('Adminassos db updated');
  150. } catch (\Throwable $e) {
  151. $this->logger->critical('An error happened while updating the adminassos db, please proceed manually.');
  152. $this->logger->debug($e);
  153. $withError = true;
  154. }
  155. if ($withError) {
  156. $organizationCreationRequest->setStatus(OrganizationCreationRequest::STATUS_OK_WITH_ERRORS);
  157. $this->logger->warning('-- Operation ended with errors, check the logs for more information --');
  158. } else {
  159. $organizationCreationRequest->setStatus(OrganizationCreationRequest::STATUS_OK);
  160. }
  161. return $organization;
  162. }
  163. /**
  164. * Lève une exception si cette organisation existe déjà.
  165. */
  166. protected function interruptIfOrganizationExists(OrganizationCreationRequest $organizationCreationRequest): void
  167. {
  168. if (
  169. $organizationCreationRequest->getSiretNumber()
  170. && $this->organizationIdentificationRepository->findOneBy(
  171. ['siretNumber' => $organizationCreationRequest->getSiretNumber()]
  172. )
  173. ) {
  174. throw new \RuntimeException("This siret number is already registered : '".$organizationCreationRequest->getSiretNumber()."'");
  175. }
  176. if (
  177. $organizationCreationRequest->getWaldecNumber()
  178. && $this->organizationIdentificationRepository->findOneBy(
  179. ['waldecNumber' => $organizationCreationRequest->getWaldecNumber()]
  180. )
  181. ) {
  182. throw new \RuntimeException("This RNA identifier (waldec number) is already registered : '".$organizationCreationRequest->getWaldecNumber()."'");
  183. }
  184. if (
  185. $organizationCreationRequest->getIdentifier()
  186. && $this->organizationIdentificationRepository->findOneBy(
  187. ['identifier' => $organizationCreationRequest->getIdentifier()]
  188. )
  189. ) {
  190. throw new \RuntimeException("This CMF identifier is already registered : '".$organizationCreationRequest->getIdentifier()."'");
  191. }
  192. $normalizedName = $this->normalizeIdentificationField($organizationCreationRequest->getName());
  193. if (
  194. $this->organizationIdentificationRepository->findOneBy(
  195. ['normalizedName' => $normalizedName, 'addressCity' => $organizationCreationRequest->getCity()]
  196. )
  197. ) {
  198. throw new \RuntimeException("An organization named '".$organizationCreationRequest->getName()."' already exists in ".$organizationCreationRequest->getCity());
  199. }
  200. $address = $this->normalizeIdentificationField(implode(' ', [
  201. $organizationCreationRequest->getStreetAddress1(),
  202. $organizationCreationRequest->getStreetAddress2(),
  203. $organizationCreationRequest->getStreetAddress3(),
  204. ]));
  205. if (
  206. $this->organizationIdentificationRepository->findOneBy(
  207. [
  208. 'normalizedAddress' => $address,
  209. 'addressCity' => $organizationCreationRequest->getCity(),
  210. 'postalCode' => $organizationCreationRequest->getPostalCode(),
  211. ]
  212. )
  213. ) {
  214. throw new \RuntimeException('An organization already exists at this address.');
  215. }
  216. }
  217. /**
  218. * Vérifie la disponibilité et la validité d'un sous domaine.
  219. *
  220. * @throws \Exception
  221. */
  222. protected function validateSubdomain(string $subdomainValue): void
  223. {
  224. if (!$this->subdomainService->isValidSubdomain($subdomainValue)) {
  225. throw new \RuntimeException('Not a valid subdomain : '.$subdomainValue);
  226. }
  227. if ($this->subdomainService->isReservedSubdomain($subdomainValue)) {
  228. throw new \RuntimeException('This subdomain is not available : '.$subdomainValue);
  229. }
  230. if ($this->subdomainService->isRegistered($subdomainValue)) {
  231. throw new \RuntimeException('This subdomain is already registered : '.$subdomainValue);
  232. }
  233. }
  234. /**
  235. * Créé une nouvelle instance d'organisation, et toutes les instances liées (paramètres, contact, adresses, ...),
  236. * selon le contenu de la requête de création.
  237. *
  238. * @throws \Throwable
  239. */
  240. protected function makeOrganizationWithRelations(
  241. OrganizationCreationRequest $organizationCreationRequest,
  242. ): Organization {
  243. // Création de l'organisation
  244. $organization = $this->makeOrganization($organizationCreationRequest);
  245. $this->logger->debug(' - Organization created');
  246. // Création des Parameters
  247. $parameters = $this->makeParameters($organizationCreationRequest);
  248. $organization->setParameters($parameters);
  249. $this->logger->debug(' - Parameters created');
  250. // Création des Settings
  251. $settings = $this->makeSettings($organizationCreationRequest);
  252. $organization->setSettings($settings);
  253. $this->logger->debug(' - Settings created');
  254. // Création de l'adresse postale
  255. $organizationAddressPostal = $this->makePostalAddress($organizationCreationRequest);
  256. $organization->addOrganizationAddressPostal($organizationAddressPostal);
  257. $this->logger->debug(' - OrganizationAddressPostal created');
  258. // Création du point de contact
  259. $contactPoint = $this->makeContactPoint($organizationCreationRequest);
  260. $organization->addContactPoint($contactPoint);
  261. $this->logger->debug(' - ContactPoint created');
  262. // Rattachement au réseau
  263. $networkOrganization = $this->makeNetworkOrganization($organizationCreationRequest);
  264. $organization->addNetworkOrganization($networkOrganization);
  265. $this->logger->debug(' - NetworkOrganization created');
  266. // Créé l'admin
  267. $adminAccess = $this->makeAdminAccess($organizationCreationRequest);
  268. $organization->addAccess($adminAccess);
  269. $this->logger->debug(' - Admin access created');
  270. // Création des cycles
  271. foreach ($this->makeCycles() as $cycle) {
  272. $organization->addCycle($cycle);
  273. }
  274. $this->logger->debug(' - Cycles created');
  275. // Création du président (si renseigné)
  276. $presidentCreationRequest = $organizationCreationRequest->getPresident();
  277. if ($presidentCreationRequest !== null) {
  278. $presidentAccess = $this->makeAccess(
  279. $presidentCreationRequest,
  280. FunctionEnum::PRESIDENT,
  281. $organizationCreationRequest->getCreationDate(),
  282. $organizationCreationRequest->getAuthorId()
  283. );
  284. $organization->addAccess($presidentAccess);
  285. $this->logger->debug(' - President access created');
  286. }
  287. // Création du directeur (si renseigné)
  288. $directorCreationRequest = $organizationCreationRequest->getDirector();
  289. if ($directorCreationRequest !== null) {
  290. $directorAccess = $this->makeAccess(
  291. $directorCreationRequest,
  292. FunctionEnum::DIRECTOR,
  293. $organizationCreationRequest->getCreationDate(),
  294. $organizationCreationRequest->getAuthorId()
  295. );
  296. $organization->addAccess($directorAccess);
  297. $this->logger->debug(' - Director access created');
  298. }
  299. // Création du sous-domaine
  300. $subdomain = $this->makeSubdomain($organizationCreationRequest);
  301. $organization->addSubdomain($subdomain);
  302. // <--- Pour la rétrocompatibilité avec la v1 ; pourra être supprimé lorsque la migration sera achevée
  303. $parameters = $organization->getParameters();
  304. $parameters->setSubDomain($organizationCreationRequest->getSubdomain());
  305. $parameters->setOtherWebsite('https://'.$organizationCreationRequest->getSubdomain().'.opentalent.fr');
  306. // --->
  307. $this->logger->debug(' - Subdomain created');
  308. return $organization;
  309. }
  310. /**
  311. * Créé une nouvelle instance d'organisation.
  312. */
  313. protected function makeOrganization(OrganizationCreationRequest $organizationCreationRequest): Organization
  314. {
  315. // Création de l'organisation
  316. $organization = new Organization();
  317. $organization->setName($organizationCreationRequest->getName());
  318. $organization->setLegalStatus($organizationCreationRequest->getLegalStatus());
  319. $organization->setPrincipalType($organizationCreationRequest->getPrincipalType());
  320. $organization->setIdentifier($organizationCreationRequest->getIdentifier());
  321. $organization->setCreationDate($organizationCreationRequest->getCreationDate());
  322. $organization->setCreateDate($organizationCreationRequest->getCreationDate());
  323. $organization->setCreatedBy($organizationCreationRequest->getAuthorId());
  324. return $organization;
  325. }
  326. /**
  327. * Create a new Parameters object from the data in an OrganizationCreationRequest.
  328. *
  329. * @param OrganizationCreationRequest $organizationCreationRequest The organization creation request
  330. *
  331. * @return Parameters The created Parameters object
  332. *
  333. * @throws \Throwable If there is an error
  334. */
  335. protected function makeParameters(OrganizationCreationRequest $organizationCreationRequest): Parameters
  336. {
  337. $parameters = new Parameters();
  338. return $parameters;
  339. }
  340. /**
  341. * Creates a new instance of the Settings class based on the given OrganizationCreationRequest object.
  342. *
  343. * @param OrganizationCreationRequest $organizationCreationRequest the OrganizationCreationRequest object containing the required data
  344. *
  345. * @return Settings the newly created instance of the Settings class
  346. */
  347. protected function makeSettings(OrganizationCreationRequest $organizationCreationRequest): Settings
  348. {
  349. $settings = new Settings();
  350. $settings->setProduct($organizationCreationRequest->getProduct());
  351. // TODO: à revoir, pour étendre à d'autres pays (voir à remplacer le champs 'country' par un champs 'currency'?)
  352. $settings->setCountry(
  353. $organizationCreationRequest->getCountryId() === 41 ? 'SWITZERLAND' : 'FRANCE'
  354. );
  355. $settings->setCreateDate($organizationCreationRequest->getCreationDate());
  356. $settings->setCreatedBy($organizationCreationRequest->getAuthorId());
  357. return $settings;
  358. }
  359. /**
  360. * Creates a new instance of the OrganizationAddressPostal class based on the given OrganizationCreationRequest object.
  361. *
  362. * @param OrganizationCreationRequest $organizationCreationRequest the OrganizationCreationRequest object containing the required data
  363. *
  364. * @return OrganizationAddressPostal the newly created instance of the OrganizationAddressPostal class
  365. */
  366. protected function makePostalAddress(OrganizationCreationRequest $organizationCreationRequest): OrganizationAddressPostal
  367. {
  368. $country = $this->countryRepository->find($organizationCreationRequest->getCountryId());
  369. if (!$country) {
  370. throw new \RuntimeException('No country found for id '.$organizationCreationRequest->getCountryId());
  371. }
  372. $addressPostal = new AddressPostal();
  373. $addressPostal->setStreetAddress($organizationCreationRequest->getStreetAddress1());
  374. $addressPostal->setStreetAddressSecond($organizationCreationRequest->getStreetAddress2());
  375. $addressPostal->setStreetAddressThird($organizationCreationRequest->getStreetAddress3());
  376. $addressPostal->setPostalCode($organizationCreationRequest->getPostalCode());
  377. $addressPostal->setAddressCity($organizationCreationRequest->getCity());
  378. $addressPostal->setAddressCountry($country);
  379. $addressPostal->setCreateDate($organizationCreationRequest->getCreationDate());
  380. $addressPostal->setCreatedBy($organizationCreationRequest->getAuthorId());
  381. $organizationAddressPostal = new OrganizationAddressPostal();
  382. $organizationAddressPostal->setAddressPostal($addressPostal);
  383. $organizationAddressPostal->setType(AddressPostalOrganizationTypeEnum::ADDRESS_HEAD_OFFICE);
  384. $organizationAddressPostal->setCreateDate($organizationCreationRequest->getCreationDate());
  385. $organizationAddressPostal->setCreatedBy($organizationCreationRequest->getAuthorId());
  386. return $organizationAddressPostal;
  387. }
  388. /**
  389. * Creates a new instance of the ContactPoint class based on the given OrganizationCreationRequest object.
  390. *
  391. * @param OrganizationCreationRequest $organizationCreationRequest the OrganizationCreationRequest object containing the required data
  392. *
  393. * @return ContactPoint the newly created instance of the ContactPoint class
  394. *
  395. * @throws NumberParseException
  396. */
  397. protected function makeContactPoint(OrganizationCreationRequest $organizationCreationRequest): ContactPoint
  398. {
  399. if (!$this->phoneNumberUtil->isPossibleNumber($organizationCreationRequest->getPhoneNumber())) {
  400. throw new \RuntimeException('Phone number is invalid or missing');
  401. }
  402. $phoneNumber = $this->phoneNumberUtil->parse($organizationCreationRequest->getPhoneNumber());
  403. $contactPoint = new ContactPoint();
  404. $contactPoint->setContactType(ContactPointTypeEnum::PRINCIPAL);
  405. $contactPoint->setEmail($organizationCreationRequest->getEmail());
  406. $contactPoint->setTelphone($phoneNumber);
  407. $contactPoint->setCreateDate($organizationCreationRequest->getCreationDate());
  408. $contactPoint->setCreatedBy($organizationCreationRequest->getAuthorId());
  409. return $contactPoint;
  410. }
  411. /**
  412. * Creates a new instance of the NetworkOrganization class based on the given OrganizationCreationRequest object.
  413. *
  414. * @param OrganizationCreationRequest $organizationCreationRequest the OrganizationCreationRequest object containing the required data
  415. *
  416. * @return NetworkOrganization the newly created instance of the NetworkOrganization class
  417. *
  418. * @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
  419. */
  420. protected function makeNetworkOrganization(OrganizationCreationRequest $organizationCreationRequest): NetworkOrganization
  421. {
  422. $parent = $this->organizationRepository->find($organizationCreationRequest->getParentId());
  423. if (!$parent) {
  424. throw new \RuntimeException('No parent organization found for id '.$organizationCreationRequest->getParentId());
  425. }
  426. if ($parent->getSettings()->getProduct() !== SettingsProductEnum::MANAGER) {
  427. throw new \RuntimeException("Parent organization must have the product 'manager' (actual product: '".$parent->getSettings()->getProduct()->value."')");
  428. }
  429. $networkOrganization = $this->organizationUtils->getActiveNetworkOrganization($parent);
  430. if (!$networkOrganization) {
  431. throw new \RuntimeException('No network found for parent '.$organizationCreationRequest->getParentId());
  432. }
  433. $network = $networkOrganization->getNetwork();
  434. // Si réseau CMF, on vérifie que le matricule est valide
  435. if ($network->getId() === NetworkEnum::CMF->value) {
  436. if (!preg_match("/FR\d{12}/", $organizationCreationRequest->getIdentifier())) {
  437. throw new \RuntimeException('CMF identifier is missing or invalid.');
  438. }
  439. }
  440. $networkOrganization = new NetworkOrganization();
  441. $networkOrganization->setParent($parent);
  442. $networkOrganization->setNetwork($network);
  443. $networkOrganization->setStartDate(DatesUtils::new());
  444. $networkOrganization->setCreateDate($organizationCreationRequest->getCreationDate());
  445. $networkOrganization->setCreatedBy($organizationCreationRequest->getAuthorId());
  446. return $networkOrganization;
  447. }
  448. /**
  449. * Creates a new instance of the Access class with admin access based on the given OrganizationCreationRequest object.
  450. *
  451. * @param OrganizationCreationRequest $organizationCreationRequest the OrganizationCreationRequest object containing the required data
  452. *
  453. * @return Access the newly created instance of the Access class with admin access
  454. */
  455. protected function makeAdminAccess(OrganizationCreationRequest $organizationCreationRequest): Access
  456. {
  457. $admin = new Person();
  458. $admin->setUsername('admin'.strtolower($organizationCreationRequest->getSubdomain()));
  459. $randomString = ByteString::fromRandom(32)->toString();
  460. $admin->setPassword($randomString);
  461. $admin->setEnabled(true);
  462. $adminAccess = new Access();
  463. $adminAccess->setAdminAccess(true);
  464. $adminAccess->setPerson($admin);
  465. $adminAccess->setLoginEnabled(true);
  466. $adminAccess->setRoles(['ROLE_ADMIN', 'ROLE_ADMIN_CORE']);
  467. $adminAccess->setCreateDate($organizationCreationRequest->getCreationDate());
  468. $adminAccess->setCreatedBy($organizationCreationRequest->getAuthorId());
  469. $contactPoint = new ContactPoint();
  470. $contactPoint->setContactType(ContactPointTypeEnum::PRINCIPAL);
  471. $contactPoint->setEmail($organizationCreationRequest->getEmail());
  472. $admin->addContactPoint($contactPoint);
  473. return $adminAccess;
  474. }
  475. /**
  476. * Creates an array of Cycle objects based on a predefined set of data.
  477. *
  478. * @return Cycle[] an array of Cycle objects
  479. */
  480. protected function makeCycles(): array
  481. {
  482. $cyclesData = [
  483. ['Cycle initiation', 10, CycleEnum::INITIATION_CYCLE],
  484. ['Cycle 1', 20, CycleEnum::CYCLE_1],
  485. ['Cycle 2', 30, CycleEnum::CYCLE_2],
  486. ['Cycle 3', 40, CycleEnum::CYCLE_3],
  487. ['Cycle 4', 50, CycleEnum::CYCLE_4],
  488. ['Hors cycle', 60, CycleEnum::OUT_CYCLE],
  489. ];
  490. $cycles = [];
  491. foreach ($cyclesData as $cycleData) {
  492. $cycle = new Cycle();
  493. $cycle->setLabel($cycleData[0]);
  494. $cycle->setOrder($cycleData[1]);
  495. $cycle->setCycleEnum($cycleData[2]);
  496. $cycle->setIsSystem(false);
  497. $cycles[] = $cycle;
  498. }
  499. return $cycles;
  500. }
  501. /**
  502. * Creates an Access object based on the given OrganizationMemberCreationRequest.
  503. *
  504. * @param int|OrganizationMemberCreationRequest $creationRequestData the request object containing the
  505. * necessary data for creating a Person object,
  506. * or the id of an existing one
  507. *
  508. * @return Access the created Access object
  509. *
  510. * @throws NumberParseException
  511. */
  512. protected function makeAccess(
  513. int|OrganizationMemberCreationRequest $creationRequestData,
  514. FunctionEnum $function,
  515. \DateTime $creationDate,
  516. ?int $authorId,
  517. ): Access {
  518. if (is_int($creationRequestData)) {
  519. $person = $this->personRepository->find($creationRequestData);
  520. } else {
  521. $person = new Person();
  522. if ($this->personRepository->findOneBy(['username' => $creationRequestData->getUsername()])) {
  523. throw new \RuntimeException('Username already in use : '.$creationRequestData->getUsername());
  524. }
  525. $person->setUsername($creationRequestData->getUsername());
  526. $person->setPassword(ByteString::fromRandom(32)->toString());
  527. $person->setGender($creationRequestData->getGender());
  528. $person->setName(
  529. ucfirst(strtolower($creationRequestData->getName()))
  530. );
  531. $person->setGivenName(
  532. ucfirst(strtolower($creationRequestData->getGivenName()))
  533. );
  534. $personPostalAddress = $this->makePersonPostalAddress($creationRequestData, $creationDate, $authorId);
  535. $person->addPersonAddressPostal($personPostalAddress);
  536. $contactPoint = $this->makePersonContactPoint($creationRequestData, $creationDate, $authorId);
  537. $person->addContactPoint($contactPoint);
  538. $person->setCreateDate($creationDate);
  539. $person->setCreatedBy($authorId);
  540. }
  541. $access = new Access();
  542. $access->setPerson($person);
  543. $functionType = $this->functionTypeRepository->findOneBy(['mission' => $function]);
  544. $organizationFunction = new OrganizationFunction();
  545. $organizationFunction->setFunctionType($functionType);
  546. $organizationFunction->setStartDate($creationDate);
  547. $organizationFunction->setCreateDate($creationDate);
  548. $organizationFunction->setCreatedBy($authorId);
  549. $access->addOrganizationFunction($organizationFunction);
  550. $access->setCreateDate($creationDate);
  551. $access->setCreatedBy($authorId);
  552. return $access;
  553. }
  554. /**
  555. * Creates a PersonAddressPostal object based on the given OrganizationMemberCreationRequest.
  556. *
  557. * @param OrganizationMemberCreationRequest $organizationMemberCreationRequest the request object containing the
  558. * necessary data for creating a
  559. * PersonAddressPostal object
  560. *
  561. * @return PersonAddressPostal the created PersonAddressPostal object
  562. */
  563. protected function makePersonPostalAddress(
  564. OrganizationMemberCreationRequest $organizationMemberCreationRequest,
  565. \DateTime $creationDate,
  566. ?int $authorId,
  567. ): PersonAddressPostal {
  568. $addressPostal = new AddressPostal();
  569. $addressPostal->setStreetAddress($organizationMemberCreationRequest->getStreetAddress1());
  570. $addressPostal->setStreetAddressSecond($organizationMemberCreationRequest->getStreetAddress2());
  571. $addressPostal->setStreetAddressThird($organizationMemberCreationRequest->getStreetAddress3());
  572. $addressPostal->setPostalCode($organizationMemberCreationRequest->getPostalCode());
  573. $addressPostal->setAddressCity($organizationMemberCreationRequest->getCity());
  574. $addressPostal->setCreateDate($creationDate);
  575. $addressPostal->setCreatedBy($authorId);
  576. $country = $this->countryRepository->find($organizationMemberCreationRequest->getCountryId());
  577. $addressPostal->setAddressCountry($country);
  578. $personAddressPostal = new PersonAddressPostal();
  579. $personAddressPostal->setAddressPostal($addressPostal);
  580. $personAddressPostal->setType(AddressPostalPersonTypeEnum::ADDRESS_PRINCIPAL);
  581. $personAddressPostal->setCreateDate($creationDate);
  582. $personAddressPostal->setCreatedBy($authorId);
  583. return $personAddressPostal;
  584. }
  585. /**
  586. * Creates a new instance of the ContactPoint class based on the given OrganizationCreationRequest object.
  587. *
  588. * @param OrganizationMemberCreationRequest $organizationMemberCreationRequest the OrganizationMemberCreationRequest object containing the required data
  589. *
  590. * @return ContactPoint the newly created instance of the ContactPoint class
  591. *
  592. * @throws NumberParseException
  593. */
  594. protected function makePersonContactPoint(
  595. OrganizationMemberCreationRequest $organizationMemberCreationRequest,
  596. \DateTime $creationDate,
  597. ?int $authorId,
  598. ): ContactPoint {
  599. if (!$this->phoneNumberUtil->isPossibleNumber($organizationMemberCreationRequest->getPhone())) {
  600. throw new \RuntimeException('Phone number is invalid or missing (person: '.$organizationMemberCreationRequest->getUsername().')');
  601. }
  602. if (
  603. $organizationMemberCreationRequest->getMobile() !== null
  604. && !$this->phoneNumberUtil->isPossibleNumber($organizationMemberCreationRequest->getMobile())) {
  605. throw new \RuntimeException('Mobile phone number is invalid (person: '.$organizationMemberCreationRequest->getUsername().')');
  606. }
  607. $phoneNumber = $this->phoneNumberUtil->parse($organizationMemberCreationRequest->getPhone());
  608. $contactPoint = new ContactPoint();
  609. $contactPoint->setContactType(ContactPointTypeEnum::PRINCIPAL);
  610. $contactPoint->setEmail($organizationMemberCreationRequest->getEmail());
  611. $contactPoint->setTelphone($phoneNumber);
  612. if ($organizationMemberCreationRequest->getMobile() !== null) {
  613. $mobileNumber = $this->phoneNumberUtil->parse($organizationMemberCreationRequest->getMobile());
  614. $contactPoint->setMobilPhone($mobileNumber);
  615. }
  616. $contactPoint->setCreateDate($creationDate);
  617. $contactPoint->setCreatedBy($authorId);
  618. return $contactPoint;
  619. }
  620. protected function makeSubdomain(OrganizationCreationRequest $organizationCreationRequest): Subdomain
  621. {
  622. $subdomain = new Subdomain();
  623. $subdomain->setSubdomain($organizationCreationRequest->getSubdomain());
  624. $subdomain->setActive(true);
  625. return $subdomain;
  626. }
  627. /**
  628. * Créé le site Typo3 et retourne l'id de la page racine du site nouvellement créé, ou null en cas d'erreur.
  629. *
  630. * @throws RedirectionExceptionInterface
  631. * @throws ClientExceptionInterface
  632. * @throws TransportExceptionInterface
  633. * @throws ServerExceptionInterface
  634. */
  635. protected function createTypo3Website(Organization $organization): ?int
  636. {
  637. $response = $this->typo3Service->createSite($organization->getId());
  638. $content = json_decode($response->getContent(), true);
  639. $rootPageUid = $content['root_uid'];
  640. if ($response->getStatusCode() === Response::HTTP_OK && $rootPageUid > 0) {
  641. // TODO: revoir l'utilité du champs cmsId
  642. $organization->setCmsId($rootPageUid);
  643. $this->entityManager->persist($organization);
  644. $this->entityManager->flush();
  645. return $rootPageUid;
  646. } else {
  647. $this->logger->critical("/!\ A critical error happened while creating the Typo3 website");
  648. $this->logger->debug($response->getContent());
  649. }
  650. return null;
  651. }
  652. protected function updateAdminassosDb(Organization $organization): void
  653. {
  654. $response = $this->apiLegacyRequestService->get(
  655. UrlBuilder::concatPath('/_internal/request/adminassos/create/organization/', [(string)$organization->getId()])
  656. );
  657. if ($response->getStatusCode() !== Response::HTTP_OK) {
  658. throw new \RuntimeException('An error happened while updating the adminassos database: '.$response->getContent());
  659. }
  660. }
  661. /**
  662. * Normalise la chaine comme sont normalisées les champs de l'entité OrganizationIdentification.
  663. *
  664. * @øee sql/schema-extensions/003-view_organization_identification.sql
  665. */
  666. protected function normalizeIdentificationField(string $value): string
  667. {
  668. $value = strtolower(trim($value));
  669. $value = preg_replace('/[éèê]/u', 'e', $value);
  670. $value = preg_replace('/[à]/u', 'a', $value);
  671. $value = preg_replace('/[ç]/u', 'c', $value);
  672. return preg_replace('/[^a-z0-9]+/u', '+', $value);
  673. }
  674. /**
  675. * /!\ Danger zone /!\.
  676. *
  677. * Supprime définitivement une organisation, ses données, ses fichiers, son site internet, et son profil Dolibarr.
  678. *
  679. * Pour éviter une suppression accidentelle, cette méthode ne doit pouvoir être exécutée que si la requête a été
  680. * envoyée depuis le localhost.
  681. *
  682. * @throws \Exception
  683. */
  684. public function delete(OrganizationDeletionRequest $organizationDeletionRequest): OrganizationDeletionRequest
  685. {
  686. SecurityUtils::preventIfNotLocalhost();
  687. $organization = $this->organizationRepository->find($organizationDeletionRequest->getOrganizationId());
  688. if (!$organization) {
  689. throw new \RuntimeException("No organization was found for id : " . $organizationDeletionRequest->getOrganizationId());
  690. }
  691. $this->logger->info(
  692. "Start the deletion of organization '".$organization->getName()."' [".$organization->getId().']'
  693. );
  694. $this->entityManager->beginTransaction();
  695. $withError = false;
  696. try {
  697. $orphanPersons = $this->getFutureOrphanPersons($organization);
  698. // On est obligé de supprimer manuellement les paramètres, car c'est l'entité Parameters qui est
  699. // propriétaire de la relation Organization ↔ Parameters.
  700. $this->entityManager->remove($organization->getParameters());
  701. // Toutes les autres entités liées seront supprimées en cascade
  702. $this->entityManager->remove($organization);
  703. // Supprime les personnes qui n'avaient pas d'autre Access attaché
  704. $deletedPersonIds = [];
  705. foreach ($orphanPersons as $person) {
  706. $deletedPersonIds[] = $person->getId();
  707. $this->entityManager->remove($person);
  708. }
  709. $this->entityManager->flush();
  710. $this->entityManager->commit();
  711. } catch (\Exception $e) {
  712. $this->logger->critical("An error happened, operation cancelled\n".$e);
  713. $this->entityManager->rollback();
  714. throw $e;
  715. }
  716. try {
  717. $this->deleteTypo3Website($organizationDeletionRequest->getOrganizationId());
  718. } catch (\Exception $e) {
  719. $this->logger->critical('An error happened while deleting the Typo3 website, please proceed manually.');
  720. $this->logger->debug($e);
  721. $withError = true;
  722. }
  723. try {
  724. $this->switchDolibarrSocietyToProspect($organization);
  725. } catch (\Exception $e) {
  726. $this->logger->critical('An error happened while updating the Dolibarr society, please proceed manually.');
  727. $this->logger->debug($e);
  728. $withError = true;
  729. }
  730. try {
  731. $this->fileManager->deleteOrganizationFiles($organizationDeletionRequest->getOrganizationId());
  732. } catch (\Exception $e) {
  733. $this->logger->critical("An error happened while deleting the organization's files, please proceed manually.");
  734. $this->logger->debug($e);
  735. $withError = true;
  736. }
  737. foreach ($deletedPersonIds as $personId) {
  738. try {
  739. $this->fileManager->deletePersonFiles($personId);
  740. } catch (\Exception $e) {
  741. $this->logger->critical("An error happened while deleting the person's files, please proceed manually (id=" . $person->getId() . ").");
  742. $this->logger->debug($e);
  743. $withError = true;
  744. }
  745. }
  746. if ($withError) {
  747. $organizationDeletionRequest->setStatus(OrganizationDeletionRequest::STATUS_OK_WITH_ERRORS);
  748. $this->logger->warning('-- Operation ended with errors, check the logs for more information --');
  749. } else {
  750. $organizationDeletionRequest->setStatus(OrganizationDeletionRequest::STATUS_OK);
  751. }
  752. return $organizationDeletionRequest;
  753. }
  754. /**
  755. * Supprime tous les Access d'une organisation, ainsi que la Person
  756. * rattachée (si celle-ci n'est pas liée à d'autres Access).
  757. *
  758. * @param Organization $organization
  759. * @return array<Person>
  760. */
  761. protected function getFutureOrphanPersons(Organization $organization): array
  762. {
  763. $orphans = [];
  764. foreach ($organization->getAccesses() as $access) {
  765. $person = $access->getPerson();
  766. if ($person->getAccesses()->count() === 1) {
  767. $orphans[] = $person;
  768. }
  769. }
  770. return $orphans;
  771. }
  772. protected function deleteTypo3Website(int $organizationId): void
  773. {
  774. $this->typo3Service->hardDeleteSite($organizationId);
  775. }
  776. protected function switchDolibarrSocietyToProspect(Organization $organization): void
  777. {
  778. $this->dolibarrApiService->switchSocietyToProspect($organization->getId());
  779. }
  780. }