DolibarrSyncServiceTest.php 54 KB

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