mirror of
https://github.com/FOSSBilling/FOSSBilling.git
synced 2026-12-01 12:48:08 +09:00
Enhance API with batch retrieval and admin transaction handling (#3769)
* Set X-Requested-With for same-origin requests * Add string type hints and update copyrights * Make addon API output admin-aware * Admin mark-as-paid: save transaction and mark processed * Use batch API fetch for order list * Use batch API retrieval for orders * Remove hardcoded 'Payment gateway' fallback * Allow mixed value type for hash filter * Fix custom admin transaction handling
This commit is contained in:
1 parent
94893fb315
commit
7927792fe1
11 files changed
+354
-52
No files matched your search
@@ -400,6 +400,9 @@ const API = {
|
||||
'Accept': 'application/json',
|
||||
'X-CSRF-Token': Tools.getCSRFToken() || '',
|
||||
};
|
||||
if (url.origin === window.location.origin) {
|
||||
headers['X-Requested-With'] = 'XMLHttpRequest';
|
||||
}
|
||||
if (body && !isFormData) {
|
||||
headers['Content-Type'] = 'application/json';
|
||||
}
|
||||
|
||||
@@ -177,7 +177,7 @@ class FOSSBillingExtension
|
||||
}
|
||||
|
||||
#[AsTwigFilter('asset_url', isSafe: ['html'], needsEnvironment: true)]
|
||||
public function assetUrl(Environment $env, $asset): string
|
||||
public function assetUrl(Environment $env, string $asset): string
|
||||
{
|
||||
$globals = $env->getGlobals();
|
||||
$themeCode = $globals['current_theme'] ?? ($globals['theme']['code'] ?? null);
|
||||
@@ -218,7 +218,7 @@ class FOSSBillingExtension
|
||||
}
|
||||
|
||||
#[AsTwigFilter('hash')]
|
||||
public function hash($value, $algo = 'xxh128'): string
|
||||
public function hash(mixed $value, string $algo = 'xxh128'): string
|
||||
{
|
||||
if (!in_array($algo, hash_algos(), true)) {
|
||||
throw new \InvalidArgumentException(sprintf('Hash algorithm "%s" is not supported.', $algo));
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
declare(strict_types=1);
|
||||
/**
|
||||
* Copyright 2022-2025 FOSSBilling
|
||||
* Copyright 2022-2026 FOSSBilling
|
||||
* Copyright 2011-2021 BoxBilling, Inc.
|
||||
* SPDX-License-Identifier: Apache-2.0.
|
||||
*
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
declare(strict_types=1);
|
||||
/**
|
||||
* Copyright 2022-2025 FOSSBilling
|
||||
* Copyright 2022-2026 FOSSBilling
|
||||
* Copyright 2011-2021 BoxBilling, Inc.
|
||||
* SPDX-License-Identifier: Apache-2.0.
|
||||
*
|
||||
@@ -599,16 +599,34 @@ class Service implements InjectionAwareInterface
|
||||
|
||||
if (($payGateway->gateway ?? null) === 'Custom' && (int) ($payGateway->enabled ?? 0) === 1) {
|
||||
$transactionService = $this->di['mod_service']('Invoice', 'Transaction');
|
||||
$invoiceTotal = $this->getTotalWithTax($invoice);
|
||||
$newtx = $transactionService->create([
|
||||
'invoice_id' => $invoice->id,
|
||||
'gateway_id' => $invoice->gateway_id,
|
||||
'currency' => $invoice->currency,
|
||||
'status' => 'received',
|
||||
'source' => 'admin',
|
||||
'post' => [
|
||||
'invoice_id' => $invoice->id,
|
||||
'txn_id' => $transactionId,
|
||||
],
|
||||
'txn_id' => $transactionId,
|
||||
]);
|
||||
$transaction = $this->di['db']->getExistingModelById('Transaction', $newtx, 'Transaction not found');
|
||||
if ((int) $transaction->invoice_id !== (int) $invoice->id) {
|
||||
throw new InformationException('Transaction ID is already associated with another invoice.');
|
||||
}
|
||||
|
||||
$result = $transactionService->processTransaction($newtx);
|
||||
$result = $this->markAsPaid($invoice, false, $execute);
|
||||
if ($result) {
|
||||
$transaction->amount = $invoiceTotal;
|
||||
$transaction->currency = $invoice->currency;
|
||||
$transaction->status = \Model_Transaction::STATUS_PROCESSED;
|
||||
$gatewayTitle = $payGateway->title ?: $payGateway->gateway;
|
||||
$transaction->note = sprintf('%s transaction No: %s', $gatewayTitle, $transactionId);
|
||||
$transaction->updated_at = date('Y-m-d H:i:s');
|
||||
$this->di['db']->store($transaction);
|
||||
}
|
||||
|
||||
return (bool) $result;
|
||||
}
|
||||
|
||||
@@ -24,6 +24,7 @@ use Box\Mod\Order\Service as OrderService;
|
||||
use Box\Mod\System\Service as SystemService;
|
||||
|
||||
use function Tests\Helpers\container;
|
||||
use function Tests\Helpers\moduleService;
|
||||
|
||||
test('gets dependency injection container', function (): void {
|
||||
$service = new Service();
|
||||
@@ -487,6 +488,135 @@ test('marks invoice as paid', function (): void {
|
||||
expect($result)->toBeBool()->toBeTrue();
|
||||
});
|
||||
|
||||
test('admin mark as paid with custom gateway records transaction and marks invoice paid', function (): void {
|
||||
$serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
|
||||
$serviceMock->shouldReceive('markAsPaid')
|
||||
->once()
|
||||
->with(Mockery::type(Model_Invoice::class), false, true)
|
||||
->andReturn(true);
|
||||
$serviceMock->shouldReceive('getTotalWithTax')
|
||||
->once()
|
||||
->with(Mockery::type(Model_Invoice::class))
|
||||
->andReturn(42.50);
|
||||
|
||||
$invoiceModel = new Model_Invoice();
|
||||
$invoiceModel->loadBean(new Tests\Helpers\DummyBean());
|
||||
$invoiceModel->id = 10;
|
||||
$invoiceModel->gateway_id = 5;
|
||||
$invoiceModel->currency = 'USD';
|
||||
$invoiceModel->status = Model_Invoice::STATUS_UNPAID;
|
||||
|
||||
$gatewayModel = new Model_PayGateway();
|
||||
$gatewayModel->loadBean(new Tests\Helpers\DummyBean());
|
||||
$gatewayModel->id = 5;
|
||||
$gatewayModel->gateway = 'Custom';
|
||||
$gatewayModel->enabled = 1;
|
||||
$gatewayModel->title = 'Manual payment';
|
||||
|
||||
$transactionModel = new Model_Transaction();
|
||||
$transactionModel->loadBean(new Tests\Helpers\DummyBean());
|
||||
$transactionModel->invoice_id = 10;
|
||||
|
||||
$transactionServiceMock = Mockery::mock(\Box\Mod\Invoice\ServiceTransaction::class);
|
||||
$transactionServiceMock->shouldReceive('create')
|
||||
->once()
|
||||
->with(Mockery::on(fn (array $data): bool => $data['invoice_id'] === 10
|
||||
&& $data['gateway_id'] === 5
|
||||
&& $data['currency'] === 'USD'
|
||||
&& $data['source'] === 'admin'
|
||||
&& $data['post'] === ['invoice_id' => 10, 'txn_id' => 'manual-reference-1']
|
||||
&& $data['txn_id'] === 'manual-reference-1'))
|
||||
->andReturn(20);
|
||||
$transactionServiceMock->shouldNotReceive('processTransaction');
|
||||
|
||||
$dbMock = Mockery::mock('\Box_Database');
|
||||
$dbMock->shouldReceive('getExistingModelById')
|
||||
->once()
|
||||
->with('PayGateway', 5, 'Payment gateway not found')
|
||||
->andReturn($gatewayModel);
|
||||
$dbMock->shouldReceive('getExistingModelById')
|
||||
->once()
|
||||
->with('Transaction', 20, 'Transaction not found')
|
||||
->andReturn($transactionModel);
|
||||
$dbMock->shouldReceive('store')
|
||||
->once()
|
||||
->with($transactionModel)
|
||||
->andReturn(20);
|
||||
|
||||
$di = container();
|
||||
$di['db'] = $dbMock;
|
||||
$di['mod_service'] = $di->protect(moduleService([
|
||||
'invoice:transaction' => $transactionServiceMock,
|
||||
]));
|
||||
|
||||
$serviceMock->setDi($di);
|
||||
|
||||
$result = $serviceMock->markAsPaidByAdmin($invoiceModel, [
|
||||
'execute' => true,
|
||||
'transactionId' => 'manual-reference-1',
|
||||
]);
|
||||
|
||||
expect($result)->toBeTrue()
|
||||
->and($transactionModel->amount)->toBe(42.50)
|
||||
->and($transactionModel->currency)->toBe('USD')
|
||||
->and($transactionModel->status)->toBe(Model_Transaction::STATUS_PROCESSED)
|
||||
->and($transactionModel->note)->toBe('Manual payment transaction No: manual-reference-1');
|
||||
});
|
||||
|
||||
test('admin mark as paid with custom gateway rejects transaction linked to another invoice', function (): void {
|
||||
$serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
|
||||
$serviceMock->shouldNotReceive('markAsPaid');
|
||||
$serviceMock->shouldReceive('getTotalWithTax')
|
||||
->once()
|
||||
->with(Mockery::type(Model_Invoice::class))
|
||||
->andReturn(42.50);
|
||||
|
||||
$invoiceModel = new Model_Invoice();
|
||||
$invoiceModel->loadBean(new Tests\Helpers\DummyBean());
|
||||
$invoiceModel->id = 10;
|
||||
$invoiceModel->gateway_id = 5;
|
||||
$invoiceModel->currency = 'USD';
|
||||
$invoiceModel->status = Model_Invoice::STATUS_UNPAID;
|
||||
|
||||
$gatewayModel = new Model_PayGateway();
|
||||
$gatewayModel->loadBean(new Tests\Helpers\DummyBean());
|
||||
$gatewayModel->id = 5;
|
||||
$gatewayModel->gateway = 'Custom';
|
||||
$gatewayModel->enabled = 1;
|
||||
|
||||
$transactionModel = new Model_Transaction();
|
||||
$transactionModel->loadBean(new Tests\Helpers\DummyBean());
|
||||
$transactionModel->invoice_id = 99;
|
||||
|
||||
$transactionServiceMock = Mockery::mock(\Box\Mod\Invoice\ServiceTransaction::class);
|
||||
$transactionServiceMock->shouldReceive('create')
|
||||
->once()
|
||||
->andReturn(20);
|
||||
|
||||
$dbMock = Mockery::mock('\Box_Database');
|
||||
$dbMock->shouldReceive('getExistingModelById')
|
||||
->once()
|
||||
->with('PayGateway', 5, 'Payment gateway not found')
|
||||
->andReturn($gatewayModel);
|
||||
$dbMock->shouldReceive('getExistingModelById')
|
||||
->once()
|
||||
->with('Transaction', 20, 'Transaction not found')
|
||||
->andReturn($transactionModel);
|
||||
$dbMock->shouldNotReceive('store');
|
||||
|
||||
$di = container();
|
||||
$di['db'] = $dbMock;
|
||||
$di['mod_service'] = $di->protect(moduleService([
|
||||
'invoice:transaction' => $transactionServiceMock,
|
||||
]));
|
||||
|
||||
$serviceMock->setDi($di);
|
||||
|
||||
expect(fn () => $serviceMock->markAsPaidByAdmin($invoiceModel, [
|
||||
'transactionId' => 'manual-reference-1',
|
||||
]))->toThrow(\FOSSBilling\InformationException::class, 'Transaction ID is already associated with another invoice.');
|
||||
});
|
||||
|
||||
test('counts income', function (): void {
|
||||
$service = new Service();
|
||||
$serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
|
||||
|
||||
@@ -56,10 +56,10 @@ class Admin extends \Api_Abstract
|
||||
[$sql, $params] = $this->getService()->getSearchQuery($data);
|
||||
$resultSet = $this->getDi()['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
|
||||
|
||||
foreach ($resultSet['list'] as $key => $result) {
|
||||
$orderObj = $this->getDi()['db']->getExistingModelById('ClientOrder', $result['id'], 'Order not found');
|
||||
$resultSet['list'][$key] = $this->getService()->toApiArray($orderObj, true, $this->getIdentity());
|
||||
}
|
||||
$resultSet['list'] = $this->getService()->getBatchForApi(
|
||||
array_column($resultSet['list'], 'id'),
|
||||
$this->getIdentity()
|
||||
);
|
||||
|
||||
return $resultSet;
|
||||
}
|
||||
|
||||
@@ -38,10 +38,10 @@ class Client extends \Api_Abstract
|
||||
|
||||
$pager = $this->getDi()['pager']->getPaginatedResultSet($query, $bindings, PaginationOptions::fromArray($data));
|
||||
|
||||
foreach ($pager['list'] as $key => $item) {
|
||||
$order = $this->getDi()['db']->getExistingModelById('ClientOrder', $item['id'], 'Client order not found');
|
||||
$pager['list'][$key] = $this->getService()->toApiArray($order);
|
||||
}
|
||||
$pager['list'] = $this->getService()->getBatchForApi(
|
||||
array_column($pager['list'], 'id'),
|
||||
$identity
|
||||
);
|
||||
|
||||
return $pager;
|
||||
}
|
||||
|
||||
@@ -47,19 +47,41 @@ test('gets an order', function (): void {
|
||||
|
||||
test('gets order list', function (): void {
|
||||
$api = new Admin();
|
||||
$identity = new Model_Admin();
|
||||
|
||||
$serviceMock = Mockery::mock(Service::class);
|
||||
$serviceMock->shouldReceive('getSearchQuery')
|
||||
->atLeast()->once()
|
||||
->once()
|
||||
->andReturn(['query', []]);
|
||||
$serviceMock->shouldReceive('getBatchForApi')
|
||||
->once()
|
||||
->with([3, 2, 1], $identity)
|
||||
->andReturn([
|
||||
['id' => 3, 'title' => 'Third order'],
|
||||
['id' => 2, 'title' => 'Second order'],
|
||||
['id' => 1, 'title' => 'First order'],
|
||||
]);
|
||||
$serviceMock->shouldReceive('toApiArray')
|
||||
->never();
|
||||
|
||||
$paginatorMock = Mockery::mock(FOSSBilling\Pagination::class);
|
||||
$paginatorMock->shouldReceive('getPaginatedResultSet')
|
||||
->atLeast()->once()
|
||||
->andReturn(['list' => []]);
|
||||
->once()
|
||||
->andReturn([
|
||||
'list' => [
|
||||
['id' => 3],
|
||||
['id' => 2],
|
||||
['id' => 1],
|
||||
],
|
||||
'total' => 3,
|
||||
'pages' => 1,
|
||||
'page' => 1,
|
||||
'per_page' => 25,
|
||||
]);
|
||||
|
||||
$modMock = Mockery::mock(FOSSBilling\Module::class);
|
||||
$modMock->shouldReceive('getConfig')
|
||||
->atLeast()->once()
|
||||
->once()
|
||||
->andReturn(['show_addons' => 0]);
|
||||
|
||||
$di = container();
|
||||
@@ -68,9 +90,17 @@ test('gets order list', function (): void {
|
||||
|
||||
$api->setDi($di);
|
||||
$api->setService($serviceMock);
|
||||
$api->setIdentity($identity);
|
||||
|
||||
$result = $api->get_list([]);
|
||||
expect($result)->toBeArray();
|
||||
expect($result)
|
||||
->toBeArray()
|
||||
->and($result['list'])->toBe([
|
||||
['id' => 3, 'title' => 'Third order'],
|
||||
['id' => 2, 'title' => 'Second order'],
|
||||
['id' => 1, 'title' => 'First order'],
|
||||
])
|
||||
->and($result['total'])->toBe(3);
|
||||
});
|
||||
|
||||
test('creates an order', function (): void {
|
||||
|
||||
@@ -25,31 +25,41 @@ test('gets dependency injection container', function (): void {
|
||||
|
||||
test('gets order list', function (): void {
|
||||
$api = new Client();
|
||||
$client = new Model_Client();
|
||||
$client->loadBean(new Tests\Helpers\DummyBean());
|
||||
$client->id = 1;
|
||||
|
||||
$serviceMock = Mockery::mock(Service::class);
|
||||
$serviceMock->shouldReceive('getSearchQuery')
|
||||
->atLeast()->once()
|
||||
->once()
|
||||
->andReturn(['query', []]);
|
||||
$serviceMock->shouldReceive('getBatchForApi')
|
||||
->once()
|
||||
->with([3, 2, 1], $client)
|
||||
->andReturn([
|
||||
['id' => 3, 'title' => 'Third order'],
|
||||
['id' => 2, 'title' => 'Second order'],
|
||||
['id' => 1, 'title' => 'First order'],
|
||||
]);
|
||||
$serviceMock->shouldReceive('toApiArray')
|
||||
->atLeast()->once()
|
||||
->andReturn([]);
|
||||
->never();
|
||||
|
||||
$resultSet = [
|
||||
'list' => [
|
||||
0 => ['id' => 1],
|
||||
['id' => 3],
|
||||
['id' => 2],
|
||||
['id' => 1],
|
||||
],
|
||||
'total' => 3,
|
||||
];
|
||||
$paginatorMock = Mockery::mock(FOSSBilling\Pagination::class);
|
||||
$paginatorMock->shouldReceive('getPaginatedResultSet')
|
||||
->atLeast()->once()
|
||||
->once()
|
||||
->andReturn($resultSet);
|
||||
|
||||
$clientOrderMock = new Model_ClientOrder();
|
||||
$clientOrderMock->loadBean(new Tests\Helpers\DummyBean());
|
||||
|
||||
$dbMock = Mockery::mock('\Box_Database');
|
||||
$dbMock->shouldReceive('getExistingModelById')
|
||||
->atLeast()->once()
|
||||
->andReturn($clientOrderMock);
|
||||
->never();
|
||||
|
||||
$di = container();
|
||||
$di['pager'] = $paginatorMock;
|
||||
@@ -57,44 +67,61 @@ test('gets order list', function (): void {
|
||||
|
||||
$api->setDi($di);
|
||||
|
||||
$client = new Model_Client();
|
||||
$client->loadBean(new Tests\Helpers\DummyBean());
|
||||
$client->id = 1;
|
||||
|
||||
$api->setIdentity($client);
|
||||
$api->setService($serviceMock);
|
||||
|
||||
$result = $api->get_list([]);
|
||||
expect($result)->toBeArray();
|
||||
expect($result)
|
||||
->toBeArray()
|
||||
->and($result['list'])->toBe([
|
||||
['id' => 3, 'title' => 'Third order'],
|
||||
['id' => 2, 'title' => 'Second order'],
|
||||
['id' => 1, 'title' => 'First order'],
|
||||
])
|
||||
->and($result['total'])->toBe(3);
|
||||
});
|
||||
|
||||
test('gets expiring order list', function (): void {
|
||||
$api = new Client();
|
||||
$client = new Model_Client();
|
||||
$client->loadBean(new Tests\Helpers\DummyBean());
|
||||
$client->id = 1;
|
||||
|
||||
$serviceMock = Mockery::mock(Service::class);
|
||||
$serviceMock->shouldReceive('getSoonExpiringActiveOrdersQuery')
|
||||
->atLeast()->once()
|
||||
->once()
|
||||
->andReturn(['query', []]);
|
||||
$serviceMock->shouldReceive('getBatchForApi')
|
||||
->once()
|
||||
->with([1], $client)
|
||||
->andReturn([
|
||||
['id' => 1, 'title' => 'Expiring order'],
|
||||
]);
|
||||
|
||||
$paginatorMock = Mockery::mock(FOSSBilling\Pagination::class);
|
||||
$paginatorMock->shouldReceive('getPaginatedResultSet')
|
||||
->atLeast()->once()
|
||||
->andReturn(['list' => []]);
|
||||
->once()
|
||||
->andReturn([
|
||||
'list' => [
|
||||
['id' => 1],
|
||||
],
|
||||
]);
|
||||
|
||||
$di = container();
|
||||
$di['pager'] = $paginatorMock;
|
||||
|
||||
$api->setDi($di);
|
||||
|
||||
$client = new Model_Client();
|
||||
$client->loadBean(new Tests\Helpers\DummyBean());
|
||||
$client->id = 1;
|
||||
|
||||
$api->setIdentity($client);
|
||||
$api->setService($serviceMock);
|
||||
|
||||
$data = ['expiring' => true];
|
||||
$result = $api->get_list($data);
|
||||
expect($result)->toBeArray();
|
||||
expect($result)
|
||||
->toBeArray()
|
||||
->and($result['list'])->toBe([
|
||||
['id' => 1, 'title' => 'Expiring order'],
|
||||
]);
|
||||
});
|
||||
|
||||
test('gets an order', function (): void {
|
||||
|
||||
@@ -105,11 +105,11 @@ class Service implements InjectionAwareInterface
|
||||
public function toApiArray(\Model_Product $model, $deep = true, $identity = null): array
|
||||
{
|
||||
$repo = $model->getTable();
|
||||
$addons = $this->getAddonsApiArray($model);
|
||||
$config = json_decode($model->config ?? '', true) ?? [];
|
||||
$pricing = $repo->getPricingArray($model);
|
||||
$starting_from = $this->getStartingFromPrice($model);
|
||||
$isAdmin = $identity instanceof \Model_Admin;
|
||||
$addons = $this->getAddonsApiArray($model, $isAdmin);
|
||||
|
||||
$result = [
|
||||
'id' => $model->id,
|
||||
@@ -122,6 +122,7 @@ class Service implements InjectionAwareInterface
|
||||
'priority' => $model->priority,
|
||||
'pricing' => $isAdmin ? $pricing : $this->getPublicPricing($pricing),
|
||||
'config' => $isAdmin ? $config : $this->getPublicConfig($config),
|
||||
'addons' => $addons,
|
||||
|
||||
'price_starting_from' => $starting_from,
|
||||
'icon_url' => $model->icon_url,
|
||||
@@ -137,7 +138,6 @@ class Service implements InjectionAwareInterface
|
||||
if ($isAdmin) {
|
||||
$result['created_at'] = $model->created_at;
|
||||
$result['updated_at'] = $model->updated_at;
|
||||
$result['addons'] = $addons;
|
||||
$result['quantity_in_stock'] = $model->quantity_in_stock;
|
||||
$result['stock_control'] = $model->stock_control;
|
||||
$result['upgrades'] = $this->getUpgradablePairs($model);
|
||||
@@ -828,18 +828,18 @@ class Service implements InjectionAwareInterface
|
||||
/**
|
||||
* @return mixed[]
|
||||
*/
|
||||
private function getAddonsApiArray(\Model_Product $model): array
|
||||
private function getAddonsApiArray(\Model_Product $model, bool $isAdmin): array
|
||||
{
|
||||
$addons = [];
|
||||
foreach ($this->getProductAddons($model) as $addon) {
|
||||
$d = $this->toAddonArray($addon);
|
||||
foreach ($this->getProductAddons($model, !$isAdmin) as $addon) {
|
||||
$d = $this->toAddonArray($addon, true, $isAdmin);
|
||||
$addons[] = $d;
|
||||
}
|
||||
|
||||
return $addons;
|
||||
}
|
||||
|
||||
public function getProductAddons(\Model_Product $model)
|
||||
public function getProductAddons(\Model_Product $model, bool $publicOnly = false)
|
||||
{
|
||||
$ids = json_decode($model->addons ?? '', true) ?? [];
|
||||
|
||||
@@ -851,16 +851,22 @@ class Service implements InjectionAwareInterface
|
||||
$slots = $count ? implode(',', array_fill(0, $count, '?')) : ''; // same as RedBean genSlots() method
|
||||
array_unshift($ids, (int) $model->id); // adding product ID as first param in array
|
||||
|
||||
return $this->di['db']->find('Product', 'type = "custom" and is_addon= 1 and id != ? and id IN (' . $slots . ')', $ids);
|
||||
$query = 'type = "custom" and is_addon= 1 and id != ? and id IN (' . $slots . ')';
|
||||
if ($publicOnly) {
|
||||
$query .= ' and active = 1 and status = "enabled"';
|
||||
}
|
||||
|
||||
return $this->di['db']->find('Product', $query, $ids);
|
||||
}
|
||||
|
||||
public function toAddonArray(\Model_Product $model, $deep = true): array
|
||||
public function toAddonArray(\Model_Product $model, $deep = true, ?bool $isAdmin = null): array
|
||||
{
|
||||
$isAdmin ??= true;
|
||||
$productPayment = $this->di['db']->load('ProductPayment', $model->product_payment_id);
|
||||
$pricing = $this->toProductPaymentApiArray($productPayment);
|
||||
$config = json_decode($model->config ?? '', true) ?? [];
|
||||
|
||||
return [
|
||||
$result = [
|
||||
'id' => $model->id,
|
||||
'type' => $model->type,
|
||||
'title' => $model->title,
|
||||
@@ -873,9 +879,15 @@ class Service implements InjectionAwareInterface
|
||||
'updated_at' => $model->updated_at,
|
||||
'icon_url' => $model->icon_url,
|
||||
|
||||
'pricing' => $pricing,
|
||||
'config' => $config,
|
||||
'pricing' => $isAdmin ? $pricing : $this->getPublicPricing($pricing),
|
||||
'config' => $isAdmin ? $config : $this->getPublicConfig($config),
|
||||
];
|
||||
|
||||
if (!$isAdmin) {
|
||||
unset($result['plugin'], $result['created_at'], $result['updated_at']);
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/*
|
||||
|
||||
@@ -109,6 +109,88 @@ test('converts product to api array', function (): void {
|
||||
expect($result)->toBeArray();
|
||||
});
|
||||
|
||||
test('converts public product to api array with addons', function (): void {
|
||||
$serviceMock = Mockery::mock(Service::class)->makePartial();
|
||||
$serviceMock->shouldReceive('getStartingFromPrice')
|
||||
->atLeast()
|
||||
->once();
|
||||
|
||||
$product = new Model_Product();
|
||||
$product->loadBean(new Tests\Helpers\DummyBean());
|
||||
$product->id = 1;
|
||||
$product->product_payment_id = 2;
|
||||
$product->addons = '[3]';
|
||||
$product->config = json_encode([
|
||||
'allow_domain_register' => true,
|
||||
'registrar' => 'hidden',
|
||||
]);
|
||||
|
||||
$addon = new Model_Product();
|
||||
$addon->loadBean(new Tests\Helpers\DummyBean());
|
||||
$addon->id = 3;
|
||||
$addon->product_payment_id = 4;
|
||||
$addon->config = json_encode([
|
||||
'allow_domain_own' => true,
|
||||
'registrar' => 'hidden',
|
||||
]);
|
||||
|
||||
$productPayment = new Model_ProductPayment();
|
||||
$productPayment->loadBean(new Tests\Helpers\DummyBean());
|
||||
$addonProductPayment = new Model_ProductPayment();
|
||||
$addonProductPayment->loadBean(new Tests\Helpers\DummyBean());
|
||||
|
||||
$productPricing = [
|
||||
'type' => 'free',
|
||||
Model_ProductPayment::FREE => ['price' => 0, 'setup' => 0],
|
||||
Model_ProductPayment::ONCE => ['price' => 0, 'setup' => 0],
|
||||
];
|
||||
$addonPricing = [
|
||||
'type' => 'once',
|
||||
Model_ProductPayment::ONCE => ['price' => 5, 'setup' => 1],
|
||||
'registrar' => 'hidden',
|
||||
];
|
||||
|
||||
$serviceMock->shouldReceive('getProductAddons')
|
||||
->once()
|
||||
->with($product, true)
|
||||
->andReturn([$addon]);
|
||||
$serviceMock->shouldReceive('toProductPaymentApiArray')
|
||||
->once()
|
||||
->with($productPayment)
|
||||
->andReturn($productPricing);
|
||||
$serviceMock->shouldReceive('toProductPaymentApiArray')
|
||||
->once()
|
||||
->with($addonProductPayment)
|
||||
->andReturn($addonPricing);
|
||||
|
||||
$dbMock = Mockery::mock('\Box_Database');
|
||||
$dbMock->shouldReceive('load')
|
||||
->once()
|
||||
->with('ProductPayment', 2)
|
||||
->andReturn($productPayment);
|
||||
$dbMock->shouldReceive('load')
|
||||
->once()
|
||||
->with('ProductPayment', 4)
|
||||
->andReturn($addonProductPayment);
|
||||
|
||||
$di = container();
|
||||
$di['db'] = $dbMock;
|
||||
$di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $serviceMock);
|
||||
|
||||
$product->setDi($di);
|
||||
$addon->setDi($di);
|
||||
$serviceMock->setDi($di);
|
||||
|
||||
$result = $serviceMock->toApiArray($product);
|
||||
|
||||
expect($result['addons'])->toHaveCount(1)
|
||||
->and($result['addons'][0]['id'])->toBe(3)
|
||||
->and($result['addons'][0]['pricing'])->not->toHaveKey('registrar')
|
||||
->and($result['addons'][0]['config'])->toBe(['allow_domain_own' => true])
|
||||
->and($result['addons'][0])->not->toHaveKeys(['plugin', 'created_at', 'updated_at'])
|
||||
->and($result['config'])->toBe(['allow_domain_register' => true]);
|
||||
});
|
||||
|
||||
test('gets product types', function (): void {
|
||||
$service = new Service();
|
||||
$modArray = [
|
||||
|
||||
Reference in new issue
Block a user