DolibarrSyncService.php 30 KB

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