Skip to content

Commit bd37431

Browse files
author
B24io
committed
task#4950 add operations journal for user role
1 parent abfd9bc commit bd37431

File tree

6 files changed

+235
-2
lines changed

6 files changed

+235
-2
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@
2020
* add method `getByCardUuid` in `\Bitrix24\Contacts\Transport\User` transport, return ContactResponse with two items: CardDTO and ContactDTO
2121
* add method `getCardByUuid` in `\Cards\Transport\Admin` transport, return CardDTO or throw exception `CardNotFound`
2222
* add method `getCardByUuid` in `\Cards\Transport\User` transport, return CardDTO or throw exception `CardNotFound`
23+
* add method `getOperationsByPeriod` in `\OperationsJournal\Transport\Admin` transport, return `OperationsJournalResponse`
24+
* add method `getOperationsByPeriod` in `\OperationsJournal\Transport\User` transport, return `OperationsJournalResponse`
2325
* add MetricDTO and transport
2426
* change mobile phone data structure in Contact DTO in JSON API response
2527
* change mobile phone in ContactDTO can be nullable

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,7 @@ Loyalty PHP SDK works with PHP 7.1 or above, need `ext-json` and `ext-curl` supp
117117

118118
## Authentication with admin and user roles
119119
SDK can work with two roles:
120-
* `admin` - can work with all cards in his bitrix24 account and loyalty application instance
120+
* `admin` - can work with all cards in his Bitrix24 account and loyalty application instance
121121
* `user` - can work only with his card
122122

