DolibarrSyncService.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Service\Dolibarr;
  4. use App\Entity\Core\AddressPostal;
  5. use App\Entity\Core\ContactPoint;
  6. use App\Entity\Organization\Organization;
  7. use App\Entity\Person\Person;
  8. use App\Enum\Access\FunctionEnum;
  9. use App\Enum\Access\RoleEnum;
  10. use App\Enum\Core\ContactPointTypeEnum;
  11. use App\Enum\Network\NetworkEnum;
  12. use App\Enum\Organization\AddressPostalOrganizationTypeEnum;
  13. use App\Enum\Organization\LegalEnum;
  14. use App\Enum\Organization\OrganizationIdsEnum;
  15. use App\Enum\Organization\SettingsProductEnum;
  16. use App\Enum\Person\GenderEnum;
  17. use App\Repository\Access\AccessRepository;
  18. use App\Repository\Access\FunctionTypeRepository;
  19. use App\Repository\Organization\OrganizationRepository;
  20. use App\Service\Core\AddressPostalUtils;
  21. use App\Service\Organization\Utils;
  22. use App\Service\Rest\Operation\BaseRestOperation;
  23. use App\Service\Rest\Operation\CreateOperation;
  24. use App\Service\Rest\Operation\DeleteOperation;
  25. use App\Service\Rest\Operation\UpdateOperation;
  26. use App\Service\Utils\ArrayUtils;
  27. use App\Service\Utils\DatesUtils;
  28. use libphonenumber\PhoneNumber;
  29. use libphonenumber\PhoneNumberFormat;
  30. use libphonenumber\PhoneNumberUtil;
  31. use Psr\Log\LoggerInterface;
  32. use Symfony\Component\HttpKernel\Exception\HttpException;
  33. use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
  34. use Symfony\Contracts\HttpClient\Exception\DecodingExceptionInterface;
  35. use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
  36. use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
  37. use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
  38. use Symfony\Contracts\HttpClient\ResponseInterface;
  39. use Symfony\Contracts\Service\Attribute\Required;
  40. use Symfony\Contracts\Translation\TranslatorInterface;
  41. /**
  42. * Push the data from the Opentalent DB into the Dolibarr DB, trough both applications
  43. * REST APIs.
  44. *
  45. * ** /!\ This sync is and must remain one-sided: Opentalent DB => Dolibarr DB **
  46. */
  47. class DolibarrSyncService
  48. {
  49. private const ASSOCIATION_SCHOOL_TAG_ID = 67;
  50. private const ASSOCIATION_PREMIUM_TAG_ID = 69;
  51. private const LOCAL_AUTH_SCHOOL_TAG_ID = 68;
  52. private const LOCAL_AUTH_PREMIUM_TAG_ID = 70;
  53. private const SYNCHRONIZED_TAGS = [
  54. self::ASSOCIATION_SCHOOL_TAG_ID => 'Association School',
  55. self::ASSOCIATION_PREMIUM_TAG_ID => 'Association School Premium',
  56. self::LOCAL_AUTH_SCHOOL_TAG_ID => 'CT School',
  57. self::LOCAL_AUTH_PREMIUM_TAG_ID => 'CT School Premium',
  58. ];
  59. private LoggerInterface $logger;
  60. public function __construct(
  61. private OrganizationRepository $organizationRepository,
  62. private AccessRepository $accessRepository,
  63. private FunctionTypeRepository $functionTypeRepository,
  64. private DolibarrApiService $dolibarrApiService,
  65. private AddressPostalUtils $addressPostalUtils,
  66. private ArrayUtils $arrayUtils,
  67. private TranslatorInterface $translator,
  68. private Utils $organizationUtils
  69. ) {
  70. }
  71. #[Required]
  72. /** @see https://symfony.com/doc/current/logging/channels_handlers.html#how-to-autowire-logger-channels */
  73. public function setLoggerInterface(LoggerInterface $cronLogger): void
  74. {
  75. $this->logger = $cronLogger;
  76. }
  77. /**
  78. * Performs a scan, comparing data from the Opentalent DB and the data returned
  79. * by the Dolibarr API.
  80. *
  81. * Errors during the scan are recorded in the $this->scanErrors
  82. *
  83. * Returns an array of DolibarrSyncOperations
  84. *
  85. * @param callable|null $progressionCallback A callback method for indicating the current progression of the process;
  86. * Shall accept two integer arguments: current progression, and total
  87. *
  88. * @return array<BaseRestOperation>
  89. *
  90. * @throws \Exception
  91. *
  92. * @noinspection NullPointerExceptionInspection
  93. */
  94. public function scan(?callable $progressionCallback = null): array
  95. {
  96. $this->logger->info('-- Scan started --');
  97. // Index the dolibarr clients by organization ids
  98. $dolibarrClientsIndex = $this->getDolibarrSocietiesIndex();
  99. $this->logger->info(count($dolibarrClientsIndex).' clients fetched from dolibarr');
  100. // Get all active accesses
  101. $membersIndex = $this->getActiveMembersIndex();
  102. // Get all the missions with an admin default role
  103. $adminMissions = [];
  104. foreach ($this->functionTypeRepository->findBy(['roleByDefault' => RoleEnum::ROLE_ADMIN]) as $functionType) {
  105. $adminMissions[] = $functionType->getMission()->value;
  106. }
  107. // Store networks ids id dolibarr
  108. $cmfDolibarrId = (int) $this->dolibarrApiService->getSociety(OrganizationIdsEnum::CMF->value)['id'];
  109. $ffecDolibarrId = (int) $this->dolibarrApiService->getSociety(OrganizationIdsEnum::FFEC->value)['id'];
  110. // Loop over the Opentalent organizations, and fill up the operations list
  111. $operations = [];
  112. $i = 0;
  113. $total = count($dolibarrClientsIndex);
  114. foreach ($dolibarrClientsIndex as $organizationId => $dolibarrSociety) {
  115. $dolibarrSociety = $this->sanitizeDolibarrData($dolibarrSociety);
  116. $organization = $this->organizationRepository->find($organizationId);
  117. if (null === $organization) {
  118. $this->logger->error('Organization '.$organizationId.' not found in the Opentalent DB');
  119. ++$i;
  120. if (null !== $progressionCallback) {
  121. $progressionCallback($i, $total);
  122. }
  123. continue;
  124. }
  125. $dolibarrSocietyId = (int) $dolibarrSociety['id'];
  126. // Populate the expected contacts array
  127. $organizationMembers = $membersIndex[$organization->getId()] ?? [];
  128. // ===== Update Society =====
  129. $newSocietyData = [];
  130. // Sync name
  131. $newSocietyData['name'] = trim($organization->getName());
  132. // Sync contact data of the client
  133. $mainAddress = $this->getOrganizationPostalAddress($organization);
  134. if (null !== $mainAddress) {
  135. $streetAddress = $this->addressPostalUtils->getFullStreetAddress($mainAddress);
  136. if ('' !== trim($mainAddress->getAddressOwner() ?? '')) {
  137. $streetAddress = $mainAddress->getAddressOwner()."\n".$streetAddress;
  138. }
  139. $newSocietyData['address'] = $streetAddress;
  140. $newSocietyData['zip'] = $mainAddress->getPostalCode();
  141. $newSocietyData['town'] = $mainAddress->getAddressCity();
  142. } else {
  143. $newSocietyData['address'] = null;
  144. $newSocietyData['zip'] = null;
  145. $newSocietyData['town'] = null;
  146. }
  147. // Sync contact
  148. $newSocietyData['email'] = $this->getOrganizationEmail($organization);
  149. $newSocietyData['phone'] = $this->getOrganizationPhone($organization);
  150. // Sync Network
  151. if (!in_array($organization->getId(), [NetworkEnum::CMF, NetworkEnum::FFEC], true)) {
  152. $newSocietyData['parent'] = ''.match (
  153. $this->getOrganizationNetworkId($organization)
  154. ) {
  155. NetworkEnum::CMF->value => $cmfDolibarrId,
  156. NetworkEnum::FFEC->value => $ffecDolibarrId,
  157. default => null
  158. };
  159. }
  160. // More infos
  161. $infos = [];
  162. $product = $organization->getSettings()->getProduct();
  163. if ($this->organizationUtils->isSchool($organization)) {
  164. $infos[] = $this->translator->trans('STUDENTS_COUNT').' : '.
  165. $this->countWithMission([FunctionEnum::STUDENT->value], $organizationMembers);
  166. }
  167. if ($this->organizationUtils->isSchool($organization) || $this->organizationUtils->isArtist($organization)) {
  168. $infos[] = $this->translator->trans('ADHERENTS_COUNT').' : '.
  169. $this->countWithMission([FunctionEnum::ADHERENT->value], $organizationMembers);
  170. }
  171. $infos[] = $this->translator->trans('ADMIN_ACCESS_COUNT').' : '.
  172. $this->countWithMission($adminMissions, $organizationMembers);
  173. // /!\ On est forcé de passer la sub-array entière pour mettre à jour le champ modifié, sinon
  174. // tous les autres champs seront passés à null...
  175. $newSocietyData['array_options'] = $dolibarrSociety['array_options'];
  176. $newSocietyData['array_options']['options_2iopeninfoopentalent'] = implode("\n", $infos);
  177. if (!empty($product)) {
  178. $newSocietyData['array_options']['options_2iopen_software_opentalent'] = $this->translator->trans($product->value);
  179. }
  180. // Set the society as active (warning: use the field 'status' for societies, and not 'statut'!)
  181. $newSocietyData['status'] = '1';
  182. // Only update the fields that are different (it's important to let it non-recursive, the subarray have to be passed entirely)
  183. $newSocietyData = $this->arrayUtils->getChanges(
  184. $dolibarrSociety,
  185. $newSocietyData,
  186. false,
  187. static function ($v1, $v2) { return ($v1 ?? '') === ($v2 ?? ''); }
  188. );
  189. // Add an update operation if some data has to be updated
  190. if (!empty($newSocietyData)) {
  191. $newSocietyData['array_options']['options_2iopen_last_sync_date'] = DatesUtils::new()->format('c');
  192. $operations[] = new UpdateOperation(
  193. 'Update society : '.$organization->getName().' ('.$organization->getId().')',
  194. 'thirdparties',
  195. $dolibarrSocietyId,
  196. $newSocietyData,
  197. $dolibarrSociety
  198. );
  199. }
  200. // ===== Update Contacts =====
  201. $dolibarrSocietyContacts = $this->dolibarrApiService->getContacts($dolibarrSocietyId);
  202. $contactsProcessed = [];
  203. foreach ($organizationMembers as $accessId => $missions) {
  204. // Check if member has office missions, skip if it doesn't
  205. if (empty(array_intersect($missions, FunctionEnum::getOfficeMissions()))) {
  206. continue;
  207. }
  208. $access = $this->accessRepository->find($accessId);
  209. $person = $access?->getPerson();
  210. // Keep track of the contacts seen
  211. $contactsProcessed[] = $person->getId();
  212. // special: if the contact hasn't a firstname and a lastname, ignore it
  213. if (empty($person->getName()) || empty($person->getGivenName())) {
  214. $this->logger->error('Person '.$person->getId().' miss a lastname and/or a firstname, ignored.');
  215. continue;
  216. }
  217. // Get the matching dolibarr contact
  218. $dolibarrContact = $this->findDolibarrContactFor($dolibarrSocietyContacts, $person);
  219. $dolibarrContact = $this->sanitizeDolibarrData($dolibarrContact);
  220. $contact = $this->getPersonContact($person);
  221. // Build parameters for the query (we'll see later if a query is needed)
  222. $newContactData = [
  223. 'civility_code' => $person->getGender() ? $this->translator->trans($person->getGender()->value) : null,
  224. 'lastname' => trim($person->getName()),
  225. 'firstname' => trim($person->getGivenName()),
  226. 'email' => $contact?->getEmail(),
  227. 'phone_pro' => $contact?->getTelphone() ? $this->formatPhoneNumber($contact->getTelphone()) : null,
  228. 'phone_mobile' => $contact?->getMobilPhone() ? $this->formatPhoneNumber($contact->getMobilPhone()) : null,
  229. 'poste' => $this->formatContactPosition($missions, $person->getGender()?->value),
  230. 'statut' => '1',
  231. ];
  232. // The person's id may be missing if the contact is new or if it was found through its name
  233. if (null !== $dolibarrContact && !(empty($dolibarrContact['array_options'] ?? []))) {
  234. $newContactData['array_options'] = $dolibarrContact['array_options'];
  235. } else {
  236. $newContactData['array_options'] = [];
  237. }
  238. $newContactData['array_options']['options_2iopen_person_id'] = (string) $person->getId();
  239. if (null === $dolibarrContact) {
  240. // New contact
  241. $newContactData['socid'] = $dolibarrSocietyId;
  242. $newContactData['array_options']['options_2iopen_last_sync_date'] = DatesUtils::new()->format('c');
  243. $operations[] = new CreateOperation(
  244. 'New contact: '.$person->getName().' '.$person->getGivenName().' ('.$person->getId().')',
  245. 'contacts',
  246. $newContactData
  247. );
  248. } else {
  249. // Only update the fields that are different (it's important to let it non-recursive, the subarray have to be passed entirely)
  250. $newContactData = $this->arrayUtils->getChanges(
  251. $dolibarrContact,
  252. $newContactData,
  253. false,
  254. static function ($v1, $v2) { return ($v1 ?? '') === ($v2 ?? ''); }
  255. );
  256. // add an update operation if some data has to be updated
  257. if (!empty($newContactData)) {
  258. $newContactData['array_options']['options_2iopen_last_sync_date'] = DatesUtils::new()->format('c');
  259. $operations[] = new UpdateOperation(
  260. 'Update contact: '.$person->getName().' '.$person->getGivenName().' ('.$person->getId().')'.
  261. ' in '.$organization->getName().' ('.$organization->getId().')',
  262. 'contacts',
  263. (int) $dolibarrContact['id'],
  264. $newContactData,
  265. $dolibarrContact
  266. );
  267. }
  268. }
  269. }
  270. foreach ($dolibarrSocietyContacts as $contactData) {
  271. if (empty($contactData['array_options']['options_2iopen_person_id'])) {
  272. continue;
  273. }
  274. $personId = (int) $contactData['array_options']['options_2iopen_person_id'];
  275. if (0 === (int) $contactData['statut']) {
  276. // contact is already disabled
  277. continue;
  278. }
  279. if (!in_array($personId, $contactsProcessed, true)) {
  280. // Ce personId n'existe plus dans les membres Opentalent de cette société, on delete
  281. $newContactData = [
  282. 'statut' => '0',
  283. 'array_options' => ['options_2iopen_last_sync_date' => DatesUtils::new()->format('c')],
  284. ];
  285. $operations[] = new UpdateOperation(
  286. 'Disable contact: '.$contactData['lastname'].' '.$contactData['firstname'].' ('.$personId.')'.
  287. ' from '.$organization->getName().' ('.$organization->getId().')',
  288. 'contacts',
  289. (int) $contactData['id'],
  290. $newContactData,
  291. $contactData
  292. );
  293. }
  294. }
  295. // ===== Update Tags =====
  296. $currentTags = $this->dolibarrApiService->getSocietyTagsIds($dolibarrSocietyId);
  297. $expectedTags = $this->getExpectedTagsFor($organization);
  298. // Remove unexpected tags
  299. foreach ($currentTags as $tagId) {
  300. if (!array_key_exists($tagId, self::SYNCHRONIZED_TAGS)) {
  301. continue;
  302. }
  303. if (!in_array($tagId, $expectedTags)) {
  304. $operations[] = new DeleteOperation(
  305. 'Delete tag: `'.self::SYNCHRONIZED_TAGS[$tagId].
  306. '` from '.$organization->getName().' ('.$organization->getId().')',
  307. "/thirdparties/$dolibarrSocietyId/categories",
  308. $tagId
  309. );
  310. }
  311. }
  312. // Add missing tags
  313. foreach ($expectedTags as $tagId) {
  314. if (!in_array($tagId, $currentTags)) {
  315. $operations[] = new CreateOperation(
  316. 'Add tag: `'.self::SYNCHRONIZED_TAGS[$tagId].
  317. '` to '.$organization->getName().' ('.$organization->getId().')',
  318. "/thirdparties/$dolibarrSocietyId/categories/$tagId",
  319. []
  320. );
  321. }
  322. }
  323. // Next society
  324. ++$i;
  325. if (null !== $progressionCallback) {
  326. $progressionCallback($i, $total);
  327. }
  328. }
  329. $this->logger->info('Scan done, '.count($operations).' required operations listed');
  330. return $operations;
  331. }
  332. /**
  333. * Execute the operations listed with the DolibarrSyncService::scan method.
  334. *
  335. * Returns an array of DolibarrSyncOperations
  336. *
  337. * @param array<BaseRestOperation> $operations
  338. * @param callable|null $progressionCallback A callback method for indicating the current progression of the process;
  339. * Shall accept two integer arguments: current progression, and total
  340. *
  341. * @return array<BaseRestOperation>
  342. *
  343. * @throws \Exception
  344. */
  345. public function execute(array $operations, ?callable $progressionCallback = null): array
  346. {
  347. $this->logger->info('-- Execution started --');
  348. $this->logger->info(count($operations).' operations pending...');
  349. $done = 0;
  350. $errors = 0;
  351. $unknown = 0;
  352. $i = 0;
  353. $total = count($operations);
  354. foreach ($operations as $operation) {
  355. if ($operation->getStatus() !== $operation::STATUS_READY) {
  356. // operation has already been treated
  357. $this->logger->warning('Tried to execute an operation that was not marked as ready : '.$operation);
  358. ++$i;
  359. if (null !== $progressionCallback) {
  360. $progressionCallback($i, $total);
  361. }
  362. continue;
  363. }
  364. $this->logger->debug($operation->getLabel());
  365. foreach ($operation->getChangeLog() as $message) {
  366. $this->logger->debug(' '.$message);
  367. }
  368. try {
  369. // Execute the request
  370. $response = $operation->execute($this->dolibarrApiService);
  371. // Check the status
  372. if ($operation->getStatus() !== $operation::STATUS_DONE) {
  373. ++$unknown;
  374. throw new \RuntimeException('Operation has an inconsistent status : '.$operation->getStatus());
  375. }
  376. // If this is an update operation, validate the result
  377. if ($operation instanceof UpdateOperation) {
  378. try {
  379. $this->validateResponse($response, $operation);
  380. } catch (\RuntimeException $e) {
  381. $this->logger->warning($e->getMessage());
  382. }
  383. }
  384. ++$done;
  385. } catch (\RuntimeException $e) {
  386. $this->logger->error('Error while executing operation : '.$operation);
  387. $this->logger->error(implode("\n", $operation->getChangeLog()));
  388. $this->logger->error($e->getMessage());
  389. ++$errors;
  390. }
  391. ++$i;
  392. if (null !== $progressionCallback) {
  393. $progressionCallback($i, $total);
  394. }
  395. }
  396. $this->logger->info('Execution ended');
  397. $this->logger->info('Done : '.$done);
  398. $this->logger->info('Errors : '.$errors);
  399. if ($unknown > 0) {
  400. $this->logger->warning('Unknown : '.$unknown);
  401. }
  402. return $operations;
  403. }
  404. /**
  405. * Scan and execute the sync process.
  406. *
  407. * @return array<BaseRestOperation>
  408. *
  409. * @throws HttpException
  410. * @throws \Exception
  411. */
  412. public function run(): array
  413. {
  414. $operations = $this->scan();
  415. $this->execute($operations);
  416. return $operations;
  417. }
  418. /**
  419. * Get the client societies dolibarr and index them by organization id.
  420. *
  421. * @return array<mixed> An index of the form [$organizationId => $dolibarrData]
  422. */
  423. protected function getDolibarrSocietiesIndex(): array
  424. {
  425. $index = [];
  426. foreach ($this->dolibarrApiService->getAllClients() as $clientData) {
  427. $organizationId = $clientData['array_options']['options_2iopen_organization_id'] ?? null;
  428. if (!($organizationId > 0)) {
  429. // Ignoring clients without contract
  430. $contract = $this->dolibarrApiService->getActiveContract((int) $clientData['id']);
  431. if (empty($contract)) {
  432. continue;
  433. }
  434. $this->logger->warning(
  435. 'Dolibarr client has no organization id: '.
  436. $clientData['name'].' ('.$clientData['id'].')'
  437. );
  438. continue;
  439. }
  440. $index[$organizationId] = $clientData;
  441. }
  442. return $index;
  443. }
  444. /**
  445. * Returns an index of all the active members with their current mission(s).
  446. *
  447. * Index is the form: [$organizationId => [$accessId => [$mission, $mission...], $accessId...], $organizationId2...]
  448. *
  449. * @return array<mixed>
  450. */
  451. protected function getActiveMembersIndex(): array
  452. {
  453. $index = [];
  454. $results = $this->accessRepository->getAllActiveMembersAndMissions();
  455. foreach ($results as $row) {
  456. $accessId = $row['id'];
  457. $organizationId = $row['organization_id'];
  458. $mission = $row['mission'];
  459. if (!array_key_exists($organizationId, $index)) {
  460. $index[$organizationId] = [];
  461. }
  462. if (!array_key_exists($accessId, $index[$organizationId])) {
  463. $index[$organizationId][$accessId] = [];
  464. }
  465. $index[$organizationId][$accessId][] = $mission->value;
  466. }
  467. return $index;
  468. }
  469. /**
  470. * Get the first contact that has the same person id.
  471. *
  472. * If none are found with the person id, try to find one with the same full name and no person id
  473. *
  474. * @param array<mixed> $dolibarrContacts
  475. *
  476. * @return array<mixed>|null
  477. */
  478. protected function findDolibarrContactFor(array $dolibarrContacts, Person $person): ?array
  479. {
  480. foreach ($dolibarrContacts as $contactData) {
  481. if (!empty($contactData['array_options']['options_2iopen_person_id'])) {
  482. $id = (int) $contactData['array_options']['options_2iopen_person_id'];
  483. if ($id === $person->getId()) {
  484. return $contactData;
  485. }
  486. }
  487. }
  488. foreach ($dolibarrContacts as $contactData) {
  489. if (
  490. !($contactData['array_options']['options_2iopen_person_id'] ?? null)
  491. && null !== $person->getName()
  492. && null !== $person->getGivenName()
  493. && strtolower($person->getName()) === strtolower($contactData['lastname'] ?? '')
  494. && strtolower($person->getGivenName()) === strtolower($contactData['firstname'] ?? '')
  495. ) {
  496. return $contactData;
  497. }
  498. }
  499. return null;
  500. }
  501. /**
  502. * Because for some fields the dolibarr api returns empty strings even when field is null in DB,
  503. * we have to post-process it to avoid unnecessary and endless update operations.
  504. *
  505. * As far as we know, there is no harm here to replace every empty string value by a null value
  506. * (no loss of information)
  507. *
  508. * @param array<mixed>|null $data
  509. *
  510. * @return array<mixed>|null
  511. */
  512. protected function sanitizeDolibarrData(?array $data): ?array
  513. {
  514. if (null === $data) {
  515. return null;
  516. }
  517. foreach ($data as $field => $value) {
  518. if (is_array($value)) {
  519. $data[$field] = $this->sanitizeDolibarrData($value);
  520. } elseif ('' === $value) {
  521. $data[$field] = null;
  522. }
  523. }
  524. return $data;
  525. }
  526. /**
  527. * Retrieve the postal address of the organization.
  528. */
  529. protected function getOrganizationPostalAddress(Organization $organization): ?AddressPostal
  530. {
  531. $addressPriorities = [
  532. AddressPostalOrganizationTypeEnum::ADDRESS_BILL,
  533. AddressPostalOrganizationTypeEnum::ADDRESS_CONTACT,
  534. AddressPostalOrganizationTypeEnum::ADDRESS_HEAD_OFFICE,
  535. AddressPostalOrganizationTypeEnum::ADDRESS_PRACTICE,
  536. AddressPostalOrganizationTypeEnum::ADDRESS_OTHER,
  537. ];
  538. $organizationAddressPostal = $organization->getOrganizationAddressPostals();
  539. foreach ($addressPriorities as $addressType) {
  540. foreach ($organizationAddressPostal as $postalAddress) {
  541. if ($postalAddress->getType() === $addressType) {
  542. return $postalAddress->getAddressPostal();
  543. }
  544. }
  545. }
  546. return null;
  547. }
  548. /**
  549. * Retrieve the phone for the organization.
  550. */
  551. protected function getOrganizationPhone(Organization $organization): ?string
  552. {
  553. $contactPriorities = [
  554. ContactPointTypeEnum::BILL,
  555. ContactPointTypeEnum::CONTACT,
  556. ContactPointTypeEnum::PRINCIPAL,
  557. ContactPointTypeEnum::OTHER,
  558. ];
  559. $contactPoints = $organization->getContactPoints();
  560. foreach ($contactPriorities as $contactType) {
  561. foreach ($contactPoints as $contactPoint) {
  562. if ($contactPoint->getContactType() === $contactType) {
  563. if (null !== $contactPoint->getTelphone()) {
  564. return $this->formatPhoneNumber($contactPoint->getTelphone());
  565. }
  566. if (null !== $contactPoint->getMobilPhone()) {
  567. return $this->formatPhoneNumber($contactPoint->getMobilPhone());
  568. }
  569. }
  570. }
  571. }
  572. return null;
  573. }
  574. /**
  575. * Retrieve the email for the organization.
  576. */
  577. protected function getOrganizationEmail(Organization $organization): ?string
  578. {
  579. $contactPriorities = [
  580. ContactPointTypeEnum::BILL,
  581. ContactPointTypeEnum::CONTACT,
  582. ContactPointTypeEnum::PRINCIPAL,
  583. ContactPointTypeEnum::OTHER,
  584. ];
  585. $contactPoints = $organization->getContactPoints();
  586. foreach ($contactPriorities as $contactType) {
  587. foreach ($contactPoints as $contactPoint) {
  588. if ($contactPoint->getContactType() === $contactType && null !== $contactPoint->getEmail()) {
  589. return $contactPoint->getEmail();
  590. }
  591. }
  592. }
  593. return null;
  594. }
  595. /**
  596. * Return the id of the first active network found for the given organization.
  597. */
  598. protected function getOrganizationNetworkId(Organization $organization): ?int
  599. {
  600. foreach ($organization->getNetworkOrganizations() as $networkOrganization) {
  601. if (null !== $networkOrganization->getEndDate() && $networkOrganization->getEndDate() < new \DateTime()) {
  602. continue;
  603. }
  604. return $networkOrganization->getNetwork()?->getId();
  605. }
  606. return null;
  607. }
  608. /**
  609. * Returns the number of accesses possessing at least one of the missions.
  610. *
  611. * @param array<string> $missions A list of missions
  612. * @param array<string, array<string>> $members An organization members as returned by getActiveMembersIndex: [$accessID => [$missions...]]
  613. * @return int
  614. */
  615. protected function countWithMission(array $missions, array $members): int
  616. {
  617. return count(array_filter(
  618. $members,
  619. static function ($actualMissions) use ($missions) {
  620. return !empty(
  621. array_intersect($actualMissions, $missions)
  622. );
  623. }
  624. ));
  625. }
  626. /**
  627. * Return the best contact point for the given Person, or null if none.
  628. */
  629. protected function getPersonContact(Person $person): ?ContactPoint
  630. {
  631. $contactPriorities = [
  632. ContactPointTypeEnum::PRINCIPAL,
  633. ContactPointTypeEnum::OTHER,
  634. ];
  635. $contactPoints = $person->getContactPoints();
  636. foreach ($contactPriorities as $contactType) {
  637. foreach ($contactPoints as $contactPoint) {
  638. if ($contactPoint->getContactType() === $contactType) {
  639. return $contactPoint;
  640. }
  641. }
  642. }
  643. return null;
  644. }
  645. /**
  646. * Format the contact position from its gender and missions.
  647. *
  648. * @param list<string> $missions
  649. */
  650. protected function formatContactPosition(array $missions, ?string $gender = 'X'): string
  651. {
  652. $to_exclude = [
  653. FunctionEnum::ADHERENT->value,
  654. FunctionEnum::STUDENT->value,
  655. FunctionEnum::OTHER->value,
  656. ];
  657. $poste = implode(
  658. ', ',
  659. array_map(
  660. function ($m) use ($gender) {
  661. return $this->translator->trans(
  662. $m,
  663. ['gender' => [
  664. GenderEnum::MISS->value => 'F',
  665. GenderEnum::MISTER->value => 'M',
  666. ][$gender] ?? 'X']
  667. );
  668. },
  669. array_filter(
  670. $missions,
  671. static function ($m) use ($to_exclude) {
  672. return !in_array($m, $to_exclude, true);
  673. }
  674. )
  675. )
  676. );
  677. if (strlen($poste) > 80) {
  678. $poste = mb_substr($poste, 0, 77, 'utf-8').'...';
  679. }
  680. return $poste;
  681. }
  682. /**
  683. * Format a phone number into international format.
  684. */
  685. protected function formatPhoneNumber(PhoneNumber $phoneNumber): mixed
  686. {
  687. $phoneUtil = PhoneNumberUtil::getInstance();
  688. return str_replace(
  689. ' ',
  690. '',
  691. $phoneUtil->format($phoneNumber, PhoneNumberFormat::INTERNATIONAL)
  692. );
  693. }
  694. /**
  695. * @return array<int>
  696. */
  697. protected function getExpectedTagsFor(Organization $organization): array
  698. {
  699. $expectedTags = [];
  700. $product = $organization->getSettings()->getProduct();
  701. // Association, school or school premium
  702. if (LegalEnum::ASSOCIATION_LAW_1901 === $organization->getLegalStatus()) {
  703. if (SettingsProductEnum::SCHOOL === $product) {
  704. $expectedTags[] = self::ASSOCIATION_SCHOOL_TAG_ID;
  705. }
  706. if (SettingsProductEnum::SCHOOL_PREMIUM === $product) {
  707. $expectedTags[] = self::ASSOCIATION_PREMIUM_TAG_ID;
  708. }
  709. }
  710. // Local authorities, school or school premium
  711. if (LegalEnum::LOCAL_AUTHORITY === $organization->getLegalStatus()) {
  712. if (SettingsProductEnum::SCHOOL === $product) {
  713. $expectedTags[] = self::LOCAL_AUTH_SCHOOL_TAG_ID;
  714. }
  715. if (SettingsProductEnum::SCHOOL_PREMIUM === $product) {
  716. $expectedTags[] = self::LOCAL_AUTH_PREMIUM_TAG_ID;
  717. }
  718. }
  719. return $expectedTags;
  720. }
  721. /**
  722. * Post-validation of the execution of the operation.
  723. * Compare the actual result to the expected one to ensure that the data was correctly updated.
  724. *
  725. * In the case of a validation error, throw an HttpException
  726. *
  727. * @throws \RuntimeException
  728. */
  729. protected function validateResponse(ResponseInterface $response, UpdateOperation|CreateOperation $operation): void
  730. {
  731. $updated = $operation->getData();
  732. try {
  733. $responseData = $response->toArray();
  734. } catch (ClientExceptionInterface|DecodingExceptionInterface|RedirectionExceptionInterface|ServerExceptionInterface|TransportExceptionInterface $e) {
  735. throw new \RuntimeException("Couldn't read the content of the response : ".$e);
  736. }
  737. // Sanitize to get rid of the null / empty strings transformations of the API
  738. $updated = $this->sanitizeDolibarrData($updated);
  739. $responseData = $this->sanitizeDolibarrData($responseData);
  740. $diffs = $this->arrayUtils->getChanges($responseData, $updated, true);
  741. if (!empty($diffs)) {
  742. /* @noinspection JsonEncodingApiUsageInspection */
  743. throw new \RuntimeException('The '.$operation->getMethod()." request had an unexpected result.\n".'Expected content: '.json_encode($updated)."\n".'Actual content : '.json_encode($responseData));
  744. }
  745. }
  746. }