DolibarrSyncService.php 30 KB

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