Migrate product models and enhance promo redemption functionality (#3587)

* Migrate product models; add `promo_redemption`

* Add DomainPricing & ProductOrder repositories

* Use Promo entity typehints and update tests

* Use DI logger, validate order config, update tests

* Replace `error_log` with logger; use stubs in tests

* Use attachOrderConfig and tighten service checks

* Clarify domain defaults and remove deprecated doc tag

* Add missing indexes to `promo_redemption` table

* Enrich promo API arrays and add redemption filters

* Various UI/JS fixes and template cleanups

* Log invoice issues as warnings; expose form_id

* Normalize spelling in UpdatePatcher comment

* Remove checkLimits production method and clean up stale test mocks

* Use getConfig() and add promo permission

* Use container logger directly, remove helpers

* Use defaults for optional Twig settings

* Import macro_functions into admin template

* Compensate promo redemptions on checkout failure

* 🐛 Fix product category and add-on availability handling
This commit is contained in:
Adam Daley authored and GitHub committed 2026-06-18 17:56:14 +01:00
1 parent 0d6c34137c
commit febec281a6
85 files changed
+10319 -6431

No files matched your search

+9 -17
View File
@@ -13,6 +13,7 @@ declare(strict_types=1);
namespace Box\Mod\Cart\Api;
use Box\Mod\Currency\Entity\Currency;
use Box\Mod\Product\Entity\Promo;
use FOSSBilling\Validation\Api\RequiredParams;
/**
@@ -98,7 +99,7 @@ class Guest extends \FOSSBilling\Api\AbstractApi
$this->getDi()['rate_limiter']->consumeOrThrow('cart_promo_apply_ip', (string) $this->getIp());
$promo = $this->getService()->findActivePromoByCode($data['promocode']);
if (!$promo instanceof \Model_Promo) {
if (!$promo instanceof Promo) {
throw new \FOSSBilling\InformationException('The promo code has expired or does not exist');
}
@@ -151,28 +152,19 @@ class Guest extends \FOSSBilling\Api\AbstractApi
public function add_item($data)
{
$cart = $this->getService()->getSessionCart();
$productService = $this->di['mod_service']('product');
$product = $this->getDi()['db']->getExistingModelById('Product', $data['id'], 'Product not found');
$product = $productService->findOneActiveById((int) $data['id']);
if (!$product instanceof \Box\Mod\Product\Entity\Product) {
throw new \FOSSBilling\Exception('Product not found');
}
if ($product->is_addon) {
if ($product->isAddon()) {
throw new \FOSSBilling\InformationException('Addon products cannot be added separately.');
}
if (is_array($data['addons'] ?? '')) {
$validAddons = json_decode($product->addons ?? '');
if (empty($validAddons)) {
$validAddons = [];
}
foreach ($data['addons'] as $addon => $properties) {
if ($properties['selected']) {
$addonModel = $this->getDi()['db']->getExistingModelById('Product', $addon, 'Addon not found');
if ($addonModel->status !== 'enabled' || !in_array($addon, $validAddons)) {
throw new \FOSSBilling\InformationException('One or more of your selected add-ons are invalid for the associated product.');
}
}
}
$productService->validateSelectedAddonsForProduct($product, $data['addons']);
}
// reset cart by default
+275 -361
View File
@@ -13,6 +13,8 @@ declare(strict_types=1);
namespace Box\Mod\Cart;
use Box\Mod\Currency\Entity\Currency;
use Box\Mod\Product\Entity\Product;
use Box\Mod\Product\Entity\Promo;
use FOSSBilling\InjectionAwareInterface;
class Service implements InjectionAwareInterface
@@ -97,12 +99,12 @@ class Service implements InjectionAwareInterface
return $cart;
}
public function addItem(\Model_Cart $cart, \Model_Product $product, array $data): bool
public function addItem(\Model_Cart $cart, Product $product, array $data): bool
{
$event_params = [...$data, 'cart_id' => $cart->id, 'product_id' => $product->id];
$event_params = [...$data, 'cart_id' => $cart->id, 'product_id' => $this->getProductId($product)];
$this->di['events_manager']->fire(['event' => 'onBeforeProductAddedToCart', 'params' => $event_params]);
$productService = $product->getService();
$productService = $this->getProductService()->getProductModuleService($product);
if ($this->isRecurrentPricing($product)) {
$required = [
@@ -119,7 +121,7 @@ class Service implements InjectionAwareInterface
unset($data['id']);
unset($data['addons']);
$productConfig = json_decode($product->config ?? '', true) ?? [];
$productConfig = json_decode($product->getConfig() ?? '', true) ?? [];
// Collect all domains that will be added: top-level (direct domain product) and
// nested under $data['domain'] (domain bundled with a hosting product).
@@ -169,44 +171,24 @@ class Service implements InjectionAwareInterface
// check for required domain product
if (method_exists($productService, 'getDomainProductFromConfig')) {
$dc = $productService->getDomainProductFromConfig($product, $data);
if (isset($dc['config']) && $dc['product'] && $dc['product'] instanceof \Model_Product) {
if (isset($dc['config']) && ($dc['product'] ?? null) instanceof Product) {
$list[] = $dc;
}
}
$productService = $this->di['mod_service']('Product');
foreach ($addons as $id => $ac) {
if (isset($ac['selected']) && (bool) $ac['selected']) {
$addon = $productService->getAddonById($id);
if ($addon instanceof \Model_Product) {
if ($this->isRecurrentPricing($addon)) {
$required = [
'period' => 'Addon period parameter not passed',
];
$this->di['validator']->checkRequiredParamsForArray($required, $ac);
if (!$this->isPeriodEnabledForProduct($addon, $ac['period'])) {
throw new \FOSSBilling\InformationException('Selected billing period is invalid for the selected add-on');
}
}
$ac['parent_id'] = $product->id;
$list[] = [
'product' => $addon,
'config' => $ac,
];
} else {
error_log('Addon not found by id ' . $id);
}
if ($addons !== []) {
$productService = $this->di['mod_service']('Product');
foreach ($productService->getSelectedAddonsForCart($product, $addons) as $selectedAddon) {
$list[] = $selectedAddon;
}
}
$pendingQuantities = [];
foreach ($list as $cartItem) {
/** @var \Model_Product $cartProduct */
/** @var Product $cartProduct */
$cartProduct = $cartItem['product'];
$requestedQty = $this->getRequestedQuantity($cartItem['config']);
$cartProductId = (int) $cartProduct->id;
$cartProductId = (int) $this->getProductId($cartProduct);
$pendingQuantities[$cartProductId] = ($pendingQuantities[$cartProductId] ?? 0) + $requestedQty;
$reservedQty = $this->getReservedQuantityInCart($cart, $cartProductId);
@@ -217,68 +199,37 @@ class Service implements InjectionAwareInterface
foreach ($list as $c) {
$productFromList = $c['product'];
$productFromListConfig = $c['config'];
$productServiceFromList = $productFromList->getService();
// @deprecated logic
if (method_exists($productServiceFromList, 'prependOrderConfig')) {
$productFromListConfig = $productServiceFromList->prependOrderConfig($productFromList, $productFromListConfig);
}
if (method_exists($productServiceFromList, 'attachOrderConfig')) {
$model = $this->di['db']->load('Product', $productFromList->id);
$productFromListConfig = $productServiceFromList->attachOrderConfig($model, $productFromListConfig);
}
if (method_exists($productServiceFromList, 'validateOrderData')) {
$productServiceFromList->validateOrderData($productFromListConfig);
}
if (method_exists($productServiceFromList, 'validateCustomForm')) {
$productServiceFromList->validateCustomForm($productFromListConfig, $this->di['db']->toArray($productFromList));
}
$productFromListConfig = $this->getProductService()->prepareCartProductConfig($productFromList, $c['config']);
$this->addProduct($cart, $productFromList, $productFromListConfig);
}
$this->di['logger']->info('Added "%s" to shopping cart', $product->title);
$this->di['logger']->info('Added "%s" to shopping cart', $this->getProductTitle($product));
$this->di['events_manager']->fire(['event' => 'onAfterProductAddedToCart', 'params' => $event_params]);
return true;
}
public function isStockAvailable(\Model_Product $product, $qty)
public function isStockAvailable(Product|int $product, $qty)
{
if ($product->stock_control) {
return $product->quantity_in_stock >= $qty;
}
return true;
return $this->getProductService()->isStockAvailable($product, $qty);
}
public function isRecurrentPricing(\Model_Product $model): bool
public function isRecurrentPricing(Product $model): bool
{
$productTable = $model->getTable();
$pricing = $productTable->getPricingArray($model);
return isset($pricing['type']) && $pricing['type'] == \Model_ProductPayment::RECURRENT;
return $this->getProductService()->isRecurrentProductPricing($model);
}
public function isPeriodEnabledForProduct(\Model_Product $model, $period)
public function isPeriodEnabledForProduct(Product $model, $period)
{
$productTable = $model->getTable();
$pricing = $productTable->getPricingArray($model);
if ($pricing['type'] == \Model_ProductPayment::RECURRENT) {
return (bool) $pricing['recurrent'][$period]['enabled'];
}
return true;
return $this->getProductService()->isProductPeriodEnabled($model, (string) $period);
}
protected function addProduct(\Model_Cart $cart, \Model_Product $product, array $data): bool
protected function addProduct(\Model_Cart $cart, Product $product, array $data): bool
{
$item = $this->di['db']->dispense('CartProduct');
$item->cart_id = $cart->id;
$item->product_id = $product->id;
$item->product_id = $this->getProductId($product);
$item->config = json_encode($data);
$this->di['db']->store($item);
@@ -398,9 +349,12 @@ class Service implements InjectionAwareInterface
return true;
}
public function applyPromo(\Model_Cart $cart, \Model_Promo $promo): bool
public function applyPromo(\Model_Cart $cart, Promo $promo): bool
{
if ($cart->promo_id == $promo->id) {
$promoId = $promo->getId();
$promoCode = $promo->getCode();
if ($cart->promo_id == $promoId) {
return true;
}
@@ -408,10 +362,10 @@ class Service implements InjectionAwareInterface
throw new \FOSSBilling\InformationException('Add products to your cart before applying promo code');
}
$cart->promo_id = $promo->id;
$cart->promo_id = $promoId;
$this->di['db']->store($cart);
$this->di['logger']->info('Applied promo code %s to shopping cart', $promo->code);
$this->di['logger']->info('Applied promo code %s to shopping cart', $promoCode);
return true;
}
@@ -464,8 +418,8 @@ class Service implements InjectionAwareInterface
}
if ($model->promo_id) {
$promo = $this->di['db']->getExistingModelById('Promo', $model->promo_id, 'Promo not found');
$promocode = $promo->code;
$promo = $this->getProductService()->findPromoById((int) $model->promo_id);
$promocode = $promo->getCode();
} else {
$promocode = null;
}
@@ -480,71 +434,24 @@ class Service implements InjectionAwareInterface
];
}
public function isClientAbleToUsePromo(\Model_Client $client, \Model_Promo $promo)
public function isClientAbleToUsePromo(\Model_Client $client, Promo $promo)
{
if (!$this->promoCanBeApplied($promo)) {
return false;
}
if (!$promo->once_per_client) {
return true;
}
return !$this->clientHadUsedPromo($client, $promo);
return $this->getProductService()->canClientUsePromo($client, $promo);
}
public function promoCanBeApplied(\Model_Promo $promo): bool
public function promoCanBeApplied(Promo $promo): bool
{
if (!$promo->active) {
return false;
}
if ($promo->maxuses && $promo->maxuses <= $promo->used) {
return false;
}
if ($promo->start_at && (strtotime($promo->start_at) - time() > 0)) {
return false;
}
if ($promo->end_at && (strtotime($promo->end_at) - time() < 0)) {
return false;
}
return true;
return $this->getProductService()->promoCanBeApplied($promo);
}
public function isPromoAvailableForClientGroup(\Model_Promo $promo)
public function isPromoAvailableForClientGroup(Promo $promo)
{
$clientGroups = json_decode($promo->client_groups ?? '', true) ?? [];
if (empty($clientGroups)) {
return true;
}
try {
$client = $this->di['loggedin_client'];
} catch (\Exception) {
$client = null;
}
if (is_null($client)) {
return false;
}
if (!$client->client_group_id) {
return false;
}
return in_array($client->client_group_id, $clientGroups);
return $this->getProductService()->isPromoAvailableForClientGroup($promo);
}
protected function clientHadUsedPromo(\Model_Client $client, \Model_Promo $promo): bool
protected function clientHadUsedPromo(\Model_Client $client, Promo $promo): bool
{
$sql = 'SELECT id FROM client_order WHERE promo_id = :promo AND client_id = :cid LIMIT 1';
$promoId = $this->di['db']->getCell($sql, [':promo' => $promo->id, ':cid' => $client->id]);
return $promoId !== null;
return $this->getProductService()->clientHasActivePromoApplication($client, $promo);
}
public function getCartProducts(\Model_Cart $model)
@@ -555,15 +462,11 @@ class Service implements InjectionAwareInterface
public function checkoutCart(\Model_Cart $cart, \Model_Client $client, $gateway_id = null): array
{
if ($cart->promo_id) {
$promo = $this->di['db']->getExistingModelById('Promo', $cart->promo_id, 'Promo not found');
$promo = $this->getProductService()->findPromoById((int) $cart->promo_id);
if (!$this->isClientAbleToUsePromo($client, $promo)) {
throw new \FOSSBilling\InformationException('You have already used this promo code. Please remove the promo code and checkout again.', null, 9874);
}
if (!$promo instanceof \Model_Promo) {
throw new \FOSSBilling\InformationException('The promo code has expired or does not exist');
}
if (!$this->isPromoAvailableForClientGroup($promo)) {
throw new \FOSSBilling\InformationException('Promo code cannot be applied to your account');
}
@@ -632,206 +535,228 @@ class Service implements InjectionAwareInterface
}
$currencyCode = $currency->getCode();
// Set default client currency
if (!$client->currency) {
$client->currency = $currencyCode;
$this->di['db']->store($client);
}
if ($client->currency != $currencyCode) {
throw new \FOSSBilling\InformationException('Selected currency :selected does not match your profile currency :code. Please change cart currency to continue.', [':selected' => $currencyCode, ':code' => $client->currency]);
}
$clientService = $this->di['mod_service']('client');
$taxed = $clientService->isClientTaxable($client);
$promoProductService = $cart->promo_id ? $this->getProductService() : null;
$promo = $cart->promo_id ? $promoProductService?->findPromoById((int) $cart->promo_id) : null;
$orders = [];
$invoice_items = [];
$master_order = null;
$requestedProductQuantities = [];
$i = 0;
$reservedOrderIds = [];
$reservedCount = 0;
foreach ($this->getCartProducts($cart) as $p) {
$item = $this->cartProductToApiArray($p);
try {
return $this->di['db']->transaction(function () use ($ca, $cart, $client, $currency, $currencyCode, $gateway_id, $taxed, $promo, $promoProductService, &$reservedOrderIds, &$reservedCount) {
// Set default client currency.
if (!$client->currency) {
$client->currency = $currencyCode;
$this->di['db']->store($client);
}
$product = $this->di['db']->getExistingModelById('Product', $item['product_id']);
if (is_null($product) || $product->status !== 'enabled') {
throw new \FOSSBilling\InformationException('Unable to complete order. One or more of the selected products are invalid.');
}
if ($client->currency != $currencyCode) {
throw new \FOSSBilling\InformationException('Selected currency :selected does not match your profile currency :code. Please change cart currency to continue.', [':selected' => $currencyCode, ':code' => $client->currency]);
}
$requestedQty = $this->getRequestedQuantity($item);
$requestedProductQuantities[$product->id] = ($requestedProductQuantities[$product->id] ?? 0) + $requestedQty;
if (!$this->isStockAvailable($product, $requestedProductQuantities[$product->id])) {
throw new \FOSSBilling\InformationException('Unable to complete order. One or more selected products are out of stock.');
}
$orders = [];
$invoice_items = [];
$invoiceModel = null;
$master_order = null;
$requestedProductQuantities = [];
$i = 0;
/*
* Convert the domain name to lowercase letters.
* Using a capital letter in a domain name still points to the same name, so this isn't going to break anything
* It will, however, avoid instances like this when a domain name is entered with a capital letter:
* https://github.com/boxbilling/boxbilling/discussions/1022#discussioncomment-1311819
*/
if ($item['type'] === 'domain' || $item['type'] === 'hosting') {
$item['register_sld'] = (isset($item['register_sld'])) ? strtolower($item['register_sld']) : null;
$item['transfer_sld'] = (isset($item['transfer_sld'])) ? strtolower($item['transfer_sld']) : null;
$item['sld'] = (isset($item['sld'])) ? strtolower($item['sld']) : null;
$item['domain']['owndomain_sld'] = (isset($item['domain']['owndomain_sld'])) ? strtolower($item['domain']['owndomain_sld']) : null;
$item['domain']['register_sld'] = (isset($item['domain']['register_sld'])) ? strtolower($item['domain']['register_sld']) : null;
$item['domain']['transfer_sld'] = (isset($item['domain']['transfer_sld'])) ? strtolower($item['domain']['transfer_sld']) : null;
foreach ($this->getCartProducts($cart) as $p) {
$item = $this->cartProductToApiArray($p);
// Domain TLD must begin with a period - add if not present for owndomain.
$item['domain']['owndomain_tld'] = (isset($item['domain']['owndomain_tld'])) ? (str_contains($item['domain']['owndomain_tld'], '.') ? $item['domain']['owndomain_tld'] : '.' . $item['domain']['owndomain_tld']) : null;
}
$product = $this->getProductService()->findProductById((int) $item['product_id']);
if ($product->getStatus() !== 'enabled') {
throw new \FOSSBilling\InformationException('Unable to complete order. One or more of the selected products are invalid.');
}
$order = $this->di['db']->dispense('ClientOrder');
$order->client_id = $client->id;
$order->promo_id = $cart->promo_id;
$order->product_id = $item['product_id'];
$order->form_id = $item['form_id'];
$requestedQty = $this->getRequestedQuantity($item);
$productId = (int) $product->getId();
$requestedProductQuantities[$productId] = ($requestedProductQuantities[$productId] ?? 0) + $requestedQty;
if (!$this->isStockAvailable($product, $requestedProductQuantities[$productId])) {
throw new \FOSSBilling\InformationException('Unable to complete order. One or more selected products are out of stock.');
}
$order->group_id = $cart->id;
$order->group_master = ($i == 0);
$order->invoice_option = 'issue-invoice';
$order->title = $item['title'];
$order->currency = $currencyCode;
$order->service_type = $item['type'];
$order->unit = $item['unit'] ?? null;
$order->period = $item['period'] ?? null;
$order->quantity = $item['quantity'] ?? null;
$order->price = $item['price'] * $currency->getConversionRate();
$order->discount = $item['discount_price'] * $currency->getConversionRate();
$order->status = \Model_ClientOrder::STATUS_PENDING_SETUP;
$order->notes = $item['notes'] ?? null;
$order->config = json_encode($item);
$order->created_at = date('Y-m-d H:i:s');
$order->updated_at = date('Y-m-d H:i:s');
$this->di['db']->store($order);
/*
* Convert the domain name to lowercase letters.
* Using a capital letter in a domain name still points to the same name, so this isn't going to break anything
* It will, however, avoid instances like this when a domain name is entered with a capital letter:
* https://github.com/boxbilling/boxbilling/discussions/1022#discussioncomment-1311819
*/
if ($item['type'] === 'domain' || $item['type'] === 'hosting') {
$item['register_sld'] = (isset($item['register_sld'])) ? strtolower($item['register_sld']) : null;
$item['transfer_sld'] = (isset($item['transfer_sld'])) ? strtolower($item['transfer_sld']) : null;
$item['sld'] = (isset($item['sld'])) ? strtolower($item['sld']) : null;
$item['domain']['owndomain_sld'] = (isset($item['domain']['owndomain_sld'])) ? strtolower($item['domain']['owndomain_sld']) : null;
$item['domain']['register_sld'] = (isset($item['domain']['register_sld'])) ? strtolower($item['domain']['register_sld']) : null;
$item['domain']['transfer_sld'] = (isset($item['domain']['transfer_sld'])) ? strtolower($item['domain']['transfer_sld']) : null;
$orders[] = $order;
// Domain TLD must begin with a period - add if not present for owndomain.
$item['domain']['owndomain_tld'] = (isset($item['domain']['owndomain_tld'])) ? (str_contains($item['domain']['owndomain_tld'], '.') ? $item['domain']['owndomain_tld'] : '.' . $item['domain']['owndomain_tld']) : null;
}
// mark promo as used
if ($cart->promo_id) {
$promo = $this->di['db']->getExistingModelById('Promo', $cart->promo_id, 'Promo Not Found');
$this->usePromo($promo);
$order = $this->di['db']->dispense('ClientOrder');
$order->client_id = $client->id;
$order->promo_id = $cart->promo_id;
$order->product_id = $item['product_id'];
$order->form_id = $item['form_id'];
// set promo info for later use
$order->promo_recurring = $promo->recurring;
$order->promo_used = 1;
$this->di['db']->store($order);
}
$orderService = $this->di['mod_service']('order');
$orderService->saveStatusChange($order, 'Order Created');
$invoice_items[] = [
'title' => $order->title,
'price' => $order->price,
'quantity' => $order->quantity,
'unit' => $order->unit,
'period' => $order->period,
'taxed' => $taxed,
'type' => \Model_InvoiceItem::TYPE_ORDER,
'rel_id' => $order->id,
'task' => \Model_InvoiceItem::TASK_ACTIVATE,
];
if ($order->discount > 0) {
$invoice_items[] = [
'title' => __trans('Discount: :product', [':product' => $order->title]),
'price' => $order->discount * -1,
'quantity' => 1,
'unit' => 'discount',
'rel_id' => $order->id,
'taxed' => $taxed,
];
}
if ($item['setup_price'] > 0) {
$setup_price = ($item['setup_price'] * $currency->getConversionRate()) - ($item['discount_setup'] * $currency->getConversionRate());
$invoice_items[] = [
'title' => __trans(':product setup', [':product' => $order->title]),
'price' => $setup_price,
'quantity' => 1,
'unit' => 'service',
'taxed' => $taxed,
];
}
// define master order to be returned
if ($master_order === null) {
$master_order = $order;
}
++$i;
}
if ($ca['total'] > 0) { // crete invoice if order total > 0
$invoiceService = $this->di['mod_service']('Invoice');
$invoiceModel = $invoiceService->prepareInvoice($client, ['client_id' => $client->id, 'items' => $invoice_items, 'gateway_id' => $gateway_id]);
$clientBalanceService = $this->di['mod_service']('Client', 'Balance');
$balanceAmount = $clientBalanceService->getClientBalance($client);
$useCredits = $balanceAmount >= $ca['total'];
$invoiceService->approveInvoice($invoiceModel, ['id' => $invoiceModel->id, 'use_credits' => $useCredits]);
if ($invoiceModel->status == \Model_Invoice::STATUS_UNPAID) {
foreach ($orders as $order) {
$order->unpaid_invoice_id = $invoiceModel->id;
$order->group_id = $cart->id;
$order->group_master = ($i == 0);
$order->invoice_option = 'issue-invoice';
$order->title = $item['title'];
$order->currency = $currencyCode;
$order->service_type = $item['type'];
$order->unit = $item['unit'] ?? null;
$order->period = $item['period'] ?? null;
$order->quantity = $item['quantity'] ?? null;
$order->price = $item['price'] * $currency->getConversionRate();
$order->discount = $item['discount_price'] * $currency->getConversionRate();
$order->status = \Model_ClientOrder::STATUS_PENDING_SETUP;
$order->notes = $item['notes'] ?? null;
$order->config = json_encode($item);
$order->created_at = date('Y-m-d H:i:s');
$order->updated_at = date('Y-m-d H:i:s');
$this->di['db']->store($order);
$orders[] = $order;
// Reserve promo capacity at order creation time.
if ($promo instanceof Promo && $promoProductService !== null) {
$promoProductService->reservePromoForOrder($promo, $order);
$reservedOrderIds[] = (int) $order->id;
++$reservedCount;
}
$orderService = $this->di['mod_service']('order');
$orderService->saveStatusChange($order, 'Order Created');
$invoice_items[] = [
'title' => $order->title,
'price' => $order->price,
'quantity' => $order->quantity,
'unit' => $order->unit,
'period' => $order->period,
'taxed' => $taxed,
'type' => \Model_InvoiceItem::TYPE_ORDER,
'rel_id' => $order->id,
'task' => \Model_InvoiceItem::TASK_ACTIVATE,
];
if ($order->discount > 0) {
$invoice_items[] = [
'title' => __trans('Discount: :product', [':product' => $order->title]),
'price' => $order->discount * -1,
'quantity' => 1,
'unit' => 'discount',
'rel_id' => $order->id,
'taxed' => $taxed,
];
}
if ($item['setup_price'] > 0) {
$setup_price = ($item['setup_price'] * $currency->getConversionRate()) - ($item['discount_setup'] * $currency->getConversionRate());
$invoice_items[] = [
'title' => __trans(':product setup', [':product' => $order->title]),
'price' => $setup_price,
'quantity' => 1,
'unit' => 'service',
'taxed' => $taxed,
];
}
if ($master_order === null) {
$master_order = $order;
}
++$i;
}
if ($ca['total'] > 0) { // crete invoice if order total > 0
$invoiceService = $this->di['mod_service']('Invoice');
$invoiceModel = $invoiceService->prepareInvoice($client, ['client_id' => $client->id, 'items' => $invoice_items, 'gateway_id' => $gateway_id]);
$clientBalanceService = $this->di['mod_service']('Client', 'Balance');
$balanceAmount = $clientBalanceService->getClientBalance($client);
$useCredits = $balanceAmount >= $ca['total'];
$invoiceService->approveInvoice($invoiceModel, ['id' => $invoiceModel->id, 'use_credits' => $useCredits]);
if ($invoiceModel->status == \Model_Invoice::STATUS_UNPAID) {
foreach ($orders as $order) {
$order->unpaid_invoice_id = $invoiceModel->id;
$this->di['db']->store($order);
}
}
}
if ($promo instanceof Promo && $promoProductService !== null) {
$redemptionStatus = isset($invoiceModel) && $invoiceModel instanceof \Model_Invoice && $invoiceModel->status === \Model_Invoice::STATUS_UNPAID
? \Box\Mod\Product\Entity\PromoRedemption::STATUS_RESERVED
: \Box\Mod\Product\Entity\PromoRedemption::STATUS_COMMITTED;
$checkoutInvoice = $invoiceModel instanceof \Model_Invoice ? $invoiceModel : null;
$promoProductService->createCheckoutPromoRedemptions($promo, $client, $orders, $checkoutInvoice, $redemptionStatus);
}
// Activate orders after the checkout state is durably persisted.
$orderService = $this->di['mod_service']('Order');
$ids = [];
foreach ($orders as $order) {
$ids[] = $order->id;
$oa = $orderService->toApiArray($order, false, $client);
$product = $this->getProductService()->findProductById((int) $oa['product_id']);
try {
if ($product->getSetup() == \Box\Mod\Product\Service::SETUP_AFTER_ORDER) {
$orderService->activateOrder($order);
}
if ($ca['total'] <= 0 && $product->getSetup() == \Box\Mod\Product\Service::SETUP_AFTER_PAYMENT && $oa['total'] - $oa['discount'] <= 0) {
$orderService->activateOrder($order);
}
if ($ca['total'] > 0 && $product->getSetup() == \Box\Mod\Product\Service::SETUP_AFTER_PAYMENT && $invoiceModel->status == \Model_Invoice::STATUS_PAID) {
$orderService->activateOrder($order);
}
} catch (\Exception $e) {
error_log($e->getMessage());
$status = 'error';
$notes = "Order could not be activated after checkout due to error: {$e->getMessage()}.";
$orderService->orderStatusAdd($order, $status, $notes);
}
}
return [
$master_order,
$invoiceModel ?? null,
$ids,
];
});
} catch (\Throwable $e) {
if ($promo instanceof Promo && $reservedCount > 0) {
try {
$promoProductService->compensateCheckoutPromoFailure($promo, $reservedOrderIds, $reservedCount);
} catch (\Throwable $compensationError) {
$this->di['logger']->error('Failed to compensate promo checkout failure', [
'exception' => $compensationError->getMessage(),
'promo_id' => $promo->getId(),
]);
}
}
throw $e;
}
// activate orders if product is setup to be activated after order place or order total is $0
$orderService = $this->di['mod_service']('Order');
$ids = [];
foreach ($orders as $order) {
$ids[] = $order->id;
$oa = $orderService->toApiArray($order, false, $client);
$product = $this->di['db']->getExistingModelById('Product', $oa['product_id']);
try {
if ($product->setup == \Model_ProductTable::SETUP_AFTER_ORDER) {
$orderService->activateOrder($order);
}
if ($ca['total'] <= 0 && $product->setup == \Model_ProductTable::SETUP_AFTER_PAYMENT && $oa['total'] - $oa['discount'] <= 0) {
$orderService->activateOrder($order);
}
if ($ca['total'] > 0 && $product->setup == \Model_ProductTable::SETUP_AFTER_PAYMENT && $invoiceModel->status == \Model_Invoice::STATUS_PAID) {
$orderService->activateOrder($order);
}
} catch (\Exception $e) {
error_log($e->getMessage());
$status = 'error';
$notes = "Order could not be activated after checkout due to error: {$e->getMessage()}.";
$orderService->orderStatusAdd($order, $status, $notes);
}
}
return [
$master_order,
$invoiceModel ?? null,
$ids,
];
}
public function usePromo(\Model_Promo $promo): void
public function usePromo(Promo $promo): void
{
$affectedRows = $this->di['db']->exec(
'UPDATE promo SET used = used + 1, updated_at = ? WHERE id = ? AND (maxuses = 0 OR maxuses IS NULL OR maxuses > used)',
[date('Y-m-d H:i:s'), $promo->id]
);
if ($affectedRows === 0) {
throw new \FOSSBilling\InformationException('This promo code has reached its maximum number of uses.');
}
$this->getProductService()->usePromo($promo);
}
public function findActivePromoByCode($code)
{
return $this->di['db']->findOne('Promo', 'code = :code AND active = 1 ORDER BY id ASC', [':code' => $code]);
return $this->getProductService()->findActivePromoByCode($code);
}
/**
@@ -842,47 +767,24 @@ class Service implements InjectionAwareInterface
*/
protected function getRelatedItemsDiscount(\Model_Cart $cart, \Model_CartProduct $model)
{
$product = $this->di['db']->load('Product', $model->product_id);
$product->setDi($this->di);
$repo = $product->getTable();
$config = $this->getItemConfig($model);
$discount = 0;
if (method_exists($repo, 'getRelatedDiscount')) {
$list = [];
$products = $this->getCartProducts($cart);
foreach ($products as $p) {
$item = $this->di['db']->toArray($p);
$item['config'] = $this->getItemConfig($p);
$list[] = $item;
}
$discount = $repo->getRelatedDiscount($list, $product, $config);
$list = [];
$products = $this->getCartProducts($cart);
foreach ($products as $p) {
$item = $this->di['db']->toArray($p);
$item['config'] = $this->getItemConfig($p);
$list[] = $item;
}
return $discount;
return $this->getProductService()->getRelatedProductDiscountByProductId((int) $model->product_id, $list, $config);
}
private function getItemTitle(\Model_CartProduct $model)
protected function getItemPromoDiscount(\Model_CartProduct $model, Promo $promo)
{
$product = $this->di['db']->load('Product', $model->product_id);
$product->setDi($this->di);
$config = $this->getItemConfig($model);
$service = $product->getService();
if (method_exists($service, 'getCartProductTitle')) {
return $service->getCartProductTitle($product, $config);
}
return $product->title;
}
protected function getItemPromoDiscount(\Model_CartProduct $model, \Model_Promo $promo)
{
$product = $this->di['db']->load('Product', $model->product_id);
$product->setDi($this->di);
$repo = $this->di['mod_service']('product');
$config = $this->getItemConfig($model);
return $repo->getProductDiscount($product, $promo, $config);
return $this->getProductService()->getProductDiscountById((int) $model->product_id, $promo, $config);
}
public function getItemConfig(\Model_CartProduct $model)
@@ -890,16 +792,28 @@ class Service implements InjectionAwareInterface
return json_decode($model->config ?? '', true) ?? [];
}
private function getProductService(): \Box\Mod\Product\Service
{
return $this->di['mod_service']('Product');
}
private function getProductId(Product $product): int
{
return (int) $product->getId();
}
private function getProductTitle(Product $product): string
{
return (string) $product->getTitle();
}
public function cartProductToApiArray(\Model_CartProduct $model): array
{
$product = $this->di['db']->load('Product', $model->product_id);
$product->setDi($this->di);
$repo = $product->getTable();
$config = $this->getItemConfig($model);
$line = $repo->getOrderLineConfig($product, $config);
$setup = $line['setup_price'];
$price = $line['price'];
$qty = $line['quantity'];
$productView = $this->getProductService()->getCartProductViewData($model);
$config = $productView['config'];
$setup = $productView['setup_price'];
$price = $productView['price'];
$qty = $productView['quantity'];
[$discount_price, $discount_setup] = $this->getProductDiscount($model, $setup);
@@ -913,12 +827,12 @@ class Service implements InjectionAwareInterface
return array_merge($config, [
'id' => $model->id,
'product_id' => $product->id,
'form_id' => $product->form_id,
'title' => $this->getItemTitle($model),
'type' => $product->type,
'product_id' => $productView['product_id'],
'form_id' => $productView['form_id'],
'title' => $productView['title'],
'type' => $productView['type'],
'quantity' => $qty,
'unit' => $repo->getUnit($product),
'unit' => $productView['unit'],
'price' => $price,
'setup_price' => $setup,
'discount' => $discount_total,
@@ -934,11 +848,11 @@ class Service implements InjectionAwareInterface
$discount_price = $this->getRelatedItemsDiscount($cart, $cartProduct);
$discount_setup = 0; // discount for setup price
if ($cart->promo_id) {
$promo = $this->di['db']->getExistingModelById('Promo', $cart->promo_id, 'Promo not found');
$promo = $this->getProductService()->findPromoById((int) $cart->promo_id);
// Promo discount should override related item discount
$discount_price = $this->getItemPromoDiscount($cartProduct, $promo);
if ($promo->freesetup) {
if ($promo->isFreeSetup()) {
$discount_setup = $setup;
}
}
+157 -221
View File
@@ -10,16 +10,32 @@
declare(strict_types=1);
use Box\Mod\Cart\Api\Guest;
use Box\Mod\Cart\Service;
use Box\Mod\Currency\Entity\Currency;
use Box\Mod\Currency\Repository\CurrencyRepository;
use Box\Mod\Currency\Service as CurrencyService;
use Box\Mod\Product\Entity\Product;
use Box\Mod\Product\Entity\Promo;
use Box\Mod\Product\Service as ProductService;
use function Tests\Helpers\container;
test('get cart', function (): void {
$guestApi = new Box\Mod\Cart\Api\Guest();
$api = new Box\Mod\Cart\Api\Guest();
$serviceMock = Mockery::mock(Box\Mod\Cart\Service::class)->makePartial();
$serviceMock->shouldReceive('getSessionCart')->atLeast()->once()
->andReturn(new Model_Cart());
$serviceMock->shouldReceive('toApiArray')->atLeast()->once()
->andReturn([]);
function getAllowedRateLimiter(): object
{
return new class {
public function consumeOrThrow(string $policy, string $subject, int $tokens = 1): FOSSBilling\Security\RateLimitResult
{
return new FOSSBilling\Security\RateLimitResult($policy, false, 10, 9);
}
};
}
test('get returns array', function (): void {
$guestApi = new Guest();
$serviceMock = Mockery::mock(Service::class)->makePartial();
$serviceMock->shouldReceive('getSessionCart')->atLeast()->once()->andReturn(new Model_Cart());
$serviceMock->shouldReceive('toApiArray')->atLeast()->once()->andReturn([]);
$guestApi->setService($serviceMock);
@@ -28,14 +44,11 @@ test('get cart', function (): void {
expect($result)->toBeArray();
});
test('reset cart', function (): void {
$guestApi = new Box\Mod\Cart\Api\Guest();
$api = new Box\Mod\Cart\Api\Guest();
$serviceMock = Mockery::mock(Box\Mod\Cart\Service::class)->makePartial();
$serviceMock->shouldReceive('getSessionCart')->atLeast()->once()
->andReturn(new Model_Cart());
$serviceMock->shouldReceive('resetCart')->atLeast()->once()
->andReturn(true);
test('reset returns true', function (): void {
$guestApi = new Guest();
$serviceMock = Mockery::mock(Service::class)->makePartial();
$serviceMock->shouldReceive('getSessionCart')->atLeast()->once()->andReturn(new Model_Cart());
$serviceMock->shouldReceive('resetCart')->atLeast()->once()->andReturn(true);
$guestApi->setService($serviceMock);
@@ -44,29 +57,25 @@ test('reset cart', function (): void {
expect($result)->toBeTrue();
});
test('set currency', function (): void {
$guestApi = new Box\Mod\Cart\Api\Guest();
$api = new Box\Mod\Cart\Api\Guest();
$serviceMock = Mockery::mock(Box\Mod\Cart\Service::class)->makePartial();
$serviceMock->shouldReceive('getSessionCart')->atLeast()->once()
->andReturn(new Model_Cart());
$serviceMock->shouldReceive('changeCartCurrency')->atLeast()->once()
->andReturn(true);
test('setCurrency returns true', function (): void {
$guestApi = new Guest();
$serviceMock = Mockery::mock(Service::class)->makePartial();
$serviceMock->shouldReceive('getSessionCart')->atLeast()->once()->andReturn(new Model_Cart());
$serviceMock->shouldReceive('changeCartCurrency')->atLeast()->once()->andReturn(true);
$currencyStub = $this->createStub('\\' . Box\Mod\Currency\Entity\Currency::class);
$validatorMock = Mockery::mock(FOSSBilling\Validate::class)->shouldIgnoreMissing();
$currencyRepositoryMock = Mockery::mock('\\' . Box\Mod\Currency\Repository\CurrencyRepository::class);
$currencyRepositoryMock
->shouldReceive('findOneByCode')
->atLeast()->once()
->andReturn($currencyStub);
$currencyMock = Mockery::mock(Currency::class)->shouldIgnoreMissing();
$currencyServiceMock = Mockery::mock('\\' . Box\Mod\Currency\Service::class)->makePartial();
$currencyServiceMock->shouldReceive('getCurrencyRepository')->atLeast()->once()
->andReturn($currencyRepositoryMock);
$currencyRepositoryMock = Mockery::mock(CurrencyRepository::class)->makePartial();
$currencyRepositoryMock->shouldReceive('findOneByCode')->atLeast()->once()->andReturn($currencyMock);
$currencyServiceMock = Mockery::mock(CurrencyService::class)->makePartial();
$currencyServiceMock->shouldReceive('getCurrencyRepository')->atLeast()->once()->andReturn($currencyRepositoryMock);
$di = container();
$di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $currencyServiceMock);
$di['validator'] = $validatorMock;
$di['mod_service'] = $di->protect(fn () => $currencyServiceMock);
$guestApi->setDi($di);
$guestApi->setService($serviceMock);
@@ -79,27 +88,23 @@ test('set currency', function (): void {
expect($result)->toBeTrue();
});
test('set currency throws not found exception when currency does not exist', function (): void {
$guestApi = new Box\Mod\Cart\Api\Guest();
$api = new Box\Mod\Cart\Api\Guest();
$serviceMock = Mockery::mock(Box\Mod\Cart\Service::class)->makePartial();
$serviceMock->shouldReceive('getSessionCart')
->andReturn(new Model_Cart());
$serviceMock->shouldReceive('changeCartCurrency')
->andReturn(true);
test('setCurrency throws exception when currency is not found', function (): void {
$guestApi = new Guest();
$serviceMock = Mockery::mock(Service::class)->makePartial();
$serviceMock->shouldNotReceive('getSessionCart');
$serviceMock->shouldNotReceive('changeCartCurrency');
$currencyRepositoryMock = Mockery::mock('\\' . Box\Mod\Currency\Repository\CurrencyRepository::class);
$currencyRepositoryMock
->shouldReceive('findOneByCode')
->atLeast()->once()
->andReturn(null);
$validatorMock = Mockery::mock(FOSSBilling\Validate::class)->shouldIgnoreMissing();
$currencyServiceMock = Mockery::mock('\\' . Box\Mod\Currency\Service::class)->makePartial();
$currencyServiceMock->shouldReceive('getCurrencyRepository')->atLeast()->once()
->andReturn($currencyRepositoryMock);
$currencyRepositoryMock = Mockery::mock(CurrencyRepository::class)->makePartial();
$currencyRepositoryMock->shouldReceive('findOneByCode')->atLeast()->once()->andReturn(null);
$currencyServiceMock = Mockery::mock(CurrencyService::class)->makePartial();
$currencyServiceMock->shouldReceive('getCurrencyRepository')->atLeast()->once()->andReturn($currencyRepositoryMock);
$di = container();
$di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $currencyServiceMock);
$di['validator'] = $validatorMock;
$di['mod_service'] = $di->protect(fn () => $currencyServiceMock);
$guestApi->setDi($di);
$guestApi->setService($serviceMock);
@@ -108,118 +113,85 @@ test('set currency throws not found exception when currency does not exist', fun
'currency' => 'EUR',
];
$this->expectException(FOSSBilling\Exception::class);
$this->expectExceptionMessage('Currency not found');
$guestApi->set_currency($data);
expect(fn () => $guestApi->set_currency($data))->toThrow(FOSSBilling\Exception::class, 'Currency not found');
});
test('get currency', function (): void {
$guestApi = new Box\Mod\Cart\Api\Guest();
$api = new Box\Mod\Cart\Api\Guest();
test('getCurrency returns array when currency found', function (): void {
$guestApi = new Guest();
$cart = new Model_Cart();
$cart->loadBean(new Tests\Helpers\DummyBean());
$cart->currency_id = 1;
$serviceMock = Mockery::mock(Box\Mod\Cart\Service::class)->makePartial();
$serviceMock->shouldReceive('getSessionCart')->atLeast()->once()
->andReturn($cart);
$serviceMock = Mockery::mock(Service::class)->makePartial();
$serviceMock->shouldReceive('getSessionCart')->atLeast()->once()->andReturn($cart);
$currencyMock = Mockery::mock('\\' . Box\Mod\Currency\Entity\Currency::class);
$currencyMock
->shouldReceive('toApiArray')
->atLeast()->once()
->andReturn([]);
$currencyMock = Mockery::mock(Currency::class)->makePartial();
$currencyMock->shouldReceive('toApiArray')->atLeast()->once()->andReturn([]);
$currencyRepositoryMock = Mockery::mock('\\' . Box\Mod\Currency\Repository\CurrencyRepository::class);
$currencyRepositoryMock
->shouldReceive('find')
->atLeast()->once()
->andReturn($currencyMock);
$currencyRepositoryMock->shouldReceive('findDefault')->never();
$currencyRepositoryMock = Mockery::mock(CurrencyRepository::class)->makePartial();
$currencyRepositoryMock->shouldReceive('find')->atLeast()->once()->andReturn($currencyMock);
$currencyRepositoryMock->shouldNotReceive('findDefault');
$currencyServiceMock = Mockery::mock('\\' . Box\Mod\Currency\Service::class)->makePartial();
$currencyServiceMock->shouldReceive('getCurrencyRepository')->atLeast()->once()
->andReturn($currencyRepositoryMock);
$currencyServiceMock = Mockery::mock(CurrencyService::class)->makePartial();
$currencyServiceMock->shouldReceive('getCurrencyRepository')->atLeast()->once()->andReturn($currencyRepositoryMock);
$di = container();
$di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $currencyServiceMock);
$di['mod_service'] = $di->protect(fn () => $currencyServiceMock);
$guestApi->setDi($di);
$guestApi->setService($serviceMock);
$data = [
'currency' => 'EUR',
];
$result = $guestApi->get_currency();
expect($result)->toBeArray();
});
test('get currency not found returns default', function (): void {
$guestApi = new Box\Mod\Cart\Api\Guest();
$api = new Box\Mod\Cart\Api\Guest();
test('getCurrency returns default currency array when currency not found', function (): void {
$guestApi = new Guest();
$cart = new Model_Cart();
$cart->loadBean(new Tests\Helpers\DummyBean());
$cart->currency_id = 1;
$serviceMock = Mockery::mock(Box\Mod\Cart\Service::class)->makePartial();
$serviceMock->shouldReceive('getSessionCart')->atLeast()->once()
->andReturn($cart);
$serviceMock = Mockery::mock(Service::class)->makePartial();
$serviceMock->shouldReceive('getSessionCart')->atLeast()->once()->andReturn($cart);
$currencyMock = Mockery::mock('\\' . Box\Mod\Currency\Entity\Currency::class);
$currencyMock
->shouldReceive('toApiArray')
->atLeast()->once()
->andReturn([]);
$currencyMock = Mockery::mock(Currency::class)->makePartial();
$currencyMock->shouldReceive('toApiArray')->atLeast()->once()->andReturn([]);
$currencyRepositoryMock = Mockery::mock('\\' . Box\Mod\Currency\Repository\CurrencyRepository::class);
$currencyRepositoryMock
->shouldReceive('find')
->atLeast()->once()
->andReturn(null);
$currencyRepositoryMock
->shouldReceive('findDefault')
->atLeast()->once()
->andReturn($currencyMock);
$currencyRepositoryMock = Mockery::mock(CurrencyRepository::class)->makePartial();
$currencyRepositoryMock->shouldReceive('find')->atLeast()->once()->andReturn(null);
$currencyRepositoryMock->shouldReceive('findDefault')->atLeast()->once()->andReturn($currencyMock);
$currencyServiceMock = Mockery::mock('\\' . Box\Mod\Currency\Service::class)->makePartial();
$currencyServiceMock->shouldReceive('getCurrencyRepository')->atLeast()->once()
->andReturn($currencyRepositoryMock);
$currencyServiceMock = Mockery::mock(CurrencyService::class)->makePartial();
$currencyServiceMock->shouldReceive('getCurrencyRepository')->atLeast()->once()->andReturn($currencyRepositoryMock);
$di = container();
$di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $currencyServiceMock);
$di['mod_service'] = $di->protect(fn () => $currencyServiceMock);
$guestApi->setDi($di);
$guestApi->setService($serviceMock);
$data = [
'currency' => 'EUR',
];
$result = $guestApi->get_currency();
expect($result)->toBeArray();
});
test('apply promo', function (): void {
$guestApi = new Box\Mod\Cart\Api\Guest();
$api = new Box\Mod\Cart\Api\Guest();
test('applyPromo returns true', function (): void {
$guestApi = new Guest();
$cart = new Model_Cart();
$cart->loadBean(new Tests\Helpers\DummyBean());
$cart->currency_id = 1;
$promo = new Promo();
$serviceMock = Mockery::mock(Box\Mod\Cart\Service::class)->makePartial();
$serviceMock->shouldReceive('getSessionCart')->atLeast()->once()
->andReturn($cart);
$serviceMock->shouldReceive('applyPromo')->atLeast()->once()
->andReturn(true);
$serviceMock->shouldReceive('findActivePromoByCode')->atLeast()->once()
->andReturn(new Model_Promo());
$serviceMock->shouldReceive('promoCanBeApplied')->atLeast()->once()
->andReturn(true);
$serviceMock->shouldReceive('isPromoAvailableForClientGroup')->atLeast()->once()
->andReturn(true);
$serviceMock = Mockery::mock(Service::class)->makePartial();
$serviceMock->shouldReceive('getSessionCart')->atLeast()->once()->andReturn($cart);
$serviceMock->shouldReceive('applyPromo')->atLeast()->once()->andReturn(true);
$serviceMock->shouldReceive('findActivePromoByCode')->atLeast()->once()->andReturn($promo);
$serviceMock->shouldReceive('promoCanBeApplied')->atLeast()->once()->andReturn(true);
$serviceMock->shouldReceive('isPromoAvailableForClientGroup')->atLeast()->once()->andReturn(true);
$di = container();
$di['rate_limiter'] = getAllowedRateLimiter();
$guestApi->setDi($di);
$guestApi->setService($serviceMock);
@@ -232,26 +204,21 @@ test('apply promo', function (): void {
expect($result)->toBeTrue();
});
test('apply promo not found exception', function (): void {
$guestApi = new Box\Mod\Cart\Api\Guest();
$api = new Box\Mod\Cart\Api\Guest();
test('applyPromo throws exception when promo not found', function (): void {
$guestApi = new Guest();
$cart = new Model_Cart();
$cart->loadBean(new Tests\Helpers\DummyBean());
$cart->currency_id = 1;
$serviceMock = Mockery::mock(Box\Mod\Cart\Service::class)->makePartial();
$serviceMock->shouldReceive('getSessionCart')
->andReturn($cart);
$serviceMock->shouldReceive('applyPromo')
->andReturn(true);
$serviceMock->shouldReceive('findActivePromoByCode')->atLeast()->once()
->andReturn(null);
$serviceMock->shouldReceive('promoCanBeApplied')
->andReturn(true);
$serviceMock->shouldReceive('isPromoAvailableForClientGroup')
->andReturn(true);
$serviceMock = Mockery::mock(Service::class)->makePartial();
$serviceMock->shouldNotReceive('getSessionCart');
$serviceMock->shouldNotReceive('applyPromo');
$serviceMock->shouldReceive('findActivePromoByCode')->atLeast()->once()->andReturn(null);
$serviceMock->shouldNotReceive('promoCanBeApplied');
$serviceMock->shouldNotReceive('isPromoAvailableForClientGroup');
$di = container();
$di['rate_limiter'] = getAllowedRateLimiter();
$guestApi->setDi($di);
$guestApi->setService($serviceMock);
@@ -260,31 +227,26 @@ test('apply promo not found exception', function (): void {
'promocode' => 'CODE',
];
$this->expectException(FOSSBilling\InformationException::class);
$this->expectExceptionMessage('The promo code has expired or does not exist');
$guestApi->apply_promo($data);
expect(fn () => $guestApi->apply_promo($data))
->toThrow(FOSSBilling\InformationException::class, 'The promo code has expired or does not exist');
});
test('apply promo can not be applied', function (): void {
$guestApi = new Box\Mod\Cart\Api\Guest();
$api = new Box\Mod\Cart\Api\Guest();
test('applyPromo throws exception when promo cannot be applied', function (): void {
$guestApi = new Guest();
$cart = new Model_Cart();
$cart->loadBean(new Tests\Helpers\DummyBean());
$cart->currency_id = 1;
$promo = new Promo();
$serviceMock = Mockery::mock(Box\Mod\Cart\Service::class)->makePartial();
$serviceMock->shouldReceive('getSessionCart')
->andReturn($cart);
$serviceMock->shouldReceive('applyPromo')
->andReturn(true);
$serviceMock->shouldReceive('findActivePromoByCode')->atLeast()->once()
->andReturn(new Model_Promo());
$serviceMock->shouldReceive('isPromoAvailableForClientGroup')->atLeast()->once()
->andReturn(true);
$serviceMock->shouldReceive('promoCanBeApplied')->atLeast()->once()
->andReturn(false);
$serviceMock = Mockery::mock(Service::class)->makePartial();
$serviceMock->shouldNotReceive('getSessionCart');
$serviceMock->shouldNotReceive('applyPromo');
$serviceMock->shouldReceive('findActivePromoByCode')->atLeast()->once()->andReturn($promo);
$serviceMock->shouldReceive('isPromoAvailableForClientGroup')->atLeast()->once()->andReturn(true);
$serviceMock->shouldReceive('promoCanBeApplied')->atLeast()->once()->andReturn(false);
$di = container();
$di['rate_limiter'] = getAllowedRateLimiter();
$guestApi->setDi($di);
$guestApi->setService($serviceMock);
@@ -293,29 +255,25 @@ test('apply promo can not be applied', function (): void {
'promocode' => 'CODE',
];
$this->expectException(FOSSBilling\InformationException::class);
$this->expectExceptionMessage('The promo code has expired or does not exist');
$guestApi->apply_promo($data);
expect(fn () => $guestApi->apply_promo($data))
->toThrow(FOSSBilling\InformationException::class, 'The promo code has expired or does not exist');
});
test('apply promo can not be applied for user', function (): void {
$guestApi = new Box\Mod\Cart\Api\Guest();
$api = new Box\Mod\Cart\Api\Guest();
test('applyPromo throws exception when promo cannot be applied for user', function (): void {
$guestApi = new Guest();
$cart = new Model_Cart();
$cart->loadBean(new Tests\Helpers\DummyBean());
$cart->currency_id = 1;
$promo = new Promo();
$serviceMock = Mockery::mock(Box\Mod\Cart\Service::class)->makePartial();
$serviceMock->shouldReceive('getSessionCart')
->andReturn($cart);
$serviceMock->shouldReceive('applyPromo')
->andReturn(true);
$serviceMock->shouldReceive('findActivePromoByCode')->atLeast()->once()
->andReturn(new Model_Promo());
$serviceMock->shouldReceive('isPromoAvailableForClientGroup')->atLeast()->once()
->andReturn(false);
$serviceMock = Mockery::mock(Service::class)->makePartial();
$serviceMock->shouldNotReceive('getSessionCart');
$serviceMock->shouldNotReceive('applyPromo');
$serviceMock->shouldReceive('findActivePromoByCode')->atLeast()->once()->andReturn($promo);
$serviceMock->shouldReceive('isPromoAvailableForClientGroup')->atLeast()->once()->andReturn(false);
$di = container();
$di['rate_limiter'] = getAllowedRateLimiter();
$guestApi->setDi($di);
$guestApi->setService($serviceMock);
@@ -324,23 +282,19 @@ test('apply promo can not be applied for user', function (): void {
'promocode' => 'CODE',
];
$this->expectException(FOSSBilling\InformationException::class);
$this->expectExceptionMessage('Promo code cannot be applied to your account');
$guestApi->apply_promo($data);
expect(fn () => $guestApi->apply_promo($data))
->toThrow(FOSSBilling\InformationException::class, 'Promo code cannot be applied to your account');
});
test('remove promo', function (): void {
$guestApi = new Box\Mod\Cart\Api\Guest();
$api = new Box\Mod\Cart\Api\Guest();
test('removePromo returns true', function (): void {
$guestApi = new Guest();
$cart = new Model_Cart();
$cart->loadBean(new Tests\Helpers\DummyBean());
$cart->currency_id = 1;
$serviceMock = Mockery::mock(Box\Mod\Cart\Service::class)->makePartial();
$serviceMock->shouldReceive('getSessionCart')->atLeast()->once()
->andReturn($cart);
$serviceMock->shouldReceive('removePromo')->atLeast()->once()
->andReturn(true);
$serviceMock = Mockery::mock(Service::class)->makePartial();
$serviceMock->shouldReceive('getSessionCart')->atLeast()->once()->andReturn($cart);
$serviceMock->shouldReceive('removePromo')->atLeast()->once()->andReturn(true);
$guestApi->setService($serviceMock);
@@ -349,18 +303,15 @@ test('remove promo', function (): void {
expect($result)->toBeTrue();
});
test('remove item', function (): void {
$guestApi = new Box\Mod\Cart\Api\Guest();
$api = new Box\Mod\Cart\Api\Guest();
test('removeItem returns true', function (): void {
$guestApi = new Guest();
$cart = new Model_Cart();
$cart->loadBean(new Tests\Helpers\DummyBean());
$cart->currency_id = 1;
$serviceMock = Mockery::mock(Box\Mod\Cart\Service::class)->makePartial();
$serviceMock->shouldReceive('getSessionCart')->atLeast()->once()
->andReturn($cart);
$serviceMock->shouldReceive('removeProduct')->atLeast()->once()
->andReturn(true);
$serviceMock = Mockery::mock(Service::class)->makePartial();
$serviceMock->shouldReceive('getSessionCart')->atLeast()->once()->andReturn($cart);
$serviceMock->shouldReceive('removeProduct')->atLeast()->once()->andReturn(true);
$di = container();
$guestApi->setDi($di);
@@ -376,30 +327,23 @@ test('remove item', function (): void {
expect($result)->toBeTrue();
});
test('add item', function (): void {
$guestApi = new Box\Mod\Cart\Api\Guest();
$api = new Box\Mod\Cart\Api\Guest();
test('addItem returns true when multiple is true', function (): void {
$guestApi = new Guest();
$cart = new Model_Cart();
$cart->loadBean(new Tests\Helpers\DummyBean());
$cart->currency_id = 1;
$product = new Product();
$product->setIsAddon(false);
$serviceMock = Mockery::mock(Box\Mod\Cart\Service::class)->makePartial();
$serviceMock->shouldReceive('getSessionCart')->atLeast()->once()
->andReturn($cart);
$serviceMock->shouldReceive('addItem')->atLeast()->once()
->andReturn(true);
$serviceMock = Mockery::mock(Service::class)->makePartial();
$serviceMock->shouldReceive('getSessionCart')->atLeast()->once()->andReturn($cart);
$serviceMock->shouldReceive('addItem')->atLeast()->once()->andReturn(true);
$productModel = new Model_Product();
$productModel->loadBean(new Tests\Helpers\DummyBean());
$dbMock = Mockery::mock('\Box_Database');
$dbMock
->shouldReceive('getExistingModelById')
->atLeast()->once()
->andReturn($productModel);
$productServiceMock = Mockery::mock(ProductService::class);
$productServiceMock->shouldReceive('findOneActiveById')->once()->with(1)->andReturn($product);
$di = container();
$di['db'] = $dbMock;
$di['mod_service'] = $di->protect(fn () => $productServiceMock);
$guestApi->setDi($di);
@@ -415,34 +359,26 @@ test('add item', function (): void {
expect($result)->toBeTrue();
});
test('add item single resets cart', function (): void {
$guestApi = new Box\Mod\Cart\Api\Guest();
$api = new Box\Mod\Cart\Api\Guest();
test('addItem returns true when multiple is false', function (): void {
$guestApi = new Guest();
$cart = new Model_Cart();
$cart->loadBean(new Tests\Helpers\DummyBean());
$cart->currency_id = 1;
$product = new Product();
$product->setIsAddon(false);
$serviceMock = Mockery::mock(Box\Mod\Cart\Service::class)->makePartial();
$serviceMock->shouldReceive('getSessionCart')->atLeast()->once()
->andReturn($cart);
$serviceMock->shouldReceive('addItem')->atLeast()->once()
->andReturn(true);
$serviceMock = Mockery::mock(Service::class)->makePartial();
$serviceMock->shouldReceive('getSessionCart')->atLeast()->once()->andReturn($cart);
$serviceMock->shouldReceive('addItem')->atLeast()->once()->andReturn(true);
$apiMock = Mockery::mock(Box\Mod\Cart\Api\Guest::class)->makePartial();
$apiMock->shouldReceive('reset')->atLeast()->once()
->andReturn(true);
$apiMock = Mockery::mock(Guest::class)->makePartial();
$apiMock->shouldReceive('reset')->atLeast()->once()->andReturn(true);
$productModel = new Model_Product();
$productModel->loadBean(new Tests\Helpers\DummyBean());
$dbMock = Mockery::mock('\Box_Database');
$dbMock
->shouldReceive('getExistingModelById')
->atLeast()->once()
->andReturn($productModel);
$productServiceMock = Mockery::mock(ProductService::class);
$productServiceMock->shouldReceive('findOneActiveById')->once()->with(1)->andReturn($product);
$di = container();
$di['db'] = $dbMock;
$di['mod_service'] = $di->protect(fn () => $productServiceMock);
$apiMock->setDi($di);
$apiMock->setService($serviceMock);
@@ -0,0 +1,88 @@
<?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 Box\Mod\Cart\Service;
use Box\Mod\Product\Service as ProductService;
use function Tests\Helpers\container;
test('cartProductToApiArray uses resolved initial domain term pricing', function (): void {
$service = new Service();
$cart = new Model_Cart();
$cart->loadBean(new Tests\Helpers\DummyBean());
$cartProduct = new Model_CartProduct();
$cartProduct->loadBean(new Tests\Helpers\DummyBean());
$cartProduct->id = 10;
$cartProduct->cart_id = 20;
$cartProduct->product_id = 1;
$cartProduct->config = json_encode([
'action' => 'register',
'register_sld' => 'example',
'register_tld' => '.com',
'register_years' => 2,
'period' => '2Y',
]);
$db = Mockery::mock(Box_Database::class);
$db->shouldReceive('load')->once()->with('Cart', $cartProduct->cart_id)->andReturn($cart);
$db->shouldReceive('find')->once()->with('CartProduct', 'cart_id = :cart_id ORDER BY id ASC', [':cart_id' => $cart->id])->andReturn([]);
$productService = Mockery::mock(ProductService::class);
$productService->shouldReceive('getCartProductViewData')->once()->with($cartProduct)->andReturn([
'product_id' => 1,
'form_id' => 2,
'type' => 'domain',
'quantity' => 1,
'unit' => 'year',
'price' => 33.0,
'setup_price' => 0.0,
'title' => 'Domain example.com registration',
'config' => [
'action' => 'register',
'register_sld' => 'example',
'register_tld' => '.com',
'register_years' => 2,
'period' => '2Y',
],
]);
$productService->shouldReceive('getRelatedProductDiscountByProductId')
->once()
->with(1, [], [
'action' => 'register',
'register_sld' => 'example',
'register_tld' => '.com',
'register_years' => 2,
'period' => '2Y',
])
->andReturn(0.0);
$di = container();
$di['db'] = $db;
$di['mod_service'] = $di->protect(function (string $serviceName) use ($productService) {
if ($serviceName === 'Product') {
return $productService;
}
throw new RuntimeException('Unexpected service request');
});
$service->setDi($di);
$result = $service->cartProductToApiArray($cartProduct);
expect($result['quantity'])->toBe(1);
expect($result['price'])->toBe(33.0);
expect($result['total'])->toBe(33.0);
expect($result['title'])->toBe('Domain example.com registration');
expect($result['unit'])->toBe('year');
});
File diff suppressed because it is too large. Load diff
+31 -34
View File
@@ -354,19 +354,8 @@ class Service implements InjectionAwareInterface
// Ensure product IDs are safe integers before using in SQL
$productIds = array_values(array_filter($productIds, static fn ($id): bool => $id > 0));
$productsById = [];
if (!empty($productIds)) {
// Use parameter placeholders instead of directly interpolating IDs into the SQL string
$placeholders = implode(',', array_fill(0, count($productIds), '?'));
$products = $this->di['db']->find('Product', 'id IN (' . $placeholders . ')', $productIds);
// Re-index products by their ID for efficient lookup
foreach ($products as $product) {
if (isset($product->id)) {
$productsById[(int) $product->id] = $product;
}
}
}
$productService = $this->di['mod_service']('product');
$productsById = !empty($productIds) ? $productService->getProductSnapshotMap($productIds) : [];
foreach ($orders as $order) {
$productId = isset($order->product_id) ? (int) $order->product_id : 0;
@@ -378,8 +367,8 @@ class Service implements InjectionAwareInterface
];
if ($product) {
$orderData['product_name'] = $product->title;
$orderData['product_type'] = $product->type;
$orderData['product_name'] = $product['title'];
$orderData['product_type'] = $product['type'];
}
$result['orders'][] = $orderData;
@@ -568,6 +557,8 @@ class Service implements InjectionAwareInterface
$this->di['db']->store($invoice);
$this->countIncome($invoice);
$productService = $this->di['mod_service']('Product');
$productService->commitReservedPromoRedemptionsForInvoice($invoice);
$this->di['events_manager']->fire(['event' => 'onAfterAdminInvoicePaymentReceived', 'params' => ['id' => $invoice->id]]);
@@ -576,7 +567,7 @@ class Service implements InjectionAwareInterface
try {
$invoiceItemService->executeTask($item);
} catch (\Exception $e) {
error_log($e->getMessage());
$this->di['logger']->warning($e->getMessage());
}
}
}
@@ -724,7 +715,9 @@ class Service implements InjectionAwareInterface
$currencyCode = $currency->getCode();
$client->currency = $currencyCode;
$this->di['db']->store($client);
$this->di['logger']->warning("Client #{$client->id} currency was not defined. Set default currency {$currencyCode}.");
if (isset($this->di['logger'])) {
$this->di['logger']->info('Client #%s currency was not defined. Set default currency %s.', $client->id, $currencyCode);
}
}
$model = $this->di['db']->dispense('Invoice');
@@ -756,7 +749,7 @@ class Service implements InjectionAwareInterface
$this->approveInvoice($model, ['id' => $invoiceId]);
$this->di['logger']->info("Approved invoice {$invoiceId} instantly.");
} catch (\Exception $e) {
error_log($e->getMessage());
$this->di['logger']->warning($e->getMessage());
}
}
@@ -935,7 +928,7 @@ class Service implements InjectionAwareInterface
public function getTotal(\Model_Invoice $invoice): float
{
$total = 0;
$invoiceItems = $this->di['db']->find('InvoiceItem', 'invoice_id = ?', [$invoice->id]);
$invoiceItems = $this->di['db']->find('InvoiceItem', 'invoice_id = ?', [$invoice->id]) ?? [];
$invoiceItemService = $this->di['mod_service']('Invoice', 'InvoiceItem');
foreach ($invoiceItems as $item) {
$total += $invoiceItemService->getTotal($item);
@@ -1040,7 +1033,7 @@ class Service implements InjectionAwareInterface
case 'manual':
// @phpstan-ignore if.alwaysFalse
if (DEBUG) {
error_log('Refunds are managed manually. No actions performed.');
$this->di['logger']->warning('Refunds are managed manually. No actions performed.');
}
break;
@@ -1058,6 +1051,7 @@ class Service implements InjectionAwareInterface
public function updateInvoice(\Model_Invoice $model, array $data): bool
{
$invoiceItemService = $this->di['mod_service']('Invoice', 'InvoiceItem');
$previousStatus = $model->status;
$this->di['events_manager']->fire(['event' => 'onBeforeAdminInvoiceUpdate', 'params' => $data]);
@@ -1138,6 +1132,11 @@ class Service implements InjectionAwareInterface
$this->di['db']->store($model);
if ($previousStatus === \Model_Invoice::STATUS_UNPAID && $model->status === \Model_Invoice::STATUS_CANCELED) {
$productService = $this->di['mod_service']('Product');
$productService->releaseReservedPromoRedemptionsForInvoice($model, 'invoice_canceled');
}
$this->di['events_manager']->fire(['event' => 'onAfterAdminInvoiceUpdate', 'params' => $this->toApiArray($model)]);
$this->di['logger']->info("Updated invoice {$model->id}.");
@@ -1147,6 +1146,9 @@ class Service implements InjectionAwareInterface
public function rmInvoice(\Model_Invoice $model): bool
{
$productService = $this->di['mod_service']('Product');
$productService->releaseReservedPromoRedemptionsForInvoice($model, 'invoice_deleted');
// remove related invoice from orders
$sql = '
UPDATE client_order
@@ -1202,7 +1204,7 @@ class Service implements InjectionAwareInterface
} catch (\Exception $e) {
// @phpstan-ignore if.alwaysFalse
if (DEBUG) {
error_log($e->getMessage());
$this->di['logger']->warning($e->getMessage());
}
}
}
@@ -1248,12 +1250,11 @@ class Service implements InjectionAwareInterface
\Model_ClientOrder::STATUS_FAILED_RENEW,
\Model_ClientOrder::STATUS_SUSPENDED,
], true)) {
$product = $this->di['db']->getExistingModelById('Product', $order->product_id, 'Product not found');
$product->setDi($this->di);
$repo = $product->getTable();
$productService = $this->di['mod_service']('Product');
$product = $productService->findProductById((int) $order->product_id);
$config = json_decode($order->config ?? '', true) ?? [];
if (method_exists($repo, 'getRenewalLineConfig')) {
if ($productService instanceof \Box\Mod\Product\Service) {
$currencyService = $this->di['mod_service']('Currency');
$currencyRepository = $currencyService->getCurrencyRepository();
$rate = $currencyRepository->getRateByCode($order->currency);
@@ -1261,7 +1262,7 @@ class Service implements InjectionAwareInterface
throw new \FOSSBilling\Exception("Currency rate for '{$order->currency}' is not configured");
}
$renewalLine = $repo->getRenewalLineConfig($product, $config);
$renewalLine = $productService->getProductRenewalLineConfig($product, $config);
$price = $renewalLine['price'] * $rate;
$line = [
'price' => $price,
@@ -1318,7 +1319,7 @@ class Service implements InjectionAwareInterface
$invoice = $this->generateForOrder($model);
$this->approveInvoice($invoice, ['id' => $invoice->id, 'use_credits' => true]);
} catch (\Exception $e) {
error_log($e->getMessage());
$this->di['logger']->warning($e->getMessage());
}
}
@@ -1765,13 +1766,9 @@ class Service implements InjectionAwareInterface
{
$invoices = $this->di['db']->find('Invoice', 'client_id = ?', [$client->id]);
foreach ($invoices as $invoice) {
$invoiceItems = $this->di['db']->find('InvoiceItem', 'invoice_id = ?', [$invoice->id]);
foreach ($invoiceItems as $invoiceItem) {
$this->di['db']->trash($invoiceItem);
if ($invoice instanceof \Model_Invoice) {
$this->rmInvoice($invoice);
}
$this->di['db']->trash($invoice);
}
}
@@ -2132,7 +2129,7 @@ class Service implements InjectionAwareInterface
return $invoice;
} catch (\Exception $e) {
error_log('Failed to generate renewal invoice for subscription payment: ' . $e->getMessage());
$this->di['logger']->warning('Failed to generate renewal invoice for subscription payment: ' . $e->getMessage());
return null;
}
+18 -53
View File
@@ -63,8 +63,8 @@ class ServiceInvoiceItem implements InjectionAwareInterface
$orderService = $this->di['mod_service']('Order');
switch ($item->task) {
case \Model_InvoiceItem::TASK_ACTIVATE:
$product = $this->di['db']->getExistingModelById('Product', $order->product_id);
if ($product->setup == \Model_Product::SETUP_AFTER_PAYMENT) {
$product = $this->di['mod_service']('Product')->findProductById((int) $order->product_id);
if ($product->getSetup() == \Box\Mod\Product\Service::SETUP_AFTER_PAYMENT) {
try {
$orderService->activateOrder($order);
} catch (\Exception $e) {
@@ -311,36 +311,12 @@ class ServiceInvoiceItem implements InjectionAwareInterface
$corderService->setUnpaidInvoice($order, $proforma);
// apply discount for new invoice if promo code is recurrent
if ($order->promo_recurring) {
$order_total = $price * $quantity;
$promo_discount = $order->discount;
$product = $this->di['db']->getExistingModelById('Product', $order->product_id, 'Product not found');
if ($product->type === \Model_ProductTable::DOMAIN && $order->promo_id) {
$promo = $this->di['db']->getExistingModelById('Promo', $order->promo_id, 'Promo not found');
$productService = $this->di['mod_service']('Product');
$config = json_decode($order->config ?? '', true) ?? [];
$promo_discount = $productService->getRenewalProductDiscount($product, $promo, $config);
$currencyService = $this->di['mod_service']('Currency');
$currencyRepository = $currencyService->getCurrencyRepository();
$rate = $currencyRepository->getRateByCode($order->currency);
if ($rate === null) {
throw new \FOSSBilling\Exception("Currency conversion rate cannot be determined for code {$order->currency}");
}
$promo_discount *= $rate;
}
if ($promo_discount > $order_total) {
$promo_discount = $order_total;
}
$discount_title = $this->_getTitleForPromoDiscount($order->promo_id, $order->currency);
$productService = $this->di['mod_service']('Product');
$promoAdjustment = $productService->getRenewalPromoAdjustment($order, (float) $price, (float) $quantity);
if ($promoAdjustment !== null) {
$pd = [
'title' => $discount_title,
'price' => $promo_discount * -1,
'title' => $promoAdjustment['title'],
'price' => $promoAdjustment['discount_amount'] * -1,
'quantity' => 1,
'unit' => 'discount',
'rel_id' => $order->id,
@@ -348,28 +324,17 @@ class ServiceInvoiceItem implements InjectionAwareInterface
];
$this->addNew($proforma, $pd);
++$order->promo_used;
$this->di['db']->store($order);
}
}
private function _getTitleForPromoDiscount($promo_id, $currency)
{
$promo = $this->di['db']->findOne('Promo', 'id = ?', [$promo_id]);
$api_guest = $this->di['api_guest'];
switch ($promo->type) {
case \Model_Promo::ABSOLUTE:
$currencyAmount = $api_guest->currency_format(['code' => $currency, 'price' => $promo->value]);
return __trans('Promotional Code: :code - :value Discount', [':code' => $promo->code, ':value' => $currencyAmount]);
case \Model_Promo::PERCENTAGE:
return __trans('Promotional Code: :code - :value%', [':code' => $promo->code, ':value' => $promo->value]);
default:
break;
$productService->createPromoRedemption(
$promoAdjustment['promo'],
$client,
$order,
$proforma,
\Box\Mod\Product\Entity\PromoRedemption::PHASE_RENEWAL,
$promoAdjustment['discount_amount'],
$promoAdjustment['currency'],
$proforma->created_at ?? date('Y-m-d H:i:s'),
\Box\Mod\Product\Entity\PromoRedemption::STATUS_RESERVED,
);
}
}
@@ -309,7 +309,7 @@
subscriptionBtn.hidden = true;
genericBtn.hidden = true;
{% if settings.prompt_subscription %}
{% if settings.prompt_subscription|default('0') %}
if(supportsSubscription && supportsOneTime && invoiceSubscribable){
document.getElementById('bodyText').textContent = `{{ 'The invoice you are paying and your chosen payment gateway both support subscription payments. What type of payment would you like to continue with?'|trans }}`;
subscriptionBtn.hidden = false;
@@ -13,7 +13,6 @@ declare(strict_types=1);
use Box\Mod\Client\Service as ClientService;
use Box\Mod\Invoice\ServiceInvoiceItem;
use Box\Mod\Invoice\ServiceTax;
use Box\Mod\System\Service as SystemService;
use function Tests\Helpers\container;
@@ -240,9 +239,6 @@ test('deletes a tax', function (): void {
test('creates a tax', function (): void {
$service = new ServiceTax();
$systemService = Mockery::mock(SystemService::class);
$systemService->shouldReceive('checkLimits')
->byDefault();
$taxModel = new Model_Tax();
$taxModel->loadBean(new Tests\Helpers\DummyBean());
@@ -256,7 +252,6 @@ test('creates a tax', function (): void {
->andReturn($newId);
$di = container();
$di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $systemService);
$di['db'] = $dbMock;
$di['logger'] = new Tests\Helpers\TestLogger();
$service->setDi($di);
+14 -6
View File
@@ -470,7 +470,8 @@ test('marks invoice as paid', function (): void {
->atLeast()->once();
$di = container();
$di['mod_service'] = $di->protect(function ($serviceName, $sub = '') use ($systemService, $itemInvoiceServiceMock, $currencyServiceMock) {
$productServiceMock = Mockery::mock(Box\Mod\Product\Service::class)->shouldIgnoreMissing();
$di['mod_service'] = $di->protect(function ($serviceName, $sub = '') use ($systemService, $itemInvoiceServiceMock, $currencyServiceMock, $productServiceMock) {
if ($serviceName == 'system') {
return $systemService;
}
@@ -480,6 +481,9 @@ test('marks invoice as paid', function (): void {
if ($serviceName == 'currency') {
return $currencyServiceMock;
}
if (strtolower($serviceName) == 'product') {
return $productServiceMock;
}
});
$di['db'] = $dbMock;
$di['events_manager'] = $eventManagerMock;
@@ -2202,11 +2206,15 @@ test('markAsPaid transitions a deposit invoice to paid status', function (): voi
$di = container();
$di['db'] = $dbMock;
$di['logger'] = new Tests\Helpers\TestLogger();
$di['mod_service'] = $di->protect(fn ($name, $sub = '') => match ([$name, $sub]) {
['system', ''] => $systemService,
['currency', ''] => $currencyService,
['Invoice', 'InvoiceItem'] => $invoiceItemService,
default => throw new RuntimeException("Unexpected service: {$name}/{$sub}"),
$productService = Mockery::mock(Box\Mod\Product\Service::class)->shouldIgnoreMissing();
$di['mod_service'] = $di->protect(function ($name, $sub = '') use ($systemService, $currencyService, $invoiceItemService, $productService) {
return match ([$name, $sub]) {
['system', ''] => $systemService,
['currency', ''] => $currencyService,
['Invoice', 'InvoiceItem'] => $invoiceItemService,
['Product', ''], ['product', ''] => $productService,
default => throw new RuntimeException("Unexpected service: {$name}/{$sub}"),
};
});
$di['events_manager'] = $eventsManager;
$service->setDi($di);
+4 -5
View File
@@ -104,8 +104,8 @@ class Admin extends \FOSSBilling\Api\AbstractApi
$this->getDi()['mod_service']('Invoice')->validateAdminMarkAsPaidRequest($data);
}
$client = $this->getDi()['db']->getExistingModelById('Client', $data['client_id'], 'Client not found');
$product = $this->getDi()['db']->getExistingModelById('Product', $data['product_id'], 'Product not found');
$client = $this->di['db']->getExistingModelById('Client', $data['client_id'], 'Client not found');
$product = $this->di['mod_service']('product')->findProductById((int) $data['product_id']);
return $this->getService()->createOrder($client, $product, $data);
}
@@ -303,12 +303,11 @@ class Admin extends \FOSSBilling\Api\AbstractApi
$order = $this->_getOrder($data);
if (!isset($data['config']) || !is_array($data['config'])) {
$config = $data['config'] ?? null;
if (!is_array($config)) {
throw new \FOSSBilling\Exception('Order config not passed');
}
$config = $data['config'];
return $this->getService()->updateOrderConfig($order, $config);
}
+2 -3
View File
@@ -97,10 +97,9 @@ class Client extends \FOSSBilling\Api\AbstractApi
public function upgradables($data)
{
$model = $this->_getOrder($data);
$product = $this->getDi()['db']->getExistingModelById('Product', $model->product_id);
$productService = $this->getDi()['mod_service']('product');
$productService = $this->di['mod_service']('product');
return $productService->getUpgradablePairs($product);
return $productService->getUpgradablePairsByProductId((int) $model->product_id);
}
/**
+102 -82
View File
@@ -13,6 +13,7 @@ declare(strict_types=1);
namespace Box\Mod\Order;
use Box\Mod\Currency\Entity\Currency;
use Box\Mod\Product\Entity\Product;
use FOSSBilling\InformationException;
use FOSSBilling\InjectionAwareInterface;
use Symfony\Component\HttpFoundation\Response;
@@ -230,16 +231,14 @@ class Service implements InjectionAwareInterface
public function getOrderService(\Model_ClientOrder $order)
{
if ($order->service_id !== null) {
// @deprecated
// @todo remove this when doctrine is removed
$core_services = [
\Model_ProductTable::CUSTOM,
\Model_ProductTable::LICENSE,
\Model_ProductTable::DOWNLOADABLE,
\Model_ProductTable::HOSTING,
\Model_ProductTable::DOMAIN,
$builtInServiceTypes = [
\Box\Mod\Product\Service::CUSTOM,
\Box\Mod\Product\Service::LICENSE,
\Box\Mod\Product\Service::DOWNLOADABLE,
\Box\Mod\Product\Service::HOSTING,
\Box\Mod\Product\Service::DOMAIN,
];
if (in_array($order->service_type, $core_services)) {
if (in_array($order->service_type, $builtInServiceTypes, true)) {
$repo_class = $this->_getServiceClassName($order);
return $this->di['db']->load($repo_class, $order->service_id);
@@ -279,9 +278,9 @@ class Service implements InjectionAwareInterface
return json_decode($model->config ?? '', true) ?? [];
}
public function productHasOrders(\Model_Product $product): bool
public function productHasOrders(Product $product): bool
{
$order = $this->di['db']->findOne('ClientOrder', 'product_id = :product_id', [':product_id' => $product->id]);
$order = $this->di['db']->findOne('ClientOrder', 'product_id = :product_id', [':product_id' => $product->getId()]);
return $order instanceof \Model_ClientOrder;
}
@@ -371,12 +370,8 @@ class Service implements InjectionAwareInterface
if ($identity instanceof \Model_Admin) {
$data['config'] = $this->getConfig($model);
$productModel = $this->di['db']->load('Product', $model->product_id);
if ($productModel instanceof \Model_Product) {
$data['plugin'] = $productModel->plugin;
} else {
$data['plugin'] = null;
}
$productService = $this->di['mod_service']('product');
$data['plugin'] = $productService->getProductPluginById((int) $model->product_id);
}
$client = $this->di['db']->getExistingModelById('Client', $model->client_id, 'Client not found');
@@ -451,14 +446,8 @@ class Service implements InjectionAwareInterface
$plugins = [];
if ($identity instanceof \Model_Admin && !empty($productIds)) {
$placeholders = implode(',', array_fill(0, count($productIds), '?'));
$productRows = $this->di['db']->getAll(
"SELECT id, plugin FROM product WHERE id IN ($placeholders)",
$productIds
);
foreach ($productRows as $row) {
$plugins[$row['id']] = $row['plugin'];
}
$productService = $this->di['mod_service']('product');
$plugins = $productService->getProductPluginMap($productIds);
}
$result = [];
@@ -520,6 +509,7 @@ class Service implements InjectionAwareInterface
$show_action_required = $data['show_action_required'] ?? null;
$id = $data['id'] ?? null;
$product_id = $data['product_id'] ?? null;
$promo_id = $data['promo_id'] ?? null;
$status = $data['status'] ?? null;
$title = $data['title'] ?? null;
$period = $data['period'] ?? null;
@@ -565,6 +555,11 @@ class Service implements InjectionAwareInterface
$bindings[':product_id'] = $product_id;
}
if ($promo_id) {
$where[] = 'co.promo_id = :promo_id';
$bindings[':promo_id'] = $promo_id;
}
if ($type) {
$where[] = 'co.service_type = :service_type';
$bindings[':service_type'] = $type;
@@ -634,7 +629,7 @@ class Service implements InjectionAwareInterface
return [$query, $bindings];
}
public function createOrder(\Model_Client $client, \Model_Product $product, array $data)
public function createOrder(\Model_Client $client, Product $product, array $data)
{
$currencyService = $this->di['mod_service']('currency');
/** @var \Box\Mod\Currency\Repository\CurrencyRepository $currencyRepository */
@@ -651,7 +646,7 @@ class Service implements InjectionAwareInterface
throw new \FOSSBilling\Exception('Currency could not be determined for order');
}
$this->di['events_manager']->fire(['event' => 'onBeforeAdminOrderCreate', 'params' => $data, 'subject' => $product->type]);
$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;
@@ -664,12 +659,12 @@ class Service implements InjectionAwareInterface
$cartService = $this->di['mod_service']('cart');
// check stock
if (!$cartService->isStockAvailable($product, $qty)) {
throw new InformationException('Product :id is out of stock.', [':id' => $product->id], 831);
throw new InformationException('Product :id is out of stock.', [':id' => $this->getProductId($product)], 831);
}
// Addons must have defined master order
$parent_order = false;
if ($product->is_addon && empty($group_id)) {
if ($this->isAddonProduct($product) && empty($group_id)) {
throw new \FOSSBilling\Exception('Group ID parameter is missing for addon product order', null, 832);
}
@@ -684,14 +679,7 @@ class Service implements InjectionAwareInterface
if ($period) {
$config['period'] = $period;
}
$se = $this->di['mod_service']('service' . $product->type);
// @deprecated logic
if (method_exists($se, 'prependOrderConfig')) {
$config = $se->prependOrderConfig($product, $config);
}
// @migration script
$se = $this->di['mod_service']('service' . $product->type);
$se = $this->di['mod_service']('service' . $this->getProductType($product));
if (method_exists($se, 'attachOrderConfig')) {
$config = $se->attachOrderConfig($product, $config);
}
@@ -727,14 +715,14 @@ class Service implements InjectionAwareInterface
) {
$order = $this->di['db']->dispense('ClientOrder');
$order->client_id = $client->id;
$order->product_id = $product->id;
$order->form_id = $product->form_id;
$order->product_id = $this->getProductId($product);
$order->form_id = $this->getProductFormId($product);
$order->group_id = ($parent_order) ? $parent_order->group_id : uniqid();
$order->group_master = ($parent_order) ? 0 : 1;
$order->title = $generatedOrderTitle ?? $data['title'] ?? $product->title;
$order->title = $generatedOrderTitle ?? $data['title'] ?? $this->getProductTitle($product);
$order->currency = $currency->getCode();
$order->service_type = $product->type;
$order->unit = $product->unit;
$order->service_type = $this->getProductType($product);
$order->unit = $this->getProductUnit($product);
$order->status = \Model_ClientOrder::STATUS_PENDING_SETUP;
$order->config = json_encode($config);
$order->invoice_option = $invoiceOption;
@@ -745,10 +733,9 @@ class Service implements InjectionAwareInterface
}
$line = null;
if (!isset($data['price']) || $product->type === \Model_Product::DOMAIN) {
$product->setDi($this->di);
$repo = $product->getTable();
$line = $repo->getOrderLineConfig($product, array_merge($config, ['quantity' => $qty]));
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]));
$order->quantity = $line['quantity'];
} else {
$order->quantity = $qty;
@@ -812,19 +799,19 @@ class Service implements InjectionAwareInterface
$invoiceService->markAsPaidByAdmin($invoice, $data);
}
} catch (\Exception $e) {
error_log($e->getMessage());
$this->di['logger']->info($e->getMessage());
try {
$invoiceService->addNote($invoice, 'Order was created, but invoice follow-up failed: ' . $e->getMessage());
} catch (\Exception $noteException) {
error_log($noteException->getMessage());
$this->di['logger']->info($noteException->getMessage());
}
}
}
$order = $this->di['db']->getExistingModelById('ClientOrder', $id, 'Order not found');
$this->di['events_manager']->fire(['event' => 'onAfterAdminOrderCreate', 'params' => ['id' => $order->id], 'subject' => $product->type]);
$this->di['events_manager']->fire(['event' => 'onAfterAdminOrderCreate', 'params' => ['id' => $order->id], 'subject' => $this->getProductType($product)]);
$this->di['logger']->info('Created order #%s', $id);
@@ -833,7 +820,7 @@ class Service implements InjectionAwareInterface
try {
$this->activateOrder($order);
} catch (\Exception $e) {
error_log($e->getMessage());
$this->di['logger']->info($e->getMessage());
}
}
@@ -868,7 +855,7 @@ class Service implements InjectionAwareInterface
$this->createFromOrder($addon);
$this->di['events_manager']->fire(['event' => 'onAfterAdminOrderActivate', 'params' => ['id' => $addon->id]]);
} catch (\Exception $e) {
error_log($e->getMessage());
$this->di['logger']->info($e->getMessage());
}
}
@@ -946,11 +933,11 @@ class Service implements InjectionAwareInterface
$order->updated_at = date('Y-m-d H:i:s');
$this->di['db']->store($order);
$productModel = $this->di['db']->load('Product', $order->product_id);
if ($productModel instanceof \Model_Product) {
$this->stockSale($productModel, $order->quantity);
if ($order->product_id) {
$productService = $this->di['mod_service']('product');
$productService->reduceStock((int) $order->product_id, $order->quantity);
} else {
error_log("Order without product ID detected Order #{$order->id}.");
$this->di['logger']->info("Order without product ID detected Order #{$order->id}.");
}
$this->saveStatusChange($order, 'Order activated');
@@ -966,17 +953,15 @@ class Service implements InjectionAwareInterface
protected function _callOnService(\Model_ClientOrder $order, $action)
{
$repo = $this->di['mod_service']('service' . $order->service_type);
// @deprecated
// @todo remove this when doctrine is removed
$core_services = [
\Model_ProductTable::CUSTOM,
\Model_ProductTable::LICENSE,
\Model_ProductTable::DOWNLOADABLE,
\Model_ProductTable::HOSTING,
\Model_ProductTable::DOMAIN,
$builtInServiceTypes = [
\Box\Mod\Product\Service::CUSTOM,
\Box\Mod\Product\Service::LICENSE,
\Box\Mod\Product\Service::DOWNLOADABLE,
\Box\Mod\Product\Service::HOSTING,
\Box\Mod\Product\Service::DOMAIN,
];
if (in_array($order->service_type, $core_services)) {
if (in_array($order->service_type, $builtInServiceTypes, true)) {
$m = 'action_' . $action;
if (!method_exists($repo, $m) || !is_callable([$repo, $m])) {
throw new \FOSSBilling\Exception('Service ' . $order->service_type . ' do not support ' . $m);
@@ -984,7 +969,7 @@ class Service implements InjectionAwareInterface
return $repo->$m($order);
}
// @new logic for services
$o = $this->di['db']->findOne(
'client_order',
'id = :id',
@@ -999,23 +984,16 @@ class Service implements InjectionAwareInterface
return $repo->$action($o, $service);
}
error_log("Service {$order->service_type} does not support action {$action}.");
$this->di['logger']->info("Service {$order->service_type} does not support action {$action}.");
return null;
}
public function stockSale(\Model_Product $product, $qty): bool
public function stockSale(Product|int $product, $qty): bool
{
if ($product->stock_control) {
if ($product->quantity_in_stock < $qty) {
throw new InformationException('Product :id is out of stock.', [':id' => $product->id], 831);
}
$product->quantity_in_stock -= $qty;
$product->updated_at = date('Y-m-d H:i:s');
$this->di['db']->store($product);
}
$productService = $this->di['mod_service']('product');
return true;
return $productService->reduceStock($product, $qty);
}
public function updatePeriod(\Model_ClientOrder $order, $period): int
@@ -1124,7 +1102,7 @@ class Service implements InjectionAwareInterface
try {
$this->renewFromOrder($addon);
} catch (\Exception $e) {
error_log($e->getMessage());
$this->di['logger']->info($e->getMessage());
}
}
}
@@ -1250,6 +1228,8 @@ class Service implements InjectionAwareInterface
$order->suspended_at = null;
$order->updated_at = date('Y-m-d H:i:s');
$this->di['db']->store($order);
$productService = $this->di['mod_service']('Product');
$productService->releaseReservedPromoRedemptionsForOrder($order, 'order_canceled');
$note = ($reason === null) ? 'Order canceled' : 'Canceled order for ' . $reason;
$this->saveStatusChange($order, $note);
@@ -1342,10 +1322,12 @@ class Service implements InjectionAwareInterface
if (!$forceDelete) {
throw $e;
}
error_log("{$e->getMessage()} in {$e->getFile()} : {$e->getFile()}");
$this->di['logger']->info("{$e->getMessage()} in {$e->getFile()} : {$e->getFile()}");
}
$id = $order->id;
$productService = $this->di['mod_service']('Product');
$productService->releaseReservedPromoRedemptionsForOrder($order, 'order_deleted');
$this->rmClientOrderStatusByOrder($order);
$this->rmOrder($order);
@@ -1379,7 +1361,7 @@ class Service implements InjectionAwareInterface
try {
$this->suspendFromOrder($order, $reason);
} catch (\Exception $e) {
error_log($e->getMessage());
$this->di['logger']->info($e->getMessage());
}
}
@@ -1422,7 +1404,7 @@ class Service implements InjectionAwareInterface
$order = $this->di['db']->getExistingModelById('ClientOrder', $orderArr['id'], 'Order not found');
$this->cancelFromOrder($order, $reason);
} catch (\Exception $e) {
error_log($e->getMessage());
$this->di['logger']->info($e->getMessage());
}
}
@@ -1558,13 +1540,13 @@ class Service implements InjectionAwareInterface
$orderId = $order->id;
$service = $this->getOrderService($order);
if (!is_object($service)) {
error_log("Order #{$orderId} has no active service.");
$this->di['logger']->info("Order #{$orderId} has no active service.");
return null;
}
$srepo = $this->di['mod_service']('service' . $order->service_type);
if (!method_exists($srepo, 'toApiArray')) {
error_log("Service #{$order->service_type} method toApiArray is missing.");
$this->di['logger']->info("Service #{$order->service_type} method toApiArray is missing.");
return null;
}
@@ -1614,6 +1596,14 @@ class Service implements InjectionAwareInterface
public function rmByClient(\Model_Client $client): void
{
$productService = $this->di['mod_service']('Product');
$orders = $this->di['db']->find('ClientOrder', 'client_id = ?', [$client->id]);
foreach ($orders as $order) {
if ($order instanceof \Model_ClientOrder) {
$productService->releaseReservedPromoRedemptionsForOrder($order, 'client_deleted');
}
}
$query = $this->di['dbal']->createQueryBuilder();
$query
->delete('client_order')
@@ -1630,4 +1620,34 @@ class Service implements InjectionAwareInterface
return $this->di['csv_response_factory']->create('client_order', 'orders.csv', $headers);
}
private function getProductId(Product $product): int
{
return (int) $product->getId();
}
private function getProductFormId(Product $product): ?int
{
return $product->getFormId();
}
private function getProductTitle(Product $product): string
{
return (string) $product->getTitle();
}
private function getProductType(Product $product): string
{
return (string) $product->getType();
}
private function getProductUnit(Product $product): string
{
return (string) $product->getUnit();
}
private function isAddonProduct(Product $product): bool
{
return $product->isAddon();
}
}
@@ -131,6 +131,12 @@
{{ mf.selectbox('product_id', admin.product_get_pairs, request.product_id, 0, 'All Products'|trans) }}
</div>
</div>
<div class="col-md-6 col-xl-4">
<div>
<label class="form-label text-muted small mb-1" for="promo_id">{{ 'Promo ID'|trans }}</label>
<input class="form-control" type="text" id="promo_id" name="promo_id" value="{{ request.promo_id }}">
</div>
</div>
<div class="col-md-6 col-xl-4">
<div>
<label class="form-label text-muted small mb-1" for="period">{{ 'Period'|trans }}</label>
+336 -290
View File
@@ -15,502 +15,558 @@ use Box\Mod\Order\Service;
use function Tests\Helpers\container;
test('gets dependency injection container', function (): void {
$api = new Admin();
$di = container();
$api->setDi($di);
$getDi = $api->getDi();
expect($getDi)->toBe($di);
});
test('gets an order', function (): void {
$api = new Admin();
$order = new Model_ClientOrder();
$order->loadBean(new Tests\Helpers\DummyBean());
$apiMock = Mockery::mock(Admin::class)->makePartial()->shouldAllowMockingProtectedMethods();
$apiMock->shouldReceive('_getOrder')
->atLeast()->once()
->andReturn($order);
$apiMock = Mockery::mock(Admin::class)->makePartial();
$apiMock->shouldAllowMockingProtectedMethods();
$apiMock->shouldReceive('_getOrder')->atLeast()->once()->andReturn($order);
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('toApiArray')
->atLeast()->once()
->andReturn([]);
$serviceMock->shouldReceive('toApiArray')->atLeast()->once()->andReturn([]);
$apiMock->setService($serviceMock);
$data = ['id' => 1];
$result = $apiMock->get($data);
expect($result)->toBeArray();
});
test('gets order list', function (): void {
test('gets list of orders', function (): void {
$api = new Admin();
$identity = new Model_Admin();
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('getSearchQuery')
->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();
$serviceMock->shouldReceive('getSearchQuery')->atLeast()->once()->andReturn(['query', []]);
$serviceMock->shouldReceive('getBatchForApi')->atLeast()->once()->andReturn([]);
$paginatorMock = Mockery::mock(FOSSBilling\Pagination::class);
$paginatorMock->shouldReceive('getPaginatedResultSet')
->once()
->andReturn([
'list' => [
['id' => 3],
['id' => 2],
['id' => 1],
],
'total' => 3,
'pages' => 1,
'page' => 1,
'per_page' => 25,
]);
$paginatorMock->shouldReceive('getPaginatedResultSet')->atLeast()->once()->andReturn(['list' => []]);
$modMock = Mockery::mock(FOSSBilling\Module::class);
$modMock->shouldReceive('getConfig')
->once()
->andReturn(['show_addons' => 0]);
$modMock->shouldReceive('getConfig')->atLeast()->once()->andReturn(['show_addons' => 0]);
$di = container();
$di['pager'] = $paginatorMock;
$di['mod'] = $di->protect(fn () => $modMock);
$di['mod'] = $di->protect(fn (): Mockery\MockInterface => $modMock);
$api->setDi($di);
$api->setService($serviceMock);
$api->setIdentity($identity);
$result = $api->get_list([]);
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);
expect($result)->toBeArray();
});
test('creates an order', function (): void {
$api = new Admin();
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('createOrder')
->atLeast()->once()
->andReturn(1);
$dbMock = Mockery::mock('\Box_Database');
$dbMock->shouldReceive('getExistingModelById')
->times(2)
->andReturn(new Model_Client(), new Model_Product());
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('createOrder')->atLeast()->once()->andReturn(1);
$productModel = new Box\Mod\Product\Entity\Product();
$productServiceMock = Mockery::mock(Box\Mod\Product\Service::class);
$productServiceMock->shouldReceive('findProductById')->once()->with(1)->andReturn($productModel);
$clientModel = new Model_Client();
$clientModel->loadBean(new Tests\Helpers\DummyBean());
$dbMock = Mockery::mock(Box_Database::class);
$dbMock->shouldReceive('getExistingModelById')->once()->andReturn($clientModel);
$di = container();
$di['db'] = $dbMock;
$di['mod_service'] = $di->protect(fn (string $name): Mockery\MockInterface => match (strtolower($name)) {
'product' => $productServiceMock,
default => Mockery::mock()->shouldIgnoreMissing(),
});
$api->setDi($di);
$api->setService($serviceMock);
$data = [
$data = ['client_id' => 1, 'product_id' => 1];
$result = $api->create($data);
expect($result)->toBeInt();
expect($result)->toBe(1);
});
test('rejects order create with mark invoice paid when invoice permission is missing', function (): void {
$api = new Admin();
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('createOrder')->never();
$staffServiceMock = Mockery::mock(Box\Mod\Staff\Service::class);
$staffServiceMock->shouldReceive('hasPermission')->byDefault()->andReturn(true);
$staffServiceMock->shouldReceive('checkPermissionsAndThrowException')
->byDefault()
->andReturn(true);
$staffServiceMock->shouldReceive('checkPermissionsAndThrowException')
->once()
->with('invoice', null, null, Mockery::any())
->andThrow(new FOSSBilling\InformationException('Denied', [], 403));
$di = container();
$di['mod_service'] = $di->protect(fn (string $name): Mockery\MockInterface => match (strtolower($name)) {
'staff' => $staffServiceMock,
default => Mockery::mock()->shouldIgnoreMissing(),
});
$api->setDi($di);
$api->setService($serviceMock);
expect(fn () => $api->create([
'client_id' => 1,
'product_id' => 1,
];
$result = $api->create($data);
expect($result)->toBeInt();
'invoice_option' => 'issue-invoice',
'mark_invoice_paid' => 1,
'gateway_id' => 5,
]))->toThrow(FOSSBilling\InformationException::class);
});
test('uses invoice service to validate mark paid request when permission granted', function (): void {
$api = new Admin();
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('createOrder')
->once()
->with(
Mockery::type(Model_Client::class),
Mockery::type(Box\Mod\Product\Entity\Product::class),
Mockery::on(fn (array $data): bool => $data['gateway_id'] === 5
&& $data['invoice_option'] === 'issue-invoice'
&& $data['mark_invoice_paid'] === true)
)
->andReturn(55);
$staffServiceMock = Mockery::mock(Box\Mod\Staff\Service::class);
$staffServiceMock->shouldReceive('hasPermission')->byDefault()->andReturn(true);
$staffServiceMock->shouldReceive('checkPermissionsAndThrowException')
->byDefault()
->andReturn(true);
$staffServiceMock->shouldReceive('checkPermissionsAndThrowException')
->once()
->with('invoice', null, null, Mockery::any());
$payGateway = new Model_PayGateway();
$payGateway->loadBean(new Tests\Helpers\DummyBean());
$invoiceServiceMock = Mockery::mock(Box\Mod\Invoice\Service::class);
$invoiceServiceMock->shouldReceive('validateAdminMarkAsPaidRequest')
->once()
->with(Mockery::on(fn (array $data): bool => $data['gateway_id'] === 5
&& $data['invoice_option'] === 'issue-invoice'
&& $data['mark_invoice_paid'] === true))
->andReturn($payGateway);
$productModel = new Box\Mod\Product\Entity\Product();
$productServiceMock = Mockery::mock(Box\Mod\Product\Service::class);
$productServiceMock->shouldReceive('findProductById')->once()->with(1)->andReturn($productModel);
$clientModel = new Model_Client();
$clientModel->loadBean(new Tests\Helpers\DummyBean());
$dbMock = Mockery::mock(Box_Database::class);
$dbMock->shouldReceive('getExistingModelById')->once()->andReturn($clientModel);
$di = container();
$di['db'] = $dbMock;
$di['mod_service'] = $di->protect(fn (string $name): Mockery\MockInterface => match (strtolower($name)) {
'staff' => $staffServiceMock,
'invoice' => $invoiceServiceMock,
'product' => $productServiceMock,
default => Mockery::mock()->shouldIgnoreMissing(),
});
$api->setDi($di);
$api->setService($serviceMock);
$result = $api->create([
'client_id' => 1,
'product_id' => 1,
'invoice_option' => 'issue-invoice',
'mark_invoice_paid' => 1,
'gateway_id' => 5,
]);
expect($result)->toBe(55);
});
test('rejects invalid invoice payment payload before order creation', function (): void {
$api = new Admin();
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('createOrder')->never();
$staffServiceMock = Mockery::mock(Box\Mod\Staff\Service::class);
$staffServiceMock->shouldReceive('hasPermission')->byDefault()->andReturn(true);
$staffServiceMock->shouldReceive('checkPermissionsAndThrowException')
->byDefault()
->andReturn(true);
$staffServiceMock->shouldReceive('checkPermissionsAndThrowException')
->once()
->with('invoice', null, null, Mockery::any());
$invoiceServiceMock = Mockery::mock(Box\Mod\Invoice\Service::class);
$invoiceServiceMock->shouldReceive('validateAdminMarkAsPaidRequest')
->once()
->andThrow(new FOSSBilling\InformationException('Transaction ID is required when using the Custom payment gateway.'));
$di = container();
$di['mod_service'] = $di->protect(fn (string $name): Mockery\MockInterface => match (strtolower($name)) {
'staff' => $staffServiceMock,
'invoice' => $invoiceServiceMock,
default => Mockery::mock()->shouldIgnoreMissing(),
});
$api->setDi($di);
$api->setService($serviceMock);
expect(fn () => $api->create([
'client_id' => 1,
'product_id' => 1,
'invoice_option' => 'issue-invoice',
'mark_invoice_paid' => 1,
'gateway_id' => 5,
]))->toThrow(FOSSBilling\InformationException::class, 'Transaction ID is required when using the Custom payment gateway.');
});
test('updates an order', function (): void {
$api = new Admin();
$order = new Model_ClientOrder();
$order->loadBean(new Tests\Helpers\DummyBean());
$apiMock = Mockery::mock(Admin::class)->makePartial()->shouldAllowMockingProtectedMethods();
$apiMock->shouldReceive('_getOrder')
->atLeast()->once()
->andReturn($order);
$apiMock = Mockery::mock(Admin::class)->makePartial();
$apiMock->shouldAllowMockingProtectedMethods();
$apiMock->shouldReceive('_getOrder')->atLeast()->once()->andReturn($order);
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('updateOrder')
->atLeast()->once()
->andReturn(true);
$serviceMock->shouldReceive('updateOrder')->atLeast()->once()->andReturn(true);
$apiMock->setService($serviceMock);
$data = [
'client_id' => 1,
'product_id' => 1,
];
$data = ['client_id' => 1, 'product_id' => 1];
$result = $apiMock->update($data);
expect($result)->toBeTrue();
});
test('activates an order', function (): void {
$api = new Admin();
$order = new Model_ClientOrder();
$order->loadBean(new Tests\Helpers\DummyBean());
$apiMock = Mockery::mock(Admin::class)->makePartial()->shouldAllowMockingProtectedMethods();
$apiMock->shouldReceive('_getOrder')
->atLeast()->once()
->andReturn($order);
$apiMock = Mockery::mock(Admin::class)->makePartial();
$apiMock->shouldAllowMockingProtectedMethods();
$apiMock->shouldReceive('_getOrder')->atLeast()->once()->andReturn($order);
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('activateOrder')
->atLeast()->once()
->andReturn(true);
$serviceMock->shouldReceive('activateOrder')->atLeast()->once()->andReturn(true);
$apiMock->setService($serviceMock);
$data = [
'client_id' => 1,
'product_id' => 1,
];
$data = ['client_id' => 1, 'product_id' => 1];
$result = $apiMock->activate($data);
expect($result)->toBeTrue();
});
test('renews an order', function (): void {
$api = new Admin();
$order = new Model_ClientOrder();
$order->loadBean(new Tests\Helpers\DummyBean());
$apiMock = Mockery::mock(Admin::class)->makePartial()->shouldAllowMockingProtectedMethods();
$apiMock->shouldReceive('_getOrder')
->atLeast()->once()
->andReturn($order);
$apiMock = Mockery::mock(Admin::class)->makePartial();
$apiMock->shouldAllowMockingProtectedMethods();
$apiMock->shouldReceive('_getOrder')->atLeast()->once()->andReturn($order);
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('renewOrder')
->atLeast()->once()
->andReturn(true);
$serviceMock->shouldReceive('renewOrder')->atLeast()->once()->andReturn(true);
$apiMock->setService($serviceMock);
$result = $apiMock->renew([]);
$data = [];
$result = $apiMock->renew($data);
expect($result)->toBeTrue();
});
test('renews pending setup order by activating it', function (): void {
$api = new Admin();
test('renewing a pending setup order delegates to activate', function (): void {
$order = new Model_ClientOrder();
$order->loadBean(new Tests\Helpers\DummyBean());
$order->status = Model_ClientOrder::STATUS_PENDING_SETUP;
$apiMock = Mockery::mock(Admin::class)->makePartial()->shouldAllowMockingProtectedMethods();
$apiMock->shouldReceive('_getOrder')
->atLeast()->once()
->andReturn($order);
$apiMock->shouldReceive('activate')
->atLeast()->once()
->andReturn(true);
$apiMock = Mockery::mock(Admin::class)->makePartial();
$apiMock->shouldAllowMockingProtectedMethods();
$apiMock->shouldReceive('_getOrder')->atLeast()->once()->andReturn($order);
$apiMock->shouldReceive('activate')->atLeast()->once()->andReturn(true);
$data = [];
$result = $apiMock->renew($data);
$result = $apiMock->renew([]);
expect($result)->toBeTrue();
});
test('suspends an order', function (): void {
$api = new Admin();
$order = new Model_ClientOrder();
$order->loadBean(new Tests\Helpers\DummyBean());
$apiMock = Mockery::mock(Admin::class)->makePartial()->shouldAllowMockingProtectedMethods();
$apiMock->shouldReceive('_getOrder')
->atLeast()->once()
->andReturn($order);
$apiMock = Mockery::mock(Admin::class)->makePartial();
$apiMock->shouldAllowMockingProtectedMethods();
$apiMock->shouldReceive('_getOrder')->atLeast()->once()->andReturn($order);
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('suspendFromOrder')
->atLeast()->once()
->andReturn(true);
$serviceMock->shouldReceive('suspendFromOrder')->atLeast()->once()->andReturn(true);
$di = container();
$apiMock->setDi($di);
$apiMock->setService($serviceMock);
$result = $apiMock->suspend([]);
$data = [];
$result = $apiMock->suspend($data);
expect($result)->toBeTrue();
});
test('unsuspends an order', function (): void {
$api = new Admin();
test('unsuspends a suspended order', function (): void {
$order = new Model_ClientOrder();
$order->loadBean(new Tests\Helpers\DummyBean());
$order->status = Model_ClientOrder::STATUS_SUSPENDED;
$apiMock = Mockery::mock(Admin::class)->makePartial()->shouldAllowMockingProtectedMethods();
$apiMock->shouldReceive('_getOrder')
->atLeast()->once()
->andReturn($order);
$apiMock = Mockery::mock(Admin::class)->makePartial();
$apiMock->shouldAllowMockingProtectedMethods();
$apiMock->shouldReceive('_getOrder')->atLeast()->once()->andReturn($order);
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('unsuspendFromOrder')
->atLeast()->once()
->andReturn(true);
$serviceMock->shouldReceive('unsuspendFromOrder')->atLeast()->once()->andReturn(true);
$apiMock->setService($serviceMock);
$result = $apiMock->unsuspend([]);
$data = [];
$result = $apiMock->unsuspend($data);
expect($result)->toBeTrue();
});
test('throws exception when unsuspending non-suspended order', function (): void {
$api = new Admin();
$order = new Model_ClientOrder();
$order->loadBean(new Tests\Helpers\DummyBean());
$order->status = Model_ClientOrder::STATUS_ACTIVE;
$apiMock = Mockery::mock(Admin::class)->makePartial()->shouldAllowMockingProtectedMethods();
$apiMock->shouldReceive('_getOrder')
->atLeast()->once()
->andReturn($order);
$apiMock = Mockery::mock(Admin::class)->makePartial();
$apiMock->shouldAllowMockingProtectedMethods();
$apiMock->shouldReceive('_getOrder')->atLeast()->once()->andReturn($order);
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('unsuspendFromOrder')
->never()
->andReturn(true);
$serviceMock->shouldReceive('unsuspendFromOrder')->never()->andReturn(true);
$apiMock->setService($serviceMock);
expect(fn () => $apiMock->unsuspend([]))
->toThrow(FOSSBilling\Exception::class);
$data = [];
expect(fn () => $apiMock->unsuspend($data))->toThrow(FOSSBilling\Exception::class);
});
test('cancels an order', function (): void {
$api = new Admin();
$order = new Model_ClientOrder();
$order->loadBean(new Tests\Helpers\DummyBean());
$apiMock = Mockery::mock(Admin::class)->makePartial()->shouldAllowMockingProtectedMethods();
$apiMock->shouldReceive('_getOrder')
->atLeast()->once()
->andReturn($order);
$apiMock = Mockery::mock(Admin::class)->makePartial();
$apiMock->shouldAllowMockingProtectedMethods();
$apiMock->shouldReceive('_getOrder')->atLeast()->once()->andReturn($order);
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('cancelFromOrder')
->atLeast()->once()
->andReturn(true);
$serviceMock->shouldReceive('cancelFromOrder')->atLeast()->once()->andReturn(true);
$di = container();
$apiMock->setDi($di);
$apiMock->setService($serviceMock);
$result = $apiMock->cancel([]);
$data = [];
$result = $apiMock->cancel($data);
expect($result)->toBeTrue();
});
test('uncancels an order', function (): void {
$api = new Admin();
test('uncancels a canceled order', function (): void {
$order = new Model_ClientOrder();
$order->loadBean(new Tests\Helpers\DummyBean());
$order->status = Model_ClientOrder::STATUS_CANCELED;
$apiMock = Mockery::mock(Admin::class)->makePartial()->shouldAllowMockingProtectedMethods();
$apiMock->shouldReceive('_getOrder')
->atLeast()->once()
->andReturn($order);
$apiMock = Mockery::mock(Admin::class)->makePartial();
$apiMock->shouldAllowMockingProtectedMethods();
$apiMock->shouldReceive('_getOrder')->atLeast()->once()->andReturn($order);
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('uncancelFromOrder')
->atLeast()->once()
->andReturn(true);
$serviceMock->shouldReceive('uncancelFromOrder')->atLeast()->once()->andReturn(true);
$apiMock->setService($serviceMock);
$result = $apiMock->uncancel([]);
$data = [];
$result = $apiMock->uncancel($data);
expect($result)->toBeTrue();
});
test('throws exception when uncanceling non-canceled order', function (): void {
$api = new Admin();
$order = new Model_ClientOrder();
$order->loadBean(new Tests\Helpers\DummyBean());
$order->status = Model_ClientOrder::STATUS_ACTIVE;
$apiMock = Mockery::mock(Admin::class)->makePartial()->shouldAllowMockingProtectedMethods();
$apiMock->shouldReceive('_getOrder')
->atLeast()->once()
->andReturn($order);
$apiMock = Mockery::mock(Admin::class)->makePartial();
$apiMock->shouldAllowMockingProtectedMethods();
$apiMock->shouldReceive('_getOrder')->atLeast()->once()->andReturn($order);
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('uncancelFromOrder')
->never()
->andReturn(true);
$serviceMock->shouldReceive('uncancelFromOrder')->never()->andReturn(true);
$apiMock->setService($serviceMock);
expect(fn () => $apiMock->uncancel([]))
->toThrow(FOSSBilling\Exception::class);
$data = [];
expect(fn () => $apiMock->uncancel($data))->toThrow(FOSSBilling\Exception::class);
});
test('deletes an order', function (): void {
$api = new Admin();
$order = new Model_ClientOrder();
$order->loadBean(new Tests\Helpers\DummyBean());
$apiMock = Mockery::mock(Admin::class)->makePartial()->shouldAllowMockingProtectedMethods();
$apiMock->shouldReceive('_getOrder')
->atLeast()->once()
->andReturn($order);
$apiMock = Mockery::mock(Admin::class)->makePartial();
$apiMock->shouldAllowMockingProtectedMethods();
$apiMock->shouldReceive('_getOrder')->atLeast()->once()->andReturn($order);
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('deleteFromOrder')
->atLeast()->once()
->andReturn(true);
$serviceMock->shouldReceive('deleteFromOrder')->atLeast()->once()->andReturn(true);
$apiMock->setService($serviceMock);
$result = $apiMock->delete([]);
$data = [];
$result = $apiMock->delete($data);
expect($result)->toBeTrue();
});
test('deletes an order with addons', function (): void {
$api = new Admin();
$order = new Model_ClientOrder();
$order->loadBean(new Tests\Helpers\DummyBean());
$apiMock = Mockery::mock(Admin::class)->makePartial()->shouldAllowMockingProtectedMethods();
$apiMock->shouldReceive('_getOrder')
->atLeast()->once()
->andReturn($order);
$apiMock = Mockery::mock(Admin::class)->makePartial();
$apiMock->shouldAllowMockingProtectedMethods();
$apiMock->shouldReceive('_getOrder')->atLeast()->once()->andReturn($order);
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('deleteFromOrder')
->atLeast()->once()
->andReturn(true);
$serviceMock->shouldReceive('getOrderAddonsList')
->atLeast()->once()
->andReturn([new Model_ClientOrder()]);
$serviceMock->shouldReceive('deleteFromOrder')->atLeast()->once()->andReturn(true);
$serviceMock->shouldReceive('getOrderAddonsList')->atLeast()->once()->andReturn([new Model_ClientOrder()]);
$apiMock->setService($serviceMock);
$data = ['delete_addons' => true];
$result = $apiMock->delete($data);
expect($result)->toBeTrue();
});
test('batch suspends expired orders', function (): void {
$api = new Admin();
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('batchSuspendExpired')
->atLeast()->once()
->andReturn(true);
$serviceMock->shouldReceive('batchSuspendExpired')->atLeast()->once()->andReturn(true);
$api->setService($serviceMock);
$result = $api->batch_suspend_expired([]);
$data = [];
$result = $api->batch_suspend_expired($data);
expect($result)->toBeTrue();
});
test('batch cancels suspended orders', function (): void {
$api = new Admin();
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('batchCancelSuspended')
->atLeast()->once()
->andReturn(true);
$serviceMock->shouldReceive('batchCancelSuspended')->atLeast()->once()->andReturn(true);
$api->setService($serviceMock);
$result = $api->batch_cancel_suspended([]);
$data = [];
$result = $api->batch_cancel_suspended($data);
expect($result)->toBeTrue();
});
test('updates order config', function (): void {
$api = new Admin();
$order = new Model_ClientOrder();
$order->loadBean(new Tests\Helpers\DummyBean());
$apiMock = Mockery::mock(Admin::class)->makePartial()->shouldAllowMockingProtectedMethods();
$apiMock->shouldReceive('_getOrder')
->atLeast()->once()
->andReturn($order);
$apiMock = Mockery::mock(Admin::class)->makePartial();
$apiMock->shouldAllowMockingProtectedMethods();
$apiMock->shouldReceive('_getOrder')->atLeast()->once()->andReturn($order);
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('updateOrderConfig')
->atLeast()->once()
->andReturn(true);
$serviceMock->shouldReceive('updateOrderConfig')->atLeast()->once()->andReturn(true);
$apiMock->setService($serviceMock);
$data = ['config' => []];
$result = $apiMock->update_config($data);
expect($result)->toBeTrue();
});
test('throws exception when updating config without config param', function (): void {
$api = new Admin();
test('throws exception when config is not set', function (): void {
$order = new Model_ClientOrder();
$order->loadBean(new Tests\Helpers\DummyBean());
$apiMock = Mockery::mock(Admin::class)->makePartial()->shouldAllowMockingProtectedMethods();
$apiMock->shouldReceive('_getOrder')
->atLeast()->once()
->andReturn($order);
$apiMock = Mockery::mock(Admin::class)->makePartial();
$apiMock->shouldAllowMockingProtectedMethods();
$apiMock->shouldReceive('_getOrder')->atLeast()->once()->andReturn($order);
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('updateOrderConfig')
->never()
->andReturn(true);
$serviceMock->shouldReceive('updateOrderConfig')->never()->andReturn(true);
$apiMock->setService($serviceMock);
expect(fn () => $apiMock->update_config([]))
->toThrow(FOSSBilling\Exception::class);
$data = [];
expect(fn () => $apiMock->update_config($data))->toThrow(FOSSBilling\Exception::class);
});
test('gets order service data', function (): void {
$api = new Admin();
test('gets order service', function (): void {
$order = new Model_ClientOrder();
$order->loadBean(new Tests\Helpers\DummyBean());
$apiMock = Mockery::mock(Admin::class)->makePartial()->shouldAllowMockingProtectedMethods();
$apiMock->shouldReceive('_getOrder')
->atLeast()->once()
->andReturn($order);
$apiMock = Mockery::mock(Admin::class)->makePartial();
$apiMock->shouldAllowMockingProtectedMethods();
$apiMock->shouldReceive('_getOrder')->atLeast()->once()->andReturn($order);
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('getOrderServiceData')
->atLeast()->once()
->andReturn([]);
$serviceMock->shouldReceive('getOrderServiceData')->atLeast()->once()->andReturn([]);
$admin = new Model_Admin();
$admin->loadBean(new RedBeanPHP\OODBBean());
$admin->loadBean(new Tests\Helpers\DummyBean());
$apiMock->setService($serviceMock);
$apiMock->setIdentity($admin);
$data = ['id' => 1];
$result = $apiMock->service($data);
expect($result)->toBeArray();
});
test('gets status history list', function (): void {
$api = new Admin();
test('gets order status history', function (): void {
$order = new Model_ClientOrder();
$order->loadBean(new Tests\Helpers\DummyBean());
$apiMock = Mockery::mock(Admin::class)->makePartial()->shouldAllowMockingProtectedMethods();
$apiMock->shouldReceive('_getOrder')
->atLeast()->once()
->andReturn($order);
$apiMock = Mockery::mock(Admin::class)->makePartial();
$apiMock->shouldAllowMockingProtectedMethods();
$apiMock->shouldReceive('_getOrder')->atLeast()->once()->andReturn($order);
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('getOrderStatusSearchQuery')
->atLeast()->once()
->andReturn(['query', []]);
$serviceMock->shouldReceive('getOrderStatusSearchQuery')->atLeast()->once()->andReturn(['query', []]);
$paginatorMock = Mockery::mock(FOSSBilling\Pagination::class);
$paginatorMock->shouldReceive('getPaginatedResultSet')
->atLeast()->once()
->andReturn([]);
$paginatorMock->shouldReceive('getPaginatedResultSet')->atLeast()->once()->andReturn([]);
$di = container();
$di['pager'] = $paginatorMock;
@@ -519,23 +575,20 @@ test('gets status history list', function (): void {
$apiMock->setService($serviceMock);
$result = $apiMock->status_history_get_list([]);
expect($result)->toBeArray();
});
test('adds status history', function (): void {
$api = new Admin();
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('orderStatusAdd')
->atLeast()->once()
->andReturn(true);
test('adds order status history', function (): void {
$order = new Model_ClientOrder();
$order->loadBean(new Tests\Helpers\DummyBean());
$apiMock = Mockery::mock(Admin::class)->makePartial()->shouldAllowMockingProtectedMethods();
$apiMock->shouldReceive('_getOrder')
->atLeast()->once()
->andReturn($order);
$apiMock = Mockery::mock(Admin::class)->makePartial();
$apiMock->shouldAllowMockingProtectedMethods();
$apiMock->shouldReceive('_getOrder')->atLeast()->once()->andReturn($order);
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('orderStatusAdd')->atLeast()->once()->andReturn(true);
$di = container();
$apiMock->setDi($di);
@@ -543,18 +596,15 @@ test('adds status history', function (): void {
$data = ['status' => Model_ClientOrder::STATUS_ACTIVE];
$result = $apiMock->status_history_add($data);
expect($result)->toBeTrue();
});
test('deletes status history', function (): void {
test('deletes order status history', function (): void {
$api = new Admin();
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('orderStatusRm')
->atLeast()->once()
->andReturn(true);
$order = new Model_ClientOrder();
$order->loadBean(new Tests\Helpers\DummyBean());
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('orderStatusRm')->atLeast()->once()->andReturn(true);
$di = container();
$api->setDi($di);
@@ -562,77 +612,72 @@ test('deletes status history', function (): void {
$data = ['id' => 1];
$result = $api->status_history_delete($data);
expect($result)->toBeTrue();
});
test('gets order statuses', function (): void {
test('gets statuses', function (): void {
$api = new Admin();
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('counter')
->atLeast()->once()
->andReturn([]);
$serviceMock->shouldReceive('counter')->atLeast()->once()->andReturn([]);
$api->setService($serviceMock);
$result = $api->get_statuses();
expect($result)->toBeArray();
});
test('gets invoice options', function (): void {
$api = new Admin();
$result = $api->get_invoice_options([]);
expect($result)->toBeArray();
});
test('gets status pairs', function (): void {
$api = new Admin();
$result = $api->get_status_pairs([]);
expect($result)->toBeArray();
});
test('gets order addons', function (): void {
$api = new Admin();
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('getOrderAddonsList')
->atLeast()->once()
->andReturn([new Model_ClientOrder()]);
$serviceMock->shouldReceive('toApiArray')
->atLeast()->once()
->andReturn([]);
test('gets addons for an order', function (): void {
$order = new Model_ClientOrder();
$order->loadBean(new Tests\Helpers\DummyBean());
$apiMock = Mockery::mock(Admin::class)->makePartial()->shouldAllowMockingProtectedMethods();
$apiMock->shouldReceive('_getOrder')
->atLeast()->once()
->andReturn($order);
$apiMock = Mockery::mock(Admin::class)->makePartial();
$apiMock->shouldAllowMockingProtectedMethods();
$apiMock->shouldReceive('_getOrder')->atLeast()->once()->andReturn($order);
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('getOrderAddonsList')->atLeast()->once()->andReturn([new Model_ClientOrder()]);
$serviceMock->shouldReceive('toApiArray')->atLeast()->once()->andReturn([]);
$apiMock->setService($serviceMock);
$data = ['status' => Model_ClientOrder::STATUS_ACTIVE];
$result = $apiMock->addons($data);
expect($result)->toBeArray();
expect($result[0])->toBeArray();
});
test('gets order with validation', function (): void {
test('gets an order via getOrder', function (): void {
$api = new Admin();
$validatorMock = Mockery::mock(FOSSBilling\Validate::class);
$validatorMock->shouldReceive('checkRequiredParamsForArray');
$validatorMock->shouldIgnoreMissing();
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('toApiArray')
->atLeast()->once()
->andReturn([]);
$serviceMock->shouldReceive('toApiArray')->atLeast()->once()->andReturn([]);
$order = new Model_ClientOrder();
$order->loadBean(new Tests\Helpers\DummyBean());
$dbMock = Mockery::mock('\Box_Database');
$dbMock->shouldReceive('getExistingModelById')
->atLeast()->once()
->andReturn($order);
$dbMock = Mockery::mock(Box_Database::class);
$dbMock->shouldReceive('getExistingModelById')->atLeast()->once()->andReturn($order);
$di = container();
$di['validator'] = $validatorMock;
@@ -646,14 +691,15 @@ test('gets order with validation', function (): void {
test('batch deletes orders', function (): void {
$api = new Admin();
$activityMock = Mockery::mock(Admin::class)->makePartial()->shouldAllowMockingProtectedMethods();
$activityMock->shouldReceive('delete')
->atLeast()->once()
->andReturn(true);
$apiMock = Mockery::mock(Admin::class)->makePartial();
$apiMock->shouldAllowMockingProtectedMethods();
$apiMock->shouldReceive('delete')->atLeast()->once()->andReturn(true);
$di = container();
$activityMock->setDi($di);
$apiMock->setDi($di);
$result = $apiMock->batch_delete(['ids' => [1, 2, 3]]);
$result = $activityMock->batch_delete(['ids' => [1, 2, 3]]);
expect($result)->toBeTrue();
});
+79 -175
View File
@@ -15,179 +15,111 @@ use Box\Mod\Order\Service;
use function Tests\Helpers\container;
test('gets dependency injection container', function (): void {
test('gets list of orders', function (): void {
$api = new Client();
$di = container();
$api->setDi($di);
$getDi = $api->getDi();
expect($getDi)->toBe($di);
});
test('gets order list', function (): void {
$api = new Client();
$orderArr = ['id' => 1];
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('getSearchQuery')->atLeast()->once()->andReturn(['query', []]);
$serviceMock->shouldReceive('getBatchForApi')->atLeast()->once()->andReturn([$orderArr]);
$pagerMock = Mockery::mock(FOSSBilling\Pagination::class);
$pagerMock->shouldReceive('getPaginatedResultSet')->atLeast()->once()->andReturn(['list' => [$orderArr]]);
$client = new Model_Client();
$client->loadBean(new Tests\Helpers\DummyBean());
$client->id = 1;
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('getSearchQuery')
->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')
->never();
$resultSet = [
'list' => [
['id' => 3],
['id' => 2],
['id' => 1],
],
'total' => 3,
];
$paginatorMock = Mockery::mock(FOSSBilling\Pagination::class);
$paginatorMock->shouldReceive('getPaginatedResultSet')
->once()
->andReturn($resultSet);
$dbMock = Mockery::mock('\Box_Database');
$dbMock->shouldReceive('getExistingModelById')
->never();
$di = container();
$di['pager'] = $paginatorMock;
$di['db'] = $dbMock;
$di['pager'] = $pagerMock;
$api->setDi($di);
$api->setIdentity($client);
$api->setService($serviceMock);
$result = $api->get_list([]);
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);
expect($result)->toBeArray();
});
test('gets expiring order list', function (): void {
test('gets list of expiring orders', function (): void {
$api = new Client();
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('getSoonExpiringActiveOrdersQuery')->atLeast()->once()->andReturn(['query', []]);
$serviceMock->shouldReceive('getBatchForApi')->atLeast()->once()->andReturn([]);
$pagerMock = Mockery::mock(FOSSBilling\Pagination::class);
$pagerMock->shouldReceive('getPaginatedResultSet')->atLeast()->once()->andReturn(['list' => []]);
$client = new Model_Client();
$client->loadBean(new Tests\Helpers\DummyBean());
$client->id = 1;
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('getSoonExpiringActiveOrdersQuery')
->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')
->once()
->andReturn([
'list' => [
['id' => 1],
],
]);
$di = container();
$di['pager'] = $paginatorMock;
$di['pager'] = $pagerMock;
$api->setDi($di);
$api->setIdentity($client);
$api->setService($serviceMock);
$data = ['expiring' => true];
$result = $api->get_list($data);
expect($result)
->toBeArray()
->and($result['list'])->toBe([
['id' => 1, 'title' => 'Expiring order'],
]);
$result = $api->get_list(['expiring' => true]);
expect($result)->toBeArray();
});
test('gets an order', function (): void {
$api = new Client();
test('gets a single order', function (): void {
$order = new Model_ClientOrder();
$order->loadBean(new Tests\Helpers\DummyBean());
$order->status = Model_ClientOrder::STATUS_ACTIVE;
$apiMock = Mockery::mock(Client::class)->makePartial()->shouldAllowMockingProtectedMethods();
$apiMock->shouldReceive('_getOrder')
->atLeast()->once()
->andReturn($order);
$apiMock = Mockery::mock(Client::class)->makePartial();
$apiMock->shouldAllowMockingProtectedMethods();
$apiMock->shouldReceive('_getOrder')->atLeast()->once()->andReturn($order);
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('toApiArray')
->atLeast()->once()
->andReturn([]);
$serviceMock->shouldReceive('toApiArray')->atLeast()->once()->andReturn([]);
$apiMock->setService($serviceMock);
$data = ['id' => 1];
$result = $apiMock->get($data);
expect($result)->toBeArray();
});
test('gets order addons', function (): void {
$api = new Client();
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('getOrderAddonsList')
->atLeast()->once()
->andReturn([new Model_ClientOrder()]);
$serviceMock->shouldReceive('toApiArray')
->atLeast()->once()
->andReturn([]);
test('gets addons', function (): void {
$order = new Model_ClientOrder();
$order->loadBean(new Tests\Helpers\DummyBean());
$apiMock = Mockery::mock(Client::class)->makePartial()->shouldAllowMockingProtectedMethods();
$apiMock->shouldReceive('_getOrder')
->atLeast()->once()
->andReturn($order);
$apiMock = Mockery::mock(Client::class)->makePartial();
$apiMock->shouldAllowMockingProtectedMethods();
$apiMock->shouldReceive('_getOrder')->atLeast()->once()->andReturn($order);
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('getOrderAddonsList')->atLeast()->once()->andReturn([new Model_ClientOrder()]);
$serviceMock->shouldReceive('toApiArray')->atLeast()->once()->andReturn([]);
$apiMock->setService($serviceMock);
$data = ['status' => Model_ClientOrder::STATUS_ACTIVE];
$result = $apiMock->addons($data);
expect($result)->toBeArray();
expect($result[0])->toBeArray();
});
test('gets order service data', function (): void {
$api = new Client();
test('gets order service', function (): void {
$order = new Model_ClientOrder();
$order->loadBean(new Tests\Helpers\DummyBean());
$order->status = Model_ClientOrder::STATUS_ACTIVE;
$apiMock = Mockery::mock(Client::class)->makePartial()->shouldAllowMockingProtectedMethods();
$apiMock->shouldReceive('_getOrder')
->atLeast()->once()
->andReturn($order);
$apiMock = Mockery::mock(Client::class)->makePartial();
$apiMock->shouldAllowMockingProtectedMethods();
$apiMock->shouldReceive('_getOrder')->atLeast()->once()->andReturn($order);
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('getOrderServiceData')
->atLeast()->once()
->andReturn([]);
$serviceMock->shouldReceive('getOrderServiceData')->atLeast()->once()->andReturn([]);
$client = new Model_Client();
$client->loadBean(new Tests\Helpers\DummyBean());
@@ -197,110 +129,91 @@ test('gets order service data', function (): void {
$data = ['id' => 1];
$result = $apiMock->service($data);
expect($result)->toBeArray();
});
test('gets upgradable products', function (): void {
$api = new Client();
test('gets upgradables', function (): void {
$order = new Model_ClientOrder();
$order->loadBean(new Tests\Helpers\DummyBean());
$order->product_id = 5;
$apiMock = Mockery::mock(Client::class)->makePartial()->shouldAllowMockingProtectedMethods();
$apiMock->shouldReceive('_getOrder')
->atLeast()->once()
->andReturn($order);
$apiMock = Mockery::mock(Client::class)->makePartial();
$apiMock->shouldAllowMockingProtectedMethods();
$apiMock->shouldReceive('_getOrder')->atLeast()->once()->andReturn($order);
$productServiceMock = Mockery::mock(Box\Mod\Product\Service::class);
$productServiceMock->shouldReceive('getUpgradablePairs')
$productServiceMock->shouldReceive('getUpgradablePairsByProductId')
->atLeast()->once()
->with(5)
->andReturn([]);
$product = new Model_Product();
$product->loadBean(new RedBeanPHP\OODBBean());
$dbMock = Mockery::mock('\Box_Database');
$dbMock->shouldReceive('getExistingModelById')
->atLeast()->once()
->andReturn($product);
$di = container();
$di['db'] = $dbMock;
$di['mod_service'] = $di->protect(fn () => $productServiceMock);
$di['mod_service'] = $di->protect(fn (string $name): Mockery\MockInterface => match (strtolower($name)) {
'product' => $productServiceMock,
default => Mockery::mock()->shouldIgnoreMissing(),
});
$apiMock->setDi($di);
$result = $apiMock->upgradables([]);
$data = [];
$result = $apiMock->upgradables($data);
expect($result)->toBeArray();
});
test('deletes a pending order', function (): void {
$api = new Client();
test('deletes a pending setup order', function (): void {
$order = new Model_ClientOrder();
$order->loadBean(new Tests\Helpers\DummyBean());
$order->status = Model_ClientOrder::STATUS_PENDING_SETUP;
$apiMock = Mockery::mock(Client::class)->makePartial()->shouldAllowMockingProtectedMethods();
$apiMock->shouldReceive('_getOrder')
->atLeast()->once()
->andReturn($order);
$apiMock = Mockery::mock(Client::class)->makePartial();
$apiMock->shouldAllowMockingProtectedMethods();
$apiMock->shouldReceive('_getOrder')->atLeast()->once()->andReturn($order);
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('deleteFromOrder')
->atLeast()->once()
->andReturn(true);
$serviceMock->shouldReceive('deleteFromOrder')->atLeast()->once()->andReturn(true);
$apiMock->setService($serviceMock);
$data = ['id' => 1];
$result = $apiMock->delete($data);
expect($result)->toBeTrue();
});
test('throws exception when deleting non-pending order', function (): void {
$api = new Client();
$order = new Model_ClientOrder();
$order->loadBean(new Tests\Helpers\DummyBean());
$apiMock = Mockery::mock(Client::class)->makePartial()->shouldAllowMockingProtectedMethods();
$apiMock->shouldReceive('_getOrder')
->atLeast()->once()
->andReturn($order);
$apiMock = Mockery::mock(Client::class)->makePartial();
$apiMock->shouldAllowMockingProtectedMethods();
$apiMock->shouldReceive('_getOrder')->atLeast()->once()->andReturn($order);
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('deleteFromOrder')
->never()
->andReturn(true);
$serviceMock->shouldReceive('deleteFromOrder')->never()->andReturn(true);
$apiMock->setService($serviceMock);
$data = ['id' => 1];
expect(fn () => $apiMock->delete($data))
->toThrow(FOSSBilling\Exception::class);
expect(fn () => $apiMock->delete($data))->toThrow(FOSSBilling\Exception::class);
});
test('gets order for client', function (): void {
test('gets order via getOrder', function (): void {
$api = new Client();
$validatorMock = Mockery::mock(FOSSBilling\Validate::class);
$validatorMock->shouldReceive('checkRequiredParamsForArray');
$order = new Model_ClientOrder();
$order->loadBean(new Tests\Helpers\DummyBean());
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('findForClientById')
->atLeast()->once()
->andReturn($order);
$serviceMock->shouldReceive('toApiArray')
->atLeast()->once()
->andReturn([]);
$serviceMock->shouldReceive('findForClientById')->atLeast()->once()->andReturn($order);
$serviceMock->shouldReceive('toApiArray')->atLeast()->once()->andReturn([]);
$client = new Model_Client();
$client->loadBean(new Tests\Helpers\DummyBean());
$di = container();
$di['validator'] = $validatorMock;
$api->setDi($di);
$api->setService($serviceMock);
$api->setIdentity($client);
@@ -308,31 +221,22 @@ test('gets order for client', function (): void {
$api->get($data);
});
test('throws exception when order not found for client', function (): void {
test('throws exception when order not found', function (): void {
$api = new Client();
$validatorMock = Mockery::mock(FOSSBilling\Validate::class);
$validatorMock->shouldReceive('checkRequiredParamsForArray');
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('findForClientById')
->atLeast()->once()
->andReturn(null);
$serviceMock->shouldReceive('toApiArray')
->never()
->andReturn([]);
$serviceMock->shouldReceive('findForClientById')->atLeast()->once()->andReturn(null);
$serviceMock->shouldReceive('toApiArray')->never()->andReturn([]);
$client = new Model_Client();
$client->loadBean(new Tests\Helpers\DummyBean());
$di = container();
$di['validator'] = $validatorMock;
$api->setDi($di);
$api->setService($serviceMock);
$api->setIdentity($client);
$data = ['id' => 1];
expect(fn () => $api->get($data))
->toThrow(FOSSBilling\Exception::class);
expect(fn () => $api->get($data))->toThrow(FOSSBilling\Exception::class);
});
File diff suppressed because it is too large. Load diff
@@ -35,7 +35,7 @@
<td>
{% if item.discount_price %}
<del>{{ (item.total * cart_currency.conversion_rate)|format_currency(cart_currency.code) }}</del>
<strong class="text-success">{{ (item.total-item.discount_price * cart_currency.conversion_rate)|format_currency(cart_currency.code) }}</strong>
<strong class="text-success">{{ ((item.total - item.discount_price) * cart_currency.conversion_rate)|format_currency(cart_currency.code) }}</strong>
{% else %}
{{ (item.total * cart_currency.conversion_rate)|format_currency(cart_currency.code) }}
{% endif %}
@@ -111,8 +111,8 @@
</tbody>
</table>
<div class="row-fluid">
<div class="span6">
<div class="row">
<div class="col-md-6">
{% if not cart.promocode %}
<a href="#" id="show-promo-field">{{ 'Have a coupon code?'|trans }}</a>
{% endif %}
@@ -134,7 +134,7 @@
</form>
</div>
<div class="span6">
<div class="col-md-6">
<table class="table table-bordered table-striped">
{% if cart.discount >0 %}
<tr>
@@ -194,7 +194,7 @@
{% if enough_in_balance %}
<p>{{ 'Total amount will be deducted from account balance'|trans }}</p>
{% endif %}
{% if settings.checkout_tos == 'explicit' %}
{% if settings.checkout_tos|default('0') == 'explicit' %}
<div class="form-check mb-1">
<input class="form-check-input" type="checkbox" value="" id="flexCheckDefault" required>
<label class="form-check-label" for="flexCheckDefault">
@@ -208,7 +208,7 @@
</div>
</div>
</fieldset>
{% if settings.checkout_tos == 'implicit' %}
{% if settings.checkout_tos|default('0') == 'implicit' %}
{# TODO: Make this translatable once support for placeholders is implemented #}
<span class="text-muted">By completing your order, you agree to our <a href="{{ 'tos'|url }}" target="_blank">{{ 'Terms of Service'|trans }}</a> and <a href="{{ 'privacy-policy'|url }}" target="_blank">{{ 'Privacy Policy'|trans }}</a>.</span>
{% endif %}
@@ -232,7 +232,7 @@
{% endif %}
{% endfor %}
{{ mf.recaptcha }}
{% if settings.signup_tos == 'explicit' %}
{% if settings.signup_tos|default('0') == 'explicit' %}
<div class="form-check mb-1">
<input class="form-check-input" type="checkbox" value="" id="flexCheckDefault" required>
<label class="form-check-label" for="flexCheckDefault">
@@ -249,7 +249,7 @@
aria-selected="true">{{ 'Already a User?'|trans }}
</button>
</div>
{% if settings.signup_tos == 'implicit' %}
{% if settings.signup_tos|default('0') == 'implicit' %}
<div class="mb-1">
{# TODO: Make this translatable once support for placeholders is implemented #}
<span class="text-muted mb-1">By creating an account, you agree to our <a href="{{ 'tos'|url }}" target="_blank">{{ 'Terms of Service'|trans }}</a> and <a href="{{ 'privacy-policy'|url }}" target="_blank">{{ 'Privacy Policy'|trans }}</a>.</span>
@@ -33,7 +33,9 @@
if (r.iframe) {
document.getElementById('payment-html-inner').innerHTML = r.result;
bootstrap.Collapse.getOrCreateInstance(checkoutEl).hide();
document.getElementById('checkout').remove();
if (checkoutEl) {
checkoutEl.remove();
}
bootstrap.Collapse.getOrCreateInstance(paymentHtmlEl).show();
} else {
const link = '{{ "invoice/banklink"|url }}' + '/' + result.invoice_hash + '/' + result.gateway_id;
@@ -52,12 +54,13 @@
function onLogin(result){
FOSSBilling.message("{{ 'You logged in successfully'|trans }}");
let registerEl = document.getElementById('register');
new bootstrap.Collapse('#register').hide();
let checkoutEl = document.getElementById('checkout');
bootstrap.Collapse.getOrCreateInstance(registerEl).hide();
document.querySelector("#checkoutButton").hidden = false;
document.querySelector("#loginMessage").hidden = true;
setTimeout(() => {
registerEl.parentElement.remove();
new bootstrap.Collapse('#checkout').show();
bootstrap.Collapse.getOrCreateInstance(checkoutEl).show();
}, 500);
}
@@ -70,12 +73,12 @@
() => {
FOSSBilling.message("{{ 'You logged in successfully'|trans }}");
let registerEl = document.getElementById('register');
new bootstrap.Collapse('#register').hide();
bootstrap.Collapse.getOrCreateInstance(registerEl).hide();
document.querySelector("#checkoutButton").hidden = false;
document.querySelector("#loginMessage").hidden = true;
setTimeout(() => {
registerEl.parentElement.remove();
new bootstrap.Collapse('#checkout').show();
bootstrap.Collapse.getOrCreateInstance(document.getElementById('checkout')).show();
}, 500);
});
}
@@ -174,7 +174,7 @@
{{ mf.recaptcha }}
{% if settings.signup_tos == 'explicit' %}
{% if settings.signup_tos|default('0') == 'explicit' %}
<div class="form-check mb-1">
<input class="form-check-input" type="checkbox" value="" id="flexCheckDefault" required>
<label class="form-check-label" for="flexCheckDefault">
@@ -188,7 +188,7 @@
<button class="btn btn-primary w-100" type="submit">{{ 'Register'|trans }}</button>
</div>
{% if settings.signup_tos == 'implicit' %}
{% if settings.signup_tos|default('0') == 'implicit' %}
<div class="mb-1">
{# TODO: Make this translatable once support for placeholders is implemented #}
<span class="text-muted mb-1">By creating an account, you agree to our <a href="{{ 'tos'|url }}" target="_blank">{{ 'Terms of Service'|trans }}</a> and <a href="{{ 'privacy-policy'|url }}" target="_blank">{{ 'Privacy Policy'|trans }}</a>.</span>
+45 -32
View File
@@ -16,6 +16,7 @@ declare(strict_types=1);
namespace Box\Mod\Product\Api;
use Box\Mod\Product\Entity\Product;
use FOSSBilling\PaginationOptions;
use FOSSBilling\Validation\Api\RequiredParams;
@@ -30,17 +31,7 @@ class Admin extends \FOSSBilling\Api\AbstractApi
{
$this->checkPermissions('product', 'view');
$service = $this->getService();
[$sql, $params] = $service->getProductSearchQuery($data);
$pager = $this->getDi()['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
foreach ($pager['list'] as $key => $item) {
$model = $this->getDi()['db']->getExistingModelById('Product', $item['id'], 'Post not found');
$pager['list'][$key] = $this->getService()->toApiArray($model, false, $this->getIdentity());
}
return $pager;
return $this->getService()->getPaginatedProducts($data, $this->getIdentity());
}
/**
@@ -66,7 +57,7 @@ class Admin extends \FOSSBilling\Api\AbstractApi
{
$this->checkPermissions('product', 'view');
$model = $this->_getProduct($data);
$model = $this->getService()->findProductById((int) $data['id']);
$service = $this->getService();
return $service->toApiArray($model, true, $this->getIdentity());
@@ -102,7 +93,7 @@ class Admin extends \FOSSBilling\Api\AbstractApi
// allow having only one domain product
if ($data['type'] == 'domain') {
$model = $service->getMainDomainProduct();
if ($model instanceof \Model_Product) {
if ($model !== null) {
throw new \FOSSBilling\InformationException('You have already created domain product.', null, 413);
}
}
@@ -236,8 +227,8 @@ class Admin extends \FOSSBilling\Api\AbstractApi
{
$this->checkPermissions('product', 'view');
$model = $this->getDi()['db']->load('Product', $data['id']);
if (!$model instanceof \Model_Product || !$model->is_addon) {
$model = $this->getService()->findProductById((int) $data['id']);
if (!$model instanceof Product || !$model->isAddon()) {
throw new \FOSSBilling\Exception('Addon not found');
}
$service = $this->getService();
@@ -273,11 +264,11 @@ class Admin extends \FOSSBilling\Api\AbstractApi
{
$this->checkPermissions('product', 'manage_products');
$model = $this->getDi()['db']->load('Product', $data['id']);
if (!$model instanceof \Model_Product || !$model->is_addon) {
$model = $this->getService()->findProductById((int) $data['id']);
if (!$model instanceof Product || !$model->isAddon()) {
throw new \FOSSBilling\Exception('Addon not found');
}
$this->getDi()['logger']->info('Updated addon #%s', $model->id);
$this->di['logger']->info('Updated addon #%s', $model->getId());
return $this->update($data);
}
@@ -337,7 +328,7 @@ class Admin extends \FOSSBilling\Api\AbstractApi
{
$this->checkPermissions('product', 'manage_categories');
$model = $this->getDi()['db']->getExistingModelById('ProductCategory', $data['id'], 'Category not found');
$model = $this->getService()->findProductCategoryById((int) $data['id']);
$title = $data['title'] ?? null;
$description = $data['description'] ?? null;
@@ -358,9 +349,9 @@ class Admin extends \FOSSBilling\Api\AbstractApi
#[RequiredParams(['id' => 'Category ID was not passed'])]
public function category_get($data)
{
$this->checkPermissions('product', 'view');
$this->checkPermissions('product', 'manage_categories');
$model = $this->getDi()['db']->getExistingModelById('ProductCategory', $data['id'], 'Category not found');
$model = $this->getService()->findProductCategoryById((int) $data['id']);
return $this->getService()->toProductCategoryApiArray($model, true, $this->getIdentity());
}
@@ -401,7 +392,7 @@ class Admin extends \FOSSBilling\Api\AbstractApi
{
$this->checkPermissions('product', 'manage_categories');
$model = $this->getDi()['db']->getExistingModelById('ProductCategory', $data['id'], 'Category not found');
$model = $this->getService()->findProductCategoryById((int) $data['id']);
$service = $this->getService();
return $service->removeProductCategory($model);
@@ -417,13 +408,11 @@ class Admin extends \FOSSBilling\Api\AbstractApi
$this->checkPermissions('product', 'view');
$service = $this->getService();
[$sql, $params] = $service->getPromoSearchQuery($data);
$pager = $this->getDi()['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
$qb = $service->getPromoSearchQueryBuilder($data);
$pager = $this->di['pager']->paginateDoctrineQuery($qb, PaginationOptions::fromArray($data));
foreach ($pager['list'] as $key => $item) {
$model = $this->getDi()['db']->getExistingModelById('Promo', $item['id'], 'Promo not found');
$pager['list'][$key] = $this->getService()->toPromoApiArray($model);
$pager['list'][$key] = $this->getService()->enrichPromoApiArray($item);
}
return $pager;
@@ -486,11 +475,36 @@ class Admin extends \FOSSBilling\Api\AbstractApi
$this->checkPermissions('product', 'view');
$id = $data['id'] ?? null;
$model = $this->getDi()['db']->getExistingModelById('Promo', $id, 'Promo not found');
$model = $this->getService()->findPromoById((int) $id);
return $this->getService()->toPromoApiArray($model, true, $this->getIdentity());
}
/**
* Get promo redemption history.
*
* @return array
*
* @throws \FOSSBilling\Exception
*/
#[RequiredParams(['promo_id' => 'Promo ID is missing'])]
public function promo_redemption_get_list($data)
{
$this->checkPermissions('product', 'view');
/** @var \Box\Mod\Product\Repository\PromoRedemptionRepository $repo */
$repo = $this->getService()->getPromoRedemptionRepository();
$qb = $repo->getSearchQueryBuilder($data);
$pager = $this->di['pager']->paginateDoctrineQuery($qb, PaginationOptions::fromArray($data));
foreach ($pager['list'] as $key => $item) {
$pager['list'][$key] = $this->getService()->enrichPromoRedemptionApiArray($item);
}
return $pager;
}
/**
* Promo code update.
*
@@ -517,9 +531,8 @@ class Admin extends \FOSSBilling\Api\AbstractApi
{
$this->checkPermissions('product', 'manage_promos');
$model = $this->getDi()['db']->getExistingModelById('Promo', $data['id'], 'Promo not found');
$service = $this->getService();
$model = $service->findPromoById((int) $data['id']);
return $service->updatePromo($model, $data);
}
@@ -536,7 +549,7 @@ class Admin extends \FOSSBilling\Api\AbstractApi
{
$this->checkPermissions('product', 'manage_promos');
$model = $this->getDi()['db']->getExistingModelById('Promo', $data['id'], 'Promo not found');
$model = $this->getService()->findPromoById((int) $data['id']);
return $this->getService()->deletePromo($model);
}
@@ -544,6 +557,6 @@ class Admin extends \FOSSBilling\Api\AbstractApi
#[RequiredParams(['id' => 'Product ID was not passed'])]
private function _getProduct($data)
{
return $this->getDi()['db']->getExistingModelById('Product', $data['id'], 'Product not found');
return $this->getService()->findProductById((int) $data['id']);
}
}
+4 -21
View File
@@ -16,7 +16,7 @@ declare(strict_types=1);
namespace Box\Mod\Product\Api;
use FOSSBilling\PaginationOptions;
use Box\Mod\Product\Entity\Product;
class Guest extends \FOSSBilling\Api\AbstractApi
{
@@ -30,15 +30,7 @@ class Guest extends \FOSSBilling\Api\AbstractApi
$data['status'] = 'enabled';
$data['show_hidden'] = false;
[$sql, $params] = $this->getService()->getProductSearchQuery($data);
$pager = $this->getDi()['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
foreach ($pager['list'] as $key => $item) {
$model = $this->getDi()['db']->getExistingModelById('Product', $item['id'], 'Post not found');
$pager['list'][$key] = $this->getService()->toApiArray($model, false);
}
return $pager;
return $this->getService()->getPaginatedProducts($data);
}
/**
@@ -78,7 +70,7 @@ class Guest extends \FOSSBilling\Api\AbstractApi
$model = $service->findOneActiveBySlug($slug);
}
if (!$model instanceof \Model_Product) {
if (!$model instanceof Product) {
throw new \FOSSBilling\Exception('Product not found');
}
@@ -93,17 +85,8 @@ class Guest extends \FOSSBilling\Api\AbstractApi
public function category_get_list($data)
{
$data['status'] = 'enabled';
$service = $this->getService();
[$sql, $params] = $service->getProductCategorySearchQuery($data);
$pager = $this->getDi()['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
foreach ($pager['list'] as $key => $item) {
$category = $this->getDi()['db']->getExistingModelById('ProductCategory', $item['id'], 'Product category not found');
$pager['list'][$key] = $this->getService()->toProductCategoryApiArray($category);
}
return $pager;
return $this->getService()->getPaginatedProductCategories($data);
}
/**
+406
View File
@@ -0,0 +1,406 @@
<?php
declare(strict_types=1);
/**
* Copyright 2022-2025 FOSSBilling
* Copyright 2011-2021 BoxBilling, Inc.
* 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 Box\Mod\Product\Entity;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: \Box\Mod\Product\Repository\ProductRepository::class)]
#[ORM\Table(name: 'product')]
class Product
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column(type: \Doctrine\DBAL\Types\Types::INTEGER)]
/** @phpstan-ignore property.unusedType (Doctrine entity ID is auto-generated by the database) */
private ?int $id = null;
#[ORM\Column(name: 'product_category_id', type: \Doctrine\DBAL\Types\Types::INTEGER, nullable: true)]
private ?int $productCategoryId = null;
#[ORM\Column(name: 'product_payment_id', type: \Doctrine\DBAL\Types\Types::INTEGER, nullable: true)]
private ?int $productPaymentId = null;
#[ORM\Column(name: 'form_id', type: \Doctrine\DBAL\Types\Types::INTEGER, nullable: true)]
private ?int $formId = null;
#[ORM\Column(type: \Doctrine\DBAL\Types\Types::STRING, length: 255, nullable: true)]
private ?string $title = null;
#[ORM\Column(type: \Doctrine\DBAL\Types\Types::STRING, length: 255, nullable: true)]
private ?string $slug = null;
#[ORM\Column(type: \Doctrine\DBAL\Types\Types::TEXT, nullable: true)]
private ?string $description = null;
#[ORM\Column(type: \Doctrine\DBAL\Types\Types::STRING, length: 50, options: ['default' => 'product'])]
private string $unit = 'product';
#[ORM\Column(type: \Doctrine\DBAL\Types\Types::BOOLEAN, options: ['default' => true])]
private bool $active = true;
#[ORM\Column(type: \Doctrine\DBAL\Types\Types::STRING, length: 50, options: ['default' => 'enabled'])]
private string $status = 'enabled';
#[ORM\Column(type: \Doctrine\DBAL\Types\Types::BOOLEAN, options: ['default' => false])]
private bool $hidden = false;
#[ORM\Column(name: 'is_addon', type: \Doctrine\DBAL\Types\Types::BOOLEAN, options: ['default' => false])]
private bool $isAddon = false;
#[ORM\Column(type: \Doctrine\DBAL\Types\Types::STRING, length: 50, options: ['default' => 'after_payment'])]
private string $setup = 'after_payment';
#[ORM\Column(type: \Doctrine\DBAL\Types\Types::TEXT, nullable: true)]
private ?string $addons = null;
#[ORM\Column(name: 'icon_url', type: \Doctrine\DBAL\Types\Types::STRING, length: 255, nullable: true)]
private ?string $iconUrl = null;
#[ORM\Column(name: 'allow_quantity_select', type: \Doctrine\DBAL\Types\Types::BOOLEAN, options: ['default' => false])]
private bool $allowQuantitySelect = false;
#[ORM\Column(name: 'stock_control', type: \Doctrine\DBAL\Types\Types::BOOLEAN, options: ['default' => false])]
private bool $stockControl = false;
#[ORM\Column(name: 'quantity_in_stock', type: \Doctrine\DBAL\Types\Types::INTEGER, options: ['default' => 0])]
private int $quantityInStock = 0;
#[ORM\Column(type: \Doctrine\DBAL\Types\Types::STRING, length: 255, nullable: true)]
private ?string $plugin = null;
#[ORM\Column(name: 'plugin_config', type: \Doctrine\DBAL\Types\Types::TEXT, nullable: true)]
private ?string $pluginConfig = null;
#[ORM\Column(type: \Doctrine\DBAL\Types\Types::TEXT, nullable: true)]
private ?string $upgrades = null;
#[ORM\Column(type: \Doctrine\DBAL\Types\Types::INTEGER, nullable: true)]
private ?int $priority = null;
#[ORM\Column(type: \Doctrine\DBAL\Types\Types::TEXT, nullable: true)]
private ?string $config = null;
#[ORM\Column(name: 'created_at', type: \Doctrine\DBAL\Types\Types::DATETIME_MUTABLE, nullable: true)]
private ?\DateTime $createdAt = null;
#[ORM\Column(name: 'updated_at', type: \Doctrine\DBAL\Types\Types::DATETIME_MUTABLE, nullable: true)]
private ?\DateTime $updatedAt = null;
#[ORM\Column(type: \Doctrine\DBAL\Types\Types::STRING, length: 255, nullable: true)]
private ?string $type = null;
public function getId(): ?int
{
return $this->id;
}
public function getProductCategoryId(): ?int
{
return $this->productCategoryId;
}
public function setProductCategoryId(?int $productCategoryId): self
{
$this->productCategoryId = $productCategoryId;
return $this;
}
public function getProductPaymentId(): ?int
{
return $this->productPaymentId;
}
public function setProductPaymentId(?int $productPaymentId): self
{
$this->productPaymentId = $productPaymentId;
return $this;
}
public function getFormId(): ?int
{
return $this->formId;
}
public function setFormId(?int $formId): self
{
$this->formId = $formId;
return $this;
}
public function getTitle(): ?string
{
return $this->title;
}
public function setTitle(?string $title): self
{
$this->title = $title;
return $this;
}
public function getSlug(): ?string
{
return $this->slug;
}
public function setSlug(?string $slug): self
{
$this->slug = $slug;
return $this;
}
public function getDescription(): ?string
{
return $this->description;
}
public function setDescription(?string $description): self
{
$this->description = $description;
return $this;
}
public function getUnit(): string
{
return $this->unit;
}
public function setUnit(string $unit): self
{
$this->unit = $unit;
return $this;
}
public function isActive(): bool
{
return $this->active;
}
public function setActive(bool $active): self
{
$this->active = $active;
return $this;
}
public function getStatus(): string
{
return $this->status;
}
public function setStatus(string $status): self
{
$this->status = $status;
return $this;
}
public function isHidden(): bool
{
return $this->hidden;
}
public function setHidden(bool $hidden): self
{
$this->hidden = $hidden;
return $this;
}
public function isAddon(): bool
{
return $this->isAddon;
}
public function setIsAddon(bool $isAddon): self
{
$this->isAddon = $isAddon;
return $this;
}
public function getSetup(): string
{
return $this->setup;
}
public function setSetup(string $setup): self
{
$this->setup = $setup;
return $this;
}
public function getAddons(): ?string
{
return $this->addons;
}
public function setAddons(?string $addons): self
{
$this->addons = $addons;
return $this;
}
public function getIconUrl(): ?string
{
return $this->iconUrl;
}
public function setIconUrl(?string $iconUrl): self
{
$this->iconUrl = $iconUrl;
return $this;
}
public function isAllowQuantitySelect(): bool
{
return $this->allowQuantitySelect;
}
public function setAllowQuantitySelect(bool $allowQuantitySelect): self
{
$this->allowQuantitySelect = $allowQuantitySelect;
return $this;
}
public function isStockControl(): bool
{
return $this->stockControl;
}
public function setStockControl(bool $stockControl): self
{
$this->stockControl = $stockControl;
return $this;
}
public function getQuantityInStock(): int
{
return $this->quantityInStock;
}
public function setQuantityInStock(int $quantityInStock): self
{
$this->quantityInStock = $quantityInStock;
return $this;
}
public function getPlugin(): ?string
{
return $this->plugin;
}
public function setPlugin(?string $plugin): self
{
$this->plugin = $plugin;
return $this;
}
public function getPluginConfig(): ?string
{
return $this->pluginConfig;
}
public function setPluginConfig(?string $pluginConfig): self
{
$this->pluginConfig = $pluginConfig;
return $this;
}
public function getUpgrades(): ?string
{
return $this->upgrades;
}
public function setUpgrades(?string $upgrades): self
{
$this->upgrades = $upgrades;
return $this;
}
public function getPriority(): ?int
{
return $this->priority;
}
public function setPriority(?int $priority): self
{
$this->priority = $priority;
return $this;
}
public function getConfig(): ?string
{
return $this->config;
}
public function setConfig(?string $config): self
{
$this->config = $config;
return $this;
}
public function getCreatedAt(): ?\DateTime
{
return $this->createdAt;
}
public function setCreatedAt(?\DateTime $createdAt): self
{
$this->createdAt = $createdAt;
return $this;
}
public function getUpdatedAt(): ?\DateTime
{
return $this->updatedAt;
}
public function setUpdatedAt(?\DateTime $updatedAt): self
{
$this->updatedAt = $updatedAt;
return $this;
}
public function getType(): ?string
{
return $this->type;
}
public function setType(?string $type): self
{
$this->type = $type;
return $this;
}
}
@@ -0,0 +1,106 @@
<?php
declare(strict_types=1);
/**
* Copyright 2022-2025 FOSSBilling
* Copyright 2011-2021 BoxBilling, Inc.
* 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 Box\Mod\Product\Entity;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: \Box\Mod\Product\Repository\ProductCategoryRepository::class)]
#[ORM\Table(name: 'product_category')]
class ProductCategory
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column(type: \Doctrine\DBAL\Types\Types::INTEGER)]
/** @phpstan-ignore property.unusedType (Doctrine entity ID is auto-generated by the database) */
private ?int $id = null;
#[ORM\Column(type: \Doctrine\DBAL\Types\Types::STRING, length: 100, nullable: true)]
private ?string $title = null;
#[ORM\Column(type: \Doctrine\DBAL\Types\Types::TEXT, nullable: true)]
private ?string $description = null;
#[ORM\Column(name: 'icon_url', type: \Doctrine\DBAL\Types\Types::STRING, length: 255, nullable: true)]
private ?string $iconUrl = null;
#[ORM\Column(name: 'created_at', type: \Doctrine\DBAL\Types\Types::DATETIME_MUTABLE, nullable: true)]
private ?\DateTime $createdAt = null;
#[ORM\Column(name: 'updated_at', type: \Doctrine\DBAL\Types\Types::DATETIME_MUTABLE, nullable: true)]
private ?\DateTime $updatedAt = null;
public function getId(): ?int
{
return $this->id;
}
public function getTitle(): ?string
{
return $this->title;
}
public function setTitle(?string $title): self
{
$this->title = $title;
return $this;
}
public function getDescription(): ?string
{
return $this->description;
}
public function setDescription(?string $description): self
{
$this->description = $description;
return $this;
}
public function getIconUrl(): ?string
{
return $this->iconUrl;
}
public function setIconUrl(?string $iconUrl): self
{
$this->iconUrl = $iconUrl;
return $this;
}
public function getCreatedAt(): ?\DateTime
{
return $this->createdAt;
}
public function setCreatedAt(?\DateTime $createdAt): self
{
$this->createdAt = $createdAt;
return $this;
}
public function getUpdatedAt(): ?\DateTime
{
return $this->updatedAt;
}
public function setUpdatedAt(?\DateTime $updatedAt): self
{
$this->updatedAt = $updatedAt;
return $this;
}
}
@@ -0,0 +1,176 @@
<?php
declare(strict_types=1);
/**
* Copyright 2022-2025 FOSSBilling
* Copyright 2011-2021 BoxBilling, Inc.
* 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 Box\Mod\Product\Entity;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: \Box\Mod\Product\Repository\ProductPaymentRepository::class)]
#[ORM\Table(name: 'product_payment')]
class ProductPayment
{
final public const string FREE = 'free';
final public const string ONCE = 'once';
final public const string RECURRENT = 'recurrent';
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column(type: \Doctrine\DBAL\Types\Types::INTEGER)]
private ?int $id = null;
#[ORM\Column(type: \Doctrine\DBAL\Types\Types::STRING, length: 30, nullable: true)]
private ?string $type = null;
#[ORM\Column(name: 'once_price', type: \Doctrine\DBAL\Types\Types::DECIMAL, precision: 18, scale: 2, options: ['default' => '0.00'])]
private string $oncePrice = '0.00';
#[ORM\Column(name: 'once_setup_price', type: \Doctrine\DBAL\Types\Types::DECIMAL, precision: 18, scale: 2, options: ['default' => '0.00'])]
private string $onceSetupPrice = '0.00';
#[ORM\Column(name: 'w_price', type: \Doctrine\DBAL\Types\Types::DECIMAL, precision: 18, scale: 2, options: ['default' => '0.00'])]
private string $wPrice = '0.00';
#[ORM\Column(name: 'm_price', type: \Doctrine\DBAL\Types\Types::DECIMAL, precision: 18, scale: 2, options: ['default' => '0.00'])]
private string $mPrice = '0.00';
#[ORM\Column(name: 'q_price', type: \Doctrine\DBAL\Types\Types::DECIMAL, precision: 18, scale: 2, options: ['default' => '0.00'])]
private string $qPrice = '0.00';
#[ORM\Column(name: 'b_price', type: \Doctrine\DBAL\Types\Types::DECIMAL, precision: 18, scale: 2, options: ['default' => '0.00'])]
private string $bPrice = '0.00';
#[ORM\Column(name: 'a_price', type: \Doctrine\DBAL\Types\Types::DECIMAL, precision: 18, scale: 2, options: ['default' => '0.00'])]
private string $aPrice = '0.00';
#[ORM\Column(name: 'bia_price', type: \Doctrine\DBAL\Types\Types::DECIMAL, precision: 18, scale: 2, options: ['default' => '0.00'])]
private string $biaPrice = '0.00';
#[ORM\Column(name: 'tria_price', type: \Doctrine\DBAL\Types\Types::DECIMAL, precision: 18, scale: 2, options: ['default' => '0.00'])]
private string $triaPrice = '0.00';
#[ORM\Column(name: 'w_setup_price', type: \Doctrine\DBAL\Types\Types::DECIMAL, precision: 18, scale: 2, options: ['default' => '0.00'])]
private string $wSetupPrice = '0.00';
#[ORM\Column(name: 'm_setup_price', type: \Doctrine\DBAL\Types\Types::DECIMAL, precision: 18, scale: 2, options: ['default' => '0.00'])]
private string $mSetupPrice = '0.00';
#[ORM\Column(name: 'q_setup_price', type: \Doctrine\DBAL\Types\Types::DECIMAL, precision: 18, scale: 2, options: ['default' => '0.00'])]
private string $qSetupPrice = '0.00';
#[ORM\Column(name: 'b_setup_price', type: \Doctrine\DBAL\Types\Types::DECIMAL, precision: 18, scale: 2, options: ['default' => '0.00'])]
private string $bSetupPrice = '0.00';
#[ORM\Column(name: 'a_setup_price', type: \Doctrine\DBAL\Types\Types::DECIMAL, precision: 18, scale: 2, options: ['default' => '0.00'])]
private string $aSetupPrice = '0.00';
#[ORM\Column(name: 'bia_setup_price', type: \Doctrine\DBAL\Types\Types::DECIMAL, precision: 18, scale: 2, options: ['default' => '0.00'])]
private string $biaSetupPrice = '0.00';
#[ORM\Column(name: 'tria_setup_price', type: \Doctrine\DBAL\Types\Types::DECIMAL, precision: 18, scale: 2, options: ['default' => '0.00'])]
private string $triaSetupPrice = '0.00';
#[ORM\Column(name: 'w_enabled', type: \Doctrine\DBAL\Types\Types::BOOLEAN, options: ['default' => true])]
private bool $wEnabled = true;
#[ORM\Column(name: 'm_enabled', type: \Doctrine\DBAL\Types\Types::BOOLEAN, options: ['default' => true])]
private bool $mEnabled = true;
#[ORM\Column(name: 'q_enabled', type: \Doctrine\DBAL\Types\Types::BOOLEAN, options: ['default' => true])]
private bool $qEnabled = true;
#[ORM\Column(name: 'b_enabled', type: \Doctrine\DBAL\Types\Types::BOOLEAN, options: ['default' => true])]
private bool $bEnabled = true;
#[ORM\Column(name: 'a_enabled', type: \Doctrine\DBAL\Types\Types::BOOLEAN, options: ['default' => true])]
private bool $aEnabled = true;
#[ORM\Column(name: 'bia_enabled', type: \Doctrine\DBAL\Types\Types::BOOLEAN, options: ['default' => true])]
private bool $biaEnabled = true;
#[ORM\Column(name: 'tria_enabled', type: \Doctrine\DBAL\Types\Types::BOOLEAN, options: ['default' => true])]
private bool $triaEnabled = true;
public function getId(): ?int
{
return $this->id;
}
public function getType(): ?string
{
return $this->type;
}
public function setType(?string $type): self
{
$this->type = $type;
return $this;
}
public function getOncePrice(): float
{
return (float) $this->oncePrice;
}
public function setOncePrice(float|int|string $price): self
{
$this->oncePrice = sprintf('%.2f', (float) $price);
return $this;
}
public function getOnceSetupPrice(): float
{
return (float) $this->onceSetupPrice;
}
public function setOnceSetupPrice(float|int|string $price): self
{
$this->onceSetupPrice = sprintf('%.2f', (float) $price);
return $this;
}
public function getPeriodPrice(string $prefix): float
{
$property = $prefix . 'Price';
return (float) $this->{$property};
}
public function getPeriodSetupPrice(string $prefix): float
{
$property = $prefix . 'SetupPrice';
return (float) $this->{$property};
}
public function isPeriodEnabled(string $prefix): bool
{
$property = $prefix . 'Enabled';
return (bool) $this->{$property};
}
public function setPeriodPricing(string $prefix, float|int|string $price, float|int|string $setupPrice, bool|int|string $enabled): self
{
$priceProperty = $prefix . 'Price';
$setupProperty = $prefix . 'SetupPrice';
$enabledProperty = $prefix . 'Enabled';
$this->{$priceProperty} = sprintf('%.2f', (float) $price);
$this->{$setupProperty} = sprintf('%.2f', (float) $setupPrice);
$this->{$enabledProperty} = (bool) $enabled;
return $this;
}
}
+326
View File
@@ -0,0 +1,326 @@
<?php
declare(strict_types=1);
/**
* Copyright 2022-2025 FOSSBilling
* Copyright 2011-2021 BoxBilling, Inc.
* 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 Box\Mod\Product\Entity;
use Doctrine\ORM\Mapping as ORM;
use FOSSBilling\Interfaces\ApiArrayInterface;
use FOSSBilling\Interfaces\TimestampInterface;
#[ORM\Entity(repositoryClass: \Box\Mod\Product\Repository\PromoRepository::class)]
#[ORM\Table(name: 'promo')]
#[ORM\HasLifecycleCallbacks]
class Promo implements ApiArrayInterface, TimestampInterface
{
final public const string ABSOLUTE = 'absolute';
final public const string PERCENTAGE = 'percentage';
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column(type: \Doctrine\DBAL\Types\Types::INTEGER)]
/** @phpstan-ignore property.unusedType (Doctrine entity ID is auto-generated by the database) */
private ?int $id = null;
#[ORM\Column(type: \Doctrine\DBAL\Types\Types::STRING, length: 100, nullable: true)]
private ?string $code = null;
#[ORM\Column(type: \Doctrine\DBAL\Types\Types::TEXT, nullable: true)]
private ?string $description = null;
#[ORM\Column(type: \Doctrine\DBAL\Types\Types::STRING, length: 30, options: ['default' => 'percentage'])]
private string $type = 'percentage';
#[ORM\Column(type: \Doctrine\DBAL\Types\Types::DECIMAL, precision: 18, scale: 2, nullable: true)]
private ?string $value = null;
#[ORM\Column(name: 'maxuses', type: \Doctrine\DBAL\Types\Types::INTEGER, options: ['default' => 0])]
private int $maxUses = 0;
#[ORM\Column(type: \Doctrine\DBAL\Types\Types::INTEGER, options: ['default' => 0])]
private int $used = 0;
#[ORM\Column(name: 'freesetup', type: \Doctrine\DBAL\Types\Types::BOOLEAN, options: ['default' => false])]
private bool $freeSetup = false;
#[ORM\Column(name: 'once_per_client', type: \Doctrine\DBAL\Types\Types::BOOLEAN, options: ['default' => false])]
private bool $oncePerClient = false;
#[ORM\Column(type: \Doctrine\DBAL\Types\Types::BOOLEAN, options: ['default' => false])]
private bool $recurring = false;
#[ORM\Column(type: \Doctrine\DBAL\Types\Types::BOOLEAN, options: ['default' => false])]
private bool $active = false;
#[ORM\Column(type: \Doctrine\DBAL\Types\Types::TEXT, nullable: true)]
private ?string $products = null;
#[ORM\Column(type: \Doctrine\DBAL\Types\Types::TEXT, nullable: true)]
private ?string $periods = null;
#[ORM\Column(name: 'client_groups', type: \Doctrine\DBAL\Types\Types::TEXT, nullable: true)]
private ?string $clientGroups = null;
#[ORM\Column(name: 'start_at', type: \Doctrine\DBAL\Types\Types::DATETIME_MUTABLE, nullable: true)]
private ?\DateTime $startAt = null;
#[ORM\Column(name: 'end_at', type: \Doctrine\DBAL\Types\Types::DATETIME_MUTABLE, nullable: true)]
private ?\DateTime $endAt = null;
#[ORM\Column(name: 'created_at', type: \Doctrine\DBAL\Types\Types::DATETIME_MUTABLE, nullable: true)]
private ?\DateTime $createdAt = null;
#[ORM\Column(name: 'updated_at', type: \Doctrine\DBAL\Types\Types::DATETIME_MUTABLE, nullable: true)]
private ?\DateTime $updatedAt = null;
public function toApiArray(): array
{
return [
'id' => $this->id,
'code' => $this->code,
'description' => $this->description,
'type' => $this->type,
'value' => $this->value !== null ? (float) $this->value : null,
'maxuses' => $this->maxUses,
'used' => $this->used,
'freesetup' => $this->freeSetup,
'once_per_client' => $this->oncePerClient,
'recurring' => $this->recurring,
'active' => $this->active,
'products' => $this->products,
'periods' => $this->periods,
'client_groups' => $this->clientGroups,
'start_at' => $this->startAt?->format('Y-m-d H:i:s'),
'end_at' => $this->endAt?->format('Y-m-d H:i:s'),
'created_at' => $this->createdAt?->format('Y-m-d H:i:s'),
'updated_at' => $this->updatedAt?->format('Y-m-d H:i:s'),
];
}
#[ORM\PrePersist]
public function onPrePersist(): void
{
$now = new \DateTime();
$this->createdAt ??= $now;
$this->updatedAt = $now;
}
#[ORM\PreUpdate]
public function updateTimestamp(): void
{
$this->updatedAt = new \DateTime();
}
public function getId(): ?int
{
return $this->id;
}
public function getCode(): ?string
{
return $this->code;
}
public function setCode(?string $code): self
{
$this->code = $code;
return $this;
}
public function getDescription(): ?string
{
return $this->description;
}
public function setDescription(?string $description): self
{
$this->description = $description;
return $this;
}
public function getType(): string
{
return $this->type;
}
public function setType(string $type): self
{
$this->type = $type;
return $this;
}
public function getValue(): ?float
{
return $this->value !== null ? (float) $this->value : null;
}
public function setValue(float|int|string|null $value): self
{
$this->value = $value !== null ? sprintf('%.2f', (float) $value) : null;
return $this;
}
public function getMaxUses(): int
{
return $this->maxUses;
}
public function setMaxUses(?int $maxUses): self
{
$this->maxUses = max(0, (int) ($maxUses ?? 0));
return $this;
}
public function getUsed(): int
{
return $this->used;
}
public function setUsed(?int $used): self
{
$this->used = max(0, (int) ($used ?? 0));
return $this;
}
public function isFreeSetup(): bool
{
return $this->freeSetup;
}
public function setFreeSetup(bool $freeSetup): self
{
$this->freeSetup = $freeSetup;
return $this;
}
public function isOncePerClient(): bool
{
return $this->oncePerClient;
}
public function setOncePerClient(bool $oncePerClient): self
{
$this->oncePerClient = $oncePerClient;
return $this;
}
public function isRecurring(): bool
{
return $this->recurring;
}
public function setRecurring(bool $recurring): self
{
$this->recurring = $recurring;
return $this;
}
public function isActive(): bool
{
return $this->active;
}
public function setActive(bool $active): self
{
$this->active = $active;
return $this;
}
public function getProducts(): ?string
{
return $this->products;
}
public function setProducts(?string $products): self
{
$this->products = $products;
return $this;
}
public function getPeriods(): ?string
{
return $this->periods;
}
public function setPeriods(?string $periods): self
{
$this->periods = $periods;
return $this;
}
public function getClientGroups(): ?string
{
return $this->clientGroups;
}
public function setClientGroups(?string $clientGroups): self
{
$this->clientGroups = $clientGroups;
return $this;
}
public function getStartAt(): ?\DateTime
{
return $this->startAt;
}
public function setStartAt(?\DateTime $startAt): self
{
$this->startAt = $startAt;
return $this;
}
public function getEndAt(): ?\DateTime
{
return $this->endAt;
}
public function setEndAt(?\DateTime $endAt): self
{
$this->endAt = $endAt;
return $this;
}
public function getCreatedAt(): ?\DateTime
{
return $this->createdAt;
}
public function setCreatedAt(?\DateTime $createdAt): void
{
$this->createdAt = $createdAt;
}
public function getUpdatedAt(): ?\DateTime
{
return $this->updatedAt;
}
public function setUpdatedAt(?\DateTime $updatedAt): void
{
$this->updatedAt = $updatedAt;
}
}
@@ -0,0 +1,265 @@
<?php
declare(strict_types=1);
/**
* Copyright 2022-2025 FOSSBilling
* Copyright 2011-2021 BoxBilling, Inc.
* 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 Box\Mod\Product\Entity;
use Doctrine\ORM\Mapping as ORM;
use FOSSBilling\Interfaces\ApiArrayInterface;
use FOSSBilling\Interfaces\TimestampInterface;
#[ORM\Entity(repositoryClass: \Box\Mod\Product\Repository\PromoRedemptionRepository::class)]
#[ORM\Table(name: 'promo_redemption')]
#[ORM\HasLifecycleCallbacks]
class PromoRedemption implements ApiArrayInterface, TimestampInterface
{
final public const string PHASE_CHECKOUT = 'checkout';
final public const string PHASE_RENEWAL = 'renewal';
final public const string STATUS_RESERVED = 'reserved';
final public const string STATUS_COMMITTED = 'committed';
final public const string STATUS_RELEASED = 'released';
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column(type: \Doctrine\DBAL\Types\Types::INTEGER)]
/** @phpstan-ignore property.unusedType (Doctrine entity ID is auto-generated by the database) */
private ?int $id = null;
#[ORM\Column(name: 'promo_id', type: \Doctrine\DBAL\Types\Types::INTEGER, nullable: true)]
private ?int $promoId = null;
#[ORM\Column(name: 'client_id', type: \Doctrine\DBAL\Types\Types::INTEGER, nullable: true)]
private ?int $clientId = null;
#[ORM\Column(name: 'client_order_id', type: \Doctrine\DBAL\Types\Types::INTEGER, nullable: true)]
private ?int $clientOrderId = null;
#[ORM\Column(name: 'invoice_id', type: \Doctrine\DBAL\Types\Types::INTEGER, nullable: true)]
private ?int $invoiceId = null;
#[ORM\Column(type: \Doctrine\DBAL\Types\Types::STRING, length: 30)]
private string $phase = self::PHASE_CHECKOUT;
#[ORM\Column(type: \Doctrine\DBAL\Types\Types::STRING, length: 30)]
private string $status = self::STATUS_RESERVED;
#[ORM\Column(name: 'discount_amount', type: \Doctrine\DBAL\Types\Types::DECIMAL, precision: 18, scale: 2, nullable: true)]
private ?string $discountAmount = null;
#[ORM\Column(type: \Doctrine\DBAL\Types\Types::STRING, length: 20, nullable: true)]
private ?string $currency = null;
#[ORM\Column(name: 'committed_at', type: \Doctrine\DBAL\Types\Types::DATETIME_MUTABLE, nullable: true)]
private ?\DateTime $committedAt = null;
#[ORM\Column(name: 'released_at', type: \Doctrine\DBAL\Types\Types::DATETIME_MUTABLE, nullable: true)]
private ?\DateTime $releasedAt = null;
#[ORM\Column(name: 'release_reason', type: \Doctrine\DBAL\Types\Types::STRING, length: 100, nullable: true)]
private ?string $releaseReason = null;
#[ORM\Column(name: 'created_at', type: \Doctrine\DBAL\Types\Types::DATETIME_MUTABLE, nullable: true)]
private ?\DateTime $createdAt = null;
#[ORM\Column(name: 'updated_at', type: \Doctrine\DBAL\Types\Types::DATETIME_MUTABLE, nullable: true)]
private ?\DateTime $updatedAt = null;
public function toApiArray(): array
{
return [
'id' => $this->id,
'promo_id' => $this->promoId,
'client_id' => $this->clientId,
'client_order_id' => $this->clientOrderId,
'invoice_id' => $this->invoiceId,
'phase' => $this->phase,
'status' => $this->status,
'discount_amount' => $this->discountAmount !== null ? (float) $this->discountAmount : null,
'currency' => $this->currency,
'committed_at' => $this->committedAt?->format('Y-m-d H:i:s'),
'released_at' => $this->releasedAt?->format('Y-m-d H:i:s'),
'release_reason' => $this->releaseReason,
'created_at' => $this->createdAt?->format('Y-m-d H:i:s'),
'updated_at' => $this->updatedAt?->format('Y-m-d H:i:s'),
];
}
#[ORM\PrePersist]
public function onPrePersist(): void
{
$now = new \DateTime();
$this->createdAt ??= $now;
$this->updatedAt = $now;
}
#[ORM\PreUpdate]
public function updateTimestamp(): void
{
$this->updatedAt = new \DateTime();
}
public function getId(): ?int
{
return $this->id;
}
public function getPromoId(): ?int
{
return $this->promoId;
}
public function setPromoId(?int $promoId): self
{
$this->promoId = $promoId;
return $this;
}
public function getClientId(): ?int
{
return $this->clientId;
}
public function setClientId(?int $clientId): self
{
$this->clientId = $clientId;
return $this;
}
public function getClientOrderId(): ?int
{
return $this->clientOrderId;
}
public function setClientOrderId(?int $clientOrderId): self
{
$this->clientOrderId = $clientOrderId;
return $this;
}
public function getInvoiceId(): ?int
{
return $this->invoiceId;
}
public function setInvoiceId(?int $invoiceId): self
{
$this->invoiceId = $invoiceId;
return $this;
}
public function getPhase(): string
{
return $this->phase;
}
public function setPhase(string $phase): self
{
$this->phase = $phase;
return $this;
}
public function getStatus(): string
{
return $this->status;
}
public function setStatus(string $status): self
{
$this->status = $status;
return $this;
}
public function getDiscountAmount(): ?float
{
return $this->discountAmount !== null ? (float) $this->discountAmount : null;
}
public function setDiscountAmount(?float $discountAmount): self
{
$this->discountAmount = $discountAmount !== null ? sprintf('%.2f', $discountAmount) : null;
return $this;
}
public function getCurrency(): ?string
{
return $this->currency;
}
public function setCurrency(?string $currency): self
{
$this->currency = $currency;
return $this;
}
public function getCommittedAt(): ?\DateTime
{
return $this->committedAt;
}
public function setCommittedAt(?\DateTime $committedAt): self
{
$this->committedAt = $committedAt;
return $this;
}
public function getReleasedAt(): ?\DateTime
{
return $this->releasedAt;
}
public function setReleasedAt(?\DateTime $releasedAt): self
{
$this->releasedAt = $releasedAt;
return $this;
}
public function getReleaseReason(): ?string
{
return $this->releaseReason;
}
public function setReleaseReason(?string $releaseReason): self
{
$this->releaseReason = $releaseReason;
return $this;
}
public function getCreatedAt(): ?\DateTime
{
return $this->createdAt;
}
public function setCreatedAt(\DateTime $createdAt): void
{
$this->createdAt = $createdAt;
}
public function getUpdatedAt(): ?\DateTime
{
return $this->updatedAt;
}
public function setUpdatedAt(\DateTime $updatedAt): void
{
$this->updatedAt = $updatedAt;
}
}
@@ -0,0 +1,58 @@
<?php
declare(strict_types=1);
/**
* Copyright 2022-2025 FOSSBilling
* Copyright 2011-2021 BoxBilling, Inc.
* 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 Box\Mod\Product\Repository;
use Doctrine\DBAL\Connection;
class DomainPricingRepository
{
public function __construct(private readonly Connection $connection)
{
}
/**
* @return array<mixed, array<'active'|'allow_register'|'allow_transfer'|'min_years'|'price_registration'|'price_renew'|'price_transfer'|'registrar'|'tld', mixed>>
*/
public function getActivePricingByTld(): array
{
$pricing = [];
$query = $this->connection->createQueryBuilder();
$query
->select('t.*', 'r.name')
->from('tld', 't')
->leftJoin('t', 'tld_registrar', 'r', 'r.id = t.tld_registrar_id')
->where('t.active = 1')
->orderBy('t.id', 'ASC');
$results = $query->executeQuery()->fetchAllAssociative();
foreach ($results as $tld) {
$pricing[$tld['tld']] = [
'tld' => $tld['tld'],
'price_registration' => $tld['price_registration'],
'price_renew' => $tld['price_renew'],
'price_transfer' => $tld['price_transfer'],
'active' => $tld['active'],
'allow_register' => $tld['allow_register'],
'allow_transfer' => $tld['allow_transfer'],
'min_years' => $tld['min_years'],
'registrar' => [
'id' => $tld['tld_registrar_id'],
'title' => $tld['name'],
],
];
}
return $pricing;
}
}
@@ -0,0 +1,60 @@
<?php
declare(strict_types=1);
/**
* Copyright 2022-2025 FOSSBilling
* Copyright 2011-2021 BoxBilling, Inc.
* 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 Box\Mod\Product\Repository;
use Box\Mod\Product\Entity\Product;
use Box\Mod\Product\Entity\ProductCategory;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\QueryBuilder;
class ProductCategoryRepository extends EntityRepository
{
/**
* @return array<int, string|null>
*/
public function getPairs(): array
{
$rows = $this->createQueryBuilder('c')
->select('c.id, c.title')
->orderBy('c.id', 'ASC')
->getQuery()
->getArrayResult();
$pairs = [];
foreach ($rows as $row) {
$pairs[(int) $row['id']] = $row['title'];
}
return $pairs;
}
public function getEnabledVisibleSearchQueryBuilder(): QueryBuilder
{
return $this->createQueryBuilder('c')
->innerJoin(Product::class, 'p', 'WITH', 'p.productCategoryId = c.id')
->andWhere('p.status = :status')
->andWhere('p.hidden = :hidden')
->andWhere('p.isAddon = :isAddon')
->setParameter('status', 'enabled')
->setParameter('hidden', false)
->setParameter('isAddon', false)
->addSelect('MAX(p.priority) AS HIDDEN maxPriority')
->groupBy('c.id')
->orderBy('maxPriority', 'ASC');
}
public function findById(int $id): ?ProductCategory
{
return $this->find($id);
}
}
@@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
/**
* Copyright 2022-2025 FOSSBilling
* Copyright 2011-2021 BoxBilling, Inc.
* 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 Box\Mod\Product\Repository;
use Doctrine\DBAL\Connection;
class ProductOrderRepository
{
public function __construct(private readonly Connection $connection)
{
}
/**
* @return list<array<string, mixed>>
*/
public function getRowsByProductId(int $productId): array
{
return $this->connection->fetchAllAssociative(
'SELECT * FROM client_order WHERE product_id = ?',
[$productId]
);
}
}
@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
/**
* Copyright 2022-2025 FOSSBilling
* Copyright 2011-2021 BoxBilling, Inc.
* 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 Box\Mod\Product\Repository;
use Doctrine\ORM\EntityRepository;
class ProductPaymentRepository extends EntityRepository
{
}
@@ -0,0 +1,201 @@
<?php
declare(strict_types=1);
/**
* Copyright 2022-2025 FOSSBilling
* Copyright 2011-2021 BoxBilling, Inc.
* 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 Box\Mod\Product\Repository;
use Box\Mod\Product\Entity\Product;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\QueryBuilder;
class ProductRepository extends EntityRepository
{
/**
* @return array<int, string|null>
*/
public function getPairs(array $data): array
{
$qb = $this->createQueryBuilder('p')
->select('p.id, p.title');
if ($data['products_only'] ?? true) {
$qb->andWhere('p.isAddon = :isAddon')
->setParameter('isAddon', false);
}
if ($data['active_only'] ?? true) {
$qb->andWhere('p.active = :active')
->setParameter('active', true);
}
if (!empty($data['type'])) {
$qb->andWhere('p.type = :type')
->setParameter('type', $data['type']);
}
$rows = $qb->orderBy('p.id', 'ASC')
->getQuery()
->getArrayResult();
$pairs = [];
foreach ($rows as $row) {
$pairs[(int) $row['id']] = $row['title'];
}
return $pairs;
}
public function getSearchQueryBuilder(array $data): QueryBuilder
{
$qb = $this->createQueryBuilder('p')
->where('p.isAddon = :isAddon')
->setParameter('isAddon', false);
if (!empty($data['type'])) {
$qb->andWhere('p.type = :type')
->setParameter('type', $data['type']);
}
if (!empty($data['status'])) {
$qb->andWhere('p.status = :status')
->setParameter('status', $data['status']);
}
if (!($data['show_hidden'] ?? true)) {
$qb->andWhere('p.hidden = :hidden')
->setParameter('hidden', false);
}
if (!empty($data['search'])) {
$qb->andWhere('p.title LIKE :search')
->setParameter('search', '%' . $data['search'] . '%');
}
return $qb->orderBy('p.priority', 'ASC');
}
public function findActiveById(int $id): ?Product
{
return $this->findOneBy([
'id' => $id,
'active' => true,
'status' => 'enabled',
'isAddon' => false,
]);
}
public function findActiveBySlug(string $slug): ?Product
{
return $this->findOneBy([
'slug' => $slug,
'active' => true,
'status' => 'enabled',
'isAddon' => false,
]);
}
public function findMainDomainProduct(): ?Product
{
return $this->findOneBy([
'type' => 'domain',
'isAddon' => false,
]);
}
public function hasProductsInCategory(int $categoryId): bool
{
$count = $this->createQueryBuilder('p')
->select('COUNT(p.id)')
->where('p.productCategoryId = :categoryId')
->setParameter('categoryId', $categoryId)
->getQuery()
->getSingleScalarResult();
return (int) $count > 0;
}
/**
* @return list<Product>
*/
public function findEnabledVisibleByCategoryId(int $categoryId): array
{
return $this->findBy([
'isAddon' => false,
'status' => 'enabled',
'hidden' => false,
'productCategoryId' => $categoryId,
], [
'priority' => 'ASC',
]);
}
/**
* @param list<int> $ids
*
* @return list<Product>
*/
public function findByIds(array $ids): array
{
if ($ids === []) {
return [];
}
return $this->findBy([
'id' => $ids,
]);
}
/**
* @param list<int> $ids
*
* @return list<Product>
*/
public function findAddonsByIds(array $ids, ?int $excludeId = null, bool $includeUnavailable = false): array
{
if ($ids === []) {
return [];
}
$qb = $this->createQueryBuilder('p')
->where('p.type = :type')
->andWhere('p.isAddon = :isAddon')
->andWhere('p.id IN (:ids)')
->setParameter('type', 'custom')
->setParameter('isAddon', true)
->setParameter('ids', $ids)
->orderBy('p.id', 'ASC');
if (!$includeUnavailable) {
$qb->andWhere('p.active = :active')
->andWhere('p.status = :status')
->setParameter('active', true)
->setParameter('status', 'enabled');
}
if ($excludeId !== null) {
$qb->andWhere('p.id != :excludeId')
->setParameter('excludeId', $excludeId);
}
return $qb->getQuery()->getResult();
}
public function findEnabledAddonById(int $id): ?Product
{
return $this->findOneBy([
'id' => $id,
'type' => 'custom',
'isAddon' => true,
'active' => true,
'status' => 'enabled',
]);
}
}
@@ -0,0 +1,131 @@
<?php
declare(strict_types=1);
/**
* Copyright 2022-2025 FOSSBilling
* Copyright 2011-2021 BoxBilling, Inc.
* 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 Box\Mod\Product\Repository;
use Box\Mod\Product\Entity\PromoRedemption;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\QueryBuilder;
class PromoRedemptionRepository extends EntityRepository
{
public function getSearchQueryBuilder(array $data): QueryBuilder
{
$qb = $this->createQueryBuilder('pr');
if (!empty($data['promo_id'])) {
$qb->andWhere('pr.promoId = :promoId')
->setParameter('promoId', $data['promo_id']);
}
if (!empty($data['client_id'])) {
$qb->andWhere('pr.clientId = :clientId')
->setParameter('clientId', $data['client_id']);
}
if (!empty($data['client_order_id'])) {
$qb->andWhere('pr.clientOrderId = :clientOrderId')
->setParameter('clientOrderId', $data['client_order_id']);
}
if (!empty($data['phase'])) {
$qb->andWhere('pr.phase = :phase')
->setParameter('phase', $data['phase']);
}
if (!empty($data['status'])) {
$qb->andWhere('pr.status = :status')
->setParameter('status', $data['status']);
}
$qb->orderBy('pr.id', 'DESC');
return $qb;
}
public function clientHasActiveCheckoutApplication(int $promoId, int $clientId): bool
{
$count = (int) $this->createQueryBuilder('pr')
->select('COUNT(pr.id)')
->where('pr.promoId = :promoId')
->andWhere('pr.clientId = :clientId')
->andWhere('pr.phase = :phase')
->andWhere('pr.status IN (:statuses)')
->setParameter('promoId', $promoId)
->setParameter('clientId', $clientId)
->setParameter('phase', PromoRedemption::PHASE_CHECKOUT)
->setParameter('statuses', [PromoRedemption::STATUS_RESERVED, PromoRedemption::STATUS_COMMITTED])
->getQuery()
->getSingleScalarResult();
return $count > 0;
}
public function countByPromoId(int $promoId): int
{
return (int) $this->createQueryBuilder('pr')
->select('COUNT(pr.id)')
->where('pr.promoId = :promoId')
->setParameter('promoId', $promoId)
->getQuery()
->getSingleScalarResult();
}
/**
* @return array{
* recorded_applications: int,
* checkout_applications: int,
* renewal_applications: int,
* active_checkout_applications: int,
* reserved_applications: int,
* committed_applications: int,
* released_applications: int,
* distinct_clients: int,
* orders_using_promo: int
* }
*/
public function getUsageStatsByPromoId(int $promoId): array
{
$stats = $this->createQueryBuilder('pr')
->select('COUNT(pr.id) AS recorded_applications')
->addSelect('SUM(CASE WHEN pr.phase = :checkoutPhase THEN 1 ELSE 0 END) AS checkout_applications')
->addSelect('SUM(CASE WHEN pr.phase = :renewalPhase THEN 1 ELSE 0 END) AS renewal_applications')
->addSelect('SUM(CASE WHEN pr.phase = :checkoutPhase AND pr.status IN (:activeStatuses) THEN 1 ELSE 0 END) AS active_checkout_applications')
->addSelect('SUM(CASE WHEN pr.status = :reservedStatus THEN 1 ELSE 0 END) AS reserved_applications')
->addSelect('SUM(CASE WHEN pr.status = :committedStatus THEN 1 ELSE 0 END) AS committed_applications')
->addSelect('SUM(CASE WHEN pr.status = :releasedStatus THEN 1 ELSE 0 END) AS released_applications')
->addSelect('COUNT(DISTINCT pr.clientId) AS distinct_clients')
->addSelect('COUNT(DISTINCT pr.clientOrderId) AS orders_using_promo')
->where('pr.promoId = :promoId')
->setParameter('promoId', $promoId)
->setParameter('checkoutPhase', PromoRedemption::PHASE_CHECKOUT)
->setParameter('renewalPhase', PromoRedemption::PHASE_RENEWAL)
->setParameter('activeStatuses', [PromoRedemption::STATUS_RESERVED, PromoRedemption::STATUS_COMMITTED])
->setParameter('reservedStatus', PromoRedemption::STATUS_RESERVED)
->setParameter('committedStatus', PromoRedemption::STATUS_COMMITTED)
->setParameter('releasedStatus', PromoRedemption::STATUS_RELEASED)
->getQuery()
->getSingleResult();
return [
'recorded_applications' => (int) ($stats['recorded_applications'] ?? 0),
'checkout_applications' => (int) ($stats['checkout_applications'] ?? 0),
'renewal_applications' => (int) ($stats['renewal_applications'] ?? 0),
'active_checkout_applications' => (int) ($stats['active_checkout_applications'] ?? 0),
'reserved_applications' => (int) ($stats['reserved_applications'] ?? 0),
'committed_applications' => (int) ($stats['committed_applications'] ?? 0),
'released_applications' => (int) ($stats['released_applications'] ?? 0),
'distinct_clients' => (int) ($stats['distinct_clients'] ?? 0),
'orders_using_promo' => (int) ($stats['orders_using_promo'] ?? 0),
];
}
}
@@ -0,0 +1,99 @@
<?php
declare(strict_types=1);
/**
* Copyright 2022-2025 FOSSBilling
* Copyright 2011-2021 BoxBilling, Inc.
* 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 Box\Mod\Product\Repository;
use Box\Mod\Product\Entity\Promo;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\QueryBuilder;
class PromoRepository extends EntityRepository
{
public function getSearchQueryBuilder(array $data): QueryBuilder
{
$qb = $this->createQueryBuilder('p');
$now = new \DateTimeImmutable();
if (!empty($data['id'])) {
$qb->andWhere('p.id = :id')
->setParameter('id', (int) $data['id']);
}
if (!empty($data['search'])) {
$qb->andWhere('p.code LIKE :search')
->setParameter('search', '%' . $data['search'] . '%');
}
switch ($data['status'] ?? null) {
case 'active':
$qb->andWhere('p.active = :active')
->andWhere('(p.startAt IS NULL OR p.startAt <= :now)')
->andWhere('(p.endAt IS NULL OR p.endAt >= :now)')
->setParameter('active', true)
->setParameter('now', $now);
break;
case 'not-started':
$qb->andWhere('p.startAt IS NOT NULL')
->andWhere('p.startAt > :now')
->setParameter('now', $now);
break;
case 'expired':
$qb->andWhere('p.endAt IS NOT NULL')
->andWhere('p.endAt < :now')
->setParameter('now', $now);
break;
}
$qb->orderBy('p.id', 'ASC');
return $qb;
}
public function findActiveByCode(string $code): ?Promo
{
return $this->findOneBy([
'code' => $code,
'active' => true,
], [
'id' => 'ASC',
]);
}
public function incrementUsageIfAvailable(int $promoId, \DateTimeInterface $updatedAt): int
{
return $this->getEntityManager()->getConnection()->executeStatement(
'UPDATE promo SET used = used + 1, updated_at = ? WHERE id = ? AND (maxuses = 0 OR maxuses IS NULL OR maxuses > used)',
[$updatedAt->format('Y-m-d H:i:s'), $promoId]
);
}
public function decrementUsage(int $promoId, int $count, \DateTimeInterface $updatedAt): int
{
return $this->getEntityManager()->getConnection()->executeStatement(
'UPDATE promo SET used = GREATEST(used - ?, 0), updated_at = ? WHERE id = ?',
[$count, $updatedAt->format('Y-m-d H:i:s'), $promoId]
);
}
public function countLinkedOrdersByPromoId(int $promoId): int
{
return (int) $this->getEntityManager()->getConnection()->fetchOne(
'SELECT COUNT(id) FROM client_order WHERE promo_id = ?',
[$promoId]
);
}
}
File diff suppressed because it is too large. Load diff
@@ -24,6 +24,108 @@
{% endblock %}
{% block content %}
<div class="card">
<div class="card-body">
<h3>{{ 'Manage Promotion'|trans }}</h3>
{% if not promo.can_be_deleted %}
<div class="alert alert-info" role="alert">
{{ 'This promotion has redemption history and can no longer be deleted. Disable it to archive it.'|trans }}
</div>
{% endif %}
{% set stats = promo.usage_stats %}
<div class="row row-cards mb-4">
<div class="col-sm-6 col-lg-4">
<div class="card card-sm">
<div class="card-body">
<div class="text-secondary">{{ 'Recorded Applications'|trans }}</div>
<div class="h2 m-0">{{ stats.recorded_applications }}</div>
</div>
</div>
</div>
<div class="col-sm-6 col-lg-4">
<div class="card card-sm">
<div class="card-body">
<div class="text-secondary">{{ 'Checkout Applications'|trans }}</div>
<div class="h2 m-0">{{ stats.checkout_applications }}</div>
</div>
</div>
</div>
<div class="col-sm-6 col-lg-4">
<div class="card card-sm">
<div class="card-body">
<div class="text-secondary">{{ 'Renewal Applications'|trans }}</div>
<div class="h2 m-0">{{ stats.renewal_applications }}</div>
</div>
</div>
</div>
<div class="col-sm-6 col-lg-4">
<div class="card card-sm">
<div class="card-body">
<div class="text-secondary">{{ 'Reserved Applications'|trans }}</div>
<div class="h2 m-0">{{ stats.reserved_applications }}</div>
</div>
</div>
</div>
<div class="col-sm-6 col-lg-4">
<div class="card card-sm">
<div class="card-body">
<div class="text-secondary">{{ 'Committed Applications'|trans }}</div>
<div class="h2 m-0">{{ stats.committed_applications }}</div>
</div>
</div>
</div>
<div class="col-sm-6 col-lg-4">
<div class="card card-sm">
<div class="card-body">
<div class="text-secondary">{{ 'Released Applications'|trans }}</div>
<div class="h2 m-0">{{ stats.released_applications }}</div>
</div>
</div>
</div>
<div class="col-sm-6 col-lg-4">
<div class="card card-sm">
<div class="card-body">
<div class="text-secondary">{{ 'Distinct Clients'|trans }}</div>
<div class="h2 m-0">{{ stats.distinct_clients }}</div>
</div>
</div>
</div>
<div class="col-sm-6 col-lg-4">
<div class="card card-sm">
<div class="card-body">
<div class="text-secondary">{{ 'Orders Using Promo'|trans }}</div>
<div class="h2 m-0">{{ stats.orders_using_promo }}</div>
</div>
</div>
</div>
<div class="col-sm-6 col-lg-4">
<div class="card card-sm">
<div class="card-body">
<div class="text-secondary">{{ 'Operational Counter'|trans }}</div>
<div class="h2 m-0">
{{ stats.operational_use_count }}
{% if stats.max_uses is not null %}/ {{ stats.max_uses }}{% else %}/ &#8734;{% endif %}
</div>
<div class="text-secondary small">
{{ 'Used only for max-use enforcement, not historical reporting.'|trans }}
</div>
<div class="text-secondary small">
{{ 'Active checkout applications'|trans }}: {{ stats.active_checkout_applications }}
</div>
<div class="text-secondary small">
{% if stats.remaining_operational_uses is null %}
{{ 'Remaining operational uses'|trans }}: {{ 'Unlimited'|trans }}
{% else %}
{{ 'Remaining operational uses'|trans }}: {{ stats.remaining_operational_uses }}
{% endif %}
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="card">
<form method="post" action="{{ 'product/promo_update'|api_url }}" {{ fb_api_form({redirect: 'product/promos'|url}) }}>
{% embed 'partial_admin_form_card.html.twig' with {
@@ -50,7 +50,7 @@
<th>{{ 'Client Groups'|trans }}</th>
<th>{{ 'Validity Period'|trans }}</th>
<th>{{ 'Enabled'|trans }}</th>
<th>{{ 'Usage'|trans }}</th>
<th>{{ 'Limit Tracking'|trans }}</th>
<th class="w-1"></th>
</tr>
</thead>
@@ -81,19 +81,35 @@
until {% if promo.end_at %}{{ promo.end_at|format_date }}{% else %}disabled{% endif %}
</td>
<td>{{ mf.boolean_badge(promo.active, 'Yes'|trans, 'No'|trans, 'text-bg-success', 'text-bg-secondary') }}</td>
<td>{{ promo.used }} / {% if promo.maxuses %}{{ promo.maxuses }}{% else %}&#8734;{% endif %}</td>
<td>
{{ promo.used }} / {% if promo.maxuses %}{{ promo.maxuses }}{% else %}&#8734;{% endif %}
<div class="text-secondary small">{{ promo.redemption_count }} {{ 'recorded applications'|trans }}</div>
</td>
<td>
<a class="btn btn-icon" href='{{ "product/promo/#{promo.id}"|url }}'>
<svg class="icon">
<use href="#edit" />
</svg>
</a>
<a class="btn btn-icon" href="{{ 'product/promo_delete'|api_url(query: { 'id': promo.id }) }}"
{{ fb_api_link({modal: {type: 'confirm', title: 'Are you sure?'|trans}, redirect: 'product/promos'|url}) }}>
<a class="btn btn-icon" href='{{ "product/promo/#{promo.id}"|url }}#promo-redemptions' title="{{ 'View Redemption History'|trans }}">
<svg class="icon">
<use href="#trash" />
<use href="#eye" />
</svg>
</a>
{% if promo.can_be_deleted %}
<a class="btn btn-icon" href="{{ 'product/promo_delete'|api_url(query: { 'id': promo.id }) }}"
{{ fb_api_link({modal: {type: 'confirm', title: 'Are you sure?'|trans}, redirect: 'product/promos'|url}) }}>
<svg class="icon">
<use href="#trash" />
</svg>
</a>
{% else %}
<button class="btn btn-icon" type="button" disabled title="{{ 'Promotions with redemption history cannot be deleted'|trans }}">
<svg class="icon">
<use href="#trash" />
</svg>
</button>
{% endif %}
</td>
</tr>
{% else %}
+150 -351
View File
@@ -11,6 +11,9 @@
declare(strict_types=1);
use Box\Mod\Product\Api\Admin;
use Box\Mod\Product\Entity\Product;
use Box\Mod\Product\Entity\ProductCategory;
use Box\Mod\Product\Entity\Promo;
use Box\Mod\Product\Service;
use function Tests\Helpers\container;
@@ -19,246 +22,148 @@ test('gets dependency injection container', function (): void {
$api = new Admin();
$di = container();
$api->setDi($di);
$getDi = $api->getDi();
expect($getDi)->toBe($di);
expect($api->getDi())->toBe($di);
});
test('gets product list', function (): void {
$api = new Admin();
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('getProductSearchQuery')
->atLeast()->once()
->andReturn(['sqlString', []]);
$pagerMock = Mockery::mock(FOSSBilling\Pagination::class);
$pagerMock->shouldReceive('getPaginatedResultSet')
->atLeast()->once()
->andReturn(['list' => []]);
$di = container();
$di['pager'] = $pagerMock;
$serviceMock->shouldReceive('getPaginatedProducts')->once()->with([], null)->andReturn(['list' => []]);
$api->setService($serviceMock);
$api->setDi($di);
$result = $api->get_list([]);
expect($result)->toBeArray();
$api->setDi(container());
expect($api->get_list([]))->toBeArray();
});
test('gets product pairs', function (): void {
$api = new Admin();
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('getPairs')
->atLeast()->once()
->andReturn([]);
$serviceMock->shouldReceive('getPairs')->atLeast()->once()->andReturn([]);
$api->setService($serviceMock);
$result = $api->get_pairs([]);
expect($result)->toBeArray();
expect($api->get_pairs([]))->toBeArray();
});
test('gets a product', function (): void {
$api = new Admin();
$data = ['id' => 1];
$model = new Model_Product();
$model->loadBean(new Tests\Helpers\DummyBean());
$dbMock = Mockery::mock('\Box_Database');
$dbMock->shouldReceive('getExistingModelById')
->atLeast()->once()
->andReturn($model);
$model = new Product();
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('toApiArray')
->atLeast()->once()
->andReturn([]);
$serviceMock->shouldReceive('findProductById')->once()->with(1)->andReturn($model);
$serviceMock->shouldReceive('toApiArray')->once()->andReturn([]);
$di = container();
$di['db'] = $dbMock;
$api->setDi($di);
$api->setDi(container());
$api->setService($serviceMock);
$result = $api->get($data);
expect($result)->toBeArray();
expect($api->get($data))->toBeArray();
});
test('gets product types', function (): void {
$api = new Admin();
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('getTypes')
->atLeast()->once()
->andReturn([]);
$serviceMock->shouldReceive('getTypes')->atLeast()->once()->andReturn([]);
$api->setService($serviceMock);
$result = $api->get_types();
expect($result)->toBeArray();
expect($api->get_types())->toBeArray();
});
test('throws exception when preparing domain product already created', function (): void {
$api = new Admin();
$data = [
'title' => 'testTitle',
'type' => 'domain',
];
$data = ['title' => 'testTitle', 'type' => 'domain'];
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('getMainDomainProduct')
->atLeast()->once()
->andReturn(new Model_ProductDomain());
$serviceMock->shouldReceive('getMainDomainProduct')->atLeast()->once()->andReturn((new Product())->setType('domain'));
$di = container();
$api->setDi($di);
$api->setDi(container());
$api->setService($serviceMock);
expect(fn (): int => $api->prepare($data))
expect(fn () => $api->prepare($data))
->toThrow(FOSSBilling\Exception::class, 'You have already created domain product');
});
test('throws exception when preparing unrecognized product type', function (): void {
$api = new Admin();
$data = [
'title' => 'testTitle',
'type' => 'customForTestException',
];
$typeArray = [
'license' => 'License',
'domain' => 'Domain',
];
$data = ['title' => 'testTitle', 'type' => 'customForTestException'];
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('getTypes')
->atLeast()->once()
->andReturn($typeArray);
$serviceMock->shouldReceive('getTypes')->atLeast()->once()->andReturn(['license' => 'License', 'domain' => 'Domain']);
$di = container();
$api->setDi($di);
$api->setDi(container());
$api->setService($serviceMock);
expect(fn (): int => $api->prepare($data))
expect(fn () => $api->prepare($data))
->toThrow(FOSSBilling\Exception::class, "Product type {$data['type']} is not registered.");
});
test('prepares a product', function (): void {
$api = new Admin();
$data = [
'title' => 'testTitle',
'type' => 'license',
];
$typeArray = [
'license' => 'License',
'domain' => 'Domain',
];
$data = ['title' => 'testTitle', 'type' => 'license'];
$newProductId = 1;
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('getTypes')
->atLeast()->once()
->andReturn($typeArray);
$serviceMock->shouldReceive('getTypes')->atLeast()->once()->andReturn(['license' => 'License', 'domain' => 'Domain']);
$serviceMock->shouldReceive('createProduct')->atLeast()->once()->andReturn($newProductId);
$serviceMock->shouldReceive('createProduct')
->atLeast()->once()
->andReturn($newProductId);
$di = container();
$api->setDi($di);
$api->setDi(container());
$api->setService($serviceMock);
$result = $api->prepare($data);
expect($result)->toBeInt();
expect($result)->toBe($newProductId);
expect($api->prepare($data))->toBe($newProductId);
});
test('updates a product', function (): void {
$api = new Admin();
$data = ['id' => 1];
$model = new Model_Product();
$model->loadBean(new Tests\Helpers\DummyBean());
$dbMock = Mockery::mock('\Box_Database');
$dbMock->shouldReceive('getExistingModelById')
->atLeast()->once()
->andReturn($model);
$model = new Product();
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('updateProduct')
->atLeast()->once()
->andReturn(true);
$serviceMock->shouldReceive('findProductById')->once()->with(1)->andReturn($model);
$serviceMock->shouldReceive('updateProduct')->once()->andReturn(true);
$di = container();
$di['db'] = $dbMock;
$api->setDi($di);
$api->setDi(container());
$api->setService($serviceMock);
$result = $api->update($data);
expect($result)->toBeBool();
expect($result)->toBeTrue();
expect($api->update($data))->toBeTrue();
});
test('throws exception when updating priority without priority param', function (): void {
$api = new Admin();
$data = [];
$api->setDi(container());
expect(fn () => $api->update_priority($data))
expect(fn () => $api->update_priority([]))
->toThrow(FOSSBilling\Exception::class, 'priority params is missing');
});
test('updates priority', function (): void {
$api = new Admin();
$data = ['priority' => []];
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('updatePriority')
->atLeast()->once()
->andReturn(true);
$serviceMock->shouldReceive('updatePriority')->atLeast()->once()->andReturn(true);
$api->setService($serviceMock);
$result = $api->update_priority($data);
expect($result)->toBeBool();
expect($result)->toBeTrue();
expect($api->update_priority(['priority' => []]))->toBeTrue();
});
test('updates product config', function (): void {
$api = new Admin();
$data = ['id' => 1];
$model = new Model_Product();
$model->loadBean(new Tests\Helpers\DummyBean());
$dbMock = Mockery::mock('\Box_Database');
$dbMock->shouldReceive('getExistingModelById')
->atLeast()->once()
->andReturn($model);
$model = new Product();
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('updateConfig')
->atLeast()->once()
->andReturn(true);
$serviceMock->shouldReceive('findProductById')->once()->with(1)->andReturn($model);
$serviceMock->shouldReceive('updateConfig')->once()->andReturn(true);
$di = container();
$di['db'] = $dbMock;
$api->setDi($di);
$api->setDi(container());
$api->setService($serviceMock);
$result = $api->update_config($data);
expect($result)->toBeBool();
expect($result)->toBeTrue();
expect($api->update_config($data))->toBeTrue();
});
test('gets addon pairs', function (): void {
$api = new Admin();
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('getAddons')
->atLeast()->once()
->andReturn([]);
$serviceMock->shouldReceive('getAddons')->atLeast()->once()->andReturn([]);
$api->setService($serviceMock);
$result = $api->addon_get_pairs([]);
expect($result)->toBeArray();
expect($api->addon_get_pairs([]))->toBeArray();
});
test('creates an addon', function (): void {
@@ -267,180 +172,115 @@ test('creates an addon', function (): void {
$newAddonId = 1;
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('createAddon')
->atLeast()->once()
->andReturn($newAddonId);
$serviceMock->shouldReceive('createAddon')->atLeast()->once()->andReturn($newAddonId);
$di = container();
$api->setDi($di);
$api->setDi(container());
$api->setService($serviceMock);
$result = $api->addon_create($data);
expect($result)->toBeInt();
expect($result)->toBe($newAddonId);
expect($api->addon_create($data))->toBe($newAddonId);
});
test('gets an addon', function (): void {
$api = new Admin();
$data = ['id' => 1];
$model = new Model_Product();
$model->loadBean(new Tests\Helpers\DummyBean());
$model->is_addon = true;
$dbMock = Mockery::mock('\Box_Database');
$dbMock->shouldReceive('load')
->atLeast()->once()
->andReturn($model);
$model = new Product();
$reflection = new ReflectionProperty($model, 'isAddon');
$reflection->setAccessible(true);
$reflection->setValue($model, true);
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('toApiArray')
->atLeast()->once()
->andReturn([]);
$serviceMock->shouldReceive('findProductById')->once()->with(1)->andReturn($model);
$serviceMock->shouldReceive('toApiArray')->once()->andReturn([]);
$di = container();
$di['db'] = $dbMock;
$api->setDi($di);
$api->setDi(container());
$api->setService($serviceMock);
$result = $api->addon_get($data);
expect($result)->toBeArray();
expect($api->addon_get($data))->toBeArray();
});
test('updates an addon', function (): void {
$api = new Admin();
$data = ['id' => 1];
$apiMock = Mockery::mock(Admin::class)->makePartial();
$apiMock->shouldReceive('update')
->atLeast()->once()
->andReturn([]);
$apiMock = Mockery::mock(Admin::class . '[update]');
$apiMock->shouldReceive('update')->atLeast()->once()->andReturn([]);
$model = new Model_Product();
$model->loadBean(new Tests\Helpers\DummyBean());
$model->is_addon = true;
$model = new Product();
$reflection = new ReflectionProperty($model, 'isAddon');
$reflection->setAccessible(true);
$reflection->setValue($model, true);
$dbMock = Mockery::mock('\Box_Database');
$dbMock->shouldReceive('load')
->atLeast()->once()
->andReturn($model);
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('findProductById')->once()->with(1)->andReturn($model);
$di = container();
$di['db'] = $dbMock;
$di['logger'] = new Tests\Helpers\TestLogger();
$di['logger'] = new Box_Log();
$apiMock->setService($serviceMock);
$apiMock->setDi($di);
$result = $apiMock->addon_update($data);
expect($result)->toBeArray();
expect($apiMock->addon_update($data))->toBeArray();
});
test('deletes an addon', function (): void {
$api = new Admin();
$apiMock = Mockery::mock(Admin::class)->makePartial();
$apiMock->shouldReceive('delete')
->atLeast()->once()
->andReturn(true);
$apiMock = Mockery::mock(Admin::class . '[delete]');
$apiMock->shouldReceive('delete')->atLeast()->once()->andReturn(true);
$result = $apiMock->addon_delete([]);
expect($result)->toBeBool();
expect($result)->toBeTrue();
expect($apiMock->addon_delete([]))->toBeTrue();
});
test('deletes a product', function (): void {
$api = new Admin();
$data = ['id' => 1];
$model = new Model_Product();
$model->loadBean(new Tests\Helpers\DummyBean());
$dbMock = Mockery::mock('\Box_Database');
$dbMock->shouldReceive('getExistingModelById')
->atLeast()->once()
->andReturn($model);
$model = new Product();
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('deleteProduct')
->atLeast()->once()
->andReturn(true);
$di = container();
$di['db'] = $dbMock;
$serviceMock->shouldReceive('findProductById')->once()->with(1)->andReturn($model);
$serviceMock->shouldReceive('deleteProduct')->once()->andReturn(true);
$api->setService($serviceMock);
$api->setDi($di);
$api->setDi(container());
$result = $api->delete($data);
expect($result)->toBeBool();
expect($result)->toBeTrue();
expect($api->delete($data))->toBeTrue();
});
test('gets category pairs', function (): void {
$api = new Admin();
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('getProductCategoryPairs')
->atLeast()->once()
->andReturn([]);
$serviceMock->shouldReceive('getProductCategoryPairs')->atLeast()->once()->andReturn([]);
$api->setService($serviceMock);
$result = $api->category_get_pairs([]);
expect($result)->toBeArray();
expect($api->category_get_pairs([]))->toBeArray();
});
test('updates a category', function (): void {
$api = new Admin();
$data = ['id' => 1];
$model = new Model_ProductCategory();
$model->loadBean(new Tests\Helpers\DummyBean());
$dbMock = Mockery::mock('\Box_Database');
$dbMock->shouldReceive('getExistingModelById')
->atLeast()->once()
->andReturn($model);
$model = new ProductCategory();
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('updateCategory')
->atLeast()->once()
->andReturn(true);
$di = container();
$di['db'] = $dbMock;
$serviceMock->shouldReceive('findProductCategoryById')->once()->with(1)->andReturn($model);
$serviceMock->shouldReceive('updateCategory')->once()->andReturn(true);
$api->setService($serviceMock);
$api->setDi($di);
$api->setDi(container());
$result = $api->category_update($data);
expect($result)->toBeBool();
expect($result)->toBeTrue();
expect($api->category_update($data))->toBeTrue();
});
test('gets a category', function (): void {
$api = new Admin();
$data = ['id' => 1];
$model = new Model_ProductCategory();
$model->loadBean(new Tests\Helpers\DummyBean());
$dbMock = Mockery::mock('\Box_Database');
$dbMock->shouldReceive('getExistingModelById')
->atLeast()->once()
->andReturn($model);
$model = new ProductCategory();
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('toProductCategoryApiArray')
->atLeast()->once()
->andReturn([]);
$di = container();
$di['db'] = $dbMock;
$serviceMock->shouldReceive('findProductCategoryById')->once()->with(1)->andReturn($model);
$serviceMock->shouldReceive('toProductCategoryApiArray')->once()->andReturn([]);
$api->setService($serviceMock);
$api->setDi($di);
$api->setDi(container());
$result = $api->category_get($data);
expect($result)->toBeArray();
expect($api->category_get($data))->toBeArray();
});
test('creates a category', function (): void {
@@ -449,66 +289,47 @@ test('creates a category', function (): void {
$newCategoryId = 1;
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('createCategory')
->atLeast()->once()
->andReturn($newCategoryId);
$serviceMock->shouldReceive('createCategory')->atLeast()->once()->andReturn($newCategoryId);
$di = container();
$api->setDi($di);
$api->setDi(container());
$api->setService($serviceMock);
$result = $api->category_create($data);
expect($result)->toBeInt();
expect($result)->toBe($newCategoryId);
expect($api->category_create($data))->toBe($newCategoryId);
});
test('deletes a category', function (): void {
$api = new Admin();
$data = ['id' => 1];
$model = new Model_ProductCategory();
$model->loadBean(new Tests\Helpers\DummyBean());
$dbMock = Mockery::mock('\Box_Database');
$dbMock->shouldReceive('getExistingModelById')
->atLeast()->once()
->andReturn($model);
$model = new ProductCategory();
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('removeProductCategory')
->atLeast()->once()
->andReturn(true);
$di = container();
$di['db'] = $dbMock;
$serviceMock->shouldReceive('findProductCategoryById')->once()->with(1)->andReturn($model);
$serviceMock->shouldReceive('removeProductCategory')->once()->andReturn(true);
$api->setService($serviceMock);
$api->setDi($di);
$api->setDi(container());
$result = $api->category_delete($data);
expect($result)->toBeBool();
expect($result)->toBeTrue();
expect($api->category_delete($data))->toBeTrue();
});
test('gets promo list', function (): void {
$api = new Admin();
$qbMock = Mockery::mock(Doctrine\ORM\QueryBuilder::class);
$promo = ['id' => 1];
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('getPromoSearchQuery')
->atLeast()->once()
->andReturn(['sqlString', []]);
$serviceMock->shouldReceive('getPromoSearchQueryBuilder')->atLeast()->once()->andReturn($qbMock);
$serviceMock->shouldReceive('enrichPromoApiArray')->once()->with($promo)->andReturn(['id' => 1]);
$pagerMock = Mockery::mock(FOSSBilling\Pagination::class);
$pagerMock->shouldReceive('getPaginatedResultSet')
->atLeast()->once()
->andReturn(['list' => []]);
$pagerMock->shouldReceive('paginateDoctrineQuery')->atLeast()->once()->andReturn(['list' => [$promo]]);
$di = container();
$di['pager'] = $pagerMock;
$api->setService($serviceMock);
$api->setDi($di);
$result = $api->promo_get_list([]);
expect($result)->toBeArray();
expect($api->promo_get_list([]))->toBeArray();
});
test('creates a promo', function (): void {
@@ -523,112 +344,90 @@ test('creates a promo', function (): void {
$newPromoId = 1;
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('createPromo')
->atLeast()->once()
->andReturn($newPromoId);
$serviceMock->shouldReceive('createPromo')->atLeast()->once()->andReturn($newPromoId);
$di = container();
$api->setDi($di);
$api->setDi(container());
$api->setService($serviceMock);
$result = $api->promo_create($data);
expect($result)->toBeInt();
expect($result)->toBe($newPromoId);
expect($api->promo_create($data))->toBe($newPromoId);
});
test('throws exception when getting promo without id', function (): void {
test('gets a promo without explicit id delegates to service', function (): void {
$api = new Admin();
$data = [];
$promo = new Promo();
$dbMock = Mockery::mock('\Box_Database');
$dbMock->shouldReceive('getExistingModelById')
->atLeast()->once()
->andThrow(new FOSSBilling\InformationException('Promo ID was not passed'));
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('findPromoById')->atLeast()->once()->andReturn($promo);
$serviceMock->shouldReceive('toPromoApiArray')->atLeast()->once()->andReturn([]);
$di = container();
$di['db'] = $dbMock;
$api->setDi($di);
$api->setService($serviceMock);
$api->setDi(container());
expect(fn () => $api->promo_get($data))
->toThrow(FOSSBilling\Exception::class, 'Promo ID was not passed');
expect($api->promo_get([]))->toBeArray();
});
test('gets a promo', function (): void {
$api = new Admin();
$data = ['id' => 1];
$model = new Model_Promo();
$model->loadBean(new Tests\Helpers\DummyBean());
$dbMock = Mockery::mock('\Box_Database');
$dbMock->shouldReceive('getExistingModelById')
->atLeast()->once()
->andReturn($model);
$di = container();
$di['db'] = $dbMock;
$promo = new Promo();
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('toPromoApiArray')
->atLeast()->once()
->andReturn([]);
$serviceMock->shouldReceive('findPromoById')->atLeast()->once()->with(1)->andReturn($promo);
$serviceMock->shouldReceive('toPromoApiArray')->atLeast()->once()->andReturn([]);
$api->setService($serviceMock);
$api->setDi(container());
expect($api->promo_get($data))->toBeArray();
});
test('gets promo redemption list', function (): void {
$api = new Admin();
$qbMock = Mockery::mock(Doctrine\ORM\QueryBuilder::class);
$repoMock = Mockery::mock(Box\Mod\Product\Repository\PromoRedemptionRepository::class);
$repoMock->shouldReceive('getSearchQueryBuilder')->atLeast()->once()->andReturn($qbMock);
$serviceMock = Mockery::mock(Service::class . '[getPromoRedemptionRepository,enrichPromoRedemptionApiArray]');
$serviceMock->shouldReceive('getPromoRedemptionRepository')->atLeast()->once()->andReturn($repoMock);
$serviceMock->shouldReceive('enrichPromoRedemptionApiArray')->atLeast()->once()->andReturn([]);
$pagerMock = Mockery::mock(FOSSBilling\Pagination::class);
$pagerMock->shouldReceive('paginateDoctrineQuery')->atLeast()->once()->andReturn(['list' => [[]]]);
$di = container();
$di['pager'] = $pagerMock;
$api->setService($serviceMock);
$api->setDi($di);
$result = $api->promo_get($data);
expect($result)->toBeArray();
expect($api->promo_redemption_get_list(['promo_id' => 1]))->toBeArray();
});
test('updates a promo', function (): void {
$api = new Admin();
$data = ['id' => 1];
$model = new Model_Promo();
$model->loadBean(new Tests\Helpers\DummyBean());
$dbMock = Mockery::mock('\Box_Database');
$dbMock->shouldReceive('getExistingModelById')
->atLeast()->once()
->andReturn($model);
$model = new Promo();
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('updatePromo')
->atLeast()->once()
->andReturn(true);
$serviceMock->shouldReceive('findPromoById')->atLeast()->once()->with(1)->andReturn($model);
$serviceMock->shouldReceive('updatePromo')->atLeast()->once()->with($model, $data)->andReturn(true);
$di = container();
$di['db'] = $dbMock;
$api->setDi($di);
$api->setDi(container());
$api->setService($serviceMock);
$result = $api->promo_update($data);
expect($result)->toBeBool();
expect($result)->toBeTrue();
expect($api->promo_update($data))->toBeTrue();
});
test('deletes a promo', function (): void {
$api = new Admin();
$data = ['id' => 1];
$model = new Model_Promo();
$model->loadBean(new Tests\Helpers\DummyBean());
$dbMock = Mockery::mock('\Box_Database');
$dbMock->shouldReceive('getExistingModelById')
->atLeast()->once()
->andReturn($model);
$model = new Promo();
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('deletePromo')
->atLeast()->once()
->andReturn(true);
$serviceMock->shouldReceive('findPromoById')->atLeast()->once()->with(1)->andReturn($model);
$serviceMock->shouldReceive('deletePromo')->atLeast()->once()->with($model)->andReturn(true);
$di = container();
$di['db'] = $dbMock;
$api->setDi($di);
$api->setDi(container());
$api->setService($serviceMock);
$result = $api->promo_delete($data);
expect($result)->toBeBool();
expect($result)->toBeTrue();
expect($api->promo_delete($data))->toBeTrue();
});
@@ -11,6 +11,7 @@
declare(strict_types=1);
use Box\Mod\Product\Api\Guest;
use Box\Mod\Product\Entity\Product;
use Box\Mod\Product\Service;
use function Tests\Helpers\container;
@@ -27,17 +28,11 @@ test('gets product with id', function (): void {
$api = new Guest();
$data = ['id' => 1];
$model = new Model_Product();
$model = new Product();
$serviceMock = Mockery::mock(Service::class);
/** @var Mockery\Expectation $expectation1 */
$expectation1 = $serviceMock->shouldReceive('findOneActiveById');
$expectation1->atLeast()->once();
$expectation1->andReturn($model);
/** @var Mockery\Expectation $expectation2 */
$expectation2 = $serviceMock->shouldReceive('toApiArray');
$expectation2->atLeast()->once();
$expectation2->andReturn([]);
$serviceMock->shouldReceive('findOneActiveById')->atLeast()->once()->andReturn($model);
$serviceMock->shouldReceive('toApiArray')->atLeast()->once()->andReturn([]);
$di = container();
$api->setDi($di);
@@ -50,17 +45,11 @@ test('gets product with slug', function (): void {
$api = new Guest();
$data = ['slug' => 'product/1'];
$model = new Model_Product();
$model = new Product();
$serviceMock = Mockery::mock(Service::class);
/** @var Mockery\Expectation $expectation1 */
$expectation1 = $serviceMock->shouldReceive('findOneActiveBySlug');
$expectation1->atLeast()->once();
$expectation1->andReturn($model);
/** @var Mockery\Expectation $expectation2 */
$expectation2 = $serviceMock->shouldReceive('toApiArray');
$expectation2->atLeast()->once();
$expectation2->andReturn([]);
$serviceMock->shouldReceive('findOneActiveBySlug')->atLeast()->once()->andReturn($model);
$serviceMock->shouldReceive('toApiArray')->atLeast()->once()->andReturn([]);
$di = container();
$api->setDi($di);
@@ -74,10 +63,7 @@ test('throws exception when product not found', function (): void {
$data = ['slug' => 'product/1'];
$serviceMock = Mockery::mock(Service::class);
/** @var Mockery\Expectation $expectation */
$expectation = $serviceMock->shouldReceive('findOneActiveBySlug');
$expectation->atLeast()->once();
$expectation->andReturn(null);
$serviceMock->shouldReceive('findOneActiveBySlug')->atLeast()->once()->andReturn(null);
$di = container();
$api->setDi($di);
@@ -87,43 +73,28 @@ test('throws exception when product not found', function (): void {
->toThrow(FOSSBilling\Exception::class, 'Product not found');
});
test('gets paginated product list', function (): void {
$api = new Guest();
$serviceMock = Mockery::mock(Service::class);
$serviceMock->shouldReceive('getPaginatedProducts')
->once()
->with(['status' => 'enabled', 'show_hidden' => false])
->andReturn(['list' => []]);
$api->setService($serviceMock);
$result = $api->get_list([]);
expect($result)->toBeArray();
});
test('gets category list', function (): void {
$api = new Guest();
$serviceMock = Mockery::mock(Service::class);
/** @var Mockery\Expectation $expectation1 */
$expectation1 = $serviceMock->shouldReceive('getProductCategorySearchQuery');
$expectation1->atLeast()->once();
$expectation1->andReturn(['sqlString', []]);
/** @var Mockery\Expectation $expectation2 */
$expectation2 = $serviceMock->shouldReceive('toProductCategoryApiArray');
$expectation2->atLeast()->once();
$expectation2->andReturn([]);
$pager = [
'list' => [
0 => ['id' => 1],
],
];
$pagerMock = Mockery::mock(FOSSBilling\Pagination::class);
/** @var Mockery\Expectation $expectation4 */
$expectation4 = $pagerMock->shouldReceive('getPaginatedResultSet');
$expectation4->atLeast()->once();
$expectation4->andReturn($pager);
$modelProductCategory = new Model_ProductCategory();
$modelProductCategory->loadBean(new Tests\Helpers\DummyBean());
$dbMock = Mockery::mock('\Box_Database');
/** @var Mockery\Expectation $expectation5 */
$expectation5 = $dbMock->shouldReceive('getExistingModelById');
$expectation5->atLeast()->once();
$expectation5->andReturn($modelProductCategory);
$di = container();
$di['db'] = $dbMock;
$di['pager'] = $pagerMock;
$serviceMock->shouldReceive('getPaginatedProductCategories')
->once()
->with(['status' => 'enabled'])
->andReturn(['list' => []]);
$api->setService($serviceMock);
$api->setDi($di);
$result = $api->category_get_list([]);
expect($result)->toBeArray();
});
@@ -131,10 +102,7 @@ test('gets category list', function (): void {
test('gets category pairs', function (): void {
$api = new Guest();
$serviceMock = Mockery::mock(Service::class);
/** @var Mockery\Expectation $expectation */
$expectation = $serviceMock->shouldReceive('getProductCategoryPairs');
$expectation->atLeast()->once();
$expectation->andReturn([]);
$serviceMock->shouldReceive('getProductCategoryPairs')->atLeast()->once()->andReturn([]);
$api->setService($serviceMock);
$result = $api->category_get_pairs([]);
File diff suppressed because it is too large. Load diff
+3 -2
View File
@@ -12,6 +12,7 @@ declare(strict_types=1);
namespace Box\Mod\Serviceapikey;
use Box\Mod\Product\Entity\Product;
use FOSSBilling\InjectionAwareInterface;
use RedBeanPHP\OODBBean;
@@ -40,9 +41,9 @@ class Service implements InjectionAwareInterface
];
}
public function attachOrderConfig(\Model_Product $product, array $data): array
public function attachOrderConfig(Product $product, array $data): array
{
$config = json_decode($product->config ?? '', true) ?? [];
$config = json_decode($product->getConfig() ?? '', true) ?? [];
return array_merge($config, $data);
}
@@ -1,10 +1,10 @@
{% if order.status == 'active' %}
<div class="card mb-4">
<div class="card-header">
<h2>{{ order.title }}</h2>
<h1>{{ order.title }}</h1>
</div>
<div class="card-body">
<h3>{{ 'API Key Details'|trans }}</h3>
<h2>{{ 'API Key Details'|trans }}</h2>
<table class="table table-striped table-bordered table-sm">
<tbody>
<tr>
@@ -16,7 +16,7 @@
</tbody>
</table>
<h4>{{ 'Reset API Key'|trans }}</h4>
<h3>{{ 'Reset API Key'|trans }}</h3>
<div class="block">
<a class="btn btn-primary" {{ fb_api_link({href: 'serviceapikey/reset'|api_url(query: {order_id: order.id}), modal: {type: 'confirm', title: 'Are you sure?'|trans}, reload: true}) }}>{{ 'Reset'|trans }}</a>
</div>
+7 -3
View File
@@ -12,6 +12,7 @@ declare(strict_types=1);
namespace Box\Mod\Servicecustom;
use Box\Mod\Product\Entity\Product;
use FOSSBilling\Environment;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Filesystem\Path;
@@ -89,12 +90,15 @@ class Service implements \FOSSBilling\InjectionAwareInterface
*/
public function action_create(\Model_ClientOrder $order)
{
$product = $this->di['db']->getExistingModelById('Product', $order->product_id, 'Product not found');
$product = $this->di['mod_service']('product')->findProductById((int) $order->product_id);
if (!$product instanceof Product) {
throw new \FOSSBilling\Exception('Product not found');
}
$model = $this->di['db']->dispense('ServiceCustom');
$model->client_id = $order->client_id;
$model->plugin = $product->plugin;
$model->plugin_config = $product->plugin_config;
$model->plugin = $product->getPlugin();
$model->plugin_config = $product->getPluginConfig();
$model->config = $order->config;
$model->created_at = date('Y-m-d H:i:s');
$model->updated_at = date('Y-m-d H:i:s');
@@ -12,23 +12,21 @@ declare(strict_types=1);
use Box\Mod\Formbuilder\Service as FormbuilderService;
use Box\Mod\Order\Service as OrderService;
use Box\Mod\Product\Entity\Product;
use Box\Mod\Product\Service as ProductService;
use Box\Mod\Servicecustom\Service;
use function Tests\Helpers\container;
afterEach(function (): void {
Mockery::close();
});
test('gets dependency injection container', function (): void {
test('di returns dependency injection container', function (): void {
$service = new Service();
$di = container();
$service->setDi($di);
$getDi = $service->getDi();
expect($getDi)->toBe($di);
expect($getDi)->toEqual($di);
});
test('validates custom form', function (): void {
test('validate custom form', function (): void {
$service = new Service();
$form = [
'fields' => [
@@ -43,9 +41,7 @@ test('validates custom form', function (): void {
];
$formbuilderService = Mockery::mock(FormbuilderService::class);
$formbuilderService->shouldReceive('getForm')
->atLeast()->once()
->andReturn($form);
$formbuilderService->shouldReceive('getForm')->atLeast()->once()->andReturn($form);
$di = container();
$di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $formbuilderService);
@@ -63,7 +59,7 @@ test('validates custom form', function (): void {
expect($result)->toBeNull();
});
test('throws exception when validating custom form with missing field name', function (): void {
test('validate custom form field name not set exception', function (): void {
$service = new Service();
$form = [
'fields' => [
@@ -78,9 +74,7 @@ test('throws exception when validating custom form with missing field name', fun
];
$formbuilderService = Mockery::mock(FormbuilderService::class);
$formbuilderService->shouldReceive('getForm')
->atLeast()->once()
->andReturn($form);
$formbuilderService->shouldReceive('getForm')->atLeast()->once()->andReturn($form);
$di = container();
$di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $formbuilderService);
@@ -96,7 +90,7 @@ test('throws exception when validating custom form with missing field name', fun
->toThrow(Exception::class);
});
test('throws exception when validating custom form with readonly field change', function (): void {
test('validate custom form readonly field change exception', function (): void {
$service = new Service();
$form = [
'fields' => [
@@ -111,9 +105,7 @@ test('throws exception when validating custom form with readonly field change',
];
$formbuilderService = Mockery::mock(FormbuilderService::class);
$formbuilderService->shouldReceive('getForm')
->atLeast()->once()
->andReturn($form);
$formbuilderService->shouldReceive('getForm')->atLeast()->once()->andReturn($form);
$di = container();
$di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $formbuilderService);
@@ -131,7 +123,112 @@ test('throws exception when validating custom form with readonly field change',
->toThrow(Exception::class);
});
test('creates action', function (): void {
test('validate custom form invalid url exception', function (): void {
$service = new Service();
$form = [
'fields' => [
0 => [
'type' => 'url',
'name' => 'website',
'label' => 'Website',
'required' => 0,
],
],
];
$formbuilderService = Mockery::mock(FormbuilderService::class);
$formbuilderService->shouldReceive('getForm')->atLeast()->once()->andReturn($form);
$formbuilderService->shouldReceive('validateUrlField')->atLeast()->once()->andReturn(false);
$di = container();
$di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $formbuilderService);
$service->setDi($di);
$product = [
'form_id' => 1,
];
$data = [
'website' => 'invalid-url',
];
expect(fn () => $service->validateCustomForm($data, $product))
->toThrow(FOSSBilling\InformationException::class, 'Field Website must be a valid URL with a TLD (e.g., https://example.com)');
});
test('validate custom form valid url', function (): void {
$service = new Service();
$form = [
'fields' => [
0 => [
'type' => 'url',
'name' => 'website',
'label' => 'Website',
'required' => 0,
],
],
];
$formbuilderService = Mockery::mock(FormbuilderService::class);
$formbuilderService->shouldReceive('getForm')->atLeast()->once()->andReturn($form);
$formbuilderService->shouldReceive('validateUrlField')->atLeast()->once()->andReturn(true);
$di = container();
$di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $formbuilderService);
$service->setDi($di);
$product = [
'form_id' => 1,
];
$data = [
'website' => 'https://example.com',
];
$result = $service->validateCustomForm($data, $product);
expect($result)->toBeNull();
});
test('validate custom form url array input throws information exception', function (): void {
$service = new Service();
$form = [
'fields' => [
0 => [
'type' => 'url',
'name' => 'website',
'label' => 'Website',
'required' => 0,
],
],
];
$formbuilderService = Mockery::mock(FormbuilderService::class);
$formbuilderService->shouldReceive('getForm')->once()->andReturn($form);
$formbuilderService->shouldNotReceive('validateUrlField');
$di = container();
$di['mod_service'] = $di->protect(function (string $module) use ($formbuilderService): Mockery\MockInterface {
if ($module !== 'formbuilder') {
throw new InvalidArgumentException(sprintf('Unexpected module requested: %s', $module));
}
return $formbuilderService;
});
$service->setDi($di);
$product = [
'form_id' => 1,
];
$data = [
'website' => ['x'],
];
expect(fn () => $service->validateCustomForm($data, $product))
->toThrow(FOSSBilling\InformationException::class, 'Field Website must be a valid URL with a TLD (e.g., https://example.com)');
});
test('action create', function (): void {
$service = new Service();
$order = new Model_ClientOrder();
$order->loadBean(new Tests\Helpers\DummyBean());
@@ -139,33 +236,35 @@ test('creates action', function (): void {
$order->client_id = 1;
$order->config = 'config';
$product = new Model_Product();
$product->loadBean(new Tests\Helpers\DummyBean());
$product->plugin = 'plugin';
$product->plugin_config = 'plugin_config';
$product = new Product();
$product->setPlugin('plugin');
$product->setPluginConfig('plugin_config');
$dbMock = Mockery::mock('\Box_Database');
$dbMock->shouldReceive('store')
->atLeast()->once()
->andReturn(1);
$dbMock->shouldReceive('getExistingModelById')
->atLeast()->once()
->andReturn($product);
$dbMock = Mockery::mock(Box_Database::class);
$dbMock->shouldReceive('store')->atLeast()->once()->andReturn(1);
$serviceCustomModel = new Model_ServiceCustom();
$serviceCustomModel->loadBean(new Tests\Helpers\DummyBean());
$dbMock->shouldReceive('dispense')
->atLeast()->once()
->andReturn($serviceCustomModel);
$dbMock->shouldReceive('dispense')->atLeast()->once()->andReturn($serviceCustomModel);
$productService = Mockery::mock(ProductService::class);
$productService->shouldReceive('findProductById')->once()->with(1)->andReturn($product);
$di = container();
$di['db'] = $dbMock;
$di['mod_service'] = $di->protect(function (string $service) use ($productService): Mockery\MockInterface {
if ($service === 'product') {
return $productService;
}
throw new RuntimeException('Unexpected service request');
});
$service->setDi($di);
$result = $service->action_create($order);
expect($result)->toBeInstanceOf(Model_ServiceCustom::class);
});
test('activates action', function (): void {
test('action activate', function (): void {
$service = new Service();
$order = new Model_ClientOrder();
$order->loadBean(new Tests\Helpers\DummyBean());
@@ -176,40 +275,36 @@ test('activates action', function (): void {
$serviceCustomModel->loadBean(new Tests\Helpers\DummyBean());
$serviceCustomModel->plugin = '';
$orderServiceMock = Mockery::mock(OrderService::class);
$orderServiceMock->shouldReceive('getOrderService')
->atLeast()->once()
->andReturn($serviceCustomModel);
$serviceMock = Mockery::mock(OrderService::class);
$serviceMock->shouldReceive('getOrderService')->atLeast()->once()->andReturn($serviceCustomModel);
$di = container();
$di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
$di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $serviceMock);
$service->setDi($di);
$result = $service->action_activate($order);
expect($result)->toBeTrue();
});
test('throws exception when activating without order service', function (): void {
test('action activate order service not created exception', function (): void {
$service = new Service();
$order = new Model_ClientOrder();
$order->loadBean(new Tests\Helpers\DummyBean());
$order->client_id = 1;
$order->config = 'config';
$orderServiceMock = Mockery::mock(OrderService::class);
$orderServiceMock->shouldReceive('getOrderService')
->atLeast()->once()
->andReturn(null);
$serviceMock = Mockery::mock(OrderService::class);
$serviceMock->shouldReceive('getOrderService')->atLeast()->once()->andReturn(null);
$di = container();
$di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
$di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $serviceMock);
$service->setDi($di);
expect(fn (): bool => $service->action_activate($order))
expect(fn () => $service->action_activate($order))
->toThrow(Exception::class);
});
test('renews action', function (): void {
test('action renew', function (): void {
$service = new Service();
$order = new Model_ClientOrder();
$order->loadBean(new Tests\Helpers\DummyBean());
@@ -220,26 +315,22 @@ test('renews action', function (): void {
$serviceCustomModel->loadBean(new Tests\Helpers\DummyBean());
$serviceCustomModel->plugin = '';
$orderServiceMock = Mockery::mock(OrderService::class);
$orderServiceMock->shouldReceive('getOrderService')
->atLeast()->once()
->andReturn($serviceCustomModel);
$serviceMock = Mockery::mock(OrderService::class);
$serviceMock->shouldReceive('getOrderService')->atLeast()->once()->andReturn($serviceCustomModel);
$dbMock = Mockery::mock('\Box_Database');
$dbMock->shouldReceive('store')
->atLeast()->once()
->andReturn(1);
$dbMock = Mockery::mock(Box_Database::class);
$dbMock->shouldReceive('store')->atLeast()->once()->andReturn(1);
$di = container();
$di['db'] = $dbMock;
$di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
$di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $serviceMock);
$service->setDi($di);
$result = $service->action_renew($order);
expect($result)->toBeTrue();
});
test('throws exception when renewing without active service', function (): void {
test('active service not found exception', function (): void {
$service = new Service();
$order = new Model_ClientOrder();
$order->loadBean(new Tests\Helpers\DummyBean());
@@ -247,20 +338,18 @@ test('throws exception when renewing without active service', function (): void
$order->client_id = 1;
$order->config = 'config';
$orderServiceMock = Mockery::mock(OrderService::class);
$orderServiceMock->shouldReceive('getOrderService')
->atLeast()->once()
->andReturn(null);
$serviceMock = Mockery::mock(OrderService::class);
$serviceMock->shouldReceive('getOrderService')->atLeast()->once()->andReturn(null);
$di = container();
$di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
$di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $serviceMock);
$service->setDi($di);
expect(fn (): bool => $service->action_renew($order))
expect(fn () => $service->action_renew($order))
->toThrow(Exception::class);
});
test('suspends action', function (): void {
test('action suspend', function (): void {
$service = new Service();
$order = new Model_ClientOrder();
$order->loadBean(new Tests\Helpers\DummyBean());
@@ -271,26 +360,22 @@ test('suspends action', function (): void {
$serviceCustomModel->loadBean(new Tests\Helpers\DummyBean());
$serviceCustomModel->plugin = '';
$orderServiceMock = Mockery::mock(OrderService::class);
$orderServiceMock->shouldReceive('getOrderService')
->atLeast()->once()
->andReturn($serviceCustomModel);
$serviceMock = Mockery::mock(OrderService::class);
$serviceMock->shouldReceive('getOrderService')->atLeast()->once()->andReturn($serviceCustomModel);
$dbMock = Mockery::mock('\Box_Database');
$dbMock->shouldReceive('store')
->atLeast()->once()
->andReturn(1);
$dbMock = Mockery::mock(Box_Database::class);
$dbMock->shouldReceive('store')->atLeast()->once()->andReturn(1);
$di = container();
$di['db'] = $dbMock;
$di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
$di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $serviceMock);
$service->setDi($di);
$result = $service->action_suspend($order);
expect($result)->toBeTrue();
});
test('unsuspends action', function (): void {
test('action unsuspend', function (): void {
$service = new Service();
$order = new Model_ClientOrder();
$order->loadBean(new Tests\Helpers\DummyBean());
@@ -301,26 +386,22 @@ test('unsuspends action', function (): void {
$serviceCustomModel->loadBean(new Tests\Helpers\DummyBean());
$serviceCustomModel->plugin = '';
$orderServiceMock = Mockery::mock(OrderService::class);
$orderServiceMock->shouldReceive('getOrderService')
->atLeast()->once()
->andReturn($serviceCustomModel);
$serviceMock = Mockery::mock(OrderService::class);
$serviceMock->shouldReceive('getOrderService')->atLeast()->once()->andReturn($serviceCustomModel);
$dbMock = Mockery::mock('\Box_Database');
$dbMock->shouldReceive('store')
->atLeast()->once()
->andReturn(1);
$dbMock = Mockery::mock(Box_Database::class);
$dbMock->shouldReceive('store')->atLeast()->once()->andReturn(1);
$di = container();
$di['db'] = $dbMock;
$di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
$di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $serviceMock);
$service->setDi($di);
$result = $service->action_unsuspend($order);
expect($result)->toBeTrue();
});
test('cancels action', function (): void {
test('action cancel', function (): void {
$service = new Service();
$order = new Model_ClientOrder();
$order->loadBean(new Tests\Helpers\DummyBean());
@@ -331,26 +412,22 @@ test('cancels action', function (): void {
$serviceCustomModel->loadBean(new Tests\Helpers\DummyBean());
$serviceCustomModel->plugin = '';
$orderServiceMock = Mockery::mock(OrderService::class);
$orderServiceMock->shouldReceive('getOrderService')
->atLeast()->once()
->andReturn($serviceCustomModel);
$serviceMock = Mockery::mock(OrderService::class);
$serviceMock->shouldReceive('getOrderService')->atLeast()->once()->andReturn($serviceCustomModel);
$dbMock = Mockery::mock('\Box_Database');
$dbMock->shouldReceive('store')
->atLeast()->once()
->andReturn(1);
$dbMock = Mockery::mock(Box_Database::class);
$dbMock->shouldReceive('store')->atLeast()->once()->andReturn(1);
$di = container();
$di['db'] = $dbMock;
$di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
$di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $serviceMock);
$service->setDi($di);
$result = $service->action_cancel($order);
expect($result)->toBeTrue();
});
test('uncancels action', function (): void {
test('action uncancel', function (): void {
$service = new Service();
$order = new Model_ClientOrder();
$order->loadBean(new Tests\Helpers\DummyBean());
@@ -361,26 +438,22 @@ test('uncancels action', function (): void {
$serviceCustomModel->loadBean(new Tests\Helpers\DummyBean());
$serviceCustomModel->plugin = '';
$orderServiceMock = Mockery::mock(OrderService::class);
$orderServiceMock->shouldReceive('getOrderService')
->atLeast()->once()
->andReturn($serviceCustomModel);
$serviceMock = Mockery::mock(OrderService::class);
$serviceMock->shouldReceive('getOrderService')->atLeast()->once()->andReturn($serviceCustomModel);
$dbMock = Mockery::mock('\Box_Database');
$dbMock->shouldReceive('store')
->atLeast()->once()
->andReturn(1);
$dbMock = Mockery::mock(Box_Database::class);
$dbMock->shouldReceive('store')->atLeast()->once()->andReturn(1);
$di = container();
$di['db'] = $dbMock;
$di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
$di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $serviceMock);
$service->setDi($di);
$result = $service->action_uncancel($order);
expect($result)->toBeTrue();
});
test('deletes action', function (): void {
test('action delete', function (): void {
$service = new Service();
$order = new Model_ClientOrder();
$order->loadBean(new Tests\Helpers\DummyBean());
@@ -391,26 +464,22 @@ test('deletes action', function (): void {
$serviceCustomModel->loadBean(new Tests\Helpers\DummyBean());
$serviceCustomModel->plugin = '';
$orderServiceMock = Mockery::mock(OrderService::class);
$orderServiceMock->shouldReceive('getOrderService')
->atLeast()->once()
->andReturn($serviceCustomModel);
$serviceMock = Mockery::mock(OrderService::class);
$serviceMock->shouldReceive('getOrderService')->atLeast()->once()->andReturn($serviceCustomModel);
$dbMock = Mockery::mock('\Box_Database');
$dbMock->shouldReceive('trash')
->atLeast()->once()
->andReturn(null);
$dbMock = Mockery::mock(Box_Database::class);
$dbMock->shouldReceive('trash')->atLeast()->once()->andReturn(null);
$di = container();
$di['db'] = $dbMock;
$di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
$di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $serviceMock);
$service->setDi($di);
$result = $service->action_delete($order);
expect($result)->toBeTrue();
});
test('gets config', function (): void {
test('get config', function (): void {
$service = new Service();
$decoded = [
'J' => 5,
@@ -425,10 +494,11 @@ test('gets config', function (): void {
$model->config = json_encode($decoded);
$result = $service->getConfig($model);
expect($result)->toBe($decoded);
expect($result)->toEqual($decoded);
});
test('converts to api array', function (): void {
test('to api array', function (): void {
$service = new Service();
$di = container();
$service->setDi($di);
@@ -444,81 +514,83 @@ test('converts to api array', function (): void {
$result = $service->toApiArray($model);
expect($result)->toBeArray();
expect($result['client_id'])->toBe($model->client_id);
expect($result['plugin'])->toBe($model->plugin);
expect($result['config_param'])->toBe('config_value');
expect($result['updated_at'])->toBe($model->updated_at);
expect($result['created_at'])->toBe($model->created_at);
expect($result['client_id'])->toEqual($model->client_id);
expect($result['plugin'])->toEqual($model->plugin);
expect($result['config_param'])->toEqual('config_value');
expect($result['updated_at'])->toEqual($model->updated_at);
expect($result['created_at'])->toEqual($model->created_at);
});
test('throws exception for forbidden custom call method', function (): void {
test('custom call forbidden method exception', function (): void {
$service = new Service();
expect(fn () => $service->customCall(new Model_ServiceCustom(), 'delete'))
->toThrow(Exception::class);
});
test('gets service custom by order id', function (): void {
test('get service custom by order id', function (): void {
$service = new Service();
$dbMock = Mockery::mock('\Box_Database');
$dbMock->shouldReceive('getExistingModelById')
->atLeast()->once()
->andReturn(new Model_ClientOrder());
$dbMock = Mockery::mock(Box_Database::class);
$dbMock->shouldReceive('getExistingModelById')->atLeast()->once()->andReturn(new Model_ClientOrder());
$orderServiceMock = Mockery::mock(OrderService::class);
$orderServiceMock->shouldReceive('getOrderService')
->atLeast()->once()
->andReturn(new Model_ServiceCustom());
$orderService = Mockery::mock(OrderService::class);
$orderService->shouldReceive('getOrderService')->atLeast()->once()->andReturn(new Model_ServiceCustom());
$di = container();
$di['db'] = $dbMock;
$di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
$di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderService);
$service->setDi($di);
$result = $service->getServiceCustomByOrderId(1);
expect($result)->toBeInstanceOf(Model_ServiceCustom::class);
});
test('throws exception when getting service custom by order id without order service', function (): void {
test('get service custom by order id rejects order owned by another client', function (): void {
$service = new Service();
$dbMock = Mockery::mock('\Box_Database');
$dbMock->shouldReceive('getExistingModelById')
->atLeast()->once()
->andReturn(new Model_ClientOrder());
$orderServiceMock = Mockery::mock(OrderService::class);
$orderServiceMock->shouldReceive('getOrderService')
->atLeast()->once()
->andReturn(null);
$dbMock = Mockery::mock(Box_Database::class);
$dbMock->shouldReceive('findOne')->once()->with('ClientOrder', 'id = ? AND client_id = ?', [1, 42])->andReturn(null);
$dbMock->shouldNotReceive('getExistingModelById');
$di = container();
$di['db'] = $dbMock;
$di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
$service->setDi($di);
expect(fn () => $service->getServiceCustomByOrderId(1, 42))
->toThrow(Exception::class, 'Order not found');
});
test('get service custom by order id order service not found exception', function (): void {
$service = new Service();
$dbMock = Mockery::mock(Box_Database::class);
$dbMock->shouldReceive('getExistingModelById')->atLeast()->once()->andReturn(new Model_ClientOrder());
$orderService = Mockery::mock(OrderService::class);
$orderService->shouldReceive('getOrderService')->atLeast()->once()->andReturn(null);
$di = container();
$di['db'] = $dbMock;
$di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderService);
$service->setDi($di);
expect(fn () => $service->getServiceCustomByOrderId(1))
->toThrow(Exception::class);
});
test('updates config', function (): void {
$service = new Service();
test('update config', function (): void {
$model = new Model_ServiceCustom();
$model->loadBean(new Tests\Helpers\DummyBean());
$model->id = 1;
$serviceMock = Mockery::mock(Service::class)->makePartial();
$serviceMock->shouldReceive('getServiceCustomByOrderId')
->atLeast()->once()
->andReturn($model);
$serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
$serviceMock->shouldReceive('getServiceCustomByOrderId')->atLeast()->once()->andReturn($model);
$dbMock = Mockery::mock('\Box_Database');
$dbMock->shouldReceive('store')
->atLeast()->once()
->andReturn(1);
$dbMock = Mockery::mock(Box_Database::class);
$dbMock->shouldReceive('store')->atLeast()->once()->andReturn(1);
$di = container();
$di['db'] = $dbMock;
$di['logger'] = new Tests\Helpers\TestLogger();
$di['logger'] = new Box_Log();
$serviceMock->setDi($di);
$config = ['param1' => 'value1'];
@@ -526,23 +598,20 @@ test('updates config', function (): void {
expect($result)->toBeNull();
});
test('throws exception when updating config with non-array', function (): void {
$service = new Service();
test('update config not array exception', function (): void {
$model = new Model_ServiceCustom();
$model->loadBean(new Tests\Helpers\DummyBean());
$model->id = 1;
$serviceMock = Mockery::mock(Service::class)->makePartial();
$serviceMock->shouldReceive('getServiceCustomByOrderId')
->never();
$serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
$serviceMock->shouldNotReceive('getServiceCustomByOrderId');
$dbMock = Mockery::mock('\Box_Database');
$dbMock->shouldReceive('store')
->never();
$dbMock = Mockery::mock(Box_Database::class);
$dbMock->shouldNotReceive('store');
$di = container();
$di['db'] = $dbMock;
$di['logger'] = new Tests\Helpers\TestLogger();
$di['logger'] = new Box_Log();
$serviceMock->setDi($di);
$config = '';
+3 -2
View File
@@ -12,6 +12,7 @@ declare(strict_types=1);
namespace Box\Mod\Servicedomain;
use Box\Mod\Product\Entity\Product;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Filesystem\Path;
use Symfony\Component\Finder\Finder;
@@ -57,7 +58,7 @@ class Service implements \FOSSBilling\InjectionAwareInterface
];
}
public function getCartProductTitle($product, array $data)
public function getCartProductTitle(Product $product, array $data)
{
if (
isset($data['action']) && $data['action'] == 'register'
@@ -73,7 +74,7 @@ class Service implements \FOSSBilling\InjectionAwareInterface
return __trans('Domain :domain transfer', [':domain' => $data['transfer_sld'] . $data['transfer_tld']]);
}
return $product->title;
return $product->getTitle();
}
public function validateOrderData(&$data): void
@@ -1,3 +1,4 @@
{% import 'macro_functions.html.twig' as mf %}
<div class="card-body">
<div class="card mb-4">
<div class="card-body">
@@ -38,9 +38,7 @@ test('gets dependency injection container', function (): void {
test('gets cart product title', function (array $data, string $expected): void {
$service = new Service();
$product = new Model_CartProduct();
$product->loadBean(new Tests\Helpers\DummyBean());
$product->title = 'Example.com Registration';
$product = (new Box\Mod\Product\Entity\Product())->setTitle('Example.com Registration');
$result = $service->getCartProductTitle($product, $data);
@@ -31,7 +31,7 @@ class Admin extends \FOSSBilling\Api\AbstractApi
{
$this->checkPermissions('servicedownloadable', 'manage');
$model = $this->getDi()['db']->getExistingModelById('Product', $data['id'], 'Product not found');
$model = $this->di['mod_service']('product')->findProductById((int) $data['id']);
$request = $this->getDi()['request'];
if (!$request->files->has('file_data')) {
@@ -79,7 +79,7 @@ class Admin extends \FOSSBilling\Api\AbstractApi
{
$this->checkPermissions('servicedownloadable', 'manage');
$model = $this->getDi()['db']->getExistingModelById('Product', $data['id'], 'Product not found');
$model = $this->di['mod_service']('product')->findProductById((int) $data['id']);
$service = $this->getService();
@@ -100,7 +100,7 @@ class Admin extends \FOSSBilling\Api\AbstractApi
{
$this->checkPermissions('servicedownloadable', 'manage');
$model = $this->getDi()['db']->getExistingModelById('Product', $data['id'], 'Product not found');
$model = $this->di['mod_service']('product')->findProductById((int) $data['id']);
$service = $this->getService();
+19 -17
View File
@@ -12,6 +12,7 @@ declare(strict_types=1);
namespace Box\Mod\Servicedownloadable;
use Box\Mod\Product\Entity\Product;
use FOSSBilling\InjectionAwareInterface;
use FOSSBilling\Tools;
use Symfony\Component\Filesystem\Filesystem;
@@ -143,9 +144,9 @@ class Service implements InjectionAwareInterface
$this->filesystem = new Filesystem();
}
public function attachOrderConfig(\Model_Product $product, array &$data): array
public function attachOrderConfig(Product $product, array &$data): array
{
$config = json_decode($product->config ?? '', true) ?? [];
$config = json_decode($product->getConfig() ?? '', true) ?? [];
$required = [
'filename' => 'Product is not configured completely.',
self::STORED_FILENAME_CONFIG_KEY => 'Product is not configured completely.',
@@ -335,7 +336,7 @@ class Service implements InjectionAwareInterface
}
}
public function uploadProductFile(\Model_Product $productModel): bool
public function uploadProductFile(Product $productModel): bool
{
$productService = $this->di['mod_service']('product');
$request = $this->di['request'];
@@ -355,7 +356,7 @@ class Service implements InjectionAwareInterface
$storedFilename = $this->storeUploadedFile($file);
$config = json_decode($productModel->config ?? '', true) ?? [];
$config = json_decode($productModel->getConfig() ?? '', true) ?? [];
$oldStoredFilename = $config[self::STORED_FILENAME_CONFIG_KEY] ?? null;
// Check if update_orders is true and update all orders
@@ -381,11 +382,12 @@ class Service implements InjectionAwareInterface
$config['filename'] = $fileName;
$config[self::STORED_FILENAME_CONFIG_KEY] = $storedFilename;
$productModel->config = json_encode($config);
$productModel->updated_at = date('Y-m-d H:i:s');
$this->di['db']->store($productModel);
$updatedAt = new \DateTime();
$productModel->setConfig(json_encode($config));
$productModel->setUpdatedAt($updatedAt);
$this->di['em']->flush();
$this->di['logger']->info('Uploaded new file for product %s', $productModel->id);
$this->di['logger']->info('Uploaded new file for product %s', $productModel->getId());
if ($oldStoredFilename !== null && $oldStoredFilename !== $storedFilename) {
$this->removeStoredFileIfOrphaned($oldStoredFilename);
@@ -510,13 +512,14 @@ class Service implements InjectionAwareInterface
return $response;
}
public function saveProductConfig(\Model_Product $productModel, array $data): bool
public function saveProductConfig(Product $productModel, $data): bool
{
$config = json_decode($productModel->config ?? '', true) ?: [];
$config = json_decode($productModel->getConfig() ?? '', true) ?: [];
$config['update_orders'] = Tools::normalizeBoolean($data['update_orders'] ?? false);
$productModel->config = json_encode($config);
$productModel->updated_at = date('Y-m-d H:i:s');
$this->di['db']->store($productModel);
$updatedAt = new \DateTime();
$productModel->setConfig(json_encode($config));
$productModel->setUpdatedAt($updatedAt);
$this->di['em']->flush();
return true;
}
@@ -526,10 +529,9 @@ class Service implements InjectionAwareInterface
*
* @throws \FOSSBilling\Exception
*/
public function sendProductFile(\Model_Product $product): Response
public function sendProductFile(Product $product): Response
{
$config = $product->config;
$config = json_decode($config ?? '', true) ?: [];
$config = json_decode($product->getConfig() ?? '', true) ?: [];
if (!isset($config['filename'], $config[self::STORED_FILENAME_CONFIG_KEY])) {
throw new \FOSSBilling\Exception('No file associated with this product.', null, 404);
@@ -552,7 +554,7 @@ class Service implements InjectionAwareInterface
$response->headers->set('Content-Type', 'application/octet-stream');
$response->headers->set('Content-Disposition', $disposition);
$this->di['logger']->info('Downloaded product %s file by admin.', $product->id);
$this->di['logger']->info('Downloaded product %s file by admin.', $product->getId());
return $response;
}
@@ -1,262 +0,0 @@
<?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 Symfony\Component\HttpFoundation\Response;
use function Tests\Helpers\container;
use function Tests\Helpers\moduleService;
test('getDi returns the dependency injection container', function (): void {
$api = new Box\Mod\Servicedownloadable\Api\Admin();
$di = container();
$api->setDi($di);
$getDi = $api->getDi();
expect($getDi)->toBe($di);
});
test('update throws exception when order is not activated', function (): void {
$api = new Box\Mod\Servicedownloadable\Api\Admin();
$data['order_id'] = 1;
$model = new Model_ClientOrder();
$dbMock = Mockery::mock('\Box_Database');
$dbMock->shouldReceive('getExistingModelById')
->atLeast()
->once()
->andReturn($model);
$orderServiceMock = Mockery::mock(Box\Mod\Order\Service::class);
$orderServiceMock->shouldReceive('getOrderService')->atLeast()->once();
$validatorMock = Mockery::mock(FOSSBilling\Validate::class);
$di = container();
$di['db'] = $dbMock;
$di['mod_service'] = $di->protect(moduleService(['order' => $orderServiceMock]));
$di['validator'] = $validatorMock;
$api->setDi($di);
expect(fn () => $api->update($data))
->toThrow(FOSSBilling\Exception::class, 'Order is not activated');
});
test('update updates downloadable product', function (): void {
$api = new Box\Mod\Servicedownloadable\Api\Admin();
$data['order_id'] = 1;
$model = new Model_ClientOrder();
$modelDownloadableModel = new Model_ServiceDownloadable();
$serviceMock = Mockery::mock(Box\Mod\Servicedownloadable\Service::class);
$serviceMock->shouldReceive('updateProductFile')
->atLeast()
->once()
->andReturn(true);
$orderServiceMock = Mockery::mock(Box\Mod\Order\Service::class);
$orderServiceMock->shouldReceive('getOrderService')
->atLeast()
->once()
->andReturn($modelDownloadableModel);
$dbMock = Mockery::mock('\Box_Database');
$dbMock->shouldReceive('getExistingModelById')
->atLeast()
->once()
->andReturn($model);
$di = container();
$di['db'] = $dbMock;
$di['mod_service'] = $di->protect(moduleService(['order' => $orderServiceMock]));
$api->setDi($di);
$api->setService($serviceMock);
$result = $api->update($data);
expect($result)->toBeBool();
expect($result)->toBeTrue();
});
test('configSave saves product configuration', function (): void {
$api = new Box\Mod\Servicedownloadable\Api\Admin();
$data = [
'id' => 1,
'update_orders' => true,
];
$productModel = new Model_Product();
$productModel->loadBean(new Tests\Helpers\DummyBean());
$productModel->config = '{"filename": "test.txt"}';
$serviceMock = Mockery::mock(Box\Mod\Servicedownloadable\Service::class);
$serviceMock->shouldReceive('saveProductConfig')
->with($productModel, $data)
->atLeast()
->once()
->andReturn(true);
$dbMock = Mockery::mock('\Box_Database');
$dbMock->shouldReceive('getExistingModelById')
->with('Product', $data['id'], 'Product not found')
->atLeast()
->once()
->andReturn($productModel);
$di = container();
$di['db'] = $dbMock;
$api->setDi($di);
$api->setService($serviceMock);
$result = $api->config_save($data);
expect($result)->toBeBool();
expect($result)->toBeTrue();
});
test('configSave throws exception when product not found', function (): void {
$api = new Box\Mod\Servicedownloadable\Api\Admin();
$data = [
'id' => 999,
'update_orders' => true,
];
$dbMock = Mockery::mock('\Box_Database');
$dbMock->shouldReceive('getExistingModelById')
->with('Product', $data['id'], 'Product not found')
->atLeast()
->once()
->andThrow(new FOSSBilling\Exception('Product not found'));
$di = container();
$di['db'] = $dbMock;
$api->setDi($di);
expect(fn () => $api->config_save($data))
->toThrow(FOSSBilling\Exception::class, 'Product not found');
});
test('sendFile throws exception when product not found', function (): void {
$api = new Box\Mod\Servicedownloadable\Api\Admin();
$data = ['id' => 999];
$dbMock = Mockery::mock('\Box_Database');
$dbMock->shouldReceive('getExistingModelById')
->with('Product', $data['id'], 'Product not found')
->atLeast()
->once()
->andThrow(new FOSSBilling\Exception('Product not found'));
$di = container();
$di['db'] = $dbMock;
$api->setDi($di);
expect(fn (): bool => $api->send_file($data))
->toThrow(FOSSBilling\Exception::class, 'Product not found');
});
test('sendFile throws exception when no file configured', function (): void {
$api = new Box\Mod\Servicedownloadable\Api\Admin();
$data = ['id' => 1];
$productModel = new Model_Product();
$productModel->loadBean(new Tests\Helpers\DummyBean());
$productModel->config = '{}';
$serviceMock = Mockery::mock(Box\Mod\Servicedownloadable\Service::class);
$serviceMock->shouldReceive('sendProductFile')
->with($productModel)
->atLeast()
->once()
->andThrow(new FOSSBilling\Exception('No file associated with this product.', null, 404));
$dbMock = Mockery::mock('\Box_Database');
$dbMock->shouldReceive('getExistingModelById')
->with('Product', $data['id'], 'Product not found')
->atLeast()
->once()
->andReturn($productModel);
$di = container();
$di['db'] = $dbMock;
$api->setDi($di);
$api->setService($serviceMock);
expect(fn (): bool => $api->send_file($data))
->toThrow(FOSSBilling\Exception::class, 'No file associated with this product.');
});
test('sendFile throws exception when file cannot be downloaded', function (): void {
$api = new Box\Mod\Servicedownloadable\Api\Admin();
$data = ['id' => 1];
$productModel = new Model_Product();
$productModel->loadBean(new Tests\Helpers\DummyBean());
$productModel->config = '{"filename": "test.txt"}';
$serviceMock = Mockery::mock(Box\Mod\Servicedownloadable\Service::class);
$serviceMock->shouldReceive('sendProductFile')
->with($productModel)
->atLeast()
->once()
->andThrow(new FOSSBilling\Exception('File cannot be downloaded at the moment. Please contact support.', null, 404));
$dbMock = Mockery::mock('\Box_Database');
$dbMock->shouldReceive('getExistingModelById')
->with('Product', $data['id'], 'Product not found')
->atLeast()
->once()
->andReturn($productModel);
$di = container();
$di['db'] = $dbMock;
$api->setDi($di);
$api->setService($serviceMock);
expect(fn (): bool => $api->send_file($data))
->toThrow(FOSSBilling\Exception::class, 'File cannot be downloaded at the moment. Please contact support.');
});
test('sendFile sends product file', function (): void {
$api = new Box\Mod\Servicedownloadable\Api\Admin();
$data = ['id' => 1];
$productModel = new Model_Product();
$productModel->loadBean(new Tests\Helpers\DummyBean());
$productModel->config = '{"filename": "test.txt"}';
$serviceMock = Mockery::mock(Box\Mod\Servicedownloadable\Service::class);
$response = new Response('download');
$serviceMock->shouldReceive('sendProductFile')
->with($productModel)
->atLeast()
->once()
->andReturn($response);
$dbMock = Mockery::mock('\Box_Database');
$dbMock->shouldReceive('getExistingModelById')
->with('Product', $data['id'], 'Product not found')
->atLeast()
->once()
->andReturn($productModel);
$di = container();
$di['db'] = $dbMock;
$api->setDi($di);
$api->setService($serviceMock);
$result = $api->send_file($data);
expect($result)->toBe($response);
});
@@ -11,118 +11,58 @@
declare(strict_types=1);
use Box\Mod\Order\Service as OrderService;
use Box\Mod\Product\Entity\Product;
use Box\Mod\Servicedownloadable\Service;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use function Tests\Helpers\container;
use function Tests\Helpers\moduleService;
test('gets dependency injection container', function (): void {
$service = new Service();
$di = container();
$service->setDi($di);
$getDi = $service->getDi();
expect($getDi)->toBe($di);
});
function serviceDownloadableCreateProductEntity(?int $id = null, ?string $config = null): Product
{
$product = new Product();
if ($id !== null) {
$reflection = new ReflectionProperty($product, 'id');
$reflection->setAccessible(true);
$reflection->setValue($product, $id);
}
if ($config !== null) {
$product->setConfig($config);
}
test('attaches order config', function (): void {
$service = new Service();
$productModel = new Model_Product();
$productModel->loadBean(new Tests\Helpers\DummyBean());
$storedFilename = str_repeat('a', 64);
$productModel->config = json_encode([
'filename' => 'temp/asdcxTest.txt',
'stored_filename' => $storedFilename,
]);
return $product;
}
$data = [];
$expected = array_merge(json_decode($productModel->config ?? '', true), $data);
$validatorMock = Mockery::mock(FOSSBilling\Validate::class);
$validatorMock->shouldReceive('checkRequiredParamsForArray')
->zeroOrMoreTimes();
$di = container();
$di['validator'] = $validatorMock;
$service->setDi($di);
$result = $service->attachOrderConfig($productModel, $data);
expect($result)->toBeArray();
expect($result)->toBe($expected);
});
test('creates action', function (): void {
$service = new Service();
$clientOrderModel = new Model_ClientOrder();
$clientOrderModel->loadBean(new Tests\Helpers\DummyBean());
$clientOrderModel->config = json_encode([
'filename' => 'temp/asdcxTest.txt',
'stored_filename' => str_repeat('b', 64),
]);
$model = new Model_ServiceDownloadable();
$model->loadBean(new Tests\Helpers\DummyBean());
$dbMock = Mockery::mock('\Box_Database');
$dbMock->shouldReceive('dispense')
->atLeast()->once()
->andReturn($model);
$dbMock->shouldReceive('store')
->atLeast()->once()
->andReturn(1);
$validatorMock = Mockery::mock(FOSSBilling\Validate::class);
$validatorMock->shouldReceive('checkRequiredParamsForArray')
->zeroOrMoreTimes();
$di = container();
$di['db'] = $dbMock;
$di['validator'] = $validatorMock;
$service->setDi($di);
$result = $service->action_create($clientOrderModel);
expect($result)->toBeInstanceOf(Model_ServiceDownloadable::class);
});
test('deletes action', function (): void {
test('action delete', function (): void {
$service = new Service();
$clientOrderModel = new Model_ClientOrder();
$orderServiceMock = Mockery::mock(OrderService::class);
$orderServiceMock->shouldReceive('getOrderService')
->atLeast()->once()
->andReturn(new Model_ServiceDownloadable());
$orderServiceMock->shouldReceive('getOrderService')->atLeast()->once()->andReturn(new Model_ServiceDownloadable());
$dbMock = Mockery::mock('\Box_Database');
$dbMock->shouldReceive('trash')
->atLeast()->once();
$dbMock = Mockery::mock(Box_Database::class);
$dbMock->shouldReceive('trash')->atLeast()->once();
$di = container();
$di['db'] = $dbMock;
$di['mod_service'] = $di->protect(moduleService(['order' => $orderServiceMock]));
$di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
$service->setDi($di);
$service->action_delete($clientOrderModel);
});
test('saves product config', function (): void {
test('save product config', function (): void {
$service = new Service();
$data = [
'update_orders' => true,
];
$productModel = new Model_Product();
$productModel->loadBean(new Tests\Helpers\DummyBean());
$productModel->config = '{"filename": "test.txt"}';
$dbMock = Mockery::mock('\Box_Database');
$dbMock->shouldReceive('store')
->atLeast()->once()
->with($productModel)
->andReturn(1);
$productModel = serviceDownloadableCreateProductEntity(config: '{"filename": "test.txt"}');
$emMock = Mockery::mock(EntityManagerInterface::class);
$emMock->shouldReceive('flush')->once();
$di = new Pimple\Container();
$di['db'] = $dbMock;
$di['em'] = $emMock;
$service->setDi($di);
$result = $service->saveProductConfig($productModel, $data);
@@ -130,31 +70,25 @@ test('saves product config', function (): void {
expect($result)->toBeBool();
expect($result)->toBeTrue();
$updatedConfig = json_decode($productModel->config, true);
$updatedConfig = json_decode($productModel->getConfig() ?? '', true);
expect($updatedConfig)->toBeArray();
expect($updatedConfig['filename'])->toBe('test.txt');
expect($updatedConfig['filename'])->toEqual('test.txt');
expect($updatedConfig['update_orders'])->toBeTrue();
expect($productModel->updated_at)->not->toBeNull();
expect($productModel->getUpdatedAt())->not->toBeNull();
});
test('saves product config with existing config', function (): void {
test('save product config with existing config', function (): void {
$service = new Service();
$data = [
'update_orders' => false,
];
$productModel = new Model_Product();
$productModel->loadBean(new Tests\Helpers\DummyBean());
$productModel->config = '{"filename": "existing.txt", "update_orders": true}';
$dbMock = Mockery::mock('\Box_Database');
$dbMock->shouldReceive('store')
->atLeast()->once()
->with($productModel)
->andReturn(1);
$productModel = serviceDownloadableCreateProductEntity(config: '{"filename": "existing.txt", "update_orders": true}');
$emMock = Mockery::mock(EntityManagerInterface::class);
$emMock->shouldReceive('flush')->once();
$di = new Pimple\Container();
$di['db'] = $dbMock;
$di['em'] = $emMock;
$service->setDi($di);
$result = $service->saveProductConfig($productModel, $data);
@@ -162,31 +96,25 @@ test('saves product config with existing config', function (): void {
expect($result)->toBeBool();
expect($result)->toBeTrue();
$updatedConfig = json_decode($productModel->config, true);
$updatedConfig = json_decode($productModel->getConfig() ?? '', true);
expect($updatedConfig)->toBeArray();
expect($updatedConfig['filename'])->toBe('existing.txt');
expect($updatedConfig['filename'])->toEqual('existing.txt');
expect($updatedConfig['update_orders'])->toBeFalse();
expect($productModel->updated_at)->not->toBeNull();
expect($productModel->getUpdatedAt())->not->toBeNull();
});
test('saves product config with no existing config', function (): void {
test('save product config with no existing config', function (): void {
$service = new Service();
$data = [
'update_orders' => true,
];
$productModel = new Model_Product();
$productModel->loadBean(new Tests\Helpers\DummyBean());
$productModel->config = null;
$dbMock = Mockery::mock('\Box_Database');
$dbMock->shouldReceive('store')
->atLeast()->once()
->with($productModel)
->andReturn(1);
$productModel = serviceDownloadableCreateProductEntity();
$emMock = Mockery::mock(EntityManagerInterface::class);
$emMock->shouldReceive('flush')->once();
$di = new Pimple\Container();
$di['db'] = $dbMock;
$di['em'] = $emMock;
$service->setDi($di);
$result = $service->saveProductConfig($productModel, $data);
@@ -194,8 +122,39 @@ test('saves product config with no existing config', function (): void {
expect($result)->toBeBool();
expect($result)->toBeTrue();
$updatedConfig = json_decode((string) $productModel->config, true);
$updatedConfig = json_decode($productModel->getConfig() ?? '', true);
expect($updatedConfig)->toBeArray();
expect($updatedConfig)->toHaveKey('update_orders');
expect($updatedConfig['update_orders'])->toBeTrue();
expect($productModel->updated_at)->not->toBeNull();
expect($productModel->getUpdatedAt())->not->toBeNull();
});
test('validate file upload allows known extension with octet stream mime', function (): void {
$service = new Service();
$service->setDi(container());
$file = Mockery::mock(UploadedFile::class)->shouldIgnoreMissing();
$file->shouldReceive('getClientOriginalExtension')->andReturn('exe');
$file->shouldReceive('getClientOriginalName')->andReturn('installer.exe');
$file->shouldReceive('getMimeType')->andReturn('application/octet-stream');
$reflection = new ReflectionMethod(Service::class, 'validateFileUpload');
$reflection->invoke($service, $file);
expect(true)->toBeTrue();
});
test('validate file upload rejects unknown extension', function (): void {
$service = new Service();
$service->setDi(container());
$file = Mockery::mock(UploadedFile::class)->shouldIgnoreMissing();
$file->shouldReceive('getClientOriginalExtension')->andReturn('php');
$file->shouldReceive('getClientOriginalName')->andReturn('shell.php');
$file->shouldReceive('getMimeType')->andReturn('application/x-httpd-php');
$reflection = new ReflectionMethod(Service::class, 'validateFileUpload');
expect(fn () => $reflection->invoke($service, $file))
->toThrow(FOSSBilling\Exception::class);
});
+3 -2
View File
@@ -12,6 +12,7 @@ declare(strict_types=1);
namespace Box\Mod\Servicehosting\Api;
use Box\Mod\Product\Entity\Product;
use FOSSBilling\Validation\Api\RequiredParams;
/**
@@ -30,9 +31,9 @@ class Guest extends \FOSSBilling\Api\AbstractApi
public function free_tlds($data = [])
{
$product_id = $data['product_id'] ?? 0;
$product = $this->getDi()['db']->getExistingModelById('Product', $product_id, 'Product was not found');
$product = $this->di['mod_service']('product')->findProductById((int) $product_id);
if ($product->type !== \Model_Product::HOSTING) {
if (!$product instanceof Product || $product->getType() !== \Box\Mod\Product\Service::HOSTING) {
$friendlyName = ucfirst(__trans('Product type'));
throw new \FOSSBilling\Exception(':friendlyName: is invalid', [':friendlyName:' => $friendlyName]);
+25 -17
View File
@@ -12,6 +12,7 @@ declare(strict_types=1);
namespace Box\Mod\Servicehosting;
use Box\Mod\Product\Entity\Product;
use FOSSBilling\Exception;
use FOSSBilling\InformationException;
use FOSSBilling\InjectionAwareInterface;
@@ -68,19 +69,26 @@ class Service implements InjectionAwareInterface
];
}
public function getCartProductTitle($product, array $data)
private function logInfo(string $message): void
{
if ($this->di !== null && isset($this->di['logger'])) {
$this->di['logger']->info($message);
}
}
public function getCartProductTitle(Product $product, array $data)
{
try {
$data = array_merge(json_decode($product->config ?? '', true) ?? [], $data);
$data = array_merge(json_decode($product->getConfig() ?? '', true) ?? [], $data);
[$sld, $tld] = $this->_getDomainTuple($data);
return __trans(':hosting for :domain', [':hosting' => $product->title, ':domain' => $sld . $tld]);
return __trans(':hosting for :domain', [':hosting' => $product->getTitle(), ':domain' => $sld . $tld]);
} catch (\Exception $e) {
// should never occur, but in case
error_log($e->getMessage());
$this->logInfo($e->getMessage());
}
return $product->title;
return $product->getTitle();
}
public function validateOrderData(array &$data): void
@@ -113,7 +121,7 @@ class Service implements InjectionAwareInterface
AND co.status != :canceled_status';
$count = (int) $this->di['db']->getCell($query, [
':service_type' => \Model_ProductTable::HOSTING,
':service_type' => \Box\Mod\Product\Service::HOSTING,
':sld' => $sld,
':tld' => $tld,
':canceled_status' => \Model_ClientOrder::STATUS_CANCELED,
@@ -1102,7 +1110,7 @@ class Service implements InjectionAwareInterface
return [$m->getLoginUrl(null), $m->getResellerLoginUrl(null)];
} catch (\Exception $e) {
$this->di['logger']->error("Error while retrieving control panel url: {$e->getMessage()}.");
$this->logInfo("Error while retrieving control panel url: {$e->getMessage()}.");
}
return [false, false];
@@ -1122,9 +1130,9 @@ class Service implements InjectionAwareInterface
return $adapter->getLoginUrl($account);
}
public function prependOrderConfig(\Model_Product $product, array $data): array
public function attachOrderConfig(Product $product, array $data): array
{
$c = json_decode($product->config ?? '', true) ?? [];
$c = json_decode($product->getConfig() ?? '', true) ?? [];
$data = array_merge($c, $data);
@@ -1155,7 +1163,7 @@ class Service implements InjectionAwareInterface
{
$action = $data['domain']['action'];
// Settings default to true for backward compatibility
// When unset, hosting products allow all domain actions.
$allowRegister = $productConfig['allow_domain_register'] ?? true;
$allowTransfer = $productConfig['allow_domain_transfer'] ?? true;
$allowOwn = $productConfig['allow_domain_own'] ?? true;
@@ -1171,12 +1179,12 @@ class Service implements InjectionAwareInterface
};
}
public function getDomainProductFromConfig(\Model_Product $product, array &$data): bool|array
public function getDomainProductFromConfig(Product $product, array &$data): bool|array
{
$data = $this->prependOrderConfig($product, $data);
$product->getService()->validateOrderData($data);
$data = $this->attachOrderConfig($product, $data);
$this->validateOrderData($data);
$c = json_decode($product->config ?? '', true) ?? [];
$c = json_decode($product->getConfig() ?? '', true) ?? [];
$dc = $data['domain'];
$action = $dc['action'];
@@ -1209,16 +1217,16 @@ class Service implements InjectionAwareInterface
$table = $this->di['mod_service']('product');
$d = $table->getMainDomainProduct();
if (!$d instanceof \Model_Product) {
if (!$d instanceof Product) {
throw new Exception('Could not find main domain product');
}
return ['product' => $d, 'config' => $dc];
}
public function getFreeTlds(\Model_Product $product, $identity = null): array
public function getFreeTlds(Product $product, $identity = null): array
{
$config = json_decode($product->config ?? '', true) ?? [];
$config = json_decode($product->getConfig() ?? '', true) ?? [];
$freeTlds = $config['free_tlds'] ?? [];
$result = [];
foreach ($freeTlds as $tld) {
@@ -3,7 +3,7 @@
{% set tlds = guest.serviceDomain_tlds({"allow_register":1}) %}
{% set transfer_tlds = guest.serviceDomain_tlds({"allow_transfer":1}) %}
{# Domain configuration settings - default to true for backward compatibility #}
{# Domain configuration settings default to enabled when unset. #}
{% set allow_register = product.config.allow_domain_register ?? true %}
{% set allow_transfer = product.config.allow_domain_transfer ?? true %}
{% set allow_own = product.config.allow_domain_own ?? true %}
@@ -14,27 +14,26 @@ use Box\Mod\Servicehosting\Api\Guest;
use function Tests\Helpers\container;
test('testFreeTlds', function (): void {
test('free tlds', function (): void {
$api = new Guest();
$di = container();
$model = new Model_Product();
$model->loadBean(new Tests\Helpers\DummyBean());
$model->type = Model_Product::HOSTING;
$dbMock = Mockery::mock('\Box_Database');
$dbMock
->shouldReceive('getExistingModelById')
->atLeast()->once()
->andReturn($model);
$model = new Box\Mod\Product\Entity\Product();
$model->setType(Box\Mod\Product\Service::HOSTING);
$di['db'] = $dbMock;
$productService = Mockery::mock(Box\Mod\Product\Service::class);
$productService->shouldReceive('findProductById')->once()->with(1)->andReturn($model);
$di['mod_service'] = $di->protect(function (string $service) use ($productService) {
if ($service === 'product') {
return $productService;
}
throw new RuntimeException('Unexpected service request');
});
$serviceMock = Mockery::mock(Box\Mod\Servicehosting\Service::class);
$serviceMock
->shouldReceive('getFreeTlds')
->atLeast()->once()
->with($model)
->andReturn([]);
$serviceMock->shouldReceive('getFreeTlds')->atLeast()->once()->with($model)->andReturn([]);
$api->setService($serviceMock);
$api->setDi($di);
@@ -42,29 +41,31 @@ test('testFreeTlds', function (): void {
expect($result)->toBeArray();
});
test('testFreeTldsProductTypeIsNotHosting', function (): void {
test('free tlds product type is not hosting', function (): void {
$api = new Guest();
$di = container();
$model = new Model_Product();
$model->loadBean(new Tests\Helpers\DummyBean());
$dbMock = Mockery::mock('\Box_Database');
$dbMock
->shouldReceive('getExistingModelById')
->atLeast()->once()
->andReturn($model);
$model = new Box\Mod\Product\Entity\Product();
$validatorStub = $this->createStub(FOSSBilling\Validate::class);
$productService = Mockery::mock(Box\Mod\Product\Service::class);
$productService->shouldReceive('findProductById')->once()->with(1)->andReturn($model);
$di['db'] = $dbMock;
$di['validator'] = $validatorStub;
$validatorMock = Mockery::mock(FOSSBilling\Validate::class)->shouldIgnoreMissing();
$di['validator'] = $validatorMock;
$di['mod_service'] = $di->protect(function (string $service) use ($productService) {
if ($service === 'product') {
return $productService;
}
throw new RuntimeException('Unexpected service request');
});
$serviceMock = Mockery::mock(Box\Mod\Servicehosting\Service::class);
$serviceMock->shouldReceive('getFreeTlds');
$serviceMock->shouldNotReceive('getFreeTlds');
$api->setService($serviceMock);
$api->setDi($di);
$this->expectException(FOSSBilling\Exception::class);
$this->expectExceptionMessage('Product type is invalid');
$api->free_tlds(['product_id' => 1]);
expect(fn () => $api->free_tlds(['product_id' => 1]))
->toThrow(FOSSBilling\Exception::class, 'Product type is invalid');
});
@@ -14,22 +14,7 @@ use Box\Mod\Servicehosting\Service;
use function Tests\Helpers\container;
dataset('validateOrderDataProvider', fn (): array => [
['server_id', 'Hosting product is not configured completely. Configure server for hosting product.', 701],
['hosting_plan_id', 'Hosting product is not configured completely. Configure hosting plan for hosting product.', 702],
['sld', 'Domain name is invalid.', 703],
['tld', 'Domain extension is invalid.', 704],
]);
test('testGetDi', function (): void {
$service = new Service();
$di = container();
$service->setDi($di);
$getDi = $service->getDi();
expect($getDi)->toBe($di);
});
test('testValidateOrderData', function (string $field, string $exceptionMessage, int $excCode): void {
test('validate order data', function (string $field, string $exceptionMessage, int $excCode): void {
$service = new Service();
$data = [
'server_id' => 1,
@@ -40,12 +25,16 @@ test('testValidateOrderData', function (string $field, string $exceptionMessage,
unset($data[$field]);
$this->expectException(FOSSBilling\Exception::class);
$this->expectExceptionMessage($exceptionMessage);
$service->validateOrderData($data);
})->with('validateOrderDataProvider');
expect(fn () => $service->validateOrderData($data))
->toThrow(FOSSBilling\Exception::class, $exceptionMessage);
})->with([
['server_id', 'Hosting product is not configured completely. Configure server for hosting product.', 701],
['hosting_plan_id', 'Hosting product is not configured completely. Configure hosting plan for hosting product.', 702],
['sld', 'Domain name is invalid.', 703],
['tld', 'Domain extension is invalid.', 704],
]);
test('testActionCreate', function (): void {
test('action create', function (): void {
$service = new Service();
$orderModel = new Model_ClientOrder();
$orderModel->loadBean(new Tests\Helpers\DummyBean());
@@ -56,32 +45,21 @@ test('testActionCreate', function (): void {
'tld' => 'com',
];
$orderServiceMock = Mockery::mock(Box\Mod\Order\Service::class);
$orderServiceMock
->shouldReceive('getConfig')
->atLeast()->once()
->andReturn($confArr);
$orderServiceMock->shouldReceive('getConfig')->atLeast()->once()->andReturn($confArr);
$hostingServerModel = new Model_ServiceHostingServer();
$hostingServerModel->loadBean(new Tests\Helpers\DummyBean());
$hostingPlansModel = new Model_ServiceHostingHp();
$hostingPlansModel->loadBean(new Tests\Helpers\DummyBean());
$dbMock = Mockery::mock('\Box_Database');
$dbMock
->shouldReceive('getExistingModelById')
->andReturn($hostingServerModel, $hostingPlansModel);
$dbMock->shouldReceive('getExistingModelById')->atLeast()->once()->andReturn($hostingServerModel, $hostingPlansModel);
$servhostingModel = new Model_ServiceHosting();
$servhostingModel->loadBean(new Tests\Helpers\DummyBean());
$dbMock
->shouldReceive('dispense')
->atLeast()->once()
->andReturn($servhostingModel);
$dbMock->shouldReceive('dispense')->atLeast()->once()->andReturn($servhostingModel);
$newserviceHostingId = 4;
$dbMock
->shouldReceive('store')
->atLeast()->once()
->andReturn($newserviceHostingId);
$dbMock->shouldReceive('store')->atLeast()->once()->andReturn($newserviceHostingId);
$di = container();
$di['db'] = $dbMock;
@@ -91,7 +69,7 @@ test('testActionCreate', function (): void {
$service->action_create($orderModel);
});
test('testActionRenew', function (): void {
test('action renew', function (): void {
$service = new Service();
$orderModel = new Model_ClientOrder();
$orderModel->loadBean(new Tests\Helpers\DummyBean());
@@ -100,10 +78,7 @@ test('testActionRenew', function (): void {
$model->loadBean(new Tests\Helpers\DummyBean());
$orderServiceMock = Mockery::mock(Box\Mod\Order\Service::class);
$orderServiceMock
->shouldReceive('getOrderService')
->atLeast()->once()
->andReturn($model);
$orderServiceMock->shouldReceive('getOrderService')->atLeast()->once()->andReturn($model);
$dbMock = Mockery::mock('\Box_Database');
$dbMock->shouldReceive('store')->atLeast()->once();
@@ -117,7 +92,7 @@ test('testActionRenew', function (): void {
expect($result)->toBeTrue();
});
test('testActionRenewOrderWithoutActiveService', function (): void {
test('action renew order without active service', function (): void {
$service = new Service();
$orderModel = new Model_ClientOrder();
$orderModel->loadBean(new Tests\Helpers\DummyBean());
@@ -130,12 +105,11 @@ test('testActionRenewOrderWithoutActiveService', function (): void {
$di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
$service->setDi($di);
$this->expectException(FOSSBilling\Exception::class);
$this->expectExceptionMessage(sprintf('Order %d has no active service', $orderModel->id));
$service->action_renew($orderModel);
expect(fn () => $service->action_renew($orderModel))
->toThrow(FOSSBilling\Exception::class, sprintf('Order %d has no active service', $orderModel->id));
});
test('testActionSuspend', function (): void {
test('action suspend', function (): void {
$service = new Service();
$orderModel = new Model_ClientOrder();
$orderModel->loadBean(new Tests\Helpers\DummyBean());
@@ -144,10 +118,7 @@ test('testActionSuspend', function (): void {
$model->loadBean(new Tests\Helpers\DummyBean());
$orderServiceMock = Mockery::mock(Box\Mod\Order\Service::class);
$orderServiceMock
->shouldReceive('getOrderService')
->atLeast()->once()
->andReturn($model);
$orderServiceMock->shouldReceive('getOrderService')->atLeast()->once()->andReturn($model);
$dbMock = Mockery::mock('\Box_Database');
$dbMock->shouldReceive('store')->atLeast()->once();
@@ -160,17 +131,14 @@ test('testActionSuspend', function (): void {
$serverManagerMock = Mockery::mock('\Server_Manager_Custom');
$serverManagerMock->shouldReceive('suspendAccount')->atLeast()->once();
$AMresultArray = [$serverManagerMock, new Server_Account()];
$serviceMock
->shouldReceive('_getAM')
->atLeast()->once()
->andReturn($AMresultArray);
$serviceMock->shouldReceive('_getAM')->atLeast()->once()->andReturn($AMresultArray);
$serviceMock->setDi($di);
$result = $serviceMock->action_suspend($orderModel);
expect($result)->toBeTrue();
});
test('testActionSuspendOrderWithoutActiveService', function (): void {
test('action suspend order without active service', function (): void {
$service = new Service();
$orderModel = new Model_ClientOrder();
$orderModel->loadBean(new Tests\Helpers\DummyBean());
@@ -183,12 +151,11 @@ test('testActionSuspendOrderWithoutActiveService', function (): void {
$di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
$service->setDi($di);
$this->expectException(FOSSBilling\Exception::class);
$this->expectExceptionMessage(sprintf('Order %d has no active service', $orderModel->id));
$service->action_suspend($orderModel);
expect(fn () => $service->action_suspend($orderModel))
->toThrow(FOSSBilling\Exception::class, sprintf('Order %d has no active service', $orderModel->id));
});
test('testActionUnsuspend', function (): void {
test('action unsuspend', function (): void {
$service = new Service();
$orderModel = new Model_ClientOrder();
$orderModel->loadBean(new Tests\Helpers\DummyBean());
@@ -197,10 +164,7 @@ test('testActionUnsuspend', function (): void {
$model->loadBean(new Tests\Helpers\DummyBean());
$orderServiceMock = Mockery::mock(Box\Mod\Order\Service::class);
$orderServiceMock
->shouldReceive('getOrderService')
->atLeast()->once()
->andReturn($model);
$orderServiceMock->shouldReceive('getOrderService')->atLeast()->once()->andReturn($model);
$dbMock = Mockery::mock('\Box_Database');
$dbMock->shouldReceive('store')->atLeast()->once();
@@ -213,17 +177,14 @@ test('testActionUnsuspend', function (): void {
$serverManagerMock = Mockery::mock('\Server_Manager_Custom');
$serverManagerMock->shouldReceive('unsuspendAccount')->atLeast()->once();
$AMresultArray = [$serverManagerMock, new Server_Account()];
$serviceMock
->shouldReceive('_getAM')
->atLeast()->once()
->andReturn($AMresultArray);
$serviceMock->shouldReceive('_getAM')->atLeast()->once()->andReturn($AMresultArray);
$serviceMock->setDi($di);
$result = $serviceMock->action_unsuspend($orderModel);
expect($result)->toBeTrue();
});
test('testActionUnsuspendOrderWithoutActiveService', function (): void {
test('action unsuspend order without active service', function (): void {
$service = new Service();
$orderModel = new Model_ClientOrder();
$orderModel->loadBean(new Tests\Helpers\DummyBean());
@@ -236,12 +197,11 @@ test('testActionUnsuspendOrderWithoutActiveService', function (): void {
$di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
$service->setDi($di);
$this->expectException(FOSSBilling\Exception::class);
$this->expectExceptionMessage(sprintf('Order %d has no active service', $orderModel->id));
$service->action_unsuspend($orderModel);
expect(fn () => $service->action_unsuspend($orderModel))
->toThrow(FOSSBilling\Exception::class, sprintf('Order %d has no active service', $orderModel->id));
});
test('testActionCancel', function (): void {
test('action cancel', function (): void {
$service = new Service();
$orderModel = new Model_ClientOrder();
$orderModel->loadBean(new Tests\Helpers\DummyBean());
@@ -250,10 +210,7 @@ test('testActionCancel', function (): void {
$model->loadBean(new Tests\Helpers\DummyBean());
$orderServiceMock = Mockery::mock(Box\Mod\Order\Service::class);
$orderServiceMock
->shouldReceive('getOrderService')
->atLeast()->once()
->andReturn($model);
$orderServiceMock->shouldReceive('getOrderService')->atLeast()->once()->andReturn($model);
$dbMock = Mockery::mock('\Box_Database');
$dbMock->shouldReceive('store')->atLeast()->once();
@@ -266,17 +223,14 @@ test('testActionCancel', function (): void {
$serverManagerMock = Mockery::mock('\Server_Manager_Custom');
$serverManagerMock->shouldReceive('cancelAccount')->atLeast()->once();
$AMresultArray = [$serverManagerMock, new Server_Account()];
$serviceMock
->shouldReceive('_getAM')
->atLeast()->once()
->andReturn($AMresultArray);
$serviceMock->shouldReceive('_getAM')->atLeast()->once()->andReturn($AMresultArray);
$serviceMock->setDi($di);
$result = $serviceMock->action_cancel($orderModel);
expect($result)->toBeTrue();
});
test('testActionCancelOrderWithoutActiveService', function (): void {
test('action cancel order without active service', function (): void {
$service = new Service();
$orderModel = new Model_ClientOrder();
$orderModel->loadBean(new Tests\Helpers\DummyBean());
@@ -289,12 +243,11 @@ test('testActionCancelOrderWithoutActiveService', function (): void {
$di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
$service->setDi($di);
$this->expectException(FOSSBilling\Exception::class);
$this->expectExceptionMessage(sprintf('Order %d has no active service', $orderModel->id));
$service->action_cancel($orderModel);
expect(fn () => $service->action_cancel($orderModel))
->toThrow(FOSSBilling\Exception::class, sprintf('Order %d has no active service', $orderModel->id));
});
test('testActionDelete', function (): void {
test('action delete', function (): void {
$service = new Service();
$orderModel = new Model_ClientOrder();
$orderModel->loadBean(new Tests\Helpers\DummyBean());
@@ -304,10 +257,7 @@ test('testActionDelete', function (): void {
$model->loadBean(new Tests\Helpers\DummyBean());
$orderServiceMock = Mockery::mock(Box\Mod\Order\Service::class);
$orderServiceMock
->shouldReceive('getOrderService')
->atLeast()->once()
->andReturn($model);
$orderServiceMock->shouldReceive('getOrderService')->atLeast()->once()->andReturn($model);
$dbMock = Mockery::mock('\Box_Database');
$dbMock->shouldReceive('trash')->atLeast()->once();
@@ -323,7 +273,7 @@ test('testActionDelete', function (): void {
$serviceMock->action_delete($orderModel);
});
test('testChangeAccountPlan', function (): void {
test('change account plan', function (): void {
$service = new Service();
$orderModel = new Model_ClientOrder();
$orderModel->loadBean(new Tests\Helpers\DummyBean());
@@ -339,27 +289,21 @@ test('testChangeAccountPlan', function (): void {
$di = container();
$di['db'] = $dbMock;
$di['logger'] = new Tests\Helpers\TestLogger();
$di['logger'] = new Box_Log();
$serviceMock = Mockery::mock(Service::class)->makePartial();
$serverManagerMock = Mockery::mock('\Server_Manager_Custom');
$serverManagerMock->shouldReceive('changeAccountPackage')->atLeast()->once();
$AMresultArray = [$serverManagerMock, new Server_Account()];
$serviceMock
->shouldReceive('_getAM')
->atLeast()->once()
->andReturn($AMresultArray);
$serviceMock
->shouldReceive('getServerPackage')
->atLeast()->once()
->andReturn(new Server_Package());
$serviceMock->shouldReceive('_getAM')->atLeast()->once()->andReturn($AMresultArray);
$serviceMock->shouldReceive('getServerPackage')->atLeast()->once()->andReturn(new Server_Package());
$serviceMock->setDi($di);
$result = $serviceMock->changeAccountPlan($orderModel, $model, $modelHp);
expect($result)->toBeTrue();
});
test('testChangeAccountUsername', function (): void {
test('change account username', function (): void {
$service = new Service();
$data = [
'username' => 'u123456',
@@ -377,17 +321,14 @@ test('testChangeAccountUsername', function (): void {
$serverManagerMock->shouldReceive('changeAccountUsername')->atLeast()->once();
$AMresultArray = [$serverManagerMock, new Server_Account()];
$serviceMock
->shouldReceive('_getAM')
->atLeast()->once()
->andReturn($AMresultArray);
$serviceMock->shouldReceive('_getAM')->atLeast()->once()->andReturn($AMresultArray);
$dbMock = Mockery::mock('\Box_Database');
$dbMock->shouldReceive('store')->atLeast()->once();
$di = container();
$di['db'] = $dbMock;
$di['logger'] = new Tests\Helpers\TestLogger();
$di['logger'] = new Box_Log();
$serviceMock->setDi($di);
@@ -395,7 +336,7 @@ test('testChangeAccountUsername', function (): void {
expect($result)->toBeTrue();
});
test('testChangeAccountUsernameMissingUsername', function (): void {
test('change account username missing username', function (): void {
$service = new Service();
$orderModel = new Model_ClientOrder();
$orderModel->loadBean(new Tests\Helpers\DummyBean());
@@ -404,12 +345,11 @@ test('testChangeAccountUsernameMissingUsername', function (): void {
$model->loadBean(new Tests\Helpers\DummyBean());
$data = [];
$this->expectException(FOSSBilling\Exception::class);
$this->expectExceptionMessage('Account username is missing or is invalid');
$service->changeAccountUsername($orderModel, $model, $data);
expect(fn () => $service->changeAccountUsername($orderModel, $model, $data))
->toThrow(FOSSBilling\Exception::class, 'Account username is missing or is invalid');
});
test('testChangeAccountIp', function (): void {
test('change account ip', function (): void {
$service = new Service();
$data = [
'ip' => '1.1.1.1',
@@ -427,17 +367,14 @@ test('testChangeAccountIp', function (): void {
$serverManagerMock->shouldReceive('changeAccountIp')->atLeast()->once();
$AMresultArray = [$serverManagerMock, new Server_Account()];
$serviceMock
->shouldReceive('_getAM')
->atLeast()->once()
->andReturn($AMresultArray);
$serviceMock->shouldReceive('_getAM')->atLeast()->once()->andReturn($AMresultArray);
$dbMock = Mockery::mock('\Box_Database');
$dbMock->shouldReceive('store')->atLeast()->once();
$di = container();
$di['db'] = $dbMock;
$di['logger'] = new Tests\Helpers\TestLogger();
$di['logger'] = new Box_Log();
$serviceMock->setDi($di);
@@ -445,7 +382,7 @@ test('testChangeAccountIp', function (): void {
expect($result)->toBeTrue();
});
test('testChangeAccountIpMissingIp', function (): void {
test('change account ip missing ip', function (): void {
$service = new Service();
$data = [];
$orderModel = new Model_ClientOrder();
@@ -454,12 +391,11 @@ test('testChangeAccountIpMissingIp', function (): void {
$model = new Model_ServiceHosting();
$model->loadBean(new Tests\Helpers\DummyBean());
$this->expectException(FOSSBilling\Exception::class);
$this->expectExceptionMessage('Account IP address is missing or is invalid');
$service->changeAccountIp($orderModel, $model, $data);
expect(fn () => $service->changeAccountIp($orderModel, $model, $data))
->toThrow(FOSSBilling\Exception::class, 'Account IP address is missing or is invalid');
});
test('testChangeAccountDomain', function (): void {
test('change account domain', function (): void {
$service = new Service();
$data = [
'tld' => 'com',
@@ -478,17 +414,14 @@ test('testChangeAccountDomain', function (): void {
$serverManagerMock->shouldReceive('changeAccountDomain')->atLeast()->once();
$AMresultArray = [$serverManagerMock, new Server_Account()];
$serviceMock
->shouldReceive('_getAM')
->atLeast()->once()
->andReturn($AMresultArray);
$serviceMock->shouldReceive('_getAM')->atLeast()->once()->andReturn($AMresultArray);
$dbMock = Mockery::mock('\Box_Database');
$dbMock->shouldReceive('store')->atLeast()->once();
$di = container();
$di['db'] = $dbMock;
$di['logger'] = new Tests\Helpers\TestLogger();
$di['logger'] = new Box_Log();
$serviceMock->setDi($di);
@@ -496,7 +429,7 @@ test('testChangeAccountDomain', function (): void {
expect($result)->toBeTrue();
});
test('testChangeAccountDomainMissingParams', function (): void {
test('change account domain missing params', function (): void {
$service = new Service();
$data = [];
$orderModel = new Model_ClientOrder();
@@ -505,12 +438,11 @@ test('testChangeAccountDomainMissingParams', function (): void {
$model = new Model_ServiceHosting();
$model->loadBean(new Tests\Helpers\DummyBean());
$this->expectException(FOSSBilling\Exception::class);
$this->expectExceptionMessage('Domain SLD or TLD is missing');
$service->changeAccountDomain($orderModel, $model, $data);
expect(fn () => $service->changeAccountDomain($orderModel, $model, $data))
->toThrow(FOSSBilling\Exception::class, 'Domain SLD or TLD is missing');
});
test('testChangeAccountPassword', function (): void {
test('change account password', function (): void {
$service = new Service();
$data = [
'password' => 'topsecret',
@@ -529,17 +461,14 @@ test('testChangeAccountPassword', function (): void {
$serverManagerMock->shouldReceive('changeAccountPassword')->atLeast()->once();
$AMresultArray = [$serverManagerMock, new Server_Account()];
$serviceMock
->shouldReceive('_getAM')
->atLeast()->once()
->andReturn($AMresultArray);
$serviceMock->shouldReceive('_getAM')->atLeast()->once()->andReturn($AMresultArray);
$dbMock = Mockery::mock('\Box_Database');
$dbMock->shouldReceive('store')->atLeast()->once();
$di = container();
$di['db'] = $dbMock;
$di['logger'] = new Tests\Helpers\TestLogger();
$di['logger'] = new Box_Log();
$serviceMock->setDi($di);
@@ -547,7 +476,7 @@ test('testChangeAccountPassword', function (): void {
expect($result)->toBeTrue();
});
test('testChangeAccountPasswordMissingParams', function (): void {
test('change account password missing params', function (): void {
$service = new Service();
$data = [];
$orderModel = new Model_ClientOrder();
@@ -556,12 +485,11 @@ test('testChangeAccountPasswordMissingParams', function (): void {
$model = new Model_ServiceHosting();
$model->loadBean(new Tests\Helpers\DummyBean());
$this->expectException(FOSSBilling\Exception::class);
$this->expectExceptionMessage('Account password is missing or is invalid');
$service->changeAccountPassword($orderModel, $model, $data);
expect(fn () => $service->changeAccountPassword($orderModel, $model, $data))
->toThrow(FOSSBilling\Exception::class, 'Account password is missing or is invalid');
});
test('testSync', function (): void {
test('sync', function (): void {
$service = new Service();
$data = [
'password' => 'topsecret',
@@ -585,23 +513,17 @@ test('testSync', function (): void {
$accountObj2->setIp('2.2.2.2');
$serverManagerMock = Mockery::mock('\Server_Manager_Custom');
$serverManagerMock
->shouldReceive('synchronizeAccount')
->atLeast()->once()
->andReturn($accountObj2);
$serverManagerMock->shouldReceive('synchronizeAccount')->atLeast()->once()->andReturn($accountObj2);
$AMresultArray = [$serverManagerMock, $accountObj];
$serviceMock
->shouldReceive('_getAM')
->atLeast()->once()
->andReturn($AMresultArray);
$serviceMock->shouldReceive('_getAM')->atLeast()->once()->andReturn($AMresultArray);
$dbMock = Mockery::mock('\Box_Database');
$dbMock->shouldReceive('store')->atLeast()->once();
$di = container();
$di['db'] = $dbMock;
$di['logger'] = new Tests\Helpers\TestLogger();
$di['logger'] = new Box_Log();
$serviceMock->setDi($di);
@@ -609,7 +531,7 @@ test('testSync', function (): void {
expect($result)->toBeTrue();
});
test('testToApiArray', function (): void {
test('to api array', function (): void {
$service = new Service();
$model = new Model_ServiceHosting();
$model->loadBean(new Tests\Helpers\DummyBean());
@@ -621,19 +543,17 @@ test('testToApiArray', function (): void {
$hostingHp->loadBean(new Tests\Helpers\DummyBean());
$dbMock = Mockery::mock('\Box_Database');
$dbMock
->shouldReceive('load')
->andReturn($hostingServer, $hostingHp);
$dbMock->shouldReceive('load')->atLeast()->once()->andReturn($hostingServer, $hostingHp);
$orderServiceMock = Mockery::mock(Box\Mod\Order\Service::class);
$orderServiceMock->shouldReceive('getServiceOrder')->atLeast()->once();
$serverManagerCustomStub = Mockery::mock('\Server_Manager_Custom');
$serverManagerCustomMock = Mockery::mock('\Server_Manager_Custom')->shouldIgnoreMissing();
$di = container();
$di['db'] = $dbMock;
$di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
$di['server_manager'] = $di->protect(fn ($manager, $config) => $serverManagerCustomStub);
$di['server_manager'] = $di->protect(fn ($manager, $config) => $serverManagerCustomMock);
$service->setDi($di);
@@ -641,7 +561,7 @@ test('testToApiArray', function (): void {
expect($result)->toBeArray();
});
test('testUpdate', function (): void {
test('update', function (): void {
$service = new Service();
$data = [
'username' => 'testUser',
@@ -655,20 +575,20 @@ test('testUpdate', function (): void {
$di = container();
$di['db'] = $dbMock;
$di['logger'] = new Tests\Helpers\TestLogger();
$di['logger'] = new Box_Log();
$service->setDi($di);
$result = $service->update($model, $data);
expect($result)->toBeTrue();
});
test('testGetServerManagers', function (): void {
test('get server managers', function (): void {
$service = new Service();
$result = $service->getServerManagers();
expect($result)->toBeArray();
});
test('testGetServerManagerConfig', function (): void {
test('get server manager config', function (): void {
$service = new Service();
$manager = 'Custom';
@@ -678,10 +598,10 @@ test('testGetServerManagerConfig', function (): void {
$result = $service->getServerManagerConfig($manager);
expect($result)->toBeArray();
expect($result)->toBe($expected);
expect($result)->toEqual($expected);
});
test('testGetServerPairs', function (): void {
test('get server pairs', function (): void {
$service = new Service();
$expected = [
'1' => 'name',
@@ -699,10 +619,7 @@ test('testGetServerPairs', function (): void {
];
$dbMock = Mockery::mock('\Box_Database');
$dbMock
->shouldReceive('getAll')
->atLeast()->once()
->andReturn($queryResult);
$dbMock->shouldReceive('getAll')->atLeast()->once()->andReturn($queryResult);
$di = container();
$di['db'] = $dbMock;
@@ -710,37 +627,31 @@ test('testGetServerPairs', function (): void {
$result = $service->getServerPairs();
expect($result)->toBeArray();
expect($result)->toBe($expected);
expect($result)->toEqual($expected);
});
test('testGetServerSearchQuery', function (): void {
test('get server search query', function (): void {
$service = new Service();
$result = $service->getServersSearchQuery([]);
expect($result[0])->toBeString();
expect($result[1])->toBeArray();
expect($result[1])->toBe([]);
expect($result[1])->toEqual([]);
});
test('testCreateServer', function (): void {
test('create server', function (): void {
$service = new Service();
$dbMock = Mockery::mock('\Box_Database');
$hostingServerModel = new Model_ServiceHostingServer();
$hostingServerModel->loadBean(new Tests\Helpers\DummyBean());
$dbMock
->shouldReceive('dispense')
->atLeast()->once()
->andReturn($hostingServerModel);
$dbMock->shouldReceive('dispense')->atLeast()->once()->andReturn($hostingServerModel);
$newId = 1;
$dbMock
->shouldReceive('store')
->atLeast()->once()
->andReturn($newId);
$dbMock->shouldReceive('store')->atLeast()->once()->andReturn($newId);
$di = container();
$di['db'] = $dbMock;
$di['logger'] = new Tests\Helpers\TestLogger();
$di['logger'] = new Box_Log();
$service->setDi($di);
@@ -753,7 +664,7 @@ test('testCreateServer', function (): void {
expect($result)->toBe($newId);
});
test('testDeleteServer', function (): void {
test('delete server', function (): void {
$service = new Service();
$hostingServerModel = new Model_ServiceHostingServer();
$hostingServerModel->loadBean(new Tests\Helpers\DummyBean());
@@ -763,14 +674,14 @@ test('testDeleteServer', function (): void {
$di = container();
$di['db'] = $dbMock;
$di['logger'] = new Tests\Helpers\TestLogger();
$di['logger'] = new Box_Log();
$service->setDi($di);
$result = $service->deleteServer($hostingServerModel);
expect($result)->toBeTrue();
});
test('testUpdateServer', function (): void {
test('update server', function (): void {
$service = new Service();
$data = [
'name' => 'newName',
@@ -798,7 +709,7 @@ test('testUpdateServer', function (): void {
$di = container();
$di['db'] = $dbMock;
$di['logger'] = new Tests\Helpers\TestLogger();
$di['logger'] = new Box_Log();
$service->setDi($di);
@@ -806,34 +717,32 @@ test('testUpdateServer', function (): void {
expect($result)->toBeTrue();
});
test('testGetServerManager', function (): void {
test('get server manager', function (): void {
$service = new Service();
$hostingServerModel = new Model_ServiceHostingServer();
$hostingServerModel->loadBean(new Tests\Helpers\DummyBean());
$hostingServerModel->manager = 'Custom';
$serverManagerCustomStub = Mockery::mock('\Server_Manager_Custom');
$serverManagerCustom = Mockery::mock('\Server_Manager_Custom')->shouldIgnoreMissing();
$di = container();
$di['server_manager'] = $di->protect(fn ($manager, $config) => $serverManagerCustomStub);
$di['server_manager'] = $di->protect(fn ($manager, $config) => $serverManagerCustom);
$service->setDi($di);
$result = $service->getServerManager($hostingServerModel);
expect($result)->toBeInstanceOf('\Server_Manager_Custom');
});
test('testGetServerManagerManagerNotDefined', function (): void {
test('get server manager manager not defined', function (): void {
$service = new Service();
$hostingServerModel = new Model_ServiceHostingServer();
$hostingServerModel->loadBean(new Tests\Helpers\DummyBean());
$this->expectException(FOSSBilling\Exception::class);
$this->expectExceptionCode(654);
$this->expectExceptionMessage('Invalid server manager. Server was not configured properly');
$service->getServerManager($hostingServerModel);
expect(fn () => $service->getServerManager($hostingServerModel))
->toThrow(FOSSBilling\Exception::class);
});
test('testGetServerManagerServerManagerInvalid', function (): void {
test('get server manager server manager invalid', function (): void {
$service = new Service();
$hostingServerModel = new Model_ServiceHostingServer();
$hostingServerModel->loadBean(new Tests\Helpers\DummyBean());
@@ -843,25 +752,16 @@ test('testGetServerManagerServerManagerInvalid', function (): void {
$di['server_manager'] = $di->protect(fn ($manager, $config): null => null);
$service->setDi($di);
$this->expectException(FOSSBilling\Exception::class);
$this->expectExceptionMessage("Server manager {$hostingServerModel->manager} is invalid.");
$service->getServerManager($hostingServerModel);
expect(fn () => $service->getServerManager($hostingServerModel))
->toThrow(FOSSBilling\Exception::class, "Server manager {$hostingServerModel->manager} is invalid.");
});
test('testTestConnection', function (): void {
$service = new Service();
test('test connection', function (): void {
$serverManagerMock = Mockery::mock('\Server_Manager_Custom');
$serverManagerMock
->shouldReceive('testConnection')
->atLeast()->once()
->andReturn(true);
$serverManagerMock->shouldReceive('testConnection')->atLeast()->once()->andReturn(true);
$serviceMock = Mockery::mock(Service::class)->makePartial();
$serviceMock
->shouldReceive('getServerManager')
->atLeast()->once()
->andReturn($serverManagerMock);
$serviceMock->shouldReceive('getServerManager')->atLeast()->once()->andReturn($serverManagerMock);
$hostingServerModel = new Model_ServiceHostingServer();
$result = $serviceMock->testConnection($hostingServerModel);
@@ -869,7 +769,7 @@ test('testTestConnection', function (): void {
expect($result)->toBeTrue();
});
test('testGetHpPairs', function (): void {
test('get hp pairs', function (): void {
$service = new Service();
$expected = [
'1' => 'free',
@@ -887,10 +787,7 @@ test('testGetHpPairs', function (): void {
];
$dbMock = Mockery::mock('\Box_Database');
$dbMock
->shouldReceive('getAll')
->atLeast()->once()
->andReturn($queryResult);
$dbMock->shouldReceive('getAll')->atLeast()->once()->andReturn($queryResult);
$di = container();
$di['db'] = $dbMock;
@@ -898,36 +795,36 @@ test('testGetHpPairs', function (): void {
$result = $service->getHpPairs();
expect($result)->toBeArray();
expect($result)->toBe($expected);
expect($result)->toEqual($expected);
});
test('testGetHpSearchQuery', function (): void {
test('get hp search query', function (): void {
$service = new Service();
$result = $service->getServersSearchQuery([]);
expect($result[0])->toBeString();
expect($result[1])->toBeArray();
expect($result[1])->toBe([]);
expect($result[1])->toEqual([]);
});
test('testDeleteHp', function (): void {
test('delete hp', function (): void {
$service = new Service();
$model = new Model_ServiceHostingHp();
$model->loadBean(new Tests\Helpers\DummyBean());
$dbMock = Mockery::mock('\Box_Database');
$dbMock->shouldReceive('findOne')->atLeast()->once()->andReturn(null);
$dbMock->shouldReceive('trash')->atLeast()->once();
$dbMock->shouldReceive('findOne')->atLeast()->once()->andReturn(null);
$di = container();
$di['db'] = $dbMock;
$di['logger'] = new Tests\Helpers\TestLogger();
$di['logger'] = new Box_Log();
$service->setDi($di);
$result = $service->deleteHp($model);
expect($result)->toBeTrue();
});
test('testToHostingHpApiArray', function (): void {
test('to hosting hp api array', function (): void {
$service = new Service();
$model = new Model_ServiceHostingHp();
$model->loadBean(new Tests\Helpers\DummyBean());
@@ -936,7 +833,7 @@ test('testToHostingHpApiArray', function (): void {
expect($result)->toBeArray();
});
test('testUpdateHp', function (): void {
test('update hp', function (): void {
$service = new Service();
$data = [
'name' => 'firstPlan',
@@ -958,7 +855,7 @@ test('testUpdateHp', function (): void {
$di = container();
$di['db'] = $dbMock;
$di['logger'] = new Tests\Helpers\TestLogger();
$di['logger'] = new Box_Log();
$service->setDi($di);
@@ -966,21 +863,19 @@ test('testUpdateHp', function (): void {
expect($result)->toBeTrue();
});
test('testCreateHp', function (): void {
test('create hp', function (): void {
$service = new Service();
$model = new Model_ServiceHostingHp();
$model->loadBean(new Tests\Helpers\DummyBean());
$newId = 1;
$dbMock = Mockery::mock('\Box_Database');
$dbMock
->shouldReceive('dispense')->atLeast()->once()->andReturn($model);
$dbMock
->shouldReceive('store')->atLeast()->once()->andReturn($newId);
$dbMock->shouldReceive('dispense')->atLeast()->once()->andReturn($model);
$dbMock->shouldReceive('store')->atLeast()->once()->andReturn($newId);
$di = container();
$di['db'] = $dbMock;
$di['logger'] = new Tests\Helpers\TestLogger();
$di['logger'] = new Box_Log();
$service->setDi($di);
@@ -989,7 +884,7 @@ test('testCreateHp', function (): void {
expect($result)->toBe($newId);
});
test('testGetServerPackage', function (): void {
test('get server package', function (): void {
$service = new Service();
$model = new Model_ServiceHostingHp();
$model->loadBean(new Tests\Helpers\DummyBean());
@@ -1002,8 +897,7 @@ test('testGetServerPackage', function (): void {
expect($result)->toBeInstanceOf('\Server_Package');
});
test('testGetServerManagerWithLog', function (): void {
$service = new Service();
test('get server manager with log', function (): void {
$hostingServerModel = new Model_ServiceHostingServer();
$hostingServerModel->loadBean(new Tests\Helpers\DummyBean());
$hostingServerModel->manager = 'Custom';
@@ -1011,19 +905,12 @@ test('testGetServerManagerWithLog', function (): void {
$clientOrderModel = new Model_ClientOrder();
$clientOrderModel->loadBean(new Tests\Helpers\DummyBean());
$serverManagerMock = Mockery::mock('\Server_Manager_Custom');
$serverManagerMock->shouldReceive('setLog')->atLeast()->once();
$serverManagerMock = Mockery::mock('\Server_Manager_Custom')->shouldIgnoreMissing();
$serviceMock = Mockery::mock(Service::class)->makePartial();
$serviceMock
->shouldReceive('getServerManager')
->atLeast()->once()
->andReturn($serverManagerMock);
$serviceMock->shouldReceive('getServerManager')->atLeast()->once()->andReturn($serverManagerMock);
$orderServiceMock = Mockery::mock(Box\Mod\Order\Service::class);
$orderServiceMock
->shouldReceive('getLogger')
->atLeast()->once()
->andReturn(new Tests\Helpers\TestLogger());
$orderServiceMock->shouldReceive('getLogger')->atLeast()->once()->andReturn(new Box_Log());
$di = container();
$di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
@@ -1033,27 +920,17 @@ test('testGetServerManagerWithLog', function (): void {
expect($result)->toBeInstanceOf('\Server_Manager_Custom');
});
test('testGetManagerUrls', function (): void {
$service = new Service();
test('get manager urls', function (): void {
$hostingServerModel = new Model_ServiceHostingServer();
$hostingServerModel->loadBean(new Tests\Helpers\DummyBean());
$hostingServerModel->manager = 'Custom';
$serverManagerMock = Mockery::mock('\Server_Manager_Custom');
$serverManagerMock
->shouldReceive('getLoginUrl')
->atLeast()->once()
->andReturn('/login');
$serverManagerMock
->shouldReceive('getResellerLoginUrl')
->atLeast()->once()
->andReturn('/admin/login');
$serverManagerMock->shouldReceive('getLoginUrl')->atLeast()->once()->andReturn('/login');
$serverManagerMock->shouldReceive('getResellerLoginUrl')->atLeast()->once()->andReturn('/admin/login');
$serviceMock = Mockery::mock(Service::class)->makePartial();
$serviceMock
->shouldReceive('getServerManager')
->atLeast()->once()
->andReturn($serverManagerMock);
$serviceMock->shouldReceive('getServerManager')->atLeast()->once()->andReturn($serverManagerMock);
$result = $serviceMock->getManagerUrls($hostingServerModel);
expect($result)->toBeArray();
@@ -1061,20 +938,13 @@ test('testGetManagerUrls', function (): void {
expect($result[1])->toBeString();
});
test('testGetManagerUrlsException', function (): void {
$service = new Service();
test('get manager urls exception', function (): void {
$hostingServerModel = new Model_ServiceHostingServer();
$hostingServerModel->loadBean(new Tests\Helpers\DummyBean());
$hostingServerModel->manager = 'Custom';
$serviceMock = Mockery::mock(Service::class)->makePartial();
$serviceMock
->shouldReceive('getServerManager')
->andThrow(new Exception('Controlled unit test exception'));
$di = container();
$di['logger'] = new Tests\Helpers\TestLogger();
$serviceMock->setDi($di);
$serviceMock->shouldReceive('getServerManager')->atLeast()->once()->andThrow(new Exception('Controlled unit test exception'));
$result = $serviceMock->getManagerUrls($hostingServerModel);
expect($result)->toBeArray();
@@ -1082,36 +952,29 @@ test('testGetManagerUrlsException', function (): void {
expect($result[1])->toBeFalse();
});
test('testGetFreeTldsFreeTldsAreNotSet', function (): void {
test('get free tlds free tlds are not set', function (): void {
$service = new Service();
$di = container();
$tldArray = ['tld' => '.com'];
$serviceDomainServiceMock = Mockery::mock(Box\Mod\Servicedomain\Service::class);
$serviceDomainServiceMock
->shouldReceive('tldToApiArray')
->atLeast()->once()
->andReturn($tldArray);
$serviceDomainServiceMock->shouldReceive('tldToApiArray')->atLeast()->once()->andReturn($tldArray);
$di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $serviceDomainServiceMock);
$tldModel = new Model_Tld();
$tldModel->loadBean(new Tests\Helpers\DummyBean());
$dbMock = Mockery::mock('\Box_Database');
$dbMock
->shouldReceive('find')
->atLeast()->once()
->andReturn([$tldModel]);
$dbMock->shouldReceive('find')->atLeast()->once()->andReturn([$tldModel]);
$di['db'] = $dbMock;
$service->setDi($di);
$model = new Model_Product();
$model->loadBean(new Tests\Helpers\DummyBean());
$result = $service->getFreeTlds($model);
$product = new Box\Mod\Product\Entity\Product();
$result = $service->getFreeTlds($product);
expect($result)->toBeArray();
});
test('testGetFreeTlds', function (): void {
test('get free tlds', function (): void {
$service = new Service();
$config = [
'free_tlds' => ['.com'],
@@ -1119,11 +982,10 @@ test('testGetFreeTlds', function (): void {
$di = container();
$service->setDi($di);
$model = new Model_Product();
$model->loadBean(new Tests\Helpers\DummyBean());
$model->config = json_encode($config);
$product = new Box\Mod\Product\Entity\Product();
$product->setConfig(json_encode($config));
$result = $service->getFreeTlds($model);
$result = $service->getFreeTlds($product);
expect($result)->toBeArray();
expect($result)->not->toBeEmpty();
});
-2
View File
@@ -21,8 +21,6 @@ class Guest extends \FOSSBilling\Api\AbstractApi
* Check license details callback. Request IP is detected automatically
* You can pass any other parameters to be validated by license plugin.
*
* @optional string $legacy - deprecated parameter. Returns result in non consistent API result
*
* @return array - bool
*/
public function check($data)
+6 -3
View File
@@ -12,6 +12,7 @@ declare(strict_types=1);
namespace Box\Mod\Servicelicense;
use Box\Mod\Product\Entity\Product;
use FOSSBilling\InjectionAwareInterface;
use Symfony\Component\Filesystem\Path;
use Symfony\Component\Finder\Finder;
@@ -44,9 +45,9 @@ class Service implements InjectionAwareInterface
/**
* Method called before adding product to cart.
*/
public function attachOrderConfig(\Model_Product $product, array $data): array
public function attachOrderConfig(Product $product, array $data): array
{
$config = json_decode($product->config ?? '', true) ?? [];
$config = json_decode($product->getConfig() ?? '', true) ?? [];
return array_merge($config, $data);
}
@@ -382,7 +383,9 @@ class Service implements InjectionAwareInterface
return new $class_name();
}
}
$this->di['logger']->warning("License #{$model->id} plugin {$model->plugin} is invalid.");
if (isset($this->di['logger'])) {
$this->di['logger']->info('License #%s plugin %s is invalid.', $model->id, $model->plugin);
}
return null;
}
@@ -78,7 +78,7 @@
</table>
<h2>{{ 'Reset License'|trans }}</h2>
<p>{{ 'You can reset your license parameters if you have changed your server'|trans }}</p>
<p>{{ 'Resetting the license will clear saved validation data (IP addresses, domains, versions, and installation paths). Use this if you moved servers; the license must then be activated again from the new environment.'|trans }}</p>
<div class="block">
<p>
<a class="btn btn-primary" {{ fb_api_link({href: 'servicelicense/reset'|api_url(query: {order_id: order.id}), modal: {type: 'confirm', title: 'Are you sure?'|trans}, message: 'License was reset'|trans}) }}>{{ 'Reset'|trans }}</a>
@@ -10,21 +10,24 @@
declare(strict_types=1);
use Box\Mod\Order\Service as OrderService;
use Box\Mod\Product\Entity\Product;
use Box\Mod\Servicelicense\Server;
use Box\Mod\Servicelicense\Service;
use function Tests\Helpers\container;
test('getDi', function (): void {
$service = new Box\Mod\Servicelicense\Service();
$di = container();
$service->setDi($di);
$getDi = $service->getDi();
expect($getDi)->toBe($di);
});
function serviceLicenseCreateProductEntity(string $config): Product
{
$product = new Product();
$product->setConfig($config);
test('attachOrderConfig with empty product config', function (): void {
$service = new Box\Mod\Servicelicense\Service();
$productModel = new Model_Product();
$productModel->loadBean(new Tests\Helpers\DummyBean());
$productModel->config = '{}';
return $product;
}
test('attach order config empty product config', function (): void {
$service = new Service();
$productModel = serviceLicenseCreateProductEntity('{}');
$data = [];
$result = $service->attachOrderConfig($productModel, $data);
@@ -32,45 +35,36 @@ test('attachOrderConfig with empty product config', function (): void {
expect($result)->toBe([]);
});
test('attachOrderConfig', function (): void {
$service = new Box\Mod\Servicelicense\Service();
$productModel = new Model_Product();
$productModel->loadBean(new Tests\Helpers\DummyBean());
$productModel->config = '["hello", "world"]';
test('attach order config', function (): void {
$service = new Service();
$productModel = serviceLicenseCreateProductEntity('["hello", "world"]');
$data = ['testing' => 'phase'];
$expected = array_merge(json_decode($productModel->config ?? '', true), $data);
$expected = array_merge(json_decode($productModel->getConfig() ?? '', true) ?? [], $data);
$result = $service->attachOrderConfig($productModel, $data);
expect($result)->toBeArray();
expect($result)->toEqual($expected);
});
test('getLicensePlugins', function (): void {
$service = new Box\Mod\Servicelicense\Service();
test('get license plugins', function (): void {
$service = new Service();
$result = $service->getLicensePlugins();
expect($result)->toBeArray();
});
test('actionCreate', function (): void {
$service = new Box\Mod\Servicelicense\Service();
test('action create', function (): void {
$service = new Service();
$clientOrderModel = new Model_ClientOrder();
$clientOrderModel->loadBean(new Tests\Helpers\DummyBean());
$serviceLicenseModel = new Model_ServiceLicense();
$serviceLicenseModel->loadBean(new Tests\Helpers\DummyBean());
$dbMock = Mockery::mock('\Box_Database');
$dbMock->shouldReceive('dispense')
->atLeast()
->once()
->andReturn($serviceLicenseModel);
$dbMock->shouldReceive('store')->atLeast()->once();
$dbMock = Mockery::mock(Box_Database::class)->shouldIgnoreMissing();
$dbMock->shouldReceive('dispense')->atLeast()->once()->andReturn($serviceLicenseModel);
$orderServiceMock = Mockery::mock(Box\Mod\Order\Service::class);
$orderServiceMock->shouldReceive('getConfig')
->atLeast()
->once()
->andReturn([]);
$orderServiceMock = Mockery::mock(OrderService::class);
$orderServiceMock->shouldReceive('getConfig')->atLeast()->once()->andReturn([]);
$di = container();
$di['db'] = $dbMock;
@@ -82,8 +76,8 @@ test('actionCreate', function (): void {
expect($result)->toBeInstanceOf(Model_ServiceLicense::class);
});
test('actionActivate', function (): void {
$service = new Box\Mod\Servicelicense\Service();
test('action activate', function (): void {
$service = new Service();
$clientOrderModel = new Model_ClientOrder();
$clientOrderModel->loadBean(new Tests\Helpers\DummyBean());
@@ -91,19 +85,12 @@ test('actionActivate', function (): void {
$serviceLicenseModel->loadBean(new Tests\Helpers\DummyBean());
$serviceLicenseModel->plugin = 'Simple';
$orderServiceMock = Mockery::mock(Box\Mod\Order\Service::class);
$orderServiceMock->shouldReceive('getConfig')
->atLeast()
->once()
->andReturn([]);
$orderServiceMock->shouldReceive('getOrderService')
->atLeast()
->once()
->andReturn($serviceLicenseModel);
$orderServiceMock = Mockery::mock(OrderService::class);
$orderServiceMock->shouldReceive('getConfig')->atLeast()->once()->andReturn([]);
$orderServiceMock->shouldReceive('getOrderService')->atLeast()->once()->andReturn($serviceLicenseModel);
$dbMock = Mockery::mock('\Box_Database');
$dbMock = Mockery::mock(Box_Database::class)->shouldIgnoreMissing();
$dbMock->shouldReceive('store')->atLeast()->once();
$dbMock->shouldReceive('findOne')->atLeast()->once()->andReturn(null);
$di = container();
$di['db'] = $dbMock;
@@ -115,8 +102,8 @@ test('actionActivate', function (): void {
expect($result)->toBeTrue();
});
test('actionActivate with license collision', function (): void {
$service = new Box\Mod\Servicelicense\Service();
test('action activate license collision', function (): void {
$service = new Service();
$clientOrderModel = new Model_ClientOrder();
$clientOrderModel->loadBean(new Tests\Helpers\DummyBean());
@@ -124,26 +111,15 @@ test('actionActivate with license collision', function (): void {
$serviceLicenseModel->loadBean(new Tests\Helpers\DummyBean());
$serviceLicenseModel->plugin = 'Simple';
$orderServiceMock = Mockery::mock(Box\Mod\Order\Service::class);
$orderServiceMock->shouldReceive('getConfig')
->atLeast()
->once()
->andReturn(['iterations' => 3]);
$orderServiceMock->shouldReceive('getOrderService')
->atLeast()
->once()
->andReturn($serviceLicenseModel);
$orderServiceMock = Mockery::mock(OrderService::class);
$orderServiceMock->shouldReceive('getConfig')->atLeast()->once()->andReturn(['iterations' => 3]);
$orderServiceMock->shouldReceive('getOrderService')->atLeast()->once()->andReturn($serviceLicenseModel);
$dbMock = Mockery::mock('\Box_Database');
$dbMock->shouldReceive('store')->atLeast()->once();
$dbMock = Mockery::mock(Box_Database::class)->shouldIgnoreMissing();
$dbMock->shouldReceive('findOne')
->times(3)
->andReturnUsing(function () use ($serviceLicenseModel) {
static $callCount = 0;
++$callCount;
return $callCount <= 2 ? $serviceLicenseModel : null;
});
->andReturn($serviceLicenseModel, $serviceLicenseModel, null);
$dbMock->shouldReceive('store')->atLeast()->once();
$di = container();
$di['db'] = $dbMock;
@@ -155,8 +131,8 @@ test('actionActivate with license collision', function (): void {
expect($result)->toBeTrue();
});
test('actionActivate with license collision max iterations exception', function (): void {
$service = new Box\Mod\Servicelicense\Service();
test('action activate license collision max iterations exception', function (): void {
$service = new Service();
$clientOrderModel = new Model_ClientOrder();
$clientOrderModel->loadBean(new Tests\Helpers\DummyBean());
@@ -164,22 +140,13 @@ test('actionActivate with license collision max iterations exception', function
$serviceLicenseModel->loadBean(new Tests\Helpers\DummyBean());
$serviceLicenseModel->plugin = 'Simple';
$orderServiceMock = Mockery::mock(Box\Mod\Order\Service::class);
$orderServiceMock->shouldReceive('getConfig')
->atLeast()
->once()
->andReturn([]);
$orderServiceMock->shouldReceive('getOrderService')
->atLeast()
->once()
->andReturn($serviceLicenseModel);
$orderServiceMock = Mockery::mock(OrderService::class);
$orderServiceMock->shouldReceive('getConfig')->atLeast()->once()->andReturn([]);
$orderServiceMock->shouldReceive('getOrderService')->atLeast()->once()->andReturn($serviceLicenseModel);
$dbMock = Mockery::mock('\Box_Database');
$dbMock->shouldReceive('store')->never();
$dbMock->shouldReceive('findOne')
->atLeast()
->once()
->andReturn($serviceLicenseModel);
$dbMock = Mockery::mock(Box_Database::class);
$dbMock->shouldNotReceive('store');
$dbMock->shouldReceive('findOne')->atLeast()->once()->andReturn($serviceLicenseModel);
$di = container();
$di['db'] = $dbMock;
@@ -187,12 +154,12 @@ test('actionActivate with license collision max iterations exception', function
$service->setDi($di);
expect(fn (): bool => $service->action_activate($clientOrderModel))
expect(fn () => $service->action_activate($clientOrderModel))
->toThrow(FOSSBilling\Exception::class);
});
test('actionActivate with plugin not found', function (): void {
$service = new Box\Mod\Servicelicense\Service();
test('action activate plugin not found', function (): void {
$service = new Service();
$clientOrderModel = new Model_ClientOrder();
$clientOrderModel->loadBean(new Tests\Helpers\DummyBean());
@@ -200,64 +167,50 @@ test('actionActivate with plugin not found', function (): void {
$serviceLicenseModel->loadBean(new Tests\Helpers\DummyBean());
$serviceLicenseModel->plugin = 'TestPlugin';
$orderServiceMock = Mockery::mock(Box\Mod\Order\Service::class);
$orderServiceMock->shouldReceive('getConfig')
->atLeast()
->once()
->andReturn([]);
$orderServiceMock->shouldReceive('getOrderService')
->atLeast()
->once()
->andReturn($serviceLicenseModel);
$orderServiceMock = Mockery::mock(OrderService::class);
$orderServiceMock->shouldReceive('getConfig')->atLeast()->once()->andReturn([]);
$orderServiceMock->shouldReceive('getOrderService')->atLeast()->once()->andReturn($serviceLicenseModel);
$di = container();
$di['logger'] = new Box_Log();
$di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
$service->setDi($di);
expect(fn (): bool => $service->action_activate($clientOrderModel))
expect(fn () => $service->action_activate($clientOrderModel))
->toThrow(FOSSBilling\Exception::class, "License plugin {$serviceLicenseModel->plugin} was not found.");
});
test('actionActivate with order activation exception', function (): void {
$service = new Box\Mod\Servicelicense\Service();
test('action activate order activation exception', function (): void {
$service = new Service();
$clientOrderModel = new Model_ClientOrder();
$clientOrderModel->loadBean(new Tests\Helpers\DummyBean());
$orderServiceMock = Mockery::mock(Box\Mod\Order\Service::class);
$orderServiceMock->shouldReceive('getConfig')
->atLeast()
->once()
->andReturn([]);
$orderServiceMock->shouldReceive('getOrderService')
->atLeast()
->once()
->andReturn(null);
$orderServiceMock = Mockery::mock(OrderService::class);
$orderServiceMock->shouldReceive('getConfig')->atLeast()->once()->andReturn([]);
$orderServiceMock->shouldReceive('getOrderService')->atLeast()->once()->andReturn(null);
$di = container();
$di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
$service->setDi($di);
expect(fn (): bool => $service->action_activate($clientOrderModel))
expect(fn () => $service->action_activate($clientOrderModel))
->toThrow(FOSSBilling\Exception::class, 'Could not activate order. Service was not created');
});
test('actionDelete', function (): void {
$service = new Box\Mod\Servicelicense\Service();
test('action delete', function (): void {
$service = new Service();
$clientOrderModel = new Model_ClientOrder();
$clientOrderModel->loadBean(new Tests\Helpers\DummyBean());
$serviceLicenseModel = new Model_ServiceLicense();
$serviceLicenseModel->loadBean(new Tests\Helpers\DummyBean());
$orderServiceMock = Mockery::mock(Box\Mod\Order\Service::class);
$orderServiceMock->shouldReceive('getOrderService')
->atLeast()
->once()
->andReturn($serviceLicenseModel);
$orderServiceMock = Mockery::mock(OrderService::class);
$orderServiceMock->shouldReceive('getOrderService')->atLeast()->once()->andReturn($serviceLicenseModel);
$dbMock = Mockery::mock('\Box_Database');
$dbMock = Mockery::mock(Box_Database::class);
$dbMock->shouldReceive('trash')->atLeast()->once();
$di = container();
@@ -269,19 +222,19 @@ test('actionDelete', function (): void {
});
test('reset', function (): void {
$service = new Box\Mod\Servicelicense\Service();
$service = new Service();
$serviceLicenseModel = new Model_ServiceLicense();
$serviceLicenseModel->loadBean(new Tests\Helpers\DummyBean());
$eventMock = Mockery::mock('\Box_EventManager');
$eventMock = Mockery::mock(Box_EventManager::class);
$eventMock->shouldReceive('fire')->atLeast()->once();
$dbMock = Mockery::mock('\Box_Database');
$dbMock = Mockery::mock(Box_Database::class);
$dbMock->shouldReceive('store')->atLeast()->once();
$di = container();
$di['db'] = $dbMock;
$di['logger'] = new Tests\Helpers\TestLogger();
$di['logger'] = new Box_Log();
$di['events_manager'] = $eventMock;
$service->setDi($di);
@@ -289,8 +242,8 @@ test('reset', function (): void {
expect($result)->toBeTrue();
});
test('isLicenseActive', function (): void {
$service = new Box\Mod\Servicelicense\Service();
test('is license active', function (): void {
$service = new Service();
$clientOrderModel = new Model_ClientOrder();
$clientOrderModel->loadBean(new Tests\Helpers\DummyBean());
$clientOrderModel->status = Model_ClientOrder::STATUS_ACTIVE;
@@ -298,11 +251,8 @@ test('isLicenseActive', function (): void {
$serviceLicenseModel = new Model_ServiceLicense();
$serviceLicenseModel->loadBean(new Tests\Helpers\DummyBean());
$orderServiceMock = Mockery::mock(Box\Mod\Order\Service::class);
$orderServiceMock->shouldReceive('getServiceOrder')
->atLeast()
->once()
->andReturn($clientOrderModel);
$orderServiceMock = Mockery::mock(OrderService::class);
$orderServiceMock->shouldReceive('getServiceOrder')->atLeast()->once()->andReturn($clientOrderModel);
$di = container();
$di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
@@ -312,16 +262,13 @@ test('isLicenseActive', function (): void {
expect($result)->toBeTrue();
});
test('isLicenseNotActive', function (): void {
$service = new Box\Mod\Servicelicense\Service();
test('is license not active', function (): void {
$service = new Service();
$serviceLicenseModel = new Model_ServiceLicense();
$serviceLicenseModel->loadBean(new Tests\Helpers\DummyBean());
$orderServiceMock = Mockery::mock(Box\Mod\Order\Service::class);
$orderServiceMock->shouldReceive('getServiceOrder')
->atLeast()
->once()
->andReturn(null);
$orderServiceMock = Mockery::mock(OrderService::class);
$orderServiceMock->shouldReceive('getServiceOrder')->atLeast()->once()->andReturn(null);
$di = container();
$di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
@@ -331,14 +278,14 @@ test('isLicenseNotActive', function (): void {
expect($result)->toBeFalse();
});
test('isValidIp', function (): void {
$service = new Box\Mod\Servicelicense\Service();
test('is valid ip', function (): void {
$service = new Service();
$serviceLicenseModel = new Model_ServiceLicense();
$serviceLicenseModel->loadBean(new Tests\Helpers\DummyBean());
$serviceLicenseModel->ips = '{}';
$value = '1.1.1.1';
$dbMock = Mockery::mock('\Box_Database');
$dbMock = Mockery::mock(Box_Database::class);
$dbMock->shouldReceive('store')->atLeast()->once();
$di = container();
@@ -350,14 +297,14 @@ test('isValidIp', function (): void {
expect($result)->toBeTrue();
});
test('isValidIp test 2', function (): void {
$service = new Box\Mod\Servicelicense\Service();
test('is valid ip test2', function (): void {
$service = new Service();
$serviceLicenseModel = new Model_ServiceLicense();
$serviceLicenseModel->loadBean(new Tests\Helpers\DummyBean());
$serviceLicenseModel->ips = '["2.2.2.2"]';
$value = '1.1.1.1';
$dbMock = Mockery::mock('\Box_Database');
$dbMock = Mockery::mock(Box_Database::class);
$dbMock->shouldReceive('store')->atLeast()->once();
$di = container();
@@ -369,8 +316,8 @@ test('isValidIp test 2', function (): void {
expect($result)->toBeTrue();
});
test('isValidIp test 3', function (): void {
$service = new Box\Mod\Servicelicense\Service();
test('is valid ip test3', function (): void {
$service = new Service();
$serviceLicenseModel = new Model_ServiceLicense();
$serviceLicenseModel->loadBean(new Tests\Helpers\DummyBean());
$serviceLicenseModel->ips = '["2.2.2.2"]';
@@ -381,14 +328,14 @@ test('isValidIp test 3', function (): void {
expect($result)->toBeFalse();
});
test('isValidVersion', function (): void {
$service = new Box\Mod\Servicelicense\Service();
test('is valid version', function (): void {
$service = new Service();
$serviceLicenseModel = new Model_ServiceLicense();
$serviceLicenseModel->loadBean(new Tests\Helpers\DummyBean());
$serviceLicenseModel->versions = '{}';
$value = '1.0';
$dbMock = Mockery::mock('\Box_Database');
$dbMock = Mockery::mock(Box_Database::class);
$dbMock->shouldReceive('store')->atLeast()->once();
$di = container();
@@ -400,14 +347,14 @@ test('isValidVersion', function (): void {
expect($result)->toBeTrue();
});
test('isValidVersion test 2', function (): void {
$service = new Box\Mod\Servicelicense\Service();
test('is valid version test2', function (): void {
$service = new Service();
$serviceLicenseModel = new Model_ServiceLicense();
$serviceLicenseModel->loadBean(new Tests\Helpers\DummyBean());
$serviceLicenseModel->versions = '["2.0"]';
$value = '1.0';
$dbMock = Mockery::mock('\Box_Database');
$dbMock = Mockery::mock(Box_Database::class);
$dbMock->shouldReceive('store')->atLeast()->once();
$di = container();
@@ -419,8 +366,8 @@ test('isValidVersion test 2', function (): void {
expect($result)->toBeTrue();
});
test('isValidVersion test 3', function (): void {
$service = new Box\Mod\Servicelicense\Service();
test('is valid version test3', function (): void {
$service = new Service();
$serviceLicenseModel = new Model_ServiceLicense();
$serviceLicenseModel->loadBean(new Tests\Helpers\DummyBean());
$serviceLicenseModel->versions = '["2.0"]';
@@ -431,14 +378,14 @@ test('isValidVersion test 3', function (): void {
expect($result)->toBeFalse();
});
test('isValidPath', function (): void {
$service = new Box\Mod\Servicelicense\Service();
test('is valid path', function (): void {
$service = new Service();
$serviceLicenseModel = new Model_ServiceLicense();
$serviceLicenseModel->loadBean(new Tests\Helpers\DummyBean());
$serviceLicenseModel->paths = '{}';
$value = '/var';
$dbMock = Mockery::mock('\Box_Database');
$dbMock = Mockery::mock(Box_Database::class);
$dbMock->shouldReceive('store')->atLeast()->once();
$di = container();
@@ -450,14 +397,14 @@ test('isValidPath', function (): void {
expect($result)->toBeTrue();
});
test('isValidPath test 2', function (): void {
$service = new Box\Mod\Servicelicense\Service();
test('is valid path test2', function (): void {
$service = new Service();
$serviceLicenseModel = new Model_ServiceLicense();
$serviceLicenseModel->loadBean(new Tests\Helpers\DummyBean());
$serviceLicenseModel->paths = '["/"]';
$value = '/var';
$dbMock = Mockery::mock('\Box_Database');
$dbMock = Mockery::mock(Box_Database::class);
$dbMock->shouldReceive('store')->atLeast()->once();
$di = container();
@@ -469,8 +416,8 @@ test('isValidPath test 2', function (): void {
expect($result)->toBeTrue();
});
test('isValidPath test 3', function (): void {
$service = new Box\Mod\Servicelicense\Service();
test('is valid path test3', function (): void {
$service = new Service();
$serviceLicenseModel = new Model_ServiceLicense();
$serviceLicenseModel->loadBean(new Tests\Helpers\DummyBean());
$serviceLicenseModel->paths = '["/"]';
@@ -481,14 +428,14 @@ test('isValidPath test 3', function (): void {
expect($result)->toBeFalse();
});
test('isValidHost', function (): void {
$service = new Box\Mod\Servicelicense\Service();
test('is valid host', function (): void {
$service = new Service();
$serviceLicenseModel = new Model_ServiceLicense();
$serviceLicenseModel->loadBean(new Tests\Helpers\DummyBean());
$serviceLicenseModel->hosts = '{}';
$value = 'site.com';
$dbMock = Mockery::mock('\Box_Database');
$dbMock = Mockery::mock(Box_Database::class);
$dbMock->shouldReceive('store')->atLeast()->once();
$di = container();
@@ -500,14 +447,14 @@ test('isValidHost', function (): void {
expect($result)->toBeTrue();
});
test('isValidHost test 2', function (): void {
$service = new Box\Mod\Servicelicense\Service();
test('is valid host test2', function (): void {
$service = new Service();
$serviceLicenseModel = new Model_ServiceLicense();
$serviceLicenseModel->loadBean(new Tests\Helpers\DummyBean());
$serviceLicenseModel->hosts = '["fossbilling.org"]';
$value = 'site.com';
$dbMock = Mockery::mock('\Box_Database');
$dbMock = Mockery::mock(Box_Database::class);
$dbMock->shouldReceive('store')->atLeast()->once();
$di = container();
@@ -519,8 +466,8 @@ test('isValidHost test 2', function (): void {
expect($result)->toBeTrue();
});
test('isValidHost test 3', function (): void {
$service = new Box\Mod\Servicelicense\Service();
test('is valid host test3', function (): void {
$service = new Service();
$serviceLicenseModel = new Model_ServiceLicense();
$serviceLicenseModel->loadBean(new Tests\Helpers\DummyBean());
$serviceLicenseModel->hosts = '["fossbilling.org"]';
@@ -531,8 +478,8 @@ test('isValidHost test 3', function (): void {
expect($result)->toBeFalse();
});
test('getAdditionalParams', function (): void {
$service = new Box\Mod\Servicelicense\Service();
test('get additional params', function (): void {
$service = new Service();
$serviceLicenseModel = new Model_ServiceLicense();
$serviceLicenseModel->loadBean(new Tests\Helpers\DummyBean());
$serviceLicenseModel->plugin = 'Simple';
@@ -541,8 +488,8 @@ test('getAdditionalParams', function (): void {
expect($result)->toBeArray();
});
test('getOwnerName', function (): void {
$service = new Box\Mod\Servicelicense\Service();
test('get owner name', function (): void {
$service = new Service();
$clientModel = new Model_Client();
$clientModel->loadBean(new Tests\Helpers\DummyBean());
$clientModel->first_name = 'John';
@@ -553,11 +500,8 @@ test('getOwnerName', function (): void {
$expected = $clientModel->first_name . ' ' . $clientModel->last_name;
$dbMock = Mockery::mock('\Box_Database');
$dbMock->shouldReceive('load')
->atLeast()
->once()
->andReturn($clientModel);
$dbMock = Mockery::mock(Box_Database::class);
$dbMock->shouldReceive('load')->atLeast()->once()->andReturn($clientModel);
$di = container();
$di['db'] = $dbMock;
@@ -566,11 +510,11 @@ test('getOwnerName', function (): void {
$result = $service->getOwnerName($serviceLicenseModel);
expect($result)->toBeString();
expect($result)->toBe($expected);
expect($result)->toEqual($expected);
});
test('getExpirationDate', function (): void {
$service = new Box\Mod\Servicelicense\Service();
test('get expiration date', function (): void {
$service = new Service();
$expected = '2004-02-12 15:19:21';
$clientOrderModel = new Model_ClientOrder();
$clientOrderModel->loadBean(new Tests\Helpers\DummyBean());
@@ -579,11 +523,8 @@ test('getExpirationDate', function (): void {
$serviceLicenseModel = new Model_ServiceLicense();
$serviceLicenseModel->loadBean(new Tests\Helpers\DummyBean());
$orderServiceMock = Mockery::mock(Box\Mod\Order\Service::class);
$orderServiceMock->shouldReceive('getServiceOrder')
->atLeast()
->once()
->andReturn($clientOrderModel);
$orderServiceMock = Mockery::mock(OrderService::class);
$orderServiceMock->shouldReceive('getServiceOrder')->atLeast()->once()->andReturn($clientOrderModel);
$di = container();
$di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
@@ -592,11 +533,11 @@ test('getExpirationDate', function (): void {
$result = $service->getExpirationDate($serviceLicenseModel);
expect($result)->toBeString();
expect($result)->toBe($expected);
expect($result)->toEqual($expected);
});
test('toApiArray', function (): void {
$service = new Box\Mod\Servicelicense\Service();
test('to api array', function (): void {
$service = new Service();
$serviceLicenseModel = new Model_ServiceLicense();
$serviceLicenseModel->loadBean(new Tests\Helpers\DummyBean());
@@ -616,25 +557,25 @@ test('toApiArray', function (): void {
$result = $service->toApiArray($serviceLicenseModel, false, new Model_Admin());
expect($result)->toBeArray();
expect(count(array_diff(array_keys($expected), array_keys($result))) == 0)->toBeTrue('Missing array key values.');
expect(count(array_diff(array_keys($expected), array_keys($result))))->toBe(0);
});
test('update', function (): void {
$service = new Box\Mod\Servicelicense\Service();
$service = new Service();
$data = [
'license_key' => '123456Licence',
'validate_ip' => '1.1.1.1',
'validate_host' => 'fossbilling.org',
'validate_version' => '1.0',
'validate_path' => '/usr',
'ips' => '2.2.2.2\n',
'ips' => "2.2.2.2\n",
'pinged_at' => '',
'plugin' => 'Simple',
];
$serviceLicenseModel = new Model_ServiceLicense();
$serviceLicenseModel->loadBean(new Tests\Helpers\DummyBean());
$dbMock = Mockery::mock('\Box_Database');
$dbMock = Mockery::mock(Box_Database::class);
$dbMock->shouldReceive('store')->atLeast()->once();
$di = container();
@@ -646,21 +587,31 @@ test('update', function (): void {
expect($result)->toBeTrue();
});
test('checkLicenseDetails with format eq 2', function (): void {
$service = new Box\Mod\Servicelicense\Service();
test('check license details format eq 2', function (): void {
$service = new Service();
$setChannelCalled = 0;
$loggerMock = new class($setChannelCalled) extends Box_Log {
public function __construct(public int &$setChannelCalled)
{
}
public function setChannel(string $channel): static
{
++$this->setChannelCalled;
return $this;
}
};
$data = [
'format' => 2,
];
$licenseServerMock = Mockery::mock(Box\Mod\Servicelicense\Server::class);
$licenseServerMock->shouldReceive('process')
->atLeast()
->once()
->andReturn([]);
$licenseServerMock = Mockery::mock(Server::class);
$licenseServerMock->shouldReceive('process')->atLeast()->once()->andReturn([]);
$di = container();
$di['logger'] = new Tests\Helpers\TestLogger();
$di['logger'] = $loggerMock;
$di['license_server'] = $licenseServerMock;
$service->setDi($di);
@@ -669,25 +620,37 @@ test('checkLicenseDetails with format eq 2', function (): void {
expect($result)->toBeArray();
expect($result)->toHaveKey('error');
expect($result)->toHaveKey('error_code');
expect($setChannelCalled)->toBeGreaterThanOrEqual(1);
});
test('checkLicenseDetails', function (): void {
$service = new Box\Mod\Servicelicense\Service();
test('check license details', function (): void {
$service = new Service();
$setChannelCalled = 0;
$loggerMock = new class($setChannelCalled) extends Box_Log {
public function __construct(public int &$setChannelCalled)
{
}
public function setChannel(string $channel): static
{
++$this->setChannelCalled;
return $this;
}
};
$data = [];
$licenseServerMock = Mockery::mock(Box\Mod\Servicelicense\Server::class);
$licenseServerMock->shouldReceive('process')
->atLeast()
->once()
->andReturn([]);
$licenseServerMock = Mockery::mock(Server::class);
$licenseServerMock->shouldReceive('process')->atLeast()->once()->andReturn([]);
$di = container();
$di['logger'] = new Tests\Helpers\TestLogger();
$di['logger'] = $loggerMock;
$di['license_server'] = $licenseServerMock;
$service->setDi($di);
$result = $service->checkLicenseDetails($data);
expect($result)->toBeArray();
expect($setChannelCalled)->toBeGreaterThanOrEqual(1);
});
@@ -1021,9 +1021,6 @@ test('create creates new admin account', function (): void {
$adminModel = new Model_Admin();
$adminModel->loadBean(new Tests\Helpers\DummyBean());
$systemServiceMock = Mockery::mock(Box\Mod\System\Service::class);
$systemServiceMock->shouldReceive('checkLimits')->byDefault();
$eventsMock = Mockery::mock('\Box_EventManager');
$eventsMock->shouldReceive('fire')->atLeast()->once();
@@ -1047,7 +1044,6 @@ test('create creates new admin account', function (): void {
$di['events_manager'] = $eventsMock;
$di['logger'] = $logStub;
$di['db'] = $dbMock;
$di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $systemServiceMock);
$di['password'] = $passwordMock;
@@ -1072,9 +1068,6 @@ test('create throws exception for duplicate email', function (): void {
$adminModel = new Model_Admin();
$adminModel->loadBean(new Tests\Helpers\DummyBean());
$systemServiceMock = Mockery::mock(Box\Mod\System\Service::class);
$systemServiceMock->shouldReceive('checkLimits')->byDefault();
$eventsMock = Mockery::mock('\Box_EventManager');
$eventsMock->shouldReceive('fire')->atLeast()->once();
@@ -1098,7 +1091,6 @@ test('create throws exception for duplicate email', function (): void {
$di['events_manager'] = $eventsMock;
$di['logger'] = $logStub;
$di['db'] = $dbMock;
$di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $systemServiceMock);
$di['password'] = $passwordMock;
@@ -1155,9 +1147,6 @@ test('createGroup creates new admin group', function (): void {
$adminGroupModel->loadBean(new Tests\Helpers\DummyBean());
$newGroupId = 1;
$systemServiceMock = Mockery::mock(Box\Mod\System\Service::class);
$systemServiceMock->shouldReceive('checkLimits')->byDefault();
$dbMock = Mockery::mock('\Box_Database');
$dbMock->shouldReceive('dispense')->atLeast()->once()
->andReturn($adminGroupModel);
@@ -1171,7 +1160,6 @@ test('createGroup creates new admin group', function (): void {
$di = container();
$di['db'] = $dbMock;
$di['logger'] = new Tests\Helpers\TestLogger();
$di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $systemServiceMock);
$serviceMock->setDi($di);
+2 -10
View File
@@ -1154,16 +1154,8 @@ class Service implements \FOSSBilling\InjectionAwareInterface
throw new \FOSSBilling\Exception('rel_new_value must be a valid positive integer product ID, received: :value', [':value' => $rel_new_value]);
}
$product = $this->di['db']->getExistingModelById('Product', $order->product_id);
$allowedUpgrades = json_decode($product->upgrades ?? '', true) ?? [];
$allowedUpgrades = array_map(static fn ($upgradeId): string => (string) $upgradeId, $allowedUpgrades);
$requestedUpgradeId = (string) $rel_new_value;
if (!in_array($requestedUpgradeId, $allowedUpgrades, true)) {
$upgrade = $this->di['db']->getExistingModelById('Product', $rel_new_value);
throw new InformationException('Sorry, but ":product" is not allowed to be upgraded to ":upgrade"', [':product' => $product->title, ':upgrade' => $upgrade->title ?? 'unknown']);
}
$productService = $this->di['mod_service']('product');
$productService->assertUpgradeAllowedByIds((int) $order->product_id, (int) $rel_new_value);
}
// check if support ticket with same uncompleted task already exists
@@ -1166,13 +1166,7 @@ test('canned create', function (): void {
->atLeast()->once()
->andReturn($randId);
$systemServiceMock = Mockery::mock(Box\Mod\System\Service::class);
$systemServiceMock->shouldReceive('checkLimits')
->byDefault()
->andReturn(null);
$di = container();
$di['mod_service'] = $di->protect(fn () => $systemServiceMock);
$di['db'] = $dbMock;
$di['logger'] = new Tests\Helpers\TestLogger();
$service->setDi($di);
@@ -1847,16 +1841,10 @@ test('kb create category', function (): void {
->atLeast()->once()
->andReturn('article-slug');
$systemServiceMock = Mockery::mock(Box\Mod\System\Service::class);
$systemServiceMock->shouldReceive('checkLimits')
->byDefault()
->andReturn(true);
$di = container();
$di['db'] = $dbMock;
$di['tools'] = $toolsMock;
$di['logger'] = new Tests\Helpers\TestLogger();
$di['mod_service'] = $di->protect(fn () => $systemServiceMock);
$service->setDi($di);
$result = $service->kbCreateCategory('Title', 'Description');