DolibarrSyncServiceTest.php 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487
  1. <?php
  2. /** @noinspection ALL */
  3. namespace App\Tests\Unit\Service\Dolibarr;
  4. use App\Entity\Access\Access;
  5. use App\Entity\Access\FunctionType;
  6. use App\Entity\Core\AddressPostal;
  7. use App\Entity\Core\ContactPoint;
  8. use App\Entity\Network\Network;
  9. use App\Entity\Network\NetworkOrganization;
  10. use App\Entity\Organization\Organization;
  11. use App\Entity\Organization\OrganizationAddressPostal;
  12. use App\Entity\Organization\Settings;
  13. use App\Entity\Person\Person;
  14. use App\Enum\Access\FunctionEnum;
  15. use App\Enum\Access\RoleEnum;
  16. use App\Enum\Core\ContactPointTypeEnum;
  17. use App\Enum\Network\NetworkEnum;
  18. use App\Enum\Organization\AddressPostalOrganizationTypeEnum;
  19. use App\Enum\Organization\LegalEnum;
  20. use App\Enum\Organization\SettingsProductEnum;
  21. use App\Enum\Person\GenderEnum;
  22. use App\Repository\Access\AccessRepository;
  23. use App\Repository\Access\FunctionTypeRepository;
  24. use App\Repository\Organization\OrganizationRepository;
  25. use App\Service\Core\AddressPostalUtils;
  26. use App\Service\Dolibarr\DolibarrApiService;
  27. use App\Service\Dolibarr\DolibarrSyncService;
  28. use App\Service\Organization\Utils;
  29. use App\Service\Rest\Operation\BaseRestOperation;
  30. use App\Service\Rest\Operation\CreateOperation;
  31. use App\Service\Rest\Operation\DeleteOperation;
  32. use App\Service\Rest\Operation\UpdateOperation;
  33. use App\Service\Utils\ArrayUtils;
  34. use App\Service\Utils\DatesUtils;
  35. use Doctrine\Common\Collections\ArrayCollection;
  36. use libphonenumber\PhoneNumber;
  37. use libphonenumber\PhoneNumberUtil;
  38. use PHPUnit\Framework\MockObject\MockObject;
  39. use PHPUnit\Framework\TestCase;
  40. use Psr\Log\LoggerInterface;
  41. use Symfony\Component\HttpClient\Exception\ServerException;
  42. use Symfony\Contracts\HttpClient\ResponseInterface;
  43. use Symfony\Contracts\Translation\TranslatorInterface;
  44. class TestableDolibarrSyncService extends DolibarrSyncService
  45. {
  46. public function getDolibarrSocietiesIndex(): array
  47. {
  48. return parent::getDolibarrSocietiesIndex();
  49. }
  50. public function findDolibarrContactFor(array $dolibarrContacts, Person $person): ?array
  51. {
  52. return parent::findDolibarrContactFor($dolibarrContacts, $person);
  53. }
  54. public function getActiveMembersIndex(): array
  55. {
  56. return parent::getActiveMembersIndex();
  57. }
  58. public function sanitizeDolibarrData(?array $data): ?array
  59. {
  60. return parent::sanitizeDolibarrData($data);
  61. }
  62. public function getOrganizationPostalAddress(Organization $organization): ?AddressPostal
  63. {
  64. return parent::getOrganizationPostalAddress($organization);
  65. }
  66. public function getOrganizationPhone(Organization $organization): ?string
  67. {
  68. return parent::getOrganizationPhone($organization);
  69. }
  70. public function getOrganizationEmail(Organization $organization): ?string
  71. {
  72. return parent::getOrganizationEmail($organization);
  73. }
  74. public function getOrganizationNetworkId(Organization $organization): ?int
  75. {
  76. return parent::getOrganizationNetworkId($organization);
  77. }
  78. public function countWithMission(array $missions, array $members): int
  79. {
  80. return parent::countWithMission($missions, $members);
  81. }
  82. public function getPersonContact(Person $person): ?ContactPoint
  83. {
  84. return parent::getPersonContact($person);
  85. }
  86. public function formatContactPosition(array $missions, ?string $gender = 'X'): string
  87. {
  88. return parent::formatContactPosition($missions, $gender);
  89. }
  90. public function formatPhoneNumber(PhoneNumber $phoneNumber): string
  91. {
  92. return parent::formatPhoneNumber($phoneNumber);
  93. }
  94. public function getExpectedTagsFor(Organization $organization): array
  95. {
  96. return parent::getExpectedTagsFor($organization);
  97. }
  98. public function validateResponse(ResponseInterface $response, BaseRestOperation $operation): void
  99. {
  100. parent::validateResponse($response, $operation);
  101. }
  102. }
  103. class DolibarrSyncServiceTest extends TestCase
  104. {
  105. private MockObject|OrganizationRepository $organizationRepository;
  106. private MockObject|AccessRepository $accessRepository;
  107. private MockObject|FunctionTypeRepository $functionTypeRepository;
  108. private MockObject|DolibarrApiService $dolibarrApiService;
  109. private MockObject|AddressPostalUtils $addressPostalUtils;
  110. private MockObject|ArrayUtils $arrayUtils;
  111. private MockObject|TranslatorInterface $translator;
  112. private MockObject|LoggerInterface $logger;
  113. private MockObject|Utils $organizationUtils;
  114. public function setUp(): void
  115. {
  116. $this->organizationRepository = $this->getMockBuilder(OrganizationRepository::class)
  117. ->disableOriginalConstructor()
  118. ->getMock();
  119. $this->accessRepository = $this->getMockBuilder(AccessRepository::class)
  120. ->disableOriginalConstructor()
  121. ->getMock();
  122. $this->functionTypeRepository = $this->getMockBuilder(FunctionTypeRepository::class)
  123. ->disableOriginalConstructor()
  124. ->getMock();
  125. $this->dolibarrApiService = $this->getMockBuilder(DolibarrApiService::class)
  126. ->disableOriginalConstructor()
  127. ->getMock();
  128. $this->addressPostalUtils = $this->getMockBuilder(AddressPostalUtils::class)
  129. ->disableOriginalConstructor()
  130. ->getMock();
  131. $this->arrayUtils = $this->getMockBuilder(ArrayUtils::class)
  132. ->disableOriginalConstructor()
  133. ->getMock();
  134. $this->translator = $this->getMockBuilder(TranslatorInterface::class)
  135. ->disableOriginalConstructor()
  136. ->getMock();
  137. $this->logger = $this->getMockBuilder(LoggerInterface::class)
  138. ->disableOriginalConstructor()
  139. ->getMock();
  140. $this->organizationUtils = $this->getMockBuilder(Utils::class)
  141. ->disableOriginalConstructor()
  142. ->getMock();
  143. $this->logger->method('info')->willReturnSelf();
  144. $this->logger->method('debug')->willReturnSelf();
  145. $this->logger->method('warning')->willReturnSelf();
  146. $this->logger->method('error')->willReturnSelf();
  147. }
  148. public function tearDown(): void
  149. {
  150. DatesUtils::clearFakeDatetime();
  151. }
  152. private function getMockForMethod(string $method)
  153. {
  154. $dolibarrSyncService = $this->getMockBuilder(TestableDolibarrSyncService::class)
  155. ->setConstructorArgs([$this->organizationRepository, $this->accessRepository, $this->functionTypeRepository,
  156. $this->dolibarrApiService, $this->addressPostalUtils, $this->arrayUtils, $this->translator, $this->organizationUtils])
  157. ->setMethodsExcept([$method, 'setLoggerInterface'])
  158. ->getMock();
  159. $dolibarrSyncService->setLoggerInterface($this->logger);
  160. return $dolibarrSyncService;
  161. }
  162. /**
  163. * Full test of the scan method.
  164. *
  165. * @see DolibarrSyncService::scan()
  166. */
  167. public function testScan(): void
  168. {
  169. $dolibarrSyncService = $this->getMockForMethod('scan');
  170. // ----- Opentalent Organizations -----
  171. $orgId1 = 10;
  172. $organization1 = $this->getMockBuilder(Organization::class)->getMock();
  173. $organization1->method('getId')->willReturn($orgId1);
  174. $organization1->method('getName')->willReturn('Organization 10');
  175. $organizationData1 = [
  176. 'fullAddress' => '1 Rue Azerty',
  177. 'addressOwner' => 'Mr Keyboard',
  178. 'postalCode' => '01110',
  179. 'city' => 'ByteCity',
  180. 'email' => 'foo@bar.net',
  181. 'phone' => '0102030405',
  182. 'networkId' => NetworkEnum::CMF->value,
  183. 'product' => SettingsProductEnum::SCHOOL,
  184. 'networkId' => NetworkEnum::CMF->value,
  185. 'legalStatus' => LegalEnum::LOCAL_AUTHORITY,
  186. ];
  187. $orgId2 = 20;
  188. $organization2 = $this->getMockBuilder(Organization::class)->getMock();
  189. $organization2->method('getId')->willReturn($orgId2);
  190. $organization2->method('getName')->willReturn('Organization 20');
  191. $organizationData2 = [
  192. 'email' => null,
  193. 'phone' => null,
  194. 'networkId' => null,
  195. 'product' => SettingsProductEnum::ARTIST,
  196. 'legalStatus' => LegalEnum::ASSOCIATION_LAW_1901,
  197. ];
  198. $orgId3 = 30;
  199. $organization3 = null; // This organization does not exist
  200. // Persons
  201. $accessId1 = 11; // Person 1
  202. $accessId2 = 21; // Person 2
  203. $accessId3 = 12; // Shall be ignored, because not an office member
  204. // access 4 does not exist
  205. $accessId5 = 13; // Invalid Person
  206. $personId1 = 100;
  207. $personData1 = [
  208. 'name' => 'Dupont',
  209. 'givenName' => 'Hercules',
  210. 'gender' => GenderEnum::MISTER,
  211. 'email' => 'an@email.net',
  212. 'phone' => '0102030405',
  213. 'mobilePhone' => '0607080910',
  214. ];
  215. $personId2 = 200;
  216. $personData2 = [
  217. 'name' => 'Simpson',
  218. 'givenName' => 'Lisa',
  219. 'gender' => null,
  220. ];
  221. $personId3 = 300; // Obsolete contact, does not exist anymore in the Opentalent DB
  222. $personId4 = 400; // Obsolete contact, does not exist anymore in the Opentalent DB
  223. $personId5 = 900; // Invalid contact with no firstname and no lastname
  224. $personData5 = [
  225. 'name' => '',
  226. 'givenName' => '',
  227. 'gender' => null,
  228. ];
  229. $activeMembers1 = [
  230. $accessId1 => [FunctionEnum::PRESIDENT->value],
  231. $accessId3 => [FunctionEnum::STUDENT->value],
  232. $accessId5 => [FunctionEnum::TREASURER->value],
  233. ];
  234. $activeMembers2 = [
  235. $accessId2 => [FunctionEnum::PRESIDENT->value],
  236. ];
  237. // ----- Opentalent : other vars -----
  238. $cmfId = 12097;
  239. $cmfDolibarrId = 12098;
  240. $ffecId = 91295;
  241. $ffecDolibarrId = 91296;
  242. // ----- Dolibarr societies -----
  243. // Existing society about to be updated
  244. $socId1 = 1;
  245. $dolibarrSociety1 = [
  246. 'id' => $socId1,
  247. 'name' => 'Organization 10',
  248. 'address' => '1 Rue Qwerty',
  249. 'zip' => '01024',
  250. 'town' => 'Ram',
  251. 'email' => 'some@email.com',
  252. 'phone' => null,
  253. 'status' => 0,
  254. 'parent' => '0',
  255. 'array_options' => [
  256. 'options_2iopeninfoopentalent' => '',
  257. 'options_2iopen_software_opentalent' => 'Opentalent Artist',
  258. ],
  259. ];
  260. // Existing society with no data
  261. $socId2 = 2;
  262. $dolibarrSociety2 = [
  263. 'id' => $socId2,
  264. 'array_options' => [],
  265. ];
  266. // This organization does not exist in the opentalent DB
  267. $socId3 = 3;
  268. $dolibarrSociety3 = null;
  269. // Dolibarr contacts
  270. $contactData1 = [
  271. 'id' => '1',
  272. 'civility_code' => '',
  273. 'lastname' => 'Dupond',
  274. 'firstname' => 'Bob',
  275. 'email' => 'abcd@mail.com',
  276. 'phone_pro' => '+33478570000',
  277. 'phone_mobile' => '+33682980000',
  278. 'poste' => 'Secrétaire',
  279. 'statut' => '1',
  280. 'array_options' => [
  281. 'options_2iopen_person_id' => '',
  282. ],
  283. ];
  284. // An obsolete contact that should be disabled
  285. $obsoleteContactData = [
  286. 'id' => '4',
  287. 'lastname' => 'Doe',
  288. 'firstname' => 'John',
  289. 'statut' => '1',
  290. 'array_options' => [
  291. 'options_2iopen_person_id' => $personId3,
  292. ],
  293. ];
  294. // An obsolete contact that should is already disabled
  295. $obsoleteContactData2 = [
  296. 'id' => '5',
  297. 'lastname' => 'Foo',
  298. 'firstname' => 'John',
  299. 'statut' => '0',
  300. 'array_options' => [
  301. 'options_2iopen_person_id' => $personId4,
  302. ],
  303. ];
  304. $dolibarrSocietyContacts1 = [$contactData1, $obsoleteContactData, $obsoleteContactData2];
  305. $dolibarrSocietyContacts2 = [];
  306. // ----- Setup Mocks -----
  307. $this->translator->method('trans')->willReturnMap([
  308. ['STUDENTS_COUNT', [], null, null, "Nombre d'élèves"],
  309. ['ADHERENTS_COUNT', [], null, null, "Nombre d'adhérents"],
  310. ['ADMIN_ACCESS_COUNT', [], null, null, "Nombre d'accès admin"],
  311. [SettingsProductEnum::SCHOOL->value, [], null, null, 'Opentalent School'],
  312. [SettingsProductEnum::ARTIST->value, [], null, null, 'Opentalent Artist'],
  313. [GenderEnum::MISTER->value, [], null, null, 'MR'],
  314. ]);
  315. // Get societies
  316. $this->organizationRepository->method('find')
  317. ->willReturnMap([
  318. [$orgId1, null, null, $organization1],
  319. [$orgId2, null, null, $organization2],
  320. [$orgId3, null, null, $organization3],
  321. ]);
  322. $dolibarrSyncService
  323. ->expects(self::once())
  324. ->method('getDolibarrSocietiesIndex')
  325. ->willReturn([
  326. $orgId1 => $dolibarrSociety1,
  327. $orgId2 => $dolibarrSociety2,
  328. $orgId3 => $dolibarrSociety3,
  329. ]);
  330. $dolibarrSyncService
  331. ->expects(self::once())
  332. ->method('getActiveMembersIndex')
  333. ->willReturn([
  334. $orgId1 => $activeMembers1,
  335. $orgId2 => $activeMembers2,
  336. $orgId3 => [],
  337. ]);
  338. // Function types
  339. $functionType1 = $this->getMockBuilder(FunctionType::class)->getMock();
  340. $functionType1->method('getMission')->willReturn(FunctionEnum::DIRECTOR);
  341. $functionType2 = $this->getMockBuilder(FunctionType::class)->getMock();
  342. $functionType2->method('getMission')->willReturn(FunctionEnum::PRESIDENT);
  343. $this->functionTypeRepository
  344. ->expects($this->once())
  345. ->method('findBy')
  346. ->with(['roleByDefault' => RoleEnum::ROLE_ADMIN])
  347. ->willReturn([$functionType1, $functionType2]);
  348. // Get CMF and FFEC ids
  349. $this->dolibarrApiService->method('getSociety')->willReturnMap(
  350. [
  351. [$cmfId, ['id' => $cmfDolibarrId]],
  352. [$ffecId, ['id' => $ffecDolibarrId]],
  353. ]
  354. );
  355. // -- Loop over organizations --
  356. $dolibarrSyncService
  357. ->expects(self::exactly(5)) // 3 organizations and 2 contacts
  358. ->method('sanitizeDolibarrData')
  359. ->willReturnCallback(function ($args) { return $args; });
  360. $addressPostal = $this->getMockBuilder(AddressPostal::class)->getMock();
  361. $dolibarrSyncService
  362. ->expects(self::exactly(2))
  363. ->method('getOrganizationPostalAddress')
  364. ->willReturnMap([
  365. [$organization1, $addressPostal],
  366. [$organization2, null],
  367. ]);
  368. $this->addressPostalUtils
  369. ->method('getFullStreetAddress')
  370. ->with($addressPostal)
  371. ->willReturn($organizationData1['fullAddress']);
  372. $addressPostal->method('getAddressOwner')->willReturn($organizationData1['addressOwner']);
  373. $addressPostal->method('getPostalCode')->willReturn($organizationData1['postalCode']);
  374. $addressPostal->method('getAddressCity')->willReturn($organizationData1['city']);
  375. $dolibarrSyncService
  376. ->expects(self::exactly(2))
  377. ->method('getOrganizationEmail')
  378. ->willReturnMap([
  379. [$organization1, $organizationData1['email']],
  380. [$organization2, $organizationData2['email']],
  381. ]);
  382. $dolibarrSyncService
  383. ->expects(self::exactly(2))
  384. ->method('getOrganizationPhone')
  385. ->willReturnMap([
  386. [$organization1, $organizationData1['phone']],
  387. [$organization2, $organizationData2['phone']],
  388. ]);
  389. $dolibarrSyncService
  390. ->expects(self::exactly(2))
  391. ->method('getOrganizationNetworkId')
  392. ->willReturnMap([
  393. [$organization1, $organizationData1['networkId']],
  394. [$organization2, $organizationData2['networkId']],
  395. ]);
  396. $settings1 = $this->getMockBuilder(Settings::class)->getMock();
  397. $settings1->method('getProduct')->willReturn($organizationData1['product']);
  398. $organization1->method('getSettings')->willReturn($settings1);
  399. $settings2 = $this->getMockBuilder(Settings::class)->getMock();
  400. $settings2->method('getProduct')->willReturn($organizationData2['product']);
  401. $organization2->method('getSettings')->willReturn($settings2);
  402. $this->organizationUtils->method('isSchool')->willReturnMap([
  403. [$organization1, true],
  404. [$organization2, false],
  405. ]);
  406. $this->organizationUtils->method('isArtist')->willReturnMap([
  407. [$organization1, false],
  408. [$organization2, true],
  409. ]);
  410. $dolibarrSyncService->method('countWithMission')->willReturnMap([
  411. [[FunctionEnum::STUDENT->value], $activeMembers1, 1],
  412. [[FunctionEnum::ADHERENT->value], $activeMembers1, 2],
  413. [[FunctionEnum::ADHERENT->value], $activeMembers2, 0],
  414. [[FunctionEnum::DIRECTOR->value, FunctionEnum::PRESIDENT->value], $activeMembers1, 1],
  415. [[FunctionEnum::DIRECTOR->value, FunctionEnum::PRESIDENT->value], $activeMembers2, 2],
  416. ]);
  417. $this->arrayUtils
  418. ->expects(self::exactly(3))
  419. ->method('getChanges')
  420. ->willReturnCallback(
  421. function (array $initialArray, array $newArray, bool $recursive = false, ?callable $callback = null) {
  422. if (in_array('name', $newArray, true)) {
  423. // Organization 1 name is already defined and has not been changed
  424. unset($newArray['name']);
  425. }
  426. if (in_array('statut', $newArray, true)) {
  427. // Contact 1 statut is already defined and has not been changed
  428. unset($newArray['statut']);
  429. }
  430. return $newArray;
  431. }
  432. );
  433. $this->dolibarrApiService->method('getContacts')->willReturnMap([
  434. [$socId1, $dolibarrSocietyContacts1],
  435. [$socId2, $dolibarrSocietyContacts2],
  436. ]);
  437. // Loop over contacts
  438. // NB: Student will be skipped since it has no office role
  439. $person1 = $this->getMockBuilder(Person::class)->getMock();
  440. $person1->method('getId')->willReturn($personId1);
  441. $person1->method('getName')->willReturn($personData1['name']);
  442. $person1->method('getGivenName')->willReturn($personData1['givenName']);
  443. $person1->method('getGender')->willReturn($personData1['gender']);
  444. $person2 = $this->getMockBuilder(Person::class)->getMock();
  445. $person2->method('getId')->willReturn($personId2);
  446. $person2->method('getName')->willReturn($personData2['name']);
  447. $person2->method('getGivenName')->willReturn($personData2['givenName']);
  448. $person2->method('getGender')->willReturn($personData2['gender']);
  449. // An invalid person that should be ignored
  450. $person5 = $this->getMockBuilder(Person::class)->getMock();
  451. $person5->method('getId')->willReturn($personId5);
  452. $person5->method('getName')->willReturn($personData5['name']);
  453. $person5->method('getGivenName')->willReturn($personData5['givenName']);
  454. $access1 = $this->getMockBuilder(Access::class)->getMock();
  455. $access1->method('getPerson')->willReturn($person1);
  456. $access2 = $this->getMockBuilder(Access::class)->getMock();
  457. $access2->method('getPerson')->willReturn($person2);
  458. $access5 = $this->getMockBuilder(Access::class)->getMock();
  459. $access5->method('getPerson')->willReturn($person5);
  460. $this->accessRepository->method('find')->willReturnMap([
  461. [$accessId1, null, null, $access1],
  462. [$accessId2, null, null, $access2],
  463. [$accessId5, null, null, $access5],
  464. ]);
  465. $dolibarrSyncService->method('findDolibarrContactFor')->willReturnMap([
  466. [$dolibarrSocietyContacts1, $person1, $contactData1],
  467. [$dolibarrSocietyContacts2, $person2, null],
  468. ]);
  469. $contactPoint1 = $this->getMockBuilder(ContactPoint::class)->getMock();
  470. $contactPoint1->method('getEmail')->willReturn($personData1['email']);
  471. $phone = $this->getMockBuilder(PhoneNumber::class)->getMock();
  472. $mobilePhone = $this->getMockBuilder(PhoneNumber::class)->getMock();
  473. $dolibarrSyncService->method('formatPhoneNumber')->willReturnMap([
  474. [$phone, $personData1['phone']],
  475. [$mobilePhone, $personData1['mobilePhone']],
  476. ]);
  477. $contactPoint1->method('getTelphone')->willReturn($phone);
  478. $contactPoint1->method('getMobilPhone')->willReturn($mobilePhone);
  479. $dolibarrSyncService->method('getPersonContact')->willReturnMap([
  480. [$person1, $contactPoint1],
  481. [$person2, null],
  482. ]);
  483. $dolibarrSyncService->method('formatContactPosition')->willReturnMap([
  484. [[FunctionEnum::PRESIDENT->value], GenderEnum::MISTER->value, 'Président'],
  485. [[FunctionEnum::PRESIDENT->value], null, 'Président(e)'],
  486. ]);
  487. // Expected logged error messages
  488. $this->logger->expects(self::exactly(2))->method('error')->withConsecutive(
  489. ['Person 900 miss a lastname and/or a firstname, ignored.'],
  490. ['Organization 30 not found in the Opentalent DB'],
  491. );
  492. // Tags
  493. $this->dolibarrApiService->method('getSocietyTagsIds')->willReturnMap([
  494. [$socId1, [1, 68]],
  495. [$socId2, [3, 67]],
  496. ]);
  497. $dolibarrSyncService->method('getExpectedTagsFor')->willReturnMap([
  498. [$organization1, [67]],
  499. [$organization2, []],
  500. ]);
  501. // Expected progression callback triggers
  502. $progressionCallbackExpectedCalls = [[1, 3], [2, 3], [3, 3]];
  503. $progressionCallback = static function ($i, $total) use (&$progressionCallbackExpectedCalls) {
  504. [$expectedI, $expectedTotal] = array_shift($progressionCallbackExpectedCalls);
  505. if ($i !== $expectedI || $total !== $expectedTotal) {
  506. throw new \AssertionError('Progression callback error, expected parameters are ('.$expectedI.','.$expectedTotal.'), got ('.$i.', '.$total.')');
  507. }
  508. };
  509. DatesUtils::setFakeDatetime('2024-01-01T00:00:00+00:00');
  510. $operations = $dolibarrSyncService->scan($progressionCallback);
  511. $this->assertCount(8, $operations);
  512. $this->assertEqualsCanonicalizing(
  513. [
  514. '[PUT thirdparties/1]',
  515. "address : `1 Rue Qwerty` => `Mr Keyboard\n1 Rue Azerty`",
  516. 'zip : `01024` => `01110`',
  517. 'town : `Ram` => `ByteCity`',
  518. 'email : `some@email.com` => `foo@bar.net`',
  519. 'phone : `` => `0102030405`',
  520. 'parent : `0` => `12098`',
  521. 'array_options.options_2iopen_software_opentalent : `Opentalent Artist` => `Opentalent School`',
  522. "array_options.options_2iopeninfoopentalent : `` => `Nombre d'élèves : 1\nNombre d'adhérents : 2\nNombre d'accès admin : 1`",
  523. 'array_options.options_2iopen_last_sync_date : (new) => `2024-01-01T00:00:00+00:00`',
  524. 'status : `0` => `1`',
  525. ],
  526. $operations[0]->getChangeLog()
  527. );
  528. $this->assertEqualsCanonicalizing(
  529. [
  530. '[PUT contacts/1]',
  531. 'civility_code : `` => `MR`',
  532. 'lastname : `Dupond` => `Dupont`',
  533. 'firstname : `Bob` => `Hercules`',
  534. 'email : `abcd@mail.com` => `an@email.net`',
  535. 'phone_pro : `+33478570000` => `0102030405`',
  536. 'phone_mobile : `+33682980000` => `0607080910`',
  537. 'poste : `Secrétaire` => `Président`',
  538. 'array_options.options_2iopen_person_id : `` => `100`',
  539. 'array_options.options_2iopen_last_sync_date : (new) => `2024-01-01T00:00:00+00:00`',
  540. ],
  541. $operations[1]->getChangeLog()
  542. );
  543. $this->assertEqualsCanonicalizing(
  544. [
  545. '[PUT contacts/4]',
  546. 'statut : `1` => `0`',
  547. 'array_options.options_2iopen_last_sync_date : (new) => `2024-01-01T00:00:00+00:00`',
  548. ],
  549. $operations[2]->getChangeLog()
  550. );
  551. $this->assertEqualsCanonicalizing(
  552. [
  553. '[DELETE /thirdparties/1/categories/68]',
  554. ],
  555. $operations[3]->getChangeLog()
  556. );
  557. $this->assertEqualsCanonicalizing(
  558. [
  559. '[POST /thirdparties/1/categories/67]',
  560. ],
  561. $operations[4]->getChangeLog()
  562. );
  563. $this->assertEqualsCanonicalizing(
  564. [
  565. '[PUT thirdparties/2]',
  566. 'address : (new) => ``',
  567. 'email : (new) => ``',
  568. 'name : (new) => `Organization 20`',
  569. 'parent : (new) => ``',
  570. 'phone : (new) => ``',
  571. 'status : (new) => `1`',
  572. 'town : (new) => ``',
  573. 'zip : (new) => ``',
  574. 'array_options.options_2iopen_software_opentalent : (new) => `Opentalent Artist`',
  575. "array_options.options_2iopeninfoopentalent : (new) => `Nombre d'adhérents : 0\nNombre d'accès admin : 2`",
  576. 'array_options.options_2iopen_last_sync_date : (new) => `2024-01-01T00:00:00+00:00`',
  577. ],
  578. $operations[5]->getChangeLog()
  579. );
  580. $this->assertEqualsCanonicalizing(
  581. [
  582. '[POST contacts]',
  583. 'civility_code : (new) => ``',
  584. 'lastname : (new) => `Simpson`',
  585. 'firstname : (new) => `Lisa`',
  586. 'email : (new) => ``',
  587. 'phone_pro : (new) => ``',
  588. 'phone_mobile : (new) => ``',
  589. 'poste : (new) => `Président(e)`',
  590. 'statut : (new) => `1`',
  591. 'array_options.options_2iopen_person_id : (new) => `200`',
  592. 'array_options.options_2iopen_last_sync_date : (new) => `2024-01-01T00:00:00+00:00`',
  593. 'socid : (new) => `2`',
  594. ],
  595. $operations[6]->getChangeLog()
  596. );
  597. $this->assertEqualsCanonicalizing(
  598. [
  599. '[DELETE /thirdparties/2/categories/67]',
  600. ],
  601. $operations[7]->getChangeLog()
  602. );
  603. $this->assertCount(0, $progressionCallbackExpectedCalls);
  604. }
  605. /**
  606. * All valid operations shall be executed
  607. * If an operation is not in status READY, a warning shall be logged, and the operation shall be skipped.
  608. *
  609. * @see DolibarrSyncService::execute()
  610. */
  611. public function testExecute(): void
  612. {
  613. $dolibarrSyncService = $this->getMockForMethod('execute');
  614. $progressionCallbackExpectedCalls = [[1, 3], [2, 3], [3, 3]];
  615. $progressionCallback = static function ($i, $total) use (&$progressionCallbackExpectedCalls) {
  616. [$expectedI, $expectedTotal] = array_shift($progressionCallbackExpectedCalls);
  617. if ($i !== $expectedI || $total !== $expectedTotal) {
  618. throw new \AssertionError('Progression callback error, expected parameters are ('.$expectedI.','.$expectedTotal.'), got ('.$i.', '.$total.')');
  619. }
  620. };
  621. $response = $this->getMockBuilder(ResponseInterface::class)->disableOriginalConstructor()->getMock();
  622. $operation1 = $this->getMockBuilder(UpdateOperation::class)->disableOriginalConstructor()->getMock();
  623. $operation1->method('getStatus')->willReturnOnConsecutiveCalls(BaseRestOperation::STATUS_READY, BaseRestOperation::STATUS_DONE);
  624. $operation1->method('getChangeLog')->willReturn(['foo']);
  625. $operation1->expects(self::once())->method('execute')->willReturn($response);
  626. $dolibarrSyncService->method('validateResponse')->with($response, $operation1)->willThrowException(new \RuntimeException());
  627. $operation2 = $this->getMockBuilder(CreateOperation::class)->disableOriginalConstructor()->getMock();
  628. $operation2->method('getStatus')->willReturn(
  629. BaseRestOperation::STATUS_READY, BaseRestOperation::STATUS_ERROR, BaseRestOperation::STATUS_ERROR // An error happened
  630. );
  631. $operation2->expects(self::once())->method('execute');
  632. $operation3 = $this->getMockBuilder(DeleteOperation::class)->disableOriginalConstructor()->getMock();
  633. $operation3->method('getStatus')->willReturn(BaseRestOperation::STATUS_DONE); // Invalid status, should log a warning and not execute
  634. $operation3->expects(self::never())->method('execute');
  635. $this->logger->expects(self::exactly(3))->method('warning'); // 1 warning from validateResponse on the Update Op, and 2 because of the bad status of the Create Op
  636. $this->logger->expects(self::exactly(3))->method('error'); // The exception thrown during the execution of the Delete op will log 3 errors
  637. $dolibarrSyncService->execute([$operation1, $operation2, $operation3], $progressionCallback);
  638. }
  639. /**
  640. * @see DolibarrSyncService::run()
  641. */
  642. public function testRun()
  643. {
  644. $dolibarrSyncService = $this->getMockForMethod('run');
  645. $operations = ['operation1', 'operation2'];
  646. $dolibarrSyncService->expects(self::once())->method('scan')->willReturn($operations);
  647. $dolibarrSyncService->expects(self::once())->method('execute')->with($operations);
  648. $result = $dolibarrSyncService->run();
  649. $this->assertEquals($operations, $result);
  650. }
  651. /**
  652. * @see DolibarrSyncService::getDolibarrSocietiesIndex()
  653. */
  654. public function testGetDolibarrSocietiesIndex(): void
  655. {
  656. $dolibarrSyncService = $this->getMockForMethod('getDolibarrSocietiesIndex');
  657. $this->dolibarrApiService
  658. ->expects($this->once())
  659. ->method('getAllClients')
  660. ->willReturn(
  661. [
  662. ['id' => 1, 'array_options' => ['options_2iopen_organization_id' => 101]],
  663. ['id' => 2, 'array_options' => ['options_2iopen_organization_id' => 102]],
  664. ['id' => 3, 'array_options' => ['options_2iopen_organization_id' => null]], // No org id but also no contract, so it's ok
  665. ['id' => 4, 'name' => 'foo', 'array_options' => ['options_2iopen_organization_id' => null]], // No org id but has a contract, a warning should be logged
  666. ]
  667. );
  668. $this->dolibarrApiService->expects(self::exactly(2))->method('getActiveContract')->willReturnMap([
  669. [3, null],
  670. [4, ['dummy non-empty data']],
  671. ]);
  672. $this->logger->expects(self::once())->method('warning')->with('Dolibarr client has no organization id: foo (4)');
  673. $index = $dolibarrSyncService->getDolibarrSocietiesIndex();
  674. $this->assertEqualsCanonicalizing(
  675. [
  676. 1 => ['id' => 1, 'array_options' => ['options_2iopen_organization_id' => 101]],
  677. 2 => ['id' => 2, 'array_options' => ['options_2iopen_organization_id' => 102]],
  678. ],
  679. $index
  680. );
  681. }
  682. /**
  683. * @see DolibarrSyncService::getActiveMembersIndex()
  684. */
  685. public function testGetActiveMembersIndex(): void
  686. {
  687. $dolibarrSyncService = $this->getMockForMethod('getActiveMembersIndex');
  688. $this->accessRepository
  689. ->expects($this->once())
  690. ->method('getAllActiveMembersAndMissions')
  691. ->willReturn(
  692. [
  693. ['id' => 1, 'organization_id' => 1, 'mission' => FunctionEnum::PRESIDENT],
  694. ['id' => 2, 'organization_id' => 1, 'mission' => FunctionEnum::STUDENT],
  695. ['id' => 3, 'organization_id' => 2, 'mission' => FunctionEnum::PRESIDENT],
  696. ['id' => 3, 'organization_id' => 2, 'mission' => FunctionEnum::TEACHER],
  697. ]
  698. );
  699. $index = $dolibarrSyncService->getActiveMembersIndex();
  700. $this->assertEqualsCanonicalizing([
  701. 1 => [1 => [FunctionEnum::PRESIDENT->value], 2 => [FunctionEnum::STUDENT->value]],
  702. 2 => [3 => [FunctionEnum::PRESIDENT->value, FunctionEnum::TEACHER->value]]
  703. ], $index);
  704. }
  705. /**
  706. * @see DolibarrSyncService::findDolibarrContactFor()
  707. */
  708. public function testFindDolibarrContactForById(): void
  709. {
  710. $dolibarrSyncService = $this->getMockForMethod('findDolibarrContactFor');
  711. $contacts = [
  712. ['id' => 1, 'array_options' => ['options_2iopen_person_id' => 101]],
  713. ['id' => 2, 'array_options' => ['options_2iopen_person_id' => 102]],
  714. ];
  715. // Find by id
  716. $person = $this->getMockBuilder(Person::class)->getMock();
  717. $person->method('getId')->willReturn(102);
  718. $contact = $dolibarrSyncService->findDolibarrContactFor($contacts, $person);
  719. $this->assertEquals(2, $contact['id']);
  720. }
  721. /**
  722. * @see DolibarrSyncService::findDolibarrContactFor()
  723. */
  724. public function testFindDolibarrContactForByName(): void
  725. {
  726. $dolibarrSyncService = $this->getMockForMethod('findDolibarrContactFor');
  727. $contacts = [
  728. ['id' => 1, 'firstname' => 'mister', 'lastname' => 'X', 'array_options' => ['options_2iopen_person_id' => null]],
  729. ['id' => 2, 'firstname' => 'miss', 'lastname' => 'Y', 'array_options' => ['options_2iopen_person_id' => null]],
  730. ];
  731. // Find by full name (contact has no person id, it should be returned)
  732. $person = $this->getMockBuilder(Person::class)->getMock();
  733. $person->method('getId')->willReturn(101);
  734. $person->method('getName')->willReturn('X');
  735. $person->method('getGivenName')->willReturn('mister');
  736. $result = $dolibarrSyncService->findDolibarrContactFor($contacts, $person);
  737. $this->assertEquals(1, $result['id']);
  738. }
  739. /**
  740. * @see DolibarrSyncService::findDolibarrContactFor()
  741. */
  742. public function testFindDolibarrContactForByNameWithConflict(): void
  743. {
  744. $dolibarrSyncService = $this->getMockForMethod('findDolibarrContactFor');
  745. $contacts = [
  746. ['id' => 1, 'firstname' => 'mister', 'lastname' => 'X', 'array_options' => ['options_2iopen_person_id' => 1]],
  747. ['id' => 2, 'firstname' => 'miss', 'lastname' => 'Y', 'array_options' => ['options_2iopen_person_id' => 2]],
  748. ];
  749. // Find by full name (contact already has another person id, it should not be returned)
  750. $person = $this->getMockBuilder(Person::class)->getMock();
  751. $person->method('getId')->willReturn(101);
  752. $person->method('getName')->willReturn('X');
  753. $person->method('getGivenName')->willReturn('mister');
  754. $result = $dolibarrSyncService->findDolibarrContactFor($contacts, $person);
  755. $this->assertEquals(null, $result);
  756. }
  757. /**
  758. * @see DolibarrSyncService::findDolibarrContactFor()
  759. */
  760. public function testFindDolibarrContactNotFound(): void
  761. {
  762. $dolibarrSyncService = $this->getMockForMethod('findDolibarrContactFor');
  763. $contacts = [
  764. ['id' => 1, 'firstname' => 'mister', 'lastname' => 'X', 'array_options' => ['options_2iopen_person_id' => 1]],
  765. ['id' => 2, 'firstname' => 'miss', 'lastname' => 'Y', 'array_options' => ['options_2iopen_person_id' => 2]],
  766. ];
  767. // Do not find
  768. $person = $this->getMockBuilder(Person::class)->getMock();
  769. $person->method('getId')->willReturn(-1);
  770. $person->method('getName')->willReturn('Presley');
  771. $person->method('getGivenName')->willReturn('Elvis');
  772. $result = $dolibarrSyncService->findDolibarrContactFor($contacts, $person);
  773. $this->assertEquals(null, $result);
  774. }
  775. /**
  776. * @see DolibarrSyncService::sanitizeDolibarrData()
  777. */
  778. public function testSanitizeDolibarrData(): void
  779. {
  780. $dolibarrSyncService = $this->getMockForMethod('sanitizeDolibarrData');
  781. $result = $dolibarrSyncService->sanitizeDolibarrData(['a' => 'A', 'b' => '', 'c' => ['d' => 'D', 'e' => '']]);
  782. $this->assertEquals(
  783. ['a' => 'A', 'b' => null, 'c' => ['d' => 'D', 'e' => null]],
  784. $result
  785. );
  786. }
  787. /**
  788. * @see DolibarrSyncService::sanitizeDolibarrData()
  789. */
  790. public function testSanitizeDolibarrDataWithNull(): void
  791. {
  792. $dolibarrSyncService = $this->getMockForMethod('sanitizeDolibarrData');
  793. $result = $dolibarrSyncService->sanitizeDolibarrData(null);
  794. $this->assertEquals(null, $result);
  795. }
  796. /**
  797. * @see DolibarrSyncService::getOrganizationPostalAddress()
  798. */
  799. public function testGetOrganizationPostalAddress(): void
  800. {
  801. $dolibarrSyncService = $this->getMockForMethod('getOrganizationPostalAddress');
  802. $organization = $this->getMockBuilder(Organization::class)->getMock();
  803. $organizationAddressPostal1 = $this->getMockBuilder(OrganizationAddressPostal::class)->getMock();
  804. $organizationAddressPostal2 = $this->getMockBuilder(OrganizationAddressPostal::class)->getMock();
  805. $organizationAddressPostal3 = $this->getMockBuilder(OrganizationAddressPostal::class)->getMock();
  806. $addressPostal = $this->getMockBuilder(AddressPostal::class)->getMock();
  807. $organizationAddressPostal1->method('getType')->willReturn(AddressPostalOrganizationTypeEnum::ADDRESS_PRACTICE);
  808. $organizationAddressPostal2->method('getType')->willReturn(AddressPostalOrganizationTypeEnum::ADDRESS_BILL);
  809. $organizationAddressPostal3->method('getType')->willReturn(AddressPostalOrganizationTypeEnum::ADDRESS_OTHER);
  810. $organizationAddressPostal2->method('getAddressPostal')->willReturn($addressPostal);
  811. $organization->expects($this->once())
  812. ->method('getOrganizationAddressPostals')
  813. ->willReturn(
  814. new ArrayCollection([$organizationAddressPostal1, $organizationAddressPostal2, $organizationAddressPostal3])
  815. );
  816. $this->assertEquals(
  817. $addressPostal,
  818. $dolibarrSyncService->getOrganizationPostalAddress($organization)
  819. );
  820. }
  821. /**
  822. * @see DolibarrSyncService::getOrganizationPostalAddress()
  823. */
  824. public function testGetOrganizationPostalAddressNoResult(): void
  825. {
  826. $dolibarrSyncService = $this->getMockForMethod('getOrganizationPostalAddress');
  827. $organization = $this->getMockBuilder(Organization::class)->getMock();
  828. $organization->expects($this->once())
  829. ->method('getOrganizationAddressPostals')
  830. ->willReturn(new ArrayCollection([]));
  831. $this->assertEquals(
  832. null,
  833. $dolibarrSyncService->getOrganizationPostalAddress($organization)
  834. );
  835. }
  836. /**
  837. * @see DolibarrSyncService::getOrganizationPhone()
  838. */
  839. public function testGetOrganizationPhoneWithExistingPhone(): void
  840. {
  841. $dolibarrSyncService = $this->getMockForMethod('getOrganizationPhone');
  842. $contactPoint1 = $this->getMockBuilder(ContactPoint::class)->getMock();
  843. $contactPoint2 = $this->getMockBuilder(ContactPoint::class)->getMock();
  844. $contactPoint3 = $this->getMockBuilder(ContactPoint::class)->getMock();
  845. $contactPoint1->method('getContactType')->willReturn(ContactPointTypeEnum::OTHER);
  846. $contactPoint2->method('getContactType')->willReturn(ContactPointTypeEnum::BILL);
  847. $contactPoint3->method('getContactType')->willReturn(ContactPointTypeEnum::PRINCIPAL);
  848. $phone = $this->getMockBuilder(PhoneNumber::class)->disableOriginalConstructor()->getMock();
  849. $contactPoint2->method('getTelphone')->willReturn($phone);
  850. $organization = $this->getMockBuilder(Organization::class)->getMock();
  851. $organization
  852. ->expects($this->once())
  853. ->method('getContactPoints')
  854. ->willReturn(
  855. new ArrayCollection([$contactPoint1, $contactPoint2, $contactPoint3])
  856. );
  857. $dolibarrSyncService->expects(self::once())->method('formatPhoneNumber')->with($phone)->willReturn('+33161626365');
  858. $this->assertEquals(
  859. '+33161626365',
  860. $dolibarrSyncService->getOrganizationPhone($organization)
  861. );
  862. }
  863. /**
  864. * @see DolibarrSyncService::getOrganizationPhone()
  865. */
  866. public function testGetOrganizationPhoneWithMobilePhone()
  867. {
  868. $dolibarrSyncService = $this->getMockForMethod('getOrganizationPhone');
  869. $contactPoint1 = $this->getMockBuilder(ContactPoint::class)->getMock();
  870. $contactPoint2 = $this->getMockBuilder(ContactPoint::class)->getMock();
  871. $contactPoint3 = $this->getMockBuilder(ContactPoint::class)->getMock();
  872. $contactPoint1->method('getContactType')->willReturn(ContactPointTypeEnum::OTHER);
  873. $contactPoint2->method('getContactType')->willReturn(ContactPointTypeEnum::BILL);
  874. $contactPoint3->method('getContactType')->willReturn(ContactPointTypeEnum::PRINCIPAL);
  875. $contactPoint2->expects($this->once())->method('getTelphone')->willReturn(null);
  876. $mobilePhone = $this->getMockBuilder(PhoneNumber::class)->disableOriginalConstructor()->getMock();
  877. $contactPoint2->method('getMobilPhone')->willReturn($mobilePhone);
  878. $organization = $this->getMockBuilder(Organization::class)->getMock();
  879. $organization
  880. ->expects($this->once())
  881. ->method('getContactPoints')
  882. ->willReturn(
  883. new ArrayCollection([$contactPoint1, $contactPoint2, $contactPoint3])
  884. );
  885. $dolibarrSyncService->expects(self::once())->method('formatPhoneNumber')->with($mobilePhone)->willReturn('+33661626365');
  886. $this->assertEquals(
  887. '+33661626365',
  888. $dolibarrSyncService->getOrganizationPhone($organization)
  889. );
  890. }
  891. /**
  892. * @see DolibarrSyncService::getOrganizationPhone()
  893. */
  894. public function testGetOrganizationPhoneWithNoPhone()
  895. {
  896. $dolibarrSyncService = $this->getMockForMethod('getOrganizationPhone');
  897. $organization = $this->getMockBuilder(Organization::class)->getMock();
  898. $organization
  899. ->expects($this->once())
  900. ->method('getContactPoints')
  901. ->willReturn(new ArrayCollection([]));
  902. $dolibarrSyncService->expects(self::never())->method('formatPhoneNumber');
  903. $this->assertEquals(
  904. null,
  905. $dolibarrSyncService->getOrganizationPhone($organization)
  906. );
  907. }
  908. /**
  909. * @see DolibarrSyncService::getOrganizationEmail()
  910. */
  911. public function testGetOrganizationEmailWithExistingEmail()
  912. {
  913. $dolibarrSyncService = $this->getMockForMethod('getOrganizationEmail');
  914. $contactPoint1 = $this->getMockBuilder(ContactPoint::class)->getMock();
  915. $contactPoint2 = $this->getMockBuilder(ContactPoint::class)->getMock();
  916. $contactPoint3 = $this->getMockBuilder(ContactPoint::class)->getMock();
  917. $contactPoint1->method('getContactType')->willReturn(ContactPointTypeEnum::OTHER);
  918. $contactPoint2->method('getContactType')->willReturn(ContactPointTypeEnum::BILL);
  919. $contactPoint3->method('getContactType')->willReturn(ContactPointTypeEnum::PRINCIPAL);
  920. $contactPoint2->method('getEmail')->willReturn('email@email.com');
  921. $organization = $this->getMockBuilder(Organization::class)->getMock();
  922. $organization
  923. ->expects($this->once())
  924. ->method('getContactPoints')
  925. ->willReturn(
  926. new ArrayCollection([$contactPoint1, $contactPoint2, $contactPoint3])
  927. );
  928. $this->assertEquals(
  929. 'email@email.com',
  930. $dolibarrSyncService->getOrganizationEmail($organization)
  931. );
  932. }
  933. /**
  934. * @see DolibarrSyncService::getOrganizationEmail()
  935. */
  936. public function testGetOrganizationEmailWithNoEmail()
  937. {
  938. $dolibarrSyncService = $this->getMockForMethod('getOrganizationEmail');
  939. $organization = $this->getMockBuilder(Organization::class)->getMock();
  940. $organization
  941. ->expects($this->once())
  942. ->method('getContactPoints')
  943. ->willReturn(new ArrayCollection([]));
  944. $this->assertEquals(
  945. null,
  946. $dolibarrSyncService->getOrganizationEmail($organization)
  947. );
  948. }
  949. /**
  950. * @see DolibarrSyncService::getOrganizationNetworkId()
  951. */
  952. public function testGetOrganizationNetworkId()
  953. {
  954. $dolibarrSyncService = $this->getMockForMethod('getOrganizationNetworkId');
  955. $organization = $this->getMockBuilder(Organization::class)->getMock();
  956. $network = $this->getMockBuilder(Network::class)->getMock();
  957. $network->method('getId')->willReturn(3);
  958. $networkOrganization = $this->getMockBuilder(NetworkOrganization::class)->getMock();
  959. $networkOrganization->method('getNetwork')->willReturn($network);
  960. $organization->method('getNetworkOrganizations')->willReturn(new ArrayCollection([$networkOrganization]));
  961. $this->assertEquals(
  962. 3,
  963. $dolibarrSyncService->getOrganizationNetworkId($organization)
  964. );
  965. }
  966. /**
  967. * @see DolibarrSyncService::getOrganizationNetworkId()
  968. */
  969. public function testGetOrganizationNetworkIdWithMultipleResult()
  970. {
  971. $dolibarrSyncService = $this->getMockForMethod('getOrganizationNetworkId');
  972. $network1 = $this->getMockBuilder(Network::class)->getMock();
  973. $network1->method('getId')->willReturn(3);
  974. $networkOrganization1 = $this->getMockBuilder(NetworkOrganization::class)->getMock();
  975. $networkOrganization1->method('getNetwork')->willReturn($network1);
  976. $networkOrganization1->method('getEndDate')->willReturn(new \DateTime('2000-01-01'));
  977. $network2 = $this->getMockBuilder(Network::class)->getMock();
  978. $network2->method('getId')->willReturn(4);
  979. $networkOrganization2 = $this->getMockBuilder(NetworkOrganization::class)->getMock();
  980. $networkOrganization2->method('getNetwork')->willReturn($network2);
  981. $networkOrganization2->method('getEndDate')->willReturn(null);
  982. $organization = $this->getMockBuilder(Organization::class)->getMock();
  983. $organization->method('getNetworkOrganizations')->willReturn(
  984. new ArrayCollection([$networkOrganization1, $networkOrganization2])
  985. );
  986. $this->assertEquals(
  987. 4,
  988. $dolibarrSyncService->getOrganizationNetworkId($organization)
  989. );
  990. }
  991. /**
  992. * @see DolibarrSyncService::getOrganizationNetworkId()
  993. */
  994. public function testGetOrganizationNetworkIdWithNoResult()
  995. {
  996. $dolibarrSyncService = $this->getMockForMethod('getOrganizationNetworkId');
  997. $organization = $this->getMockBuilder(Organization::class)->getMock();
  998. $network = $this->getMockBuilder(Network::class)->getMock();
  999. $network->method('getId')->willReturn(3);
  1000. $networkOrganization = $this->getMockBuilder(NetworkOrganization::class)->getMock();
  1001. $networkOrganization->method('getNetwork')->willReturn($network);
  1002. $networkOrganization->method('getEndDate')->willReturn(new \DateTime('2000-01-01'));
  1003. $organization->method('getNetworkOrganizations')->willReturn(new ArrayCollection([$networkOrganization]));
  1004. $this->assertEquals(
  1005. null,
  1006. $dolibarrSyncService->getOrganizationNetworkId($organization)
  1007. );
  1008. }
  1009. /**
  1010. * @see DolibarrSyncService::countWithMission()
  1011. */
  1012. public function testCountWithMission()
  1013. {
  1014. $dolibarrSyncService = $this->getMockForMethod('countWithMission');
  1015. $members = [
  1016. 123 => [FunctionEnum::PRESIDENT->value, FunctionEnum::TEACHER->value],
  1017. 124 => [FunctionEnum::TEACHER->value],
  1018. 125 => [FunctionEnum::STUDENT->value],
  1019. 126 => [FunctionEnum::TREASURER->value],
  1020. ];
  1021. $this->assertEquals(
  1022. 2,
  1023. $dolibarrSyncService->countWithMission([FunctionEnum::TEACHER->value], $members)
  1024. );
  1025. $this->assertEquals(
  1026. 3,
  1027. $dolibarrSyncService->countWithMission(
  1028. [FunctionEnum::TEACHER->value, FunctionEnum::TREASURER->value],
  1029. $members
  1030. )
  1031. );
  1032. $this->assertEquals(
  1033. 1,
  1034. $dolibarrSyncService->countWithMission([FunctionEnum::STUDENT->value], $members)
  1035. );
  1036. $this->assertEquals(
  1037. 0,
  1038. $dolibarrSyncService->countWithMission([FunctionEnum::ARCHIVIST->value], $members)
  1039. );
  1040. }
  1041. /**
  1042. * @see DolibarrSyncService::getPersonContact()
  1043. */
  1044. public function testGetPersonContact()
  1045. {
  1046. $dolibarrSyncService = $this->getMockForMethod('getPersonContact');
  1047. $person = $this->getMockBuilder(Person::class)->getMock();
  1048. $contactPoint1 = $this->getMockBuilder(ContactPoint::class)->getMock();
  1049. $contactPoint2 = $this->getMockBuilder(ContactPoint::class)->getMock();
  1050. $contactPoint1->method('getContactType')->willReturn(ContactPointTypeEnum::OTHER);
  1051. $contactPoint2->method('getContactType')->willReturn(ContactPointTypeEnum::PRINCIPAL);
  1052. $person->expects($this->once())->method('getContactPoints')->willReturn(new ArrayCollection([$contactPoint1, $contactPoint2]));
  1053. $this->assertEquals(
  1054. $contactPoint2,
  1055. $dolibarrSyncService->getPersonContact($person)
  1056. );
  1057. $person2 = $this->getMockBuilder(Person::class)->getMock();
  1058. $person2->expects($this->once())->method('getContactPoints')->willReturn(new ArrayCollection([]));
  1059. $this->assertEquals(
  1060. null,
  1061. $dolibarrSyncService->getPersonContact($person2)
  1062. );
  1063. }
  1064. /**
  1065. * @see DolibarrSyncService::formatContactPosition()
  1066. */
  1067. public function testFormatContactPosition()
  1068. {
  1069. $dolibarrSyncService = $this->getMockForMethod('formatContactPosition');
  1070. $this->translator->method('trans')->willReturnMap(
  1071. [
  1072. [FunctionEnum::PRESIDENT->value, ['gender' => 'X'], null, null, 'Président(e)'],
  1073. [FunctionEnum::PRESIDENT->value, ['gender' => 'M'], null, null, 'Président'],
  1074. [FunctionEnum::PRESIDENT->value, ['gender' => 'F'], null, null, 'Présidente'],
  1075. [FunctionEnum::DIRECTOR->value, ['gender' => 'X'], null, null, 'Directeur(ice)'],
  1076. [FunctionEnum::DIRECTOR->value, ['gender' => 'M'], null, null, 'Directeur'],
  1077. [FunctionEnum::DIRECTOR->value, ['gender' => 'F'], null, null, 'Directrice'],
  1078. [FunctionEnum::TEACHER->value, ['gender' => 'X'], null, null, 'Professeur(e)'],
  1079. [FunctionEnum::ARCHIVIST->value, ['gender' => 'X'], null, null, 'Archiviste'],
  1080. [FunctionEnum::TREASURER->value, ['gender' => 'X'], null, null, 'Trésorier(ère)'],
  1081. [FunctionEnum::ADMINISTRATIVE_STAFF->value, ['gender' => 'X'], null, null, 'Personnel administratif'],
  1082. ]
  1083. );
  1084. $this->assertEquals(
  1085. 'Président(e)',
  1086. $dolibarrSyncService->formatContactPosition([FunctionEnum::PRESIDENT->value])
  1087. );
  1088. $this->assertEquals(
  1089. 'Président',
  1090. $dolibarrSyncService->formatContactPosition([FunctionEnum::PRESIDENT->value], 'MISTER')
  1091. );
  1092. $this->assertEquals(
  1093. 'Présidente',
  1094. $dolibarrSyncService->formatContactPosition([FunctionEnum::PRESIDENT->value], 'MISS')
  1095. );
  1096. $this->assertEquals(
  1097. 'Présidente, Directrice',
  1098. $dolibarrSyncService->formatContactPosition(
  1099. [FunctionEnum::PRESIDENT->value, FunctionEnum::DIRECTOR->value],
  1100. 'MISS'
  1101. )
  1102. );
  1103. $this->assertEquals(
  1104. 'Président, Directeur',
  1105. $dolibarrSyncService->formatContactPosition(
  1106. [FunctionEnum::PRESIDENT->value, FunctionEnum::DIRECTOR->value, FunctionEnum::ADHERENT->value],
  1107. 'MISTER'
  1108. )
  1109. );
  1110. $this->assertEquals(
  1111. 'Président, Directeur',
  1112. $dolibarrSyncService->formatContactPosition(
  1113. [FunctionEnum::PRESIDENT->value, FunctionEnum::DIRECTOR->value, FunctionEnum::ADHERENT->value],
  1114. 'MISTER'
  1115. )
  1116. );
  1117. $this->assertEquals(
  1118. 'Président(e), Directeur(ice), Professeur(e), Archiviste, Trésorier(ère), Pers...',
  1119. $dolibarrSyncService->formatContactPosition(
  1120. [
  1121. FunctionEnum::PRESIDENT->value,
  1122. FunctionEnum::DIRECTOR->value,
  1123. FunctionEnum::TEACHER->value,
  1124. FunctionEnum::ARCHIVIST->value,
  1125. FunctionEnum::TREASURER->value,
  1126. FunctionEnum::ADMINISTRATIVE_STAFF->value,
  1127. ],
  1128. 'X'
  1129. )
  1130. );
  1131. }
  1132. /**
  1133. * @see DolibarrSyncService::formatPhoneNumber()
  1134. */
  1135. public function testFormatPhoneNumber()
  1136. {
  1137. $dolibarrSyncService = $this->getMockForMethod('formatPhoneNumber');
  1138. $phoneUtil = PhoneNumberUtil::getInstance();
  1139. $phoneNumber = $phoneUtil->parse('01 02 03 04 05', 'FR');
  1140. $this->assertEquals(
  1141. '+33102030405',
  1142. $dolibarrSyncService->formatPhoneNumber($phoneNumber)
  1143. );
  1144. }
  1145. public function testGetExpectedTagsFor()
  1146. {
  1147. $dolibarrSyncService = $this->getMockForMethod('getExpectedTagsFor');
  1148. $organization1 = $this->getMockBuilder(Organization::class)->getMock();
  1149. $organization1->method('getLegalStatus')->willReturn(LegalEnum::ASSOCIATION_LAW_1901);
  1150. $settings1 = $this->getMockBuilder(Settings::class)->getMock();
  1151. $settings1->method('getProduct')->willReturn(SettingsProductEnum::SCHOOL);
  1152. $organization1->method('getSettings')->willReturn($settings1);
  1153. $organization2 = $this->getMockBuilder(Organization::class)->getMock();
  1154. $organization2->method('getLegalStatus')->willReturn(LegalEnum::ASSOCIATION_LAW_1901);
  1155. $settings2 = $this->getMockBuilder(Settings::class)->getMock();
  1156. $settings2->method('getProduct')->willReturn(SettingsProductEnum::SCHOOL_PREMIUM);
  1157. $organization2->method('getSettings')->willReturn($settings2);
  1158. $organization3 = $this->getMockBuilder(Organization::class)->getMock();
  1159. $organization3->method('getLegalStatus')->willReturn(LegalEnum::LOCAL_AUTHORITY);
  1160. $settings3 = $this->getMockBuilder(Settings::class)->getMock();
  1161. $settings3->method('getProduct')->willReturn(SettingsProductEnum::SCHOOL);
  1162. $organization3->method('getSettings')->willReturn($settings3);
  1163. $organization4 = $this->getMockBuilder(Organization::class)->getMock();
  1164. $organization4->method('getLegalStatus')->willReturn(LegalEnum::LOCAL_AUTHORITY);
  1165. $settings4 = $this->getMockBuilder(Settings::class)->getMock();
  1166. $settings4->method('getProduct')->willReturn(SettingsProductEnum::SCHOOL_PREMIUM);
  1167. $organization4->method('getSettings')->willReturn($settings4);
  1168. $organization5 = $this->getMockBuilder(Organization::class)->getMock();
  1169. $organization5->method('getLegalStatus')->willReturn(LegalEnum::LOCAL_AUTHORITY);
  1170. $settings5 = $this->getMockBuilder(Settings::class)->getMock();
  1171. $settings5->method('getProduct')->willReturn(SettingsProductEnum::ARTIST);
  1172. $organization5->method('getSettings')->willReturn($settings5);
  1173. $this->assertEquals(
  1174. $dolibarrSyncService->getExpectedTagsFor($organization1),
  1175. [67]
  1176. );
  1177. $this->assertEquals(
  1178. $dolibarrSyncService->getExpectedTagsFor($organization2),
  1179. [69]
  1180. );
  1181. $this->assertEquals(
  1182. $dolibarrSyncService->getExpectedTagsFor($organization3),
  1183. [68]
  1184. );
  1185. $this->assertEquals(
  1186. $dolibarrSyncService->getExpectedTagsFor($organization4),
  1187. [70]
  1188. );
  1189. $this->assertEquals(
  1190. $dolibarrSyncService->getExpectedTagsFor($organization5),
  1191. []
  1192. );
  1193. }
  1194. /**
  1195. * @see DolibarrSyncService::validateResponse()
  1196. */
  1197. public function testValidateResponse(): void
  1198. {
  1199. $dolibarrSyncService = $this->getMockForMethod('validateResponse');
  1200. $response = $this->getMockBuilder(ResponseInterface::class)->getMock();
  1201. $response->method('toArray')->willReturn(['a' => 1]);
  1202. $operation = $this->getMockBuilder(CreateOperation::class)->disableOriginalConstructor()->getMock();
  1203. $operation->method('getData')->willReturn(['a' => 1]);
  1204. $dolibarrSyncService->expects(self::exactly(2))->method('sanitizeDolibarrData')->with(['a' => 1])->willReturn(['a' => 1]);
  1205. $this->arrayUtils->expects(self::once())->method('getChanges')->with(['a' => 1], ['a' => 1], true)->willReturn([]);
  1206. $dolibarrSyncService->validateResponse($response, $operation);
  1207. }
  1208. /**
  1209. * @see DolibarrSyncService::validateResponse()
  1210. */
  1211. public function testValidateResponseInvalid(): void
  1212. {
  1213. $dolibarrSyncService = $this->getMockForMethod('validateResponse');
  1214. $response = $this->getMockBuilder(ResponseInterface::class)->getMock();
  1215. $response->method('toArray')->willReturn(['a' => 1]);
  1216. $operation = $this->getMockBuilder(CreateOperation::class)->disableOriginalConstructor()->getMock();
  1217. $operation->method('getData')->willReturn(['a' => 0]);
  1218. $dolibarrSyncService->expects(self::exactly(2))
  1219. ->method('sanitizeDolibarrData')
  1220. ->willReturnMap([
  1221. [['a' => 1], ['a' => 1]],
  1222. [['a' => 0], ['a' => 0]],
  1223. ]);
  1224. $this->arrayUtils->expects(self::once())->method('getChanges')->with(['a' => 1], ['a' => 0], true)->willReturn(['a' => 0]);
  1225. $this->expectException(\RuntimeException::class);
  1226. $dolibarrSyncService->validateResponse($response, $operation);
  1227. }
  1228. /**
  1229. * @see DolibarrSyncService::validateResponse()
  1230. */
  1231. public function testValidateResponseRequestError(): void
  1232. {
  1233. $dolibarrSyncService = $this->getMockForMethod('validateResponse');
  1234. $response = $this->getMockBuilder(ResponseInterface::class)->getMock();
  1235. $response->method('getInfo')->willReturnMap([
  1236. ['http_code', '200'], ['url', 'http://url.com'], ['response_headers', []],
  1237. ]);
  1238. $response->method('getContent')->willReturn('');
  1239. $response->method('toArray')->willThrowException(new ServerException($response));
  1240. $operation = $this->getMockBuilder(CreateOperation::class)->disableOriginalConstructor()->getMock();
  1241. $operation->method('getData')->willReturn(['a' => 0]);
  1242. $dolibarrSyncService->expects(self::never())->method('sanitizeDolibarrData');
  1243. $this->arrayUtils->expects(self::never())->method('getChanges');
  1244. $this->expectException(\RuntimeException::class);
  1245. $dolibarrSyncService->validateResponse($response, $operation);
  1246. }
  1247. }