src/Manager/EchoParkRestManager.php line 579

Open in your IDE?
  1. <?php
  2. namespace App\Manager;
  3. use App\Entity\Authorization;
  4. use App\Entity\AuthorizationGroup;
  5. use App\Entity\Contact;
  6. use App\Entity\Group;
  7. use App\Entity\GroupRealEstate;
  8. use App\Entity\Instance;
  9. use App\Entity\RealEstate;
  10. use App\Entity\Taxonomy\Category;
  11. use App\Entity\Taxonomy\CategoryRealEstate;
  12. use App\Entity\Taxonomy\CategoryType;
  13. use App\Entity\User;
  14. use App\Entity\UserGroup;
  15. use App\Service\File\FileService;
  16. use Doctrine\ORM\EntityManagerInterface;
  17. use phpDocumentor\Reflection\Types\Boolean;
  18. use Psr\Log\LoggerInterface;
  19. use Symfony\Component\Cache\Adapter\FilesystemAdapter;
  20. use Symfony\Component\HttpFoundation\File\UploadedFile;
  21. use Symfony\Component\Mime\Part\DataPart;
  22. use Symfony\Component\Mime\Part\Multipart\FormDataPart;
  23. use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
  24. use Symfony\Contracts\HttpClient\Exception\DecodingExceptionInterface;
  25. use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
  26. use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
  27. use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
  28. use Symfony\Contracts\HttpClient\HttpClientInterface;
  29. class EchoParkRestManager
  30. {
  31.     public function __construct(
  32.         private HttpClientInterface $client,
  33.         private EntityManagerInterface $entityManager,
  34.         private FileService $fileService,
  35.         private LoggerInterface $logger
  36.     ) {
  37.     }
  38.     public function getToken(Instance $instance): ?string
  39.     {
  40.         $cache = new FilesystemAdapter();
  41.         $instanceCache $cache->getItem('instance_token_'.$instance->getId());
  42.         if (!$instanceCache->isHit()) {
  43.             $response $this->client->request(
  44.                 method'POST',
  45.                 url$instance->getUrl().'api/login_check',
  46.                 optionsarray_merge(
  47.                     ['verify_peer' => false'verify_host' => false],
  48.                     json_decode($instance->getOptions(), true)
  49.                 )
  50.             );
  51.             $response $response->toArray();
  52.             $return $response['token'];
  53.             $instanceCache->expiresAfter(\DateInterval::createFromDateString('20 minutes'));
  54.             $cache->save($instanceCache->set($return));
  55.         } else {
  56.             $return $instanceCache->get();
  57.         }
  58.         return $return;
  59.     }
  60.     public function getUserDetails(User $user): array
  61.     {
  62.         $cache = new FilesystemAdapter();
  63.         $instanceCache $cache->getItem('instance_user_'.$user->getId());
  64.         if (!$user->getEchoparkName()) {
  65.             return [];
  66.         }
  67.         if (!$instanceCache->isHit()) {
  68.             $token $this->getToken($user->getInstance());
  69.             $instance $user->getInstance();
  70.             $username $user->getEchoparkName();
  71.             $response $this->client->request(
  72.                 method'POST',
  73.                 url$instance->getUrl()."api/rest/v1.2/$username/switchUser",
  74.                 options$this->getOptions($token, [])
  75.             );
  76.             $response $response->toArray();
  77.             $token $response['token'];
  78.             $response $this->client->request(
  79.                 method'GET',
  80.                 url$instance->getUrl().'api/rest/v1.2/users/me',
  81.                 options$this->getOptions($token, [])
  82.             );
  83.             $return = [
  84.                 'token' => $token,
  85.                 'user' => $response->toArray(),
  86.             ];
  87.             $instanceCache->expiresAfter(\DateInterval::createFromDateString('20 minutes'));
  88.             $cache->save($instanceCache->set($return));
  89.         } else {
  90.             $return $instanceCache->get();
  91.         }
  92.         return $return;
  93.     }
  94.     public function getUserDetailsForPartUser(User $user): array
  95.     {
  96.         return $this->getUserDetails($user);
  97.     }
  98.     public function getRequestList(User $userbool $withoutCache): array
  99.     {
  100.         $userData $this->getUserDetails($user);
  101.         $communityId $this->getCommunityId($user$userData);
  102.         if (!$user->getEchoparkName() || !$communityId) {
  103.             return [];
  104.         }
  105.         $cache = new FilesystemAdapter();
  106.         $instanceCache $cache->getItem('instance_request_list_'.$communityId.'_'.$user->getId());
  107.         if (!$instanceCache->isHit() || $withoutCache) {
  108.             $response $this->client->request(
  109.                 method'GET',
  110.                 url$user->getInstance()->getUrl() . "api/rest/v1.2/$communityId/requests",
  111.                 options$this->getOptions($userData['token'], [])
  112.             );
  113.             $return $response->toArray();
  114.             $instanceCache->expiresAfter(\DateInterval::createFromDateString('1 hour'));
  115.             $cache->save($instanceCache->set($return));
  116.         } else {
  117.             $return $instanceCache->get();
  118.         }
  119.         return $return;
  120.     }
  121.     public function getRequestDetail(User $userint $id): array
  122.     {
  123.         $userData $this->getUserDetails($user);
  124.         $communityId $this->getCommunityId($user$userData);
  125.         if (!$user->getEchoparkName() || !$communityId) {
  126.             return [];
  127.         }
  128.         $response $this->client->request(
  129.             method'POST',
  130.             url$user->getInstance()->getUrl()."api/rest/v1.2/$communityId/requests/$id",
  131.             options$this->getOptions($userData['token'], [
  132.                 'body' => [
  133.                     'withSteps'=>1,
  134.                     'withRecipients'=>1,
  135.                     'withForms'=>1,
  136.                     'withPictures'=>1,
  137.                     'withMessages'=>1,
  138.                 ]
  139.             ])
  140.         );
  141.         return $response->toArray();
  142.     }
  143.     public function getRequestConsigne(User $userint $id): array
  144.     {
  145.         $userData $this->getUserDetails($user);
  146.         $communityId $this->getCommunityId($user$userData);
  147.         if (!$user->getEchoparkName() || !$communityId) {
  148.             return [];
  149.         }
  150.         $response $this->client->request(
  151.             method'GET',
  152.             url$user->getInstance()->getUrl()."api/rest/v1.2/request_consigne/notification/$id",
  153.             options$this->getOptions($userData['token'], [])
  154.         );
  155.         return $response->toArray();
  156.     }
  157.     public function getRequestConsigneDetail(User $user, array $data): array
  158.     {
  159.         $userData $this->getUserDetails($user);
  160.         $communityId $this->getCommunityId($user$userData);
  161.         if (!$user->getEchoparkName() || !$communityId) {
  162.             return [];
  163.         }
  164.         $requestTypeId $data['requestTypeId'];
  165.         $domaineTreeId $data['domaineTreeId'];
  166.         $realEstateId $data['realEstateId'];
  167.         $response $this->client->request(
  168.             method'GET',
  169.             url$user->getInstance()->getUrl()."api/rest/v1.2/request_consigne/notification/$communityId/$requestTypeId/$domaineTreeId/$realEstateId",
  170.             options$this->getOptions($userData['token'], [])
  171.         );
  172.         return $response->toArray();
  173.     }
  174.     public function getRequestPicture(User $userint $id): array
  175.     {
  176.         $userData $this->getUserDetails($user);
  177.         $communityId $this->getCommunityId($user$userData);
  178.         if (!$user->getEchoparkName() || !$communityId) {
  179.             return [];
  180.         }
  181.         $response $this->client->request(
  182.             method'GET',
  183.             url$user->getInstance()->getUrl()."api/rest/v1.2/$communityId/getPicture/$id",
  184.             options$this->getOptions($userData['token'], [])
  185.         );
  186.         return $response->toArray();
  187.     }
  188.     public function getTenantList(User $user): array
  189.     {
  190.         $userData $this->getUserDetails($user);
  191.         $communityId $this->getCommunityId($user$userData);
  192.         if (!$user->getEchoparkName() || !$communityId) {
  193.             return [];
  194.         }
  195.         $response $this->client->request(
  196.             method'GET',
  197.             url$user->getInstance()->getUrl()."api/rest/v1.2/$communityId/tenants",
  198.             options$this->getOptions($userData['token'], [])
  199.         );
  200.         return $response->toArray();
  201.     }
  202.     public function getRequestsForms(User $user): array
  203.     {
  204.         $userData $this->getUserDetails($user);
  205.         $communityId $this->getCommunityId($user$userData);
  206.         if (!$user->getEchoparkName() || !$communityId) {
  207.             return [];
  208.         }
  209.         $response $this->client->request(
  210.             method'GET',
  211.             url$user->getInstance()->getUrl()."api/rest/v1.2/$communityId/getRequestsForms",
  212.             options$this->getOptions($userData['token'], [])
  213.         );
  214.         return $response->toArray();
  215.     }
  216.     public function setRequest(User $user, array $data): array
  217.     {
  218.         $userData $this->getUserDetails($user);
  219.         $communityId $this->getCommunityId($user$userData);
  220.         if (!$user->getEchoparkName() || !$communityId) {
  221.             return [];
  222.         }
  223.         $response $this->client->request(
  224.             method'POST',
  225.             url$user->getInstance()->getUrl() . "api/rest/v1.2/$communityId/setRequest",
  226.             options$this->getOptions($userData['token'], ['body' => $data])
  227.         );
  228.         return $response->toArray();
  229.     }
  230.     public function setDebrief(User $user, array $data): array
  231.     {
  232.         $userData $this->getUserDetails($user);
  233.         $communityId $this->getCommunityId($user$userData);
  234.         if (!$user->getEchoparkName() || !$communityId) {
  235.             return [];
  236.         }
  237.         $response $this->client->request(
  238.             method'POST',
  239.             url$user->getInstance()->getUrl()."api/rest/v1.2/$communityId/debriefing",
  240.             options$this->getOptions($userData['token'], ['body' => $data])
  241.         );
  242.         return $response->toArray();
  243.     }
  244.     public function setRead(User $user, array $data): array
  245.     {
  246.         $userData $this->getUserDetails($user);
  247.         $communityId $this->getCommunityId($user$userData);
  248.         if (!$user->getEchoparkName() || !$communityId) {
  249.             return [];
  250.         }
  251.         $response $this->client->request(
  252.             method'GET',
  253.             url$user->getInstance()->getUrl()."api/rest/v1.2/$communityId/requests/set/read",
  254.             options$this->getOptions($userData['token'], ['body' => $data])
  255.         );
  256.         return $response->toArray();
  257.     }
  258.     public function setStep(User $user, array $data): array
  259.     {
  260.         $userData $this->getUserDetails($user);
  261.         $communityId $this->getCommunityId($user$userData);
  262.         $requestId $data['requestId'];
  263.         if (!$user->getEchoparkName() || !$communityId) {
  264.             return [];
  265.         }
  266.         $response $this->client->request(
  267.             method'POST',
  268.             url$user->getInstance()->getUrl()."api/rest/v1.2/$communityId/setStep/$requestId",
  269.             options$this->getOptions($userData['token'], ['body' => $data])
  270.         );
  271.         return $response->toArray();
  272.     }
  273.     public function setRequestMessage(User $user, array $data): array
  274.     {
  275.         $userData $this->getUserDetails($user);
  276.         $communityId $this->getCommunityId($user$userData);
  277.         $requestId $data['requestId'];
  278.         if (!$user->getEchoparkName() || !$communityId) {
  279.             return [];
  280.         }
  281.         $response $this->client->request(
  282.             method'POST',
  283.             url$user->getInstance()->getUrl()."api/rest/v1.2/$communityId/requests/$requestId/set/message",
  284.             options$this->getOptions($userData['token'], ['body' => $data])
  285.         );
  286.         return $response->toArray(false);
  287.     }
  288.     public function setRequestForm(User $user, array $data): array
  289.     {
  290.         $userData $this->getUserDetails($user);
  291.         $communityId $this->getCommunityId($user$userData);
  292.         $requestId $data['requestId'];
  293.         if (!$user->getEchoparkName() || !$communityId) {
  294.             return [];
  295.         }
  296.         $response $this->client->request(
  297.             method'POST',
  298.             url$user->getInstance()->getUrl()."api/rest/v1.2/$communityId/requests/$requestId/set/form",
  299.             options$this->getOptions($userData['token'], ['body' => $data])
  300.         );
  301.         return $response->toArray();
  302.     }
  303.     public function setDomain(User $user, array $data): array
  304.     {
  305.         $userData $this->getUserDetails($user);
  306.         $communityId $this->getCommunityId($user$userData);
  307.         $requestId $data['requestId'];
  308.         if (!$user->getEchoparkName() || !$communityId) {
  309.             return [];
  310.         }
  311.         $response $this->client->request(
  312.             method'GET',
  313.             url$user->getInstance()->getUrl()."api/rest/v1.2/$requestId/setDomain",
  314.             options$this->getOptions($userData['token'], ['body' => $data])
  315.         );
  316.         return $response->toArray();
  317.     }
  318.     /**
  319.      * @throws TransportExceptionInterface
  320.      * @throws ServerExceptionInterface
  321.      * @throws RedirectionExceptionInterface
  322.      * @throws DecodingExceptionInterface
  323.      * @throws ClientExceptionInterface
  324.      */
  325.     public function setPicture(User $userint $requestIdUploadedFile $file): array
  326.     {
  327.         $userData $this->getUserDetails($user);
  328.         $communityId $this->getCommunityId($user$userData);
  329.         if (!$user->getEchoparkName() || !$communityId) {
  330.             return [];
  331.         }
  332.         $file $this->fileService->upload($file'echopark_uploads_directory' true);
  333.         $this->logger->info($file);
  334.         $data = [
  335.             'file' => DataPart::fromPath($file),
  336.         ];
  337.         $formData = new FormDataPart($data);
  338.         $headers $formData->getPreparedHeaders()->toArray();
  339.         $response $this->client->request(
  340.             method'POST',
  341.             url$user->getInstance()->getUrl()."api/rest/v1.2/$communityId/setPicture/$requestId",
  342.             options: [
  343.                 'verify_peer' => false,
  344.                 'verify_host' => false,
  345.                 'auth_bearer' => $userData['token'],
  346.                 'headers' => $headers,
  347.                 'body'=>$formData->bodyToString()
  348.             ]
  349.         );
  350.         return $response->toArray();
  351.     }
  352.     /**
  353.      * @throws TransportExceptionInterface
  354.      * @throws ServerExceptionInterface
  355.      * @throws RedirectionExceptionInterface
  356.      * @throws DecodingExceptionInterface
  357.      * @throws ClientExceptionInterface
  358.      */
  359.     public function getFormFile(User $userint $fieldDataId): array
  360.     {
  361.         $userData $this->getUserDetails($user);
  362.         $communityId $this->getCommunityId($user$userData);
  363.         if (!$user->getEchoparkName() || !$communityId) {
  364.             return [];
  365.         }
  366.         $response $this->client->request(
  367.             method'GET',
  368.             url$user->getInstance()->getUrl()."api/rest/v1.2/$communityId/getFormFile/$fieldDataId",
  369.             options$this->getOptions($userData['token'], [])
  370.         );
  371.         return $response->toArray();
  372.     }
  373.     /**
  374.      * @throws TransportExceptionInterface
  375.      * @throws ServerExceptionInterface
  376.      * @throws RedirectionExceptionInterface
  377.      * @throws DecodingExceptionInterface
  378.      * @throws ClientExceptionInterface
  379.      */
  380.     public function getDocx(User $userint $requestIdint $field): array
  381.     {
  382.         $userData $this->getUserDetails($user);
  383.         $communityId $this->getCommunityId($user$userData);
  384.         if (!$user->getEchoparkName() || !$communityId) {
  385.             return [];
  386.         }
  387.         $response $this->client->request(
  388.             method'GET',
  389.             url$user->getInstance()->getUrl()."api/rest/v1.2/$communityId/getDocx/$requestId/$field",
  390.             options$this->getOptions($userData['token'], [])
  391.         );
  392.         return $response->toArray();
  393.     }
  394.     /**
  395.      * @throws TransportExceptionInterface
  396.      * @throws ServerExceptionInterface
  397.      * @throws RedirectionExceptionInterface
  398.      * @throws DecodingExceptionInterface
  399.      * @throws ClientExceptionInterface
  400.      */
  401.     public function getMessageFile(User $userint $messageFileId): array
  402.     {
  403.         $userData $this->getUserDetails($user);
  404.         $communityId $this->getCommunityId($user$userData);
  405.         if (!$user->getEchoparkName() || !$communityId) {
  406.             return [];
  407.         }
  408.         $response $this->client->request(
  409.             method'GET',
  410.             url$user->getInstance()->getUrl()."api/rest/v1.2/$communityId/getMessageFile/$messageFileId",
  411.             options$this->getOptions($userData['token'], [])
  412.         );
  413.         return $response->toArray();
  414.     }
  415.     public function getRequestsMap(User $user): array
  416.     {
  417.         $cache = new FilesystemAdapter();
  418.         $userData $this->getUserDetails($user);
  419.         $communityId $this->getCommunityId($user$userData);
  420.         $instanceCache $cache->getItem('instance_requestmap_user_'.$user->getId() . '_' $communityId);
  421.         if (!$instanceCache->isHit()) {
  422.             if (!$user->getEchoparkName() || !$communityId) {
  423.                 return [];
  424.             }
  425.             $response $this->client->request(
  426.                 method'GET',
  427.                 url$user->getInstance()->getUrl()."api/rest/v1.2/requestsmap/$communityId",
  428.                 options$this->getOptions($userData['token'], [])
  429.             );
  430.             $return $response->toArray();
  431.             $instanceCache->expiresAfter(\DateInterval::createFromDateString('6 days'));
  432.             $cache->save($instanceCache->set($return));
  433.         } else {
  434.             $return $instanceCache->get();
  435.         }
  436.         return $return;
  437.     }
  438.     private function getCommunityId(User $user, array $userData): ?int
  439.     {
  440.         $communityId $user->getEchoparkMainCommunityId();
  441.         if (!$user->getEchoparkMainCommunityId()) {
  442.             $communityId $userData['user']['communitiesIds'][0]['id'];
  443.             $user->setEchoparkMainCommunityId($communityId);
  444.             $this->entityManager->flush();
  445.         }
  446.         return $communityId;
  447.     }
  448.     private function getOptions(string $token, array $data): array
  449.     {
  450.         return array_merge(
  451.             $data,
  452.             [
  453.                 'verify_peer' => false,
  454.                 'verify_host' => false,
  455.                 'auth_bearer' => $token,
  456.             ],
  457.         );
  458.     }
  459.     public function getRealEstates(string $instanceNameint $communityId): bool
  460.     {
  461.         $instance $this->entityManager->getRepository(Instance::class)->findOneBy(['name' => $instanceName]);
  462.         if(!is_object($instance) && is_null($instance->getCompany())) {
  463.             return false;
  464.         }
  465.         $companyId $instance->getCompany()->getId();
  466.         $token $this->getToken($instance);
  467.         $response $this->client->request(
  468.             method'GET',
  469.             url$instance->getUrl()."api/rest/v1.2/$communityId/getRealEstateArbo",
  470.             options$this->getOptions($token, [])
  471.         );
  472.         $categoryType $this->entityManager->getRepository(CategoryType::class)->findOneBy(['main' => true'company' => $companyId'enabled' => 1'deleted' => 0]);
  473.         $categoriesByExternalId $this->entityManager->getRepository(Category::class)->getAllCategoriesForCompany($companyId$communityId);
  474.         $realEstatesByExternalId $this->entityManager->getRepository(RealEstate::class)->getAllRealEstatesForCompany($instance->getCompany(), $communityId);
  475.         $realEstateCategories $this->entityManager->getRepository(CategoryRealEstate::class)->getAllForCompany($companyId$communityId);
  476.         foreach ($categoriesByExternalId as $category) {
  477.             $category->setEnabled(0);
  478.             $category->setDeleted(1);
  479.             $this->entityManager->persist($category);
  480.         }
  481.         foreach ($realEstatesByExternalId as $realEstate) {
  482.             $realEstate->setEnabled(0);
  483.             $realEstate->setDeleted(1);
  484.             $this->entityManager->persist($realEstate);
  485.             $mainContact $realEstate->getMainContact();
  486.             if(is_object($mainContact)) {
  487.                 $mainContact->setEnabled(0);
  488.                 $mainContact->setDeleted(1);
  489.                 $this->entityManager->persist($mainContact);
  490.             }
  491.         }
  492.         foreach ($realEstateCategories as $rel) {
  493.             $rel->setEnabled(0);
  494.             $rel->setDeleted(1);
  495.             $this->entityManager->persist($rel);
  496.         }
  497.         $this->updateRealEstateArbo($response->toArray(), $parent null$categoryType$categoriesByExternalId$realEstatesByExternalId$realEstateCategories$communityId);
  498.         $this->entityManager->flush();
  499.         $this->entityManager->clear();
  500.         return true;
  501.     }
  502.     private function updateRealEstateArbo($realEstates$parent null$categoryType, array &$categoriesByExternalId, array &$realEstatesByExternalId, array &$realEstateCategories$communityId):void
  503.     {
  504.         $i 0;
  505.         foreach ($realEstates as $item) {
  506.             if ($i == 0) {
  507.                 var_dump($item['attr']['name']);
  508.                 $i++;
  509.             }
  510.             $id $item['attr']['id'];
  511.             if(!empty($item['children'])) {
  512.                 /* Catégorie *//* rajoute la company dans la recherche ! et réactiver. Idem pour toutes les maj de cette fonction */
  513.                 if(!isset($categoriesByExternalId[$id])) {
  514.                     $category = new Category();
  515.                     $category->setExternalId($id);
  516.                     $category->setExternalRef($communityId);
  517.                     $categoriesByExternalId[$id] = $category;
  518.                 } else {
  519.                     $category $categoriesByExternalId[$id];
  520.                 }
  521.                 $category->setCategoryType($categoryType);
  522.                 $category->setCompany($categoryType->getCompany());
  523.                 $category->setName($item['attr']['name']);
  524.                 $category->setParent($parent);
  525.                 $category->setEnabled(1);
  526.                 $category->setDeleted(0);
  527.                 $this->entityManager->persist($category);
  528.                 $this->updateRealEstateArbo($item['children'], $category$categoryType$categoriesByExternalId$realEstatesByExternalId$realEstateCategories$communityId);
  529.             } else {
  530.                 /* Patrimoine */
  531.                 if (!isset($realEstatesByExternalId[$id])) {
  532.                     $realEstate = new RealEstate();
  533.                     $realEstate->setExternalId($item['attr']['id']);
  534.                     $realEstate->setExternalRef($communityId);
  535.                     $mainContact = new Contact();
  536.                     $realEstatesByExternalId[$id] = $realEstate;
  537.                 } else {
  538.                     $realEstate $realEstatesByExternalId[$id];
  539.                     $mainContact $realEstate->getMainContact();
  540.                     if(!is_object($mainContact)) {
  541.                         $mainContact = new Contact();
  542.                     }
  543.                 }
  544.                 $mainContact->setTitle('Adresse ' $item['attr']['name']);
  545.                 $mainContact->setAddress($item['attr']['address'] ?? '');
  546.                 $mainContact->setAdditionalAddress(null);
  547.                 $mainContact->setPostalCode($item['attr']['cp'] ?? '');
  548.                 $mainContact->setCity($item['attr']['city'] ?? '');
  549.                 $mainContact->setCountry('France');
  550.                 $mainContact->setState('France');
  551.                 $mainContact->setEnabled(1);
  552.                 $mainContact->setDeleted(0);
  553.                 $this->entityManager->persist($mainContact);
  554.                 $realEstate->setMainContact($mainContact);
  555.                 $realEstate->setCompany($categoryType->getCompany());
  556.                 $realEstate->setCode($item['attr']['name']);
  557.                 $realEstate->setName($item['attr']['name']);
  558.                 $realEstate->setEnabled(1);
  559.                 $realEstate->setDeleted(0);
  560.                 $this->entityManager->persist($realEstate);
  561.                 $key $realEstate->getId() . '-' $parent->getId();
  562.                 if (!isset($realEstateCategories[$key])) {
  563.                     $realEstateCategory = new CategoryRealEstate();
  564.                     $realEstateCategory->setCategory($parent);
  565.                     $realEstateCategory->setRealEstate($realEstate);
  566.                 } else {
  567.                     $realEstateCategory $realEstateCategories[$key];
  568.                 }
  569.                 $realEstateCategory->setEnabled(1);
  570.                 $realEstateCategory->setDeleted(0);
  571.                 $this->entityManager->persist($realEstateCategory);
  572.             }
  573.         }
  574.     }
  575.     public function getVisitUsers(string $instanceName): bool
  576.     {
  577.         $instance $this->entityManager->getRepository(Instance::class)->findOneBy(['name' => $instanceName]);
  578.         if(!is_object($instance) && is_null($instance->getCompany())) {
  579.             return false;
  580.         }
  581.         $companyId $instance->getCompany()->getId();
  582.         $token $this->getToken($instance);
  583.         $response $this->client->request(
  584.             method'GET',
  585.             url$instance->getUrl()."api/rest/v1.2/echoqualite-users",
  586.             options$this->getOptions($token, [])
  587.         );
  588.         $referents $this->client->request(
  589.             method'GET',
  590.             url$instance->getUrl()."api/rest/v1.2/echoqualite-referents",
  591.             options$this->getOptions($token, [])
  592.         );
  593.         $realEstatesByExternalId $this->entityManager->getRepository(RealEstate::class)->getAllRealEstatesForCompany($instance->getCompany());
  594.         $usersByExternalId $this->entityManager->getRepository(User::class)->getAllByExternalId($companyId);
  595.         $rolesByCode $this->entityManager->getRepository(Authorization::class)->getAuthorizationsByCode();
  596.         $groupsByUsers $this->entityManager->getRepository(Group::class)->getAllVisitGroupsByUser($companyId);
  597.         $this->updateUserAccess($response->toArray(), $realEstatesByExternalId$usersByExternalId$rolesByCode$groupsByUsers$referents->toArray(), $instance);
  598.         $this->entityManager->flush();
  599.         $this->entityManager->clear();
  600.         return true;
  601.     }
  602.     private function updateUserAccess($access$realEstatesByExternalId$usersByExternalId$rolesByCode$groupsByUsers$referents$instance):void
  603.     {
  604.         var_dump('updateUserAccess');
  605.         $usersUpdates = [];
  606.         $usersEideticUpdates = [];
  607.         $token $this->getToken($instance);
  608.         $company $instance->getCompany();
  609.         $reorganizedTable = [];
  610.         foreach ($access as $item) {
  611.             $externalUserId $item['utilisateur_id'];
  612.             if(!isset($reorganizedTable[$externalUserId])) {
  613.                 $reorganizedTable[$externalUserId] = [];
  614.             }
  615.             if(!isset($reorganizedTable[$externalUserId][$item['patrimoine_enfant_id']])) {
  616.                 $reorganizedTable[$externalUserId][$item['patrimoine_enfant_id']] = [];
  617.             }
  618.             array_push($reorganizedTable[$externalUserId][$item['patrimoine_enfant_id']], $item);
  619.             /* On récupère les info du user sur EP seulement si c'est la 1ère fois qu'on a ce user dans la boucle */
  620.             if(!in_array($externalUserId$usersUpdates)) {
  621.                 $theUserData $this->client->request(
  622.                     method'POST',
  623.                     url$instance->getUrl() . "api/rest/v1.2/get-user",
  624.                     options$this->getOptions($token, ['body' => ['id' => $externalUserId]]),
  625.                 );
  626.                 $theUser $theUserData->toArray()[0];
  627.                 if(!empty($theUser['email'])) {
  628.                     if (!isset($usersByExternalId[$externalUserId])) {
  629.                         $user = new User();
  630.                         $user->setExternalId($externalUserId);
  631.                         $user->setPassword('tmp');
  632.                     } else {
  633.                         $user $usersByExternalId[$externalUserId];
  634.                     }
  635.                     $user->setEmail($theUser['email']);
  636.                     $user->setFirstName($theUser['firstname']);
  637.                     $user->setLastName($theUser['lastname']);
  638.                     $user->setEchoparkName($theUser['username']);
  639.                     if (!empty($theUser['gsm'])) {
  640.                         $user->setGsm($theUser['gsm']);
  641.                     }
  642.                     if (!empty($theUser['phone'])) {
  643.                         $user->setPhone($theUser['phone']);
  644.                     }
  645.                     $user->setCompany($instance->getCompany());
  646.                     $this->entityManager->persist($user);
  647.                     $this->entityManager->flush();
  648.                     $usersByExternalId[$externalUserId] = $user;
  649.                 }
  650.                 array_push($usersEideticUpdates$user->getId());
  651.                 array_push($usersUpdates$externalUserId);
  652.             }
  653.         }
  654.         /* Dans EP le user peut avoir plusieurs rôles echoqualité sur un patrimoine, on ne garde que celui qui est le plus élévé. */
  655.         /* Pour chaque user */
  656.         foreach ($reorganizedTable as $userTable) {
  657.             $username null;
  658.             $pat null;
  659.             /* Pour chaque patrimoine */
  660.             foreach ($userTable as $realEstateTable) {
  661.                 $bestRole null;
  662.                 $userExternalId null;
  663.                 $realEstateExternalId null;
  664.                 /* Pour chaque rôle (patrimoine attribué à l'utilisateur), on boucle sur la liste de ses droits pour trouver le plus haut level */
  665.                 foreach ($realEstateTable as $roleTable) {
  666.                     $userExternalId $roleTable['utilisateur_id'];
  667.                     $realEstateExternalId $roleTable['patrimoine_enfant_id'];
  668.                     if(!isset($realEstatesByExternalId[$realEstateExternalId])) {
  669.                         continue;
  670.                     }
  671.                     if(isset($usersByExternalId[$userExternalId])) {
  672.                         $user $usersByExternalId[$userExternalId];
  673.                         //$pat = $roleTable['patrimoine_enfant_nom'];
  674.                         if ($roleTable['role'] == 'MANAGER') {
  675.                             $bestRole = ['ROLE_VISIT_MANAGER'];
  676.                         } else if ($roleTable['role'] == 'GESTIONNAIRE REFERENT' && $bestRole != 'MANAGER') {
  677.                             $bestRole = ['ROLE_VISIT_MANAGER''ROLE_PLANIFICATION_VISIT'];
  678.                         } else if ($bestRole == null) {
  679.                             $bestRole = ['ROLE_VISIT_TECHNICIAN'];
  680.                         }
  681.                     }
  682.                 }
  683.                 /* Pour chaque plus haut level d'authorazation qu'on a trouvé pour le user sur le patrimoine */
  684.                 if($bestRole != null) {
  685.                     foreach ($bestRole as $role) {
  686.                         $authorization $rolesByCode[$role];
  687.                         $group null;
  688.                         /* On récupère le group s'il existe déjà */
  689.                         if(isset($groupsByUsers[$user->getId()]) && isset($groupsByUsers[$user->getId()][$authorization->getCode()])) {
  690.                             $group $groupsByUsers[$user->getId()][$authorization->getCode()];
  691.                         }
  692.                         /* On créé le groupe s'il n'existe pas */
  693.                         if (!is_object($group)) {
  694.                             $group = new Group();
  695.                             $group->setName($user->getEmail() . ' - ' $role);
  696.                             $group->setCompany($company);
  697.                             $this->entityManager->persist($group);
  698.                             /* On ajour le user au groupe */
  699.                             $userGroup = new UserGroup();
  700.                             $userGroup->setUser($user);
  701.                             $userGroup->setGroup($group);
  702.                             $this->entityManager->persist($userGroup);
  703.                             /* On lui donne l'authorisation sur laquelle on boucle */
  704.                             $groupAuthorization = new AuthorizationGroup();
  705.                             $groupAuthorization->setAuthorization($authorization);
  706.                             $groupAuthorization->setGroup($group);
  707.                             $this->entityManager->persist($groupAuthorization);
  708.                             /* On ajoute le group au tab */
  709.                             $groupsByUsers[$user->getId()][$authorization->getCode()] = $group;
  710.                         }
  711.                         /* On récupère la relation groupe - realestate pour chaque patrimoine */
  712.                         $groupRealEstates $group->getRealEstates();
  713.                         //var_dump(count($groupRealEstates));
  714.                         $findRealEstateGroup null;
  715.                         /* Pour chaque patrimoine attribué au groupe */
  716.                         foreach ($groupRealEstates as $groupRealEstate) {
  717.                             /* On désactive */
  718.                             $groupRealEstate->setEnabled(0);
  719.                             $groupRealEstate->setDeleted(1);
  720.                             /* Si la relation existe toujours, on réactive */
  721.                             if($groupRealEstate->getRealEstate()->getExternalId() == $realEstateExternalId) {
  722.                                 $groupRealEstate->setEnabled(0);
  723.                                 $groupRealEstate->setDeleted(1);
  724.                                 /* La relation existe déjà */
  725.                                 $findRealEstateGroup $groupRealEstate;
  726.                             }
  727.                             $this->entityManager->persist($groupRealEstate);
  728.                         }
  729.                         /* Si la relation n'existe pas on la créé */
  730.                         if($findRealEstateGroup == null) {
  731.                             $groupRealEstate = new GroupRealEstate();
  732.                             $groupRealEstate->setGroup($group);
  733.                             $groupRealEstate->setRealEstate($realEstatesByExternalId[$realEstateExternalId]);
  734.                             $this->entityManager->persist($groupRealEstate);
  735.                         }
  736.                     }
  737.                 }
  738.                 /* Set realestate referent if empty */
  739.                 if(isset($realEstatesByExternalId[$realEstateExternalId]) && isset($referents[$realEstateExternalId])) {
  740.                     $realEstate $realEstatesByExternalId[$realEstateExternalId];
  741.                     if(is_null($realEstate->getReferent()) && isset($usersByExternalId[$referents[$realEstateExternalId]])) {
  742.                         $realEstate->setReferent($usersByExternalId[$referents[$realEstateExternalId]]);
  743.                         $this->entityManager->persist($realEstate);
  744.                     }
  745.                 }
  746.             }
  747.         }
  748.     }
  749.     private int $batchSize 500;
  750.     private int $i 0;
  751.     private function persistAndMaybeFlush(object $entity): void
  752.     {
  753.         $this->entityManager->persist($entity);
  754.         if ((++$this->$this->batchSize) === 0) {
  755.             $this->entityManager->flush();
  756.         }
  757.     }
  758. }