DolibarrSyncService.php 30 KB

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