DolibarrSyncServiceTest.php 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401
  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. * @see DolibarrSyncService::scan()
  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. * @see DolibarrSyncService::execute()
  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. /**
  538. * @see DolibarrSyncService::run()
  539. */
  540. public function testRun() {
  541. $dolibarrSyncService = $this->getMockBuilder(TestableDolibarrSyncService::class)
  542. ->setConstructorArgs([$this->organizationRepository, $this->accessRepository, $this->functionTypeRepository,
  543. $this->dolibarrApiService, $this->addressPostalUtils, $this->arrayUtils, $this->translator, $this->logger])
  544. ->setMethodsExcept(['run'])
  545. ->getMock();
  546. $operations = ['operation1', 'operation2'];
  547. $dolibarrSyncService->expects(self::once())->method('scan')->willReturn($operations);
  548. $dolibarrSyncService->expects(self::once())->method('execute')->with($operations);
  549. $result = $dolibarrSyncService->run();
  550. $this->assertEquals($operations, $result);
  551. }
  552. /**
  553. * @see DolibarrSyncService::getDolibarrSocietiesIndex()
  554. */
  555. public function testGetDolibarrSocietiesIndex(): void
  556. {
  557. $dolibarrSyncService = $this->getMockBuilder(TestableDolibarrSyncService::class)
  558. ->setConstructorArgs([$this->organizationRepository, $this->accessRepository, $this->functionTypeRepository,
  559. $this->dolibarrApiService, $this->addressPostalUtils, $this->arrayUtils, $this->translator, $this->logger])
  560. ->setMethodsExcept(['getDolibarrSocietiesIndex'])
  561. ->getMock();
  562. $this->dolibarrApiService
  563. ->expects($this->once())
  564. ->method('getAllClients')
  565. ->willReturn(
  566. [
  567. ['id' => 1, 'array_options' => ['options_2iopen_organization_id' => 101]],
  568. ['id' => 2, 'array_options' => ['options_2iopen_organization_id' => 102]],
  569. ['id' => 3, 'array_options' => ['options_2iopen_organization_id' => null]], // No org id but also no contract, so it's ok
  570. ['id' => 4, 'name' => 'foo', 'array_options' => ['options_2iopen_organization_id' => null]], // No org id but has a contract, a warning should be logged
  571. ]
  572. );
  573. $this->dolibarrApiService->expects(self::exactly(2))->method('getActiveContract')->willReturnMap([
  574. [3, null],
  575. [4, ['dummy non-empty data']]
  576. ]);
  577. $this->logger->expects(self::once())->method('warning')->with('Dolibarr client has no organization id: foo (4)');
  578. $index = $dolibarrSyncService->getDolibarrSocietiesIndex();
  579. $this->assertEqualsCanonicalizing(
  580. [
  581. 1 => ['id' => 1, 'array_options' => ['options_2iopen_organization_id' => 101]],
  582. 2 => ['id' => 2, 'array_options' => ['options_2iopen_organization_id' => 102]]
  583. ],
  584. $index
  585. );
  586. }
  587. /**
  588. * @see DolibarrSyncService::getActiveMembersIndex()
  589. */
  590. public function testGetActiveMembersIndex(): void
  591. {
  592. $dolibarrSyncService = $this->getMockBuilder(TestableDolibarrSyncService::class)
  593. ->setConstructorArgs([$this->organizationRepository, $this->accessRepository, $this->functionTypeRepository,
  594. $this->dolibarrApiService, $this->addressPostalUtils, $this->arrayUtils, $this->translator, $this->logger])
  595. ->setMethodsExcept(['getActiveMembersIndex'])
  596. ->getMock();
  597. $this->accessRepository
  598. ->expects($this->once())
  599. ->method('getAllActiveMembersAndMissions')
  600. ->willReturn(
  601. [
  602. ['id' => 1, 'organization_id' => 1, 'mission' => FunctionEnum::PRESIDENT()->getValue()],
  603. ['id' => 2, 'organization_id' => 1, 'mission' => FunctionEnum::STUDENT()->getValue()],
  604. ['id' => 3, 'organization_id' => 2, 'mission' => FunctionEnum::PRESIDENT()->getValue()],
  605. ['id' => 3, 'organization_id' => 2, 'mission' => FunctionEnum::TEACHER()->getValue()]
  606. ]
  607. );
  608. $index = $dolibarrSyncService->getActiveMembersIndex();
  609. $this->assertEqualsCanonicalizing([
  610. 1 => [1 => [FunctionEnum::PRESIDENT()->getValue()], 2 => [FunctionEnum::STUDENT()->getValue()]],
  611. 2 => [3 => [FunctionEnum::PRESIDENT()->getValue(), FunctionEnum::TEACHER()->getValue()]]
  612. ], $index);
  613. }
  614. /**
  615. * @see DolibarrSyncService::findDolibarrContactFor()
  616. */
  617. public function testFindDolibarrContactForById(): void
  618. {
  619. $dolibarrSyncService = $this->getMockBuilder(TestableDolibarrSyncService::class)
  620. ->setConstructorArgs([$this->organizationRepository, $this->accessRepository, $this->functionTypeRepository,
  621. $this->dolibarrApiService, $this->addressPostalUtils, $this->arrayUtils, $this->translator, $this->logger])
  622. ->setMethodsExcept(['findDolibarrContactFor'])
  623. ->getMock();
  624. $contacts = [
  625. ['id' => 1, 'array_options' => ['options_2iopen_person_id' => 101]],
  626. ['id' => 2, 'array_options' => ['options_2iopen_person_id' => 102]],
  627. ];
  628. // Find by id
  629. $person = $this->getMockBuilder(Person::class)->getMock();
  630. $person->method('getId')->willReturn(102);
  631. $contact = $dolibarrSyncService->findDolibarrContactFor($contacts, $person);
  632. $this->assertEquals(2, $contact['id']);
  633. }
  634. /**
  635. * @see DolibarrSyncService::findDolibarrContactFor()
  636. */
  637. public function testFindDolibarrContactForByName(): void
  638. {
  639. $dolibarrSyncService = $this->getMockBuilder(TestableDolibarrSyncService::class)
  640. ->setConstructorArgs([$this->organizationRepository, $this->accessRepository, $this->functionTypeRepository,
  641. $this->dolibarrApiService, $this->addressPostalUtils, $this->arrayUtils, $this->translator, $this->logger])
  642. ->setMethodsExcept(['findDolibarrContactFor'])
  643. ->getMock();
  644. $contacts = [
  645. ['id' => 1, 'firstname' => 'mister', 'lastname' => 'X', 'array_options' => ['options_2iopen_person_id' => null]],
  646. ['id' => 2, 'firstname' => 'miss', 'lastname' => 'Y', 'array_options' => ['options_2iopen_person_id' => null]],
  647. ];
  648. // Find by full name (contact has no person id, it should be returned)
  649. $person = $this->getMockBuilder(Person::class)->getMock();
  650. $person->method('getId')->willReturn(101);
  651. $person->method('getName')->willReturn('X');
  652. $person->method('getGivenName')->willReturn('mister');
  653. $result = $dolibarrSyncService->findDolibarrContactFor($contacts, $person);
  654. $this->assertEquals(1, $result['id']);
  655. }
  656. /**
  657. * @see DolibarrSyncService::findDolibarrContactFor()
  658. */
  659. public function testFindDolibarrContactForByNameWithConflict(): void
  660. {
  661. $dolibarrSyncService = $this->getMockBuilder(TestableDolibarrSyncService::class)
  662. ->setConstructorArgs([$this->organizationRepository, $this->accessRepository, $this->functionTypeRepository,
  663. $this->dolibarrApiService, $this->addressPostalUtils, $this->arrayUtils, $this->translator, $this->logger])
  664. ->setMethodsExcept(['findDolibarrContactFor'])
  665. ->getMock();
  666. $contacts = [
  667. ['id' => 1, 'firstname' => 'mister', 'lastname' => 'X', 'array_options' => ['options_2iopen_person_id' => 1]],
  668. ['id' => 2, 'firstname' => 'miss', 'lastname' => 'Y', 'array_options' => ['options_2iopen_person_id' => 2]],
  669. ];
  670. // Find by full name (contact already has another person id, it should not be returned)
  671. $person = $this->getMockBuilder(Person::class)->getMock();
  672. $person->method('getId')->willReturn(101);
  673. $person->method('getName')->willReturn('X');
  674. $person->method('getGivenName')->willReturn('mister');
  675. $result = $dolibarrSyncService->findDolibarrContactFor($contacts, $person);
  676. $this->assertEquals(null, $result);
  677. }
  678. /**
  679. * @see DolibarrSyncService::findDolibarrContactFor()
  680. */
  681. public function testFindDolibarrContactNotFound(): void
  682. {
  683. $dolibarrSyncService = $this->getMockBuilder(TestableDolibarrSyncService::class)
  684. ->setConstructorArgs([$this->organizationRepository, $this->accessRepository, $this->functionTypeRepository,
  685. $this->dolibarrApiService, $this->addressPostalUtils, $this->arrayUtils, $this->translator, $this->logger])
  686. ->setMethodsExcept(['findDolibarrContactFor'])
  687. ->getMock();
  688. $contacts = [
  689. ['id' => 1, 'firstname' => 'mister', 'lastname' => 'X', 'array_options' => ['options_2iopen_person_id' => 1]],
  690. ['id' => 2, 'firstname' => 'miss', 'lastname' => 'Y', 'array_options' => ['options_2iopen_person_id' => 2]],
  691. ];
  692. // Do not find
  693. $person = $this->getMockBuilder(Person::class)->getMock();
  694. $person->method('getId')->willReturn(-1);
  695. $person->method('getName')->willReturn('Presley');
  696. $person->method('getGivenName')->willReturn('Elvis');
  697. $result = $dolibarrSyncService->findDolibarrContactFor($contacts, $person);
  698. $this->assertEquals(null, $result);
  699. }
  700. /**
  701. * @see DolibarrSyncService::sanitizeDolibarrData()
  702. */
  703. public function testSanitizeDolibarrData(): void
  704. {
  705. $dolibarrSyncService = $this->getMockBuilder(TestableDolibarrSyncService::class)
  706. ->setConstructorArgs([$this->organizationRepository, $this->accessRepository, $this->functionTypeRepository,
  707. $this->dolibarrApiService, $this->addressPostalUtils, $this->arrayUtils, $this->translator, $this->logger])
  708. ->setMethodsExcept(['sanitizeDolibarrData'])
  709. ->getMock();
  710. $result = $dolibarrSyncService->sanitizeDolibarrData(['a' => 'A', 'b' => '', 'c' => ['d' => 'D', 'e' => '']]);
  711. $this->assertEquals(
  712. ['a' => 'A', 'b' => null, 'c' => ['d' => 'D', 'e' => null]],
  713. $result
  714. );
  715. }
  716. /**
  717. * @see DolibarrSyncService::sanitizeDolibarrData()
  718. */
  719. public function testSanitizeDolibarrDataWithNull(): void
  720. {
  721. $dolibarrSyncService = $this->getMockBuilder(TestableDolibarrSyncService::class)
  722. ->setConstructorArgs([$this->organizationRepository, $this->accessRepository, $this->functionTypeRepository,
  723. $this->dolibarrApiService, $this->addressPostalUtils, $this->arrayUtils, $this->translator, $this->logger])
  724. ->setMethodsExcept(['sanitizeDolibarrData'])
  725. ->getMock();
  726. $result = $dolibarrSyncService->sanitizeDolibarrData(null);
  727. $this->assertEquals(null, $result);
  728. }
  729. /**
  730. * @see DolibarrSyncService::getOrganizationPostalAddress()
  731. */
  732. public function testGetOrganizationPostalAddress(): void
  733. {
  734. $dolibarrSyncService = $this->getMockBuilder(TestableDolibarrSyncService::class)
  735. ->setConstructorArgs([$this->organizationRepository, $this->accessRepository, $this->functionTypeRepository,
  736. $this->dolibarrApiService, $this->addressPostalUtils, $this->arrayUtils, $this->translator, $this->logger])
  737. ->setMethodsExcept(['getOrganizationPostalAddress'])
  738. ->getMock();
  739. $organization = $this->getMockBuilder(Organization::class)->getMock();
  740. $organizationAddressPostal1 = $this->getMockBuilder(OrganizationAddressPostal::class)->getMock();
  741. $organizationAddressPostal2 = $this->getMockBuilder(OrganizationAddressPostal::class)->getMock();
  742. $organizationAddressPostal3 = $this->getMockBuilder(OrganizationAddressPostal::class)->getMock();
  743. $addressPostal = $this->getMockBuilder(AddressPostal::class)->getMock();
  744. $organizationAddressPostal1->method('getType')->willReturn(AddressPostalOrganizationTypeEnum::ADDRESS_PRACTICE()->getValue());
  745. $organizationAddressPostal2->method('getType')->willReturn(AddressPostalOrganizationTypeEnum::ADDRESS_BILL()->getValue());
  746. $organizationAddressPostal3->method('getType')->willReturn(AddressPostalOrganizationTypeEnum::ADDRESS_OTHER()->getValue());
  747. $organizationAddressPostal2->method('getAddressPostal')->willReturn($addressPostal);
  748. $organization->expects($this->once())
  749. ->method('getOrganizationAddressPostals')
  750. ->willReturn(
  751. new ArrayCollection([$organizationAddressPostal1, $organizationAddressPostal2, $organizationAddressPostal3])
  752. );
  753. $this->assertEquals(
  754. $addressPostal,
  755. $dolibarrSyncService->getOrganizationPostalAddress($organization)
  756. );
  757. }
  758. /**
  759. * @see DolibarrSyncService::getOrganizationPostalAddress()
  760. */
  761. public function testGetOrganizationPostalAddressNoResult(): void
  762. {
  763. $dolibarrSyncService = $this->getMockBuilder(TestableDolibarrSyncService::class)
  764. ->setConstructorArgs([$this->organizationRepository, $this->accessRepository, $this->functionTypeRepository,
  765. $this->dolibarrApiService, $this->addressPostalUtils, $this->arrayUtils, $this->translator, $this->logger])
  766. ->setMethodsExcept(['getOrganizationPostalAddress'])
  767. ->getMock();
  768. $organization = $this->getMockBuilder(Organization::class)->getMock();
  769. $organization->expects($this->once())
  770. ->method('getOrganizationAddressPostals')
  771. ->willReturn(new ArrayCollection([]));
  772. $this->assertEquals(
  773. null,
  774. $dolibarrSyncService->getOrganizationPostalAddress($organization)
  775. );
  776. }
  777. /**
  778. * @see DolibarrSyncService::getOrganizationPhone()
  779. */
  780. public function testGetOrganizationPhoneWithExistingPhone(): void
  781. {
  782. $dolibarrSyncService = $this->getMockBuilder(TestableDolibarrSyncService::class)
  783. ->setConstructorArgs([$this->organizationRepository, $this->accessRepository, $this->functionTypeRepository,
  784. $this->dolibarrApiService, $this->addressPostalUtils, $this->arrayUtils, $this->translator, $this->logger])
  785. ->setMethodsExcept(['getOrganizationPhone'])
  786. ->getMock();
  787. $contactPoint1 = $this->getMockBuilder(ContactPoint::class)->getMock();
  788. $contactPoint2 = $this->getMockBuilder(ContactPoint::class)->getMock();
  789. $contactPoint3 = $this->getMockBuilder(ContactPoint::class)->getMock();
  790. $contactPoint1->method('getContactType')->willReturn(ContactPointTypeEnum::OTHER()->getValue());
  791. $contactPoint2->method('getContactType')->willReturn(ContactPointTypeEnum::BILL()->getValue());
  792. $contactPoint3->method('getContactType')->willReturn(ContactPointTypeEnum::PRINCIPAL()->getValue());
  793. $phone = $this->getMockBuilder(PhoneNumber::class)->disableOriginalConstructor()->getMock();
  794. $contactPoint2->method('getTelphone')->willReturn($phone);
  795. $organization = $this->getMockBuilder(Organization::class)->getMock();
  796. $organization
  797. ->expects($this->once())
  798. ->method('getContactPoints')
  799. ->willReturn(
  800. new ArrayCollection([$contactPoint1, $contactPoint2, $contactPoint3])
  801. );
  802. $dolibarrSyncService->expects(self::once())->method('formatPhoneNumber')->with($phone)->willReturn('+33161626365');
  803. $this->assertEquals(
  804. '+33161626365',
  805. $dolibarrSyncService->getOrganizationPhone($organization)
  806. );
  807. }
  808. /**
  809. * @see DolibarrSyncService::getOrganizationPhone()
  810. */
  811. public function testGetOrganizationPhoneWithMobilePhone() {
  812. $dolibarrSyncService = $this->getMockBuilder(TestableDolibarrSyncService::class)
  813. ->setConstructorArgs([$this->organizationRepository, $this->accessRepository, $this->functionTypeRepository,
  814. $this->dolibarrApiService, $this->addressPostalUtils, $this->arrayUtils, $this->translator, $this->logger])
  815. ->setMethodsExcept(['getOrganizationPhone'])
  816. ->getMock();
  817. $contactPoint1 = $this->getMockBuilder(ContactPoint::class)->getMock();
  818. $contactPoint2 = $this->getMockBuilder(ContactPoint::class)->getMock();
  819. $contactPoint3 = $this->getMockBuilder(ContactPoint::class)->getMock();
  820. $contactPoint1->method('getContactType')->willReturn(ContactPointTypeEnum::OTHER()->getValue());
  821. $contactPoint2->method('getContactType')->willReturn(ContactPointTypeEnum::BILL()->getValue());
  822. $contactPoint3->method('getContactType')->willReturn(ContactPointTypeEnum::PRINCIPAL()->getValue());
  823. $contactPoint2->expects($this->once())->method('getTelphone')->willReturn(null);
  824. $mobilePhone = $this->getMockBuilder(PhoneNumber::class)->disableOriginalConstructor()->getMock();
  825. $contactPoint2->method('getMobilPhone')->willReturn($mobilePhone);
  826. $organization = $this->getMockBuilder(Organization::class)->getMock();
  827. $organization
  828. ->expects($this->once())
  829. ->method('getContactPoints')
  830. ->willReturn(
  831. new ArrayCollection([$contactPoint1, $contactPoint2, $contactPoint3])
  832. );
  833. $dolibarrSyncService->expects(self::once())->method('formatPhoneNumber')->with($mobilePhone)->willReturn('+33661626365');
  834. $this->assertEquals(
  835. '+33661626365',
  836. $dolibarrSyncService->getOrganizationPhone($organization)
  837. );
  838. }
  839. /**
  840. * @see DolibarrSyncService::getOrganizationPhone()
  841. */
  842. public function testGetOrganizationPhoneWithNoPhone() {
  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(['getOrganizationPhone'])
  847. ->getMock();
  848. $organization = $this->getMockBuilder(Organization::class)->getMock();
  849. $organization
  850. ->expects($this->once())
  851. ->method('getContactPoints')
  852. ->willReturn(new ArrayCollection([]));
  853. $dolibarrSyncService->expects(self::never())->method('formatPhoneNumber');
  854. $this->assertEquals(
  855. null,
  856. $dolibarrSyncService->getOrganizationPhone($organization)
  857. );
  858. }
  859. /**
  860. * @see DolibarrSyncService::getOrganizationEmail()
  861. */
  862. public function testGetOrganizationEmailWithExistingEmail() {
  863. $dolibarrSyncService = $this->getMockBuilder(TestableDolibarrSyncService::class)
  864. ->setConstructorArgs([$this->organizationRepository, $this->accessRepository, $this->functionTypeRepository,
  865. $this->dolibarrApiService, $this->addressPostalUtils, $this->arrayUtils, $this->translator, $this->logger])
  866. ->setMethodsExcept(['getOrganizationEmail'])
  867. ->getMock();
  868. $contactPoint1 = $this->getMockBuilder(ContactPoint::class)->getMock();
  869. $contactPoint2 = $this->getMockBuilder(ContactPoint::class)->getMock();
  870. $contactPoint3 = $this->getMockBuilder(ContactPoint::class)->getMock();
  871. $contactPoint1->method('getContactType')->willReturn(ContactPointTypeEnum::OTHER()->getValue());
  872. $contactPoint2->method('getContactType')->willReturn(ContactPointTypeEnum::BILL()->getValue());
  873. $contactPoint3->method('getContactType')->willReturn(ContactPointTypeEnum::PRINCIPAL()->getValue());
  874. $contactPoint2->method('getEmail')->willReturn('email@email.com');
  875. $organization = $this->getMockBuilder(Organization::class)->getMock();
  876. $organization
  877. ->expects($this->once())
  878. ->method('getContactPoints')
  879. ->willReturn(
  880. new ArrayCollection([$contactPoint1, $contactPoint2, $contactPoint3])
  881. );
  882. $this->assertEquals(
  883. 'email@email.com',
  884. $dolibarrSyncService->getOrganizationEmail($organization)
  885. );
  886. }
  887. /**
  888. * @see DolibarrSyncService::getOrganizationEmail()
  889. */
  890. public function testGetOrganizationEmailWithNoEmail() {
  891. $dolibarrSyncService = $this->getMockBuilder(TestableDolibarrSyncService::class)
  892. ->setConstructorArgs([$this->organizationRepository, $this->accessRepository, $this->functionTypeRepository,
  893. $this->dolibarrApiService, $this->addressPostalUtils, $this->arrayUtils, $this->translator, $this->logger])
  894. ->setMethodsExcept(['getOrganizationEmail'])
  895. ->getMock();
  896. $organization = $this->getMockBuilder(Organization::class)->getMock();
  897. $organization
  898. ->expects($this->once())
  899. ->method('getContactPoints')
  900. ->willReturn(new ArrayCollection([]));
  901. $this->assertEquals(
  902. null,
  903. $dolibarrSyncService->getOrganizationEmail($organization)
  904. );
  905. }
  906. /**
  907. * @see DolibarrSyncService::getOrganizationNetworkId()
  908. */
  909. public function testGetOrganizationNetworkId() {
  910. $dolibarrSyncService = $this->getMockBuilder(TestableDolibarrSyncService::class)
  911. ->setConstructorArgs([$this->organizationRepository, $this->accessRepository, $this->functionTypeRepository,
  912. $this->dolibarrApiService, $this->addressPostalUtils, $this->arrayUtils, $this->translator, $this->logger])
  913. ->setMethodsExcept(['getOrganizationNetworkId'])
  914. ->getMock();
  915. $organization = $this->getMockBuilder(Organization::class)->getMock();
  916. $network = $this->getMockBuilder(Network::class)->getMock();
  917. $network->method('getId')->willReturn(3);
  918. $networkOrganization = $this->getMockBuilder(NetworkOrganization::class)->getMock();
  919. $networkOrganization->method('getNetwork')->willReturn($network);
  920. $organization->method('getNetworkOrganizations')->willReturn(new ArrayCollection([$networkOrganization]));
  921. $this->assertEquals(
  922. 3,
  923. $dolibarrSyncService->getOrganizationNetworkId($organization)
  924. );
  925. }
  926. /**
  927. * @see DolibarrSyncService::getOrganizationNetworkId()
  928. */
  929. public function testGetOrganizationNetworkIdWithMultipleResult() {
  930. $dolibarrSyncService = $this->getMockBuilder(TestableDolibarrSyncService::class)
  931. ->setConstructorArgs([$this->organizationRepository, $this->accessRepository, $this->functionTypeRepository,
  932. $this->dolibarrApiService, $this->addressPostalUtils, $this->arrayUtils, $this->translator, $this->logger])
  933. ->setMethodsExcept(['getOrganizationNetworkId'])
  934. ->getMock();
  935. $network1 = $this->getMockBuilder(Network::class)->getMock();
  936. $network1->method('getId')->willReturn(3);
  937. $networkOrganization1 = $this->getMockBuilder(NetworkOrganization::class)->getMock();
  938. $networkOrganization1->method('getNetwork')->willReturn($network1);
  939. $networkOrganization1->method('getEndDate')->willReturn(new \DateTime('2000-01-01'));
  940. $network2 = $this->getMockBuilder(Network::class)->getMock();
  941. $network2->method('getId')->willReturn(4);
  942. $networkOrganization2 = $this->getMockBuilder(NetworkOrganization::class)->getMock();
  943. $networkOrganization2->method('getNetwork')->willReturn($network2);
  944. $networkOrganization2->method('getEndDate')->willReturn(null);
  945. $organization = $this->getMockBuilder(Organization::class)->getMock();
  946. $organization->method('getNetworkOrganizations')->willReturn(
  947. new ArrayCollection([$networkOrganization1, $networkOrganization2])
  948. );
  949. $this->assertEquals(
  950. 4,
  951. $dolibarrSyncService->getOrganizationNetworkId($organization)
  952. );
  953. }
  954. /**
  955. * @see DolibarrSyncService::getOrganizationNetworkId()
  956. */
  957. public function testGetOrganizationNetworkIdWithNoResult() {
  958. $dolibarrSyncService = $this->getMockBuilder(TestableDolibarrSyncService::class)
  959. ->setConstructorArgs([$this->organizationRepository, $this->accessRepository, $this->functionTypeRepository,
  960. $this->dolibarrApiService, $this->addressPostalUtils, $this->arrayUtils, $this->translator, $this->logger])
  961. ->setMethodsExcept(['getOrganizationNetworkId'])
  962. ->getMock();
  963. $organization = $this->getMockBuilder(Organization::class)->getMock();
  964. $network = $this->getMockBuilder(Network::class)->getMock();
  965. $network->method('getId')->willReturn(3);
  966. $networkOrganization = $this->getMockBuilder(NetworkOrganization::class)->getMock();
  967. $networkOrganization->method('getNetwork')->willReturn($network);
  968. $networkOrganization->method('getEndDate')->willReturn(new \DateTime('2000-01-01'));
  969. $organization->method('getNetworkOrganizations')->willReturn(new ArrayCollection([$networkOrganization]));
  970. $this->assertEquals(
  971. null,
  972. $dolibarrSyncService->getOrganizationNetworkId($organization)
  973. );
  974. }
  975. /**
  976. * @see DolibarrSyncService::countWithMission()
  977. */
  978. public function testCountWithMission() {
  979. $dolibarrSyncService = $this->getMockBuilder(TestableDolibarrSyncService::class)
  980. ->setConstructorArgs([$this->organizationRepository, $this->accessRepository, $this->functionTypeRepository,
  981. $this->dolibarrApiService, $this->addressPostalUtils, $this->arrayUtils, $this->translator, $this->logger])
  982. ->setMethodsExcept(['countWithMission'])
  983. ->getMock();
  984. $members = [
  985. 123 => [FunctionEnum::PRESIDENT()->getValue(), FunctionEnum::TEACHER()->getValue()],
  986. 124 => [FunctionEnum::TEACHER()->getValue()],
  987. 125 => [FunctionEnum::STUDENT()->getValue()],
  988. 126 => [FunctionEnum::TREASURER()->getValue()],
  989. ];
  990. $this->assertEquals(
  991. 2,
  992. $dolibarrSyncService->countWithMission([FunctionEnum::TEACHER()->getValue()], $members)
  993. );
  994. $this->assertEquals(
  995. 3,
  996. $dolibarrSyncService->countWithMission(
  997. [FunctionEnum::TEACHER()->getValue(), FunctionEnum::TREASURER()->getValue()],
  998. $members
  999. )
  1000. );
  1001. $this->assertEquals(
  1002. 1,
  1003. $dolibarrSyncService->countWithMission([FunctionEnum::STUDENT()->getValue()], $members)
  1004. );
  1005. $this->assertEquals(
  1006. 0,
  1007. $dolibarrSyncService->countWithMission([FunctionEnum::ARCHIVIST()->getValue()], $members)
  1008. );
  1009. }
  1010. /**
  1011. * @see DolibarrSyncService::getPersonContact()
  1012. */
  1013. public function testGetPersonContact() {
  1014. $dolibarrSyncService = $this->getMockBuilder(TestableDolibarrSyncService::class)
  1015. ->setConstructorArgs([$this->organizationRepository, $this->accessRepository, $this->functionTypeRepository,
  1016. $this->dolibarrApiService, $this->addressPostalUtils, $this->arrayUtils, $this->translator, $this->logger])
  1017. ->setMethodsExcept(['getPersonContact'])
  1018. ->getMock();
  1019. $person = $this->getMockBuilder(Person::class)->getMock();
  1020. $contactPoint1 = $this->getMockBuilder(ContactPoint::class)->getMock();
  1021. $contactPoint2 = $this->getMockBuilder(ContactPoint::class)->getMock();
  1022. $contactPoint1->method('getContactType')->willReturn(ContactPointTypeEnum::OTHER()->getValue());
  1023. $contactPoint2->method('getContactType')->willReturn(ContactPointTypeEnum::PRINCIPAL()->getValue());
  1024. $person->expects($this->once())->method('getContactPoints')->willReturn(new ArrayCollection([$contactPoint1, $contactPoint2]));
  1025. $this->assertEquals(
  1026. $contactPoint2,
  1027. $dolibarrSyncService->getPersonContact($person)
  1028. );
  1029. $person2 = $this->getMockBuilder(Person::class)->getMock();
  1030. $person2->expects($this->once())->method('getContactPoints')->willReturn(new ArrayCollection([]));
  1031. $this->assertEquals(
  1032. null,
  1033. $dolibarrSyncService->getPersonContact($person2)
  1034. );
  1035. }
  1036. /**
  1037. * @see DolibarrSyncService::formatContactPosition()
  1038. */
  1039. public function testFormatContactPosition() {
  1040. $dolibarrSyncService = $this->getMockBuilder(TestableDolibarrSyncService::class)
  1041. ->setConstructorArgs([$this->organizationRepository, $this->accessRepository, $this->functionTypeRepository,
  1042. $this->dolibarrApiService, $this->addressPostalUtils, $this->arrayUtils, $this->translator, $this->logger])
  1043. ->setMethodsExcept(['formatContactPosition'])
  1044. ->getMock();
  1045. $this->translator->method('trans')->willReturnMap(
  1046. [
  1047. [FunctionEnum::PRESIDENT()->getValue(), ['gender' => 'X'], null, null, 'Président(e)'],
  1048. [FunctionEnum::PRESIDENT()->getValue(), ['gender' => 'M'], null, null, 'Président'],
  1049. [FunctionEnum::PRESIDENT()->getValue(), ['gender' => 'F'], null, null, 'Présidente'],
  1050. [FunctionEnum::DIRECTOR()->getValue(), ['gender' => 'X'], null, null, 'Directeur(ice)'],
  1051. [FunctionEnum::DIRECTOR()->getValue(), ['gender' => 'M'], null, null, 'Directeur'],
  1052. [FunctionEnum::DIRECTOR()->getValue(), ['gender' => 'F'], null, null, 'Directrice'],
  1053. [FunctionEnum::TEACHER()->getValue(), ['gender' => 'X'], null, null, 'Professeur(e)'],
  1054. [FunctionEnum::ARCHIVIST()->getValue(), ['gender' => 'X'], null, null, 'Archiviste'],
  1055. [FunctionEnum::TREASURER()->getValue(), ['gender' => 'X'], null, null, 'Trésorier(ère)'],
  1056. [FunctionEnum::ADMINISTRATIVE_STAFF()->getValue(), ['gender' => 'X'], null, null, 'Personnel administratif'],
  1057. ]
  1058. );
  1059. $this->assertEquals(
  1060. 'Président(e)',
  1061. $dolibarrSyncService->formatContactPosition([FunctionEnum::PRESIDENT()->getValue()])
  1062. );
  1063. $this->assertEquals(
  1064. 'Président',
  1065. $dolibarrSyncService->formatContactPosition([FunctionEnum::PRESIDENT()->getValue()], 'MISTER')
  1066. );
  1067. $this->assertEquals(
  1068. 'Présidente',
  1069. $dolibarrSyncService->formatContactPosition([FunctionEnum::PRESIDENT()->getValue()], 'MISS')
  1070. );
  1071. $this->assertEquals(
  1072. 'Présidente, Directrice',
  1073. $dolibarrSyncService->formatContactPosition(
  1074. [FunctionEnum::PRESIDENT()->getValue(), FunctionEnum::DIRECTOR()->getValue()],
  1075. 'MISS'
  1076. )
  1077. );
  1078. $this->assertEquals(
  1079. 'Président, Directeur',
  1080. $dolibarrSyncService->formatContactPosition(
  1081. [FunctionEnum::PRESIDENT()->getValue(), FunctionEnum::DIRECTOR()->getValue(), FunctionEnum::ADHERENT()->getValue()],
  1082. 'MISTER'
  1083. )
  1084. );
  1085. $this->assertEquals(
  1086. 'Président, Directeur',
  1087. $dolibarrSyncService->formatContactPosition(
  1088. [FunctionEnum::PRESIDENT()->getValue(), FunctionEnum::DIRECTOR()->getValue(), FunctionEnum::ADHERENT()->getValue()],
  1089. 'MISTER'
  1090. )
  1091. );
  1092. $this->assertEquals(
  1093. 'Président(e), Directeur(ice), Professeur(e), Archiviste, Trésorier(ère), Pers...',
  1094. $dolibarrSyncService->formatContactPosition(
  1095. [
  1096. FunctionEnum::PRESIDENT()->getValue(),
  1097. FunctionEnum::DIRECTOR()->getValue(),
  1098. FunctionEnum::TEACHER()->getValue(),
  1099. FunctionEnum::ARCHIVIST()->getValue(),
  1100. FunctionEnum::TREASURER()->getValue(),
  1101. FunctionEnum::ADMINISTRATIVE_STAFF()->getValue(),
  1102. ],
  1103. 'X'
  1104. )
  1105. );
  1106. }
  1107. /**
  1108. * @see DolibarrSyncService::formatPhoneNumber()
  1109. */
  1110. public function testFormatPhoneNumber() {
  1111. $dolibarrSyncService = $this->getMockBuilder(TestableDolibarrSyncService::class)
  1112. ->setConstructorArgs([$this->organizationRepository, $this->accessRepository, $this->functionTypeRepository,
  1113. $this->dolibarrApiService, $this->addressPostalUtils, $this->arrayUtils, $this->translator, $this->logger])
  1114. ->setMethodsExcept(['formatPhoneNumber'])
  1115. ->getMock();
  1116. $phoneUtil = PhoneNumberUtil::getInstance();
  1117. $phoneNumber = $phoneUtil->parse('01 02 03 04 05', "FR");
  1118. $this->assertEquals(
  1119. '+33102030405',
  1120. $dolibarrSyncService->formatPhoneNumber($phoneNumber)
  1121. );
  1122. }
  1123. /**
  1124. * @see DolibarrSyncService::validateResponse()
  1125. */
  1126. public function testValidateResponse(): void {
  1127. $dolibarrSyncService = $this->getMockBuilder(TestableDolibarrSyncService::class)
  1128. ->setConstructorArgs([$this->organizationRepository, $this->accessRepository, $this->functionTypeRepository,
  1129. $this->dolibarrApiService, $this->addressPostalUtils, $this->arrayUtils, $this->translator, $this->logger])
  1130. ->setMethodsExcept(['validateResponse'])
  1131. ->getMock();
  1132. $response = $this->getMockBuilder(ResponseInterface::class)->getMock();
  1133. $response->method('toArray')->willReturn(['a' => 1]);
  1134. $operation = $this->getMockBuilder(CreateOperation::class)->disableOriginalConstructor()->getMock();
  1135. $operation->method('getData')->willReturn(['a' => 1]);
  1136. $dolibarrSyncService->expects(self::exactly(2))->method('sanitizeDolibarrData')->with(['a' => 1])->willReturn(['a' => 1]);
  1137. $this->arrayUtils->expects(self::once())->method('getChanges')->with(['a' => 1], ['a' => 1], true)->willReturn([]);
  1138. $dolibarrSyncService->validateResponse($response, $operation);
  1139. }
  1140. /**
  1141. * @see DolibarrSyncService::validateResponse()
  1142. */
  1143. public function testValidateResponseInvalid(): void {
  1144. $dolibarrSyncService = $this->getMockBuilder(TestableDolibarrSyncService::class)
  1145. ->setConstructorArgs([$this->organizationRepository, $this->accessRepository, $this->functionTypeRepository,
  1146. $this->dolibarrApiService, $this->addressPostalUtils, $this->arrayUtils, $this->translator, $this->logger])
  1147. ->setMethodsExcept(['validateResponse'])
  1148. ->getMock();
  1149. $response = $this->getMockBuilder(ResponseInterface::class)->getMock();
  1150. $response->method('toArray')->willReturn(['a' => 1]);
  1151. $operation = $this->getMockBuilder(CreateOperation::class)->disableOriginalConstructor()->getMock();
  1152. $operation->method('getData')->willReturn(['a' => 0]);
  1153. $dolibarrSyncService->expects(self::exactly(2))
  1154. ->method('sanitizeDolibarrData')
  1155. ->willReturnMap([
  1156. [['a' => 1], ['a' => 1]],
  1157. [['a' => 0], ['a' => 0]]
  1158. ]);
  1159. $this->arrayUtils->expects(self::once())->method('getChanges')->with(['a' => 1], ['a' => 0], true)->willReturn(['a' => 0]);
  1160. $this->expectException(RuntimeException::class);
  1161. $dolibarrSyncService->validateResponse($response, $operation);
  1162. }
  1163. /**
  1164. * @see DolibarrSyncService::validateResponse()
  1165. */
  1166. public function testValidateResponseRequestError(): void {
  1167. $dolibarrSyncService = $this->getMockBuilder(TestableDolibarrSyncService::class)
  1168. ->setConstructorArgs([$this->organizationRepository, $this->accessRepository, $this->functionTypeRepository,
  1169. $this->dolibarrApiService, $this->addressPostalUtils, $this->arrayUtils, $this->translator, $this->logger])
  1170. ->setMethodsExcept(['validateResponse'])
  1171. ->getMock();
  1172. $response = $this->getMockBuilder(ResponseInterface::class)->getMock();
  1173. $response->method('getInfo')->willReturnMap([
  1174. ['http_code', '200'], ['url', 'http://url.com'], ['response_headers', []]
  1175. ]);
  1176. $response->method('getContent')->willReturn("");
  1177. $response->method('toArray')->willThrowException(new ServerException($response));
  1178. $operation = $this->getMockBuilder(CreateOperation::class)->disableOriginalConstructor()->getMock();
  1179. $operation->method('getData')->willReturn(['a' => 0]);
  1180. $dolibarrSyncService->expects(self::never())->method('sanitizeDolibarrData');
  1181. $this->arrayUtils->expects(self::never())->method('getChanges');
  1182. $this->expectException(RuntimeException::class);
  1183. $dolibarrSyncService->validateResponse($response, $operation);
  1184. }
  1185. }