123123
Bitrix24 Application Loyalty Program and bonus cards work with many Bitrix24 accounts, each account has a `CLIENT_API_KEY`
Lines changed: 138 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,138 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
require_once dirname(__DIR__, 2) . '/vendor/autoload.php';
5+
6+
use \Monolog\Logger;
7+
use \B24io\Loyalty\SDK;
8+
use \B24io\Loyalty\SDK\OperationsJournal\DTO\OperationType;
9+
use Ramsey\Uuid\Uuid;
10+
11+
use GuzzleHttp\HandlerStack;
12+
use GuzzleHttp\Middleware;
13+
use GuzzleHttp\MessageFormatter;
14+
15+
$argv = getopt('', ['clientApiKey::', 'authApiKey::', 'apiEndpoint::', 'dateFrom::', 'dateTo::']);
16+
$fileName = basename(__FILE__);
17+
18+
19+
$clientApiKey = $argv['clientApiKey'];
20+
if ($clientApiKey === null) {
21+
throw new \InvalidArgumentException(sprintf('error: argument «clientApiKey» not found') . PHP_EOL);
22+
}
23+
$authApiKey = $argv['authApiKey'];
24+
if ($authApiKey === null) {
25+
throw new \InvalidArgumentException(sprintf('error: argument «authApiKey» not found') . PHP_EOL);
26+
}
27+
$apiEndpoint = $argv['apiEndpoint'];
28+
if ($apiEndpoint === null) {
29+
throw new \InvalidArgumentException(sprintf('error: argument «apiEndpoint» not found') . PHP_EOL);
30+
}
31+
$dateFrom = new \DateTime($argv['dateFrom']);
32+
$dateTo = new \DateTime($argv['dateTo']);
33+
34+
// check connection to API
35+
$log = new Logger('loyalty-php-sdk');
36+
$log->pushHandler(new \Monolog\Handler\StreamHandler('loyalty-php-sdk-example.log', Logger::DEBUG));
37+
$guzzleHandlerStack = HandlerStack::create();
38+
$guzzleHandlerStack->push(Middleware::log($log, new MessageFormatter(MessageFormatter::SHORT)));
39+
$httpClient = new \GuzzleHttp\Client();
40+
$log->info('loyalty.apiClient.start');
41+
42+
$token = new SDK\Auth\DTO\Token(
43+
SDK\Transport\DTO\Role::initializeByCode('user'),
44+
Uuid::fromString($clientApiKey),
45+
Uuid::fromString($authApiKey)
46+
);
47+
$apiClient = new SDK\ApiClient($apiEndpoint, $token, $httpClient, $log);
48+
$apiClient->setGuzzleHandlerStack($guzzleHandlerStack);
49+
50+
$operationsTransport = SDK\OperationsJournal\Transport\User\Fabric::getOperationsJournalTransport($apiClient, $log);
51+
$decimalMoneyFormatter = new \Money\Formatter\DecimalMoneyFormatter(new \Money\Currencies\ISOCurrencies());
52+
try {
53+
$operationsResponse = $operationsTransport->getOperationsByPeriod($dateFrom, $dateTo);
54+
55+
print (sprintf('operations journal response: ' . PHP_EOL));
56+
print (sprintf('- date from: %s' . PHP_EOL, $operationsResponse->getOperationsJournal()->getDateFrom()->format(\DATE_ATOM)));
57+
print (sprintf('- date to: %s' . PHP_EOL, $operationsResponse->getOperationsJournal()->getDateTo()->format(\DATE_ATOM)));
58+
print (sprintf('- count: %s' . PHP_EOL, $operationsResponse->getOperationsJournal()->getOperations()->count()));
59+
60+
$decimalMoneyFormatter = new \Money\Formatter\DecimalMoneyFormatter(new \Money\Currencies\ISOCurrencies());
61+
foreach ($operationsResponse->getOperationsJournal()->getOperations() as $cnt => $op) {
62+
switch ($op->getOperationType()) {
63+
case OperationType::BITRIX24_DEAL_PERCENTAGE_DISCOUNT_PAYMENT_TRANSACTION():
64+
/**
65+
* @var SDK\OperationsJournal\DTO\Bitrix24\DealPercentageDiscount $op
66+
*/
67+
print(sprintf(
68+
'%s | %s | user - %s |b24Deal - %s |card uuid - %s | percent %s --- %s',
69+
$cnt,
70+
$op->getOperationType()->key(),
71+
$op->getUserId()->getId(),
72+
$op->getDealId(),
73+
$op->getCardUuid()->toString(),
74+
$op->getPercentage()->format(),
75+
$op->getReason()->getComment()
76+
) . PHP_EOL);
77+
break;
78+
case OperationType::BITRIX24_DEAL_MONETARY_DISCOUNT_PAYMENT_TRANSACTION():
79+
/**
80+
* @var SDK\OperationsJournal\DTO\Bitrix24\DealMonetaryDiscount $op
81+
*/
82+
print(sprintf(
83+
'%s | %s | user - %s |b24Deal - %s |card uuid - %s | %s %s --- %s',
84+
$cnt,
85+
$op->getOperationType()->key(),
86+
$op->getUserId()->getId(),
87+
$op->getDealId(),
88+
$op->getCardUuid()->toString(),
89+
$decimalMoneyFormatter->format($op->getValue()),
90+
$op->getValue()->getCurrency()->getCode(),
91+
$op->getReason()->getComment()
92+
) . PHP_EOL);
93+
break;
94+
case OperationType::ACCRUAL_TRANSACTION():
95+
case OperationType::PAYMENT_TRANSACTION():
96+
/**
97+
* @var SDK\Transactions\DTO\TransactionInterface $op
98+
*/
99+
print(sprintf(
100+
'%s | %s | user - %s |card uuid - %s | %s %s --- %s',
101+
$cnt,
102+
$op->getOperationType()->key(),
103+
$op->getUserId()->getId(),
104+
$op->getCardUuid()->toString(),
105+
$decimalMoneyFormatter->format($op->getValue()),
106+
$op->getValue()->getCurrency()->getCode(),
107+
$op->getReason()->getComment()
108+
) . PHP_EOL);
109+
break;
110+
case OperationType::PURCHASE():
111+
/**
112+
* @var SDK\OperationsJournal\DTO\Purchases\Purchase $op
113+
*/
114+
print(sprintf(
115+
'%s | %s | user - %s |card uuid - %s | purchase id - %s | %s',
116+
$cnt,
117+
$op->getOperationType()->key(),
118+
$op->getUserId()->getId(),
119+
$op->getCardUuid()->toString(),
120+
$op->getPurchaseId()->getId(),
121+
$op->getReason()->getComment()
122+
) . PHP_EOL);
123+
break;
124+
default:
125+
print(sprintf(
126+
'%s | %s | user - %s |card uuid - %s | %s',
127+
$cnt,
128+
$op->getOperationType()->key(),
129+
$op->getUserId()->getId(),
130+
$op->getCardUuid()->toString(),
131+
$op->getReason()->getComment()
132+
) . PHP_EOL);
133+
break;
134+
}
135+
}
136+
} catch (\Throwable $exception) {
137+
var_dump($exception->getMessage());
138+
}

