DolibarrSyncServiceTest.php 54 KB

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