DolibarrSyncService.php 29 KB

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