浏览代码

Merge branch 'feature/dolibarr_routes_update' into develop

Olivier Massot 4 年之前
父节点
当前提交
00b9af6d15

+ 6 - 1
.env

@@ -44,5 +44,10 @@ OPENTALENT_CONFIG=/config/opentalent
 ###< opentalent config folder ###
 
 ###> dolibarr client ###
-DOLIBARR_BASE_URI='https://prod-erp.2iopenservice.com/api/index.php/'
+DOLIBARR_API_BASE_URI='https://prod-erp.2iopenservice.com/api/index.php/'
+DOLIBARR_API_TOKEN='Bocc4zC0J186v8J6QCqu7DnoIw4I7mCJ'
 ###< dolibarr client ###
+
+###> mobyt client ###
+MOBYT_API_BASE_URI='https://app.mobyt.fr/API/v1.0/REST/'
+###< mobyt client ###

+ 0 - 1
composer.json

@@ -14,7 +14,6 @@
         "api-platform/core": "^2.6",
         "blackfire/php-sdk": "^1.23",
         "composer/package-versions-deprecated": "^1.11",
-
         "doctrine/doctrine-bundle": "^2.1",
         "doctrine/doctrine-migrations-bundle": "^3.0",
         "doctrine/orm": "^2.9",

+ 8 - 1
config/packages/framework.yaml

@@ -23,4 +23,11 @@ framework:
             openstreetmap:
                 base_uri: 'https://nominatim.openstreetmap.org/'
             dolibarr_client:
-                base_uri: '%env(DOLIBARR_BASE_URI)%'
+                base_uri: '%env(DOLIBARR_API_BASE_URI)%'
+                headers:
+                    DOLAPIKEY: '%env(DOLIBARR_API_TOKEN)%'
+                    Accept: 'application/json'
+            mobyt_client:
+                base_uri: '%env(MOBYT_API_BASE_URI)%'
+                headers:
+                    Content-Type: 'application/json'

+ 5 - 16
src/ApiResources/Dolibarr/DolibarrAccount.php

@@ -14,6 +14,11 @@ use Symfony\Component\Serializer\Annotation\Groups;
 #[ApiResource(
     itemOperations: [
         'get' => [
+            'security' => '(is_granted("ROLE_ADMIN_CORE") or 
+                            is_granted("ROLE_ADMINISTRATIF_MANAGER_CORE") or 
+                            is_granted("ROLE_PEDAGOGICS_MANAGER_CORE") or 
+                            is_granted("ROLE_FINANCIAL_MANAGER_CORE")
+                           ) and object.getOrganizationId() == user.getOrganization().getId()',
             'method' => 'GET',
             'path' => '/dolibarr/account/{organizationId}',
             'requirements' => ['organizationId' => '\d+'],
@@ -54,12 +59,6 @@ class DolibarrAccount
     #[Groups('dolibarr_get')]
     private ?object $contract = null;
 
-    /**
-     * Sms credit remaining
-     */
-    #[Groups('dolibarr_get')]
-    private string $smsCredit = "";
-
     /**
      * Last bills
      */
@@ -116,16 +115,6 @@ class DolibarrAccount
         $this->contract = $contract;
     }
 
-    public function getSmsCredit(): string
-    {
-        return $this->smsCredit;
-    }
-
-    public function setSmsCredit(string $smsCredit): void
-    {
-        $this->smsCredit = $smsCredit;
-    }
-
     public function getBills(): array
     {
         return $this->bills;

+ 16 - 0
src/ApiResources/Dolibarr/DolibarrBill.php

@@ -31,6 +31,12 @@ class DolibarrBill
     #[Groups('dolibarr_get')]
     private int $id;
 
+    /**
+     * Bill reference
+     */
+    #[Groups('dolibarr_get')]
+    private string $ref;
+
     /**
      * Id of the society
      */
@@ -71,6 +77,16 @@ class DolibarrBill
         $this->id = $id;
     }
 
