diff --git a/cspell.json b/cspell.json index bf7a732c1..0fb5699dc 100644 --- a/cspell.json +++ b/cspell.json @@ -47,7 +47,13 @@ "resends", "Parenthesise", "yagiz", - "overpayments" + "overpayments", + "Litepicker", + "servicecustomtest", + "customtest", + "Customtest", + "mysite", + "myhost" ], "ignoreWords": [ diff --git a/frontend/core/api.js b/frontend/core/api.js index 8052aa478..827c882d6 100644 --- a/frontend/core/api.js +++ b/frontend/core/api.js @@ -464,7 +464,7 @@ const API = { let errorObj; if (error.name === 'AbortError') { errorObj = { - message: timeoutMessage || 'Request timed out after ' + (timeoutMs / 1000) + ' seconds', + message: timeoutMessage || `Request timed out after ${timeoutMs / 1000} seconds`, code: 'timeout_error' }; } else if (error.name === 'TypeError' && error.message.includes('NetworkError')) { diff --git a/phpstan.neon b/phpstan.neon index 26ff14da5..f79bbe92c 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -17,7 +17,6 @@ parameters: - src/library/Model/Admin.php - src/library/Model/Client.php - src/library/Model/ServiceLicense.php - - src/library/Model/Product.php - src/library/Server/Manager/Custom.php - src/library/Server/Manager/Whm.php - src/data/cache (?) diff --git a/src/install/sql/content.sql b/src/install/sql/content.sql index 3d55e0ebf..b61302094 100644 --- a/src/install/sql/content.sql +++ b/src/install/sql/content.sql @@ -303,7 +303,7 @@ LOCK TABLES `setting` WRITE; INSERT INTO `setting` (`id`, `param`, `value`, `public`, `category`, `hash`, `created_at`, `updated_at`) VALUES - (1,'last_patch','71',0,NULL,NULL,'2024-12-30 12:00:00','2024-12-30 12:00:00'), + (1,'last_patch','72',0,NULL,NULL,'2024-12-30 12:00:00','2024-12-30 12:00:00'), (2,'company_name','Company Name',0,NULL,NULL,'2022-12-01 12:00:00','2022-12-01 12:00:00'), (3,'company_email','support@yourcompany.com',0,NULL,NULL,'2022-12-01 12:00:00','2022-12-01 12:00:00'), (4,'company_signature','FOSSBilling.org - Client Management, Invoicing and Support Software',0,NULL,NULL,'2022-12-01 12:00:00','2022-12-01 12:00:00'), diff --git a/src/install/sql/structure.sql b/src/install/sql/structure.sql index 7424a3cde..2888c0a3c 100644 --- a/src/install/sql/structure.sql +++ b/src/install/sql/structure.sql @@ -857,6 +857,37 @@ CREATE TABLE `promo` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `promo_redemption` +-- + +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `promo_redemption` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT, + `promo_id` bigint(20) DEFAULT NULL, + `client_id` bigint(20) DEFAULT NULL, + `client_order_id` bigint(20) DEFAULT NULL, + `invoice_id` bigint(20) DEFAULT NULL, + `phase` varchar(30) NOT NULL DEFAULT 'checkout', + `status` varchar(30) NOT NULL DEFAULT 'reserved', + `discount_amount` decimal(18,2) DEFAULT NULL, + `currency` varchar(20) DEFAULT NULL, + `committed_at` datetime DEFAULT NULL, + `released_at` datetime DEFAULT NULL, + `release_reason` varchar(100) DEFAULT NULL, + `created_at` datetime DEFAULT NULL, + `updated_at` datetime DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `promo_id_idx` (`promo_id`), + KEY `client_id_idx` (`client_id`), + KEY `client_order_id_idx` (`client_order_id`), + KEY `invoice_id_idx` (`invoice_id`), + KEY `phase_idx` (`phase`), + KEY `status_idx` (`status`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `service_custom` -- diff --git a/src/library/FOSSBilling/UpdatePatcher.php b/src/library/FOSSBilling/UpdatePatcher.php index ecd42c290..1b5ce7eff 100644 --- a/src/library/FOSSBilling/UpdatePatcher.php +++ b/src/library/FOSSBilling/UpdatePatcher.php @@ -458,6 +458,7 @@ class UpdatePatcher implements InjectionAwareInterface 69 => 'patch69', 70 => 'patch70', 71 => 'patch71', + 72 => 'patch72', ]; ksort($patches, SORT_NATURAL); @@ -1758,4 +1759,158 @@ class UpdatePatcher implements InjectionAwareInterface ]); } } + + private function patch72(): void + { + $this->executeFileActions([ + Path::join(PATH_LIBRARY, 'Model', 'Product.php') => 'unlink', + Path::join(PATH_LIBRARY, 'Model', 'ProductCategory.php') => 'unlink', + Path::join(PATH_LIBRARY, 'Model', 'ProductCustom.php') => 'unlink', + Path::join(PATH_LIBRARY, 'Model', 'ProductDomain.php') => 'unlink', + Path::join(PATH_LIBRARY, 'Model', 'ProductDomainTable.php') => 'unlink', + Path::join(PATH_LIBRARY, 'Model', 'ProductDownloadable.php') => 'unlink', + Path::join(PATH_LIBRARY, 'Model', 'ProductHosting.php') => 'unlink', + Path::join(PATH_LIBRARY, 'Model', 'ProductLicense.php') => 'unlink', + Path::join(PATH_LIBRARY, 'Model', 'ProductPayment.php') => 'unlink', + Path::join(PATH_LIBRARY, 'Model', 'ProductTable.php') => 'unlink', + Path::join(PATH_LIBRARY, 'Model', 'Promo.php') => 'unlink', + Path::join(PATH_CACHE, 'classMap.php') => 'unlink', + Path::join(PATH_CACHE, 'fallbackClassMap.php') => 'unlink', + ]); + + $schemaManager = $this->di['dbal']->createSchemaManager(); + if (!$schemaManager->tablesExist(['promo_redemption'])) { + $this->executeSql( + "CREATE TABLE `promo_redemption` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT, + `promo_id` bigint(20) DEFAULT NULL, + `client_id` bigint(20) DEFAULT NULL, + `client_order_id` bigint(20) DEFAULT NULL, + `invoice_id` bigint(20) DEFAULT NULL, + `phase` varchar(30) NOT NULL DEFAULT 'checkout', + `status` varchar(30) NOT NULL DEFAULT 'reserved', + `discount_amount` decimal(18,2) DEFAULT NULL, + `currency` varchar(20) DEFAULT NULL, + `committed_at` datetime DEFAULT NULL, + `released_at` datetime DEFAULT NULL, + `release_reason` varchar(100) DEFAULT NULL, + `created_at` datetime DEFAULT NULL, + `updated_at` datetime DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `promo_id_idx` (`promo_id`), + KEY `client_id_idx` (`client_id`), + KEY `client_order_id_idx` (`client_order_id`), + KEY `invoice_id_idx` (`invoice_id`), + KEY `phase_idx` (`phase`), + KEY `status_idx` (`status`) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8;" + ); + } + + $table = $schemaManager->introspectTable('promo_redemption'); + $columns = []; + + if (!$table->hasColumn('status')) { + $columns[] = "ADD COLUMN `status` varchar(30) NOT NULL DEFAULT 'reserved' AFTER `phase`"; + } + + if (!$table->hasColumn('committed_at')) { + $columns[] = 'ADD COLUMN `committed_at` datetime DEFAULT NULL AFTER `currency`'; + } + + if (!$table->hasColumn('released_at')) { + $columns[] = 'ADD COLUMN `released_at` datetime DEFAULT NULL AFTER `committed_at`'; + } + + if (!$table->hasColumn('release_reason')) { + $columns[] = 'ADD COLUMN `release_reason` varchar(100) DEFAULT NULL AFTER `released_at`'; + } + + if ($columns !== []) { + $this->executeSql('ALTER TABLE promo_redemption ' . implode(', ', $columns)); + } + + $table = $schemaManager->introspectTable('promo_redemption'); + $expectedIndexes = [ + 'promo_id_idx' => 'promo_id', + 'client_id_idx' => 'client_id', + 'client_order_id_idx' => 'client_order_id', + 'invoice_id_idx' => 'invoice_id', + 'phase_idx' => 'phase', + 'status_idx' => 'status', + ]; + + foreach ($expectedIndexes as $indexName => $columnName) { + if (!$table->hasIndex($indexName)) { + $this->executeSql(sprintf( + 'ALTER TABLE promo_redemption ADD INDEX `%s` (`%s`)', + $indexName, + $columnName + )); + } + } + + $existingRedemptions = (int) $this->di['dbal']->executeQuery('SELECT COUNT(id) FROM promo_redemption')->fetchOne(); + if ($existingRedemptions === 0) { + $orders = $this->di['dbal']->executeQuery( + 'SELECT id, promo_id, client_id, promo_used, discount, currency, created_at, updated_at + FROM client_order + WHERE promo_id IS NOT NULL' + )->fetchAllAssociative(); + + foreach ($orders as $order) { + $checkoutCreatedAt = $order['created_at'] ?? date('Y-m-d H:i:s'); + $renewalCreatedAt = $order['updated_at'] ?: $checkoutCreatedAt; + $discountAmount = $order['discount'] !== null ? (float) $order['discount'] : null; + + $this->di['dbal']->insert('promo_redemption', [ + 'promo_id' => $order['promo_id'], + 'client_id' => $order['client_id'], + 'client_order_id' => $order['id'], + 'invoice_id' => null, + 'phase' => 'checkout', + 'status' => 'committed', + 'discount_amount' => $discountAmount, + 'currency' => $order['currency'], + 'committed_at' => $checkoutCreatedAt, + 'released_at' => null, + 'release_reason' => null, + 'created_at' => $checkoutCreatedAt, + 'updated_at' => $checkoutCreatedAt, + ]); + + $renewalCount = max(0, ((int) ($order['promo_used'] ?? 1)) - 1); + for ($i = 0; $i < $renewalCount; ++$i) { + $this->di['dbal']->insert('promo_redemption', [ + 'promo_id' => $order['promo_id'], + 'client_id' => $order['client_id'], + 'client_order_id' => $order['id'], + 'invoice_id' => null, + 'phase' => 'renewal', + 'status' => 'committed', + 'discount_amount' => $discountAmount, + 'currency' => $order['currency'], + 'committed_at' => $renewalCreatedAt, + 'released_at' => null, + 'release_reason' => null, + 'created_at' => $renewalCreatedAt, + 'updated_at' => $renewalCreatedAt, + ]); + } + } + } + + // Normalize rows written by a previous partial migration run that pre-dated the + // status column; those rows have a NULL/empty status. Legitimate 'reserved' + // rows created by concurrent checkouts are left untouched so the payment flow + // can commit or release them normally. + $this->executeSql(" + UPDATE promo_redemption + SET + status = 'committed', + committed_at = COALESCE(committed_at, created_at), + release_reason = NULL + WHERE status IS NULL OR status = '' + "); + } } diff --git a/src/library/Model/Product.php b/src/library/Model/Product.php deleted file mode 100644 index 9f6c3270e..000000000 --- a/src/library/Model/Product.php +++ /dev/null @@ -1,57 +0,0 @@ -di = $di; - } - - public function getDi(): ?Pimple\Container - { - return $this->di; - } - - public function getTable(): object - { - $tableName = 'Model_Product' . ucfirst($this->type ?? '') . 'Table'; - if (!class_exists($tableName)) { - $tableName = 'Model_ProductTable'; - } - $productTable = new $tableName(); - $productTable->setDi($this->di); - - return $productTable; - } - - public function getService() - { - return $this->di['mod_service']('service' . $this->type); - } -} diff --git a/src/library/Model/ProductCategory.php b/src/library/Model/ProductCategory.php deleted file mode 100644 index 4814ff5b6..000000000 --- a/src/library/Model/ProductCategory.php +++ /dev/null @@ -1,14 +0,0 @@ -di['period']($config['period']); - - return max(1, $period->getQty()); - } - - return max(1, (int) ($config['register_years'] ?? $config['quantity'] ?? 1)); - } - - private function getTldModel(array $config): Model_Tld - { - $rtable = $this->di['mod_service']('servicedomain', 'Tld'); - $tld = ''; - - if (!isset($config['action'])) { - throw new FOSSBilling\Exception('Could not determine domain price. Domain action is missing', null, 498); - } - - if ($config['action'] == 'register') { - $tld = $config['register_tld']; - } - - if ($config['action'] == 'transfer') { - $tld = $config['transfer_tld']; - } - - $tld = $rtable->findOneByTld($tld); - if (!$tld instanceof Model_Tld) { - throw new FOSSBilling\Exception('Unknown TLD. Could not determine registration price'); - } - - return $tld; - } - - private function getRegistrationTotal(Model_Tld $tld, int $years): float - { - if ($years <= 0) { - return 0.0; - } - - if ($years <= 1) { - return (float) $tld->price_registration; - } - - return (float) $tld->price_registration + (($years - 1) * (float) $tld->price_renew); - } - - protected function getStartingFromPrice(Model_Product $model) - { - $p = []; - $prices = $this->getPricingArray($model); - foreach ($prices as $tld) { - $p[] = $tld['price_registration']; - } - - return empty($p) ? 0 : min($p); - } - - public function isRecurrentPricing(Model_Product $model): bool - { - return false; - } - - /** - * Determine discount for items in cart (Hosting and related domain discount). - * - * @param array $items Array of cart products - * @param Model_Product $product current product in iteration - * @param array $config configurations specified in product config - * - * @return number discount - */ - public function getRelatedDiscount(array $items, Model_Product $product, array $config) - { - /**For each cart product, - * Compare it with other items in the cart - * If a domain has related hosting package, determine discount configured. - */ - foreach ($items as $addon) { - if ( - $this->isActionNameSet($addon, 'register') - && $this->_isFreeDomainSet($addon) - && $this->registerDomainMatch($addon, $config) - ) { - if ($this->_hasFreePeriod($addon)) { - $factor = $this->discountFactor($addon, $config['period']); - $tld = $this->getTldModel($config); - - return $this->getRegistrationTotal($tld, $factor); - } - - return 0; - } - - if ( - $this->isActionNameSet($addon, 'transfer') - && $this->isFreeTransferSet($addon) - && $this->transferDomainMatch($addon, $config) - ) { - return $this->getProductPrice($product, $config); - } - } - - return 0; - } - - private function _hasFreePeriod($addon): bool - { - $free_domain_periods = $addon['config']['free_domain_periods'] ?? []; - $addon_period = $addon['config']['period']; - if (in_array($addon_period, $free_domain_periods)) { - return true; - } - - return false; - } - - /** - * Determine the number of years configured for free domain. - */ - private function discountFactor($addon, $period) - { - $ref_item_period = $this->di['period']($period); - $ref_item_qty = $ref_item_period->getQty(); - - $addon_period = $addon['config']['period']; - $addon_sys_period = $this->di['period']($addon_period); - $addon_qty = $addon_sys_period->getQty(); - - $free_domain_periods = $addon['config']['free_domain_periods'] ?? []; - if (FOSSBilling\Tools::safeCount($free_domain_periods) > 0) { - // if hosting and domain periods are equal, return domain quantity (year) - if ($addon_period == $period) { - if (in_array($addon_period, $free_domain_periods)) { - return $ref_item_qty; - } - } - - if (str_contains((string) $addon_period, 'Y')) { - if (min($ref_item_qty, $addon_qty) == 1) { - return 1; - } - - $free_domain_qtys = []; - foreach ($free_domain_periods as $fp) { - $prd = $this->di['period']($fp); - $qnty = $prd->getQty(); - if ($ref_item_qty - $qnty > 0) { - $free_domain_qtys[] = $qnty; - } - } - - if (count($free_domain_qtys) > 0) { - return min($ref_item_qty, min($free_domain_qtys)); - } - } - } - - return 0; - } - - /** - * @param string $actionName - */ - private function isActionNameSet($item, $actionName): bool - { - return isset($item['config']['domain']['action']) && $item['config']['domain']['action'] == $actionName; - } - - private function _isFreeDomainSet($item): bool - { - $free_domain = $item['config']['free_domain'] ?? false; - - if (!$free_domain) { - return false; - } - - $tld = $item['config']['tld'] ?? null; - $free_tlds = $item['config']['free_tlds'] ?? []; - - // When free_tlds is empty, all TLDs are eligible for a free domain. - if (empty($free_tlds)) { - return true; - } - - // When free_tlds is non-empty, only whitelisted TLDs are eligible. - return $tld !== null && in_array($tld, $free_tlds); - } - - private function registerDomainMatch($item, $config) - { - if (!isset($item['config']['domain']['register_sld'])) { - return false; - } - - return $item['config']['domain']['register_sld'] == $config['register_sld'] && $item['config']['domain']['register_tld'] == $config['register_tld']; - } - - private function transferDomainMatch($item, $config) - { - if (!isset($item['config']['domain']['transfer_sld'])) { - return false; - } - - return $item['config']['domain']['transfer_sld'] == $config['transfer_sld'] && $item['config']['domain']['transfer_tld'] == $config['transfer_tld']; - } - - private function isFreeTransferSet($item): bool - { - return isset($item['config']['free_transfer']) && $item['config']['free_transfer']; - } - - /** - * @return array> - */ - #[Override] - public function getPricingArray(Model_Product $product): array - { - $pricing = []; - - $query = $this->di['dbal']->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'); - - $result = $query->executeQuery(); - $results = $result->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; - } - - /** - * @return array{price: float, quantity: int, setup_price: float} - */ - #[Override] - public function getOrderLineConfig(Model_Product $product, ?array $config = null): array - { - if (!isset($config['action'])) { - throw new FOSSBilling\Exception('Could not determine domain price. Domain action is missing', null, 498); - } - - if ($config['action'] == 'owndomain') { - return [ - 'price' => 0.0, - 'quantity' => 1, - 'setup_price' => 0.0, - ]; - } - - $tld = $this->getTldModel($config); - - if ($config['action'] == 'register') { - return [ - 'price' => $this->getRegistrationTotal($tld, $this->getRegistrationYears($config)), - 'quantity' => 1, - 'setup_price' => 0.0, - ]; - } - - return [ - 'price' => (float) $tld->price_transfer, - 'quantity' => 1, - 'setup_price' => 0.0, - ]; - } - - /** - * Resolved pricing for renewal lines in default currency. - * - * @return array{price: float, quantity: int} - */ - public function getRenewalLineConfig(Model_Product $product, ?array $config = null): array - { - $tld = $this->getTldModel($config ?? []); - - return [ - 'price' => (float) $tld->price_renew, - 'quantity' => $this->getRegistrationYears($config ?? []), - ]; - } - - #[Override] - public function getProductPrice(Model_Product $product, ?array $config = null) - { - if (($config['action'] ?? null) == 'owndomain') { - return 0; - } - - $tld = $this->getTldModel($config ?? []); - - if ($config['action'] == 'register') { - return $tld->price_registration; - } - - if ($config['action'] == 'transfer') { - return $tld->price_transfer; - } - - return 0; - } - - #[Override] - public function getProductSetupPrice(Model_Product $product, ?array $config = null): float - { - return (float) 0; - } - - public function rm(Model_Product $product): never - { - throw new FOSSBilling\Exception('Domain product cannot be removed.'); - } -} diff --git a/src/library/Model/ProductHosting.php b/src/library/Model/ProductHosting.php deleted file mode 100644 index 665459f6d..000000000 --- a/src/library/Model/ProductHosting.php +++ /dev/null @@ -1,14 +0,0 @@ -di = $di; - } - - public function getDi(): ?Pimple\Container - { - return $this->di; - } - - public function getUnit(Model_Product $model) - { - return $model->unit; - } - - private function _getPeriodKey(Box_Period $period): string - { - $code = $period->getCode(); - - try { - return match ($code) { - '1W' => 'w', - '1M' => 'm', - '3M' => 'q', - '6M' => 'b', - '12M' => 'a', - '1Y' => 'a', - '2Y' => 'bia', - '3Y' => 'tria', - }; - } catch (UnhandledMatchError) { - throw new FOSSBilling\Exception('Unknown period selected ' . $code); - } - } - - public function getPricingArray(Model_Product $model) - { - if ($model->product_payment_id) { - $service = $this->di['mod_service']('product'); - $productPayment = $this->di['db']->load('ProductPayment', $model->product_payment_id); - - return $service->toProductPaymentApiArray($productPayment); - } - - throw new FOSSBilling\Exception('Product pricing could not be determined. ' . static::class); - } - - /** - * Resolved pricing for the initial order line in default currency. - * - * @return array{price: float, quantity: int, setup_price: float} - */ - public function getOrderLineConfig(Model_Product $product, ?array $config = null): array - { - $quantity = max(1, (int) ($config['quantity'] ?? 1)); - - return [ - 'price' => (float) $this->getProductPrice($product, $config), - 'quantity' => $quantity, - 'setup_price' => (float) $this->getProductSetupPrice($product, $config), - ]; - } - - /** - * Price for one unit. - * - * @return float - */ - public function getProductSetupPrice(Model_Product $product, ?array $config = null) - { - $pp = $this->di['db']->load('ProductPayment', $product->product_payment_id); - - if ($pp->type == Model_ProductPayment::FREE) { - $price = 0; - } - - if ($pp->type == Model_ProductPayment::ONCE) { - $price = (float) $pp->once_setup_price; - } - - if ($pp->type == Model_ProductPayment::RECURRENT) { - $period = new Box_Period($config['period']); - $key = $this->_getPeriodKey($period); - $price = (float) $pp->{$key . '_setup_price'}; - } - - if (isset($price)) { - return $price; - } - - throw new FOSSBilling\Exception('Unknown period selected for setup price'); - } - - /** - * Price for one unit. - * - * @return float - */ - public function getProductPrice(Model_Product $product, ?array $config = null) - { - $pp = $this->di['db']->load('ProductPayment', $product->product_payment_id); - - if ($pp->type == Model_ProductPayment::FREE) { - $price = 0; - } - - if ($pp->type == Model_ProductPayment::ONCE) { - $price = $pp->once_price; - } - - if ($pp->type == Model_ProductPayment::RECURRENT) { - if (!isset($config['period'])) { - throw new FOSSBilling\Exception('Product :id payment type is recurrent, but period was not selected', [':id' => $product->id]); - } - - $period = new Box_Period($config['period']); - $key = $this->_getPeriodKey($period); - $price = $pp->{$key . '_price'}; - } - - if (isset($price)) { - return $price; - } - - throw new FOSSBilling\Exception('Unknown Period selected for price'); - } -} diff --git a/src/library/Model/Promo.php b/src/library/Model/Promo.php deleted file mode 100644 index a996bad45..000000000 --- a/src/library/Model/Promo.php +++ /dev/null @@ -1,16 +0,0 @@ -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 diff --git a/src/modules/Cart/Service.php b/src/modules/Cart/Service.php index c0bddad4c..c79021c49 100644 --- a/src/modules/Cart/Service.php +++ b/src/modules/Cart/Service.php @@ -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; } } diff --git a/src/modules/Cart/tests/Unit/Api/GuestTest.php b/src/modules/Cart/tests/Unit/Api/GuestTest.php index a4bc9c401..6358306ca 100644 --- a/src/modules/Cart/tests/Unit/Api/GuestTest.php +++ b/src/modules/Cart/tests/Unit/Api/GuestTest.php @@ -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); diff --git a/src/modules/Cart/tests/Unit/DomainPricingTest.php b/src/modules/Cart/tests/Unit/DomainPricingTest.php new file mode 100644 index 000000000..d3390b1c8 --- /dev/null +++ b/src/modules/Cart/tests/Unit/DomainPricingTest.php @@ -0,0 +1,88 @@ +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'); +}); diff --git a/src/modules/Cart/tests/Unit/ServiceTest.php b/src/modules/Cart/tests/Unit/ServiceTest.php index 1b8efc827..ce7478d48 100644 --- a/src/modules/Cart/tests/Unit/ServiceTest.php +++ b/src/modules/Cart/tests/Unit/ServiceTest.php @@ -10,52 +10,80 @@ declare(strict_types=1); -use function Tests\Helpers\container; -use function Tests\Helpers\moduleService; +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\Entity\PromoRedemption; +use Box\Mod\Product\Service as ProductService; +use Symfony\Component\HttpFoundation\Request; -test('dependency injection', function (): void { - $service = new Box\Mod\Cart\Service(); - $service = new Box\Mod\Cart\Service(); +use function Tests\Helpers\container; + +function createProductEntity(?int $id = null, ?string $type = null, ?string $config = null): Product +{ + $product = new Product(); + if ($id !== null) { + $reflection = new ReflectionProperty($product, 'id'); + $reflection->setAccessible(true); + $reflection->setValue($product, $id); + } + if ($type !== null) { + $product->setType($type); + } + if ($config !== null) { + $product->setConfig($config); + } + + return $product; +} + +function createPromoEntity(int $id): Promo +{ + $promo = new Promo(); + $reflection = new ReflectionProperty($promo, 'id'); + $reflection->setAccessible(true); + $reflection->setValue($promo, $id); + + return $promo; +} + +test('gets dependency injection container', function (): void { + $service = new Service(); $di = container(); - $db = Mockery::mock('Box_Database'); + $db = Mockery::mock(Box_Database::class)->shouldIgnoreMissing(); $di['db'] = $db; $service->setDi($di); $result = $service->getDi(); - expect($result)->toEqual($di); }); -test('get search query', function (): void { - $service = new Box\Mod\Cart\Service(); - $service = new Box\Mod\Cart\Service(); +test('gets search query', function (): void { + $service = new Service(); $result = $service->getSearchQuery([]); - expect($result[0])->toBeString(); expect($result[1])->toBeArray(); - expect(strpos((string) $result[0], 'SELECT cart.id FROM cart'))->not->toBeFalse(); + expect(strpos($result[0], 'SELECT cart.id FROM cart'))->not->toBeFalse(); }); -test('get session cart exists', function (): void { - $service = new Box\Mod\Cart\Service(); - $service = new Box\Mod\Cart\Service(); +test('getSessionCart returns existing cart', function (): void { + $service = new Service(); - $sessionId = 'rrcpqo7tkjh14d2vmf0car64k7'; + $session_id = 'rrcpqo7tkjh14d2vmf0car64k7'; $model = new Model_Cart(); $model->loadBean(new Tests\Helpers\DummyBean()); - $model->session_id = $sessionId; + $model->session_id = $session_id; - $dbMock = Mockery::mock('Box_Database'); - $dbMock->shouldReceive('findOne') - ->atLeast()->once() - ->andReturn($model); + $dbMock = Mockery::mock(Box_Database::class); + $dbMock->shouldReceive('findOne')->atLeast()->once()->andReturn($model); - $sessionMock = Mockery::mock(FOSSBilling\Session::class); - $sessionMock->shouldReceive('getId') - ->atLeast()->once() - ->andReturn($sessionId); + $sessionMock = Mockery::mock(FOSSBilling\Session::class)->shouldIgnoreMissing(); + $sessionMock->shouldReceive('getId')->atLeast()->once()->andReturn($session_id); $di = container(); $di['db'] = $dbMock; @@ -64,151 +92,113 @@ test('get session cart exists', function (): void { $result = $service->getSessionCart(); - expect($result)->toBeInstanceOf('Model_Cart'); - expect($result->session_id)->toEqual($sessionId); + expect($result)->toBeInstanceOf(Model_Cart::class); + expect($result->session_id)->toEqual($session_id); }); -dataset('getSessionCartDoesNotExistProvider', fn (): array => [ - [ - 100, - 'atLeastOnce', - 'never', - ], - [ - null, - 'never', - 'atLeastOnce', - ], -]); +test('getSessionCart creates a new cart when one does not exist', function (?int $sessionGetWillReturn, string $getCurrencyByClientIdExpects, string $getDefaultExpects): void { + $service = new Service(); -test('get session cart does not exist', function (?int $sessionGetWillReturn, string $getCurrencyByClientIdExpects, string $getDefaultExpects): void { - $service = new Box\Mod\Cart\Service(); - $service = new Box\Mod\Cart\Service(); - - $currencyModel = Mockery::mock(Box\Mod\Currency\Entity\Currency::class); + $currencyModel = Mockery::mock(Currency::class)->shouldIgnoreMissing(); $currencyId = random_int(0, 1000); - $currencyModel->shouldReceive('getId') - ->byDefault() - ->andReturn($currencyId); + $currencyModel->shouldReceive('getId')->andReturn($currencyId); - $sessionId = 'rrcpqo7tkjh14d2vmf0car64k7'; - $model = null; - $dbMock = Mockery::mock('Box_Database'); - $dbMock->shouldReceive('findOne') - ->atLeast()->once() - ->andReturn($model); + $session_id = 'rrcpqo7tkjh14d2vmf0car64k7'; + $dbMock = Mockery::mock(Box_Database::class); + $dbMock->shouldReceive('findOne')->atLeast()->once()->andReturn(null); $modelCart = new Model_Cart(); $modelCart->loadBean(new Tests\Helpers\DummyBean()); - $dbMock->shouldReceive('dispense') - ->atLeast()->once() - ->andReturn($modelCart); - $dbMock->shouldReceive('store') - ->atLeast()->once() - ->andReturn(1); + $dbMock->shouldReceive('dispense')->atLeast()->once()->andReturn($modelCart); + $dbMock->shouldReceive('store')->atLeast()->once()->andReturn(1); - $sessionMock = Mockery::mock(FOSSBilling\Session::class); - $sessionMock->shouldReceive('getId') - ->atLeast()->once() - ->andReturn($sessionId); - $sessionMock->shouldReceive('get') - ->atLeast()->once() - ->andReturn($sessionGetWillReturn); + $sessionMock = Mockery::mock(FOSSBilling\Session::class)->shouldIgnoreMissing(); + $sessionMock->shouldReceive('getId')->atLeast()->once()->andReturn($session_id); + $sessionMock->shouldReceive('get')->atLeast()->once()->andReturn($sessionGetWillReturn); - $currencyRepositoryMock = Mockery::mock(Box\Mod\Currency\Repository\CurrencyRepository::class)->shouldIgnoreMissing(); + $currencyRepositoryMock = Mockery::mock(CurrencyRepository::class)->makePartial(); if ($sessionGetWillReturn === null) { - $currencyRepositoryMock->shouldReceive('findDefault') - ->atLeast()->once() - ->andReturn($currencyModel); + $currencyRepositoryMock->shouldReceive('findDefault')->atLeast()->once()->andReturn($currencyModel); } else { - $currencyRepositoryMock->shouldReceive('findDefault')->never(); + $currencyRepositoryMock->shouldNotReceive('findDefault'); } - $currencyServiceMock = Mockery::mock(Box\Mod\Currency\Service::class)->makePartial(); + $currencyServiceMock = Mockery::mock(CurrencyService::class)->makePartial(); if ($getCurrencyByClientIdExpects === 'atLeastOnce') { - $currencyServiceMock->shouldReceive('getCurrencyByClientId') - ->atLeast()->once() - ->andReturn($currencyModel); + $currencyServiceMock->shouldReceive('getCurrencyByClientId')->atLeast()->once()->andReturn($currencyModel); } else { - $currencyServiceMock->shouldReceive('getCurrencyByClientId')->never(); + $currencyServiceMock->shouldNotReceive('getCurrencyByClientId'); } - $currencyServiceMock->shouldReceive('getCurrencyRepository') - ->atLeast()->once() - ->andReturn($currencyRepositoryMock); + $currencyServiceMock->shouldReceive('getCurrencyRepository')->atLeast()->once()->andReturn($currencyRepositoryMock); $di = container(); $di['db'] = $dbMock; $di['session'] = $sessionMock; - $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $currencyServiceMock); + $di['mod_service'] = $di->protect(fn () => $currencyServiceMock); $service->setDi($di); $result = $service->getSessionCart(); - expect($result)->toBeInstanceOf('Model_Cart'); - expect($result->session_id)->toEqual($sessionId); + expect($result)->toBeInstanceOf(Model_Cart::class); + expect($result->session_id)->toEqual($session_id); expect($result->currency_id)->toEqual($currencyId); -})->with('getSessionCartDoesNotExistProvider'); +})->with([ + [100, 'atLeastOnce', 'never'], + [null, 'never', 'atLeastOnce'], +]); -test('is stock available returns false when insufficient', function (): void { - $service = new Box\Mod\Cart\Service(); - $product = new Model_Product(); - $product->loadBean(new Tests\Helpers\DummyBean()); - $product->stock_control = true; - $product->quantity_in_stock = 5; +test('isStockAvailable returns false when product out of stock', function (): void { + $product = createProductEntity(); + $productService = Mockery::mock(ProductService::class); + $productService->shouldReceive('isStockAvailable')->once()->with($product, 6)->andReturn(false); + $di = container(); + $di['mod_service'] = $di->protect(static fn () => $productService); + $service = new Service(); + $service->setDi($di); $result = $service->isStockAvailable($product, 6); - expect($result)->toBeFalse(); }); -test('is stock available returns true when no stock control', function (): void { - $service = new Box\Mod\Cart\Service(); - $product = new Model_Product(); - $product->loadBean(new Tests\Helpers\DummyBean()); - $product->stock_control = false; - $product->quantity_in_stock = 5; +test('isStockAvailable returns true when product in stock', function (): void { + $product = createProductEntity(); + $productService = Mockery::mock(ProductService::class); + $productService->shouldReceive('isStockAvailable')->once()->with($product, 6)->andReturn(true); + $di = container(); + $di['mod_service'] = $di->protect(static fn () => $productService); + $service = new Service(); + $service->setDi($di); $result = $service->isStockAvailable($product, 6); - expect($result)->toBeTrue(); }); -test('is recurrent pricing', function (): void { - $service = new Box\Mod\Cart\Service(); - $productTable = Mockery::mock(Model_ProductTable::class); - $productTable->shouldReceive('getPricingArray') - ->atLeast()->once() - ->andReturn(['type' => Model_ProductPayment::RECURRENT]); +test('isRecurrentPricing returns true', function (): void { + $productService = Mockery::mock(ProductService::class); + $productService->shouldReceive('isRecurrentProductPricing')->once()->with(Mockery::type(Product::class))->andReturn(true); - $productModelMock = Mockery::mock(Model_Product::class)->makePartial(); - $productModelMock->shouldReceive('getTable') - ->atLeast()->once() - ->andReturn($productTable); + $productModelMock = createProductEntity(); + + $di = container(); + $di['mod_service'] = $di->protect(static fn () => $productService); + $service = new Service(); + $service->setDi($di); $result = $service->isRecurrentPricing($productModelMock); expect($result)->toBeTrue(); }); -test('is period enabled for product', function (): void { - $service = new Box\Mod\Cart\Service(); +test('isPeriodEnabledForProduct returns false', function (): void { $enabled = false; - $pricingArray = [ - 'type' => Model_ProductPayment::RECURRENT, - 'recurrent' => [ - 'monthly' => [ - 'enabled' => $enabled, - ], - ], - ]; - $productTable = Mockery::mock(Model_ProductTable::class); - $productTable->shouldReceive('getPricingArray') - ->atLeast()->once() - ->andReturn($pricingArray); + $productService = Mockery::mock(ProductService::class); + $productService->shouldReceive('isProductPeriodEnabled')->once()->with(Mockery::type(Product::class), 'monthly')->andReturn($enabled); - $productModelMock = Mockery::mock(Model_Product::class)->makePartial(); - $productModelMock->shouldReceive('getTable') - ->atLeast()->once() - ->andReturn($productTable); + $productModelMock = createProductEntity(); + + $di = container(); + $di['mod_service'] = $di->protect(static fn () => $productService); + $service = new Service(); + $service->setDi($di); $result = $service->isPeriodEnabledForProduct($productModelMock, 'monthly'); @@ -216,26 +206,16 @@ test('is period enabled for product', function (): void { expect($result)->toEqual($enabled); }); -test('is period enabled for product not recurrent', function (): void { - $service = new Box\Mod\Cart\Service(); - $enabled = false; - $pricingArray = [ - 'type' => Model_ProductPayment::FREE, - 'recurrent' => [ - 'monthly' => [ - 'enabled' => $enabled, - ], - ], - ]; - $productTable = Mockery::mock(Model_ProductTable::class); - $productTable->shouldReceive('getPricingArray') - ->atLeast()->once() - ->andReturn($pricingArray); +test('isPeriodEnabledForProduct returns true', function (): void { + $productService = Mockery::mock(ProductService::class); + $productService->shouldReceive('isProductPeriodEnabled')->once()->with(Mockery::type(Product::class), 'monthly')->andReturn(true); - $productModelMock = Mockery::mock(Model_Product::class)->makePartial(); - $productModelMock->shouldReceive('getTable') - ->atLeast()->once() - ->andReturn($productTable); + $productModelMock = createProductEntity(); + + $di = container(); + $di['mod_service'] = $di->protect(static fn () => $productService); + $service = new Service(); + $service->setDi($di); $result = $service->isPeriodEnabledForProduct($productModelMock, 'monthly'); @@ -243,108 +223,68 @@ test('is period enabled for product not recurrent', function (): void { expect($result)->toBeTrue(); }); -test('remove product', function (): void { - $service = new Box\Mod\Cart\Service(); +test('removeProduct returns true', function (): void { $cartProduct = new Model_CartProduct(); $cartProduct->loadBean(new Tests\Helpers\DummyBean()); - $dbMock = Mockery::mock(Box_Database::class); - $dbMock->shouldReceive('findOne') - ->atLeast()->once() - ->andReturn($cartProduct); - $dbMock->shouldReceive('find') - ->atLeast()->once() - ->andReturn([$cartProduct]); - $dbMock->shouldReceive('trash') - ->atLeast()->once() - ->andReturn(null); + $dbMock = Mockery::mock(Box_Database::class)->makePartial(); + $dbMock->shouldReceive('findOne')->atLeast()->once()->andReturn($cartProduct); + $dbMock->shouldReceive('find')->atLeast()->once()->andReturn([$cartProduct]); + $dbMock->shouldReceive('trash')->atLeast()->once()->andReturn(null); $di = container(); $di['db'] = $dbMock; + $di['logger'] = new Tests\Helpers\TestLogger(); + $service = new Service(); $service->setDi($di); $cart = new Model_Cart(); $cart->loadBean(new Tests\Helpers\DummyBean()); $result = $service->removeProduct($cart, 1); - expect($result)->toBeTrue(); }); -test('remove product cart product not found', function (): void { - $service = new Box\Mod\Cart\Service(); - $dbMock = Mockery::mock(Box_Database::class); - $dbMock->shouldReceive('findOne') - ->atLeast()->once() - ->andReturn(null); - $dbMock->shouldReceive('trash')->never(); - - $di = container(); - $di['db'] = $dbMock; - $service->setDi($di); - - $cart = new Model_Cart(); - $cart->loadBean(new Tests\Helpers\DummyBean()); - $this->expectException(FOSSBilling\Exception::class); - $service->removeProduct($cart, 1); -}); - -test('change cart currency', function (): void { - $service = new Box\Mod\Cart\Service(); - - $dbMock = Mockery::mock(Box_Database::class); - $dbMock->shouldReceive('store') - ->atLeast()->once() - ->andReturn(1); - - $cart = new Model_Cart(); - $cart->loadBean(new Tests\Helpers\DummyBean()); - - $currency = Mockery::mock(Box\Mod\Currency\Entity\Currency::class); - $currency->shouldReceive('getId')->atLeast()->once()->andReturn(1); - $currency->shouldReceive('getCode')->atLeast()->once()->andReturn('USD'); - $currency->shouldReceive('getTitle')->byDefault()->andReturn('USD'); +test('removeProduct throws exception when cart product not found', function (): void { + $dbMock = Mockery::mock(Box_Database::class)->makePartial(); + $dbMock->shouldReceive('findOne')->atLeast()->once()->andReturn(null); + $dbMock->shouldNotReceive('trash'); $di = container(); $di['db'] = $dbMock; $di['logger'] = new Tests\Helpers\TestLogger(); + $service = new Service(); + $service->setDi($di); + + $cart = new Model_Cart(); + $cart->loadBean(new Tests\Helpers\DummyBean()); + + expect(fn () => $service->removeProduct($cart, 1))->toThrow(FOSSBilling\Exception::class); +}); + +test('changeCartCurrency returns true', function (): void { + $dbMock = Mockery::mock(Box_Database::class)->makePartial(); + $dbMock->shouldReceive('store')->atLeast()->once()->andReturn(1); + + $cart = new Model_Cart(); + $cart->loadBean(new Tests\Helpers\DummyBean()); + + $currency = Mockery::mock(Currency::class)->shouldIgnoreMissing(); + + $di = container(); + $di['db'] = $dbMock; + $di['logger'] = new Tests\Helpers\TestLogger(); + $service = new Service(); $service->setDi($di); $result = $service->changeCartCurrency($cart, $currency); - expect($result)->toBeTrue(); }); -test('reset cart', function (): void { - $service = new Box\Mod\Cart\Service(); - $dbMock = Mockery::mock(Box_Database::class); - $dbMock->shouldReceive('find') - ->atLeast()->once() - ->andReturn([new Model_Product(), new Model_Product()]); - $dbMock->shouldReceive('trash') - ->atLeast()->once() - ->andReturn(null); - $dbMock->shouldReceive('store') - ->atLeast()->once() - ->andReturn(1); - - $cart = new Model_Cart(); - $cart->loadBean(new Tests\Helpers\DummyBean()); - - $di = container(); - $di['db'] = $dbMock; - $service->setDi($di); - - $result = $service->resetCart($cart); - - expect($result)->toBeTrue(); -}); - -test('remove promo', function (): void { - $service = new Box\Mod\Cart\Service(); - $dbMock = Mockery::mock(Box_Database::class); - $dbMock->shouldReceive('store') - ->atLeast()->once() - ->andReturn(1); +test('resetCart returns true', function (): void { + $dbMock = Mockery::mock(Box_Database::class)->makePartial(); + $dbMock->shouldReceive('find')->atLeast()->once()->andReturn([new Model_CartProduct(), new Model_CartProduct()]); + $dbMock->shouldReceive('trash')->atLeast()->once()->andReturn(null); + $dbMock->shouldReceive('store')->atLeast()->once()->andReturn(1); $cart = new Model_Cart(); $cart->loadBean(new Tests\Helpers\DummyBean()); @@ -352,26 +292,36 @@ test('remove promo', function (): void { $di = container(); $di['db'] = $dbMock; $di['logger'] = new Tests\Helpers\TestLogger(); + $service = new Service(); $service->setDi($di); - $result = $service->removePromo($cart); - + $result = $service->resetCart($cart); expect($result)->toBeTrue(); }); -test('apply promo', function (): void { - $service = new Box\Mod\Cart\Service(); - $dbMock = Mockery::mock(Box_Database::class); - $dbMock->shouldReceive('store') - ->atLeast()->once() - ->andReturn(1); - $dbMock->shouldReceive('find') - ->atLeast()->once() - ->andReturn([new Model_CartProduct(), new Model_CartProduct()]); +test('removePromo returns true', function (): void { + $dbMock = Mockery::mock(Box_Database::class)->makePartial(); + $dbMock->shouldReceive('store')->atLeast()->once()->andReturn(1); - $promo = new Model_Promo(); - $promo->loadBean(new Tests\Helpers\DummyBean()); - $promo->id = 2; + $cart = new Model_Cart(); + $cart->loadBean(new Tests\Helpers\DummyBean()); + + $di = container(); + $di['db'] = $dbMock; + $di['logger'] = new Tests\Helpers\TestLogger(); + $service = new Service(); + $service->setDi($di); + + $result = $service->removePromo($cart); + expect($result)->toBeTrue(); +}); + +test('applyPromo returns true', function (): void { + $dbMock = Mockery::mock(Box_Database::class)->makePartial(); + $dbMock->shouldReceive('store')->atLeast()->once()->andReturn(1); + $dbMock->shouldReceive('find')->atLeast()->once()->andReturn([new Model_CartProduct(), new Model_CartProduct()]); + + $promo = createPromoEntity(2); $cart = new Model_Cart(); $cart->loadBean(new Tests\Helpers\DummyBean()); @@ -380,27 +330,21 @@ test('apply promo', function (): void { $di = container(); $di['db'] = $dbMock; $di['logger'] = new Tests\Helpers\TestLogger(); + $service = new Service(); $service->setDi($di); $result = $service->applyPromo($cart, $promo); - expect($result)->toBeTrue(); }); -test('apply promo already applied', function (): void { - $service = new Box\Mod\Cart\Service(); +test('applyPromo returns true when already applied', function (): void { + $dbMock = Mockery::mock(Box_Database::class)->makePartial(); + $dbMock->shouldNotReceive('store'); - $dbMock = Mockery::mock(Box_Database::class); - $dbMock->shouldReceive('store')->never(); + $serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods(); + $serviceMock->shouldNotReceive('isEmptyCart'); - $serviceMock = Mockery::mock(Box\Mod\Cart\Service::class) - ->makePartial() - ->shouldAllowMockingProtectedMethods(); - $serviceMock->shouldReceive('isEmptyCart')->never(); - - $promo = new Model_Promo(); - $promo->loadBean(new Tests\Helpers\DummyBean()); - $promo->id = 5; + $promo = createPromoEntity(5); $cart = new Model_Cart(); $cart->loadBean(new Tests\Helpers\DummyBean()); @@ -412,26 +356,17 @@ test('apply promo already applied', function (): void { $serviceMock->setDi($di); $result = $serviceMock->applyPromo($cart, $promo); - expect($result)->toBeTrue(); }); -test('apply promo empty cart exception', function (): void { - $service = new Box\Mod\Cart\Service(); +test('applyPromo throws exception when cart is empty', function (): void { + $dbMock = Mockery::mock(Box_Database::class)->makePartial(); + $dbMock->shouldNotReceive('store'); - $dbMock = Mockery::mock(Box_Database::class); - $dbMock->shouldReceive('store')->never(); + $serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods(); + $serviceMock->shouldReceive('isEmptyCart')->atLeast()->once()->andReturn(true); - $serviceMock = Mockery::mock(Box\Mod\Cart\Service::class) - ->makePartial() - ->shouldAllowMockingProtectedMethods(); - $serviceMock->shouldReceive('isEmptyCart') - ->atLeast()->once() - ->andReturn(true); - - $promo = new Model_Promo(); - $promo->loadBean(new Tests\Helpers\DummyBean()); - $promo->id = 2; + $promo = createPromoEntity(2); $cart = new Model_Cart(); $cart->loadBean(new Tests\Helpers\DummyBean()); @@ -442,223 +377,148 @@ test('apply promo empty cart exception', function (): void { $di['logger'] = new Tests\Helpers\TestLogger(); $serviceMock->setDi($di); - $this->expectException(FOSSBilling\Exception::class); - $serviceMock->applyPromo($cart, $promo); + expect(fn () => $serviceMock->applyPromo($cart, $promo))->toThrow(FOSSBilling\Exception::class); }); -test('rm', function (): void { - $service = new Box\Mod\Cart\Service(); - $dbMock = Mockery::mock(Box_Database::class); - $dbMock->shouldReceive('find') - ->atLeast()->once() - ->andReturn([new Model_CartProduct()]); - $dbMock->shouldReceive('trash') - ->atLeast()->once() - ->andReturn(null); +test('rm returns true', function (): void { + $dbMock = Mockery::mock(Box_Database::class)->makePartial(); + $dbMock->shouldReceive('find')->atLeast()->once()->andReturn([new Model_CartProduct()]); + $dbMock->shouldReceive('trash')->atLeast()->once()->andReturn(null); $cart = new Model_Cart(); $cart->loadBean(new Tests\Helpers\DummyBean()); $di = container(); $di['db'] = $dbMock; + $di['logger'] = new Tests\Helpers\TestLogger(); + $service = new Service(); $service->setDi($di); $result = $service->rm($cart); + expect($result)->toBeTrue(); +}); + +test('isClientAbleToUsePromo returns false when client cannot use promo', function (): void { + $promo = createPromoEntity(1) + ->setOncePerClient(true); + + $client = new Model_Client(); + $client->loadBean(new Tests\Helpers\DummyBean()); + + $productService = Mockery::mock(ProductService::class); + $productService->shouldReceive('canClientUsePromo')->once()->with($client, $promo)->andReturn(false); + + $di = container(); + $di['logger'] = new Tests\Helpers\TestLogger(); + $di['mod_service'] = $di->protect(fn () => $productService); + + $serviceMock = new Service(); + $serviceMock->setDi($di); + + $result = $serviceMock->isClientAbleToUsePromo($client, $promo); + expect($result)->toBeFalse(); +}); + +test('clientHadUsedPromo returns true', function (): void { + $promo = createPromoEntity(1); + + $client = new Model_Client(); + $client->loadBean(new Tests\Helpers\DummyBean()); + + $productService = Mockery::mock(ProductService::class); + $productService->shouldReceive('clientHasActivePromoApplication')->once()->with($client, $promo)->andReturn(true); + + $di = container(); + $di['logger'] = new Tests\Helpers\TestLogger(); + $di['mod_service'] = $di->protect(fn () => $productService); + $service = new Service(); + $service->setDi($di); + + $reflection = new ReflectionObject($service); + $method = $reflection->getMethod('clientHadUsedPromo'); + $result = $method->invoke($service, $client, $promo); expect($result)->toBeTrue(); }); -test('is client able to use promo', function (): void { - $service = new Box\Mod\Cart\Service(); - - $serviceMock = Mockery::mock(Box\Mod\Cart\Service::class) - ->makePartial() - ->shouldAllowMockingProtectedMethods(); - $serviceMock->shouldReceive('promoCanBeApplied') - ->atLeast()->once() - ->andReturn(true); - $serviceMock->shouldReceive('clientHadUsedPromo') - ->atLeast()->once() - ->andReturn(true); - - $promo = new Model_Promo(); - $promo->loadBean(new Tests\Helpers\DummyBean()); - $promo->once_per_client = true; +test('isClientAbleToUsePromo returns true once per client', function (): void { + $promo = createPromoEntity(1); $client = new Model_Client(); $client->loadBean(new Tests\Helpers\DummyBean()); - $di = container(); - $di['logger'] = new Tests\Helpers\TestLogger(); - $serviceMock->setDi($di); - - $result = $serviceMock->isClientAbleToUsePromo($client, $promo); - - expect($result)->toBeFalse(); -}); - -test('client had used promo', function (): void { - $service = new Box\Mod\Cart\Service(); - - $serviceMock = Mockery::mock(Box\Mod\Cart\Service::class)->makePartial(); - $serviceMock->shouldReceive('promoCanBeApplied') - ->atLeast()->once() - ->andReturn(true); - - $dbMock = Mockery::mock(Box_Database::class); - $dbMock->shouldReceive('getCell') - ->atLeast()->once() - ->andReturn(1); - - $promo = new Model_Promo(); - $promo->loadBean(new Tests\Helpers\DummyBean()); - $promo->once_per_client = true; - - $client = new Model_Client(); - $client->loadBean(new Tests\Helpers\DummyBean()); + $productService = Mockery::mock(ProductService::class); + $productService->shouldReceive('canClientUsePromo')->once()->with($client, $promo)->andReturn(true); $di = container(); $di['logger'] = new Tests\Helpers\TestLogger(); - $di['db'] = $dbMock; + $di['mod_service'] = $di->protect(fn () => $productService); + + $serviceMock = new Service(); $serviceMock->setDi($di); $result = $serviceMock->isClientAbleToUsePromo($client, $promo); - - expect($result)->toBeFalse(); -}); - -test('is client able to use promo once per client', function (): void { - $service = new Box\Mod\Cart\Service(); - - $serviceMock = Mockery::mock(Box\Mod\Cart\Service::class) - ->makePartial() - ->shouldAllowMockingProtectedMethods(); - $serviceMock->shouldReceive('promoCanBeApplied') - ->atLeast()->once() - ->andReturn(true); - $serviceMock->shouldReceive('clientHadUsedPromo')->never(); - - $promo = new Model_Promo(); - $promo->loadBean(new Tests\Helpers\DummyBean()); - - $client = new Model_Client(); - $client->loadBean(new Tests\Helpers\DummyBean()); - - $di = container(); - $di['logger'] = new Tests\Helpers\TestLogger(); - $serviceMock->setDi($di); - - $result = $serviceMock->isClientAbleToUsePromo($client, $promo); - expect($result)->toBeTrue(); }); -test('is client able to use promo can not be applied', function (): void { - $service = new Box\Mod\Cart\Service(); - - $serviceMock = Mockery::mock(Box\Mod\Cart\Service::class) - ->makePartial() - ->shouldAllowMockingProtectedMethods(); - $serviceMock->shouldReceive('promoCanBeApplied') - ->atLeast()->once() - ->andReturn(false); - $serviceMock->shouldReceive('clientHadUsedPromo')->never(); - - $promo = new Model_Promo(); - $promo->loadBean(new Tests\Helpers\DummyBean()); +test('isClientAbleToUsePromo returns false when promo cannot be applied', function (): void { + $promo = createPromoEntity(1); $client = new Model_Client(); $client->loadBean(new Tests\Helpers\DummyBean()); + $productService = Mockery::mock(ProductService::class); + $productService->shouldReceive('canClientUsePromo')->once()->with($client, $promo)->andReturn(false); + $di = container(); $di['logger'] = new Tests\Helpers\TestLogger(); + $di['mod_service'] = $di->protect(fn () => $productService); + + $serviceMock = new Service(); $serviceMock->setDi($di); $result = $serviceMock->isClientAbleToUsePromo($client, $promo); - expect($result)->toBeFalse(); }); -dataset('promoCanBeAppliedProvider', function (): array { - $promo1 = new Model_Promo(); - $promo1->loadBean(new Tests\Helpers\DummyBean()); - $promo1->active = false; - - $promo2 = new Model_Promo(); - $promo2->loadBean(new Tests\Helpers\DummyBean()); - $promo2->active = true; - $promo2->maxuses = 5; - $promo2->used = 5; - - $promo3 = new Model_Promo(); - $promo3->loadBean(new Tests\Helpers\DummyBean()); - $promo3->active = true; - $promo3->maxuses = 10; - $promo3->used = 5; - $promo3->start_at = date('c', strtotime('tomorrow')); - - $promo4 = new Model_Promo(); - $promo4->loadBean(new Tests\Helpers\DummyBean()); - $promo4->active = true; - $promo4->maxuses = 10; - $promo4->used = 5; - $promo4->start_at = date('c', strtotime('yesterday')); - $promo4->end_at = date('c', strtotime('yesterday')); - - $promo5 = new Model_Promo(); - $promo5->loadBean(new Tests\Helpers\DummyBean()); - $promo5->active = true; - $promo5->maxuses = 10; - $promo5->used = 5; - $promo5->start_at = date('c', strtotime('yesterday')); - $promo5->end_at = date('c', strtotime('tomorrow')); - - return [ - [$promo1, false], - [$promo2, false], - [$promo3, false], - [$promo4, false], - [$promo5, true], - ]; -}); - -test('promo can be applied', function (Model_Promo $promo, bool $expectedResult): void { - $service = new Box\Mod\Cart\Service(); - $dbMock = Mockery::mock(Box_Database::class); - $dbMock->shouldReceive('store')->never(); +test('promoCanBeApplied returns expected result', function (Promo $promo, bool $expectedResult): void { + $productService = Mockery::mock(ProductService::class); + $productService->shouldReceive('promoCanBeApplied')->once()->with($promo)->andReturn($expectedResult); $di = container(); - $di['db'] = $dbMock; + $di['logger'] = new Tests\Helpers\TestLogger(); + $di['mod_service'] = $di->protect(fn () => $productService); + $service = new Service(); $service->setDi($di); $result = $service->promoCanBeApplied($promo); - expect($result)->toEqual($expectedResult); -})->with('promoCanBeAppliedProvider'); +})->with([ + [createPromoEntity(1)->setActive(false), false], + [createPromoEntity(2)->setActive(true)->setMaxUses(5)->setUsed(5), false], + [createPromoEntity(3)->setActive(true)->setMaxUses(10)->setUsed(5)->setStartAt(new DateTime('tomorrow')), false], + [createPromoEntity(4)->setActive(true)->setMaxUses(10)->setUsed(5)->setStartAt(new DateTime('yesterday'))->setEndAt(new DateTime('yesterday')), false], + [createPromoEntity(5)->setActive(true)->setMaxUses(10)->setUsed(5)->setStartAt(new DateTime('yesterday'))->setEndAt(new DateTime('tomorrow')), true], +]); -test('get cart products', function (): void { - $service = new Box\Mod\Cart\Service(); - $dbMock = Mockery::mock(Box_Database::class); - $dbMock->shouldReceive('find') - ->atLeast()->once() - ->andReturn([new Model_CartProduct()]); +test('getCartProducts returns array of cart products', function (): void { + $dbMock = Mockery::mock(Box_Database::class)->makePartial(); + $dbMock->shouldReceive('find')->atLeast()->once()->andReturn([new Model_CartProduct()]); $di = container(); $di['db'] = $dbMock; + $service = new Service(); $service->setDi($di); $cart = new Model_Cart(); $cart->loadBean(new Tests\Helpers\DummyBean()); $result = $service->getCartProducts($cart); - expect($result)->toBeArray(); - expect($result[0])->toBeInstanceOf('Model_CartProduct'); + expect($result[0])->toBeInstanceOf(Model_CartProduct::class); }); -test('checkout cart', function (): void { - $service = new Box\Mod\Cart\Service(); - +test('checkoutCart returns array with expected keys', function (): void { $cart = new Model_Cart(); $cart->loadBean(new Tests\Helpers\DummyBean()); $cart->promo_id = 1; @@ -666,44 +526,35 @@ test('checkout cart', function (): void { $order = new Model_ClientOrder(); $order->loadBean(new Tests\Helpers\DummyBean()); - $serviceMock = Mockery::mock(Box\Mod\Cart\Service::class)->makePartial(); - $serviceMock->shouldReceive('createFromCart') - ->atLeast()->once() - ->andReturn([$order, 1, [1]]); - $serviceMock->shouldReceive('isClientAbleToUsePromo') - ->atLeast()->once() - ->andReturn(true); - $serviceMock->shouldReceive('rm') - ->atLeast()->once() - ->andReturn(true); - $serviceMock->shouldReceive('isPromoAvailableForClientGroup') - ->atLeast()->once() - ->andReturn(true); + $serviceMock = Mockery::mock(Service::class)->makePartial(); + $serviceMock->shouldReceive('createFromCart')->atLeast()->once()->andReturn([$order, 1, [1]]); + $serviceMock->shouldReceive('isClientAbleToUsePromo')->atLeast()->once()->andReturn(true); + $serviceMock->shouldReceive('rm')->atLeast()->once()->andReturn(true); + $serviceMock->shouldReceive('isPromoAvailableForClientGroup')->atLeast()->once()->andReturn(true); - $eventMock = Mockery::mock(Box_EventManager::class); - $eventMock->shouldReceive('fire') - ->atLeast()->once(); + $eventMock = Mockery::mock(Box_EventManager::class)->shouldIgnoreMissing(); + $eventMock->shouldReceive('fire')->atLeast()->once(); $invoice = new Model_Invoice(); $invoice->loadBean(new Tests\Helpers\DummyBean()); $invoice->hash = sha1('str'); - $promo = new Model_Promo(); - $promo->loadBean(new Tests\Helpers\DummyBean()); + $promo = new Promo(); - $dbMock = Mockery::mock(Box_Database::class); - $dbMock->shouldReceive('getExistingModelById') - ->atLeast()->once() - ->andReturn($promo); + $dbMock = Mockery::mock(Box_Database::class)->shouldIgnoreMissing(); $client = new Model_Client(); $client->loadBean(new Tests\Helpers\DummyBean()); + $productService = Mockery::mock(ProductService::class); + $productService->shouldReceive('findPromoById')->once()->with(1)->andReturn($promo); + $di = container(); $di['events_manager'] = $eventMock; $di['db'] = $dbMock; $di['logger'] = new Tests\Helpers\TestLogger(); - $di['request'] = new Symfony\Component\HttpFoundation\Request(); + $di['request'] = new Request(); + $di['mod_service'] = $di->protect(fn () => $productService); $serviceMock->setDi($di); $result = $serviceMock->checkoutCart($cart, $client); @@ -715,9 +566,7 @@ test('checkout cart', function (): void { expect($result)->toHaveKey('orders'); }); -test('checkout cart client is not able to use promo exception', function (): void { - $service = new Box\Mod\Cart\Service(); - +test('checkoutCart throws exception when client is not able to use promo', function (): void { $cart = new Model_Cart(); $cart->loadBean(new Tests\Helpers\DummyBean()); $cart->promo_id = 1; @@ -725,16 +574,13 @@ test('checkout cart client is not able to use promo exception', function (): voi $order = new Model_ClientOrder(); $order->loadBean(new Tests\Helpers\DummyBean()); - $serviceMock = Mockery::mock(Box\Mod\Cart\Service::class)->makePartial(); - $serviceMock->shouldReceive('isClientAbleToUsePromo') - ->atLeast()->once() - ->andReturn(false); + $serviceMock = Mockery::mock(Service::class)->makePartial(); + $serviceMock->shouldReceive('isClientAbleToUsePromo')->atLeast()->once()->andReturn(false); - $dbMock = Mockery::mock(Box_Database::class); - - $dbMock->shouldReceive('getExistingModelById') - ->atLeast()->once() - ->andReturn(new Model_Promo()); + $dbMock = Mockery::mock(Box_Database::class)->shouldIgnoreMissing(); + $promo = new Promo(); + $productService = Mockery::mock(ProductService::class); + $productService->shouldReceive('findPromoById')->once()->with(1)->andReturn($promo); $client = new Model_Client(); $client->loadBean(new Tests\Helpers\DummyBean()); @@ -742,24 +588,21 @@ test('checkout cart client is not able to use promo exception', function (): voi $di = container(); $di['db'] = $dbMock; $di['logger'] = new Tests\Helpers\TestLogger(); + $di['mod_service'] = $di->protect(fn () => $productService); $serviceMock->setDi($di); - $this->expectException(FOSSBilling\Exception::class); - $serviceMock->checkoutCart($cart, $client); + expect(fn () => $serviceMock->checkoutCart($cart, $client))->toThrow(FOSSBilling\Exception::class); }); -test('use promo', function (): void { - $service = new Box\Mod\Cart\Service(); - $promo = new Model_Promo(); - $promo->loadBean(new Tests\Helpers\DummyBean()); +test('usePromo returns null', function (): void { + $promo = createPromoEntity(1); - $dbMock = Mockery::mock(Box_Database::class); - $dbMock->shouldReceive('exec') - ->atLeast()->once() - ->andReturn(1); + $productService = Mockery::mock(ProductService::class); + $productService->shouldReceive('usePromo')->once()->with($promo); $di = container(); - $di['db'] = $dbMock; + $di['mod_service'] = $di->protect(fn () => $productService); + $service = new Service(); $service->setDi($di); $result = $service->usePromo($promo); @@ -767,347 +610,759 @@ test('use promo', function (): void { expect($result)->toBeNull(); }); -test('find active promo by code', function (): void { - $service = new Box\Mod\Cart\Service(); - $promo = new Model_Promo(); - $promo->loadBean(new Tests\Helpers\DummyBean()); +test('createFromCart uses database transaction', function (): void { + $cart = new Model_Cart(); + $cart->loadBean(new Tests\Helpers\DummyBean()); + $cart->currency_id = 2; - $dbMock = Mockery::mock(Box_Database::class); - $dbMock->shouldReceive('findOne') - ->atLeast()->once() - ->andReturn($promo); + $client = new Model_Client(); + $client->loadBean(new Tests\Helpers\DummyBean()); + $client->currency = 'USD'; + + $currency = Mockery::mock(Currency::class)->makePartial(); + $currency->shouldReceive('getCode')->once()->andReturn('USD'); + + $currencyRepository = Mockery::mock(CurrencyRepository::class); + $currencyRepository->shouldReceive('find')->once()->with(2)->andReturn($currency); + $currencyRepository->shouldNotReceive('findDefault'); + + $currencyService = Mockery::mock(CurrencyService::class); + $currencyService->shouldReceive('getCurrencyRepository')->once()->andReturn($currencyRepository); + + $clientService = Mockery::mock(Box\Mod\Client\Service::class); + $clientService->shouldReceive('isClientTaxable')->once()->with($client)->andReturn(false); + + $order = new Model_ClientOrder(); + $order->loadBean(new Tests\Helpers\DummyBean()); + $order->id = 99; + + $dbMock = Mockery::mock(Box_Database::class)->makePartial(); + $dbMock->shouldReceive('transaction')->once()->with(Mockery::type(Closure::class))->andReturn([$order, null, [99]]); + + $serviceMock = Mockery::mock(Service::class)->makePartial(); + $serviceMock->shouldReceive('getSessionCart')->once()->andReturn($cart); + $serviceMock->shouldReceive('toApiArray')->once()->with($cart)->andReturn([ + 'items' => [['id' => 1]], + 'total' => 0, + ]); $di = container(); $di['db'] = $dbMock; + $di['mod_service'] = $di->protect(function ($serviceName, $sub = '') use ($currencyService, $clientService) { + if ($serviceName === 'currency') { + return $currencyService; + } + if ($serviceName === 'client') { + return $clientService; + } + }); + + $serviceMock->setDi($di); + $result = $serviceMock->createFromCart($client); + + expect($result)->toBe([$order, null, [99]]); +}); + +test('createFromCart with promo entity uses product promo service', function (): void { + $cart = new Model_Cart(); + $cart->loadBean(new Tests\Helpers\DummyBean()); + $cart->id = 3; + $cart->currency_id = 2; + $cart->promo_id = 7; + + $client = new Model_Client(); + $client->loadBean(new Tests\Helpers\DummyBean()); + $client->id = 9; + $client->currency = 'USD'; + + $currency = Mockery::mock(Currency::class)->makePartial(); + $currency->shouldReceive('getCode')->once()->andReturn('USD'); + $currency->shouldReceive('getConversionRate')->atLeast()->once()->andReturn(1.0); + + $currencyRepository = Mockery::mock(CurrencyRepository::class); + $currencyRepository->shouldReceive('find')->once()->with(2)->andReturn($currency); + + $currencyService = Mockery::mock(CurrencyService::class); + $currencyService->shouldReceive('getCurrencyRepository')->once()->andReturn($currencyRepository); + + $clientService = Mockery::mock(Box\Mod\Client\Service::class); + $clientService->shouldReceive('isClientTaxable')->once()->with($client)->andReturn(false); + + $promo = new Promo(); + $promo->setCode('PROMO'); + $promoIdReflection = new ReflectionProperty($promo, 'id'); + $promoIdReflection->setAccessible(true); + $promoIdReflection->setValue($promo, 7); + + $productService = Mockery::mock(ProductService::class); + $productService->shouldReceive('findPromoById')->once()->with(7)->andReturn($promo); + $productService->shouldReceive('reservePromoForOrder')->once()->with($promo, Mockery::type(Model_ClientOrder::class)); + $productService->shouldReceive('createCheckoutPromoRedemptions')->once()->with( + $promo, + $client, + Mockery::on(function (array $orders): bool { + return count($orders) === 1 && $orders[0] instanceof Model_ClientOrder; + }), + null, + PromoRedemption::STATUS_COMMITTED + ); + + $product = new Product(); + $productIdReflection = new ReflectionProperty($product, 'id'); + $productIdReflection->setAccessible(true); + $productIdReflection->setValue($product, 5); + $product->setStatus('enabled'); + $product->setType('service'); + $product->setSetup('manual'); + + $cartProduct = new Model_CartProduct(); + $cartProduct->loadBean(new Tests\Helpers\DummyBean()); + $cartProduct->id = 13; + + $order = new Model_ClientOrder(); + $order->loadBean(new Tests\Helpers\DummyBean()); + $order->id = 42; + + $orderService = Mockery::mock(Box\Mod\Order\Service::class)->makePartial(); + $orderService->shouldReceive('saveStatusChange')->once()->with(Mockery::type(Model_ClientOrder::class), 'Order Created'); + $orderService->shouldReceive('toApiArray')->once()->with(Mockery::type(Model_ClientOrder::class), false, $client)->andReturn([ + 'product_id' => 5, + 'total' => 0, + 'discount' => 0, + ]); + + $dbMock = Mockery::mock(Box_Database::class)->makePartial(); + $dbMock->shouldReceive('transaction')->once()->with(Mockery::type(Closure::class))->andReturnUsing(fn (Closure $callback) => $callback()); + $dbMock->shouldReceive('dispense')->once()->with('ClientOrder')->andReturn($order); + $dbMock->shouldReceive('store')->atLeast()->once(); + + $serviceMock = Mockery::mock(Service::class)->makePartial(); + $serviceMock->shouldReceive('getSessionCart')->once()->andReturn($cart); + $serviceMock->shouldReceive('toApiArray')->once()->with($cart)->andReturn([ + 'items' => [['id' => 1]], + 'total' => 0, + ]); + $serviceMock->shouldReceive('getCartProducts')->once()->with($cart)->andReturn([$cartProduct]); + $serviceMock->shouldReceive('cartProductToApiArray')->once()->with($cartProduct)->andReturn([ + 'product_id' => 5, + 'form_id' => null, + 'title' => 'Example product', + 'type' => 'service', + 'unit' => 'service', + 'period' => '1M', + 'quantity' => 1, + 'price' => 0, + 'discount_price' => 0, + 'setup_price' => 0, + 'discount_setup' => 0, + 'notes' => null, + ]); + $serviceMock->shouldReceive('isStockAvailable')->once()->with($product, 1)->andReturn(true); + + $productService->shouldReceive('findProductById')->twice()->with(5)->andReturn($product); + + $di = container(); + $di['db'] = $dbMock; + $di['mod_service'] = $di->protect(function ($serviceName, $sub = '') use ($currencyService, $clientService, $productService, $orderService) { + return match ($serviceName) { + 'currency' => $currencyService, + 'client' => $clientService, + 'Product' => $productService, + 'order', 'Order' => $orderService, + default => null, + }; + }); + + $serviceMock->setDi($di); + $result = $serviceMock->createFromCart($client); + + expect($result)->toBe([$order, null, [42]]); +}); + +test('createFromCart compensates promo usage on transaction failure', function (): void { + $cart = new Model_Cart(); + $cart->loadBean(new Tests\Helpers\DummyBean()); + $cart->id = 3; + $cart->currency_id = 2; + $cart->promo_id = 7; + + $client = new Model_Client(); + $client->loadBean(new Tests\Helpers\DummyBean()); + $client->id = 9; + $client->currency = 'USD'; + + $currency = Mockery::mock(Currency::class)->makePartial(); + $currency->shouldReceive('getCode')->once()->andReturn('USD'); + $currency->shouldReceive('getConversionRate')->atLeast()->once()->andReturn(1.0); + + $currencyRepository = Mockery::mock(CurrencyRepository::class); + $currencyRepository->shouldReceive('find')->once()->with(2)->andReturn($currency); + + $currencyService = Mockery::mock(CurrencyService::class); + $currencyService->shouldReceive('getCurrencyRepository')->once()->andReturn($currencyRepository); + + $clientService = Mockery::mock(Box\Mod\Client\Service::class); + $clientService->shouldReceive('isClientTaxable')->once()->with($client)->andReturn(false); + + $promo = new Promo(); + $promo->setCode('PROMO'); + $promoIdReflection = new ReflectionProperty($promo, 'id'); + $promoIdReflection->setAccessible(true); + $promoIdReflection->setValue($promo, 7); + + $productService = Mockery::mock(ProductService::class); + $productService->shouldReceive('findPromoById')->once()->with(7)->andReturn($promo); + $productService->shouldReceive('reservePromoForOrder')->once()->with($promo, Mockery::type(Model_ClientOrder::class)); + + // Simulate Doctrine-side failure during redemption creation. + $productService->shouldReceive('createCheckoutPromoRedemptions') + ->andThrow(new RuntimeException('Doctrine flush failed')); + + // The compensating method must be invoked with the order ID and count. + $productService->shouldReceive('compensateCheckoutPromoFailure') + ->once() + ->with($promo, [42], 1); + + $product = new Product(); + $productIdReflection = new ReflectionProperty($product, 'id'); + $productIdReflection->setAccessible(true); + $productIdReflection->setValue($product, 5); + $product->setStatus('enabled'); + $product->setType('service'); + $product->setSetup('manual'); + + $cartProduct = new Model_CartProduct(); + $cartProduct->loadBean(new Tests\Helpers\DummyBean()); + $cartProduct->id = 13; + + $order = new Model_ClientOrder(); + $order->loadBean(new Tests\Helpers\DummyBean()); + $order->id = 42; + + $orderService = Mockery::mock(Box\Mod\Order\Service::class)->makePartial(); + $orderService->shouldReceive('saveStatusChange')->once()->with(Mockery::type(Model_ClientOrder::class), 'Order Created'); + + $dbMock = Mockery::mock(Box_Database::class)->makePartial(); + $dbMock->shouldReceive('transaction')->once()->with(Mockery::type(Closure::class))->andReturnUsing(fn (Closure $callback) => $callback()); + $dbMock->shouldReceive('dispense')->once()->with('ClientOrder')->andReturn($order); + $dbMock->shouldReceive('store')->atLeast()->once(); + + $serviceMock = Mockery::mock(Service::class)->makePartial(); + $serviceMock->shouldReceive('getSessionCart')->once()->andReturn($cart); + $serviceMock->shouldReceive('toApiArray')->once()->with($cart)->andReturn([ + 'items' => [['id' => 1]], + 'total' => 0, + ]); + $serviceMock->shouldReceive('getCartProducts')->once()->with($cart)->andReturn([$cartProduct]); + $serviceMock->shouldReceive('cartProductToApiArray')->once()->with($cartProduct)->andReturn([ + 'product_id' => 5, + 'form_id' => null, + 'title' => 'Example product', + 'type' => 'service', + 'unit' => 'service', + 'period' => '1M', + 'quantity' => 1, + 'price' => 0, + 'discount_price' => 0, + 'setup_price' => 0, + 'discount_setup' => 0, + 'notes' => null, + ]); + $serviceMock->shouldReceive('isStockAvailable')->once()->with($product, 1)->andReturn(true); + + $productService->shouldReceive('findProductById')->once()->with(5)->andReturn($product); + + $di = container(); + $di['db'] = $dbMock; + $di['logger'] = new Box_Log(); + $di['mod_service'] = $di->protect(function ($serviceName, $sub = '') use ($currencyService, $clientService, $productService, $orderService) { + return match ($serviceName) { + 'currency' => $currencyService, + 'client' => $clientService, + 'Product' => $productService, + 'order', 'Order' => $orderService, + default => null, + }; + }); + + $serviceMock->setDi($di); + + expect(fn () => $serviceMock->createFromCart($client)) + ->toThrow(RuntimeException::class, 'Doctrine flush failed'); +}); + +test('usePromo throws exception when limit reached', function (): void { + $promo = createPromoEntity(1); + + $productService = Mockery::mock(ProductService::class); + $productService->shouldReceive('usePromo')->once()->with($promo)->andThrow(new FOSSBilling\InformationException('This promo code has reached its maximum number of uses.')); + + $di = container(); + $di['mod_service'] = $di->protect(fn () => $productService); + $service = new Service(); + $service->setDi($di); + + expect(fn () => $service->usePromo($promo))->toThrow(FOSSBilling\InformationException::class); +}); + +test('findActivePromoByCode returns promo', function (): void { + $promo = new Promo(); + + $productService = Mockery::mock(ProductService::class); + $productService->shouldReceive('findActivePromoByCode')->once()->with('CODE')->andReturn($promo); + + $di = container(); + $di['mod_service'] = $di->protect(fn () => $productService); + $service = new Service(); $service->setDi($di); $result = $service->findActivePromoByCode('CODE'); - expect($result)->toBeInstanceOf('Model_Promo'); + expect($result)->toBeInstanceOf(Promo::class); }); -test('add item throws exception when out of stock', function (): void { - $service = new Box\Mod\Cart\Service(); +test('addItem throws exception when recurring payment period param missing', function (): void { $cartModel = new Model_Cart(); $cartModel->loadBean(new Tests\Helpers\DummyBean()); - $productModel = new Model_Product(); - $productModel->loadBean(new Tests\Helpers\DummyBean()); - $productModel->type = 'hosting'; + $productModel = createProductEntity(type: 'Custom'); $data = []; - $eventMock = Mockery::mock('\Box_EventManager'); - $eventMock->shouldReceive('fire') - ->atLeast()->once(); + $eventMock = Mockery::mock(Box_EventManager::class)->shouldIgnoreMissing(); + $eventMock->shouldReceive('fire')->atLeast()->once(); + $serviceHostingServiceMock = Mockery::mock(Box\Mod\Servicehosting\Service::class)->shouldIgnoreMissing(); - $serviceHostingServiceMock = Mockery::mock(Box\Mod\Servicehosting\Service::class); - $serviceHostingServiceMock->shouldReceive('getDomainProductFromConfig') - ->atLeast()->once() - ->andReturn([]); - - $serviceMock = Mockery::mock(Box\Mod\Cart\Service::class)->makePartial(); - $serviceMock->shouldReceive('isRecurrentPricing') - ->atLeast()->once() - ->andReturn(false); - $serviceMock->shouldReceive('isStockAvailable') - ->atLeast()->once() - ->andReturn(false); + $serviceMock = Mockery::mock(Service::class)->makePartial(); + $serviceMock->shouldReceive('isRecurrentPricing')->atLeast()->once()->andReturn(true); + $productService = new ProductService(); $di = container(); $di['events_manager'] = $eventMock; - $di['mod_service'] = $di->protect(moduleService(['servicehosting' => $serviceHostingServiceMock])); + $di['mod_service'] = $di->protect(function ($name) use ($serviceHostingServiceMock, $productService) { + if ($name === 'Product') { + return $productService; + } - $serviceMock->setDi($di); - $productModel->setDi($di); - - $this->expectException(FOSSBilling\Exception::class); - $this->expectExceptionMessage('This item is currently out of stock'); - $serviceMock->addItem($cartModel, $productModel, $data); -}); - -test('add item for hosting type product', function (): void { - $service = new Box\Mod\Cart\Service(); - $cartModel = new Model_Cart(); - $cartModel->loadBean(new Tests\Helpers\DummyBean()); - - $productModel = new Model_Product(); - $productModel->loadBean(new Tests\Helpers\DummyBean()); - $productModel->type = 'hosting'; - - $data = []; - - $eventMock = Mockery::mock('\Box_EventManager'); - $eventMock->shouldReceive('fire') - ->atLeast()->once(); - - $productDomainModel = new Model_ProductDomain(); - $productDomainModel->loadBean(new Tests\Helpers\DummyBean()); - $domainProduct = ['config' => [], 'product' => $productDomainModel]; - - $serviceHostingServiceMock = Mockery::mock(Box\Mod\Servicehosting\Service::class); - $serviceHostingServiceMock->shouldReceive('getDomainProductFromConfig') - ->atLeast()->once() - ->andReturn($domainProduct); - $serviceHostingServiceMock->shouldReceive('prependOrderConfig') - ->atLeast()->once() - ->andReturn([]); - $serviceHostingServiceMock->shouldReceive('validateOrderData') - ->atLeast()->once() - ->andReturn(true); - - $serviceMock = Mockery::mock(Box\Mod\Cart\Service::class)->makePartial()->shouldAllowMockingProtectedMethods(); - $serviceMock->shouldReceive('isRecurrentPricing') - ->atLeast()->once() - ->andReturn(false); - $serviceMock->shouldReceive('isStockAvailable') - ->atLeast()->once() - ->andReturn(true); - $serviceMock->shouldReceive('addProduct') - ->atLeast()->once(); - - $di = container(); - $di['events_manager'] = $eventMock; - $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $serviceHostingServiceMock); - $di['logger'] = new Tests\Helpers\TestLogger(); - - $serviceMock->setDi($di); - $productModel->setDi($di); - $productDomainModel->setDi($di); - - $result = $serviceMock->addItem($cartModel, $productModel, $data); - expect($result)->toBeTrue(); -}); - -test('add item for license type product', function (): void { - $service = new Box\Mod\Cart\Service(); - $cartModel = new Model_Cart(); - $cartModel->loadBean(new Tests\Helpers\DummyBean()); - - $productModel = new Model_Product(); - $productModel->loadBean(new Tests\Helpers\DummyBean()); - $productModel->type = 'license'; - - $data = []; - - $eventMock = Mockery::mock('\Box_EventManager'); - $eventMock->shouldReceive('fire') - ->atLeast()->once(); - - $serviceLicenseServiceMock = Mockery::mock(Box\Mod\Servicelicense\Service::class); - $serviceLicenseServiceMock->shouldReceive('attachOrderConfig') - ->atLeast()->once() - ->andReturn([]); - $serviceLicenseServiceMock->shouldReceive('validateOrderData') - ->atLeast()->once() - ->andReturn(true); - - $serviceMock = Mockery::mock(Box\Mod\Cart\Service::class)->makePartial()->shouldAllowMockingProtectedMethods(); - $serviceMock->shouldReceive('isRecurrentPricing') - ->atLeast()->once() - ->andReturn(false); - $serviceMock->shouldReceive('isStockAvailable') - ->atLeast()->once() - ->andReturn(true); - $serviceMock->shouldReceive('addProduct') - ->atLeast()->once(); - - $dbMock = Mockery::mock('\Box_Database'); - $dbMock->shouldReceive('find') - ->byDefault() - ->andReturn([]); - $dbMock->shouldReceive('load') - ->atLeast()->once() - ->andReturn($productModel); - - $di = container(); - $di['events_manager'] = $eventMock; - $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $serviceLicenseServiceMock); - $di['logger'] = new Tests\Helpers\TestLogger(); - $di['db'] = $dbMock; - - $serviceMock->setDi($di); - $productModel->setDi($di); - - $result = $serviceMock->addItem($cartModel, $productModel, $data); - expect($result)->toBeTrue(); -}); - -test('add item for custom type product', function (): void { - $service = new Box\Mod\Cart\Service(); - $cartModel = new Model_Cart(); - $cartModel->loadBean(new Tests\Helpers\DummyBean()); - - $productModel = new Model_Product(); - $productModel->loadBean(new Tests\Helpers\DummyBean()); - $productModel->type = 'custom'; - - $data = []; - - $eventMock = Mockery::mock('\Box_EventManager'); - $eventMock->shouldReceive('fire') - ->atLeast()->once(); - - $serviceCustomServiceMock = Mockery::mock(Box\Mod\Servicecustom\Service::class); - $serviceCustomServiceMock->shouldReceive('validateCustomForm') - ->atLeast()->once(); - - $serviceMock = Mockery::mock(Box\Mod\Cart\Service::class)->makePartial(); - $serviceMock->shouldReceive('isRecurrentPricing') - ->atLeast()->once() - ->andReturn(false); - $serviceMock->shouldReceive('isStockAvailable') - ->atLeast()->once() - ->andReturn(true); - - $cartProduct = new Model_CartProduct(); - $cartProduct->loadBean(new Tests\Helpers\DummyBean()); - - $dbMock = Mockery::mock('\Box_Database'); - $dbMock->shouldReceive('find') - ->byDefault() - ->andReturn([]); - $dbMock->shouldReceive('toArray') - ->atLeast()->once() - ->andReturn([]); - $dbMock->shouldReceive('dispense') - ->atLeast()->once() - ->andReturn($cartProduct); - $dbMock->shouldReceive('store') - ->atLeast()->once(); - - $di = container(); - $di['events_manager'] = $eventMock; - $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $serviceCustomServiceMock); - $di['logger'] = new Tests\Helpers\TestLogger(); - $di['db'] = $dbMock; - - $serviceMock->setDi($di); - $productModel->setDi($di); - - $result = $serviceMock->addItem($cartModel, $productModel, $data); - expect($result)->toBeTrue(); -}); - -test('add item throws exception when recurring payment period param missing', function (): void { - $service = new Box\Mod\Cart\Service(); - $cartModel = new Model_Cart(); - $cartModel->loadBean(new Tests\Helpers\DummyBean()); - - $productModel = new Model_Product(); - $productModel->loadBean(new Tests\Helpers\DummyBean()); - $productModel->type = 'Custom'; - - $data = []; - - $eventMock = Mockery::mock('\Box_EventManager'); - $eventMock->shouldReceive('fire') - ->atLeast()->once(); - - $serviceHostingServiceMock = Mockery::mock(Box\Mod\Servicehosting\Service::class); - - $serviceMock = Mockery::mock(Box\Mod\Cart\Service::class)->makePartial(); - $serviceMock->shouldReceive('isRecurrentPricing') - ->atLeast()->once() - ->andReturn(true); - - $di = container(); - $di['events_manager'] = $eventMock; - $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $serviceHostingServiceMock); - - $validatorMock = Mockery::mock(FOSSBilling\Validate::class); - $validatorMock->shouldReceive('checkRequiredParamsForArray') - ->andThrow(new FOSSBilling\Exception('Period parameter not passed')); + return $serviceHostingServiceMock; + }); + $validatorMock = Mockery::mock(FOSSBilling\Validate::class)->shouldIgnoreMissing(); + $validatorMock->shouldReceive('checkRequiredParamsForArray')->andThrow(new FOSSBilling\Exception('Period parameter not passed')); $di['validator'] = $validatorMock; - + $productService->setDi($di); $serviceMock->setDi($di); - $productModel->setDi($di); - $this->expectException(FOSSBilling\Exception::class); - $this->expectExceptionMessage('Period parameter not passed'); - $serviceMock->addItem($cartModel, $productModel, $data); + expect(fn () => $serviceMock->addItem($cartModel, $productModel, $data)) + ->toThrow(FOSSBilling\Exception::class, 'Period parameter not passed'); }); -test('add item throws exception when recurring payment period is not enabled', function (): void { - $service = new Box\Mod\Cart\Service(); +test('addItem throws exception when recurring payment period is not enabled', function (): void { $cartModel = new Model_Cart(); $cartModel->loadBean(new Tests\Helpers\DummyBean()); - $productModel = new Model_Product(); - $productModel->loadBean(new Tests\Helpers\DummyBean()); - $productModel->type = 'hosting'; + $productModel = createProductEntity(type: 'hosting'); $data = ['period' => '1W']; - $eventMock = Mockery::mock('\Box_EventManager'); - $eventMock->shouldReceive('fire') - ->atLeast()->once(); + $eventMock = Mockery::mock(Box_EventManager::class)->shouldIgnoreMissing(); + $eventMock->shouldReceive('fire')->atLeast()->once(); - $serviceHostingServiceMock = Mockery::mock(Box\Mod\Servicehosting\Service::class); + $serviceHostingServiceMock = Mockery::mock(Box\Mod\Servicehosting\Service::class)->shouldIgnoreMissing(); - $serviceMock = Mockery::mock(Box\Mod\Cart\Service::class)->makePartial(); - $serviceMock->shouldReceive('isRecurrentPricing') - ->atLeast()->once() - ->andReturn(true); - $serviceMock->shouldReceive('isPeriodEnabledForProduct') - ->atLeast()->once() - ->andReturn(false); + $serviceMock = Mockery::mock(Service::class)->makePartial(); + $serviceMock->shouldReceive('isRecurrentPricing')->atLeast()->once()->andReturn(true); + $serviceMock->shouldReceive('isPeriodEnabledForProduct')->atLeast()->once()->andReturn(false); + $productService = new ProductService(); $di = container(); $di['events_manager'] = $eventMock; - $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $serviceHostingServiceMock); + $di['mod_service'] = $di->protect(function ($name) use ($serviceHostingServiceMock, $productService) { + if ($name === 'Product') { + return $productService; + } - $validatorMock = Mockery::mock(FOSSBilling\Validate::class); - $validatorMock->shouldReceive('checkRequiredParamsForArray'); + return $serviceHostingServiceMock; + }); + $validatorMock = Mockery::mock(FOSSBilling\Validate::class)->shouldIgnoreMissing(); $di['validator'] = $validatorMock; - + $productService->setDi($di); $serviceMock->setDi($di); - $productModel->setDi($di); - $this->expectException(FOSSBilling\Exception::class); - $this->expectExceptionMessage('Selected billing period is invalid'); - $serviceMock->addItem($cartModel, $productModel, $data); + expect(fn () => $serviceMock->addItem($cartModel, $productModel, $data)) + ->toThrow(FOSSBilling\Exception::class, 'Selected billing period is invalid'); }); -test('to api array', function (): void { - $service = new Box\Mod\Cart\Service(); +test('addItem throws exception when out of stock', function (): void { + $cartModel = new Model_Cart(); + $cartModel->loadBean(new Tests\Helpers\DummyBean()); + + $productModel = createProductEntity(type: 'hosting'); + + $data = []; + + $eventMock = Mockery::mock(Box_EventManager::class)->shouldIgnoreMissing(); + $eventMock->shouldReceive('fire')->atLeast()->once(); + + $serviceHostingServiceMock = Mockery::mock(Box\Mod\Servicehosting\Service::class)->shouldIgnoreMissing(); + + $serviceMock = Mockery::mock(Service::class)->makePartial(); + $serviceMock->shouldReceive('isRecurrentPricing')->atLeast()->once()->andReturn(false); + $serviceMock->shouldReceive('isStockAvailable')->atLeast()->once()->andReturn(false); + + $dbMock = Mockery::mock(Box_Database::class); + $dbMock->shouldReceive('find')->atLeast()->once()->andReturn([]); + + $productService = new ProductService(); + $di = container(); + $di['db'] = $dbMock; + $di['events_manager'] = $eventMock; + $di['mod_service'] = $di->protect(function ($name) use ($serviceHostingServiceMock, $productService) { + if ($name === 'Product') { + return $productService; + } + + return $serviceHostingServiceMock; + }); + + $productService->setDi($di); + $serviceMock->setDi($di); + + expect(fn () => $serviceMock->addItem($cartModel, $productModel, $data)) + ->toThrow(FOSSBilling\Exception::class, 'This item is currently out of stock'); +}); + +test('addItem rejects cumulative stock overflow', function (): void { + $cartModel = new Model_Cart(); + $cartModel->loadBean(new Tests\Helpers\DummyBean()); + $cartModel->id = 10; + + $productModel = createProductEntity(id: 7, type: 'hosting'); + $productModel->setStockControl(true); + $productModel->setQuantityInStock(1); + + $existingCartProduct = new Model_CartProduct(); + $existingCartProduct->loadBean(new Tests\Helpers\DummyBean()); + $existingCartProduct->product_id = 7; + $existingCartProduct->config = json_encode(['quantity' => 1]); + + $eventMock = Mockery::mock(Box_EventManager::class)->shouldIgnoreMissing(); + $eventMock->shouldReceive('fire')->atLeast()->once(); + + $serviceHostingServiceMock = Mockery::mock(Box\Mod\Servicehosting\Service::class)->shouldIgnoreMissing(); + $productServiceMock = Mockery::mock(ProductService::class)->shouldIgnoreMissing(); + $productServiceMock->shouldReceive('isStockAvailable')->once()->with($productModel, 2)->andReturn(false); + + $dbMock = Mockery::mock(Box_Database::class); + $dbMock->shouldReceive('find')->atLeast()->once()->with('CartProduct', Mockery::any(), Mockery::any())->andReturn([$existingCartProduct]); + $dbMock->shouldNotReceive('store'); + + $serviceMock = Mockery::mock(Service::class)->makePartial(); + $serviceMock->shouldReceive('isRecurrentPricing')->atLeast()->once()->andReturn(false); + + $di = container(); + $di['db'] = $dbMock; + $di['events_manager'] = $eventMock; + $di['mod_service'] = $di->protect(function ($name) use ($serviceHostingServiceMock, $productServiceMock) { + if ($name === 'Product') { + return $productServiceMock; + } + + return $serviceHostingServiceMock; + }); + + $serviceMock->setDi($di); + + expect(fn () => $serviceMock->addItem($cartModel, $productModel, ['quantity' => 1])) + ->toThrow(FOSSBilling\Exception::class, 'This item is currently out of stock'); +}); + +test('addItem rejects duplicate domain register', function (): void { + $cartModel = new Model_Cart(); + $cartModel->loadBean(new Tests\Helpers\DummyBean()); + $cartModel->id = 1; + + $productModel = createProductEntity(type: 'domain'); + + // An existing cart item already holds example.com via register keys. + $existingCartProduct = new Model_CartProduct(); + $existingCartProduct->loadBean(new Tests\Helpers\DummyBean()); + $existingCartProduct->config = json_encode(['register_sld' => 'example', 'register_tld' => '.com']); + + $dbMock = Mockery::mock(Box_Database::class); + $dbMock->shouldReceive('find')->atLeast()->once()->with('CartProduct', Mockery::any(), Mockery::any())->andReturn([$existingCartProduct]); + + $eventMock = Mockery::mock(Box_EventManager::class)->shouldIgnoreMissing(); + $eventMock->shouldReceive('fire')->atLeast()->once(); + + $serviceMock = Mockery::mock(Service::class)->makePartial(); + $serviceMock->shouldReceive('isRecurrentPricing')->atLeast()->once()->andReturn(false); + + $serviceHostingServiceMock = Mockery::mock(Box\Mod\Servicehosting\Service::class)->shouldIgnoreMissing(); + + $productService = new ProductService(); + $di = container(); + $di['db'] = $dbMock; + $di['events_manager'] = $eventMock; + $di['mod_service'] = $di->protect(function ($name) use ($serviceHostingServiceMock, $productService) { + if ($name === 'Product') { + return $productService; + } + + return $serviceHostingServiceMock; + }); + $productService->setDi($di); + $serviceMock->setDi($di); + + expect(fn () => $serviceMock->addItem($cartModel, $productModel, ['register_sld' => 'example', 'register_tld' => '.com'])) + ->toThrow(FOSSBilling\InformationException::class, 'This domain is already in the cart.'); +}); + +test('addItem rejects duplicate domain transfer', function (): void { + $cartModel = new Model_Cart(); + $cartModel->loadBean(new Tests\Helpers\DummyBean()); + $cartModel->id = 2; + + $productModel = createProductEntity(type: 'domain'); + + // An existing cart item holds example.net via transfer keys. + $existingCartProduct = new Model_CartProduct(); + $existingCartProduct->loadBean(new Tests\Helpers\DummyBean()); + $existingCartProduct->config = json_encode(['transfer_sld' => 'example', 'transfer_tld' => '.net']); + + $dbMock = Mockery::mock(Box_Database::class); + $dbMock->shouldReceive('find')->atLeast()->once()->with('CartProduct', Mockery::any(), Mockery::any())->andReturn([$existingCartProduct]); + + $eventMock = Mockery::mock(Box_EventManager::class)->shouldIgnoreMissing(); + $eventMock->shouldReceive('fire')->atLeast()->once(); + + $serviceMock = Mockery::mock(Service::class)->makePartial(); + $serviceMock->shouldReceive('isRecurrentPricing')->atLeast()->once()->andReturn(false); + + $serviceHostingServiceMock = Mockery::mock(Box\Mod\Servicehosting\Service::class)->shouldIgnoreMissing(); + + $productService = new ProductService(); + $di = container(); + $di['db'] = $dbMock; + $di['events_manager'] = $eventMock; + $di['mod_service'] = $di->protect(function ($name) use ($serviceHostingServiceMock, $productService) { + if ($name === 'Product') { + return $productService; + } + + return $serviceHostingServiceMock; + }); + $productService->setDi($di); + $serviceMock->setDi($di); + + expect(fn () => $serviceMock->addItem($cartModel, $productModel, ['transfer_sld' => 'example', 'transfer_tld' => '.net'])) + ->toThrow(FOSSBilling\InformationException::class, 'This domain is already in the cart.'); +}); + +test('addItem rejects duplicate domain nested', function (): void { + $cartModel = new Model_Cart(); + $cartModel->loadBean(new Tests\Helpers\DummyBean()); + $cartModel->id = 3; + + $productModel = createProductEntity(type: 'hosting'); + + // An existing hosting cart item stores the domain under the nested 'domain' key. + $existingCartProduct = new Model_CartProduct(); + $existingCartProduct->loadBean(new Tests\Helpers\DummyBean()); + $existingCartProduct->config = json_encode([ + 'domain' => ['register_sld' => 'mysite', 'register_tld' => '.org'], + ]); + + $dbMock = Mockery::mock(Box_Database::class); + $dbMock->shouldReceive('find')->atLeast()->once()->with('CartProduct', Mockery::any(), Mockery::any())->andReturn([$existingCartProduct]); + + $eventMock = Mockery::mock(Box_EventManager::class)->shouldIgnoreMissing(); + $eventMock->shouldReceive('fire')->atLeast()->once(); + + $serviceMock = Mockery::mock(Service::class)->makePartial(); + $serviceMock->shouldReceive('isRecurrentPricing')->atLeast()->once()->andReturn(false); + + $serviceHostingServiceMock = Mockery::mock(Box\Mod\Servicehosting\Service::class)->shouldIgnoreMissing(); + + $productService = new ProductService(); + $di = container(); + $di['db'] = $dbMock; + $di['events_manager'] = $eventMock; + $di['mod_service'] = $di->protect(function ($name) use ($serviceHostingServiceMock, $productService) { + if ($name === 'Product') { + return $productService; + } + + return $serviceHostingServiceMock; + }); + $productService->setDi($di); + $serviceMock->setDi($di); + + expect(fn () => $serviceMock->addItem($cartModel, $productModel, [ + 'domain' => ['register_sld' => 'mysite', 'register_tld' => '.org'], + ]))->toThrow(FOSSBilling\InformationException::class, 'This domain is already in the cart.'); +}); + +test('addItem for hosting type returns true', function (): void { + $cartModel = new Model_Cart(); + $cartModel->loadBean(new Tests\Helpers\DummyBean()); + + $productModel = createProductEntity(type: 'hosting'); + + $data = []; + + $eventMock = Mockery::mock(Box_EventManager::class)->shouldIgnoreMissing(); + $eventMock->shouldReceive('fire')->atLeast()->once(); + + $productDomainModel = createProductEntity(type: 'domain'); + $domainProduct = ['config' => [], 'product' => $productDomainModel]; + + $serviceHostingServiceMock = Mockery::mock(Box\Mod\Servicehosting\Service::class)->shouldIgnoreMissing(); + $serviceHostingServiceMock->shouldReceive('getDomainProductFromConfig')->atLeast()->once()->andReturn($domainProduct); + $serviceHostingServiceMock->shouldReceive('attachOrderConfig')->atLeast()->once()->andReturn([]); + + $serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods(); + $serviceMock->shouldReceive('isRecurrentPricing')->atLeast()->once()->andReturn(false); + $serviceMock->shouldReceive('isStockAvailable')->atLeast()->once()->andReturn(true); + $serviceMock->shouldReceive('addProduct')->atLeast()->once(); + + $dbMock = Mockery::mock(Box_Database::class); + $dbMock->shouldReceive('find')->atLeast()->once()->andReturn([]); + + $productService = new ProductService(); + $di = container(); + $di['db'] = $dbMock; + $di['events_manager'] = $eventMock; + $di['mod_service'] = $di->protect(function ($name) use ($serviceHostingServiceMock, $productService) { + if ($name === 'Product') { + return $productService; + } + + return $serviceHostingServiceMock; + }); + $di['logger'] = new Box_Log(); + + $productService->setDi($di); + $serviceMock->setDi($di); + $result = $serviceMock->addItem($cartModel, $productModel, $data); + expect($result)->toBeTrue(); +}); + +test('addItem for license type returns true', function (): void { + $cartModel = new Model_Cart(); + $cartModel->loadBean(new Tests\Helpers\DummyBean()); + + $productModel = createProductEntity(type: 'license'); + + $data = []; + + $eventMock = Mockery::mock(Box_EventManager::class)->shouldIgnoreMissing(); + $eventMock->shouldReceive('fire')->atLeast()->once(); + + $serviceLicenseServiceMock = Mockery::mock(Box\Mod\Servicelicense\Service::class); + $serviceLicenseServiceMock->shouldReceive('attachOrderConfig')->atLeast()->once()->andReturn([]); + $serviceLicenseServiceMock->shouldReceive('validateOrderData')->atLeast()->once()->andReturn(true); + + $serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods(); + $serviceMock->shouldReceive('isRecurrentPricing')->atLeast()->once()->andReturn(false); + $serviceMock->shouldReceive('isStockAvailable')->atLeast()->once()->andReturn(true); + $serviceMock->shouldReceive('addProduct')->atLeast()->once(); + + $dbMock = Mockery::mock(Box_Database::class); + $dbMock->shouldReceive('find')->atLeast()->once()->andReturn([]); + + $productService = new ProductService(); + $di = container(); + $di['events_manager'] = $eventMock; + $di['mod_service'] = $di->protect(function ($name) use ($serviceLicenseServiceMock, $productService) { + if ($name === 'Product') { + return $productService; + } + + return $serviceLicenseServiceMock; + }); + $di['logger'] = new Box_Log(); + $di['db'] = $dbMock; + + $productService->setDi($di); + $serviceMock->setDi($di); + $result = $serviceMock->addItem($cartModel, $productModel, $data); + expect($result)->toBeTrue(); +}); + +test('addItem for custom type returns true', function (): void { + $cartModel = new Model_Cart(); + $cartModel->loadBean(new Tests\Helpers\DummyBean()); + + $productModel = createProductEntity(type: 'custom'); + + $data = []; + + $eventMock = Mockery::mock(Box_EventManager::class)->shouldIgnoreMissing(); + $eventMock->shouldReceive('fire')->atLeast()->once(); + + $serviceCustomServiceMock = Mockery::mock(Box\Mod\Servicecustom\Service::class); + $serviceCustomServiceMock->shouldReceive('validateCustomForm')->atLeast()->once(); + + $serviceMock = Mockery::mock(Service::class)->makePartial(); + $serviceMock->shouldReceive('isRecurrentPricing')->atLeast()->once()->andReturn(false); + $serviceMock->shouldReceive('isStockAvailable')->atLeast()->once()->andReturn(true); + + $dbMock = Mockery::mock(Box_Database::class); + $dbMock->shouldReceive('find')->atLeast()->once()->andReturn([]); + $cartProduct = new Model_CartProduct(); + $cartProduct->loadBean(new Tests\Helpers\DummyBean()); + $dbMock->shouldReceive('dispense')->atLeast()->once()->andReturn($cartProduct); + $dbMock->shouldReceive('store')->atLeast()->once(); + + $productService = new ProductService(); + $di = container(); + $di['events_manager'] = $eventMock; + $di['mod_service'] = $di->protect(function ($name) use ($serviceCustomServiceMock, $productService) { + if ($name === 'Product') { + return $productService; + } + + return $serviceCustomServiceMock; + }); + $di['logger'] = new Box_Log(); + $di['db'] = $dbMock; + + $productService->setDi($di); + $serviceMock->setDi($di); + $result = $serviceMock->addItem($cartModel, $productModel, $data); + expect($result)->toBeTrue(); +}); + +test('toApiArray returns expected structure', function (): void { $cartModel = new Model_Cart(); $cartModel->loadBean(new Tests\Helpers\DummyBean()); $cartProductModel = new Model_CartProduct(); $cartProductModel->loadBean(new Tests\Helpers\DummyBean()); - $serviceMock = Mockery::mock(Box\Mod\Cart\Service::class)->makePartial(); - $serviceMock->shouldReceive('getCartProducts') - ->atLeast()->once() - ->andReturn([$cartProductModel]); - + $serviceMock = Mockery::mock(Service::class)->makePartial(); + $serviceMock->shouldReceive('getCartProducts')->atLeast()->once()->andReturn([$cartProductModel]); $cartProductApiArray = [ 'total' => 1, 'setup_price' => 0, 'discount' => 0, ]; - $serviceMock->shouldReceive('cartProductToApiArray') - ->atLeast()->once() - ->andReturn($cartProductApiArray); + $serviceMock->shouldReceive('cartProductToApiArray')->atLeast()->once()->andReturn($cartProductApiArray); - $currencyServiceMock = Mockery::mock(Box\Mod\Currency\Service::class); - $currencyModelMock = Mockery::mock(Box\Mod\Currency\Entity\Currency::class); - $currencyModelMock->shouldReceive('toApiArray') - ->atLeast()->once() - ->andReturn([]); + $currencyService = Mockery::mock(CurrencyService::class)->shouldIgnoreMissing(); - $currencyRepositoryMock = Mockery::mock(Box\Mod\Currency\Repository\CurrencyRepository::class)->shouldIgnoreMissing(); - $currencyRepositoryMock->shouldReceive('find') - ->atLeast()->once() - ->andReturn($currencyModelMock); + $dbMock = Mockery::mock(Box_Database::class)->shouldIgnoreMissing(); + $currencyModel = Mockery::mock(Currency::class)->shouldIgnoreMissing(); + $currencyModel->shouldReceive('toApiArray')->andReturn([]); - $currencyServiceMock->shouldReceive('getCurrencyRepository') - ->atLeast()->once() - ->andReturn($currencyRepositoryMock); + $currencyRepositoryMock = Mockery::mock(CurrencyRepository::class)->makePartial(); + $currencyRepositoryMock->shouldReceive('find')->atLeast()->once()->andReturn($currencyModel); - $di = container(); - $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $currencyServiceMock); + $currencyService->shouldReceive('getCurrencyRepository')->atLeast()->once()->andReturn($currencyRepositoryMock); + + $di = new Pimple\Container(); + $di['db'] = $dbMock; + $di['mod_service'] = $di->protect(fn () => $currencyService); $serviceMock->setDi($di); @@ -1121,13 +1376,11 @@ test('to api array', function (): void { 'currency' => [], 'subtotal' => 1, ]; - expect($result)->toBeArray(); expect($result)->toEqual($expected); }); -test('get product discount with promo', function (): void { - $service = new Box\Mod\Cart\Service(); +test('getProductDiscount returns discount array', function (): void { $cartProductModel = new Model_CartProduct(); $cartProductModel->loadBean(new Tests\Helpers\DummyBean()); @@ -1135,29 +1388,22 @@ test('get product discount with promo', function (): void { $modelCart->loadBean(new Tests\Helpers\DummyBean()); $modelCart->promo_id = 1; - $promoModel = new Model_Promo(); - $promoModel->loadBean(new Tests\Helpers\DummyBean()); + $promoModel = new Promo(); $discountPrice = 25; - $dbMock = Mockery::mock('\Box_Database'); - $dbMock->shouldReceive('load') - ->atLeast()->once() - ->andReturn($modelCart); - $dbMock->shouldReceive('getExistingModelById') - ->atLeast()->once() - ->andReturn($promoModel); + $dbMock = Mockery::mock(Box_Database::class); + $dbMock->shouldReceive('load')->atLeast()->once()->with('Cart', Mockery::any())->andReturn($modelCart); $di = container(); $di['db'] = $dbMock; + $productService = Mockery::mock(ProductService::class)->shouldIgnoreMissing(); + $productService->shouldReceive('findPromoById')->once()->with(1)->andReturn($promoModel); + $di['mod_service'] = $di->protect(fn () => $productService); - $serviceMock = Mockery::mock(Box\Mod\Cart\Service::class)->makePartial()->shouldAllowMockingProtectedMethods(); - $serviceMock->shouldReceive('getRelatedItemsDiscount') - ->atLeast()->once() - ->andReturn(0); - $serviceMock->shouldReceive('getItemPromoDiscount') - ->atLeast()->once() - ->andReturn($discountPrice); + $serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods(); + $serviceMock->shouldReceive('getRelatedItemsDiscount')->atLeast()->once()->andReturn(0); + $serviceMock->shouldReceive('getItemPromoDiscount')->atLeast()->once()->andReturn($discountPrice); $serviceMock->setDi($di); $setupPrice = 0; @@ -1165,32 +1411,25 @@ test('get product discount with promo', function (): void { expect($result)->toBeArray(); expect($result[0])->toEqual($discountPrice); - expect($result[1])->toEqual(0); + $discountSetup = 0; + expect($result[1])->toEqual($discountSetup); }); -test('get product discount with no promo', function (): void { - $service = new Box\Mod\Cart\Service(); +test('getProductDiscount returns zeros when no promo', function (): void { $cartProductModel = new Model_CartProduct(); $cartProductModel->loadBean(new Tests\Helpers\DummyBean()); $modelCart = new Model_Cart(); $modelCart->loadBean(new Tests\Helpers\DummyBean()); - $promoModel = new Model_Promo(); - $promoModel->loadBean(new Tests\Helpers\DummyBean()); - - $dbMock = Mockery::mock('\Box_Database'); - $dbMock->shouldReceive('load') - ->atLeast()->once() - ->andReturn($modelCart); + $dbMock = Mockery::mock(Box_Database::class); + $dbMock->shouldReceive('load')->atLeast()->once()->with('Cart', Mockery::any())->andReturn($modelCart); $di = container(); $di['db'] = $dbMock; - $serviceMock = Mockery::mock(Box\Mod\Cart\Service::class)->makePartial()->shouldAllowMockingProtectedMethods(); - $serviceMock->shouldReceive('getRelatedItemsDiscount') - ->atLeast()->once() - ->andReturn(0); + $serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods(); + $serviceMock->shouldReceive('getRelatedItemsDiscount')->atLeast()->once()->andReturn(0); $serviceMock->setDi($di); $setupPrice = 0; @@ -1201,8 +1440,7 @@ test('get product discount with no promo', function (): void { expect($result[1])->toEqual(0); }); -test('get product discount with product qty set and free setup', function (): void { - $service = new Box\Mod\Cart\Service(); +test('getProductDiscount returns free setup discount', function (): void { $cartProductModel = new Model_CartProduct(); $cartProductModel->loadBean(new Tests\Helpers\DummyBean()); @@ -1210,30 +1448,22 @@ test('get product discount with product qty set and free setup', function (): vo $modelCart->loadBean(new Tests\Helpers\DummyBean()); $modelCart->promo_id = 1; - $promoModel = new Model_Promo(); - $promoModel->loadBean(new Tests\Helpers\DummyBean()); - $promoModel->freesetup = 1; + $promoModel = new Promo(); + $promoModel->setFreeSetup(true); $discountPrice = 25; - $dbMock = Mockery::mock('\Box_Database'); - $dbMock->shouldReceive('load') - ->atLeast()->once() - ->andReturn($modelCart); - $dbMock->shouldReceive('getExistingModelById') - ->atLeast()->once() - ->andReturn($promoModel); - + $dbMock = Mockery::mock(Box_Database::class); + $dbMock->shouldReceive('load')->atLeast()->once()->with('Cart', Mockery::any())->andReturn($modelCart); $di = container(); $di['db'] = $dbMock; + $productService = Mockery::mock(ProductService::class)->shouldIgnoreMissing(); + $productService->shouldReceive('findPromoById')->once()->with(1)->andReturn($promoModel); + $di['mod_service'] = $di->protect(fn () => $productService); - $serviceMock = Mockery::mock(Box\Mod\Cart\Service::class)->makePartial()->shouldAllowMockingProtectedMethods(); - $serviceMock->shouldReceive('getRelatedItemsDiscount') - ->atLeast()->once() - ->andReturn(0); - $serviceMock->shouldReceive('getItemPromoDiscount') - ->atLeast()->once() - ->andReturn($discountPrice); + $serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods(); + $serviceMock->shouldReceive('getRelatedItemsDiscount')->atLeast()->once()->andReturn(0); + $serviceMock->shouldReceive('getItemPromoDiscount')->atLeast()->once()->andReturn($discountPrice); $serviceMock->setDi($di); $setupPrice = 25; @@ -1241,66 +1471,51 @@ test('get product discount with product qty set and free setup', function (): vo expect($result)->toBeArray(); expect($result[0])->toEqual($discountPrice); - expect($result[1])->toEqual($setupPrice); + $discountSetup = $setupPrice; + expect($result[1])->toEqual($discountSetup); }); -dataset('isPromoAvailableForClientGroupProvider', function () { - $promo1 = new Model_Promo(); - $promo1->loadBean(new Tests\Helpers\DummyBean()); - $promo1->client_groups = json_encode([]); +test('isPromoAvailableForClientGroup returns expected result', function (Promo $promo, ?Model_Client $client, bool $expectedResult): void { + $productService = Mockery::mock(ProductService::class); + $productService->shouldReceive('isPromoAvailableForClientGroup')->once()->with($promo)->andReturn($expectedResult); - $client1 = new Model_Client(); - $client1->loadBean(new Tests\Helpers\DummyBean()); - - $promo2 = new Model_Promo(); - $promo2->loadBean(new Tests\Helpers\DummyBean()); - $promo2->client_groups = json_encode([1, 2]); - - $client2 = new Model_Client(); - $client2->loadBean(new Tests\Helpers\DummyBean()); - $client2->client_group_id = null; - - $promo3 = new Model_Promo(); - $promo3->loadBean(new Tests\Helpers\DummyBean()); - $promo3->client_groups = json_encode([1, 2]); - - $client3 = new Model_Client(); - $client3->loadBean(new Tests\Helpers\DummyBean()); - $client3->client_group_id = 3; - - $promo4 = new Model_Promo(); - $promo4->loadBean(new Tests\Helpers\DummyBean()); - $promo4->client_groups = json_encode([1, 2]); - - $client4 = new Model_Client(); - $client4->loadBean(new Tests\Helpers\DummyBean()); - $client4->client_group_id = 2; - - $promo5 = new Model_Promo(); - $promo5->loadBean(new Tests\Helpers\DummyBean()); - $promo5->client_groups = json_encode([]); - - $promo6 = new Model_Promo(); - $promo6->loadBean(new Tests\Helpers\DummyBean()); - $promo6->client_groups = json_encode([1, 2]); - - return [ - 'no client groups set for promo - any client valid' => [$promo1, $client1, true], - 'client groups set for promo - client not in any group' => [$promo2, $client2, false], - 'client groups set for promo - client group not included' => [$promo3, $client3, false], - 'client groups set for promo - applies to client' => [$promo4, $client4, true], - 'no client groups set - guest valid' => [$promo5, null, true], - 'client groups set - guest invalid' => [$promo6, null, false], - ]; -}); - -test('is promo available for client group', function (Model_Promo $promo, ?Model_Client $client, bool $expectedResult): void { - $service = new Box\Mod\Cart\Service(); $di = container(); $di['loggedin_client'] = $client; + $di['mod_service'] = $di->protect(fn () => $productService); + $service = new Service(); $service->setDi($di); $result = $service->isPromoAvailableForClientGroup($promo); expect($result)->toEqual($expectedResult); -})->with('isPromoAvailableForClientGroupProvider'); +})->with([ + [createPromoEntity(1)->setClientGroups(json_encode([])), (function (): Model_Client { + $c = new Model_Client(); + $c->loadBean(new Tests\Helpers\DummyBean()); + + return $c; + })(), true], + [createPromoEntity(2)->setClientGroups(json_encode([1, 2])), (function (): Model_Client { + $c = new Model_Client(); + $c->loadBean(new Tests\Helpers\DummyBean()); + $c->client_group_id = null; + + return $c; + })(), false], + [createPromoEntity(3)->setClientGroups(json_encode([1, 2])), (function (): Model_Client { + $c = new Model_Client(); + $c->loadBean(new Tests\Helpers\DummyBean()); + $c->client_group_id = 3; + + return $c; + })(), false], + [createPromoEntity(4)->setClientGroups(json_encode([1, 2])), (function (): Model_Client { + $c = new Model_Client(); + $c->loadBean(new Tests\Helpers\DummyBean()); + $c->client_group_id = 2; + + return $c; + })(), true], + [createPromoEntity(5)->setClientGroups(json_encode([])), null, true], + [createPromoEntity(6)->setClientGroups(json_encode([1, 2])), null, false], +]); diff --git a/src/modules/Invoice/Service.php b/src/modules/Invoice/Service.php index e8bed4ca1..ea479bc8b 100644 --- a/src/modules/Invoice/Service.php +++ b/src/modules/Invoice/Service.php @@ -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; } diff --git a/src/modules/Invoice/ServiceInvoiceItem.php b/src/modules/Invoice/ServiceInvoiceItem.php index 5157bd865..e9de49e02 100644 --- a/src/modules/Invoice/ServiceInvoiceItem.php +++ b/src/modules/Invoice/ServiceInvoiceItem.php @@ -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, + ); } } diff --git a/src/modules/Invoice/templates/client/mod_invoice_invoice.html.twig b/src/modules/Invoice/templates/client/mod_invoice_invoice.html.twig index b49ea9a94..d465655f2 100644 --- a/src/modules/Invoice/templates/client/mod_invoice_invoice.html.twig +++ b/src/modules/Invoice/templates/client/mod_invoice_invoice.html.twig @@ -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; diff --git a/src/modules/Invoice/tests/Unit/ServiceTaxTest.php b/src/modules/Invoice/tests/Unit/ServiceTaxTest.php index b07cccad5..39a1376ce 100644 --- a/src/modules/Invoice/tests/Unit/ServiceTaxTest.php +++ b/src/modules/Invoice/tests/Unit/ServiceTaxTest.php @@ -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); diff --git a/src/modules/Invoice/tests/Unit/ServiceTest.php b/src/modules/Invoice/tests/Unit/ServiceTest.php index e23dc11cc..1f67ae030 100644 --- a/src/modules/Invoice/tests/Unit/ServiceTest.php +++ b/src/modules/Invoice/tests/Unit/ServiceTest.php @@ -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); diff --git a/src/modules/Order/Api/Admin.php b/src/modules/Order/Api/Admin.php index ccbf1bbc8..b8b6d08c2 100644 --- a/src/modules/Order/Api/Admin.php +++ b/src/modules/Order/Api/Admin.php @@ -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); } diff --git a/src/modules/Order/Api/Client.php b/src/modules/Order/Api/Client.php index 35472278f..f0c80bd97 100644 --- a/src/modules/Order/Api/Client.php +++ b/src/modules/Order/Api/Client.php @@ -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); } /** diff --git a/src/modules/Order/Service.php b/src/modules/Order/Service.php index e94bea753..8daf80d4b 100644 --- a/src/modules/Order/Service.php +++ b/src/modules/Order/Service.php @@ -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(); + } } diff --git a/src/modules/Order/templates/admin/mod_order_index.html.twig b/src/modules/Order/templates/admin/mod_order_index.html.twig index 331bfb673..2cf4d5047 100644 --- a/src/modules/Order/templates/admin/mod_order_index.html.twig +++ b/src/modules/Order/templates/admin/mod_order_index.html.twig @@ -131,6 +131,12 @@ {{ mf.selectbox('product_id', admin.product_get_pairs, request.product_id, 0, 'All Products'|trans) }} +
+
+ + +
+
diff --git a/src/modules/Order/tests/Unit/Api/AdminTest.php b/src/modules/Order/tests/Unit/Api/AdminTest.php index a59771e91..9fc0ba7ec 100644 --- a/src/modules/Order/tests/Unit/Api/AdminTest.php +++ b/src/modules/Order/tests/Unit/Api/AdminTest.php @@ -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(); }); diff --git a/src/modules/Order/tests/Unit/Api/ClientTest.php b/src/modules/Order/tests/Unit/Api/ClientTest.php index d070fbb50..b7e4dd238 100644 --- a/src/modules/Order/tests/Unit/Api/ClientTest.php +++ b/src/modules/Order/tests/Unit/Api/ClientTest.php @@ -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); }); diff --git a/src/modules/Order/tests/Unit/ServiceTest.php b/src/modules/Order/tests/Unit/ServiceTest.php index 8639160f0..8b27c0cc1 100644 --- a/src/modules/Order/tests/Unit/ServiceTest.php +++ b/src/modules/Order/tests/Unit/ServiceTest.php @@ -11,50 +11,41 @@ declare(strict_types=1); use Box\Mod\Order\Service; +use Box\Mod\Product\Entity\Product; use function Tests\Helpers\container; -class OrderPdoMock extends PDO +function orderServiceCreateProductEntity(?int $id = null, ?string $type = null): Product { - public function __construct() - { + $product = new Product(); + if ($id !== null) { + $reflection = new ReflectionProperty($product, 'id'); + $reflection->setAccessible(true); + $reflection->setValue($product, $id); } + if ($type !== null) { + $product->setType($type); + } + + return $product; } -class OrderPdoStatementsMock extends PDOStatement -{ - public function __construct() - { - } -} - -test('gets dependency injection container', function (): void { +test('counter returns status counts', function (): void { $service = new Service(); - $di = container(); - $service->setDi($di); - $getDi = $service->getDi(); - expect($getDi)->toBe($di); -}); -test('counts orders by status', function (): void { - $service = new Service(); - $counter = [ - Model_ClientOrder::STATUS_ACTIVE => 1, - ]; - $dbMock = Mockery::mock('\Box_Database'); - $dbMock->shouldReceive('getAssoc') - ->atLeast()->once() - ->andReturn($counter); + $counter = [Model_ClientOrder::STATUS_ACTIVE => 1]; + $dbMock = Mockery::mock(Box_Database::class); + $dbMock->shouldReceive('getAssoc')->atLeast()->once()->andReturn($counter); $di = container(); $di['db'] = $dbMock; - $service->setDi($di); $result = $service->counter(); + expect($result)->toBeArray(); expect($result)->toHaveKey('total'); - expect($result['total'])->toBe(array_sum($counter)); + expect($result['total'])->toEqual(array_sum($counter)); expect($result)->toHaveKey(Model_ClientOrder::STATUS_PENDING_SETUP); expect($result)->toHaveKey(Model_ClientOrder::STATUS_FAILED_SETUP); expect($result)->toHaveKey(Model_ClientOrder::STATUS_ACTIVE); @@ -62,26 +53,20 @@ test('counts orders by status', function (): void { expect($result)->toHaveKey(Model_ClientOrder::STATUS_CANCELED); }); -test('fires event after admin activates order', function (): void { +test('onAfterAdminOrderActivate fires template', function (): void { $params = ['id' => 1]; - $eventMock = Mockery::mock('\Box_Event'); - $eventMock->shouldReceive('getParameters') - ->atLeast()->once() - ->andReturn($params); + $eventMock = Mockery::mock(Box_Event::class); + $eventMock->shouldReceive('getParameters')->atLeast()->once()->andReturn($params); $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); $emailServiceMock = Mockery::mock(Box\Mod\Email\Service::class); - $emailServiceMock->shouldReceive('sendTemplate') - ->atLeast()->once() - ->andReturn(true); + $emailServiceMock->shouldReceive('sendTemplate')->atLeast()->once()->andReturn(true); $orderArr = [ 'id' => 1, @@ -90,12 +75,9 @@ test('fires event after admin activates order', function (): void { ]; $serviceMock = Mockery::mock(Service::class)->makePartial(); - $serviceMock->shouldReceive('getOrderServiceData') - ->atLeast()->once() - ->andReturn([]); - $serviceMock->shouldReceive('toApiArray') - ->atLeast()->once() - ->andReturn($orderArr); + $serviceMock->shouldAllowMockingProtectedMethods(); + $serviceMock->shouldReceive('getOrderServiceData')->atLeast()->once()->andReturn([]); + $serviceMock->shouldReceive('toApiArray')->atLeast()->once()->andReturn($orderArr); $admin = new Model_Admin(); $admin->loadBean(new Tests\Helpers\DummyBean()); @@ -112,35 +94,28 @@ test('fires event after admin activates order', function (): void { } }); - $eventMock->shouldReceive('getDi') - ->atLeast()->once() - ->andReturn($di); - + $eventMock->shouldReceive('getDi')->atLeast()->once()->andReturn($di); $serviceMock->setDi($di); $serviceMock->onAfterAdminOrderActivate($eventMock); }); -test('logs exception when email fails on activate', function (): void { +test('onAfterAdminOrderActivate logs exceptions', function (): void { $params = ['id' => 1]; - $eventMock = Mockery::mock('\Box_Event'); - $eventMock->shouldReceive('getParameters') - ->atLeast()->once() - ->andReturn($params); + $eventMock = Mockery::mock(Box_Event::class); + $eventMock->shouldReceive('getParameters')->atLeast()->once()->andReturn($params); $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); $emailServiceMock = Mockery::mock(Box\Mod\Email\Service::class); $emailServiceMock->shouldReceive('sendTemplate') ->atLeast()->once() - ->andThrow(new Exception('Email send failure')); + ->andThrow(new Exception('PHPUnit controlled exception')); $orderArr = [ 'id' => 1, @@ -149,18 +124,13 @@ test('logs exception when email fails on activate', function (): void { ]; $serviceMock = Mockery::mock(Service::class)->makePartial(); - $serviceMock->shouldReceive('getOrderServiceData') - ->atLeast()->once() - ->andReturn([]); - $serviceMock->shouldReceive('toApiArray') - ->atLeast()->once() - ->andReturn($orderArr); + $serviceMock->shouldAllowMockingProtectedMethods(); + $serviceMock->shouldReceive('getOrderServiceData')->atLeast()->once()->andReturn([]); + $serviceMock->shouldReceive('toApiArray')->atLeast()->once()->andReturn($orderArr); $admin = new Model_Admin(); $admin->loadBean(new Tests\Helpers\DummyBean()); - $loggerMock = new Tests\Helpers\TestLogger(); - $di = container(); $di['db'] = $dbMock; $di['loggedin_admin'] = $admin; @@ -172,40 +142,27 @@ test('logs exception when email fails on activate', function (): void { return $serviceMock; } }); - $di['logger'] = $loggerMock; - - $eventMock->shouldReceive('getDi') - ->atLeast()->once() - ->andReturn($di); + $eventMock->shouldReceive('getDi')->atLeast()->once()->andReturn($di); $serviceMock->setDi($di); $serviceMock->onAfterAdminOrderActivate($eventMock); - - expect($loggerMock->calls)->toHaveCount(1); - expect($loggerMock->calls[0]['method'])->toBe('error'); }); -test('logs exception when email fails on renew', function (): void { +test('onAfterAdminOrderRenew fires template', function (): void { $params = ['id' => 1]; - $eventMock = Mockery::mock('\Box_Event'); - $eventMock->shouldReceive('getParameters') - ->atLeast()->once() - ->andReturn($params); + $eventMock = Mockery::mock(Box_Event::class); + $eventMock->shouldReceive('getParameters')->atLeast()->once()->andReturn($params); $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); $emailServiceMock = Mockery::mock(Box\Mod\Email\Service::class); - $emailServiceMock->shouldReceive('sendTemplate') - ->atLeast()->once() - ->andThrow(new Exception('Email send failure')); + $emailServiceMock->shouldReceive('sendTemplate')->atLeast()->once()->andReturn(true); $orderArr = [ 'id' => 1, @@ -214,18 +171,13 @@ test('logs exception when email fails on renew', function (): void { ]; $serviceMock = Mockery::mock(Service::class)->makePartial(); - $serviceMock->shouldReceive('getOrderServiceData') - ->atLeast()->once() - ->andReturn([]); - $serviceMock->shouldReceive('toApiArray') - ->atLeast()->once() - ->andReturn($orderArr); + $serviceMock->shouldAllowMockingProtectedMethods(); + $serviceMock->shouldReceive('getOrderServiceData')->atLeast()->once()->andReturn([]); + $serviceMock->shouldReceive('toApiArray')->atLeast()->once()->andReturn($orderArr); $admin = new Model_Admin(); $admin->loadBean(new Tests\Helpers\DummyBean()); - $loggerMock = new Tests\Helpers\TestLogger(); - $di = container(); $di['db'] = $dbMock; $di['loggedin_admin'] = $admin; @@ -237,38 +189,29 @@ test('logs exception when email fails on renew', function (): void { return $serviceMock; } }); - $di['logger'] = $loggerMock; + $serviceMock->setDi($di); - $eventMock->shouldReceive('getDi') - ->atLeast()->once() - ->andReturn($di); + $eventMock->shouldReceive('getDi')->atLeast()->once()->andReturn($di); $serviceMock->onAfterAdminOrderRenew($eventMock); - - expect($loggerMock->calls)->toHaveCount(1); - expect($loggerMock->calls[0]['method'])->toBe('error'); }); -test('fires event after admin suspends order', function (): void { +test('onAfterAdminOrderRenew logs exceptions', function (): void { $params = ['id' => 1]; - $eventMock = Mockery::mock('\Box_Event'); - $eventMock->shouldReceive('getParameters') - ->atLeast()->once() - ->andReturn($params); + $eventMock = Mockery::mock(Box_Event::class); + $eventMock->shouldReceive('getParameters')->atLeast()->once()->andReturn($params); $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); $emailServiceMock = Mockery::mock(Box\Mod\Email\Service::class); $emailServiceMock->shouldReceive('sendTemplate') ->atLeast()->once() - ->andReturn(true); + ->andThrow(new Exception('PHPUnit controlled exception')); $orderArr = [ 'id' => 1, @@ -277,12 +220,9 @@ test('fires event after admin suspends order', function (): void { ]; $serviceMock = Mockery::mock(Service::class)->makePartial(); - $serviceMock->shouldReceive('getOrderServiceData') - ->atLeast()->once() - ->andReturn([]); - $serviceMock->shouldReceive('toApiArray') - ->atLeast()->once() - ->andReturn($orderArr); + $serviceMock->shouldAllowMockingProtectedMethods(); + $serviceMock->shouldReceive('getOrderServiceData')->atLeast()->once()->andReturn([]); + $serviceMock->shouldReceive('toApiArray')->atLeast()->once()->andReturn($orderArr); $admin = new Model_Admin(); $admin->loadBean(new Tests\Helpers\DummyBean()); @@ -298,34 +238,76 @@ test('fires event after admin suspends order', function (): void { return $serviceMock; } }); + $serviceMock->setDi($di); - $eventMock->shouldReceive('getDi') - ->atLeast()->once() - ->andReturn($di); + $eventMock->shouldReceive('getDi')->atLeast()->once()->andReturn($di); + + $serviceMock->onAfterAdminOrderRenew($eventMock); +}); + +test('onAfterAdminOrderSuspend fires template', function (): void { + $params = ['id' => 1]; + + $eventMock = Mockery::mock(Box_Event::class); + $eventMock->shouldReceive('getParameters')->atLeast()->once()->andReturn($params); + + $order = new Model_ClientOrder(); + $order->loadBean(new Tests\Helpers\DummyBean()); + + $dbMock = Mockery::mock(Box_Database::class); + $dbMock->shouldReceive('getExistingModelById')->atLeast()->once()->andReturn($order); + + $emailServiceMock = Mockery::mock(Box\Mod\Email\Service::class); + $emailServiceMock->shouldReceive('sendTemplate')->atLeast()->once()->andReturn(true); + + $orderArr = [ + 'id' => 1, + 'client' => ['id' => 1], + 'service_type' => 'domain', + ]; + + $serviceMock = Mockery::mock(Service::class)->makePartial(); + $serviceMock->shouldAllowMockingProtectedMethods(); + $serviceMock->shouldReceive('getOrderServiceData')->atLeast()->once()->andReturn([]); + $serviceMock->shouldReceive('toApiArray')->atLeast()->once()->andReturn($orderArr); + + $admin = new Model_Admin(); + $admin->loadBean(new Tests\Helpers\DummyBean()); + + $di = container(); + $di['db'] = $dbMock; + $di['loggedin_admin'] = $admin; + $di['mod_service'] = $di->protect(function ($serviceName) use ($emailServiceMock, $serviceMock) { + if ($serviceName == 'email') { + return $emailServiceMock; + } + if ($serviceName == 'order') { + return $serviceMock; + } + }); + + $serviceMock->setDi($di); + $eventMock->shouldReceive('getDi')->atLeast()->once()->andReturn($di); $serviceMock->onAfterAdminOrderSuspend($eventMock); }); -test('logs exception when email fails on suspend', function (): void { +test('onAfterAdminOrderSuspend logs exceptions', function (): void { $params = ['id' => 1]; - $eventMock = Mockery::mock('\Box_Event'); - $eventMock->shouldReceive('getParameters') - ->atLeast()->once() - ->andReturn($params); + $eventMock = Mockery::mock(Box_Event::class); + $eventMock->shouldReceive('getParameters')->atLeast()->once()->andReturn($params); $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); $emailServiceMock = Mockery::mock(Box\Mod\Email\Service::class); $emailServiceMock->shouldReceive('sendTemplate') ->atLeast()->once() - ->andThrow(new Exception('Email send failure')); + ->andThrow(new Exception('PHPUnit controlled exception')); $orderArr = [ 'id' => 1, @@ -334,18 +316,13 @@ test('logs exception when email fails on suspend', function (): void { ]; $serviceMock = Mockery::mock(Service::class)->makePartial(); - $serviceMock->shouldReceive('getOrderServiceData') - ->atLeast()->once() - ->andReturn([]); - $serviceMock->shouldReceive('toApiArray') - ->atLeast()->once() - ->andReturn($orderArr); + $serviceMock->shouldAllowMockingProtectedMethods(); + $serviceMock->shouldReceive('getOrderServiceData')->atLeast()->once()->andReturn([]); + $serviceMock->shouldReceive('toApiArray')->atLeast()->once()->andReturn($orderArr); $admin = new Model_Admin(); $admin->loadBean(new Tests\Helpers\DummyBean()); - $loggerMock = new Tests\Helpers\TestLogger(); - $di = container(); $di['db'] = $dbMock; $di['loggedin_admin'] = $admin; @@ -357,38 +334,27 @@ test('logs exception when email fails on suspend', function (): void { return $serviceMock; } }); - $di['logger'] = $loggerMock; + $serviceMock->setDi($di); - $eventMock->shouldReceive('getDi') - ->atLeast()->once() - ->andReturn($di); + $eventMock->shouldReceive('getDi')->atLeast()->once()->andReturn($di); $serviceMock->onAfterAdminOrderSuspend($eventMock); - - expect($loggerMock->calls)->toHaveCount(1); - expect($loggerMock->calls[0]['method'])->toBe('error'); }); -test('fires event after admin unsuspends order', function (): void { +test('onAfterAdminOrderUnsuspend fires template', function (): void { $params = ['id' => 1]; - $eventMock = Mockery::mock('\Box_Event'); - $eventMock->shouldReceive('getParameters') - ->atLeast()->once() - ->andReturn($params); + $eventMock = Mockery::mock(Box_Event::class); + $eventMock->shouldReceive('getParameters')->atLeast()->once()->andReturn($params); $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); $emailServiceMock = Mockery::mock(Box\Mod\Email\Service::class); - $emailServiceMock->shouldReceive('sendTemplate') - ->atLeast()->once() - ->andReturn(true); + $emailServiceMock->shouldReceive('sendTemplate')->atLeast()->once()->andReturn(true); $orderArr = [ 'id' => 1, @@ -397,12 +363,9 @@ test('fires event after admin unsuspends order', function (): void { ]; $serviceMock = Mockery::mock(Service::class)->makePartial(); - $serviceMock->shouldReceive('getOrderServiceData') - ->atLeast()->once() - ->andReturn([]); - $serviceMock->shouldReceive('toApiArray') - ->atLeast()->once() - ->andReturn($orderArr); + $serviceMock->shouldAllowMockingProtectedMethods(); + $serviceMock->shouldReceive('getOrderServiceData')->atLeast()->once()->andReturn([]); + $serviceMock->shouldReceive('toApiArray')->atLeast()->once()->andReturn($orderArr); $admin = new Model_Admin(); $admin->loadBean(new Tests\Helpers\DummyBean()); @@ -418,34 +381,29 @@ test('fires event after admin unsuspends order', function (): void { return $serviceMock; } }); + $serviceMock->setDi($di); - $eventMock->shouldReceive('getDi') - ->atLeast()->once() - ->andReturn($di); + $eventMock->shouldReceive('getDi')->atLeast()->once()->andReturn($di); $serviceMock->onAfterAdminOrderUnsuspend($eventMock); }); -test('logs exception when email fails on unsuspend', function (): void { +test('onAfterAdminOrderUnsuspend logs exceptions', function (): void { $params = ['id' => 1]; - $eventMock = Mockery::mock('\Box_Event'); - $eventMock->shouldReceive('getParameters') - ->atLeast()->once() - ->andReturn($params); + $eventMock = Mockery::mock(Box_Event::class); + $eventMock->shouldReceive('getParameters')->atLeast()->once()->andReturn($params); $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); $emailServiceMock = Mockery::mock(Box\Mod\Email\Service::class); $emailServiceMock->shouldReceive('sendTemplate') ->atLeast()->once() - ->andThrow(new Exception('Email send failure')); + ->andThrow(new Exception('PHPUnit controlled exception')); $orderArr = [ 'id' => 1, @@ -454,18 +412,13 @@ test('logs exception when email fails on unsuspend', function (): void { ]; $serviceMock = Mockery::mock(Service::class)->makePartial(); - $serviceMock->shouldReceive('getOrderServiceData') - ->atLeast()->once() - ->andReturn([]); - $serviceMock->shouldReceive('toApiArray') - ->atLeast()->once() - ->andReturn($orderArr); + $serviceMock->shouldAllowMockingProtectedMethods(); + $serviceMock->shouldReceive('getOrderServiceData')->atLeast()->once()->andReturn([]); + $serviceMock->shouldReceive('toApiArray')->atLeast()->once()->andReturn($orderArr); $admin = new Model_Admin(); $admin->loadBean(new Tests\Helpers\DummyBean()); - $loggerMock = new Tests\Helpers\TestLogger(); - $di = container(); $di['db'] = $dbMock; $di['loggedin_admin'] = $admin; @@ -477,38 +430,27 @@ test('logs exception when email fails on unsuspend', function (): void { return $serviceMock; } }); - $di['logger'] = $loggerMock; + $serviceMock->setDi($di); - $eventMock->shouldReceive('getDi') - ->atLeast()->once() - ->andReturn($di); + $eventMock->shouldReceive('getDi')->atLeast()->once()->andReturn($di); $serviceMock->onAfterAdminOrderUnsuspend($eventMock); - - expect($loggerMock->calls)->toHaveCount(1); - expect($loggerMock->calls[0]['method'])->toBe('error'); }); -test('fires event after admin cancels order', function (): void { +test('onAfterAdminOrderCancel fires template', function (): void { $params = ['id' => 1]; - $eventMock = Mockery::mock('\Box_Event'); - $eventMock->shouldReceive('getParameters') - ->atLeast()->once() - ->andReturn($params); + $eventMock = Mockery::mock(Box_Event::class); + $eventMock->shouldReceive('getParameters')->atLeast()->once()->andReturn($params); $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); $emailServiceMock = Mockery::mock(Box\Mod\Email\Service::class); - $emailServiceMock->shouldReceive('sendTemplate') - ->atLeast()->once() - ->andReturn(true); + $emailServiceMock->shouldReceive('sendTemplate')->atLeast()->once()->andReturn(true); $orderArr = [ 'id' => 1, @@ -517,9 +459,8 @@ test('fires event after admin cancels order', function (): void { ]; $serviceMock = Mockery::mock(Service::class)->makePartial(); - $serviceMock->shouldReceive('toApiArray') - ->atLeast()->once() - ->andReturn($orderArr); + $serviceMock->shouldAllowMockingProtectedMethods(); + $serviceMock->shouldReceive('toApiArray')->atLeast()->once()->andReturn($orderArr); $admin = new Model_Admin(); $admin->loadBean(new Tests\Helpers\DummyBean()); @@ -535,34 +476,29 @@ test('fires event after admin cancels order', function (): void { return $serviceMock; } }); + $serviceMock->setDi($di); - $eventMock->shouldReceive('getDi') - ->atLeast()->once() - ->andReturn($di); + $eventMock->shouldReceive('getDi')->atLeast()->once()->andReturn($di); $serviceMock->onAfterAdminOrderCancel($eventMock); }); -test('logs exception when email fails on cancel', function (): void { +test('onAfterAdminOrderCancel logs exceptions', function (): void { $params = ['id' => 1]; - $eventMock = Mockery::mock('\Box_Event'); - $eventMock->shouldReceive('getParameters') - ->atLeast()->once() - ->andReturn($params); + $eventMock = Mockery::mock(Box_Event::class); + $eventMock->shouldReceive('getParameters')->atLeast()->once()->andReturn($params); $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); $emailServiceMock = Mockery::mock(Box\Mod\Email\Service::class); $emailServiceMock->shouldReceive('sendTemplate') ->atLeast()->once() - ->andThrow(new Exception('Email send failure')); + ->andThrow(new Exception('PHPUnit controlled exception')); $orderArr = [ 'id' => 1, @@ -571,15 +507,12 @@ test('logs exception when email fails on cancel', function (): void { ]; $serviceMock = Mockery::mock(Service::class)->makePartial(); - $serviceMock->shouldReceive('toApiArray') - ->atLeast()->once() - ->andReturn($orderArr); + $serviceMock->shouldAllowMockingProtectedMethods(); + $serviceMock->shouldReceive('toApiArray')->atLeast()->once()->andReturn($orderArr); $admin = new Model_Admin(); $admin->loadBean(new Tests\Helpers\DummyBean()); - $loggerMock = new Tests\Helpers\TestLogger(); - $di = container(); $di['db'] = $dbMock; $di['loggedin_admin'] = $admin; @@ -591,38 +524,27 @@ test('logs exception when email fails on cancel', function (): void { return $serviceMock; } }); - $di['logger'] = $loggerMock; + $serviceMock->setDi($di); - $eventMock->shouldReceive('getDi') - ->atLeast()->once() - ->andReturn($di); + $eventMock->shouldReceive('getDi')->atLeast()->once()->andReturn($di); $serviceMock->onAfterAdminOrderCancel($eventMock); - - expect($loggerMock->calls)->toHaveCount(1); - expect($loggerMock->calls[0]['method'])->toBe('error'); }); -test('fires event after admin uncancels order', function (): void { +test('onAfterAdminOrderUncancel fires template', function (): void { $params = ['id' => 1]; - $eventMock = Mockery::mock('\Box_Event'); - $eventMock->shouldReceive('getParameters') - ->atLeast()->once() - ->andReturn($params); + $eventMock = Mockery::mock(Box_Event::class); + $eventMock->shouldReceive('getParameters')->atLeast()->once()->andReturn($params); $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); $emailServiceMock = Mockery::mock(Box\Mod\Email\Service::class); - $emailServiceMock->shouldReceive('sendTemplate') - ->atLeast()->once() - ->andReturn(true); + $emailServiceMock->shouldReceive('sendTemplate')->atLeast()->once()->andReturn(true); $orderArr = [ 'id' => 1, @@ -631,12 +553,9 @@ test('fires event after admin uncancels order', function (): void { ]; $serviceMock = Mockery::mock(Service::class)->makePartial(); - $serviceMock->shouldReceive('getOrderServiceData') - ->atLeast()->once() - ->andReturn([]); - $serviceMock->shouldReceive('toApiArray') - ->atLeast()->once() - ->andReturn($orderArr); + $serviceMock->shouldAllowMockingProtectedMethods(); + $serviceMock->shouldReceive('getOrderServiceData')->atLeast()->once()->andReturn([]); + $serviceMock->shouldReceive('toApiArray')->atLeast()->once()->andReturn($orderArr); $admin = new Model_Admin(); $admin->loadBean(new Tests\Helpers\DummyBean()); @@ -652,34 +571,29 @@ test('fires event after admin uncancels order', function (): void { return $serviceMock; } }); + $serviceMock->setDi($di); - $eventMock->shouldReceive('getDi') - ->atLeast()->once() - ->andReturn($di); + $eventMock->shouldReceive('getDi')->atLeast()->once()->andReturn($di); $serviceMock->onAfterAdminOrderUncancel($eventMock); }); -test('logs exception when email fails on uncancel', function (): void { +test('onAfterAdminOrderUncancel logs exceptions', function (): void { $params = ['id' => 1]; - $eventMock = Mockery::mock('\Box_Event'); - $eventMock->shouldReceive('getParameters') - ->atLeast()->once() - ->andReturn($params); + $eventMock = Mockery::mock(Box_Event::class); + $eventMock->shouldReceive('getParameters')->atLeast()->once()->andReturn($params); $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); $emailServiceMock = Mockery::mock(Box\Mod\Email\Service::class); $emailServiceMock->shouldReceive('sendTemplate') ->atLeast()->once() - ->andThrow(new Exception('Email send failure')); + ->andThrow(new Exception('PHPUnit controlled exception')); $orderArr = [ 'id' => 1, @@ -688,18 +602,13 @@ test('logs exception when email fails on uncancel', function (): void { ]; $serviceMock = Mockery::mock(Service::class)->makePartial(); - $serviceMock->shouldReceive('getOrderServiceData') - ->atLeast()->once() - ->andReturn([]); - $serviceMock->shouldReceive('toApiArray') - ->atLeast()->once() - ->andReturn($orderArr); + $serviceMock->shouldAllowMockingProtectedMethods(); + $serviceMock->shouldReceive('getOrderServiceData')->atLeast()->once()->andReturn([]); + $serviceMock->shouldReceive('toApiArray')->atLeast()->once()->andReturn($orderArr); $admin = new Model_Admin(); $admin->loadBean(new Tests\Helpers\DummyBean()); - $loggerMock = new Tests\Helpers\TestLogger(); - $di = container(); $di['db'] = $dbMock; $di['loggedin_admin'] = $admin; @@ -711,194 +620,181 @@ test('logs exception when email fails on uncancel', function (): void { return $serviceMock; } }); - $di['logger'] = $loggerMock; + $serviceMock->setDi($di); - $eventMock->shouldReceive('getDi') - ->atLeast()->once() - ->andReturn($di); + $eventMock->shouldReceive('getDi')->atLeast()->once()->andReturn($di); $serviceMock->onAfterAdminOrderUncancel($eventMock); - - expect($loggerMock->calls)->toHaveCount(1); - expect($loggerMock->calls[0]['method'])->toBe('error'); }); -test('gets order core service', function (): void { - $orderService = new Service(); - $modelService = new Model_ServiceCustom(); +test('getOrderService returns core service', function (): void { + $service = new Model_ServiceCustom(); - $dbMock = Mockery::mock('\Box_Database'); - $dbMock->shouldReceive('findOne') - ->never(); - $dbMock->shouldReceive('load') - ->atLeast()->once() - ->andReturn($modelService); + $dbMock = Mockery::mock(Box_Database::class); + $dbMock->shouldReceive('findOne')->never(); + $dbMock->shouldReceive('load')->atLeast()->once()->andReturn($service); $toolsMock = Mockery::mock(FOSSBilling\Tools::class); - $toolsMock->shouldReceive('to_camel_case') - ->atLeast()->once() - ->andReturn('ServiceCustom'); + $toolsMock->shouldReceive('to_camel_case')->atLeast()->once()->andReturn('ServiceCustom'); $di = container(); $di['db'] = $dbMock; $di['tools'] = $toolsMock; - $orderService->setDi($di); + + $svc = new Service(); + $svc->setDi($di); $order = new Model_ClientOrder(); $order->loadBean(new Tests\Helpers\DummyBean()); $order->service_id = 1; - $order->service_type = Model_ProductTable::CUSTOM; + $order->service_type = Box\Mod\Product\Service::CUSTOM; - $result = $orderService->getOrderService($order); - expect($result)->toBeInstanceOf('Model_ServiceCustom'); + $result = $svc->getOrderService($order); + + expect($result)->toBeInstanceOf(Model_ServiceCustom::class); }); -test('gets order non-core service', function (): void { - $orderService = new Service(); - $modelService = new Model_ServiceCustom(); +test('getOrderService returns non-core service', function (): void { + $service = new Model_ServiceCustom(); - $dbMock = Mockery::mock('\Box_Database'); - $dbMock->shouldReceive('getExistingModelById') - ->never() - ->andReturn($modelService); - $dbMock->shouldReceive('findOne') - ->atLeast()->once() - ->andReturn($modelService); + $dbMock = Mockery::mock(Box_Database::class); + $dbMock->shouldReceive('getExistingModelById')->never(); + $dbMock->shouldReceive('findOne')->atLeast()->once()->andReturn($service); $di = container(); $di['db'] = $dbMock; - $orderService->setDi($di); + + $svc = new Service(); + $svc->setDi($di); $order = new Model_ClientOrder(); $order->loadBean(new Tests\Helpers\DummyBean()); $order->service_id = 1; - $result = $orderService->getOrderService($order); - expect($result)->toBeInstanceOf('Model_ServiceCustom'); + $result = $svc->getOrderService($order); + + expect($result)->toBeInstanceOf(Model_ServiceCustom::class); }); -test('returns null when service id not set', function (): void { - $orderService = new Service(); - $modelService = new Model_ServiceCustom(); +test('getOrderService returns null when service id is not set', function (): void { + $service = new Model_ServiceCustom(); - $dbMock = Mockery::mock('\Box_Database'); - $dbMock->shouldReceive('getExistingModelById') - ->never() - ->andReturn($modelService); - $dbMock->shouldReceive('findOne') - ->never() - ->andReturn($modelService); + $dbMock = Mockery::mock(Box_Database::class); + $dbMock->shouldReceive('getExistingModelById')->never(); + $dbMock->shouldReceive('findOne')->never(); $di = container(); $di['db'] = $dbMock; - $orderService->setDi($di); + + $svc = new Service(); + $svc->setDi($di); $order = new Model_ClientOrder(); $order->loadBean(new Tests\Helpers\DummyBean()); - $result = $orderService->getOrderService($order); + $result = $svc->getOrderService($order); + expect($result)->toBeNull(); }); -test('gets service order', function (): void { - $orderService = new Service(); +test('getServiceOrder returns order', function (): void { $order = new Model_ClientOrder(); $order->loadBean(new Tests\Helpers\DummyBean()); - $dbMock = Mockery::mock('\Box_Database'); - $dbMock->shouldReceive('findOne') - ->atLeast()->once() - ->andReturn($order); + $dbMock = Mockery::mock(Box_Database::class); + $dbMock->shouldReceive('findOne')->atLeast()->once()->andReturn($order); $toolsMock = Mockery::mock(FOSSBilling\Tools::class); - $toolsMock->shouldReceive('from_camel_case') - ->atLeast()->once() - ->andReturn('servicecustom'); + $toolsMock->shouldReceive('from_camel_case')->atLeast()->once()->andReturn('servicecustom'); $di = container(); $di['db'] = $dbMock; $di['tools'] = $toolsMock; - $orderService->setDi($di); - $modelService = new Model_ServiceCustom(); - $modelService->loadBean(new Tests\Helpers\DummyBean()); - $modelService->id = 1; + $svc = new Service(); + $svc->setDi($di); - $result = $orderService->getServiceOrder($modelService); - expect($result)->toBeInstanceOf('Model_ClientOrder'); + $service = new Model_ServiceCustom(); + $service->loadBean(new Tests\Helpers\DummyBean()); + $service->id = 1; + + $result = $svc->getServiceOrder($service); + + expect($result)->toBeInstanceOf(Model_ClientOrder::class); }); -test('gets order config', function (): void { - $orderService = new Service(); +test('getConfig returns config', function (): void { + $svc = new Service(); $di = container(); - $orderService->setDi($di); + $svc->setDi($di); $order = new Model_ClientOrder(); $order->loadBean(new Tests\Helpers\DummyBean()); - $result = $orderService->getConfig($order); + $result = $svc->getConfig($order); + expect($result)->toBeArray(); }); -test('checks if product has orders', function ($order, $expectedResult): void { - $orderService = new Service(); - $dbMock = Mockery::mock('\Box_Database'); - $dbMock->shouldReceive('findOne') - ->atLeast()->once() - ->andReturn($order); +dataset('productHasOrdersProvider', function (): array { + $order = new Model_ClientOrder(); + $order->loadBean(new Tests\Helpers\DummyBean()); + + return [ + 'order present' => [$order, true], + 'order absent' => [null, false], + ]; +}); + +test('productHasOrders returns expected result', function (?Model_ClientOrder $order, bool $expectedResult): void { + $dbMock = Mockery::mock(Box_Database::class); + $dbMock->shouldReceive('findOne')->atLeast()->once()->andReturn($order); $di = container(); $di['db'] = $dbMock; - $orderService->setDi($di); - $product = new Model_Product(); - $product->loadBean(new Tests\Helpers\DummyBean()); - $product->id = 1; + $svc = new Service(); + $svc->setDi($di); - $result = $orderService->productHasOrders($product); - expect($result)->toBe($expectedResult); -})->with([ - [new Model_ClientOrder(), true], - [null, false], -]); + $product = orderServiceCreateProductEntity(1); -test('saves status change', function (): void { - $orderService = new Service(); + $result = $svc->productHasOrders($product); + + expect($result)->toEqual($expectedResult); +})->with('productHasOrdersProvider'); + +test('saveStatusChange records history', function (): void { $orderStatus = new Model_ClientOrderStatus(); $orderStatus->loadBean(new Tests\Helpers\DummyBean()); - $dbMock = Mockery::mock('\Box_Database'); - $dbMock->shouldReceive('dispense') - ->atLeast()->once() - ->andReturn($orderStatus); - $dbMock->shouldReceive('store') - ->atLeast()->once() - ->andReturn(1); + $dbMock = Mockery::mock(Box_Database::class); + $dbMock->shouldReceive('dispense')->atLeast()->once()->andReturn($orderStatus); + $dbMock->shouldReceive('store')->atLeast()->once()->andReturn(1); $di = container(); $di['db'] = $dbMock; - $orderService->setDi($di); + + $svc = new Service(); + $svc->setDi($di); $order = new Model_ClientOrder(); $order->loadBean(new Tests\Helpers\DummyBean()); - $result = $orderService->saveStatusChange($order); + $result = $svc->saveStatusChange($order); + expect($result)->toBeNull(); }); -test('gets soon expiring active orders', function (): void { +test('getSoonExpiringActiveOrders executes query', function (): void { $order = new Model_ClientOrder(); $order->loadBean(new Tests\Helpers\DummyBean()); - $dbMock = Mockery::mock('\Box_Database'); - $dbMock->shouldReceive('getAll') - ->atLeast()->once() - ->andReturn([[], []]); + $dbMock = Mockery::mock(Box_Database::class); + $dbMock->shouldReceive('getAll')->atLeast()->once()->andReturn([[], []]); $serviceMock = Mockery::mock(Service::class)->makePartial(); - $serviceMock->shouldReceive('getSoonExpiringActiveOrdersQuery') - ->atLeast()->once() - ->andReturn(['query', []]); + $serviceMock->shouldAllowMockingProtectedMethods(); + $serviceMock->shouldReceive('getSoonExpiringActiveOrdersQuery')->atLeast()->once()->andReturn(['query', []]); $di = container(); $di['db'] = $dbMock; @@ -907,28 +803,29 @@ test('gets soon expiring active orders', function (): void { $serviceMock->getSoonExpiringActiveOrders(); }); -test('gets soon expiring active orders query', function (): void { - $orderService = new Service(); +test('getSoonExpiringActiveOrdersQuery builds expected SQL and bindings', function (): void { $randId = 1; $orderStatus = new Model_ClientOrderStatus(); $orderStatus->loadBean(new Tests\Helpers\DummyBean()); $systemService = Mockery::mock(Box\Mod\System\Service::class); - $systemService->shouldReceive('getParamValue') - ->atLeast()->once() - ->andReturn($randId); + $systemService->shouldReceive('getParamValue')->atLeast()->once()->andReturn($randId); $di = container(); - $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $systemService); + $di['mod_service'] = $di->protect(fn (string $name): Mockery\MockInterface => match (strtolower($name)) { + 'system' => $systemService, + default => Mockery::mock()->shouldIgnoreMissing(), + }); - $orderService->setDi($di); + $svc = new Service(); + $svc->setDi($di); $order = new Model_ClientOrder(); $order->loadBean(new Tests\Helpers\DummyBean()); $data = ['client_id' => $randId]; - $result = $orderService->getSoonExpiringActiveOrdersQuery($data); + $result = $svc->getSoonExpiringActiveOrdersQuery($data); $expectedQuery = 'SELECT co.* FROM client_order co @@ -941,75 +838,99 @@ test('gets soon expiring active orders query', function (): void { $expectedBindings = [ ':client_id' => $randId, - ':status' => 'active', - ':invoice_option' => 'issue-invoice', ':unpaid_invoice_status' => Model_Invoice::STATUS_UNPAID, + ':status' => Model_ClientOrder::STATUS_ACTIVE, + ':invoice_option' => 'issue-invoice', ':days_until_expiration' => $randId, ]; expect($result[0])->toBeString(); expect($result[1])->toBeArray(); - expect($result[0])->toBe($expectedQuery); - expect($result[1])->toBe($expectedBindings); + expect($result[0])->toEqual($expectedQuery); + expect($result[1])->toEqual($expectedBindings); }); -test('gets related order id by type', function (): void { - $orderService = new Service(); +test('getRelatedOrderIdByType returns id', function (): void { $id = 1; $model = new Model_ClientOrder(); $model->loadBean(new Tests\Helpers\DummyBean()); $model->id = $id; - $dbMock = Mockery::mock('\Box_Database'); - $dbMock->shouldReceive('findOne') - ->with('ClientOrder', 'group_id = :group_id AND service_type = :service_type', Mockery::type('array')) - ->atLeast()->once() - ->andReturn($model); + $dbMock = Mockery::mock(Box_Database::class); + $dbMock->shouldReceive('findOne')->atLeast()->once()->with('ClientOrder', Mockery::any(), Mockery::any())->andReturn($model); $di = container(); $di['db'] = $dbMock; - $orderService->setDi($di); - $result = $orderService->getRelatedOrderIdByType($model, 'domain'); + $svc = new Service(); + $svc->setDi($di); + + $result = $svc->getRelatedOrderIdByType($model, 'domain'); + expect($result)->toBeInt(); - expect($result)->toBe($id); + expect($result)->toEqual($id); }); -test('returns null when related order not found', function (): void { - $orderService = new Service(); +test('getRelatedOrderIdByType returns null when not found', function (): void { + $id = 1; $model = new Model_ClientOrder(); $model->loadBean(new Tests\Helpers\DummyBean()); - $model->id = 1; + $model->id = $id; - $dbMock = Mockery::mock('\Box_Database'); - $dbMock->shouldReceive('findOne') - ->with('ClientOrder', 'group_id = :group_id AND service_type = :service_type', Mockery::type('array')) - ->atLeast()->once() - ->andReturn(null); + $dbMock = Mockery::mock(Box_Database::class); + $dbMock->shouldReceive('findOne')->atLeast()->once()->with('ClientOrder', Mockery::any(), Mockery::any())->andReturn(null); $di = container(); $di['db'] = $dbMock; - $orderService->setDi($di); - $result = $orderService->getRelatedOrderIdByType($model, 'domain'); + $svc = new Service(); + $svc->setDi($di); + + $result = $svc->getRelatedOrderIdByType($model, 'domain'); + expect($result)->toBeNull(); }); -test('gets logger', function (): void { - $orderService = new Service(); +test('getLogger returns logger with event items', function (): void { $model = new Model_ClientOrder(); $model->loadBean(new Tests\Helpers\DummyBean()); + $model->id = 5; + $model->status = 'active'; + + $capturedItems = []; + $logger = new class($capturedItems) extends Box_Log { + public function __construct(public array &$capturedItems) + { + } + + public function addWriter($writer): static + { + return $this; + } + + public function setEventItem(string $name, mixed $value): static + { + $this->capturedItems[] = [$name, $value]; + + return $this; + } + }; $di = container(); - $di['logger'] = new Tests\Helpers\TestLogger(); - $orderService->setDi($di); + $di['logger'] = $logger; - $result = $orderService->getLogger($model); - expect($result)->toBeInstanceOf('\Box_Log'); + $svc = new Service(); + $svc->setDi($di); + + $result = $svc->getLogger($model); + + expect($result)->toBeInstanceOf(Box_Log::class); + expect($capturedItems)->toHaveCount(2); + expect($capturedItems[0])->toEqual(['client_order_id', 5]); + expect($capturedItems[1])->toEqual(['status', 'active']); }); -test('converts order to api array', function (): void { - $orderService = new Service(); +test('toApiArray returns expected keys', function (): void { $model = new Model_ClientOrder(); $model->loadBean(new Tests\Helpers\DummyBean()); $model->config = '{}'; @@ -1018,51 +939,45 @@ test('converts order to api array', function (): void { $model->client_id = 1; $clientService = Mockery::mock(Box\Mod\Client\Service::class); - $clientService->shouldReceive('toApiArray') - ->atLeast()->once() - ->andReturn([]); + $clientService->shouldReceive('toApiArray')->atLeast()->once()->andReturn([]); $supportService = Mockery::mock(Box\Mod\Support\Service::class); - $supportService->shouldReceive('getActiveTicketsCountForOrder') - ->atLeast()->once() - ->andReturn(1); + $supportService->shouldReceive('getActiveTicketsCountForOrder')->atLeast()->once()->andReturn(1); $dbMock = Mockery::mock(Box_Database::class); - $dbMock->shouldReceive('toArray') - ->atLeast()->once() - ->andReturn([]); - $dbMock->shouldReceive('getAssoc') - ->atLeast()->once() - ->andReturn([]); + $dbMock->shouldReceive('toArray')->atLeast()->once()->andReturn([]); + $dbMock->shouldReceive('getAssoc')->atLeast()->once()->andReturn([]); - $modelProduct = new Model_Product(); - $modelProduct->loadBean(new Tests\Helpers\DummyBean()); $modelClient = new Model_Client(); $modelClient->loadBean(new Tests\Helpers\DummyBean()); - $dbMock->shouldReceive('load') - ->atLeast()->once() - ->andReturnUsing(fn (...$args): Model_Product => match ($args[0]) { - 'Product' => $modelProduct, - }); + $exceptionError = 'Client not found'; $dbMock->shouldReceive('getExistingModelById') - ->with('Client', $model->client_id, 'Client not found') ->atLeast()->once() + ->with('Client', $model->client_id, $exceptionError) ->andReturn($modelClient); + $productService = Mockery::mock(Box\Mod\Product\Service::class); + $productService->shouldReceive('getProductPluginById')->once()->with((int) $model->product_id)->andReturn(null); + $di = container(); - $di['mod_service'] = $di->protect(function ($serviceName) use ($clientService, $supportService) { + $di['mod_service'] = $di->protect(function ($serviceName) use ($clientService, $supportService, $productService) { if ($serviceName == 'client') { return $clientService; } if ($serviceName == 'support') { return $supportService; } + if ($serviceName == 'product') { + return $productService; + } }); $di['db'] = $dbMock; - $orderService->setDi($di); - $result = $orderService->toApiArray($model, true, new Model_Admin()); + $svc = new Service(); + $svc->setDi($di); + + $result = $svc->toApiArray($model, true, new Model_Admin()); expect($result)->toHaveKey('config'); expect($result)->toHaveKey('total'); @@ -1073,126 +988,145 @@ test('converts order to api array', function (): void { expect($result)->toHaveKey('client'); }); -test('gets search query with various filters', function (array $data, string $expectedStr, array $expectedParams): void { - $orderService = new Service(); +dataset('searchQueryData', function (): array { + return [ + 'no data' => [[], 'SELECT co.* from client_order co', []], + 'client_id' => [ + ['client_id' => 1], + 'co.client_id = :client_id', + [':client_id' => '1'], + ], + 'invoice_option' => [ + ['invoice_option' => 'issue-invoice'], + 'co.invoice_option = :invoice_option', + [':invoice_option' => 'issue-invoice'], + ], + 'id' => [ + ['id' => 1], + 'co.id = :id', + [':id' => '1'], + ], + 'status' => [ + ['status' => 'pending_setup'], + 'co.status = :status', + [':status' => 'pending_setup'], + ], + 'product_id' => [ + ['product_id' => 1], + 'co.product_id = :product_id', + [':product_id' => '1'], + ], + 'type' => [ + ['type' => 'custom'], + 'co.service_type = :service_type', + [':service_type' => 'custom'], + ], + 'title' => [ + ['title' => 'titleField'], + 'co.title LIKE :title', + [':title' => '%titleField%'], + ], + 'period' => [ + ['period' => '1Y'], + 'co.period = :period', + [':period' => '1Y'], + ], + 'hide_addons' => [ + ['hide_addons' => true], + 'co.group_master = 1', + [], + ], + 'created_at' => [ + ['created_at' => '2012-12-11'], + "DATE_FORMAT(co.created_at, '%Y-%m-%d') = :created_at", + [':created_at' => '2012-12-11'], + ], + 'date_from' => [ + ['date_from' => '2012-12-11'], + 'UNIX_TIMESTAMP(co.created_at) >= :date_from', + [':date_from' => strtotime('2012-12-11')], + ], + 'date_to' => [ + ['date_to' => '2012-12-11'], + 'UNIX_TIMESTAMP(co.created_at) <= :date_to', + [':date_to' => strtotime('2012-12-11')], + ], + 'search numeric' => [ + ['search' => 120], + 'co.id = :search', + [':search' => 120], + ], + 'search string' => [ + ['search' => 'John'], + '(c.first_name LIKE :first_name OR c.last_name LIKE :last_name OR co.title LIKE :title)', + [ + ':first_name' => '%John%', + ':last_name' => '%John%', + ':title' => '%John%', + ], + ], + 'ids' => [ + ['ids' => [1, 2, 3]], + 'co.id IN (:ids)', + [':ids' => '1, 2, 3'], + ], + 'promo_id' => [ + ['promo_id' => 9], + 'co.promo_id = :promo_id', + [':promo_id' => 9], + ], + 'meta' => [ + ['meta' => ['param' => 'value']], + '(meta.name = :meta_name1 AND meta.value LIKE :meta_value1)', + [ + ':meta_name1' => 'param', + ':meta_value1' => 'value%', + ], + ], + ]; +}); + +test('getSearchQuery returns expected query and bindings', function (array $data, string $expectedStr, array $expectedParams): void { $di = container(); - $orderService->setDi($di); + $svc = new Service(); + $svc->setDi($di); + + $result = $svc->getSearchQuery($data); - $result = $orderService->getSearchQuery($data); expect($result[0])->toBeString(); expect($result[1])->toBeArray(); + expect($result[0])->toContain($expectedStr); + expect($result[1])->toEqual($expectedParams); +})->with('searchQueryData'); - expect(str_contains((string) $result[0], $expectedStr))->toBeTrue($result[0]); - expect(array_diff_key($result[1], $expectedParams))->toBe([]); -})->with([ - [[], 'SELECT co.* from client_order co', []], - [ - ['client_id' => 1], - 'co.client_id = :client_id', - [':client_id' => '1'], - ], - [ - ['invoice_option' => 'issue-invoice'], - 'co.invoice_option = :invoice_option', - [':invoice_option' => 'issue-invoice'], - ], - [ - ['id' => 1], - 'co.id = :id', - [':id' => '1'], - ], - [ - ['status' => 'pending_setup'], - 'co.status = :status', - [':status' => 'pending_setup'], - ], - [ - ['product_id' => 1], - 'co.product_id = :product_id', - [':product_id' => '1'], - ], - [ - ['type' => 'custom'], - 'co.service_type = :service_type', - [':service_type' => 'custom'], - ], - [ - ['title' => 'titleField'], - 'co.title LIKE :title', - [':title' => '%titleField%'], - ], - [ - ['period' => '1Y'], - 'co.period = :period', - [':period' => '1Y'], - ], - [ - ['hide_addons' => true], - 'co.group_master = 1', - [], - ], - [ - ['created_at' => '2012-12-11'], - "DATE_FORMAT(co.created_at, '%Y-%m-%d') = :created_at", - [':created_at' => '2012-12-11'], - ], - [ - ['date_from' => '2012-12-11'], - 'UNIX_TIMESTAMP(co.created_at) >= :date_from', - [':date_from' => strtotime('2012-12-11')], - ], - [ - ['date_to' => '2012-12-11'], - 'UNIX_TIMESTAMP(co.created_at) <= :date_to', - [':date_to' => strtotime('2012-12-11')], - ], - [ - ['search' => 120], - 'co.id = :search', - [':search' => 120], - ], - [ - ['search' => 'John'], - '(c.first_name LIKE :first_name OR c.last_name LIKE :last_name OR co.title LIKE :title)', - [ - ':first_name' => '%John%', - ':last_name' => '%John%', - ':title' => '%John%', - ], - ], - [ - ['ids' => [1, 2, 3]], - 'co.id IN (:ids)', - [':ids' => [1, 2, 3]], - ], - [ - ['meta' => ['param' => 'value']], - '(meta.name = :meta_name1 AND meta.value LIKE :meta_value1)', - [ - ':meta_name1' => 'param', - ':meta_value1' => 'value%', - ], - ], -]); +test('getSearchQuery keeps client scope when action required filter is used', function (): void { + $di = container(); -test('throws exception when creating order with missing currency', function (): void { - $orderService = new Service(); + $svc = new Service(); + $svc->setDi($di); + + [$query, $bindings] = $svc->getSearchQuery([ + 'client_id' => 42, + 'show_action_required' => true, + ]); + + expect($query)->toContain('co.client_id = :client_id'); + expect($query)->toContain("(co.status = 'pending_setup' OR co.status = 'failed_setup' OR co.status ='failed_renew')"); + expect($bindings[':client_id'])->toBe(42); +}); + +test('createOrder throws when no order currency is set', function (): void { $modelClient = new Model_Client(); $modelClient->loadBean(new Tests\Helpers\DummyBean()); - $modelProduct = new Model_Product(); - $modelProduct->loadBean(new Tests\Helpers\DummyBean()); + $modelProduct = orderServiceCreateProductEntity(); - $currencyRepositoryMock = Mockery::mock(Box\Mod\Currency\Repository\CurrencyRepository::class)->shouldIgnoreMissing(); - $currencyRepositoryMock->shouldReceive('findDefault') - ->atLeast()->once() - ->andReturn(null); + $currencyRepositoryMock = Mockery::mock(Box\Mod\Currency\Repository\CurrencyRepository::class); + $currencyRepositoryMock->shouldReceive('findDefault')->atLeast()->once()->andReturn(null); $currencyServiceMock = Mockery::mock(Box\Mod\Currency\Service::class); - $currencyServiceMock->shouldReceive('getCurrencyRepository') - ->atLeast()->once() - ->andReturn($currencyRepositoryMock); + $currencyServiceMock->shouldReceive('getCurrencyRepository')->atLeast()->once()->andReturn($currencyRepositoryMock); $di = container(); $di['mod_service'] = $di->protect(function ($serviceName) use ($currencyServiceMock) { @@ -1201,42 +1135,36 @@ test('throws exception when creating order with missing currency', function (): } }); - $orderService->setDi($di); + $svc = new Service(); + $svc->setDi($di); - expect(fn () => $orderService->createOrder($modelClient, $modelProduct, [])) + expect(fn () => $svc->createOrder($modelClient, $modelProduct, [])) ->toThrow(FOSSBilling\Exception::class, 'Currency could not be determined for order'); }); -test('throws exception when creating order for out of stock product', function (): void { - $orderService = new Service(); +test('createOrder throws when out of stock', function (): void { $modelClient = new Model_Client(); $modelClient->loadBean(new Tests\Helpers\DummyBean()); $modelClient->currency = 'USD'; - $modelProduct = new Model_Product(); - $modelProduct->loadBean(new Tests\Helpers\DummyBean()); - $modelProduct->id = 1; + $modelProduct = orderServiceCreateProductEntity(1); - $currencyModel = Mockery::mock(Box\Mod\Currency\Entity\Currency::class); + $currencyModel = Mockery::mock(Box\Mod\Currency\Entity\Currency::class)->shouldIgnoreMissing(); - $currencyRepositoryMock = Mockery::mock(Box\Mod\Currency\Repository\CurrencyRepository::class)->shouldIgnoreMissing(); - $currencyRepositoryMock->shouldReceive('findOneByCode') - ->atLeast()->once() - ->andReturn($currencyModel); + $currencyRepositoryMock = Mockery::mock(Box\Mod\Currency\Repository\CurrencyRepository::class); + $currencyRepositoryMock->shouldReceive('findOneByCode')->atLeast()->once()->andReturn($currencyModel); $currencyServiceMock = Mockery::mock(Box\Mod\Currency\Service::class); - $currencyServiceMock->shouldReceive('getCurrencyRepository') - ->atLeast()->once() - ->andReturn($currencyRepositoryMock); + $currencyServiceMock->shouldReceive('getCurrencyRepository')->atLeast()->once()->andReturn($currencyRepositoryMock); $cartServiceMock = Mockery::mock(Box\Mod\Cart\Service::class); $cartServiceMock->shouldReceive('isStockAvailable') - ->with($modelProduct, 1) ->atLeast()->once() + ->with($modelProduct, Mockery::any()) ->andReturn(false); - $eventMock = Mockery::mock('\Box_EventManager'); - $eventMock->shouldReceive('fire'); + $eventMock = Mockery::mock(Box_EventManager::class); + $eventMock->shouldReceive('fire')->atLeast()->once(); $di = container(); $di['mod_service'] = $di->protect(function ($serviceName) use ($currencyServiceMock, $cartServiceMock) { @@ -1247,46 +1175,39 @@ test('throws exception when creating order for out of stock product', function ( return $cartServiceMock; } }); - $di['events_manager'] = $eventMock; - $orderService->setDi($di); + $svc = new Service(); + $svc->setDi($di); - expect(fn () => $orderService->createOrder($modelClient, $modelProduct, [])) - ->toThrow(FOSSBilling\InformationException::class, 'Product 1 is out of stock.'); + expect(fn () => $svc->createOrder($modelClient, $modelProduct, [])) + ->toThrow(FOSSBilling\Exception::class, 'Product 1 is out of stock.'); }); -test('throws exception when creating addon order with missing group id', function (): void { - $orderService = new Service(); +test('createOrder throws when group id missing for addon', function (): void { $modelClient = new Model_Client(); $modelClient->loadBean(new Tests\Helpers\DummyBean()); $modelClient->currency = 'USD'; - $modelProduct = new Model_Product(); - $modelProduct->loadBean(new Tests\Helpers\DummyBean()); - $modelProduct->id = 1; - $modelProduct->is_addon = 1; + $modelProduct = orderServiceCreateProductEntity(1); + $modelProduct->setIsAddon(true); - $currencyModel = Mockery::mock(Box\Mod\Currency\Entity\Currency::class); + $currencyModel = Mockery::mock(Box\Mod\Currency\Entity\Currency::class)->shouldIgnoreMissing(); - $currencyRepositoryMock = Mockery::mock(Box\Mod\Currency\Repository\CurrencyRepository::class)->shouldIgnoreMissing(); - $currencyRepositoryMock->shouldReceive('findOneByCode') - ->atLeast()->once() - ->andReturn($currencyModel); + $currencyRepositoryMock = Mockery::mock(Box\Mod\Currency\Repository\CurrencyRepository::class); + $currencyRepositoryMock->shouldReceive('findOneByCode')->atLeast()->once()->andReturn($currencyModel); $currencyServiceMock = Mockery::mock(Box\Mod\Currency\Service::class); - $currencyServiceMock->shouldReceive('getCurrencyRepository') - ->atLeast()->once() - ->andReturn($currencyRepositoryMock); + $currencyServiceMock->shouldReceive('getCurrencyRepository')->atLeast()->once()->andReturn($currencyRepositoryMock); $cartServiceMock = Mockery::mock(Box\Mod\Cart\Service::class); $cartServiceMock->shouldReceive('isStockAvailable') - ->with($modelProduct, 1) ->atLeast()->once() + ->with($modelProduct, Mockery::any()) ->andReturn(true); - $eventMock = Mockery::mock('\Box_EventManager'); - $eventMock->shouldReceive('fire'); + $eventMock = Mockery::mock(Box_EventManager::class); + $eventMock->shouldReceive('fire')->atLeast()->once(); $di = container(); $di['mod_service'] = $di->protect(function ($serviceName) use ($currencyServiceMock, $cartServiceMock) { @@ -1297,45 +1218,38 @@ test('throws exception when creating addon order with missing group id', functio return $cartServiceMock; } }); - $di['events_manager'] = $eventMock; - $orderService->setDi($di); + $svc = new Service(); + $svc->setDi($di); - expect(fn () => $orderService->createOrder($modelClient, $modelProduct, [])) + expect(fn () => $svc->createOrder($modelClient, $modelProduct, [])) ->toThrow(FOSSBilling\Exception::class, 'Group ID parameter is missing for addon product order'); }); -test('throws exception when creating order with parent not found', function (): void { - $orderService = new Service(); +test('createOrder throws when parent order not found', function (): void { $modelClient = new Model_Client(); $modelClient->loadBean(new Tests\Helpers\DummyBean()); $modelClient->currency = 'USD'; - $modelProduct = new Model_Product(); - $modelProduct->loadBean(new Tests\Helpers\DummyBean()); - $modelProduct->id = 1; + $modelProduct = orderServiceCreateProductEntity(1); - $currencyModel = Mockery::mock(Box\Mod\Currency\Entity\Currency::class); + $currencyModel = Mockery::mock(Box\Mod\Currency\Entity\Currency::class)->shouldIgnoreMissing(); - $currencyRepositoryMock = Mockery::mock(Box\Mod\Currency\Repository\CurrencyRepository::class)->shouldIgnoreMissing(); - $currencyRepositoryMock->shouldReceive('findOneByCode') - ->atLeast()->once() - ->andReturn($currencyModel); + $currencyRepositoryMock = Mockery::mock(Box\Mod\Currency\Repository\CurrencyRepository::class); + $currencyRepositoryMock->shouldReceive('findOneByCode')->atLeast()->once()->andReturn($currencyModel); $currencyServiceMock = Mockery::mock(Box\Mod\Currency\Service::class); - $currencyServiceMock->shouldReceive('getCurrencyRepository') - ->atLeast()->once() - ->andReturn($currencyRepositoryMock); + $currencyServiceMock->shouldReceive('getCurrencyRepository')->atLeast()->once()->andReturn($currencyRepositoryMock); $cartServiceMock = Mockery::mock(Box\Mod\Cart\Service::class); $cartServiceMock->shouldReceive('isStockAvailable') - ->with($modelProduct, 1) ->atLeast()->once() + ->with($modelProduct, Mockery::any()) ->andReturn(true); - $eventMock = Mockery::mock('\Box_EventManager'); - $eventMock->shouldReceive('fire'); + $eventMock = Mockery::mock(Box_EventManager::class); + $eventMock->shouldReceive('fire')->atLeast()->once(); $di = container(); $di['mod_service'] = $di->protect(function ($serviceName) use ($currencyServiceMock, $cartServiceMock) { @@ -1346,10 +1260,10 @@ test('throws exception when creating order with parent not found', function (): return $cartServiceMock; } }); - $di['events_manager'] = $eventMock; - $serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods(); + $serviceMock = Mockery::mock(Service::class)->makePartial(); + $serviceMock->shouldAllowMockingProtectedMethods(); $serviceMock->shouldReceive('getMasterOrderForClient') ->atLeast()->once() ->andReturn(null); @@ -1360,230 +1274,525 @@ test('throws exception when creating order with parent not found', function (): ->toThrow(FOSSBilling\Exception::class, 'Parent order 1 was not found'); }); -test('creates order', function (): void { - $orderService = new Service(); +test('createOrder creates order', function (): void { $modelClient = new Model_Client(); $modelClient->loadBean(new Tests\Helpers\DummyBean()); $modelClient->currency = 'USD'; - $modelProduct = new Model_Product(); - $modelProduct->loadBean(new Tests\Helpers\DummyBean()); - $modelProduct->id = 1; - $modelProduct->type = 'custom'; + $modelProduct = orderServiceCreateProductEntity(1, 'custom'); + + $currencyModel = Mockery::mock(Box\Mod\Currency\Entity\Currency::class)->shouldIgnoreMissing(); + $currencyModel->shouldReceive('getCode')->andReturn('USD'); + + $currencyRepositoryMock = Mockery::mock(Box\Mod\Currency\Repository\CurrencyRepository::class); + $currencyRepositoryMock->shouldReceive('findOneByCode')->atLeast()->once()->andReturn($currencyModel); - $currencyModel = Mockery::mock(Box\Mod\Currency\Entity\Currency::class); - $currencyModel->shouldReceive('getCode') - ->atLeast()->once() - ->andReturn('USD'); - $currencyRepositoryMock = Mockery::mock(Box\Mod\Currency\Repository\CurrencyRepository::class)->shouldIgnoreMissing(); - $currencyRepositoryMock->shouldReceive('findOneByCode') - ->atLeast()->once() - ->andReturn($currencyModel); $currencyServiceMock = Mockery::mock(Box\Mod\Currency\Service::class); - $currencyServiceMock->shouldReceive('getCurrencyRepository') - ->atLeast()->once() - ->andReturn($currencyRepositoryMock); + $currencyServiceMock->shouldReceive('getCurrencyRepository')->atLeast()->once()->andReturn($currencyRepositoryMock); $cartServiceMock = Mockery::mock(Box\Mod\Cart\Service::class); $cartServiceMock->shouldReceive('isStockAvailable') - ->with($modelProduct, 1) ->atLeast()->once() + ->with($modelProduct, Mockery::any()) ->andReturn(true); - $eventMock = Mockery::mock('\Box_EventManager'); - $eventMock->shouldReceive('fire'); + $eventMock = Mockery::mock(Box_EventManager::class); + $eventMock->shouldReceive('fire')->atLeast()->once(); + $productServiceMock = Mockery::mock(Box\Mod\Servicecustom\Service::class); + $pricingServiceMock = Mockery::mock(Box\Mod\Product\Service::class); + $pricingServiceMock->shouldReceive('getProductOrderLineConfig')->never(); $clientOrderModel = new Model_ClientOrder(); $clientOrderModel->loadBean(new Tests\Helpers\DummyBean()); - $dbMock = Mockery::mock('\Box_Database'); - $dbMock->shouldReceive('dispense') - ->with('ClientOrder') - ->atLeast()->once() - ->andReturn($clientOrderModel); - $newId = 1; - $dbMock->shouldReceive('store') - ->with($clientOrderModel) - ->atLeast()->once() - ->andReturn($newId); + $dbMock = Mockery::mock(Box_Database::class); + $dbMock->shouldReceive('transaction') + ->once() + ->andReturnUsing(fn (callable $callback) => $callback()); + $dbMock->shouldReceive('dispense')->atLeast()->once()->with('ClientOrder')->andReturn($clientOrderModel); - $periodMock = Mockery::mock('\Box_Period'); - $periodMock->shouldReceive('getCode') + $newId = 1; + $dbMock->shouldReceive('store')->atLeast()->once()->with($clientOrderModel)->andReturn($newId); + $dbMock->shouldReceive('getExistingModelById') ->atLeast()->once() - ->andReturn('1Y'); + ->with('ClientOrder', $newId, 'Order not found') + ->andReturn($clientOrderModel); + + $periodMock = Mockery::mock(Box_Period::class); + $periodMock->shouldReceive('getCode')->atLeast()->once()->andReturn('1Y'); $di = container(); - $di['mod_service'] = $di->protect(function ($serviceName) use ($currencyServiceMock, $cartServiceMock, $productServiceMock) { + $di['mod_service'] = $di->protect(function ($serviceName) use ($currencyServiceMock, $cartServiceMock, $productServiceMock, $pricingServiceMock) { if ($serviceName == 'currency') { return $currencyServiceMock; } if ($serviceName == 'cart') { return $cartServiceMock; } + if ($serviceName == 'Product') { + return $pricingServiceMock; + } if ($serviceName == 'servicecustom') { return $productServiceMock; } }); $di['events_manager'] = $eventMock; - $createdOrder = new Model_ClientOrder(); - $createdOrder->loadBean(new Tests\Helpers\DummyBean()); - $createdOrder->id = $newId; - $dbMock->shouldReceive('getExistingModelById') - ->with('ClientOrder', $newId, 'Order not found') - ->once() - ->andReturn($createdOrder); + $di['db'] = $dbMock; + $di['period'] = $di->protect(fn (): Mockery\MockInterface => $periodMock); + $di['logger'] = new Box_Log(); + + $svc = new Service(); + $svc->setDi($di); + + $result = $svc->createOrder($modelClient, $modelProduct, ['period' => '1Y', 'price' => '10', 'notes' => 'test']); + + expect($result)->toEqual($newId); +}); + +test('createOrder sets form id from product', function (): void { + $modelClient = new Model_Client(); + $modelClient->loadBean(new Tests\Helpers\DummyBean()); + $modelClient->currency = 'USD'; + + $modelProduct = orderServiceCreateProductEntity(1, 'custom'); + $modelProduct->setFormId(42); + + $currencyModel = Mockery::mock(Box\Mod\Currency\Entity\Currency::class)->shouldIgnoreMissing(); + + $currencyRepositoryMock = Mockery::mock(Box\Mod\Currency\Repository\CurrencyRepository::class); + $currencyRepositoryMock->shouldReceive('findOneByCode')->atLeast()->once()->andReturn($currencyModel); + + $currencyServiceMock = Mockery::mock(Box\Mod\Currency\Service::class); + $currencyServiceMock->shouldReceive('getCurrencyRepository')->atLeast()->once()->andReturn($currencyRepositoryMock); + + $cartServiceMock = Mockery::mock(Box\Mod\Cart\Service::class); + $cartServiceMock->shouldReceive('isStockAvailable') + ->atLeast()->once() + ->with($modelProduct, Mockery::any()) + ->andReturn(true); + + $eventMock = Mockery::mock(Box_EventManager::class); + $eventMock->shouldReceive('fire')->atLeast()->once(); + + $productServiceMock = Mockery::mock(Box\Mod\Servicecustom\Service::class); + $pricingServiceMock = Mockery::mock(Box\Mod\Product\Service::class); + $pricingServiceMock->shouldReceive('getProductOrderLineConfig')->never(); + + $clientOrderModel = new Model_ClientOrder(); + $clientOrderModel->loadBean(new Tests\Helpers\DummyBean()); + + $dbMock = Mockery::mock(Box_Database::class); $dbMock->shouldReceive('transaction') ->once() ->andReturnUsing(fn (callable $callback) => $callback()); + $dbMock->shouldReceive('dispense')->atLeast()->once()->with('ClientOrder')->andReturn($clientOrderModel); + + $newId = 1; + $dbMock->shouldReceive('store')->atLeast()->once()->with($clientOrderModel)->andReturn($newId); + $dbMock->shouldReceive('getExistingModelById') + ->atLeast()->once() + ->with('ClientOrder', $newId, 'Order not found') + ->andReturn($clientOrderModel); + + $periodMock = Mockery::mock(Box_Period::class); + $periodMock->shouldReceive('getCode')->atLeast()->once()->andReturn('1Y'); + + $di = container(); + $di['mod_service'] = $di->protect(function ($serviceName) use ($currencyServiceMock, $cartServiceMock, $productServiceMock, $pricingServiceMock) { + if ($serviceName == 'currency') { + return $currencyServiceMock; + } + if ($serviceName == 'cart') { + return $cartServiceMock; + } + if ($serviceName == 'Product') { + return $pricingServiceMock; + } + if ($serviceName == 'servicecustom') { + return $productServiceMock; + } + }); + $di['events_manager'] = $eventMock; $di['db'] = $dbMock; $di['period'] = $di->protect(fn (): Mockery\MockInterface => $periodMock); - $di['logger'] = new Tests\Helpers\TestLogger(); + $di['logger'] = new Box_Log(); + + $svc = new Service(); + $svc->setDi($di); + + $svc->createOrder($modelClient, $modelProduct, ['period' => '1Y', 'price' => '10']); + + expect($clientOrderModel->form_id)->toEqual(42); +}); + +test('createOrder returns success when invoice follow up fails', function (): void { + $modelClient = new Model_Client(); + $modelClient->loadBean(new Tests\Helpers\DummyBean()); + $modelClient->currency = 'USD'; + + $modelProduct = orderServiceCreateProductEntity(1, 'custom'); + + $currencyModel = Mockery::mock(Box\Mod\Currency\Entity\Currency::class)->shouldIgnoreMissing(); + + $currencyRepositoryMock = Mockery::mock(Box\Mod\Currency\Repository\CurrencyRepository::class); + $currencyRepositoryMock->shouldReceive('findOneByCode')->atLeast()->once()->andReturn($currencyModel); + + $currencyServiceMock = Mockery::mock(Box\Mod\Currency\Service::class); + $currencyServiceMock->shouldReceive('getCurrencyRepository')->atLeast()->once()->andReturn($currencyRepositoryMock); + + $cartServiceMock = Mockery::mock(Box\Mod\Cart\Service::class); + $cartServiceMock->shouldReceive('isStockAvailable') + ->atLeast()->once() + ->with($modelProduct, Mockery::any()) + ->andReturn(true); + + $eventMock = Mockery::mock(Box_EventManager::class); + $eventMock->shouldReceive('fire')->atLeast()->once(); + + $productServiceMock = Mockery::mock(Box\Mod\Servicecustom\Service::class); + $pricingServiceMock = Mockery::mock(Box\Mod\Product\Service::class); + $pricingServiceMock->shouldReceive('getProductOrderLineConfig')->never(); + + $clientOrderModel = new Model_ClientOrder(); + $clientOrderModel->loadBean(new Tests\Helpers\DummyBean()); + + $invoiceModel = new Model_Invoice(); + $invoiceModel->loadBean(new Tests\Helpers\DummyBean()); + $invoiceModel->id = 10; + + $invoiceServiceMock = Mockery::mock(Box\Mod\Invoice\Service::class); + $invoiceServiceMock->shouldReceive('generateForOrder') + ->once() + ->with($clientOrderModel) + ->andReturn($invoiceModel); + $invoiceServiceMock->shouldReceive('approveInvoice') + ->once() + ->with($invoiceModel, ['id' => $invoiceModel->id, 'use_credits' => true]) + ->andReturn(true); + $invoiceServiceMock->shouldReceive('markAsPaidByAdmin') + ->once() + ->with($invoiceModel, Mockery::on(fn (array $data): bool => $data['invoice_option'] === 'issue-invoice' + && $data['mark_invoice_paid'] === true + && $data['gateway_id'] === 7)) + ->andThrow(new Exception('Payment follow-up failed')); + $invoiceServiceMock->shouldReceive('addNote') + ->once() + ->with( + $invoiceModel, + Mockery::on(fn (string $note): bool => str_contains($note, 'Order was created, but invoice follow-up failed: Payment follow-up failed')) + ) + ->andReturn(true); + + $dbMock = Mockery::mock(Box_Database::class); + $dbMock->shouldReceive('transaction') + ->once() + ->andReturnUsing(fn (callable $callback) => $callback()); + $dbMock->shouldReceive('dispense')->atLeast()->once()->with('ClientOrder')->andReturn($clientOrderModel); + + $newId = 1; + $dbMock->shouldReceive('store')->atLeast()->once()->with($clientOrderModel)->andReturn($newId); + $dbMock->shouldReceive('getExistingModelById') + ->atLeast()->once() + ->with('ClientOrder', $newId, 'Order not found') + ->andReturn($clientOrderModel); + + $periodMock = Mockery::mock(Box_Period::class); + $periodMock->shouldReceive('getCode')->atLeast()->once()->andReturn('1Y'); + + $di = container(); + $di['mod_service'] = $di->protect(function ($serviceName) use ($cartServiceMock, $currencyServiceMock, $invoiceServiceMock, $productServiceMock, $pricingServiceMock) { + if ($serviceName == 'currency') { + return $currencyServiceMock; + } + if ($serviceName == 'cart') { + return $cartServiceMock; + } + if ($serviceName == 'Product') { + return $pricingServiceMock; + } + if ($serviceName == 'invoice') { + return $invoiceServiceMock; + } + if ($serviceName == 'servicecustom') { + return $productServiceMock; + } + }); + $di['events_manager'] = $eventMock; + $di['db'] = $dbMock; + $di['period'] = $di->protect(fn (): Mockery\MockInterface => $periodMock); + $di['logger'] = new Box_Log(); + + $svc = new Service(); + $svc->setDi($di); + + $result = $svc->createOrder($modelClient, $modelProduct, [ + 'period' => '1Y', + 'price' => '10', + 'invoice_option' => 'issue-invoice', + 'mark_invoice_paid' => true, + 'gateway_id' => 7, + ]); - $orderService->setDi($di); - $result = $orderService->createOrder($modelClient, $modelProduct, ['period' => '1Y', 'price' => '10', 'notes' => 'test']); expect($result)->toBe($newId); }); -test('gets master order for client', function (): void { - $orderService = new Service(); +test('createOrder uses product pricing service for domain orders', function (): void { + $modelClient = new Model_Client(); + $modelClient->loadBean(new Tests\Helpers\DummyBean()); + $modelClient->currency = 'USD'; + + $modelProduct = orderServiceCreateProductEntity(10, Box\Mod\Product\Service::DOMAIN); + $modelProduct->setUnit('year'); + + $currencyModel = Mockery::mock(Box\Mod\Currency\Entity\Currency::class)->shouldIgnoreMissing(); + $currencyModel->shouldReceive('getCode')->andReturn('USD'); + + $currencyRepositoryMock = Mockery::mock(Box\Mod\Currency\Repository\CurrencyRepository::class); + $currencyRepositoryMock->shouldReceive('findOneByCode')->once()->with('USD')->andReturn($currencyModel); + $currencyRepositoryMock->shouldReceive('getRateByCode')->once()->with('USD')->andReturn(1.0); + + $currencyServiceMock = Mockery::mock(Box\Mod\Currency\Service::class); + $currencyServiceMock->shouldReceive('getCurrencyRepository')->atLeast()->once()->andReturn($currencyRepositoryMock); + + $cartServiceMock = Mockery::mock(Box\Mod\Cart\Service::class); + $cartServiceMock->shouldReceive('isStockAvailable') + ->atLeast()->once() + ->with($modelProduct, Mockery::any()) + ->andReturn(true); + + $eventMock = Mockery::mock(Box_EventManager::class); + $eventMock->shouldReceive('fire')->atLeast()->once(); + + $domainServiceMock = Mockery::mock(Box\Mod\Servicedomain\Service::class)->shouldIgnoreMissing(); + + $pricingServiceMock = Mockery::mock(Box\Mod\Product\Service::class); + $pricingServiceMock->shouldReceive('getProductOrderLineConfig') + ->once() + ->with( + $modelProduct, + Mockery::on(static fn (array $config): bool => ($config['quantity'] ?? null) === 1) + ) + ->andReturn([ + 'price' => 22.0, + 'quantity' => 2, + 'setup_price' => 0.0, + ]); + + $clientOrderModel = new Model_ClientOrder(); + $clientOrderModel->loadBean(new Tests\Helpers\DummyBean()); + + $dbMock = Mockery::mock(Box_Database::class); + $dbMock->shouldReceive('transaction') + ->once() + ->andReturnUsing(fn (callable $callback) => $callback()); + $dbMock->shouldReceive('dispense')->atLeast()->once()->with('ClientOrder')->andReturn($clientOrderModel); + + $newId = 10; + $dbMock->shouldReceive('store')->atLeast()->once()->with($clientOrderModel)->andReturn($newId); + $dbMock->shouldReceive('getExistingModelById') + ->atLeast()->once() + ->with('ClientOrder', $newId, 'Order not found') + ->andReturn($clientOrderModel); + + $di = container(); + $di['mod_service'] = $di->protect(function ($serviceName) use ($currencyServiceMock, $cartServiceMock, $domainServiceMock, $pricingServiceMock) { + if ($serviceName == 'currency') { + return $currencyServiceMock; + } + if ($serviceName == 'cart') { + return $cartServiceMock; + } + if ($serviceName == 'Product') { + return $pricingServiceMock; + } + if ($serviceName == 'servicedomain') { + return $domainServiceMock; + } + }); + $di['events_manager'] = $eventMock; + $di['db'] = $dbMock; + $di['logger'] = new Box_Log(); + + $svc = new Service(); + $svc->setDi($di); + + $result = $svc->createOrder($modelClient, $modelProduct, [ + 'action' => 'register', + 'register_tld' => '.com', + 'register_sld' => 'example', + 'register_years' => 2, + ]); + + expect($result)->toBe($newId); + expect($clientOrderModel->quantity)->toBe(2); + expect($clientOrderModel->price)->toBe(22.0); +}); + +test('getMasterOrderForClient returns master order', function (): void { $clientModel = new Model_Client(); $clientModel->loadBean(new Tests\Helpers\DummyBean()); $clientOrderModel = new Model_ClientOrder(); $clientOrderModel->loadBean(new Tests\Helpers\DummyBean()); - $dbMock = Mockery::mock('\Box_Database'); - $dbMock->shouldReceive('findOne') - ->with('ClientOrder', 'group_id = :group_id AND group_master = 1 AND client_id = :client_id', Mockery::type('array')) - ->atLeast()->once() - ->andReturn($clientOrderModel); + $dbMock = Mockery::mock(Box_Database::class); + $dbMock->shouldReceive('findOne')->atLeast()->once()->with('ClientOrder', Mockery::any(), Mockery::any())->andReturn($clientOrderModel); $di = container(); $di['db'] = $dbMock; - $orderService->setDi($di); - $result = $orderService->getMasterOrderForClient($clientModel, 1); - expect($result)->toBeInstanceOf('Model_ClientOrder'); + + $svc = new Service(); + $svc->setDi($di); + + $result = $svc->getMasterOrderForClient($clientModel, 1); + + expect($result)->toBeInstanceOf(Model_ClientOrder::class); }); -test('throws exception when activating non-pending order', function (): void { - $orderService = new Service(); +test('activateOrder throws for non-pending order', function (): void { $clientOrderModel = new Model_ClientOrder(); $clientOrderModel->loadBean(new Tests\Helpers\DummyBean()); $clientOrderModel->status = Model_ClientOrder::STATUS_CANCELED; - expect(fn (): bool => $orderService->activateOrder($clientOrderModel)) + $svc = new Service(); + + expect(fn () => $svc->activateOrder($clientOrderModel)) ->toThrow(FOSSBilling\Exception::class, 'Only pending setup or failed orders can be activated'); }); -test('activates order', function (): void { +test('activateOrder activates pending order', function (): void { $clientOrderModel = new Model_ClientOrder(); $clientOrderModel->loadBean(new Tests\Helpers\DummyBean()); $clientOrderModel->status = Model_ClientOrder::STATUS_PENDING_SETUP; $clientOrderModel->group_master = 1; - $eventMock = Mockery::mock('\Box_EventManager'); - $eventMock->shouldReceive('fire'); + $eventMock = Mockery::mock(Box_EventManager::class); + $eventMock->shouldReceive('fire')->atLeast()->once(); $di = container(); $di['events_manager'] = $eventMock; - $di['logger'] = new Tests\Helpers\TestLogger(); + $di['logger'] = new Box_Log(); $serviceMock = Mockery::mock(Service::class)->makePartial(); - $serviceMock->shouldReceive('createFromOrder') - ->atLeast()->once() - ->andReturn([]); - $serviceMock->shouldReceive('activateOrderAddons'); + $serviceMock->shouldAllowMockingProtectedMethods(); + $serviceMock->shouldReceive('createFromOrder')->atLeast()->once()->andReturn([]); + $serviceMock->shouldReceive('activateOrderAddons')->atLeast()->once(); $serviceMock->setDi($di); + $result = $serviceMock->activateOrder($clientOrderModel); + expect($result)->toBeTrue(); }); -test('activates order addons', function (): void { +test('activateOrderAddons activates addons', function (): void { $order = new Model_ClientOrder(); $order->loadBean(new Tests\Helpers\DummyBean()); $serviceMock = Mockery::mock(Service::class)->makePartial(); - $serviceMock->shouldReceive('createFromOrder') - ->atLeast()->once() - ->andReturn([]); + $serviceMock->shouldAllowMockingProtectedMethods(); + $serviceMock->shouldReceive('createFromOrder')->atLeast()->once()->andReturn([]); $clientOrderModel = new Model_ClientOrder(); $clientOrderModel->loadBean(new Tests\Helpers\DummyBean()); $clientOrderModel->status = Model_ClientOrder::STATUS_PENDING_SETUP; $clientOrderModel->group_master = 1; + $serviceMock->shouldReceive('getOrderAddonsList') ->atLeast()->once() ->andReturn([$clientOrderModel]); - $eventMock = Mockery::mock('\Box_EventManager'); - $eventMock->shouldReceive('fire'); + $eventMock = Mockery::mock(Box_EventManager::class); + $eventMock->shouldReceive('fire')->atLeast()->once(); $di = container(); $di['events_manager'] = $eventMock; $serviceMock->setDi($di); + $result = $serviceMock->activateOrderAddons($clientOrderModel); + expect($result)->toBeTrue(); }); -test('gets order addons list', function (): void { - $orderService = new Service(); +test('getOrderAddonsList returns addons', function (): void { $modelClientOrder = new Model_ClientOrder(); $modelClientOrder->loadBean(new Tests\Helpers\DummyBean()); - $dbMock = Mockery::mock('\Box_Database'); - $dbMock->shouldReceive('find') - ->with('ClientOrder', 'group_id = :group_id AND client_id = :client_id and (group_master = 0 OR group_master IS NULL)', Mockery::type('array')) - ->atLeast()->once() - ->andReturn([new Model_ClientOrder()]); + $dbMock = Mockery::mock(Box_Database::class); + $dbMock->shouldReceive('find')->atLeast()->once()->with('ClientOrder', Mockery::any(), Mockery::any())->andReturn([new Model_ClientOrder()]); $di = container(); $di['db'] = $dbMock; - $orderService->setDi($di); - $result = $orderService->getOrderAddonsList($modelClientOrder); + $svc = new Service(); + $svc->setDi($di); + + $result = $svc->getOrderAddonsList($modelClientOrder); + expect($result)->toBeArray(); - expect($result[0])->toBeInstanceOf('\Model_ClientOrder'); + expect($result[0])->toBeInstanceOf(Model_ClientOrder::class); }); -test('handles stock sale', function (): void { - $orderService = new Service(); - $productModel = new Model_Product(); - $productModel->loadBean(new Tests\Helpers\DummyBean()); - $productModel->id = 1; - $productModel->stock_control = 1; - $productModel->quantity_in_stock = 3; +test('stockSale reduces stock', function (): void { + $productModel = orderServiceCreateProductEntity(); - $dbMock = Mockery::mock('\Box_Database'); - $dbMock->shouldReceive('store') - ->with($productModel); + $productService = Mockery::mock(Box\Mod\Product\Service::class); + $productService->shouldReceive('reduceStock')->once()->with($productModel, 2)->andReturn(true); $di = container(); - $di['db'] = $dbMock; - $orderService->setDi($di); + $di['mod_service'] = $di->protect(function ($serviceName) use ($productService) { + if ($serviceName == 'product') { + return $productService; + } + }); + + $svc = new Service(); + $svc->setDi($di); + + $result = $svc->stockSale($productModel, 2); - $result = $orderService->stockSale($productModel, 2); expect($result)->toBeTrue(); }); -test('updates order', function (): void { - $orderService = new Service(); +test('stockSale throws when quantity would go negative', function (): void { + $productModel = orderServiceCreateProductEntity(1); + + $productService = Mockery::mock(Box\Mod\Product\Service::class); + $productService->shouldReceive('reduceStock') + ->once() + ->with($productModel, 2) + ->andThrow(new FOSSBilling\InformationException('Product :id is out of stock.', [':id' => 1], 831)); + + $di = container(); + $di['mod_service'] = $di->protect(function ($serviceName) use ($productService) { + if ($serviceName == 'product') { + return $productService; + } + }); + + $svc = new Service(); + $svc->setDi($di); + + expect(fn () => $svc->stockSale($productModel, 2)) + ->toThrow(FOSSBilling\InformationException::class, 'Product 1 is out of stock.'); +}); + +test('updateOrder updates fields', function (): void { $clientOrderModel = new Model_ClientOrder(); $clientOrderModel->loadBean(new Tests\Helpers\DummyBean()); - $eventMock = Mockery::mock('\Box_EventManager'); - $eventMock->shouldReceive('fire'); + $eventMock = Mockery::mock(Box_EventManager::class); + $eventMock->shouldReceive('fire')->atLeast()->once(); - $dbMock = Mockery::mock('\Box_Database'); - $dbMock->shouldReceive('store') - ->with($clientOrderModel); + $dbMock = Mockery::mock(Box_Database::class); + $dbMock->shouldReceive('store')->atLeast()->once()->with($clientOrderModel); $di = container(); $di['events_manager'] = $eventMock; $di['db'] = $dbMock; - $di['logger'] = new Tests\Helpers\TestLogger(); + $di['logger'] = new Box_Log(); $data = [ 'period' => '1Y', @@ -1600,125 +1809,171 @@ test('updates order', function (): void { ]; $serviceMock = Mockery::mock(Service::class)->makePartial(); - $serviceMock->shouldReceive('updatePeriod') - ->with($clientOrderModel, $data['period']); - $serviceMock->shouldReceive('updateOrderMeta') - ->with($clientOrderModel, $data['meta']); + $serviceMock->shouldAllowMockingProtectedMethods(); + $serviceMock->shouldReceive('updatePeriod')->atLeast()->once()->with($clientOrderModel, $data['period']); + $serviceMock->shouldReceive('updateOrderMeta')->atLeast()->once()->with($clientOrderModel, $data['meta']); $serviceMock->setDi($di); + $result = $serviceMock->updateOrder($clientOrderModel, $data); + expect($result)->toBeTrue(); }); -test('renews order', function (): void { +test('renewOrder renews order', function (): void { $clientOrderModel = new Model_ClientOrder(); $clientOrderModel->loadBean(new Tests\Helpers\DummyBean()); $clientOrderModel->group_master = 1; $clientOrderModel->status = Model_ClientOrder::STATUS_PENDING_SETUP; - $eventMock = Mockery::mock('\Box_EventManager'); - $eventMock->shouldReceive('fire'); + $eventMock = Mockery::mock(Box_EventManager::class); + $eventMock->shouldReceive('fire')->atLeast()->once(); $di = container(); $di['events_manager'] = $eventMock; - $di['logger'] = new Tests\Helpers\TestLogger(); + $di['logger'] = new Box_Log(); $serviceMock = Mockery::mock(Service::class)->makePartial(); - $serviceMock->shouldReceive('renewFromOrder') - ->with($clientOrderModel); - $serviceMock->shouldReceive('getOrderAddonsList') - ->atLeast()->once() - ->andReturn([$clientOrderModel]); + $serviceMock->shouldAllowMockingProtectedMethods(); + $serviceMock->shouldReceive('renewFromOrder')->atLeast()->once()->with($clientOrderModel); + $serviceMock->shouldReceive('getOrderAddonsList')->atLeast()->once()->andReturn([$clientOrderModel]); $serviceMock->setDi($di); + $result = $serviceMock->renewOrder($clientOrderModel); + expect($result)->toBeTrue(); }); -test('renews from order', function (): void { - $serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods(); - $serviceMock->shouldReceive('_callOnService') - ->atLeast()->once(); +test('renewFromOrder extends expiration', function (): void { + $serviceMock = Mockery::mock(Service::class)->makePartial(); + $serviceMock->shouldAllowMockingProtectedMethods(); + $serviceMock->shouldReceive('_callOnService')->atLeast()->once(); + $clientOrderModel = new Model_ClientOrder(); $clientOrderModel->loadBean(new Tests\Helpers\DummyBean()); $clientOrderModel->period = '1Y'; + $clientOrderModel->expires_at = '2026-01-01 00:00:00'; - $periodMock = Mockery::mock('\Box_Period'); - - $dbMock = Mockery::mock('Box_Database'); - - $invoiceServiceMock = Mockery::mock(Box\Mod\Invoice\Service::class); - $invoiceServiceMock->shouldReceive('findPaidInvoicesForOrder'); + $expectedExpiration = strtotime('2027-01-01 00:00:00'); + $periodMock = Mockery::mock(Box_Period::class); $periodMock->shouldReceive('getExpirationTime') ->atLeast()->once() - ->andReturn(time() + 3600); + ->with(strtotime('2026-01-01 00:00:00')) + ->andReturn($expectedExpiration); + + $dbMock = Mockery::mock(Box_Database::class); + $dbMock->shouldReceive('store')->atLeast()->once(); + + $serviceMock->shouldReceive('saveStatusChange') + ->atLeast()->once() + ->with($clientOrderModel, 'Order renewed'); $di = container(); $di['mod_config'] = $di->protect(fn ($name): array => []); - $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $invoiceServiceMock); $di['period'] = $di->protect(fn (): Mockery\MockInterface => $periodMock); - $statusModel = new Model_ClientOrderStatus(); - $statusModel->loadBean(new Tests\Helpers\DummyBean()); - $dbMock->shouldReceive('dispense') - ->with('ClientOrderStatus') - ->byDefault() - ->andReturn($statusModel); - $dbMock->shouldReceive('store') - ->byDefault(); $di['db'] = $dbMock; $serviceMock->setDi($di); $serviceMock->renewFromOrder($clientOrderModel); + + expect($clientOrderModel->expires_at)->toEqual('2027-01-01 00:00:00'); + expect($clientOrderModel->status)->toEqual(Model_ClientOrder::STATUS_ACTIVE); }); -test('throws exception when suspending non-active order', function (): void { - $orderService = new Service(); +test('renewFromOrder extends free first term on first paid renewal', function (): void { + $clientOrderModel = new Model_ClientOrder(); + $clientOrderModel->loadBean(new Tests\Helpers\DummyBean()); + $clientOrderModel->period = '1Y'; + $clientOrderModel->status = Model_ClientOrder::STATUS_ACTIVE; + $clientOrderModel->activated_at = '2025-01-01 00:00:00'; + $clientOrderModel->expires_at = '2026-01-01 00:00:00'; + + $serviceMock = Mockery::mock(Service::class)->makePartial(); + $serviceMock->shouldAllowMockingProtectedMethods(); + $serviceMock->shouldReceive('_callOnService') + ->once() + ->with(Mockery::on(fn ($order): bool => $order === $clientOrderModel), Model_ClientOrder::ACTION_RENEW); + + $expectedExpiration = strtotime('2027-01-01 00:00:00'); + $periodMock = Mockery::mock(Box_Period::class); + $periodMock->shouldReceive('getExpirationTime') + ->once() + ->with(strtotime('2026-01-01 00:00:00')) + ->andReturn($expectedExpiration); + + $dbMock = Mockery::mock(Box_Database::class); + $dbMock->shouldReceive('store')->atLeast()->once(); + + $serviceMock->shouldReceive('saveStatusChange') + ->once() + ->with($clientOrderModel, 'Order renewed'); + + $di = container(); + $di['mod_config'] = $di->protect(fn ($name): array => []); + $di['period'] = $di->protect(fn (): Mockery\MockInterface => $periodMock); + $di['db'] = $dbMock; + + $serviceMock->setDi($di); + $serviceMock->renewFromOrder($clientOrderModel); + + expect($clientOrderModel->expires_at)->toEqual('2027-01-01 00:00:00'); + expect($clientOrderModel->status)->toEqual(Model_ClientOrder::STATUS_ACTIVE); +}); + +test('suspendFromOrder throws for non-active order', function (): void { $clientOrderModel = new Model_ClientOrder(); $clientOrderModel->loadBean(new Tests\Helpers\DummyBean()); $clientOrderModel->status = Model_ClientOrder::STATUS_SUSPENDED; - $eventMock = Mockery::mock('\Box_EventManager'); - $eventMock->shouldReceive('fire'); + $eventMock = Mockery::mock(Box_EventManager::class); + $eventMock->shouldReceive('fire')->atLeast()->once(); $di = container(); $di['events_manager'] = $eventMock; - $orderService->setDi($di); + $svc = new Service(); + $svc->setDi($di); - expect(fn (): bool => $orderService->suspendFromOrder($clientOrderModel)) + expect(fn () => $svc->suspendFromOrder($clientOrderModel)) ->toThrow(FOSSBilling\Exception::class, 'Only active orders can be suspended'); }); -test('suspends from order', function (): void { +test('suspendFromOrder suspends active order', function (): void { $clientOrderModel = new Model_ClientOrder(); $clientOrderModel->loadBean(new Tests\Helpers\DummyBean()); $clientOrderModel->status = Model_ClientOrder::STATUS_ACTIVE; - $eventMock = Mockery::mock('\Box_EventManager'); - $eventMock->shouldReceive('fire'); + $eventMock = Mockery::mock(Box_EventManager::class); + $eventMock->shouldReceive('fire')->atLeast()->once(); - $dbMock = Mockery::mock('\Box_Database'); - $dbMock->shouldReceive('store') - ->with($clientOrderModel); + $dbMock = Mockery::mock(Box_Database::class); + $dbMock->shouldReceive('store')->atLeast()->once()->with($clientOrderModel); $di = container(); $di['events_manager'] = $eventMock; - $di['logger'] = new Tests\Helpers\TestLogger(); + $di['logger'] = new Box_Log(); $di['db'] = $dbMock; - $serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods(); - $serviceMock->shouldReceive('_callOnService'); - $serviceMock->shouldReceive('saveStatusChange'); + $serviceMock = Mockery::mock(Service::class)->makePartial(); + $serviceMock->shouldAllowMockingProtectedMethods(); + $serviceMock->shouldReceive('_callOnService')->atLeast()->once(); + $serviceMock->shouldReceive('saveStatusChange')->atLeast()->once(); $serviceMock->setDi($di); + $result = $serviceMock->suspendFromOrder($clientOrderModel); + expect($result)->toBeTrue(); }); -test('removes orders by client', function (): void { - $orderService = new Service(); +test('rmByClient removes all client orders', function (): void { $clientModel = new Model_Client(); $clientModel->loadBean(new Tests\Helpers\DummyBean()); + $clientModel->id = 100; + + $orderModel = new Model_ClientOrder(); + $orderModel->loadBean(new Tests\Helpers\DummyBean()); $queryBuilderMock = new class { private bool $deleteCalled = false; @@ -1799,114 +2054,347 @@ test('removes orders by client', function (): void { } }; - $di = new Pimple\Container(); + $dbMock = Mockery::mock(Box_Database::class); + $dbMock->shouldReceive('find') + ->once() + ->with('ClientOrder', 'client_id = ?', [100]) + ->andReturn([$orderModel]); + + $productServiceMock = Mockery::mock(Box\Mod\Product\Service::class); + $productServiceMock->shouldReceive('releaseReservedPromoRedemptionsForOrder') + ->once() + ->with($orderModel, 'client_deleted'); + + $di = container(); + $di['db'] = $dbMock; $di['dbal'] = $dbalMock; - $orderService->setDi($di); - $orderService->rmByClient($clientModel); + $di['mod_service'] = $di->protect(fn (string $name): Mockery\MockInterface => match (strtolower($name)) { + 'product' => $productServiceMock, + default => Mockery::mock()->shouldIgnoreMissing(), + }); + + $svc = new Service(); + $svc->setDi($di); + + $svc->rmByClient($clientModel); expect($queryBuilderMock->getDeleteTable())->toBe('client_order'); expect($queryBuilderMock->getWhereCond())->toBe('client_id = :id'); expect($queryBuilderMock->getParamId())->toBe($clientModel->id); }); -test('updates period', function (): void { - $orderService = new Service(); +test('updatePeriod sets period when given', function (): void { $period = '1Y'; $di = container(); - $periodMock = Mockery::mock('\Box_Period'); - $periodMock->shouldReceive('getCode'); + $periodMock = Mockery::mock(Box_Period::class); + $periodMock->shouldReceive('getCode')->atLeast()->once(); $di['period'] = $di->protect(fn (): Mockery\MockInterface => $periodMock); - $orderService->setDi($di); + $svc = new Service(); + $svc->setDi($di); + $clientOrder = new Model_ClientOrder(); $clientOrder->loadBean(new Tests\Helpers\DummyBean()); - $result = $orderService->updatePeriod($clientOrder, $period); - expect($result)->toBe(1); + + $result = $svc->updatePeriod($clientOrder, $period); + + expect($result)->toEqual(1); }); -test('updates period when empty', function (): void { - $orderService = new Service(); +test('updatePeriod clears period when empty string', function (): void { $period = ''; $di = container(); - $periodMock = Mockery::mock('\Box_Period'); - $periodMock->shouldReceive('getCode') - ->never(); + + $periodMock = Mockery::mock(Box_Period::class); + $periodMock->shouldReceive('getCode')->never(); $di['period'] = $di->protect(fn (): Mockery\MockInterface => $periodMock); - $orderService->setDi($di); + $svc = new Service(); + $svc->setDi($di); + $clientOrder = new Model_ClientOrder(); $clientOrder->loadBean(new Tests\Helpers\DummyBean()); - $result = $orderService->updatePeriod($clientOrder, $period); - expect($result)->toBe(2); + + $result = $svc->updatePeriod($clientOrder, $period); + + expect($result)->toEqual(2); }); -test('updates period when not set', function (): void { - $orderService = new Service(); +test('updatePeriod does nothing when null', function (): void { $period = null; $di = container(); - $periodMock = Mockery::mock('\Box_Period'); - $periodMock->shouldReceive('getCode') - ->never(); + + $periodMock = Mockery::mock(Box_Period::class); + $periodMock->shouldReceive('getCode')->never(); $di['period'] = $di->protect(fn (): Mockery\MockInterface => $periodMock); - $orderService->setDi($di); + $svc = new Service(); + $svc->setDi($di); + $clientOrder = new Model_ClientOrder(); $clientOrder->loadBean(new Tests\Helpers\DummyBean()); - $result = $orderService->updatePeriod($clientOrder, $period); - expect($result)->toBe(0); + + $result = $svc->updatePeriod($clientOrder, $period); + + expect($result)->toEqual(0); }); -test('updates order meta when not set', function (): void { - $orderService = new Service(); +test('updateOrderMeta returns 0 when meta is not an array', function (): void { $meta = null; $clientOrder = new Model_ClientOrder(); $clientOrder->loadBean(new Tests\Helpers\DummyBean()); - $result = $orderService->updateOrderMeta($clientOrder, $meta); - expect($result)->toBe(0); + + $svc = new Service(); + + $result = $svc->updateOrderMeta($clientOrder, $meta); + + expect($result)->toEqual(0); }); -test('updates order meta when empty', function (): void { - $orderService = new Service(); +test('updateOrderMeta clears existing meta when empty', function (): void { $meta = []; $di = container(); - $dBMock = Mockery::mock('\Box_Database'); - $dBMock->shouldReceive('exec') - ->atLeast()->once(); + $dBMock = Mockery::mock(Box_Database::class); + $dBMock->shouldReceive('exec')->atLeast()->once(); $di['db'] = $dBMock; - $orderService->setDi($di); + $svc = new Service(); + $svc->setDi($di); + $clientOrder = new Model_ClientOrder(); $clientOrder->loadBean(new Tests\Helpers\DummyBean()); - $result = $orderService->updateOrderMeta($clientOrder, $meta); - expect($result)->toBe(1); + + $result = $svc->updateOrderMeta($clientOrder, $meta); + + expect($result)->toEqual(1); }); -test('updates order meta', function (): void { - $orderService = new Service(); +test('updateOrderMeta stores new meta entries', function (): void { $meta = ['key' => 'value']; $di = container(); - $dBMock = Mockery::mock('\Box_Database'); + $dBMock = Mockery::mock(Box_Database::class); $dBMock->shouldReceive('findOne') - ->with('ClientOrderMeta', 'client_order_id = :id AND name = :n', Mockery::type('array')) ->atLeast()->once() + ->with('ClientOrderMeta', Mockery::any(), Mockery::any()) ->andReturn(null); $clientOrderMetaModel = new Model_ClientOrderMeta(); $clientOrderMetaModel->loadBean(new Tests\Helpers\DummyBean()); + $dBMock->shouldReceive('dispense') - ->with('ClientOrderMeta') ->atLeast()->once() + ->with('ClientOrderMeta') ->andReturn($clientOrderMetaModel); - $dBMock->shouldReceive('store') - ->atLeast()->once(); + $dBMock->shouldReceive('store')->atLeast()->once(); + $di['db'] = $dBMock; - $orderService->setDi($di); + $svc = new Service(); + $svc->setDi($di); + $clientOrder = new Model_ClientOrder(); $clientOrder->loadBean(new Tests\Helpers\DummyBean()); - $result = $orderService->updateOrderMeta($clientOrder, $meta); - expect($result)->toBe(2); + + $result = $svc->updateOrderMeta($clientOrder, $meta); + + expect($result)->toEqual(2); +}); + +test('updateOrderConfig succeeds when no form id is set', function (): void { + $di = container(); + + $dbMock = Mockery::mock(Box_Database::class); + $dbMock->shouldReceive('store')->once(); + $di['db'] = $dbMock; + $di['logger'] = new Box_Log(); + + $svc = new Service(); + $svc->setDi($di); + + $order = new Model_ClientOrder(); + $order->loadBean(new Tests\Helpers\DummyBean()); + $order->form_id = null; + + $result = $svc->updateOrderConfig($order, ['key' => 'value']); + + expect($result)->toBeTrue(); +}); + +test('updateOrderConfig throws when required field is missing', function (): void { + $form = [ + 'fields' => [ + ['name' => 'hostname', 'label' => 'Hostname', 'type' => 'text', 'required' => true, 'options' => []], + ], + ]; + + $formbuilderServiceMock = Mockery::mock(Box\Mod\Formbuilder\Service::class); + $formbuilderServiceMock->shouldReceive('getForm')->once()->with(7)->andReturn($form); + + $di = container(); + $di['mod_service'] = $di->protect(function ($serviceName) use ($formbuilderServiceMock) { + if ($serviceName === 'formbuilder') { + return $formbuilderServiceMock; + } + }); + + $svc = new Service(); + $svc->setDi($di); + + $order = new Model_ClientOrder(); + $order->loadBean(new Tests\Helpers\DummyBean()); + $order->form_id = 7; + + expect(fn () => $svc->updateOrderConfig($order, [])) + ->toThrow(FOSSBilling\Exception::class, '', 4892); +}); + +test('updateOrderConfig throws for invalid select option', function (): void { + $form = [ + 'fields' => [ + ['name' => 'plan', 'label' => 'Plan', 'type' => 'select', 'required' => false, 'options' => ['basic' => 'Basic', 'pro' => 'Pro']], + ], + ]; + + $formbuilderServiceMock = Mockery::mock(Box\Mod\Formbuilder\Service::class); + $formbuilderServiceMock->shouldReceive('getForm')->once()->andReturn($form); + + $di = container(); + $di['mod_service'] = $di->protect(function ($serviceName) use ($formbuilderServiceMock) { + if ($serviceName === 'formbuilder') { + return $formbuilderServiceMock; + } + }); + + $svc = new Service(); + $svc->setDi($di); + + $order = new Model_ClientOrder(); + $order->loadBean(new Tests\Helpers\DummyBean()); + $order->form_id = 8; + + expect(fn () => $svc->updateOrderConfig($order, ['plan' => 'enterprise'])) + ->toThrow(FOSSBilling\Exception::class, '', 4893); +}); + +test('updateOrderConfig select rejects array value', function (): void { + $form = [ + 'fields' => [ + ['name' => 'plan', 'label' => 'Plan', 'type' => 'select', 'required' => false, 'options' => ['basic' => 'Basic', 'pro' => 'Pro']], + ], + ]; + + $formbuilderServiceMock = Mockery::mock(Box\Mod\Formbuilder\Service::class); + $formbuilderServiceMock->shouldReceive('getForm')->once()->andReturn($form); + + $di = container(); + $di['mod_service'] = $di->protect(function ($serviceName) use ($formbuilderServiceMock) { + if ($serviceName === 'formbuilder') { + return $formbuilderServiceMock; + } + }); + + $svc = new Service(); + $svc->setDi($di); + + $order = new Model_ClientOrder(); + $order->loadBean(new Tests\Helpers\DummyBean()); + $order->form_id = 11; + + expect(fn () => $svc->updateOrderConfig($order, ['plan' => ['pro']])) + ->toThrow(FOSSBilling\Exception::class, '', 4893); +}); + +test('updateOrderConfig throws for invalid radio option', function (): void { + $form = [ + 'fields' => [ + ['name' => 'os', 'label' => 'OS', 'type' => 'radio', 'required' => false, 'options' => ['linux' => 'Linux', 'windows' => 'Windows']], + ], + ]; + + $formbuilderServiceMock = Mockery::mock(Box\Mod\Formbuilder\Service::class); + $formbuilderServiceMock->shouldReceive('getForm')->once()->andReturn($form); + + $di = container(); + $di['mod_service'] = $di->protect(function ($serviceName) use ($formbuilderServiceMock) { + if ($serviceName === 'formbuilder') { + return $formbuilderServiceMock; + } + }); + + $svc = new Service(); + $svc->setDi($di); + + $order = new Model_ClientOrder(); + $order->loadBean(new Tests\Helpers\DummyBean()); + $order->form_id = 9; + + expect(fn () => $svc->updateOrderConfig($order, ['os' => 'macos'])) + ->toThrow(FOSSBilling\Exception::class, '', 4893); +}); + +test('updateOrderConfig throws for invalid checkbox option', function (): void { + $form = [ + 'fields' => [ + ['name' => 'addons', 'label' => 'Addons', 'type' => 'checkbox', 'required' => false, 'options' => ['backup', 'ssl']], + ], + ]; + + $formbuilderServiceMock = Mockery::mock(Box\Mod\Formbuilder\Service::class); + $formbuilderServiceMock->shouldReceive('getForm')->once()->andReturn($form); + + $di = container(); + $di['mod_service'] = $di->protect(function ($serviceName) use ($formbuilderServiceMock) { + if ($serviceName === 'formbuilder') { + return $formbuilderServiceMock; + } + }); + + $svc = new Service(); + $svc->setDi($di); + + $order = new Model_ClientOrder(); + $order->loadBean(new Tests\Helpers\DummyBean()); + $order->form_id = 10; + + expect(fn () => $svc->updateOrderConfig($order, ['addons' => ['backup', 'ddos-protection']])) + ->toThrow(FOSSBilling\Exception::class, '', 4894); +}); + +test('updateOrderConfig succeeds with valid form data', function (): void { + $form = [ + 'fields' => [ + ['name' => 'hostname', 'label' => 'Hostname', 'type' => 'text', 'required' => true, 'options' => []], + ['name' => 'plan', 'label' => 'Plan', 'type' => 'select', 'required' => false, 'options' => ['basic' => 'Basic', 'pro' => 'Pro']], + ['name' => 'addons', 'label' => 'Addons', 'type' => 'checkbox', 'required' => false, 'options' => ['backup', 'ssl']], + ], + ]; + + $formbuilderServiceMock = Mockery::mock(Box\Mod\Formbuilder\Service::class); + $formbuilderServiceMock->shouldReceive('getForm')->once()->andReturn($form); + + $dbMock = Mockery::mock(Box_Database::class); + $dbMock->shouldReceive('store')->once(); + + $di = container(); + $di['mod_service'] = $di->protect(function ($serviceName) use ($formbuilderServiceMock) { + if ($serviceName === 'formbuilder') { + return $formbuilderServiceMock; + } + }); + $di['db'] = $dbMock; + $di['logger'] = new Box_Log(); + + $svc = new Service(); + $svc->setDi($di); + + $order = new Model_ClientOrder(); + $order->loadBean(new Tests\Helpers\DummyBean()); + $order->form_id = 11; + + $result = $svc->updateOrderConfig($order, ['hostname' => 'myhost.example.com', 'plan' => 'pro', 'addons' => ['backup', 'ssl']]); + + expect($result)->toBeTrue(); }); diff --git a/src/modules/Orderbutton/templates/client/mod_orderbutton_checkout.html.twig b/src/modules/Orderbutton/templates/client/mod_orderbutton_checkout.html.twig index 6f335ca8d..18d01b110 100644 --- a/src/modules/Orderbutton/templates/client/mod_orderbutton_checkout.html.twig +++ b/src/modules/Orderbutton/templates/client/mod_orderbutton_checkout.html.twig @@ -35,7 +35,7 @@ {% if item.discount_price %} {{ (item.total * cart_currency.conversion_rate)|format_currency(cart_currency.code) }} - {{ (item.total-item.discount_price * cart_currency.conversion_rate)|format_currency(cart_currency.code) }} + {{ ((item.total - item.discount_price) * cart_currency.conversion_rate)|format_currency(cart_currency.code) }} {% else %} {{ (item.total * cart_currency.conversion_rate)|format_currency(cart_currency.code) }} {% endif %} @@ -111,8 +111,8 @@ -
-
+
+
{% if not cart.promocode %} {{ 'Have a coupon code?'|trans }} {% endif %} @@ -134,7 +134,7 @@
-
+
{% if cart.discount >0 %} @@ -194,7 +194,7 @@ {% if enough_in_balance %}

{{ 'Total amount will be deducted from account balance'|trans }}

{% endif %} - {% if settings.checkout_tos == 'explicit' %} + {% if settings.checkout_tos|default('0') == 'explicit' %}
- {% if settings.checkout_tos == 'implicit' %} + {% if settings.checkout_tos|default('0') == 'implicit' %} {# TODO: Make this translatable once support for placeholders is implemented #} By completing your order, you agree to our {{ 'Terms of Service'|trans }} and {{ 'Privacy Policy'|trans }}. {% endif %} diff --git a/src/modules/Orderbutton/templates/client/mod_orderbutton_client.html.twig b/src/modules/Orderbutton/templates/client/mod_orderbutton_client.html.twig index 726620e6c..182bdfc20 100644 --- a/src/modules/Orderbutton/templates/client/mod_orderbutton_client.html.twig +++ b/src/modules/Orderbutton/templates/client/mod_orderbutton_client.html.twig @@ -232,7 +232,7 @@ {% endif %} {% endfor %} {{ mf.recaptcha }} - {% if settings.signup_tos == 'explicit' %} + {% if settings.signup_tos|default('0') == 'explicit' %}
- {% if settings.signup_tos == 'implicit' %} + {% if settings.signup_tos|default('0') == 'implicit' %}
{# TODO: Make this translatable once support for placeholders is implemented #} By creating an account, you agree to our {{ 'Terms of Service'|trans }} and {{ 'Privacy Policy'|trans }}. diff --git a/src/modules/Orderbutton/templates/client/mod_orderbutton_js.html.twig b/src/modules/Orderbutton/templates/client/mod_orderbutton_js.html.twig index 803fb3d85..2ce6df8b8 100644 --- a/src/modules/Orderbutton/templates/client/mod_orderbutton_js.html.twig +++ b/src/modules/Orderbutton/templates/client/mod_orderbutton_js.html.twig @@ -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); }); } diff --git a/src/modules/Page/templates/client/mod_page_signup.html.twig b/src/modules/Page/templates/client/mod_page_signup.html.twig index 600d7cac9..1509af710 100644 --- a/src/modules/Page/templates/client/mod_page_signup.html.twig +++ b/src/modules/Page/templates/client/mod_page_signup.html.twig @@ -174,7 +174,7 @@ {{ mf.recaptcha }} - {% if settings.signup_tos == 'explicit' %} + {% if settings.signup_tos|default('0') == 'explicit' %}
- {% if settings.signup_tos == 'implicit' %} + {% if settings.signup_tos|default('0') == 'implicit' %}
{# TODO: Make this translatable once support for placeholders is implemented #} By creating an account, you agree to our {{ 'Terms of Service'|trans }} and {{ 'Privacy Policy'|trans }}. diff --git a/src/modules/Product/Api/Admin.php b/src/modules/Product/Api/Admin.php index cca6b09cc..1187170d4 100644 --- a/src/modules/Product/Api/Admin.php +++ b/src/modules/Product/Api/Admin.php @@ -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']); } } diff --git a/src/modules/Product/Api/Guest.php b/src/modules/Product/Api/Guest.php index a04c4e5d6..535fa66e9 100644 --- a/src/modules/Product/Api/Guest.php +++ b/src/modules/Product/Api/Guest.php @@ -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); } /** diff --git a/src/modules/Product/Entity/Product.php b/src/modules/Product/Entity/Product.php new file mode 100644 index 000000000..435697325 --- /dev/null +++ b/src/modules/Product/Entity/Product.php @@ -0,0 +1,406 @@ + '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; + } +} diff --git a/src/modules/Product/Entity/ProductCategory.php b/src/modules/Product/Entity/ProductCategory.php new file mode 100644 index 000000000..5b93216f7 --- /dev/null +++ b/src/modules/Product/Entity/ProductCategory.php @@ -0,0 +1,106 @@ +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; + } +} diff --git a/src/modules/Product/Entity/ProductPayment.php b/src/modules/Product/Entity/ProductPayment.php new file mode 100644 index 000000000..903046122 --- /dev/null +++ b/src/modules/Product/Entity/ProductPayment.php @@ -0,0 +1,176 @@ + '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; + } +} diff --git a/src/modules/Product/Entity/Promo.php b/src/modules/Product/Entity/Promo.php new file mode 100644 index 000000000..909031fb0 --- /dev/null +++ b/src/modules/Product/Entity/Promo.php @@ -0,0 +1,326 @@ + '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; + } +} diff --git a/src/modules/Product/Entity/PromoRedemption.php b/src/modules/Product/Entity/PromoRedemption.php new file mode 100644 index 000000000..992e9c5bf --- /dev/null +++ b/src/modules/Product/Entity/PromoRedemption.php @@ -0,0 +1,265 @@ + $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; + } +} diff --git a/src/modules/Product/Repository/DomainPricingRepository.php b/src/modules/Product/Repository/DomainPricingRepository.php new file mode 100644 index 000000000..29851c055 --- /dev/null +++ b/src/modules/Product/Repository/DomainPricingRepository.php @@ -0,0 +1,58 @@ +> + */ + 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; + } +} diff --git a/src/modules/Product/Repository/ProductCategoryRepository.php b/src/modules/Product/Repository/ProductCategoryRepository.php new file mode 100644 index 000000000..0f69a336a --- /dev/null +++ b/src/modules/Product/Repository/ProductCategoryRepository.php @@ -0,0 +1,60 @@ + + */ + 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); + } +} diff --git a/src/modules/Product/Repository/ProductOrderRepository.php b/src/modules/Product/Repository/ProductOrderRepository.php new file mode 100644 index 000000000..1bf9276e3 --- /dev/null +++ b/src/modules/Product/Repository/ProductOrderRepository.php @@ -0,0 +1,33 @@ +> + */ + public function getRowsByProductId(int $productId): array + { + return $this->connection->fetchAllAssociative( + 'SELECT * FROM client_order WHERE product_id = ?', + [$productId] + ); + } +} diff --git a/src/library/Model/ProductDownloadable.php b/src/modules/Product/Repository/ProductPaymentRepository.php similarity index 68% rename from src/library/Model/ProductDownloadable.php rename to src/modules/Product/Repository/ProductPaymentRepository.php index 60bcdf6ed..e4801d780 100644 --- a/src/library/Model/ProductDownloadable.php +++ b/src/modules/Product/Repository/ProductPaymentRepository.php @@ -9,6 +9,11 @@ declare(strict_types=1); * @copyright FOSSBilling (https://www.fossbilling.org) * @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0 */ -class Model_ProductDownloadable extends RedBeanPHP\SimpleModel + +namespace Box\Mod\Product\Repository; + +use Doctrine\ORM\EntityRepository; + +class ProductPaymentRepository extends EntityRepository { } diff --git a/src/modules/Product/Repository/ProductRepository.php b/src/modules/Product/Repository/ProductRepository.php new file mode 100644 index 000000000..172264754 --- /dev/null +++ b/src/modules/Product/Repository/ProductRepository.php @@ -0,0 +1,201 @@ + + */ + 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 + */ + public function findEnabledVisibleByCategoryId(int $categoryId): array + { + return $this->findBy([ + 'isAddon' => false, + 'status' => 'enabled', + 'hidden' => false, + 'productCategoryId' => $categoryId, + ], [ + 'priority' => 'ASC', + ]); + } + + /** + * @param list $ids + * + * @return list + */ + public function findByIds(array $ids): array + { + if ($ids === []) { + return []; + } + + return $this->findBy([ + 'id' => $ids, + ]); + } + + /** + * @param list $ids + * + * @return list + */ + 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', + ]); + } +} diff --git a/src/modules/Product/Repository/PromoRedemptionRepository.php b/src/modules/Product/Repository/PromoRedemptionRepository.php new file mode 100644 index 000000000..42e7d952c --- /dev/null +++ b/src/modules/Product/Repository/PromoRedemptionRepository.php @@ -0,0 +1,131 @@ +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), + ]; + } +} diff --git a/src/modules/Product/Repository/PromoRepository.php b/src/modules/Product/Repository/PromoRepository.php new file mode 100644 index 000000000..12076d3d2 --- /dev/null +++ b/src/modules/Product/Repository/PromoRepository.php @@ -0,0 +1,99 @@ +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] + ); + } +} diff --git a/src/modules/Product/Service.php b/src/modules/Product/Service.php index 370844bb6..4d41d5b86 100644 --- a/src/modules/Product/Service.php +++ b/src/modules/Product/Service.php @@ -12,7 +12,23 @@ declare(strict_types=1); namespace Box\Mod\Product; +use Box\Mod\Product\Entity\Product; +use Box\Mod\Product\Entity\ProductCategory; +use Box\Mod\Product\Entity\ProductPayment; +use Box\Mod\Product\Entity\Promo; +use Box\Mod\Product\Entity\PromoRedemption; +use Box\Mod\Product\Repository\DomainPricingRepository; +use Box\Mod\Product\Repository\ProductCategoryRepository; +use Box\Mod\Product\Repository\ProductOrderRepository; +use Box\Mod\Product\Repository\ProductPaymentRepository; +use Box\Mod\Product\Repository\ProductRepository; +use Box\Mod\Product\Repository\PromoRedemptionRepository; +use Box\Mod\Product\Repository\PromoRepository; +use Doctrine\DBAL\Connection; +use Doctrine\ORM\QueryBuilder; +use Doctrine\ORM\Tools\Pagination\Paginator as DoctrinePaginator; use FOSSBilling\InjectionAwareInterface; +use FOSSBilling\PaginationOptions; class Service implements InjectionAwareInterface { @@ -29,6 +45,13 @@ class Service implements InjectionAwareInterface final public const string SETUP_MANUAL = 'manual'; protected ?\Pimple\Container $di = null; + protected ?ProductRepository $productRepository = null; + protected ?ProductCategoryRepository $productCategoryRepository = null; + protected ?ProductPaymentRepository $productPaymentRepository = null; + protected ?PromoRepository $promoRepository = null; + protected ?PromoRedemptionRepository $promoRedemptionRepository = null; + protected ?DomainPricingRepository $domainPricingRepository = null; + protected ?ProductOrderRepository $productOrderRepository = null; public function setDi(\Pimple\Container $di): void { @@ -40,6 +63,89 @@ class Service implements InjectionAwareInterface return $this->di; } + public function getPromoRedemptionRepository(): PromoRedemptionRepository + { + if ($this->promoRedemptionRepository === null) { + if ($this->di === null) { + throw new \FOSSBilling\Exception('The dependency injection container has not been set.'); + } + + $this->promoRedemptionRepository = $this->di['em']->getRepository(PromoRedemption::class); + } + + return $this->promoRedemptionRepository; + } + + public function getPromoRepository(): PromoRepository + { + if ($this->promoRepository === null) { + if ($this->di === null) { + throw new \FOSSBilling\Exception('The dependency injection container has not been set.'); + } + + $this->promoRepository = $this->di['em']->getRepository(Promo::class); + } + + return $this->promoRepository; + } + + public function getProductRepository(): ProductRepository + { + if ($this->productRepository === null) { + if ($this->di === null) { + throw new \FOSSBilling\Exception('The dependency injection container has not been set.'); + } + + $this->productRepository = $this->di['em']->getRepository(Product::class); + } + + return $this->productRepository; + } + + public function getProductCategoryRepository(): ProductCategoryRepository + { + if ($this->productCategoryRepository === null) { + if ($this->di === null) { + throw new \FOSSBilling\Exception('The dependency injection container has not been set.'); + } + + $this->productCategoryRepository = $this->di['em']->getRepository(ProductCategory::class); + } + + return $this->productCategoryRepository; + } + + public function getProductPaymentRepository(): ProductPaymentRepository + { + if ($this->productPaymentRepository === null) { + if ($this->di === null) { + throw new \FOSSBilling\Exception('The dependency injection container has not been set.'); + } + + $this->productPaymentRepository = $this->di['em']->getRepository(ProductPayment::class); + } + + return $this->productPaymentRepository; + } + + public function getDomainPricingRepository(): DomainPricingRepository + { + if ($this->domainPricingRepository === null) { + $this->domainPricingRepository = new DomainPricingRepository($this->getDbalConnection()); + } + + return $this->domainPricingRepository; + } + + public function getProductOrderRepository(): ProductOrderRepository + { + if ($this->productOrderRepository === null) { + $this->productOrderRepository = new ProductOrderRepository($this->getDbalConnection()); + } + + return $this->productOrderRepository; + } + /** * @return mixed[] */ @@ -71,84 +177,55 @@ class Service implements InjectionAwareInterface public function getPairs($data): array { - $sql = 'SELECT id, title - FROM product - WHERE 1'; - - $type = $data['type'] ?? null; - $products_only = $data['products_only'] ?? true; - $active_only = $data['active_only'] ?? true; - - $params = []; - if ($products_only) { - $sql .= ' AND is_addon = 0'; - } - - if ($active_only) { - $sql .= ' AND active = 1'; - } - - if ($type) { - $sql .= ' AND type = :type'; - $params['type'] = $type; - } - - $rows = $this->di['db']->getAll($sql, $params); - $result = []; - foreach ($rows as $record) { - $result[$record['id']] = $record['title']; - } - - return $result; + return $this->getProductRepository()->getPairs($data); } - public function toApiArray(\Model_Product $model, $deep = true, $identity = null): array + public function toApiArray(Product $model, $deep = true, $identity = null): array { - $repo = $model->getTable(); - $config = json_decode($model->config ?? '', true) ?? []; - $pricing = $repo->getPricingArray($model); + $config = json_decode($this->getProductConfigJson($model) ?? '', true) ?? []; + $pricing = $this->getProductPricingArray($model); $starting_from = $this->getStartingFromPrice($model); $isAdmin = $identity instanceof \Model_Admin; $addons = $this->getAddonsApiArray($model, $isAdmin); $result = [ - 'id' => $model->id, - 'product_category_id' => $model->product_category_id, - 'type' => $model->type, - 'title' => $model->title, - 'slug' => $model->slug, - 'description' => $model->description, - 'unit' => $model->unit, - 'priority' => $model->priority, + 'id' => $this->getProductId($model), + 'product_category_id' => $this->getProductCategoryId($model), + 'type' => $this->getProductType($model), + 'title' => $this->getProductTitle($model), + 'slug' => $this->getProductSlug($model), + 'description' => $this->getProductDescription($model), + 'unit' => $this->getProductUnit($model), + 'priority' => $this->getProductPriority($model), 'pricing' => $isAdmin ? $pricing : $this->getPublicPricing($pricing), 'config' => $isAdmin ? $config : $this->getPublicConfig($config), 'addons' => $addons, 'price_starting_from' => $starting_from, - 'icon_url' => $model->icon_url, + 'icon_url' => $this->getProductIconUrl($model), // stock control - 'allow_quantity_select' => $model->allow_quantity_select, + 'allow_quantity_select' => $this->isAllowQuantitySelect($model), - // The order form is exposed to guests because the form itself - // is fetched publicly on the checkout step. - 'form_id' => $model->form_id, + // Exposed publicly so the order form can be fetched during guest checkout. + 'form_id' => $this->getProductFormId($model), ]; if ($isAdmin) { - $result['created_at'] = $model->created_at; - $result['updated_at'] = $model->updated_at; - $result['quantity_in_stock'] = $model->quantity_in_stock; - $result['stock_control'] = $model->stock_control; + $result['created_at'] = $this->formatDateTimeValue($this->getProductCreatedAt($model)); + $result['updated_at'] = $this->formatDateTimeValue($this->getProductUpdatedAt($model)); + $result['addons'] = $addons; + $result['quantity_in_stock'] = $this->getProductQuantityInStock($model); + $result['stock_control'] = $this->isStockControlled($model); $result['upgrades'] = $this->getUpgradablePairs($model); - $result['status'] = $model->status; - $result['hidden'] = $model->hidden; - $result['setup'] = $model->setup; - if ($model->product_category_id) { - $productCategory = $this->di['db']->load('ProductCategory', $model->product_category_id); + $result['status'] = $this->getProductStatus($model); + $result['hidden'] = $this->isProductHidden($model); + $result['setup'] = $this->getProductSetup($model); + if ($this->getProductCategoryId($model)) { + $productCategory = $this->findProductCategoryById((int) $this->getProductCategoryId($model)); $result['category'] = [ - 'id' => $productCategory->id, - 'title' => $productCategory->title, + 'id' => $productCategory->getId(), + 'title' => $productCategory->getTitle(), ]; } } @@ -209,17 +286,123 @@ class Service implements InjectionAwareInterface return $data; } - public function getMainDomainProduct() + public function getMainDomainProduct(): ?Product { - return $this->di['db']->findOne('Product', 'type = ?', [self::DOMAIN]); + return $this->getProductRepository()->findMainDomainProduct(); + } + + public function getCartProductTitle(Product $product, ?array $config = null): string + { + $service = $this->getProductModuleService($product); + if (method_exists($service, 'getCartProductTitle')) { + return $service->getCartProductTitle($product, $config ?? []); + } + + return (string) $this->getProductTitle($product); + } + + public function validateSelectedAddonsForProduct(Product $product, array $addons): void + { + $validAddons = json_decode($this->getProductAddonsJson($product) ?? '', true); + if (empty($validAddons)) { + $validAddons = []; + } + + foreach ($addons as $addonId => $properties) { + if (!($properties['selected'] ?? false)) { + continue; + } + + $addon = $this->getAddonById((int) $addonId); + if (!$addon instanceof Product || $this->getProductStatus($addon) !== 'enabled' || !in_array((int) $addonId, $validAddons)) { + throw new \FOSSBilling\InformationException('One or more of your selected add-ons are invalid for the associated product.'); + } + } + } + + public function prepareCartProductConfig(Product $product, array $config): array + { + $service = $this->getProductModuleService($product); + + if (method_exists($service, 'attachOrderConfig')) { + $config = $service->attachOrderConfig($product, $config); + } + + if (method_exists($service, 'validateOrderData')) { + $service->validateOrderData($config); + } + + if (method_exists($service, 'validateCustomForm')) { + $service->validateCustomForm($config, $this->getProductValidationData($product)); + } + + return $config; + } + + /** + * @return array> + */ + public function getDomainPricingArray(): array + { + return $this->getDomainPricingRepository()->getActivePricingByTld(); + } + + public function getProductPricingArray(Product $product): array + { + if ($this->getProductType($product) === self::DOMAIN) { + return $this->getDomainPricingArray(); + } + + if ($this->getProductPaymentId($product)) { + $productPayment = $this->getProductPaymentById((int) $this->getProductPaymentId($product)); + + return $this->toProductPaymentApiArray($productPayment); + } + + throw new \FOSSBilling\Exception('Product pricing could not be determined.'); + } + + public function getProductUnit(Product $product): string + { + if ($this->getProductType($product) === self::DOMAIN) { + return 'year'; + } + + return (string) $product->getUnit(); + } + + public function isRecurrentProductPricing(Product $product): bool + { + $pricing = $this->getProductPricingArray($product); + + return isset($pricing['type']) && $pricing['type'] == ProductPayment::RECURRENT; + } + + public function isProductPeriodEnabled(Product $product, string $period): bool + { + $pricing = $this->getProductPricingArray($product); + if (($pricing['type'] ?? null) == ProductPayment::RECURRENT) { + return (bool) ($pricing['recurrent'][$period]['enabled'] ?? false); + } + + return true; + } + + public function getRelatedProductDiscount(Product $product, array $items, ?array $config = null): float + { + if ($this->getProductType($product) === self::DOMAIN) { + return $this->getDomainRelatedDiscount($items, $config ?? []); + } + + return 0.0; } public function getPaymentTypes(): array { return [ - \Model_ProductPayment::FREE => 'Free', - \Model_ProductPayment::ONCE => 'One Time', - \Model_ProductPayment::RECURRENT => 'Recurrent', + ProductPayment::FREE => 'Free', + ProductPayment::ONCE => 'One time', + ProductPayment::RECURRENT => 'Recurrent', ]; } @@ -228,37 +411,33 @@ class Service implements InjectionAwareInterface $sql = 'SELECT MAX(priority) FROM product LIMIT 1'; $priority = $this->di['db']->getCell($sql); - $modelPayment = $this->di['db']->dispense('ProductPayment'); - $modelPayment->type = \Model_ProductPayment::FREE; - $paymentId = $this->di['db']->store($modelPayment); + $productPayment = $this->createDefaultProductPayment(); + $paymentId = (int) $productPayment->getId(); - $model = $this->di['db']->dispense('Product'); - $model->product_payment_id = $paymentId; - $model->product_category_id = $categoryId; - $model->status = \Model_Product::STATUS_DISABLED; - $model->title = $title; - $model->slug = $this->di['tools']->slug($title); - $model->type = $type; - $model->setup = self::SETUP_AFTER_PAYMENT; - $model->priority = $priority + 10; + $slug = $this->generateUniqueProductSlug($title); - $model->updated_at = date('Y-m-d H:i:s'); - $model->created_at = date('Y-m-d H:i:s'); + $model = new Product(); + $model + ->setProductPaymentId($paymentId) + ->setProductCategoryId($categoryId !== null ? (int) $categoryId : null) + ->setStatus('disabled') + ->setTitle($title) + ->setSlug($slug) + ->setType($type) + ->setSetup(self::SETUP_AFTER_PAYMENT) + ->setPriority((int) $priority + 10) + ->setUpdatedAt(new \DateTime()) + ->setCreatedAt(new \DateTime()); - // try save with slug - try { - $productId = $this->di['db']->store($model); - } catch (\Exception) { - $model->slug = $this->di['tools']->slug($title) . '-' . random_int(1, 9999); - } - $productId = $this->di['db']->store($model); - - $this->di['logger']->info('Created new product #%s', $model->id); + $this->di['em']->persist($model); + $this->di['em']->flush(); + $productId = $model->getId(); + $this->di['logger']->info('Created new product #%s', $model->getId()); return (int) $productId; } - public function updateProduct(\Model_Product $model, $data): bool + public function updateProduct(Product $model, $data): bool { // pricing if (isset($data['pricing'])) { @@ -267,107 +446,56 @@ class Service implements InjectionAwareInterface if (!isset($data['pricing']['type']) || !array_key_exists($data['pricing']['type'], $types)) { throw new \FOSSBilling\InformationException('Pricing type is required'); } - $productPayment = $this->di['db']->getExistingModelById('ProductPayment', $model->product_payment_id, 'Product payment not found'); - - $pricing = $data['pricing']; - $productPayment->type = $data['pricing']['type']; - - if ($data['pricing']['type'] == \Model_ProductPayment::ONCE) { - $productPayment->once_setup_price = (float) $data['pricing']['once']['setup']; - $productPayment->once_price = (float) $data['pricing']['once']['price']; - } - - if ($data['pricing']['type'] == \Model_ProductPayment::RECURRENT) { - if (isset($pricing['recurrent']['1W'])) { - $productPayment->w_setup_price = $pricing['recurrent']['1W']['setup']; - $productPayment->w_price = $pricing['recurrent']['1W']['price']; - $productPayment->w_enabled = $pricing['recurrent']['1W']['enabled'] ?? 0; - } - - if (isset($pricing['recurrent']['1M'])) { - $productPayment->m_setup_price = $pricing['recurrent']['1M']['setup']; - $productPayment->m_price = $pricing['recurrent']['1M']['price']; - $productPayment->m_enabled = $pricing['recurrent']['1M']['enabled'] ?? 0; - } - - if (isset($pricing['recurrent']['3M'])) { - $productPayment->q_setup_price = $pricing['recurrent']['3M']['setup']; - $productPayment->q_price = $pricing['recurrent']['3M']['price']; - $productPayment->q_enabled = $pricing['recurrent']['3M']['enabled'] ?? 0; - } - - if (isset($pricing['recurrent']['6M'])) { - $productPayment->b_setup_price = $pricing['recurrent']['6M']['setup']; - $productPayment->b_price = $pricing['recurrent']['6M']['price']; - $productPayment->b_enabled = $pricing['recurrent']['6M']['enabled'] ?? 0; - } - - if (isset($pricing['recurrent']['1Y'])) { - $productPayment->a_setup_price = $pricing['recurrent']['1Y']['setup']; - $productPayment->a_price = $pricing['recurrent']['1Y']['price']; - $productPayment->a_enabled = $pricing['recurrent']['1Y']['enabled'] ?? 0; - } - - if (isset($pricing['recurrent']['2Y'])) { - $productPayment->bia_setup_price = $pricing['recurrent']['2Y']['setup']; - $productPayment->bia_price = $pricing['recurrent']['2Y']['price']; - $productPayment->bia_enabled = $pricing['recurrent']['2Y']['enabled'] ?? 0; - } - - if (isset($pricing['recurrent']['3Y'])) { - $productPayment->tria_setup_price = $pricing['recurrent']['3Y']['setup']; - $productPayment->tria_price = $pricing['recurrent']['3Y']['price']; - $productPayment->tria_enabled = $pricing['recurrent']['3Y']['enabled'] ?? 0; - } - } - - $this->di['db']->store($productPayment); + $productPayment = $this->getProductPaymentById((int) $this->getProductPaymentId($model)); + $this->applyPricingToProductPayment($productPayment, $data['pricing']); + $this->di['em']->flush(); } if (isset($data['config']) && is_array($data['config'])) { - $current = json_decode($model->config ?? '', true) ?? []; + $current = json_decode($this->getProductConfigJson($model) ?? '', true) ?? []; $c = array_merge($current, $data['config']); - $model->config = json_encode($c); + $this->setProductConfigJson($model, json_encode($c)); } - $form_id = $data['form_id'] ?? $model->form_id; + $form_id = $data['form_id'] ?? $this->getProductFormId($model); + $productCategoryId = $data['product_category_id'] ?? $this->getProductCategoryId($model); - $model->product_category_id = $data['product_category_id'] ?? $model->product_category_id; - $model->form_id = empty($form_id) ? null : $form_id; - $model->icon_url = $data['icon_url'] ?? $model->icon_url; - $model->status = $data['status'] ?? $model->status; - $model->hidden = (int) ($data['hidden'] ?? $model->hidden); - $model->slug = $data['slug'] ?? $model->slug; - $model->setup = $data['setup'] ?? $model->setup; + $this->setProductCategoryIdValue($model, empty($productCategoryId) ? null : (int) $productCategoryId); + $this->setProductFormIdValue($model, empty($form_id) ? null : (int) $form_id); + $this->setProductIconUrlValue($model, $data['icon_url'] ?? $this->getProductIconUrl($model)); + $this->setProductStatusValue($model, (string) ($data['status'] ?? $this->getProductStatus($model))); + $this->setProductHiddenValue($model, (bool) ($data['hidden'] ?? $this->isProductHidden($model))); + $this->setProductSlugValue($model, $data['slug'] ?? $this->getProductSlug($model)); + $this->setProductSetupValue($model, (string) ($data['setup'] ?? $this->getProductSetup($model))); // remove empty value in data['upgrades]; if (is_array($data['upgrades'] ?? null)) { $upgrades = array_values(array_filter($data['upgrades'])); if (empty($upgrades)) { - $model->upgrades = null; + $this->setProductUpgradesJson($model, null); } else { - $model->upgrades = json_encode($upgrades); + $this->setProductUpgradesJson($model, json_encode($upgrades)); } } if (is_array($data['addons'] ?? null)) { $addons = array_values(array_filter($data['addons'])); if (empty($addons)) { - $model->addons = null; + $this->setProductAddonsJsonValue($model, null); } else { - $model->addons = json_encode($addons); + $this->setProductAddonsJsonValue($model, json_encode($addons)); } } - $model->title = $data['title'] ?? $model->title; - $model->stock_control = $data['stock_control'] ?? $model->stock_control; - $model->allow_quantity_select = $data['allow_quantity_select'] ?? $model->allow_quantity_select; - $model->quantity_in_stock = $data['quantity_in_stock'] ?? $model->quantity_in_stock; - $model->description = $data['description'] ?? $model->description; - $model->plugin = $data['plugin'] ?? $model->plugin; - $model->updated_at = date('Y-m-d H:i:s'); + $this->setProductTitleValue($model, $data['title'] ?? $this->getProductTitle($model)); + $this->setProductStockControlValue($model, (bool) ($data['stock_control'] ?? $this->isStockControlled($model))); + $this->setProductAllowQuantitySelectValue($model, (bool) ($data['allow_quantity_select'] ?? $this->isAllowQuantitySelect($model))); + $this->setProductQuantityInStockValue($model, (int) ($data['quantity_in_stock'] ?? $this->getProductQuantityInStock($model))); + $this->setProductDescriptionValue($model, $data['description'] ?? $this->getProductDescription($model)); + $this->setProductPluginValue($model, $data['plugin'] ?? $this->getProductPlugin($model)); + $this->setProductUpdatedAtValue($model, new \DateTime()); - $this->di['db']->store($model); + $this->di['em']->flush(); - $this->di['logger']->info('Updated product #%s configuration', $model->id); + $this->di['logger']->info('Updated product #%s configuration', $this->getProductId($model)); return true; } @@ -375,23 +503,24 @@ class Service implements InjectionAwareInterface public function updatePriority($data): bool { foreach ($data['priority'] as $id => $p) { - $model = $this->di['db']->load('Product', $id); - if ($model instanceof \Model_Product) { - $model->priority = $p; - $model->updated_at = date('Y-m-d H:i:s'); - $this->di['db']->store($model); + $model = $this->getProductRepository()->find((int) $id); + if ($model instanceof Product) { + $model->setPriority((int) $p); + $model->setUpdatedAt(new \DateTime()); } } + $this->di['em']->flush(); + $this->di['logger']->info('Changed product priorities'); return true; } - public function updateConfig(\Model_Product $model, $data): bool + public function updateConfig(Product $model, $data): bool { /* add new config value */ - $config = json_decode($model->config ?? '', true) ?? []; + $config = json_decode($this->getProductConfigJson($model) ?? '', true) ?? []; if (isset($data['config']) && is_array($data['config'])) { $config = array_intersect_key((array) $config, $data['config']); @@ -412,11 +541,11 @@ class Service implements InjectionAwareInterface $config[$data['new_config_name']] = $data['new_config_value']; } - $model->config = json_encode($config); - $model->updated_at = date('Y-m-d H:i:s'); - $this->di['db']->store($model); + $this->setProductConfigJson($model, json_encode($config)); + $this->setProductUpdatedAtValue($model, new \DateTime()); + $this->di['em']->flush(); - $this->di['logger']->info('Updated product #%s configuration', $model->id); + $this->di['logger']->info('Updated product #%s configuration', $this->getProductId($model)); return true; } @@ -442,150 +571,117 @@ class Service implements InjectionAwareInterface public function createAddon($title, $description = null, $setup = null, $status = null, $iconUrl = null) { - $modelPayment = $this->di['db']->dispense('ProductPayment'); - $modelPayment->type = \Model_ProductPayment::FREE; - $paymentId = $this->di['db']->store($modelPayment); + $productPayment = $this->createDefaultProductPayment(); + $paymentId = (int) $productPayment->getId(); - $model = $this->di['db']->dispense('Product'); - $model->product_payment_id = $paymentId; - $model->product_category_id = null; - $model->status = $status ?? \Model_Product::STATUS_DISABLED; - $model->title = $title; - $model->slug = $this->di['tools']->slug($title); - $model->type = self::CUSTOM; - $model->setup = $setup ?? self::SETUP_AFTER_PAYMENT; - $model->is_addon = 1; + $slug = $this->generateUniqueProductSlug($title); - $model->icon_url = $iconUrl; - $model->description = $description; + $model = new Product(); + $model + ->setProductPaymentId($paymentId) + ->setProductCategoryId(null) + ->setStatus($status ?? 'disabled') + ->setTitle($title) + ->setSlug($slug) + ->setType(self::CUSTOM) + ->setSetup($setup ?? self::SETUP_AFTER_PAYMENT) + ->setIsAddon(true) + ->setIconUrl($iconUrl) + ->setDescription($description) + ->setUpdatedAt(new \DateTime()) + ->setCreatedAt(new \DateTime()); - $model->updated_at = date('Y-m-d H:i:s'); - $model->created_at = date('Y-m-d H:i:s'); - - // try save with slug - try { - $productId = $this->di['db']->store($model); - } catch (\Exception) { - $model->slug = $this->di['tools']->slug($title) . '-' . random_int(1, 9999); - $productId = $this->di['db']->store($model); - } + $this->di['em']->persist($model); + $this->di['em']->flush(); + $productId = $model->getId(); $this->di['logger']->info('Created new addon #%s', $productId); return $productId; } - public function deleteProduct(\Model_Product $product): bool + public function deleteProduct(Product $product): bool { $orderService = $this->di['mod_service']('order'); if ($orderService->productHasOrders($product)) { throw new \FOSSBilling\InformationException('Cannot remove product which has active orders.'); } - $id = $product->id; - $this->di['db']->trash($product); + $id = $this->getProductId($product); + $this->di['em']->remove($product); + $this->di['em']->flush(); $this->di['logger']->info('Deleted product #%s', $id); return true; } + public function getPaginatedProducts(array $data, $identity = null): array + { + return $this->paginateMappedQuery( + $this->getProductSearchQueryBuilder($data), + PaginationOptions::fromArray($data), + fn (Product $product): array => $this->toApiArray($product, false, $identity), + ); + } + /** * @return mixed[] */ - public function getProductCategoryPairs(): array + public function getProductCategoryPairs(array $data = []): array { - $sql = 'SELECT id, title - FROM product_category'; - - $rows = $this->di['db']->getAll($sql); - $result = []; - foreach ($rows as $record) { - $result[$record['id']] = $record['title']; - } - - return $result; + return $this->getProductCategoryRepository()->getPairs(); } - public function updateCategory(\Model_ProductCategory $productCategory, $title = null, $description = null, $icon_url = null): bool + public function updateCategory(ProductCategory $productCategory, $title = null, $description = null, $icon_url = null): bool { - $productCategory->title = $title; - $productCategory->icon_url = $icon_url; - $productCategory->description = $description; + $productCategory + ->setTitle($title) + ->setIconUrl($icon_url) + ->setDescription($description) + ->setUpdatedAt(new \DateTime()); + $this->di['em']->flush(); - $productCategory->updated_at = date('Y-m-d H:i:s'); - $this->di['db']->store($productCategory); - - $this->di['logger']->info('Updated product category #%s', $productCategory->id); + $this->di['logger']->info('Updated product category #%s', $productCategory->getId()); return true; } public function createCategory($title, $description = null, $icon_url = null) { - $model = $this->di['db']->dispense('ProductCategory'); - $model->title = $title; - $model->description = $description; - $model->icon_url = $icon_url; - $model->updated_at = date('Y-m-d H:i:s'); - $model->created_at = date('Y-m-d H:i:s'); - $id = $this->di['db']->store($model); + $model = (new ProductCategory()) + ->setTitle($title) + ->setDescription($description) + ->setIconUrl($icon_url) + ->setUpdatedAt(new \DateTime()) + ->setCreatedAt(new \DateTime()); + $this->di['em']->persist($model); + $this->di['em']->flush(); + $id = $model->getId(); $this->di['logger']->info('Created new product category #%s', $id); return $id; } - public function removeProductCategory(\Model_ProductCategory $category): bool + public function removeProductCategory(ProductCategory $category): bool { - $model = $this->di['db']->findOne('Product', 'product_category_id = :category_id', [':category_id' => $category->id]); - if ($model instanceof \Model_Product) { + if ($this->getProductRepository()->hasProductsInCategory((int) $category->getId())) { throw new \FOSSBilling\InformationException('Cannot remove product category with products'); } - $id = $category->id; - $this->di['db']->trash($category); + $id = $category->getId(); + $this->di['em']->remove($category); + $this->di['em']->flush(); $this->di['logger']->info('Deleted product category #%s', $id); return true; } - public function getProductSearchQuery(array $data): array + public function getProductSearchQueryBuilder(array $data): QueryBuilder { - $sql = 'SELECT m.* - FROM product as m - LEFT JOIN product_payment as pp on m.product_payment_id = pp.id - WHERE m.is_addon = 0'; - - $type = $data['type'] ?? null; - $search = $data['search'] ?? null; - $status = $data['status'] ?? null; - $show_hidden = $data['show_hidden'] ?? true; - - $params = []; - if ($type) { - $sql .= ' AND m.type = :type'; - $params[':type'] = $type; - } - - if ($status) { - $sql .= ' AND m.status = :status'; - $params[':status'] = $status; - } - - if (!$show_hidden) { - $sql .= ' AND m.hidden = 0'; - } - - if ($search) { - $sql .= ' AND m.title LIKE :search'; - $params[':search'] = '%' . $search . '%'; - } - - $sql .= ' ORDER BY m.priority ASC'; - - return [$sql, $params]; + return $this->getProductRepository()->getSearchQueryBuilder($data); } - public function toProductCategoryApiArray(\Model_ProductCategory $model, $deep = true, $identity = null) + public function toProductCategoryApiArray(ProductCategory $model, $deep = true, $identity = null) { $min_price = 0; $products = []; @@ -595,7 +691,7 @@ class Service implements InjectionAwareInterface foreach ($pr as $p) { $pa = $this->toApiArray($p, false, $identity); if (reset($pr) == $p) { - $type = $p->type; + $type = $this->getProductType($p); } $products[] = $pa; $startingPrice = $pa['price_starting_from'] ?? 0; @@ -607,70 +703,52 @@ class Service implements InjectionAwareInterface } } - $data = $this->di['db']->toArray($model); - $data['price_starting_from'] = $min_price; - $data['icon_url'] = $model->icon_url; - $data['type'] = $type; - $data['products'] = $products; - - return $data; + return [ + 'id' => $model->getId(), + 'title' => $model->getTitle(), + 'description' => $model->getDescription(), + 'icon_url' => $model->getIconUrl(), + 'created_at' => $this->formatDateTimeValue($model->getCreatedAt()), + 'updated_at' => $this->formatDateTimeValue($model->getUpdatedAt()), + 'price_starting_from' => $min_price, + 'type' => $type, + 'products' => $products, + ]; } /** * @param int $id - * - * @return \Model_Product */ - public function findOneActiveById($id) + public function findOneActiveById($id): ?Product { - return $this->di['db']->findOne('Product', "id = ? and active = 1 and status = 'enabled' and is_addon = 0", [$id]); + return $this->getProductRepository()->findActiveById((int) $id); } /** * @param string $slug - * - * @return \Model_Product */ - public function findOneActiveBySlug($slug) + public function findOneActiveBySlug($slug): ?Product { - return $this->di['db']->findOne('Product', "slug = ? and active = 1 and status = 'enabled' and is_addon = 0", [$slug]); + return $this->getProductRepository()->findActiveBySlug((string) $slug); } - public function getProductCategorySearchQuery($data): array + public function getPaginatedProductCategories(array $data, $identity = null): array { - $sql = 'SELECT m.id, - m.title, - m.description, - m.icon_url, - m.created_at, - m.updated_at, - Max(p.priority) AS MaxPrio - FROM product_category AS m - LEFT JOIN product p - ON p.product_category_id = m.id - WHERE p.status = \'enabled\' - AND p.hidden = 0 - GROUP BY m.id, - m.title, - m.description, - m.icon_url, - m.created_at, - m.updated_at - ORDER BY MaxPrio ASC;'; - - $params = []; - - return [$sql, $params]; + return $this->paginateMappedQuery( + $this->getProductCategorySearchQueryBuilder($data), + PaginationOptions::fromArray($data), + fn (ProductCategory $category): array => $this->toProductCategoryApiArray($category, true, $identity), + ); } - public function getStartingFromPrice(\Model_Product $model) + public function getStartingFromPrice(Product $model) { - if ($model->type == self::DOMAIN) { + if ($this->getProductType($model) == self::DOMAIN) { return $this->getStartingDomainPrice(); } - if ($model->product_payment_id) { - $productPaymentModel = $this->di['db']->load('ProductPayment', $model->product_payment_id); + if ($this->getProductPaymentId($model)) { + $productPaymentModel = $this->getProductPaymentById((int) $this->getProductPaymentId($model)); return $this->getStartingPrice($productPaymentModel); } @@ -681,27 +759,43 @@ class Service implements InjectionAwareInterface /** * @return mixed[] */ - public function getUpgradablePairs(\Model_Product $model): array + public function getUpgradablePairs(Product $model): array { - if (is_null($model->upgrades)) { - $model->upgrades = ''; - } - $ids = json_decode($model->upgrades ?? '', true); + $ids = json_decode($this->getProductUpgradesJson($model) ?? '', true); $pids = $this->getProductTitlesByIds($ids); - unset($pids[$model->id]); + unset($pids[$this->getProductId($model)]); return $pids; } - public function canUpgradeTo(\Model_Product $model, \Model_Product $new) + public function getUpgradablePairsByProductId(int $productId): array { - if ($model->id == $new->id) { + return $this->getUpgradablePairs($this->findProductById($productId)); + } + + public function canUpgradeTo(Product $model, Product $new): bool + { + if ($this->getProductId($model) === $this->getProductId($new)) { return false; } $pairs = $this->getUpgradablePairs($model); - return array_key_exists($new->id, $pairs); + return array_key_exists($this->getProductId($new), $pairs); + } + + public function assertUpgradeAllowedByIds(int $productId, int $upgradeProductId): void + { + $product = $this->findProductById($productId); + $allowedUpgrades = $this->getUpgradablePairsByProductId($productId); + + if (array_key_exists($upgradeProductId, $allowedUpgrades)) { + return; + } + + $upgrade = $this->findProductById($upgradeProductId); + + throw new \FOSSBilling\InformationException('Sorry, but ":product" is not allowed to be upgraded to ":upgrade"', [':product' => $product->getTitle() ?? 'unknown', ':upgrade' => $upgrade->getTitle() ?? 'unknown']); } /** @@ -713,91 +807,105 @@ class Service implements InjectionAwareInterface return []; } - $count = \FOSSBilling\Tools::safeCount($ids); - $slots = $count ? implode(',', array_fill(0, $count, '?')) : ''; // same as RedBean genSlots() method - - $rows = $this->di['db']->getAll('SELECT id, title FROM product WHERE id in (' . $slots . ')', $ids); - $result = []; - foreach ($rows as $record) { - $result[$record['id']] = $record['title']; + foreach ($this->getProductRepository()->findByIds($this->normalizeProductIds((array) $ids)) as $product) { + $productId = $product->getId(); + if ($productId === null) { + continue; + } + + $result[$productId] = $product->getTitle(); } return $result; } - public function getCategoryProducts(\Model_ProductCategory $model) + public function getCategoryProducts(ProductCategory $model) { - return $this->di['db']->find('Product', 'is_addon = 0 and status="enabled" and hidden = 0 and product_category_id = ?', [$model->id]); + return $this->getProductRepository()->findEnabledVisibleByCategoryId((int) $model->getId()); } - public function toProductPaymentApiArray(\Model_ProductPayment $model): array + public function getProductCategorySearchQueryBuilder(array $data): QueryBuilder + { + return $this->getProductCategoryRepository()->getEnabledVisibleSearchQueryBuilder(); + } + + public function findProductCategoryById(int $id): ProductCategory + { + $category = $this->getProductCategoryRepository()->findById($id); + if (!$category instanceof ProductCategory) { + throw new \FOSSBilling\Exception('Category not found'); + } + + return $category; + } + + public function toProductPaymentApiArray(ProductPayment $model): array { $periods = []; - $periods['1W'] = ['price' => $model->w_price, 'setup' => $model->w_setup_price, 'enabled' => $model->w_enabled]; - $periods['1M'] = ['price' => $model->m_price, 'setup' => $model->m_setup_price, 'enabled' => $model->m_enabled]; - $periods['3M'] = ['price' => $model->q_price, 'setup' => $model->q_setup_price, 'enabled' => $model->q_enabled]; - $periods['6M'] = ['price' => $model->b_price, 'setup' => $model->b_setup_price, 'enabled' => $model->b_enabled]; - $periods['1Y'] = ['price' => $model->a_price, 'setup' => $model->a_setup_price, 'enabled' => $model->a_enabled]; - $periods['2Y'] = ['price' => $model->bia_price, 'setup' => $model->bia_setup_price, 'enabled' => $model->bia_enabled]; - $periods['3Y'] = ['price' => $model->tria_price, 'setup' => $model->tria_setup_price, 'enabled' => $model->tria_enabled]; + $periods['1W'] = ['price' => $model->getPeriodPrice('w'), 'setup' => $model->getPeriodSetupPrice('w'), 'enabled' => $model->isPeriodEnabled('w')]; + $periods['1M'] = ['price' => $model->getPeriodPrice('m'), 'setup' => $model->getPeriodSetupPrice('m'), 'enabled' => $model->isPeriodEnabled('m')]; + $periods['3M'] = ['price' => $model->getPeriodPrice('q'), 'setup' => $model->getPeriodSetupPrice('q'), 'enabled' => $model->isPeriodEnabled('q')]; + $periods['6M'] = ['price' => $model->getPeriodPrice('b'), 'setup' => $model->getPeriodSetupPrice('b'), 'enabled' => $model->isPeriodEnabled('b')]; + $periods['1Y'] = ['price' => $model->getPeriodPrice('a'), 'setup' => $model->getPeriodSetupPrice('a'), 'enabled' => $model->isPeriodEnabled('a')]; + $periods['2Y'] = ['price' => $model->getPeriodPrice('bia'), 'setup' => $model->getPeriodSetupPrice('bia'), 'enabled' => $model->isPeriodEnabled('bia')]; + $periods['3Y'] = ['price' => $model->getPeriodPrice('tria'), 'setup' => $model->getPeriodSetupPrice('tria'), 'enabled' => $model->isPeriodEnabled('tria')]; return [ - 'type' => $model->type, - \Model_ProductPayment::FREE => ['price' => 0, 'setup' => 0], - \Model_ProductPayment::ONCE => ['price' => $model->once_price, 'setup' => $model->once_setup_price], - \Model_ProductPayment::RECURRENT => $periods, + 'type' => $model->getType(), + ProductPayment::FREE => ['price' => 0, 'setup' => 0], + ProductPayment::ONCE => ['price' => $model->getOncePrice(), 'setup' => $model->getOnceSetupPrice()], + ProductPayment::RECURRENT => $periods, ]; } public function getStartingDomainPrice(): float { - $sql = 'SELECT min(price_registration) - FROM tld - WHERE active = 1'; + $pricing = $this->getDomainPricingArray(); + $registrationPrices = array_column($pricing, 'price_registration'); - return (float) $this->di['db']->getCell($sql); + return $registrationPrices === [] ? 0.0 : (float) min($registrationPrices); } - public function getStartingPrice(\Model_ProductPayment $model) + public function getStartingPrice(ProductPayment $model) { - if ($model->type == 'free') { + if ($model->getType() == ProductPayment::FREE) { return 0; } - if ($model->type == 'once') { - return $model->once_price; + if ($model->getType() == ProductPayment::ONCE) { + return $model->getOncePrice(); } - if ($model->type == 'recurrent') { + if ($model->getType() == ProductPayment::RECURRENT) { $p = []; - if ($model->w_enabled) { - $p[] = $model->w_price; + if ($model->isPeriodEnabled('w')) { + $p[] = $model->getPeriodPrice('w'); } - if ($model->m_enabled) { - $p[] = $model->m_price; + if ($model->isPeriodEnabled('m')) { + $p[] = $model->getPeriodPrice('m'); } - if ($model->q_enabled) { - $p[] = $model->q_price; + if ($model->isPeriodEnabled('q')) { + $p[] = $model->getPeriodPrice('q'); } - if ($model->b_enabled) { - $p[] = $model->b_price; + if ($model->isPeriodEnabled('b')) { + $p[] = $model->getPeriodPrice('b'); } - if ($model->a_enabled) { - $p[] = $model->a_price; + if ($model->isPeriodEnabled('a')) { + $p[] = $model->getPeriodPrice('a'); } - if ($model->bia_enabled) { - $p[] = $model->bia_price; + if ($model->isPeriodEnabled('bia')) { + $p[] = $model->getPeriodPrice('bia'); } - if ($model->tria_enabled) { - $p[] = $model->tria_price; + if ($model->isPeriodEnabled('tria')) { + $p[] = $model->getPeriodPrice('tria'); } if ($p) { @@ -810,28 +918,98 @@ class Service implements InjectionAwareInterface return null; } - public function getAddonById($id) + public function getAddonById(int $id): ?Product { - return $this->di['db']->findOne('Product', "type = 'custom' and is_addon = 1 and id = ?", [$id]); + return $this->getProductRepository()->findEnabledAddonById($id); } - private function getPeriods(\Model_Promo $model): array + /** + * @return list + */ + public function getSelectedAddonsForCart(Product $parentProduct, array $addons): array { - return json_decode($model->periods ?? '', true) ?? []; + $selectedAddons = []; + foreach ($addons as $id => $addonConfig) { + if (!isset($addonConfig['selected']) || !(bool) $addonConfig['selected']) { + continue; + } + + $addon = $this->getAddonById($id); + if (!$addon instanceof Product) { + error_log('Addon not found by id ' . $id); + + continue; + } + + if ($this->isRecurrentProductPricing($addon)) { + $required = [ + 'period' => 'Addon period parameter not passed', + ]; + $this->di['validator']->checkRequiredParamsForArray($required, $addonConfig); + + if (!$this->isProductPeriodEnabled($addon, (string) $addonConfig['period'])) { + throw new \FOSSBilling\InformationException('Selected billing period is invalid for the selected add-on'); + } + } + + $addonConfig['parent_id'] = $this->getProductId($parentProduct); + $selectedAddons[] = [ + 'product' => $addon, + 'config' => $addonConfig, + ]; + } + + return $selectedAddons; } - private function getProducts(\Model_Promo $model): array + public function isStockAvailable(Product|int $product, $qty): bool { - return json_decode($model->products ?? '', true) ?? []; + $resolvedProduct = $this->resolveStockProduct($product); + if ($this->isStockControlled($resolvedProduct)) { + return $this->getProductQuantityInStock($resolvedProduct) >= (int) $qty; + } + + return true; + } + + public function reduceStock(Product|int $product, $qty): bool + { + $resolvedProduct = $this->resolveStockProduct($product); + if (!$this->isStockControlled($resolvedProduct)) { + return true; + } + + $quantity = (int) $qty; + $available = $this->getProductQuantityInStock($resolvedProduct); + if ($available < $quantity) { + throw new \FOSSBilling\InformationException('Product :id is out of stock.', [':id' => $this->getProductId($resolvedProduct)], 831); + } + + $this->setProductQuantityInStockValue($resolvedProduct, $available - $quantity); + $this->setProductUpdatedAtValue($resolvedProduct, new \DateTime()); + + $this->di['em']->flush(); + + return true; + } + + private function getPeriods(Promo $model): array + { + return $this->decodePromoSelection($this->getPromoSourceArray($model)['periods'] ?? null); + } + + private function getProducts(Promo $model): array + { + return $this->decodePromoSelection($this->getPromoSourceArray($model)['products'] ?? null); } /** * @return mixed[] */ - private function getAddonsApiArray(\Model_Product $model, bool $isAdmin): array + private function getAddonsApiArray(Product $model, bool $isAdmin = false): array { $addons = []; - foreach ($this->getProductAddons($model, !$isAdmin) as $addon) { + foreach ($this->getProductAddons($model, $isAdmin) as $addon) { $d = $this->toAddonArray($addon, true, $isAdmin); $addons[] = $d; } @@ -839,45 +1017,127 @@ class Service implements InjectionAwareInterface return $addons; } - public function getProductAddons(\Model_Product $model, bool $publicOnly = false) + public function getProductAddons(Product $model, bool $includeUnavailable = false) { - $ids = json_decode($model->addons ?? '', true) ?? []; + $ids = $this->normalizeProductIds(json_decode($this->getProductAddonsJson($model) ?? '', true) ?? []); if ($ids === []) { return []; } - $count = \FOSSBilling\Tools::safeCount($ids); - $slots = $count ? implode(',', array_fill(0, $count, '?')) : ''; // same as RedBean genSlots() method - array_unshift($ids, (int) $model->id); // adding product ID as first param in array - - $query = 'type = "custom" and is_addon= 1 and id != ? and id IN (' . $slots . ')'; - if ($publicOnly) { - $query .= ' and active = 1 and status = "enabled"'; - } - - return $this->di['db']->find('Product', $query, $ids); + return $this->getProductRepository()->findAddonsByIds($ids, (int) $this->getProductId($model), $includeUnavailable); } - public function toAddonArray(\Model_Product $model, $deep = true, ?bool $isAdmin = null): array + /** + * @param list $ids + * + * @return array + */ + public function getProductSnapshotMap(array $ids): array { - $isAdmin ??= true; - $productPayment = $this->di['db']->load('ProductPayment', $model->product_payment_id); + $result = []; + foreach ($this->getProductRepository()->findByIds($this->normalizeProductIds($ids)) as $product) { + $productId = $product->getId(); + if ($productId === null) { + continue; + } + + $result[$productId] = [ + 'id' => $productId, + 'title' => $product->getTitle(), + 'type' => $product->getType(), + 'plugin' => $product->getPlugin(), + ]; + } + + return $result; + } + + public function getRelatedProductDiscountByProductId(int $productId, array $items, ?array $config = null): float + { + return $this->getRelatedProductDiscount($this->findProductById($productId), $items, $config); + } + + public function getCartProductTitleById(int $productId, ?array $config = null): string + { + return $this->getCartProductTitle($this->findProductById($productId), $config); + } + + public function getProductDiscountById(int $productId, Promo $promo, ?array $config = null) + { + return $this->getProductDiscount($this->findProductById($productId), $promo, $config); + } + + /** + * @return array{ + * product_id: int, + * form_id: ?int, + * type: ?string, + * quantity: int|float|string, + * unit: string, + * price: float|int|string, + * setup_price: float|int|string, + * title: string, + * config: array + * } + */ + public function getCartProductViewData(\Model_CartProduct $item): array + { + $product = $this->findProductById((int) $item->product_id); + $config = json_decode($item->config ?? '', true) ?? []; + $line = $this->getProductOrderLineConfig($product, $config); + + return [ + 'product_id' => (int) $this->getProductId($product), + 'form_id' => $this->getProductFormId($product), + 'type' => $this->getProductType($product), + 'quantity' => $line['quantity'], + 'unit' => $this->getProductUnit($product), + 'price' => $line['price'], + 'setup_price' => $line['setup_price'], + 'title' => $this->getCartProductTitle($product, $config), + 'config' => $config, + ]; + } + + /** + * @param list $ids + * + * @return array + */ + public function getProductPluginMap(array $ids): array + { + $result = []; + foreach ($this->getProductSnapshotMap($ids) as $productId => $product) { + $result[$productId] = $product['plugin']; + } + + return $result; + } + + public function getProductPluginById(int $id): ?string + { + return $this->getProductPluginMap([$id])[$id] ?? null; + } + + public function toAddonArray(Product $model, $deep = true, bool $isAdmin = false): array + { + $productPayment = $this->getProductPaymentById((int) $this->getProductPaymentId($model)); $pricing = $this->toProductPaymentApiArray($productPayment); - $config = json_decode($model->config ?? '', true) ?? []; + $config = json_decode($this->getProductConfigJson($model) ?? '', true) ?? []; $result = [ - 'id' => $model->id, - 'type' => $model->type, - 'title' => $model->title, - 'slug' => $model->slug, - 'description' => $model->description, - 'unit' => $model->unit, - 'plugin' => $model->plugin, - 'allow_quantity_select' => $model->allow_quantity_select, - 'created_at' => $model->created_at, - 'updated_at' => $model->updated_at, - 'icon_url' => $model->icon_url, + 'id' => $this->getProductId($model), + 'type' => $this->getProductType($model), + 'title' => $this->getProductTitle($model), + 'slug' => $this->getProductSlug($model), + 'description' => $this->getProductDescription($model), + 'unit' => $this->getProductUnit($model), + 'plugin' => $this->getProductPlugin($model), + 'allow_quantity_select' => $this->isAllowQuantitySelect($model), + 'created_at' => $this->formatDateTimeValue($this->getProductCreatedAt($model)), + 'updated_at' => $this->formatDateTimeValue($this->getProductUpdatedAt($model)), + 'icon_url' => $this->getProductIconUrl($model), 'pricing' => $isAdmin ? $pricing : $this->getPublicPricing($pricing), 'config' => $isAdmin ? $config : $this->getPublicConfig($config), @@ -893,164 +1153,460 @@ class Service implements InjectionAwareInterface /* * Product Promotion Functions */ - public function getPromoSearchQuery($data): array + public function getPromoSearchQueryBuilder(array $data): QueryBuilder { - $sql = 'SELECT * - FROM promo - WHERE 1'; - - $search = $data['search'] ?? null; - $id = $data['id'] ?? null; - $status = $data['status'] ?? null; - - $params = []; - if ($id) { - $sql .= ' AND id = :id'; - $params['id'] = $id; - } - - if ($search) { - $sql .= ' AND code like :search'; - $params['search'] = '%' . $search . '%'; - } - - switch ($status) { - case 'active': - $sql .= ' AND start_at <= :start_at AND end_at >= :end_at'; - $params['start_at'] = time(); - $params['end_at'] = time(); - - break; - case 'not-started': - $sql .= ' AND start_at <= :start_at'; - $params['start_at'] = time(); - - break; - case 'expired': - $sql .= ' AND start_at <= :end_at'; - $params['end_at'] = time(); - - break; - } - - $sql .= ' ORDER BY id asc'; - - return [$sql, $params]; + return $this->getPromoRepository()->getSearchQueryBuilder($data); } public function createPromo($code, $type, $value, $products, $periods, $clientGroups, $data) { - if ($this->di['db']->findOne('Promo', 'code = :code', [':code' => $code])) { + if ($this->getPromoRepository()->findOneBy(['code' => $code]) instanceof Promo) { throw new \FOSSBilling\InformationException('This promotion code already exists.'); } - $model = $this->di['db']->dispense('Promo'); - $model->code = $code; - $model->type = $type; - $model->value = $value; - $model->active = $data['active'] ?? 0; - $model->freesetup = $data['freesetup'] ?? 0; - $model->once_per_client = (bool) ($data['once_per_client'] ?? 0); - $model->recurring = (bool) ($data['recurring'] ?? 0); - $model->maxuses = isset($data['maxuses']) ? (int) $data['maxuses'] : null; - $model->start_at = !empty($data['start_at']) ? date('Y-m-d H:i:s', strtotime((string) $data['start_at'])) : null; - $model->end_at = !empty($data['end_at']) ? date('Y-m-d H:i:s', strtotime((string) $data['end_at'])) : null; - $model->products = json_encode($products); - $model->periods = json_encode($periods); - $model->client_groups = json_encode($clientGroups); - $model->updated_at = date('Y-m-d H:i:s'); - $model->created_at = date('Y-m-d H:i:s'); - $promoId = $this->di['db']->store($model); + $promo = new Promo(); + $promo->setCode($code); + $this->applyPromoDataToEntity($promo, [ + ...$data, + 'type' => $type, + 'value' => $value, + 'products' => $products, + 'periods' => $periods, + 'client_groups' => $clientGroups, + ]); - $this->di['logger']->info('Created new promotion code %s', $model->code); + $this->di['em']->persist($promo); + $this->di['em']->flush(); + $promoId = (int) $promo->getId(); + + $this->di['logger']->info('Created new promotion code %s', $promo->getCode()); return $promoId; } - public function toPromoApiArray(\Model_Promo $model, $deep = false, $identity = null) + public function findActivePromoByCode($code): ?Promo { - $products = $model->products ? $this->getProductTitlesByIds(json_decode($model->products, true)) : null; - $clientGroups = $model->client_groups ? $this->di['tools']->getPairsForTableByIds('client_group', json_decode($model->client_groups, true)) : null; + return $this->getPromoRepository()->findActiveByCode((string) $code); + } + + public function findPromoById(int $id): Promo + { + $promo = $this->getPromoRepository()->find($id); + if (!$promo instanceof Promo) { + throw new \FOSSBilling\Exception('Promo not found'); + } + + return $promo; + } + + public function promoCanBeApplied(Promo $promo): bool + { + $promoData = $this->getPromoSourceArray($promo); + + if (empty($promoData['active'])) { + return false; + } + + $maxUses = (int) ($promoData['maxuses'] ?? 0); + $used = (int) ($promoData['used'] ?? 0); + if ($maxUses > 0 && $maxUses <= $used) { + return false; + } + + if (!empty($promoData['start_at']) && (strtotime((string) $promoData['start_at']) - time() > 0)) { + return false; + } + + if (!empty($promoData['end_at']) && (strtotime((string) $promoData['end_at']) - time() < 0)) { + return false; + } + + return true; + } + + public function isPromoAvailableForClientGroup(Promo $promo, ?\Model_Client $client = null): bool + { + $promoData = $this->getPromoSourceArray($promo); + $clientGroups = $this->decodePromoSelection($promoData['client_groups'] ?? null); + + if (empty($clientGroups)) { + return true; + } + + if ($client === null) { + 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); + } + + public function canClientUsePromo(\Model_Client $client, Promo $promo): bool + { + if (!$this->promoCanBeApplied($promo)) { + return false; + } + + $promoData = $this->getPromoSourceArray($promo); + if (empty($promoData['once_per_client'])) { + return true; + } + + return !$this->clientHasActivePromoApplication($client, $promo); + } + + public function usePromo(Promo $promo): void + { + $promoId = (int) ($this->getPromoSourceArray($promo)['id'] ?? 0); + $affectedRows = $this->getPromoRepository()->incrementUsageIfAvailable($promoId, new \DateTimeImmutable()); + if ($affectedRows === 0) { + throw new \FOSSBilling\InformationException('This promo code has reached its maximum number of uses.'); + } + } + + public function reservePromoForOrder(Promo $promo, \Model_ClientOrder $order): void + { + $this->usePromo($promo); + $promoData = $this->getPromoSourceArray($promo); + + $order->promo_recurring = (int) !empty($promoData['recurring']); + $order->promo_used = 1; + $this->di['db']->store($order); + } + + public function getPromoDiscountTitle(Promo $promo, string $currency): string + { + $api_guest = $this->di['api_guest']; + $promoData = $this->getPromoSourceArray($promo); + + return match ($promoData['type'] ?? null) { + Promo::ABSOLUTE => __trans('Promotional Code: :code - :value Discount', [ + ':code' => $promoData['code'] ?? '', + ':value' => $api_guest->currency_format(['code' => $currency, 'price' => $promoData['value'] ?? 0]), + ]), + Promo::PERCENTAGE => __trans('Promotional Code: :code - :value%', [ + ':code' => $promoData['code'] ?? '', + ':value' => $promoData['value'] ?? 0, + ]), + default => __trans('Promotional Code: :code', [':code' => $promoData['code'] ?? '']), + }; + } + + /** + * @param list<\Model_ClientOrder> $orders + */ + public function createCheckoutPromoRedemptions( + Promo $promo, + \Model_Client $client, + array $orders, + ?\Model_Invoice $invoice, + string $status, + ): void { + if ($orders === []) { + return; + } + + foreach ($orders as $order) { + $redemption = $this->newPromoRedemption( + $promo, + $client, + $order, + $invoice, + PromoRedemption::PHASE_CHECKOUT, + (float) $order->discount, + $order->currency, + $order->created_at, + $status, + ); + + $this->di['em']->persist($redemption); + } + + $this->di['em']->flush(); + } + + /** + * Compensate for a failed checkout by removing orphaned promo redemption + * rows and decrementing the promo usage counter. + * + * Needed because RedBean's transaction (orders/invoices) operates on a + * separate database connection from Doctrine (promo redemptions, promo.used). + * When the RedBean transaction rolls back, Doctrine-side changes persist + * orphaned unless explicitly cleaned up. + * + * @param int[] $orderIds Order IDs from the rolled-back RedBean transaction + * @param int $reservedCount Number of successful reservePromoForOrder() calls + */ + public function compensateCheckoutPromoFailure(Promo $promo, array $orderIds, int $reservedCount): void + { + if ($reservedCount <= 0) { + return; + } + + $promoId = (int) ($this->getPromoSourceArray($promo)['id'] ?? 0); + if ($promoId <= 0) { + return; + } + + if ($orderIds !== []) { + $redemptions = $this->getPromoRedemptionRepository()->findBy([ + 'promoId' => $promoId, + 'clientOrderId' => $orderIds, + ]); + foreach ($redemptions as $redemption) { + $this->di['em']->remove($redemption); + } + if ($redemptions !== []) { + $this->di['em']->flush(); + } + } + + $this->getPromoRepository()->decrementUsage($promoId, $reservedCount, new \DateTimeImmutable()); + } + + /** + * @return array{ + * promo: Promo, + * discount_amount: float, + * title: string, + * currency: string + * }|null + */ + public function getRenewalPromoAdjustment(\Model_ClientOrder $order, float $price, float $quantity): ?array + { + if (!$order->promo_recurring || !$order->promo_id) { + return null; + } + + $promo = $this->findPromoById((int) $order->promo_id); + $product = $this->findProductById((int) $order->product_id); + $discountAmount = (float) $order->discount; + + if ($this->getProductType($product) === self::DOMAIN) { + $config = json_decode($order->config ?? '', true) ?? []; + $discountAmount = $this->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}"); + } + + $discountAmount *= $rate; + } + + $orderTotal = $price * $quantity; + $discountAmount = min($discountAmount, $orderTotal); + if ($discountAmount <= 0) { + return null; + } + + return [ + 'promo' => $promo, + 'discount_amount' => $discountAmount, + 'title' => $this->getPromoDiscountTitle($promo, $order->currency), + 'currency' => $order->currency, + ]; + } + + public function toPromoApiArray(Promo $model, $deep = false, $identity = null) + { + return $this->enrichPromoApiArray($this->getPromoApiSourceArray($model), $deep, $identity); + } + + public function enrichPromoApiArray(array $result, $deep = false, $identity = null): array + { + $products = !empty($result['products']) ? $this->getProductTitlesByIds($this->decodePromoSelection($result['products'])) : null; + $clientGroups = !empty($result['client_groups']) ? $this->di['tools']->getPairsForTableByIds('client_group', $this->decodePromoSelection($result['client_groups'])) : null; + $usageStats = $deep ? $this->getPromoUsageStatsByValues((int) $result['id'], (int) ($result['used'] ?? 0), isset($result['maxuses']) ? (int) $result['maxuses'] : null) : null; + $redemptionCount = $usageStats['recorded_applications'] ?? $this->getPromoRedemptionCountById((int) $result['id']); - $result = $this->di['db']->toArray($model); $result['applies_to'] = $products; $result['cgroups'] = $clientGroups; - $result['products'] = json_decode($model->products ?? '', true); - $result['periods'] = json_decode($model->periods ?? '', true); - $result['client_groups'] = json_decode($model->client_groups ?? '', true); + $result['products'] = $this->decodePromoSelection($result['products'] ?? null); + $result['periods'] = $this->decodePromoSelection($result['periods'] ?? null); + $result['client_groups'] = $this->decodePromoSelection($result['client_groups'] ?? null); + $result['redemption_count'] = $redemptionCount; + $result['can_be_deleted'] = !$this->hasPromoRedemptionHistoryById((int) $result['id'], $redemptionCount); + if ($usageStats !== null) { + $result['usage_stats'] = $usageStats; + } return $result; } - public function updatePromo(\Model_Promo $model, array $data = []): bool + public function enrichPromoRedemptionApiArray(array $row): array { - $model->code = $data['code'] ?? $model->code; - $model->type = $data['type'] ?? $model->type; - $model->value = $data['value'] ?? $model->value; - $model->active = $data['active'] ?? $model->active; - $model->freesetup = $data['freesetup'] ?? $model->freesetup; - $model->once_per_client = $data['once_per_client'] ?? $model->once_per_client; - $model->recurring = $data['recurring'] ?? $model->recurring; - $model->used = $data['used'] ?? $model->used; - $model->start_at = !empty($data['start_at']) ? date('Y-m-d H:i:s', strtotime((string) $data['start_at'])) : null; - $model->end_at = !empty($data['end_at']) ? date('Y-m-d H:i:s', strtotime((string) $data['end_at'])) : null; - $model->maxuses = (int) ($data['maxuses'] ?? $model->maxuses); + $result = $row; + $result['client'] = null; + $result['order'] = null; + $result['invoice'] = null; - if (!is_array($data['products'] ?? null)) { - $model->products = null; - } else { - $products = array_values(array_filter($data['products'])); - if (empty($products)) { - $model->products = null; - } else { - $model->products = json_encode($products); - } + if (!empty($result['client_id'])) { + $client = $this->di['db']->getRow( + 'SELECT id, first_name, last_name, email FROM client WHERE id = :id', + [':id' => $result['client_id']] + ); + + $result['client'] = [ + 'id' => (int) $result['client_id'], + 'first_name' => $client['first_name'] ?? null, + 'last_name' => $client['last_name'] ?? null, + 'email' => $client['email'] ?? null, + ]; } - if (!is_array($data['client_groups'] ?? null)) { - $model->client_groups = null; - } else { - $client_groups = array_values(array_filter($data['client_groups'])); - if (empty($client_groups)) { - $model->client_groups = null; - } else { - $model->client_groups = json_encode($client_groups); + + if (!empty($result['client_order_id'])) { + $order = $this->di['db']->getRow( + 'SELECT id, title, created_at FROM client_order WHERE id = :id', + [':id' => $result['client_order_id']] + ); + + $result['order'] = [ + 'id' => (int) $result['client_order_id'], + 'title' => $order['title'] ?? null, + 'created_at' => $order['created_at'] ?? null, + ]; + } + + if (!empty($result['invoice_id'])) { + $invoice = $this->di['db']->getRow( + 'SELECT id, serie_nr, status, created_at FROM invoice WHERE id = :id', + [':id' => $result['invoice_id']] + ); + + $result['invoice'] = [ + 'id' => (int) $result['invoice_id'], + 'serie_nr' => $invoice['serie_nr'] ?? null, + 'status' => $invoice['status'] ?? null, + 'created_at' => $invoice['created_at'] ?? null, + ]; + } + + return $result; + } + + public function createPromoRedemption( + Promo $promo, + \Model_Client $client, + ?\Model_ClientOrder $order, + ?\Model_Invoice $invoice, + string $phase, + ?float $discountAmount, + ?string $currency, + ?string $createdAt = null, + string $status = PromoRedemption::STATUS_COMMITTED, + ): int { + $redemption = $this->newPromoRedemption($promo, $client, $order, $invoice, $phase, $discountAmount, $currency, $createdAt, $status); + $this->di['em']->persist($redemption); + $this->di['em']->flush(); + + return (int) $redemption->getId(); + } + + public function clientHasActivePromoApplication(\Model_Client $client, Promo $promo): bool + { + $promoId = (int) ($this->getPromoSourceArray($promo)['id'] ?? 0); + + return $this->getPromoRedemptionRepository()->clientHasActiveCheckoutApplication($promoId, (int) $client->id); + } + + public function commitReservedPromoRedemptionsForInvoice(\Model_Invoice $invoice): void + { + $redemptions = $this->getPromoRedemptionRepository()->findBy([ + 'invoiceId' => (int) $invoice->id, + 'status' => PromoRedemption::STATUS_RESERVED, + ]); + + if ($redemptions === []) { + return; + } + + $committedAt = $invoice->paid_at ? new \DateTime((string) $invoice->paid_at) : new \DateTime(); + foreach ($redemptions as $redemption) { + if (!$redemption instanceof PromoRedemption) { + continue; + } + + $redemption + ->setStatus(PromoRedemption::STATUS_COMMITTED) + ->setCommittedAt(clone $committedAt) + ->setReleasedAt(null) + ->setReleaseReason(null); + } + + $this->di['em']->flush(); + } + + public function releaseReservedPromoRedemptionsForInvoice(\Model_Invoice $invoice, string $reason): void + { + $redemptions = $this->getPromoRedemptionRepository()->findBy([ + 'invoiceId' => (int) $invoice->id, + 'status' => PromoRedemption::STATUS_RESERVED, + ]); + + $this->releasePromoRedemptions($redemptions, $reason); + } + + public function releaseReservedPromoRedemptionsForOrder(\Model_ClientOrder $order, string $reason): void + { + $redemptions = $this->getPromoRedemptionRepository()->findBy([ + 'clientOrderId' => (int) $order->id, + 'status' => PromoRedemption::STATUS_RESERVED, + ]); + + $this->releasePromoRedemptions($redemptions, $reason); + } + + public function updatePromo(Promo $model, array $data = []): bool + { + $promo = $model; + if (($data['code'] ?? null) !== null && $data['code'] !== $promo->getCode()) { + $existing = $this->getPromoRepository()->findOneBy(['code' => $data['code']]); + if ($existing instanceof Promo && $existing->getId() !== $promo->getId()) { + throw new \FOSSBilling\InformationException('This promotion code already exists.'); } } - if (!is_array($data['periods'] ?? null)) { - $model->periods = null; - } else { - $periods = array_values(array_filter($data['periods'])); - if (empty($periods)) { - $model->periods = null; - } else { - $model->periods = json_encode($periods); - } - } + $this->applyPromoDataToEntity($promo, $data); + $this->di['em']->flush(); - $model->updated_at = date('Y-m-d H:i:s'); - $this->di['db']->store($model); - - $this->di['logger']->info('Update promo code %s', $model->code); + $this->di['logger']->info('Update promo code %s', $promo->getCode()); return true; } - public function deletePromo(\Model_Promo $model): bool + public function deletePromo(Promo $model): bool { - $sql = 'UPDATE client_order SET promo_id = NULL WHERE promo_id = :id'; + $promo = $model; + $promoId = (int) $promo->getId(); + if ($this->hasPromoRedemptionHistoryById($promoId)) { + throw new \FOSSBilling\InformationException('Promotions with redemption history cannot be deleted. Disable the promotion instead.'); + } - $this->di['db']->exec($sql, [':id' => $model->id]); - $this->di['db']->trash($model); + $this->di['em']->remove($promo); + $this->di['em']->flush(); - $this->di['logger']->info('Removed promo code %s', $model->code); + $this->di['logger']->info('Removed promo code %s', $promo->getCode()); return true; } - public function isPromoLinkedToProduct(\Model_Promo $promo, \Model_Product $product) + public function isPromoLinkedToProduct(Promo $promo, Product $product) { - if ($product->is_addon) { + if ($product->isAddon()) { return false; } @@ -1059,10 +1615,496 @@ class Service implements InjectionAwareInterface return true; } - return in_array($product->id, $products); + return in_array($this->getProductId($product), $products); } - public function getProductDiscount(\Model_Product $product, \Model_Promo $promo, ?array $config = null) + /** + * Resolve initial order line pricing for a product from the active pricing backend. + * + * @return array{price: float|int|string, quantity: int|float|string, setup_price?: float|int|string} + */ + public function getProductOrderLineConfig(Product $product, ?array $config = null): array + { + if ($this->getProductType($product) === self::DOMAIN) { + return $this->getDomainOrderLineConfig($config ?? []); + } + + $quantity = max(1, (int) ($config['quantity'] ?? 1)); + + return [ + 'price' => (float) $this->getProductPrice($product, $config), + 'quantity' => $quantity, + 'setup_price' => (float) $this->getProductSetupPrice($product, $config), + ]; + } + + /** + * Resolve renewal line pricing for a product from the active pricing backend. + * + * @return array{price: float|int|string, quantity: int|float|string, setup_price?: float|int|string} + */ + public function getProductRenewalLineConfig(Product $product, ?array $config = null): array + { + if ($this->getProductType($product) === self::DOMAIN) { + return $this->getDomainRenewalLineConfig($config ?? []); + } + + return $this->getProductOrderLineConfig($product, $config); + } + + public function getProductSetupPrice(Product $product, ?array $config = null): float + { + if ($this->getProductType($product) === self::DOMAIN) { + return 0.0; + } + + $pp = $this->getProductPaymentById((int) $this->getProductPaymentId($product)); + + if ($pp->getType() == ProductPayment::FREE) { + return 0.0; + } + + if ($pp->getType() == ProductPayment::ONCE) { + return $pp->getOnceSetupPrice(); + } + + if ($pp->getType() == ProductPayment::RECURRENT) { + $period = new \Box_Period((string) ($config['period'] ?? '')); + $key = $this->getProductPaymentPeriodKey($period); + + return $pp->getPeriodSetupPrice($key); + } + + throw new \FOSSBilling\Exception('Unknown period selected for setup price'); + } + + public function getProductPrice(Product $product, ?array $config = null): float|int|string + { + if ($this->getProductType($product) === self::DOMAIN) { + return $this->getDomainProductPrice($config ?? []); + } + + $pp = $this->getProductPaymentById((int) $this->getProductPaymentId($product)); + + if ($pp->getType() == ProductPayment::FREE) { + return 0.0; + } + + if ($pp->getType() == ProductPayment::ONCE) { + return $pp->getOncePrice(); + } + + if ($pp->getType() == ProductPayment::RECURRENT) { + if (!isset($config['period'])) { + throw new \FOSSBilling\Exception('Product :id payment type is recurrent, but period was not selected', [':id' => $this->getProductId($product)]); + } + + $period = new \Box_Period((string) $config['period']); + $key = $this->getProductPaymentPeriodKey($period); + + return $pp->getPeriodPrice($key); + } + + throw new \FOSSBilling\Exception('Unknown Period selected for price'); + } + + private function getProductPaymentPeriodKey(\Box_Period $period): string + { + $code = $period->getCode(); + + try { + return match ($code) { + '1W' => 'w', + '1M' => 'm', + '3M' => 'q', + '6M' => 'b', + '12M', '1Y' => 'a', + '2Y' => 'bia', + '3Y' => 'tria', + }; + } catch (\UnhandledMatchError) { + throw new \FOSSBilling\Exception('Unknown period selected ' . $code); + } + } + + private function getProductPaymentById(int $id): ProductPayment + { + $productPayment = $this->getProductPaymentRepository()->find($id); + if (!$productPayment instanceof ProductPayment) { + throw new \FOSSBilling\Exception('Product payment not found'); + } + + return $productPayment; + } + + private function getDbalConnection(): Connection + { + if ($this->di === null) { + throw new \FOSSBilling\Exception('The dependency injection container has not been set.'); + } + + if (isset($this->di['dbal']) && $this->di['dbal'] instanceof Connection) { + return $this->di['dbal']; + } + + return $this->di['em']->getConnection(); + } + + private function createDefaultProductPayment(): ProductPayment + { + $productPayment = new ProductPayment(); + $productPayment->setType(ProductPayment::FREE); + $this->di['em']->persist($productPayment); + $this->di['em']->flush(); + + return $productPayment; + } + + private function generateUniqueProductSlug(string $title): string + { + $slug = $this->di['tools']->slug($title); + + while ($this->getProductRepository()->findOneBy(['slug' => $slug]) instanceof Product) { + $slug = $this->di['tools']->slug($title) . '-' . random_int(1, 9999); + } + + return $slug; + } + + private function resolveStockProduct(Product|int $product): Product + { + if ($product instanceof Product) { + return $product; + } + + return $this->findProductById($product); + } + + /** + * @param mixed[] $ids + * + * @return list + */ + private function normalizeProductIds(array $ids): array + { + return array_values(array_unique(array_filter( + array_map('intval', $ids), + static fn (int $id): bool => $id > 0 + ))); + } + + /** + * @param array $pricing + */ + private function applyPricingToProductPayment(ProductPayment $productPayment, array $pricing): void + { + $productPayment->setType((string) $pricing['type']); + + if ($pricing['type'] == ProductPayment::ONCE) { + $productPayment + ->setOnceSetupPrice((float) ($pricing['once']['setup'] ?? 0)) + ->setOncePrice((float) ($pricing['once']['price'] ?? 0)); + } + + if ($pricing['type'] == ProductPayment::RECURRENT) { + $periodMap = [ + '1W' => 'w', + '1M' => 'm', + '3M' => 'q', + '6M' => 'b', + '1Y' => 'a', + '2Y' => 'bia', + '3Y' => 'tria', + ]; + + foreach ($periodMap as $period => $prefix) { + if (!isset($pricing['recurrent'][$period])) { + continue; + } + + $periodPricing = $pricing['recurrent'][$period]; + $productPayment->setPeriodPricing( + $prefix, + (float) ($periodPricing['price'] ?? 0), + (float) ($periodPricing['setup'] ?? 0), + $periodPricing['enabled'] ?? false + ); + } + } + } + + public function findProductById(int $id): Product + { + $product = $this->getProductRepository()->find($id); + if (!$product instanceof Product) { + throw new \FOSSBilling\Exception('Product not found'); + } + + return $product; + } + + public function getProductModuleService(Product $product): object + { + $type = $this->getProductType($product); + if ($type === null || $type === '') { + throw new \FOSSBilling\Exception('Product type could not be determined.'); + } + + return $this->di['mod_service']('service' . $type); + } + + private function getProductId(Product $product): ?int + { + return $product->getId(); + } + + private function getProductCategoryId(Product $product): ?int + { + return $product->getProductCategoryId(); + } + + private function getProductPaymentId(Product $product): ?int + { + return $product->getProductPaymentId(); + } + + private function getProductFormId(Product $product): ?int + { + return $product->getFormId(); + } + + private function getProductType(Product $product): ?string + { + return $product->getType(); + } + + private function getProductTitle(Product $product): ?string + { + return $product->getTitle(); + } + + private function getProductSlug(Product $product): ?string + { + return $product->getSlug(); + } + + private function getProductDescription(Product $product): ?string + { + return $product->getDescription(); + } + + private function getProductPriority(Product $product): ?int + { + return $product->getPriority(); + } + + private function getProductIconUrl(Product $product): ?string + { + return $product->getIconUrl(); + } + + private function isAllowQuantitySelect(Product $product): bool + { + return $product->isAllowQuantitySelect(); + } + + private function getProductQuantityInStock(Product $product): int + { + return $product->getQuantityInStock(); + } + + private function isStockControlled(Product $product): bool + { + return $product->isStockControl(); + } + + private function getProductStatus(Product $product): string + { + return $product->getStatus(); + } + + private function isProductHidden(Product $product): bool + { + return $product->isHidden(); + } + + private function getProductSetup(Product $product): string + { + return $product->getSetup(); + } + + private function getProductAddonsJson(Product $product): ?string + { + return $product->getAddons(); + } + + private function getProductPlugin(Product $product): ?string + { + return $product->getPlugin(); + } + + private function getProductConfigJson(Product $product): ?string + { + return $product->getConfig(); + } + + /** + * @return array + */ + private function getProductValidationData(Product $product): array + { + return [ + 'id' => $this->getProductId($product), + 'product_category_id' => $this->getProductCategoryId($product), + 'product_payment_id' => $this->getProductPaymentId($product), + 'form_id' => $this->getProductFormId($product), + 'title' => $this->getProductTitle($product), + 'description' => $this->getProductDescription($product), + 'unit' => $this->getProductUnit($product), + 'status' => $this->getProductStatus($product), + 'config' => json_decode($this->getProductConfigJson($product) ?? '', true) ?? [], + 'plugin' => $this->getProductPlugin($product), + 'type' => $this->getProductType($product), + ]; + } + + private function getProductUpgradesJson(Product $product): ?string + { + return $product->getUpgrades(); + } + + private function getProductCreatedAt(Product $product): mixed + { + return $product->getCreatedAt(); + } + + private function getProductUpdatedAt(Product $product): mixed + { + return $product->getUpdatedAt(); + } + + private function setProductCategoryIdValue(Product $product, ?int $value): void + { + $product->setProductCategoryId($value); + } + + private function setProductFormIdValue(Product $product, ?int $value): void + { + $product->setFormId($value); + } + + private function setProductIconUrlValue(Product $product, ?string $value): void + { + $product->setIconUrl($value); + } + + private function setProductStatusValue(Product $product, string $value): void + { + $product->setStatus($value); + } + + private function setProductHiddenValue(Product $product, bool $value): void + { + $product->setHidden($value); + } + + private function setProductSlugValue(Product $product, ?string $value): void + { + $product->setSlug($value); + } + + private function setProductSetupValue(Product $product, string $value): void + { + $product->setSetup($value); + } + + private function setProductUpgradesJson(Product $product, ?string $value): void + { + $product->setUpgrades($value); + } + + private function setProductAddonsJsonValue(Product $product, ?string $value): void + { + $product->setAddons($value); + } + + private function setProductTitleValue(Product $product, ?string $value): void + { + $product->setTitle($value); + } + + private function setProductStockControlValue(Product $product, bool $value): void + { + $product->setStockControl($value); + } + + private function setProductAllowQuantitySelectValue(Product $product, bool $value): void + { + $product->setAllowQuantitySelect($value); + } + + private function setProductQuantityInStockValue(Product $product, int $value): void + { + $product->setQuantityInStock($value); + } + + private function setProductDescriptionValue(Product $product, ?string $value): void + { + $product->setDescription($value); + } + + private function setProductPluginValue(Product $product, ?string $value): void + { + $product->setPlugin($value); + } + + private function setProductConfigJson(Product $product, ?string $value): void + { + $product->setConfig($value); + } + + private function setProductUpdatedAtValue(Product $product, \DateTime $value): void + { + $product->setUpdatedAt($value); + } + + private function formatDateTimeValue(mixed $value): ?string + { + if ($value instanceof \DateTimeInterface) { + return $value->format('Y-m-d H:i:s'); + } + + return $value !== null ? (string) $value : null; + } + + /** + * @param callable(object): array $mapper + * + * @return array{pages:int,page:int,per_page:int,total:int,list:array} + */ + private function paginateMappedQuery(QueryBuilder $qb, PaginationOptions $pagination, callable $mapper): array + { + $offset = ($pagination->page - 1) * $pagination->perPage; + $qb->setFirstResult($offset) + ->setMaxResults($pagination->perPage); + $paginator = new DoctrinePaginator($qb, true); + $total = count($paginator); + + $list = []; + foreach ($paginator as $entity) { + $list[] = $mapper($entity); + } + + return [ + 'pages' => $total > 0 ? (int) ceil($total / $pagination->perPage) : 0, + 'page' => $pagination->page, + 'per_page' => $pagination->perPage, + 'total' => $total, + 'list' => $list, + ]; + } + + public function getProductDiscount(Product $product, Promo $promo, ?array $config = null) { if (!$this->isPromoLinkedToProduct($promo, $product)) { return 0; @@ -1076,9 +2118,7 @@ class Service implements InjectionAwareInterface } } - $product->setDi($this->di); - $repo = $product->getTable(); - $line = $repo->getOrderLineConfig($product, $config); + $line = $this->getProductOrderLineConfig($product, $config); $price = $line['price'] * $line['quantity']; if ($price == 0) { @@ -1087,14 +2127,16 @@ class Service implements InjectionAwareInterface $discount = 0; - switch ($promo->type) { - case \Model_Promo::ABSOLUTE: - $discount += $promo->value; + $promoData = $this->getPromoSourceArray($promo); + + switch ($promoData['type'] ?? null) { + case Promo::ABSOLUTE: + $discount += (float) ($promoData['value'] ?? 0); break; - case \Model_Promo::PERCENTAGE: - $discount += round($price * $promo->value / 100, 2); + case Promo::PERCENTAGE: + $discount += round($price * (float) ($promoData['value'] ?? 0) / 100, 2); break; @@ -1105,7 +2147,7 @@ class Service implements InjectionAwareInterface return $discount; } - public function getRenewalProductDiscount(\Model_Product $product, \Model_Promo $promo, ?array $config = null): float + public function getRenewalProductDiscount(Product $product, Promo $promo, ?array $config = null): float { if (!$this->isPromoLinkedToProduct($promo, $product)) { return 0; @@ -1118,43 +2160,455 @@ class Service implements InjectionAwareInterface } } - $product->setDi($this->di); - $repo = $product->getTable(); - if (!method_exists($repo, 'getRenewalLineConfig')) { - return $this->getProductDiscount($product, $promo, $config); - } - - $line = $repo->getRenewalLineConfig($product, $config); + $line = $this->getProductRenewalLineConfig($product, $config); $price = $line['price'] * $line['quantity']; if ($price == 0) { return 0; } - return match ($promo->type) { - \Model_Promo::ABSOLUTE => (float) $promo->value, - \Model_Promo::PERCENTAGE => round($price * $promo->value / 100, 2), + $promoData = $this->getPromoSourceArray($promo); + + return match ($promoData['type'] ?? null) { + Promo::ABSOLUTE => (float) ($promoData['value'] ?? 0), + Promo::PERCENTAGE => round($price * (float) ($promoData['value'] ?? 0) / 100, 2), default => 0, }; } - public function isPromoLinkedToTld(\Model_Promo $promo, \Model_Tld $tld): bool + public function isPromoLinkedToTld(Promo $promo, \Model_Tld $tld): bool { - foreach ($promo->PromoItem as $item) { - if ($item->tld_id == $tld->id) { - return true; - } + unset($tld); + + if ($this->getProducts($promo) === []) { + return true; } - return false; + $domainProduct = $this->getMainDomainProduct(); + if (!$domainProduct instanceof Product) { + return false; + } + + return $this->isPromoLinkedToProduct($promo, $domainProduct); } // Function to get all orders for a product - public function getOrdersForProduct(\Model_Product $product) + public function getOrdersForProduct(Product $product) { - // return type Model_ClientOrder that have product_id = $product->id - $sql = 'SELECT * FROM client_order WHERE product_id = :product_id'; + return $this->getProductOrderRepository()->getRowsByProductId((int) $this->getProductId($product)); + } - return $this->di['db']->getAll($sql, [':product_id' => $product->id], '\Model_ClientOrder'); + /** + * @param list $redemptions + */ + private function releasePromoRedemptions(array $redemptions, string $reason): void + { + if ($redemptions === []) { + return; + } + + $releasedAt = new \DateTime(); + $checkoutReleaseCounts = []; + foreach ($redemptions as $redemption) { + if ($redemption->getStatus() !== PromoRedemption::STATUS_RESERVED) { + continue; + } + + $redemption + ->setStatus(PromoRedemption::STATUS_RELEASED) + ->setReleasedAt(clone $releasedAt) + ->setReleaseReason($reason); + + if ($redemption->getPhase() === PromoRedemption::PHASE_CHECKOUT && $redemption->getPromoId() !== null) { + $promoId = (int) $redemption->getPromoId(); + $checkoutReleaseCounts[$promoId] = ($checkoutReleaseCounts[$promoId] ?? 0) + 1; + } + } + + foreach ($checkoutReleaseCounts as $promoId => $releaseCount) { + $this->getPromoRepository()->decrementUsage($promoId, $releaseCount, $releasedAt); + } + + $this->di['em']->flush(); + } + + private function newPromoRedemption( + Promo $promo, + \Model_Client $client, + ?\Model_ClientOrder $order, + ?\Model_Invoice $invoice, + string $phase, + ?float $discountAmount, + ?string $currency, + ?string $createdAt, + string $status, + ): PromoRedemption { + $promoId = (int) ($this->getPromoSourceArray($promo)['id'] ?? 0); + $timestamp = $createdAt ?? date('Y-m-d H:i:s'); + $dateTime = new \DateTime($timestamp); + $redemption = new PromoRedemption(); + $redemption + ->setPromoId($promoId) + ->setClientId((int) $client->id) + ->setClientOrderId($order?->id !== null ? (int) $order->id : null) + ->setInvoiceId($invoice?->id !== null ? (int) $invoice->id : null) + ->setPhase($phase) + ->setStatus($status) + ->setDiscountAmount($discountAmount) + ->setCurrency($currency); + $redemption->setCreatedAt($dateTime); + $redemption->setUpdatedAt(clone $dateTime); + if ($status === PromoRedemption::STATUS_COMMITTED) { + $redemption->setCommittedAt(clone $dateTime); + } + + return $redemption; + } + + private function getPromoApiSourceArray(Promo $model): array + { + return $model->toApiArray(); + } + + private function getPromoSourceArray(Promo $model): array + { + return $this->getPromoApiSourceArray($model); + } + + private function getPromoRedemptionCountById(int $promoId): int + { + return $this->getPromoRedemptionRepository()->countByPromoId($promoId); + } + + private function getDomainRegistrationYears(array $config): int + { + if (isset($config['period']) && is_string($config['period']) && $config['period'] !== '') { + $period = $this->di['period']($config['period']); + + return max(1, $period->getQty()); + } + + return max(1, (int) ($config['register_years'] ?? $config['quantity'] ?? 1)); + } + + private function getDomainTldModel(array $config): \Model_Tld + { + $tldService = $this->di['mod_service']('servicedomain', 'Tld'); + $tld = ''; + + if (!isset($config['action'])) { + throw new \FOSSBilling\Exception('Could not determine domain price. Domain action is missing', null, 498); + } + + if ($config['action'] === 'register') { + $tld = $config['register_tld'] ?? ''; + } + + if ($config['action'] === 'transfer') { + $tld = $config['transfer_tld'] ?? ''; + } + + $tld = $tldService->findOneByTld($tld); + if (!$tld instanceof \Model_Tld) { + throw new \FOSSBilling\Exception('Unknown TLD. Could not determine registration price'); + } + + return $tld; + } + + private function getDomainRegistrationTotal(\Model_Tld $tld, int $years): float + { + if ($years <= 0) { + return 0.0; + } + + if ($years <= 1) { + return (float) $tld->price_registration; + } + + return (float) $tld->price_registration + (($years - 1) * (float) $tld->price_renew); + } + + /** + * @return array{price: float, quantity: int, setup_price: float} + */ + private function getDomainOrderLineConfig(array $config): array + { + if (($config['action'] ?? null) === 'owndomain') { + return [ + 'price' => 0.0, + 'quantity' => 1, + 'setup_price' => 0.0, + ]; + } + + $tld = $this->getDomainTldModel($config); + if (($config['action'] ?? null) === 'register') { + return [ + 'price' => $this->getDomainRegistrationTotal($tld, $this->getDomainRegistrationYears($config)), + 'quantity' => 1, + 'setup_price' => 0.0, + ]; + } + + return [ + 'price' => (float) $tld->price_transfer, + 'quantity' => 1, + 'setup_price' => 0.0, + ]; + } + + /** + * @return array{price: float, quantity: int} + */ + private function getDomainRenewalLineConfig(array $config): array + { + $tld = $this->getDomainTldModel($config); + + return [ + 'price' => (float) $tld->price_renew, + 'quantity' => $this->getDomainRegistrationYears($config), + ]; + } + + public function getDomainProductPrice(array $config): float + { + if (($config['action'] ?? null) === 'owndomain') { + return 0.0; + } + + $tld = $this->getDomainTldModel($config); + + return match ($config['action'] ?? null) { + 'register' => (float) $tld->price_registration, + 'transfer' => (float) $tld->price_transfer, + default => 0.0, + }; + } + + private function getDomainRelatedDiscount(array $items, array $config): float + { + foreach ($items as $addon) { + if ( + $this->isDomainActionNameSet($addon, 'register') + && $this->isFreeDomainEnabled($addon) + && $this->registerDomainMatches($addon, $config) + ) { + if ($this->hasFreeDomainPeriod($addon)) { + $discountYears = $this->getFreeDomainDiscountYears($addon, (string) ($config['period'] ?? '')); + $tld = $this->getDomainTldModel($config); + + return $this->getDomainRegistrationTotal($tld, $discountYears); + } + + return 0.0; + } + + if ( + $this->isDomainActionNameSet($addon, 'transfer') + && $this->isFreeTransferEnabled($addon) + && $this->transferDomainMatches($addon, $config) + ) { + return $this->getDomainProductPrice($config); + } + } + + return 0.0; + } + + private function hasFreeDomainPeriod(array $addon): bool + { + $freeDomainPeriods = $addon['config']['free_domain_periods'] ?? []; + $addonPeriod = $addon['config']['period'] ?? null; + + return $addonPeriod !== null && in_array($addonPeriod, $freeDomainPeriods, true); + } + + private function getFreeDomainDiscountYears(array $addon, string $period): int + { + $referencePeriod = $this->di['period']($period); + $referenceQty = $referencePeriod->getQty(); + + $addonPeriod = $addon['config']['period']; + $addonQty = $this->di['period']($addonPeriod)->getQty(); + + $freeDomainPeriods = $addon['config']['free_domain_periods'] ?? []; + if (\FOSSBilling\Tools::safeCount($freeDomainPeriods) > 0) { + if ($addonPeriod === $period && in_array($addonPeriod, $freeDomainPeriods, true)) { + return $referenceQty; + } + + if (str_contains((string) $addonPeriod, 'Y')) { + if (min($referenceQty, $addonQty) === 1) { + return 1; + } + + $freeDomainQtys = []; + foreach ($freeDomainPeriods as $freePeriod) { + $quantity = $this->di['period']($freePeriod)->getQty(); + if ($referenceQty - $quantity > 0) { + $freeDomainQtys[] = $quantity; + } + } + + if ($freeDomainQtys !== []) { + return min($referenceQty, min($freeDomainQtys)); + } + } + } + + return 0; + } + + private function isDomainActionNameSet(array $item, string $actionName): bool + { + return isset($item['config']['domain']['action']) && $item['config']['domain']['action'] === $actionName; + } + + private function isFreeDomainEnabled(array $item): bool + { + $freeDomain = $item['config']['free_domain'] ?? false; + if (!$freeDomain) { + return false; + } + + $tld = $item['config']['tld'] ?? null; + $freeTlds = $item['config']['free_tlds'] ?? []; + if ($freeTlds === []) { + return true; + } + + return $tld !== null && in_array($tld, $freeTlds, true); + } + + private function registerDomainMatches(array $item, array $config): bool + { + if (!isset($item['config']['domain']['register_sld'])) { + return false; + } + + return ($item['config']['domain']['register_sld'] ?? null) === ($config['register_sld'] ?? null) + && ($item['config']['domain']['register_tld'] ?? null) === ($config['register_tld'] ?? null); + } + + private function transferDomainMatches(array $item, array $config): bool + { + if (!isset($item['config']['domain']['transfer_sld'])) { + return false; + } + + return ($item['config']['domain']['transfer_sld'] ?? null) === ($config['transfer_sld'] ?? null) + && ($item['config']['domain']['transfer_tld'] ?? null) === ($config['transfer_tld'] ?? null); + } + + private function isFreeTransferEnabled(array $item): bool + { + return !empty($item['config']['free_transfer']); + } + + /** + * @return array{ + * operational_use_count: int, + * max_uses: int|null, + * remaining_operational_uses: int|null, + * 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 + * } + */ + private function getPromoUsageStatsByValues(int $promoId, int $operationalUseCount, ?int $maxUses): array + { + $repoStats = $this->getPromoRedemptionRepository()->getUsageStatsByPromoId($promoId); + + return [ + 'operational_use_count' => $operationalUseCount, + 'max_uses' => $maxUses, + 'remaining_operational_uses' => $maxUses !== null ? max($maxUses - $operationalUseCount, 0) : null, + 'recorded_applications' => $repoStats['recorded_applications'], + 'checkout_applications' => $repoStats['checkout_applications'], + 'renewal_applications' => $repoStats['renewal_applications'], + 'active_checkout_applications' => $repoStats['active_checkout_applications'], + 'reserved_applications' => $repoStats['reserved_applications'], + 'committed_applications' => $repoStats['committed_applications'], + 'released_applications' => $repoStats['released_applications'], + 'distinct_clients' => $repoStats['distinct_clients'], + 'orders_using_promo' => $repoStats['orders_using_promo'], + ]; + } + + private function hasPromoRedemptionHistoryById(int $promoId, ?int $redemptionCount = null): bool + { + $redemptionCount ??= $this->getPromoRedemptionCountById($promoId); + if ($redemptionCount > 0) { + return true; + } + + $orderCount = $this->getPromoRepository()->countLinkedOrdersByPromoId($promoId); + + return $orderCount > 0; + } + + private function applyPromoDataToEntity(Promo $promo, array $data): void + { + $promo + ->setCode($data['code'] ?? $promo->getCode()) + ->setDescription($data['description'] ?? $promo->getDescription()) + ->setType((string) ($data['type'] ?? $promo->getType())) + ->setValue($data['value'] ?? $promo->getValue()) + ->setActive((bool) ($data['active'] ?? $promo->isActive())) + ->setFreeSetup((bool) ($data['freesetup'] ?? $promo->isFreeSetup())) + ->setOncePerClient((bool) ($data['once_per_client'] ?? $promo->isOncePerClient())) + ->setRecurring((bool) ($data['recurring'] ?? $promo->isRecurring())) + ->setUsed(isset($data['used']) ? (int) $data['used'] : $promo->getUsed()) + ->setMaxUses(isset($data['maxuses']) ? (int) $data['maxuses'] : $promo->getMaxUses()) + ->setProducts($this->encodePromoSelection($data['products'] ?? $this->decodePromoSelection($promo->getProducts()))) + ->setPeriods($this->encodePromoSelection($data['periods'] ?? $this->decodePromoSelection($promo->getPeriods()))) + ->setClientGroups($this->encodePromoSelection($data['client_groups'] ?? $this->decodePromoSelection($promo->getClientGroups()))) + ->setStartAt($this->normalizePromoDateTimeObject($data['start_at'] ?? $promo->getStartAt())) + ->setEndAt($this->normalizePromoDateTimeObject($data['end_at'] ?? $promo->getEndAt())); + } + + /** + * @param array|null $selection + */ + private function encodePromoSelection(mixed $selection): ?string + { + if (!is_array($selection)) { + return null; + } + + $selection = array_values(array_filter($selection)); + + return $selection === [] ? null : json_encode($selection); + } + + /** + * @return array + */ + private function decodePromoSelection(?string $selection): array + { + return json_decode($selection ?? '', true) ?? []; + } + + private function normalizePromoDateTime(mixed $value): ?string + { + return !empty($value) ? date('Y-m-d H:i:s', strtotime((string) $value)) : null; + } + + private function normalizePromoDateTimeObject(mixed $value): ?\DateTime + { + if ($value instanceof \DateTime) { + return clone $value; + } + + $normalized = $this->normalizePromoDateTime($value); + + return $normalized !== null ? new \DateTime($normalized) : null; } } diff --git a/src/modules/Product/templates/admin/mod_product_promo.html.twig b/src/modules/Product/templates/admin/mod_product_promo.html.twig index 74299e939..0805368c9 100644 --- a/src/modules/Product/templates/admin/mod_product_promo.html.twig +++ b/src/modules/Product/templates/admin/mod_product_promo.html.twig @@ -24,6 +24,108 @@ {% endblock %} {% block content %} +
+
+

{{ 'Manage Promotion'|trans }}

+ {% if not promo.can_be_deleted %} + + {% endif %} + {% set stats = promo.usage_stats %} +
+
+
+
+
{{ 'Recorded Applications'|trans }}
+
{{ stats.recorded_applications }}
+
+
+
+
+
+
+
{{ 'Checkout Applications'|trans }}
+
{{ stats.checkout_applications }}
+
+
+
+
+
+
+
{{ 'Renewal Applications'|trans }}
+
{{ stats.renewal_applications }}
+
+
+
+
+
+
+
{{ 'Reserved Applications'|trans }}
+
{{ stats.reserved_applications }}
+
+
+
+
+
+
+
{{ 'Committed Applications'|trans }}
+
{{ stats.committed_applications }}
+
+
+
+
+
+
+
{{ 'Released Applications'|trans }}
+
{{ stats.released_applications }}
+
+
+
+
+
+
+
{{ 'Distinct Clients'|trans }}
+
{{ stats.distinct_clients }}
+
+
+
+
+
+
+
{{ 'Orders Using Promo'|trans }}
+
{{ stats.orders_using_promo }}
+
+
+
+
+
+
+
{{ 'Operational Counter'|trans }}
+
+ {{ stats.operational_use_count }} + {% if stats.max_uses is not null %}/ {{ stats.max_uses }}{% else %}/ ∞{% endif %} +
+
+ {{ 'Used only for max-use enforcement, not historical reporting.'|trans }} +
+
+ {{ 'Active checkout applications'|trans }}: {{ stats.active_checkout_applications }} +
+
+ {% if stats.remaining_operational_uses is null %} + {{ 'Remaining operational uses'|trans }}: {{ 'Unlimited'|trans }} + {% else %} + {{ 'Remaining operational uses'|trans }}: {{ stats.remaining_operational_uses }} + {% endif %} +
+
+
+
+
+
+
+
{% embed 'partial_admin_form_card.html.twig' with { diff --git a/src/modules/Product/templates/admin/mod_product_promos.html.twig b/src/modules/Product/templates/admin/mod_product_promos.html.twig index fbb921e82..03da2ae16 100644 --- a/src/modules/Product/templates/admin/mod_product_promos.html.twig +++ b/src/modules/Product/templates/admin/mod_product_promos.html.twig @@ -50,7 +50,7 @@
- + @@ -81,19 +81,35 @@ until {% if promo.end_at %}{{ promo.end_at|format_date }}{% else %}disabled{% endif %} - + {% else %} diff --git a/src/modules/Product/tests/Unit/Api/AdminTest.php b/src/modules/Product/tests/Unit/Api/AdminTest.php index 71f6dcbcc..47c41579b 100644 --- a/src/modules/Product/tests/Unit/Api/AdminTest.php +++ b/src/modules/Product/tests/Unit/Api/AdminTest.php @@ -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(); }); diff --git a/src/modules/Product/tests/Unit/Api/GuestTest.php b/src/modules/Product/tests/Unit/Api/GuestTest.php index 453c87ef9..88902bcf7 100644 --- a/src/modules/Product/tests/Unit/Api/GuestTest.php +++ b/src/modules/Product/tests/Unit/Api/GuestTest.php @@ -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([]); diff --git a/src/modules/Product/tests/Unit/ServiceTest.php b/src/modules/Product/tests/Unit/ServiceTest.php index ebe13e13a..2815abb66 100644 --- a/src/modules/Product/tests/Unit/ServiceTest.php +++ b/src/modules/Product/tests/Unit/ServiceTest.php @@ -10,19 +10,200 @@ declare(strict_types=1); +use Box\Mod\Product\Entity\Product; +use Box\Mod\Product\Entity\ProductCategory; +use Box\Mod\Product\Entity\ProductPayment; +use Box\Mod\Product\Entity\Promo; +use Box\Mod\Product\Entity\PromoRedemption; +use Box\Mod\Product\Repository\ProductCategoryRepository; +use Box\Mod\Product\Repository\ProductPaymentRepository; +use Box\Mod\Product\Repository\ProductRepository; +use Box\Mod\Product\Repository\PromoRedemptionRepository; +use Box\Mod\Product\Repository\PromoRepository; use Box\Mod\Product\Service; +use Doctrine\DBAL\Connection; +use Doctrine\DBAL\DriverManager; use function Tests\Helpers\container; -test('gets dependency injection container', function (): void { - $service = new Service(); - $di = container(); - $service->setDi($di); - $getDi = $service->getDi(); - expect($getDi)->toBe($di); -}); +function productTestCreateProductEntity(int $id): Product +{ + $product = new Product(); + $reflection = new ReflectionProperty($product, 'id'); + $reflection->setAccessible(true); + $reflection->setValue($product, $id); -test('gets product pairs', function (): void { + return $product; +} + +function productTestCreatePromoEntity(int $id): Promo +{ + $promo = new Promo(); + $reflection = new ReflectionProperty($promo, 'id'); + $reflection->setAccessible(true); + $reflection->setValue($promo, $id); + + return $promo; +} + +function productTestCreateProductCategoryEntity(int $id): ProductCategory +{ + $category = new ProductCategory(); + $reflection = new ReflectionProperty($category, 'id'); + $reflection->setAccessible(true); + $reflection->setValue($category, $id); + + return $category; +} + +function productTestCreateProductPaymentEntity(int $id): ProductPayment +{ + $productPayment = new ProductPayment(); + $reflection = new ReflectionProperty($productPayment, 'id'); + $reflection->setAccessible(true); + $reflection->setValue($productPayment, $id); + + return $productPayment; +} + +function productTestCreateEntityManagerWithRepositories( + ?ProductRepository $productRepo = null, + ?ProductPaymentRepository $paymentRepo = null, + ?Product $persistedProduct = null, + ?ProductPayment $persistedPayment = null, + ?ProductCategoryRepository $categoryRepo = null, + ?ProductCategory $persistedCategory = null, +): object { + return new class($productRepo, $paymentRepo, $persistedProduct, $persistedPayment, $categoryRepo, $persistedCategory) { + public int $flushCalls = 0; + + public function __construct( + private ?ProductRepository $productRepo, + private ?ProductPaymentRepository $paymentRepo, + private ?Product $persistedProduct, + private ?ProductPayment $persistedPayment, + private ?ProductCategoryRepository $categoryRepo, + private ?ProductCategory $persistedCategory, + ) { + } + + public function getRepository(string $class): object + { + return match ($class) { + Product::class => $this->productRepo ?? throw new RuntimeException('Product repository not configured'), + ProductPayment::class => $this->paymentRepo ?? throw new RuntimeException('ProductPayment repository not configured'), + ProductCategory::class => $this->categoryRepo ?? throw new RuntimeException('ProductCategory repository not configured'), + default => throw new RuntimeException('Unexpected repository ' . $class), + }; + } + + public function persist(object $entity): void + { + if ($entity instanceof Product && $this->persistedProduct instanceof Product) { + $reflection = new ReflectionProperty($entity, 'id'); + $reflection->setAccessible(true); + $reflection->setValue($entity, $this->persistedProduct->getId()); + } + + if ($entity instanceof ProductPayment && $this->persistedPayment instanceof ProductPayment) { + $reflection = new ReflectionProperty($entity, 'id'); + $reflection->setAccessible(true); + $reflection->setValue($entity, $this->persistedPayment->getId()); + } + + if ($entity instanceof ProductCategory && $this->persistedCategory instanceof ProductCategory) { + $reflection = new ReflectionProperty($entity, 'id'); + $reflection->setAccessible(true); + $reflection->setValue($entity, $this->persistedCategory->getId()); + } + } + + public function remove(object $entity): void + { + } + + public function flush(): void + { + ++$this->flushCalls; + } + }; +} + +function productTestCreateProductPaymentEntityManager(ProductPaymentRepository $paymentRepo): object +{ + return new class($paymentRepo) { + public int $flushCalls = 0; + + public function __construct(private ProductPaymentRepository $paymentRepo) + { + } + + public function getRepository(string $class): object + { + return $this->paymentRepo; + } + + public function persist(object $entity): void + { + } + + public function flush(): void + { + ++$this->flushCalls; + } + }; +} + +function productTestCreateDomainPricingDbalConnection(): Connection +{ + $connection = DriverManager::getConnection([ + 'driver' => 'pdo_sqlite', + 'memory' => true, + ]); + + $connection->executeStatement('CREATE TABLE tld_registrar (id INTEGER PRIMARY KEY, name TEXT)'); + $connection->executeStatement('CREATE TABLE tld ( + id INTEGER PRIMARY KEY, + tld_registrar_id INTEGER, + tld TEXT, + price_registration NUMERIC, + price_renew NUMERIC, + price_transfer NUMERIC, + allow_register INTEGER, + allow_transfer INTEGER, + active INTEGER, + min_years INTEGER + )'); + $connection->executeStatement("INSERT INTO tld_registrar (id, name) VALUES (1, 'Registrar A')"); + $connection->executeStatement("INSERT INTO tld (id, tld_registrar_id, tld, price_registration, price_renew, price_transfer, allow_register, allow_transfer, active, min_years) VALUES (1, 1, '.com', 10.00, 12.00, 14.00, 1, 1, 1, 1)"); + $connection->executeStatement("INSERT INTO tld (id, tld_registrar_id, tld, price_registration, price_renew, price_transfer, allow_register, allow_transfer, active, min_years) VALUES (2, 1, '.net', 11.00, 13.00, 15.00, 1, 1, 0, 1)"); + + return $connection; +} + +function productTestCreateProductOrderDbalConnection(): Connection +{ + $connection = DriverManager::getConnection([ + 'driver' => 'pdo_sqlite', + 'memory' => true, + ]); + + $connection->executeStatement('CREATE TABLE client_order (id INTEGER PRIMARY KEY, product_id INTEGER)'); + $connection->executeStatement('INSERT INTO client_order (id, product_id) VALUES (11, 7)'); + $connection->executeStatement('INSERT INTO client_order (id, product_id) VALUES (12, 8)'); + + return $connection; +} + +function productTestCreateDomainTldServiceMock(Model_Tld $tld): Mockery\MockInterface +{ + $tldService = Mockery::mock(Box\Mod\Servicedomain\ServiceTld::class); + $tldService->shouldReceive('findOneByTld')->atLeast()->once()->with('.com')->andReturn($tld); + + return $tldService; +} + +test('get pairs', function (): void { $service = new Service(); $data = [ 'type' => 'domain', @@ -41,160 +222,60 @@ test('gets product pairs', function (): void { '1' => 'title4test', ]; - $dbMock = Mockery::mock('\Box_Database'); - /** @var Mockery\Expectation $expectation */ - $expectation = $dbMock->shouldReceive('getAll'); - $expectation->atLeast()->once(); - $expectation->andReturn($execArray); + $productRepo = Mockery::mock(ProductRepository::class); + $productRepo->shouldReceive('getPairs')->once()->with($data)->andReturn($expectArray); $di = container(); - $di['db'] = $dbMock; + $di['em'] = productTestCreateEntityManagerWithRepositories($productRepo); $service->setDi($di); $result = $service->getPairs($data); expect($result)->toBeArray(); - expect($result)->toBe($expectArray); + expect($result)->toEqual($expectArray); }); -test('converts product to api array', function (): void { +test('to api array', function (): void { $serviceMock = Mockery::mock(Service::class)->makePartial(); - /** @var Mockery\Expectation $expectation1 */ - $expectation1 = $serviceMock->shouldReceive('getStartingFromPrice'); - $expectation1->atLeast()->once(); - /** @var Mockery\Expectation $expectation2 */ - $expectation2 = $serviceMock->shouldReceive('getUpgradablePairs'); - $expectation2->atLeast()->once(); - + $serviceMock->shouldReceive('getStartingFromPrice')->atLeast()->once(); + $serviceMock->shouldReceive('getUpgradablePairs')->atLeast()->once(); $productPaymentArray = [ 'type' => 'free', - Model_ProductPayment::FREE => ['price' => 0, 'setup' => 0], - Model_ProductPayment::ONCE => ['price' => 1, 'setup' => 10], - Model_ProductPayment::RECURRENT => [], + ProductPayment::FREE => ['price' => 0, 'setup' => 0], + ProductPayment::ONCE => ['price' => 1, 'setup' => 10], + ProductPayment::RECURRENT => [], ]; - /** @var Mockery\Expectation $expectation3 */ - $expectation3 = $serviceMock->shouldReceive('toProductPaymentApiArray'); - $expectation3->atLeast()->once(); - $expectation3->andReturn($productPaymentArray); + $serviceMock->shouldReceive('toProductPaymentApiArray')->atLeast()->once()->andReturn($productPaymentArray); - $model = new Model_Product(); - $model->loadBean(new Tests\Helpers\DummyBean()); - $model->product_category_id = 1; - $model->product_payment_id = 2; - $model->config = '{}'; + $model = productTestCreateProductEntity(1) + ->setProductCategoryId(1) + ->setProductPaymentId(2) + ->setConfig('{}'); - $modelProductCategory = new Model_ProductCategory(); - $modelProductCategory->loadBean(new Tests\Helpers\DummyBean()); - $modelProductCategory->type = 'free'; + $modelProductCategory = productTestCreateProductCategoryEntity(1)->setTitle('Category'); - $modelProductPayment = new Model_ProductPayment(); + $modelProductPayment = new ProductPayment(); - $dbMock = Mockery::mock('\Box_Database'); - /** @var Mockery\Expectation $expectation4 */ - $expectation4 = $dbMock->shouldReceive('load'); - $expectation4->atLeast()->once(); - $expectation4->andReturnUsing(fn ($type): Model_ProductPayment|\Model_ProductCategory => match ($type) { - 'ProductPayment' => $modelProductPayment, - 'ProductCategory' => $modelProductCategory, - }); + $paymentRepo = Mockery::mock(ProductPaymentRepository::class); + $paymentRepo->shouldReceive('find')->once()->with(2)->andReturn($modelProductPayment); + + $categoryRepo = Mockery::mock(ProductCategoryRepository::class); + $categoryRepo->shouldReceive('findById')->once()->with(1)->andReturn($modelProductCategory); $di = container(); - $di['db'] = $dbMock; + $di['em'] = productTestCreateEntityManagerWithRepositories(null, $paymentRepo, null, null, $categoryRepo); $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $serviceMock); - $model->setDi($di); $serviceMock->setDi($di); $result = $serviceMock->toApiArray($model, true, new Model_Admin()); expect($result)->toBeArray(); }); -test('converts public product to api array with addons', function (): void { - $serviceMock = Mockery::mock(Service::class)->makePartial(); - $serviceMock->shouldReceive('getStartingFromPrice') - ->atLeast() - ->once(); - - $product = new Model_Product(); - $product->loadBean(new Tests\Helpers\DummyBean()); - $product->id = 1; - $product->product_payment_id = 2; - $product->addons = '[3]'; - $product->config = json_encode([ - 'allow_domain_register' => true, - 'registrar' => 'hidden', - ]); - - $addon = new Model_Product(); - $addon->loadBean(new Tests\Helpers\DummyBean()); - $addon->id = 3; - $addon->product_payment_id = 4; - $addon->config = json_encode([ - 'allow_domain_own' => true, - 'registrar' => 'hidden', - ]); - - $productPayment = new Model_ProductPayment(); - $productPayment->loadBean(new Tests\Helpers\DummyBean()); - $addonProductPayment = new Model_ProductPayment(); - $addonProductPayment->loadBean(new Tests\Helpers\DummyBean()); - - $productPricing = [ - 'type' => 'free', - Model_ProductPayment::FREE => ['price' => 0, 'setup' => 0], - Model_ProductPayment::ONCE => ['price' => 0, 'setup' => 0], - ]; - $addonPricing = [ - 'type' => 'once', - Model_ProductPayment::ONCE => ['price' => 5, 'setup' => 1], - 'registrar' => 'hidden', - ]; - - $serviceMock->shouldReceive('getProductAddons') - ->once() - ->with($product, true) - ->andReturn([$addon]); - $serviceMock->shouldReceive('toProductPaymentApiArray') - ->once() - ->with($productPayment) - ->andReturn($productPricing); - $serviceMock->shouldReceive('toProductPaymentApiArray') - ->once() - ->with($addonProductPayment) - ->andReturn($addonPricing); - - $dbMock = Mockery::mock('\Box_Database'); - $dbMock->shouldReceive('load') - ->once() - ->with('ProductPayment', 2) - ->andReturn($productPayment); - $dbMock->shouldReceive('load') - ->once() - ->with('ProductPayment', 4) - ->andReturn($addonProductPayment); - - $di = container(); - $di['db'] = $dbMock; - $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $serviceMock); - - $product->setDi($di); - $addon->setDi($di); - $serviceMock->setDi($di); - - $result = $serviceMock->toApiArray($product); - - expect($result['addons'])->toHaveCount(1) - ->and($result['addons'][0]['id'])->toBe(3) - ->and($result['addons'][0]['pricing'])->not->toHaveKey('registrar') - ->and($result['addons'][0]['config'])->toBe(['allow_domain_own' => true]) - ->and($result['addons'][0])->not->toHaveKeys(['plugin', 'created_at', 'updated_at']) - ->and($result['config'])->toBe(['allow_domain_register' => true]); -}); - -test('gets product types', function (): void { +test('get types', function (): void { $service = new Service(); $modArray = [ - 'servicetest', + 'servicecustomtest', ]; $expectedArray = [ @@ -205,13 +286,10 @@ test('gets product types', function (): void { 'domain' => 'Domain', ]; - $expectedArray['test'] = 'Test'; + $expectedArray['customtest'] = 'Customtest'; $extensionServiceMock = Mockery::mock(Box\Mod\Extension\Service::class); - /** @var Mockery\Expectation $expectation */ - $expectation = $extensionServiceMock->shouldReceive('getInstalledMods'); - $expectation->atLeast()->once(); - $expectation->andReturn($modArray); + $extensionServiceMock->shouldReceive('getInstalledMods')->atLeast()->once()->andReturn($modArray); $di = container(); $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $extensionServiceMock); @@ -219,132 +297,449 @@ test('gets product types', function (): void { $service->setDi($di); $result = $service->getTypes(); expect($result)->toBeArray(); - expect($result)->toBe($expectedArray); + expect($result)->toEqual($expectedArray); }); -test('gets main domain product', function (): void { +test('get main domain product', function (): void { $service = new Service(); - $model = new Model_Product(); + $model = productTestCreateProductEntity(1); + $model->setType(Service::DOMAIN); - $dbMock = Mockery::mock('\Box_Database'); - /** @var Mockery\Expectation $expectation */ - $expectation = $dbMock->shouldReceive('findOne'); - $expectation->atLeast()->once(); - $expectation->andReturn($model); + $productRepository = Mockery::mock(ProductRepository::class); + $productRepository->shouldReceive('findMainDomainProduct')->once()->andReturn($model); $di = container(); - $di['db'] = $dbMock; + $di['em'] = productTestCreateEntityManagerWithRepositories($productRepository); $service->setDi($di); $result = $service->getMainDomainProduct(); - expect($result)->toBeInstanceOf('\Model_Product'); + expect($result)->toBeInstanceOf(Product::class); }); -test('gets payment types', function (): void { +test('get cart product title uses product service specific title', function (): void { + $service = new Service(); + $productService = new class { + public function getCartProductTitle(Product $product, array $config): string + { + return $product->getTitle() . ' ' . ($config['suffix'] ?? ''); + } + }; + + $product = productTestCreateProductEntity(1)->setType(Service::CUSTOM)->setTitle('Example'); + + $di = container(); + $di['mod_service'] = $di->protect(fn (string $serviceName): object => match ($serviceName) { + 'servicecustom' => $productService, + default => throw new RuntimeException('Unexpected service request ' . $serviceName), + }); + + $service->setDi($di); + expect($service->getCartProductTitle($product, ['suffix' => 'Title']))->toBe('Example Title'); +}); + +test('get cart product title falls back to product title', function (): void { + $service = new Service(); + $productService = new stdClass(); + $product = productTestCreateProductEntity(1)->setType(Service::CUSTOM)->setTitle('Example'); + + $di = container(); + $di['mod_service'] = $di->protect(fn (string $serviceName): object => match ($serviceName) { + 'servicecustom' => $productService, + default => throw new RuntimeException('Unexpected service request ' . $serviceName), + }); + + $service->setDi($di); + expect($service->getCartProductTitle($product, []))->toBe('Example'); +}); + +test('get related product discount returns zero for non domain products', function (): void { + $service = new Service(); + $product = productTestCreateProductEntity(1)->setType(Service::CUSTOM); + + $service->setDi(container()); + expect($service->getRelatedProductDiscount($product, [['id' => 1]], ['period' => '1Y']))->toBe(0.0); +}); + +test('get selected addons for cart returns prepared addon items', function (): void { + $parentProduct = productTestCreateProductEntity(10); + $addon = productTestCreateProductEntity(20)->setStatus('enabled')->setType(Service::CUSTOM)->setIsAddon(true); + + $validator = Mockery::mock(FOSSBilling\Validate::class); + $validator->shouldNotReceive('checkRequiredParamsForArray'); + + $serviceMock = Mockery::mock(Service::class)->makePartial(); + $serviceMock->shouldReceive('getAddonById')->once()->with(20)->andReturn($addon); + $serviceMock->shouldReceive('isRecurrentProductPricing')->once()->with($addon)->andReturn(false); + + $di = container(); + $di['validator'] = $validator; + $serviceMock->setDi($di); + + $result = $serviceMock->getSelectedAddonsForCart($parentProduct, [ + 20 => ['selected' => true], + ]); + + expect($result)->toHaveCount(1); + expect($result[0]['product'])->toBe($addon); + expect($result[0]['config']['parent_id'])->toBe(10); +}); + +test('reduce stock updates doctrine product state', function (): void { + $service = new Service(); + $product = productTestCreateProductEntity(1) + ->setStockControl(true) + ->setQuantityInStock(5); + + $di = container(); + $di['em'] = productTestCreateEntityManagerWithRepositories(); + $service->setDi($di); + + $result = $service->reduceStock($product, 2); + + expect($result)->toBeTrue(); + expect($product->getQuantityInStock())->toBe(3); +}); + +test('is stock available uses doctrine product state', function (): void { + $service = new Service(); + $product = productTestCreateProductEntity(1) + ->setStockControl(true) + ->setQuantityInStock(1); + + $di = container(); + $di['em'] = productTestCreateEntityManagerWithRepositories(); + $service->setDi($di); + + expect($service->isStockAvailable($product, 2))->toBeFalse(); +}); + +test('get product pricing array uses product payment implementation', function (): void { + $service = new Service(); + $product = productTestCreateProductEntity(1) + ->setType(Service::CUSTOM) + ->setProductPaymentId(15); + + $productPayment = productTestCreateProductPaymentEntity(15) + ->setType(ProductPayment::ONCE) + ->setOncePrice(20.0) + ->setOnceSetupPrice(5.0); + + $paymentRepo = Mockery::mock(ProductPaymentRepository::class); + $paymentRepo->shouldReceive('find')->once()->with(15)->andReturn($productPayment); + + $di = container(); + $di['em'] = productTestCreateProductPaymentEntityManager($paymentRepo); + $service->setDi($di); + + $pricing = $service->getProductPricingArray($product); + + expect($pricing['type'])->toBe(ProductPayment::ONCE); + expect($pricing[ProductPayment::ONCE]['price'])->toBe(20.0); + expect($pricing[ProductPayment::ONCE]['setup'])->toBe(5.0); +}); + +test('get product unit returns configured unit for non domain products', function (): void { + $service = new Service(); + $product = productTestCreateProductEntity(1) + ->setType(Service::CUSTOM) + ->setUnit('license'); + + $service->setDi(container()); + + expect($service->getProductUnit($product))->toBe('license'); +}); + +test('get product order line config uses product payment pricing for recurring products', function (): void { + $service = new Service(); + $product = productTestCreateProductEntity(9) + ->setType(Service::CUSTOM) + ->setProductPaymentId(15); + + $productPayment = productTestCreateProductPaymentEntity(15) + ->setType(ProductPayment::RECURRENT) + ->setPeriodPricing('a', 20.0, 5.0, true); + + $paymentRepo = Mockery::mock(ProductPaymentRepository::class); + $paymentRepo->shouldReceive('find')->twice()->with(15)->andReturn($productPayment); + + $di = container(); + $di['em'] = productTestCreateProductPaymentEntityManager($paymentRepo); + $service->setDi($di); + + $line = $service->getProductOrderLineConfig($product, ['period' => '1Y', 'quantity' => 2]); + + expect($line)->toBe(['price' => 20.0, 'quantity' => 2, 'setup_price' => 5.0]); +}); + +test('get product renewal line config uses generic pricing implementation', function (): void { + $service = new Service(); + $product = productTestCreateProductEntity(9) + ->setType(Service::CUSTOM) + ->setProductPaymentId(15); + + $productPayment = productTestCreateProductPaymentEntity(15) + ->setType(ProductPayment::RECURRENT) + ->setPeriodPricing('a', 20.0, 5.0, true); + + $paymentRepo = Mockery::mock(ProductPaymentRepository::class); + $paymentRepo->shouldReceive('find')->twice()->with(15)->andReturn($productPayment); + + $di = container(); + $di['em'] = productTestCreateProductPaymentEntityManager($paymentRepo); + $service->setDi($di); + + $line = $service->getProductRenewalLineConfig($product, ['period' => '1Y', 'quantity' => 2]); + + expect($line)->toBe(['price' => 20.0, 'quantity' => 2, 'setup_price' => 5.0]); +}); + +test('get related product discount uses domain pricing implementation', function (): void { + $service = new Service(); + $tld = new Model_Tld(); + $tld->loadBean(new Tests\Helpers\DummyBean()); + $tld->tld = '.com'; + $tld->price_registration = 13; + $tld->price_renew = 20; + $tld->price_transfer = 15; + + $tldService = productTestCreateDomainTldServiceMock($tld); + + $di = container(); + $di['period'] = $di->protect(fn (string $period): Box_Period => new Box_Period($period)); + $di['mod_service'] = $di->protect(function (string $serviceName, ?string $sub = null) use ($tldService) { + if ($serviceName === 'servicedomain' && $sub === 'Tld') { + return $tldService; + } + + throw new RuntimeException('Unexpected service request'); + }); + $service->setDi($di); + + $product = productTestCreateProductEntity(1)->setType(Service::DOMAIN); + + $discount = $service->getRelatedProductDiscount($product, [[ + 'config' => [ + 'action' => 'register', + 'domain' => [ + 'action' => 'register', + 'register_sld' => 'example', + 'register_tld' => '.com', + ], + 'free_domain' => true, + 'free_domain_periods' => ['2Y'], + 'period' => '2Y', + ], + ]], [ + 'action' => 'register', + 'register_sld' => 'example', + 'register_tld' => '.com', + 'period' => '2Y', + ]); + + expect($discount)->toBe(33.0); +}); + +test('get domain pricing array returns active tlds', function (): void { + $service = new Service(); + $connection = productTestCreateDomainPricingDbalConnection(); + + $di = container(); + $di['dbal'] = $connection; + $service->setDi($di); + + $result = $service->getDomainPricingArray(); + + expect($result)->toHaveKey('.com'); + expect($result)->not->toHaveKey('.net'); + expect($result['.com']['price_registration'])->toEqual(10.0); + expect($result['.com']['registrar']['title'])->toBe('Registrar A'); +}); + +test('get product pricing array uses domain pricing implementation', function (): void { + $service = new Service(); + $connection = productTestCreateDomainPricingDbalConnection(); + + $product = productTestCreateProductEntity(1)->setType(Service::DOMAIN); + + $di = container(); + $di['dbal'] = $connection; + $service->setDi($di); + + $result = $service->getProductPricingArray($product); + + expect($result)->toHaveKey('.com'); + expect($result['.com']['price_registration'])->toEqual(10.0); +}); + +test('get product unit uses domain unit', function (): void { + $service = new Service(); + $product = productTestCreateProductEntity(1)->setType(Service::DOMAIN); + + $service->setDi(container()); + + expect($service->getProductUnit($product))->toBe('year'); +}); + +test('get product order line config uses domain pricing implementation', function (): void { + $service = new Service(); + $tld = new Model_Tld(); + $tld->loadBean(new Tests\Helpers\DummyBean()); + $tld->tld = '.com'; + $tld->price_registration = 13; + $tld->price_renew = 20; + $tld->price_transfer = 15; + + $tldService = productTestCreateDomainTldServiceMock($tld); + + $di = container(); + $di['period'] = $di->protect(fn (string $period): Box_Period => new Box_Period($period)); + $di['mod_service'] = $di->protect(function (string $serviceName, ?string $sub = null) use ($tldService) { + if ($serviceName === 'servicedomain' && $sub === 'Tld') { + return $tldService; + } + + throw new RuntimeException('Unexpected service request'); + }); + $service->setDi($di); + + $product = productTestCreateProductEntity(1)->setType(Service::DOMAIN); + + $line = $service->getProductOrderLineConfig($product, [ + 'action' => 'register', + 'register_tld' => '.com', + 'register_years' => 2, + 'period' => '2Y', + ]); + + expect($line)->toBe(['price' => 33.0, 'quantity' => 1, 'setup_price' => 0.0]); +}); + +test('get product renewal line config uses domain pricing implementation', function (): void { + $service = new Service(); + $tld = new Model_Tld(); + $tld->loadBean(new Tests\Helpers\DummyBean()); + $tld->tld = '.com'; + $tld->price_registration = 13; + $tld->price_renew = 20; + $tld->price_transfer = 15; + + $tldService = productTestCreateDomainTldServiceMock($tld); + + $di = container(); + $di['period'] = $di->protect(fn (string $period): Box_Period => new Box_Period($period)); + $di['mod_service'] = $di->protect(function (string $serviceName, ?string $sub = null) use ($tldService) { + if ($serviceName === 'servicedomain' && $sub === 'Tld') { + return $tldService; + } + + throw new RuntimeException('Unexpected service request'); + }); + $service->setDi($di); + + $product = productTestCreateProductEntity(1)->setType(Service::DOMAIN); + + $line = $service->getProductRenewalLineConfig($product, [ + 'action' => 'register', + 'register_tld' => '.com', + 'register_years' => 2, + 'period' => '2Y', + ]); + + expect($line)->toBe(['price' => 20.0, 'quantity' => 2]); +}); + +test('get orders for product uses product order repository', function (): void { + $service = new Service(); + $connection = productTestCreateProductOrderDbalConnection(); + + $di = container(); + $di['dbal'] = $connection; + $service->setDi($di); + + $product = productTestCreateProductEntity(7); + $rows = $service->getOrdersForProduct($product); + + expect($rows)->toHaveCount(1); + expect((int) $rows[0]['id'])->toBe(11); + expect((int) $rows[0]['product_id'])->toBe(7); +}); + +test('get payment types', function (): void { $service = new Service(); $expected = [ 'free' => 'Free', - 'once' => 'One Time', + 'once' => 'One time', 'recurrent' => 'Recurrent', ]; $result = $service->getPaymentTypes(); expect($result)->toBeArray(); - expect($result)->toBe($expected); + expect($result)->toEqual($expected); }); -test('creates a product', function (): void { +test('create product', function (): void { $service = new Service(); - $systemServiceMock = Mockery::mock(Box\Mod\System\Service::class); - /** @var Mockery\Expectation $expectation0 */ - $expectation0 = $systemServiceMock->shouldReceive('checkLimits'); - - $modelPayment = new Model_ProductPayment(); - $modelPayment->loadBean(new Tests\Helpers\DummyBean()); - - $modelProduct = new Model_Product(); - $modelProduct->loadBean(new Tests\Helpers\DummyBean()); $newProductId = 1; $dbMock = Mockery::mock('\Box_Database'); - /** @var Mockery\Expectation $expectation1 */ - $expectation1 = $dbMock->shouldReceive('getCell'); - $expectation1->atLeast()->once(); - $expectation1->andReturn(0); - - /** @var Mockery\Expectation $expectation2 */ - $expectation2 = $dbMock->shouldReceive('dispense'); - $expectation2->atLeast()->once(); - $expectation2->andReturnUsing(fn ($type): Model_ProductPayment|\Model_Product => match ($type) { - 'ProductPayment' => $modelPayment, - 'Product' => $modelProduct, - }); - - /** @var Mockery\Expectation $expectation3 */ - $expectation3 = $dbMock->shouldReceive('store'); - $expectation3->atLeast()->once(); - $expectation3->andReturn($newProductId); + $dbMock->shouldReceive('getCell')->atLeast()->once()->andReturn(0); $toolMock = Mockery::mock(FOSSBilling\Tools::class); - /** @var Mockery\Expectation $expectation4 */ - $expectation4 = $toolMock->shouldReceive('slug'); + $toolMock->shouldReceive('slug')->atLeast()->once()->andReturn('title'); + + $productRepo = Mockery::mock(ProductRepository::class); + $productRepo->shouldReceive('findOneBy')->once()->with(['slug' => 'title'])->andReturn(null); $di = container(); - $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $systemServiceMock); $di['db'] = $dbMock; + $di['em'] = productTestCreateEntityManagerWithRepositories($productRepo, null, productTestCreateProductEntity($newProductId), productTestCreateProductPaymentEntity(1)); $di['tools'] = $toolMock; - $di['logger'] = new Tests\Helpers\TestLogger(); + $di['logger'] = new Box_Log(); $service->setDi($di); $result = $service->createProduct('title', 'domain'); expect($result)->toBeInt(); - expect($result)->toBe($newProductId); + expect($result)->toEqual($newProductId); }); -test('throws exception when updating product with missing pricing type', function (): void { +test('update product missing pricing type', function (): void { $serviceMock = Mockery::mock(Service::class)->makePartial(); $typesArr = [ 'free' => 'Free', - 'once' => 'One Time', + 'once' => 'One time', 'recurrent' => 'Recurrent', ]; - /** @var Mockery\Expectation $expectation */ - $expectation = $serviceMock->shouldReceive('getPaymentTypes'); - $expectation->atLeast()->once(); - $expectation->andReturn($typesArr); + $serviceMock->shouldReceive('getPaymentTypes')->atLeast()->once()->andReturn($typesArr); - $data = ['pricing' => []]; + $data = [ + 'pricing' => [], + ]; - $modelProduct = new Model_Product(); - $modelProduct->loadBean(new Tests\Helpers\DummyBean()); + $modelProduct = productTestCreateProductEntity(1); expect(fn () => $serviceMock->updateProduct($modelProduct, $data)) ->toThrow(FOSSBilling\Exception::class, 'Pricing type is required'); }); -test('updates a product', function (): void { - $modelProduct = new Model_Product(); - $modelProduct->loadBean(new Tests\Helpers\DummyBean()); +test('update product', function (): void { + $modelProduct = productTestCreateProductEntity(1); $serviceMock = Mockery::mock(Service::class)->makePartial(); $typesArr = [ 'free' => 'Free', - 'once' => 'One Time', + 'once' => 'One time', 'recurrent' => 'Recurrent', ]; - /** @var Mockery\Expectation $expectation1 */ - $expectation1 = $serviceMock->shouldReceive('getPaymentTypes'); - $expectation1->atLeast()->once(); - $expectation1->andReturn($typesArr); + $serviceMock->shouldReceive('getPaymentTypes')->atLeast()->once()->andReturn($typesArr); $data = [ 'pricing' => [ - 'type' => Model_ProductPayment::RECURRENT, - Model_ProductPayment::RECURRENT => [ + 'type' => ProductPayment::RECURRENT, + ProductPayment::RECURRENT => [ [ '1W' => [ 'setup' => '', @@ -372,23 +767,16 @@ test('updates a product', function (): void { 'plugin' => 'plug in', ]; - $modelProductPayment = new Model_ProductPayment(); - $modelProductPayment->loadBean(new Tests\Helpers\DummyBean()); + $modelProduct->setProductPaymentId(1); - $dbMock = Mockery::mock('\Box_Database'); - /** @var Mockery\Expectation $expectation2 */ - $expectation2 = $dbMock->shouldReceive('getExistingModelById'); - $expectation2->atLeast()->once(); - $expectation2->andReturn($modelProductPayment); + $productPayment = productTestCreateProductPaymentEntity(1); - /** @var Mockery\Expectation $expectation3 */ - $expectation3 = $dbMock->shouldReceive('store'); - $expectation3->atLeast()->once(); - $expectation3->andReturn(1); + $paymentRepo = Mockery::mock(ProductPaymentRepository::class); + $paymentRepo->shouldReceive('find')->once()->with($productPayment->getId())->andReturn($productPayment); $di = container(); - $di['db'] = $dbMock; - $di['logger'] = new Tests\Helpers\TestLogger(); + $di['em'] = productTestCreateProductPaymentEntityManager($paymentRepo); + $di['logger'] = new Box_Log(); $serviceMock->setDi($di); @@ -396,7 +784,7 @@ test('updates a product', function (): void { expect($result)->toBeTrue(); }); -test('updates priority', function (): void { +test('update priority', function (): void { $service = new Service(); $data = [ 'priority' => [ @@ -405,21 +793,20 @@ test('updates priority', function (): void { ], ]; - $modelProduct = new Model_Product(); - $modelProduct->loadBean(new Tests\Helpers\DummyBean()); + $productA = productTestCreateProductEntity(1); + $productB = productTestCreateProductEntity(5); - $dbMock = Mockery::mock('\Box_Database'); - /** @var Mockery\Expectation $expectation1 */ - $expectation1 = $dbMock->shouldReceive('load'); - $expectation1->atLeast()->once(); - $expectation1->andReturn($modelProduct); - - /** @var Mockery\Expectation $expectation2 */ - $expectation2 = $dbMock->shouldReceive('store'); + $productRepo = Mockery::mock(ProductRepository::class); + $productRepo->shouldReceive('find')->twice()->andReturnUsing(function ($id) use ($productA, $productB) { + return match ($id) { + 1 => $productA, + 5 => $productB, + }; + }); $di = container(); - $di['db'] = $dbMock; - $di['logger'] = new Tests\Helpers\TestLogger(); + $di['em'] = productTestCreateEntityManagerWithRepositories($productRepo); + $di['logger'] = new Box_Log(); $service->setDi($di); @@ -427,11 +814,9 @@ test('updates priority', function (): void { expect($result)->toBeTrue(); }); -test('updates config', function (): void { +test('update config', function (): void { $service = new Service(); - $modelProduct = new Model_Product(); - $modelProduct->loadBean(new Tests\Helpers\DummyBean()); - $modelProduct->config = '{"settings":5,"max":"10"}'; + $modelProduct = productTestCreateProductEntity(1)->setConfig('{"settings":5,"max":"10"}'); $data = [ 'config' => [ @@ -442,14 +827,9 @@ test('updates config', function (): void { 'new_config_value' => 'newValue', ]; - $dbMock = Mockery::mock('\Box_Database'); - /** @var Mockery\Expectation $expectation */ - $expectation = $dbMock->shouldReceive('store'); - $expectation->atLeast()->once(); - $di = container(); - $di['db'] = $dbMock; - $di['logger'] = new Tests\Helpers\TestLogger(); + $di['em'] = productTestCreateEntityManagerWithRepositories(); + $di['logger'] = new Box_Log(); $service->setDi($di); @@ -457,7 +837,7 @@ test('updates config', function (): void { expect($result)->toBeTrue(); }); -test('gets addons', function (): void { +test('get addons', function (): void { $service = new Service(); $addonsRows = [ [ @@ -471,124 +851,85 @@ test('gets addons', function (): void { ]; $dbMock = Mockery::mock('\Box_Database'); - /** @var Mockery\Expectation $expectation */ - $expectation = $dbMock->shouldReceive('getAll'); - $expectation->atLeast()->once(); - $expectation->andReturn($addonsRows); + $dbMock->shouldReceive('getAll')->atLeast()->once()->andReturn($addonsRows); $di = container(); $di['db'] = $dbMock; - $di['logger'] = new Tests\Helpers\TestLogger(); + $di['logger'] = new Box_Log(); $service->setDi($di); $result = $service->getAddons(); expect($result)->toBeArray(); - expect($result)->toBe($expected); + expect($result)->toEqual($expected); }); -test('creates an addon', function (): void { +test('create addon', function (): void { $service = new Service(); $newProductId = 1; - $modelPayment = new Model_ProductPayment(); - $modelPayment->loadBean(new Tests\Helpers\DummyBean()); - - $modelProduct = new Model_Product(); - $modelProduct->loadBean(new Tests\Helpers\DummyBean()); - - $dbMock = Mockery::mock('\Box_Database'); - /** @var Mockery\Expectation $expectation1 */ - $expectation1 = $dbMock->shouldReceive('store'); - $expectation1->atLeast()->once(); - $expectation1->andReturn($newProductId); - - /** @var Mockery\Expectation $expectation2 */ - $expectation2 = $dbMock->shouldReceive('dispense'); - $expectation2->atLeast()->once(); - $expectation2->andReturnUsing(fn ($type): Model_ProductPayment|\Model_Product => match ($type) { - 'ProductPayment' => $modelPayment, - 'Product' => $modelProduct, - }); + $dbMock = Mockery::mock('\Box_Database')->shouldIgnoreMissing(); $toolMock = Mockery::mock(FOSSBilling\Tools::class); - /** @var Mockery\Expectation $expectation3 */ - $expectation3 = $toolMock->shouldReceive('slug'); - $expectation3->atLeast()->once(); + $toolMock->shouldReceive('slug')->atLeast()->once()->andReturn('title'); + + $productRepo = Mockery::mock(ProductRepository::class); + $productRepo->shouldReceive('findOneBy')->once()->with(['slug' => 'title'])->andReturn(null); $di = container(); $di['db'] = $dbMock; - $di['logger'] = new Tests\Helpers\TestLogger(); + $di['em'] = productTestCreateEntityManagerWithRepositories($productRepo, null, productTestCreateProductEntity($newProductId), productTestCreateProductPaymentEntity(1)); + $di['logger'] = new Box_Log(); $di['tools'] = $toolMock; $service->setDi($di); $result = $service->createAddon('title'); expect($result)->toBeInt(); - expect($result)->toBe($newProductId); + expect($result)->toEqual($newProductId); }); -test('throws exception when deleting product with active orders', function (): void { +test('delete product active order exception', function (): void { $service = new Service(); - $model = new Model_Product(); + $model = productTestCreateProductEntity(1); $orderServiceMock = Mockery::mock(Box\Mod\Order\Service::class); - /** @var Mockery\Expectation $expectation */ - $expectation = $orderServiceMock->shouldReceive('productHasOrders'); - $expectation->atLeast()->once(); - $expectation->andReturn(true); + $orderServiceMock->shouldReceive('productHasOrders')->atLeast()->once()->andReturn(true); $di = container(); $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock); $service->setDi($di); - expect(fn (): bool => $service->deleteProduct($model)) + expect(fn () => $service->deleteProduct($model)) ->toThrow(FOSSBilling\Exception::class, 'Cannot remove product which has active orders.'); }); -test('gets product category pairs', function (): void { +test('get product category pairs', function (): void { $service = new Service(); - $execArray = [ - [ - 'id' => 1, - 'title' => 'title4test', - ], - ]; - $expectArray = [ '1' => 'title4test', ]; - $dbMock = Mockery::mock('\Box_Database'); - /** @var Mockery\Expectation $expectation */ - $expectation = $dbMock->shouldReceive('getAll'); - $expectation->atLeast()->once(); - $expectation->andReturn($execArray); + $categoryRepo = Mockery::mock(ProductCategoryRepository::class); + $categoryRepo->shouldReceive('getPairs')->once()->andReturn($expectArray); $di = container(); - $di['db'] = $dbMock; + $di['em'] = productTestCreateEntityManagerWithRepositories(null, null, null, null, $categoryRepo); $service->setDi($di); $result = $service->getProductCategoryPairs(); expect($result)->toBeArray(); - expect($result)->toBe($expectArray); + expect($result)->toEqual($expectArray); }); -test('updates a category', function (): void { +test('update category', function (): void { $service = new Service(); - $model = new Model_ProductCategory(); - $model->loadBean(new Tests\Helpers\DummyBean()); - - $dbMock = Mockery::mock('\Box_Database'); - /** @var Mockery\Expectation $expectation */ - $expectation = $dbMock->shouldReceive('store'); - $expectation->atLeast()->once(); - $expectation->andReturn(1); + $model = productTestCreateProductCategoryEntity(1); $di = container(); - $di['db'] = $dbMock; - $di['logger'] = new Tests\Helpers\TestLogger(); + $di['em'] = productTestCreateEntityManagerWithRepositories(); + $di['logger'] = new Box_Log(); $service->setDi($di); @@ -597,81 +938,46 @@ test('updates a category', function (): void { expect($result)->toBeTrue(); }); -test('creates a category', function (): void { +test('create category', function (): void { $service = new Service(); $newCategoryId = 1; - $systemServiceMock = Mockery::mock(Box\Mod\System\Service::class); - /** @var Mockery\Expectation $expectation0 */ - $expectation0 = $systemServiceMock->shouldReceive('checkLimits'); - - $model = new Model_ProductCategory(); - $model->loadBean(new Tests\Helpers\DummyBean()); - - $dbMock = Mockery::mock('\Box_Database'); - /** @var Mockery\Expectation $expectation1 */ - $expectation1 = $dbMock->shouldReceive('dispense'); - $expectation1->atLeast()->once(); - $expectation1->andReturn($model); - - /** @var Mockery\Expectation $expectation2 */ - $expectation2 = $dbMock->shouldReceive('store'); - $expectation2->atLeast()->once(); - $expectation2->andReturn($newCategoryId); - $di = container(); - $di['db'] = $dbMock; - $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $systemServiceMock); - $di['logger'] = new Tests\Helpers\TestLogger(); + $di['em'] = productTestCreateEntityManagerWithRepositories(null, null, null, null, null, productTestCreateProductCategoryEntity($newCategoryId)); + $di['logger'] = new Box_Log(); $service->setDi($di); $result = $service->createCategory('title'); + expect($result)->toBeInt(); - expect($result)->toBe($newCategoryId); + expect($result)->toEqual($newCategoryId); }); -test('throws exception when removing category with products', function (): void { +test('remove product category category has products exception', function (): void { $service = new Service(); - $modelProductCategory = new Model_ProductCategory(); - $modelProductCategory->loadBean(new Tests\Helpers\DummyBean()); - - $modelProduct = new Model_Product(); - $modelProduct->loadBean(new Tests\Helpers\DummyBean()); - - $dbMock = Mockery::mock('\Box_Database'); - /** @var Mockery\Expectation $expectation */ - $expectation = $dbMock->shouldReceive('findOne'); - $expectation->atLeast()->once(); - $expectation->andReturn($modelProduct); + $modelProductCategory = productTestCreateProductCategoryEntity(1); + $productRepository = Mockery::mock(ProductRepository::class); + $productRepository->shouldReceive('hasProductsInCategory')->once()->with((int) $modelProductCategory->getId())->andReturn(true); $di = container(); - $di['db'] = $dbMock; + $di['em'] = productTestCreateEntityManagerWithRepositories($productRepository); $service->setDi($di); - expect(fn (): bool => $service->removeProductCategory($modelProductCategory)) + expect(fn () => $service->removeProductCategory($modelProductCategory)) ->toThrow(FOSSBilling\Exception::class, 'Cannot remove product category with products'); }); -test('removes a product category', function (): void { +test('remove product category', function (): void { $service = new Service(); - $modelProductCategory = new Model_ProductCategory(); - $modelProductCategory->loadBean(new Tests\Helpers\DummyBean()); - - $dbMock = Mockery::mock('\Box_Database'); - /** @var Mockery\Expectation $expectation1 */ - $expectation1 = $dbMock->shouldReceive('findOne'); - $expectation1->atLeast()->once(); - $expectation1->andReturn(null); - - /** @var Mockery\Expectation $expectation2 */ - $expectation2 = $dbMock->shouldReceive('trash'); - $expectation2->atLeast()->once(); + $modelProductCategory = productTestCreateProductCategoryEntity(1); + $productRepository = Mockery::mock(ProductRepository::class); + $productRepository->shouldReceive('hasProductsInCategory')->once()->with((int) $modelProductCategory->getId())->andReturn(false); $di = container(); - $di['db'] = $dbMock; - $di['logger'] = new Tests\Helpers\TestLogger(); + $di['em'] = productTestCreateEntityManagerWithRepositories($productRepository); + $di['logger'] = new Box_Log(); $service->setDi($di); @@ -680,77 +986,70 @@ test('removes a product category', function (): void { expect($result)->toBeTrue(); }); -test('gets promo search query', function (): void { +test('create promo', function (): void { $service = new Service(); - $data = [ - 'search' => 'keyword', - 'id' => 1, - 'status' => 'active', - ]; + + $promoRepo = Mockery::mock(PromoRepository::class); + $promoRepo->shouldReceive('findOneBy')->once()->with(['code' => 'code'])->andReturn(null); + + $emMock = new class($promoRepo) { + public function __construct(private object $promoRepo) + { + } + + public function getRepository(string $class): object + { + return $this->promoRepo; + } + + public function persist(object $entity): void + { + $reflection = new ReflectionProperty($entity, 'id'); + $reflection->setAccessible(true); + $reflection->setValue($entity, 1); + } + + public function flush(): void + { + } + }; $di = container(); - $service->setDi($di); - - [$sql, $params] = $service->getPromoSearchQuery($data); - - expect($sql)->toBeString(); - expect($params)->toBeArray(); -}); - -test('creates a promo', function (): void { - $service = new Service(); - $systemServiceMock = Mockery::mock(Box\Mod\System\Service::class); - /** @var Mockery\Expectation $expectation0 */ - $expectation0 = $systemServiceMock->shouldReceive('checkLimits'); - - $model = new Model_Promo(); - $model->loadBean(new Tests\Helpers\DummyBean()); - - $newPromoId = 1; - - $dbMock = Mockery::mock('\Box_Database'); - /** @var Mockery\Expectation $expectation1 */ - $expectation1 = $dbMock->shouldReceive('findOne'); - $expectation1->atLeast()->once(); - $expectation1->andReturn(null); - - /** @var Mockery\Expectation $expectation2 */ - $expectation2 = $dbMock->shouldReceive('dispense'); - $expectation2->atLeast()->once(); - $expectation2->andReturn($model); - - /** @var Mockery\Expectation $expectation3 */ - $expectation3 = $dbMock->shouldReceive('store'); - $expectation3->atLeast()->once(); - $expectation3->andReturn($newPromoId); - - $di = container(); - $di['db'] = $dbMock; - $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $systemServiceMock); - $di['logger'] = new Tests\Helpers\TestLogger(); + $di['logger'] = new Box_Log(); + $di['em'] = $emMock; $service->setDi($di); $result = $service->createPromo('code', 'percentage', 50, [], [], [], []); expect($result)->toBeInt(); - expect($result)->toBe($newPromoId); + expect($result)->toEqual(1); }); -test('converts promo to api array', function (): void { +test('to promo api array', function (): void { $service = new Service(); - $model = new Model_Promo(); - $model->loadBean(new Tests\Helpers\DummyBean()); - $model->products = '{}'; - $model->periods = '{}'; + $model = productTestCreatePromoEntity(1) + ->setProducts('{}') + ->setPeriods('{}'); - $dbMock = Mockery::mock('\Box_Database'); - /** @var Mockery\Expectation $expectation */ - $expectation = $dbMock->shouldReceive('toArray'); - $expectation->atLeast()->once(); - $expectation->andReturn([]); + $repoMock = Mockery::mock(PromoRedemptionRepository::class); + $repoMock->shouldReceive('countByPromoId')->once()->with(1)->andReturn(0); + + $promoRepo = Mockery::mock(PromoRepository::class); + $promoRepo->shouldReceive('countLinkedOrdersByPromoId')->once()->with(1)->andReturn(0); + + $emMock = new class($promoRepo, $repoMock) { + public function __construct(private object $promoRepo, private object $redemptionRepo) + { + } + + public function getRepository(string $class): object + { + return $class === Promo::class ? $this->promoRepo : $this->redemptionRepo; + } + }; $di = container(); - $di['db'] = $dbMock; - $di['tools'] = Mockery::mock(FOSSBilling\Tools::class); + $di['tools'] = Mockery::mock(FOSSBilling\Tools::class)->shouldIgnoreMissing(); + $di['em'] = $emMock; $service->setDi($di); @@ -758,11 +1057,577 @@ test('converts promo to api array', function (): void { expect($result)->toBeArray(); }); -test('updates a promo', function (): void { +test('to promo api array includes usage stats for deep requests', function (): void { $service = new Service(); - $model = new Model_Promo(); - $model->loadBean(new Tests\Helpers\DummyBean()); + $model = productTestCreatePromoEntity(1) + ->setUsed(5) + ->setMaxUses(10) + ->setProducts('{}') + ->setPeriods('{}'); + $repoMock = Mockery::mock(PromoRedemptionRepository::class); + $repoMock->shouldReceive('getUsageStatsByPromoId')->once()->with(1)->andReturn([ + 'recorded_applications' => 7, + 'checkout_applications' => 5, + 'renewal_applications' => 2, + 'active_checkout_applications' => 4, + 'reserved_applications' => 1, + 'committed_applications' => 5, + 'released_applications' => 1, + 'distinct_clients' => 3, + 'orders_using_promo' => 4, + ]); + + $promoRepo = Mockery::mock(PromoRepository::class); + $promoRepo->shouldNotReceive('countLinkedOrdersByPromoId'); + + $emMock = new class($promoRepo, $repoMock) { + public function __construct(private object $promoRepo, private object $redemptionRepo) + { + } + + public function getRepository(string $class): object + { + return $class === Promo::class ? $this->promoRepo : $this->redemptionRepo; + } + }; + + $di = container(); + $di['tools'] = Mockery::mock(FOSSBilling\Tools::class)->shouldIgnoreMissing(); + $di['em'] = $emMock; + + $service->setDi($di); + + $result = $service->toPromoApiArray($model, true); + expect($result['redemption_count'])->toBe(7); + expect($result['usage_stats']['operational_use_count'])->toBe(5); + expect($result['usage_stats']['max_uses'])->toBe(10); + expect($result['usage_stats']['remaining_operational_uses'])->toBe(5); + expect($result['usage_stats']['checkout_applications'])->toBe(5); + expect($result['usage_stats']['renewal_applications'])->toBe(2); + expect($result['usage_stats']['active_checkout_applications'])->toBe(4); + expect($result['usage_stats']['reserved_applications'])->toBe(1); + expect($result['usage_stats']['committed_applications'])->toBe(5); + expect($result['usage_stats']['released_applications'])->toBe(1); + expect($result['usage_stats']['distinct_clients'])->toBe(3); + expect($result['usage_stats']['orders_using_promo'])->toBe(4); +}); + +test('client has active promo application', function (): void { + $service = new Service(); + $promo = productTestCreatePromoEntity(5); + + $client = new Model_Client(); + $client->loadBean(new Tests\Helpers\DummyBean()); + $client->id = 9; + + $repoMock = Mockery::mock(PromoRedemptionRepository::class); + $repoMock->shouldReceive('clientHasActiveCheckoutApplication')->once()->with(5, 9)->andReturn(true); + + $emMock = new class($repoMock) { + public function __construct(private $repo) + { + } + + public function getRepository(string $class): object + { + return $this->repo; + } + }; + + $di = container(); + $di['em'] = $emMock; + + $service->setDi($di); + + expect($service->clientHasActivePromoApplication($client, $promo))->toBeTrue(); +}); + +test('promo can be applied', function (Promo $promo, bool $expectedResult): void { + $service = new Service(); + expect($service->promoCanBeApplied($promo))->toBe($expectedResult); +})->with([ + 'inactive' => [fn () => productTestCreatePromoEntity(1)->setActive(false), false], + 'max uses reached' => [fn () => productTestCreatePromoEntity(2)->setActive(true)->setMaxUses(5)->setUsed(5), false], + 'not yet started' => [fn () => productTestCreatePromoEntity(3)->setActive(true)->setMaxUses(10)->setUsed(5)->setStartAt(new DateTime('tomorrow')), false], + 'already ended' => [fn () => productTestCreatePromoEntity(4)->setActive(true)->setMaxUses(10)->setUsed(5)->setStartAt(new DateTime('yesterday'))->setEndAt(new DateTime('yesterday')), false], + 'within window' => [fn () => productTestCreatePromoEntity(5)->setActive(true)->setMaxUses(10)->setUsed(5)->setStartAt(new DateTime('yesterday'))->setEndAt(new DateTime('tomorrow')), true], +]); + +test('can client use promo returns false when promo cannot be applied', function (): void { + $serviceMock = Mockery::mock(Service::class)->makePartial(); + $serviceMock->shouldReceive('promoCanBeApplied')->once()->andReturn(false); + + $promo = productTestCreatePromoEntity(1); + + $client = new Model_Client(); + $client->loadBean(new Tests\Helpers\DummyBean()); + + expect($serviceMock->canClientUsePromo($client, $promo))->toBeFalse(); +}); + +test('can client use promo returns true when promo is not once per client', function (): void { + $serviceMock = Mockery::mock(Service::class)->makePartial(); + $serviceMock->shouldReceive('promoCanBeApplied')->once()->andReturn(true); + $serviceMock->shouldNotReceive('clientHasActivePromoApplication'); + + $promo = productTestCreatePromoEntity(1) + ->setOncePerClient(false); + + $client = new Model_Client(); + $client->loadBean(new Tests\Helpers\DummyBean()); + + expect($serviceMock->canClientUsePromo($client, $promo))->toBeTrue(); +}); + +test('can client use promo returns false when client already has active promo application', function (): void { + $serviceMock = Mockery::mock(Service::class)->makePartial(); + $serviceMock->shouldReceive('promoCanBeApplied')->once()->andReturn(true); + + $promo = productTestCreatePromoEntity(1) + ->setOncePerClient(true); + + $client = new Model_Client(); + $client->loadBean(new Tests\Helpers\DummyBean()); + + $serviceMock->shouldReceive('clientHasActivePromoApplication')->once()->with($client, $promo)->andReturn(true); + + expect($serviceMock->canClientUsePromo($client, $promo))->toBeFalse(); +}); + +test('use promo', function (): void { + $service = new Service(); + $promo = productTestCreatePromoEntity(12); + + $promoRepo = Mockery::mock(PromoRepository::class); + $promoRepo->shouldReceive('incrementUsageIfAvailable')->once()->with(12, Mockery::type(DateTimeInterface::class))->andReturn(1); + + $emMock = new class($promoRepo) { + public function __construct(private object $promoRepo) + { + } + + public function getRepository(string $class): object + { + return $this->promoRepo; + } + }; + + $di = container(); + $di['em'] = $emMock; + $service->setDi($di); + + $service->usePromo($promo); + expect(true)->toBeTrue(); +}); + +test('use promo limit reached', function (): void { + $service = new Service(); + $promo = productTestCreatePromoEntity(12); + + $promoRepo = Mockery::mock(PromoRepository::class); + $promoRepo->shouldReceive('incrementUsageIfAvailable')->once()->andReturn(0); + + $emMock = new class($promoRepo) { + public function __construct(private object $promoRepo) + { + } + + public function getRepository(string $class): object + { + return $this->promoRepo; + } + }; + + $di = container(); + $di['em'] = $emMock; + $service->setDi($di); + + expect(fn () => $service->usePromo($promo)) + ->toThrow(FOSSBilling\InformationException::class, 'This promo code has reached its maximum number of uses.'); +}); + +test('reserve promo for order', function (): void { + $service = new Service(); + $promo = productTestCreatePromoEntity(1) + ->setRecurring(true); + + $order = new Model_ClientOrder(); + $order->loadBean(new Tests\Helpers\DummyBean()); + + $dbMock = Mockery::mock('\Box_Database'); + $dbMock->shouldReceive('store')->once()->with($order); + + $serviceMock = Mockery::mock(Service::class)->makePartial(); + $serviceMock->shouldReceive('usePromo')->once()->with($promo); + + $di = container(); + $di['db'] = $dbMock; + $serviceMock->setDi($di); + + $serviceMock->reservePromoForOrder($promo, $order); + + expect($order->promo_recurring)->toBe(1); + expect($order->promo_used)->toBe(1); +}); + +test('create checkout promo redemptions persists each order and flushes once', function (): void { + $service = new Service(); + $promo = productTestCreatePromoEntity(4); + + $client = new Model_Client(); + $client->loadBean(new Tests\Helpers\DummyBean()); + $client->id = 8; + + $invoice = new Model_Invoice(); + $invoice->loadBean(new Tests\Helpers\DummyBean()); + $invoice->id = 16; + + $firstOrder = new Model_ClientOrder(); + $firstOrder->loadBean(new Tests\Helpers\DummyBean()); + $firstOrder->id = 11; + $firstOrder->discount = 5.0; + $firstOrder->currency = 'USD'; + $firstOrder->created_at = '2026-01-01 12:00:00'; + + $secondOrder = new Model_ClientOrder(); + $secondOrder->loadBean(new Tests\Helpers\DummyBean()); + $secondOrder->id = 12; + $secondOrder->discount = 7.0; + $secondOrder->currency = 'USD'; + $secondOrder->created_at = '2026-01-01 12:05:00'; + + $emMock = new class { + public array $persisted = []; + public int $flushCalls = 0; + + public function persist(object $entity): void + { + $this->persisted[] = $entity; + } + + public function flush(): void + { + ++$this->flushCalls; + } + }; + + $di = container(); + $di['em'] = $emMock; + + $service->setDi($di); + $service->createCheckoutPromoRedemptions( + $promo, + $client, + [$firstOrder, $secondOrder], + $invoice, + PromoRedemption::STATUS_RESERVED, + ); + + expect($emMock->persisted)->toHaveCount(2); + expect($emMock->flushCalls)->toBe(1); + expect($emMock->persisted[0]->getClientOrderId())->toBe(11); + expect($emMock->persisted[1]->getClientOrderId())->toBe(12); +}); + +test('find active promo by code', function (): void { + $service = new Service(); + $promoEntity = new Promo(); + $promoEntity->setCode('CODE'); + $reflection = new ReflectionProperty($promoEntity, 'id'); + $reflection->setAccessible(true); + $reflection->setValue($promoEntity, 14); + + $promoRepo = Mockery::mock(PromoRepository::class); + $promoRepo->shouldReceive('findActiveByCode')->once()->with('CODE')->andReturn($promoEntity); + + $emMock = new class($promoRepo) { + public function __construct(private object $promoRepo) + { + } + + public function getRepository(string $class): object + { + return $this->promoRepo; + } + }; + + $di = container(); + $di['em'] = $emMock; + $service->setDi($di); + + expect($service->findActivePromoByCode('CODE'))->toBe($promoEntity); +}); + +test('get promo discount title', function (): void { + $service = new Service(); + $promo = productTestCreatePromoEntity(1) + ->setCode('PROMO') + ->setType(Promo::ABSOLUTE) + ->setValue(5.0); + + $apiGuest = new class { + public function currency_format(array $data): string + { + return $data['code'] . ' ' . $data['price']; + } + }; + + $di = container(); + $di['api_guest'] = $apiGuest; + $service->setDi($di); + + expect($service->getPromoDiscountTitle($promo, 'USD')) + ->toBe('Promotional Code: PROMO - USD 5 Discount'); +}); + +test('get renewal promo adjustment for domain order', function (): void { + $service = new Service(); + $order = new Model_ClientOrder(); + $order->loadBean(new Tests\Helpers\DummyBean()); + $order->promo_id = 15; + $order->promo_recurring = true; + $order->product_id = 17; + $order->discount = 2.0; + $order->currency = 'EUR'; + $order->config = json_encode(['period' => '1Y']); + + $product = productTestCreateProductEntity(17)->setType(Service::DOMAIN); + + $dbMock = Mockery::mock('\Box_Database')->shouldIgnoreMissing(); + + $promoEntity = productTestCreatePromoEntity(15) + ->setCode('PROMO') + ->setType(Promo::ABSOLUTE) + ->setValue(5.0); + + $promoRepo = Mockery::mock(PromoRepository::class); + $promoRepo->shouldReceive('find')->once()->with(15)->andReturn($promoEntity); + + $currencyRepository = Mockery::mock(Box\Mod\Currency\Repository\CurrencyRepository::class); + $currencyRepository->shouldReceive('getRateByCode')->once()->with('EUR')->andReturn(2.0); + + $currencyService = Mockery::mock(Box\Mod\Currency\Service::class); + $currencyService->shouldReceive('getCurrencyRepository')->once()->andReturn($currencyRepository); + + $apiGuest = new class { + public function currency_format(array $data): string + { + return $data['code'] . ' ' . $data['price']; + } + }; + + $serviceMock = Mockery::mock(Service::class)->makePartial(); + $serviceMock->shouldReceive('findProductById')->once()->with((int) $order->product_id)->andReturn($product); + $serviceMock->shouldReceive('getRenewalProductDiscount')->once()->with($product, $promoEntity, ['period' => '1Y'])->andReturn(5.0); + + $di = container(); + $di['db'] = $dbMock; + $di['api_guest'] = $apiGuest; + $di['em'] = new class($promoRepo) { + public function __construct(private object $promoRepo) + { + } + + public function getRepository(string $class): object + { + return match ($class) { + Promo::class => $this->promoRepo, + default => throw new RuntimeException('Unexpected repository ' . $class), + }; + } + }; + $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $currencyService); + $serviceMock->setDi($di); + + $result = $serviceMock->getRenewalPromoAdjustment($order, 20.0, 1.0); + + expect($result['promo'])->toBe($promoEntity); + expect($result['discount_amount'])->toBe(10.0); + expect($result['title'])->toBe('Promotional Code: PROMO - EUR 5 Discount'); + expect($result['currency'])->toBe('EUR'); +}); + +test('get product discount uses product order line config', function (): void { + $service = new Service(); + $promo = new Promo(); + $promo->setType(Promo::PERCENTAGE); + $promo->setValue(10); + + $product = productTestCreateProductEntity(5)->setIsAddon(false); + + $serviceMock = Mockery::mock(Service::class)->makePartial(); + $serviceMock->shouldReceive('getProductOrderLineConfig')->once()->with($product, ['period' => '1Y'])->andReturn([ + 'price' => 100.0, + 'quantity' => 2, + ]); + + expect($serviceMock->getProductDiscount($product, $promo, ['period' => '1Y']))->toBe(20.0); +}); + +test('get renewal product discount uses product renewal line config', function (): void { + $service = new Service(); + $promo = new Promo(); + $promo->setType(Promo::PERCENTAGE); + $promo->setValue(25); + + $product = productTestCreateProductEntity(5)->setIsAddon(false); + + $serviceMock = Mockery::mock(Service::class)->makePartial(); + $serviceMock->shouldReceive('getProductRenewalLineConfig')->once()->with($product, ['period' => '1Y'])->andReturn([ + 'price' => 40.0, + 'quantity' => 2, + ]); + + expect($serviceMock->getRenewalProductDiscount($product, $promo, ['period' => '1Y']))->toBe(20.0); +}); + +test('is promo available for client group', function (Promo $promo, ?Model_Client $client, bool $expectedResult): void { + $service = new Service(); + $di = container(); + $di['loggedin_client'] = $client; + $service->setDi($di); + + expect($service->isPromoAvailableForClientGroup($promo))->toBe($expectedResult); +})->with([ + 'no restrictions' => [fn () => productTestCreatePromoEntity(1)->setClientGroups(json_encode([])), fn () => $client = new Model_Client(), true], + 'restricted and no client group' => [fn () => productTestCreatePromoEntity(2)->setClientGroups(json_encode([1, 2])), function () { + $client = new Model_Client(); + $client->loadBean(new Tests\Helpers\DummyBean()); + $client->client_group_id = null; + + return $client; + }, false], + 'restricted and wrong client group' => [fn () => productTestCreatePromoEntity(3)->setClientGroups(json_encode([1, 2])), function () { + $client = new Model_Client(); + $client->loadBean(new Tests\Helpers\DummyBean()); + $client->client_group_id = 3; + + return $client; + }, false], + 'restricted and matching client group' => [fn () => productTestCreatePromoEntity(4)->setClientGroups(json_encode([1, 2])), function () { + $client = new Model_Client(); + $client->loadBean(new Tests\Helpers\DummyBean()); + $client->client_group_id = 2; + + return $client; + }, true], + 'no restrictions and no client' => [fn () => productTestCreatePromoEntity(5)->setClientGroups(json_encode([])), null, true], + 'restricted and no client' => [fn () => productTestCreatePromoEntity(6)->setClientGroups(json_encode([1, 2])), null, false], +]); + +test('release reserved promo redemptions for invoice releases reservations and decrements operational counter', function (): void { + $service = new Service(); + $invoice = new Model_Invoice(); + $invoice->loadBean(new Tests\Helpers\DummyBean()); + $invoice->id = 11; + + $checkoutRedemption = (new PromoRedemption()) + ->setPromoId(7) + ->setPhase(PromoRedemption::PHASE_CHECKOUT) + ->setStatus(PromoRedemption::STATUS_RESERVED); + $secondCheckoutRedemption = (new PromoRedemption()) + ->setPromoId(7) + ->setPhase(PromoRedemption::PHASE_CHECKOUT) + ->setStatus(PromoRedemption::STATUS_RESERVED); + $renewalRedemption = (new PromoRedemption()) + ->setPromoId(7) + ->setPhase(PromoRedemption::PHASE_RENEWAL) + ->setStatus(PromoRedemption::STATUS_RESERVED); + + $repoMock = Mockery::mock(PromoRedemptionRepository::class); + $repoMock->shouldReceive('findBy')->once()->with([ + 'invoiceId' => 11, + 'status' => PromoRedemption::STATUS_RESERVED, + ])->andReturn([$checkoutRedemption, $secondCheckoutRedemption, $renewalRedemption]); + + $promoRepo = Mockery::mock(PromoRepository::class); + $promoRepo->shouldReceive('decrementUsage')->once()->with(7, 2, Mockery::type(DateTimeInterface::class)); + + $di = container(); + $di['em'] = new class($promoRepo, $repoMock) { + public int $flushCalls = 0; + + public function __construct(private object $promoRepo, private object $redemptionRepo) + { + } + + public function getRepository(string $class): object + { + return $class === Promo::class ? $this->promoRepo : $this->redemptionRepo; + } + + public function flush(): void + { + ++$this->flushCalls; + } + }; + + $service->setDi($di); + $service->releaseReservedPromoRedemptionsForInvoice($invoice, 'invoice_deleted'); + + expect($checkoutRedemption->getStatus())->toBe(PromoRedemption::STATUS_RELEASED); + expect($renewalRedemption->getStatus())->toBe(PromoRedemption::STATUS_RELEASED); + expect($checkoutRedemption->getReleaseReason())->toBe('invoice_deleted'); + expect($di['em']->flushCalls)->toBe(1); +}); + +test('compensateCheckoutPromoFailure deletes orphaned redemptions and decrements usage', function (): void { + $service = new Service(); + + $promo = productTestCreatePromoEntity(7)->setCode('COMPENSATE'); + + $redemption = new PromoRedemption(); + $redemption->setPromoId(7); + $redemption->setClientOrderId(42); + $redemption->setStatus(PromoRedemption::STATUS_COMMITTED); + + $redemptionRepo = Mockery::mock(PromoRedemptionRepository::class); + $redemptionRepo->shouldReceive('findBy') + ->once() + ->with(['promoId' => 7, 'clientOrderId' => [42, 43]]) + ->andReturn([$redemption]); + + $promoRepo = Mockery::mock(PromoRepository::class); + $promoRepo->shouldReceive('decrementUsage') + ->once() + ->with(7, 2, Mockery::type(DateTimeInterface::class)); + + $emMock = new class($promoRepo, $redemptionRepo) { + public int $removeCalls = 0; + + public function __construct( + private object $promoRepo, + private object $redemptionRepo, + ) { + } + + public function getRepository(string $class): object + { + return $class === Promo::class ? $this->promoRepo : $this->redemptionRepo; + } + + public function remove(object $entity): void + { + ++$this->removeCalls; + } + + public function flush(): void + { + } + }; + + $di = container(); + $di['em'] = $emMock; + + $service->setDi($di); + $service->compensateCheckoutPromoFailure($promo, [42, 43], 2); + + expect($emMock->removeCalls)->toBe(1); +}); + +test('update promo', function (): void { + $service = new Service(); $data = [ 'code' => 'GO', 'type' => 'absolute', @@ -779,46 +1644,191 @@ test('updates a promo', function (): void { 'periods' => [], ]; - $dbMock = Mockery::mock('\Box_Database'); - /** @var Mockery\Expectation $expectation */ - $expectation = $dbMock->shouldReceive('store'); - $expectation->atLeast()->once(); + $promoEntity = new Promo(); + $promoEntity->setCode('OLD'); + $reflection = new ReflectionProperty($promoEntity, 'id'); + $reflection->setAccessible(true); + $reflection->setValue($promoEntity, 1); + + $promoRepo = Mockery::mock(PromoRepository::class); + $promoRepo->shouldReceive('findOneBy')->once()->with(['code' => 'GO'])->andReturn(null); + + $emMock = new class($promoRepo) { + public function __construct(private object $promoRepo) + { + } + + public function getRepository(string $class): object + { + return $this->promoRepo; + } + + public function flush(): void + { + } + }; $di = container(); - $di['db'] = $dbMock; - $di['logger'] = new Tests\Helpers\TestLogger(); + $di['logger'] = new Box_Log(); + $di['em'] = $emMock; $service->setDi($di); - $result = $service->updatePromo($model, $data); + $result = $service->updatePromo($promoEntity, $data); expect($result)->toBeBool(); expect($result)->toBeTrue(); }); -test('deletes a promo', function (): void { +test('delete promo', function (): void { $service = new Service(); - $model = new Model_Promo(); - $model->loadBean(new Tests\Helpers\DummyBean()); + $promoEntity = productTestCreatePromoEntity(1) + ->setCode('PROMO'); - $dbMock = Mockery::mock('\Box_Database'); - /** @var Mockery\Expectation $expectation1 */ - $expectation1 = $dbMock->shouldReceive('exec'); - $expectation1->atLeast()->once(); + $redemptionRepo = Mockery::mock(PromoRedemptionRepository::class); + $redemptionRepo->shouldReceive('countByPromoId')->once()->with(1)->andReturn(0); - /** @var Mockery\Expectation $expectation2 */ - $expectation2 = $dbMock->shouldReceive('trash'); - $expectation2->atLeast()->once(); + $promoRepo = Mockery::mock(PromoRepository::class); + $promoRepo->shouldReceive('countLinkedOrdersByPromoId')->once()->with(1)->andReturn(0); + + $emMock = new class($promoRepo, $redemptionRepo) { + public function __construct(private object $promoRepo, private object $redemptionRepo) + { + } + + public function getRepository(string $class): object + { + return $class === Promo::class ? $this->promoRepo : $this->redemptionRepo; + } + + public function remove(object $entity): void + { + assert($entity instanceof Promo); + } + + public function flush(): void + { + } + }; $di = container(); - $di['db'] = $dbMock; - $di['logger'] = new Tests\Helpers\TestLogger(); + $di['db'] = Mockery::mock('\Box_Database')->shouldIgnoreMissing(); + $di['logger'] = new Box_Log(); + $di['em'] = $emMock; $service->setDi($di); - $result = $service->deletePromo($model); + $result = $service->deletePromo($promoEntity); expect($result)->toBeBool(); expect($result)->toBeTrue(); }); -test('gets product search query', function (): void { +test('delete promo blocks deletion when redemption history exists', function (): void { + $service = new Service(); + $promoEntity = productTestCreatePromoEntity(1); + + $redemptionRepo = Mockery::mock(PromoRedemptionRepository::class); + $redemptionRepo->shouldReceive('countByPromoId')->once()->with(1)->andReturn(1); + + $promoRepo = Mockery::mock(PromoRepository::class); + $promoRepo->shouldNotReceive('countLinkedOrdersByPromoId'); + + $emMock = new class($promoRepo, $redemptionRepo) { + public function __construct(private object $promoRepo, private object $redemptionRepo) + { + } + + public function getRepository(string $class): object + { + return $class === Promo::class ? $this->promoRepo : $this->redemptionRepo; + } + }; + + $di = container(); + $di['db'] = Mockery::mock('\Box_Database')->shouldIgnoreMissing(); + $di['em'] = $emMock; + + $service->setDi($di); + + expect(fn () => $service->deletePromo($promoEntity)) + ->toThrow(FOSSBilling\InformationException::class, 'Promotions with redemption history cannot be deleted. Disable the promotion instead.'); +}); + +test('delete promo blocks deletion when linked orders exist without ledger history', function (): void { + $service = new Service(); + $promoEntity = productTestCreatePromoEntity(1); + + $redemptionRepo = Mockery::mock(PromoRedemptionRepository::class); + $redemptionRepo->shouldReceive('countByPromoId')->once()->with(1)->andReturn(0); + + $promoRepo = Mockery::mock(PromoRepository::class); + $promoRepo->shouldReceive('countLinkedOrdersByPromoId')->once()->with(1)->andReturn(1); + + $emMock = new class($promoRepo, $redemptionRepo) { + public function __construct(private object $promoRepo, private object $redemptionRepo) + { + } + + public function getRepository(string $class): object + { + return $class === Promo::class ? $this->promoRepo : $this->redemptionRepo; + } + }; + + $di = container(); + $di['em'] = $emMock; + + $service->setDi($di); + + expect(fn () => $service->deletePromo($promoEntity)) + ->toThrow(FOSSBilling\InformationException::class, 'Promotions with redemption history cannot be deleted. Disable the promotion instead.'); +}); + +test('is promo linked to tld returns true when promo has no product restrictions', function (): void { + $service = new Service(); + $promo = new Promo(); + + $tld = new Model_Tld(); + $tld->loadBean(new Tests\Helpers\DummyBean()); + $tld->id = 1; + + expect($service->isPromoLinkedToTld($promo, $tld))->toBeTrue(); +}); + +test('is promo linked to tld uses main domain product linkage', function (): void { + $service = new Service(); + $promo = new Promo(); + $promo->setProducts(json_encode([10])); + + $domainProduct = productTestCreateProductEntity(10) + ->setIsAddon(false); + + $tld = new Model_Tld(); + $tld->loadBean(new Tests\Helpers\DummyBean()); + $tld->id = 1; + + $serviceMock = Mockery::mock(Service::class)->makePartial(); + $serviceMock->shouldReceive('getMainDomainProduct')->once()->andReturn($domainProduct); + + expect($serviceMock->isPromoLinkedToTld($promo, $tld))->toBeTrue(); +}); + +test('is promo linked to tld returns false when domain product is not linked', function (): void { + $service = new Service(); + $promo = new Promo(); + $promo->setProducts(json_encode([25])); + + $domainProduct = productTestCreateProductEntity(10) + ->setIsAddon(false); + + $tld = new Model_Tld(); + $tld->loadBean(new Tests\Helpers\DummyBean()); + $tld->id = 1; + + $serviceMock = Mockery::mock(Service::class)->makePartial(); + $serviceMock->shouldReceive('getMainDomainProduct')->once()->andReturn($domainProduct); + + expect($serviceMock->isPromoLinkedToTld($promo, $tld))->toBeFalse(); +}); + +test('get product search query', function (): void { $service = new Service(); $data = [ 'search' => 'keyword', @@ -828,336 +1838,321 @@ test('gets product search query', function (): void { ]; $di = container(); + $service->setDi($di); - [$sql, $params] = $service->getProductSearchQuery($data); - - expect($sql)->toBeString(); - expect($params)->toBeArray(); -}); - -test('converts product category to api array', function (): void { - $serviceMock = Mockery::mock(Service::class)->makePartial(); - $model = new Model_ProductCategory(); - $model->loadBean(new Tests\Helpers\DummyBean()); - - $modelProduct = new Model_Product(); - $modelProduct->loadBean(new Tests\Helpers\DummyBean()); - $modelProduct->type = 'custom'; - $categoryProductsArr = [$modelProduct]; - - /** @var Mockery\Expectation $expectation1 */ - $expectation1 = $serviceMock->shouldReceive('getCategoryProducts'); - $expectation1->atLeast()->once(); - $expectation1->andReturn($categoryProductsArr); - - $apiArrayResult = ['price_starting_from' => 1]; - /** @var Mockery\Expectation $expectation2 */ - $expectation2 = $serviceMock->shouldReceive('toApiArray'); - $expectation2->atLeast()->once(); - $expectation2->andReturn($apiArrayResult); - - $dbMock = Mockery::mock('\Box_Database'); - /** @var Mockery\Expectation $expectation3 */ - $expectation3 = $dbMock->shouldReceive('toArray'); - $expectation3->atLeast()->once(); - $expectation3->andReturn([]); + $repo = Mockery::mock(ProductRepository::class); + $qb = Mockery::mock(Doctrine\ORM\QueryBuilder::class)->shouldIgnoreMissing(); + $repo->shouldReceive('getSearchQueryBuilder')->once()->with($data)->andReturn($qb); $di = container(); - $di['db'] = $dbMock; + $di['em'] = new class($repo) { + public function __construct(private ProductRepository $repo) + { + } - $serviceMock->setDi($di); + public function getRepository(string $class): object + { + return $this->repo; + } + }; + + $service->setDi($di); + + $result = $service->getProductSearchQueryBuilder($data); + + expect($result)->toBe($qb); +}); + +test('to product category api array', function (): void { + $service = new Service(); + $model = productTestCreateProductCategoryEntity(1) + ->setTitle('Category') + ->setDescription('Description') + ->setIconUrl('http://urltoimg.com/img.jpg'); + + $modelProduct = productTestCreateProductEntity(1)->setType('custom'); + $categoryProductsArr = [ + $modelProduct, + ]; + + $serviceMock = Mockery::mock(Service::class)->makePartial(); + + $serviceMock->shouldReceive('getCategoryProducts')->atLeast()->once()->andReturn($categoryProductsArr); + + $apiArrayResult = [ + 'price_starting_from' => 1, + ]; + $serviceMock->shouldReceive('toApiArray')->atLeast()->once()->andReturn($apiArrayResult); + + $serviceMock->setDi(container()); $result = $serviceMock->toProductCategoryApiArray($model); expect($result)->toBeArray(); }); -test('converts product category to api array with minimum price', function (): void { +test('to product category api array starting from value not zero', function (): void { + $service = new Service(); + $model = productTestCreateProductCategoryEntity(1); + + $modelProduct = productTestCreateProductEntity(1)->setType('custom'); + $categoryProductsArr = [ + $modelProduct, + $modelProduct, + $modelProduct, + $modelProduct, + ]; + $serviceMock = Mockery::mock(Service::class)->makePartial(); - $model = new Model_ProductCategory(); - $model->loadBean(new Tests\Helpers\DummyBean()); - $modelProduct = new Model_Product(); - $modelProduct->loadBean(new Tests\Helpers\DummyBean()); - $modelProduct->type = 'custom'; - $categoryProductsArr = [$modelProduct, $modelProduct, $modelProduct, $modelProduct]; - - /** @var Mockery\Expectation $expectation1 */ - $expectation1 = $serviceMock->shouldReceive('getCategoryProducts'); - $expectation1->atLeast()->once(); - $expectation1->andReturn($categoryProductsArr); + $serviceMock->shouldReceive('getCategoryProducts')->atLeast()->once()->andReturn($categoryProductsArr); $min = 1; - /** @var Mockery\Expectation $expectation2 */ - $expectation2 = $serviceMock->shouldReceive('toApiArray'); - $expectation2->atLeast()->once(); - $expectation2->andReturnUsing(function () { - static $count = 0; - ++$count; + $serviceMock->shouldReceive('toApiArray')->atLeast()->once()->andReturn( + ['price_starting_from' => 4], + ['price_starting_from' => 5], + ['price_starting_from' => 2], + ['price_starting_from' => $min], + ); - return match ($count) { - 1 => ['price_starting_from' => 4], - 2 => ['price_starting_from' => 5], - 3 => ['price_starting_from' => 2], - 4 => ['price_starting_from' => 1], - }; - }); - - $dbMock = Mockery::mock('\Box_Database'); - /** @var Mockery\Expectation $expectation3 */ - $expectation3 = $dbMock->shouldReceive('toArray'); - $expectation3->atLeast()->once(); - $expectation3->andReturn([]); - - $di = container(); - $di['db'] = $dbMock; - - $serviceMock->setDi($di); + $serviceMock->setDi(container()); $result = $serviceMock->toProductCategoryApiArray($model); expect($result)->toBeArray(); - expect($result['price_starting_from'])->toBe($min); + expect($result['price_starting_from'])->toEqual($min); }); -test('finds one active product by id', function (): void { +test('find one active by id', function (): void { $service = new Service(); - $model = new Model_Product(); + $model = productTestCreateProductEntity(1); - $dbMock = Mockery::mock('\Box_Database'); - /** @var Mockery\Expectation $expectation */ - $expectation = $dbMock->shouldReceive('findOne'); - $expectation->atLeast()->once(); - $expectation->andReturn($model); + $repo = Mockery::mock(ProductRepository::class); + $repo->shouldReceive('findActiveById')->once()->with(1)->andReturn($model); $di = container(); - $di['db'] = $dbMock; + $di['em'] = new class($repo) { + public function __construct(private ProductRepository $repo) + { + } + + public function getRepository(string $class): object + { + return $this->repo; + } + }; $service->setDi($di); $result = $service->findOneActiveById(1); - expect($result)->toBeInstanceOf('\Model_Product'); + expect($result)->toBeInstanceOf(Product::class); }); -test('finds one active product by slug', function (): void { +test('find one active by slug', function (): void { $service = new Service(); - $model = new Model_Product(); + $model = productTestCreateProductEntity(1); - $dbMock = Mockery::mock('\Box_Database'); - /** @var Mockery\Expectation $expectation */ - $expectation = $dbMock->shouldReceive('findOne'); - $expectation->atLeast()->once(); - $expectation->andReturn($model); + $repo = Mockery::mock(ProductRepository::class); + $repo->shouldReceive('findActiveBySlug')->once()->with('product/1')->andReturn($model); $di = container(); - $di['db'] = $dbMock; + $di['em'] = new class($repo) { + public function __construct(private ProductRepository $repo) + { + } + + public function getRepository(string $class): object + { + return $this->repo; + } + }; $service->setDi($di); $result = $service->findOneActiveBySlug('product/1'); - expect($result)->toBeInstanceOf('\Model_Product'); + expect($result)->toBeInstanceOf(Product::class); }); -test('gets product category search query', function (): void { +test('get product category search query builder', function (): void { $service = new Service(); - [$sql, $params] = $service->getProductCategorySearchQuery([]); - - expect($sql)->toBeString(); - expect($params)->toBeArray(); - expect($params)->toBe([]); -}); - -test('gets starting from price for free product', function (): void { - $service = new Service(); - $productModel = new Model_Product(); - $productModel->loadBean(new Tests\Helpers\DummyBean()); - $productModel->product_payment_id = 1; - - $productPaymentModel = new Model_ProductPayment(); - $productPaymentModel->loadBean(new Tests\Helpers\DummyBean()); - $productPaymentModel->type = 'free'; - - $dbMock = Mockery::mock('\Box_Database'); - /** @var Mockery\Expectation $expectation */ - $expectation = $dbMock->shouldReceive('load'); - $expectation->atLeast()->once(); - $expectation->andReturn($productPaymentModel); + $qb = Mockery::mock(Doctrine\ORM\QueryBuilder::class)->shouldIgnoreMissing(); + $categoryRepo = Mockery::mock(ProductCategoryRepository::class); + $categoryRepo->shouldReceive('getEnabledVisibleSearchQueryBuilder')->once()->andReturn($qb); $di = container(); - $di['db'] = $dbMock; + $di['em'] = productTestCreateEntityManagerWithRepositories(null, null, null, null, $categoryRepo); + + $service->setDi($di); + $result = $service->getProductCategorySearchQueryBuilder([]); + expect($result)->toBe($qb); +}); + +test('get starting from price type free', function (): void { + $service = new Service(); + $productModel = productTestCreateProductEntity(1)->setProductPaymentId(1); + + $productPaymentModel = productTestCreateProductPaymentEntity(1) + ->setType(ProductPayment::FREE); + + $paymentRepo = Mockery::mock(ProductPaymentRepository::class); + $paymentRepo->shouldReceive('find')->once()->with(1)->andReturn($productPaymentModel); + + $di = container(); + $di['em'] = productTestCreateProductPaymentEntityManager($paymentRepo); $service->setDi($di); $result = $service->getStartingFromPrice($productModel); expect($result)->toBeInt(); - expect($result)->toBe(0); + expect($result)->toEqual('0'); }); -test('returns null for starting price when payment not defined', function (): void { +test('get starting from price payment not defined', function (): void { $service = new Service(); - $productModel = new Model_Product(); - $productModel->loadBean(new Tests\Helpers\DummyBean()); + $productModel = productTestCreateProductEntity(1); $result = $service->getStartingFromPrice($productModel); expect($result)->toBeNull(); }); -test('gets starting from price for domain type', function (): void { +test('get starting from price domain type', function (): void { + $service = new Service(); + $productModel = productTestCreateProductEntity(1) + ->setType(Service::DOMAIN) + ->setProductPaymentId(1); + $serviceMock = Mockery::mock(Service::class)->makePartial(); - $productModel = new Model_Product(); - $productModel->loadBean(new Tests\Helpers\DummyBean()); - $productModel->type = Service::DOMAIN; - $productModel->product_payment_id = 1; - - /** @var Mockery\Expectation $expectation1 */ - $expectation1 = $serviceMock->shouldReceive('getStartingDomainPrice'); - $expectation1->atLeast()->once(); - $expectation1->andReturn(10.00); - - /** @var Mockery\Expectation $expectation2 */ - $expectation2 = $serviceMock->shouldReceive('getStartingPrice'); - $expectation2->never(); + $serviceMock->shouldReceive('getStartingDomainPrice')->atLeast()->once()->andReturn(10.00); + $serviceMock->shouldNotReceive('getStartingPrice'); $result = $serviceMock->getStartingFromPrice($productModel); - expect($result)->not()->toBeNull(); + expect($result)->not->toBeNull(); }); -test('gets upgradable pairs', function (): void { +test('get upgradable pairs', function (): void { $service = new Service(); - $productModel = new Model_Product(); - $productModel->loadBean(new Tests\Helpers\DummyBean()); - $productModel->upgrades = '{}'; + $productModel = productTestCreateProductEntity(1)->setUpgrades('{}'); $expected = []; $result = $service->getUpgradablePairs($productModel); expect($result)->toBeArray(); - expect($result)->toBe($expected); + expect($result)->toEqual($expected); }); -test('gets product titles by ids', function (): void { +test('get product titles by ids', function (): void { $service = new Service(); $ids = ['1', '2']; - - $dbMock = Mockery::mock('\Box_Database'); - /** @var Mockery\Expectation $expectation */ - $expectation = $dbMock->shouldReceive('getAll'); - $expectation->atLeast()->once(); - $expectation->andReturn([]); + $expected = [ + 1 => 'test', + 2 => 'Another', + ]; + $productRepository = Mockery::mock(ProductRepository::class); + $productRepository->shouldReceive('findByIds')->once()->with([1, 2])->andReturn([ + productTestCreateProductEntity(1)->setTitle('test'), + productTestCreateProductEntity(2)->setTitle('Another'), + ]); $di = container(); - $di['db'] = $dbMock; + $di['em'] = productTestCreateEntityManagerWithRepositories($productRepository); $service->setDi($di); $result = $service->getProductTitlesByIds($ids); expect($result)->toBeArray(); + expect($result)->toBe($expected); }); -test('gets category products', function (): void { +test('get category products', function (): void { $service = new Service(); - $productCategoryModel = new Model_ProductCategory(); - $productCategoryModel->loadBean(new Tests\Helpers\DummyBean()); + $productCategoryModel = productTestCreateProductCategoryEntity(1); - $productModel = new Model_Product(); - $productModel->loadBean(new Tests\Helpers\DummyBean()); - - $dbMock = Mockery::mock('\Box_Database'); - /** @var Mockery\Expectation $expectation */ - $expectation = $dbMock->shouldReceive('find'); - $expectation->atLeast()->once(); - $expectation->andReturn([$productModel]); + $productModel = productTestCreateProductEntity(1); + $productRepository = Mockery::mock(ProductRepository::class); + $productRepository->shouldReceive('findEnabledVisibleByCategoryId')->once()->with((int) $productCategoryModel->getId())->andReturn([$productModel]); $di = container(); - $di['db'] = $dbMock; + $di['em'] = productTestCreateEntityManagerWithRepositories($productRepository); $service->setDi($di); $result = $service->getCategoryProducts($productCategoryModel); expect($result)->toBeArray(); }); -test('converts product payment to api array', function (): void { +test('to product payment api array', function (): void { $service = new Service(); - $productPaymentModel = new Model_ProductPayment(); - $productPaymentModel->loadBean(new Tests\Helpers\DummyBean()); + $productPaymentModel = productTestCreateProductPaymentEntity(1); $result = $service->toProductPaymentApiArray($productPaymentModel); expect($result)->toBeArray(); }); -test('gets starting price', function (): void { +test('get starting price', function (): void { $service = new Service(); - $productPaymentModel = new Model_ProductPayment(); - $productPaymentModel->loadBean(new Tests\Helpers\DummyBean()); - $productPaymentModel->type = 'recurrent'; + $productPaymentModel = productTestCreateProductPaymentEntity(1) + ->setType(ProductPayment::RECURRENT); $minPrice = 1; - $productPaymentModel->w_enabled = true; - $productPaymentModel->w_price = 2; - $productPaymentModel->m_enabled = true; - $productPaymentModel->m_price = 4; - $productPaymentModel->q_enabled = true; - $productPaymentModel->q_price = 8; - $productPaymentModel->b_enabled = true; - $productPaymentModel->b_price = $minPrice; - $productPaymentModel->a_enabled = true; - $productPaymentModel->a_price = 10; - $productPaymentModel->bia_enabled = true; - $productPaymentModel->bia_price = 12; - $productPaymentModel->tria_enabled = true; - $productPaymentModel->tria_price = 14; + $productPaymentModel->setPeriodPricing('w', 2, 0, true); + $productPaymentModel->setPeriodPricing('m', 4, 0, true); + $productPaymentModel->setPeriodPricing('q', 8, 0, true); + $productPaymentModel->setPeriodPricing('b', $minPrice, 0, true); + $productPaymentModel->setPeriodPricing('a', 10, 0, true); + $productPaymentModel->setPeriodPricing('bia', 12, 0, true); + $productPaymentModel->setPeriodPricing('tria', 14, 0, true); $result = $service->getStartingPrice($productPaymentModel); - expect($result)->toBeInt(); - expect($result)->toBe($minPrice); + expect($result)->toBeNumeric(); + expect($result)->toEqual($minPrice); }); -test('checks if product can upgrade to another product', function (): void { +test('can upgrade to returns true', function (): void { + $service = new Service(); $serviceMock = Mockery::mock(Service::class)->makePartial(); - /** @var Mockery\Expectation $expectation */ - $expectation = $serviceMock->shouldReceive('getUpgradablePairs'); - $expectation->atLeast()->once(); - $expectation->andReturn(['2' => 'Hosting']); + $serviceMock->shouldReceive('getUpgradablePairs')->atLeast()->once()->andReturn(['2' => 'Hosting']); - $productModel = new Model_Product(); - $productModel->loadBean(new Tests\Helpers\DummyBean()); - $productModel->id = 1; - - $newProductModel = new Model_Product(); - $newProductModel->loadBean(new Tests\Helpers\DummyBean()); - $newProductModel->id = 2; + $productModel = productTestCreateProductEntity(1); + $newProductModel = productTestCreateProductEntity(2); $result = $serviceMock->canUpgradeTo($productModel, $newProductModel); expect($result)->toBeTrue(); }); -test('returns false when upgrade is impossible', function (): void { +test('can upgrade to upgrade is impossible', function (): void { + $service = new Service(); $serviceMock = Mockery::mock(Service::class)->makePartial(); - /** @var Mockery\Expectation $expectation */ - $expectation = $serviceMock->shouldReceive('getUpgradablePairs'); - $expectation->atLeast()->once(); - $expectation->andReturn(['4' => 'Domain']); + $serviceMock->shouldReceive('getUpgradablePairs')->atLeast()->once()->andReturn(['4' => 'Domain']); - $productModel = new Model_Product(); - $productModel->loadBean(new Tests\Helpers\DummyBean()); - $productModel->id = 1; - - $newProductModel = new Model_Product(); - $newProductModel->loadBean(new Tests\Helpers\DummyBean()); - $newProductModel->id = 2; + $productModel = productTestCreateProductEntity(1); + $newProductModel = productTestCreateProductEntity(2); $result = $serviceMock->canUpgradeTo($productModel, $newProductModel); expect($result)->toBeFalse(); }); -test('returns false when trying to upgrade to same product', function (): void { +test('can upgrade to same products', function (): void { $service = new Service(); - $productModel = new Model_Product(); - $productModel->loadBean(new Tests\Helpers\DummyBean()); - $productModel->id = 1; - - $newProductModel = new Model_Product(); - $newProductModel->loadBean(new Tests\Helpers\DummyBean()); - $newProductModel->id = 1; + $productModel = productTestCreateProductEntity(1); + $newProductModel = productTestCreateProductEntity(1); $result = $service->canUpgradeTo($productModel, $newProductModel); expect($result)->toBeFalse(); }); + +test('assert upgrade allowed by ids throws helpful exception', function (): void { + $service = new Service(); + $currentProduct = productTestCreateProductEntity(1) + ->setTitle('Starter'); + $upgradeProduct = productTestCreateProductEntity(2) + ->setTitle('Pro'); + + $serviceMock = Mockery::mock(Service::class)->makePartial(); + $serviceMock->shouldReceive('getUpgradablePairsByProductId')->once()->with(1)->andReturn([]); + $serviceMock->shouldReceive('findProductById')->twice()->andReturnUsing(function ($id) use ($currentProduct, $upgradeProduct) { + return match ($id) { + 1 => $currentProduct, + 2 => $upgradeProduct, + }; + }); + + expect(fn () => $serviceMock->assertUpgradeAllowedByIds(1, 2)) + ->toThrow(FOSSBilling\InformationException::class, 'Sorry, but "Starter" is not allowed to be upgraded to "Pro"'); +}); diff --git a/src/modules/Serviceapikey/Service.php b/src/modules/Serviceapikey/Service.php index 5c22b4441..a2caa036f 100644 --- a/src/modules/Serviceapikey/Service.php +++ b/src/modules/Serviceapikey/Service.php @@ -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); } diff --git a/src/modules/Serviceapikey/templates/client/mod_serviceapikey_manage.html.twig b/src/modules/Serviceapikey/templates/client/mod_serviceapikey_manage.html.twig index 4e1b34027..f5e510130 100644 --- a/src/modules/Serviceapikey/templates/client/mod_serviceapikey_manage.html.twig +++ b/src/modules/Serviceapikey/templates/client/mod_serviceapikey_manage.html.twig @@ -1,10 +1,10 @@ {% if order.status == 'active' %}
-

{{ order.title }}

+

{{ order.title }}

-

{{ 'API Key Details'|trans }}

+

{{ 'API Key Details'|trans }}

{{ 'Client Groups'|trans }} {{ 'Validity Period'|trans }} {{ 'Enabled'|trans }}{{ 'Usage'|trans }}{{ 'Limit Tracking'|trans }}
{{ mf.boolean_badge(promo.active, 'Yes'|trans, 'No'|trans, 'text-bg-success', 'text-bg-secondary') }}{{ promo.used }} / {% if promo.maxuses %}{{ promo.maxuses }}{% else %}∞{% endif %} + {{ promo.used }} / {% if promo.maxuses %}{{ promo.maxuses }}{% else %}∞{% endif %} +
{{ promo.redemption_count }} {{ 'recorded applications'|trans }}
+
- + - + + {% if promo.can_be_deleted %} + + + + + + {% else %} + + {% endif %}
@@ -16,7 +16,7 @@
-

{{ 'Reset API Key'|trans }}

+

{{ 'Reset API Key'|trans }}

diff --git a/src/modules/Servicecustom/Service.php b/src/modules/Servicecustom/Service.php index 56e693f4d..a15b78cdb 100644 --- a/src/modules/Servicecustom/Service.php +++ b/src/modules/Servicecustom/Service.php @@ -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'); diff --git a/src/modules/Servicecustom/tests/Unit/ServiceTest.php b/src/modules/Servicecustom/tests/Unit/ServiceTest.php index 958e2bf33..4cc0fbe79 100644 --- a/src/modules/Servicecustom/tests/Unit/ServiceTest.php +++ b/src/modules/Servicecustom/tests/Unit/ServiceTest.php @@ -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 = ''; diff --git a/src/modules/Servicedomain/Service.php b/src/modules/Servicedomain/Service.php index 7ab9a5fc3..0e828517d 100644 --- a/src/modules/Servicedomain/Service.php +++ b/src/modules/Servicedomain/Service.php @@ -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 diff --git a/src/modules/Servicedomain/templates/admin/mod_servicedomain_manage.html.twig b/src/modules/Servicedomain/templates/admin/mod_servicedomain_manage.html.twig index 40a76ea4d..ad59cb87e 100644 --- a/src/modules/Servicedomain/templates/admin/mod_servicedomain_manage.html.twig +++ b/src/modules/Servicedomain/templates/admin/mod_servicedomain_manage.html.twig @@ -1,3 +1,4 @@ +{% import 'macro_functions.html.twig' as mf %}
diff --git a/src/modules/Servicedomain/tests/Unit/ServiceTest.php b/src/modules/Servicedomain/tests/Unit/ServiceTest.php index 6b5b45fe8..ccc8b14b5 100644 --- a/src/modules/Servicedomain/tests/Unit/ServiceTest.php +++ b/src/modules/Servicedomain/tests/Unit/ServiceTest.php @@ -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); diff --git a/src/modules/Servicedownloadable/Api/Admin.php b/src/modules/Servicedownloadable/Api/Admin.php index 8548aadfa..329021f76 100644 --- a/src/modules/Servicedownloadable/Api/Admin.php +++ b/src/modules/Servicedownloadable/Api/Admin.php @@ -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(); diff --git a/src/modules/Servicedownloadable/Service.php b/src/modules/Servicedownloadable/Service.php index ce968dbd8..b5ae3f212 100644 --- a/src/modules/Servicedownloadable/Service.php +++ b/src/modules/Servicedownloadable/Service.php @@ -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; } diff --git a/src/modules/Servicedownloadable/tests/Unit/Api/AdminTest.php b/src/modules/Servicedownloadable/tests/Unit/Api/AdminTest.php deleted file mode 100644 index d667907a3..000000000 --- a/src/modules/Servicedownloadable/tests/Unit/Api/AdminTest.php +++ /dev/null @@ -1,262 +0,0 @@ -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); -}); diff --git a/src/modules/Servicedownloadable/tests/Unit/ServiceTest.php b/src/modules/Servicedownloadable/tests/Unit/ServiceTest.php index 7718726dc..9182dc72d 100644 --- a/src/modules/Servicedownloadable/tests/Unit/ServiceTest.php +++ b/src/modules/Servicedownloadable/tests/Unit/ServiceTest.php @@ -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); }); diff --git a/src/modules/Servicehosting/Api/Guest.php b/src/modules/Servicehosting/Api/Guest.php index f529f074f..dd0dae4d3 100644 --- a/src/modules/Servicehosting/Api/Guest.php +++ b/src/modules/Servicehosting/Api/Guest.php @@ -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]); diff --git a/src/modules/Servicehosting/Service.php b/src/modules/Servicehosting/Service.php index 5ee3449ad..e2f03ea3f 100644 --- a/src/modules/Servicehosting/Service.php +++ b/src/modules/Servicehosting/Service.php @@ -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) { diff --git a/src/modules/Servicehosting/templates/client/mod_servicehosting_order_form.html.twig b/src/modules/Servicehosting/templates/client/mod_servicehosting_order_form.html.twig index 3f5ef0677..537d88065 100644 --- a/src/modules/Servicehosting/templates/client/mod_servicehosting_order_form.html.twig +++ b/src/modules/Servicehosting/templates/client/mod_servicehosting_order_form.html.twig @@ -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 %} diff --git a/src/modules/Servicehosting/tests/Unit/Api/GuestTest.php b/src/modules/Servicehosting/tests/Unit/Api/GuestTest.php index 904b3b364..415ba0204 100644 --- a/src/modules/Servicehosting/tests/Unit/Api/GuestTest.php +++ b/src/modules/Servicehosting/tests/Unit/Api/GuestTest.php @@ -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'); }); diff --git a/src/modules/Servicehosting/tests/Unit/ServiceTest.php b/src/modules/Servicehosting/tests/Unit/ServiceTest.php index fd2cc23f4..4dcd85e98 100644 --- a/src/modules/Servicehosting/tests/Unit/ServiceTest.php +++ b/src/modules/Servicehosting/tests/Unit/ServiceTest.php @@ -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(); }); diff --git a/src/modules/Servicelicense/Api/Guest.php b/src/modules/Servicelicense/Api/Guest.php index c5985926a..5f2249ef5 100644 --- a/src/modules/Servicelicense/Api/Guest.php +++ b/src/modules/Servicelicense/Api/Guest.php @@ -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) diff --git a/src/modules/Servicelicense/Service.php b/src/modules/Servicelicense/Service.php index 35a7ce220..bc79052a4 100644 --- a/src/modules/Servicelicense/Service.php +++ b/src/modules/Servicelicense/Service.php @@ -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; } diff --git a/src/modules/Servicelicense/templates/client/mod_servicelicense_manage.html.twig b/src/modules/Servicelicense/templates/client/mod_servicelicense_manage.html.twig index dfe1e5206..ba9c9fa18 100644 --- a/src/modules/Servicelicense/templates/client/mod_servicelicense_manage.html.twig +++ b/src/modules/Servicelicense/templates/client/mod_servicelicense_manage.html.twig @@ -78,7 +78,7 @@

{{ 'Reset License'|trans }}

-

{{ 'You can reset your license parameters if you have changed your server'|trans }}

+

{{ '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 }}

{{ 'Reset'|trans }} diff --git a/src/modules/Servicelicense/tests/Unit/ServiceTest.php b/src/modules/Servicelicense/tests/Unit/ServiceTest.php index 1edc41074..858471983 100644 --- a/src/modules/Servicelicense/tests/Unit/ServiceTest.php +++ b/src/modules/Servicelicense/tests/Unit/ServiceTest.php @@ -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); }); diff --git a/src/modules/Staff/tests/Unit/ServiceTest.php b/src/modules/Staff/tests/Unit/ServiceTest.php index d0ef55f29..22369e15f 100644 --- a/src/modules/Staff/tests/Unit/ServiceTest.php +++ b/src/modules/Staff/tests/Unit/ServiceTest.php @@ -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); diff --git a/src/modules/Support/Service.php b/src/modules/Support/Service.php index d6be6a2a5..76a3ec05e 100644 --- a/src/modules/Support/Service.php +++ b/src/modules/Support/Service.php @@ -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 diff --git a/src/modules/Support/tests/Unit/ServiceTest.php b/src/modules/Support/tests/Unit/ServiceTest.php index b84d0d45a..ff2830c9c 100644 --- a/src/modules/Support/tests/Unit/ServiceTest.php +++ b/src/modules/Support/tests/Unit/ServiceTest.php @@ -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'); diff --git a/src/themes/admin_default/assets/fossbilling.js b/src/themes/admin_default/assets/fossbilling.js index bcaa7a608..00645d6b2 100644 --- a/src/themes/admin_default/assets/fossbilling.js +++ b/src/themes/admin_default/assets/fossbilling.js @@ -66,20 +66,30 @@ async function copyTextToClipboard(text) { function handleClipboardResult(button, success) { if (success) { let tooltip = bootstrap.Tooltip.getInstance(button); + let createdForThisAction = false; if (!tooltip) { tooltip = new bootstrap.Tooltip(button, { trigger: 'manual' }); + createdForThisAction = true; } + const hadOriginalTitle = Object.prototype.hasOwnProperty.call(button.dataset, 'bsOriginalTitle'); const originalTitle = button.dataset.bsOriginalTitle; button.dataset.bsOriginalTitle = 'Copied'; tooltip.show(); setTimeout(() => { - button.dataset.bsOriginalTitle = originalTitle; + if (hadOriginalTitle) { + button.dataset.bsOriginalTitle = originalTitle; + } else { + delete button.dataset.bsOriginalTitle; + } tooltip.hide(); + if (createdForThisAction) { + tooltip.dispose(); + } }, 2000); } else { if (typeof FOSSBilling !== 'undefined' && FOSSBilling.message) { - FOSSBilling.message('Failed to copy to clipboard', 'error'); + FOSSBilling.message('Failed to copy to clipboard. Please select the text and copy it manually.', 'error'); } } } @@ -106,7 +116,9 @@ document.addEventListener('DOMContentLoaded', () => { } if (document.querySelector('.sortable')) { - loadAdminFeature(() => import('sortable-tablesort/dist/sortable.min.js'), 'sortable tables'); + loadAdminFeature(async () => { + await import('sortable-tablesort/dist/sortable.min.js'); + }, 'sortable tables'); } if (document.querySelector('#theme-settings')) { diff --git a/src/themes/admin_default/html/partial_pricing.html.twig b/src/themes/admin_default/html/partial_pricing.html.twig index 94eb13832..89e2ce90d 100644 --- a/src/themes/admin_default/html/partial_pricing.html.twig +++ b/src/themes/admin_default/html/partial_pricing.html.twig @@ -96,7 +96,8 @@