DolibarrSyncService.php 30 KB

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