DolibarrSyncServiceTest.php 58 KB

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