4 Commits

Author SHA1 Message Date
c763fe6c71 fix(statements/transactions) 2026-06-02 21:00:44 +03:00
a412af3e07 fix(transactions) 2026-06-02 19:46:51 +03:00
9b62a59705 saloon update 2026-04-25 13:59:25 +03:00
Anatoliy Poloz
d4db68f2e7 refactor(error): handling 2026-04-07 18:47:53 +03:00
11 changed files with 285 additions and 102 deletions

View File

@@ -11,8 +11,8 @@
],
"require": {
"php": "^8.4",
"saloonphp/saloon": "^3.0",
"saloonphp/laravel-plugin": "^3.0",
"saloonphp/saloon": "^4.0",
"saloonphp/laravel-plugin": "^4.0",
"saloonphp/pagination-plugin": "^2.0",
"spatie/laravel-data": "^4.0",
"guzzlehttp/guzzle": "^7.0",

View File

@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace Apoloz\AlfaBank\Data\Statement;
use Spatie\LaravelData\Data;
class CartInfoData extends Data
{
public function __construct(
public ?string $documentCode = null,
public ?string $documentContent = null,
public ?string $documentDate = null,
public ?string $documentNumber = null,
public ?string $paymentNumber = null,
public ?string $restAmount = null,
) {}
}

View File

@@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
namespace Apoloz\AlfaBank\Data\Statement;
use Spatie\LaravelData\Data;
class CurTransferData extends Data
{
public function __construct(
public ?string $bankOperationCode = null,
public ?string $beneficiaryBankAccount = null,
public ?string $beneficiaryBankName = null,
public ?string $beneficiaryBankOption = null,
public ?string $beneficiaryCustomerAccount = null,
public ?string $beneficiaryCustomerName = null,
public ?string $detailsOfCharges = null,
public ?string $exchangeRate = null,
public ?string $instructedAmount = null,
public ?string $instructionCode = null,
public ?string $intermediaryBankAccount = null,
public ?string $intermediaryBankName = null,
public ?string $intermediaryBankOption = null,
public ?string $orderingCustomerAccount = null,
public ?string $orderingCustomerName = null,
public ?string $payeeBankBic = null,
public ?string $payeeBankCorrAccount = null,
public ?string $payeeBankName = null,
public ?string $payerInn = null,
public ?string $receiverCorrespondentAccount = null,
public ?string $receiverCorrespondentName = null,
public ?string $regulatoryReporting = null,
public ?string $senderCorrespondentAccount = null,
public ?string $senderCorrespondentName = null,
public ?string $senderCorrespondentOption = null,
public ?string $senderToReceiverInformation = null,
public ?string $transactionRelatedReference = null,
public ?string $valueDateCurrencyInterbankSettledAmount = null,
) {}
}

View File

@@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace Apoloz\AlfaBank\Data\Statement;
use Spatie\LaravelData\Data;
class DepartmentalInfoData extends Data
{
public function __construct(
public ?string $uip = null,
public ?string $drawerStatus101 = null,
public ?string $kbk = null,
public ?string $oktmo = null,
public ?string $reasonCode106 = null,
public ?string $taxPeriod107 = null,
public ?string $docNumber108 = null,
public ?string $docDate109 = null,
public ?string $paymentKind110 = null,
) {}
}

View File

@@ -1,29 +1,17 @@
<?php
declare(strict_types=1);
/*
// MODULE_CONTRACT: Defines the data structure for detailed Russian Ruble (RUR) transfer information within a transaction.
// RESPONSIBILITY: To hold and type-safely represent comprehensive details about the payer and payee in an RUR transfer.
// INPUTS: Raw JSON object from the API response.
// OUTPUTS: A structured object containing RUR transfer details.
// LINKS: TransactionData.php
*/
namespace Apoloz\AlfaBank\Data\Statement;
// <SECTION name="module_imports" intent="Import the base Spatie Laravel Data class.">
// <BELIEF_STATE "Extending `Spatie\LaravelData\Data` enables automatic casting from JSON and provides other DTO benefits.">
use Spatie\LaravelData\Data;
// </SECTION>
// <SECTION name="class_definition" intent="Define a DTO for Russian Ruble transfer details.">
// <BELIEF_STATE "This DTO provides a clear, type-safe contract for highly detailed RUR transfer information, which is critical for financial reconciliation and compliance with Russian banking standards.">
class RurTransferData extends Data
{
// <SECTION name="constructor_properties" intent="Define the comprehensive properties of an RUR transfer.">
// <BELIEF_STATE "The constructor includes a wide array of optional fields covering full payee and payer details (account, bank BIC, correspondent account, INN, KPP, name), as well as specific payment attributes like `paymentKind110`, `priority`, `receiptDate`, and `valueDate`. All are optional as not all fields may be present or relevant in every transaction record.">
public function __construct(
public ?CartInfoData $cartInfo = null,
public ?string $deliveryKind = null,
public ?DepartmentalInfoData $departmentalInfo = null,
public ?string $payeeAccount = null,
public ?string $payeeBankBic = null,
public ?string $payeeBankCorrAccount = null,
@@ -38,10 +26,10 @@ class RurTransferData extends Data
public ?string $payerInn = null,
public ?string $payerKpp = null,
public ?string $payerName = null,
public ?string $payingCondition = null,
public ?string $paymentKind110 = null,
public ?string $priority = null,
public ?string $purposeCode = null,
public ?string $receiptDate = null,
public ?string $valueDate = null,
) {}
// </SECTION>
}

View File

@@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
namespace Apoloz\AlfaBank\Data\Statement;
use Spatie\LaravelData\Data;
class SwiftTransferData extends Data
{
public function __construct(
public ?string $bankOperationCode = null,
public ?string $beneficiaryBankAccount = null,
public ?string $beneficiaryBankName = null,
public ?string $beneficiaryBankOption = null,
public ?string $beneficiaryCustomerAccount = null,
public ?string $beneficiaryCustomerName = null,
public ?string $detailsOfCharges = null,
public ?string $exchangeRate = null,
public ?string $instructedAmount = null,
public ?string $instructionCode = null,
public ?string $intermediaryBankAccount = null,
public ?string $intermediaryBankName = null,
public ?string $intermediaryBankOption = null,
public ?string $orderingCustomerAccount = null,
public ?string $orderingCustomerName = null,
public ?string $payeeBankCorrAccount = null,
public ?string $payeeBankName = null,
public ?string $payeeBankBic = null,
public ?string $payerInn = null,
public ?string $receiverCorrespondentAccount = null,
public ?string $receiverCorrespondentName = null,
public ?string $regulatoryReporting = null,
public ?string $senderCorrespondentAccount = null,
public ?string $senderCorrespondentName = null,
public ?string $senderCorrespondentOption = null,
public ?string $senderToReceiverInformation = null,
public ?string $transactionRelatedReference = null,
public ?string $valueDateCurrencyInterbankSettledAmount = null,
) {}
}

View File

@@ -1,35 +1,18 @@
<?php
declare(strict_types=1);
/*
// MODULE_CONTRACT: Defines the data structure for a paginated collection of TransactionData objects.
// RESPONSIBILITY: To provide a structured, type-safe container for lists of account transactions returned by the API, including pagination metadata.
// INPUTS: Raw JSON array from the API response.
// OUTPUTS: An object containing pagination details and a collection of `TransactionData`.
// LINKS: Requests/Statement/GetTransactionsRequest.php
*/
namespace Apoloz\AlfaBank\Data\Statement;
// <SECTION name="module_imports" intent="Import necessary DTOs and Spatie Laravel Data components.">
// <BELIEF_STATE "This collection DTO relies on `PaginationData` for metadata and `TransactionData` for the individual items. `DataCollection` and `DataCollectionOf` are Spatie Data features for handling typed arrays of DTOs.">
use Apoloz\AlfaBank\Data\PaginationData;
use Spatie\LaravelData\Attributes\DataCollectionOf;
use Spatie\LaravelData\Data;
use Spatie\LaravelData\DataCollection;
// </SECTION>
// <SECTION name="class_definition" intent="Define a DTO for a collection of account transactions.">
// <BELIEF_STATE "A dedicated DTO for a collection ensures that the structure of paginated lists is consistent and type-safe, providing a reliable contract for consumers to manage financial statements.">
class TransactionCollectionData extends Data
{
// <SECTION name="constructor_properties" intent="Define the properties of the transaction collection.">
// <BELIEF_STATE "The collection structure includes pagination metadata (`pagination`) and the actual list of transactions (`transactions`). The `#[DataCollectionOf(TransactionData::class)]` attribute is crucial for ensuring that each item in the `transactions` array is automatically cast to a `TransactionData` DTO.">
public function __construct(
public PaginationData $pagination,
#[DataCollectionOf(TransactionData::class)]
public DataCollection $transactions
public DataCollection $transactions,
public ?array $_links = null,
) {}
// </SECTION>
}

View File

@@ -1,39 +1,32 @@
<?php
declare(strict_types=1);
/*
// MODULE_CONTRACT: Defines the data structure for a single transaction record.
// RESPONSIBILITY: To hold and type-safely represent the details of an individual account transaction.
// INPUTS: Raw JSON object from the API response.
// OUTPUTS: A structured object containing transaction details.
// LINKS: TransactionCollectionData.php
*/
namespace Apoloz\AlfaBank\Data\Statement;
// <SECTION name="module_imports" intent="Import necessary DTOs and Spatie Laravel Data components.">
// <BELIEF_STATE "This DTO includes nested `AmountData` for monetary values and `RurTransferData` for detailed transfer information.">
use Spatie\LaravelData\Data;
// </SECTION>
// <SECTION name="class_definition" intent="Define a DTO for a single account transaction.">
// <BELIEF_STATE "This DTO provides a comprehensive, type-safe representation of a transaction, essential for consistent data handling and financial reporting.">
class TransactionData extends Data
{
// <SECTION name="constructor_properties" intent="Define all properties that describe an account transaction.">
// <BELIEF_STATE "The constructor includes key identifiers like `uuid`, `transactionId`, `operationDate`, `number`, and `direction` (DEBIT/CREDIT). Crucially, `amount` and `amountRub` use the nested `AmountData` DTO to ensure monetary values are correctly associated with their currencies. `paymentPurpose` and `rurTransfer` provide additional context, with `rurTransfer` being another nested DTO for specific RUR details.">
public function __construct(
public string $uuid,
public string $transactionId,
public string $operationDate,
public string $number,
public string $direction, // DEBIT, CREDIT
public AmountData $amount, // Nested DTO for amount
public AmountData $amountRub, // Nested DTO for amount in RUB
public string $direction,
public AmountData $amount,
public AmountData $amountRub,
public ?string $documentDate = null,
public ?string $filial = null,
public ?string $operationCode = null,
public ?string $paymentPurpose = null,
public ?RurTransferData $rurTransfer = null, // Nested DTO for RUR specific transfer details
public ?string $priority = null,
public ?string $revaln = null,
public ?string $correspondingAccount = null,
public ?string $debtorCode = null,
public ?string $extendedDebtorCode = null,
public ?RurTransferData $rurTransfer = null,
public ?SwiftTransferData $swiftTransfer = null,
public ?CurTransferData $curTransfer = null,
) {}
// </SECTION>
}

View File

@@ -1,49 +1,30 @@
<?php
declare(strict_types=1);
/*
// MODULE_CONTRACT: Represents the API call to retrieve a list of account transactions.
// RESPONSIBILITY: To define the HTTP method, endpoint, and query parameters for fetching statement data, and to map the response to a structured collection DTO.
// INPUTS: Account number, date range, and pagination parameters.
// OUTPUTS: TransactionCollectionData (a DTO containing a list of transactions).
// LINKS: AlfaBankConnector.php#paginate
*/
namespace Apoloz\AlfaBank\Requests\Statement;
// <SECTION name="module_imports" intent="Import the response DTO and Saloon framework components.">
// <BELIEF_STATE "This request requires the `TransactionCollectionData` DTO to structure its response. It's a GET request, so it doesn't need body-related traits.">
use Apoloz\AlfaBank\Data\Statement\TransactionCollectionData;
use Apoloz\AlfaBank\Traits\HasAlfaPagination;
use Saloon\Enums\Method;
use Saloon\Http\Request;
use Saloon\Http\Response;
class GetTransactionsRequest extends Request
{
use HasAlfaPagination;
protected Method $method = Method::GET;
public function __construct(
protected string $accountNumber,
protected string $executeDateFrom,
protected string $executeDateTo,
?int $limit = 1000,
?int $offset = 0
) {
$this->limit = $limit;
$this->offset = $offset;
}
protected string $statementDate,
protected int $page = 1,
protected ?string $curFormat = null,
) {}
public function resolveEndpoint(): string
{
return '/api/jp/v1/statement/transactions';
}
// </SECTION>
// <SECTION name="response_dto_caster" intent="Transform the raw API JSON response into a structured collection DTO.">
// <BELIEF_STATE "The API returns a list of transactions. Casting this directly to a `TransactionCollectionData` DTO provides a type-safe, iterable object for the end-user, which is a significant improvement over dealing with raw arrays.">
public function createDtoFromResponse(Response $response): TransactionCollectionData
{
return TransactionCollectionData::from($response->json());
@@ -51,11 +32,11 @@ class GetTransactionsRequest extends Request
protected function defaultQuery(): array
{
return array_merge([
return array_filter([
'accountNumber' => $this->accountNumber,
'executeDateFrom' => $this->executeDateFrom,
'executeDateTo' => $this->executeDateTo,
], $this->getPaginationQuery());
'statementDate' => $this->statementDate,
'page' => $this->page,
'curFormat' => $this->curFormat,
], fn ($v) => $v !== null);
}
// </SECTION>
}

View File

@@ -43,7 +43,8 @@ trait HasAlfaErrorHandling
if (str_contains($contentType, 'application/json')) {
$data = $response->json();
$errorCode = $data['error'] ?? $data['ErrorCode'] ?? 'HTTP_' . $response->status();
$errorDescription = $data['error_description'] ?? $data['message'] ?? 'Request failed';
$rawDescription = $data['error_description'] ?? $data['message'] ?? 'Request failed';
$errorDescription = $this->decodeBankMessage($rawDescription);
} else {
$errorCode = 'HTTP_' . $response->status();
$errorDescription = 'Request failed with status ' . $response->status();
@@ -55,4 +56,15 @@ trait HasAlfaErrorHandling
"({$requestId}) {$errorDescription}"
);
}
private function decodeBankMessage(string $message): string
{
$decoded = preg_replace_callback(
'/%u([0-9A-Fa-f]{4})/',
fn ($m) => mb_convert_encoding(pack('H*', $m[1]), 'UTF-8', 'UCS-2BE'),
$message
);
return urldecode($decoded);
}
}

