DolibarrSyncService.php 35 KB

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