DolibarrSyncService.php 29 KB

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