Skip to content

Commit

Permalink
Merge pull request #66 from rarus/dev
Browse files Browse the repository at this point in the history
Сделать пример по запросу для роли организация метода getSalesHistory
  • Loading branch information
mesilov authored Sep 7, 2018
2 parents 6119812 + cd343d3 commit 63fde32
Show file tree
Hide file tree
Showing 12 changed files with 345 additions and 162 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
# bonus-server-php-sdk change log

## 0.5.4 (7.09.2018)
- для сущности `Transactions` для роли `Organization` для метода `getTransactionsByCard` изменён тип возвращаемого результата на `PaginationResponse` [issue#64](https://github.com/rarus/bonus-server-php-sdk/issues/64)
- исправления ошибок в тестах
- переписан пример `complex.s2.php` с учётом требуемых сценариев

## 0.5.3 (31.08.2018)
- добавлены уровни для карт [issue#61](https://github.com/rarus/bonus-server-php-sdk/issues/61)
- для сущности `Cards` для роли `Organization` добавлен метод `getCardLevelList` [issue#61](https://github.com/rarus/bonus-server-php-sdk/issues/61)
Expand Down
153 changes: 95 additions & 58 deletions examples/complex.s2.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,12 @@

use \Rarus\BonusServer\Cards;
use \Rarus\BonusServer\Users;
use \Rarus\BonusServer\Shops;
use \Rarus\BonusServer\Shops\DTO\ShopCollection;
use \Rarus\BonusServer\Transactions;
use \Rarus\BonusServer\Transactions\DTO\Points\Transactions\TransactionCollection;
use \Rarus\BonusServer\Transactions\DTO\SalesHistory\HistoryItemCollection;
use \Rarus\BonusServer\Transactions\DTO\Document\DocumentId;

print('вывод истории операций в ЛК клиента' . PHP_EOL);

Expand All @@ -16,70 +21,102 @@
*/

$orgCardsTransport = Cards\Transport\Role\Organization\Fabric::getInstance($apiClient, new \Money\Currency('RUB'), $log);
$orgUsersTransport = Users\Transport\Role\Organization\Fabric::getInstance($apiClient, new \Money\Currency('RUB'), $log);
$orgShopsTransport = Shops\Transport\Role\Organization\Fabric::getInstance($apiClient, new \Money\Currency('RUB'), $log);
$orgTransactionsTransport = Transactions\Transport\Role\Organization\Fabric::getInstance($apiClient, new \Money\Currency('RUB'), $log);

// готовим тестовые данные
$newUser = \Rarus\BonusServer\Users\DTO\Fabric::createNewInstance(
'grishi-' . random_int(0, PHP_INT_MAX),
'Михаил Гришин',
'+7978 888 22 22',
'grishi@rarus.ru',
null,
new \DateTime('06.06.1985')
);
$user = $orgUsersTransport->addNewUser($newUser);

$cardLevels = $orgCardsTransport->getCardLevelList();
$newCard = Cards\DTO\Fabric::createNewInstance('12345987654321', (string)random_int(1000000, 100000000), new \Money\Currency('RUB'));
$newCard->setCardLevelId($cardLevels->getFirstLevel()->getLevelId());
$card = $orgCardsTransport->addNewCard($newCard, new \Money\Money(5000000000, new \Money\Currency('RUB')));
$updatedCard = $orgCardsTransport->attachToUser($card, $user);

$activatedCard = $orgCardsTransport->activate($card);

// получаем тестовые данные
// получили пользователя
$user = $orgUsersTransport->getByUserId($user->getUserId());
var_dump($user->getName());
var_dump($user->getEmail());

// получили список карт по пользователю
$cards = $orgCardsTransport->getByUser($user);
print(sprintf('количество карт: %s' . PHP_EOL, $cards->count()));

foreach ($cards as $card) {
print('---------------' . PHP_EOL);
print(sprintf('получаем транзакции баллов по карте с id %s' . PHP_EOL, $card->getCardId()->getId()));
// получение транзакций бонусных баллов по карте
$transactionCollection = $orgTransactionsTransport->getTransactionsByCard($card);
// - тестовые данные генерируются на стороне БС

// получили карту с демоданными
$card = $orgCardsTransport->getByCardId(new Cards\DTO\CardId('e0a84c5e-bf66-4100-98ba-858bb66c0ce5'));

// получили магазины организации
$shopCollection = $orgShopsTransport->list();

print('---------------' . PHP_EOL);
print(sprintf('получаем транзакции баллов по карте с id %s' . PHP_EOL, $card->getCardId()->getId()));


// получаем историю покупок по карте
// там содержится информация о покупках
$salesHistory = $orgTransactionsTransport->getSalesHistoryByCard($card);

//
// получение транзакций бонусных баллов по карте вообще всех
$transactionsWithPagination = $orgTransactionsTransport->getTransactionsByCard($card);
print(sprintf('получение всех транзакций по карте и их показ: %s шт.' . PHP_EOL, $transactionsWithPagination->getTransactionCollection()->count()));
showTransactionsList($transactionsWithPagination->getTransactionCollection(), $salesHistory, $shopCollection);


// получаем первые 10 транзакций
$transactionsWithPagination = $orgTransactionsTransport->getTransactionsByCard($card, null, null, new \Rarus\BonusServer\Transport\DTO\Pagination(10, 1));
print(sprintf('получение первых 10 транзакций по карте и их показ: %s шт.' . PHP_EOL, $transactionsWithPagination->getTransactionCollection()->count()));
showTransactionsList($transactionsWithPagination->getTransactionCollection(), $salesHistory, $shopCollection);

// получаем n транзакций по фильтру с датами
$dateFrom = DateTime::createFromFormat('Y.m.d H:i:s', '2018.09.05 09:14:00', new \DateTimeZone('UTC'));
$dateTo = DateTime::createFromFormat('Y.m.d H:i:s', '2018.09.05 09:20:00', new \DateTimeZone('UTC'));

$transactionsWithPagination = $orgTransactionsTransport->getTransactionsByCard($card, $dateFrom, $dateTo);
print(sprintf('получение транзакций по карте за период времени и их показ: %s шт.' . PHP_EOL, $transactionsWithPagination->getTransactionCollection()->count()));

showTransactionsList($transactionsWithPagination->getTransactionCollection(), $salesHistory, $shopCollection);

/**
* @param TransactionCollection $transactionCollection
* @param HistoryItemCollection $historyItemCollection
* @param ShopCollection $shopCollection
*/
function showTransactionsList(TransactionCollection $transactionCollection, HistoryItemCollection $historyItemCollection, ShopCollection $shopCollection): void
{
print(' GUID | timestamp | тип |баллы в копейках| баллы будут доступны до | Id магазина | документ покупки | стоимость ' . PHP_EOL);
foreach ($transactionCollection as $trx) {
print(sprintf('-- %s | %s %s | %s' . PHP_EOL,
$trx->getPointId()->getId(),
print(sprintf('%s | %s | %s | %s | %s | %s | %s | %s ' . PHP_EOL,
$trx->getRowNumber(),
$trx->getTime()->format(\DATE_ATOM),
$trx->getType()->getCode(),
$trx->getSum()->getAmount(),
$trx->getSum()->getCurrency()->getCode(),
$trx->getType()->getCode())
);
}
// получение истории покупок по карте
$salesHistory = $orgTransactionsTransport->getSalesHistoryByCard($card);
print(sprintf('история покупок: ' . PHP_EOL));
foreach ($salesHistory as $historyItem) {
print(sprintf('%s | %s | %s %s' . PHP_EOL,
$historyItem->getLineNumber(),
$historyItem->getDocumentId()->getId(),
$historyItem->getSum()->getAmount(),
$historyItem->getSum()->getCurrency()->getCode()
$trx->getInvalidatePeriod()->format(\DATE_ATOM),
findShopAndGetName($shopCollection, $trx->getShopId()),
$trx->getDocumentId()->getId(),
findItemInSalesHistoryAndGetSumAsString($historyItemCollection, $trx->getDocumentId())
));
print('====== табличная часть: ' . PHP_EOL);
foreach ($historyItem->getProducts() as $productRow) {
print(sprintf(' %s | %s | %s cnt | %s %s ' . PHP_EOL,
$productRow->getArticleId()->getId(),
$productRow->getName(),
$productRow->getQuantity(),
$productRow->getPrice()->getAmount(),
$productRow->getPrice()->getCurrency()
));
}
}

/**
* @param HistoryItemCollection $historyItemCollection
* @param DocumentId $documentId
*
* @return string
*/
function findItemInSalesHistoryAndGetSumAsString(Transactions\DTO\SalesHistory\HistoryItemCollection $historyItemCollection, DocumentId $documentId): string
{
$sum = 'n/a';
foreach ($historyItemCollection as $historyItem) {
if ($historyItem->getDocumentId()->getId() === $documentId->getId()) {
return $historyItem->getSum()->getAmount();
}
}

return $sum;
}

/**
* @param ShopCollection $shopCollection
* @param null|Shops\DTO\ShopId $shopId
*
* @return string
*/
function findShopAndGetName(Shops\DTO\ShopCollection $shopCollection, Shops\DTO\ShopId $shopId): string
{
if ($shopId === null || $shopId->getId() === '') {
return 'n/a';
}

foreach ($shopCollection as $shopItem) {
if ($shopItem->getShopId()->getId() === $shopId->getId()) {
return $shopItem->getName();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,12 @@ class PaginationResponse extends \Rarus\BonusServer\Transport\DTO\PaginationResp
*/
private $cardCollection;

/**
* PaginationResponse constructor.
*
* @param CardCollection $cardCollection
* @param Pagination $pagination
*/
public function __construct(CardCollection $cardCollection, Pagination $pagination)
{
$this->cardCollection = $cardCollection;
Expand Down
35 changes: 0 additions & 35 deletions src/Rarus/BonusServer/Transactions/DTO/Points/Fabric.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,41 +23,6 @@
*/
class Fabric
{
/**
* @param Currency $currency
* @param array $arPointTransaction
* @param \DateTimeZone $dateTimeZone
*
* @return PointTransaction
* @throws \Rarus\BonusServer\Exceptions\ApiClientException
*/
public static function initPointTransactionFromServerResponse(Currency $currency, array $arPointTransaction, \DateTimeZone $dateTimeZone): PointTransaction
{
$currencies = new ISOCurrencies();
$moneyParser = new DecimalMoneyParser($currencies);

$pointTrx = new PointTransaction();
$pointTrx
->setRowNumber((int)$arPointTransaction['row_number'])
->setPointId(new PointId((string)$arPointTransaction['id']))
->setCardId(new CardId((string)$arPointTransaction['card_id']))
->setMastercardId(new CardId((string)$arPointTransaction['mastercard_id']))
->setTime(DateTimeParser::parseTimestampFromServerResponse((string)$arPointTransaction['time'], $dateTimeZone))
->setSum($moneyParser->parse((string)$arPointTransaction['sum'], $currency->getCode()))
->setType($arPointTransaction['type'] === 0 ? Type\Fabric::getRefund() : Type\Fabric::getSale())
->setAuthor((string)$arPointTransaction['author'])
->setDescription((string)$arPointTransaction['description'])
->setDocumentId(new DocumentId((string)$arPointTransaction['doc_id']))
->setCashRegisterId(new CashRegisterId((string)$arPointTransaction['kkm_id']))
->setShopId(new ShopId((string)$arPointTransaction['shop_id']))
->setDocumentTypeId((string)$arPointTransaction['doc_type'])
->setInvalidatePeriod(DateTimeParser::parseTimestampFromServerResponse((string)$arPointTransaction['invalidate_period'], $dateTimeZone))
->setActivationPeriod(DateTimeParser::parseTimestampFromServerResponse((string)$arPointTransaction['activation_period'], $dateTimeZone))
->setDiscountId(new DiscountId((string)$arPointTransaction['discount_id']));

return $pointTrx;
}

/**
* @param Currency $currency
* @param array $arPoint
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
<?php
declare(strict_types=1);

namespace Rarus\BonusServer\Transactions\DTO\Points\Transactions;

use Money\Currency;
use Money\Currencies\ISOCurrencies;
use Money\Parser\DecimalMoneyParser;

use Rarus\BonusServer\Cards\DTO\CardId;
use Rarus\BonusServer\Discounts\DTO\DiscountId;
use Rarus\BonusServer\Shops\DTO\ShopId;
use Rarus\BonusServer\Transactions\DTO\CashRegister\CashRegisterId;
use Rarus\BonusServer\Transactions\DTO\Document\DocumentId;
use Rarus\BonusServer\Transactions\DTO\Type;
use Rarus\BonusServer\Transactions\DTO\Points\PointId;

use Rarus\BonusServer\Util\DateTimeParser;

/**
* Class Fabric
*
* @package Rarus\BonusServer\Transactions\DTO\Points
*/
class Fabric
{
/**
* @param Currency $currency
* @param array $arPointTransaction
* @param \DateTimeZone $dateTimeZone
*
* @return Transaction
* @throws \Rarus\BonusServer\Exceptions\ApiClientException
*/
public static function initPointTransactionFromServerResponse(Currency $currency, array $arPointTransaction, \DateTimeZone $dateTimeZone): Transaction
{
$currencies = new ISOCurrencies();
$moneyParser = new DecimalMoneyParser($currencies);

$pointTrx = new Transaction();
$pointTrx
->setRowNumber((int)$arPointTransaction['row_number'])
->setPointId(new PointId((string)$arPointTransaction['id']))
->setCardId(new CardId((string)$arPointTransaction['card_id']))
->setMastercardId(new CardId((string)$arPointTransaction['mastercard_id']))
->setTime(DateTimeParser::parseTimestampFromServerResponse((string)$arPointTransaction['time'], $dateTimeZone))
->setSum($moneyParser->parse((string)$arPointTransaction['sum'], $currency->getCode()))
->setType($arPointTransaction['type'] === 0 ? Type\Fabric::getRefund() : Type\Fabric::getSale())
->setAuthor((string)$arPointTransaction['author'])
->setDescription((string)$arPointTransaction['description'])
->setDocumentId(new DocumentId((string)$arPointTransaction['doc_id']))
->setCashRegisterId(new CashRegisterId((string)$arPointTransaction['kkm_id']))
->setShopId(new ShopId((string)$arPointTransaction['shop_id']))
->setDocumentTypeId((string)$arPointTransaction['doc_type'])
->setInvalidatePeriod(DateTimeParser::parseTimestampFromServerResponse((string)$arPointTransaction['invalidate_period'], $dateTimeZone))
->setActivationPeriod(DateTimeParser::parseTimestampFromServerResponse((string)$arPointTransaction['activation_period'], $dateTimeZone))
->setDiscountId(new DiscountId((string)$arPointTransaction['discount_id']));

return $pointTrx;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);

namespace Rarus\BonusServer\Transactions\DTO\Points\Transactions;

use Rarus\BonusServer\Transport\DTO\Pagination;

/**
* Class PaginationResponse
*
* @package Rarus\BonusServer\Transactions\DTO\Points\Transactions
*/
class PaginationResponse extends \Rarus\BonusServer\Transport\DTO\PaginationResponse
{
/**
* @var TransactionCollection
*/
private $transactionCollection;

/**
* PaginationResponse constructor.
*
* @param TransactionCollection $transactionCollection
* @param Pagination $pagination
*/
public function __construct(TransactionCollection $transactionCollection, Pagination $pagination)
{
$this->transactionCollection = $transactionCollection;
$this->pagination = $pagination;
}

/**
* @return TransactionCollection
*/
public function getTransactionCollection(): TransactionCollection
{
return $this->transactionCollection;
}
}
Loading

0 comments on commit 63fde32

Please sign in to comment.