DolibarrSyncService.php 35 KB

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