+    public function getRef(): string
+    {
+        return $this->ref;
+    }
+
+    public function setRef(string $ref): void
+    {
+        $this->ref = $ref;
+    }
+
     public function getSocId(): int
     {
         return $this->socId;

+ 89 - 0
src/ApiResources/Mobyt/MobytUserStatus.php

@@ -0,0 +1,89 @@
+<?php
+declare(strict_types=1);
+
+namespace App\ApiResources\Mobyt;
+
+use ApiPlatform\Core\Annotation\ApiProperty;
+use ApiPlatform\Core\Annotation\ApiResource;
+use Symfony\Component\Serializer\Annotation\Groups;
+
+/**
+ * Statut de l'utilisateur Mobyt correspondant à l'organization donnée en paramètre
+ */
+#[ApiResource(
+    itemOperations: [
+        'get' => [
+            'security' => 'is_granted("ROLE_TEXTO") and object.getOrganizationId() == user.getOrganization().getId()',
+            'method' => 'GET',
+            'path' => '/mobyt/status/{organizationId}',
+            'requirements' => ['organizationId' => '\d+'],
+            'normalization_context' => [
+                'groups' => ['mobyt_get']
+            ],
+        ],
+    ]
+)]
+class MobytUserStatus
+{
+    #[ApiProperty(identifier: true)]
+    #[Groups('mobyt_get')]
+    private int $organizationId;
+
+    /**
+     * Is there a Mobyt account active for this user
+     */
+    #[Groups('mobyt_get')]
+    private bool $active = false;
+
+    /**
+     * Amount of sms remaining
+     */
+    #[Groups('mobyt_get')]
+    private int $amount = 0;
+
+    /**
+     * Money remaining
+     */
+    #[Groups('mobyt_get')]
+    private float $money = 0;
+
+    public function getOrganizationId(): int
+    {
+        return $this->organizationId;
+    }
+
+    public function setOrganizationId(int $organizationId): void
+    {
+        $this->organizationId = $organizationId;
+    }
+
+    public function isActive(): bool
+    {
+        return $this->active;
+    }
+
+    public function setActive(bool $active): void
+    {
+        $this->active = $active;
+    }
+
+    public function getAmount(): int
+    {
+        return $this->amount;
+    }
+
+    public function setAmount(int $amount): void
+    {
+        $this->amount = $amount;
+    }
+
+    public function getMoney(): float
+    {
+        return $this->money;
+    }
+
+    public function setMoney(float $money): void
+    {
+        $this->money = $money;
+    }
+}

+ 1 - 2
src/DataProvider/Dolibarr/DolibarrAccountDataProvider.php

@@ -79,6 +79,7 @@ final class DolibarrAccountDataProvider implements ItemDataProviderInterface, Re
         foreach ($billsData as $billData) {
             $bill = new DolibarrBill();
             $bill->setId((int)$billData['id']);
+            $bill->setRef($billData['ref']);
             $bill->setSocId($dolibarrAccount->getSocId());
             $bill->setTaxExcludedAmount((float)$billData['total_ht']);
             $bill->setTaxIncludedAmount((float)$billData['total_ttc']);
@@ -87,8 +88,6 @@ final class DolibarrAccountDataProvider implements ItemDataProviderInterface, Re
             $dolibarrAccount->addBill($bill);
         }
 
-        // $dolibarrAccount->setSmsCredit();
-
         return $dolibarrAccount;
     }
 }

+ 55 - 0
src/DataProvider/Mobyt/MobytUserStatusDataProvider.php

@@ -0,0 +1,55 @@
+<?php
+declare(strict_types=1);
+
+namespace App\DataProvider\Mobyt;
+
+use ApiPlatform\Core\DataProvider\ItemDataProviderInterface;
+use ApiPlatform\Core\DataProvider\RestrictedDataProviderInterface;
+use App\ApiResources\Mobyt\MobytUserStatus;
+use App\Repository\Organization\OrganizationRepository;
+use App\Service\Mobyt\MobytService;
+
+/**
+ * Custom provider pour les MobytUserStatus récupérés via l'api Mobyt
+ * @package App\DataProvider\Utils
+ */
+final class MobytUserStatusDataProvider implements ItemDataProviderInterface, RestrictedDataProviderInterface
+{
+    public function __construct(
+        private MobytService $mobytService,
+        private OrganizationRepository $organizationRepository,
+    ) {}
+
+    public function supports(string $resourceClass, string $operationName = null, array $context = []): bool
+    {
+        return MobytUserStatus::class === $resourceClass;
+    }
+
+    public function getItem(string $resourceClass, $id, string $operationName = null, array $context = []): ?MobytUserStatus
+    {
+        $userStatus = new MobytUserStatus();
+        $userStatus->setOrganizationId($id);
+
+        $organization = $this->organizationRepository->find($id);
+        $parameters = $organization->getParameters();
+        $mobytLogin = $parameters->getUsernameSMS();
+        $mobytPassword = $parameters->getPasswordSMS();
+        if (!$mobytLogin) {
+            return $userStatus;
+        }
+
+        $userStatusData = $this->mobytService->getUserStatus($id, $mobytLogin, $mobytPassword);
+        $userStatus->setActive(true);
+        $userStatus->setMoney($userStatusData['money']);
+
+        $topQualitySmsAmount = null;
+        foreach ($userStatusData['sms'] as $_ => $smsTypeData) {
+            // we only retrieve the 'top quality sms', which are identified by the letter L in the mobyt api
+            if ($smsTypeData['type'] === 'L') {
+                $topQualitySmsAmount = $smsTypeData['quantity'];
+            }
+        }
+        $userStatus->setAmount($topQualitySmsAmount);
+        return $userStatus;
+    }
+}

