Ver Fonte

add mobyt service and mobyt user status dataprovider

Olivier Massot há 4 anos atrás
pai
commit
03777e1c3f

+ 4 - 0
.env

@@ -47,3 +47,7 @@ OPENTALENT_CONFIG=/config/opentalent
 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",

+ 5 - 1
config/packages/framework.yaml

@@ -25,5 +25,9 @@ framework:
             dolibarr_client:
                 base_uri: '%env(DOLIBARR_API_BASE_URI)%'
                 headers:
-                    Accept: 'application/json'
                     DOLAPIKEY: '%env(DOLIBARR_API_TOKEN)%'
+                    Accept: 'application/json'
+            mobyt_client:
+                base_uri: '%env(MOBYT_API_BASE_URI)%'
+                headers:
+                    Content-Type: 'application/json'

+ 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;
+    }
+}

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

@@ -88,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;
+    }
+}

+ 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);
+        }
+    }
+}