View File

@@ -7,22 +7,66 @@ use Saloon\Http\Faking\MockResponse;
test('can get transactions statement', function (): void {
$mockClient = new \Saloon\Http\Faking\MockClient([
GetTransactionsRequest::class => MockResponse::make([
'pagination' => [
'totalCount' => 1,
'limit' => 10,
'offset' => 0,
'_links' => [
['rel' => 'prev', 'href' => '?accountNumber=40702810500006103990&statementDate=2018-03-15&page=1'],
['rel' => 'next', 'href' => '?accountNumber=40702810500006103990&statementDate=2018-03-15&page=3'],
],
'transactions' => [
[
'uuid' => 'uuid-123',
'transactionId' => 'tx-123',
'operationDate' => '2023-01-01',
'number' => '1',
'uuid' => '55daccdf-de87-3879-976c-8b8415c8caf9',
'transactionId' => '1211206MOCO#DS0000017',
'operationDate' => '2018-12-31T00:00:00Z',
'number' => '1843',
'direction' => 'CREDIT',
'amount' => ['amount' => 100.00, 'currencyName' => 'RUB'],
'amountRub' => ['amount' => 100.00, 'currencyName' => 'RUB'],
'paymentPurpose' => 'Test',
'correspondingAccount' => '408...',
'amountRub' => ['amount' => 100.00, 'currencyName' => 'RUR'],
'documentDate' => '2021-10-07',
'filial' => 'АО "АЛЬФА-БАНК"',
'operationCode' => '01',
'paymentPurpose' => 'НДС не облагается',
'priority' => '5',
'revaln' => 'ПК',
'correspondingAccount' => '30101810400000000225',
'debtorCode' => '0',
'extendedDebtorCode' => '50012008',
'rurTransfer' => [
'cartInfo' => [
'documentCode' => 'doc-code',
'documentNumber' => 'doc-num',
],
'deliveryKind' => 'электронно',
'departmentalInfo' => [
'kbk' => '39210202010061000160',
'oktmo' => '11605000',
],
'payeeAccount' => '40802810401300015422',
'payeeBankBic' => '044525593',
'payeeInn' => '7728168971',
'payeeName' => 'Наименование получателя',
'payerAccount' => '40802810701300000761',
'payerBankBic' => '044525593',
'payerInn' => '7728168971',
'payerName' => 'Гаврилов Добрыня Петрович',
'payingCondition' => 'payingCondition',
'paymentKind110' => '1',
'purposeCode' => '1',
'receiptDate' => '2018-12-31',
'valueDate' => '2018-12-31',
],
'swiftTransfer' => [
'bankOperationCode' => 'CRED',
'beneficiaryBankAccount' => 'LOYDGB21323',
'beneficiaryBankName' => 'АО "АЛЬФА-БАНК"',
'exchangeRate' => '67,74',
'instructedAmount' => 'USD70,00',
],
'curTransfer' => [
'bankOperationCode' => 'CRED',
'intermediaryBankOption' => 'D',
'intermediaryBankName' => 'АО "АЛЬФА-БАНК"',
'orderingCustomerName' => 'ООО Радуга',
'exchangeRate' => '67,74',
],
],
],
], 200, ['Content-Type' => 'application/json']),
@@ -32,10 +76,69 @@ test('can get transactions statement', function (): void {
$connector = new AlfaBankConnector($config);
$connector->withMockClient($mockClient);
$request = new GetTransactionsRequest('408...', '2023-01-01', '2023-01-02');
$request = new GetTransactionsRequest(
accountNumber: '40702810500006103990',
statementDate: '2018-03-15',
page: 2,
curFormat: 'swiftTransfer',
);
$response = $connector->send($request);
expect($response->status())->toBe(200)
->and($response->dto()->transactions[0]->transactionId)->toBe('tx-123')
->and($response->dto()->transactions[0]->amount->amount)->toBe(100.00);
$dto = $response->dto();
expect($response->status())->toBe(200);
expect($dto->_links)->toBeArray()->toHaveCount(2);
expect($dto->transactions)->toHaveCount(1);
$tx = $dto->transactions[0];
expect($tx->transactionId)->toBe('1211206MOCO#DS0000017')
->and($tx->direction)->toBe('CREDIT')
->and($tx->amount->amount)->toBe(100.00)
->and($tx->amountRub->currencyName)->toBe('RUR')
->and($tx->documentDate)->toBe('2021-10-07')
->and($tx->filial)->toBe('АО "АЛЬФА-БАНК"')
->and($tx->operationCode)->toBe('01')
->and($tx->priority)->toBe('5')
->and($tx->revaln)->toBe('ПК')
->and($tx->debtorCode)->toBe('0')
->and($tx->extendedDebtorCode)->toBe('50012008');
expect($tx->rurTransfer)->not->toBeNull();
expect($tx->rurTransfer->cartInfo)->not->toBeNull();
expect($tx->rurTransfer->cartInfo->documentCode)->toBe('doc-code');
expect($tx->rurTransfer->deliveryKind)->toBe('электронно');
expect($tx->rurTransfer->departmentalInfo)->not->toBeNull();
expect($tx->rurTransfer->departmentalInfo->kbk)->toBe('39210202010061000160');
expect($tx->rurTransfer->payingCondition)->toBe('payingCondition');
expect($tx->rurTransfer->purposeCode)->toBe('1');
expect($tx->rurTransfer->receiptDate)->toBe('2018-12-31');
expect($tx->swiftTransfer)->not->toBeNull();
expect($tx->swiftTransfer->bankOperationCode)->toBe('CRED');
expect($tx->swiftTransfer->instructedAmount)->toBe('USD70,00');
expect($tx->curTransfer)->not->toBeNull();
expect($tx->curTransfer->orderingCustomerName)->toBe('ООО Радуга');
});
test('can get transactions with default page', function (): void {
$mockClient = new \Saloon\Http\Faking\MockClient([
GetTransactionsRequest::class => MockResponse::make([
'_links' => [],
'transactions' => [],
], 200, ['Content-Type' => 'application/json']),
]);
$config = createTestConfig();
$connector = new AlfaBankConnector($config);
$connector->withMockClient($mockClient);
$request = new GetTransactionsRequest(
accountNumber: '40702810500006103990',
statementDate: '2018-03-15',
);
$response = $connector->send($request);
expect($response->status())->toBe(200);
expect($response->dto()->transactions)->toHaveCount(0);
});