DolibarrSyncService.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846
  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. foreach ($dolibarrSocietyContacts as $contactData) {
  267. if (empty($contactData['array_options']['options_2iopen_person_id'])) {
  268. continue;
  269. }
  270. $personId = (int) $contactData['array_options']['options_2iopen_person_id'];
  271. if (0 === (int) $contactData['statut']) {
  272. // contact is already disabled
  273. continue;
  274. }
  275. if (!in_array($personId, $contactsProcessed, true)) {
  276. // Ce personId n'existe plus dans les membres Opentalent de cette société, on delete
  277. $operations[] = new UpdateOperation(
  278. 'Disable contact: '.$contactData['lastname'].' '.$contactData['firstname'].' ('.$personId.')'.
  279. ' from '.$organization->getName().' ('.$organization->getId().')',
  280. 'contacts',
  281. (int) $contactData['id'],
  282. ['statut' => '0'],
  283. $contactData
  284. );
  285. }
  286. }
  287. // ===== Update Tags =====
  288. $currentTags = $this->dolibarrApiService->getSocietyTagsIds($dolibarrSocietyId);
  289. $expectedTags = $this->getExpectedTagsFor($organization);
  290. // Remove unexpected tags
  291. foreach ($currentTags as $tagId) {
  292. if (!array_key_exists($tagId, self::SYNCHRONIZED_TAGS)) {
  293. continue;
  294. }
  295. if (!in_array($tagId, $expectedTags)) {
  296. $operations[] = new DeleteOperation(
  297. 'Delete tag: `'.self::SYNCHRONIZED_TAGS[$tagId].
  298. '` from '.$organization->getName().' ('.$organization->getId().')',
  299. "/thirdparties/$dolibarrSocietyId/categories",
  300. $tagId
  301. );
  302. }
  303. }
  304. // Add missing tags
  305. foreach ($expectedTags as $tagId) {
  306. if (!in_array($tagId, $currentTags)) {
  307. $operations[] = new CreateOperation(
  308. 'Add tag: `'.self::SYNCHRONIZED_TAGS[$tagId].
  309. '` to '.$organization->getName().' ('.$organization->getId().')',
  310. "/thirdparties/$dolibarrSocietyId/categories/$tagId",
  311. []
  312. );
  313. }
  314. }
  315. // Next society
  316. ++$i;
  317. if (null !== $progressionCallback) {
  318. $progressionCallback($i, $total);
  319. }
  320. }
  321. $this->logger->info('Scan done, '.count($operations).' required operations listed');
  322. return $operations;
  323. }
  324. /**
  325. * Execute the operations listed with the DolibarrSyncService::scan method.
  326. *
  327. * Returns an array of DolibarrSyncOperations
  328. *
  329. * @param array<BaseRestOperation> $operations
  330. * @param callable|null $progressionCallback A callback method for indicating the current progression of the process;
  331. * Shall accept two integer arguments: current progression, and total
  332. *
  333. * @return array<BaseRestOperation>
  334. *
  335. * @throws \Exception
  336. */
  337. public function execute(array $operations, ?callable $progressionCallback = null): array
  338. {
  339. $this->logger->info('-- Execution started --');
  340. $this->logger->info(count($operations).' operations pending...');
  341. $done = 0;
  342. $errors = 0;
  343. $unknown = 0;
  344. $i = 0;
  345. $total = count($operations);
  346. foreach ($operations as $operation) {
  347. if ($operation->getStatus() !== $operation::STATUS_READY) {
  348. // operation has already been treated
  349. $this->logger->warning('Tried to execute an operation that was not marked as ready : '.$operation);
  350. ++$i;
  351. if (null !== $progressionCallback) {
  352. $progressionCallback($i, $total);
  353. }
  354. continue;
  355. }
  356. $this->logger->debug($operation->getLabel());
  357. foreach ($operation->getChangeLog() as $message) {
  358. $this->logger->debug(' '.$message);
  359. }
  360. try {
  361. // Execute the request
  362. $response = $operation->execute($this->dolibarrApiService);
  363. // Check the status
  364. if ($operation->getStatus() !== $operation::STATUS_DONE) {
  365. ++$unknown;
  366. throw new \RuntimeException('Operation has an inconsistent status : '.$operation->getStatus());
  367. }
  368. // If this is an update operation, validate the result
  369. if ($operation instanceof UpdateOperation) {
  370. try {
  371. $this->validateResponse($response, $operation);
  372. } catch (\RuntimeException $e) {
  373. $this->logger->warning($e->getMessage());
  374. }
  375. }
  376. ++$done;
  377. } catch (\RuntimeException $e) {
  378. $this->logger->error('Error while executing operation : '.$operation);
  379. $this->logger->error(implode("\n", $operation->getChangeLog()));
  380. $this->logger->error($e->getMessage());
  381. ++$errors;
  382. }
  383. ++$i;
  384. if (null !== $progressionCallback) {
  385. $progressionCallback($i, $total);
  386. }
  387. }
  388. $this->logger->info('Execution ended');
  389. $this->logger->info('Done : '.$done);
  390. $this->logger->info('Errors : '.$errors);
  391. if ($unknown > 0) {
  392. $this->logger->warning('Unknown : '.$unknown);
  393. }
  394. return $operations;
  395. }
  396. /**
  397. * Scan and execute the sync process.
  398. *
  399. * @return array<BaseRestOperation>
  400. *
  401. * @throws HttpException
  402. * @throws \Exception
  403. */
  404. public function run(): array
  405. {
  406. $operations = $this->scan();
  407. $this->execute($operations);
  408. return $operations;
  409. }
  410. /**
  411. * Get the client societies dolibarr and index them by organization id.
  412. *
  413. * @return array<mixed> An index of the form [$organizationId => $dolibarrData]
  414. */
  415. protected function getDolibarrSocietiesIndex(): array
  416. {
  417. $index = [];
  418. foreach ($this->dolibarrApiService->getAllClients() as $clientData) {
  419. $organizationId = $clientData['array_options']['options_2iopen_organization_id'] ?? null;
  420. if (!($organizationId > 0)) {
  421. // Ignoring clients without contract
  422. $contract = $this->dolibarrApiService->getActiveContract((int) $clientData['id']);
  423. if (empty($contract)) {
  424. continue;
  425. }
  426. $this->logger->warning(
  427. 'Dolibarr client has no organization id: '.
  428. $clientData['name'].' ('.$clientData['id'].')'
  429. );
  430. continue;
  431. }
  432. $index[$organizationId] = $clientData;
  433. }
  434. return $index;
  435. }
  436. /**
  437. * Returns an index of all the active members with their current mission(s).
  438. *
  439. * Index is the form: [$organizationId => [$accessId => [$mission, $mission...], $accessId...], $organizationId2...]
  440. *
  441. * @return array<mixed>
  442. */
  443. protected function getActiveMembersIndex(): array
  444. {
  445. $index = [];
  446. $results = $this->accessRepository->getAllActiveMembersAndMissions();
  447. foreach ($results as $row) {
  448. $accessId = $row['id'];
  449. $organizationId = $row['organization_id'];
  450. $mission = $row['mission'];
  451. if (!array_key_exists($organizationId, $index)) {
  452. $index[$organizationId] = [];
  453. }
  454. if (!array_key_exists($accessId, $index[$organizationId])) {
  455. $index[$organizationId][$accessId] = [];
  456. }
  457. $index[$organizationId][$accessId][] = $mission->value;
  458. }
  459. return $index;
  460. }
  461. /**
  462. * Get the first contact that has the same person id.
  463. *
  464. * If none are found with the person id, try to find one with the same full name and no person id
  465. *
  466. * @param array<mixed> $dolibarrContacts
  467. *
  468. * @return array<mixed>|null
  469. */
  470. protected function findDolibarrContactFor(array $dolibarrContacts, Person $person): ?array
  471. {
  472. foreach ($dolibarrContacts as $contactData) {
  473. if (!empty($contactData['array_options']['options_2iopen_person_id'])) {
  474. $id = (int) $contactData['array_options']['options_2iopen_person_id'];
  475. if ($id === $person->getId()) {
  476. return $contactData;
  477. }
  478. }
  479. }
  480. foreach ($dolibarrContacts as $contactData) {
  481. if (
  482. !($contactData['array_options']['options_2iopen_person_id'] ?? null)
  483. && null !== $person->getName()
  484. && null !== $person->getGivenName()
  485. && strtolower($person->getName()) === strtolower($contactData['lastname'] ?? '')
  486. && strtolower($person->getGivenName()) === strtolower($contactData['firstname'] ?? '')
  487. ) {
  488. return $contactData;
  489. }
  490. }
  491. return null;
  492. }
  493. /**
  494. * Because for some fields the dolibarr api returns empty strings even when field is null in DB,
  495. * we have to post-process it to avoid unnecessary and endless update operations.
  496. *
  497. * As far as we know, there is no harm here to replace every empty string value by a null value
  498. * (no loss of information)
  499. *
  500. * @param array<mixed>|null $data
  501. *
  502. * @return array<mixed>|null
  503. */
  504. protected function sanitizeDolibarrData(?array $data): ?array
  505. {
  506. if (null === $data) {
  507. return null;
  508. }
  509. foreach ($data as $field => $value) {
  510. if (is_array($value)) {
  511. $data[$field] = $this->sanitizeDolibarrData($value);
  512. } elseif ('' === $value) {
  513. $data[$field] = null;
  514. }
  515. }
  516. return $data;
  517. }
  518. /**
  519. * Retrieve the postal address of the organization.
  520. */
  521. protected function getOrganizationPostalAddress(Organization $organization): ?AddressPostal
  522. {
  523. $addressPriorities = [
  524. AddressPostalOrganizationTypeEnum::ADDRESS_BILL,
  525. AddressPostalOrganizationTypeEnum::ADDRESS_CONTACT,
  526. AddressPostalOrganizationTypeEnum::ADDRESS_HEAD_OFFICE,
  527. AddressPostalOrganizationTypeEnum::ADDRESS_PRACTICE,
  528. AddressPostalOrganizationTypeEnum::ADDRESS_OTHER,
  529. ];
  530. $organizationAddressPostal = $organization->getOrganizationAddressPostals();
  531. foreach ($addressPriorities as $addressType) {
  532. foreach ($organizationAddressPostal as $postalAddress) {
  533. if ($postalAddress->getType() === $addressType) {
  534. return $postalAddress->getAddressPostal();
  535. }
  536. }
  537. }
  538. return null;
  539. }
  540. /**
  541. * Retrieve the phone for the organization.
  542. */
  543. protected function getOrganizationPhone(Organization $organization): ?string
  544. {
  545. $contactPriorities = [
  546. ContactPointTypeEnum::BILL,
  547. ContactPointTypeEnum::CONTACT,
  548. ContactPointTypeEnum::PRINCIPAL,
  549. ContactPointTypeEnum::OTHER,
  550. ];
  551. $contactPoints = $organization->getContactPoints();
  552. foreach ($contactPriorities as $contactType) {
  553. foreach ($contactPoints as $contactPoint) {
  554. if ($contactPoint->getContactType() === $contactType) {
  555. if (null !== $contactPoint->getTelphone()) {
  556. return $this->formatPhoneNumber($contactPoint->getTelphone());
  557. }
  558. if (null !== $contactPoint->getMobilPhone()) {
  559. return $this->formatPhoneNumber($contactPoint->getMobilPhone());
  560. }
  561. }
  562. }
  563. }
  564. return null;
  565. }
  566. /**
  567. * Retrieve the email for the organization.
  568. */
  569. protected function getOrganizationEmail(Organization $organization): ?string
  570. {
  571. $contactPriorities = [
  572. ContactPointTypeEnum::BILL,
  573. ContactPointTypeEnum::CONTACT,
  574. ContactPointTypeEnum::PRINCIPAL,
  575. ContactPointTypeEnum::OTHER,
  576. ];
  577. $contactPoints = $organization->getContactPoints();
  578. foreach ($contactPriorities as $contactType) {
  579. foreach ($contactPoints as $contactPoint) {
  580. if ($contactPoint->getContactType() === $contactType && null !== $contactPoint->getEmail()) {
  581. return $contactPoint->getEmail();
  582. }
  583. }
  584. }
  585. return null;
  586. }
  587. /**
  588. * Return the id of the first active network found for the given organization.
  589. */
  590. protected function getOrganizationNetworkId(Organization $organization): ?int
  591. {
  592. foreach ($organization->getNetworkOrganizations() as $networkOrganization) {
  593. if (null !== $networkOrganization->getEndDate() && $networkOrganization->getEndDate() < new \DateTime()) {
  594. continue;
  595. }
  596. return $networkOrganization->getNetwork()?->getId();
  597. }
  598. return null;
  599. }
  600. /**
  601. * Returns the number of accesses possessing at least one of the missions.
  602. *
  603. * @param array<string> $missions A list of missions
  604. * @param array<string, array<string>> $members An organization members as returned by getActiveMembersIndex: [$accessID => [$missions...]]
  605. * @return int
  606. */
  607. protected function countWithMission(array $missions, array $members): int
  608. {
  609. return count(array_filter(
  610. $members,
  611. static function ($actualMissions) use ($missions) {
  612. return !empty(
  613. array_intersect($actualMissions, $missions)
  614. );
  615. }
  616. ));
  617. }
  618. /**
  619. * Return the best contact point for the given Person, or null if none.
  620. */
  621. protected function getPersonContact(Person $person): ?ContactPoint
  622. {
  623. $contactPriorities = [
  624. ContactPointTypeEnum::PRINCIPAL,
  625. ContactPointTypeEnum::OTHER,
  626. ];
  627. $contactPoints = $person->getContactPoints();
  628. foreach ($contactPriorities as $contactType) {
  629. foreach ($contactPoints as $contactPoint) {
  630. if ($contactPoint->getContactType() === $contactType) {
  631. return $contactPoint;
  632. }
  633. }
  634. }
  635. return null;
  636. }
  637. /**
  638. * Format the contact position from its gender and missions.
  639. *
  640. * @param list<string> $missions
  641. */
  642. protected function formatContactPosition(array $missions, ?string $gender = 'X'): string
  643. {
  644. $to_exclude = [
  645. FunctionEnum::ADHERENT->value,
  646. FunctionEnum::STUDENT->value,
  647. FunctionEnum::OTHER->value,
  648. ];
  649. $poste = implode(
  650. ', ',
  651. array_map(
  652. function ($m) use ($gender) {
  653. return $this->translator->trans(
  654. $m,
  655. ['gender' => [
  656. GenderEnum::MISS->value => 'F',
  657. GenderEnum::MISTER->value => 'M',
  658. ][$gender] ?? 'X']
  659. );
  660. },
  661. array_filter(
  662. $missions,
  663. static function ($m) use ($to_exclude) {
  664. return !in_array($m, $to_exclude, true);
  665. }
  666. )
  667. )
  668. );
  669. if (strlen($poste) > 80) {
  670. $poste = mb_substr($poste, 0, 77, 'utf-8').'...';
  671. }
  672. return $poste;
  673. }
  674. /**
  675. * Format a phone number into international format.
  676. */
  677. protected function formatPhoneNumber(PhoneNumber $phoneNumber): mixed
  678. {
  679. $phoneUtil = PhoneNumberUtil::getInstance();
  680. return str_replace(
  681. ' ',
  682. '',
  683. $phoneUtil->format($phoneNumber, PhoneNumberFormat::INTERNATIONAL)
  684. );
  685. }
  686. /**
  687. * @return array<int>
  688. */
  689. protected function getExpectedTagsFor(Organization $organization): array
  690. {
  691. $expectedTags = [];
  692. $product = $organization->getSettings()->getProduct();
  693. // Association, school or school premium
  694. if (LegalEnum::ASSOCIATION_LAW_1901 === $organization->getLegalStatus()) {
  695. if (SettingsProductEnum::SCHOOL === $product) {
  696. $expectedTags[] = self::ASSOCIATION_SCHOOL_TAG_ID;
  697. }
  698. if (SettingsProductEnum::SCHOOL_PREMIUM === $product) {
  699. $expectedTags[] = self::ASSOCIATION_PREMIUM_TAG_ID;
  700. }
  701. }
  702. // Local authorities, school or school premium
  703. if (LegalEnum::LOCAL_AUTHORITY === $organization->getLegalStatus()) {
  704. if (SettingsProductEnum::SCHOOL === $product) {
  705. $expectedTags[] = self::LOCAL_AUTH_SCHOOL_TAG_ID;
  706. }
  707. if (SettingsProductEnum::SCHOOL_PREMIUM === $product) {
  708. $expectedTags[] = self::LOCAL_AUTH_PREMIUM_TAG_ID;
  709. }
  710. }
  711. return $expectedTags;
  712. }
  713. /**
  714. * Post-validation of the execution of the operation.
  715. * Compare the actual result to the expected one to ensure that the data was correctly updated.
  716. *
  717. * In the case of a validation error, throw an HttpException
  718. *
  719. * @throws \RuntimeException
  720. */
  721. protected function validateResponse(ResponseInterface $response, UpdateOperation|CreateOperation $operation): void
  722. {
  723. $updated = $operation->getData();
  724. try {
  725. $responseData = $response->toArray();
  726. } catch (ClientExceptionInterface|DecodingExceptionInterface|RedirectionExceptionInterface|ServerExceptionInterface|TransportExceptionInterface $e) {
  727. throw new \RuntimeException("Couldn't read the content of the response : ".$e);
  728. }
  729. // Sanitize to get rid of the null / empty strings transformations of the API
  730. $updated = $this->sanitizeDolibarrData($updated);
  731. $responseData = $this->sanitizeDolibarrData($responseData);
  732. $diffs = $this->arrayUtils->getChanges($responseData, $updated, true);
  733. if (!empty($diffs)) {
  734. /* @noinspection JsonEncodingApiUsageInspection */
  735. throw new \RuntimeException('The '.$operation->getMethod()." request had an unexpected result.\n".'Expected content: '.json_encode($updated)."\n".'Actual content : '.json_encode($responseData));
  736. }
  737. }
  738. }