DolibarrSyncService.php 34 KB

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