mirror of
https://github.com/FOSSBilling/FOSSBilling.git
synced 2026-11-30 04:07:07 +09:00
Add shared price validation for orders (#3952)
* Add shared price validation for orders * Fix quantity validation and item update behavior
This commit is contained in:
1 parent
7cd38132f1
commit
ca3625202a
7 files changed
+220
-17
No files matched your search
@@ -0,0 +1,61 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
/**
|
||||
* Copyright 2022-2026 FOSSBilling
|
||||
* SPDX-License-Identifier: Apache-2.0.
|
||||
*
|
||||
* @copyright FOSSBilling (https://www.fossbilling.org)
|
||||
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0
|
||||
*/
|
||||
|
||||
namespace FOSSBilling\Validation;
|
||||
|
||||
use FOSSBilling\InformationException;
|
||||
|
||||
final class PriceValidator
|
||||
{
|
||||
public static function validateAmount(mixed $value, string $fieldName = 'Price'): float
|
||||
{
|
||||
$amount = self::validateNumericAmount($value, $fieldName);
|
||||
|
||||
if ($amount < 0) {
|
||||
throw new InformationException(':field cannot be negative.', [':field' => $fieldName]);
|
||||
}
|
||||
|
||||
return $amount;
|
||||
}
|
||||
|
||||
public static function validateSignedAmount(mixed $value, string $fieldName = 'Price'): float
|
||||
{
|
||||
return self::validateNumericAmount($value, $fieldName);
|
||||
}
|
||||
|
||||
public static function validateQuantity(mixed $value): int
|
||||
{
|
||||
if (!is_numeric($value)) {
|
||||
throw new InformationException('Quantity must be a valid number.');
|
||||
}
|
||||
|
||||
$quantity = (float) $value;
|
||||
if (!is_finite($quantity) || $quantity > PHP_INT_MAX || $quantity < PHP_INT_MIN) {
|
||||
throw new InformationException('Quantity must be a valid number.');
|
||||
}
|
||||
|
||||
return max(1, (int) $quantity);
|
||||
}
|
||||
|
||||
private static function validateNumericAmount(mixed $value, string $fieldName): float
|
||||
{
|
||||
if (!is_numeric($value)) {
|
||||
throw new InformationException(':field must be a valid number.', [':field' => $fieldName]);
|
||||
}
|
||||
|
||||
$amount = (float) $value;
|
||||
if (!is_finite($amount)) {
|
||||
throw new InformationException(':field must be a valid number.', [':field' => $fieldName]);
|
||||
}
|
||||
|
||||
return $amount;
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ declare(strict_types=1);
|
||||
namespace Box\Mod\Invoice;
|
||||
|
||||
use FOSSBilling\InjectionAwareInterface;
|
||||
use FOSSBilling\Validation\PriceValidator;
|
||||
|
||||
class ServiceInvoiceItem implements InjectionAwareInterface
|
||||
{
|
||||
@@ -145,10 +146,10 @@ class ServiceInvoiceItem implements InjectionAwareInterface
|
||||
$pi->status = $status;
|
||||
$pi->title = $data['title'];
|
||||
$pi->period = $period;
|
||||
$pi->quantity = $data['quantity'] ?? 1;
|
||||
$pi->quantity = PriceValidator::validateQuantity($data['quantity'] ?? 1);
|
||||
$pi->unit = $data['unit'] ?? null;
|
||||
$pi->charged = $data['charged'] ?? 0;
|
||||
$pi->price = (float) ($data['price'] ?? 0);
|
||||
$pi->price = PriceValidator::validateSignedAmount($data['price'] ?? 0);
|
||||
$pi->taxed = $data['taxed'] ?? false;
|
||||
$pi->created_at = date('Y-m-d H:i:s');
|
||||
$pi->updated_at = date('Y-m-d H:i:s');
|
||||
@@ -188,12 +189,12 @@ class ServiceInvoiceItem implements InjectionAwareInterface
|
||||
public function update(\Model_InvoiceItem $item, array $data): void
|
||||
{
|
||||
$item->title = $data['title'] ?? $item->title;
|
||||
$item->price = $data['price'] ?? $item->price;
|
||||
if (isset($data['price'])) {
|
||||
$item->price = PriceValidator::validateSignedAmount($data['price']);
|
||||
}
|
||||
|
||||
$item_quantity = $data['quantity'] ?? 1;
|
||||
|
||||
if ($item_quantity != $item->quantity) {
|
||||
$item->quantity = $item_quantity > 0 ? $item_quantity : 1;
|
||||
if (array_key_exists('quantity', $data)) {
|
||||
$item->quantity = PriceValidator::validateQuantity($data['quantity']);
|
||||
}
|
||||
|
||||
if (isset($data['taxed']) && !empty($data['taxed'])) {
|
||||
|
||||
@@ -163,7 +163,8 @@ test('executes task for custom type', function (): void {
|
||||
test('adds new item', function (): void {
|
||||
$service = new ServiceInvoiceItem();
|
||||
$data = [
|
||||
'title' => 'Guacamole',
|
||||
'title' => 'Discount',
|
||||
'price' => -10,
|
||||
];
|
||||
$invoiceItemModel = new Model_InvoiceItem();
|
||||
$invoiceItemModel->loadBean(new Tests\Helpers\DummyBean());
|
||||
@@ -188,6 +189,7 @@ test('adds new item', function (): void {
|
||||
$invoiceModel->loadBean(new Tests\Helpers\DummyBean());
|
||||
$result = $service->addNew($invoiceModel, $data);
|
||||
expect($result)->toBeInt()->toBe($newId);
|
||||
expect($invoiceItemModel->price)->toBe(-10.0);
|
||||
});
|
||||
|
||||
test('gets total', function (): void {
|
||||
@@ -235,6 +237,7 @@ test('updates an item', function (): void {
|
||||
$service = new ServiceInvoiceItem();
|
||||
$invoiceItemModel = new Model_InvoiceItem();
|
||||
$invoiceItemModel->loadBean(new Tests\Helpers\DummyBean());
|
||||
$invoiceItemModel->quantity = 3;
|
||||
|
||||
$data = [
|
||||
'title' => 'New Engine',
|
||||
@@ -252,6 +255,8 @@ test('updates an item', function (): void {
|
||||
$service->setDi($di);
|
||||
|
||||
$service->update($invoiceItemModel, $data);
|
||||
|
||||
expect($invoiceItemModel->quantity)->toBe(3);
|
||||
});
|
||||
|
||||
test('removes an item', function (): void {
|
||||
|
||||
@@ -15,6 +15,7 @@ use Box\Mod\Currency\Entity\Currency;
|
||||
use Box\Mod\Product\Entity\Product;
|
||||
use FOSSBilling\InformationException;
|
||||
use FOSSBilling\InjectionAwareInterface;
|
||||
use FOSSBilling\Validation\PriceValidator;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class Service implements InjectionAwareInterface
|
||||
@@ -646,6 +647,9 @@ class Service implements InjectionAwareInterface
|
||||
|
||||
public function createOrder(\Model_Client $client, Product $product, array $data)
|
||||
{
|
||||
$quantity = PriceValidator::validateQuantity($data['quantity'] ?? 1);
|
||||
$price = isset($data['price']) ? PriceValidator::validateAmount($data['price']) : null;
|
||||
|
||||
$currencyService = $this->di['mod_service']('currency');
|
||||
/** @var \Box\Mod\Currency\Repository\CurrencyRepository $currencyRepository */
|
||||
$currencyRepository = $currencyService->getCurrencyRepository();
|
||||
@@ -664,7 +668,6 @@ class Service implements InjectionAwareInterface
|
||||
$this->di['events_manager']->fire(['event' => 'onBeforeAdminOrderCreate', 'params' => $data, 'subject' => $this->getProductType($product)]);
|
||||
|
||||
$period = (isset($data['period']) && !empty($data['period'])) ? $data['period'] : null;
|
||||
$qty = $data['quantity'] ?? 1;
|
||||
$config = (isset($data['config']) && is_array($data['config'])) ? $data['config'] : [];
|
||||
$group_id = $data['group_id'] ?? null;
|
||||
$activate = (bool) ($data['activate'] ?? false);
|
||||
@@ -673,7 +676,7 @@ class Service implements InjectionAwareInterface
|
||||
|
||||
$cartService = $this->di['mod_service']('cart');
|
||||
// check stock
|
||||
if (!$cartService->isStockAvailable($product, $qty)) {
|
||||
if (!$cartService->isStockAvailable($product, $quantity)) {
|
||||
throw new InformationException('Product :id is out of stock.', [':id' => $this->getProductId($product)], 831);
|
||||
}
|
||||
|
||||
@@ -724,8 +727,9 @@ class Service implements InjectionAwareInterface
|
||||
$invoiceOption,
|
||||
$parent_order,
|
||||
$period,
|
||||
$price,
|
||||
$product,
|
||||
$qty,
|
||||
$quantity,
|
||||
&$invoice
|
||||
) {
|
||||
$order = $this->di['db']->dispense('ClientOrder');
|
||||
@@ -750,14 +754,14 @@ class Service implements InjectionAwareInterface
|
||||
$line = null;
|
||||
if (!isset($data['price']) || $this->getProductType($product) === \Box\Mod\Product\Service::DOMAIN) {
|
||||
$productService = $this->di['mod_service']('Product');
|
||||
$line = $productService->getProductOrderLineConfig($product, array_merge($config, ['quantity' => $qty]));
|
||||
$line = $productService->getProductOrderLineConfig($product, array_merge($config, ['quantity' => $quantity]));
|
||||
$order->quantity = $line['quantity'];
|
||||
} else {
|
||||
$order->quantity = $qty;
|
||||
$order->quantity = $quantity;
|
||||
}
|
||||
|
||||
if (isset($data['price'])) {
|
||||
$order->price = $data['price'];
|
||||
if ($price !== null) {
|
||||
$order->price = $price;
|
||||
} else {
|
||||
$rate = $currencyRepository->getRateByCode($currency->getCode());
|
||||
if ($rate === null) {
|
||||
@@ -1092,7 +1096,9 @@ class Service implements InjectionAwareInterface
|
||||
|
||||
$order->invoice_option = $data['invoice_option'] ?? $order->invoice_option;
|
||||
$order->title = $data['title'] ?? $order->title;
|
||||
$order->price = $data['price'] ?? $order->price;
|
||||
if (isset($data['price'])) {
|
||||
$order->price = PriceValidator::validateAmount($data['price']);
|
||||
}
|
||||
if (isset($data['status']) && $data['status'] !== $order->status) {
|
||||
if (!in_array($data['status'], \Model_ClientOrder::getValidStatuses(), true)) {
|
||||
throw new InformationException('Invalid order status: :status', [':status:' => $data['status']]);
|
||||
|
||||
@@ -320,7 +320,7 @@
|
||||
</div>
|
||||
<div class="col-lg-6">
|
||||
<label class="form-label" for="order_price">{{ 'Price'|trans }}</label>
|
||||
<input class="form-control" id="order_price" type="text" name="price" value="{{ order.price }}" required>
|
||||
<input class="form-control" id="order_price" type="number" min="0" step="any" name="price" value="{{ order.price }}" required>
|
||||
</div>
|
||||
<div class="col-lg-6">
|
||||
<label class="form-label">{{ 'Invoice Option'|trans }}</label>
|
||||
|
||||
@@ -2480,3 +2480,34 @@ test('updateOrderConfig succeeds with valid form data', function (): void {
|
||||
|
||||
expect($result)->toBeTrue();
|
||||
});
|
||||
|
||||
test('createOrder rejects invalid price and quantity', function (array $data, string $message): void {
|
||||
$service = new Service();
|
||||
$client = new Model_Client();
|
||||
$product = orderServiceCreateProductEntity(1, 'custom');
|
||||
|
||||
expect(fn () => $service->createOrder($client, $product, $data))
|
||||
->toThrow(FOSSBilling\InformationException::class, $message);
|
||||
})->with([
|
||||
'negative price' => [['price' => -1], 'Price cannot be negative'],
|
||||
'invalid price' => [['price' => 'invalid'], 'Price must be a valid number'],
|
||||
'invalid quantity' => [['quantity' => 'invalid'], 'Quantity must be a valid number'],
|
||||
]);
|
||||
|
||||
test('updateOrder rejects a negative price', function (): void {
|
||||
$order = new Model_ClientOrder();
|
||||
$order->loadBean(new Tests\Helpers\DummyBean());
|
||||
|
||||
$events = Mockery::mock(Box_EventManager::class);
|
||||
$events->shouldReceive('fire')->once();
|
||||
|
||||
$di = container();
|
||||
$di['events_manager'] = $events;
|
||||
|
||||
$service = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
|
||||
$service->shouldReceive('updatePeriod')->once();
|
||||
$service->setDi($di);
|
||||
|
||||
expect(fn () => $service->updateOrder($order, ['price' => -1]))
|
||||
->toThrow(FOSSBilling\InformationException::class, 'Price cannot be negative');
|
||||
});
|
||||
@@ -0,0 +1,99 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Copyright 2022-2026 FOSSBilling
|
||||
* SPDX-License-Identifier: Apache-2.0.
|
||||
*
|
||||
* @copyright FOSSBilling (https://www.fossbilling.org)
|
||||
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use FOSSBilling\InformationException;
|
||||
use FOSSBilling\Validation\PriceValidator;
|
||||
|
||||
dataset('validAmounts', fn (): array => [
|
||||
'integer' => [10, 10.0],
|
||||
'decimal string' => ['10.50', 10.50],
|
||||
'zero' => [0, 0.0],
|
||||
]);
|
||||
|
||||
dataset('invalidAmounts', fn (): array => [
|
||||
'negative int' => [-1],
|
||||
'non-numeric string' => ['abc'],
|
||||
'empty string' => [''],
|
||||
'null' => [null],
|
||||
'array' => [[]],
|
||||
'boolean' => [true],
|
||||
]);
|
||||
|
||||
dataset('validQuantities', fn (): array => [
|
||||
'integer' => [5, 5],
|
||||
'numeric string' => ['3', 3],
|
||||
'one' => [1, 1],
|
||||
]);
|
||||
|
||||
dataset('flooredQuantities', fn (): array => [
|
||||
'zero' => [0, 1],
|
||||
'negative int' => [-5, 1],
|
||||
]);
|
||||
|
||||
dataset('invalidQuantities', fn (): array => [
|
||||
'non-numeric string' => ['abc'],
|
||||
'empty string' => [''],
|
||||
'null' => [null],
|
||||
'infinite' => [INF],
|
||||
'overflowed numeric string' => ['1e999'],
|
||||
'integer overflow' => [(string) PHP_INT_MAX . '0'],
|
||||
]);
|
||||
|
||||
test('validateAmount accepts valid amounts', function (mixed $input, float $expected): void {
|
||||
$result = PriceValidator::validateAmount($input);
|
||||
|
||||
expect($result)->toBeFloat();
|
||||
expect($result)->toEqual($expected);
|
||||
})->with('validAmounts');
|
||||
|
||||
test('validateAmount rejects invalid amounts', function (mixed $input): void {
|
||||
expect(fn () => PriceValidator::validateAmount($input))
|
||||
->toThrow(InformationException::class);
|
||||
})->with('invalidAmounts');
|
||||
|
||||
test('validateAmount uses custom field name in error', function (): void {
|
||||
expect(fn () => PriceValidator::validateAmount(-5, 'Setup fee'))
|
||||
->toThrow(InformationException::class, 'Setup fee cannot be negative.');
|
||||
});
|
||||
|
||||
test('validateAmount rejects non-numeric with field name', function (): void {
|
||||
expect(fn () => PriceValidator::validateAmount('abc', 'Unit price'))
|
||||
->toThrow(InformationException::class, 'Unit price must be a valid number.');
|
||||
});
|
||||
|
||||
test('validateSignedAmount accepts negative adjustments', function (): void {
|
||||
expect(PriceValidator::validateSignedAmount('-10.50'))->toBe(-10.50);
|
||||
});
|
||||
|
||||
test('validateSignedAmount rejects non-numeric values', function (): void {
|
||||
expect(fn () => PriceValidator::validateSignedAmount('not-a-price'))
|
||||
->toThrow(InformationException::class, 'Price must be a valid number.');
|
||||
});
|
||||
|
||||
test('validateQuantity accepts valid quantities', function (mixed $input, int $expected): void {
|
||||
$result = PriceValidator::validateQuantity($input);
|
||||
|
||||
expect($result)->toBeInt();
|
||||
expect($result)->toEqual($expected);
|
||||
})->with('validQuantities');
|
||||
|
||||
test('validateQuantity floors to minimum 1', function (mixed $input, int $expected): void {
|
||||
$result = PriceValidator::validateQuantity($input);
|
||||
|
||||
expect($result)->toBeInt();
|
||||
expect($result)->toEqual($expected);
|
||||
})->with('flooredQuantities');
|
||||
|
||||
test('validateQuantity rejects invalid values', function (mixed $input): void {
|
||||
expect(fn () => PriceValidator::validateQuantity($input))
|
||||
->toThrow(InformationException::class);
|
||||
})->with('invalidQuantities');
|
||||
Reference in new issue
Block a user