src/ApiClient.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,7 @@ public function executeApiRequest($apiMethod, $requestType, array $arHttpRequest
136136
}
137137
if ($this->authToken->getRole()->isUser()) {
138138
$url = sprintf(
139-
'%s?loyalty_client_api_key=%s',
139+
'%s&loyalty_client_api_key=%s',
140140
$this->apiEndpoint . $apiMethod,
141141
$this->authToken->getClientApiKey()->toString()
142142
);
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace B24io\Loyalty\SDK\OperationsJournal\Transport\User;
6+
7+
use B24io\Loyalty\SDK\ApiClient;
8+
use Psr\Log\LoggerInterface;
9+
10+
/**
11+
* Class Fabric
12+
*
13+
* @package B24io\Loyalty\SDK\OperationsJournal\Transport\User
14+
*/
15+
class Fabric
16+
{
17+
/**
18+
* @param ApiClient $apiClient
19+
* @param LoggerInterface $logger
20+
*
21+
* @return Transport
22+
*/
23+
public static function getOperationsJournalTransport(ApiClient $apiClient, LoggerInterface $logger): Transport
24+
{
25+
return new Transport($apiClient, $logger);
26+
}
27+
}
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace B24io\Loyalty\SDK\OperationsJournal\Transport\User;
6+
7+
use B24io\Loyalty\SDK;
8+
use B24io\Loyalty\SDK\Cards;
9+
10+
use Fig\Http\Message\RequestMethodInterface;
11+
12+
/**
13+
* Class Transport
14+
*
15+
* @package B24io\Loyalty\SDK\Turnover\Transport\Admin
16+
*/
17+
class Transport extends SDK\Transport\AbstractTransport
18+
{
19+
/**
20+
* @param \DateTime $dateFrom
21+
* @param \DateTime $dateTo
22+
*
23+
* @return SDK\OperationsJournal\Transport\DTO\OperationsJournalResponse
24+
* @throws SDK\Exceptions\ApiClientException
25+
* @throws SDK\Exceptions\NetworkException
26+
* @throws SDK\Exceptions\TransportFormatException
27+
* @throws SDK\Exceptions\UnknownException
28+
*/
29+
public function getOperationsByPeriod(
30+
\DateTime $dateFrom,
31+
\DateTime $dateTo
32+
): SDK\OperationsJournal\Transport\DTO\OperationsJournalResponse {
33+
$this->log->debug(
34+
'b24io.loyalty.sdk.OperationsJournal.transport.user.getOperationsByPeriod.start',
35+
[
36+
'dateFrom' => $dateFrom->format(\DATE_ATOM),
37+
'dateTo' => $dateTo->format(\DATE_ATOM),
38+
]
39+
);
40+
41+
$requestResult = $this->apiClient->executeApiRequest(
42+
sprintf(
43+
'user/operations-journal/get-by-card-uuid/%s/?dateFrom=%s&dateTo=%s',
44+
$this->apiClient->getAuthToken()->getAuthApiKey()->toString(),
45+
urlencode($dateFrom->format(\DATE_RFC3339)),
46+
urlencode($dateTo->format(\DATE_RFC3339))
47+
),
48+
RequestMethodInterface::METHOD_GET,
49+
[]
50+
);
51+
52+
$operationsJournal = new SDK\OperationsJournal\Transport\DTO\OperationsJournalResponse(
53+
SDK\OperationsJournal\DTO\Fabric::initOperationsJournalFromArray($requestResult['result'], $this->log),
54+
$this->initMetadata($requestResult['meta'])
55+
);
56+
57+
$this->log->debug(
58+
'b24io.loyalty.sdk.turnover.transport.user.getOperationsByPeriod.finish',
59+
[
60+
'metadata' => SDK\Transport\Formatters\Metadata::toArray($operationsJournal->getMeta()),
61+
]
62+
);
63+
64+
return $operationsJournal;
65+
}
66+
}

0 commit comments

Comments
 (0)