DolibarrSyncServiceTest.php 53 KB

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