DolibarrSyncService.php 29 KB

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