+ 5 - 13
src/Service/Dolibarr/DolibarrService.php

@@ -9,6 +9,8 @@ use Symfony\Contracts\HttpClient\HttpClientInterface;
 
 /**
  * Service d'appel à l'API dolibarr
+ *
+ * @see https://prod-erp.2iopenservice.com/api/index.php/explorer/
  */
 class DolibarrService
 {
@@ -70,7 +72,7 @@ class DolibarrService
             $organization->getId()
         );
 
-        return $this->request("api/index.php/thirdparties",'POST', $body);
+        return $this->request("api/index.php/thirdparties",'POST', ['body' => $body]);
     }
 
     /**
@@ -79,23 +81,13 @@ class DolibarrService
      *
      * @param string $path
      * @param string $method
-     * @param string|null $body
+     * @param array $options
      * @return array
      * @throws NotFoundHttpException
      */
-    private function request(string $path, string $method = 'GET', string $body = ''): array
+    private function request(string $path, string $method = 'GET', array $options = []): array
     {
         try {
-            $options = [
-                'headers' => [
-                    'Accept'=> 'application/json',
-                    'DOLAPIKEY' => 'Bocc4zC0J186v8J6QCqu7DnoIw4I7mCJ'
-                ]
-            ];
-
-            if ($body !== null) {
-                $options['body'] = $body;
-            }
             $uri = ltrim($path, '/');
             $response = $this->client->request($method, $uri, $options);
             return json_decode($response->getContent(), true);

+ 67 - 0
src/Service/Mobyt/MobytService.php

@@ -0,0 +1,67 @@
+<?php
+
+namespace App\Service\Mobyt;
+
+use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
+use Symfony\Contracts\HttpClient\Exception\HttpExceptionInterface;
+use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
+use Symfony\Contracts\HttpClient\HttpClientInterface;
+
+/**
+ * Service d'appel à l'API Mobyt
+ */
+class MobytService
+{
+    private HttpClientInterface $client;
+    private string $userId;
+    private string $sessionKey;
+
+    function __construct(
+        HttpClientInterface $mobyt_client
+    )
+    {
+        $this->client = $mobyt_client;
+    }
+
+    private function connect(string $login, string $password){
+        $response = $this->client->request('GET', sprintf('login?username=%s&password=%s', $login, $password));
+        list($this->userId, $this->sessionKey) = explode(';', $response->getContent());
+        return true;
+    }
+
+    /**
+     * Get a dolibarr society by its opentalent organization id
+     *
+     * @param int $organizationId
+     * @return array
+     */
+    public function getUserStatus(int $organizationId, string $login, string $password): array {
+        $this->connect($login, $password);
+        return $this->request(
+            'status?getMoney=true&typeAliases=true',
+            'GET',
+            ['headers' => [ 'user_key' => $this->userId, 'Session_key' => $this->sessionKey ]]
+        );
+    }
+
+    /**
+     * Send an HTTP request to the Dolibarr API,
+     * and return the decoded content of the response's body
+     *
+     * @param string $path
+     * @param string $method
+     * @param array $options
+     * @return array
+     * @throws NotFoundHttpException
+     */
+    private function request(string $path, string $method = 'GET', array $options = []): array
+    {
+        try {
+            $uri = ltrim($path, '/');
+            $response = $this->client->request($method, $uri, $options);
+            return json_decode($response->getContent(), true);
+        } catch (HttpExceptionInterface | TransportExceptionInterface $e) {
+            throw new NotFoundHttpException('data_not_found', $e, 404);
+        }
+    }
+}