DolibarrSyncServiceTest.php 60 KB

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