diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS
index 8c074bcc5..89782bc3e 100644
--- a/.github/CODEOWNERS
+++ b/.github/CODEOWNERS
@@ -5,4 +5,4 @@
/src/library/FOSSBilling/GeoIP/ @BelleNottelling
/src/library/FOSSBilling/Fingerprint.php @BelleNottelling
/src/library/FOSSBilling/SentryHelper.php @BelleNottelling
-/src/tests/ @BelleNottelling
+/tests/ @BelleNottelling
diff --git a/.github/SECURITY.md b/.github/SECURITY.md
index 52e6ba228..69bc7b804 100644
--- a/.github/SECURITY.md
+++ b/.github/SECURITY.md
@@ -29,7 +29,7 @@ Reports covering any of the following topics will be rejected by the FOSSBilling
- Weak SSL/TLS/SSH algorithms or protocols.
- Attacks involving physical access to a user’s device, or involving a device or network that’s already seriously compromised (eg man-in-the-middle).
- The user attacks themselves.
-- Anything in `/tests-legacy` or `tests`.
+- Anything in `/tests`.
### A special note on AI tooling
diff --git a/.github/labeler.yml b/.github/labeler.yml
index 51b061138..91cf30996 100644
--- a/.github/labeler.yml
+++ b/.github/labeler.yml
@@ -73,5 +73,4 @@ npm:
tests/CI:
- any:
- changed-files:
- - any-glob-to-any-file: ["tests-legacy/**/*"]
- any-glob-to-any-file: ["tests/**/*"]
diff --git a/.github/scripts/run-docker-live-tests.sh b/.github/scripts/run-docker-live-tests.sh
index e3da5dd07..2607ac65d 100644
--- a/.github/scripts/run-docker-live-tests.sh
+++ b/.github/scripts/run-docker-live-tests.sh
@@ -90,5 +90,5 @@ compose run --rm --no-deps \
app \
sh -euxc "
cd /workspace
- ./src/vendor/bin/phpunit --configuration phpunit-live.xml
+ ./src/vendor/bin/pest --test-directory ../tests --configuration phpunit-live.xml
"
diff --git a/.github/workflows/cypress-tests.yml b/.github/workflows/cypress-tests.yml
index f3a86b223..19647c01a 100644
--- a/.github/workflows/cypress-tests.yml
+++ b/.github/workflows/cypress-tests.yml
@@ -61,6 +61,6 @@ jobs:
name: cypress-artifacts
if-no-files-found: ignore
path: |
- tests/e2e/cypress/screenshots
- tests/e2e/cypress/videos
- tests/e2e/cypress/downloads
+ tests/E2E/Cypress/artifacts/screenshots
+ tests/E2E/Cypress/artifacts/videos
+ tests/E2E/Cypress/artifacts/downloads
diff --git a/.github/workflows/php-build-test.yml b/.github/workflows/php-build-test.yml
index 3fbb8ccc6..ef192bbf5 100644
--- a/.github/workflows/php-build-test.yml
+++ b/.github/workflows/php-build-test.yml
@@ -75,13 +75,13 @@ jobs:
fossbilling:test-${{ matrix.php }} \
./src/vendor/bin/phpstan analyse --configuration phpstan.neon --memory-limit=512M
- - name: 'PHPUnit'
- id: phpunit
+ - name: 'Pest'
+ id: pest
run: |
docker run --rm \
--env APP_ENV=test \
fossbilling:test-${{ matrix.php }} \
- ./src/vendor/bin/phpunit --configuration phpunit.xml.dist
+ ./src/vendor/bin/pest --test-directory ../tests --configuration phpunit.xml.dist
- name: 'Write Job Summary'
if: always()
@@ -97,5 +97,5 @@ jobs:
| Cache mode | `${{ inputs.write-cache && 'read/write' || 'read-only' }}` |
| Docker build | `${{ inputs.write-cache && steps.build_write_cache.outcome || steps.build_read_cache.outcome }}` |
| PHPStan | `${{ steps.phpstan.outcome }}` |
- | PHPUnit | `${{ steps.phpunit.outcome }}` |
+ | Pest | `${{ steps.pest.outcome }}` |
EOF
diff --git a/.gitignore b/.gitignore
index d66f350e2..1b145694c 100644
--- a/.gitignore
+++ b/.gitignore
@@ -17,10 +17,6 @@ DOCKER_ENV
docker_tag
Dockerfile-php-build
-### phpunit/phpunit ###
-.phpunit.result.cache
-.phpunit.cache/test-results
-
### node_modules ###
node_modules
@@ -31,6 +27,4 @@ src/themes/huraga/config/settings_data.json
output.log
### Cypress ###
-tests/e2e/cypress/downloads
-tests/e2e/cypress/screenshots
-tests/e2e/cypress/videos
+tests/E2E/Cypress/artifacts
diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php
index e18264f88..6a200bccd 100644
--- a/.php-cs-fixer.dist.php
+++ b/.php-cs-fixer.dist.php
@@ -15,25 +15,23 @@ if (!file_exists(__DIR__ . '/src')) {
return (new PhpCsFixer\Config())
->setRules([
- '@PHP84Migration' => true,
- '@Symfony' => true,
+ '@auto' => true, // Applies newest PER-CS and optimizations for PHP, based on project's composer.json file.
+ '@PHP8x5Migration' => true, // Rules to improve code for PHP 8.5 compatibility.
+ '@Symfony' => true, // Rules that follow the official Symfony Coding Standards.
'concat_space' => ['spacing' => 'one'],
'protected_to_private' => false,
'yoda_style' => ['equal' => false, 'identical' => false, 'less_and_greater' => false], // Enforce non-Yoda style.
'blank_line_before_statement' => ['statements' => ['break', 'continue', 'return', 'throw', 'try']], // Removed 'declare' from the default list.
- /* Risky */
'get_class_to_class_keyword' => true, // Risky if the get_class function is overridden. In our case, it's not.
'dir_constant' => true, // Risky when the function dirname is overridden. In our case, it's not.
'array_push' => true, // Risky when the function array_push is overridden. In our case, it's not.
'no_useless_sprintf' => true, // Risky when the function sprintf is overridden. In our case, it's not.
- 'php_unit_construct' => true, // https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/master/doc/rules/php_unit/php_unit_construct.rst
- 'php_unit_mock_short_will_return' => true, // https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/master/doc/rules/php_unit/php_unit_mock_short_will_return.rst
- 'no_homoglyph_names' => true, // https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/master/doc/rules/naming/no_homoglyph_names.rst
+ 'no_homoglyph_names' => true, // Risky - https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/master/doc/rules/naming/no_homoglyph_names.rst.
])
->setRiskyAllowed(true)
->setFinder(
(new PhpCsFixer\Finder())
- ->in([__DIR__ . '/src', __DIR__ . '/tests', __DIR__ . '/tests-legacy'])
+ ->in([__DIR__ . '/src', __DIR__ . '/tests'])
->exclude([
'data',
'locale',
@@ -44,4 +42,5 @@ return (new PhpCsFixer\Config())
'config-sample.php'
)
)
- ->setParallelConfig(PhpCsFixer\Runner\Parallel\ParallelConfigFactory::detect());
+ ->setParallelConfig(PhpCsFixer\Runner\Parallel\ParallelConfigFactory::detect())
+ ->setCacheFile(__DIR__.'/cache/.php-cs-fixer.cache');
diff --git a/AGENTS.md b/AGENTS.md
index 41258e32e..a27370181 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -41,7 +41,7 @@ FOSSBilling is a free and open-source billing and client management solution des
* [PostCSS](https://postcss.org/) with Autoprefixer: CSS post-processing
* [svg-sprite](https://github.com/svg-sprite/svg-sprite): SVG sprite generation for icons
* **Testing:**
- * [PHPUnit](https://phpunit.de/): Unit and integration testing framework
+ * [Pest](https://pestphp.com/): Unit, module, and live API test framework
* **Code Quality & Analysis:**
* [PHP-CS-Fixer](https://cs.symfony.com/): PSR-12 coding standards enforcement
* [Rector](https://getrector.org/): Automated PHP code refactoring and modernization
@@ -135,18 +135,15 @@ cd src/themes/huraga && npm run dev
### Testing
-**PHPUnit Tests:** Run the PHP test suite using PHPUnit:
+**Pest Tests:** Run the PHP test suite using Pest:
```bash
composer test
```
-The project has two test suites:
-
-* **Library Tests:** Located in `tests-legacy/library/` for testing core library functionality
-* **Module Tests:** Located in `tests-legacy/modules/` for testing individual modules
-
-`phpunit.xml.dist` currently runs the legacy PHPUnit suites by default. The `tests/` directory contains newer test and end-to-end test structure, including Cypress tests under `tests/e2e`.
+The default suite covers unit tests in `tests/Unit` and module unit tests in `src/modules/*/tests/Unit`.
+Live API tests are in `tests/Modules` and run through Pest with `phpunit-live.xml` when `APP_URL` and `TEST_API_KEY` are available.
+Cypress end-to-end tests live under `tests/E2E/Cypress`.
### Code Quality Tools
@@ -196,8 +193,7 @@ src/
└── vendor/ # Composer dependencies
frontend/ # Core frontend source and shared build tooling
-tests/ # Modern and end-to-end test structure
-tests-legacy/ # Legacy PHPUnit tests
+tests/ # Pest, live API, and end-to-end test structure
```
### Front-end Guidelines
@@ -239,7 +235,7 @@ tests-legacy/ # Legacy PHPUnit tests
2. **Development Setup:** Install dependencies and build assets
3. **Code Quality:** Run tests and code quality tools before submitting
4. **Module Development:** Understand the distinction between Service modules and Extension modules
-5. **Testing:** Write tests for new functionality using PHPUnit
+5. **Testing:** Write tests for new functionality using Pest
## Key Files and Directories
@@ -249,7 +245,7 @@ tests-legacy/ # Legacy PHPUnit tests
* **`package.json`:** Node.js dependencies, build scripts, and workspace configuration
* **`frontend/`:** Core frontend source and shared esbuild helper code
* **`src/public/`:** Public shared assets, default branding, and gateway icons
-* **`phpunit.xml.dist`:** PHPUnit testing configuration
+* **`phpunit.xml.dist`:** Pest/PHPUnit testing configuration
* **`phpstan.neon`:** PHPStan static analysis configuration
* **`.php-cs-fixer.dist.php`:** PHP-CS-Fixer coding standards configuration
* **`rector.php`:** Rector refactoring rules configuration
diff --git a/Dockerfile b/Dockerfile
index 27252be72..98ed5ef51 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -148,7 +148,6 @@ COPY --from=release-tree /app/src ./src
COPY --from=php-dev-vendor /app/src/vendor ./src/vendor
COPY composer.json composer.lock phpstan.neon phpstan-baseline.neon phpunit.xml.dist phpunit-live.xml ./
COPY tests ./tests
-COPY tests-legacy ./tests-legacy
RUN set -eux; \
php -r '$config = require "./src/config-sample.php"; file_put_contents("./src/config.php", "=7.0",
+ "php": ">=7.3"
+ },
+ "conflict": {
+ "phpunit/phpunit": "<8.0"
+ },
+ "require-dev": {
+ "phpunit/phpunit": "^8.5 || ^9.6.17",
+ "symplify/easy-coding-standard": "^12.1.14"
+ },
+ "type": "library",
+ "autoload": {
+ "files": [
+ "library/helpers.php",
+ "library/Mockery.php"
+ ],
+ "psr-4": {
+ "Mockery\\": "library/Mockery"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "BSD-3-Clause"
+ ],
+ "authors": [
+ {
+ "name": "Pádraic Brady",
+ "email": "padraic.brady@gmail.com",
+ "homepage": "https://github.com/padraic",
+ "role": "Author"
+ },
+ {
+ "name": "Dave Marshall",
+ "email": "dave.marshall@atstsolutions.co.uk",
+ "homepage": "https://davedevelopment.co.uk",
+ "role": "Developer"
+ },
+ {
+ "name": "Nathanael Esayeas",
+ "email": "nathanael.esayeas@protonmail.com",
+ "homepage": "https://github.com/ghostwriter",
+ "role": "Lead Developer"
+ }
+ ],
+ "description": "Mockery is a simple yet flexible PHP mock object framework",
+ "homepage": "https://github.com/mockery/mockery",
+ "keywords": [
+ "BDD",
+ "TDD",
+ "library",
+ "mock",
+ "mock objects",
+ "mockery",
+ "stub",
+ "test",
+ "test double",
+ "testing"
+ ],
+ "support": {
+ "docs": "https://docs.mockery.io/",
+ "issues": "https://github.com/mockery/mockery/issues",
+ "rss": "https://github.com/mockery/mockery/releases.atom",
+ "security": "https://github.com/mockery/mockery/security/advisories",
+ "source": "https://github.com/mockery/mockery"
+ },
+ "time": "2024-05-16T03:13:13+00:00"
+ },
{
"name": "myclabs/deep-copy",
"version": "1.13.4",
@@ -7797,6 +8024,580 @@
},
"time": "2025-12-06T11:56:16+00:00"
},
+ {
+ "name": "nunomaduro/collision",
+ "version": "v8.9.4",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/nunomaduro/collision.git",
+ "reference": "716af8f95a470e9094cfca09ed897b023be191a5"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/nunomaduro/collision/zipball/716af8f95a470e9094cfca09ed897b023be191a5",
+ "reference": "716af8f95a470e9094cfca09ed897b023be191a5",
+ "shasum": ""
+ },
+ "require": {
+ "filp/whoops": "^2.18.4",
+ "nunomaduro/termwind": "^2.4.0",
+ "php": "^8.2.0",
+ "symfony/console": "^7.4.8 || ^8.0.8"
+ },
+ "conflict": {
+ "laravel/framework": "<11.48.0 || >=14.0.0",
+ "phpunit/phpunit": "<11.5.50 || >=14.0.0"
+ },
+ "require-dev": {
+ "brianium/paratest": "^7.8.5",
+ "larastan/larastan": "^3.9.6",
+ "laravel/framework": "^11.48.0 || ^12.56.0 || ^13.5.0",
+ "laravel/pint": "^1.29.1",
+ "orchestra/testbench-core": "^9.12.0 || ^10.12.1 || ^11.2.1",
+ "pestphp/pest": "^3.8.5 || ^4.4.3 || ^5.0.0",
+ "sebastian/environment": "^7.2.1 || ^8.0.4 || ^9.3.0"
+ },
+ "type": "library",
+ "extra": {
+ "laravel": {
+ "providers": [
+ "NunoMaduro\\Collision\\Adapters\\Laravel\\CollisionServiceProvider"
+ ]
+ },
+ "branch-alias": {
+ "dev-8.x": "8.x-dev"
+ }
+ },
+ "autoload": {
+ "files": [
+ "./src/Adapters/Phpunit/Autoload.php"
+ ],
+ "psr-4": {
+ "NunoMaduro\\Collision\\": "src/"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Nuno Maduro",
+ "email": "enunomaduro@gmail.com"
+ }
+ ],
+ "description": "Cli error handling for console/command-line PHP applications.",
+ "keywords": [
+ "artisan",
+ "cli",
+ "command-line",
+ "console",
+ "dev",
+ "error",
+ "handling",
+ "laravel",
+ "laravel-zero",
+ "php",
+ "symfony"
+ ],
+ "support": {
+ "issues": "https://github.com/nunomaduro/collision/issues",
+ "source": "https://github.com/nunomaduro/collision"
+ },
+ "funding": [
+ {
+ "url": "https://www.paypal.com/paypalme/enunomaduro",
+ "type": "custom"
+ },
+ {
+ "url": "https://github.com/nunomaduro",
+ "type": "github"
+ },
+ {
+ "url": "https://www.patreon.com/nunomaduro",
+ "type": "patreon"
+ }
+ ],
+ "time": "2026-04-21T14:04:20+00:00"
+ },
+ {
+ "name": "nunomaduro/termwind",
+ "version": "v2.4.0",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/nunomaduro/termwind.git",
+ "reference": "712a31b768f5daea284c2169a7d227031001b9a8"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/nunomaduro/termwind/zipball/712a31b768f5daea284c2169a7d227031001b9a8",
+ "reference": "712a31b768f5daea284c2169a7d227031001b9a8",
+ "shasum": ""
+ },
+ "require": {
+ "ext-mbstring": "*",
+ "php": "^8.2",
+ "symfony/console": "^7.4.4 || ^8.0.4"
+ },
+ "require-dev": {
+ "illuminate/console": "^11.47.0",
+ "laravel/pint": "^1.27.1",
+ "mockery/mockery": "^1.6.12",
+ "pestphp/pest": "^2.36.0 || ^3.8.4 || ^4.3.2",
+ "phpstan/phpstan": "^1.12.32",
+ "phpstan/phpstan-strict-rules": "^1.6.2",
+ "symfony/var-dumper": "^7.3.5 || ^8.0.4",
+ "thecodingmachine/phpstan-strict-rules": "^1.0.0"
+ },
+ "type": "library",
+ "extra": {
+ "laravel": {
+ "providers": [
+ "Termwind\\Laravel\\TermwindServiceProvider"
+ ]
+ },
+ "branch-alias": {
+ "dev-2.x": "2.x-dev"
+ }
+ },
+ "autoload": {
+ "files": [
+ "src/Functions.php"
+ ],
+ "psr-4": {
+ "Termwind\\": "src/"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Nuno Maduro",
+ "email": "enunomaduro@gmail.com"
+ }
+ ],
+ "description": "It's like Tailwind CSS, but for the console.",
+ "keywords": [
+ "cli",
+ "console",
+ "css",
+ "package",
+ "php",
+ "style"
+ ],
+ "support": {
+ "issues": "https://github.com/nunomaduro/termwind/issues",
+ "source": "https://github.com/nunomaduro/termwind/tree/v2.4.0"
+ },
+ "funding": [
+ {
+ "url": "https://www.paypal.com/paypalme/enunomaduro",
+ "type": "custom"
+ },
+ {
+ "url": "https://github.com/nunomaduro",
+ "type": "github"
+ },
+ {
+ "url": "https://github.com/xiCO2k",
+ "type": "github"
+ }
+ ],
+ "time": "2026-02-16T23:10:27+00:00"
+ },
+ {
+ "name": "pestphp/pest",
+ "version": "v4.7.2",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/pestphp/pest.git",
+ "reference": "40b88b62ef8a7c6fcae5fc28f1fa747f601c131b"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/pestphp/pest/zipball/40b88b62ef8a7c6fcae5fc28f1fa747f601c131b",
+ "reference": "40b88b62ef8a7c6fcae5fc28f1fa747f601c131b",
+ "shasum": ""
+ },
+ "require": {
+ "brianium/paratest": "^7.20.0",
+ "composer/xdebug-handler": "^3.0.5",
+ "nunomaduro/collision": "^8.9.4",
+ "nunomaduro/termwind": "^2.4.0",
+ "pestphp/pest-plugin": "^4.0.0",
+ "pestphp/pest-plugin-arch": "^4.0.2",
+ "pestphp/pest-plugin-mutate": "^4.0.1",
+ "pestphp/pest-plugin-profanity": "^4.2.1",
+ "php": "^8.3.0",
+ "phpunit/phpunit": "^12.5.28",
+ "symfony/process": "^7.4.13|^8.1.0"
+ },
+ "conflict": {
+ "filp/whoops": "<2.18.3",
+ "phpunit/phpunit": ">12.5.28",
+ "sebastian/exporter": "<7.0.0",
+ "webmozart/assert": "<1.11.0"
+ },
+ "require-dev": {
+ "mrpunyapal/peststan": "^0.2.10",
+ "pestphp/pest-dev-tools": "^4.1.0",
+ "pestphp/pest-plugin-browser": "^4.3.1",
+ "pestphp/pest-plugin-type-coverage": "^4.0.4",
+ "psy/psysh": "^0.12.23"
+ },
+ "bin": [
+ "bin/pest"
+ ],
+ "type": "library",
+ "extra": {
+ "pest": {
+ "plugins": [
+ "Pest\\Mutate\\Plugins\\Mutate",
+ "Pest\\Plugins\\Configuration",
+ "Pest\\Plugins\\Bail",
+ "Pest\\Plugins\\Cache",
+ "Pest\\Plugins\\Coverage",
+ "Pest\\Plugins\\Init",
+ "Pest\\Plugins\\Environment",
+ "Pest\\Plugins\\Help",
+ "Pest\\Plugins\\Memory",
+ "Pest\\Plugins\\Only",
+ "Pest\\Plugins\\Printer",
+ "Pest\\Plugins\\ProcessIsolation",
+ "Pest\\Plugins\\Profile",
+ "Pest\\Plugins\\Retry",
+ "Pest\\Plugins\\Snapshot",
+ "Pest\\Plugins\\Verbose",
+ "Pest\\Plugins\\Version",
+ "Pest\\Plugins\\Shard",
+ "Pest\\Plugins\\Tia",
+ "Pest\\Plugins\\Parallel"
+ ]
+ },
+ "phpstan": {
+ "includes": [
+ "extension.neon"
+ ]
+ }
+ },
+ "autoload": {
+ "files": [
+ "src/Functions.php",
+ "src/Pest.php"
+ ],
+ "psr-4": {
+ "Pest\\": "src/"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Nuno Maduro",
+ "email": "enunomaduro@gmail.com"
+ }
+ ],
+ "description": "The elegant PHP Testing Framework.",
+ "keywords": [
+ "framework",
+ "pest",
+ "php",
+ "test",
+ "testing",
+ "unit"
+ ],
+ "support": {
+ "issues": "https://github.com/pestphp/pest/issues",
+ "source": "https://github.com/pestphp/pest/tree/v4.7.2"
+ },
+ "funding": [
+ {
+ "url": "https://www.paypal.com/paypalme/enunomaduro",
+ "type": "custom"
+ },
+ {
+ "url": "https://github.com/nunomaduro",
+ "type": "github"
+ }
+ ],
+ "time": "2026-06-01T06:08:59+00:00"
+ },
+ {
+ "name": "pestphp/pest-plugin",
+ "version": "v4.0.0",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/pestphp/pest-plugin.git",
+ "reference": "9d4b93d7f73d3f9c3189bb22c220fef271cdf568"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/pestphp/pest-plugin/zipball/9d4b93d7f73d3f9c3189bb22c220fef271cdf568",
+ "reference": "9d4b93d7f73d3f9c3189bb22c220fef271cdf568",
+ "shasum": ""
+ },
+ "require": {
+ "composer-plugin-api": "^2.0.0",
+ "composer-runtime-api": "^2.2.2",
+ "php": "^8.3"
+ },
+ "conflict": {
+ "pestphp/pest": "<4.0.0"
+ },
+ "require-dev": {
+ "composer/composer": "^2.8.10",
+ "pestphp/pest": "^4.0.0",
+ "pestphp/pest-dev-tools": "^4.0.0"
+ },
+ "type": "composer-plugin",
+ "extra": {
+ "class": "Pest\\Plugin\\Manager"
+ },
+ "autoload": {
+ "psr-4": {
+ "Pest\\Plugin\\": "src/"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "description": "The Pest plugin manager",
+ "keywords": [
+ "framework",
+ "manager",
+ "pest",
+ "php",
+ "plugin",
+ "test",
+ "testing",
+ "unit"
+ ],
+ "support": {
+ "source": "https://github.com/pestphp/pest-plugin/tree/v4.0.0"
+ },
+ "funding": [
+ {
+ "url": "https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=66BYDWAT92N6L",
+ "type": "custom"
+ },
+ {
+ "url": "https://github.com/nunomaduro",
+ "type": "github"
+ },
+ {
+ "url": "https://www.patreon.com/nunomaduro",
+ "type": "patreon"
+ }
+ ],
+ "time": "2025-08-20T12:35:58+00:00"
+ },
+ {
+ "name": "pestphp/pest-plugin-arch",
+ "version": "v4.0.2",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/pestphp/pest-plugin-arch.git",
+ "reference": "3fb0d02a91b9da504b139dc7ab2a31efb7c3215c"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/pestphp/pest-plugin-arch/zipball/3fb0d02a91b9da504b139dc7ab2a31efb7c3215c",
+ "reference": "3fb0d02a91b9da504b139dc7ab2a31efb7c3215c",
+ "shasum": ""
+ },
+ "require": {
+ "pestphp/pest-plugin": "^4.0.0",
+ "php": "^8.3",
+ "ta-tikoma/phpunit-architecture-test": "^0.8.7"
+ },
+ "require-dev": {
+ "pestphp/pest": "^4.4.6",
+ "pestphp/pest-dev-tools": "^4.1.0"
+ },
+ "type": "library",
+ "extra": {
+ "pest": {
+ "plugins": [
+ "Pest\\Arch\\Plugin"
+ ]
+ }
+ },
+ "autoload": {
+ "files": [
+ "src/Autoload.php"
+ ],
+ "psr-4": {
+ "Pest\\Arch\\": "src/"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "description": "The Arch plugin for Pest PHP.",
+ "keywords": [
+ "arch",
+ "architecture",
+ "framework",
+ "pest",
+ "php",
+ "plugin",
+ "test",
+ "testing",
+ "unit"
+ ],
+ "support": {
+ "source": "https://github.com/pestphp/pest-plugin-arch/tree/v4.0.2"
+ },
+ "funding": [
+ {
+ "url": "https://www.paypal.com/paypalme/enunomaduro",
+ "type": "custom"
+ },
+ {
+ "url": "https://github.com/nunomaduro",
+ "type": "github"
+ }
+ ],
+ "time": "2026-04-10T17:20:19+00:00"
+ },
+ {
+ "name": "pestphp/pest-plugin-mutate",
+ "version": "v4.0.1",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/pestphp/pest-plugin-mutate.git",
+ "reference": "d9b32b60b2385e1688a68cc227594738ec26d96c"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/pestphp/pest-plugin-mutate/zipball/d9b32b60b2385e1688a68cc227594738ec26d96c",
+ "reference": "d9b32b60b2385e1688a68cc227594738ec26d96c",
+ "shasum": ""
+ },
+ "require": {
+ "nikic/php-parser": "^5.6.1",
+ "pestphp/pest-plugin": "^4.0.0",
+ "php": "^8.3",
+ "psr/simple-cache": "^3.0.0"
+ },
+ "require-dev": {
+ "pestphp/pest": "^4.0.0",
+ "pestphp/pest-dev-tools": "^4.0.0",
+ "pestphp/pest-plugin-type-coverage": "^4.0.0"
+ },
+ "type": "library",
+ "autoload": {
+ "psr-4": {
+ "Pest\\Mutate\\": "src/"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Nuno Maduro",
+ "email": "enunomaduro@gmail.com"
+ },
+ {
+ "name": "Sandro Gehri",
+ "email": "sandrogehri@gmail.com"
+ }
+ ],
+ "description": "Mutates your code to find untested cases",
+ "keywords": [
+ "framework",
+ "mutate",
+ "mutation",
+ "pest",
+ "php",
+ "plugin",
+ "test",
+ "testing",
+ "unit"
+ ],
+ "support": {
+ "source": "https://github.com/pestphp/pest-plugin-mutate/tree/v4.0.1"
+ },
+ "funding": [
+ {
+ "url": "https://www.paypal.com/paypalme/enunomaduro",
+ "type": "custom"
+ },
+ {
+ "url": "https://github.com/gehrisandro",
+ "type": "github"
+ },
+ {
+ "url": "https://github.com/nunomaduro",
+ "type": "github"
+ }
+ ],
+ "time": "2025-08-21T20:19:25+00:00"
+ },
+ {
+ "name": "pestphp/pest-plugin-profanity",
+ "version": "v4.2.1",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/pestphp/pest-plugin-profanity.git",
+ "reference": "343cfa6f3564b7e35df0ebb77b7fa97039f72b27"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/pestphp/pest-plugin-profanity/zipball/343cfa6f3564b7e35df0ebb77b7fa97039f72b27",
+ "reference": "343cfa6f3564b7e35df0ebb77b7fa97039f72b27",
+ "shasum": ""
+ },
+ "require": {
+ "pestphp/pest-plugin": "^4.0.0",
+ "php": "^8.3"
+ },
+ "require-dev": {
+ "faissaloux/pest-plugin-inside": "^1.9",
+ "pestphp/pest": "^4.0.0",
+ "pestphp/pest-dev-tools": "^4.0.0"
+ },
+ "type": "library",
+ "extra": {
+ "pest": {
+ "plugins": [
+ "Pest\\Profanity\\Plugin"
+ ]
+ }
+ },
+ "autoload": {
+ "psr-4": {
+ "Pest\\Profanity\\": "src/"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "description": "The Pest Profanity Plugin",
+ "keywords": [
+ "framework",
+ "pest",
+ "php",
+ "plugin",
+ "profanity",
+ "test",
+ "testing",
+ "unit"
+ ],
+ "support": {
+ "source": "https://github.com/pestphp/pest-plugin-profanity/tree/v4.2.1"
+ },
+ "time": "2025-12-08T00:13:17+00:00"
+ },
{
"name": "phar-io/manifest",
"version": "2.0.4",
@@ -7915,6 +8716,182 @@
},
"time": "2022-02-21T01:04:05+00:00"
},
+ {
+ "name": "phpdocumentor/reflection-common",
+ "version": "2.2.0",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/phpDocumentor/ReflectionCommon.git",
+ "reference": "1d01c49d4ed62f25aa84a747ad35d5a16924662b"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/phpDocumentor/ReflectionCommon/zipball/1d01c49d4ed62f25aa84a747ad35d5a16924662b",
+ "reference": "1d01c49d4ed62f25aa84a747ad35d5a16924662b",
+ "shasum": ""
+ },
+ "require": {
+ "php": "^7.2 || ^8.0"
+ },
+ "type": "library",
+ "extra": {
+ "branch-alias": {
+ "dev-2.x": "2.x-dev"
+ }
+ },
+ "autoload": {
+ "psr-4": {
+ "phpDocumentor\\Reflection\\": "src/"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Jaap van Otterdijk",
+ "email": "opensource@ijaap.nl"
+ }
+ ],
+ "description": "Common reflection classes used by phpdocumentor to reflect the code structure",
+ "homepage": "http://www.phpdoc.org",
+ "keywords": [
+ "FQSEN",
+ "phpDocumentor",
+ "phpdoc",
+ "reflection",
+ "static analysis"
+ ],
+ "support": {
+ "issues": "https://github.com/phpDocumentor/ReflectionCommon/issues",
+ "source": "https://github.com/phpDocumentor/ReflectionCommon/tree/2.x"
+ },
+ "time": "2020-06-27T09:03:43+00:00"
+ },
+ {
+ "name": "phpdocumentor/reflection-docblock",
+ "version": "6.0.3",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/phpDocumentor/ReflectionDocBlock.git",
+ "reference": "7bae67520aa9f5ecc506d646810bd40d9da54582"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/phpDocumentor/ReflectionDocBlock/zipball/7bae67520aa9f5ecc506d646810bd40d9da54582",
+ "reference": "7bae67520aa9f5ecc506d646810bd40d9da54582",
+ "shasum": ""
+ },
+ "require": {
+ "doctrine/deprecations": "^1.1",
+ "ext-filter": "*",
+ "php": "^7.4 || ^8.0",
+ "phpdocumentor/reflection-common": "^2.2",
+ "phpdocumentor/type-resolver": "^2.0",
+ "phpstan/phpdoc-parser": "^2.0",
+ "webmozart/assert": "^1.9.1 || ^2"
+ },
+ "require-dev": {
+ "mockery/mockery": "~1.3.5 || ~1.6.0",
+ "phpstan/extension-installer": "^1.1",
+ "phpstan/phpstan": "^1.8",
+ "phpstan/phpstan-mockery": "^1.1",
+ "phpstan/phpstan-webmozart-assert": "^1.2",
+ "phpunit/phpunit": "^9.5",
+ "psalm/phar": "^5.26",
+ "shipmonk/dead-code-detector": "^0.5.1"
+ },
+ "type": "library",
+ "extra": {
+ "branch-alias": {
+ "dev-master": "5.x-dev"
+ }
+ },
+ "autoload": {
+ "psr-4": {
+ "phpDocumentor\\Reflection\\": "src"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Mike van Riel",
+ "email": "me@mikevanriel.com"
+ },
+ {
+ "name": "Jaap van Otterdijk",
+ "email": "opensource@ijaap.nl"
+ }
+ ],
+ "description": "With this component, a library can provide support for annotations via DocBlocks or otherwise retrieve information that is embedded in a DocBlock.",
+ "support": {
+ "issues": "https://github.com/phpDocumentor/ReflectionDocBlock/issues",
+ "source": "https://github.com/phpDocumentor/ReflectionDocBlock/tree/6.0.3"
+ },
+ "time": "2026-03-18T20:49:53+00:00"
+ },
+ {
+ "name": "phpdocumentor/type-resolver",
+ "version": "2.0.0",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/phpDocumentor/TypeResolver.git",
+ "reference": "327a05bbee54120d4786a0dc67aad30226ad4cf9"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/phpDocumentor/TypeResolver/zipball/327a05bbee54120d4786a0dc67aad30226ad4cf9",
+ "reference": "327a05bbee54120d4786a0dc67aad30226ad4cf9",
+ "shasum": ""
+ },
+ "require": {
+ "doctrine/deprecations": "^1.0",
+ "php": "^7.4 || ^8.0",
+ "phpdocumentor/reflection-common": "^2.0",
+ "phpstan/phpdoc-parser": "^2.0"
+ },
+ "require-dev": {
+ "ext-tokenizer": "*",
+ "phpbench/phpbench": "^1.2",
+ "phpstan/extension-installer": "^1.4",
+ "phpstan/phpstan": "^2.1",
+ "phpstan/phpstan-phpunit": "^2.0",
+ "phpunit/phpunit": "^9.5",
+ "psalm/phar": "^4"
+ },
+ "type": "library",
+ "extra": {
+ "branch-alias": {
+ "dev-1.x": "1.x-dev",
+ "dev-2.x": "2.x-dev"
+ }
+ },
+ "autoload": {
+ "psr-4": {
+ "phpDocumentor\\Reflection\\": "src"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Mike van Riel",
+ "email": "me@mikevanriel.com"
+ }
+ ],
+ "description": "A PSR-5 based resolver of Class names, Types and Structural Element Names",
+ "support": {
+ "issues": "https://github.com/phpDocumentor/TypeResolver/issues",
+ "source": "https://github.com/phpDocumentor/TypeResolver/tree/2.0.0"
+ },
+ "time": "2026-01-06T21:53:42+00:00"
+ },
{
"name": "phpstan/extension-installer",
"version": "1.4.3",
@@ -7963,6 +8940,53 @@
},
"time": "2024-09-04T20:21:43+00:00"
},
+ {
+ "name": "phpstan/phpdoc-parser",
+ "version": "2.3.2",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/phpstan/phpdoc-parser.git",
+ "reference": "a004701b11273a26cd7955a61d67a7f1e525a45a"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/phpstan/phpdoc-parser/zipball/a004701b11273a26cd7955a61d67a7f1e525a45a",
+ "reference": "a004701b11273a26cd7955a61d67a7f1e525a45a",
+ "shasum": ""
+ },
+ "require": {
+ "php": "^7.4 || ^8.0"
+ },
+ "require-dev": {
+ "doctrine/annotations": "^2.0",
+ "nikic/php-parser": "^5.3.0",
+ "php-parallel-lint/php-parallel-lint": "^1.2",
+ "phpstan/extension-installer": "^1.0",
+ "phpstan/phpstan": "^2.0",
+ "phpstan/phpstan-phpunit": "^2.0",
+ "phpstan/phpstan-strict-rules": "^2.0",
+ "phpunit/phpunit": "^9.6",
+ "symfony/process": "^5.2"
+ },
+ "type": "library",
+ "autoload": {
+ "psr-4": {
+ "PHPStan\\PhpDocParser\\": [
+ "src/"
+ ]
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "description": "PHPDoc parser with support for nullable, intersection and generic types",
+ "support": {
+ "issues": "https://github.com/phpstan/phpdoc-parser/issues",
+ "source": "https://github.com/phpstan/phpdoc-parser/tree/2.3.2"
+ },
+ "time": "2026-01-25T14:56:51+00:00"
+ },
{
"name": "phpstan/phpstan",
"version": "2.2.1",
@@ -8079,16 +9103,16 @@
},
{
"name": "phpunit/php-code-coverage",
- "version": "12.5.6",
+ "version": "12.5.7",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/php-code-coverage.git",
- "reference": "876099a072646c7745f673d7aeab5382c4439691"
+ "reference": "186dab580576598076de6818596d12b61801880e"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/876099a072646c7745f673d7aeab5382c4439691",
- "reference": "876099a072646c7745f673d7aeab5382c4439691",
+ "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/186dab580576598076de6818596d12b61801880e",
+ "reference": "186dab580576598076de6818596d12b61801880e",
"shasum": ""
},
"require": {
@@ -8099,13 +9123,13 @@
"php": ">=8.3",
"phpunit/php-text-template": "^5.0",
"sebastian/complexity": "^5.0",
- "sebastian/environment": "^8.0.3",
- "sebastian/lines-of-code": "^4.0",
+ "sebastian/environment": "^8.1.2",
+ "sebastian/lines-of-code": "^4.0.1",
"sebastian/version": "^6.0",
"theseer/tokenizer": "^2.0.1"
},
"require-dev": {
- "phpunit/phpunit": "^12.5.1"
+ "phpunit/phpunit": "^12.5.28"
},
"suggest": {
"ext-pcov": "PHP extension that provides line coverage",
@@ -8143,7 +9167,7 @@
"support": {
"issues": "https://github.com/sebastianbergmann/php-code-coverage/issues",
"security": "https://github.com/sebastianbergmann/php-code-coverage/security/policy",
- "source": "https://github.com/sebastianbergmann/php-code-coverage/tree/12.5.6"
+ "source": "https://github.com/sebastianbergmann/php-code-coverage/tree/12.5.7"
},
"funding": [
{
@@ -8163,7 +9187,7 @@
"type": "tidelift"
}
],
- "time": "2026-04-15T08:23:17+00:00"
+ "time": "2026-06-01T13:24:19+00:00"
},
{
"name": "phpunit/php-file-iterator",
@@ -8512,6 +9536,57 @@
],
"time": "2026-05-27T14:01:10+00:00"
},
+ {
+ "name": "psr/simple-cache",
+ "version": "3.0.0",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/php-fig/simple-cache.git",
+ "reference": "764e0b3939f5ca87cb904f570ef9be2d78a07865"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/php-fig/simple-cache/zipball/764e0b3939f5ca87cb904f570ef9be2d78a07865",
+ "reference": "764e0b3939f5ca87cb904f570ef9be2d78a07865",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=8.0.0"
+ },
+ "type": "library",
+ "extra": {
+ "branch-alias": {
+ "dev-master": "3.0.x-dev"
+ }
+ },
+ "autoload": {
+ "psr-4": {
+ "Psr\\SimpleCache\\": "src/"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "PHP-FIG",
+ "homepage": "https://www.php-fig.org/"
+ }
+ ],
+ "description": "Common interfaces for simple caching",
+ "keywords": [
+ "cache",
+ "caching",
+ "psr",
+ "psr-16",
+ "simple-cache"
+ ],
+ "support": {
+ "source": "https://github.com/php-fig/simple-cache/tree/3.0.0"
+ },
+ "time": "2021-10-29T13:26:27+00:00"
+ },
{
"name": "react/cache",
"version": "v1.2.0",
@@ -9552,26 +10627,26 @@
},
{
"name": "sebastian/global-state",
- "version": "8.0.2",
+ "version": "8.0.3",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/global-state.git",
- "reference": "ef1377171613d09edd25b7816f05be8313f9115d"
+ "reference": "b164d3274d6537ab462591c5755f76a8f5b1aae9"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/sebastianbergmann/global-state/zipball/ef1377171613d09edd25b7816f05be8313f9115d",
- "reference": "ef1377171613d09edd25b7816f05be8313f9115d",
+ "url": "https://api.github.com/repos/sebastianbergmann/global-state/zipball/b164d3274d6537ab462591c5755f76a8f5b1aae9",
+ "reference": "b164d3274d6537ab462591c5755f76a8f5b1aae9",
"shasum": ""
},
"require": {
"php": ">=8.3",
"sebastian/object-reflector": "^5.0",
- "sebastian/recursion-context": "^7.0"
+ "sebastian/recursion-context": "^7.0.1"
},
"require-dev": {
"ext-dom": "*",
- "phpunit/phpunit": "^12.0"
+ "phpunit/phpunit": "^12.5.28"
},
"type": "library",
"extra": {
@@ -9602,7 +10677,7 @@
"support": {
"issues": "https://github.com/sebastianbergmann/global-state/issues",
"security": "https://github.com/sebastianbergmann/global-state/security/policy",
- "source": "https://github.com/sebastianbergmann/global-state/tree/8.0.2"
+ "source": "https://github.com/sebastianbergmann/global-state/tree/8.0.3"
},
"funding": [
{
@@ -9622,7 +10697,7 @@
"type": "tidelift"
}
],
- "time": "2025-08-29T11:29:25+00:00"
+ "time": "2026-06-01T15:10:33+00:00"
},
{
"name": "sebastian/lines-of-code",
@@ -10059,91 +11134,6 @@
],
"time": "2024-10-20T05:08:20+00:00"
},
- {
- "name": "symfony/phpunit-bridge",
- "version": "v7.4.8",
- "source": {
- "type": "git",
- "url": "https://github.com/symfony/phpunit-bridge.git",
- "reference": "140bbbe1cd1c21a084494ccddeee33f3c3381d7d"
- },
- "dist": {
- "type": "zip",
- "url": "https://api.github.com/repos/symfony/phpunit-bridge/zipball/140bbbe1cd1c21a084494ccddeee33f3c3381d7d",
- "reference": "140bbbe1cd1c21a084494ccddeee33f3c3381d7d",
- "shasum": ""
- },
- "require": {
- "php": ">=8.1.0"
- },
- "require-dev": {
- "symfony/deprecation-contracts": "^2.5|^3",
- "symfony/error-handler": "^6.4.3|^7.0.3|^8.0"
- },
- "bin": [
- "bin/simple-phpunit"
- ],
- "type": "symfony-bridge",
- "extra": {
- "thanks": {
- "url": "https://github.com/sebastianbergmann/phpunit",
- "name": "phpunit/phpunit"
- }
- },
- "autoload": {
- "files": [
- "bootstrap.php"
- ],
- "psr-4": {
- "Symfony\\Bridge\\PhpUnit\\": ""
- },
- "exclude-from-classmap": [
- "/Tests/",
- "/bin/"
- ]
- },
- "notification-url": "https://packagist.org/downloads/",
- "license": [
- "MIT"
- ],
- "authors": [
- {
- "name": "Nicolas Grekas",
- "email": "p@tchwork.com"
- },
- {
- "name": "Symfony Community",
- "homepage": "https://symfony.com/contributors"
- }
- ],
- "description": "Provides utilities for PHPUnit, especially user deprecation notices management",
- "homepage": "https://symfony.com",
- "keywords": [
- "testing"
- ],
- "support": {
- "source": "https://github.com/symfony/phpunit-bridge/tree/v7.4.8"
- },
- "funding": [
- {
- "url": "https://symfony.com/sponsor",
- "type": "custom"
- },
- {
- "url": "https://github.com/fabpot",
- "type": "github"
- },
- {
- "url": "https://github.com/nicolas-grekas",
- "type": "github"
- },
- {
- "url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
- "type": "tidelift"
- }
- ],
- "time": "2026-03-24T13:12:05+00:00"
- },
{
"name": "symfony/process",
"version": "v7.4.13",
@@ -10275,6 +11265,65 @@
],
"time": "2026-03-24T13:12:05+00:00"
},
+ {
+ "name": "ta-tikoma/phpunit-architecture-test",
+ "version": "0.8.7",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/ta-tikoma/phpunit-architecture-test.git",
+ "reference": "1248f3f506ca9641d4f68cebcd538fa489754db8"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/ta-tikoma/phpunit-architecture-test/zipball/1248f3f506ca9641d4f68cebcd538fa489754db8",
+ "reference": "1248f3f506ca9641d4f68cebcd538fa489754db8",
+ "shasum": ""
+ },
+ "require": {
+ "nikic/php-parser": "^4.18.0 || ^5.0.0",
+ "php": "^8.1.0",
+ "phpdocumentor/reflection-docblock": "^5.3.0 || ^6.0.0",
+ "phpunit/phpunit": "^10.5.5 || ^11.0.0 || ^12.0.0 || ^13.0.0",
+ "symfony/finder": "^6.4.0 || ^7.0.0 || ^8.0.0"
+ },
+ "require-dev": {
+ "laravel/pint": "^1.13.7",
+ "phpstan/phpstan": "^1.10.52"
+ },
+ "type": "library",
+ "autoload": {
+ "psr-4": {
+ "PHPUnit\\Architecture\\": "src/"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Ni Shi",
+ "email": "futik0ma011@gmail.com"
+ },
+ {
+ "name": "Nuno Maduro",
+ "email": "enunomaduro@gmail.com"
+ }
+ ],
+ "description": "Methods for testing application architecture",
+ "keywords": [
+ "architecture",
+ "phpunit",
+ "stucture",
+ "test",
+ "testing"
+ ],
+ "support": {
+ "issues": "https://github.com/ta-tikoma/phpunit-architecture-test/issues",
+ "source": "https://github.com/ta-tikoma/phpunit-architecture-test/tree/0.8.7"
+ },
+ "time": "2026-02-17T17:25:14+00:00"
+ },
{
"name": "theseer/tokenizer",
"version": "2.0.1",
@@ -10324,6 +11373,72 @@
}
],
"time": "2025-12-08T11:19:18+00:00"
+ },
+ {
+ "name": "webmozart/assert",
+ "version": "2.4.0",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/webmozarts/assert.git",
+ "reference": "9007ea6f45ecf352a9422b36644e4bfc039b9155"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/webmozarts/assert/zipball/9007ea6f45ecf352a9422b36644e4bfc039b9155",
+ "reference": "9007ea6f45ecf352a9422b36644e4bfc039b9155",
+ "shasum": ""
+ },
+ "require": {
+ "ext-ctype": "*",
+ "ext-date": "*",
+ "ext-filter": "*",
+ "php": "^8.2"
+ },
+ "suggest": {
+ "ext-intl": "",
+ "ext-simplexml": "",
+ "ext-spl": ""
+ },
+ "type": "library",
+ "extra": {
+ "psalm": {
+ "pluginClass": "Webmozart\\Assert\\PsalmPlugin"
+ },
+ "branch-alias": {
+ "dev-master": "2.0-dev",
+ "dev-feature/2-0": "2.0-dev"
+ }
+ },
+ "autoload": {
+ "psr-4": {
+ "Webmozart\\Assert\\": "src/"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Bernhard Schussek",
+ "email": "bschussek@gmail.com"
+ },
+ {
+ "name": "Woody Gilk",
+ "email": "woody.gilk@gmail.com"
+ }
+ ],
+ "description": "Assertions to validate method input/output with nice error messages.",
+ "keywords": [
+ "assert",
+ "check",
+ "validate"
+ ],
+ "support": {
+ "issues": "https://github.com/webmozarts/assert/issues",
+ "source": "https://github.com/webmozarts/assert/tree/2.4.0"
+ },
+ "time": "2026-05-20T13:07:01+00:00"
}
],
"aliases": [],
diff --git a/cspell.json b/cspell.json
index dde9834ff..cc81d3ce1 100644
--- a/cspell.json
+++ b/cspell.json
@@ -421,6 +421,8 @@
"undismissed",
"filp",
"phpunit",
+ "passthru",
+ "pwned",
"hcaptcha",
"hCaptcha",
"LEMP",
@@ -454,7 +456,6 @@
"RPDO"
],
"ignorePaths": [
- "tests-legacy/**",
"node_modules/**",
"src/themes/*/assets/**",
"src/install/assets/**",
diff --git a/cypress.config.js b/cypress.config.js
index 57fad9ddf..17463bc49 100644
--- a/cypress.config.js
+++ b/cypress.config.js
@@ -2,8 +2,8 @@ module.exports = {
projectId: 'zap1kb',
e2e: {
baseUrl: process.env.CYPRESS_BASE_URL || 'http://localhost',
- specPattern: 'tests/e2e/cypress/e2e/**/*.cy.js',
- supportFile: 'tests/e2e/cypress/support/e2e.js',
+ specPattern: 'tests/E2E/Cypress/specs/**/*.cy.js',
+ supportFile: 'tests/E2E/Cypress/support/e2e.js',
},
defaultCommandTimeout: 10000,
viewportWidth: 1280,
@@ -14,7 +14,7 @@ module.exports = {
},
video: false,
screenshotOnRunFailure: true,
- screenshotsFolder: 'tests/e2e/cypress/screenshots',
- videosFolder: 'tests/e2e/cypress/videos',
- downloadsFolder: 'tests/e2e/cypress/downloads',
+ screenshotsFolder: 'tests/E2E/Cypress/artifacts/screenshots',
+ videosFolder: 'tests/E2E/Cypress/artifacts/videos',
+ downloadsFolder: 'tests/E2E/Cypress/artifacts/downloads',
};
diff --git a/data/class-header.txt b/data/class-header.txt
index 366274fdd..95118aa01 100755
--- a/data/class-header.txt
+++ b/data/class-header.txt
@@ -1,5 +1,5 @@
/**
- * Copyright 2022-2025 FOSSBilling
+ * Copyright 2022-2026 FOSSBilling
* SPDX-License-Identifier: Apache-2.0
*
* @copyright FOSSBilling (https://www.fossbilling.org)
diff --git a/phpstan.neon b/phpstan.neon
index 26023259f..26ff14da5 100644
--- a/phpstan.neon
+++ b/phpstan.neon
@@ -2,7 +2,11 @@ includes:
- phpstan-baseline.neon
parameters:
- level: 3
+ level: 5
+ reportUnmatchedIgnoredErrors: false
+ dynamicConstantNames:
+ - DEBUG
+ - INSTANCE_ID
paths:
- src
bootstrapFiles:
@@ -17,6 +21,7 @@ parameters:
- src/library/Server/Manager/Custom.php
- src/library/Server/Manager/Whm.php
- src/data/cache (?)
+ - '*/tests/*'
universalObjectCratesClasses:
- RedBeanPHP\SimpleModel
- RedBeanPHP\OODBBean
diff --git a/phpunit-live.xml b/phpunit-live.xml
index 925b62b78..5ec585233 100644
--- a/phpunit-live.xml
+++ b/phpunit-live.xml
@@ -1,17 +1,25 @@
-
+
+
+ src
+
+
+ src/vendor
+ src/data
+
+
- tests/
+ tests/Modules
-
\ No newline at end of file
+
diff --git a/phpunit.xml.dist b/phpunit.xml.dist
index 207c6de01..cae6d3845 100644
--- a/phpunit.xml.dist
+++ b/phpunit.xml.dist
@@ -1,30 +1,40 @@
-
-
+
-
- tests-legacy/library
+
+ tests/Unit
- tests-legacy/modules
+ src/modules/*/tests/Unit
+
+
+ tests/Modules
+
+
+ tests/E2E
+ src/modules/*/tests/E2E
-
-
-
-
-
src
- src/data
- src/library/Registrar/includes
- src/themes
- src/vendor
- src/install
- src/library/PdoSessionHandler.php
+ src/vendor
+ src/data
diff --git a/rector.php b/rector.php
index 036190afc..184ed630b 100644
--- a/rector.php
+++ b/rector.php
@@ -4,29 +4,19 @@ declare(strict_types=1);
use Rector\Config\RectorConfig;
use Rector\Caching\ValueObject\Storage\FileCacheStorage;
-use Rector\Doctrine\Set\DoctrineSetList;
-use Rector\PHPUnit\Set\PHPUnitSetList;
-use Rector\TypeDeclaration\Rector\Class_\TypedPropertyFromCreateMockAssignRector;
return RectorConfig::configure()
->withPaths([
__DIR__ . '/src',
__DIR__ . '/tests',
- __DIR__ . '/tests-legacy'
])
->withSkip([
__DIR__ . '/src/vendor',
__DIR__ . '/src/data/cache',
- TypedPropertyFromCreateMockAssignRector::class => [
- __DIR__ . "/tests-legacy/modules/Extension/ServiceTest.php"
- ],
])
->withAttributesSets()
->withPhpSets()
- ->withSets([
- DoctrineSetList::DOCTRINE_CODE_QUALITY,
- PHPUnitSetList::PHPUNIT_110,
- ])
+ ->withComposerBased(doctrine: true, phpunit: true)
->withTypeCoverageLevel(30)
->withDeadCodeLevel(30)
->withCache('./cache/rector', FileCacheStorage::class)
diff --git a/src/di.php b/src/di.php
index 82f3f8b5f..427b33617 100644
--- a/src/di.php
+++ b/src/di.php
@@ -117,7 +117,12 @@ $di['pdo'] = function () {
* @return \Box_Database The new Box_Database object that was just created.
*/
$di['db'] = function () use ($di) {
- RedBeanPHP\R::setup($di['pdo']);
+ $pdo = $di->offsetGet('pdo');
+ if (!$pdo instanceof PDO) {
+ throw new RuntimeException('PDO service must resolve to a PDO instance');
+ }
+
+ RedBeanPHP\R::setup($pdo);
RedBeanPHP\Util\DispenseHelper::setEnforceNamingPolicy(false);
// SECURITY: bind string literals as PARAM_STR, not PARAM_INT. Without
@@ -238,7 +243,12 @@ $di['events_manager'] = function () use ($di) {
* @var \FOSSBilling\Session $di['session']
*/
$di['session'] = function () use ($di) {
- $handler = new PdoSessionHandler($di['pdo']);
+ $pdo = $di->offsetGet('pdo');
+ if (!$pdo instanceof PDO) {
+ throw new RuntimeException('PDO service must resolve to a PDO instance');
+ }
+
+ $handler = new PdoSessionHandler($pdo);
$session = new FOSSBilling\Session($handler);
$session->setDi($di);
$session->setupSession();
@@ -641,7 +651,7 @@ $di['table'] = $di->protect(function ($name) use ($di) {
* @return \Box\Mod\Servicelicense\Server
*/
$di['license_server'] = function () use ($di) {
- $server = new Box\Mod\Servicelicense\Server($di['logger']);
+ $server = new Box\Mod\Servicelicense\Server();
$server->setDi($di);
return $server;
@@ -683,7 +693,14 @@ $di['translate'] = $di->protect(function ($textDomain = '') {
return $tr;
});
-$di['csv_response_factory'] = fn (): FOSSBilling\Http\CsvResponseFactory => new FOSSBilling\Http\CsvResponseFactory($di['db']);
+$di['csv_response_factory'] = function () use ($di): FOSSBilling\Http\CsvResponseFactory {
+ $database = $di->offsetGet('db');
+ if (!$database instanceof Box_Database) {
+ throw new RuntimeException('Database service must resolve to a Box_Database instance');
+ }
+
+ return new FOSSBilling\Http\CsvResponseFactory($database);
+};
$di['twig_factory'] = fn (): FOSSBilling\Twig\TwigFactory => new FOSSBilling\Twig\TwigFactory($di);
diff --git a/src/index.php b/src/index.php
index 7d720e0ee..3ee278a8c 100644
--- a/src/index.php
+++ b/src/index.php
@@ -73,7 +73,7 @@ if ($request->query->has('restore_token')) {
}
}
-$di['session'];
+$di['session']->getId();
$timeCollector?->stopMeasure('session_start');
if (strncasecmp($url, ADMIN_PREFIX, strlen(ADMIN_PREFIX)) === 0) {
diff --git a/src/install/install.php b/src/install/install.php
index 2bb71df4e..997b11f11 100644
--- a/src/install/install.php
+++ b/src/install/install.php
@@ -90,7 +90,7 @@ const URL_ADMIN = SYSTEM_URL . 'admin';
// Load action and initialize the installer
$action = $request->query->get('a', 'index');
-$action = is_string($action) && $action !== '' ? $action : 'index';
+$action = $action !== '' ? $action : 'index';
$installer = new FOSSBilling_Installer($request, $preConfigProxyCandidate);
// Run the installer only in non-CLI mode
diff --git a/src/library/Api/Abstract.php b/src/library/Api/Abstract.php
index fa8d68831..e4aeeef94 100644
--- a/src/library/Api/Abstract.php
+++ b/src/library/Api/Abstract.php
@@ -34,13 +34,24 @@ class Api_Abstract implements InjectionAwareInterface
protected ?Pimple\Container $di = null;
+ public function __construct()
+ {
+ if (function_exists('Tests\Helpers\container')) {
+ $this->di = Tests\Helpers\container();
+ }
+ }
+
public function setDi(Pimple\Container $di): void
{
$this->di = $di;
}
- protected function getDi(): ?Pimple\Container
+ public function getDi(): ?Pimple\Container
{
+ if ($this->di === null && function_exists('Tests\Helpers\container')) {
+ $this->di = Tests\Helpers\container();
+ }
+
return $this->di;
}
@@ -57,6 +68,7 @@ class Api_Abstract implements InjectionAwareInterface
*/
public function getMod()
{
+ // @phpstan-ignore booleanNot.alwaysFalse (Runtime check to ensure mod is set)
if (!$this->mod) {
throw new FOSSBilling\Exception('Mod object is not set for the service');
}
diff --git a/src/library/Api/Handler.php b/src/library/Api/Handler.php
index f34f519fe..78ce37b35 100644
--- a/src/library/Api/Handler.php
+++ b/src/library/Api/Handler.php
@@ -59,7 +59,7 @@ final class Api_Handler implements InjectionAwareInterface
throw new FOSSBilling\Exception('Invalid module name', null, 714);
}
- $service = $this->di['mod']('extension')->getService();
+ $service = $this->getDi()['mod']('extension')->getService();
if (!$service->isExtensionActive('mod', $mod)) {
throw new FOSSBilling\Exception('FOSSBilling module :mod is not installed/activated', [':mod' => $mod], 715);
@@ -67,11 +67,12 @@ final class Api_Handler implements InjectionAwareInterface
// permissions check
if ($this->type == 'admin') {
- $staff_service = $this->di['mod_service']('Staff');
+ $staff_service = $this->getDi()['mod_service']('Staff');
if (!$staff_service->hasPermission($this->identity, $mod)) {
if ($this->_acl_exception) {
throw new FOSSBilling\Exception('You do not have access to the :mod module', [':mod' => $mod], 725);
}
+ // @phpstan-ignore if.alwaysFalse (DEBUG is a runtime constant that may be true during debugging)
if (DEBUG) {
error_log('You do not have access to ' . $mod . ' module');
}
@@ -88,14 +89,14 @@ final class Api_Handler implements InjectionAwareInterface
throw new FOSSBilling\Exception('Api class must be an instance of Api_Abstract', null, 730);
}
- $bb_mod = $this->di['mod']($mod);
+ $bb_mod = $this->getDi()['mod']($mod);
$api->setDi($this->di);
$api->setMod($bb_mod);
$api->setIdentity($this->identity);
- $api->setIp($this->di['request']->getClientIp());
+ $api->setIp($this->getDi()['request']->getClientIp());
if ($bb_mod->hasService()) {
- $api->setService($this->di['mod_service']($mod));
+ $api->setService($this->getDi()['mod_service']($mod));
}
if (!method_exists($api, $method_name) || !is_callable([$api, $method_name])) {
diff --git a/src/library/Box/App.php b/src/library/Box/App.php
index 44ea9ea80..e973930f5 100644
--- a/src/library/Box/App.php
+++ b/src/library/Box/App.php
@@ -315,7 +315,8 @@ class Box_App
];
foreach ($adminApiPrefixes as $adminApiPrefix) {
- $realAdminApiUrl = SYSTEM_URL[-1] === '/' ? substr(SYSTEM_URL, 0, -1) . $adminApiPrefix : SYSTEM_URL . $adminApiPrefix;
+ $systemUrl = SYSTEM_URL;
+ $realAdminApiUrl = str_ends_with($systemUrl, '/') ? substr($systemUrl, 0, -1) . $adminApiPrefix : $systemUrl . $adminApiPrefix;
$allowedURLs[] = parse_url($realAdminApiUrl)['path'];
}
foreach ($allowedURLs as $url) {
@@ -353,7 +354,7 @@ class Box_App
protected function checkAdminPrefix(): bool
{
$requestPath = $this->getRequestPath();
- $realAdminUrl = SYSTEM_URL[-1] === '/' ? substr(SYSTEM_URL, 0, -1) . ADMIN_PREFIX : SYSTEM_URL . ADMIN_PREFIX;
+ $realAdminUrl = rtrim(SYSTEM_URL, '/') . ADMIN_PREFIX;
$realAdminPath = parse_url($realAdminUrl)['path'];
if (preg_match('/^' . str_replace('/', '\/', $realAdminPath) . '(.*)/', $requestPath) !== 0) {
diff --git a/src/library/Box/AppClient.php b/src/library/Box/AppClient.php
index 407e2d220..151481abe 100644
--- a/src/library/Box/AppClient.php
+++ b/src/library/Box/AppClient.php
@@ -67,6 +67,7 @@ class Box_AppClient extends Box_App
return new Response($content);
} catch (Exception $e) {
+ // @phpstan-ignore if.alwaysFalse (DEBUG is a runtime constant that may be true during debugging)
if (DEBUG) {
error_log($e->getMessage());
}
diff --git a/src/library/Box/EventManager.php b/src/library/Box/EventManager.php
index f992ef570..10732ab58 100644
--- a/src/library/Box/EventManager.php
+++ b/src/library/Box/EventManager.php
@@ -28,7 +28,9 @@ class Box_EventManager implements FOSSBilling\InjectionAwareInterface
public function fire($data)
{
if (!isset($data['event']) || empty($data['event'])) {
- error_log('Invoked event call without providing event name');
+ if ($this->di !== null && isset($this->di['logger'])) {
+ $this->di['logger']->warning('Invoked event call without providing event name');
+ }
return false;
}
diff --git a/src/library/Box/Log.php b/src/library/Box/Log.php
index 9601c38b1..dfba6f6f9 100644
--- a/src/library/Box/Log.php
+++ b/src/library/Box/Log.php
@@ -26,14 +26,14 @@ declare(strict_types=1);
*/
class Box_Log implements FOSSBilling\InjectionAwareInterface
{
- final public const int EMERG = 0; // Emergency: system is unusable
- final public const int ALERT = 1; // Alert: action must be taken immediately
- final public const int CRIT = 2; // Critical: critical conditions
- final public const int ERR = 3; // Error: error conditions
- final public const int WARN = 4; // Warning: warning conditions
- final public const int NOTICE = 5; // Notice: normal but significant condition
- final public const int INFO = 6; // Informational: informational messages
- final public const int DEBUG = 7; // Debug: debug messages
+ final public const int EMERG = 0;
+ final public const int ALERT = 1;
+ final public const int CRIT = 2;
+ final public const int ERR = 3;
+ final public const int WARN = 4;
+ final public const int NOTICE = 5;
+ final public const int INFO = 6;
+ final public const int DEBUG = 7;
protected array $_priorities = [
self::EMERG => 'EMERGENCY',
@@ -168,6 +168,7 @@ class Box_Log implements FOSSBilling\InjectionAwareInterface
}
// do not log debug level messages if debug is OFF
+ // @phpstan-ignore identical.alwaysTrue (DEBUG is a runtime constant that may be true during debugging)
if ($event['priority'] > self::INFO && DEBUG === false) {
return;
}
diff --git a/src/library/Box/Period.php b/src/library/Box/Period.php
index 0f7b67d2b..bda4c21c5 100644
--- a/src/library/Box/Period.php
+++ b/src/library/Box/Period.php
@@ -117,7 +117,7 @@ class Box_Period
return $this->qty . $this->unit;
}
- public function getTitle()
+ public function getTitle(): string
{
$qty = $this->qty;
$placeholders = [':number' => $qty];
diff --git a/src/library/Box/Translate.php b/src/library/Box/Translate.php
index 130877c00..f7f604d7f 100644
--- a/src/library/Box/Translate.php
+++ b/src/library/Box/Translate.php
@@ -9,6 +9,50 @@ declare(strict_types=1);
* @copyright FOSSBilling (https://www.fossbilling.org)
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0
*/
+if (!function_exists('__trans')) {
+ /**
+ * Translate a message with optional value substitution.
+ *
+ * @param string $msgid The message to translate
+ * @param array|null $values Optional values to substitute in the translated message
+ *
+ * @return string The translated message
+ */
+ function __trans(string $msgid, ?array $values = null): string
+ {
+ $translated = _gettext($msgid);
+
+ if (is_array($values)) {
+ $translated = strtr($translated, $values);
+ }
+
+ return $translated;
+ }
+}
+
+if (!function_exists('__pluralTrans')) {
+ /**
+ * Translate a plural message with optional value substitution.
+ *
+ * @param string $msgid The singular message to translate
+ * @param string $msgidPlural The plural message to translate
+ * @param int $number The number to determine which form to use
+ * @param array|null $values Optional values to substitute in the translated message
+ *
+ * @return string The translated message
+ */
+ function __pluralTrans(string $msgid, string $msgidPlural, int $number, ?array $values = null): string
+ {
+ $translated = _ngettext($msgid, $msgidPlural, $number);
+
+ if (is_array($values)) {
+ $translated = strtr($translated, $values);
+ }
+
+ return $translated;
+ }
+}
+
class Box_Translate
{
protected $domain = 'messages';
@@ -58,28 +102,6 @@ class Box_Translate
_bindtextdomain($this->domain, PATH_LANGS);
_bind_textdomain_codeset($this->domain, $codeset);
_textdomain($this->domain);
-
- function __trans(string $msgid, ?array $values = null): string
- {
- $translated = _gettext($msgid);
-
- if (is_array($values)) {
- $translated = strtr($translated, $values);
- }
-
- return $translated;
- }
-
- function __pluralTrans(string $msgid, string $msgidPlural, int $number, ?array $values = null): string
- {
- $translated = _ngettext($msgid, $msgidPlural, $number);
-
- if (is_array($values)) {
- $translated = strtr($translated, $values);
- }
-
- return $translated;
- }
}
/**
diff --git a/src/library/FOSSBilling/Doctrine/EntityManagerFactory.php b/src/library/FOSSBilling/Doctrine/EntityManagerFactory.php
index a5485b994..b39b34332 100644
--- a/src/library/FOSSBilling/Doctrine/EntityManagerFactory.php
+++ b/src/library/FOSSBilling/Doctrine/EntityManagerFactory.php
@@ -30,6 +30,7 @@ class EntityManagerFactory
static fn (\SplFileInfo $directory): string => $directory->getPathname(),
iterator_to_array($finder)
);
+ $moduleEntityPaths = array_values($moduleEntityPaths);
$cache = new FilesystemAdapter('doctrine', 0, PATH_CACHE);
diff --git a/src/library/FOSSBilling/ExtensionManager.php b/src/library/FOSSBilling/ExtensionManager.php
index 7213cc737..0ab8d803c 100644
--- a/src/library/FOSSBilling/ExtensionManager.php
+++ b/src/library/FOSSBilling/ExtensionManager.php
@@ -170,10 +170,6 @@ class ExtensionManager implements InjectionAwareInterface
$json = $response->toArray();
- if (is_null($json)) {
- throw new Exception('Unable to connect to the FOSSBilling extension directory.', null, 1545);
- }
-
if (isset($json['error']) && is_array($json['error'])) {
throw new Exception($json['error']['message'], null, 746);
}
diff --git a/src/library/FOSSBilling/Fingerprint.php b/src/library/FOSSBilling/Fingerprint.php
index 916549466..729c543ce 100644
--- a/src/library/FOSSBilling/Fingerprint.php
+++ b/src/library/FOSSBilling/Fingerprint.php
@@ -126,13 +126,11 @@ class Fingerprint
++$itemCount;
$scoreSubtract += $properties['weight'];
$differing[] = $name;
- } elseif (!$exitsInFingerprint && !$exitsInCurrentFingerprint) {
- // Do nothing in this case, as the property isn't in either fingerprint.
- } else {
+ } elseif ($exitsInFingerprint && $exitsInCurrentFingerprint) {
++$itemCount;
$hashedData = hash('md5', (string) $properties['source']);
- if ($fingerprint[$name] !== $hashedData) {
+ if (($fingerprint[$name] ?? null) !== $hashedData) {
$scoreSubtract += $properties['weight'];
$differing[] = $name;
}
diff --git a/src/library/FOSSBilling/GeoIP/Country.php b/src/library/FOSSBilling/GeoIP/Country.php
index f59a57998..c52c1b096 100644
--- a/src/library/FOSSBilling/GeoIP/Country.php
+++ b/src/library/FOSSBilling/GeoIP/Country.php
@@ -39,8 +39,8 @@ class Country implements \JsonSerializable
// Instance the language
$country = CountryAlpha2::from($countryRecord['iso_code']);
- $this->name = $country->getNameInLanguage($language) ?? 'Unknown';
- $this->flag = $country->getFlagEmoji() ?? '';
+ $this->name = $country->getNameInLanguage($language);
+ $this->flag = $country->getFlagEmoji();
foreach ($country->getCurrenciesAlpha3() as $currency) {
$currencies[] = $currency->value;
diff --git a/src/library/FOSSBilling/Http/RequestFactory.php b/src/library/FOSSBilling/Http/RequestFactory.php
index 3bea5a61f..3a08c4b32 100644
--- a/src/library/FOSSBilling/Http/RequestFactory.php
+++ b/src/library/FOSSBilling/Http/RequestFactory.php
@@ -197,7 +197,7 @@ final class RequestFactory
private static function parseForwardedHeader(string $header): array
{
- $firstForwardedValue = explode(',', $header)[0] ?? '';
+ $firstForwardedValue = explode(',', $header)[0];
$values = [];
foreach (explode(';', $firstForwardedValue) as $part) {
diff --git a/src/library/FOSSBilling/Mail.php b/src/library/FOSSBilling/Mail.php
index 5c42dd3ea..2f5127dbd 100644
--- a/src/library/FOSSBilling/Mail.php
+++ b/src/library/FOSSBilling/Mail.php
@@ -110,7 +110,7 @@ class Mail
*/
public function setPriority(int $priority): void
{
- if (is_int($priority) && $priority >= Email::PRIORITY_HIGHEST && $priority <= Email::PRIORITY_LOWEST) {
+ if ($priority >= Email::PRIORITY_HIGHEST && $priority <= Email::PRIORITY_LOWEST) {
$this->email->priority($priority);
} else {
throw new InformationException('Provided priority (:priority) is invalid. Please provide an integer between 1 and 5 or use the pre-defined symfony constants.', [':priority' => $priority]);
@@ -181,7 +181,7 @@ class Mail
}
$host = urlencode(trim((string) $options['smtp_host']));
- $port = Tools::normalizePort($options['smtp_port'] ?? null);
+ $port = Tools::normalizePort($options['smtp_port']);
if ($port === null) {
throw new InformationException('SMTP port is invalid');
}
diff --git a/src/library/FOSSBilling/Monolog.php b/src/library/FOSSBilling/Monolog.php
index e2e651088..496909b89 100644
--- a/src/library/FOSSBilling/Monolog.php
+++ b/src/library/FOSSBilling/Monolog.php
@@ -62,23 +62,22 @@ class Monolog
}
/**
- * Convert numeric FOSSBilling priority to Monolog priority.
+ * Convert numeric FOSSBilling priority to Monolog Level.
*/
- public function parsePriority(int $priority): int
+ public function parsePriority(int $priority): Level
{
- // Map numeric priority to Monolog priority
- $map = [
- \Box_Log::EMERG => Level::Emergency->value,
- \Box_Log::ALERT => Level::Alert->value,
- \Box_Log::CRIT => Level::Critical->value,
- \Box_Log::ERR => Level::Error->value,
- \Box_Log::WARN => Level::Warning->value,
- \Box_Log::NOTICE => Level::Notice->value,
- \Box_Log::INFO => Level::Info->value,
- \Box_Log::DEBUG => Level::Debug->value,
- ];
-
- return $map[$priority] ?? Level::Debug->value;
+ // Map numeric priority to Monolog Level
+ return match ($priority) {
+ \Box_Log::EMERG => Level::Emergency,
+ \Box_Log::ALERT => Level::Alert,
+ \Box_Log::CRIT => Level::Critical,
+ \Box_Log::ERR => Level::Error,
+ \Box_Log::WARN => Level::Warning,
+ \Box_Log::NOTICE => Level::Notice,
+ \Box_Log::INFO => Level::Info,
+ \Box_Log::DEBUG => Level::Debug,
+ default => Level::Debug,
+ };
}
public function write(array $event, string $channel = 'application'): void
diff --git a/src/library/FOSSBilling/PasswordManager.php b/src/library/FOSSBilling/PasswordManager.php
index f7e9179cf..cf62bfd4a 100644
--- a/src/library/FOSSBilling/PasswordManager.php
+++ b/src/library/FOSSBilling/PasswordManager.php
@@ -68,7 +68,8 @@ class PasswordManager
public function hashIt(string $password): string
{
$hash = password_hash($password, $this->algo, $this->options);
- if (!is_string($hash)) {
+ // @phpstan-ignore identical.alwaysFalse (password_hash can return false on failure)
+ if ($hash === false) {
throw new \Exception("Password hashing failed with {$this->algo} and the following options: " . print_r($this->options, true));
}
diff --git a/src/library/FOSSBilling/Security/RateLimiter.php b/src/library/FOSSBilling/Security/RateLimiter.php
index 54b99f148..88fdc849e 100644
--- a/src/library/FOSSBilling/Security/RateLimiter.php
+++ b/src/library/FOSSBilling/Security/RateLimiter.php
@@ -140,12 +140,12 @@ class RateLimiter implements InjectionAwareInterface
'limit' => (int) ($policy['limit'] ?? 60),
];
- if (($factoryConfig['policy'] ?? null) === 'token_bucket') {
+ if ($factoryConfig['policy'] === 'token_bucket') {
$factoryConfig['rate'] = [
'amount' => (int) ($policy['limit'] ?? 60),
'interval' => (string) ($policy['interval'] ?? '1 minute'),
];
- } elseif (($factoryConfig['policy'] ?? null) !== 'no_limit') {
+ } elseif ($factoryConfig['policy'] !== 'no_limit') {
$factoryConfig['interval'] = (string) ($policy['interval'] ?? '1 minute');
}
diff --git a/src/library/FOSSBilling/SentryHelper.php b/src/library/FOSSBilling/SentryHelper.php
index c71689a74..c33146e56 100644
--- a/src/library/FOSSBilling/SentryHelper.php
+++ b/src/library/FOSSBilling/SentryHelper.php
@@ -30,7 +30,7 @@ class SentryHelper
final public const string last_change = '0.6.0';
// A full list of our own modules which we want to receive error reports for
- private static array $allowedModules = [
+ private const array ALLOWED_MODULES = [
'activity',
'api',
'branding',
@@ -73,13 +73,13 @@ class SentryHelper
];
// Themes we want to receive error reports for
- private static array $allowedThemes = [
+ private const array ALLOWED_THEMES = [
'admin_default',
'huraga',
];
// Array containing instance IDs that are blacklisted from error reporting and a timestamp of when their blacklist expires.
- private static array $blacklistedInstances = [
+ private const array BLACKLISTED_INSTANCES = [
'49f78ad3-9e99-492d-aa86-09ba959b16ee' => '2025-08-21',
'40ea07d8-84db-49a0-8dcc-7ef53f9a38be' => '2025-12-01',
];
@@ -241,19 +241,20 @@ class SentryHelper
public static function skipReporting(?string $module = null, ?string $theme = null): bool
{
+ // @phpstan-ignore-next-line
if (!defined('INSTANCE_ID') || !INSTANCE_ID || INSTANCE_ID === 'Unknown' || INSTANCE_ID === 'XXXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXXX') {
return true;
}
- if (array_key_exists(INSTANCE_ID, self::$blacklistedInstances) && strtotime((string) self::$blacklistedInstances[INSTANCE_ID]) >= time()) {
+ if (array_key_exists(INSTANCE_ID, self::BLACKLISTED_INSTANCES) && strtotime((string) self::BLACKLISTED_INSTANCES[INSTANCE_ID]) >= time()) {
return true;
}
- if (is_string($module) && !in_array(strtolower($module), self::$allowedModules)) {
+ if (is_string($module) && !in_array(strtolower($module), self::ALLOWED_MODULES, true)) {
return true;
}
- if (is_string($theme) && !in_array(strtolower($theme), self::$allowedThemes)) {
+ if (is_string($theme) && !in_array(strtolower($theme), self::ALLOWED_THEMES, true)) {
return true;
}
diff --git a/src/library/FOSSBilling/Session.php b/src/library/FOSSBilling/Session.php
index 5c4efa476..e1fe0dd70 100644
--- a/src/library/FOSSBilling/Session.php
+++ b/src/library/FOSSBilling/Session.php
@@ -132,7 +132,7 @@ class Session implements InjectionAwareInterface
$sessionName = session_name();
$sessionID = session_id();
if ($sessionID === '') {
- $sessionID = $sessionName !== '' ? ($_COOKIE[$sessionName] ?? '') : '';
+ $sessionID = $sessionName !== false ? ($_COOKIE[$sessionName] ?? '') : '';
}
if ($sessionID === '') {
@@ -170,14 +170,12 @@ class Session implements InjectionAwareInterface
$cookieParams = session_get_cookie_params();
$cookieOptions = [
'expires' => time() - 3600,
- 'path' => $cookieParams['path'] ?? '/',
- 'domain' => $cookieParams['domain'] ?? '',
- 'secure' => $cookieParams['secure'] ?? false,
- 'httponly' => $cookieParams['httponly'] ?? false,
+ 'path' => $cookieParams['path'],
+ 'domain' => $cookieParams['domain'],
+ 'secure' => $cookieParams['secure'],
+ 'httponly' => $cookieParams['httponly'],
];
- if (!empty($cookieParams['samesite'])) {
- $cookieOptions['samesite'] = $cookieParams['samesite'];
- }
+ $cookieOptions['samesite'] = $cookieParams['samesite'];
setcookie($sessionName, '', $cookieOptions);
unset($_COOKIE[$sessionName]);
}
@@ -191,7 +189,7 @@ class Session implements InjectionAwareInterface
$sessionID = session_id();
if ($sessionID === '') {
$sessionName = session_name();
- $sessionID = $sessionName !== '' ? ($_COOKIE[$sessionName] ?? '') : '';
+ $sessionID = $sessionName !== false ? ($_COOKIE[$sessionName] ?? '') : '';
}
if ($sessionID === '') {
@@ -240,11 +238,11 @@ class Session implements InjectionAwareInterface
setcookie($sessionName, $sessionId, [
'expires' => 0,
- 'path' => $params['path'] ?? '/',
- 'domain' => $params['domain'] ?? '',
- 'secure' => $params['secure'] ?? false,
- 'httponly' => $params['httponly'] ?? true,
- 'samesite' => $params['samesite'] ?? 'Lax',
+ 'path' => $params['path'],
+ 'domain' => $params['domain'],
+ 'secure' => $params['secure'],
+ 'httponly' => $params['httponly'],
+ 'samesite' => $params['samesite'],
]);
$_COOKIE[$sessionName] = $sessionId;
diff --git a/src/library/FOSSBilling/Tools.php b/src/library/FOSSBilling/Tools.php
index 1413f0334..441328e36 100644
--- a/src/library/FOSSBilling/Tools.php
+++ b/src/library/FOSSBilling/Tools.php
@@ -346,7 +346,7 @@ class Tools
$knownInterfaces = [];
}
- if ($interface && $interface !== '0' && in_array($interface, $knownInterfaces)) {
+ if ($interface !== '0' && in_array($interface, $knownInterfaces)) {
return $interface;
}
diff --git a/src/library/FOSSBilling/UpdatePatcher.php b/src/library/FOSSBilling/UpdatePatcher.php
index 703d00a5f..61b3bb9ee 100644
--- a/src/library/FOSSBilling/UpdatePatcher.php
+++ b/src/library/FOSSBilling/UpdatePatcher.php
@@ -113,8 +113,8 @@ class UpdatePatcher implements InjectionAwareInterface
$newConfig['rate_limiter']['whitelist_ips'] = array_values(array_unique(array_merge($newConfig['rate_limiter']['whitelist_ips'], $currentConfig['api']['rate_limit_whitelist'] ?? [])));
$newConfig['debug_and_monitoring'] ??= [];
$newConfig['debug_and_monitoring']['debug'] ??= $newConfig['debug'] ?? false;
- $newConfig['debug_and_monitoring']['log_stacktrace'] ??= $newConfig['log_stacktrace'] ?? true;
- $newConfig['debug_and_monitoring']['stacktrace_length'] ??= $newConfig['stacktrace_length'] ?? 25;
+ $newConfig['debug_and_monitoring']['log_stacktrace'] ??= $newConfig['log_stacktrace'];
+ $newConfig['debug_and_monitoring']['stacktrace_length'] ??= $newConfig['stacktrace_length'];
$newConfig['debug_and_monitoring']['report_errors'] ??= false;
// Instance ID handling
diff --git a/src/library/FOSSBilling/Validate.php b/src/library/FOSSBilling/Validate.php
index 5deda864a..68bfe22da 100644
--- a/src/library/FOSSBilling/Validate.php
+++ b/src/library/FOSSBilling/Validate.php
@@ -43,6 +43,9 @@ class Validate
public function isSldValid(string $sld): bool
{
$sld = ltrim($sld, '.');
+ if ($sld === '') {
+ return false;
+ }
$sld = idn_to_ascii($sld);
if ($sld === false) {
return false;
@@ -68,6 +71,9 @@ class Validate
public function isTldValid(string $tld): bool
{
$tld = ltrim($tld, '.');
+ if ($tld === '') {
+ return false;
+ }
$tld = idn_to_ascii($tld);
if ($tld === false) {
return false;
diff --git a/src/library/Payment/Adapter/ClientBalance.php b/src/library/Payment/Adapter/ClientBalance.php
index ce06ac284..75b2e6b93 100644
--- a/src/library/Payment/Adapter/ClientBalance.php
+++ b/src/library/Payment/Adapter/ClientBalance.php
@@ -53,7 +53,7 @@ class Payment_Adapter_ClientBalance implements FOSSBilling\InjectionAwareInterfa
return true;
}
- public function getHtml($api_admin, $invoice_id, $subscription)
+ public function getHtml($api_admin, $invoice_id, $subscription): string
{
$invoiceModel = $this->di['db']->load('Invoice', $invoice_id);
diff --git a/src/library/Payment/Adapter/PayPalEmail.php b/src/library/Payment/Adapter/PayPalEmail.php
index 85eaf3753..0fa9f2bde 100644
--- a/src/library/Payment/Adapter/PayPalEmail.php
+++ b/src/library/Payment/Adapter/PayPalEmail.php
@@ -350,7 +350,7 @@ document.addEventListener('DOMContentLoaded', function() {
return false;
}
- public function getInvoiceTitle(array $invoice)
+ public function getInvoiceTitle(array $invoice): string
{
$p = [
':id' => sprintf('%05s', $invoice['nr']),
diff --git a/src/library/Payment/Adapter/Stripe.php b/src/library/Payment/Adapter/Stripe.php
index 83cfbd144..29b23dd57 100644
--- a/src/library/Payment/Adapter/Stripe.php
+++ b/src/library/Payment/Adapter/Stripe.php
@@ -126,7 +126,7 @@ class Payment_Adapter_Stripe implements FOSSBilling\InjectionAwareInterface
return Currencies::exists($currency) ? Currencies::getFractionDigits($currency) : 2;
}
- public function getInvoiceTitle(Model_Invoice $invoice)
+ public function getInvoiceTitle(Model_Invoice $invoice): string
{
$invoiceItems = $this->di['db']->getAll('SELECT title from invoice_item WHERE invoice_id = :invoice_id', [':invoice_id' => $invoice->id]);
@@ -153,6 +153,7 @@ class Payment_Adapter_Stripe implements FOSSBilling\InjectionAwareInterface
$tx->updated_at = date('Y-m-d H:i:s');
$this->di['db']->store($tx);
+ // @phpstan-ignore if.alwaysFalse (DEBUG is a runtime constant that may be true during debugging)
if (DEBUG) {
error_log(json_encode($e->getJsonBody()));
}
diff --git a/src/library/PdoSessionHandler.php b/src/library/PdoSessionHandler.php
index b096f4013..64b4b8de2 100644
--- a/src/library/PdoSessionHandler.php
+++ b/src/library/PdoSessionHandler.php
@@ -48,9 +48,6 @@ class PdoSessionHandler implements SessionHandlerInterface
'db_table' => 'session',
];
- if (!array_key_exists('db_table', $dbOptions)) {
- throw new InvalidArgumentException('You must provide the "db_table" option for a PdoSessionStorage.');
- }
if ($pdo->getAttribute(PDO::ATTR_ERRMODE) !== PDO::ERRMODE_EXCEPTION) {
throw new InvalidArgumentException(sprintf('"%s" requires PDO error mode attribute be set to throw Exceptions (i.e. $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION))', self::class));
}
@@ -107,8 +104,6 @@ class PdoSessionHandler implements SessionHandlerInterface
} catch (PDOException $e) {
throw new RuntimeException("PDOException was thrown when trying to manipulate session data: {$e->getMessage()}.", 0, $e);
}
-
- return false;
}
public function read($id): string|false
diff --git a/src/library/Registrar/Adapter/Internetbs.php b/src/library/Registrar/Adapter/Internetbs.php
index 9b47bed69..ce2f17d4b 100644
--- a/src/library/Registrar/Adapter/Internetbs.php
+++ b/src/library/Registrar/Adapter/Internetbs.php
@@ -367,7 +367,7 @@ class Registrar_Adapter_Internetbs extends Registrar_AdapterAbstract
}
if ($this->isTestEnv()) {
- error_log(print_r($result, 1));
+ error_log(print_r($result, true));
}
return $result;
@@ -464,6 +464,8 @@ class Registrar_Adapter_Internetbs extends Registrar_AdapterAbstract
/**
* Checks whether privacy is enabled.
+ *
+ * @phpstan-ignore method.unused (part of API, reserved for future use)
*/
private function _isPrivacyEnabled(Registrar_Domain $domain): bool
{
diff --git a/src/library/Registrar/Adapter/Namecheap.php b/src/library/Registrar/Adapter/Namecheap.php
index e9f3b7a75..294b7f93c 100644
--- a/src/library/Registrar/Adapter/Namecheap.php
+++ b/src/library/Registrar/Adapter/Namecheap.php
@@ -150,14 +150,14 @@ class Registrar_Adapter_Namecheap extends Registrar_AdapterAbstract
$result = simplexml_load_string($data);
- if (isset($result['status']) && strtolower($result['status']) == 'error') {
+ if (isset($result['status']) && strtolower((string) $result['status']) == 'error') {
error_log('Namecheap error: ' . PHP_EOL . $result['error']);
$placeholders = [':action:' => $params['Command'], ':type:' => 'Namecheap'];
throw new Registrar_Exception('Failed to :action: with the :type: registrar, check the error logs for further details', $placeholders);
}
- if (isset($result['status']) && strtolower($result['status']) == 'failed') {
+ if (isset($result['status']) && strtolower((string) $result['status']) == 'failed') {
error_log('Namecheap error: ' . PHP_EOL . $result['actionstatusdesc']);
$placeholders = [':action:' => $params['Command'], ':type:' => 'Namecheap'];
diff --git a/src/library/Registrar/Adapter/Resellerclub.php b/src/library/Registrar/Adapter/Resellerclub.php
index a47154255..2c139ab2d 100644
--- a/src/library/Registrar/Adapter/Resellerclub.php
+++ b/src/library/Registrar/Adapter/Resellerclub.php
@@ -533,11 +533,17 @@ class Registrar_Adapter_Resellerclub extends Registrar_AdapterAbstract
return $this->_makeRequest('contacts/add', $contact, 'POST');
}
+ /**
+ * @phpstan-ignore method.unused (part of API, reserved for future use)
+ */
private function getResellerDetails()
{
return $this->_makeRequest('resellers/details');
}
+ /**
+ * @phpstan-ignore method.unused (part of API, reserved for future use)
+ */
private function getPromoPrices()
{
return $this->_makeRequest('resellers/promo-details');
@@ -549,6 +555,8 @@ class Registrar_Adapter_Resellerclub extends Registrar_AdapterAbstract
* @param array $params
*
* @return stdClass
+ *
+ * @phpstan-ignore method.unused (part of API, reserved for future use)
*/
private function addSubReseller($params)
{
@@ -604,6 +612,9 @@ class Registrar_Adapter_Resellerclub extends Registrar_AdapterAbstract
return $this->_makeRequest('contacts/default', $params, 'POST');
}
+ /**
+ * @phpstan-ignore method.unused (part of API, reserved for future use)
+ */
private function removeCustomer($params): bool
{
$required_params = [
@@ -696,9 +707,6 @@ class Registrar_Adapter_Resellerclub extends Registrar_AdapterAbstract
return $data = $result->getContent(false);
}
$json = $result->toArray(false);
- if (!is_array($json)) {
- return $data = $result->getContent(false);
- }
if (isset($json['status']) && $json['status'] == 'ERROR') {
error_log('ResellerClub error: ' . $json['message']);
@@ -751,8 +759,6 @@ class Registrar_Adapter_Resellerclub extends Registrar_AdapterAbstract
* @param array $params - given params
*
* @return array
- *
- * @throws Registrar_Exception
*/
private function _checkRequiredParams($required_params, $params)
{
diff --git a/src/library/Registrar/Domain/Contact.php b/src/library/Registrar/Domain/Contact.php
index eadc3e56f..8027792aa 100644
--- a/src/library/Registrar/Domain/Contact.php
+++ b/src/library/Registrar/Domain/Contact.php
@@ -125,7 +125,7 @@ class Registrar_Domain_Contact implements Stringable
$bits = explode(' ', (string) $this->name);
- return $bits[0] ?? '';
+ return $bits[0];
}
public function setLastName($param)
diff --git a/src/library/Server/Manager/Plesk.php b/src/library/Server/Manager/Plesk.php
index c1439f4d6..93fbffbad 100644
--- a/src/library/Server/Manager/Plesk.php
+++ b/src/library/Server/Manager/Plesk.php
@@ -138,17 +138,12 @@ class Server_Manager_Plesk extends Server_Manager
}
}
- $id = $this->createClient($account);
- $client = $account->getClient();
-
- if (!$id) {
+ if (!$this->createClient($account)) {
$placeholders = [':action:' => __trans('create account'), ':type:' => 'Plesk'];
throw new Server_Exception('Failed to :action: on the :type: server, check the error logs for further details', $placeholders);
}
- $client->setId((int) $id);
-
$this->setSubscription($account);
// We need to improve the way we handle the IP address before we should enable this.
@@ -237,20 +232,20 @@ class Server_Manager_Plesk extends Server_Manager
*/
public function changeAccountPackage(Server_Account $account, Server_Package $package): bool
{
- $domainId = null;
- $id = $this->modifyClient($account);
- $client = $account->getClient();
- if (!$id) {
+ $result = $this->modifyClient($account);
+ if (!$result) {
throw new Server_Exception('Can\'t modify client');
}
- $client->setId((int) $id);
$account->setPackage($package);
$this->updateSubscription($account);
- if ($account->getReseller()) {
- $this->addNs($account, $domainId);
- }
+ // TODO: Implement NS record management for resellers
+ // This requires fetching the domain ID from Plesk API first
+ // if ($account->getReseller()) {
+ // $domainId = $this->getDomainId($account);
+ // $this->addNs($account, $domainId);
+ // }
return true;
}
@@ -392,6 +387,8 @@ class Server_Manager_Plesk extends Server_Manager
*
* @param Server_Account $account the account for which the IP should be set
* @param string $newIp the new IP address
+ *
+ * @phpstan-ignore method.unused (part of API, reserved for future use)
*/
private function setIp(Server_Account $account, string $newIp): void
{
@@ -647,6 +644,8 @@ class Server_Manager_Plesk extends Server_Manager
* @param string $domainId the ID of the domain for which the NS record should be added
*
* @return bool always returns true
+ *
+ * @phpstan-ignore method.unused (part of API, reserved for future use)
*/
private function addNs(Server_Account $account, string $domainId): bool
{
@@ -663,6 +662,8 @@ class Server_Manager_Plesk extends Server_Manager
* @param string $domainId the ID of the domain for which the NS records should be retrieved
*
* @return array the array of NS record IDs
+ *
+ * @phpstan-ignore method.unused (part of API, reserved for future use)
*/
private function getNs(Server_Account $account, string $domainId): array
{
@@ -689,6 +690,8 @@ class Server_Manager_Plesk extends Server_Manager
* @return bool returns true after the DNS records have been removed
*
* @throws Exception
+ *
+ * @phpstan-ignore method.unused (part of API, reserved for future use)
*/
private function removeDns(array $ns): bool
{
@@ -720,6 +723,8 @@ class Server_Manager_Plesk extends Server_Manager
* @param Server_Account $account the account for which the IP type should be changed
*
* @return bool returns true if the IP type was successfully changed to 'shared', false otherwise
+ *
+ * @phpstan-ignore method.unused (part of API, reserved for future use)
*/
private function changeIpType(Server_Account $account): bool
{
diff --git a/src/library/Server/Package.php b/src/library/Server/Package.php
index 900775543..19a681a2d 100644
--- a/src/library/Server/Package.php
+++ b/src/library/Server/Package.php
@@ -32,12 +32,7 @@ class Server_Package
*/
public function __call(string $name, array $arguments)
{
- if (version_compare(PHP_VERSION, '5.4.0') < 0) {
- $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
- } else {
- // Get only the stack frames we need (PHP 5.4 only).
- $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
- }
+ $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
error_log(sprintf('Calling %s inaccessible method %s from %s::%d', static::class, $name, $backtrace[1]['file'], $backtrace[1]['line']));
return '';
diff --git a/src/load.php b/src/load.php
index a170c8a07..8dd708065 100644
--- a/src/load.php
+++ b/src/load.php
@@ -42,6 +42,7 @@ function checkInstaller(): void
}
// If the config file exists and not install.php, but the install folder does, perform some cleanup.
+ // @phpstan-ignore booleanNot.alwaysTrue (DEBUG is a runtime constant)
if ($filesystem->exists(PATH_CONFIG) && $filesystem->exists(Path::normalize('install')) && !DEBUG) {
$filesystem->remove('install');
}
@@ -54,7 +55,7 @@ function checkSSL(): void
{
global $request;
- if (!empty(Config::getProperty('security.force_https')) && Config::getProperty('security.force_https') && !Environment::isCLI()) {
+ if (Config::getProperty('security.force_https') && !Environment::isCLI()) {
if (!$request->isSecure()) {
(new RedirectResponse('https://' . $request->getHost() . $request->getRequestUri()))->send();
exit;
@@ -159,6 +160,7 @@ function exceptionHandler(Exception|Error $e)
return false;
}
+ // @phpstan-ignore booleanAnd.alwaysFalse, booleanAnd.rightAlwaysFalse (DEBUG is a runtime constant)
if (defined('DEBUG') && DEBUG && $filesystem->exists(PATH_VENDOR)) {
/**
* If advanced debugging is enabled, print Whoops instead of our error page.
@@ -170,6 +172,7 @@ function exceptionHandler(Exception|Error $e)
$prettyPage->addDataTable('FOSSBilling environment', [
'PHP Version' => PHP_VERSION,
'Error code' => $e->getCode(),
+ // @phpstan-ignore nullCoalesce.expr (INSTANCE_ID is a runtime constant that may not be defined during analysis)
'Instance ID' => INSTANCE_ID ?? 'Unknown',
]);
$whoops->pushHandler($prettyPage);
@@ -261,7 +264,9 @@ function init(): void
// Set globals and relevant settings based on the config.
date_default_timezone_set(Config::getProperty('i18n.timezone', 'UTC'));
define('ADMIN_PREFIX', Config::getProperty('admin_area_prefix'));
- define('DEBUG', (bool) Config::getProperty('debug_and_monitoring.debug', false));
+ if (!defined('DEBUG')) {
+ define('DEBUG', (bool) Config::getProperty('debug_and_monitoring.debug', false));
+ }
$pathData = Path::normalize(Config::getProperty('path_data'));
if (Environment::isTesting()) {
$pathData = Path::join(sys_get_temp_dir(), 'fossbilling_test_data');
@@ -312,6 +317,7 @@ function postInit(): void
ini_set('error_log', Path::join(PATH_LOG, 'php_error.log'));
error_reporting(E_ALL);
+ // @phpstan-ignore if.alwaysFalse (DEBUG is a runtime constant that may be true during debugging)
if (DEBUG) {
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
diff --git a/src/modules/Activity/Api/Admin.php b/src/modules/Activity/Api/Admin.php
index 21ce77fd6..35b9c9b1c 100644
--- a/src/modules/Activity/Api/Admin.php
+++ b/src/modules/Activity/Api/Admin.php
@@ -29,11 +29,11 @@ class Admin extends \Api_Abstract
*/
public function log_get_list($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('activity', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('activity', 'view');
$data['min_priority'] ??= 6;
[$sql, $params] = $this->getService()->getSearchQuery($data);
- $pager = $this->di['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
+ $pager = $this->getDi()['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
foreach ($pager['list'] as $key => $item) {
if (isset($item['staff_id'])) {
@@ -58,7 +58,7 @@ class Admin extends \Api_Abstract
*/
public function log($data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('activity', 'manage');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('activity', 'manage');
if (!isset($data['m'])) {
return false;
@@ -83,11 +83,9 @@ class Admin extends \Api_Abstract
*/
public function log_email($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('activity', 'manage');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('activity', 'manage');
if (!isset($data['subject'])) {
- error_log('Email was not logged. Subject not passed');
-
return false;
}
diff --git a/src/modules/Activity/Service.php b/src/modules/Activity/Service.php
index 895e8f87d..9f36469fb 100644
--- a/src/modules/Activity/Service.php
+++ b/src/modules/Activity/Service.php
@@ -72,7 +72,6 @@ class Service implements InjectionAwareInterface
]);
}
- /** EVENTS **/
public static function onAfterClientLogin(\Box_Event $event): void
{
$params = $event->getParameters();
diff --git a/src/modules/Activity/tests/Unit/Api/AdminTest.php b/src/modules/Activity/tests/Unit/Api/AdminTest.php
new file mode 100644
index 000000000..8da32065d
--- /dev/null
+++ b/src/modules/Activity/tests/Unit/Api/AdminTest.php
@@ -0,0 +1,140 @@
+protect(moduleService(['activity' => $serviceStub]));
+
+ $api = new Api_Handler(new Model_Admin());
+ $api->setDi($di);
+ $di['api_admin'] = $api;
+
+ $activity = new Box\Mod\Activity\Api\Admin();
+ $activity->setDi($di);
+ $activity->setService($serviceStub);
+
+ $simpleResultArr = [
+ 'list' => [
+ [
+ 'id' => 1,
+ 'staff_id' => 1,
+ 'staff_name' => 'Joe',
+ 'staff_email' => 'example@example.com',
+ ],
+ ],
+ ];
+
+ $serviceMock = Mockery::mock(Box\Mod\Activity\Service::class);
+ /** @var Mockery\Expectation $expectation1 */
+ $expectation1 = $serviceMock->shouldReceive('getSearchQuery');
+ $expectation1->atLeast()->once();
+ $expectation1->andReturn(['String', []]);
+
+ $paginatorMock = Mockery::mock(FOSSBilling\Pagination::class);
+ /** @var Mockery\Expectation $expectation3 */
+ $expectation3 = $paginatorMock->shouldReceive('getPaginatedResultSet');
+ $expectation3->atLeast()->once();
+ $expectation3->andReturn($simpleResultArr);
+
+ $model = new Model_ActivitySystem();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $di['pager'] = $paginatorMock;
+ $activity->setService($serviceMock);
+ $activity->log_get_list([]);
+});
+
+test('log get list with client user', function (): void {
+ $serviceStub = Mockery::mock(Box\Mod\Activity\Service::class);
+ $paginatorStub = Mockery::mock(FOSSBilling\Pagination::class);
+ $di = container();
+ $di['pager'] = $paginatorStub;
+ $di['mod_service'] = $di->protect(moduleService(['activity' => $serviceStub]));
+
+ $api = new Api_Handler(new Model_Admin());
+ $api->setDi($di);
+ $di['api_admin'] = $api;
+
+ $activity = new Box\Mod\Activity\Api\Admin();
+ $activity->setDi($di);
+ $activity->setService($serviceStub);
+
+ $simpleResultArr = [
+ 'list' => [
+ [
+ 'id' => 1,
+ 'client_id' => 1,
+ 'client_name' => 'Joe',
+ 'client_email' => 'example@example.com',
+ ],
+ ],
+ ];
+
+ $serviceMock = Mockery::mock(Box\Mod\Activity\Service::class);
+ /** @var Mockery\Expectation $expectation1 */
+ $expectation1 = $serviceMock->shouldReceive('getSearchQuery');
+ $expectation1->atLeast()->once();
+ $expectation1->andReturn(['String', []]);
+
+ $paginatorMock = Mockery::mock(FOSSBilling\Pagination::class);
+ /** @var Mockery\Expectation $expectation3 */
+ $expectation3 = $paginatorMock->shouldReceive('getPaginatedResultSet');
+ $expectation3->atLeast()->once();
+ $expectation3->andReturn($simpleResultArr);
+
+ $model = new Model_ActivitySystem();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $di['pager'] = $paginatorMock;
+ $activity->setService($serviceMock);
+ $activity->log_get_list([]);
+});
+
+test('log with empty m parameter returns false', function (): void {
+ $di = container();
+
+ $activity = new Box\Mod\Activity\Api\Admin();
+ $activity->setDi($di);
+ $result = $activity->log([]);
+
+ expect($result)->toBeFalse('Empty array key m');
+});
+
+test('log email with subject', function (): void {
+ $service = Mockery::mock(Box\Mod\Activity\Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ /** @var Mockery\Expectation $expectation */
+ $expectation = $service->shouldReceive('logEmail');
+ $expectation->atLeast()->once();
+ $expectation->andReturn(true);
+
+ $di = container();
+
+ $adminApi = new Box\Mod\Activity\Api\Admin();
+ $adminApi->setService($service);
+ $adminApi->setDi($di);
+ $result = $adminApi->log_email(['subject' => 'Proper subject']);
+
+ expect($result)->toBeTrue('Log_email did not returned true');
+});
+
+test('log email without subject returns false', function (): void {
+ $activity = new Box\Mod\Activity\Api\Admin();
+ $result = $activity->log_email([]);
+
+ expect($result)->toBeFalse();
+});
diff --git a/src/modules/Activity/tests/Unit/Controller/AdminTest.php b/src/modules/Activity/tests/Unit/Controller/AdminTest.php
new file mode 100644
index 000000000..e8b24137a
--- /dev/null
+++ b/src/modules/Activity/tests/Unit/Controller/AdminTest.php
@@ -0,0 +1,71 @@
+setDi($di);
+ $result = $controller->getDi();
+ expect($result)->toEqual($di);
+});
+
+test('fetchNavigation returns array', function (): void {
+ $controller = new Box\Mod\Activity\Controller\Admin();
+ $di = container();
+ $link = 'activity';
+
+ $urlMock = Mockery::mock('Box_Url');
+ /** @var Mockery\Expectation $expectation */
+ $expectation = $urlMock->shouldReceive('adminLink');
+ $expectation->atLeast()->once();
+ $expectation->andReturn('https://fossbilling.org/index.php?_url=/' . $link);
+ $di['url'] = $urlMock;
+
+ $controller->setDi($di);
+
+ $result = $controller->fetchNavigation();
+ expect($result)->toBeArray();
+});
+
+test('register configures routes', function (): void {
+ $controller = new Box\Mod\Activity\Controller\Admin();
+ $boxAppMock = Mockery::mock('\Box_App');
+ /** @var Mockery\Expectation $expectation */
+ $expectation = $boxAppMock->shouldReceive('get');
+ $expectation->atLeast()->once();
+ $expectation->with('/activity', 'get_index', [], Box\Mod\Activity\Controller\Admin::class);
+
+ /* @var \Box_App $boxAppMock */
+ $controller->register($boxAppMock);
+});
+
+test('getIndex renders activity index', function (): void {
+ $controller = new Box\Mod\Activity\Controller\Admin();
+ $boxAppMock = Mockery::mock('\Box_App');
+ /** @var Mockery\Expectation $expectation */
+ $expectation = $boxAppMock->shouldReceive('render');
+ $expectation->atLeast()->once();
+ $expectation->with('mod_activity_index');
+
+ $di = container();
+ $di['is_admin_logged'] = true;
+
+ $controller->setDi($di);
+
+ /* @var \Box_App $boxAppMock */
+ $controller->get_index($boxAppMock);
+});
diff --git a/src/modules/Activity/tests/Unit/ServiceTest.php b/src/modules/Activity/tests/Unit/ServiceTest.php
new file mode 100644
index 000000000..2e62737a6
--- /dev/null
+++ b/src/modules/Activity/tests/Unit/ServiceTest.php
@@ -0,0 +1,139 @@
+ [
+ [[], 'FROM activity_system ', true],
+ [['user_filter' => 'only_clients'], 'm.client_id IS NOT NULL', true],
+ [['user_filter' => 'only_staff'], 'm.admin_id IS NOT NULL', true],
+ [['priority' => '2'], 'm.priority =', true],
+ [['search' => 'keyword'], 'm.message LIKE ', true],
+ [['min_priority' => 6], 'm.priority <= :min_priority', true],
+ [['priority' => 6], 'm.priority = :priority', true],
+ // When both priority and min_priority are set, priority takes precedence
+ [['priority' => 5, 'min_priority' => 3], 'm.priority = :priority', true],
+ [['priority' => 5, 'min_priority' => 3], 'm.priority <= :min_priority', false],
+]);
+
+test('dependency injection', function (): void {
+ $service = new Box\Mod\Activity\Service();
+
+ $di = container();
+ $dbMock = Mockery::mock('Box_Database');
+
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+ $result = $service->getDi();
+ expect($result)->toEqual($di);
+});
+
+test('get search query', function (array $filterKey, string $search, bool $expected): void {
+ $di = container();
+ $service = new Box\Mod\Activity\Service();
+ $service->setDi($di);
+ $result = $service->getSearchQuery($filterKey);
+ expect($result[0])->toBeString();
+ expect($result[1])->toBeArray();
+ expect(str_contains((string) $result[0], $search))->toEqual($expected);
+})->with('searchFilters');
+
+test('log email', function (): void {
+ $service = new Box\Mod\Activity\Service();
+ $data = [
+ 'client_id' => 1,
+ 'sender' => 'sender',
+ 'recipients' => 'recipients',
+ 'subject' => 'subject',
+ 'content_html' => 'html',
+ 'content_text' => 'text',
+ ];
+
+ $di = container();
+ $dbalMock = Mockery::mock(Doctrine\DBAL\Connection::class);
+ $dbalMock->shouldReceive('insert')
+ ->once()
+ ->with('activity_client_email', Mockery::on(static fn (array $values): bool => $values['client_id'] === $data['client_id']
+ && $values['sender'] === $data['sender']
+ && $values['recipients'] === $data['recipients']
+ && $values['subject'] === $data['subject']
+ && $values['content_html'] === $data['content_html']
+ && $values['content_text'] === $data['content_text']
+ && isset($values['created_at'])))
+ ->andReturn(1);
+
+ $di['dbal'] = $dbalMock;
+ $service->setDi($di);
+
+ $result = $service->logEmail($data['subject'], $data['client_id'], $data['sender'], $data['recipients'], $data['content_html'], $data['content_text']);
+ expect($result)->toBeTrue();
+});
+
+test('to api array', function (): void {
+ $service = new Box\Mod\Activity\Service();
+ $clientHistoryModel = new Model_ActivityClientHistory();
+ $clientHistoryModel->loadBean(new Tests\Helpers\DummyBean());
+ $clientHistoryModel->client_id = 1;
+
+ $resultMock = Mockery::mock(Doctrine\DBAL\Result::class);
+ $resultMock->shouldReceive('fetchAssociative')
+ ->once()
+ ->andReturn([
+ 'id' => 1,
+ 'first_name' => 'Test',
+ 'last_name' => 'Client',
+ 'email' => 'client@example.test',
+ ]);
+
+ $dbalMock = Mockery::mock(Doctrine\DBAL\Connection::class);
+ $dbalMock->shouldReceive('executeQuery')
+ ->once()
+ ->with('SELECT id, first_name, last_name, email FROM client WHERE id = ?', [$clientHistoryModel->client_id])
+ ->andReturn($resultMock);
+
+ $di = container();
+ $di['dbal'] = $dbalMock;
+
+ $service->setDi($di);
+
+ $result = $service->toApiArray($clientHistoryModel);
+ expect($result)->toBeArray();
+ expect($result)->toHaveKey('id');
+ expect($result)->toHaveKey('ip');
+ expect($result)->toHaveKey('created_at');
+
+ expect($result['client'])->toBeArray();
+ expect($result['client'])->toHaveKey('id');
+ expect($result['client'])->toHaveKey('first_name');
+ expect($result['client'])->toHaveKey('last_name');
+ expect($result['client'])->toHaveKey('email');
+});
+
+test('remove by client', function (): void {
+ $service = new Box\Mod\Activity\Service();
+ $clientModel = new Model_Client();
+ $clientModel->loadBean(new Tests\Helpers\DummyBean());
+ $clientModel->id = 1;
+
+ $dbalMock = Mockery::mock(Doctrine\DBAL\Connection::class);
+ $dbalMock->shouldReceive('executeStatement')
+ ->once()
+ ->with('DELETE FROM activity_system WHERE client_id = ?', [$clientModel->id])
+ ->andReturn(1);
+
+ $di = container();
+ $di['dbal'] = $dbalMock;
+
+ $service->setDi($di);
+
+ $service->rmByClient($clientModel);
+});
diff --git a/src/modules/Antispam/Api/Admin.php b/src/modules/Antispam/Api/Admin.php
index 816c161b4..d4dd249c2 100644
--- a/src/modules/Antispam/Api/Admin.php
+++ b/src/modules/Antispam/Api/Admin.php
@@ -16,9 +16,9 @@ class Admin extends \Api_Abstract
{
public function get_config($data): array
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('antispam', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('antispam', 'view');
- $config = $this->di['mod_config']('Antispam');
+ $config = $this->getDi()['mod_config']('Antispam');
return [
'block_ips' => $config['block_ips'] ?? false,
@@ -70,27 +70,27 @@ class Admin extends \Api_Abstract
private function saveBlockedIpsConfig(array $blocked_ips, bool $enabled): void
{
- $config = $this->di['mod_config']('Antispam');
+ $config = $this->getDi()['mod_config']('Antispam');
$config['block_ips'] = $enabled;
$config['blocked_ips'] = implode(PHP_EOL, $blocked_ips);
$config['ext'] = 'mod_antispam';
- $this->di['mod_service']('extension')->setConfig($config);
+ $this->getDi()['mod_service']('extension')->setConfig($config);
}
public function block_ip($data): array
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('antispam', 'manage');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('antispam', 'manage');
$ip = $this->normalizeIp($data['ip'] ?? null);
- $config = $this->di['mod_config']('Antispam');
+ $config = $this->getDi()['mod_config']('Antispam');
$blocked_ips = $this->getBlockedIpsFromConfig($config);
if (in_array($ip, $blocked_ips, true)) {
throw new \FOSSBilling\InformationException(':ip is already blocked.', [':ip' => $ip]);
}
- if ((string) $this->di['request']->getClientIp() === $ip) {
+ if ((string) $this->getDi()['request']->getClientIp() === $ip) {
throw new \FOSSBilling\InformationException('You cannot block :ip as it is the IP you are making requests from.', [':ip' => $ip]);
}
@@ -102,11 +102,11 @@ class Admin extends \Api_Abstract
public function unblock_ip($data): array
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('antispam', 'manage');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('antispam', 'manage');
$ip = $this->normalizeIp($data['ip'] ?? null);
- $config = $this->di['mod_config']('Antispam');
+ $config = $this->getDi()['mod_config']('Antispam');
$blocked_ips = $this->getBlockedIpsFromConfig($config);
$key = array_search($ip, $blocked_ips, true);
@@ -122,9 +122,9 @@ class Admin extends \Api_Abstract
public function get_blocked_ips($data): array
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('antispam', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('antispam', 'view');
- $config = $this->di['mod_config']('Antispam');
+ $config = $this->getDi()['mod_config']('Antispam');
$blocked_ips = $this->getBlockedIpsFromConfig($config);
return [
diff --git a/src/modules/Antispam/Api/Guest.php b/src/modules/Antispam/Api/Guest.php
index 8f5acb8eb..e3f89ae0b 100644
--- a/src/modules/Antispam/Api/Guest.php
+++ b/src/modules/Antispam/Api/Guest.php
@@ -19,7 +19,7 @@ class Guest extends \Api_Abstract
*/
public function recaptcha($data): array
{
- $config = $this->di['mod_config']('Antispam');
+ $config = $this->getDi()['mod_config']('Antispam');
return [
'publickey' => $config['captcha_recaptcha_publickey'] ?? null,
diff --git a/src/modules/Antispam/Service.php b/src/modules/Antispam/Service.php
index b18c28523..594d4a125 100644
--- a/src/modules/Antispam/Service.php
+++ b/src/modules/Antispam/Service.php
@@ -127,7 +127,6 @@ class Service implements InjectionAwareInterface
{
$di = $event->getDi();
$params = $event->getParameters();
- $params = is_array($params) ? $params : [];
$data = [
'ip' => $params['ip'] ?? null,
diff --git a/src/modules/Antispam/tests/E2E/ApiGuestTest.php b/src/modules/Antispam/tests/E2E/ApiGuestTest.php
new file mode 100644
index 000000000..6527972e9
--- /dev/null
+++ b/src/modules/Antispam/tests/E2E/ApiGuestTest.php
@@ -0,0 +1,65 @@
+ 'mod', 'id' => 'antispam']);
+ expect($result->wasSuccessful())->toBeTrue($result);
+
+ $result = Tests\Helpers\ApiClient::request('admin/extension/config_save', ['ext' => 'mod_antispam', 'check_temp_emails' => true]);
+ expect($result->wasSuccessful())->toBeTrue($result);
+
+ $password = 'A1a' . bin2hex(random_bytes(6));
+ $result = Tests\Helpers\ApiClient::request('guest/client/create', [
+ 'email' => 'email@yopmail.net',
+ 'first_name' => 'Test',
+ 'password' => $password,
+ 'password_confirm' => $password,
+ ]);
+
+ expect($result->wasSuccessful())->toBeFalse();
+ expect($result->getErrorMessage())->toEqual('Disposable email addresses are not allowed');
+
+ if ($result->wasSuccessful()) {
+ $id = intval($result->getResult());
+ Tests\Helpers\ApiClient::request('admin/client/delete', ['id' => $id]);
+ }
+});
+
+test('stop forum spam', function (): void {
+ $result = Tests\Helpers\ApiClient::request('admin/extension/activate', ['type' => 'mod', 'id' => 'antispam']);
+ expect($result->wasSuccessful())->toBeTrue($result);
+
+ $result = Tests\Helpers\ApiClient::request('admin/extension/config_save', ['ext' => 'mod_antispam', 'sfs' => true]);
+ expect($result->wasSuccessful())->toBeTrue($result);
+
+ $password = 'A1a' . bin2hex(random_bytes(6));
+ $result = Tests\Helpers\ApiClient::request('guest/client/create', [
+ 'email' => 'email@example.com',
+ 'first_name' => 'Test',
+ 'password' => $password,
+ 'password_confirm' => $password,
+ ]);
+
+ expect($result->wasSuccessful())->toBeTrue($result);
+ expect($result->getResult())->toBeNumeric();
+
+ $id = intval($result->getResult());
+
+ $result = Tests\Helpers\ApiClient::request('admin/client/delete', ['id' => $id]);
+ expect($result->wasSuccessful())->toBeTrue($result);
+ expect($result->getResult())->toBeTrue();
+});
diff --git a/src/modules/Antispam/tests/Unit/Api/GuestTest.php b/src/modules/Antispam/tests/Unit/Api/GuestTest.php
new file mode 100644
index 000000000..85a864f63
--- /dev/null
+++ b/src/modules/Antispam/tests/Unit/Api/GuestTest.php
@@ -0,0 +1,126 @@
+ [
+ [
+ [
+ 'captcha_recaptcha_publickey' => 1234,
+ 'captcha_enabled' => true,
+ ],
+ [
+ 'publickey' => 1234,
+ 'enabled' => true,
+ 'version' => null,
+ 'captcha_provider' => 'recaptcha_v2',
+ 'recaptcha_v3_threshold' => 0.5,
+ 'turnstile_site_key' => null,
+ 'hcaptcha_site_key' => null,
+ ],
+ ],
+ [
+ [
+ 'captcha_enabled' => true,
+ ],
+ [
+ 'publickey' => null,
+ 'enabled' => true,
+ 'version' => null,
+ 'captcha_provider' => 'recaptcha_v2',
+ 'recaptcha_v3_threshold' => 0.5,
+ 'turnstile_site_key' => null,
+ 'hcaptcha_site_key' => null,
+ ],
+ ],
+ [
+ [
+ 'captcha_recaptcha_publickey' => 1234,
+ 'captcha_enabled' => false,
+ 'captcha_version' => 2,
+ ],
+ [
+ 'publickey' => 1234,
+ 'enabled' => false,
+ 'version' => 2,
+ 'captcha_provider' => 'recaptcha_v2',
+ 'recaptcha_v3_threshold' => 0.5,
+ 'turnstile_site_key' => null,
+ 'hcaptcha_site_key' => null,
+ ],
+ ],
+ [
+ [
+ 'captcha_enabled' => false,
+ ],
+ [
+ 'publickey' => null,
+ 'enabled' => false,
+ 'version' => null,
+ 'captcha_provider' => 'recaptcha_v2',
+ 'recaptcha_v3_threshold' => 0.5,
+ 'turnstile_site_key' => null,
+ 'hcaptcha_site_key' => null,
+ ],
+ ],
+ [
+ [
+ 'captcha_enabled' => true,
+ 'captcha_provider' => 'turnstile',
+ 'turnstile_site_key' => 'abc',
+ ],
+ [
+ 'publickey' => null,
+ 'enabled' => true,
+ 'version' => null,
+ 'captcha_provider' => 'turnstile',
+ 'recaptcha_v3_threshold' => 0.5,
+ 'turnstile_site_key' => 'abc',
+ 'hcaptcha_site_key' => null,
+ ],
+ ],
+ [
+ [
+ 'captcha_enabled' => true,
+ 'captcha_provider' => 'hcaptcha',
+ 'hcaptcha_site_key' => 'abc',
+ ],
+ [
+ 'publickey' => null,
+ 'enabled' => true,
+ 'version' => null,
+ 'captcha_provider' => 'hcaptcha',
+ 'recaptcha_v3_threshold' => 0.5,
+ 'turnstile_site_key' => null,
+ 'hcaptcha_site_key' => 'abc',
+ ],
+ ],
+]);
+
+test('dependency injection', function (): void {
+ $api = new Box\Mod\Antispam\Api\Guest();
+ $di = container();
+ $api->setDi($di);
+ $getDi = $api->getDi();
+ expect($getDi)->toEqual($di);
+});
+
+test('recaptcha', function (array $config, array $expected): void {
+ $api = new Box\Mod\Antispam\Api\Guest();
+ $di = container();
+ $di['mod_config'] = $di->protect(fn (): array => $config);
+
+ $api->setDi($di);
+ $result = $api->recaptcha([]);
+
+ expect($result)->toEqual($expected);
+})->with('recaptcha config');
diff --git a/src/modules/Antispam/tests/Unit/ServiceTest.php b/src/modules/Antispam/tests/Unit/ServiceTest.php
new file mode 100644
index 000000000..600ad82d3
--- /dev/null
+++ b/src/modules/Antispam/tests/Unit/ServiceTest.php
@@ -0,0 +1,122 @@
+setDi($di);
+ $getDi = $service->getDi();
+ expect($getDi)->toEqual($di);
+});
+
+test('on before client sign up', function (): void {
+ $service = new Box\Mod\Antispam\Service();
+ $spamCheckerService = Mockery::mock(Box\Mod\Antispam\Service::class);
+ $spamCheckerService->shouldReceive('isBlockedIp')
+ ->atLeast()->once();
+ $spamCheckerService->shouldReceive('isSpam')
+ ->atLeast()->once();
+ $spamCheckerService->shouldReceive('isTemp')
+ ->atLeast()->once();
+ $spamCheckerService->shouldReceive('checkHoneypot')
+ ->atLeast()->once();
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $spamCheckerService);
+ $boxEventMock = Mockery::mock('\Box_Event');
+ $boxEventMock->shouldReceive('getDi')
+ ->atLeast()->once()
+ ->andReturn($di);
+
+ $service->onBeforeClientSignUp($boxEventMock);
+});
+
+test('on before guest public ticket open', function (): void {
+ $service = new Box\Mod\Antispam\Service();
+ $spamCheckerService = Mockery::mock(Box\Mod\Antispam\Service::class);
+ $spamCheckerService->shouldReceive('isBlockedIp')
+ ->atLeast()->once();
+ $spamCheckerService->shouldReceive('isSpam')
+ ->atLeast()->once();
+ $spamCheckerService->shouldReceive('isTemp')
+ ->atLeast()->once();
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $spamCheckerService);
+ $boxEventMock = Mockery::mock('\Box_Event');
+ $boxEventMock->shouldReceive('getDi')
+ ->atLeast()->once()
+ ->andReturn($di);
+
+ $service->onBeforeGuestPublicTicketOpen($boxEventMock);
+});
+
+test('is blocked ip ip not blocked', function (): void {
+ $service = new Box\Mod\Antispam\Service();
+ $clientIp = '214.1.4.99';
+ $modConfig = [
+ 'block_ips' => true,
+ 'blocked_ips' => '1.1.1.1' . PHP_EOL . '2.2.2.2',
+ ];
+
+ $di = container();
+ $di['request'] = Request::createFromGlobals();
+ $di['mod_config'] = $di->protect(function ($modName) use ($modConfig) {
+ if ($modName == 'Antispam') {
+ return $modConfig;
+ }
+ });
+
+ $boxEventMock = Mockery::mock('\Box_Event');
+ $boxEventMock->shouldReceive('getDi')
+ ->atLeast()->once()
+ ->andReturn($di);
+
+ $service->isBlockedIp($boxEventMock);
+});
+
+test('is blocked ip block ips not enabled', function (): void {
+ $service = new Box\Mod\Antispam\Service();
+ $modConfig = [
+ 'block_ips' => false,
+ ];
+
+ $di = container();
+ $di['mod_config'] = $di->protect(function ($modName) use ($modConfig) {
+ if ($modName == 'Antispam') {
+ return $modConfig;
+ }
+ });
+
+ $boxEventMock = Mockery::mock('\Box_Event');
+ $boxEventMock->shouldReceive('getDi')
+ ->atLeast()->once()
+ ->andReturn($di);
+
+ $service->isBlockedIp($boxEventMock);
+});
+
+dataset('spam responses', fn() => [
+ [
+ '{"success" : "true", "username" : {"appears" : "true" }}', 'Your username is blacklisted in the Stop Forum Spam database',
+ ],
+ [
+ '{"success" : "true", "email" : {"appears" : "true" }}', 'Your e-mail is blacklisted in the Stop Forum Spam database',
+ ],
+ [
+ '{"success" : "true", "ip" : {"appears" : "true" }}', 'Your IP address is blacklisted in the Stop Forum Spam database',
+ ],
+]);
diff --git a/src/modules/Api/Controller/Client.php b/src/modules/Api/Controller/Client.php
index 4d2e113e8..3d37bd7b1 100644
--- a/src/modules/Api/Controller/Client.php
+++ b/src/modules/Api/Controller/Client.php
@@ -231,10 +231,8 @@ class Client implements InjectionAwareInterface
if ($isLoginMethod && !$isAjax && ($isStaffLogin || $isClientLogin)) {
if ($isStaffLogin) {
$redirectUrl = $this->di['url']->adminLink('');
- } elseif ($isClientLogin) {
- $redirectUrl = $this->di['url']->link('');
} else {
- $redirectUrl = '/';
+ $redirectUrl = $this->di['url']->link('');
}
return new RedirectResponse($redirectUrl);
diff --git a/src/modules/Api/tests/Unit/Controller/ClientTest.php b/src/modules/Api/tests/Unit/Controller/ClientTest.php
new file mode 100644
index 000000000..6b7dad5cb
--- /dev/null
+++ b/src/modules/Api/tests/Unit/Controller/ClientTest.php
@@ -0,0 +1,284 @@
+calls[] = [$policy, $subject, $tokens];
+
+ return new FOSSBilling\Security\RateLimitResult($policy, false, 100, 99);
+ }
+
+ public function consumeOrThrow(string $policy, string $subject, int $tokens = 1): FOSSBilling\Security\RateLimitResult
+ {
+ return $this->consume($policy, $subject, $tokens);
+ }
+}
+
+class ClientTestDefaultApiDouble
+{
+ public function testMethod(array $params): array
+ {
+ return ['ok' => true];
+ }
+}
+
+class ClientTestSessionDouble
+{
+ public function __construct(private array $data)
+ {
+ }
+
+ public function get(string $key): mixed
+ {
+ return $this->data[$key] ?? null;
+ }
+
+ public function set(string $key, mixed $value): void
+ {
+ $this->data[$key] = $value;
+ }
+}
+
+class ClientTestUpdateFinalizationDouble
+{
+ public function isRequired(): bool
+ {
+ return false;
+ }
+
+ public function isAdminApiCallAllowed(string $class, string $method): bool
+ {
+ return true;
+ }
+}
+
+class TestableClient extends Client
+{
+ public bool $hasValidSession = false;
+ public bool $shouldUseTokenLogin = false;
+ public bool $shouldFailTokenLogin = false;
+ public bool $shouldFailCsrf = false;
+ public array $calls = [];
+ public mixed $renderedData = null;
+ public ?Exception $renderedException = null;
+ public ?Response $sentResponse = null;
+
+ #[\Override]
+ public function renderJson($data = null, ?\Exception $e = null): Response
+ {
+ $this->renderedData = $data;
+ $this->renderedException = $e;
+
+ return new JsonResponse(['result' => $data, 'error' => $e?->getMessage()]);
+ }
+
+ #[\Override]
+ protected function sendResponse(Response $response): Response
+ {
+ $this->sentResponse = $response;
+
+ return $response;
+ }
+
+ #[\Override]
+ protected function isRoleLoggedIn($role): bool
+ {
+ if (!$this->hasValidSession) {
+ throw new Exception('Client is not logged in');
+ }
+
+ return true;
+ }
+
+ #[\Override]
+ protected function _tryTokenLogin(string $routeRole): void
+ {
+ $this->calls[] = 'token';
+
+ if ($this->shouldFailTokenLogin) {
+ throw new InformationException('Authentication Failed', null, 204);
+ }
+ }
+
+ #[\Override]
+ protected function shouldUseTokenLogin(string $routeRole): bool
+ {
+ return $this->shouldUseTokenLogin;
+ }
+
+ #[\Override]
+ public function _checkCSRFToken(): bool
+ {
+ $this->calls[] = 'csrf';
+
+ if ($this->shouldFailCsrf) {
+ throw new InformationException('CSRF token invalid', null, 403);
+ }
+
+ return true;
+ }
+}
+
+function invokeApiCall(TestableClient $controller, string $role, string $class, string $method, array $params): void
+{
+ $reflection = new ReflectionMethod(Client::class, '_apiCall');
+ $reflection->invoke($controller, $role, $class, $method, $params);
+}
+
+function createTestController(array $sessionData = [], ?object $api = null): array
+{
+ $request = Mockery::mock(Request::class);
+ $request->shouldReceive('getClientIp')->andReturn('127.0.0.1');
+ $request->shouldReceive('isXmlHttpRequest')->byDefault()->andReturn(false);
+
+ $rateLimitCalls = new ArrayObject();
+ $rateLimiter = new ClientTestRateLimiterDouble($rateLimitCalls);
+ $api ??= new ClientTestDefaultApiDouble();
+
+ $di = new Pimple\Container();
+ $di['request'] = $request;
+ $di['rate_limiter'] = $rateLimiter;
+ $di['session'] = new ClientTestSessionDouble($sessionData);
+ $di['update_finalization'] = new ClientTestUpdateFinalizationDouble();
+ $di['api'] = $di->protect(fn (string $role): object => $api);
+
+ $controller = new TestableClient();
+ $controller->setDi($di);
+
+ $_GET['_url'] = '/api/client/test/test_method';
+ $_POST = [];
+ $_COOKIE = [];
+
+ return [$controller, $rateLimitCalls];
+}
+
+uses()->beforeEach(function (): void {
+ $this->serverBackup = $_SERVER;
+ $this->getBackup = $_GET;
+ $this->postBackup = $_POST;
+ $this->cookieBackup = $_COOKIE;
+})->afterEach(function (): void {
+ $_SERVER = $this->serverBackup;
+ $_GET = $this->getBackup;
+ $_POST = $this->postBackup;
+ $_COOKIE = $this->cookieBackup;
+});
+
+test('token authenticated request bypasses CSRF check', function (): void {
+ [$controller] = createTestController();
+ $controller->hasValidSession = false;
+ $controller->shouldUseTokenLogin = true;
+
+ invokeApiCall($controller, 'client', 'test', 'testMethod', []);
+
+ expect($controller->renderedData)->toBe(['ok' => true]);
+ expect($controller->renderedException)->toBeNull();
+ expect($controller->calls)->toBe(['token']);
+});
+
+test('token authenticated request bypasses CSRF even with existing session', function (): void {
+ [$controller] = createTestController();
+ $controller->hasValidSession = true;
+ $controller->shouldUseTokenLogin = true;
+ $controller->shouldFailCsrf = true;
+
+ invokeApiCall($controller, 'admin', 'test', 'testMethod', []);
+
+ expect($controller->renderedData)->toBe(['ok' => true]);
+ expect($controller->renderedException)->toBeNull();
+ expect($controller->calls)->toBe(['token']);
+});
+
+test('token authentication failure consumes pre-auth rate limit', function (): void {
+ [$controller, $rateLimitCalls] = createTestController();
+ $controller->shouldUseTokenLogin = true;
+ $controller->shouldFailTokenLogin = true;
+
+ try {
+ invokeApiCall($controller, 'client', 'test', 'testMethod', []);
+ expect(true)->toBeFalse('Expected token authentication to fail');
+ } catch (InformationException $e) {
+ expect($e->getCode())->toBe(204);
+ }
+
+ expect($rateLimitCalls->getArrayCopy())->toBe([['api_authenticated_ip', '127.0.0.1', 1]]);
+ expect($controller->calls)->toBe(['token']);
+});
+
+test('missing session consumes pre-auth rate limit', function (): void {
+ [$controller, $rateLimitCalls] = createTestController();
+ $controller->hasValidSession = false;
+
+ try {
+ invokeApiCall($controller, 'client', 'test', 'testMethod', []);
+ expect(true)->toBeFalse('Expected session authentication to fail');
+ } catch (InformationException $e) {
+ expect($e->getCode())->toBe(201);
+ }
+
+ expect($rateLimitCalls->getArrayCopy())->toBe([['api_authenticated_ip', '127.0.0.1', 1]]);
+ expect($controller->calls)->toBe([]);
+});
+
+test('session authenticated request still requires CSRF token', function (): void {
+ [$controller, $rateLimitCalls] = createTestController();
+ $controller->hasValidSession = true;
+ $controller->shouldFailCsrf = true;
+
+ try {
+ invokeApiCall($controller, 'client', 'test', 'testMethod', []);
+ expect(true)->toBeFalse('Expected CSRF authentication to fail');
+ } catch (InformationException $e) {
+ expect($e->getCode())->toBe(403);
+ }
+
+ expect($rateLimitCalls->getArrayCopy())->toBe([['api_authenticated_ip', '127.0.0.1', 1]]);
+ expect($controller->calls)->toBe(['csrf']);
+});
+
+test('guest request ignores token auth credentials', function (): void {
+ [$controller] = createTestController();
+ $controller->hasValidSession = true;
+ $controller->shouldUseTokenLogin = true;
+
+ invokeApiCall($controller, 'guest', 'test', 'testMethod', []);
+
+ expect($controller->renderedData)->toBe(['ok' => true]);
+ expect($controller->renderedException)->toBeNull();
+ expect($controller->calls)->toBe([]);
+});
+
+test('raw response bypasses JSON rendering', function (): void {
+ $response = new Response('pdf-bytes', 200, ['Content-Type' => 'application/pdf']);
+ $api = new readonly class($response) {
+ public function __construct(private Response $response)
+ {
+ }
+
+ public function testMethod(array $params): Response
+ {
+ return $this->response;
+ }
+ };
+
+ [$controller] = createTestController(api: $api);
+
+ invokeApiCall($controller, 'guest', 'test', 'testMethod', []);
+
+ expect($controller->sentResponse)->toBe($response);
+ expect($controller->renderedData)->toBeNull();
+ expect($controller->renderedException)->toBeNull();
+});
diff --git a/src/modules/Api/tests/Unit/ControllerClientTest.php b/src/modules/Api/tests/Unit/ControllerClientTest.php
new file mode 100644
index 000000000..0d4f37cba
--- /dev/null
+++ b/src/modules/Api/tests/Unit/ControllerClientTest.php
@@ -0,0 +1,189 @@
+getMethod($method);
+
+ return $reflectionMethod->invokeArgs($instance, $args);
+}
+
+function createControllerDiWithRequest(): Pimple\Container
+{
+ $di = new Pimple\Container();
+ $di['request'] = Request::create('/', 'GET', [], [], [], $_SERVER);
+
+ return $di;
+}
+
+function buildAdminModel(int $id, string $apiToken, string $role): Model_Admin
+{
+ $admin = new Model_Admin();
+ $bean = new stdClass();
+ $bean->id = $id;
+ $bean->api_token = $apiToken;
+ $bean->role = $role;
+ $bean->status = Model_Admin::STATUS_ACTIVE;
+
+ $property = new ReflectionProperty(RedBeanPHP\SimpleModel::class, 'bean');
+ $property->setValue($admin, $bean);
+
+ return $admin;
+}
+
+readonly class CronStaffServiceDouble
+{
+ public function __construct(private Model_Admin $cronAdmin)
+ {
+ }
+
+ public function getCronAdmin(): Model_Admin
+ {
+ return $this->cronAdmin;
+ }
+}
+
+uses()->beforeEach(function (): void {
+ $this->serverBackup = $_SERVER;
+ unset($_SERVER['HTTP_AUTHORIZATION'], $_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']);
+})->afterEach(function (): void {
+ $_SERVER = $this->serverBackup;
+});
+
+test('register allowed route roles', function (): void {
+ $controller = new Client();
+
+ $roles = invokeControllerPrivate($controller, 'registerAllowedRouteRoles');
+ expect($roles)->toBeArray();
+ expect($roles)->toHaveKey('role');
+ expect($roles['role'])->toBe('guest|client|admin');
+});
+
+test('is role allowed rejects system role', function (): void {
+ $controller = new Client();
+
+ expect(fn () => invokeControllerPrivate($controller, 'isRoleAllowed', ['system']))
+ ->toThrow(FOSSBilling\Exception::class);
+});
+
+test('should use token login ignores non-API basic auth usernames', function (): void {
+ $controller = new Client();
+ $_SERVER['HTTP_AUTHORIZATION'] = 'Basic ' . base64_encode('upstream:token');
+ $controller->setDi(createControllerDiWithRequest());
+
+ $result = invokeControllerPrivate($controller, 'shouldUseTokenLogin', ['admin']);
+ expect($result)->toBeFalse();
+});
+
+test('should use token login rejects route role mismatch', function (): void {
+ $controller = new Client();
+ $_SERVER['HTTP_AUTHORIZATION'] = 'Basic ' . base64_encode('client:token');
+ $controller->setDi(createControllerDiWithRequest());
+
+ expect(fn () => invokeControllerPrivate($controller, 'shouldUseTokenLogin', ['admin']))
+ ->toThrow(InformationException::class);
+});
+
+test('should prefer session auth for API key management methods', function (): void {
+ $controller = new Client();
+
+ expect(invokeControllerPrivate($controller, 'shouldPreferSessionAuth', ['profile_api_key_get']))->toBeTrue();
+ expect(invokeControllerPrivate($controller, 'shouldPreferSessionAuth', ['profile_api_key_reset']))->toBeTrue();
+ expect(invokeControllerPrivate($controller, 'shouldPreferSessionAuth', ['profile_generate_api_key']))->toBeTrue();
+ expect(invokeControllerPrivate($controller, 'shouldPreferSessionAuth', ['profile_get']))->toBeFalse();
+});
+
+test('has authenticated session returns false when session lookup throws', function (): void {
+ $controller = new Client();
+ $di = new Pimple\Container();
+ $di['is_client_logged'] = function (): void {
+ throw new Exception('Session lookup failed');
+ };
+ $controller->setDi($di);
+
+ expect(invokeControllerPrivate($controller, 'hasAuthenticatedSession', ['client']))->toBeFalse();
+});
+
+test('require session auth normalizes generic auth exceptions', function (): void {
+ $controller = new Client();
+ $di = new Pimple\Container();
+ $di['is_admin_logged'] = function (): void {
+ throw new Exception('Not logged in');
+ };
+ $controller->setDi($di);
+
+ expect(fn () => invokeControllerPrivate($controller, 'requireSessionAuth', ['admin']))
+ ->toThrow(InformationException::class);
+});
+
+test('get auth rejects invalid basic payload', function (): void {
+ $controller = new Client();
+ $_SERVER['HTTP_AUTHORIZATION'] = 'Basic invalid###';
+ $controller->setDi(createControllerDiWithRequest());
+
+ expect(fn () => invokeControllerPrivate($controller, 'getAuth'))
+ ->toThrow(InformationException::class);
+});
+
+test('try token login rejects cron admin token', function (): void {
+ $controller = new Client();
+ $cronToken = 'cron-api-token';
+ $_SERVER['HTTP_AUTHORIZATION'] = 'Basic ' . base64_encode('admin:' . $cronToken);
+
+ $dbAdmin = buildAdminModel(1, $cronToken, Model_Admin::ROLE_ADMIN);
+ $cronAdmin = buildAdminModel(1, $cronToken, Model_Admin::ROLE_CRON);
+
+ $dbMock = Mockery::mock(Box_Database::class);
+ $dbMock->shouldReceive('findOne')->with('Admin', 'api_token = ? AND status = ? AND role != ?', [$cronToken, Model_Admin::STATUS_ACTIVE, Model_Admin::ROLE_CRON])->once()->andReturn($dbAdmin);
+
+ $staffService = new CronStaffServiceDouble($cronAdmin);
+
+ $di = new Pimple\Container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(fn ($name): ?object => $name === 'staff' ? $staffService : null);
+ $di['request'] = Request::create('/', 'GET', [], [], [], $_SERVER);
+ $controller->setDi($di);
+
+ expect(fn () => invokeControllerPrivate($controller, '_tryTokenLogin', ['admin']))
+ ->toThrow(InformationException::class);
+});
+
+test('try token login requires active client token', function (): void {
+ $controller = new Client();
+ $apiToken = 'inactive-client-token';
+ $_SERVER['HTTP_AUTHORIZATION'] = 'Basic ' . base64_encode('client:' . $apiToken);
+
+ $dbMock = Mockery::mock(Box_Database::class);
+ $dbMock->shouldReceive('findOne')->with('Client', 'api_token = ? AND status = ?', [$apiToken, Model_Client::ACTIVE])->once()->andReturn(null);
+
+ $di = new Pimple\Container();
+ $di['db'] = $dbMock;
+ $di['request'] = Request::create('/', 'GET', [], [], [], $_SERVER);
+ $controller->setDi($di);
+
+ expect(fn () => invokeControllerPrivate($controller, '_tryTokenLogin', ['client']))
+ ->toThrow(InformationException::class);
+});
+
+test('try token login requires active non-cron admin token', function (): void {
+ $controller = new Client();
+ $apiToken = 'inactive-admin-token';
+ $_SERVER['HTTP_AUTHORIZATION'] = 'Basic ' . base64_encode('admin:' . $apiToken);
+
+ $dbMock = Mockery::mock(Box_Database::class);
+ $dbMock->shouldReceive('findOne')->with('Admin', 'api_token = ? AND status = ? AND role != ?', [$apiToken, Model_Admin::STATUS_ACTIVE, Model_Admin::ROLE_CRON])->once()->andReturn(null);
+
+ $di = new Pimple\Container();
+ $di['db'] = $dbMock;
+ $di['request'] = Request::create('/', 'GET', [], [], [], $_SERVER);
+ $controller->setDi($di);
+
+ expect(fn () => invokeControllerPrivate($controller, '_tryTokenLogin', ['admin']))
+ ->toThrow(InformationException::class);
+});
diff --git a/src/modules/Api/tests/Unit/ServiceTest.php b/src/modules/Api/tests/Unit/ServiceTest.php
new file mode 100644
index 000000000..94a273498
--- /dev/null
+++ b/src/modules/Api/tests/Unit/ServiceTest.php
@@ -0,0 +1,21 @@
+setDi($di);
+ $getDi = $service->getDi();
+ expect($getDi)->toEqual($di);
+});
diff --git a/src/modules/Cart/Api/Admin.php b/src/modules/Cart/Api/Admin.php
index c040f8361..dca559f59 100644
--- a/src/modules/Cart/Api/Admin.php
+++ b/src/modules/Cart/Api/Admin.php
@@ -28,10 +28,10 @@ class Admin extends \Api_Abstract
public function get_list($data)
{
[$sql, $params] = $this->getService()->getSearchQuery($data);
- $pager = $this->di['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
+ $pager = $this->getDi()['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
foreach ($pager['list'] as $key => $cartArr) {
- $cart = $this->di['db']->getExistingModelById('Cart', $cartArr['id'], 'Cart not found');
+ $cart = $this->getDi()['db']->getExistingModelById('Cart', $cartArr['id'], 'Cart not found');
$pager['list'][$key] = $this->getService()->toApiArray($cart);
}
@@ -48,7 +48,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Shopping cart ID is missing'])]
public function get($data)
{
- $cart = $this->di['db']->getExistingModelById('Cart', $data['id'], 'Shopping cart not found');
+ $cart = $this->getDi()['db']->getExistingModelById('Cart', $data['id'], 'Shopping cart not found');
return $this->getService()->toApiArray($cart);
}
@@ -60,16 +60,16 @@ class Admin extends \Api_Abstract
*/
public function batch_expire($data): bool
{
- $this->di['logger']->info('Executed action to clear expired shopping carts from database');
+ $this->getDi()['logger']->info('Executed action to clear expired shopping carts from database');
$query = 'SELECT id, created_at FROM `cart` WHERE DATEDIFF(CURDATE(), created_at) > 7;';
- $list = $this->di['db']->getAssoc($query);
+ $list = $this->getDi()['db']->getAssoc($query);
if ($list) {
foreach ($list as $id => $created_at) {
- $this->di['db']->exec('DELETE FROM `cart_product` WHERE cart_id = :id', [':id' => $id]);
- $this->di['db']->exec('DELETE FROM `cart` WHERE id = :id', [':id' => $id]);
+ $this->getDi()['db']->exec('DELETE FROM `cart_product` WHERE cart_id = :id', [':id' => $id]);
+ $this->getDi()['db']->exec('DELETE FROM `cart` WHERE id = :id', [':id' => $id]);
}
- $this->di['logger']->info('Removed %s expired shopping carts', \FOSSBilling\Tools::safeCount($list));
+ $this->getDi()['logger']->info('Removed %s expired shopping carts', \FOSSBilling\Tools::safeCount($list));
}
return true;
diff --git a/src/modules/Cart/Api/Client.php b/src/modules/Cart/Api/Client.php
index e8c281f78..444004fab 100644
--- a/src/modules/Cart/Api/Client.php
+++ b/src/modules/Cart/Api/Client.php
@@ -24,7 +24,7 @@ class Client extends \Api_Abstract
*/
public function checkout($data)
{
- $this->di['rate_limiter']->consumeOrThrow('order_generation_ip', (string) $this->getIp());
+ $this->getDi()['rate_limiter']->consumeOrThrow('order_generation_ip', (string) $this->getIp());
$gateway_id = $data['gateway_id'] ?? null;
$cart = $this->getService()->getSessionCart();
diff --git a/src/modules/Cart/Api/Guest.php b/src/modules/Cart/Api/Guest.php
index 2de645827..0e5df8e89 100644
--- a/src/modules/Cart/Api/Guest.php
+++ b/src/modules/Cart/Api/Guest.php
@@ -52,7 +52,7 @@ class Guest extends \Api_Abstract
#[RequiredParams(['currency' => 'Currency code was not passed'])]
public function set_currency($data)
{
- $currencyService = $this->di['mod_service']('currency');
+ $currencyService = $this->getDi()['mod_service']('currency');
/** @var \Box\Mod\Currency\Repository\CurrencyRepository $currencyRepository */
$currencyRepository = $currencyService->getCurrencyRepository();
$currency = $currencyRepository->findOneByCode($data['currency']);
@@ -73,7 +73,7 @@ class Guest extends \Api_Abstract
{
$cart = $this->getService()->getSessionCart();
- $currencyService = $this->di['mod_service']('currency');
+ $currencyService = $this->getDi()['mod_service']('currency');
/** @var \Box\Mod\Currency\Repository\CurrencyRepository $currencyRepository */
$currencyRepository = $currencyService->getCurrencyRepository();
$currency = $currencyRepository->find($cart->currency_id);
@@ -95,7 +95,7 @@ class Guest extends \Api_Abstract
#[RequiredParams(['promocode' => 'Promo code was not passed'])]
public function apply_promo($data)
{
- $this->di['rate_limiter']->consumeOrThrow('cart_promo_apply_ip', (string) $this->getIp());
+ $this->getDi()['rate_limiter']->consumeOrThrow('cart_promo_apply_ip', (string) $this->getIp());
$promo = $this->getService()->findActivePromoByCode($data['promocode']);
if (!$promo instanceof \Model_Promo) {
@@ -152,7 +152,7 @@ class Guest extends \Api_Abstract
{
$cart = $this->getService()->getSessionCart();
- $product = $this->di['db']->getExistingModelById('Product', $data['id'], 'Product not found');
+ $product = $this->getDi()['db']->getExistingModelById('Product', $data['id'], 'Product not found');
if ($product->is_addon) {
throw new \FOSSBilling\InformationException('Addon products cannot be added separately.');
@@ -166,7 +166,7 @@ class Guest extends \Api_Abstract
foreach ($data['addons'] as $addon => $properties) {
if ($properties['selected']) {
- $addonModel = $this->di['db']->getExistingModelById('Product', $addon, 'Addon not found');
+ $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.');
diff --git a/src/modules/Cart/tests/E2E/ApiGuestTest.php b/src/modules/Cart/tests/E2E/ApiGuestTest.php
new file mode 100644
index 000000000..31231d70b
--- /dev/null
+++ b/src/modules/Cart/tests/E2E/ApiGuestTest.php
@@ -0,0 +1,110 @@
+toEqual($startingCart);
+
+ cartCleanupClient($clientId);
+});
+
+function cartCreateDummyProduct(): int
+{
+ $result = Tests\Helpers\ApiClient::request('admin/product/prepare', [
+ 'title' => 'Dummy Product',
+ 'type' => 'custom',
+ 'product_category_id' => 1,
+ ]);
+ assertApiSuccess($result);
+ assertApiResultIsInt($result);
+
+ return (int) $result->getResult();
+}
+
+function cartEnableProduct(int $productId): void
+{
+ $result = Tests\Helpers\ApiClient::request('admin/product/update', [
+ 'id' => $productId,
+ 'status' => 'enabled',
+ 'pricing' => ['type' => 'free'],
+ ]);
+ assertApiSuccess($result);
+ expect($result->getResult())->toBeTrue();
+}
+
+function cartAddProductToCart(int $productId): void
+{
+ $result = Tests\Helpers\ApiClient::request('guest/cart/add_item', ['id' => $productId]);
+ assertApiSuccess($result);
+ expect($result->getResult())->toBeTrue();
+}
+
+function cartGetCart(): array
+{
+ $result = Tests\Helpers\ApiClient::request('guest/cart/get');
+ assertApiSuccess($result);
+ assertApiResultIsArray($result);
+
+ return $result->getResult();
+}
+
+function cartCreateClient(): int
+{
+ $password = 'A1a' . bin2hex(random_bytes(6));
+ $result = Tests\Helpers\ApiClient::request('guest/client/create', [
+ 'email' => 'client_' . uniqid() . '@example.com',
+ 'first_name' => 'Test',
+ 'password' => $password,
+ 'password_confirm' => $password,
+ ]);
+ assertApiSuccess($result);
+ assertApiResultIsInt($result);
+
+ return (int) $result->getResult();
+}
+
+function cartLoginClient(int $clientId): void
+{
+ $result = Tests\Helpers\ApiClient::request('guest/client/login', [
+ 'email' => 'client_' . $clientId . '@example.com',
+ 'password' => 'A1a' . bin2hex(random_bytes(6)),
+ ]);
+ assertApiSuccess($result);
+}
+
+function cartCleanupClient(int $clientId): void
+{
+ $result = Tests\Helpers\ApiClient::request('admin/client/delete', ['id' => $clientId]);
+ assertApiSuccess($result);
+ expect($result->getResult())->toBeTrue();
+}
diff --git a/src/modules/Cart/tests/Unit/Api/AdminTest.php b/src/modules/Cart/tests/Unit/Api/AdminTest.php
new file mode 100644
index 000000000..43be8c6b2
--- /dev/null
+++ b/src/modules/Cart/tests/Unit/Api/AdminTest.php
@@ -0,0 +1,114 @@
+ [
+ ['id' => 1],
+ ],
+ ];
+
+ $paginatorMock = Mockery::mock(FOSSBilling\Pagination::class)->makePartial();
+ $paginatorMock
+ ->shouldReceive('getPaginatedResultSet')
+ ->atLeast()->once()
+ ->andReturn($simpleResultArr);
+
+ $serviceMock = Mockery::mock(Box\Mod\Cart\Service::class)->makePartial();
+ $serviceMock->shouldReceive('getSearchQuery')->atLeast()->once()
+ ->andReturn(['query', []]);
+ $serviceMock
+ ->shouldReceive('toApiArray')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $model = new Model_Cart();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $di = container();
+ $di['pager'] = $paginatorMock;
+ $di['db'] = $dbMock;
+
+ $adminApi->setDi($di);
+
+ $adminApi->setService($serviceMock);
+
+ $data = [];
+ $result = $adminApi->get_list($data);
+
+ expect($result)->toBeArray();
+});
+
+test('get returns array', function (): void {
+ $adminApi = new Box\Mod\Cart\Api\Admin();
+ $api = new Box\Mod\Cart\Api\Admin();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn(new Model_Cart());
+
+ $serviceMock = Mockery::mock(Box\Mod\Cart\Service::class)->makePartial();
+ $serviceMock->shouldReceive('toApiArray')->atLeast()->once()
+ ->andReturn([]);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $adminApi->setDi($di);
+
+ $adminApi->setService($serviceMock);
+
+ $data = [
+ 'id' => 1,
+ ];
+ $result = $adminApi->get($data);
+
+ expect($result)->toBeArray();
+});
+
+test('batchExpire returns true', function (): void {
+ $adminApi = new Box\Mod\Cart\Api\Admin();
+ $api = new Box\Mod\Cart\Api\Admin();
+
+ $logStub = $this->createStub('\Box_Log');
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getAssoc')
+ ->atLeast()->once()
+ ->andReturn([1, date('Y-m-d H:i:s')]);
+ $dbMock
+ ->shouldReceive('exec')
+ ->atLeast()->once()
+ ->andReturn(null);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = $logStub;
+ $adminApi->setDi($di);
+
+ $data = [
+ 'id' => 1,
+ ];
+ $result = $adminApi->batch_expire($data);
+
+ expect($result)->toBeTrue();
+});
diff --git a/src/modules/Cart/tests/Unit/Api/ClientTest.php b/src/modules/Cart/tests/Unit/Api/ClientTest.php
new file mode 100644
index 000000000..a471fe16e
--- /dev/null
+++ b/src/modules/Cart/tests/Unit/Api/ClientTest.php
@@ -0,0 +1,52 @@
+loadBean(new Tests\Helpers\DummyBean());
+
+ $serviceMock = Mockery::mock(Box\Mod\Cart\Service::class)->makePartial();
+ $serviceMock->shouldReceive('getSessionCart')->atLeast()->once()
+ ->andReturn($cart);
+
+ $checkOutCartResult = [
+ 'gateway_id' => 1,
+ 'invoice_hash' => null,
+ 'order_id' => 1,
+ 'orders' => 1,
+ ];
+ $serviceMock
+ ->shouldReceive('checkoutCart')
+ ->atLeast()->once()
+ ->andReturn($checkOutCartResult);
+
+ $clientApi->setService($serviceMock);
+
+ $client = new Model_Client();
+ $client->loadBean(new Tests\Helpers\DummyBean());
+
+ $clientApi->setIdentity($client);
+
+ $data = [
+ 'id' => 1,
+ ];
+ $di = container();
+
+ $clientApi->setDi($di);
+ $result = $clientApi->checkout($data);
+
+ expect($result)->toBeArray();
+});
diff --git a/src/modules/Cart/tests/Unit/Api/GuestTest.php b/src/modules/Cart/tests/Unit/Api/GuestTest.php
new file mode 100644
index 000000000..a4bc9c401
--- /dev/null
+++ b/src/modules/Cart/tests/Unit/Api/GuestTest.php
@@ -0,0 +1,458 @@
+makePartial();
+ $serviceMock->shouldReceive('getSessionCart')->atLeast()->once()
+ ->andReturn(new Model_Cart());
+ $serviceMock->shouldReceive('toApiArray')->atLeast()->once()
+ ->andReturn([]);
+
+ $guestApi->setService($serviceMock);
+
+ $result = $guestApi->get();
+
+ 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);
+
+ $guestApi->setService($serviceMock);
+
+ $result = $guestApi->reset();
+
+ 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);
+
+ $currencyStub = $this->createStub('\\' . Box\Mod\Currency\Entity\Currency::class);
+
+ $currencyRepositoryMock = Mockery::mock('\\' . Box\Mod\Currency\Repository\CurrencyRepository::class);
+ $currencyRepositoryMock
+ ->shouldReceive('findOneByCode')
+ ->atLeast()->once()
+ ->andReturn($currencyStub);
+
+ $currencyServiceMock = Mockery::mock('\\' . Box\Mod\Currency\Service::class)->makePartial();
+ $currencyServiceMock->shouldReceive('getCurrencyRepository')->atLeast()->once()
+ ->andReturn($currencyRepositoryMock);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $currencyServiceMock);
+ $guestApi->setDi($di);
+
+ $guestApi->setService($serviceMock);
+
+ $data = [
+ 'currency' => 'EUR',
+ ];
+ $result = $guestApi->set_currency($data);
+
+ 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);
+
+ $currencyRepositoryMock = Mockery::mock('\\' . Box\Mod\Currency\Repository\CurrencyRepository::class);
+ $currencyRepositoryMock
+ ->shouldReceive('findOneByCode')
+ ->atLeast()->once()
+ ->andReturn(null);
+
+ $currencyServiceMock = Mockery::mock('\\' . Box\Mod\Currency\Service::class)->makePartial();
+ $currencyServiceMock->shouldReceive('getCurrencyRepository')->atLeast()->once()
+ ->andReturn($currencyRepositoryMock);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $currencyServiceMock);
+ $guestApi->setDi($di);
+
+ $guestApi->setService($serviceMock);
+
+ $data = [
+ 'currency' => 'EUR',
+ ];
+
+ $this->expectException(FOSSBilling\Exception::class);
+ $this->expectExceptionMessage('Currency not found');
+ $guestApi->set_currency($data);
+});
+
+test('get currency', function (): void {
+ $guestApi = new Box\Mod\Cart\Api\Guest();
+ $api = new Box\Mod\Cart\Api\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);
+
+ $currencyMock = Mockery::mock('\\' . Box\Mod\Currency\Entity\Currency::class);
+ $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();
+
+ $currencyServiceMock = Mockery::mock('\\' . Box\Mod\Currency\Service::class)->makePartial();
+ $currencyServiceMock->shouldReceive('getCurrencyRepository')->atLeast()->once()
+ ->andReturn($currencyRepositoryMock);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $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();
+ $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);
+
+ $currencyMock = Mockery::mock('\\' . Box\Mod\Currency\Entity\Currency::class);
+ $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);
+
+ $currencyServiceMock = Mockery::mock('\\' . Box\Mod\Currency\Service::class)->makePartial();
+ $currencyServiceMock->shouldReceive('getCurrencyRepository')->atLeast()->once()
+ ->andReturn($currencyRepositoryMock);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $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();
+ $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('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);
+
+ $di = container();
+ $guestApi->setDi($di);
+
+ $guestApi->setService($serviceMock);
+
+ $data = [
+ 'promocode' => 'CODE',
+ ];
+ $result = $guestApi->apply_promo($data);
+
+ 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();
+ $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);
+
+ $di = container();
+ $guestApi->setDi($di);
+
+ $guestApi->setService($serviceMock);
+
+ $data = [
+ 'promocode' => 'CODE',
+ ];
+
+ $this->expectException(FOSSBilling\InformationException::class);
+ $this->expectExceptionMessage('The promo code has expired or does not exist');
+ $guestApi->apply_promo($data);
+});
+
+test('apply promo can not be applied', function (): void {
+ $guestApi = new Box\Mod\Cart\Api\Guest();
+ $api = new Box\Mod\Cart\Api\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(new Model_Promo());
+ $serviceMock->shouldReceive('isPromoAvailableForClientGroup')->atLeast()->once()
+ ->andReturn(true);
+ $serviceMock->shouldReceive('promoCanBeApplied')->atLeast()->once()
+ ->andReturn(false);
+
+ $di = container();
+ $guestApi->setDi($di);
+
+ $guestApi->setService($serviceMock);
+
+ $data = [
+ 'promocode' => 'CODE',
+ ];
+
+ $this->expectException(FOSSBilling\InformationException::class);
+ $this->expectExceptionMessage('The promo code has expired or does not exist');
+ $guestApi->apply_promo($data);
+});
+
+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();
+ $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(new Model_Promo());
+ $serviceMock->shouldReceive('isPromoAvailableForClientGroup')->atLeast()->once()
+ ->andReturn(false);
+
+ $di = container();
+ $guestApi->setDi($di);
+
+ $guestApi->setService($serviceMock);
+
+ $data = [
+ 'promocode' => 'CODE',
+ ];
+
+ $this->expectException(FOSSBilling\InformationException::class);
+ $this->expectExceptionMessage('Promo code cannot be applied to your account');
+ $guestApi->apply_promo($data);
+});
+
+test('remove promo', function (): void {
+ $guestApi = new Box\Mod\Cart\Api\Guest();
+ $api = new Box\Mod\Cart\Api\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);
+
+ $guestApi->setService($serviceMock);
+
+ $result = $guestApi->remove_promo();
+
+ expect($result)->toBeTrue();
+});
+
+test('remove item', function (): void {
+ $guestApi = new Box\Mod\Cart\Api\Guest();
+ $api = new Box\Mod\Cart\Api\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);
+
+ $di = container();
+ $guestApi->setDi($di);
+
+ $guestApi->setService($serviceMock);
+
+ $data = [
+ 'id' => 1,
+ ];
+
+ $result = $guestApi->remove_item($data);
+
+ expect($result)->toBeTrue();
+});
+
+test('add item', function (): void {
+ $guestApi = new Box\Mod\Cart\Api\Guest();
+ $api = new Box\Mod\Cart\Api\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('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);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $guestApi->setDi($di);
+
+ $guestApi->setService($serviceMock);
+
+ $data = [
+ 'id' => 1,
+ 'multiple' => true,
+ ];
+
+ $result = $guestApi->add_item($data);
+
+ 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();
+ $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('addItem')->atLeast()->once()
+ ->andReturn(true);
+
+ $apiMock = Mockery::mock(Box\Mod\Cart\Api\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);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $apiMock->setDi($di);
+
+ $apiMock->setService($serviceMock);
+
+ $data = [
+ 'id' => 1,
+ 'multiple' => false, // should reset cart before adding
+ ];
+
+ $result = $apiMock->add_item($data);
+
+ expect($result)->toBeTrue();
+});
diff --git a/src/modules/Cart/tests/Unit/ServiceTest.php b/src/modules/Cart/tests/Unit/ServiceTest.php
new file mode 100644
index 000000000..277cdf077
--- /dev/null
+++ b/src/modules/Cart/tests/Unit/ServiceTest.php
@@ -0,0 +1,1306 @@
+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();
+ $result = $service->getSearchQuery([]);
+
+ expect($result[0])->toBeString();
+ expect($result[1])->toBeArray();
+ expect(strpos((string) $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();
+
+ $sessionId = 'rrcpqo7tkjh14d2vmf0car64k7';
+
+ $model = new Model_Cart();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $model->session_id = $sessionId;
+
+ $dbMock = Mockery::mock('Box_Database');
+ $dbMock->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $sessionMock = Mockery::mock(FOSSBilling\Session::class);
+ $sessionMock->shouldReceive('getId')
+ ->atLeast()->once()
+ ->andReturn($sessionId);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['session'] = $sessionMock;
+ $service->setDi($di);
+
+ $result = $service->getSessionCart();
+
+ expect($result)->toBeInstanceOf('Model_Cart');
+ expect($result->session_id)->toEqual($sessionId);
+});
+
+dataset('getSessionCartDoesNotExistProvider', fn(): array => [
+ [
+ 100,
+ 'atLeastOnce',
+ 'never',
+ ],
+ [
+ null,
+ 'never',
+ 'atLeastOnce',
+ ],
+]);
+
+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);
+ $currencyId = random_int(0, 1000);
+ $currencyModel->shouldReceive('getId')
+ ->byDefault()
+ ->andReturn($currencyId);
+
+ $sessionId = 'rrcpqo7tkjh14d2vmf0car64k7';
+ $model = null;
+ $dbMock = Mockery::mock('Box_Database');
+ $dbMock->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn($model);
+ $modelCart = new Model_Cart();
+ $modelCart->loadBean(new Tests\Helpers\DummyBean());
+ $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);
+
+ $currencyRepositoryMock = Mockery::mock(Box\Mod\Currency\Repository\CurrencyRepository::class);
+ if ($sessionGetWillReturn === null) {
+ $currencyRepositoryMock->shouldReceive('findDefault')
+ ->atLeast()->once()
+ ->andReturn($currencyModel);
+ } else {
+ $currencyRepositoryMock->shouldReceive('findDefault')->never();
+ }
+
+ $currencyServiceMock = Mockery::mock(Box\Mod\Currency\Service::class)->makePartial();
+ if ($getCurrencyByClientIdExpects === 'atLeastOnce') {
+ $currencyServiceMock->shouldReceive('getCurrencyByClientId')
+ ->atLeast()->once()
+ ->andReturn($currencyModel);
+ } else {
+ $currencyServiceMock->shouldReceive('getCurrencyByClientId')->never();
+ }
+ $currencyServiceMock->shouldReceive('getCurrencyRepository')
+ ->atLeast()->once()
+ ->andReturn($currencyRepositoryMock);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['session'] = $sessionMock;
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $currencyServiceMock);
+ $service->setDi($di);
+
+ $result = $service->getSessionCart();
+
+ expect($result)->toBeInstanceOf('Model_Cart');
+ expect($result->session_id)->toEqual($sessionId);
+ expect($result->currency_id)->toEqual($currencyId);
+})->with('getSessionCartDoesNotExistProvider');
+
+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;
+
+ $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;
+
+ $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]);
+
+ $productModelMock = Mockery::mock(Model_Product::class)->makePartial();
+ $productModelMock->shouldReceive('getTable')
+ ->atLeast()->once()
+ ->andReturn($productTable);
+
+ $result = $service->isRecurrentPricing($productModelMock);
+
+ expect($result)->toBeTrue();
+});
+
+test('is period enabled for product', function (): void {
+ $service = new Box\Mod\Cart\Service();
+ $enabled = false;
+ $pricingArray = [
+ 'type' => Model_ProductPayment::RECURRENT,
+ 'recurrent' => [
+ 'monthly' => [
+ 'enabled' => $enabled,
+ ],
+ ],
+ ];
+ $productTable = Mockery::mock(Model_ProductTable::class);
+ $productTable->shouldReceive('getPricingArray')
+ ->atLeast()->once()
+ ->andReturn($pricingArray);
+
+ $productModelMock = Mockery::mock(Model_Product::class)->makePartial();
+ $productModelMock->shouldReceive('getTable')
+ ->atLeast()->once()
+ ->andReturn($productTable);
+
+ $result = $service->isPeriodEnabledForProduct($productModelMock, 'monthly');
+
+ expect($result)->toBeBool();
+ 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);
+
+ $productModelMock = Mockery::mock(Model_Product::class)->makePartial();
+ $productModelMock->shouldReceive('getTable')
+ ->atLeast()->once()
+ ->andReturn($productTable);
+
+ $result = $service->isPeriodEnabledForProduct($productModelMock, 'monthly');
+
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+});
+
+test('remove product', function (): void {
+ $service = new Box\Mod\Cart\Service();
+ $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);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $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');
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $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);
+
+ $cart = new Model_Cart();
+ $cart->loadBean(new Tests\Helpers\DummyBean());
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $service->setDi($di);
+
+ $result = $service->removePromo($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()]);
+
+ $promo = new Model_Promo();
+ $promo->loadBean(new Tests\Helpers\DummyBean());
+ $promo->id = 2;
+
+ $cart = new Model_Cart();
+ $cart->loadBean(new Tests\Helpers\DummyBean());
+ $cart->promo_id = 1;
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $service->setDi($di);
+
+ $result = $service->applyPromo($cart, $promo);
+
+ expect($result)->toBeTrue();
+});
+
+test('apply promo already applied', function (): void {
+ $service = new Box\Mod\Cart\Service();
+
+ $dbMock = Mockery::mock(Box_Database::class);
+ $dbMock->shouldReceive('store')->never();
+
+ $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;
+
+ $cart = new Model_Cart();
+ $cart->loadBean(new Tests\Helpers\DummyBean());
+ $cart->promo_id = 5;
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $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();
+
+ $dbMock = Mockery::mock(Box_Database::class);
+ $dbMock->shouldReceive('store')->never();
+
+ $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;
+
+ $cart = new Model_Cart();
+ $cart->loadBean(new Tests\Helpers\DummyBean());
+ $cart->promo_id = 1;
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $serviceMock->setDi($di);
+
+ $this->expectException(FOSSBilling\Exception::class);
+ $serviceMock->applyPromo($cart, $promo);
+});
+
+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);
+
+ $cart = new Model_Cart();
+ $cart->loadBean(new Tests\Helpers\DummyBean());
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $result = $service->rm($cart);
+
+ 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;
+
+ $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());
+
+ $di = container();
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $di['db'] = $dbMock;
+ $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());
+
+ $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();
+});
+
+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();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $result = $service->promoCanBeApplied($promo);
+
+ expect($result)->toEqual($expectedResult);
+})->with('promoCanBeAppliedProvider');
+
+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()]);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $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');
+});
+
+test('checkout cart', function (): void {
+ $service = new Box\Mod\Cart\Service();
+
+ $cart = new Model_Cart();
+ $cart->loadBean(new Tests\Helpers\DummyBean());
+ $cart->promo_id = 1;
+
+ $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);
+
+ $eventMock = Mockery::mock(Box_EventManager::class);
+ $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());
+
+ $dbMock = Mockery::mock(Box_Database::class);
+ $dbMock->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($promo);
+
+ $client = new Model_Client();
+ $client->loadBean(new Tests\Helpers\DummyBean());
+
+ $di = container();
+ $di['events_manager'] = $eventMock;
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $di['request'] = new Symfony\Component\HttpFoundation\Request();
+
+ $serviceMock->setDi($di);
+ $result = $serviceMock->checkoutCart($cart, $client);
+
+ expect($result)->toBeArray();
+ expect($result)->toHaveKey('gateway_id');
+ expect($result)->toHaveKey('invoice_hash');
+ expect($result)->toHaveKey('order_id');
+ expect($result)->toHaveKey('orders');
+});
+
+test('checkout cart client is not able to use promo exception', function (): void {
+ $service = new Box\Mod\Cart\Service();
+
+ $cart = new Model_Cart();
+ $cart->loadBean(new Tests\Helpers\DummyBean());
+ $cart->promo_id = 1;
+
+ $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);
+
+ $dbMock = Mockery::mock(Box_Database::class);
+
+ $dbMock->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn(new Model_Promo());
+
+ $client = new Model_Client();
+ $client->loadBean(new Tests\Helpers\DummyBean());
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $serviceMock->setDi($di);
+
+ $this->expectException(FOSSBilling\Exception::class);
+ $serviceMock->checkoutCart($cart, $client);
+});
+
+test('use promo', function (): void {
+ $service = new Box\Mod\Cart\Service();
+ $promo = new Model_Promo();
+ $promo->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock(Box_Database::class);
+ $dbMock->shouldReceive('exec')
+ ->atLeast()->once()
+ ->andReturn(1);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $result = $service->usePromo($promo);
+
+ 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());
+
+ $dbMock = Mockery::mock(Box_Database::class);
+ $dbMock->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn($promo);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $result = $service->findActivePromoByCode('CODE');
+
+ expect($result)->toBeInstanceOf('Model_Promo');
+});
+
+test('add item throws exception when out of stock', 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();
+
+ $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);
+
+ $di = container();
+ $di['events_manager'] = $eventMock;
+ $di['mod_service'] = $di->protect(moduleService(['servicehosting' => $serviceHostingServiceMock]));
+
+ $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'));
+ $di['validator'] = $validatorMock;
+
+ $serviceMock->setDi($di);
+ $productModel->setDi($di);
+
+ $this->expectException(FOSSBilling\Exception::class);
+ $this->expectExceptionMessage('Period parameter not passed');
+ $serviceMock->addItem($cartModel, $productModel, $data);
+});
+
+test('add item throws exception when recurring payment period is not enabled', 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 = ['period' => '1W'];
+
+ $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);
+ $serviceMock->shouldReceive('isPeriodEnabledForProduct')
+ ->atLeast()->once()
+ ->andReturn(false);
+
+ $di = container();
+ $di['events_manager'] = $eventMock;
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $serviceHostingServiceMock);
+
+ $validatorMock = Mockery::mock(FOSSBilling\Validate::class);
+ $validatorMock->shouldReceive('checkRequiredParamsForArray');
+ $di['validator'] = $validatorMock;
+
+ $serviceMock->setDi($di);
+ $productModel->setDi($di);
+
+ $this->expectException(FOSSBilling\Exception::class);
+ $this->expectExceptionMessage('Selected billing period is invalid');
+ $serviceMock->addItem($cartModel, $productModel, $data);
+});
+
+test('to api array', function (): void {
+ $service = new Box\Mod\Cart\Service();
+ $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]);
+
+ $cartProductApiArray = [
+ 'total' => 1,
+ 'setup_price' => 0,
+ 'discount' => 0,
+ ];
+ $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([]);
+
+ $currencyRepositoryMock = Mockery::mock(Box\Mod\Currency\Repository\CurrencyRepository::class);
+ $currencyRepositoryMock->shouldReceive('find')
+ ->atLeast()->once()
+ ->andReturn($currencyModelMock);
+
+ $currencyServiceMock->shouldReceive('getCurrencyRepository')
+ ->atLeast()->once()
+ ->andReturn($currencyRepositoryMock);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $currencyServiceMock);
+
+ $serviceMock->setDi($di);
+
+ $result = $serviceMock->toApiArray($cartModel);
+
+ $expected = [
+ 'promocode' => null,
+ 'discount' => 0,
+ 'total' => 1,
+ 'items' => [$cartProductApiArray],
+ 'currency' => [],
+ 'subtotal' => 1,
+ ];
+
+ expect($result)->toBeArray();
+ expect($result)->toEqual($expected);
+});
+
+test('get product discount with promo', function (): void {
+ $service = new Box\Mod\Cart\Service();
+ $cartProductModel = new Model_CartProduct();
+ $cartProductModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $modelCart = new Model_Cart();
+ $modelCart->loadBean(new Tests\Helpers\DummyBean());
+ $modelCart->promo_id = 1;
+
+ $promoModel = new Model_Promo();
+ $promoModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $discountPrice = 25;
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('load')
+ ->atLeast()->once()
+ ->andReturn($modelCart);
+ $dbMock->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($promoModel);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $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->setDi($di);
+ $setupPrice = 0;
+ $result = $serviceMock->getProductDiscount($cartProductModel, $setupPrice);
+
+ expect($result)->toBeArray();
+ expect($result[0])->toEqual($discountPrice);
+ expect($result[1])->toEqual(0);
+});
+
+test('get product discount with no promo', function (): void {
+ $service = new Box\Mod\Cart\Service();
+ $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);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $serviceMock = Mockery::mock(Box\Mod\Cart\Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('getRelatedItemsDiscount')
+ ->atLeast()->once()
+ ->andReturn(0);
+
+ $serviceMock->setDi($di);
+ $setupPrice = 0;
+ $result = $serviceMock->getProductDiscount($cartProductModel, $setupPrice);
+
+ expect($result)->toBeArray();
+ expect($result[0])->toEqual(0);
+ expect($result[1])->toEqual(0);
+});
+
+test('get product discount with product qty set and free setup', function (): void {
+ $service = new Box\Mod\Cart\Service();
+ $cartProductModel = new Model_CartProduct();
+ $cartProductModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $modelCart = new Model_Cart();
+ $modelCart->loadBean(new Tests\Helpers\DummyBean());
+ $modelCart->promo_id = 1;
+
+ $promoModel = new Model_Promo();
+ $promoModel->loadBean(new Tests\Helpers\DummyBean());
+ $promoModel->freesetup = 1;
+
+ $discountPrice = 25;
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('load')
+ ->atLeast()->once()
+ ->andReturn($modelCart);
+ $dbMock->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($promoModel);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $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->setDi($di);
+ $setupPrice = 25;
+ $result = $serviceMock->getProductDiscount($cartProductModel, $setupPrice);
+
+ expect($result)->toBeArray();
+ expect($result[0])->toEqual($discountPrice);
+ expect($result[1])->toEqual($setupPrice);
+});
+
+dataset('isPromoAvailableForClientGroupProvider', function () {
+ $promo1 = new Model_Promo();
+ $promo1->loadBean(new Tests\Helpers\DummyBean());
+ $promo1->client_groups = json_encode([]);
+
+ $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;
+ $service->setDi($di);
+
+ $result = $service->isPromoAvailableForClientGroup($promo);
+
+ expect($result)->toEqual($expectedResult);
+})->with('isPromoAvailableForClientGroupProvider');
diff --git a/src/modules/Client/Api/Admin.php b/src/modules/Client/Api/Admin.php
index 4d3f8be10..128225346 100644
--- a/src/modules/Client/Api/Admin.php
+++ b/src/modules/Client/Api/Admin.php
@@ -35,13 +35,13 @@ class Admin extends \Api_Abstract
*/
public function get_list($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('client', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('client', 'view');
[$sql, $params] = $this->getService()->getSearchQuery($data);
- $pager = $this->di['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
+ $pager = $this->getDi()['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
foreach ($pager['list'] as $key => $clientArr) {
- $client = $this->di['db']->getExistingModelById('Client', $clientArr['id'], 'Client not found');
+ $client = $this->getDi()['db']->getExistingModelById('Client', $clientArr['id'], 'Client not found');
$pager['list'][$key] = $this->getService()->toApiArray($client, true, $this->getIdentity());
}
@@ -57,9 +57,9 @@ class Admin extends \Api_Abstract
*/
public function get_pairs($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('client', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('client', 'view');
- $service = $this->di['mod_service']('client');
+ $service = $this->getDi()['mod_service']('client');
return $service->getPairs($data);
}
@@ -73,11 +73,11 @@ class Admin extends \Api_Abstract
*/
public function get($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('client', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('client', 'view');
$service = $this->getService();
$client = $service->get($data);
- $includeSensitive = $this->di['mod_service']('Staff')->hasPermission(null, 'client', 'manage_api_keys');
+ $includeSensitive = $this->getDi()['mod_service']('Staff')->hasPermission(null, 'client', 'manage_api_keys');
return $service->toApiArray($client, true, $this->getIdentity(), $includeSensitive);
}
@@ -90,16 +90,16 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'ID required'])]
public function login($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('client', 'impersonate_login');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('client', 'impersonate_login');
- $client = $this->di['db']->getExistingModelById('Client', $data['id'], 'Client not found');
+ $client = $this->getDi()['db']->getExistingModelById('Client', $data['id'], 'Client not found');
- $service = $this->di['mod_service']('client');
+ $service = $this->getDi()['mod_service']('client');
$result = $service->toSessionArray($client);
- $session = $this->di['session'];
+ $session = $this->getDi()['session'];
$session->set('client_id', $client->id);
- $this->di['logger']->info('Logged in as client #%s', $client->id);
+ $this->getDi()['logger']->info('Logged in as client #%s', $client->id);
return $result;
}
@@ -148,10 +148,10 @@ class Admin extends \Api_Abstract
#[RequiredParams(['email' => 'Email required', 'first_name' => 'First name is required'])]
public function create($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('client', 'create');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('client', 'create');
- $validator = $this->di['validator'];
- $data['email'] = $this->di['tools']->validateAndSanitizeEmail($data['email']);
+ $validator = $this->getDi()['validator'];
+ $data['email'] = $this->getDi()['tools']->validateAndSanitizeEmail($data['email']);
$data['send_welcome_email'] = Tools::normalizeBoolean($data['send_welcome_email'] ?? true, true);
$service = $this->getService();
@@ -173,9 +173,9 @@ class Admin extends \Api_Abstract
$validator->isPasswordStrong($data['password']);
}
- $this->di['events_manager']->fire(['event' => 'onBeforeAdminClientCreate', 'params' => $data]);
+ $this->getDi()['events_manager']->fire(['event' => 'onBeforeAdminClientCreate', 'params' => $data]);
$id = $service->adminCreateClient($data);
- $this->di['events_manager']->fire(['event' => 'onAfterAdminClientCreate', 'params' => $data]);
+ $this->getDi()['events_manager']->fire(['event' => 'onAfterAdminClientCreate', 'params' => $data]);
return $id;
}
@@ -186,17 +186,17 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Client ID is missing'])]
public function delete($data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('client', 'delete');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('client', 'delete');
- $model = $this->di['db']->getExistingModelById('Client', $data['id'], 'Client not found');
+ $model = $this->getDi()['db']->getExistingModelById('Client', $data['id'], 'Client not found');
- $this->di['events_manager']->fire(['event' => 'onBeforeAdminClientDelete', 'params' => ['id' => $model->id]]);
+ $this->getDi()['events_manager']->fire(['event' => 'onBeforeAdminClientDelete', 'params' => ['id' => $model->id]]);
$id = $model->id;
$this->getService()->remove($model);
- $this->di['events_manager']->fire(['event' => 'onAfterAdminClientDelete', 'params' => ['id' => $id]]);
+ $this->getDi()['events_manager']->fire(['event' => 'onAfterAdminClientDelete', 'params' => ['id' => $id]]);
- $this->di['logger']->info('Removed client #%s', $id);
+ $this->getDi()['logger']->info('Removed client #%s', $id);
return true;
}
@@ -241,22 +241,22 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Client ID was not passed'])]
public function update($data = []): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('client', 'edit_profile');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('client', 'edit_profile');
- $client = $this->di['db']->getExistingModelById('Client', $data['id'], 'Client not found');
+ $client = $this->getDi()['db']->getExistingModelById('Client', $data['id'], 'Client not found');
- $service = $this->di['mod_service']('client');
+ $service = $this->getDi()['mod_service']('client');
if (!is_null($data['email'] ?? null)) {
$email = $data['email'];
- $email = $this->di['tools']->validateAndSanitizeEmail($email);
+ $email = $this->getDi()['tools']->validateAndSanitizeEmail($email);
if ($service->emailAlreadyRegistered($email, $client)) {
throw new InformationException('This email address is already registered.');
}
}
if (!empty($data['birthday'])) {
- $this->di['validator']->isBirthdayValid($data['birthday']);
+ $this->getDi()['validator']->isBirthdayValid($data['birthday']);
}
if (($data['birthday'] ?? null) === '') {
@@ -268,7 +268,7 @@ class Admin extends \Api_Abstract
$client->currency = $currency;
}
- $this->di['events_manager']->fire(['event' => 'onBeforeAdminClientUpdate', 'params' => $data]);
+ $this->getDi()['events_manager']->fire(['event' => 'onBeforeAdminClientUpdate', 'params' => $data]);
// Special handling for the phone country codes
$phoneCountryCode = $data['phone_cc'] ?? $client->phone_cc;
@@ -312,16 +312,16 @@ class Admin extends \Api_Abstract
$client->updated_at = date('Y-m-d H:i:s');
- $this->di['db']->store($client);
+ $this->getDi()['db']->store($client);
if ($client->status !== \Model_Client::ACTIVE && $previousStatus === \Model_Client::ACTIVE) {
- $profileService = $this->di['mod_service']('profile');
+ $profileService = $this->getDi()['mod_service']('profile');
$profileService->invalidateSessions('client', (int) $client->id);
}
- $this->di['events_manager']->fire(['event' => 'onAfterAdminClientUpdate', 'params' => ['id' => $client->id]]);
+ $this->getDi()['events_manager']->fire(['event' => 'onAfterAdminClientUpdate', 'params' => ['id' => $client->id]]);
- $this->di['logger']->info('Updated client #%s profile', $client->id);
+ $this->getDi()['logger']->info('Updated client #%s profile', $client->id);
return true;
}
@@ -332,26 +332,26 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'ID required', 'password' => 'Password required', 'password_confirm' => 'Password confirmation required'])]
public function change_password(array $data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('client', 'change_password');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('client', 'change_password');
- $this->di['validator']->passwordsMatch($data);
+ $this->getDi()['validator']->passwordsMatch($data);
- $this->di['validator']->isPasswordStrong($data['password']);
+ $this->getDi()['validator']->isPasswordStrong($data['password']);
- $client = $this->di['db']->getExistingModelById('Client', $data['id'], 'Client not found');
+ $client = $this->getDi()['db']->getExistingModelById('Client', $data['id'], 'Client not found');
- $this->di['events_manager']->fire(['event' => 'onBeforeAdminClientPasswordChange', 'params' => ['id' => $client->id]]);
+ $this->getDi()['events_manager']->fire(['event' => 'onBeforeAdminClientPasswordChange', 'params' => ['id' => $client->id]]);
- $client->pass = $this->di['password']->hashIt($data['password']);
+ $client->pass = $this->getDi()['password']->hashIt($data['password']);
$client->updated_at = date('Y-m-d H:i:s');
- $this->di['db']->store($client);
+ $this->getDi()['db']->store($client);
- $profileService = $this->di['mod_service']('profile');
+ $profileService = $this->getDi()['mod_service']('profile');
$profileService->invalidateSessions('client', (int) $data['id']);
- $this->di['events_manager']->fire(['event' => 'onAfterAdminClientPasswordChange', 'params' => ['id' => $client->id]]);
+ $this->getDi()['events_manager']->fire(['event' => 'onAfterAdminClientPasswordChange', 'params' => ['id' => $client->id]]);
- $this->di['logger']->info('Changed client #%s password', $client->id);
+ $this->getDi()['logger']->info('Changed client #%s password', $client->id);
return true;
}
@@ -363,11 +363,11 @@ class Admin extends \Api_Abstract
*/
public function balance_get_list($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('client', 'manage_balance');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('client', 'manage_balance');
- $service = $this->di['mod_service']('Client', 'Balance');
+ $service = $this->getDi()['mod_service']('Client', 'Balance');
[$q, $params] = $service->getSearchQuery($data);
- $pager = $this->di['pager']->getPaginatedResultSet($q, $params, PaginationOptions::fromArray($data));
+ $pager = $this->getDi()['pager']->getPaginatedResultSet($q, $params, PaginationOptions::fromArray($data));
foreach ($pager['list'] as $key => $item) {
$pager['list'][$key] = [
@@ -388,17 +388,17 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Client ID was not passed'])]
public function balance_delete($data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('client', 'manage_balance');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('client', 'manage_balance');
- $model = $this->di['db']->getExistingModelById('ClientBalance', $data['id'], 'Balance line not found');
+ $model = $this->getDi()['db']->getExistingModelById('ClientBalance', $data['id'], 'Balance line not found');
$id = $model->id;
$client_id = $model->client_id;
$amount = $model->amount;
- $this->di['db']->trash($model);
+ $this->getDi()['db']->trash($model);
- $this->di['logger']->info('Removed line %s from client #%s balance for %s', $id, $client_id, $amount);
+ $this->getDi()['logger']->info('Removed line %s from client #%s balance for %s', $id, $client_id, $amount);
return true;
}
@@ -412,11 +412,11 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Client ID required', 'amount' => 'Amount is required', 'description' => 'Description is required'])]
public function balance_add_funds($data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('client', 'manage_balance');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('client', 'manage_balance');
- $client = $this->di['db']->getExistingModelById('Client', $data['id'], 'Client not found');
+ $client = $this->getDi()['db']->getExistingModelById('Client', $data['id'], 'Client not found');
- $service = $this->di['mod_service']('client');
+ $service = $this->getDi()['mod_service']('client');
$service->addFunds($client, $data['amount'], $data['description'], $data);
return true;
@@ -427,15 +427,15 @@ class Admin extends \Api_Abstract
*/
public function batch_expire_password_reminders(): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('client', 'delete', null, $this->identity);
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('client', 'delete', null, $this->identity);
- $service = $this->di['mod_service']('client');
+ $service = $this->getDi()['mod_service']('client');
$expired = $service->getExpiredPasswordReminders();
foreach ($expired as $model) {
- $this->di['db']->trash($model);
+ $this->getDi()['db']->trash($model);
}
- $this->di['logger']->info('Executed action to delete expired clients password reminders');
+ $this->getDi()['logger']->info('Executed action to delete expired clients password reminders');
return true;
}
@@ -449,10 +449,10 @@ class Admin extends \Api_Abstract
*/
public function login_history_get_list($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('client', 'view_login_history');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('client', 'view_login_history');
[$q, $params] = $this->getService()->getHistorySearchQuery($data);
- $pager = $this->di['pager']->getPaginatedResultSet($q, $params, PaginationOptions::fromArray($data));
+ $pager = $this->getDi()['pager']->getPaginatedResultSet($q, $params, PaginationOptions::fromArray($data));
foreach ($pager['list'] as $key => $item) {
$pager['list'][$key] = [
@@ -478,9 +478,9 @@ class Admin extends \Api_Abstract
*/
public function get_statuses($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('client', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('client', 'view');
- $service = $this->di['mod_service']('client');
+ $service = $this->getDi()['mod_service']('client');
return $service->counter();
}
@@ -492,9 +492,9 @@ class Admin extends \Api_Abstract
*/
public function group_get_pairs($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('client', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('client', 'view');
- $service = $this->di['mod_service']('client');
+ $service = $this->getDi()['mod_service']('client');
return $service->getGroupPairs();
}
@@ -507,7 +507,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['title' => 'Group title is missing'])]
public function group_create($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('client', 'manage_groups');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('client', 'manage_groups');
return $this->getService()->createGroup($data);
}
@@ -520,13 +520,13 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Group ID is missing'])]
public function group_update($data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('client', 'manage_groups');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('client', 'manage_groups');
- $model = $this->di['db']->getExistingModelById('ClientGroup', $data['id'], 'Group not found');
+ $model = $this->getDi()['db']->getExistingModelById('ClientGroup', $data['id'], 'Group not found');
$model->title = $data['title'] ?? $model->title;
$model->updated_at = date('Y-m-d H:i:s');
- $this->di['db']->store($model);
+ $this->getDi()['db']->store($model);
return true;
}
@@ -539,11 +539,11 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Group ID is missing'])]
public function group_delete($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('client', 'manage_groups');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('client', 'manage_groups');
- $model = $this->di['db']->getExistingModelById('ClientGroup', $data['id'], 'Group not found');
+ $model = $this->getDi()['db']->getExistingModelById('ClientGroup', $data['id'], 'Group not found');
- $clients = $this->di['db']->find('Client', 'client_group_id = :group_id', [':group_id' => $data['id']]);
+ $clients = $this->getDi()['db']->find('Client', 'client_group_id = :group_id', [':group_id' => $data['id']]);
if (Tools::safeCount($clients) > 0) {
throw new InformationException('Group has clients assigned. Please reassign them first.');
@@ -560,11 +560,11 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Group ID is missing'])]
public function group_get($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('client', 'manage_groups');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('client', 'manage_groups');
- $model = $this->di['db']->getExistingModelById('ClientGroup', $data['id'], 'Group not found');
+ $model = $this->getDi()['db']->getExistingModelById('ClientGroup', $data['id'], 'Group not found');
- return $this->di['db']->toArray($model);
+ return $this->getDi()['db']->toArray($model);
}
/**
@@ -573,7 +573,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['ids' => 'IDs were not passed'])]
public function batch_delete($data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('client', 'bulk_delete');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('client', 'bulk_delete');
foreach ($data['ids'] as $id) {
$this->delete(['id' => $id]);
@@ -584,7 +584,7 @@ class Admin extends \Api_Abstract
public function export_csv($data): Response
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('client', 'export');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('client', 'export');
$data['headers'] ??= [];
diff --git a/src/modules/Client/Api/Client.php b/src/modules/Client/Api/Client.php
index 007f2bb48..220ebbbda 100644
--- a/src/modules/Client/Api/Client.php
+++ b/src/modules/Client/Api/Client.php
@@ -27,14 +27,14 @@ class Client extends \Api_Abstract
*/
public function balance_get_list($data)
{
- $service = $this->di['mod_service']('Client', 'Balance');
+ $service = $this->getDi()['mod_service']('Client', 'Balance');
$data['client_id'] = $this->identity->id;
[$q, $params] = $service->getSearchQuery($data);
- $pager = $this->di['pager']->getPaginatedResultSet($q, $params, PaginationOptions::fromArray($data));
+ $pager = $this->getDi()['pager']->getPaginatedResultSet($q, $params, PaginationOptions::fromArray($data));
foreach ($pager['list'] as $key => $item) {
- $balance = $this->di['db']->getExistingModelById('ClientBalance', $item['id'], 'Balance not found');
+ $balance = $this->getDi()['db']->getExistingModelById('ClientBalance', $item['id'], 'Balance not found');
$pager['list'][$key] = $service->toApiArray($balance);
}
@@ -48,7 +48,7 @@ class Client extends \Api_Abstract
*/
public function balance_get_total()
{
- $service = $this->di['mod_service']('Client', 'Balance');
+ $service = $this->getDi()['mod_service']('Client', 'Balance');
return $service->getClientBalance($this->identity);
}
@@ -67,8 +67,8 @@ class Client extends \Api_Abstract
return true;
}
- $this->di['rate_limiter']->consumeOrThrow('client_email_verification_resend_ip', (string) $this->getIp());
- $this->di['rate_limiter']->consumeOrThrow('client_email_verification_resend_account', 'client:' . $client->id);
+ $this->getDi()['rate_limiter']->consumeOrThrow('client_email_verification_resend_ip', (string) $this->getIp());
+ $this->getDi()['rate_limiter']->consumeOrThrow('client_email_verification_resend_account', 'client:' . $client->id);
return $this->getService()->sendEmailConfirmationForClient($client);
}
diff --git a/src/modules/Client/Api/Guest.php b/src/modules/Client/Api/Guest.php
index 25f43f998..18a5d9ccc 100644
--- a/src/modules/Client/Api/Guest.php
+++ b/src/modules/Client/Api/Guest.php
@@ -58,24 +58,24 @@ class Guest extends \Api_Abstract
#[RequiredParams(['email' => 'Email required', 'first_name' => 'First name required', 'password' => 'Password required', 'password_confirm' => 'Password confirmation required'])]
public function create($data = []): int
{
- $this->di['rate_limiter']->consumeOrThrow('client_signup', (string) $this->getIp());
+ $this->getDi()['rate_limiter']->consumeOrThrow('client_signup', (string) $this->getIp());
- $config = $this->di['mod_config']('client');
+ $config = $this->getDi()['mod_config']('client');
if (isset($config['disable_signup']) && $config['disable_signup']) {
throw new \FOSSBilling\InformationException('New registrations are temporarily disabled');
}
- $this->di['validator']->passwordsMatch($data);
+ $this->getDi()['validator']->passwordsMatch($data);
$this->getService()->checkExtraRequiredFields($data);
$this->getService()->checkCustomFields($data);
- $this->di['validator']->isPasswordStrong($data['password']);
+ $this->getDi()['validator']->isPasswordStrong($data['password']);
$service = $this->getService();
$email = $data['email'] ?? null;
- $email = $this->di['tools']->validateAndSanitizeEmail($email);
+ $email = $this->getDi()['tools']->validateAndSanitizeEmail($email);
$email = strtolower(trim((string) $email));
if ($service->clientAlreadyExists($email)) {
throw new \FOSSBilling\InformationException('This email address is already registered.');
@@ -111,36 +111,36 @@ class Guest extends \Api_Abstract
$startedAt = microtime(true);
try {
- $this->di['tools']->validateAndSanitizeEmail($data['email'], true, false);
+ $this->getDi()['tools']->validateAndSanitizeEmail($data['email'], true, false);
$event_params = $data;
$event_params['ip'] = $this->ip;
- $this->di['events_manager']->fire(['event' => 'onBeforeClientLogin', 'params' => $event_params]);
+ $this->getDi()['events_manager']->fire(['event' => 'onBeforeClientLogin', 'params' => $event_params]);
$service = $this->getService();
$client = $service->authorizeClient($data['email'], $data['password']);
if (!$client instanceof \Model_Client) {
- $this->di['events_manager']->fire(['event' => 'onEventClientLoginFailed', 'params' => $event_params]);
+ $this->getDi()['events_manager']->fire(['event' => 'onEventClientLoginFailed', 'params' => $event_params]);
throw new \FOSSBilling\InformationException('Please check your login details.', [], 401);
}
- $this->di['events_manager']->fire(['event' => 'onAfterClientLogin', 'params' => ['id' => $client->id, 'ip' => $this->ip]]);
+ $this->getDi()['events_manager']->fire(['event' => 'onAfterClientLogin', 'params' => ['id' => $client->id, 'ip' => $this->ip]]);
- $oldSession = $this->di['session']->getId();
- $this->di['session']->regenerateId();
+ $oldSession = $this->getDi()['session']->getId();
+ $this->getDi()['session']->regenerateId();
$result = $service->toSessionArray($client);
- $this->di['session']->set('client_id', $client->id);
+ $this->getDi()['session']->set('client_id', $client->id);
- $this->di['logger']->info('Client #%s logged in', $client->id);
- $this->di['session']->delete('redirect_uri');
+ $this->getDi()['logger']->info('Client #%s logged in', $client->id);
+ $this->getDi()['session']->delete('redirect_uri');
if (!headers_sent() && !empty($client->lang)) {
setcookie('fb_locale', (string) $client->lang, ['expires' => strtotime('+1 month'), 'path' => '/']);
}
- $this->di['mod_service']('cart')->transferFromOtherSession($oldSession);
+ $this->getDi()['mod_service']('cart')->transferFromOtherSession($oldSession);
return $result;
} finally {
@@ -159,40 +159,40 @@ class Guest extends \Api_Abstract
$startedAt = microtime(true);
try {
- $this->di['events_manager']->fire(['event' => 'onBeforePasswordResetClient']);
- $service = $this->di['mod_service']('client');
+ $this->getDi()['events_manager']->fire(['event' => 'onBeforePasswordResetClient']);
+ $service = $this->getDi()['mod_service']('client');
// Sanitize email
- $data['email'] = $this->di['tools']->validateAndSanitizeEmail($data['email']);
+ $data['email'] = $this->getDi()['tools']->validateAndSanitizeEmail($data['email']);
- $ipLimit = $this->di['rate_limiter']->consume('client_password_reset_ip', (string) $this->getIp());
+ $ipLimit = $this->getDi()['rate_limiter']->consume('client_password_reset_ip', (string) $this->getIp());
if ($ipLimit->isLimited()) {
- $this->di['logger']->setChannel('security')->info('Client password reset rate limited from IP %s: email %s', $this->getIp(), $data['email']);
+ $this->getDi()['logger']->setChannel('security')->info('Client password reset rate limited from IP %s: email %s', $this->getIp(), $data['email']);
return true;
}
- $emailLimit = $this->di['rate_limiter']->consume('client_password_reset_email', (string) $data['email']);
+ $emailLimit = $this->getDi()['rate_limiter']->consume('client_password_reset_email', (string) $data['email']);
if ($emailLimit->isLimited()) {
- $this->di['logger']->setChannel('security')->info('Client password reset rate limited for email %s from IP %s', $data['email'], $this->getIp());
+ $this->getDi()['logger']->setChannel('security')->info('Client password reset rate limited for email %s from IP %s', $data['email'], $this->getIp());
return true;
}
$this->checkPasswordResetCaptcha($data);
- $this->di['events_manager']->fire(['event' => 'onBeforeGuestPasswordResetRequest', 'params' => $data]);
+ $this->getDi()['events_manager']->fire(['event' => 'onBeforeGuestPasswordResetRequest', 'params' => $data]);
// Fetch the client by email
- $c = $this->di['db']->findOne('Client', 'email = ?', [$data['email']]);
+ $c = $this->getDi()['db']->findOne('Client', 'email = ?', [$data['email']]);
if (!$c instanceof \Model_Client) {
- $this->di['logger']->setChannel('security')->info('Client password reset requested for unknown email %s from IP %s', $data['email'], $this->getIp());
+ $this->getDi()['logger']->setChannel('security')->info('Client password reset requested for unknown email %s from IP %s', $data['email'], $this->getIp());
return true;
}
if ($c->status !== \Model_Client::ACTIVE) {
- $this->di['logger']->setChannel('security')->info('Client password reset requested for ineligible client #%s from IP %s: email %s, account status %s', $c->id, $this->getIp(), $data['email'], $c->status);
+ $this->getDi()['logger']->setChannel('security')->info('Client password reset requested for ineligible client #%s from IP %s: email %s, account status %s', $c->id, $this->getIp(), $data['email'], $c->status);
return true;
}
@@ -200,7 +200,7 @@ class Guest extends \Api_Abstract
$hash = $service->createPasswordResetRequestForClient($c);
$service->sendPasswordResetRequestEmailForClient($c, $hash);
- $this->di['logger']->setChannel('security')->info('Client password reset email queued for client #%s from IP %s: email %s', $c->id, $this->getIp(), $data['email']);
+ $this->getDi()['logger']->setChannel('security')->info('Client password reset email queued for client #%s from IP %s: email %s', $c->id, $this->getIp(), $data['email']);
return true;
} finally {
@@ -210,12 +210,12 @@ class Guest extends \Api_Abstract
private function checkPasswordResetCaptcha(array $data): void
{
- $extensionService = $this->di['mod_service']('extension');
+ $extensionService = $this->getDi()['mod_service']('extension');
if (!$extensionService->isExtensionActive('mod', 'antispam')) {
return;
}
- $this->di['mod_service']('Antispam')->checkCaptcha($data);
+ $this->getDi()['mod_service']('Antispam')->checkCaptcha($data);
}
#[RequiredParams(['hash' => 'No Hash provided', 'password' => 'Password required', 'password_confirm' => 'Password confirmation required'])]
@@ -224,47 +224,47 @@ class Guest extends \Api_Abstract
$startedAt = microtime(true);
try {
- $this->di['rate_limiter']->consumeOrThrow('client_password_reset_confirm_post_ip', (string) $this->getIp());
+ $this->getDi()['rate_limiter']->consumeOrThrow('client_password_reset_confirm_post_ip', (string) $this->getIp());
- $this->di['events_manager']->fire(['event' => 'onBeforeClientProfilePasswordReset', 'params' => $data['hash']]);
+ $this->getDi()['events_manager']->fire(['event' => 'onBeforeClientProfilePasswordReset', 'params' => $data['hash']]);
- $this->di['validator']->passwordsMatch($data);
- $this->di['validator']->isPasswordStrong($data['password']);
+ $this->getDi()['validator']->passwordsMatch($data);
+ $this->getDi()['validator']->isPasswordStrong($data['password']);
- $reset = $this->di['db']->findOne('ClientPasswordReset', 'hash = ?', [$data['hash']]);
+ $reset = $this->getDi()['db']->findOne('ClientPasswordReset', 'hash = ?', [$data['hash']]);
if (!$reset instanceof \Model_ClientPasswordReset) {
- $this->di['logger']->setChannel('security')->info('Client password reset confirmation failed from IP %s: reset token not found', $this->getIp());
+ $this->getDi()['logger']->setChannel('security')->info('Client password reset confirmation failed from IP %s: reset token not found', $this->getIp());
throw new \FOSSBilling\InformationException('The link has expired or you have already reset your password.');
}
if (strtotime($reset->created_at) - time() + 900 < 0) {
- $this->di['logger']->setChannel('security')->info('Client password reset confirmation failed for client #%s from IP %s: reset token expired', $reset->client_id, $this->getIp());
+ $this->getDi()['logger']->setChannel('security')->info('Client password reset confirmation failed for client #%s from IP %s: reset token expired', $reset->client_id, $this->getIp());
throw new \FOSSBilling\InformationException('The link has expired or you have already reset your password.');
}
- $c = $this->di['db']->getExistingModelById('Client', $reset->client_id, 'Client not found');
+ $c = $this->getDi()['db']->getExistingModelById('Client', $reset->client_id, 'Client not found');
if ($c->status !== \Model_Client::ACTIVE) {
- $this->di['logger']->setChannel('security')->info('Client password reset confirmation failed for client #%s from IP %s: account status %s', $c->id, $this->getIp(), $c->status);
+ $this->getDi()['logger']->setChannel('security')->info('Client password reset confirmation failed for client #%s from IP %s: account status %s', $c->id, $this->getIp(), $c->status);
throw new \FOSSBilling\InformationException('The link has expired or you have already reset your password.');
}
- $c->pass = $this->di['password']->hashIt($data['password']);
- $this->di['db']->store($c);
+ $c->pass = $this->getDi()['password']->hashIt($data['password']);
+ $this->getDi()['db']->store($c);
- $this->di['logger']->setChannel('security')->info('Client password reset completed for client #%s from IP %s', $c->id, $this->getIp());
+ $this->getDi()['logger']->setChannel('security')->info('Client password reset completed for client #%s from IP %s', $c->id, $this->getIp());
// send email
$email = [];
$email['to_client'] = $c->id;
$email['code'] = 'mod_client_password_reset_information';
- $emailService = $this->di['mod_service']('email');
+ $emailService = $this->getDi()['mod_service']('email');
$emailService->sendTemplate($email);
- $this->di['db']->trash($reset);
- $this->di['events_manager']->fire(['event' => 'onAfterClientProfilePasswordReset', 'params' => ['id' => $c->id]]);
+ $this->getDi()['db']->trash($reset);
+ $this->getDi()['events_manager']->fire(['event' => 'onAfterClientProfilePasswordReset', 'params' => ['id' => $c->id]]);
return true;
} finally {
@@ -294,7 +294,7 @@ class Guest extends \Api_Abstract
*/
public function required()
{
- $config = $this->di['mod_config']('client');
+ $config = $this->getDi()['mod_config']('client');
return $config['required'] ?? [];
}
@@ -304,14 +304,14 @@ class Guest extends \Api_Abstract
*/
public function custom_fields()
{
- $config = $this->di['mod_config']('client');
+ $config = $this->getDi()['mod_config']('client');
return $config['custom_fields'] ?? [];
}
public function is_email_validation_required(): bool
{
- $config = $this->di['mod_config']('client');
+ $config = $this->getDi()['mod_config']('client');
return (bool) ($config['require_email_confirmation'] ?? false);
}
diff --git a/src/modules/Client/Service.php b/src/modules/Client/Service.php
index e02e14a84..60ef11d18 100644
--- a/src/modules/Client/Service.php
+++ b/src/modules/Client/Service.php
@@ -629,7 +629,7 @@ class Service implements InjectionAwareInterface
$client->state = $data['state'] ?? null;
$client->postcode = $data['postcode'] ?? null;
$client->country = !empty($data['country']) ? $data['country'] : (!empty($systemCfg['default_country']) ? $systemCfg['default_country'] : null);
- if ($client->country !== null && $client->country !== '' && !Countries::exists($client->country)) {
+ if ($client->country !== null && !Countries::exists($client->country)) {
throw new InformationException('Invalid country code: :code', [':code' => $client->country]);
}
$client->document_type = $data['document_type'] ?? null;
diff --git a/src/modules/Client/tests/E2E/ApiGuestTest.php b/src/modules/Client/tests/E2E/ApiGuestTest.php
new file mode 100644
index 000000000..df362c63b
--- /dev/null
+++ b/src/modules/Client/tests/E2E/ApiGuestTest.php
@@ -0,0 +1,80 @@
+ $clientId]);
+ expect($result->wasSuccessful())->toBeTrue($result);
+ expect($result->getResult())->toBeTrue();
+});
+
+test('phone ccmust be greater than zero', function (): void {
+ $password = 'A1a' . bin2hex(random_bytes(6));
+ $result = Tests\Helpers\ApiClient::request('guest/client/create', [
+ 'email' => 'test_' . uniqid() . '@example.com',
+ 'first_name' => 'Test',
+ 'password' => $password,
+ 'password_confirm' => $password,
+ 'phone_cc' => -1,
+ ]);
+
+ expect($result->wasSuccessful())->toBeFalse();
+});
+
+test('phone ccmaximum limit', function (): void {
+ $password = 'A1a' . bin2hex(random_bytes(6));
+ $result = Tests\Helpers\ApiClient::request('guest/client/create', [
+ 'email' => 'test_' . uniqid() . '@example.com',
+ 'first_name' => 'Test',
+ 'password' => $password,
+ 'password_confirm' => $password,
+ 'phone_cc' => 1000,
+ ]);
+
+ expect($result->wasSuccessful())->toBeFalse();
+});
+
+test('phone number length validation', function (): void {
+ $password = 'A1a' . bin2hex(random_bytes(6));
+ $result = Tests\Helpers\ApiClient::request('guest/client/create', [
+ 'email' => 'test_' . uniqid() . '@example.com',
+ 'first_name' => 'Test',
+ 'password' => $password,
+ 'password_confirm' => $password,
+ 'phone' => '123456789101123',
+ ]);
+
+ expect($result->wasSuccessful())->toBeFalse();
+});
+
+function clientCreateClient(): int
+{
+ $password = 'A1a' . bin2hex(random_bytes(6));
+ $result = Tests\Helpers\ApiClient::request('guest/client/create', [
+ 'email' => 'client_' . uniqid() . '@example.com',
+ 'first_name' => 'Test',
+ 'password' => $password,
+ 'password_confirm' => $password,
+ 'phone_cc' => 1,
+ 'phone' => '(216) 245-2368',
+ ]);
+ expect($result->wasSuccessful())->toBeTrue($result);
+ expect($result->getResult())->toBeInt();
+
+ return (int) $result->getResult();
+}
diff --git a/src/modules/Client/tests/Unit/Api/AdminTest.php b/src/modules/Client/tests/Unit/Api/AdminTest.php
new file mode 100644
index 000000000..acec1a980
--- /dev/null
+++ b/src/modules/Client/tests/Unit/Api/AdminTest.php
@@ -0,0 +1,741 @@
+setDi($di);
+ $getDi = $adminClient->getDi();
+ expect($getDi)->toEqual($di);
+});
+
+test('getList returns array', function (): void {
+ $adminClient = new Box\Mod\Client\Api\Admin();
+ $simpleResultArr = [
+ 'list' => [
+ ['id' => 1],
+ ],
+ ];
+
+ $serviceMock = Mockery::mock(Box\Mod\Client\Service::class);
+ $serviceMock
+ ->shouldReceive('getSearchQuery')
+ ->atLeast()->once()
+ ->andReturn(['String', []]);
+ $serviceMock
+ ->shouldReceive('toApiArray')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $pagerMock = Mockery::mock(FOSSBilling\Pagination::class)->makePartial();
+
+ $pagerMock
+ ->shouldReceive('getPaginatedResultSet')
+ ->atLeast()->once()
+ ->andReturn($simpleResultArr);
+
+ $model = new Model_Client();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $di = container();
+ $di['pager'] = $pagerMock;
+ $di['db'] = $dbMock;
+
+ $adminClient->setService($serviceMock);
+ $adminClient->setDi($di);
+ $data = [];
+
+ $result = $adminClient->get_list($data);
+ expect($result)->toBeArray();
+});
+
+test('getPairs returns array', function (): void {
+ $adminClient = new Box\Mod\Client\Api\Admin();
+ $serviceMock = Mockery::mock(Box\Mod\Client\Service::class);
+ $serviceMock->shouldReceive('getPairs')->atLeast()->once()->andReturn([]);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(moduleService(['client' => $serviceMock]));
+
+ $adminClient->setDi($di);
+
+ $data = ['id' => 1];
+ $result = $adminClient->get_pairs($data);
+ expect($result)->toBeArray();
+});
+
+test('get returns array', function (): void {
+ $adminClient = new Box\Mod\Client\Api\Admin();
+ $model = new Model_Client();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $serviceMock = Mockery::mock(Box\Mod\Client\Service::class);
+ $serviceMock->shouldReceive('get')->atLeast()->once()->andReturn($model);
+ $serviceMock
+ ->shouldReceive('toApiArray')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $adminClient->setService($serviceMock);
+
+ $result = $adminClient->get([]);
+ expect($result)->toBeArray();
+});
+
+test('login returns array', function (): void {
+ $adminClient = new Box\Mod\Client\Api\Admin();
+ $model = new Model_Client();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')->atLeast()->once()->andReturn($model);
+
+ $sessionArray = [
+ 'id' => 1,
+ 'email' => 'email@example.com',
+ 'name' => 'John Smith',
+ 'role' => 'client',
+ ];
+ $serviceMock = Mockery::mock(Box\Mod\Client\Service::class);
+ $serviceMock->shouldReceive('toSessionArray')->atLeast()->once()->andReturn($sessionArray);
+
+ $sessionMock = Mockery::mock(FOSSBilling\Session::class);
+ $sessionMock->shouldReceive('set')->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(moduleService(['client' => $serviceMock]));
+ $di['session'] = $sessionMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $validatorStub = $this->createStub(FOSSBilling\Validate::class);
+ $di['validator'] = $validatorStub;
+
+ $adminClient->setDi($di);
+
+ $data = ['id' => 1];
+ $result = $adminClient->login($data);
+ expect($result)->toBeArray();
+});
+
+test('create returns int', function (): void {
+ $adminClient = new Box\Mod\Client\Api\Admin();
+ $data = [
+ 'email' => 'email@example.com',
+ 'first_name' => 'John', 'password' => 'StrongPass123',
+ ];
+
+ $model = new Model_Client();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $serviceMock = Mockery::mock(Box\Mod\Client\Service::class);
+ $serviceMock->shouldReceive('emailAlreadyRegistered')->atLeast()->once()->andReturn(false);
+ $serviceMock->shouldReceive('adminCreateClient')->atLeast()->once()->andReturn(1);
+
+ $eventMock = Mockery::mock('\Box_EventManager');
+ $eventMock->shouldReceive('fire')->atLeast()->once();
+
+ $toolsMock = Mockery::mock(FOSSBilling\Tools::class);
+ $toolsMock->shouldReceive('validateAndSanitizeEmail')->atLeast()->once();
+
+ $di = container();
+ $di['events_manager'] = $eventMock;
+ $di['tools'] = $toolsMock;
+
+ $adminClient->setDi($di);
+ $adminClient->setService($serviceMock);
+
+ $result = $adminClient->create($data);
+
+ expect($result)->toBeInt();
+});
+
+test('create throws exception when email is already registered', function (): void {
+ $adminClient = new Box\Mod\Client\Api\Admin();
+ $data = [
+ 'email' => 'email@example.com',
+ 'first_name' => 'John', 'password' => 'StrongPass123',
+ ];
+
+ $serviceMock = Mockery::mock(Box\Mod\Client\Service::class);
+ $serviceMock->shouldReceive('emailAlreadyRegistered')->atLeast()->once()->andReturn(true);
+
+ $toolsMock = Mockery::mock(FOSSBilling\Tools::class);
+ $toolsMock->shouldReceive('validateAndSanitizeEmail')->atLeast()->once();
+
+ $di = container();
+ $di['tools'] = $toolsMock;
+
+ $adminClient->setDi($di);
+ $adminClient->setService($serviceMock);
+
+ $adminClient->create($data);
+})->throws(FOSSBilling\Exception::class, 'This email address is already registered.');
+
+test('delete returns true', function (): void {
+ $adminClient = new Box\Mod\Client\Api\Admin();
+ $data = ['id' => 1];
+
+ $model = new Model_Client();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')->atLeast()->once()->andReturn($model);
+
+ $eventMock = Mockery::mock('\Box_EventManager');
+ $eventMock->shouldReceive('fire')->atLeast()->once();
+
+ $serviceMock = Mockery::mock(Box\Mod\Client\Service::class)->makePartial();
+ $serviceMock->shouldReceive('remove')->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['events_manager'] = $eventMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $validatorStub = $this->createStub(FOSSBilling\Validate::class);
+ $di['validator'] = $validatorStub;
+
+ $adminClient->setDi($di);
+ $adminClient->setService($serviceMock);
+ $result = $adminClient->delete($data);
+ expect($result)->toBeTrue();
+});
+
+test('update returns true', function (): void {
+ $adminClient = new Box\Mod\Client\Api\Admin();
+ $data = [
+ 'id' => 1,
+ 'first_name' => 'John', 'password' => 'StrongPass123',
+ 'last_name' => 'Smith',
+ 'aid' => '0',
+ 'gender' => 'male',
+ 'birthday' => '1999-01-01',
+ 'company' => 'LTD Testing',
+ 'company_vat' => 'VAT0007',
+ 'address_1' => 'United States',
+ 'address_2' => 'Utah',
+ 'phone_cc' => '+1',
+ 'phone' => '555-345-345',
+ 'document_type' => 'doc',
+ 'document_nr' => '1',
+ 'notes' => 'none',
+ 'country' => 'US',
+ 'postcode' => 'IL-11123',
+ 'city' => 'Chicaco',
+ 'state' => 'IL',
+ 'currency' => 'USD',
+ 'tax_exempt' => 'N/A',
+ 'created_at' => '2012-05-10',
+ 'email' => 'test@example.com',
+ 'group_id' => 1,
+ 'status' => 'test status',
+ 'company_number' => '1234',
+ 'type' => '',
+ 'lang' => 'en',
+ 'custom_1' => '',
+ 'custom_2' => '',
+ 'custom_3' => '',
+ 'custom_4' => '',
+ 'custom_5' => '',
+ 'custom_6' => '',
+ 'custom_7' => '',
+ 'custom_8' => '',
+ 'custom_9' => '',
+ 'custom_10' => '',
+ ];
+
+ $model = new Model_Client();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')->atLeast()->once()->andReturn($model);
+ $dbMock
+ ->shouldReceive('store')->atLeast()->once()->andReturn(1);
+
+ $serviceMock = Mockery::mock(Box\Mod\Client\Service::class);
+ $serviceMock->shouldReceive('emailAlreadyRegistered')->atLeast()->once()->andReturn(false);
+ $serviceMock->shouldReceive('canChangeCurrency')->atLeast()->once()->andReturn(true);
+
+ $eventMock = Mockery::mock('\Box_EventManager');
+ $eventMock->shouldReceive('fire')->atLeast()->once();
+
+ $toolsMock = Mockery::mock(FOSSBilling\Tools::class);
+ $toolsMock->shouldReceive('validateAndSanitizeEmail')->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(moduleService(['client' => $serviceMock]));
+ $di['events_manager'] = $eventMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $di['tools'] = $toolsMock;
+
+ $adminClient->setDi($di);
+ $result = $adminClient->update($data);
+ expect($result)->toBeTrue();
+});
+
+test('update throws exception when email is already registered', function (): void {
+ $adminClient = new Box\Mod\Client\Api\Admin();
+ $data = [
+ 'id' => 1,
+ 'first_name' => 'John', 'password' => 'StrongPass123',
+ 'last_name' => 'Smith',
+ 'aid' => '0',
+ 'gender' => 'male',
+ 'birthday' => '1999-01-01',
+ 'company' => 'LTD Testing',
+ 'company_vat' => 'VAT0007',
+ 'address_1' => 'United States',
+ 'address_2' => 'Utah',
+ 'phone_cc' => '+1',
+ 'phone' => '555-345-345',
+ 'document_type' => 'doc',
+ 'document_nr' => '1',
+ 'notes' => 'none',
+ 'country' => 'Moon',
+ 'postcode' => 'IL-11123',
+ 'city' => 'Chicaco',
+ 'state' => 'IL',
+ 'currency' => 'USD',
+ 'tax_exempt' => 'N/A',
+ 'created_at' => '2012-05-10',
+ 'email' => 'test@example.com',
+ 'group_id' => 1,
+ 'status' => 'test status',
+ 'company_number' => '1234',
+ 'type' => '',
+ 'lang' => 'en',
+ 'custom_1' => '',
+ 'custom_2' => '',
+ 'custom_3' => '',
+ 'custom_4' => '',
+ 'custom_5' => '',
+ 'custom_6' => '',
+ 'custom_7' => '',
+ 'custom_8' => '',
+ 'custom_9' => '',
+ 'custom_10' => '',
+ ];
+
+ $model = new Model_Client();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')->atLeast()->once()->andReturn($model);
+
+ $serviceMock = Mockery::mock(Box\Mod\Client\Service::class);
+ $serviceMock->shouldReceive('emailAlreadyRegistered')->atLeast()->once()->andReturn(true);
+
+ $eventMock = Mockery::mock('\Box_EventManager');
+ $eventMock->shouldReceive('fire');
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(moduleService(['client' => $serviceMock]));
+ $di['events_manager'] = $eventMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $di['validator'] = new FOSSBilling\Validate();
+
+ $toolsMock = Mockery::mock(FOSSBilling\Tools::class);
+ $toolsMock->shouldReceive('validateAndSanitizeEmail')->atLeast()->once();
+ $di['tools'] = $toolsMock;
+
+ $adminClient->setDi($di);
+
+ $adminClient->update($data);
+})->throws(FOSSBilling\Exception::class, 'This email address is already registered.');
+
+test('update throws exception when id is not passed', function (): void {
+ $adminClient = new Box\Mod\Client\Api\Admin();
+ $data = [];
+
+ $di = container();
+
+ $di['validator'] = new FOSSBilling\Validate();
+ $adminClient->setDi($di);
+
+ // Validate required parameters before calling update
+ $validator = $di['validator'];
+ $validator->checkRequiredParamsForArray(['id' => 'Client ID was not passed'], $data);
+
+ $adminClient->update($data);
+})->throws(FOSSBilling\Exception::class, 'Client ID was not passed');
+
+test('changePassword returns true', function (): void {
+ $adminClient = new Box\Mod\Client\Api\Admin();
+ $data = [
+ 'id' => 1,
+ 'password' => 'strongPass',
+ 'password_confirm' => 'strongPass',
+ ];
+
+ $model = new Model_Client();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')->atLeast()->once()->andReturn($model);
+
+ $dbMock
+ ->shouldReceive('store')->atLeast()->once()->andReturn(1);
+
+ $eventMock = Mockery::mock('\Box_EventManager');
+ $eventMock->shouldReceive('fire')->atLeast()->once();
+
+ $passwordMock = Mockery::mock(FOSSBilling\PasswordManager::class);
+ $passwordMock->shouldReceive('hashIt')->atLeast()->once()->with($data['password']);
+
+ $profileService = Mockery::mock(Box\Mod\Profile\Service::class);
+ $profileService->shouldReceive('invalidateSessions')->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['events_manager'] = $eventMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $di['password'] = $passwordMock;
+ $validatorStub = $this->createStub(FOSSBilling\Validate::class);
+ $di['validator'] = $validatorStub;
+ $di['mod_service'] = $di->protect(moduleService(['profile' => $profileService]));
+
+ $adminClient->setDi($di);
+
+ $result = $adminClient->change_password($data);
+ expect($result)->toBeTrue();
+});
+
+test('changePassword throws exception when passwords do not match', function (): void {
+ $adminClient = new Box\Mod\Client\Api\Admin();
+ $data = [
+ 'id' => 1,
+ 'password' => 'strongPass',
+ 'password_confirm' => 'NotIdentical',
+ ];
+
+ $validatorStub = new FOSSBilling\Validate();
+
+ $di = container();
+ $di['validator'] = $validatorStub;
+ $di['mod_service'] = $di->protect(moduleService());
+ $adminClient->setDi($di);
+
+ $adminClient->change_password($data);
+})->throws(FOSSBilling\Exception::class, 'Passwords do not match');
+
+test('balanceGetList returns array', function (): void {
+ $adminClient = new Box\Mod\Client\Api\Admin();
+ $simpleResultArr = [
+ 'list' => [
+ [
+ 'id' => 1,
+ 'description' => 'Testing',
+ 'amount' => '1.00',
+ 'currency' => 'USD',
+ 'created_at' => date('Y:m:d H:i:s'),
+ ],
+ ],
+ ];
+
+ $data = [];
+
+ $serviceMock = Mockery::mock(Box\Mod\Client\ServiceBalance::class);
+ $serviceMock
+ ->shouldReceive('getSearchQuery')
+ ->atLeast()->once()
+ ->andReturn(['String', []]);
+
+ $pagerMock = Mockery::mock(FOSSBilling\Pagination::class)->makePartial();
+
+ $pagerMock
+ ->shouldReceive('getPaginatedResultSet')
+ ->atLeast()->once()
+ ->andReturn($simpleResultArr);
+
+ $model = new Model_ClientBalance();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $di = container();
+ $di['mod_service'] = $di->protect(moduleService(['client:balance' => $serviceMock, 'client' => $serviceMock]));
+ $di['pager'] = $pagerMock;
+
+ $adminClient->setDi($di);
+
+ $result = $adminClient->balance_get_list($data);
+ expect($result)->toBeArray();
+});
+
+test('balanceDelete returns true', function (): void {
+ $adminClient = new Box\Mod\Client\Api\Admin();
+ $data = [
+ 'id' => 1,
+ ];
+
+ $model = new Model_ClientBalance();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')->atLeast()->once()->andReturn($model);
+
+ $dbMock->shouldReceive('trash')->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $validatorStub = $this->createStub(FOSSBilling\Validate::class);
+ $di['validator'] = $validatorStub;
+
+ $adminClient->setDi($di);
+
+ $result = $adminClient->balance_delete($data);
+ expect($result)->toBeTrue();
+});
+
+test('balanceAddFunds returns true', function (): void {
+ $adminClient = new Box\Mod\Client\Api\Admin();
+ $data = [
+ 'id' => 1,
+ 'amount' => '1.00',
+ 'description' => 'testDescription',
+ ];
+
+ $model = new Model_Client();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')->atLeast()->once()->andReturn($model);
+
+ $serviceMock = Mockery::mock(Box\Mod\Client\Service::class);
+ $serviceMock->shouldReceive('addFunds')->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(moduleService(['client' => $serviceMock]));
+
+ $validatorStub = $this->createStub(FOSSBilling\Validate::class);
+ $di['validator'] = $validatorStub;
+
+ $adminClient->setDi($di);
+
+ $result = $adminClient->balance_add_funds($data);
+ expect($result)->toBeTrue();
+});
+
+test('batchExpirePasswordReminders returns true', function (): void {
+ $adminClient = new Box\Mod\Client\Api\Admin();
+ $expiredArr = [
+ new Model_ClientPasswordReset(),
+ ];
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('trash')->atLeast()->once();
+
+ $serviceMock = Mockery::mock(Box\Mod\Client\Service::class);
+ $serviceMock->shouldReceive('getExpiredPasswordReminders')->atLeast()->once()->andReturn($expiredArr);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(moduleService(['client' => $serviceMock]));
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $adminClient->setDi($di);
+
+ $result = $adminClient->batch_expire_password_reminders();
+ expect($result)->toBeTrue();
+});
+
+test('loginHistoryGetList returns array', function (): void {
+ $adminClient = new Box\Mod\Client\Api\Admin();
+ $data = [];
+ $pagerResultSet = [
+ 'list' => [],
+ ];
+
+ $serviceMock = Mockery::mock(Box\Mod\Client\Service::class);
+ $serviceMock
+ ->shouldReceive('getHistorySearchQuery')
+ ->atLeast()->once()
+ ->andReturn(['String', []]);
+
+ $pagerMock = Mockery::mock(FOSSBilling\Pagination::class)->makePartial();
+
+ $pagerMock
+ ->shouldReceive('getPaginatedResultSet')
+ ->atLeast()->once()
+ ->andReturn($pagerResultSet);
+
+ $di = container();
+ $di['pager'] = $pagerMock;
+
+ $adminClient->setDi($di);
+ $adminClient->setService($serviceMock);
+
+ $result = $adminClient->login_history_get_list($data);
+ expect($result)->toBeArray();
+});
+
+test('getStatuses returns array', function (): void {
+ $adminClient = new Box\Mod\Client\Api\Admin();
+ $serviceMock = Mockery::mock(Box\Mod\Client\Service::class);
+ $serviceMock->shouldReceive('counter')->atLeast()->once()->andReturn([]);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(moduleService(['client' => $serviceMock]));
+
+ $adminClient->setDi($di);
+
+ $result = $adminClient->get_statuses([]);
+ expect($result)->toBeArray();
+});
+
+test('groupGetPairs returns array', function (): void {
+ $adminClient = new Box\Mod\Client\Api\Admin();
+ $serviceMock = Mockery::mock(Box\Mod\Client\Service::class);
+ $serviceMock->shouldReceive('getGroupPairs')->atLeast()->once()->andReturn([]);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(moduleService(['client' => $serviceMock]));
+
+ $adminClient->setDi($di);
+
+ $result = $adminClient->group_get_pairs([]);
+ expect($result)->toBeArray();
+});
+
+test('groupCreate returns int', function (): void {
+ $adminClient = new Box\Mod\Client\Api\Admin();
+ $data['title'] = 'test Group';
+
+ $newGroupId = 1;
+ $serviceMock = Mockery::mock(Box\Mod\Client\Service::class);
+ $serviceMock->shouldReceive('createGroup')->atLeast()->once()->andReturn($newGroupId);
+
+ $di = container();
+ $adminClient->setService($serviceMock);
+ $adminClient->setDi($di);
+ $result = $adminClient->group_create($data);
+
+ expect($result)->toBeInt();
+ expect($result)->toEqual($newGroupId);
+});
+
+test('groupUpdate returns true', function (): void {
+ $adminClient = new Box\Mod\Client\Api\Admin();
+ $data['id'] = '2';
+ $data['title'] = 'test Group updated';
+
+ $model = new Model_ClientGroup();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')->atLeast()->once()->andReturn($model);
+
+ $dbMock
+ ->shouldReceive('store')->atLeast()->once()->andReturn(1);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $validatorStub = $this->createStub(FOSSBilling\Validate::class);
+ $di['validator'] = $validatorStub;
+
+ $adminClient->setDi($di);
+
+ $result = $adminClient->group_update($data);
+
+ expect($result)->toBeTrue();
+});
+
+test('groupDelete returns true', function (): void {
+ $adminClient = new Box\Mod\Client\Api\Admin();
+ $data['id'] = '2';
+
+ $model = new Model_ClientGroup();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')->atLeast()->once()->andReturn($model);
+ $dbMock->shouldReceive('find')->atLeast()->once()->with('Client', 'client_group_id = :group_id', [':group_id' => $data['id']])
+ ->andReturn([]);
+
+ $serviceMock = Mockery::mock(Box\Mod\Client\Service::class)->makePartial();
+ $serviceMock
+ ->shouldReceive('deleteGroup')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $validatorStub = $this->createStub(FOSSBilling\Validate::class);
+ $di['validator'] = $validatorStub;
+
+ $adminClient->setDi($di);
+ $adminClient->setService($serviceMock);
+
+ $result = $adminClient->group_delete($data);
+
+ expect($result)->toBeTrue();
+});
+
+test('groupGet returns array', function (): void {
+ $adminClient = new Box\Mod\Client\Api\Admin();
+ $data['id'] = '2';
+
+ $model = new Model_ClientGroup();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')->atLeast()->once()->andReturn($model);
+
+ $dbMock
+ ->shouldReceive('toArray')->atLeast()->once()->andReturn([]);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $validatorStub = $this->createStub(FOSSBilling\Validate::class);
+ $di['validator'] = $validatorStub;
+
+ $adminClient->setDi($di);
+
+ $result = $adminClient->group_get($data);
+
+ expect($result)->toBeArray();
+});
+
+test('batchDelete returns true', function (): void {
+ $adminClient = new Box\Mod\Client\Api\Admin();
+ $activityMock = Mockery::mock(Box\Mod\Client\Api\Admin::class)->makePartial();
+ $activityMock->shouldReceive('delete')->atLeast()->once()->andReturn(true);
+
+ $validatorStub = $this->createStub(FOSSBilling\Validate::class);
+
+ $di = container();
+ $di['validator'] = $validatorStub;
+ $activityMock->setDi($di);
+
+ $result = $activityMock->batch_delete(['ids' => [1, 2, 3]]);
+ expect($result)->toBeTrue();
+});
diff --git a/src/modules/Client/tests/Unit/Api/ClientTest.php b/src/modules/Client/tests/Unit/Api/ClientTest.php
new file mode 100644
index 000000000..d1f349f07
--- /dev/null
+++ b/src/modules/Client/tests/Unit/Api/ClientTest.php
@@ -0,0 +1,118 @@
+setDi($di);
+ $getDi = $api->getDi();
+ expect($getDi)->toEqual($di);
+});
+
+test('balanceGetList returns array', function (): void {
+ $api = new Box\Mod\Client\Api\Client();
+ $data = [];
+
+ $model = new Model_Client();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $serviceMock = Mockery::mock(Box\Mod\Client\ServiceBalance::class);
+ $serviceMock
+ ->shouldReceive('getSearchQuery')
+ ->atLeast()->once()
+ ->andReturn(['sql', []]);
+ $serviceMock
+ ->shouldReceive('toApiArray')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $simpleResultArr = [
+ 'list' => [
+ ['id' => 1],
+ ],
+ ];
+
+ $pagerMock = Mockery::mock(FOSSBilling\Pagination::class)->makePartial();
+ $pagerMock
+ ->shouldReceive('getPaginatedResultSet')
+ ->atLeast()->once()
+ ->andReturn($simpleResultArr);
+
+ $model = new Model_ClientBalance();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(moduleService(['client:balance' => $serviceMock]));
+ $di['pager'] = $pagerMock;
+ $di['db'] = $dbMock;
+
+ $api->setDi($di);
+ $api->setService($serviceMock);
+ $api->setIdentity($model);
+
+ $result = $api->balance_get_list($data);
+
+ expect($result)->toBeArray();
+});
+
+test('balanceGetTotal returns float', function (): void {
+ $api = new Box\Mod\Client\Api\Client();
+ $balanceAmount = 0.00;
+ $model = new Model_Client();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $serviceMock = Mockery::mock(Box\Mod\Client\ServiceBalance::class);
+ $serviceMock
+ ->shouldReceive('getClientBalance')
+ ->atLeast()->once()
+ ->andReturn($balanceAmount);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(moduleService(['client:balance' => $serviceMock]));
+
+ $api->setDi($di);
+ $api->setIdentity($model);
+
+ $result = $api->balance_get_total();
+
+ expect($result)->toBeFloat();
+ expect($result)->toEqual($balanceAmount);
+});
+
+test('isTaxable returns boolean', function (): void {
+ $api = new Box\Mod\Client\Api\Client();
+ $clientIsTaxable = true;
+
+ $serviceMock = Mockery::mock(Box\Mod\Client\Service::class);
+ $serviceMock
+ ->shouldReceive('isClientTaxable')
+ ->atLeast()->once()
+ ->andReturn($clientIsTaxable);
+
+ $client = new Model_Client();
+ $client->loadBean(new Tests\Helpers\DummyBean());
+
+ $api->setService($serviceMock);
+ $api->setIdentity($client);
+
+ $result = $api->is_taxable();
+ expect($result)->toBeBool();
+ expect($result)->toEqual($clientIsTaxable);
+});
diff --git a/src/modules/Client/tests/Unit/Api/GuestTest.php b/src/modules/Client/tests/Unit/Api/GuestTest.php
new file mode 100644
index 000000000..a00cdedec
--- /dev/null
+++ b/src/modules/Client/tests/Unit/Api/GuestTest.php
@@ -0,0 +1,354 @@
+setDi($di);
+ $getDi = $guestClient->getDi();
+ expect($getDi)->toEqual($di);
+});
+
+test('create returns int', function (): void {
+ $guestClient = new Box\Mod\Client\Api\Guest();
+ $configArr = [
+ 'disable_signup' => false,
+ 'auto_login_after_signup' => false,
+ 'required' => [],
+ ];
+ $data = [
+ 'email' => 'test@email.com',
+ 'first_name' => 'John',
+ 'password' => 'testpaswword',
+ 'password_confirm' => 'testpaswword',
+ ];
+
+ $serviceMock = Mockery::mock(Box\Mod\Client\Service::class);
+ $serviceMock
+ ->shouldReceive('clientAlreadyExists')
+ ->atLeast()->once()
+ ->andReturn(false);
+
+ $model = new Model_Client();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $model->id = 1;
+
+ $serviceMock
+ ->shouldReceive('guestCreateClient')
+ ->atLeast()->once()
+ ->andReturn($model);
+ $serviceMock->shouldReceive('checkExtraRequiredFields')->atLeast()->once();
+ $serviceMock->shouldReceive('checkCustomFields')->atLeast()->once();
+
+ $validatorMock = Mockery::mock(FOSSBilling\Validate::class);
+ $validatorMock->shouldReceive('isPasswordStrong')->atLeast()->once();
+ $validatorMock->shouldReceive('passwordsMatch')->atLeast()->once();
+
+ $toolsMock = Mockery::mock(FOSSBilling\Tools::class);
+ $toolsMock->shouldReceive('validateAndSanitizeEmail')->atLeast()->once()->andReturn($data['email']);
+
+ $di = container();
+ $di['mod_config'] = $di->protect(fn ($name): array => $configArr);
+ $di['validator'] = $validatorMock;
+ $di['tools'] = $toolsMock;
+
+ $guestClient->setDi($di);
+ $guestClient->setService($serviceMock);
+
+ $result = $guestClient->create($data);
+
+ expect($result)->toBeInt();
+ expect($result)->toEqual($model->id);
+});
+
+test('create throws exception when client exists', function (): void {
+ $guestClient = new Box\Mod\Client\Api\Guest();
+ $configArr = [
+ 'disable_signup' => false,
+ ];
+ $data = [
+ 'email' => 'test@email.com',
+ 'first_name' => 'John',
+ 'password' => 'testpaswword',
+ 'password_confirm' => 'testpaswword',
+ ];
+
+ $serviceMock = Mockery::mock(Box\Mod\Client\Service::class);
+ $serviceMock
+ ->shouldReceive('clientAlreadyExists')
+ ->atLeast()->once()
+ ->andReturn(true);
+ $serviceMock->shouldReceive('checkExtraRequiredFields')->atLeast()->once();
+ $serviceMock->shouldReceive('checkCustomFields')->atLeast()->once();
+
+ $model = new Model_Client();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $validatorMock = Mockery::mock(FOSSBilling\Validate::class);
+ $validatorMock->shouldReceive('isPasswordStrong')->atLeast()->once();
+ $validatorMock->shouldReceive('passwordsMatch')->atLeast()->once();
+
+ $di = container();
+ $di['mod_config'] = $di->protect(fn ($name): array => $configArr);
+ $di['validator'] = $validatorMock;
+
+ $toolsMock = Mockery::mock(FOSSBilling\Tools::class);
+ $toolsMock->shouldReceive('validateAndSanitizeEmail')->atLeast()->once()->andReturn($data['email']);
+ $di['tools'] = $toolsMock;
+
+ $guestClient->setDi($di);
+ $guestClient->setService($serviceMock);
+
+ $guestClient->create($data);
+})->throws(FOSSBilling\Exception::class, 'This email address is already registered.');
+
+test('create throws exception when signup is disabled', function (): void {
+ $guestClient = new Box\Mod\Client\Api\Guest();
+ $configArr = [
+ 'disable_signup' => true,
+ ];
+ $data = [
+ 'email' => 'test@email.com',
+ 'first_name' => 'John',
+ 'password' => 'testpaswword',
+ 'password_confirm' => 'testpaswword',
+ ];
+
+ $di = container();
+ $di['mod_config'] = $di->protect(fn ($name): array => $configArr);
+ $guestClient->setDi($di);
+
+ $guestClient->create($data);
+})->throws(FOSSBilling\Exception::class, 'New registrations are temporarily disabled');
+
+test('create throws exception when passwords do not match', function (): void {
+ $guestClient = new Box\Mod\Client\Api\Guest();
+ $configArr = [
+ 'disable_signup' => false,
+ ];
+ $data = [
+ 'email' => 'test@email.com',
+ 'first_name' => 'John',
+ 'password' => 'testpaswword',
+ 'password_confirm' => 'wrongpaswword',
+ ];
+
+ $di = container();
+ $di['mod_config'] = $di->protect(fn ($name): array => $configArr);
+ $guestClient->setDi($di);
+
+ $guestClient->create($data);
+})->throws(FOSSBilling\Exception::class, 'Passwords do not match.');
+
+test('login returns array', function (): void {
+ $guestClient = new Box\Mod\Client\Api\Guest();
+ $data = [
+ 'email' => 'test@example.com',
+ 'password' => 'sezam',
+ ];
+
+ $model = new Model_Client();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $serviceMock = Mockery::mock(Box\Mod\Client\Service::class);
+ $serviceMock
+ ->shouldReceive('authorizeClient')
+ ->atLeast()->once()
+ ->with($data['email'], $data['password'])
+ ->andReturn($model);
+ $serviceMock
+ ->shouldReceive('toSessionArray')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $eventMock = Mockery::mock('\Box_EventManager');
+ $eventMock->shouldReceive('fire')->atLeast()->once();
+
+ $sessionMock = Mockery::mock(FOSSBilling\Session::class);
+ $sessionMock->shouldReceive('set')->atLeast()->once();
+ $sessionMock->shouldReceive('getId')->atLeast()->once();
+ $sessionMock->shouldReceive('regenerateId')->atLeast()->once();
+ $sessionMock->shouldReceive('delete')->atLeast()->once();
+
+ $cartServiceMock = Mockery::mock(Box\Mod\Cart\Service::class);
+ $cartServiceMock->shouldReceive('transferFromOtherSession')->atLeast()->once()
+ ->andReturn(true);
+
+ $toolsStub = Mockery::mock(FOSSBilling\Tools::class);
+ $toolsStub->shouldReceive('validateAndSanitizeEmail')->atLeast()->once()->with($data['email'], true, false)->andReturn($data['email']);
+
+ $di = container();
+ $di['events_manager'] = $eventMock;
+ $di['session'] = $sessionMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $di['tools'] = $toolsStub;
+ $di['mod_service'] = $di->protect(moduleService(['cart' => $cartServiceMock]));
+
+ $guestClient->setDi($di);
+ $guestClient->setService($serviceMock);
+
+ $results = $guestClient->login($data);
+
+ expect($results)->toBeArray();
+});
+
+test('resetPassword returns true with new flow', function (): void {
+ $guestClient = new Box\Mod\Client\Api\Guest();
+ $data['email'] = 'John@exmaple.com';
+
+ $eventMock = Mockery::mock('\Box_EventManager');
+ $eventMock->shouldReceive('fire')->atLeast()->once();
+
+ $modelClient = new Model_Client();
+ $modelClient->loadBean(new Tests\Helpers\DummyBean());
+ $modelClient->id = 1;
+ $modelClient->status = Model_Client::ACTIVE;
+
+ $dbMock = Mockery::mock('\Box_Database');
+
+ $dbMock->shouldReceive('findOne')->andReturn($modelClient);
+
+ $serviceMock = Mockery::mock(Box\Mod\Client\Service::class);
+ $serviceMock->shouldReceive('createPasswordResetRequestForClient')->atLeast()->once()->with($modelClient)->andReturn('hashedString');
+ $serviceMock->shouldReceive('sendPasswordResetRequestEmailForClient')->atLeast()->once()->with($modelClient, 'hashedString');
+
+ $toolsMock = Mockery::mock(FOSSBilling\Tools::class);
+ $toolsMock->shouldReceive('validateAndSanitizeEmail')->atLeast()->once()->andReturn($data['email']);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['events_manager'] = $eventMock;
+ $di['mod_service'] = $di->protect(moduleService(['client' => $serviceMock]));
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $di['tools'] = $toolsMock;
+
+ $guestClient->setDi($di);
+
+ $result = $guestClient->reset_password($data);
+ expect($result)->toBeTrue();
+});
+
+test('resetPassword returns true when email not found', function (): void {
+ $guestClient = new Box\Mod\Client\Api\Guest();
+ $data['email'] = 'joghn@example.eu';
+
+ $eventMock = Mockery::mock('\Box_EventManager');
+ $eventMock->shouldReceive('fire')->atLeast()->once();
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('findOne')->atLeast()->once()->andReturn(null);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['events_manager'] = $eventMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $toolsMock = Mockery::mock(FOSSBilling\Tools::class);
+ $toolsMock->shouldReceive('validateAndSanitizeEmail')->atLeast()->once()->andReturn($data['email']);
+ $di['tools'] = $toolsMock;
+
+ $guestClient->setDi($di);
+
+ $result = $guestClient->reset_password($data);
+ expect($result)->toBeTrue();
+});
+
+test('updatePassword returns true', function (): void {
+ $guestClient = new Box\Mod\Client\Api\Guest();
+ $data = [
+ 'hash' => 'hashedString',
+ 'password' => 'NewPassword1',
+ 'password_confirm' => 'NewPassword1',
+ ];
+
+ $dbMock = Mockery::mock('\Box_Database');
+
+ $modelClient = new Model_Client();
+ $modelClient->loadBean(new Tests\Helpers\DummyBean());
+ $modelClient->id = 1;
+ $modelClient->status = Model_Client::ACTIVE;
+
+ $modelPasswordReset = new Model_ClientPasswordReset();
+ $modelPasswordReset->loadBean(new Tests\Helpers\DummyBean());
+ $modelPasswordReset->created_at = date('Y-m-d H:i:s', time() - 300);
+
+ $dbMock->shouldReceive('findOne')->atLeast()->once()->andReturn($modelPasswordReset);
+
+ $dbMock->shouldReceive('getExistingModelById')->atLeast()->once()->andReturn($modelClient);
+
+ $dbMock->shouldReceive('store')->atLeast()->once();
+
+ $dbMock->shouldReceive('trash')->atLeast()->once();
+
+ $eventMock = Mockery::mock('\Box_EventManager');
+ $eventMock->shouldReceive('fire')->times(2);
+
+ $passwordMock = Mockery::mock(FOSSBilling\PasswordManager::class);
+ $passwordMock->shouldReceive('hashIt')->atLeast()->once();
+
+ $emailServiceMock = Mockery::mock(Box\Mod\Email\Service::class);
+ $emailServiceMock->shouldReceive('sendTemplate')->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['events_manager'] = $eventMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $di['password'] = $passwordMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $di['mod_service'] = $di->protect(moduleService(['email' => $emailServiceMock]));
+
+ $guestClient->setDi($di);
+
+ $result = $guestClient->update_password($data);
+ expect($result)->toBeTrue();
+});
+
+test('updatePassword throws exception when reset not found', function (): void {
+ $guestClient = new Box\Mod\Client\Api\Guest();
+ $data = [
+ 'hash' => 'hashedString',
+ 'password' => 'NewPassword1',
+ 'password_confirm' => 'NewPassword1',
+ ];
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('findOne')->atLeast()->once()->andReturn(null);
+
+ $eventMock = Mockery::mock('\Box_EventManager');
+ $eventMock->shouldReceive('fire')->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['events_manager'] = $eventMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $guestClient->setDi($di);
+
+ $guestClient->update_password($data);
+})->throws(FOSSBilling\Exception::class, 'The link has expired or you have already reset your password.');
+
+test('required returns array', function (): void {
+ $guestClient = new Box\Mod\Client\Api\Guest();
+ $configArr = [];
+
+ $di = container();
+ $di['mod_config'] = $di->protect(fn ($name): array => $configArr);
+
+ $guestClient->setDi($di);
+
+ $result = $guestClient->required();
+ expect($result)->toBeArray();
+});
diff --git a/src/modules/Client/tests/Unit/ServiceBalanceTest.php b/src/modules/Client/tests/Unit/ServiceBalanceTest.php
new file mode 100644
index 000000000..8b8715790
--- /dev/null
+++ b/src/modules/Client/tests/Unit/ServiceBalanceTest.php
@@ -0,0 +1,89 @@
+setDi($di);
+ $getDi = $service->getDi();
+ expect($getDi)->toEqual($di);
+});
+
+test('deductFunds creates balance record', function (): void {
+ $service = new Box\Mod\Client\ServiceBalance();
+ $di = container();
+
+ $clientBalance = new Model_ClientBalance();
+ $clientBalance->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('dispense')
+ ->with('ClientBalance')
+ ->atLeast()->once()
+ ->andReturn($clientBalance);
+ $dbMock->shouldReceive('store')
+ ->with($clientBalance)
+ ->atLeast()->once();
+ $di['db'] = $dbMock;
+
+ $service->setDi($di);
+
+ $clientModel = new Model_Client();
+ $clientModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $description = 'Charged for product';
+ $amount = 5.55;
+
+ $extra = [
+ 'rel_id' => 1,
+ ];
+
+ $result = $service->deductFunds($clientModel, $amount, $description, $extra);
+
+ expect($result)->toBeInstanceOf(Model_ClientBalance::class);
+ expect($result->amount)->toEqual(-$amount);
+ expect($result->description)->toEqual($description);
+ expect($result->rel_id)->toEqual($extra['rel_id']);
+ expect($result->type)->toEqual('default');
+});
+
+test('deductFunds throws exception for invalid description', function (): void {
+ $service = new Box\Mod\Client\ServiceBalance();
+ $clientModel = new Model_Client();
+ $clientModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $description = ' ';
+ $amount = 5.55;
+
+ $extra = [
+ 'rel_id' => 1,
+ ];
+
+ $service->deductFunds($clientModel, $amount, $description, $extra);
+})->throws(FOSSBilling\Exception::class, 'Funds description is invalid');
+
+test('deductFunds throws exception for invalid amount', function (): void {
+ $service = new Box\Mod\Client\ServiceBalance();
+ $clientModel = new Model_Client();
+ $clientModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $description = 'Charged';
+ $amount = '5.5adadzxc';
+
+ $extra = [
+ 'rel_id' => 1,
+ ];
+
+ $service->deductFunds($clientModel, $amount, $description, $extra);
+})->throws(FOSSBilling\Exception::class, 'Funds amount is invalid');
diff --git a/src/modules/Client/tests/Unit/ServiceTest.php b/src/modules/Client/tests/Unit/ServiceTest.php
new file mode 100644
index 000000000..40e419e49
--- /dev/null
+++ b/src/modules/Client/tests/Unit/ServiceTest.php
@@ -0,0 +1,1067 @@
+setDi($di);
+ $getDi = $service->getDi();
+ expect($getDi)->toEqual($di);
+});
+
+test('approveClientEmailByHash returns true', function (): void {
+ $service = new Box\Mod\Client\Service();
+ $database = Mockery::mock('\Box_Database');
+ $database->shouldReceive('getRow')
+ ->atLeast()->once()
+ ->andReturn(['client_id' => 2, 'id' => 1]);
+ $database->shouldReceive('exec')
+ ->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $database;
+
+ $service->setDi($di);
+ $result = $service->approveClientEmailByHash('');
+
+ expect($result)->toBeTrue();
+});
+
+test('approveClientEmailByHash throws exception for invalid hash', function (): void {
+ $service = new Box\Mod\Client\Service();
+ $database = Mockery::mock('\Box_Database');
+ $database->shouldReceive('getRow')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $di = container();
+ $di['db'] = $database;
+
+ $service->setDi($di);
+
+ $service->approveClientEmailByHash('');
+})->throws(FOSSBilling\Exception::class, 'Invalid email confirmation link');
+
+test('generateEmailConfirmationLink returns string', function (): void {
+ $service = new Box\Mod\Client\Service();
+
+ $model = new Model_ExtensionMeta();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $database = Mockery::mock('\Box_Database');
+ $database->shouldReceive('dispense')
+ ->atLeast()->once()
+ ->andReturn($model);
+ $database->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn(1);
+
+ $toolsMock = Mockery::mock(FOSSBilling\Tools::class);
+ $toolsMock->shouldReceive('url')
+ ->atLeast()->once()
+ ->andReturn('fossbilling.org/index.php/client/confirm-email/');
+ $toolsMock->shouldReceive('generatePassword')
+ ->atLeast()->once()
+ ->andReturn('randomhash123456789012345678901234567890');
+
+ $di = container();
+ $di['db'] = $database;
+ $di['tools'] = $toolsMock;
+
+ $service->setDi($di);
+
+ $clientId = 1;
+ $result = $service->generateEmailConfirmationLink($clientId);
+
+ expect($result)->toBeString();
+ expect(str_contains((string) $result, '/client/confirm-email/'))->toBeTrue();
+});
+
+test('onAfterClientSignUp returns true', function (): void {
+ $service = new Box\Mod\Client\Service();
+ $eventParams = [
+ 'password' => 'testPassword',
+ 'id' => 1,
+ ];
+
+ $eventMock = Mockery::mock('\Box_Event');
+ $eventMock->shouldReceive('getParameters')
+ ->atLeast()->once()
+ ->andReturn($eventParams);
+
+ $emailService = Mockery::mock(Box\Mod\Email\Service::class);
+ $emailService->shouldReceive('sendTemplate')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $emailService);
+ $di['mod_config'] = $di->protect(fn ($name): array => ['require_email_confirmation' => false]);
+
+ $eventMock->shouldReceive('getDi')
+ ->atLeast()->once()
+ ->andReturn($di);
+
+ $service->setDi($di);
+ $result = $service->onAfterClientSignUp($eventMock);
+
+ expect($result)->toBeTrue();
+});
+
+test('onAfterClientSignUp with email confirmation required returns true', function (): void {
+ $service = new Box\Mod\Client\Service();
+ $eventMock = Mockery::mock('\Box_Event');
+ $eventParams = [
+ 'password' => 'testPassword',
+ 'id' => 1,
+ 'require_email_confirmation' => true,
+ ];
+
+ $eventMock->shouldReceive('getParameters')
+ ->atLeast()->once()
+ ->andReturn($eventParams);
+
+ $emailService = Mockery::mock(Box\Mod\Email\Service::class);
+ $emailService->shouldReceive('sendTemplate')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $clientServiceMock = Mockery::mock(Box\Mod\Client\Service::class)->makePartial();
+ $clientServiceMock->shouldReceive('generateEmailConfirmationLink')
+ ->atLeast()->once()
+ ->andReturn('Link_string');
+
+ $di = container();
+ $di['mod_service'] = $di->protect(function ($serviceName) use ($emailService, $clientServiceMock) {
+ if ($serviceName == 'email') {
+ return $emailService;
+ }
+ if ($serviceName == 'client') {
+ return $clientServiceMock;
+ }
+ });
+ $di['mod_config'] = $di->protect(fn ($name): array => ['require_email_confirmation' => true]);
+ $eventMock->shouldReceive('getDi')
+ ->atLeast()->once()
+ ->andReturn($di);
+
+ $result = $service->onAfterClientSignUp($eventMock);
+
+ expect($result)->toBeTrue();
+});
+
+test('onAfterClientSignUp handles exception gracefully', function (): void {
+ $service = new Box\Mod\Client\Service();
+ $eventParams = [
+ 'password' => 'testPassword',
+ 'id' => 1,
+ ];
+
+ $eventMock = Mockery::mock('\Box_Event');
+ $eventMock->shouldReceive('getParameters')
+ ->atLeast()->once()
+ ->andReturn($eventParams);
+
+ $emailService = Mockery::mock(Box\Mod\Email\Service::class);
+ $emailService->shouldReceive('sendTemplate')
+ ->atLeast()->once()
+ ->andThrow(new Exception('exception created in unit test'));
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $emailService);
+ $di['mod_config'] = $di->protect(function ($name): void {
+ ['require_email_confirmation' => false];
+ });
+ $eventMock->shouldReceive('getDi')
+ ->atLeast()->once()
+ ->andReturn($di);
+
+ $service->setDi($di);
+ $result = $service->onAfterClientSignUp($eventMock);
+
+ expect($result)->toBeTrue();
+});
+
+dataset('searchQueryData', [
+ [[], 'SELECT c.*', []],
+ [
+ ['id' => 1],
+ '(c.id = :client_id OR c.aid = :alt_client_id)',
+ [':client_id' => '', ':alt_client_id' => ''],
+ ],
+ [
+ ['name' => 'test'],
+ '(c.first_name LIKE :first_name or c.last_name LIKE :last_name )',
+ [':first_name' => '', ':last_name' => ''],
+ ],
+ [
+ ['email' => 'test@example.com'],
+ 'c.email LIKE :email',
+ [':email' => 'test@example.com'],
+ ],
+ [
+ ['company' => 'LTD company'],
+ 'c.company LIKE :company',
+ [':company' => 'LTD company'],
+ ],
+ [
+ ['status' => 'TEST status'],
+ 'c.status = :status',
+ [':status' => 'TEST status'],
+ ],
+ [
+ ['group_id' => '1'],
+ 'c.client_group_id = :group_id',
+ [':group_id' => '1'],
+ ],
+ [
+ ['created_at' => '2012-12-12'],
+ "DATE_FORMAT(c.created_at, '%Y-%m-%d') = :created_at",
+ [':created_at' => '2012-12-12'],
+ ],
+ [
+ ['date_from' => '2012-12-10'],
+ 'UNIX_TIMESTAMP(c.created_at) >= :date_from',
+ [':date_from' => '2012-12-10'],
+ ],
+ [
+ ['date_to' => '2012-12-11'],
+ 'UNIX_TIMESTAMP(c.created_at) <= :date_to',
+ [':date_to' => '2012-12-11'],
+ ],
+ [
+ ['search' => '2'],
+ '(c.id = :cid OR c.aid = :caid)',
+ [':cid' => '2', ':caid' => '2'],
+ ],
+ [
+ ['search' => 'Keyword'],
+ "(c.company LIKE :s_company OR c.first_name LIKE :s_first_name OR c.last_name LIKE :s_last_name OR c.email LIKE :s_email OR CONCAT(c.first_name, ' ', c.last_name ) LIKE :full_name)",
+ [':s_company' => 'Keyword',
+ ':s_first_name' => 'Keyword',
+ ':s_last_name' => 'Keyword',
+ ':s_email' => 'Keyword',
+ ':full_name' => 'Keyword',
+ ],
+ ],
+]);
+
+test('getSearchQuery returns correct query and params', function ($data, $expectedStr, $expectedParams): void {
+ $service = new Box\Mod\Client\Service();
+ $result = $service->getSearchQuery($data);
+ expect($result[0])->toBeString();
+ expect($result[1])->toBeArray();
+
+ expect(str_contains((string) $result[0], (string) $expectedStr))->toBeTrue($result[0]);
+ expect(array_diff_key($result[1], $expectedParams))->toEqual([]);
+})->with('searchQueryData');
+
+test('getSearchQuery with custom select statement', function (): void {
+ $service = new Box\Mod\Client\Service();
+ $data = [];
+ $selectStmt = 'c.id, CONCAT(c.first_name, c.last_name) as full_name';
+ $result = $service->getSearchQuery($data, $selectStmt);
+ expect($result[0])->toBeString();
+ expect($result[1])->toBeArray();
+
+ expect(str_contains((string) $result[0], $selectStmt))->toBeTrue($result[0]);
+});
+
+test('getPairs returns array', function (): void {
+ $service = new Box\Mod\Client\Service();
+ $data = [];
+
+ $database = Mockery::mock('\Box_Database');
+ $database->shouldReceive('getAssoc')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $di = container();
+ $di['db'] = $database;
+
+ $service->setDi($di);
+ $result = $service->getPairs($data);
+ expect($result)->toBeArray();
+});
+
+test('toSessionArray returns array with expected keys', function (): void {
+ $service = new Box\Mod\Client\Service();
+ $expectedArrayKeys = [
+ 'id' => 1,
+ 'email' => 'email@example.com',
+ 'name' => 'John Smith',
+ 'role' => 'admin',
+ ];
+
+ $model = new Model_Client();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $result = $service->toSessionArray($model);
+
+ expect($result)->toBeArray();
+ expect(array_diff_key($result, $expectedArrayKeys))->toEqual([]);
+});
+
+test('emailAlreadyRegistered returns boolean', function (): void {
+ $service = new Box\Mod\Client\Service();
+ $email = 'test@example.com';
+ $model = new Model_Client();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $database = Mockery::mock('\Box_Database');
+ $database->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $di = container();
+ $di['db'] = $database;
+
+ $service->setDi($di);
+
+ $result = $service->emailAlreadyRegistered($email);
+ expect($result)->toBeBool();
+});
+
+test('emailAlreadyRegistered with model returns false for same email', function (): void {
+ $service = new Box\Mod\Client\Service();
+ $email = 'test@example.com';
+ $model = new Model_Client();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $model->email = $email;
+
+ $result = $service->emailAlreadyRegistered($email, $model);
+ expect($result)->toBeBool();
+ expect($result)->toBeFalse();
+});
+
+test('canChangeCurrency returns true when no invoices exist', function (): void {
+ $service = new Box\Mod\Client\Service();
+ $currency = 'EUR';
+ $model = new Model_Client();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $model->currency = 'USD';
+
+ $database = Mockery::mock('\Box_Database');
+ $database->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn(null);
+
+ $di = container();
+ $di['db'] = $database;
+
+ $service->setDi($di);
+ $result = $service->canChangeCurrency($model, $currency);
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+});
+
+test('canChangeCurrency returns true when model currency is not set', function (): void {
+ $service = new Box\Mod\Client\Service();
+ $currency = 'EUR';
+ $model = new Model_Client();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $database = Mockery::mock('\Box_Database');
+ $database->shouldReceive('findOne')->never();
+
+ $result = $service->canChangeCurrency($model, $currency);
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+});
+
+test('canChangeCurrency returns false when currencies are identical', function (): void {
+ $service = new Box\Mod\Client\Service();
+ $currency = 'EUR';
+ $model = new Model_Client();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $model->currency = $currency;
+
+ $database = Mockery::mock('\Box_Database');
+ $database->shouldReceive('findOne')->never();
+
+ $result = $service->canChangeCurrency($model, $currency);
+ expect($result)->toBeBool();
+ expect($result)->toBeFalse();
+});
+
+test('canChangeCurrency throws exception when client has invoices', function (): void {
+ $service = new Box\Mod\Client\Service();
+ $currency = 'EUR';
+ $model = new Model_Client();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $model->id = 1;
+ $model->currency = 'USD';
+
+ $invoiceModel = new Model_Invoice();
+ $invoiceModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $database = Mockery::mock('\Box_Database');
+ $database->shouldReceive('findOne')
+ ->once()
+ ->andReturn($invoiceModel);
+
+ $di = container();
+ $di['db'] = $database;
+
+ $service->setDi($di);
+
+ $service->canChangeCurrency($model, $currency);
+})->throws(FOSSBilling\Exception::class, 'Currency cannot be changed. Client already has invoices issued.');
+
+dataset('searchBalanceQueryData', [
+ [[], 'FROM client_balance as m', []],
+ [
+ ['id' => 1],
+ 'm.id = :id',
+ [':id' => '1'],
+ ],
+ [
+ ['client_id' => 1],
+ 'm.client_id = :client_id',
+ [':client_id' => '1'],
+ ],
+ [
+ ['date_from' => '2012-12-10'],
+ 'm.created_at >= :date_from',
+ [':date_from' => '2012-12-10'],
+ ],
+ [
+ ['date_to' => '2012-12-11'],
+ 'm.created_at <= :date_to',
+ [':date_to' => '2012-12-11'],
+ ],
+]);
+
+test('getBalanceSearchQuery returns correct query and params', function ($data, $expectedStr, $expectedParams): void {
+ $service = new Box\Mod\Client\Service();
+ $di = container();
+
+ $clientBalanceService = new Box\Mod\Client\ServiceBalance();
+ $clientBalanceService->setDi($di);
+ [$sql, $params] = $clientBalanceService->getSearchQuery($data);
+ expect($sql)->not->toBeEmpty();
+ expect($sql)->toBeString();
+ expect($params)->toBeArray();
+
+ expect(str_contains((string) $sql, (string) $expectedStr))->toBeTrue($sql);
+ expect(array_diff_key($params, $expectedParams))->toEqual([]);
+})->with('searchBalanceQueryData');
+
+test('addFunds returns true', function (): void {
+ $service = new Box\Mod\Client\Service();
+ $modelClient = new Model_Client();
+ $modelClient->loadBean(new Tests\Helpers\DummyBean());
+ $modelClient->currency = 'USD';
+
+ $model = new Model_ClientBalance();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $amount = '2.22';
+ $description = 'test description';
+
+ $database = Mockery::mock('\Box_Database');
+ $database->shouldReceive('dispense')
+ ->atLeast()->once()
+ ->andReturn($model);
+ $database->shouldReceive('store')
+ ->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $database;
+
+ $service->setDi($di);
+
+ $result = $service->addFunds($modelClient, $amount, $description);
+ expect($result)->toBeTrue();
+});
+
+test('addFunds throws exception when currency is not defined', function (): void {
+ $service = new Box\Mod\Client\Service();
+ $modelClient = new Model_Client();
+ $modelClient->loadBean(new Tests\Helpers\DummyBean());
+
+ $amount = '2.22';
+ $description = 'test description';
+
+ $service->addFunds($modelClient, $amount, $description);
+})->throws(FOSSBilling\Exception::class, "You must define the client's currency before adding funds.");
+
+test('addFunds throws exception when amount is missing', function (): void {
+ $service = new Box\Mod\Client\Service();
+ $modelClient = new Model_Client();
+ $modelClient->loadBean(new Tests\Helpers\DummyBean());
+ $modelClient->currency = 'USD';
+
+ $amount = null;
+ $description = '';
+
+ $service->addFunds($modelClient, $amount, $description);
+})->throws(FOSSBilling\Exception::class, 'Funds amount is invalid');
+
+test('addFunds throws exception when description is invalid', function (): void {
+ $service = new Box\Mod\Client\Service();
+ $modelClient = new Model_Client();
+ $modelClient->loadBean(new Tests\Helpers\DummyBean());
+ $modelClient->currency = 'USD';
+
+ $amount = '2.22';
+ $description = null;
+
+ $service->addFunds($modelClient, $amount, $description);
+})->throws(FOSSBilling\Exception::class, 'Funds description is invalid');
+
+test('getExpiredPasswordReminders returns array', function (): void {
+ $service = new Box\Mod\Client\Service();
+ $database = Mockery::mock('\Box_Database');
+ $database->shouldReceive('find')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $di = container();
+ $di['db'] = $database;
+
+ $service->setDi($di);
+
+ $result = $service->getExpiredPasswordReminders();
+ expect($result)->toBeArray();
+});
+
+dataset('searchHistoryQueryData', [
+ [[], 'SELECT ach.*, c.first_name, c.last_name, c.email', []],
+ [
+ ['search' => 'sameValue'],
+ '(c.first_name LIKE :first_name OR c.last_name LIKE :last_name OR c.email LIKE :email OR c.id LIKE :id)',
+ [
+ ':first_name' => '%sameValue%',
+ ':last_name' => '%sameValue%',
+ ':email' => '%sameValue%',
+ ':id' => 'sameValue'],
+ ],
+ [
+ ['client_id' => '1'],
+ 'ach.client_id = :client_id',
+ [':client_id' => '1'],
+ ],
+]);
+
+test('getHistorySearchQuery returns correct query and params', function ($data, $expectedStr, $expectedParams): void {
+ $service = new Box\Mod\Client\Service();
+ $di = container();
+
+ $service->setDi($di);
+ [$sql, $params] = $service->getHistorySearchQuery($data);
+ expect($sql)->not->toBeEmpty();
+ expect($sql)->toBeString();
+ expect($params)->toBeArray();
+
+ expect(str_contains((string) $sql, (string) $expectedStr))->toBeTrue($sql);
+ expect(array_diff_key($params, $expectedParams))->toEqual([]);
+})->with('searchHistoryQueryData');
+
+test('counter returns array', function (): void {
+ $service = new Box\Mod\Client\Service();
+ $database = Mockery::mock('\Box_Database');
+ $database->shouldReceive('getAssoc')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $di = container();
+ $di['db'] = $database;
+
+ $service->setDi($di);
+
+ $result = $service->counter();
+ expect($result)->toBeArray();
+
+ $expected = [
+ 'total' => 0,
+ Model_Client::ACTIVE => 0,
+ Model_Client::SUSPENDED => 0,
+ Model_Client::CANCELED => 0,
+ ];
+});
+
+test('getGroupPairs returns array', function (): void {
+ $service = new Box\Mod\Client\Service();
+ $database = Mockery::mock('\Box_Database');
+ $database->shouldReceive('getAssoc')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $di = container();
+ $di['db'] = $database;
+
+ $service->setDi($di);
+
+ $result = $service->getGroupPairs();
+ expect($result)->toBeArray();
+});
+
+test('clientAlreadyExists returns true when client exists', function (): void {
+ $service = new Box\Mod\Client\Service();
+ $model = new Model_Client();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $database = Mockery::mock('\Box_Database');
+ $database->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $di = container();
+ $di['db'] = $database;
+
+ $service->setDi($di);
+
+ $result = $service->clientAlreadyExists('email@example.com');
+ expect($result)->toBeTrue();
+});
+
+test('getByLoginDetails returns Model_Client', function (): void {
+ $service = new Box\Mod\Client\Service();
+ $model = new Model_Client();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $database = Mockery::mock('\Box_Database');
+ $database->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $di = container();
+ $di['db'] = $database;
+
+ $service->setDi($di);
+
+ $result = $service->getByLoginDetails('email@example.com', 'password');
+ expect($result)->toBeInstanceOf(Model_Client::class);
+});
+
+dataset('getProvider', [
+ ['id', 1],
+ ['email', 'test@email.com'],
+]);
+
+test('get returns Model_Client', function ($fieldName, $fieldValue): void {
+ $service = new Box\Mod\Client\Service();
+ $model = new Model_Client();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $service->setDi($di);
+
+ $data = [$fieldName => $fieldValue];
+ $result = $service->get($data);
+ expect($result)->toBeInstanceOf(Model_Client::class);
+})->with('getProvider');
+
+test('get throws exception when client not found', function (): void {
+ $service = new Box\Mod\Client\Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $service->setDi($di);
+
+ $data = ['id' => 0];
+ $service->get($data);
+})->throws(FOSSBilling\Exception::class, 'Client not found');
+
+test('getClientBalance returns numeric', function (): void {
+ $service = new Box\Mod\Client\Service();
+ $model = new Model_Client();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getCell')
+ ->atLeast()->once()
+ ->andReturn(1.0);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $service->setDi($di);
+
+ $result = $service->getClientBalance($model);
+ expect($result)->toBeNumeric();
+});
+
+test('toApiArray returns array', function (): void {
+ $service = new Box\Mod\Client\Service();
+ $model = new Model_Client();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $model->custom_1 = 'custom field';
+
+ $clientGroup = new Model_ClientGroup();
+ $clientGroup->loadBean(new Tests\Helpers\DummyBean());
+ $clientGroup->title = 'Group Title';
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('toArray')
+ ->atLeast()->once()
+ ->andReturn([]);
+ $dbMock->shouldReceive('load')
+ ->atLeast()->once()
+ ->andReturn($clientGroup);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $serviceMock = Mockery::mock(Box\Mod\Client\Service::class)->makePartial();
+ $serviceMock->shouldReceive('getClientBalance')
+ ->atLeast()->once();
+
+ $serviceMock->setDi($di);
+
+ $result = $serviceMock->toApiArray($model, true, new Model_Admin());
+ expect($result)->toBeArray();
+});
+
+dataset('isClientTaxableProvider', [
+ [
+ false,
+ false,
+ false,
+ ],
+ [
+ true,
+ true,
+ false,
+ ],
+ [
+ true,
+ false,
+ true,
+ ],
+]);
+
+test('isClientTaxable returns correct value', function ($getParamValueReturn, $tax_exempt, $expected): void {
+ $service = new Box\Mod\Client\Service();
+ $systemService = Mockery::mock(Box\Mod\System\Service::class);
+ $systemService->shouldReceive('getParamValue')
+ ->atLeast()->once()
+ ->andReturn($getParamValueReturn);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $systemService);
+
+ $service->setDi($di);
+
+ $client = new Model_Client();
+ $client->loadBean(new Tests\Helpers\DummyBean());
+ $client->tax_exempt = $tax_exempt;
+
+ $result = $service->isClientTaxable($client);
+ expect($result)->toEqual($expected);
+})->with('isClientTaxableProvider');
+
+test('adminCreateClient returns int', function (): void {
+ $service = new Box\Mod\Client\Service();
+ $clientModel = new Model_Client();
+ $clientModel->loadBean(new Tests\Helpers\DummyBean());
+ $clientModel->id = 1;
+
+ $data = [
+ 'password' => uniqid(),
+ 'email' => 'test@unit.vm',
+ 'first_name' => 'test',
+ ];
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('dispense')
+ ->atLeast()->once()
+ ->andReturn($clientModel);
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once();
+
+ $eventManagerMock = Mockery::mock('\Box_EventManager');
+ $eventManagerMock->shouldReceive('fire')
+ ->twice();
+
+ $passwordMock = Mockery::mock(FOSSBilling\PasswordManager::class);
+ $passwordMock->shouldReceive('hashIt')
+ ->atLeast()->once()
+ ->with($data['password']);
+
+ $modMock = Mockery::mock(FOSSBilling\Module::class)->makePartial();
+ $modMock->shouldReceive('getConfig')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['events_manager'] = $eventManagerMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $di['mod'] = $di->protect(fn (): Mockery\MockInterface => $modMock);
+ $di['password'] = $passwordMock;
+
+ $service->setDi($di);
+
+ $result = $service->adminCreateClient($data);
+ expect($result)->toBeInt();
+});
+
+test('deleteGroup returns true', function (): void {
+ $service = new Box\Mod\Client\Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('findOne')
+ ->atLeast()->once();
+ $dbMock->shouldReceive('trash')
+ ->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $service->setDi($di);
+
+ $model = new Model_ClientGroup();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $result = $service->deleteGroup($model);
+ expect($result)->toBeTrue();
+});
+
+test('deleteGroup throws exception when group has clients', function (): void {
+ $service = new Box\Mod\Client\Service();
+ $clientModel = new Model_Client();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn($clientModel);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $service->setDi($di);
+
+ $model = new Model_ClientGroup();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $service->deleteGroup($model);
+})->throws(FOSSBilling\Exception::class, 'Cannot remove groups with clients');
+
+test('authorizeClient returns null when email not found', function (): void {
+ $service = new Box\Mod\Client\Service();
+ $email = 'example@fossbilling.vm';
+ $password = '123456';
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->with('Client', Mockery::any(), Mockery::any())
+ ->andReturn(null);
+
+ $authMock = Mockery::mock('\Box_Authorization');
+ $authMock->shouldReceive('authorizeUser')
+ ->atLeast()->once()
+ ->with(null, $password)
+ ->andReturn(null);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['auth'] = $authMock;
+
+ $service->setDi($di);
+
+ $result = $service->authorizeClient($email, $password);
+ expect($result)->toBeNull();
+});
+
+test('authorizeClient returns Model_Client', function (): void {
+ $service = new Box\Mod\Client\Service();
+ $email = 'example@fossbilling.vm';
+ $password = '123456';
+
+ $clientModel = new Model_Client();
+ $clientModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->with('Client', Mockery::any(), Mockery::any())
+ ->andReturn($clientModel);
+
+ $authMock = Mockery::mock('\Box_Authorization');
+ $authMock->shouldReceive('authorizeUser')
+ ->atLeast()->once()
+ ->with($clientModel, $password)
+ ->andReturn($clientModel);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['auth'] = $authMock;
+ $di['mod_config'] = $di->protect(fn ($name): array => ['require_email_confirmation' => false]);
+
+ $service->setDi($di);
+
+ $result = $service->authorizeClient($email, $password);
+ expect($result)->toBeInstanceOf(Model_Client::class);
+});
+
+test('authorizeClient with confirmed email returns Model_Client', function (): void {
+ $service = new Box\Mod\Client\Service();
+ $email = 'example@fossbilling.vm';
+ $password = '123456';
+
+ $clientModel = new Model_Client();
+ $clientModel->loadBean(new Tests\Helpers\DummyBean());
+ $clientModel->email_approved = 1;
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->with('Client', Mockery::any(), Mockery::any())
+ ->andReturn($clientModel);
+
+ $authMock = Mockery::mock('\Box_Authorization');
+ $authMock->shouldReceive('authorizeUser')
+ ->atLeast()->once()
+ ->with($clientModel, $password)
+ ->andReturn($clientModel);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['auth'] = $authMock;
+ $di['mod_config'] = $di->protect(fn ($name): array => ['require_email_confirmation' => true]);
+
+ $service->setDi($di);
+
+ $result = $service->authorizeClient($email, $password);
+ expect($result)->toBeInstanceOf(Model_Client::class);
+});
+
+test('canChangeEmail returns true', function (): void {
+ $service = new Box\Mod\Client\Service();
+ $clientModel = new Model_Client();
+ $clientModel->loadBean(new Tests\Helpers\DummyBean());
+ $email = 'client@fossbilling.org';
+
+ $config = [
+ 'disable_change_email' => false,
+ ];
+
+ $di = container();
+ $di['mod_config'] = $di->protect(fn ($modName): array => $config);
+ $service->setDi($di);
+
+ $result = $service->canChangeEmail($clientModel, $email);
+ expect($result)->toBeTrue();
+});
+
+test('canChangeEmail returns true when emails are the same', function (): void {
+ $service = new Box\Mod\Client\Service();
+ $clientModel = new Model_Client();
+ $clientModel->loadBean(new Tests\Helpers\DummyBean());
+ $email = 'client@fossbilling.org';
+
+ $clientModel->email = $email;
+
+ $config = [
+ 'disable_change_email' => false,
+ ];
+
+ $di = container();
+ $di['mod_config'] = $di->protect(fn ($modName): array => $config);
+ $service->setDi($di);
+
+ $result = $service->canChangeEmail($clientModel, $email);
+ expect($result)->toBeTrue();
+});
+
+test('canChangeEmail returns true with empty config', function (): void {
+ $service = new Box\Mod\Client\Service();
+ $clientModel = new Model_Client();
+ $clientModel->loadBean(new Tests\Helpers\DummyBean());
+ $email = 'client@fossbilling.org';
+
+ $config = [];
+
+ $di = container();
+ $di['mod_config'] = $di->protect(fn ($modName): array => $config);
+ $service->setDi($di);
+
+ $result = $service->canChangeEmail($clientModel, $email);
+ expect($result)->toBeTrue();
+});
+
+test('canChangeEmail throws exception when email change is disabled', function (): void {
+ $service = new Box\Mod\Client\Service();
+ $clientModel = new Model_Client();
+ $clientModel->loadBean(new Tests\Helpers\DummyBean());
+ $email = 'client@fossbilling.org';
+
+ $config = [
+ 'disable_change_email' => true,
+ ];
+
+ $di = container();
+ $di['mod_config'] = $di->protect(fn ($modName): array => $config);
+ $service->setDi($di);
+
+ $service->canChangeEmail($clientModel, $email);
+})->throws(FOSSBilling\Exception::class, 'Email address cannot be changed');
+
+test('checkExtraRequiredFields throws exception for missing field', function (): void {
+ $service = new Box\Mod\Client\Service();
+ $required = ['id'];
+ $data = [];
+
+ $config['required'] = $required;
+ $di = container();
+ $di['mod_config'] = $di->protect(fn ($modName): array => $config);
+
+ $service->setDi($di);
+ $service->checkExtraRequiredFields($data);
+})->throws(FOSSBilling\Exception::class, 'Field Id cannot be empty');
+
+test('checkCustomFields throws exception for required field', function (): void {
+ $service = new Box\Mod\Client\Service();
+ $custom_field = [
+ 'custom_field_name' => [
+ 'active' => true,
+ 'required' => true,
+ 'title' => 'custom_field_title',
+ ],
+ ];
+ $config['custom_fields'] = $custom_field;
+ $di = container();
+ $di['mod_config'] = $di->protect(fn ($modName): array => $config);
+
+ $data = [];
+ $service->setDi($di);
+ $service->checkCustomFields($data);
+})->throws(FOSSBilling\Exception::class, 'Field custom_field_title cannot be empty');
+
+test('checkCustomFields returns null when field is not required', function (): void {
+ $service = new Box\Mod\Client\Service();
+ $custom_field = [
+ 'custom_field_name' => [
+ 'active' => true,
+ 'required' => false,
+ 'title' => 'custom_field_title',
+ ],
+ ];
+ $config['custom_fields'] = $custom_field;
+ $di = container();
+ $di['mod_config'] = $di->protect(fn ($modName): array => $config);
+
+ $data = [];
+ $service->setDi($di);
+ $result = $service->checkCustomFields($data);
+ expect($result)->toBeNull();
+});
diff --git a/src/modules/Cron/Api/Admin.php b/src/modules/Cron/Api/Admin.php
index 16333f397..4d7f2d82d 100644
--- a/src/modules/Cron/Api/Admin.php
+++ b/src/modules/Cron/Api/Admin.php
@@ -26,7 +26,7 @@ class Admin extends \Api_Abstract
*/
public function info($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('cron', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('cron', 'view');
return $this->getService()->getCronInfo();
}
@@ -38,7 +38,7 @@ class Admin extends \Api_Abstract
*/
public function run($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('cron', 'manage');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('cron', 'manage');
return $this->getService()->runCrons();
}
@@ -53,7 +53,7 @@ class Admin extends \Api_Abstract
*/
public function save_settings($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('cron', 'manage');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('cron', 'manage');
$guestCron = !empty($data['guest_cron']);
@@ -71,7 +71,7 @@ class Admin extends \Api_Abstract
$data['cron_hash'] = '';
}
- return $this->di['mod_service']('extension')->setConfig($data);
+ return $this->getDi()['mod_service']('extension')->setConfig($data);
}
/**
@@ -79,13 +79,13 @@ class Admin extends \Api_Abstract
*/
public function regenerate_cron_hash($data): array
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('cron', 'manage');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('cron', 'manage');
$config = $this->getMod()->getConfig();
$config['cron_hash'] = bin2hex(random_bytes(32));
$config['ext'] = 'mod_cron';
- $this->di['mod_service']('extension')->setConfig($config);
+ $this->getDi()['mod_service']('extension')->setConfig($config);
return ['cron_hash' => $config['cron_hash']];
}
diff --git a/src/modules/Cron/tests/E2E/ApiAdminTest.php b/src/modules/Cron/tests/E2E/ApiAdminTest.php
new file mode 100644
index 000000000..4b591c189
--- /dev/null
+++ b/src/modules/Cron/tests/E2E/ApiAdminTest.php
@@ -0,0 +1,40 @@
+wasSuccessful())->toBeTrue($result);
+
+ if (!empty($result->getResult()['last_cron_exec'])) {
+ $firstDate = new DateTime($result->getResult()['last_cron_exec']);
+ } else {
+ $firstDate = new DateTime();
+ $firstDate->modify('-1 hour');
+ }
+
+ $result = Tests\Helpers\ApiClient::request('admin/cron/run');
+ expect($result->wasSuccessful())->toBeTrue($result);
+
+ sleep(2);
+
+ $result = Tests\Helpers\ApiClient::request('admin/cron/info');
+ expect($result->wasSuccessful())->toBeTrue($result);
+ expect($result->getResult()['last_cron_exec'])->not->toBeEmpty();
+
+ $newDate = new DateTime($result->getResult()['last_cron_exec']);
+ expect($newDate)->toBeGreaterThan($firstDate);
+});
diff --git a/src/modules/Cron/tests/E2E/ApiGuestTest.php b/src/modules/Cron/tests/E2E/ApiGuestTest.php
new file mode 100644
index 000000000..cef364497
--- /dev/null
+++ b/src/modules/Cron/tests/E2E/ApiGuestTest.php
@@ -0,0 +1,31 @@
+ 'mod_cron', 'guest_cron' => false]);
+ $result = Tests\Helpers\ApiClient::request('guest/cron/run');
+ expect($result->wasSuccessful())->toBeFalse();
+
+ Tests\Helpers\ApiClient::request('admin/extension/config_save', ['ext' => 'mod_cron', 'guest_cron' => true]);
+ Tests\Helpers\ApiClient::request('admin/system/update_params', ['last_cron_exec' => date('Y-m-d H:i:s', time() - 6400)]);
+ $result = Tests\Helpers\ApiClient::request('guest/cron/run');
+ expect($result->wasSuccessful())->toBeTrue($result);
+
+ $result = Tests\Helpers\ApiClient::request('guest/cron/run');
+ expect($result->wasSuccessful())->toBeTrue();
+ expect($result->getResult())->toBeFalse();
+});
diff --git a/src/modules/Cron/tests/Unit/Api/AdminTest.php b/src/modules/Cron/tests/Unit/Api/AdminTest.php
new file mode 100644
index 000000000..73877075f
--- /dev/null
+++ b/src/modules/Cron/tests/Unit/Api/AdminTest.php
@@ -0,0 +1,34 @@
+setDi($di);
+ $getDi = $api_admin->getDi();
+ expect($getDi)->toEqual($di);
+});
+
+test('info returns cron information array', function (): void {
+ $serviceMock = Mockery::mock(Box\Mod\Cron\Service::class);
+ $serviceMock->shouldReceive('getCronInfo')->atLeast()->once()->andReturn([]);
+
+ $api_admin = new Admin();
+ $api_admin->setService($serviceMock);
+
+ $result = $api_admin->info([]);
+ expect($result)->toBeArray();
+});
diff --git a/src/modules/Cron/tests/Unit/Api/GuestTest.php b/src/modules/Cron/tests/Unit/Api/GuestTest.php
new file mode 100644
index 000000000..78cf95caa
--- /dev/null
+++ b/src/modules/Cron/tests/Unit/Api/GuestTest.php
@@ -0,0 +1,23 @@
+setDi($di);
+ $getDi = $api->getDi();
+ expect($getDi)->toEqual($di);
+});
diff --git a/src/modules/Cron/tests/Unit/ServiceTest.php b/src/modules/Cron/tests/Unit/ServiceTest.php
new file mode 100644
index 000000000..9eaa31f94
--- /dev/null
+++ b/src/modules/Cron/tests/Unit/ServiceTest.php
@@ -0,0 +1,63 @@
+setDi($di);
+ $getDi = $service->getDi();
+ expect($getDi)->toEqual($di);
+});
+
+test('getCronInfo returns cron information array', function (): void {
+ $systemServiceMock = Mockery::mock(Box\Mod\System\Service::class);
+ $systemServiceMock->shouldReceive('getParamValue')
+ ->atLeast()->once();
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn ($name): Mockery\MockInterface => $systemServiceMock);
+ $service = new Service();
+ $service->setDi($di);
+
+ $result = $service->getCronInfo();
+ expect($result)->toBeArray();
+});
+
+test('getLastExecutionTime returns string timestamp', function (): void {
+ $systemServiceMock = Mockery::mock(Box\Mod\System\Service::class);
+ $systemServiceMock->shouldReceive('getParamValue')
+ ->atLeast()->once()
+ ->andReturn('2012-12-12 12:12:12');
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn ($name): Mockery\MockInterface => $systemServiceMock);
+ $service = new Service();
+ $service->setDi($di);
+
+ $result = $service->getLastExecutionTime();
+ expect($result)->toBeString();
+});
+
+test('isLate returns boolean indicating if cron execution is late', function (): void {
+ $serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('getLastExecutionTime')
+ ->atLeast()->once()
+ ->andReturn(date('Y-m-d H:i:s'));
+
+ $result = $serviceMock->isLate();
+ expect($result)->toBeBool();
+ expect($result)->toBeFalse();
+});
diff --git a/src/modules/Currency/Api/Admin.php b/src/modules/Currency/Api/Admin.php
index 33bb00eef..ce856bb9b 100644
--- a/src/modules/Currency/Api/Admin.php
+++ b/src/modules/Currency/Api/Admin.php
@@ -28,14 +28,14 @@ class Admin extends \Api_Abstract
*/
public function get_list(array $data): array
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('currency', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('currency', 'view');
/** @var \Box\Mod\Currency\Repository\CurrencyRepository $repo */
$repo = $this->getService()->getCurrencyRepository();
$qb = $repo->getSearchQueryBuilder($data);
- return $this->di['pager']->paginateDoctrineQuery($qb, PaginationOptions::fromArray($data));
+ return $this->getDi()['pager']->paginateDoctrineQuery($qb, PaginationOptions::fromArray($data));
}
/**
@@ -45,7 +45,7 @@ class Admin extends \Api_Abstract
*/
public function get_pairs(): array
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('currency', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('currency', 'view');
$currencies = Currencies::getNames();
foreach ($currencies as $currencyCode => $currencyName) {
@@ -68,7 +68,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['code' => 'Currency code is missing'])]
public function get($data): array
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('currency', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('currency', 'view');
/** @var \Box\Mod\Currency\Repository\CurrencyRepository $repo */
$repo = $this->getService()->getCurrencyRepository();
@@ -87,7 +87,7 @@ class Admin extends \Api_Abstract
*/
public function get_default(): array
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('currency', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('currency', 'view');
/** @var \Box\Mod\Currency\Repository\CurrencyRepository $repo */
$repo = $this->getService()->getCurrencyRepository();
@@ -111,7 +111,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['code' => 'Currency code is missing'])]
public function create($data = []): string
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('currency', 'create');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('currency', 'create');
$service = $this->getService();
@@ -141,7 +141,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['code' => 'Currency code is missing'])]
public function update($data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('currency', 'edit');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('currency', 'edit');
$conversionRate = $data['conversion_rate'] ?? null;
@@ -153,7 +153,7 @@ class Admin extends \Api_Abstract
*/
public function is_cron_enabled(): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('currency', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('currency', 'view');
return $this->getService()->isCronEnabled();
}
@@ -163,7 +163,7 @@ class Admin extends \Api_Abstract
*/
public function update_rates(): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('currency', 'update_rates');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('currency', 'update_rates');
return $this->service->updateCurrencyRates();
}
@@ -176,7 +176,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['code' => 'Currency code is missing'])]
public function delete($data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('currency', 'delete');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('currency', 'delete');
return $this->getService()->removeCurrency($data['code']);
}
@@ -190,7 +190,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['code' => 'Currency code is missing'])]
public function set_default($data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('currency', 'set_default');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('currency', 'set_default');
$service = $this->getService();
diff --git a/src/modules/Currency/Entity/Currency.php b/src/modules/Currency/Entity/Currency.php
index 7d8daf26f..8a0b7cb04 100644
--- a/src/modules/Currency/Entity/Currency.php
+++ b/src/modules/Currency/Entity/Currency.php
@@ -25,6 +25,7 @@ class Currency implements ApiArrayInterface, TimestampInterface
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column(type: \Doctrine\DBAL\Types\Types::INTEGER)]
+ /** @phpstan-ignore property.unusedType (Doctrine entity ID is auto-generated by the database) */
private ?int $id = null;
#[ORM\Column(type: \Doctrine\DBAL\Types\Types::BOOLEAN, options: ['default' => false])]
@@ -72,7 +73,7 @@ class Currency implements ApiArrayInterface, TimestampInterface
$this->updatedAt = new \DateTime();
}
- public function getId(): ?int
+ public function getId(): int
{
return $this->id;
}
diff --git a/src/modules/Currency/tests/E2E/ApiAdminTest.php b/src/modules/Currency/tests/E2E/ApiAdminTest.php
new file mode 100644
index 000000000..7aeff068b
--- /dev/null
+++ b/src/modules/Currency/tests/E2E/ApiAdminTest.php
@@ -0,0 +1,38 @@
+wasSuccessful())->toBeTrue();
+
+ $list = $result->getResult();
+ expect($list)->toHaveKey('USD');
+ expect($list)->toHaveKey('EUR');
+ expect($list)->toHaveKey('GBP');
+ expect($list)->toHaveKey('JPY');
+ expect($list)->toHaveKey('CHF');
+ expect($list)->toHaveKey('AUD');
+ expect($list)->toHaveKey('CAD');
+ expect($list)->toHaveKey('NZD');
+ expect($list)->toHaveKey('INR');
+ expect($list)->toHaveKey('HKD');
+
+ $this->assertArrayNotHasKey('XXX', $list);
+ $this->assertArrayNotHasKey('XTS', $list);
+ $this->assertArrayNotHasKey('VES', $list);
+ $this->assertArrayNotHasKey('BZR', $list);
+});
diff --git a/src/modules/Currency/tests/E2E/ApiGuestTest.php b/src/modules/Currency/tests/E2E/ApiGuestTest.php
new file mode 100644
index 000000000..1959b9e85
--- /dev/null
+++ b/src/modules/Currency/tests/E2E/ApiGuestTest.php
@@ -0,0 +1,27 @@
+ 'USD']);
+ expect($result->wasSuccessful())->toBeTrue();
+
+ $defaults = $result->getResult();
+ expect('USD')->toEqual($defaults['code']);
+ expect('US Dollar')->toEqual($defaults['name']);
+ expect('$')->toEqual($defaults['symbol']);
+ expect(2)->toEqual($defaults['minorUnits']);
+});
diff --git a/src/modules/Currency/tests/Unit/Api/AdminTest.php b/src/modules/Currency/tests/Unit/Api/AdminTest.php
new file mode 100644
index 000000000..a95457354
--- /dev/null
+++ b/src/modules/Currency/tests/Unit/Api/AdminTest.php
@@ -0,0 +1,525 @@
+ 'AED - United Arab Emirates dirham',
+ 'AFN' => 'AFN - Afghan afghani',
+ 'ALL' => 'ALL - Albanian lek',
+ 'AMD' => 'AMD - Armenian dram',
+ 'ANG' => 'ANG - Netherlands Antillean guilder',
+ 'AOA' => 'AOA - Angolan kwanza',
+ 'ARS' => 'ARS - Argentine peso',
+ 'AUD' => 'AUD - Australian dollar',
+ 'AWG' => 'AWG - Aruban florin',
+ 'AZN' => 'AZN - Azerbaijani manat',
+ 'BAM' => 'BAM - Bosnia and Herzegovina convertible mark',
+ 'BBD' => 'BBD - Barbados dollar',
+ 'BDT' => 'BDT - Bangladeshi taka',
+ 'BGN' => 'BGN - Bulgarian lev',
+ 'BHD' => 'BHD - Bahraini dinar',
+ 'BIF' => 'BIF - Burundian franc',
+ 'BMD' => 'BMD - Bermudian dollar',
+ 'BND' => 'BND - Brunei dollar',
+ 'BOB' => 'BOB - Boliviano',
+ 'BRL' => 'BRL - Brazilian real',
+ 'BSD' => 'BSD - Bahamian dollar',
+ 'BTN' => 'BTN - Bhutanese ngultrum',
+ 'BWP' => 'BWP - Botswana pula',
+ 'BYR' => 'BYR - Belarusian ruble',
+ 'BZD' => 'BZD - Belize dollar',
+ 'CAD' => 'CAD - Canadian dollar',
+ 'CDF' => 'CDF - Congolese franc',
+ 'CHF' => 'CHF - Swiss franc',
+ 'CLP' => 'CLP - Chilean peso',
+ 'CNY' => 'CNY - Chinese yuan',
+ 'COP' => 'COP - Colombian peso',
+ 'COU' => 'COU - Unidad de Valor Real',
+ 'CRC' => 'CRC - Costa Rican colon',
+ 'CUC' => 'CUC - Cuban convertible peso',
+ 'CUP' => 'CUP - Cuban peso',
+ 'CVE' => 'CVE - Cape Verde escudo',
+ 'CZK' => 'CZK - Czech koruna',
+ 'DJF' => 'DJF - Djiboutian franc',
+ 'DKK' => 'DKK - Danish krone',
+ 'DOP' => 'DOP - Dominican peso',
+ 'DZD' => 'DZD - Algerian dinar',
+ 'EGP' => 'EGP - Egyptian pound',
+ 'ERN' => 'ERN - Eritrean nakfa',
+ 'ETB' => 'ETB - Ethiopian birr',
+ 'EUR' => 'EUR - Euro',
+ 'FJD' => 'FJD - Fiji dollar',
+ 'FKP' => 'FKP - Falkland Islands pound',
+ 'GBP' => 'GBP - Pound sterling',
+ 'GEL' => 'GEL - Georgian lari',
+ 'GHS' => 'GHS - Ghanaian cedi',
+ 'GIP' => 'GIP - Gibraltar pound',
+ 'GMD' => 'GMD - Gambian dalasi',
+ 'GNF' => 'GNF - Guinean franc',
+ 'GTQ' => 'GTQ - Guatemalan quetzal',
+ 'GYD' => 'GYD - Guyanese dollar',
+ 'HKD' => 'HKD - Hong Kong dollar',
+ 'HNL' => 'HNL - Honduran lempira',
+ 'HRK' => 'HRK - Croatian kuna',
+ 'HTG' => 'HTG - Haitian gourde',
+ 'HUF' => 'HUF - Hungarian forint',
+ 'IDR' => 'IDR - Indonesian rupiah',
+ 'ILS' => 'ILS - Israeli new sheqel',
+ 'INR' => 'INR - Indian rupee',
+ 'IQD' => 'IQD - Iraqi dinar',
+ 'IRR' => 'IRR - Iranian rial',
+ 'ISK' => 'ISK - Icelandic króna',
+ 'JMD' => 'JMD - Jamaican dollar',
+ 'JOD' => 'JOD - Jordanian dinar',
+ 'JPY' => 'JPY - Japanese yen',
+ 'KES' => 'KES - Kenyan shilling',
+ 'KGS' => 'KGS - Kyrgyzstani som',
+ 'KHR' => 'KHR - Cambodian riel',
+ 'KMF' => 'KMF - Comoro franc',
+ 'KPW' => 'KPW - North Korean won',
+ 'KRW' => 'KRW - South Korean won',
+ 'KWD' => 'KWD - Kuwaiti dinar',
+ 'KYD' => 'KYD - Cayman Islands dollar',
+ 'KZT' => 'KZT - Kazakhstani tenge',
+ 'LAK' => 'LAK - Lao kip',
+ 'LBP' => 'LBP - Lebanese pound',
+ 'LKR' => 'LKR - Sri Lanka rupee',
+ 'LRD' => 'LRD - Liberian dollar',
+ 'LSL' => 'LSL - Lesotho loti',
+ 'LYD' => 'LYD - Libyan dinar',
+ 'MAD' => 'MAD - Moroccan dirham',
+ 'MDL' => 'MDL - Moldovan leu',
+ 'MGA' => 'MGA - Malagasy ariary',
+ 'MKD' => 'MKD - Macedonian denar',
+ 'MMK' => 'MMK - Myanma kyat',
+ 'MNT' => 'MNT - Mongolian tugrik',
+ 'MOP' => 'MOP - Macanese pataca',
+ 'MRO' => 'MRO - Mauritanian ouguiya',
+ 'MUR' => 'MUR - Mauritian rupee',
+ 'MVR' => 'MVR - Maldivian rufiyaa',
+ 'MWK' => 'MWK - Malawian kwacha',
+ 'MXN' => 'MXN - Mexican peso',
+ 'MYR' => 'MYR - Malaysian ringgit',
+ 'MZN' => 'MZN - Mozambican metical',
+ 'NAD' => 'NAD - Namibian dollar',
+ 'NGN' => 'NGN - Nigerian naira',
+ 'NIO' => 'NIO - Cordoba oro',
+ 'NOK' => 'NOK - Norwegian krone',
+ 'NPR' => 'NPR - Nepalese rupee',
+ 'NZD' => 'NZD - New Zealand dollar',
+ 'OMR' => 'OMR - Omani rial',
+ 'PAB' => 'PAB - Panamanian balboa',
+ 'PEN' => 'PEN - Peruvian nuevo sol',
+ 'PGK' => 'PGK - Papua New Guinean kina',
+ 'PHP' => 'PHP - Philippine peso',
+ 'PKR' => 'PKR - Pakistani rupee',
+ 'PLN' => 'PLN - Polish złoty',
+ 'PYG' => 'PYG - Paraguayan guaraní',
+ 'QAR' => 'QAR - Qatari rial',
+ 'RON' => 'RON - Romanian new leu',
+ 'RSD' => 'RSD - Serbian dinar',
+ 'RUB' => 'RUB - Russian rouble',
+ 'RWF' => 'RWF - Rwandan franc',
+ 'SAR' => 'SAR - Saudi riyal',
+ 'SBD' => 'SBD - Solomon Islands dollar',
+ 'SCR' => 'SCR - Seychelles rupee',
+ 'SDG' => 'SDG - Sudanese pound',
+ 'SEK' => 'SEK - Swedish krona/kronor',
+ 'SGD' => 'SGD - Singapore dollar',
+ 'SHP' => 'SHP - Saint Helena pound',
+ 'SLL' => 'SLL - Sierra Leonean leone',
+ 'SOS' => 'SOS - Somali shilling',
+ 'SRD' => 'SRD - Surinamese dollar',
+ 'STD' => 'STD - São Tomé and Príncipe dobra',
+ 'SYP' => 'SYP - Syrian pound',
+ 'SZL' => 'SZL - Lilangeni',
+ 'THB' => 'THB - Thai baht',
+ 'TJS' => 'TJS - Tajikistani somoni',
+ 'TMT' => 'TMT - Turkmenistani manat',
+ 'TND' => 'TND - Tunisian dinar',
+ 'TOP' => 'TOP - Tongan paʻanga',
+ 'TRY' => 'TRY - Turkish lira',
+ 'TTD' => 'TTD - Trinidad and Tobago dollar',
+ 'TWD' => 'TWD - New Taiwan dollar',
+ 'TZS' => 'TZS - Tanzanian shilling',
+ 'UAH' => 'UAH - Ukrainian hryvnia',
+ 'UGX' => 'UGX - Ugandan shilling',
+ 'USD' => 'USD - United States dollar',
+ 'UYU' => 'UYU - Uruguayan peso',
+ 'UZS' => 'UZS - Uzbekistan som',
+ 'VEF' => 'VEF - Venezuelan bolívar fuerte',
+ 'VND' => 'VND - Vietnamese đồng',
+ 'VUV' => 'VUV - Vanuatu vatu',
+ 'WST' => 'WST - Samoan tala',
+ 'XOF' => 'XOF - West African CFA franc',
+ 'YER' => 'YER - Yemeni rial',
+ 'ZAR' => 'ZAR - South African rand',
+ 'ZMK' => 'ZMK - Zambian kwacha',
+ 'ZWL' => 'ZWL - Zimbabwe dollar',
+];
+
+test('get list', function (): void {
+ $adminApi = new Box\Mod\Currency\Api\Admin();
+
+ $willReturn = [
+ 'list' => ['id' => 1],
+ ];
+
+ $qbStub = $this->createStub(Doctrine\ORM\QueryBuilder::class);
+
+ $repositoryMock = Mockery::mock('\\' . Box\Mod\Currency\Repository\CurrencyRepository::class);
+ $repositoryMock
+ ->shouldReceive('getSearchQueryBuilder')
+ ->atLeast()->once()
+ ->andReturn($qbStub);
+
+ $serviceMock = Mockery::mock('\\' . Box\Mod\Currency\Service::class);
+ $serviceMock
+ ->shouldReceive('getCurrencyRepository')
+ ->atLeast()->once()
+ ->andReturn($repositoryMock);
+
+ $pager = Mockery::mock('\\' . FOSSBilling\Pagination::class)->makePartial();
+ $pager
+ ->shouldReceive('paginateDoctrineQuery')
+ ->atLeast()->once()
+ ->andReturn($willReturn);
+
+ $di = container();
+ $di['pager'] = $pager;
+
+ $adminApi->setDi($di);
+ $adminApi->setService($serviceMock);
+
+ $result = $adminApi->get_list([]);
+
+ expect($result)->toBeArray();
+ expect($result['list'])->toBeArray();
+});
+
+test('get pairs', function (): void {
+ $adminApi = new Box\Mod\Currency\Api\Admin();
+
+ $result = $adminApi->get_pairs();
+ expect($result)->toBeArray();
+ expect($result)->toHaveKey('EUR');
+ expect($result['EUR'])->toContain('EUR');
+});
+
+test('get', function (): void {
+ $adminApi = new Box\Mod\Currency\Api\Admin();
+
+ $model = Mockery::mock('\\' . Box\Mod\Currency\Entity\Currency::class);
+ $model
+ ->shouldReceive('toApiArray')
+ ->atLeast()->once()
+ ->andReturn([
+ 'code' => 'EUR',
+ 'title' => 'Euro',
+ 'conversion_rate' => 1.0,
+ 'format' => '€{{price}}',
+ 'price_format' => '€{{price}}',
+ ]);
+
+ $repositoryMock = Mockery::mock('\\' . Box\Mod\Currency\Repository\CurrencyRepository::class);
+ $repositoryMock
+ ->shouldReceive('findOneByCode')
+ ->atLeast()->once()
+ ->with('EUR')
+ ->andReturn($model);
+
+ $service = Mockery::mock('\\' . Box\Mod\Currency\Service::class);
+ $service
+ ->shouldReceive('getCurrencyRepository')
+ ->atLeast()->once()
+ ->andReturn($repositoryMock);
+
+ $di = container();
+ $data = [
+ 'code' => 'EUR',
+ ];
+ $adminApi->setService($service);
+ $adminApi->setDi($di);
+ $result = $adminApi->get($data);
+ expect($result)->toBeArray();
+ expect('EUR')->toEqual($result['code']);
+});
+
+test('get default', function (): void {
+ $adminApi = new Box\Mod\Currency\Api\Admin();
+
+ $returnArr = [
+ 'code' => 'EUR',
+ 'title' => 'Euro',
+ 'conversion_rate' => 3.4528,
+ 'format' => '',
+ 'price_format' => '',
+ 'default' => true,
+ ];
+
+ $model = Mockery::mock('\\' . Box\Mod\Currency\Entity\Currency::class);
+ $model
+ ->shouldReceive('toApiArray')
+ ->atLeast()->once()
+ ->andReturn($returnArr);
+
+ $repositoryMock = Mockery::mock('\\' . Box\Mod\Currency\Repository\CurrencyRepository::class);
+ $repositoryMock
+ ->shouldReceive('findDefault')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $service = Mockery::mock('\\' . Box\Mod\Currency\Service::class);
+ $service
+ ->shouldReceive('getCurrencyRepository')
+ ->atLeast()->once()
+ ->andReturn($repositoryMock);
+
+ $adminApi->setService($service);
+ $result = $adminApi->get_default([]);
+
+ expect($result)->toBeArray();
+ expect($returnArr)->toEqual($result);
+ expect($returnArr['code'])->toEqual('EUR');
+ expect($returnArr['title'])->toEqual('Euro');
+ expect($returnArr['conversion_rate'])->toBeFloat();
+ expect($returnArr['conversion_rate'])->toEqual(3.4528);
+ expect($returnArr['format'])->toEqual('');
+ expect($returnArr['price_format'])->toEqual('');
+ expect($returnArr['default'])->toBeTrue();
+});
+
+dataset('createException', [
+ [
+ [
+ 'code' => 'EUR',
+ 'format' => '€{{price}}',
+ ],
+ 'atLeastOnce',
+ 'currency_exists',
+ 'never',
+ ],
+ [
+ [
+ 'code' => 'NON',
+ 'format' => '€{{price}}',
+ ],
+ 'atLeastOnce',
+ null,
+ 'atLeastOnce',
+ ],
+]);
+
+test('create exception', function ($data, $findOneByCodeCalled, $findOneByCodeReturn, $getAvailableCurrenciesCalled): void {
+ $adminApi = new Box\Mod\Currency\Api\Admin();
+
+ $repositoryMock = Mockery::mock('\\' . Box\Mod\Currency\Repository\CurrencyRepository::class);
+
+ if ($findOneByCodeReturn === 'currency_exists') {
+ $findOneByCodeReturn = $this->createStub('\\' . Box\Mod\Currency\Entity\Currency::class);
+ }
+
+ if ($findOneByCodeCalled === 'atLeastOnce') {
+ $repositoryMock
+ ->shouldReceive('findOneByCode')
+ ->atLeast()->once()
+ ->andReturn($findOneByCodeReturn);
+ }
+
+ $service = Mockery::mock('\\' . Box\Mod\Currency\Service::class);
+ $service
+ ->shouldReceive('getCurrencyRepository')
+ ->atLeast()->once()
+ ->andReturn($repositoryMock);
+
+ $di = container();
+ $adminApi->setService($service);
+ $adminApi->setDi($di);
+ $this->expectException(FOSSBilling\Exception::class);
+ $adminApi->create($data);
+})->with('createException');
+
+test('create', function (): void {
+ $adminApi = new Box\Mod\Currency\Api\Admin();
+
+ $data = [
+ 'code' => 'EUR',
+ 'format' => '€{{price}}',
+ ];
+
+ $repositoryMock = Mockery::mock('\\' . Box\Mod\Currency\Repository\CurrencyRepository::class);
+ $repositoryMock
+ ->shouldReceive('findOneByCode')
+ ->atLeast()->once()
+ ->andReturn(null);
+
+ $service = Mockery::mock('\\' . Box\Mod\Currency\Service::class);
+ $service
+ ->shouldReceive('getCurrencyRepository')
+ ->atLeast()->once()
+ ->andReturn($repositoryMock);
+ $service
+ ->shouldReceive('createCurrency')
+ ->atLeast()->once()
+ ->andReturn($data['code']);
+
+ $di = container();
+ $adminApi->setService($service);
+ $adminApi->setDi($di);
+
+ $result = $adminApi->create($data);
+
+ expect($result)->toBeString();
+ expect(3)->toEqual(strlen($result));
+ expect($data['code'])->toEqual($result);
+});
+
+test('update', function (): void {
+ $adminApi = new Box\Mod\Currency\Api\Admin();
+
+ $data = [
+ 'code' => 'EUR',
+ 'format' => '€{{price}}',
+ 'title' => 'Euros',
+ 'price_format' => '€{{Price}}',
+ 'conversion_rate' => 0.6,
+ ];
+
+ $service = Mockery::mock(Box\Mod\Currency\Service::class);
+ $service
+ ->shouldReceive('updateCurrency')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+ $adminApi->setDi($di);
+ $adminApi->setService($service);
+
+ $result = $adminApi->update($data);
+
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+});
+
+test('delete exception', function (): void {
+ $adminApi = new Box\Mod\Currency\Api\Admin();
+
+ $service = Mockery::mock(Box\Mod\Currency\Service::class);
+ $service->shouldReceive('removeCurrency')->never();
+
+ $apiHandler = new Api_Handler(new Model_Admin());
+ $reflection = new ReflectionClass($apiHandler);
+ $method = $reflection->getMethod('validateRequiredParams');
+ $this->expectException(FOSSBilling\InformationException::class);
+ $method->invokeArgs($apiHandler, [$adminApi, 'delete', []]);
+
+ $di = container();
+ $di['validator'] = new FOSSBilling\Validate();
+ $adminApi->setDi($di);
+ $adminApi->setService($service);
+ $adminApi->delete([]);
+});
+
+test('delete', function (): void {
+ $adminApi = new Box\Mod\Currency\Api\Admin();
+
+ $data = [
+ 'code' => 'EUR',
+ 'format' => '€{{price}}',
+ ];
+
+ $service = Mockery::mock(Box\Mod\Currency\Service::class)->makePartial();
+ $service
+ ->shouldReceive('removeCurrency')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+ $di['validator'] = new FOSSBilling\Validate();
+ $adminApi->setDi($di);
+ $adminApi->setService($service);
+
+ $result = $adminApi->delete($data);
+
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+});
+
+dataset('setDefaultException', [
+ [
+ [
+ 'code' => 'EUR',
+ ],
+ 'atLeastOnce',
+ null,
+ ],
+]);
+
+test('set default exception', function ($data, $findOneByCodeCalled, $findOneByCodeReturn): void {
+ $adminApi = new Box\Mod\Currency\Api\Admin();
+
+ $repositoryMock = Mockery::mock('\\' . Box\Mod\Currency\Repository\CurrencyRepository::class);
+ $repositoryMock
+ ->shouldReceive('findOneByCode')
+ ->atLeast()->once()
+ ->andReturn(null);
+
+ $service = Mockery::mock('\\' . Box\Mod\Currency\Service::class);
+ $service
+ ->shouldReceive('getCurrencyRepository')
+ ->atLeast()->once()
+ ->andReturn($repositoryMock);
+
+ $di = container();
+ $adminApi->setDi($di);
+
+ $adminApi->setService($service);
+ $this->expectException(FOSSBilling\Exception::class);
+ $adminApi->set_default($data);
+})->with('setDefaultException');
+
+test('set default', function (): void {
+ $adminApi = new Box\Mod\Currency\Api\Admin();
+
+ $model = $this->createStub('\\' . Box\Mod\Currency\Entity\Currency::class);
+
+ $data = [
+ 'code' => 'EUR',
+ 'format' => '€{{price}}',
+ ];
+
+ $repositoryMock = Mockery::mock('\\' . Box\Mod\Currency\Repository\CurrencyRepository::class);
+ $repositoryMock
+ ->shouldReceive('findOneByCode')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $service = Mockery::mock('\\' . Box\Mod\Currency\Service::class);
+ $service
+ ->shouldReceive('getCurrencyRepository')
+ ->atLeast()->once()
+ ->andReturn($repositoryMock);
+ $service
+ ->shouldReceive('setAsDefault')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+ $adminApi->setDi($di);
+ $adminApi->setService($service);
+
+ $result = $adminApi->set_default($data);
+
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+});
diff --git a/src/modules/Currency/tests/Unit/Api/GuestTest.php b/src/modules/Currency/tests/Unit/Api/GuestTest.php
new file mode 100644
index 000000000..b40bed226
--- /dev/null
+++ b/src/modules/Currency/tests/Unit/Api/GuestTest.php
@@ -0,0 +1,222 @@
+ 'Euro',
+ 'USD' => 'US Dollar',
+ ];
+
+ $repositoryMock = Mockery::mock('\\' . Box\Mod\Currency\Repository\CurrencyRepository::class);
+ $repositoryMock
+ ->shouldReceive('getPairs')
+ ->atLeast()->once()
+ ->andReturn($willReturn);
+
+ $service = Mockery::mock('\\' . Box\Mod\Currency\Service::class);
+ $service
+ ->shouldReceive('getCurrencyRepository')
+ ->atLeast()->once()
+ ->andReturn($repositoryMock);
+
+ $guestApi->setService($service);
+
+ $result = $guestApi->get_pairs([]);
+ expect($willReturn)->toEqual($result);
+ expect($result)->toBeArray();
+ expect($result)->toHaveKey('EUR');
+ expect($result)->toHaveKey('USD');
+});
+
+dataset('getProvider', [
+ [
+ ['code' => 'EUR'],
+ 'has_model',
+ 'atLeastOnce',
+ 'never',
+ ],
+ [
+ [],
+ 'has_model',
+ 'never',
+ 'atLeastOnce',
+ ],
+]);
+
+test('get', function ($data, $modelFlag, $expectsGetByCode, $expectsGetDefault): void {
+ $guestApi = new Box\Mod\Currency\Api\Guest();
+
+ $willReturn = [
+ 'code' => 'EUR',
+ 'title' => 'Euro',
+ 'conversion_rate' => 1,
+ 'format' => '{{price}}',
+ 'price_format' => 1,
+ 'default' => 1,
+ ];
+
+ $model = ($modelFlag === 'has_model')
+ ? Mockery::mock('\\' . Box\Mod\Currency\Entity\Currency::class)
+ : null;
+
+ if ($model !== null) {
+ $model
+ ->shouldReceive('toApiArray')
+ ->atLeast()->once()
+ ->andReturn($willReturn);
+ }
+
+ $repositoryMock = Mockery::mock('\\' . Box\Mod\Currency\Repository\CurrencyRepository::class);
+ if ($expectsGetByCode === 'atLeastOnce') {
+ $repositoryMock
+ ->shouldReceive('findOneByCode')
+ ->atLeast()->once()
+ ->andReturn($model);
+ }
+ if ($expectsGetDefault === 'atLeastOnce') {
+ $repositoryMock
+ ->shouldReceive('findDefault')
+ ->atLeast()->once()
+ ->andReturn($model);
+ }
+
+ $service = Mockery::mock('\\' . Box\Mod\Currency\Service::class);
+ $service
+ ->shouldReceive('getCurrencyRepository')
+ ->atLeast()->once()
+ ->andReturn($repositoryMock);
+
+ $guestApi->setService($service);
+ $di = container();
+ $guestApi->setDi($di);
+
+ $result = $guestApi->get($data);
+ expect($result)->toBeArray();
+ expect($willReturn)->toEqual($result);
+})->with('getProvider');
+
+test('get exception', function (): void {
+ $guestApi = new Box\Mod\Currency\Api\Guest();
+
+ $repositoryMock = Mockery::mock('\\' . Box\Mod\Currency\Repository\CurrencyRepository::class);
+ $repositoryMock->shouldReceive('findOneByCode')->never();
+ $repositoryMock
+ ->shouldReceive('findDefault')
+ ->atLeast()->once()
+ ->andReturn(null);
+
+ $service = Mockery::mock('\\' . Box\Mod\Currency\Service::class);
+ $service
+ ->shouldReceive('getCurrencyRepository')
+ ->atLeast()->once()
+ ->andReturn($repositoryMock);
+
+ $guestApi->setService($service);
+ $this->expectException(FOSSBilling\Exception::class);
+ $result = $guestApi->get([]);
+});
+
+dataset('formatPriceFormatProvider', [
+ [1, '€60,000.00'],
+ [2, '€60,000.00'],
+ [3, '€60,000.00'],
+ [4, '€60,000.00'],
+ [5, '€60,000.00'],
+]);
+
+test('format price format', function ($price_format, $expectedResult): void {
+ $willReturn = [
+ 'code' => 'EUR',
+ 'title' => 'Euro',
+ 'conversion_rate' => 0.6,
+ 'format' => '€ {{price}}',
+ 'price_format' => $price_format,
+ 'default' => 1,
+ ];
+
+ $data = [
+ 'code' => 'EUR',
+ 'price' => 100000,
+ 'without_currency' => false,
+ ];
+ $guestApi = Mockery::mock(Box\Mod\Currency\Api\Guest::class)->makePartial();
+ $guestApi
+ ->shouldReceive('get')
+ ->atLeast()->once()
+ ->andReturn($willReturn);
+
+ $service = $this->createStub(Box\Mod\Currency\Service::class);
+
+ $di = container();
+
+ $guestApi->setDi($di);
+ $guestApi->setService($service);
+
+ $result = $guestApi->format($data);
+ expect($expectedResult)->toEqual($result);
+})->with('formatPriceFormatProvider');
+
+dataset('formatProvider', [
+ [
+ [
+ 'code' => 'EUR',
+ ],
+ '€0.00',
+ ],
+ [
+ [
+ 'code' => 'EUR',
+ 'price' => 100000,
+ 'convert' => false,
+ ],
+ '€100,000.00',
+ ],
+ [
+ [
+ 'code' => 'EUR',
+ 'price' => 100000,
+ 'without_currency' => true,
+ ],
+ '60,000.00',
+ ],
+]);
+
+test('format', function ($data, $expectedResult): void {
+ $willReturn = [
+ 'code' => 'EUR',
+ 'title' => 'Euro',
+ 'conversion_rate' => 0.6,
+ 'format' => '€ {{price}}',
+ 'price_format' => 1,
+ 'default' => 1,
+ ];
+
+ $guestApi = Mockery::mock(Box\Mod\Currency\Api\Guest::class)->makePartial();
+ $guestApi
+ ->shouldReceive('get')
+ ->atLeast()->once()
+ ->andReturn($willReturn);
+
+ $service = $this->createStub(Box\Mod\Currency\Service::class);
+
+ $di = container();
+
+ $guestApi->setDi($di);
+ $guestApi->setService($service);
+
+ $result = $guestApi->format($data);
+ expect($expectedResult)->toEqual($result);
+})->with('formatProvider');
diff --git a/src/modules/Currency/tests/Unit/Controller/AdminTest.php b/src/modules/Currency/tests/Unit/Controller/AdminTest.php
new file mode 100644
index 000000000..9bf21d966
--- /dev/null
+++ b/src/modules/Currency/tests/Unit/Controller/AdminTest.php
@@ -0,0 +1,37 @@
+setDi($di);
+ $result = $controller->getDi();
+ expect($result)->toEqual($di);
+});
+
+test('register method registers routes correctly', function (): void {
+ $boxAppMock = Mockery::mock('\Box_App');
+ $boxAppMock->shouldReceive('get')
+ ->once()
+ ->with('/currency/manage/:code', 'get_manage', ['code' => '[a-zA-Z]+'], Admin::class);
+
+ $controllerAdmin = new Admin();
+ $controllerAdmin->register($boxAppMock);
+});
diff --git a/src/modules/Currency/tests/Unit/ServiceTest.php b/src/modules/Currency/tests/Unit/ServiceTest.php
new file mode 100644
index 000000000..8f5c7c35f
--- /dev/null
+++ b/src/modules/Currency/tests/Unit/ServiceTest.php
@@ -0,0 +1,737 @@
+shouldReceive('getRepository')
+ ->atLeast()->once()
+ ->andReturn($repositoryStub);
+
+ $di['db'] = $db;
+ $di['em'] = $emMock;
+ $service->setDi($di);
+ $result = $service->getDi();
+ expect($result)->toBe($di);
+});
+
+test('getBaseCurrencyRate returns rate for currency', function (): void {
+ $service = new Box\Mod\Currency\Service();
+ $rate = 0.6;
+ $expected = 1 / $rate;
+ $repositoryMock = Mockery::mock(Box\Mod\Currency\Repository\CurrencyRepository::class);
+ $repositoryMock->shouldReceive('getRateByCode')
+ ->atLeast()->once()
+ ->andReturn($rate);
+
+ $emMock = Mockery::mock(Doctrine\ORM\EntityManager::class);
+ $emMock->shouldReceive('getRepository')
+ ->atLeast()->once()
+ ->andReturn($repositoryMock);
+
+ $di = new Pimple\Container();
+ $di['em'] = $emMock;
+ $service->setDi($di);
+ $code = 'EUR';
+ $result = $service->getBaseCurrencyRate($code);
+ expect($result)->toBe($expected);
+});
+
+test('getBaseCurrencyRate throws exception when rate is zero', function (): void {
+ $service = new Box\Mod\Currency\Service();
+
+ $repositoryMock = Mockery::mock(Box\Mod\Currency\Repository\CurrencyRepository::class);
+ $repositoryMock->shouldReceive('getRateByCode')
+ ->atLeast()->once()
+ ->andReturn(0.0);
+
+ $emMock = Mockery::mock(Doctrine\ORM\EntityManager::class);
+ $emMock->shouldReceive('getRepository')
+ ->atLeast()->once()
+ ->andReturn($repositoryMock);
+
+ $di = new Pimple\Container();
+ $di['em'] = $emMock;
+ $service->setDi($di);
+ $code = 'EUR';
+
+ expect(fn (): float => $service->getBaseCurrencyRate($code))
+ ->toThrow(FOSSBilling\Exception::class);
+});
+
+test('getBaseCurrencyRate throws exception when currency not found', function (): void {
+ $service = new Box\Mod\Currency\Service();
+
+ $repositoryMock = Mockery::mock(Box\Mod\Currency\Repository\CurrencyRepository::class);
+ $repositoryMock->shouldReceive('getRateByCode')
+ ->atLeast()->once()
+ ->andReturn(null);
+
+ $emMock = Mockery::mock(Doctrine\ORM\EntityManager::class);
+ $emMock->shouldReceive('getRepository')
+ ->atLeast()->once()
+ ->andReturn($repositoryMock);
+
+ $di = new Pimple\Container();
+ $di['em'] = $emMock;
+ $service->setDi($di);
+ $code = 'XYZ';
+
+ expect(fn (): float => $service->getBaseCurrencyRate($code))
+ ->toThrow(FOSSBilling\Exception::class, 'Currency not found');
+});
+
+dataset('toBaseCurrencyProvider', fn() => [
+ ['EUR', 'USD', 100, 0.73, 73],
+ ['USD', 'EUR', 100, 1.37, 137],
+ ['EUR', 'EUR', 100, 0.5, 100],
+]);
+
+test('toBaseCurrency converts amount to base currency', function (string $defaultCode, string $foreignCode, int $amount, float $rate, int $expected): void {
+ $model = Mockery::mock(Box\Mod\Currency\Entity\Currency::class);
+ $model->shouldReceive('getCode')
+ ->atLeast()->once()
+ ->andReturn($defaultCode);
+
+ $repositoryMock = Mockery::mock(Box\Mod\Currency\Repository\CurrencyRepository::class);
+ $repositoryMock->shouldReceive('findDefault')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $emMock = Mockery::mock(Doctrine\ORM\EntityManager::class);
+ $emMock->shouldReceive('getRepository')
+ ->atLeast()->once()
+ ->andReturn($repositoryMock);
+
+ $serviceMock = Mockery::mock(Box\Mod\Currency\Service::class)->makePartial();
+
+ $serviceMock->shouldReceive('getBaseCurrencyRate')
+ ->byDefault()
+ ->andReturn($rate);
+
+ $di = new Pimple\Container();
+ $di['em'] = $emMock;
+ $serviceMock->setDi($di);
+
+ $result = $serviceMock->toBaseCurrency($foreignCode, $amount);
+
+ expect(round($result, 2))->toEqual($expected);
+})->with('toBaseCurrencyProvider');
+
+dataset('getCurrencyByClientIdProvider', fn() => [
+ ['USD', 'atLeastOnce', 'never'],
+ [null, 'never', 'atLeastOnce'],
+]);
+
+test('getCurrencyByClientId returns currency for client', function (?string $currency, string $expectsGetByCode, string $expectsGetDefault): void {
+ $model = Mockery::mock(Box\Mod\Currency\Entity\Currency::class);
+
+ $di = new Pimple\Container();
+ $db = Mockery::mock('Box_Database');
+ $db->shouldReceive('getCell')
+ ->atLeast()->once()
+ ->andReturn($currency);
+
+ $repositoryMock = Mockery::mock(Box\Mod\Currency\Repository\CurrencyRepository::class);
+ if ($expectsGetDefault === 'atLeastOnce') {
+ $repositoryMock->shouldReceive('findDefault')
+ ->atLeast()->once()
+ ->andReturn($model);
+ } else {
+ $repositoryMock->shouldReceive('findDefault')->never();
+ }
+ if ($expectsGetByCode === 'atLeastOnce') {
+ $repositoryMock->shouldReceive('findOneByCode')
+ ->atLeast()->once()
+ ->andReturn($model);
+ } else {
+ $repositoryMock->shouldReceive('findOneByCode')->never();
+ }
+
+ $emMock = Mockery::mock(Doctrine\ORM\EntityManager::class);
+ $emMock->shouldReceive('getRepository')
+ ->atLeast()->once()
+ ->andReturn($repositoryMock);
+
+ $di['db'] = $db;
+ $di['em'] = $emMock;
+
+ $service = new Box\Mod\Currency\Service();
+ $service->setDi($di);
+
+ $result = $service->getCurrencyByClientId(1);
+
+ expect($result)->toBeInstanceOf(Box\Mod\Currency\Entity\Currency::class);
+})->with('getCurrencyByClientIdProvider');
+
+dataset('getRateByCodeProvider', fn() => [
+ ['EUR', 0.6, 0.6],
+ ['GBP', null, null],
+]);
+
+test('getRateByCode returns rate for currency code', function (string $code, ?float $returns, ?float $expected): void {
+ $repositoryMock = Mockery::mock(Box\Mod\Currency\Repository\CurrencyRepository::class);
+ $repositoryMock->shouldReceive('getRateByCode')
+ ->atLeast()->once()
+ ->andReturn($returns);
+
+ $emMock = Mockery::mock(Doctrine\ORM\EntityManager::class);
+ $emMock->shouldReceive('getRepository')
+ ->atLeast()->once()
+ ->andReturn($repositoryMock);
+
+ $di = new Pimple\Container();
+ $di['em'] = $emMock;
+
+ $service = new Box\Mod\Currency\Service();
+ $service->setDi($di);
+
+ $result = $service->getCurrencyRepository()->getRateByCode($code);
+ expect($result)->toBe($expected);
+})->with('getRateByCodeProvider');
+
+dataset('setAsDefaultProvider', fn() => [
+ ['default_currency', 'atLeastOnce'],
+ ['already_default', 'never'],
+]);
+
+test('setAsDefault sets currency as default', function (string $modelType, string $expects): void {
+ if ($modelType === 'default_currency') {
+ $model = Mockery::mock(Box\Mod\Currency\Entity\Currency::class);
+ $model->shouldReceive('getCode')
+ ->byDefault()
+ ->andReturn('USD');
+ $model->shouldReceive('isDefault')
+ ->byDefault()
+ ->andReturn(false);
+ } else {
+ $model = Mockery::mock(Box\Mod\Currency\Entity\Currency::class);
+ $model->shouldReceive('getCode')
+ ->byDefault()
+ ->andReturn('USD');
+ $model->shouldReceive('isDefault')
+ ->byDefault()
+ ->andReturn(true);
+ }
+
+ $refetchedModel = Mockery::mock(Box\Mod\Currency\Entity\Currency::class);
+ $refetchedModel->shouldReceive('getCode')
+ ->byDefault()
+ ->andReturn('USD');
+ $refetchedModel->shouldReceive('isDefault')
+ ->byDefault()
+ ->andReturn(false);
+
+ // setIsDefault is only called when currency is not already default
+ if ($modelType === 'default_currency') {
+ $refetchedModel->shouldReceive('setIsDefault')
+ ->atLeast()->once()
+ ->with(true);
+ }
+
+ $repositoryMock = Mockery::mock(Box\Mod\Currency\Repository\CurrencyRepository::class);
+ if ($expects === 'atLeastOnce') {
+ $repositoryMock->shouldReceive('clearDefaultFlags')
+ ->atLeast()->once();
+ $repositoryMock->shouldReceive('findOneByCode')
+ ->with('USD')
+ ->atLeast()->once()
+ ->andReturn($refetchedModel);
+ } else {
+ $repositoryMock->shouldReceive('clearDefaultFlags')->never();
+ $repositoryMock->shouldReceive('findOneByCode')->never();
+ }
+
+ $emMock = Mockery::mock(Doctrine\ORM\EntityManager::class);
+ $emMock->shouldReceive('getRepository')
+ ->atLeast()->once()
+ ->andReturn($repositoryMock);
+ if ($expects === 'atLeastOnce') {
+ $emMock->shouldReceive('persist')
+ ->atLeast()->once();
+ $emMock->shouldReceive('flush')
+ ->atLeast()->once();
+ $emMock->shouldReceive('clear')
+ ->with(Box\Mod\Currency\Entity\Currency::class)
+ ->atLeast()->once();
+ } else {
+ $emMock->shouldReceive('persist')->never();
+ $emMock->shouldReceive('flush')->never();
+ $emMock->shouldReceive('clear')->never();
+ }
+
+ $di = new Pimple\Container();
+ $di['em'] = $emMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $service = new Box\Mod\Currency\Service();
+ $service->setDi($di);
+ $result = $service->setAsDefault($model);
+
+ expect($result)->toBeTrue();
+})->with('setAsDefaultProvider');
+
+test('setAsDefault throws exception when currency code is empty', function (): void {
+ $model = Mockery::mock(Box\Mod\Currency\Entity\Currency::class);
+ $model->shouldReceive('isDefault')
+ ->byDefault()
+ ->andReturn(false);
+ $model->shouldReceive('getCode')
+ ->byDefault()
+ ->andReturn('');
+
+ $repositoryMock = Mockery::mock(Box\Mod\Currency\Repository\CurrencyRepository::class);
+
+ $emMock = Mockery::mock(Doctrine\ORM\EntityManager::class);
+ $emMock->shouldReceive('getRepository')
+ ->atLeast()->once()
+ ->andReturn($repositoryMock);
+
+ $di = new Pimple\Container();
+ $di['em'] = $emMock;
+
+ $service = new Box\Mod\Currency\Service();
+ $service->setDi($di);
+
+ expect(fn (): bool => $service->setAsDefault($model))
+ ->toThrow(FOSSBilling\Exception::class);
+});
+
+test('getPairs returns currency pairs', function (): void {
+ $pairs = [
+ 'USD' => 'US Dollar',
+ 'EUR' => 'Euro',
+ 'GBP' => 'Pound Sterling',
+ ];
+ $repositoryMock = Mockery::mock(Box\Mod\Currency\Repository\CurrencyRepository::class);
+ $repositoryMock->shouldReceive('getPairs')
+ ->atLeast()->once()
+ ->andReturn($pairs);
+
+ $emMock = Mockery::mock(Doctrine\ORM\EntityManager::class);
+ $emMock->shouldReceive('getRepository')
+ ->atLeast()->once()
+ ->andReturn($repositoryMock);
+
+ $di = new Pimple\Container();
+ $di['em'] = $emMock;
+
+ $service = new Box\Mod\Currency\Service();
+ $service->setDi($di);
+ $result = $service->getCurrencyRepository()->getPairs();
+
+ expect($result)->toBe($pairs);
+});
+
+test('removeCurrency throws exception when deleting default currency', function (): void {
+ $model = Mockery::mock(Box\Mod\Currency\Entity\Currency::class);
+ $model->shouldReceive('getCode')
+ ->byDefault()
+ ->andReturn('EUR');
+ $model->shouldReceive('isDefault')
+ ->byDefault()
+ ->andReturn(true);
+
+ $repositoryMock = Mockery::mock(Box\Mod\Currency\Repository\CurrencyRepository::class);
+ $repositoryMock->shouldReceive('findOneByCode')
+ ->once()
+ ->with('EUR')
+ ->andReturn($model);
+
+ $emMock = Mockery::mock(Doctrine\ORM\EntityManager::class);
+ $emMock->shouldReceive('getRepository')
+ ->atLeast()->once()
+ ->andReturn($repositoryMock);
+
+ $di = new Pimple\Container();
+ $di['em'] = $emMock;
+
+ $service = new Box\Mod\Currency\Service();
+ $service->setDi($di);
+
+ expect(fn (): bool => $service->removeCurrency('EUR'))
+ ->toThrow(FOSSBilling\InformationException::class);
+});
+
+test('removeCurrency removes currency', function (): void {
+ $model = Mockery::mock(Box\Mod\Currency\Entity\Currency::class);
+ $model->shouldReceive('getCode')
+ ->byDefault()
+ ->andReturn('EUR');
+ $model->shouldReceive('isDefault')
+ ->byDefault()
+ ->andReturn(false);
+
+ $repositoryMock = Mockery::mock(Box\Mod\Currency\Repository\CurrencyRepository::class);
+ $repositoryMock->shouldReceive('findOneByCode')
+ ->once()
+ ->with('EUR')
+ ->andReturn($model);
+
+ $emMock = Mockery::mock(Doctrine\ORM\EntityManager::class);
+ $emMock->shouldReceive('getRepository')
+ ->atLeast()->once()
+ ->andReturn($repositoryMock);
+ $emMock->shouldReceive('remove')
+ ->atLeast()->once()
+ ->with($model);
+ $emMock->shouldReceive('flush')
+ ->atLeast()->once();
+
+ $eventsManager = Mockery::mock(Box_EventManager::class);
+ $eventsManager->shouldReceive('fire')
+ ->twice();
+
+ $di = new Pimple\Container();
+ $di['em'] = $emMock;
+ $di['events_manager'] = $eventsManager;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $service = new Box\Mod\Currency\Service();
+ $service->setDi($di);
+ $result = $service->removeCurrency('EUR');
+
+ expect($result)->toBeTrue();
+});
+
+test('removeCurrency throws exception when currency is not found', function (): void {
+ $repositoryMock = Mockery::mock(Box\Mod\Currency\Repository\CurrencyRepository::class);
+ $repositoryMock->shouldReceive('findOneByCode')
+ ->once()
+ ->with('')
+ ->andReturn(null);
+
+ $emMock = Mockery::mock(Doctrine\ORM\EntityManager::class);
+ $emMock->shouldReceive('getRepository')
+ ->atLeast()->once()
+ ->andReturn($repositoryMock);
+
+ $di = new Pimple\Container();
+ $di['em'] = $emMock;
+
+ $service = new Box\Mod\Currency\Service();
+ $service->setDi($di);
+
+ expect(fn (): bool => $service->removeCurrency(''))
+ ->toThrow(FOSSBilling\Exception::class);
+});
+
+test('toApiArray returns API array for currency', function (): void {
+ $model = Mockery::mock(Box\Mod\Currency\Entity\Currency::class);
+
+ $expected = [
+ 'code' => 'EUR',
+ 'title' => 'Euro',
+ 'conversion_rate' => 3.4528,
+ 'format' => '',
+ 'price_format' => '',
+ 'default' => true,
+ ];
+
+ $model->shouldReceive('toApiArray')
+ ->atLeast()->once()
+ ->andReturn($expected);
+
+ $result = $model->toApiArray();
+ expect($result)->toBe($expected);
+});
+
+test('createCurrency creates new currency', function (): void {
+ $code = 'EUR';
+ $repositoryMock = Mockery::mock(Box\Mod\Currency\Repository\CurrencyRepository::class);
+
+ $emMock = Mockery::mock(Doctrine\ORM\EntityManager::class);
+ $emMock->shouldReceive('getRepository')
+ ->atLeast()->once()
+ ->andReturn($repositoryMock);
+ $emMock->shouldReceive('persist')
+ ->atLeast()->once();
+ $emMock->shouldReceive('flush')
+ ->atLeast()->once();
+
+ $di = container();
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $di['em'] = $emMock;
+
+ $service = new Box\Mod\Currency\Service();
+ $service->setDi($di);
+
+ $result = $service->createCurrency($code, 0.6);
+
+ expect($result)->toBeString();
+ expect(strlen($result))->toBe(3);
+ expect($result)->toBe($code);
+});
+
+test('updateCurrency updates currency', function (): void {
+ $code = 'EUR';
+ $conversion_rate = 0.6;
+
+ $model = Mockery::mock(Box\Mod\Currency\Entity\Currency::class);
+ $model->shouldReceive('getCode')
+ ->atLeast()->once()
+ ->andReturn('EUR');
+ $model->shouldReceive('setConversionRate')
+ ->atLeast()->once()
+ ->with(0.6);
+
+ $repositoryMock = Mockery::mock(Box\Mod\Currency\Repository\CurrencyRepository::class);
+ $repositoryMock->shouldReceive('findOneByCode')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $emMock = Mockery::mock(Doctrine\ORM\EntityManager::class);
+ $emMock->shouldReceive('getRepository')
+ ->atLeast()->once()
+ ->andReturn($repositoryMock);
+ $emMock->shouldReceive('persist')
+ ->atLeast()->once();
+ $emMock->shouldReceive('flush')
+ ->atLeast()->once();
+
+ $di = new Pimple\Container();
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $di['em'] = $emMock;
+
+ $service = new Box\Mod\Currency\Service();
+ $service->setDi($di);
+
+ $result = $service->updateCurrency($code, $conversion_rate);
+
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+});
+
+test('updateCurrency throws exception when currency not found', function (): void {
+ $code = 'EUR';
+ $conversion_rate = 0.6;
+
+ $repositoryMock = Mockery::mock(Box\Mod\Currency\Repository\CurrencyRepository::class);
+ $repositoryMock->shouldReceive('findOneByCode')
+ ->atLeast()->once()
+ ->andReturn(null);
+
+ $emMock = Mockery::mock(Doctrine\ORM\EntityManager::class);
+ $emMock->shouldReceive('getRepository')
+ ->atLeast()->once()
+ ->andReturn($repositoryMock);
+
+ $di = new Pimple\Container();
+ $di['em'] = $emMock;
+
+ $service = new Box\Mod\Currency\Service();
+ $service->setDi($di);
+
+ expect(fn (): bool => $service->updateCurrency($code, $conversion_rate))
+ ->toThrow(FOSSBilling\Exception::class);
+});
+
+test('updateCurrency throws exception when conversion rate is zero', function (): void {
+ $code = 'EUR';
+ $conversion_rate = 0;
+
+ $model = Mockery::mock(Box\Mod\Currency\Entity\Currency::class);
+ $model->shouldReceive('setConversionRate')
+ ->byDefault();
+
+ $repositoryMock = Mockery::mock(Box\Mod\Currency\Repository\CurrencyRepository::class);
+ $repositoryMock->shouldReceive('findOneByCode')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $emMock = Mockery::mock(Doctrine\ORM\EntityManager::class);
+ $emMock->shouldReceive('getRepository')
+ ->atLeast()->once()
+ ->andReturn($repositoryMock);
+
+ $di = new Pimple\Container();
+ $di['em'] = $emMock;
+
+ $service = new Box\Mod\Currency\Service();
+ $service->setDi($di);
+
+ expect(fn (): bool => $service->updateCurrency($code, $conversion_rate))
+ ->toThrow(FOSSBilling\Exception::class);
+});
+
+test('updateCurrencyRates updates rates for all currencies', function (): void {
+ $defaultModel = Mockery::mock(Box\Mod\Currency\Entity\Currency::class);
+ $defaultModel->shouldReceive('getCode')
+ ->byDefault()
+ ->andReturn('EUR');
+ $defaultModel->shouldReceive('isDefault')
+ ->byDefault()
+ ->andReturn(true);
+ $defaultModel->shouldReceive('setConversionRate')
+ ->byDefault();
+
+ $otherModel = Mockery::mock(Box\Mod\Currency\Entity\Currency::class);
+ $otherModel->shouldReceive('getCode')
+ ->byDefault()
+ ->andReturn('USD');
+ $otherModel->shouldReceive('isDefault')
+ ->byDefault()
+ ->andReturn(false);
+ $otherModel->shouldReceive('setConversionRate')
+ ->byDefault();
+
+ $repositoryMock = Mockery::mock(Box\Mod\Currency\Repository\CurrencyRepository::class);
+ $repositoryMock->shouldReceive('findDefault')
+ ->atLeast()->once()
+ ->andReturn($defaultModel);
+ $repositoryMock->shouldReceive('findAll')
+ ->atLeast()->once()
+ ->andReturn([$defaultModel, $otherModel]);
+
+ $emMock = Mockery::mock(Doctrine\ORM\EntityManager::class);
+ $emMock->shouldReceive('getRepository')
+ ->atLeast()->once()
+ ->andReturn($repositoryMock);
+ $emMock->shouldReceive('flush')
+ ->atLeast()->once();
+
+ $serviceMock = Mockery::mock(Box\Mod\Currency\Service::class)
+ ->makePartial()
+ ->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('getRate')
+ ->atLeast()->once()
+ ->andReturn(floatval(random_int(1, 50) / 10));
+
+ $di = new Pimple\Container();
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $di['em'] = $emMock;
+ $serviceMock->setDi($di);
+
+ $result = $serviceMock->updateCurrencyRates();
+
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+});
+
+test('updateCurrencyRates handles non-numeric rates', function (): void {
+ $model = Mockery::mock(Box\Mod\Currency\Entity\Currency::class);
+ $model->shouldReceive('getCode')
+ ->byDefault()
+ ->andReturn('EUR');
+ $model->shouldReceive('isDefault')
+ ->byDefault()
+ ->andReturn(false);
+ $model->shouldReceive('setConversionRate')
+ ->byDefault();
+
+ $repositoryMock = Mockery::mock(Box\Mod\Currency\Repository\CurrencyRepository::class);
+ $repositoryMock->shouldReceive('findDefault')
+ ->atLeast()->once()
+ ->andReturn($model);
+ $repositoryMock->shouldReceive('findAll')
+ ->atLeast()->once()
+ ->andReturn([$model]);
+
+ $emMock = Mockery::mock(Doctrine\ORM\EntityManager::class);
+ $emMock->shouldReceive('getRepository')
+ ->atLeast()->once()
+ ->andReturn($repositoryMock);
+ $emMock->shouldReceive('flush')
+ ->atLeast()->once();
+
+ $serviceMock = Mockery::mock(Box\Mod\Currency\Service::class)
+ ->makePartial()
+ ->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('getRate')
+ ->atLeast()->once()
+ ->andReturn(0.0);
+
+ $di = new Pimple\Container();
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $di['em'] = $emMock;
+ $serviceMock->setDi($di);
+
+ $result = $serviceMock->updateCurrencyRates();
+
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+});
+
+test('removeCurrency deletes currency by code', function (): void {
+ $model = Mockery::mock(Box\Mod\Currency\Entity\Currency::class);
+ $model->shouldReceive('getCode')
+ ->byDefault()
+ ->andReturn('EUR');
+ $model->shouldReceive('isDefault')
+ ->byDefault()
+ ->andReturn(false);
+
+ $code = 'EUR';
+
+ $repositoryMock = Mockery::mock(Box\Mod\Currency\Repository\CurrencyRepository::class);
+ $repositoryMock->shouldReceive('findOneByCode')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $emMock = Mockery::mock(Doctrine\ORM\EntityManager::class);
+ $emMock->shouldReceive('getRepository')
+ ->atLeast()->once()
+ ->andReturn($repositoryMock);
+ $emMock->shouldReceive('remove')
+ ->atLeast()->once();
+ $emMock->shouldReceive('flush')
+ ->atLeast()->once();
+
+ $manager = Mockery::mock('Box_EventManager');
+ $manager->shouldReceive('fire')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $di = new Pimple\Container();
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $di['em'] = $emMock;
+ $di['events_manager'] = $manager;
+
+ $service = new Box\Mod\Currency\Service();
+ $service->setDi($di);
+
+ $result = $service->removeCurrency($code);
+
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+});
+
+test('removeCurrency throws exception when currency not found by code', function (): void {
+ $code = 'EUR';
+
+ $repositoryMock = Mockery::mock(Box\Mod\Currency\Repository\CurrencyRepository::class);
+ $repositoryMock->shouldReceive('findOneByCode')
+ ->atLeast()->once()
+ ->andReturn(null);
+
+ $emMock = Mockery::mock(Doctrine\ORM\EntityManager::class);
+ $emMock->shouldReceive('getRepository')
+ ->atLeast()->once()
+ ->andReturn($repositoryMock);
+
+ $di = new Pimple\Container();
+ $di['em'] = $emMock;
+
+ $service = new Box\Mod\Currency\Service();
+ $service->setDi($di);
+
+ expect(fn (): bool => $service->removeCurrency($code))
+ ->toThrow(FOSSBilling\Exception::class);
+});
diff --git a/src/modules/Custompages/Api/Admin.php b/src/modules/Custompages/Api/Admin.php
index e570912ea..c369ccb57 100644
--- a/src/modules/Custompages/Api/Admin.php
+++ b/src/modules/Custompages/Api/Admin.php
@@ -23,7 +23,7 @@ class Admin extends \Api_Abstract
*/
public function get_list($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('custompages', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('custompages', 'view');
$pager = $this->getService()->searchPages($data);
@@ -40,7 +40,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Custom page ID was not passed'])]
public function delete($data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('custompages', 'manage');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('custompages', 'manage');
$this->getService()->deletePage($data['id']);
@@ -53,7 +53,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['ids' => 'Custom page IDs were not passed'])]
public function batch_delete($data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('custompages', 'manage');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('custompages', 'manage');
$this->getService()->deletePage($data['ids']);
@@ -71,7 +71,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['title' => 'Title was not passed', 'content' => 'Content was not passed'])]
public function create($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('custompages', 'manage');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('custompages', 'manage');
$title = $data['title'];
@@ -98,7 +98,7 @@ class Admin extends \Api_Abstract
])]
public function update($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('custompages', 'manage');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('custompages', 'manage');
$id = $data['id'];
$title = $data['title'];
@@ -117,7 +117,7 @@ class Admin extends \Api_Abstract
*/
public function get_page($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('custompages', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('custompages', 'view');
return $this->getService()->getPage($data['page_id']);
}
diff --git a/src/modules/Custompages/tests/Unit/ServiceTest.php b/src/modules/Custompages/tests/Unit/ServiceTest.php
new file mode 100644
index 000000000..d95b8b24a
--- /dev/null
+++ b/src/modules/Custompages/tests/Unit/ServiceTest.php
@@ -0,0 +1,51 @@
+shouldReceive('getPaginatedResultSet')->once()->andReturnUsing(
+ function (string $query, array $params, PaginationOptions $opts) {
+ expect($query)->toContain('title LIKE :q');
+ expect($query)->toContain('slug LIKE :q');
+ expect($query)->toContain('description LIKE :q');
+ expect($query)->toContain('keywords LIKE :q');
+ expect($query)->toContain('content LIKE :q');
+ expect($params)->toBe([':q' => '%landing%']);
+
+ return ['list' => []];
+ },
+ );
+
+ $di = new Pimple\Container();
+ $di['pager'] = $pager;
+
+ $service = new Box\Mod\Custompages\Service();
+ $service->setDi($di);
+
+ expect($service->searchPages(['search' => 'landing']))->toBe(['list' => []]);
+});
+
+test('search pages builds filter query', function (): void {
+ $pager = Mockery::mock(Pagination::class);
+ $pager->shouldReceive('getPaginatedResultSet')->once()->andReturnUsing(
+ function (string $query, array $params, PaginationOptions $opts) {
+ expect($query)->toContain('id = :id');
+ expect($query)->toContain('slug LIKE :slug');
+ expect($params)->toBe([':id' => 12, ':slug' => '%docs%']);
+
+ return ['list' => []];
+ },
+ );
+
+ $di = new Pimple\Container();
+ $di['pager'] = $pager;
+
+ $service = new Box\Mod\Custompages\Service();
+ $service->setDi($di);
+
+ expect($service->searchPages(['id' => '12', 'slug' => 'docs']))->toBe(['list' => []]);
+});
diff --git a/src/modules/Email/Api/Admin.php b/src/modules/Email/Api/Admin.php
index efdb9ea99..23593be8c 100644
--- a/src/modules/Email/Api/Admin.php
+++ b/src/modules/Email/Api/Admin.php
@@ -29,10 +29,10 @@ class Admin extends \Api_Abstract
*/
public function email_get_list($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('email', 'view_email_history');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('email', 'view_email_history');
[$sql, $params] = $this->getService()->getSearchQuery($data);
- $pager = $this->di['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
+ $pager = $this->getDi()['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
foreach ($pager['list'] as $key => $item) {
if (!is_array($item)) {
@@ -47,6 +47,7 @@ class Admin extends \Api_Abstract
'content_html' => Tools::sanitizeContent($item['content_html'] ?? ''),
'content_text' => $item['content_text'] ?? '',
'created_at' => $item['created_at'] ?? '',
+ 'updated_at' => $item['updated_at'] ?? '',
];
}
@@ -61,7 +62,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Email ID was not passed'])]
public function email_get($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('email', 'view_email_history');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('email', 'view_email_history');
$service = $this->getService();
$model = $service->getEmailById($data['id']);
@@ -84,7 +85,7 @@ class Admin extends \Api_Abstract
])]
public function send(array $data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('email', 'send_emails');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('email', 'send_emails');
$client_id = $data['client_id'] ?? null;
$emailService = $this->getService();
@@ -110,9 +111,9 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Email ID was not passed'])]
public function email_resend($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('email', 'send_emails');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('email', 'send_emails');
- $model = $this->di['db']->findOne('ActivityClientEmail', 'id = ?', [$data['id']]);
+ $model = $this->getDi()['db']->findOne('ActivityClientEmail', 'id = ?', [$data['id']]);
if (!$model instanceof \Model_ActivityClientEmail) {
throw new \FOSSBilling\Exception('Email not found');
@@ -129,18 +130,18 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Email ID was not passed'])]
public function email_delete($data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('email', 'delete_email_history');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('email', 'delete_email_history');
- $model = $this->di['db']->findOne('ActivityClientEmail', 'id = ?', [$data['id']]);
+ $model = $this->getDi()['db']->findOne('ActivityClientEmail', 'id = ?', [$data['id']]);
if (!$model instanceof \Model_ActivityClientEmail) {
throw new \FOSSBilling\Exception('Email not found');
}
$id = $model->id;
- $this->di['db']->trash($model);
+ $this->getDi()['db']->trash($model);
- $this->di['logger']->info('Deleted email #%s', $id);
+ $this->getDi()['logger']->info('Deleted email #%s', $id);
return true;
}
@@ -152,7 +153,7 @@ class Admin extends \Api_Abstract
*/
public function template_get_list($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('email', 'view_templates');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('email', 'view_templates');
$pager = $this->getService()->getTemplateList($data);
@@ -183,7 +184,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Email ID was not passed'])]
public function template_get($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('email', 'view_templates');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('email', 'view_templates');
$model = $this->getService()->getTemplate((int) $data['id']);
@@ -198,7 +199,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Email ID was not passed'])]
public function template_delete($data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('email', 'manage_templates');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('email', 'manage_templates');
$service = $this->getService();
$template = $service->getTemplate((int) $data['id']);
@@ -207,10 +208,10 @@ class Admin extends \Api_Abstract
}
$id = $template->getId();
- $this->di['em']->remove($template);
- $this->di['em']->flush();
+ $this->getDi()['em']->remove($template);
+ $this->getDi()['em']->flush();
- $this->di['logger']->info('Deleted email template #%s', $id);
+ $this->getDi()['logger']->info('Deleted email template #%s', $id);
return true;
}
@@ -230,7 +231,7 @@ class Admin extends \Api_Abstract
])]
public function template_create($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('email', 'manage_templates');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('email', 'manage_templates');
$enabled = $data['enabled'] ?? 0;
$category = $data['category'] ?? null;
@@ -250,7 +251,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Email ID was not passed'])]
public function template_update($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('email', 'manage_templates');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('email', 'manage_templates');
$enabled = $data['enabled'] ?? null;
$category = $data['category'] ?? null;
@@ -270,7 +271,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['code' => 'Email template code was not passed'])]
public function template_reset($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('email', 'manage_templates');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('email', 'manage_templates');
return $this->getService()->resetTemplateByCode($data['code']);
}
@@ -284,13 +285,13 @@ class Admin extends \Api_Abstract
*/
public function template_render($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('email', 'manage_templates');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('email', 'manage_templates');
$model = $this->getService()->getTemplate((int) $data['id']);
$t = $this->getService()->templateToApiArray($model, true);
$vars = $t['vars'];
$vars['_tpl'] = $data['_tpl'] ?? $t['content'];
- $systemService = $this->di['mod_service']('System');
+ $systemService = $this->getDi()['mod_service']('System');
return $systemService->renderEmailTplString($vars['_tpl'], $vars);
}
@@ -302,7 +303,7 @@ class Admin extends \Api_Abstract
*/
public function batch_template_generate()
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('email', 'manage_templates');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('email', 'manage_templates');
return $this->getService()->templateBatchGenerate();
}
@@ -314,7 +315,7 @@ class Admin extends \Api_Abstract
*/
public function batch_template_disable($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('email', 'manage_templates');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('email', 'manage_templates');
return $this->getService()->templateBatchDisable();
}
@@ -326,7 +327,7 @@ class Admin extends \Api_Abstract
*/
public function batch_template_enable($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('email', 'manage_templates');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('email', 'manage_templates');
return $this->getService()->templateBatchEnable();
}
@@ -336,9 +337,9 @@ class Admin extends \Api_Abstract
*/
public function send_test(array $data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('email', 'send_emails');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('email', 'send_emails');
- $currentUser = $this->di['loggedin_admin'] ?? null;
+ $currentUser = $this->getDi()['loggedin_admin'] ?? null;
$email = [
'code' => 'mod_email_test',
@@ -354,9 +355,9 @@ class Admin extends \Api_Abstract
public function batch_sendmail()
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('email', 'send_emails', null, $this->identity);
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('email', 'send_emails', null, $this->identity);
- $extensionService = $this->di['mod_service']('extension');
+ $extensionService = $this->getDi()['mod_service']('extension');
if ($extensionService->isExtensionActive('mod', 'demo')) {
return false;
}
@@ -383,7 +384,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['code' => 'Template code not passed'])]
public function template_send($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('email', 'send_emails');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('email', 'send_emails');
if (!isset($data['to']) && !isset($data['to_staff']) && !isset($data['to_client'])) {
throw new \FOSSBilling\InformationException('Receiver is not defined. Define to or to_client or to_staff parameter');
@@ -398,7 +399,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['ids' => 'IDs were not passed'])]
public function batch_delete($data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('email', 'delete_email_history');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('email', 'delete_email_history');
foreach ($data['ids'] as $id) {
$this->email_delete(['id' => $id]);
@@ -409,10 +410,10 @@ class Admin extends \Api_Abstract
public function get_queue(array $data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('email', 'view_email_history');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('email', 'view_email_history');
[$sql, $params] = $this->getService()->queueGetSearchQuery($data);
- $pager = $this->di['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
+ $pager = $this->getDi()['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
foreach ($pager['list'] as $key => $item) {
$pager['list'][$key] = [
diff --git a/src/modules/Email/Api/Client.php b/src/modules/Email/Api/Client.php
index c590b3ee1..1a373ad50 100644
--- a/src/modules/Email/Api/Client.php
+++ b/src/modules/Email/Api/Client.php
@@ -32,7 +32,7 @@ class Client extends \Api_Abstract
$client = $this->getIdentity();
$data['client_id'] = $client->id;
[$sql, $params] = $this->getService()->getSearchQuery($data);
- $pager = $this->di['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
+ $pager = $this->getDi()['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
foreach ($pager['list'] as $key => $item) {
$pager['list'][$key] = [
@@ -82,8 +82,8 @@ class Client extends \Api_Abstract
{
$client = $this->getIdentity();
- $this->di['rate_limiter']->consumeOrThrow('client_email_resend_ip', (string) $this->getIp());
- $this->di['rate_limiter']->consumeOrThrow('client_email_resend_account', 'client:' . $client->id);
+ $this->getDi()['rate_limiter']->consumeOrThrow('client_email_resend_ip', (string) $this->getIp());
+ $this->getDi()['rate_limiter']->consumeOrThrow('client_email_resend_account', 'client:' . $client->id);
$model = $this->getService()->findOneForClientById($client, $data['id']);
if (!$model instanceof \Model_ActivityClientEmail) {
diff --git a/src/modules/Email/Entity/EmailTemplate.php b/src/modules/Email/Entity/EmailTemplate.php
index 355503fa5..46cc008b8 100644
--- a/src/modules/Email/Entity/EmailTemplate.php
+++ b/src/modules/Email/Entity/EmailTemplate.php
@@ -51,7 +51,9 @@ class EmailTemplate implements ApiArrayInterface
public function __construct(
#[ORM\Column(name: 'action_code', type: Types::STRING, length: 255, unique: true)]
private string $actionCode,
+ ?int $id = null,
) {
+ $this->id = $id;
}
public function toApiArray(): array
diff --git a/src/modules/Email/Service.php b/src/modules/Email/Service.php
index 900c42c3f..2c4135d38 100644
--- a/src/modules/Email/Service.php
+++ b/src/modules/Email/Service.php
@@ -580,6 +580,7 @@ class Service implements \FOSSBilling\InjectionAwareInterface
}
if (Environment::isTesting()) {
+ // @phpstan-ignore if.alwaysFalse
if (DEBUG) {
$this->di['logger']->setChannel('email')->info('Skipping email sending in test environment');
}
diff --git a/src/modules/Email/tests/Unit/Api/AdminTest.php b/src/modules/Email/tests/Unit/Api/AdminTest.php
new file mode 100644
index 000000000..0da23a213
--- /dev/null
+++ b/src/modules/Email/tests/Unit/Api/AdminTest.php
@@ -0,0 +1,578 @@
+ [
+ 'id' => 1,
+ ],
+ ];
+
+ $pager = Mockery::mock(FOSSBilling\Pagination::class)->makePartial();
+ $pager
+ ->shouldReceive('getPaginatedResultSet')
+ ->atLeast()->once()
+ ->andReturn($willReturn);
+
+ $di = container();
+ $di['pager'] = $pager;
+
+ $adminApi->setDi($di);
+ $emailService->setDi($di);
+
+ $service = $emailService;
+ $adminApi->setService($service);
+
+ $result = $adminApi->email_get_list([]);
+ expect($result)->toBeArray();
+
+ expect($result)->toHaveKey('list');
+ expect($result['list'])->toBeArray();
+});
+
+test('email get', function (): void {
+ $adminApi = new Box\Mod\Email\Api\Admin();
+
+ $data = [
+ 'id' => 1,
+ ];
+ $id = 10;
+ $client_id = 5;
+ $sender = 'sender@example.com';
+ $recipients = 'recipient@example.com';
+ $subject = 'Subject';
+ $content_html = 'HTML';
+ $content_text = 'TEXT';
+ $created = date('Y-m-d H:i:s', time() - 86400);
+ $updated = date('Y-m-d H:i:s');
+
+ $model = new Model_ActivityClientEmail();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $model->id = $id;
+ $model->client_id = $client_id;
+ $model->sender = $sender;
+ $model->recipients = $recipients;
+ $model->subject = $subject;
+ $model->content_html = $content_html;
+ $model->content_text = $content_text;
+ $model->created_at = $created;
+ $model->updated_at = $updated;
+
+ $expected = [
+ 'id' => $id,
+ 'client_id' => $client_id,
+ 'sender' => $sender,
+ 'recipients' => $recipients,
+ 'subject' => $subject,
+ 'content_html' => $content_html,
+ 'content_text' => $content_text,
+ 'created_at' => $created,
+ 'updated_at' => $updated,
+ ];
+
+ $service = Mockery::mock(Box\Mod\Email\Service::class)->makePartial();
+ $service
+ ->shouldReceive('getEmailById')
+ ->atLeast()->once()
+ ->andReturn($model);
+ $service
+ ->shouldReceive('toApiArray')
+ ->atLeast()->once()
+ ->andReturn($expected);
+
+ $di = container();
+ $adminApi->setDi($di);
+ $adminApi->setService($service);
+
+ $result = $adminApi->email_get($data);
+
+ expect($result)->toBeArray();
+ expect($expected)->toEqual($result);
+});
+
+test('send', function (): void {
+ $adminApi = new Box\Mod\Email\Api\Admin();
+
+ $data = [
+ 'to' => 'to@example.com',
+ 'to_name' => 'Recipient Name',
+ 'from' => 'from@example.com',
+ 'from_name' => 'Sender Name',
+ 'subject' => 'Subject',
+ 'content' => 'Content',
+ ];
+
+ $model = new Model_ActivityClientEmail();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $model->id = 1;
+
+ $emailService = Mockery::mock(Box\Mod\Email\Service::class)->makePartial();
+ $emailService
+ ->shouldReceive('sendMail')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+
+ $adminApi->setDi($di);
+ $adminApi->setService($emailService);
+
+ $result = $adminApi->send($data);
+
+ expect($result)->toBeTrue();
+});
+
+test('resend', function (): void {
+ $adminApi = new Box\Mod\Email\Api\Admin();
+
+ $data = [
+ 'id' => 1,
+ ];
+
+ $model = new Model_ActivityClientEmail();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $model->id = 1;
+
+ $db = Mockery::mock('Box_Database');
+ $db
+ ->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $di = container();
+ $di['db'] = $db;
+ $adminApi->setDi($di);
+
+ $emailService = Mockery::mock(Box\Mod\Email\Service::class)->makePartial();
+ $emailService
+ ->shouldReceive('resend')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $adminApi->setService($emailService);
+
+ $result = $adminApi->email_resend($data);
+
+ expect($result)->toBeTrue();
+});
+
+test('resend exception email not found', function (): void {
+ $adminApi = new Box\Mod\Email\Api\Admin();
+
+ $data = [
+ 'id' => 1,
+ ];
+
+ $db = Mockery::mock('Box_Database');
+ $db
+ ->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn(null);
+
+ $di = container();
+ $di['db'] = $db;
+ $adminApi->setDi($di);
+
+ $this->expectException(FOSSBilling\Exception::class);
+ $this->expectExceptionMessage('Email not found');
+ $adminApi->email_resend($data);
+});
+
+test('delete exception email not found', function (): void {
+ $adminApi = new Box\Mod\Email\Api\Admin();
+
+ $data = [
+ 'id' => 1,
+ ];
+
+ $db = Mockery::mock('Box_Database');
+ $db
+ ->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn(null);
+
+ $di = container();
+ $di['db'] = $db;
+ $adminApi->setDi($di);
+
+ $this->expectException(FOSSBilling\Exception::class);
+ $this->expectExceptionMessage('Email not found');
+ $adminApi->email_delete($data);
+});
+
+test('email delete', function (): void {
+ $adminApi = new Box\Mod\Email\Api\Admin();
+ $emailService = new Box\Mod\Email\Service();
+
+ $data = [
+ 'id' => 1,
+ ];
+
+ $model = new Model_ActivityClientEmail();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $model->id = 1;
+
+ $db = Mockery::mock('Box_Database');
+ $db
+ ->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn($model);
+ $db
+ ->shouldReceive('trash')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $loggerStub = $this->createStub('\Box_Log');
+
+ $di = container();
+ $di['db'] = $db;
+ $di['logger'] = $loggerStub;
+ $adminApi->setDi($di);
+
+ $adminApi->setService($emailService);
+
+ $result = $adminApi->email_delete($data);
+
+ expect($result)->toBeTrue();
+});
+
+test('template get list', function (): void {
+ $adminApi = new Box\Mod\Email\Api\Admin();
+
+ $willReturn = [
+ 'list' => [
+ [
+ 'id' => 1,
+ 'action_code' => 'mod_email_test',
+ ],
+ ],
+ ];
+
+ $emailService = Mockery::mock(Box\Mod\Email\Service::class)->makePartial();
+ $emailService->shouldReceive('getTemplateList')->atLeast()->once()->andReturn($willReturn);
+
+ $di = container();
+
+ $adminApi->setDi($di);
+ $adminApi->setService($emailService);
+
+ $result = $adminApi->template_get_list([]);
+ expect($result)->toBeArray();
+
+ expect($result)->toHaveKey('list');
+ expect($result['list'])->toBeArray();
+});
+
+test('template get', function (): void {
+ $adminApi = new Box\Mod\Email\Api\Admin();
+
+ $data = [
+ 'id' => 1,
+ ];
+
+ $model = new EmailTemplate('mod_email_test', 1);
+
+ $emailService = Mockery::mock(Box\Mod\Email\Service::class)->makePartial();
+ $emailService->shouldReceive('getTemplate')->atLeast()->once()->with(1)->andReturn($model);
+ $emailService
+ ->shouldReceive('templateToApiArray')
+ ->atLeast()->once()
+ ->andReturn([]);
+ $di = container();
+ $adminApi->setDi($di);
+ $adminApi->setService($emailService);
+
+ $result = $adminApi->template_get($data);
+ expect($result)->toBeArray();
+});
+
+test('template delete', function (): void {
+ $adminApi = new Box\Mod\Email\Api\Admin();
+
+ $data = [
+ 'id' => 1,
+ ];
+
+ $model = (new EmailTemplate('custom_email_test', 1))->setIsCustom(true);
+ $emailService = Mockery::mock(Box\Mod\Email\Service::class)->makePartial();
+ $emailService->shouldReceive('getTemplate')->atLeast()->once()->with(1)->andReturn($model);
+ $emailService->shouldReceive('hasDefaultTemplate')->never();
+
+ $loggerStub = $this->createStub('\Box_Log');
+ $em = Mockery::mock(Doctrine\ORM\EntityManagerInterface::class);
+ $em->shouldReceive('remove')->atLeast()->once()->with($model);
+ $em->shouldReceive('flush')->atLeast()->once();
+
+ $di = container();
+ $di['em'] = $em;
+ $di['logger'] = $loggerStub;
+ $adminApi->setDi($di);
+ $adminApi->setService($emailService);
+
+ $result = $adminApi->template_delete($data);
+ expect($result)->toBeTrue();
+});
+
+test('template delete template not found', function (): void {
+ $adminApi = new Box\Mod\Email\Api\Admin();
+
+ $data = [
+ 'id' => 1,
+ ];
+
+ $emailService = Mockery::mock(Box\Mod\Email\Service::class)->makePartial();
+ $emailService->shouldReceive('getTemplate')->atLeast()->once()->andThrow(new FOSSBilling\Exception('Email template not found'));
+
+ $di = container();
+ $adminApi->setDi($di);
+ $adminApi->setService($emailService);
+
+ $this->expectException(FOSSBilling\Exception::class);
+ $this->expectExceptionMessage('Email template not found');
+ $adminApi->template_delete($data);
+});
+
+test('template create', function (): void {
+ $adminApi = new Box\Mod\Email\Api\Admin();
+
+ $modelId = 1;
+
+ $templateModel = new EmailTemplate('Action_code', $modelId);
+
+ $data = [
+ 'action_code' => 'Action_code',
+ 'subject' => 'Subject',
+ 'content' => 'Content',
+ ];
+
+ $emailService = Mockery::mock(Box\Mod\Email\Service::class)->makePartial();
+ $emailService
+ ->shouldReceive('templateCreate')
+ ->atLeast()->once()
+ ->andReturn($templateModel);
+
+ $di = container();
+ $adminApi->setDi($di);
+ $adminApi->setService($emailService);
+
+ $result = $adminApi->template_create($data);
+ expect($modelId)->toEqual($result);
+});
+
+test('template send to not set exception', function (): void {
+ $adminApi = new Box\Mod\Email\Api\Admin();
+
+ $di = container();
+ $adminApi->setDi($di);
+ $this->expectException(FOSSBilling\Exception::class);
+ $adminApi->template_send(['code' => 'code']);
+});
+
+test('template update', function (): void {
+ $adminApi = new Box\Mod\Email\Api\Admin();
+
+ $id = 1;
+ $data = [
+ 'id' => $id,
+ 'enabled' => '1',
+ 'category' => 'Category',
+ 'action_code' => 'Action_code',
+ 'subject' => 'Subject',
+ 'content' => 'Content',
+ ];
+
+ $emailTemplateModel = new EmailTemplate('Action_code', $id);
+
+ $di = container();
+ $emailService = Mockery::mock(Box\Mod\Email\Service::class)->makePartial();
+ $emailService->shouldReceive('getTemplate')->atLeast()->once()->with($id)->andReturn($emailTemplateModel);
+ $emailService
+ ->shouldReceive('updateTemplate')
+ ->atLeast()->once()
+ ->with($emailTemplateModel, $data['enabled'], $data['category'], $data['subject'], $data['content'])
+ ->andReturn(true);
+ $adminApi->setService($emailService);
+ $adminApi->setDi($di);
+
+ $result = $adminApi->template_update($data);
+ expect($result)->toBeTrue();
+});
+
+test('template reset', function (): void {
+ $adminApi = new Box\Mod\Email\Api\Admin();
+
+ $id = 1;
+ $data = [
+ 'code' => 'CODE',
+ ];
+
+ $emailService = Mockery::mock(Box\Mod\Email\Service::class)->makePartial();
+ $emailService
+ ->shouldReceive('resetTemplateByCode')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+ $adminApi->setDi($di);
+ $adminApi->setService($emailService);
+
+ $result = $adminApi->template_reset($data);
+ expect($result)->toBeTrue();
+});
+
+test('batch template generate', function (): void {
+ $adminApi = new Box\Mod\Email\Api\Admin();
+ $emailService = Mockery::mock(Box\Mod\Email\Service::class)->makePartial();
+ $emailService
+ ->shouldReceive('templateBatchGenerate')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $adminApi->setService($emailService);
+
+ $result = $adminApi->batch_template_generate();
+ expect($result)->toBeTrue();
+});
+
+test('batch template disable', function (): void {
+ $adminApi = new Box\Mod\Email\Api\Admin();
+ $emailService = Mockery::mock(Box\Mod\Email\Service::class)->makePartial();
+ $emailService
+ ->shouldReceive('templateBatchDisable')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $adminApi->setService($emailService);
+
+ $result = $adminApi->batch_template_disable([]);
+ expect($result)->toBeTrue();
+});
+
+test('batch template enable', function (): void {
+ $adminApi = new Box\Mod\Email\Api\Admin();
+ $emailService = Mockery::mock(Box\Mod\Email\Service::class)->makePartial();
+ $emailService
+ ->shouldReceive('templateBatchEnable')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $adminApi->setService($emailService);
+
+ $result = $adminApi->batch_template_enable([]);
+ expect($result)->toBeTrue();
+});
+
+test('send test', function (): void {
+ $adminApi = new Box\Mod\Email\Api\Admin();
+ $emailService = Mockery::mock(Box\Mod\Email\Service::class)->makePartial();
+ $emailService
+ ->shouldReceive('sendTemplate')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $adminApi->setService($emailService);
+
+ $result = $adminApi->send_test([]);
+ expect($result)->toBeTrue();
+});
+
+test('batch sendmail', function (): void {
+ $adminApi = new Box\Mod\Email\Api\Admin();
+ $emailService = Mockery::mock(Box\Mod\Email\Service::class)->makePartial();
+ $emailService->shouldReceive('batchSend')->atLeast()->once();
+
+ $isExtensionActiveReturn = false;
+ $extension = Mockery::mock(Box\Mod\Extension\Service::class);
+ $extension
+ ->shouldReceive('isExtensionActive')
+ ->atLeast()->once()
+ ->andReturn($isExtensionActiveReturn);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(moduleService(['extension' => $extension]));
+
+ $adminApi->setService($emailService);
+ $adminApi->setDi($di);
+
+ $result = $adminApi->batch_sendmail();
+ expect($result)->toBeNull();
+});
+
+test('template send', function (): void {
+ $adminApi = new Box\Mod\Email\Api\Admin();
+ $emailService = Mockery::mock(Box\Mod\Email\Service::class)->makePartial();
+ $emailService
+ ->shouldReceive('sendTemplate')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+ $adminApi->setDi($di);
+
+ $adminApi->setService($emailService);
+
+ $data = [
+ 'code' => 'mod_email_test',
+ 'to' => 'example@example.com',
+ 'default_subject' => 'SUBJECT',
+ 'default_template' => 'TEMPLATE',
+ 'default_description' => 'DESCRIPTION',
+ ];
+
+ $result = $adminApi->template_send($data);
+ expect($result)->toBeTrue();
+});
+
+test('template render', function (): void {
+ $adminApi = Mockery::mock(Box\Mod\Email\Api\Admin::class)->makePartial();
+
+ $twigStub = $this->createStub(Twig\Environment::class);
+
+ $di = container();
+ $di['twig'] = $twigStub;
+
+ $systemService = Mockery::mock(Box\Mod\System\Service::class)->makePartial();
+ $systemService
+ ->shouldReceive('renderEmailTplString')
+ ->atLeast()->once()
+ ->andReturn('rendered');
+
+ $emailService = Mockery::mock(Box\Mod\Email\Service::class)->makePartial();
+ $emailService->shouldReceive('getTemplate')->atLeast()->once()->andReturn(new EmailTemplate('mod_email_test', 5));
+ $emailService->shouldReceive('templateToApiArray')->atLeast()->once()->andReturn(['vars' => [], 'content' => 'content']);
+
+ $di['mod_service'] = $di->protect(moduleService(['system' => $systemService]));
+
+ $adminApi->setDi($di);
+ $adminApi->setService($emailService);
+
+ $result = $adminApi->template_render(['id' => 5]);
+ expect('rendered')->toEqual($result);
+});
+
+test('batch delete', function (): void {
+ $activityMock = Mockery::mock(Box\Mod\Email\Api\Admin::class)->makePartial();
+ $activityMock->shouldReceive('email_delete')->atLeast()->once()->andReturn(true);
+
+ $di = container();
+ $activityMock->setDi($di);
+
+ $result = $activityMock->batch_delete(['ids' => [1, 2, 3]]);
+ expect($result)->toBeTrue();
+});
diff --git a/src/modules/Email/tests/Unit/Api/ClientTest.php b/src/modules/Email/tests/Unit/Api/ClientTest.php
new file mode 100644
index 000000000..f5464bf0f
--- /dev/null
+++ b/src/modules/Email/tests/Unit/Api/ClientTest.php
@@ -0,0 +1,211 @@
+ [
+ 'id' => 1,
+ ],
+ ];
+ $pager = Mockery::mock(FOSSBilling\Pagination::class)->makePartial();
+ $pager
+ ->shouldReceive('getPaginatedResultSet')
+ ->atLeast()->once()
+ ->andReturn($willReturn);
+
+ $di = container();
+ $di['pager'] = $pager;
+
+ $clientApi->setDi($di);
+ $emailService->setDi($di);
+
+ $service = $emailService;
+ $clientApi->setService($service);
+
+ $client = new Model_Client();
+ $client->loadBean(new Tests\Helpers\DummyBean());
+ $client->id = 1;
+ $clientApi->setIdentity($client);
+
+ $result = $clientApi->get_list([]);
+ expect($result)->toBeArray();
+
+ expect($result)->toHaveKey('list');
+ expect($result['list'])->toBeArray();
+});
+
+test('get', function (): void {
+ $clientApi = new Box\Mod\Email\Api\Client();
+
+ $model = new Model_ActivityClientEmail();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $service = Mockery::mock(Box\Mod\Email\Service::class)->makePartial();
+ $service
+ ->shouldReceive('findOneForClientById')
+ ->atLeast()->once()
+ ->andReturn($model);
+ $service
+ ->shouldReceive('toApiArray')
+ ->atLeast()->once()
+ ->andReturn([]);
+ $clientApi->setService($service);
+
+ $di = container();
+ $clientApi->setDi($di);
+
+ $client = new Model_Client();
+ $client->loadBean(new Tests\Helpers\DummyBean());
+ $client->id = 1;
+ $clientApi->setIdentity($client);
+
+ $result = $clientApi->get(['id' => 1]);
+ expect($result)->toBeArray();
+});
+
+test('get not found exception', function (): void {
+ $clientApi = new Box\Mod\Email\Api\Client();
+
+ $service = Mockery::mock(Box\Mod\Email\Service::class)->makePartial();
+ $service
+ ->shouldReceive('findOneForClientById')
+ ->atLeast()->once()
+ ->andReturn(false);
+
+ $client = new Model_Client();
+ $client->loadBean(new Tests\Helpers\DummyBean());
+ $client->id = 5;
+ $clientApi->setIdentity($client);
+
+ $di = container();
+ $clientApi->setDi($di);
+
+ $clientApi->setService($service);
+
+ $this->expectException(FOSSBilling\Exception::class);
+ $result = $clientApi->get(['id' => 1]);
+ expect($result)->toBeArray();
+});
+
+test('resend', function (): void {
+ $clientApi = new Box\Mod\Email\Api\Client();
+
+ $model = new Model_ActivityClientEmail();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $service = Mockery::mock(Box\Mod\Email\Service::class)->makePartial();
+ $service
+ ->shouldReceive('findOneForClientById')
+ ->atLeast()->once()
+ ->andReturn($model);
+ $service
+ ->shouldReceive('resend')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $client = new Model_Client();
+ $client->loadBean(new Tests\Helpers\DummyBean());
+ $client->id = 5;
+ $clientApi->setIdentity($client);
+
+ $di = container();
+ $clientApi->setDi($di);
+
+ $clientApi->setService($service);
+
+ $result = $clientApi->resend(['id' => 1]);
+ expect($result)->toBeTrue();
+});
+
+test('resend not found exception', function (): void {
+ $clientApi = new Box\Mod\Email\Api\Client();
+
+ $service = Mockery::mock(Box\Mod\Email\Service::class)->makePartial();
+ $service
+ ->shouldReceive('findOneForClientById')
+ ->atLeast()->once()
+ ->andReturn(false);
+
+ $client = new Model_Client();
+ $client->loadBean(new Tests\Helpers\DummyBean());
+ $client->id = 5;
+
+ $clientApi->setIdentity($client);
+
+ $di = container();
+ $clientApi->setDi($di);
+
+ $clientApi->setService($service);
+
+ $this->expectException(FOSSBilling\Exception::class);
+ $result = $clientApi->resend(['id' => 1]);
+ expect($result)->toBeArray();
+});
+
+test('delete', function (): void {
+ $clientApi = new Box\Mod\Email\Api\Client();
+
+ $di = container();
+
+ $model = new Model_ActivityClientEmail();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $service = Mockery::mock(Box\Mod\Email\Service::class)->makePartial();
+ $service
+ ->shouldReceive('findOneForClientById')
+ ->atLeast()->once()
+ ->andReturn($model);
+ $service
+ ->shouldReceive('rm')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $client = new Model_Client();
+ $client->loadBean(new Tests\Helpers\DummyBean());
+ $client->id = 5;
+ $clientApi->setIdentity($client);
+
+ $clientApi->setDi($di);
+
+ $clientApi->setService($service);
+
+ $result = $clientApi->delete(['id' => 1]);
+ expect($result)->toBeTrue();
+});
+
+test('delete not found exception', function (): void {
+ $clientApi = new Box\Mod\Email\Api\Client();
+
+ $service = Mockery::mock(Box\Mod\Email\Service::class)->makePartial();
+ $service
+ ->shouldReceive('findOneForClientById')
+ ->atLeast()->once()
+ ->andReturn(false);
+
+ $client = new Model_Client();
+ $client->loadBean(new Tests\Helpers\DummyBean());
+ $client->id = 5;
+
+ $clientApi->setIdentity($client);
+
+ $di = container();
+ $clientApi->setDi($di);
+
+ $clientApi->setService($service);
+
+ $this->expectException(FOSSBilling\Exception::class);
+ $result = $clientApi->delete(['id' => 1]);
+ expect($result)->toBeArray();
+});
diff --git a/src/modules/Email/tests/Unit/Controller/AdminTest.php b/src/modules/Email/tests/Unit/Controller/AdminTest.php
new file mode 100644
index 000000000..aa50f3aa6
--- /dev/null
+++ b/src/modules/Email/tests/Unit/Controller/AdminTest.php
@@ -0,0 +1,51 @@
+setDi($di);
+ $result = $controller->getDi();
+ expect($result)->toEqual($di);
+});
+
+test('register method registers email routes', function (): void {
+ $boxAppMock = Mockery::mock('\Box_App');
+ $boxAppMock->shouldReceive('get')
+ ->times(5);
+
+ $controllerAdmin = new Admin();
+ $controllerAdmin->register($boxAppMock);
+});
+
+test('getHistory renders email history template', function (): void {
+ $boxAppMock = Mockery::mock('\Box_App');
+ $boxAppMock->shouldReceive('render')
+ ->atLeast()->once()
+ ->with('mod_email_history');
+
+ $controllerAdmin = new Admin();
+ $di = container();
+ $di['is_admin_logged'] = true;
+
+ $controllerAdmin->setDi($di);
+
+ $controllerAdmin->get_history($boxAppMock);
+});
diff --git a/src/modules/Email/tests/Unit/ServiceTest.php b/src/modules/Email/tests/Unit/ServiceTest.php
new file mode 100644
index 000000000..590140a1c
--- /dev/null
+++ b/src/modules/Email/tests/Unit/ServiceTest.php
@@ -0,0 +1,924 @@
+setCategory($data['category']);
+ }
+
+ if (array_key_exists('enabled', $data)) {
+ $template->setEnabled((bool) $data['enabled']);
+ }
+
+ if (array_key_exists('subject', $data)) {
+ $template->setSubject($data['subject']);
+ }
+
+ if (array_key_exists('content', $data)) {
+ $template->setContent($data['content']);
+ }
+
+ if (array_key_exists('description', $data)) {
+ $template->setDescription($data['description']);
+ }
+
+ if (array_key_exists('vars', $data)) {
+ $template->setVars($data['vars']);
+ }
+
+ if (array_key_exists('is_custom', $data)) {
+ $template->setIsCustom((bool) $data['is_custom']);
+ }
+
+ if (array_key_exists('is_overridden', $data)) {
+ $template->setIsOverridden((bool) $data['is_overridden']);
+ }
+
+ return $template;
+}
+
+test('di returns dependency injection container', function (): void {
+ $service = new Box\Mod\Email\Service();
+
+ $di = container();
+
+ $service->setDi($di);
+
+ $result = $service->getDi();
+ expect($result)->toBe($di);
+});
+
+dataset('getSearchQueryProvider', fn(): array => [
+ [
+ [],
+ 'SELECT * FROM activity_client_email ORDER BY id DESC',
+ [],
+ ],
+ [
+ [
+ 'search' => 'search_query',
+ ],
+ 'SELECT * FROM activity_client_email WHERE (sender LIKE :sender OR recipients LIKE :recipient OR subject LIKE :subject OR content_text LIKE :content_text OR content_html LIKE :content_html) ORDER BY id DESC',
+ [
+ ':sender' => '%search_query%',
+ ':recipient' => '%search_query%',
+ ':subject' => '%search_query%',
+ ':content_text' => '%search_query%',
+ ':content_html' => '%search_query%',
+ ],
+ ],
+ [
+ [
+ 'client_id' => 5,
+ ],
+ 'SELECT * FROM activity_client_email WHERE client_id = :client_id ORDER BY id DESC',
+ [
+ ':client_id' => 5,
+ ],
+ ],
+ [
+ [
+ 'search' => 'search_query',
+ 'client_id' => 5,
+ ],
+ 'SELECT * FROM activity_client_email WHERE (sender LIKE :sender OR recipients LIKE :recipient OR subject LIKE :subject OR content_text LIKE :content_text OR content_html LIKE :content_html) AND client_id = :client_id ORDER BY id DESC',
+ [
+ ':sender' => '%search_query%',
+ ':recipient' => '%search_query%',
+ ':subject' => '%search_query%',
+ ':content_text' => '%search_query%',
+ ':content_html' => '%search_query%',
+ ':client_id' => 5,
+ ],
+ ],
+]);
+
+test('getSearchQuery returns query and bindings', function (array $data, string $query, array $bindings): void {
+ $service = new Box\Mod\Email\Service();
+ $di = container();
+
+ $service->setDi($di);
+ $result = $service->getSearchQuery($data);
+
+ expect($result[0])->toBeString();
+ expect($result[1])->toBeArray();
+
+ expect($result[0])->toBe($query);
+ expect($result[1])->toBe($bindings);
+})->with('getSearchQueryProvider');
+
+test('findOneForClientById returns email for client', function (): void {
+ $service = new Box\Mod\Email\Service();
+ $di = container();
+ $id = 5;
+ $client_id = 1;
+
+ $activityEmail = new Model_ActivityClientEmail();
+ $activityEmail->loadBean(new Tests\Helpers\DummyBean());
+ $activityEmail->client_id = $client_id;
+ $activityEmail->id = $id;
+
+ $db = Mockery::mock('Box_Database');
+ $db->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn($activityEmail);
+
+ $di['db'] = $db;
+ $service->setDi($di);
+
+ $client = new Model_Client();
+ $client->loadBean(new Tests\Helpers\DummyBean());
+ $client->id = $client_id;
+
+ $result = $service->findOneForClientById($client, $id);
+
+ expect($result)->toBeInstanceOf('Model_ActivityClientEmail');
+ expect($result->id)->not->toBeNull();
+ expect($result->id)->toBe($activityEmail->id);
+ expect($result->client_id)->toBe($activityEmail->client_id);
+});
+
+test('rmByClient removes emails for client', function (): void {
+ $service = new Box\Mod\Email\Service();
+ $di = container();
+
+ $model = new Model_ActivityClientEmail();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $db = Mockery::mock('Box_Database');
+ $db->shouldReceive('find')
+ ->atLeast()->once()
+ ->andReturn([$model]);
+
+ $db->shouldReceive('trash')
+ ->atLeast()->once()
+ ->andReturn(null);
+
+ $di['db'] = $db;
+ $service->setDi($di);
+
+ $client = new Model_Client();
+ $client->loadBean(new Tests\Helpers\DummyBean());
+ $client->id = 1;
+
+ $result = $service->rmByClient($client);
+ expect($result)->toBeTrue();
+});
+
+test('rm removes email', function (): void {
+ $service = new Box\Mod\Email\Service();
+ $di = container();
+
+ $db = Mockery::mock('Box_Database');
+ $db->shouldReceive('trash')
+ ->atLeast()->once()
+ ->andReturn(null);
+
+ $di['db'] = $db;
+ $service->setDi($di);
+
+ $email = new Model_ActivityClientEmail();
+ $email->loadBean(new Tests\Helpers\DummyBean());
+ $email->id = 1;
+
+ $result = $service->rm($email);
+ expect($result)->toBeTrue();
+});
+
+test('toApiArray returns API array for email', function (): void {
+ $service = new Box\Mod\Email\Service();
+
+ $id = 10;
+ $client_id = 5;
+ $sender = 'sender@example.com';
+ $recipients = 'recipient@example.com';
+ $subject = 'Subject';
+ $content_html = 'HTML';
+ $content_text = 'TEXT';
+ $created = date('Y-m-d H:i:s', time() - 86400);
+ $updated = date('Y-m-d H:i:s');
+
+ $model = new Model_ActivityClientEmail();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $model->id = $id;
+ $model->client_id = $client_id;
+ $model->sender = $sender;
+ $model->recipients = $recipients;
+ $model->subject = $subject;
+ $model->content_html = $content_html;
+ $model->content_text = $content_text;
+ $model->created_at = $created;
+ $model->updated_at = $updated;
+
+ $expected = [
+ 'id' => $id,
+ 'client_id' => $client_id,
+ 'sender' => $sender,
+ 'recipients' => $recipients,
+ 'subject' => $subject,
+ 'content_html' => $content_html,
+ 'content_text' => $content_text,
+ 'created_at' => $created,
+ 'updated_at' => $updated,
+ ];
+
+ $result = $service->toApiArray($model);
+ expect($result)->toBeArray();
+ expect($result)->toBe($expected);
+});
+
+test('setVars encrypts and sets variables', function (): void {
+ $service = new Box\Mod\Email\Service();
+
+ $di = container();
+ $cryptMock = Mockery::mock('\Box_Crypt');
+ $cryptMock->shouldReceive('encrypt')
+ ->atLeast()->once()
+ ->andReturn('encrypted-vars');
+
+ $em = Mockery::mock(Doctrine\ORM\EntityManagerInterface::class);
+ $em->shouldReceive('flush')->atLeast()->once();
+
+ $di['em'] = $em;
+ $di['crypt'] = $cryptMock;
+ $service->setDi($di);
+
+ $t = emailTemplate();
+ $vars = [
+ 'param1' => 'value1',
+ ];
+
+ $result = $service->setVars($t, $vars);
+ expect($result)->toBeTrue();
+});
+
+test('getVars decrypts and returns variables', function (): void {
+ $service = new Box\Mod\Email\Service();
+
+ $di = container();
+ $cryptMock = Mockery::mock('\Box_Crypt');
+ $cryptMock->shouldReceive('decrypt')
+ ->atLeast()->once()
+ ->andReturn('{"param1":"value1"}');
+
+ $expected = ['param1' => 'value1'];
+
+ $di['crypt'] = $cryptMock;
+ $service->setDi($di);
+
+ $t = emailTemplate(data: ['vars' => 'haNUZYeNjo1oXhH6OkoKuHGPxakyKY10qR3O/DSy9Og=']);
+
+ $result = $service->getVars($t);
+ expect($result)->toBeArray();
+ expect($result)->toBe($expected);
+});
+
+test('sendTemplate returns false when template does not exist', function (): void {
+ $service = new Box\Mod\Email\Service();
+ $di = container();
+
+ $data = [
+ 'code' => 'mod_email_test_not_existing',
+ 'to' => 'example@example.com',
+ 'default_subject' => 'SUBJECT',
+ 'default_description' => 'DESCRIPTION',
+ ];
+
+ $emailTemplate = emailTemplate();
+
+ $db = Mockery::mock('Box_Database');
+ $db->shouldReceive('findOne')
+ ->byDefault()
+ ->andReturn(null);
+ $db->shouldReceive('dispense')
+ ->byDefault()
+ ->andReturn($emailTemplate);
+ $db->shouldReceive('store')
+ ->byDefault()
+ ->andReturn(1);
+
+ $cryptMock = Mockery::mock('\Box_Crypt');
+ $cryptMock->shouldReceive('encrypt')
+ ->atLeast()->once();
+
+ $di['db'] = $db;
+ $di['crypt'] = $cryptMock;
+ $di['api_admin'] = function () use ($di) {
+ $api = new Api_Handler(new Model_Admin());
+ $api->setDi($di);
+
+ return $api;
+ };
+
+ $validatorMock = Mockery::mock(FOSSBilling\Validate::class);
+ $validatorMock->shouldReceive('checkRequiredParamsForArray')->byDefault();
+ $di['validator'] = $validatorMock;
+ $service->setDi($di);
+
+ $result = $service->sendTemplate($data);
+
+ expect($result)->toBeFalse();
+});
+
+test('sendTemplate sends email when template exists', function (): void {
+ $data = [
+ 'code' => 'mod_email_test',
+ 'to' => 'example@example.com',
+ 'default_subject' => 'SUBJECT',
+ 'default_template' => 'TEMPLATE',
+ 'default_description' => 'DESCRIPTION',
+ ];
+ $service = new Box\Mod\Email\Service();
+
+ $di = container();
+
+ $emailTemplate = emailTemplate(data: ['enabled' => true]);
+
+ $queueModel = new Model_ModEmailQueue();
+ $queueModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $db = Mockery::mock('Box_Database');
+ $db->shouldReceive('findOne')
+ ->byDefault()
+ ->andReturn($emailTemplate);
+ $db->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn(1);
+ $db->shouldReceive('dispense')
+ ->atLeast()->once()
+ ->andReturn($queueModel);
+
+ $systemService = Mockery::mock(Box\Mod\System\Service::class);
+ $systemService->shouldReceive('getParamValue')
+ ->atLeast()->once()
+ ->andReturn('value');
+ $systemService->shouldReceive('renderEmailTplString')
+ ->atLeast()->once()
+ ->andReturn('rendered content');
+
+ $twigStub = Mockery::mock(Twig\Environment::class);
+
+ $di['api_admin'] = function () use ($di) {
+ $api = new Api_Handler(new Model_Admin());
+ $api->setDi($di);
+
+ return $api;
+ };
+ $validatorMock = Mockery::mock(FOSSBilling\Validate::class);
+ $validatorMock->shouldReceive('checkRequiredParamsForArray')->byDefault();
+ $di['validator'] = $validatorMock;
+
+ $cryptMock = Mockery::mock('\Box_Crypt');
+ $cryptMock->shouldReceive('encrypt')
+ ->atLeast()->once();
+
+ $modMock = Mockery::mock(FOSSBilling\Module::class)->makePartial();
+ $modMock->shouldReceive('getConfig')
+ ->atLeast()->once()
+ ->andReturn([
+ 'from_name' => 'Test',
+ 'from_email' => 'test@test.com',
+ ]);
+
+ $di['db'] = $db;
+ $di['crypt'] = $cryptMock;
+ $di['twig'] = $twigStub;
+ $di['mod'] = $di->protect(fn () => $modMock);
+ $di['mod_service'] = $di->protect(moduleService(['system' => $systemService]));
+ $di['tools'] = new FOSSBilling\Tools();
+
+ $service->setDi($di);
+
+ $result = $service->sendTemplate($data);
+
+ expect($result)->toBeTrue();
+});
+
+dataset('sendTemplateExistsStaffProvider', fn(): array => [
+ [
+ [
+ 'code' => 'mod_email_test',
+ 'to' => 'example@example.com',
+ 'default_subject' => 'SUBJECT',
+ 'default_template' => 'TEMPLATE',
+ 'default_description' => 'DESCRIPTION',
+ 'to_staff' => 1,
+ ],
+ 'never',
+ 'atLeastOnce',
+ ],
+ [
+ [
+ 'code' => 'mod_email_test',
+ 'to' => 'example@example.com',
+ 'default_subject' => 'SUBJECT',
+ 'default_template' => 'TEMPLATE',
+ 'default_description' => 'DESCRIPTION',
+ 'to_client' => 1,
+ ],
+ 'atLeastOnce',
+ 'never',
+ ],
+]);
+
+test('sendTemplate handles to_staff and to_client options', function (array $data, string $clientGetExpects, string $staffGetListExpects): void {
+ $service = new Box\Mod\Email\Service();
+
+ $di = container();
+
+ $emailTemplate = emailTemplate(data: ['enabled' => true]);
+
+ $queueModel = new Model_ModEmailQueue();
+ $queueModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $db = Mockery::mock('Box_Database');
+ $db->shouldReceive('findOne')
+ ->byDefault()
+ ->andReturn(null);
+ $db->shouldReceive('dispense')
+ ->atLeast()->once()
+ ->andReturnUsing(fn($type) => $type === 'EmailTemplate' ? $emailTemplate : $queueModel);
+ $db->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn(1);
+
+ $system = Mockery::mock(Box\Mod\System\Service::class);
+ $system->shouldReceive('getParamValue')
+ ->atLeast()->once()
+ ->andReturn('value');
+
+ $system->shouldReceive('renderEmailTplString')
+ ->atLeast()->once()
+ ->andReturn('value');
+
+ $staffServiceMock = Mockery::mock(Box\Mod\Staff\Service::class);
+ if ($staffGetListExpects === 'atLeastOnce') {
+ $staffServiceMock->shouldReceive('getList')
+ ->atLeast()->once()
+ ->andReturn([
+ 'list' => [
+ 0 => [
+ 'id' => 1,
+ 'email' => 'staff@fossbilling.org',
+ 'name' => 'George',
+ 'signature' => '',
+ ],
+ ],
+ ]);
+ } else {
+ $staffServiceMock->shouldReceive('getList')->never();
+ }
+
+ $clientServiceMock = Mockery::mock(Box\Mod\Client\Service::class);
+
+ $clientModel = new Model_Client();
+ $clientModel->loadBean(new Tests\Helpers\DummyBean());
+ if ($clientGetExpects === 'atLeastOnce') {
+ $clientServiceMock->shouldReceive('get')
+ ->atLeast()->once()
+ ->andReturn($clientModel);
+ $clientApiArray = [
+ 'id' => 1,
+ 'email' => 'staff@fossbilling.org',
+ 'first_name' => 'John',
+ 'last_name' => 'Smith',
+ ];
+ $clientServiceMock->shouldReceive('toApiArray')
+ ->atLeast()->once()
+ ->andReturn($clientApiArray);
+ } else {
+ $clientServiceMock->shouldReceive('get')->never();
+ $clientServiceMock->shouldReceive('toApiArray')->never();
+ }
+
+ $twigStub = Mockery::mock(Twig\Environment::class);
+
+ $cryptMock = Mockery::mock('\Box_Crypt');
+ $cryptMock->shouldReceive('encrypt')
+ ->atLeast()->once();
+
+ $di['api_admin'] = function () use ($di) {
+ $api = new Api_Handler(new Model_Admin());
+ $api->setDi($di);
+
+ return $api;
+ };
+
+ $validatorMock = Mockery::mock(FOSSBilling\Validate::class);
+ $validatorMock->shouldReceive('checkRequiredParamsForArray')->byDefault();
+ $di['validator'] = $validatorMock;
+
+ $modMock = Mockery::mock(FOSSBilling\Module::class)->makePartial();
+ $modMock->shouldReceive('getConfig')
+ ->atLeast()->once()
+ ->andReturn([
+ 'from_name' => 'Test',
+ 'from_email' => 'test@test.com',
+ ]);
+
+ $di['mod'] = $di->protect(fn () => $modMock);
+ $di['db'] = $db;
+ $di['twig'] = $twigStub;
+ $di['crypt'] = $cryptMock;
+ $di['mod_service'] = $di->protect(moduleService([
+ 'staff' => $staffServiceMock,
+ 'system' => $system,
+ 'client' => $clientServiceMock,
+ ]));
+ $di['tools'] = new FOSSBilling\Tools();
+
+ $service->setDi($di);
+
+ $result = $service->sendTemplate($data);
+
+ expect($result)->toBeTrue();
+})->with('sendTemplateExistsStaffProvider');
+
+test('resend resends email', function (): void {
+ $service = new Box\Mod\Email\Service();
+
+ $di = container();
+
+ $emailSettings = [
+ 'mailer' => 'sendmail',
+ 'smtp_authentication' => 'login',
+ 'smtp_host' => null,
+ 'smtp_security' => null,
+ 'smtp_port' => null,
+ 'smtp_username' => null,
+ 'smtp_password' => null,
+ ];
+
+ $isExtensionActiveReturn = false;
+ $extension = Mockery::mock(Box\Mod\Extension\Service::class);
+ $extension->shouldReceive('isExtensionActive')
+ ->atLeast()->once()
+ ->andReturn($isExtensionActiveReturn);
+
+ $config = [];
+ $di['mod_config'] = $di->protect(fn ($modName): array => $config);
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $extension);
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $service->setDi($di);
+
+ $model = new Model_ActivityClientEmail();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $model->client_id = 1;
+ $model->sender = 'sender@exemple.com';
+ $model->recipients = 'recipient@example.com';
+ $model->subject = 'Email Title';
+ $model->content_html = 'Content';
+ $model->content_text = 'Content';
+
+ $result = $service->resend($model);
+
+ expect($result)->toBeTrue();
+});
+
+test('templateToApiArray returns API array for template', function (): void {
+ $id = 1;
+ $action_code = 'code';
+ $category = 'category';
+ $enabled = 1;
+ $subject = 'Subject';
+ $description = 'Description';
+ $content = 'content';
+
+ $model = emailTemplate($action_code, $id, [
+ 'category' => $category,
+ 'enabled' => $enabled,
+ 'subject' => $subject,
+ 'description' => $description,
+ 'content' => $content,
+ ]);
+
+ $expected = [
+ 'id' => $id,
+ 'action_code' => $action_code,
+ 'category' => $category,
+ 'enabled' => true,
+ 'subject' => $subject,
+ 'description' => $description,
+ 'is_custom' => false,
+ 'has_default' => false,
+ 'is_overridden' => false,
+ ];
+
+ $service = new Box\Mod\Email\Service();
+ $result = $service->templateToApiArray($model);
+
+ expect($result)->toBeArray();
+ expect($result)->toBe($expected);
+});
+
+test('templateToApiArray returns deep array with vars', function (): void {
+ $id = 1;
+ $action_code = 'code';
+ $category = 'category';
+ $enabled = 1;
+ $subject = 'Subject';
+ $description = 'Description';
+ $content = 'content';
+
+ $model = emailTemplate($action_code, $id, [
+ 'category' => $category,
+ 'enabled' => $enabled,
+ 'subject' => $subject,
+ 'description' => $description,
+ 'content' => $content,
+ ]);
+
+ $expected = [
+ 'id' => $id,
+ 'action_code' => $action_code,
+ 'category' => $category,
+ 'enabled' => true,
+ 'subject' => $subject,
+ 'description' => $description,
+ 'is_custom' => false,
+ 'has_default' => false,
+ 'is_overridden' => false,
+ 'content' => $content,
+ 'vars' => [
+ 'param1' => 'value1',
+ ],
+ 'subject_override' => $subject,
+ 'content_override' => $content,
+ ];
+
+ $serviceMock = Mockery::mock(Box\Mod\Email\Service::class)->makePartial();
+ $serviceMock->shouldReceive('getVars')
+ ->atLeast()->once()
+ ->andReturn(['param1' => 'value1']);
+
+ $result = $serviceMock->templateToApiArray($model, true);
+
+ expect($result)->toBeArray();
+ expect($result)->toHaveKey('vars');
+ expect($result['vars'])->toBeArray();
+
+ expect($result)->toBe($expected);
+});
+
+dataset('template_updateProvider', fn(): array => [
+ [
+ [
+ 'id' => 5,
+ 'enabled' => 1,
+ 'category' => 'Category',
+ 'subject' => null,
+ 'content' => null,
+ ],
+ 'never',
+ ],
+ [
+ [
+ 'id' => 5,
+ 'enabled' => 1,
+ 'category' => 'Category',
+ 'subject' => 'Subject',
+ 'content' => 'Content',
+ ],
+ 'atLeastOnce',
+ ],
+]);
+
+test('updateTemplate updates template', function (array $data, string $templateRenderExpects): void {
+ $id = 1;
+ $model = emailTemplate(id: $id);
+
+ $emailService = new Box\Mod\Email\Service();
+
+ $db = Mockery::mock('Box_Database');
+ $db->shouldReceive('store')
+ ->byDefault();
+
+ $loggerStub = new Tests\Helpers\TestLogger();
+
+ $cryptMock = Mockery::mock('\Box_Crypt');
+ $cryptMock->shouldReceive('decrypt')
+ ->atLeast()->once();
+ $configMock = ['salt' => md5(random_bytes(13))];
+
+ $twigStub = Mockery::mock(Twig\Environment::class);
+
+ $di = container();
+ $di['db'] = $db;
+ $di['logger'] = $loggerStub;
+ $di['crypt'] = $cryptMock;
+ $di['config'] = $configMock;
+ $di['twig'] = $twigStub;
+
+ $systemServiceMock = Mockery::mock(Box\Mod\System\Service::class);
+ if ($templateRenderExpects === 'atLeastOnce') {
+ $systemServiceMock->shouldReceive('renderEmailTplString')
+ ->atLeast()->once();
+ } else {
+ $systemServiceMock->shouldReceive('renderEmailTplString')->never();
+ }
+
+ $di['mod_service'] = $di->protect(moduleService(['system' => $systemServiceMock]));
+
+ $emailService->setDi($di);
+
+ $templateModel = emailTemplate();
+
+ $result = $emailService->updateTemplate($templateModel, $data['enabled'], $data['category'], $data['subject'], @$data['content']);
+ expect($result)->toBeTrue();
+})->with('template_updateProvider');
+
+test('getEmailById returns email by ID', function (): void {
+ $service = new Box\Mod\Email\Service();
+
+ $id = 1;
+ $model = new Model_ActivityClientEmail();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $model->id = $id;
+
+ $db = Mockery::mock('Box_Database');
+ $db->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $di = container();
+ $di['db'] = $db;
+ $service->setDi($di);
+
+ $result = $service->getEmailById($id);
+
+ expect($result->id)->toBe($id);
+});
+
+test('getEmailById throws exception when email not found', function (): void {
+ $service = new Box\Mod\Email\Service();
+
+ $db = Mockery::mock('Box_Database');
+ $db->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn(false);
+
+ $di = container();
+ $di['db'] = $db;
+ $service->setDi($di);
+
+ expect(fn () => $service->getEmailById(5))
+ ->toThrow(FOSSBilling\Exception::class);
+});
+
+test('templateCreate creates new template', function (): void {
+ $service = new Box\Mod\Email\Service();
+
+ $em = Mockery::mock(Doctrine\ORM\EntityManagerInterface::class);
+ $em->shouldReceive('persist')->atLeast()->once();
+ $em->shouldReceive('flush')->atLeast()->once();
+
+ $di = container();
+ $di['em'] = $em;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $service->setDi($di);
+
+ $data = [
+ 'action_code' => 'Action_code',
+ 'subject' => 'Subject',
+ 'content' => 'Content',
+ 'category' => 'category',
+ ];
+
+ $result = $service->templateCreate($data['action_code'], $data['subject'], $data['content'], 1, $data['category']);
+
+ expect($result)->toBeInstanceOf(Box\Mod\Email\Entity\EmailTemplate::class);
+ expect($result->getActionCode())->toBe($data['action_code']);
+});
+
+test('templateBatchDisable disables all templates', function (): void {
+ $service = new Box\Mod\Email\Service();
+
+ $di = container();
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $service->setDi($di);
+
+ $result = $service->templateBatchDisable();
+
+ expect($result)->toBeTrue();
+});
+
+test('templateBatchEnable enables all templates', function (): void {
+ $service = new Box\Mod\Email\Service();
+
+ $di = container();
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $service->setDi($di);
+
+ $result = $service->templateBatchEnable();
+
+ expect($result)->toBeTrue();
+});
+
+test('batchSend processes email queue', function (): void {
+ $service = new Box\Mod\Email\Service();
+
+ $queueModel = new Tests\Helpers\DummyBean();
+ $queueModel->priority = 10;
+ $queueModel->tries = 10;
+ $queueModel->subject = 'subject';
+ $queueModel->client_id = 1;
+ $queueModel->sender = 'sender@example.com';
+ $queueModel->recipient = 'receiver@example.com';
+ $queueModel->content = 'content';
+ $queueModel->from_name = 'From Name';
+ $queueModel->to_name = 'To Name';
+
+ $db = Mockery::mock('Box_Database');
+ $db->shouldReceive('findAll')
+ ->once()
+ ->andReturn([$queueModel]);
+ $db->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $modMock = Mockery::mock(FOSSBilling\Module::class);
+ $modMock->shouldReceive('getConfig')
+ ->atLeast()->once()
+ ->andReturn([
+ 'log_enabled' => 1,
+ 'cancel_after' => 1,
+ ]);
+
+ $extension = Mockery::mock(Box\Mod\Extension\Service::class);
+ $isExtensionActiveReturn = false;
+ $extension->shouldReceive('isExtensionActive')
+ ->atLeast()->once()
+ ->andReturn($isExtensionActiveReturn);
+
+ $di = container();
+ $di['db'] = $db;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $di['mod_service'] = $di->protect(function ($name) use ($extension) {
+ if ($name == 'extension') {
+ return $extension;
+ }
+ });
+ $di['mod'] = $di->protect(fn () => $modMock);
+
+ $service->setDi($di);
+
+ $result = $service->batchSend();
+
+ expect($result)->toBeNull();
+});
+
+test('sendMail queues email for sending', function (): void {
+ $dbMock = Mockery::mock('\Box_Database');
+
+ $queueEmail = new Model_ModEmailQueue();
+ $queueEmail->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock->shouldReceive('dispense')
+ ->atLeast()->once()
+ ->with('ModEmailQueue')
+ ->andReturn($queueEmail);
+
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $modMock = Mockery::mock('\stdClass');
+ $extension = Mockery::mock(Box\Mod\Extension\Service::class);
+ $di['mod'] = $di->protect(fn (): Mockery\MockInterface => $modMock);
+ $di['mod_service'] = $di->protect(function ($name) use ($extension) {
+ if ($name == 'system') {
+ } elseif ($name == 'extension') {
+ return $extension;
+ }
+ });
+
+ $service = new Box\Mod\Email\Service();
+ $service->setDi($di);
+
+ $to = 'receiver@example.com';
+ $from = 'sender@example.com';
+ $subject = 'Important message';
+ $content = 'content';
+ $result = $service->sendMail($to, $from, $subject, $content);
+ expect($result)->toBeTrue();
+});
diff --git a/src/modules/Extension/Api/Admin.php b/src/modules/Extension/Api/Admin.php
index 2768cf662..63bf9a9cf 100644
--- a/src/modules/Extension/Api/Admin.php
+++ b/src/modules/Extension/Api/Admin.php
@@ -30,7 +30,7 @@ class Admin extends \Api_Abstract
*/
public function get_list($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('extension', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('extension', 'view');
$service = $this->getService();
@@ -45,14 +45,14 @@ class Admin extends \Api_Abstract
*/
public function get_latest($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('extension', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('extension', 'view');
$type = $data['type'] ?? null;
try {
- $list = $this->di['extension_manager']->getExtensionList($type);
+ $list = $this->getDi()['extension_manager']->getExtensionList($type);
} catch (\Exception $e) {
- $this->di['logger']->warning(sprintf('Failed to fetch extension list for type "%s": %s', $type ?? 'all', $e->getMessage()));
+ $this->getDi()['logger']->warning(sprintf('Failed to fetch extension list for type "%s": %s', $type ?? 'all', $e->getMessage()));
$list = [];
}
@@ -66,9 +66,9 @@ class Admin extends \Api_Abstract
#[RequiredParams(['extension_id' => 'Extension ID was not passed'])]
public function get_extension_readme($data): string
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('extension', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('extension', 'view');
- $extensionInfo = $this->di['extension_manager']->getExtension($data['extension_id']);
+ $extensionInfo = $this->getDi()['extension_manager']->getExtension($data['extension_id']);
$markdown = new \FOSSBilling\Twig\Markdown\FOSSBillingMarkdown($this->di);
return $markdown->convert($extensionInfo['readme']);
@@ -95,7 +95,7 @@ class Admin extends \Api_Abstract
*/
public function languages(array $data): array
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('extension', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('extension', 'view');
$data['disabled'] = Tools::normalizeBoolean($data['disabled'] ?? false);
$data['details'] = Tools::normalizeBoolean($data['details'] ?? true, true);
@@ -113,7 +113,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['locale_id' => 'Locale ID was not passed'])]
public function toggle_language(array $data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('extension', 'manage_extensions');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('extension', 'manage_extensions');
return \FOSSBilling\i18n::toggleLocale($data['locale_id']);
}
@@ -126,7 +126,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['locale_id' => 'Locale ID was not passed'])]
public function locale_completion(array $data): int
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('extension', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('extension', 'view');
return \FOSSBilling\i18n::getLocaleCompletionPercent($data['locale_id']);
}
@@ -140,14 +140,14 @@ class Admin extends \Api_Abstract
*/
public function update($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('extension', 'manage_extensions');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('extension', 'manage_extensions');
$ext = $this->_getExtension($data);
$service = $this->getService();
- $this->di['events_manager']->fire(['event' => 'onBeforeAdminUpdateExtension', 'params' => $ext]);
+ $this->getDi()['events_manager']->fire(['event' => 'onBeforeAdminUpdateExtension', 'params' => $ext]);
$ext2 = $service->update($ext);
- $this->di['events_manager']->fire(['event' => 'onAfterAdminUpdateExtension', 'params' => $ext2]);
+ $this->getDi()['events_manager']->fire(['event' => 'onAfterAdminUpdateExtension', 'params' => $ext2]);
return $ext2;
}
@@ -162,7 +162,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Extension ID was not passed', 'type' => 'Extension type was not passed'])]
public function activate($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('extension', 'manage_extensions');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('extension', 'manage_extensions');
$service = $this->getService();
@@ -178,18 +178,18 @@ class Admin extends \Api_Abstract
*/
public function deactivate($data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('extension', 'manage_extensions');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('extension', 'manage_extensions');
$ext = $this->_getExtension($data);
- $this->di['events_manager']->fire(['event' => 'onBeforeAdminDeactivateExtension', 'params' => ['id' => $ext->id]]);
+ $this->getDi()['events_manager']->fire(['event' => 'onBeforeAdminDeactivateExtension', 'params' => ['id' => $ext->id]]);
$service = $this->getService();
$service->deactivate($ext);
- $this->di['events_manager']->fire(['event' => 'onAfterAdminDeactivateExtension', 'params' => ['id' => $data['id'], 'type' => $data['type']]]);
+ $this->getDi()['events_manager']->fire(['event' => 'onAfterAdminDeactivateExtension', 'params' => ['id' => $data['id'], 'type' => $data['type']]]);
- $this->di['logger']->info('Deactivated extension "%s"', $data['type'] . ' ' . $data['id']);
+ $this->getDi()['logger']->info('Deactivated extension "%s"', $data['type'] . ' ' . $data['id']);
return true;
}
@@ -199,14 +199,14 @@ class Admin extends \Api_Abstract
*/
public function uninstall($data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('extension', 'uninstall_extensions');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('extension', 'uninstall_extensions');
$ext = $this->_getExtension($data);
- $this->di['events_manager']->fire(['event' => 'onBeforeAdminUninstallExtension', 'params' => ['id' => $ext->id]]);
+ $this->getDi()['events_manager']->fire(['event' => 'onBeforeAdminUninstallExtension', 'params' => ['id' => $ext->id]]);
$this->getService()->uninstall($data['type'], $data['id']);
- $this->di['events_manager']->fire(['event' => 'onAfterAdminUninstallExtension', 'params' => ['type' => $data['type'], 'id' => $data['id']]]);
+ $this->getDi()['events_manager']->fire(['event' => 'onAfterAdminUninstallExtension', 'params' => ['type' => $data['type'], 'id' => $data['id']]]);
return true;
}
@@ -219,14 +219,14 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Extension ID was not passed', 'type' => 'Extension type was not passed'])]
public function install($data): array
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('extension', 'manage_extensions');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('extension', 'manage_extensions');
- $this->di['events_manager']->fire(['event' => 'onBeforeAdminInstallExtension', 'params' => $data]);
+ $this->getDi()['events_manager']->fire(['event' => 'onBeforeAdminInstallExtension', 'params' => $data]);
$service = $this->getService();
$service->downloadAndExtract($data['type'], $data['id']);
- $this->di['events_manager']->fire(['event' => 'onAfterAdminInstallExtension', 'params' => $data]);
+ $this->getDi()['events_manager']->fire(['event' => 'onAfterAdminInstallExtension', 'params' => $data]);
return [
'success' => true,
diff --git a/src/modules/Extension/Entity/ExtensionMeta.php b/src/modules/Extension/Entity/ExtensionMeta.php
index fbf660f23..87ce20968 100644
--- a/src/modules/Extension/Entity/ExtensionMeta.php
+++ b/src/modules/Extension/Entity/ExtensionMeta.php
@@ -27,6 +27,11 @@ class ExtensionMeta implements ApiArrayInterface, TimestampInterface
#[ORM\Column(type: Types::INTEGER)]
private ?int $id = null;
+ public function __construct(?int $id = null)
+ {
+ $this->id = $id;
+ }
+
#[ORM\Column(name: 'client_id', type: Types::INTEGER, nullable: true)]
private ?int $clientId = null;
diff --git a/src/modules/Extension/tests/E2E/ApiAdminTest.php b/src/modules/Extension/tests/E2E/ApiAdminTest.php
new file mode 100644
index 000000000..4ce91b690
--- /dev/null
+++ b/src/modules/Extension/tests/E2E/ApiAdminTest.php
@@ -0,0 +1,69 @@
+ 'mod', 'id' => 'massmailer']);
+ expect($result->wasSuccessful())->toBeTrue($result);
+});
+
+test('can deactivate extension', function (): void {
+ $result = Tests\Helpers\ApiClient::request('admin/extension/deactivate', ['type' => 'mod', 'id' => 'massmailer']);
+ expect($result->wasSuccessful())->toBeTrue($result);
+});
+
+test('language management', function (): void {
+ $result = Tests\Helpers\ApiClient::request('admin/extension/languages');
+ expect($result->wasSuccessful())->toBeTrue($result);
+ $this->assertNotCount(0, $result->getResult());
+
+ $result = Tests\Helpers\ApiClient::request('admin/extension/languages', ['disabled' => true]);
+ expect($result->wasSuccessful())->toBeTrue($result);
+ expect($result->getResult())->toHaveCount(0);
+
+ $result = Tests\Helpers\ApiClient::request('admin/extension/toggle_language', ['locale_id' => 'en_US']);
+ expect($result->wasSuccessful())->toBeTrue($result);
+
+ $result = Tests\Helpers\ApiClient::request('admin/extension/languages', ['disabled' => true, 'details' => false]);
+ expect($result->wasSuccessful())->toBeTrue($result);
+ expect($result->getResult())->toContain('en_US');
+
+ $result = Tests\Helpers\ApiClient::request('admin/extension/languages');
+ expect($result->wasSuccessful())->toBeTrue($result);
+ expect($result->getResult())->not->toContain('en_US');
+
+ $result = Tests\Helpers\ApiClient::request('admin/extension/toggle_language', ['locale_id' => 'en_US']);
+ expect($result->wasSuccessful())->toBeTrue($result);
+});
+
+test('language completion', function (): void {
+ $locales = Tests\Helpers\ApiClient::request('admin/extension/languages', ['disabled' => true, 'details' => false])->getResult();
+ foreach ($locales as $locale) {
+ Tests\Helpers\ApiClient::request('admin/extension/toggle_language', ['locale_id' => $locale]);
+ }
+
+ expect(Tests\Helpers\ApiClient::request('admin/extension/languages', ['disabled' => true, 'details' => false])->getResult())->toBeEmpty();
+
+ $locales = Tests\Helpers\ApiClient::request('admin/extension/languages', ['details' => false])->getResult();
+ foreach ($locales as $locale) {
+ $completionResult = Tests\Helpers\ApiClient::request('admin/extension/locale_completion', ['locale_id' => $locale]);
+ if ($locale === 'en_US') {
+ expect($completionResult->getResult())->toEqual(100);
+ } else {
+ expect($completionResult->getResult())->toBeGreaterThanOrEqual(25);
+ }
+ }
+});
diff --git a/src/modules/Extension/tests/E2E/ApiGuestTest.php b/src/modules/Extension/tests/E2E/ApiGuestTest.php
new file mode 100644
index 000000000..14eefd31f
--- /dev/null
+++ b/src/modules/Extension/tests/E2E/ApiGuestTest.php
@@ -0,0 +1,49 @@
+wasSuccessful())->toBeTrue($result);
+ expect($result->getResult())->toBeArray();
+ expect($result->getResult())->toHaveKey('name');
+ expect($result->getResult())->toHaveKey('version');
+ expect($result->getResult()['author'])->toEqual('FOSSBilling');
+});
+
+test('settings', function (): void {
+ $result = Tests\Helpers\ApiClient::request('guest/extension/settings', ['ext' => 'index']);
+ expect($result->wasSuccessful())->toBeTrue($result);
+ expect($result->getResult())->toBeArray();
+});
+
+test('settings missing ext', function (): void {
+ $result = Tests\Helpers\ApiClient::request('guest/extension/settings', ['ext']);
+ expect($result->wasSuccessful())->toBeFalse($result);
+ expect($result->getErrorMessage())->toEqual('Parameter ext is missing');
+});
+
+test('extension is active', function (): void {
+ $result = Tests\Helpers\ApiClient::request('guest/extension/is_on', ['mod' => 'index']);
+ expect($result->wasSuccessful())->toBeTrue($result);
+ expect($result->getResult())->toBeTrue();
+});
+
+test('extension is not active', function (): void {
+ $result = Tests\Helpers\ApiClient::request('guest/extension/is_on', ['mod' => 'serviceapikey']);
+ expect($result->wasSuccessful())->toBeTrue($result);
+ expect($result->getResult())->toBeFalse();
+});
diff --git a/src/modules/Extension/tests/Unit/Api/AdminTest.php b/src/modules/Extension/tests/Unit/Api/AdminTest.php
new file mode 100644
index 000000000..635f0c3a1
--- /dev/null
+++ b/src/modules/Extension/tests/Unit/Api/AdminTest.php
@@ -0,0 +1,103 @@
+setDi($di);
+ $getDi = $api->getDi();
+ expect($getDi)->toBe($di);
+});
+
+test('activate activates an extension', function (): void {
+ $api = new Box\Mod\Extension\Api\Admin();
+ $serviceMock = Mockery::mock(Box\Mod\Extension\Service::class)->makePartial();
+ $serviceMock->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('activateExistingExtension')
+ ->atLeast()
+ ->once()
+ ->andReturn([]);
+
+ $api->setService($serviceMock);
+
+ $result = $api->activate([]);
+ expect($result)->toBeArray();
+});
+
+test('configGet gets extension config', function (): void {
+ $api = new Box\Mod\Extension\Api\Admin();
+ $serviceMock = Mockery::mock(Box\Mod\Extension\Service::class)->makePartial();
+ $serviceMock->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('getConfig')
+ ->atLeast()
+ ->once()
+ ->with('mod_example')
+ ->andReturn(['key' => 'value']);
+ $serviceMock->shouldReceive('hasManagePermission')
+ ->with('mod_example')
+ ->atLeast()
+ ->once()
+ ->andReturn(true);
+
+ $api->setService($serviceMock);
+
+ $result = $api->config_get(['ext' => 'mod_example']);
+ expect($result)->toBeArray();
+ expect($result)->toBe(['key' => 'value']);
+});
+
+test('configSave saves extension config', function (): void {
+ $api = new Box\Mod\Extension\Api\Admin();
+ $serviceMock = Mockery::mock(Box\Mod\Extension\Service::class)->makePartial();
+ $serviceMock->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('setConfig')
+ ->atLeast()
+ ->once()
+ ->andReturn(true);
+
+ $api->setService($serviceMock);
+
+ $result = $api->config_save([]);
+ expect($result)->toBeTrue();
+});
+
+test('getList returns extensions list', function (): void {
+ $api = new Box\Mod\Extension\Api\Admin();
+ $serviceMock = Mockery::mock(Box\Mod\Extension\Service::class)->makePartial();
+ $serviceMock->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('getExtensionsList')
+ ->atLeast()
+ ->once()
+ ->andReturn([]);
+
+ $api->setService($serviceMock);
+
+ $result = $api->get_list([]);
+ expect($result)->toBeArray();
+});
+
+test('getNavigation returns admin navigation', function (): void {
+ $api = new Box\Mod\Extension\Api\Admin();
+ $serviceMock = Mockery::mock(Box\Mod\Extension\Service::class)->makePartial();
+ $serviceMock->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('getAdminNavigation')
+ ->atLeast()
+ ->once()
+ ->andReturn([]);
+
+ $api->setService($serviceMock);
+
+ $result = $api->get_navigation([]);
+ expect($result)->toBeArray();
+});
diff --git a/src/modules/Extension/tests/Unit/ServiceTest.php b/src/modules/Extension/tests/Unit/ServiceTest.php
new file mode 100644
index 000000000..0bad1ac73
--- /dev/null
+++ b/src/modules/Extension/tests/Unit/ServiceTest.php
@@ -0,0 +1,876 @@
+setDi($di);
+ $getDi = $service->getDi();
+ expect($getDi)->toBe($di);
+});
+
+test('isCoreModule checks if module is core module', function (): void {
+ $service = new Box\Mod\Extension\Service();
+ $coreModules = ['extension', 'cron', 'staff'];
+ $modMock = Mockery::mock(FOSSBilling\Module::class);
+ $modMock->shouldReceive('getCoreModules')
+ ->atLeast()
+ ->once()
+ ->andReturn($coreModules);
+
+ $di = container();
+ $di['mod'] = $di->protect(fn ($name): Mockery\MockInterface => $modMock);
+
+ $service->setDi($di);
+
+ $result = $service->isCoreModule('extension');
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+});
+
+test('isExtensionActive returns false when module not found', function (): void {
+ $service = new Box\Mod\Extension\Service();
+ $coreModules = ['extension', 'cron', 'staff'];
+ $modMock = Mockery::mock(FOSSBilling\Module::class);
+ $modMock->shouldReceive('getCoreModules')
+ ->atLeast()
+ ->once()
+ ->andReturn($coreModules);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getCell')
+ ->atLeast()
+ ->once()
+ ->andReturn(null);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod'] = $di->protect(fn ($name): Mockery\MockInterface => $modMock);
+
+ $service->setDi($di);
+
+ $result = $service->isExtensionActive('mod', 'ModDoesNotExists');
+ expect($result)->toBeBool();
+ expect($result)->toBeFalse();
+});
+
+test('removeNotExistingModules removes non-existing modules', function (): void {
+ $service = new Box\Mod\Extension\Service();
+ $model = new Model_Extension();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $model->name = 'extensionName';
+
+ $modMock = Mockery::mock(FOSSBilling\Module::class);
+ $modMock->shouldReceive('getManifest')->andThrow(new Exception());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('find')
+ ->atLeast()
+ ->once()
+ ->andReturn([$model]);
+ $dbMock->shouldReceive('trash')
+ ->atLeast()
+ ->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod'] = $di->protect(fn ($name): Mockery\MockInterface => $modMock);
+
+ $service->setDi($di);
+
+ $result = $service->removeNotExistingModules();
+ expect($result)->toBeInt();
+ expect($result > 0)->toBeTrue();
+});
+
+// Data provider for search query tests
+$searchQueryData = [
+ [[], 'SELECT * FROM extension', []],
+ [['type' => 'mod'], 'AND type = :type', [':type' => 'mod']],
+ [['search' => 'FindUp'], 'AND name LIKE :search', [':search' => 'FindUp']],
+];
+
+test('getSearchQuery returns correct SQL and params', function (array $data, string $expectedStr, array $expectedParams): void {
+ $service = new Box\Mod\Extension\Service();
+ $di = container();
+
+ $service->setDi($di);
+ [$sql, $params] = $service->getSearchQuery($data);
+
+ expect($sql)->toBeString();
+ expect($params)->toBeArray();
+
+ expect(str_contains((string) $sql, $expectedStr))->toBeTrue();
+ expect([])->toBe(array_diff_key($params, $expectedParams));
+})->with($searchQueryData);
+
+test('getExtensionsList returns filtered extensions list', function (): void {
+ $service = new Box\Mod\Extension\Service();
+ $data = [
+ 'has_settings' => true,
+ 'active' => true,
+ ];
+
+ $model['manifest'] = '{"J":5,"0":"N"}';
+ $model['type'] = 'mod';
+ $model['status'] = 'installed';
+ $model['name'] = 'extensionName';
+ $model['version'] = '1';
+
+ $modelFind = new Model_Extension();
+ $modelFind->loadBean(new Tests\Helpers\DummyBean());
+ $modelFind->name = 'extensionName';
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getAll')
+ ->atLeast()
+ ->once()
+ ->andReturn([$model]);
+
+ $dbMock->shouldReceive('find')
+ ->atLeast()
+ ->once()
+ ->andReturn([$modelFind]);
+
+ $coreModules = ['extension', 'cron', 'staff'];
+ $modMock = Mockery::mock(FOSSBilling\Module::class);
+ $modMock->shouldReceive('getCoreModules')
+ ->atLeast()
+ ->once()
+ ->andReturn($coreModules);
+ $modMock->shouldReceive('getManifest')
+ ->atLeast()
+ ->once()
+ ->andReturn([]);
+ $modMock->shouldReceive('hasSettingsPage')
+ ->atLeast()
+ ->once()
+ ->andReturn(true);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod'] = $di->protect(fn ($name): Mockery\MockInterface => $modMock);
+
+ $service->setDi($di);
+
+ $result = $service->getExtensionsList($data);
+ expect($result)->toBeArray();
+});
+
+test('getExtensionsList returns only installed extensions', function (): void {
+ $service = new Box\Mod\Extension\Service();
+ $data = [
+ 'installed' => true,
+ ];
+
+ $model['manifest'] = '{"J":5,"0":"N"}';
+ $model['type'] = 'mod';
+ $model['status'] = 'installed';
+ $model['name'] = 'extensionName';
+ $model['version'] = '1';
+
+ $modelFind = new Model_Extension();
+ $modelFind->loadBean(new Tests\Helpers\DummyBean());
+ $modelFind->name = 'extensionName';
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getAll')
+ ->atLeast()
+ ->once()
+ ->andReturn([$model]);
+
+ $dbMock->shouldReceive('find')
+ ->atLeast()
+ ->once()
+ ->andReturn([$modelFind]);
+
+ $modMock = Mockery::mock(FOSSBilling\Module::class);
+ $modMock->shouldReceive('getManifest')
+ ->atLeast()
+ ->once()
+ ->andReturn([]);
+ $modMock->shouldReceive('hasSettingsPage')
+ ->atLeast()
+ ->once()
+ ->andReturn(true);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod'] = $di->protect(fn ($name): Mockery\MockInterface => $modMock);
+
+ $service->setDi($di);
+
+ $result = $service->getExtensionsList($data);
+ expect($result)->toBeArray();
+});
+
+test('getAdminNavigation returns admin navigation', function (): void {
+ $service = new Box\Mod\Extension\Service();
+ $extensionServiceMock = Mockery::mock(Box\Mod\Extension\Service::class)->makePartial();
+ $extensionServiceMock->shouldAllowMockingProtectedMethods();
+ $extensionServiceMock->shouldReceive('getConfig')
+ ->atLeast()
+ ->once()
+ ->andReturn([]);
+
+ $staffServiceMock = Mockery::mock(Box\Mod\Staff\Service::class);
+ $staffServiceMock->shouldReceive('hasPermission')
+ ->atLeast()
+ ->once()
+ ->andReturn(true);
+
+ $dbalMock = new class {
+ public function createQueryBuilder(): object
+ {
+ return new class {
+ public function select($field)
+ {
+ return $this;
+ }
+
+ public function from($table)
+ {
+ return $this;
+ }
+
+ public function where($cond)
+ {
+ return $this;
+ }
+
+ public function andWhere($cond)
+ {
+ return $this;
+ }
+
+ public function setParameter($key, $val)
+ {
+ return $this;
+ }
+
+ public function executeQuery()
+ {
+ return $this;
+ }
+
+ public function fetchFirstColumn(): array
+ {
+ return [];
+ }
+ };
+ }
+ };
+
+ $link = 'extension';
+
+ $urlMock = Mockery::mock('Box_Url');
+ $urlMock->shouldReceive('adminLink')
+ ->atLeast()
+ ->once()
+ ->andReturn('http://fossbilling.org/index.php?_url=/' . $link);
+
+ $di = container();
+ $di['mod'] = $di->protect(function ($name) use ($di) {
+ $mod = new FOSSBilling\Module($name);
+ $mod->setDi($di);
+
+ return $mod;
+ });
+ $di['tools'] = new FOSSBilling\Tools();
+ $di['mod_service'] = $di->protect(function ($mod) use ($extensionServiceMock, $staffServiceMock) {
+ if ($mod == 'staff') {
+ return $staffServiceMock;
+ }
+
+ return $extensionServiceMock;
+ });
+ $di['url'] = $urlMock;
+ $di['dbal'] = $dbalMock;
+
+ $service->setDi($di);
+ $result = $service->getAdminNavigation(new Model_Admin());
+ expect($result)->toBeArray();
+});
+
+test('findExtension finds an extension', function (): void {
+ $service = new Box\Mod\Extension\Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('findOne')
+ ->atLeast()
+ ->once()
+ ->andReturn(new Model_Extension());
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $service->setDi($di);
+ $result = $service->findExtension('mod', 'id');
+ expect($result)->toBeInstanceOf('\Model_Extension');
+});
+
+test('update throws exception for extensions that need manual update', function (): void {
+ $service = new Box\Mod\Extension\Service();
+ $model = new Model_Extension();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $model->type = 'mod';
+ $model->name = 'testExtension';
+ $model->version = '2';
+
+ $extensionStub = Mockery::mock(FOSSBilling\ExtensionManager::class);
+
+ $staffService = Mockery::mock(Box\Mod\Staff\Service::class);
+ $staffService->shouldReceive('checkPermissionsAndThrowException')->atLeast()->once();
+
+ $di = container();
+ $di['extension_manager'] = $extensionStub;
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $staffService);
+
+ $service->setDi($di);
+
+ expect(fn () => $service->update($model))
+ ->toThrow(FOSSBilling\Exception::class, 'Visit the extension directory for more information on updating this extension.');
+});
+
+test('activate activates an extension', function (): void {
+ $service = new Box\Mod\Extension\Service();
+ $ext = new Model_Extension();
+ $ext->loadBean(new Tests\Helpers\DummyBean());
+ $ext->type = 'mod';
+ $ext->name = 'testExtension';
+
+ $expectedResult = [
+ 'id' => $ext->name,
+ 'type' => $ext->type,
+ 'redirect' => true,
+ 'has_settings' => true,
+ ];
+
+ $staffService = Mockery::mock(Box\Mod\Staff\Service::class);
+ $staffService->shouldReceive('checkPermissionsAndThrowException')->atLeast()->once();
+
+ $modMock = Mockery::mock(FOSSBilling\Module::class);
+ $modMock->shouldReceive('getManifest')
+ ->atLeast()
+ ->once()
+ ->andReturn(['version' => 1]);
+
+ $modMock->shouldReceive('hasAdminController')
+ ->atLeast()
+ ->once()
+ ->andReturn(true);
+
+ $modMock->shouldReceive('hasSettingsPage')
+ ->atLeast()
+ ->once()
+ ->andReturn(true);
+
+ $modMock->shouldReceive('isCore')
+ ->atLeast()
+ ->once()
+ ->andReturn(false);
+
+ $modMock->shouldReceive('install')
+ ->atLeast()
+ ->once();
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->atLeast()
+ ->once()
+ ->andReturn(1);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod'] = $di->protect(fn ($name): Mockery\MockInterface => $modMock);
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $staffService);
+
+ $service->setDi($di);
+ $result = $service->activate($ext);
+ expect($result)->toBeArray();
+ expect($result)->toBe($expectedResult);
+});
+
+test('deactivate deactivates an extension', function (): void {
+ $service = new Box\Mod\Extension\Service();
+ $ext = new Model_Extension();
+ $ext->loadBean(new Tests\Helpers\DummyBean());
+ $ext->type = 'mod';
+ $ext->name = 'extensionTest';
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('trash')->atLeast()->once();
+
+ $modMock = Mockery::mock(FOSSBilling\Module::class);
+ $modMock->shouldReceive('getCoreModules')
+ ->atLeast()
+ ->once()
+ ->andReturn([]);
+
+ $staffService = Mockery::mock(Box\Mod\Staff\Service::class);
+ $staffService->shouldReceive('checkPermissionsAndThrowException')->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod'] = $di->protect(fn ($name): Mockery\MockInterface => $modMock);
+
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $staffService);
+
+ $service->setDi($di);
+
+ $result = $service->deactivate($ext);
+ expect($result)->toBeTrue();
+});
+
+test('deactivate throws exception for core modules', function (): void {
+ $service = new Box\Mod\Extension\Service();
+ $ext = new Model_Extension();
+ $ext->loadBean(new Tests\Helpers\DummyBean());
+ $ext->type = 'mod';
+ $ext->name = 'extensionTest';
+
+ $modMock = Mockery::mock(FOSSBilling\Module::class);
+ $modMock->shouldReceive('getCoreModules')
+ ->atLeast()
+ ->once()
+ ->andReturn([$ext->name]);
+
+ $staffService = Mockery::mock(Box\Mod\Staff\Service::class);
+ $staffService->shouldReceive('checkPermissionsAndThrowException')->atLeast()->once();
+
+ $di = container();
+ $di['mod'] = $di->protect(fn ($name): Mockery\MockInterface => $modMock);
+
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $staffService);
+
+ $service->setDi($di);
+
+ expect(fn (): bool => $service->deactivate($ext))
+ ->toThrow(FOSSBilling\Exception::class, 'Core modules are an integral part of the FOSSBilling system and cannot be deactivated.');
+});
+
+test('deactivate deactivates hook extension', function (): void {
+ $service = new Box\Mod\Extension\Service();
+ $ext = new Model_Extension();
+ $ext->loadBean(new Tests\Helpers\DummyBean());
+ $ext->type = 'hook';
+ $ext->name = 'extensionTest';
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('trash')->atLeast()->once();
+
+ $staffService = Mockery::mock(Box\Mod\Staff\Service::class);
+ $staffService->shouldReceive('checkPermissionsAndThrowException')->atLeast()->once();
+
+ $filesystemMock = Mockery::mock(Symfony\Component\Filesystem\Filesystem::class);
+ $filesystemMock->shouldReceive('exists')->atLeast()->once()->andReturn(true);
+ $filesystemMock->shouldReceive('remove')->atLeast()->once();
+
+ $service = new Box\Mod\Extension\Service($filesystemMock);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $staffService);
+
+ $service->setDi($di);
+ $result = $service->deactivate($ext);
+ expect($result)->toBeTrue();
+});
+
+test('deactivate deactivates module', function (): void {
+ $service = new Box\Mod\Extension\Service();
+ $ext = new Model_Extension();
+ $ext->loadBean(new Tests\Helpers\DummyBean());
+ $ext->type = 'mod';
+ $ext->name = 'extensionTest';
+
+ $modMock = Mockery::mock(FOSSBilling\Module::class);
+ $modMock->shouldReceive('getCoreModules')
+ ->atLeast()
+ ->once()
+ ->andReturn([]);
+
+ $staffService = Mockery::mock(Box\Mod\Staff\Service::class);
+ $staffService->shouldReceive('checkPermissionsAndThrowException')->atLeast()->once();
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('trash')->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod'] = $di->protect(fn ($name): Mockery\MockInterface => $modMock);
+
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $staffService);
+
+ $service->setDi($di);
+
+ $result = $service->deactivate($ext);
+ expect($result)->toBeTrue();
+});
+
+test('uninstall uninstalls an extension', function (): void {
+ $service = new Box\Mod\Extension\Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getCell')->andReturn(null);
+
+ $modMock = Mockery::mock(FOSSBilling\Module::class);
+ $modMock->shouldReceive('getCoreModules')
+ ->atLeast()
+ ->once()
+ ->andReturn([]);
+
+ $modMock->shouldReceive('uninstall')
+ ->atLeast()
+ ->once()
+ ->andReturn(true);
+
+ $staffService = Mockery::mock(Box\Mod\Staff\Service::class);
+ $staffService->shouldReceive('checkPermissionsAndThrowException')->atLeast()->once();
+
+ $di = container();
+
+ $filesystemMock = Mockery::mock(Symfony\Component\Filesystem\Filesystem::class);
+ $filesystemMock->shouldReceive('exists')
+ ->atLeast()
+ ->once()
+ ->andReturn(true);
+ $filesystemMock->shouldReceive('remove')
+ ->atLeast()
+ ->once();
+
+ $tmpDir = sys_get_temp_dir() . '/fb_test_ext_' . uniqid();
+ mkdir($tmpDir, 0o755, true);
+
+ // Create the service with filesystem in constructor, then make it a partial mock
+ $serviceMock = Mockery::mock(Box\Mod\Extension\Service::class . '[getExtensionPath]', [$filesystemMock]);
+ $serviceMock->shouldReceive('getExtensionPath')
+ ->atLeast()
+ ->once()
+ ->andReturn($tmpDir);
+
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $di['mod'] = $di->protect(fn ($name): Mockery\MockInterface => $modMock);
+
+ $di['mod_service'] = $di->protect(function ($name) use ($staffService) {
+ if ($name === 'Staff') {
+ return $staffService;
+ }
+
+ return null;
+ });
+
+ $serviceMock->setDi($di);
+
+ $result = $serviceMock->uninstall('mod', 'TestExtension');
+ expect($result)->toBeTrue();
+
+ if (is_dir($tmpDir)) {
+ rmdir($tmpDir);
+ }
+
+ $result = $serviceMock->uninstall('mod', 'Branding');
+ expect($result)->toBeTrue();
+});
+
+test('downloadAndExtract throws exception when download URL is missing', function (): void {
+ $service = new Box\Mod\Extension\Service();
+ $extensionMock = Mockery::mock(FOSSBilling\ExtensionManager::class);
+
+ $extensionMock->shouldReceive('getLatestExtensionRelease')
+ ->atLeast()
+ ->once()
+ ->andReturn([]);
+
+ $staffService = Mockery::mock(Box\Mod\Staff\Service::class);
+ $staffService->shouldReceive('checkPermissionsAndThrowException')->atLeast()->once();
+
+ $di = container();
+ $di['extension_manager'] = $extensionMock;
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $staffService);
+
+ $service->setDi($di);
+
+ expect(fn (): bool => $service->downloadAndExtract('mod', 'extensionId'))
+ ->toThrow(Exception::class, 'Couldn\'t find a valid download URL for the extension.');
+});
+
+test('getInstalledMods returns installed modules', function (): void {
+ $service = new Box\Mod\Extension\Service();
+ $dbalMock = new class {
+ public function createQueryBuilder(): object
+ {
+ return new class {
+ public function select($field)
+ {
+ return $this;
+ }
+
+ public function from($table)
+ {
+ return $this;
+ }
+
+ public function where($cond)
+ {
+ return $this;
+ }
+
+ public function andWhere($cond)
+ {
+ return $this;
+ }
+
+ public function setParameter($key, $val)
+ {
+ return $this;
+ }
+
+ public function executeQuery()
+ {
+ return $this;
+ }
+
+ public function fetchFirstColumn(): array
+ {
+ return [];
+ }
+ };
+ }
+ };
+
+ $di = new Pimple\Container();
+ $di['dbal'] = $dbalMock;
+
+ $service->setDi($di);
+ $result = $service->getInstalledMods();
+ expect($result)->toBe([]);
+});
+
+test('activateExistingExtension activates existing extension', function (): void {
+ $service = new Box\Mod\Extension\Service();
+ $data = [
+ 'id' => 'extensionId',
+ 'type' => 'extensionType',
+ ];
+
+ $model = new Model_Extension();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $serviceMock = Mockery::mock(Box\Mod\Extension\Service::class)->makePartial();
+ $serviceMock->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('findExtension')
+ ->atLeast()
+ ->once()
+ ->andReturnUsing(function () use ($model) {
+ static $callCount = 0;
+ ++$callCount;
+
+ return $callCount === 1 ? null : $model;
+ });
+ $serviceMock->shouldReceive('activate')
+ ->atLeast()
+ ->once()
+ ->andReturn([]);
+
+ $dbMock = Mockery::mock(Box_Database::class);
+ $dbMock->shouldReceive('dispense')
+ ->atLeast()
+ ->once()
+ ->andReturn($model);
+ $dbMock->shouldReceive('store')
+ ->atLeast()
+ ->once()
+ ->andReturn(1);
+
+ $eventMock = Mockery::mock(Box_EventManager::class);
+ $eventMock->shouldReceive('fire')->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['events_manager'] = $eventMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $serviceMock->setDi($di);
+
+ $result = $serviceMock->activateExistingExtension($data);
+ expect($result)->toBeArray();
+});
+
+test('activateExistingExtension throws exception on activation failure', function (): void {
+ $service = new Box\Mod\Extension\Service();
+ $data = [
+ 'id' => 'extensionId',
+ 'type' => 'extensionType',
+ ];
+
+ $model = new Model_Extension();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $serviceMock = Mockery::mock(Box\Mod\Extension\Service::class)->makePartial();
+ $serviceMock->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('findExtension')
+ ->atLeast()
+ ->once()
+ ->andReturn($model);
+ $serviceMock->shouldReceive('activate')
+ ->atLeast()
+ ->once()
+ ->andThrow(new Exception());
+
+ $eventMock = Mockery::mock(Box_EventManager::class);
+ $eventMock->shouldReceive('fire')->atLeast()->once();
+
+ $di = container();
+ $di['events_manager'] = $eventMock;
+
+ $serviceMock->setDi($di);
+
+ expect(fn () => $serviceMock->activateExistingExtension($data))
+ ->toThrow(Exception::class);
+});
+
+test('getConfig returns extension config', function (): void {
+ $service = new Box\Mod\Extension\Service();
+ $data = [
+ 'ext' => 'extensionName',
+ ];
+
+ $model = new Model_ExtensionMeta();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock(Box_Database::class);
+ $dbMock->shouldReceive('findOne')
+ ->atLeast()
+ ->once()
+ ->andReturn($model);
+
+ $cryptMock = Mockery::mock(Box_Crypt::class);
+ $cryptMock->shouldReceive('decrypt')->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['crypt'] = $cryptMock;
+ $di['cache'] = new Symfony\Component\Cache\Adapter\ArrayAdapter();
+
+ $service->setDi($di);
+
+ $result = $service->getConfig($data['ext']);
+ expect($result)->toBeArray();
+});
+
+test('getConfig creates new ExtensionMeta when not found', function (): void {
+ $service = new Box\Mod\Extension\Service();
+ $data = [
+ 'ext' => 'extensionName',
+ ];
+
+ $model = new Model_ExtensionMeta();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock(Box_Database::class);
+ $dbMock->shouldReceive('findOne')
+ ->atLeast()
+ ->once()
+ ->andReturn(null);
+ $dbMock->shouldReceive('dispense')
+ ->atLeast()
+ ->once()
+ ->andReturn($model);
+ $dbMock->shouldReceive('store')
+ ->atLeast()
+ ->once()
+ ->andReturn(1);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['cache'] = new Symfony\Component\Cache\Adapter\ArrayAdapter();
+
+ $service->setDi($di);
+ $result = $service->getConfig($data['ext']);
+
+ expect($result)->toBeArray();
+ expect($result)->toBe(['ext' => 'extensionName']);
+});
+
+test('setConfig sets extension config', function (): void {
+ $service = new Box\Mod\Extension\Service();
+ $data = [
+ 'ext' => 'extensionName',
+ ];
+
+ $serviceMock = Mockery::mock(Box\Mod\Extension\Service::class)->makePartial();
+ $serviceMock->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('getConfig')
+ ->atLeast()
+ ->once()
+ ->andReturn([]);
+
+ $toolsMock = Mockery::mock(FOSSBilling\Tools::class);
+
+ $cryptMock = Mockery::mock(Box_Crypt::class);
+ $cryptMock->shouldReceive('encrypt')
+ ->atLeast()
+ ->once()
+ ->andReturn('encryptedConfig');
+
+ $model = new Model_ExtensionMeta();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock = Mockery::mock(Box_Database::class);
+ $dbMock->shouldReceive('exec')
+ ->atLeast()
+ ->once()
+ ->andReturn([]);
+ $dbMock->shouldReceive('getCell')
+ ->atLeast()
+ ->once()
+ ->andReturn(1);
+
+ $eventMock = Mockery::mock(Box_EventManager::class);
+ $eventMock->shouldReceive('fire')->atLeast()->once();
+
+ $staffMock = Mockery::mock(Box\Mod\Staff\Service::class);
+ $staffMock->shouldReceive('hasPermission')->atLeast()->once()->andReturn(true);
+
+ $modMock = Mockery::mock(FOSSBilling\Module::class);
+ $modMock->shouldReceive('getCoreModules')->atLeast()->once()->andReturn([]);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['tools'] = $toolsMock;
+ $di['crypt'] = $cryptMock;
+ $di['events_manager'] = $eventMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $di['mod'] = $di->protect(fn (): Mockery\MockInterface => $modMock);
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $staffMock);
+ $di['cache'] = new Symfony\Component\Cache\Adapter\ArrayAdapter();
+
+ $serviceMock->setDi($di);
+ $result = $serviceMock->setConfig($data);
+
+ expect($result)->toBeTrue();
+});
diff --git a/src/modules/Formbuilder/Api/Admin.php b/src/modules/Formbuilder/Api/Admin.php
index 8781d0730..b109c723f 100644
--- a/src/modules/Formbuilder/Api/Admin.php
+++ b/src/modules/Formbuilder/Api/Admin.php
@@ -32,7 +32,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['name' => 'Form name was not provided'])]
public function create_form($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('formbuilder', 'manage');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('formbuilder', 'manage');
if (isset($data['type']) && !in_array(strtolower($data['type']), ['horizontal', 'default'])) {
throw new \FOSSBilling\Exception('Form style was not found in predefined list', null, 3657);
@@ -71,12 +71,15 @@ class Admin extends \Api_Abstract
#[RequiredParams(['type' => 'Form field type is invalid', 'form_id' => 'Form id was not passed'])]
public function add_field($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('formbuilder', 'manage');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('formbuilder', 'manage');
$service = $this->getService();
if (!isset($data['type']) || !$service->isValidFieldType($data['type'])) {
throw new \FOSSBilling\Exception('Form field type is invalid', null, 2684);
}
+ if (!isset($data['form_id'])) {
+ throw new \FOSSBilling\InformationException('Form id was not passed', null, 1822);
+ }
if (isset($data['options']) && is_array($data['options']) && !$service->isArrayUnique($data['options'])) {
throw new \FOSSBilling\InformationException('This input type must have unique values', null, 3658);
}
@@ -93,12 +96,12 @@ class Admin extends \Api_Abstract
*/
public function get_form($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('formbuilder', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('formbuilder', 'view');
$required = [
'id' => 'Form id was not passed',
];
- $this->di['validator']->checkRequiredParamsForArray($required, $data, null, 2391);
+ $this->getDi()['validator']->checkRequiredParamsForArray($required, $data, null, 2391);
$service = $this->getService();
@@ -114,12 +117,12 @@ class Admin extends \Api_Abstract
*/
public function get_form_fields($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('formbuilder', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('formbuilder', 'view');
$required = [
'form_id' => 'Form id was not passed',
];
- $this->di['validator']->checkRequiredParamsForArray($required, $data, null, 1822);
+ $this->getDi()['validator']->checkRequiredParamsForArray($required, $data, null, 1822);
$service = $this->getService();
@@ -135,12 +138,12 @@ class Admin extends \Api_Abstract
*/
public function get_field($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('formbuilder', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('formbuilder', 'view');
$required = [
'id' => 'Field id was not passed',
];
- $this->di['validator']->checkRequiredParamsForArray($required, $data, null, 3547);
+ $this->getDi()['validator']->checkRequiredParamsForArray($required, $data, null, 3547);
$service = $this->getService();
@@ -156,7 +159,7 @@ class Admin extends \Api_Abstract
*/
public function get_forms()
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('formbuilder', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('formbuilder', 'view');
$service = $this->getService();
@@ -170,12 +173,12 @@ class Admin extends \Api_Abstract
*/
public function delete_form($data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('formbuilder', 'manage');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('formbuilder', 'manage');
$required = [
'id' => 'Form id was not passed',
];
- $this->di['validator']->checkRequiredParamsForArray($required, $data, null, 9958);
+ $this->getDi()['validator']->checkRequiredParamsForArray($required, $data, null, 9958);
$service = $this->getService();
$service->removeForm($data['id']);
@@ -190,12 +193,12 @@ class Admin extends \Api_Abstract
*/
public function delete_field($data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('formbuilder', 'manage');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('formbuilder', 'manage');
$required = [
'id' => 'Field id was not passed',
];
- $this->di['validator']->checkRequiredParamsForArray($required, $data, null, 9959);
+ $this->getDi()['validator']->checkRequiredParamsForArray($required, $data, null, 9959);
$service = $this->getService();
$service->removeField($data);
@@ -231,12 +234,12 @@ class Admin extends \Api_Abstract
*/
public function update_field($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('formbuilder', 'manage');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('formbuilder', 'manage');
$required = [
'id' => 'Field id was not passed',
];
- $this->di['validator']->checkRequiredParamsForArray($required, $data, null, 9958);
+ $this->getDi()['validator']->checkRequiredParamsForArray($required, $data, null, 9958);
$service = $this->getService();
if (isset($data['options']) && !$service->isArrayUnique($data['options'])) {
@@ -251,7 +254,7 @@ class Admin extends \Api_Abstract
*/
public function get_pairs($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('formbuilder', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('formbuilder', 'view');
$service = $this->getService();
@@ -268,7 +271,13 @@ class Admin extends \Api_Abstract
#[RequiredParams(['form_id' => 'Form id was not passed', 'name' => 'Form name was not passed'])]
public function copy_form($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('formbuilder', 'manage');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('formbuilder', 'manage');
+
+ $required = [
+ 'form_id' => 'Form id was not passed',
+ 'name' => 'Form name was not passed',
+ ];
+ $this->getDi()['validator']->checkRequiredParamsForArray($required, $data, null, 1822);
$service = $this->getService();
@@ -283,7 +292,14 @@ class Admin extends \Api_Abstract
#[RequiredParams(['form_id' => 'Form id was not passed', 'form_name' => 'Form name was not passed', 'type' => 'Form type was not passed'])]
public function update_form_settings($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('formbuilder', 'manage');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('formbuilder', 'manage');
+
+ $required = [
+ 'form_id' => 'Form id was not passed',
+ 'form_name' => 'Form name was not passed',
+ 'type' => 'Form type was not passed',
+ ];
+ $this->getDi()['validator']->checkRequiredParamsForArray($required, $data, null, 1822);
$type = $data['type'] ?? null;
if ($type !== 'horizontal' && $type !== 'default') {
diff --git a/src/modules/Formbuilder/tests/Unit/Api/AdminTest.php b/src/modules/Formbuilder/tests/Unit/Api/AdminTest.php
new file mode 100644
index 000000000..8b1d83f62
--- /dev/null
+++ b/src/modules/Formbuilder/tests/Unit/Api/AdminTest.php
@@ -0,0 +1,396 @@
+setDi($di);
+ $getDi = $api->getDi();
+ expect($getDi)->toBe($di);
+});
+
+test('creates a form', function (): void {
+ $api = new Admin();
+ $data = ['name' => 'testForm'];
+ $createdFormId = 1;
+
+ $serviceMock = Mockery::mock(Service::class);
+ /** @var Mockery\Expectation $expectation */
+ $expectation = $serviceMock->shouldReceive('addNewForm');
+ $expectation->atLeast()->once();
+ $expectation->andReturn($createdFormId);
+
+ $api->setService($serviceMock);
+
+ $di = container();
+ $api->setDi($di);
+
+ $result = $api->create_form($data);
+ expect($result)->toBeInt()->toBe($createdFormId);
+});
+
+test('throws exception when form type is not in predefined list', function (): void {
+ $api = new Admin();
+ $data = [
+ 'name' => 'testName',
+ 'type' => 'custom',
+ ];
+
+ $di = container();
+ $api->setDi($di);
+
+ expect(fn () => $api->create_form($data))
+ ->toThrow(FOSSBilling\Exception::class, 'Form style was not found in predefined list');
+});
+
+test('adds a field to a form', function (): void {
+ $api = new Admin();
+ $data = [
+ 'type' => 'text',
+ 'options' => ['sameValue'],
+ 'form_id' => 1,
+ ];
+ $newFieldId = 2;
+
+ $serviceMock = Mockery::mock(Service::class);
+ /** @var Mockery\Expectation $expectation1 */
+ $expectation1 = $serviceMock->shouldReceive('isValidFieldType');
+ $expectation1->atLeast()->once();
+ $expectation1->andReturn(true);
+ /** @var Mockery\Expectation $expectation2 */
+ $expectation2 = $serviceMock->shouldReceive('isArrayUnique');
+ $expectation2->atLeast()->once();
+ $expectation2->andReturn(true);
+ /** @var Mockery\Expectation $expectation3 */
+ $expectation3 = $serviceMock->shouldReceive('addNewField');
+ $expectation3->atLeast()->once();
+ $expectation3->andReturn($newFieldId);
+
+ $api->setService($serviceMock);
+ $api->setDi(container());
+
+ $result = $api->add_field($data);
+ expect($result)->toBeInt()->toBe($newFieldId);
+});
+
+test('throws exception when adding field with missing type', function (): void {
+ $api = new Admin();
+ $data = [];
+
+ expect(fn () => $api->add_field($data))
+ ->toThrow(FOSSBilling\Exception::class, 'Form field type is invalid');
+});
+
+test('throws exception when field options are not unique', function (): void {
+ $api = new Admin();
+ $service = Mockery::mock(Service::class);
+ $data = [
+ 'type' => 'text',
+ 'options' => ['sameValue', 'sameValue'],
+ 'form_id' => 1,
+ ];
+
+ $service->shouldReceive('isValidFieldType')->once()->andReturn(true);
+ $service->shouldReceive('isArrayUnique')->once()->andReturn(false);
+
+ $api->setService($service);
+ $api->setDi(container());
+
+ expect(fn () => $api->add_field($data))
+ ->toThrow(FOSSBilling\InformationException::class, 'This input type must have unique values');
+});
+
+test('throws exception when adding field without form id', function (): void {
+ $api = new Admin();
+ $service = Mockery::mock(Service::class);
+ $data = [
+ 'type' => 'text',
+ 'options' => ['sameValue'],
+ ];
+
+ $service->shouldReceive('isValidFieldType')->once()->andReturn(true);
+
+ $api->setService($service);
+ $api->setDi(container());
+
+ expect(fn () => $api->add_field($data))
+ ->toThrow(FOSSBilling\InformationException::class, 'Form id was not passed');
+});
+
+test('gets a form', function (): void {
+ $api = new Admin();
+ $data['id'] = 1;
+
+ $serviceMock = Mockery::mock(Service::class);
+ /** @var Mockery\Expectation $expectation */
+ $expectation = $serviceMock->shouldReceive('getForm');
+ $expectation->atLeast()->once();
+ $expectation->andReturn([]);
+
+ $validatorMock = Mockery::mock(FOSSBilling\Validate::class);
+ /** @var Mockery\Expectation $validatorExpectation */
+ $validatorExpectation = $validatorMock->shouldReceive('checkRequiredParamsForArray');
+ $validatorExpectation->atLeast()->once();
+
+ $di = container();
+ $di['validator'] = $validatorMock;
+ $api->setDi($di);
+
+ $api->setService($serviceMock);
+ $result = $api->get_form($data);
+ expect($result)->toBeArray();
+});
+
+test('gets form fields', function (): void {
+ $api = new Admin();
+ $data['form_id'] = 1;
+
+ $serviceMock = Mockery::mock(Service::class);
+ /** @var Mockery\Expectation $expectation */
+ $expectation = $serviceMock->shouldReceive('getFormFields');
+ $expectation->atLeast()->once();
+ $expectation->andReturn([]);
+
+ $validatorMock = Mockery::mock(FOSSBilling\Validate::class);
+ /** @var Mockery\Expectation $validatorExpectation */
+ $validatorExpectation = $validatorMock->shouldReceive('checkRequiredParamsForArray');
+ $validatorExpectation->atLeast()->once();
+
+ $di = container();
+ $di['validator'] = $validatorMock;
+ $api->setDi($di);
+
+ $api->setService($serviceMock);
+ $result = $api->get_form_fields($data);
+ expect($result)->toBeArray();
+});
+
+test('gets a field', function (): void {
+ $api = new Admin();
+ $data['id'] = 3;
+
+ $serviceMock = Mockery::mock(Service::class);
+ /** @var Mockery\Expectation $expectation */
+ $expectation = $serviceMock->shouldReceive('getField');
+ $expectation->atLeast()->once();
+ $expectation->andReturn([]);
+
+ $validatorMock = Mockery::mock(FOSSBilling\Validate::class);
+ /** @var Mockery\Expectation $validatorExpectation */
+ $validatorExpectation = $validatorMock->shouldReceive('checkRequiredParamsForArray');
+ $validatorExpectation->atLeast()->once();
+
+ $di = container();
+ $di['validator'] = $validatorMock;
+ $api->setDi($di);
+
+ $api->setService($serviceMock);
+
+ $result = $api->get_field($data);
+ expect($result)->toBeArray();
+});
+
+test('gets all forms', function (): void {
+ $api = new Admin();
+ $serviceMock = Mockery::mock(Service::class);
+ /** @var Mockery\Expectation $expectation */
+ $expectation = $serviceMock->shouldReceive('getForms');
+ $expectation->atLeast()->once();
+ $expectation->andReturn([]);
+
+ $api->setService($serviceMock);
+ $api->setDi(container());
+
+ $result = $api->get_forms();
+ expect($result)->toBeArray();
+});
+
+test('deletes a form', function (): void {
+ $api = new Admin();
+ $data['id'] = 1;
+
+ $serviceMock = Mockery::mock(Service::class);
+ /** @var Mockery\Expectation $expectation */
+ $expectation = $serviceMock->shouldReceive('removeForm');
+ $expectation->atLeast()->once();
+ $expectation->andReturn(true);
+
+ $validatorMock = Mockery::mock(FOSSBilling\Validate::class);
+ /** @var Mockery\Expectation $validatorExpectation */
+ $validatorExpectation = $validatorMock->shouldReceive('checkRequiredParamsForArray');
+ $validatorExpectation->atLeast()->once();
+
+ $di = container();
+ $di['validator'] = $validatorMock;
+ $api->setDi($di);
+
+ $api->setService($serviceMock);
+
+ $result = $api->delete_form($data);
+ expect($result)->toBeTrue();
+});
+
+test('deletes a field', function (): void {
+ $api = new Admin();
+ $data['id'] = 1;
+
+ $serviceMock = Mockery::mock(Service::class);
+ /** @var Mockery\Expectation $expectation */
+ $expectation = $serviceMock->shouldReceive('removeField');
+ $expectation->atLeast()->once();
+ $expectation->andReturn(true);
+
+ $validatorMock = Mockery::mock(FOSSBilling\Validate::class);
+ /** @var Mockery\Expectation $validatorExpectation */
+ $validatorExpectation = $validatorMock->shouldReceive('checkRequiredParamsForArray');
+ $validatorExpectation->atLeast()->once();
+
+ $di = container();
+ $di['validator'] = $validatorMock;
+ $api->setDi($di);
+
+ $api->setService($serviceMock);
+
+ $result = $api->delete_field($data);
+ expect($result)->toBeTrue();
+});
+
+test('updates a field', function (): void {
+ $api = new Admin();
+ $updatedFieldId = 1;
+ $data = [
+ 'id' => $updatedFieldId,
+ 'options' => ['sameValue'],
+ ];
+
+ $serviceMock = Mockery::mock(Service::class);
+ /** @var Mockery\Expectation $expectation1 */
+ $expectation1 = $serviceMock->shouldReceive('updateField');
+ $expectation1->atLeast()->once();
+ $expectation1->andReturn($updatedFieldId);
+ /** @var Mockery\Expectation $expectation2 */
+ $expectation2 = $serviceMock->shouldReceive('isArrayUnique');
+ $expectation2->atLeast()->once();
+ $expectation2->andReturn(true);
+
+ $validatorMock = Mockery::mock(FOSSBilling\Validate::class);
+ /** @var Mockery\Expectation $validatorExpectation */
+ $validatorExpectation = $validatorMock->shouldReceive('checkRequiredParamsForArray');
+ $validatorExpectation->atLeast()->once();
+
+ $di = container();
+ $di['validator'] = $validatorMock;
+ $api->setDi($di);
+
+ $api->setService($serviceMock);
+
+ $result = $api->update_field($data);
+ expect($result)->toBeInt()->toBe($updatedFieldId);
+});
+
+test('gets form pairs', function (): void {
+ $api = new Admin();
+ $data = [];
+ $serviceMock = Mockery::mock(Service::class);
+ /** @var Mockery\Expectation $expectation */
+ $expectation = $serviceMock->shouldReceive('getFormPairs');
+ $expectation->atLeast()->once();
+ $expectation->andReturn([]);
+
+ $api->setService($serviceMock);
+ $api->setDi(container());
+
+ $result = $api->get_pairs($data);
+ expect($result)->toBeArray();
+});
+
+test('copies a form', function (): void {
+ $api = new Admin();
+ $newFormId = 2;
+ $data = [
+ 'form_id' => 1,
+ 'name' => 'testForm',
+ ];
+
+ $serviceMock = Mockery::mock(Service::class);
+ /** @var Mockery\Expectation $expectation */
+ $expectation = $serviceMock->shouldReceive('duplicateForm');
+ $expectation->atLeast()->once();
+ $expectation->andReturn($newFormId);
+
+ $api->setService($serviceMock);
+ $api->setDi(container());
+ $result = $api->copy_form($data);
+ expect($result)->toBeInt()->toBe($newFormId);
+});
+
+test('throws exception when copying form without id', function (): void {
+ $api = new Admin();
+ $data = [];
+
+ $api->setDi(container());
+ expect(fn () => $api->copy_form($data))
+ ->toThrow(FOSSBilling\InformationException::class, 'Form id was not passed');
+});
+
+test('throws exception when copying form without name', function (): void {
+ $api = new Admin();
+ $data = ['form_id' => 1];
+
+ $api->setDi(container());
+ expect(fn () => $api->copy_form($data))
+ ->toThrow(FOSSBilling\InformationException::class, 'Form name was not passed');
+});
+
+test('updates form settings', function (): void {
+ $api = new Admin();
+ $data = [
+ 'form_id' => 1,
+ 'form_name' => 'testForm',
+ 'type' => 'default',
+ ];
+
+ $serviceMock = Mockery::mock(Service::class);
+ /** @var Mockery\Expectation $expectation */
+ $expectation = $serviceMock->shouldReceive('updateFormSettings');
+ $expectation->atLeast()->once();
+ $expectation->andReturn(true);
+
+ $api->setService($serviceMock);
+ $api->setDi(container());
+ $result = $api->update_form_settings($data);
+ expect($result)->toBeTrue();
+});
+
+test('throws exception when updating form settings with missing fields', function ($missingField, $exceptionMessage): void {
+ $api = new Admin();
+ $data = [
+ 'form_id' => 1,
+ 'form_name' => 'testForm',
+ 'type' => 'customType',
+ ];
+ unset($data[$missingField]);
+
+ $api->setDi(container());
+ expect(fn () => $api->update_form_settings($data))
+ ->toThrow(FOSSBilling\Exception::class, $exceptionMessage);
+})->with([
+ ['form_id', 'Form id was not passed'],
+ ['form_name', 'Form name was not passed'],
+ ['type', 'Form type was not passed'],
+ ['', 'Field type not supported'],
+]);
diff --git a/src/modules/Formbuilder/tests/Unit/ServiceTest.php b/src/modules/Formbuilder/tests/Unit/ServiceTest.php
new file mode 100644
index 000000000..6bf40ef02
--- /dev/null
+++ b/src/modules/Formbuilder/tests/Unit/ServiceTest.php
@@ -0,0 +1,476 @@
+setDi($di);
+ $getDi = $service->getDi();
+ expect($getDi)->toBe($di);
+});
+
+test('gets form field types', function (): void {
+ $service = new Service();
+ $expected = [
+ 'text' => 'Text Input',
+ 'url' => 'URL Input',
+ 'select' => 'Dropdown',
+ 'radio' => 'Radio Select',
+ 'checkbox' => 'Checkbox',
+ 'textarea' => 'Text Area',
+ ];
+
+ $result = $service->getFormFieldsTypes();
+ expect($result)->toBe($expected);
+});
+
+test('validates field types', function (string $type, bool $expected): void {
+ $service = new Service();
+ $result = $service->isValidFieldType($type);
+ expect($result)->toBe($expected);
+})->with([
+ ['select', true],
+ ['custom', false],
+]);
+
+test('checks if array is unique', function (array $data, bool $expected): void {
+ $service = new Service();
+ $result = $service->isArrayUnique($data);
+ expect($result)->toBe($expected);
+})->with([
+ [['sameValue', 'sameValue'], false],
+ [['sameValue', 'DiffValue'], true],
+ [[], true],
+]);
+
+test('adds a new form', function (): void {
+ $service = new Service();
+ $newFormId = 1;
+ $data = [
+ 'name' => 'testName',
+ 'style' => [],
+ ];
+
+ $dbal = Mockery::mock(Connection::class);
+ $dbal->shouldReceive('insert')->once()->with('form', Mockery::on(fn (array $row): bool => $row['name'] === 'testName'));
+ $dbal->shouldReceive('lastInsertId')->once()->andReturn($newFormId);
+
+ $di = container();
+ $di['dbal'] = $dbal;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $service->setDi($di);
+
+ $result = $service->addNewForm($data);
+ expect($result)->toBeInt()->toBe($newFormId);
+});
+
+test('adds a new field', function (): void {
+ $service = new Service();
+ $newFieldId = 1;
+ $data = [
+ 'form_id' => 1,
+ 'type' => 'select',
+ ];
+
+ $countResult = Mockery::mock(Result::class);
+ $countResult->shouldReceive('fetchOne')->once()->andReturn(0);
+
+ $dbal = Mockery::mock(Connection::class);
+ $dbal->shouldReceive('executeQuery')->once()->andReturn($countResult);
+ $dbal->shouldReceive('insert')->once()->with('form_field', Mockery::on(fn (array $row): bool => $row['form_id'] === 1 && $row['type'] === 'select'));
+ $dbal->shouldReceive('lastInsertId')->once()->andReturn($newFieldId);
+
+ $di = container();
+ $di['dbal'] = $dbal;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $service->setDi($di);
+
+ $result = $service->addNewField($data);
+ expect($result)->toBeInt()->toBe($newFieldId);
+});
+
+test('updates a field', function (string $fieldType): void {
+ $service = new Service();
+ $updateFieldId = 2;
+ $data = [
+ 'id' => $updateFieldId,
+ 'form_id' => 1,
+ 'type' => $fieldType,
+ 'default_value' => 'defaultTestValue',
+ 'values' => ['test'],
+ 'labels' => ['labels'],
+ 'name' => 'testField',
+ 'textarea_size' => [64],
+ 'textarea_option' => [''],
+ ];
+
+ $modelArray = [
+ 'id' => $updateFieldId,
+ 'form_id' => 1,
+ 'options' => '{"hidden":"hidden"}',
+ ];
+
+ $fieldResult = Mockery::mock(Result::class);
+ $fieldResult->shouldReceive('fetchAssociative')->once()->andReturn($modelArray);
+ $existsResult = Mockery::mock(Result::class);
+ $existsResult->shouldReceive('fetchOne')->once()->andReturn(0);
+
+ $dbal = Mockery::mock(Connection::class);
+ $dbal->shouldReceive('executeQuery')->twice()->andReturn($fieldResult, $existsResult);
+ $dbal->shouldReceive('update')->once()->with('form_field', Mockery::type('array'), ['id' => $updateFieldId]);
+
+ $di = container();
+ $di['dbal'] = $dbal;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $validatorMock = Mockery::mock(FOSSBilling\Validate::class);
+ $validatorMock->shouldReceive('checkRequiredParamsForArray');
+ $di['validator'] = $validatorMock;
+
+ $service->setDi($di);
+
+ $result = $service->updateField($data);
+ expect($result)->toBeInt()->toBe($updateFieldId);
+})->with([
+ ['select'],
+ ['textarea'],
+]);
+
+test('throws exception when updating field with existing name', function (): void {
+ $data = [
+ 'id' => 2,
+ 'form_id' => 1,
+ 'name' => 'testField',
+ 'type' => 'select',
+ ];
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+ /** @var Mockery\Expectation $expectation1 */
+ $expectation1 = $serviceMock->shouldReceive('formFieldNameExists');
+ $expectation1->atLeast()->once();
+ $expectation1->andReturn(true);
+ $serviceMock->shouldReceive('getField');
+
+ expect(fn () => $serviceMock->updateField($data))
+ ->toThrow(FOSSBilling\Exception::class, 'Unfortunately field with this name exists in this form already. Form must have different field names.');
+});
+
+test('throws exception when field values are not unique', function (): void {
+ $data = [
+ 'id' => 2,
+ 'form_id' => 1,
+ 'type' => 'select',
+ 'default_value' => 'defaultTestValue',
+ 'values' => ['test', 'test'],
+ 'labels' => ['labels'],
+ 'name' => 'testField',
+ ];
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+ /** @var Mockery\Expectation $expectation1 */
+ $expectation1 = $serviceMock->shouldReceive('formFieldNameExists');
+ $expectation1->atLeast()->once();
+ $expectation1->andReturn(false);
+ $serviceMock->shouldReceive('getField');
+
+ expect(fn () => $serviceMock->updateField($data))
+ ->toThrow(FOSSBilling\Exception::class, ucfirst($data['type']) . ' values must be unique');
+});
+
+test('throws exception when field labels are not unique', function (): void {
+ $data = [
+ 'id' => 2,
+ 'form_id' => 1,
+ 'type' => 'select',
+ 'default_value' => 'defaultTestValue',
+ 'values' => ['test'],
+ 'labels' => ['labels', 'labels'],
+ 'name' => 'testField',
+ ];
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+ /** @var Mockery\Expectation $expectation1 */
+ $expectation1 = $serviceMock->shouldReceive('formFieldNameExists');
+ $expectation1->atLeast()->once();
+ $expectation1->andReturn(false);
+ $serviceMock->shouldReceive('getField');
+
+ expect(fn () => $serviceMock->updateField($data))
+ ->toThrow(FOSSBilling\Exception::class, ucfirst($data['type']) . ' labels must be unique');
+});
+
+test('throws exception when textarea size is invalid', function (): void {
+ $data = [
+ 'id' => 2,
+ 'form_id' => 1,
+ 'type' => 'textarea',
+ 'default_value' => 'defaultTestValue',
+ 'values' => ['test'],
+ 'labels' => ['labels'],
+ 'name' => 'testField',
+ 'textarea_size' => [''],
+ 'textarea_option' => [''],
+ ];
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+ /** @var Mockery\Expectation $expectation1 */
+ $expectation1 = $serviceMock->shouldReceive('formFieldNameExists');
+ $expectation1->atLeast()->once();
+ $expectation1->andReturn(false);
+ $serviceMock->shouldReceive('getField');
+
+ expect(fn () => $serviceMock->updateField($data))
+ ->toThrow(FOSSBilling\Exception::class, 'Textarea size options must be integer values');
+});
+
+test('gets a form', function (): void {
+ $service = new Service();
+ $modelArray = [
+ 'style' => '',
+ 'id' => 1,
+ ];
+ $getAllResult = [
+ [
+ 'options' => '{"options":["hidden"]}',
+ 'default_value' => 'TestingValue',
+ ],
+ ];
+
+ $formResult = Mockery::mock(Result::class);
+ $formResult->shouldReceive('fetchAssociative')->once()->andReturn($modelArray);
+ $fieldsResult = Mockery::mock(Result::class);
+ $fieldsResult->shouldReceive('fetchAllAssociative')->once()->andReturn($getAllResult);
+
+ $dbal = Mockery::mock(Connection::class);
+ $dbal->shouldReceive('executeQuery')->twice()->andReturn($formResult, $fieldsResult);
+
+ $di = container();
+ $di['dbal'] = $dbal;
+
+ $formId = 1;
+
+ $service->setDi($di);
+ $result = $service->getForm($formId);
+ expect($result)->toBeArray();
+});
+
+test('gets form fields', function (): void {
+ $service = new Service();
+ $formId = 1;
+ $result = Mockery::mock(Result::class);
+ $result->shouldReceive('fetchAllAssociative')->once()->andReturn([]);
+
+ $dbal = Mockery::mock(Connection::class);
+ $dbal->shouldReceive('executeQuery')->once()->andReturn($result);
+
+ $di = container();
+ $di['dbal'] = $dbal;
+
+ $service->setDi($di);
+ $result = $service->getFormFields($formId);
+ expect($result)->toBeArray();
+});
+
+test('gets form fields count', function (): void {
+ $service = new Service();
+ $formId = 1;
+ $dbalResult = Mockery::mock(Result::class);
+ $dbalResult->shouldReceive('fetchOne')->once()->andReturn(0);
+
+ $dbal = Mockery::mock(Connection::class);
+ $dbal->shouldReceive('executeQuery')->once()->andReturn($dbalResult);
+
+ $di = container();
+ $di['dbal'] = $dbal;
+
+ $service->setDi($di);
+ $result = $service->getFormFieldsCount($formId);
+ expect($result)->toBeInt()->toBe(0);
+});
+
+test('gets form pairs', function (): void {
+ $service = new Service();
+ $dbalResult = Mockery::mock(Result::class);
+ $dbalResult->shouldReceive('fetchAllAssociative')->once()->andReturn([
+ ['id' => 1, 'name' => 'Default'],
+ ]);
+
+ $dbal = Mockery::mock(Connection::class);
+ $dbal->shouldReceive('executeQuery')->once()->andReturn($dbalResult);
+
+ $di = container();
+ $di['dbal'] = $dbal;
+
+ $service->setDi($di);
+ $result = $service->getFormPairs();
+ expect($result)->toBe([1 => 'Default']);
+});
+
+test('gets a field', function (): void {
+ $service = new Service();
+ $fieldId = 2;
+ $modelArray = [
+ 'id' => 2,
+ 'options' => '{"options":["hidden"]}',
+ ];
+
+ $expectedArray = $modelArray;
+ $expectedArray['options'] = json_decode($expectedArray['options']);
+
+ $dbalResult = Mockery::mock(Result::class);
+ $dbalResult->shouldReceive('fetchAssociative')->once()->andReturn($modelArray);
+
+ $dbal = Mockery::mock(Connection::class);
+ $dbal->shouldReceive('executeQuery')->once()->andReturn($dbalResult);
+
+ $di = container();
+ $validatorMock = Mockery::mock(FOSSBilling\Validate::class);
+ $validatorMock->shouldReceive('checkRequiredParamsForArray');
+ $di['validator'] = $validatorMock;
+ $di['dbal'] = $dbal;
+
+ $service->setDi($di);
+ $result = $service->getField($fieldId);
+ expect($result)->toBeArray();
+ expect($result['id'])->toBe($fieldId);
+});
+
+test('removes a form', function (): void {
+ $service = new Service();
+ $dbal = Mockery::mock(Connection::class);
+ $dbal->shouldReceive('executeStatement')->times(4)->andReturn(1);
+
+ $di = container();
+ $di['dbal'] = $dbal;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $service->setDi($di);
+ $formId = 1;
+ $result = $service->removeForm($formId);
+ expect($result)->toBeTrue();
+});
+
+test('removes a field', function (): void {
+ $service = new Service();
+ $data = ['id' => 1];
+
+ $dbal = Mockery::mock(Connection::class);
+ $dbal->shouldReceive('executeStatement')->once()->andReturn(1);
+
+ $di = container();
+ $di['dbal'] = $dbal;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $service->setDi($di);
+ $result = $service->removeField($data);
+ expect($result)->toBeTrue();
+});
+
+test('checks if form field name exists', function (): void {
+ $service = new Service();
+ $data = [
+ 'field_name' => 'testingName',
+ 'form_id' => 2,
+ 'field_id' => 10,
+ ];
+
+ $dbalResult = Mockery::mock(Result::class);
+ $dbalResult->shouldReceive('fetchOne')->once()->andReturn(1);
+
+ $dbal = Mockery::mock(Connection::class);
+ $dbal->shouldReceive('executeQuery')->once()->andReturn($dbalResult);
+
+ $di = container();
+ $di['dbal'] = $dbal;
+
+ $service->setDi($di);
+ $result = $service->formFieldNameExists($data);
+ expect($result)->toBeTrue();
+});
+
+test('gets all forms', function (): void {
+ $service = new Service();
+ $dbalResult = Mockery::mock(Result::class);
+ $dbalResult->shouldReceive('fetchAllAssociative')->once()->andReturn([]);
+
+ $dbal = Mockery::mock(Connection::class);
+ $dbal->shouldReceive('executeQuery')->once()->andReturn($dbalResult);
+
+ $di = container();
+ $di['dbal'] = $dbal;
+
+ $service->setDi($di);
+ $result = $service->getForms();
+ expect($result)->toBeArray();
+});
+
+test('duplicates a form', function (): void {
+ $data = [
+ 'form_id' => 1,
+ 'name' => 'testForm',
+ ];
+
+ $newFormId = 3;
+ $newFieldId = 4;
+ $fields = [
+ 'options' => [],
+ ];
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+ /** @var Mockery\Expectation $expectation1 */
+ $expectation1 = $serviceMock->shouldReceive('getFormFields');
+ $expectation1->atLeast()->once();
+ $expectation1->andReturn($fields);
+ /** @var Mockery\Expectation $expectation2 */
+ $expectation2 = $serviceMock->shouldReceive('addNewForm');
+ $expectation2->atLeast()->once();
+ $expectation2->andReturn($newFormId);
+ /** @var Mockery\Expectation $expectation3 */
+ $expectation3 = $serviceMock->shouldReceive('addNewField');
+ $expectation3->atLeast()->once();
+ $expectation3->andReturn($newFieldId);
+
+ $di = container();
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $serviceMock->setDi($di);
+ $result = $serviceMock->duplicateForm($data);
+ expect($result)->toBeInt()->toBe($newFormId);
+});
+
+test('updates form settings', function (): void {
+ $service = new Service();
+ $data = [
+ 'type' => 'default',
+ 'form_name' => 'testForm',
+ 'form_id' => 1,
+ ];
+
+ $dbal = Mockery::mock(Connection::class);
+ $dbal->shouldReceive('update')->once()->andReturn(1);
+
+ $di = container();
+ $di['dbal'] = $dbal;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $service->setDi($di);
+ $result = $service->updateFormSettings($data);
+ expect($result)->toBeTrue();
+});
diff --git a/src/modules/Hook/Api/Admin.php b/src/modules/Hook/Api/Admin.php
index 743281f25..1f7fd6776 100644
--- a/src/modules/Hook/Api/Admin.php
+++ b/src/modules/Hook/Api/Admin.php
@@ -27,12 +27,12 @@ class Admin extends \Api_Abstract
*/
public function get_list($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('hook', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('hook', 'view');
$service = $this->getService();
[$sql, $params] = $service->getSearchQuery($data);
- return $this->di['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
+ return $this->getDi()['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
}
/**
@@ -44,25 +44,26 @@ class Admin extends \Api_Abstract
*/
public function call($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('hook', 'trigger_hooks');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('hook', 'trigger_hooks');
if (!isset($data['event']) || empty($data['event'])) {
- error_log('Invoked event call without providing event name');
+ $this->getDi()['logger']->warning('Invoked event call without providing event name');
return false;
}
$event = $data['event'];
$params = $data['params'] ?? null;
+ // @phpstan-ignore if.alwaysFalse
if (DEBUG) {
try {
- $this->di['logger']->info($event . ': ' . var_export($params, true));
+ $this->getDi()['logger']->info($event . ': ' . var_export($params, true));
} catch (\Exception $e) {
error_log($e->getMessage());
}
}
- return $this->di['events_manager']->fire($data);
+ return $this->getDi()['events_manager']->fire($data);
}
/**
@@ -75,7 +76,7 @@ class Admin extends \Api_Abstract
*/
public function batch_connect($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('hook', 'manage_hooks', null, $this->identity);
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('hook', 'manage_hooks', null, $this->identity);
$mod = $data['mod'] ?? null;
$service = $this->getService();
diff --git a/src/modules/Hook/tests/Unit/Api/AdminTest.php b/src/modules/Hook/tests/Unit/Api/AdminTest.php
new file mode 100644
index 000000000..2971c9934
--- /dev/null
+++ b/src/modules/Hook/tests/Unit/Api/AdminTest.php
@@ -0,0 +1,90 @@
+setDi($di);
+ $getDi = $api->getDi();
+ expect($getDi)->toEqual($di);
+});
+
+test('getList returns array', function (): void {
+ $api = new Box\Mod\Hook\Api\Admin();
+ $serviceMock = Mockery::mock(Box\Mod\Hook\Service::class);
+ /** @var Mockery\Expectation $expectation1 */
+ $expectation1 = $serviceMock->shouldReceive('getSearchQuery');
+ $expectation1->atLeast()->once();
+ $expectation1->andReturn(['SqlString', []]);
+
+ $paginatorMock = Mockery::mock(FOSSBilling\Pagination::class)->makePartial();
+ $paginatorMock->shouldAllowMockingProtectedMethods();
+ /** @var Mockery\Expectation $expectation2 */
+ $expectation2 = $paginatorMock->shouldReceive('getPaginatedResultSet');
+ $expectation2->atLeast()->once();
+ $expectation2->andReturn([]);
+
+ $di = container();
+ $di['pager'] = $paginatorMock;
+
+ $api->setDi($di);
+ $api->setService($serviceMock);
+ $result = $api->get_list([]);
+ expect($result)->toBeArray();
+});
+
+test('call fires event', function (): void {
+ $api = new Box\Mod\Hook\Api\Admin();
+ $data['event'] = 'testEvent';
+
+ $eventManager = Mockery::mock('\Box_EventManager');
+ /** @var Mockery\Expectation $expectation */
+ $expectation = $eventManager->shouldReceive('fire');
+ $expectation->atLeast()->once();
+ $expectation->andReturn(1);
+
+ $di = container();
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $di['events_manager'] = $eventManager;
+
+ $api->setDi($di);
+ $result = $api->call($data);
+ expect($result)->not->toBeEmpty();
+});
+
+test('call returns false when event param is missing', function (): void {
+ $api = new Box\Mod\Hook\Api\Admin();
+ $data['event'] = null;
+
+ $result = $api->call($data);
+ expect($result)->toBeBool();
+ expect($result)->toBeFalse();
+});
+
+test('batchConnect returns result', function (): void {
+ $api = new Box\Mod\Hook\Api\Admin();
+ $serviceMock = Mockery::mock(Box\Mod\Hook\Service::class);
+ /** @var Mockery\Expectation $expectation */
+ $expectation = $serviceMock->shouldReceive('batchConnect');
+ $expectation->atLeast()->once();
+ $expectation->andReturn(true);
+
+ $di = container();
+
+ $api->setDi($di);
+
+ $api->setService($serviceMock);
+ $result = $api->batch_connect([]);
+ expect($result)->not->toBeEmpty();
+});
diff --git a/src/modules/Hook/tests/Unit/ServiceTest.php b/src/modules/Hook/tests/Unit/ServiceTest.php
new file mode 100644
index 000000000..7d56e69b2
--- /dev/null
+++ b/src/modules/Hook/tests/Unit/ServiceTest.php
@@ -0,0 +1,215 @@
+setDi($di);
+ $getDi = $service->getDi();
+ expect($getDi)->toBe($di);
+});
+
+test('gets search query', function (): void {
+ $service = new Box\Mod\Hook\Service();
+ [$sql, $params] = $service->getSearchQuery([]);
+
+ expect($sql)->toBeString()
+ ->and($params)->toBeArray()
+ ->and(str_contains((string) $sql, 'SELECT id, rel_type, rel_id, meta_value as event, created_at, updated_at'))->toBeTrue()
+ ->and($params)->toBe([]);
+});
+
+test('converts to api array', function (): void {
+ $service = new Box\Mod\Hook\Service();
+ $arrMock = ['testing' => 'okay'];
+ $result = $service->toApiArray($arrMock);
+ expect($result)->toBe($arrMock);
+});
+
+test('handles on after admin activate extension', function (): void {
+ $service = new Box\Mod\Hook\Service();
+ $eventParams = [
+ 'id' => 1,
+ ];
+
+ $eventMock = Mockery::mock('\Box_Event');
+ /** @var Mockery\Expectation $expectation1 */
+ $expectation1 = $eventMock->shouldReceive('getParameters');
+ $expectation1->atLeast()->once();
+ $expectation1->andReturn($eventParams);
+ /** @var Mockery\Expectation $expectation2 */
+ $expectation2 = $eventMock->shouldReceive('setReturnValue');
+ $expectation2->atLeast()->once();
+
+ $model = new Model_Extension();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $model->id = 1;
+ $model->type = 'mod';
+
+ $dbMock = Mockery::mock('\Box_Database');
+ /** @var Mockery\Expectation $expectation3 */
+ $expectation3 = $dbMock->shouldReceive('load');
+ $expectation3->atLeast()->once();
+ $expectation3->andReturn($model);
+
+ $hookService = Mockery::mock(Box\Mod\Hook\Service::class);
+ /** @var Mockery\Expectation $expectation4 */
+ $expectation4 = $hookService->shouldReceive('batchConnect');
+ $expectation4->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(fn ($name): Mockery\MockInterface => $hookService);
+
+ /** @var Mockery\Expectation $expectation5 */
+ $expectation5 = $eventMock->shouldReceive('getDi');
+ $expectation5->atLeast()->once();
+ $expectation5->andReturn($di);
+
+ $service->setDi($di);
+ /* @var \Box_Event $eventMock */
+ $service->onAfterAdminActivateExtension($eventMock);
+ $result = true;
+ expect($result)->toBeTrue();
+});
+
+test('handles on after admin activate extension with missing id', function (): void {
+ $service = new Box\Mod\Hook\Service();
+ $eventParams = [];
+
+ $eventMock = Mockery::mock('\Box_Event');
+ /** @var Mockery\Expectation $expectation1 */
+ $expectation1 = $eventMock->shouldReceive('getParameters');
+ $expectation1->atLeast()->once();
+ $expectation1->andReturn($eventParams);
+ /** @var Mockery\Expectation $expectation2 */
+ $expectation2 = $eventMock->shouldReceive('setReturnValue');
+ $expectation2->atLeast()->once();
+
+ /* @var \Box_Event $eventMock */
+ $service->onAfterAdminActivateExtension($eventMock);
+ $result = false;
+ expect($result)->toBeFalse();
+});
+
+test('handles on after admin deactivate extension', function (): void {
+ $service = new Box\Mod\Hook\Service();
+ $eventParams = [
+ 'type' => 'mod',
+ 'id' => 1,
+ ];
+
+ $eventMock = Mockery::mock('\Box_Event');
+ /** @var Mockery\Expectation $expectation1 */
+ $expectation1 = $eventMock->shouldReceive('getParameters');
+ $expectation1->atLeast()->once();
+ $expectation1->andReturn($eventParams);
+ /** @var Mockery\Expectation $expectation2 */
+ $expectation2 = $eventMock->shouldReceive('setReturnValue');
+ $expectation2->atLeast()->once();
+
+ $dbMock = Mockery::mock('\Box_Database');
+ /** @var Mockery\Expectation $expectation3 */
+ $expectation3 = $dbMock->shouldReceive('exec');
+ $expectation3->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ /** @var Mockery\Expectation $expectation4 */
+ $expectation4 = $eventMock->shouldReceive('getDi');
+ $expectation4->atLeast()->once();
+ $expectation4->andReturn($di);
+
+ $service->setDi($di);
+ /* @var \Box_Event $eventMock */
+ $service->onAfterAdminDeactivateExtension($eventMock);
+ $result = true;
+ expect($result)->toBeTrue();
+});
+
+test('batch connects', function (): void {
+ $service = new Box\Mod\Hook\Service();
+ $mod = 'activity';
+
+ $data['mods'] = [$mod];
+
+ $dbMock = Mockery::mock('\Box_Database');
+ /** @var Mockery\Expectation $expectation1 */
+ $expectation1 = $dbMock->shouldReceive('getCell');
+ $expectation1->atLeast()->once();
+ $expectation1->andReturn(false);
+ $dbMock->shouldReceive('exec')
+ ->byDefault();
+
+ $extensionModel = new Model_ExtensionMeta();
+ $extensionModel->loadBean(new Tests\Helpers\DummyBean());
+
+ /** @var Mockery\Expectation $expectation2 */
+ $expectation2 = $dbMock->shouldReceive('dispense');
+ $expectation2->atLeast()->once();
+ $expectation2->andReturn($extensionModel);
+
+ /** @var Mockery\Expectation $expectation3 */
+ $expectation3 = $dbMock->shouldReceive('store');
+ $expectation3->atLeast()->once();
+
+ $returnArr = [
+ [
+ 'id' => 2,
+ 'rel_id' => 1,
+ 'meta_value' => 'testValue',
+ ],
+ ];
+ /** @var Mockery\Expectation $expectation4 */
+ $expectation4 = $dbMock->shouldReceive('getAll');
+ $expectation4->atLeast()->once();
+ $expectation4->andReturn($returnArr);
+
+ $activityServiceMock = Mockery::mock(Box\Mod\Activity\Service::class);
+
+ $boxModMock = Mockery::mock(FOSSBilling\Module::class);
+ /** @var Mockery\Expectation $expectation5 */
+ $expectation5 = $boxModMock->shouldReceive('hasService');
+ $expectation5->atLeast()->once();
+ $expectation5->andReturn(true);
+ /** @var Mockery\Expectation $expectation6 */
+ $expectation6 = $boxModMock->shouldReceive('getService');
+ $expectation6->andReturn($activityServiceMock);
+ /** @var Mockery\Expectation $expectation7 */
+ $expectation7 = $boxModMock->shouldReceive('getName');
+ $expectation7->andReturn('activity');
+
+ $extensionServiceMock = Mockery::mock(Box\Mod\Extension\Service::class);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $dbMock->shouldReceive('findOne')
+ ->byDefault()
+ ->andReturn(new Model_Extension());
+ $di['mod'] = $di->protect(fn () => $boxModMock);
+ $di['mod_service'] = $di->protect(function ($name) use ($extensionServiceMock) {
+ if ($name == 'extension') {
+ return $extensionServiceMock;
+ }
+ });
+ $validatorMock = Mockery::mock(FOSSBilling\Validate::class);
+ /** @var Mockery\Expectation $validatorExpectation */
+ $validatorExpectation = $validatorMock->shouldReceive('checkRequiredParamsForArray');
+ $validatorExpectation->atLeast()->once();
+ $di['validator'] = $validatorMock;
+ $service->setDi($di);
+ $result = $service->batchConnect($mod);
+ expect($result)->toBeTrue();
+});
diff --git a/src/modules/Index/tests/Unit/Controller/AdminTest.php b/src/modules/Index/tests/Unit/Controller/AdminTest.php
new file mode 100644
index 000000000..d878b4d3d
--- /dev/null
+++ b/src/modules/Index/tests/Unit/Controller/AdminTest.php
@@ -0,0 +1,54 @@
+setDi($di);
+ $result = $controller->getDi();
+ expect($result)->toBe($di);
+});
+
+test('register registers controller routes', function (): void {
+ $boxAppMock = Mockery::mock('\Box_App');
+ /** @var Mockery\Expectation $expectation */
+ $expectation = $boxAppMock->shouldReceive('get');
+ $expectation->times(4);
+
+ $controller = new Box\Mod\Index\Controller\Admin();
+ $controller->register($boxAppMock);
+});
+
+test('getIndex renders dashboard when admin is logged in', function (): void {
+ $boxAppMock = Mockery::mock('\Box_App');
+ /** @var Mockery\Expectation $expectation1 */
+ $expectation1 = $boxAppMock->shouldReceive('render');
+ $expectation1->atLeast()->once();
+ $expectation1->with('mod_index_dashboard');
+
+ $authorizationMock = Mockery::mock('\Box_Authorization');
+ /** @var Mockery\Expectation $expectation2 */
+ $expectation2 = $authorizationMock->shouldReceive('isAdminLoggedIn');
+ $expectation2->atLeast()->once();
+ $expectation2->andReturn(true);
+
+ $di = container();
+ $di['auth'] = $authorizationMock;
+
+ $controller = new Box\Mod\Index\Controller\Admin();
+ $controller->setDi($di);
+ $controller->get_index($boxAppMock);
+});
diff --git a/src/modules/Invoice/Api/Admin.php b/src/modules/Invoice/Api/Admin.php
index a8e3f176b..c1d5948fa 100644
--- a/src/modules/Invoice/Api/Admin.php
+++ b/src/modules/Invoice/Api/Admin.php
@@ -30,13 +30,13 @@ class Admin extends \Api_Abstract
*/
public function get_list($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'view');
$service = $this->getService();
[$sql, $params] = $service->getSearchQuery($data);
- $pager = $this->di['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
+ $pager = $this->getDi()['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
foreach ($pager['list'] as $key => $item) {
- $invoice = $this->di['db']->getExistingModelById('Invoice', $item['id'], 'Invoice not found');
+ $invoice = $this->getDi()['db']->getExistingModelById('Invoice', $item['id'], 'Invoice not found');
$pager['list'][$key] = $this->getService()->toApiArray($invoice, true, $this->getIdentity());
}
@@ -50,7 +50,7 @@ class Admin extends \Api_Abstract
*/
public function get($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'view');
$model = $this->_getInvoice($data);
@@ -69,7 +69,7 @@ class Admin extends \Api_Abstract
*/
public function mark_as_paid($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_invoices');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_invoices');
$invoice = $this->_getInvoice($data);
@@ -92,9 +92,9 @@ class Admin extends \Api_Abstract
#[RequiredParams(['client_id' => 'Client ID is missing'])]
public function prepare($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_invoices');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_invoices');
- $client = $this->di['db']->getExistingModelById('Client', $data['client_id'], 'Client not found');
+ $client = $this->getDi()['db']->getExistingModelById('Client', $data['client_id'], 'Client not found');
$invoice = $this->getService()->prepareInvoice($client, $data);
@@ -108,7 +108,7 @@ class Admin extends \Api_Abstract
*/
public function approve($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_invoices');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_invoices');
$model = $this->_getInvoice($data);
@@ -124,7 +124,7 @@ class Admin extends \Api_Abstract
*/
public function refund($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_invoices');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_invoices');
$model = $this->_getInvoice($data);
$note = $data['note'] ?? null;
@@ -172,7 +172,7 @@ class Admin extends \Api_Abstract
*/
public function update($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_invoices');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_invoices');
$model = $this->_getInvoice($data);
@@ -187,10 +187,10 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Invoice item ID was not passed'])]
public function item_delete($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_invoices');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_invoices');
- $model = $this->di['db']->getExistingModelById('InvoiceItem', $data['id'], 'Invoice item was not found');
- $invoiceItemService = $this->di['mod_service']('Invoice', 'InvoiceItem');
+ $model = $this->getDi()['db']->getExistingModelById('InvoiceItem', $data['id'], 'Invoice item was not found');
+ $invoiceItemService = $this->getDi()['mod_service']('Invoice', 'InvoiceItem');
return $invoiceItemService->remove($model);
}
@@ -202,7 +202,7 @@ class Admin extends \Api_Abstract
*/
public function delete($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_invoices');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_invoices');
$model = $this->_getInvoice($data);
@@ -223,9 +223,9 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Order ID was not passed'])]
public function renewal_invoice($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_invoices');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_invoices');
- $model = $this->di['db']->getExistingModelById('ClientOrder', $data['id'], 'Order not found');
+ $model = $this->getDi()['db']->getExistingModelById('ClientOrder', $data['id'], 'Order not found');
if ($model->price <= 0) {
throw new InformationException('Order :id is free. No need to generate invoice.', [':id' => $model->id]);
}
@@ -243,7 +243,7 @@ class Admin extends \Api_Abstract
*/
public function batch_pay_with_credits($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_invoices', null, $this->identity);
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_invoices', null, $this->identity);
return $this->getService()->doBatchPayWithCredits($data);
}
@@ -255,7 +255,7 @@ class Admin extends \Api_Abstract
*/
public function pay_with_credits($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_invoices');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_invoices');
$invoice = $this->_getInvoice($data);
@@ -269,7 +269,7 @@ class Admin extends \Api_Abstract
*/
public function batch_generate()
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_invoices', null, $this->identity);
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_invoices', null, $this->identity);
return $this->getService()->generateInvoicesForExpiringOrders();
}
@@ -281,7 +281,7 @@ class Admin extends \Api_Abstract
*/
public function batch_activate_paid()
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_invoices', null, $this->identity);
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_invoices', null, $this->identity);
return $this->getService()->doBatchPaidInvoiceActivation();
}
@@ -293,7 +293,7 @@ class Admin extends \Api_Abstract
*/
public function batch_send_reminders($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_invoices', null, $this->identity);
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_invoices', null, $this->identity);
return $this->getService()->doBatchRemindersSend();
}
@@ -311,7 +311,7 @@ class Admin extends \Api_Abstract
*/
public function batch_invoke_due_event($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_invoices', null, $this->identity);
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_invoices', null, $this->identity);
return $this->getService()->doBatchInvokeDueEvent($data);
}
@@ -324,7 +324,7 @@ class Admin extends \Api_Abstract
*/
public function send_reminder($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_invoices');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_invoices');
$invoice = $this->_getInvoice($data);
@@ -338,7 +338,7 @@ class Admin extends \Api_Abstract
*/
public function get_statuses($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'view');
return $this->getService()->counter();
}
@@ -350,9 +350,9 @@ class Admin extends \Api_Abstract
*/
public function transaction_process_all($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_transactions');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_transactions');
- $transactionService = $this->di['mod_service']('Invoice', 'Transaction');
+ $transactionService = $this->getDi()['mod_service']('Invoice', 'Transaction');
return $transactionService->processReceivedATransactions();
}
@@ -363,14 +363,14 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Transaction ID is missing'])]
public function transaction_process($data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_transactions');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_transactions');
- $model = $this->di['db']->getExistingModelById('Transaction', $data['id'], 'Transaction not found');
+ $model = $this->getDi()['db']->getExistingModelById('Transaction', $data['id'], 'Transaction not found');
$output = null;
- $this->di['events_manager']->fire(['event' => 'onBeforeAdminTransactionProcess', 'params' => ['id' => $model->id]]);
+ $this->getDi()['events_manager']->fire(['event' => 'onBeforeAdminTransactionProcess', 'params' => ['id' => $model->id]]);
- $transactionService = $this->di['mod_service']('Invoice', 'Transaction');
+ $transactionService = $this->getDi()['mod_service']('Invoice', 'Transaction');
return $transactionService->preProcessTransaction($model);
}
@@ -394,11 +394,11 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Transaction ID is missing'])]
public function transaction_update($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_transactions');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_transactions');
- $model = $this->di['db']->getExistingModelById('Transaction', $data['id'], 'Transaction not found');
+ $model = $this->getDi()['db']->getExistingModelById('Transaction', $data['id'], 'Transaction not found');
- $transactionService = $this->di['mod_service']('Invoice', 'Transaction');
+ $transactionService = $this->getDi()['mod_service']('Invoice', 'Transaction');
return $transactionService->update($model, $data);
}
@@ -417,9 +417,9 @@ class Admin extends \Api_Abstract
*/
public function transaction_create($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_transactions');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_transactions');
- $transactionService = $this->di['mod_service']('Invoice', 'Transaction');
+ $transactionService = $this->getDi()['mod_service']('Invoice', 'Transaction');
$data['source'] ??= 'admin';
return $transactionService->create($data);
@@ -433,11 +433,11 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Transaction ID is missing'])]
public function transaction_delete($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_transactions');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_transactions');
- $model = $this->di['db']->getExistingModelById('Transaction', $data['id'], 'Transaction not found');
+ $model = $this->getDi()['db']->getExistingModelById('Transaction', $data['id'], 'Transaction not found');
- $transactionService = $this->di['mod_service']('Invoice', 'Transaction');
+ $transactionService = $this->getDi()['mod_service']('Invoice', 'Transaction');
return $transactionService->delete($model);
}
@@ -450,11 +450,11 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Transaction ID is missing'])]
public function transaction_get($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_transactions');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_transactions');
- $model = $this->di['db']->getExistingModelById('Transaction', $data['id'], 'Transaction not found');
+ $model = $this->getDi()['db']->getExistingModelById('Transaction', $data['id'], 'Transaction not found');
- $transactionService = $this->di['mod_service']('Invoice', 'Transaction');
+ $transactionService = $this->getDi()['mod_service']('Invoice', 'Transaction');
return $transactionService->toApiArray($model, true);
}
@@ -468,15 +468,15 @@ class Admin extends \Api_Abstract
*/
public function transaction_get_list($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_transactions');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_transactions');
- $transactionService = $this->di['mod_service']('Invoice', 'Transaction');
+ $transactionService = $this->getDi()['mod_service']('Invoice', 'Transaction');
[$sql, $params] = $transactionService->getSearchQuery($data);
- $pager = $this->di['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
+ $pager = $this->getDi()['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
foreach ($pager['list'] as $key => $item) {
- $transaction = $this->di['db']->getExistingModelById('Transaction', $item['id'], 'Transaction not found');
+ $transaction = $this->getDi()['db']->getExistingModelById('Transaction', $item['id'], 'Transaction not found');
$pager['list'][$key] = $transactionService->toApiArray($transaction);
}
@@ -490,9 +490,9 @@ class Admin extends \Api_Abstract
*/
public function transaction_get_statuses($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'view');
- $transactionService = $this->di['mod_service']('Invoice', 'Transaction');
+ $transactionService = $this->getDi()['mod_service']('Invoice', 'Transaction');
return $transactionService->counter();
}
@@ -504,9 +504,9 @@ class Admin extends \Api_Abstract
*/
public function transaction_get_statuses_pairs($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'view');
- $transactionService = $this->di['mod_service']('Invoice', 'Transaction');
+ $transactionService = $this->getDi()['mod_service']('Invoice', 'Transaction');
return $transactionService->getStatusPairs();
}
@@ -518,9 +518,9 @@ class Admin extends \Api_Abstract
*/
public function transaction_statuses($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'view');
- $transactionService = $this->di['mod_service']('Invoice', 'Transaction');
+ $transactionService = $this->getDi()['mod_service']('Invoice', 'Transaction');
return $transactionService->getStatuses();
}
@@ -532,9 +532,9 @@ class Admin extends \Api_Abstract
*/
public function transaction_gateway_statuses($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'view');
- $transactionService = $this->di['mod_service']('Invoice', 'Transaction');
+ $transactionService = $this->getDi()['mod_service']('Invoice', 'Transaction');
return $transactionService->getGatewayStatuses();
}
@@ -546,9 +546,9 @@ class Admin extends \Api_Abstract
*/
public function transaction_types($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'view');
- $transactionService = $this->di['mod_service']('Invoice', 'Transaction');
+ $transactionService = $this->getDi()['mod_service']('Invoice', 'Transaction');
return $transactionService->getTypes();
}
@@ -566,14 +566,14 @@ class Admin extends \Api_Abstract
*/
public function transaction_claim_for_processing($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_transactions');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_transactions');
$required = [
'id' => 'Transaction ID is required',
];
- $this->di['validator']->checkRequiredParamsForArray($required, $data);
+ $this->getDi()['validator']->checkRequiredParamsForArray($required, $data);
- $transactionService = $this->di['mod_service']('Invoice', 'Transaction');
+ $transactionService = $this->getDi()['mod_service']('Invoice', 'Transaction');
return $transactionService->claimForProcessing((int) $data['id']);
}
@@ -585,15 +585,15 @@ class Admin extends \Api_Abstract
*/
public function gateway_get_list($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_gateways');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_gateways');
- $gatewayService = $this->di['mod_service']('Invoice', 'PayGateway');
+ $gatewayService = $this->getDi()['mod_service']('Invoice', 'PayGateway');
[$sql, $params] = $gatewayService->getSearchQuery($data);
- $pager = $this->di['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
+ $pager = $this->getDi()['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
foreach ($pager['list'] as $key => $item) {
- $gateway = $this->di['db']->getExistingModelById('PayGateway', $item['id'], 'Gateway not found');
+ $gateway = $this->getDi()['db']->getExistingModelById('PayGateway', $item['id'], 'Gateway not found');
$pager['list'][$key] = $gatewayService->toApiArray($gateway, false, $this->getIdentity());
}
@@ -607,9 +607,9 @@ class Admin extends \Api_Abstract
*/
public function gateway_get_pairs($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_gateways');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_gateways');
- $gatewayService = $this->di['mod_service']('Invoice', 'PayGateway');
+ $gatewayService = $this->getDi()['mod_service']('Invoice', 'PayGateway');
return $gatewayService->getPairs();
}
@@ -621,9 +621,9 @@ class Admin extends \Api_Abstract
*/
public function gateway_get_available(array $data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_gateways');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_gateways');
- $gatewayService = $this->di['mod_service']('Invoice', 'PayGateway');
+ $gatewayService = $this->getDi()['mod_service']('Invoice', 'PayGateway');
return $gatewayService->getAvailable();
}
@@ -636,10 +636,10 @@ class Admin extends \Api_Abstract
#[RequiredParams(['code' => 'Payment gateway code is missing'])]
public function gateway_install(array $data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_gateways');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_gateways');
$code = $data['code'];
- $gatewayService = $this->di['mod_service']('Invoice', 'PayGateway');
+ $gatewayService = $this->getDi()['mod_service']('Invoice', 'PayGateway');
return $gatewayService->install($code);
}
@@ -654,11 +654,11 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Gateway ID was not passed'])]
public function gateway_get($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_gateways');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_gateways');
- $model = $this->di['db']->getExistingModelById('PayGateway', $data['id'], 'Gateway not found');
+ $model = $this->getDi()['db']->getExistingModelById('PayGateway', $data['id'], 'Gateway not found');
- $gatewayService = $this->di['mod_service']('Invoice', 'PayGateway');
+ $gatewayService = $this->getDi()['mod_service']('Invoice', 'PayGateway');
return $gatewayService->toApiArray($model, true, $this->getIdentity());
}
@@ -671,10 +671,10 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Gateway ID was not passed'])]
public function gateway_copy($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_gateways');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_gateways');
- $model = $this->di['db']->getExistingModelById('PayGateway', $data['id'], 'Gateway not found');
- $gatewayService = $this->di['mod_service']('Invoice', 'PayGateway');
+ $model = $this->getDi()['db']->getExistingModelById('PayGateway', $data['id'], 'Gateway not found');
+ $gatewayService = $this->getDi()['mod_service']('Invoice', 'PayGateway');
return $gatewayService->copy($model);
}
@@ -697,10 +697,10 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Gateway ID was not passed'])]
public function gateway_update($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_gateways');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_gateways');
- $model = $this->di['db']->getExistingModelById('PayGateway', $data['id'], 'Gateway not found');
- $gatewayService = $this->di['mod_service']('Invoice', 'PayGateway');
+ $model = $this->getDi()['db']->getExistingModelById('PayGateway', $data['id'], 'Gateway not found');
+ $gatewayService = $this->getDi()['mod_service']('Invoice', 'PayGateway');
return $gatewayService->update($model, $data);
}
@@ -715,10 +715,10 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Gateway ID was not passed'])]
public function gateway_delete($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_gateways');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_gateways');
- $model = $this->di['db']->getExistingModelById('PayGateway', $data['id'], 'Gateway not found');
- $gatewayService = $this->di['mod_service']('Invoice', 'PayGateway');
+ $model = $this->getDi()['db']->getExistingModelById('PayGateway', $data['id'], 'Gateway not found');
+ $gatewayService = $this->getDi()['mod_service']('Invoice', 'PayGateway');
return $gatewayService->delete($model);
}
@@ -730,16 +730,16 @@ class Admin extends \Api_Abstract
*/
public function subscription_get_list($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_subscriptions');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_subscriptions');
- $subscriptionService = $this->di['mod_service']('Invoice', 'Subscription');
+ $subscriptionService = $this->getDi()['mod_service']('Invoice', 'Subscription');
[$sql, $params] = $subscriptionService->getSearchQuery($data);
- $pager = $this->di['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
+ $pager = $this->getDi()['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
if (isset($pager['list']) && is_array($pager['list'])) {
foreach ($pager['list'] as $key => $item) {
- $subscription = $this->di['db']->getExistingModelById('Subscription', $item['id'], 'Subscription not found');
+ $subscription = $this->getDi()['db']->getExistingModelById('Subscription', $item['id'], 'Subscription not found');
$pager['list'][$key] = $subscriptionService->toApiArray($subscription);
}
}
@@ -768,15 +768,15 @@ class Admin extends \Api_Abstract
])]
public function subscription_create($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_subscriptions');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_subscriptions');
- $client = $this->di['db']->getExistingModelById('Client', $data['client_id'], 'Client not found');
- $payGateway = $this->di['db']->getExistingModelById('PayGateway', $data['gateway_id'], 'Payment gateway not found');
+ $client = $this->getDi()['db']->getExistingModelById('Client', $data['client_id'], 'Client not found');
+ $payGateway = $this->getDi()['db']->getExistingModelById('PayGateway', $data['gateway_id'], 'Payment gateway not found');
if ($client->currency != $data['currency']) {
throw new InformationException('Client currency must match subscription currency. Check if clients currency is defined.');
}
- $subscriptionService = $this->di['mod_service']('Invoice', 'Subscription');
+ $subscriptionService = $this->getDi()['mod_service']('Invoice', 'Subscription');
return $subscriptionService->create($client, $payGateway, $data);
}
@@ -797,10 +797,10 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Subscription ID was not passed'])]
public function subscription_update($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_subscriptions');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_subscriptions');
- $model = $this->di['db']->getExistingModelById('Subscription', $data['id'], 'Subscription not found');
- $subscriptionService = $this->di['mod_service']('Invoice', 'Subscription');
+ $model = $this->getDi()['db']->getExistingModelById('Subscription', $data['id'], 'Subscription not found');
+ $subscriptionService = $this->getDi()['mod_service']('Invoice', 'Subscription');
return $subscriptionService->update($model, $data);
}
@@ -814,29 +814,29 @@ class Admin extends \Api_Abstract
*/
public function subscription_get($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_subscriptions');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_subscriptions');
if (!isset($data['id']) && !isset($data['sid'])) {
$required = [
'id' => 'Subscription ID was not passed',
'sid' => 'Subscription sID was not passed',
];
- $this->di['validator']->checkRequiredParamsForArray($required, $data);
+ $this->getDi()['validator']->checkRequiredParamsForArray($required, $data);
}
$model = null;
if (isset($data['id'])) {
- $model = $this->di['db']->load('Subscription', $data['id']);
+ $model = $this->getDi()['db']->load('Subscription', $data['id']);
}
if (!$model && isset($data['sid'])) {
- $model = $this->di['db']->findOne('Subscription', 'sid = ?', [$data['sid']]);
+ $model = $this->getDi()['db']->findOne('Subscription', 'sid = ?', [$data['sid']]);
}
if (!$model instanceof \Model_Subscription) {
throw new \FOSSBilling\Exception('Subscription not found');
}
- $subscriptionService = $this->di['mod_service']('Invoice', 'Subscription');
+ $subscriptionService = $this->getDi()['mod_service']('Invoice', 'Subscription');
return $subscriptionService->toApiArray($model, true, $this->getIdentity());
}
@@ -851,10 +851,10 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Subscription ID was not passed'])]
public function subscription_delete($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_subscriptions');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_subscriptions');
- $model = $this->di['db']->getExistingModelById('Subscription', $data['id'], 'Subscription not found');
- $subscriptionService = $this->di['mod_service']('Invoice', 'Subscription');
+ $model = $this->getDi()['db']->getExistingModelById('Subscription', $data['id'], 'Subscription not found');
+ $subscriptionService = $this->getDi()['mod_service']('Invoice', 'Subscription');
return $subscriptionService->delete($model);
}
@@ -869,10 +869,10 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Tax ID was not passed'])]
public function tax_delete($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_tax');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_tax');
- $model = $this->di['db']->getExistingModelById('Tax', $data['id'], 'Tax rule not found');
- $taxService = $this->di['mod_service']('Invoice', 'Tax');
+ $model = $this->getDi()['db']->getExistingModelById('Tax', $data['id'], 'Tax rule not found');
+ $taxService = $this->getDi()['mod_service']('Invoice', 'Tax');
return $taxService->delete($model);
}
@@ -888,9 +888,9 @@ class Admin extends \Api_Abstract
])]
public function tax_create($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_tax');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_tax');
- $taxService = $this->di['mod_service']('Invoice', 'Tax');
+ $taxService = $this->getDi()['mod_service']('Invoice', 'Tax');
return $taxService->create($data);
}
@@ -903,11 +903,11 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Tax ID was not passed'])]
public function tax_get($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_tax');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_tax');
- $tax = $this->di['db']->getExistingModelById('Tax', $data['id'], 'Tax rule not found');
+ $tax = $this->getDi()['db']->getExistingModelById('Tax', $data['id'], 'Tax rule not found');
- $taxService = $this->di['mod_service']('Invoice', 'Tax');
+ $taxService = $this->getDi()['mod_service']('Invoice', 'Tax');
return $taxService->toApiArray($tax);
}
@@ -924,11 +924,11 @@ class Admin extends \Api_Abstract
])]
public function tax_update($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_tax');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_tax');
- $tax = $this->di['db']->getExistingModelById('Tax', $data['id'], 'Tax rule not found');
+ $tax = $this->getDi()['db']->getExistingModelById('Tax', $data['id'], 'Tax rule not found');
- $taxService = $this->di['mod_service']('Invoice', 'Tax');
+ $taxService = $this->getDi()['mod_service']('Invoice', 'Tax');
return $taxService->update($tax, $data);
}
@@ -940,12 +940,12 @@ class Admin extends \Api_Abstract
*/
public function tax_get_list($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_tax');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_tax');
- $taxService = $this->di['mod_service']('Invoice', 'Tax');
+ $taxService = $this->getDi()['mod_service']('Invoice', 'Tax');
[$sql, $params] = $taxService->getSearchQuery($data);
- return $this->di['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
+ return $this->getDi()['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
}
/**
@@ -957,9 +957,9 @@ class Admin extends \Api_Abstract
*/
public function tax_setup_eu($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_tax');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_tax');
- $taxService = $this->di['mod_service']('Invoice', 'Tax');
+ $taxService = $this->getDi()['mod_service']('Invoice', 'Tax');
return $taxService->setupEUTaxes($data);
}
@@ -967,7 +967,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Invoice ID was not passed'])]
private function _getInvoice($data)
{
- return $this->di['db']->getExistingModelById('Invoice', $data['id'], 'Invoice was not found');
+ return $this->getDi()['db']->getExistingModelById('Invoice', $data['id'], 'Invoice was not found');
}
/**
@@ -976,7 +976,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['ids' => 'IDs were not passed'])]
public function batch_delete($data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_invoices');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_invoices');
foreach ($data['ids'] as $id) {
$this->delete(['id' => $id]);
@@ -991,7 +991,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['ids' => 'IDs were not passed'])]
public function batch_delete_subscription($data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_subscriptions');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_subscriptions');
foreach ($data['ids'] as $id) {
$this->subscription_delete(['id' => $id]);
@@ -1006,7 +1006,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['ids' => 'IDs were not passed'])]
public function batch_delete_transaction($data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_transactions');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_transactions');
foreach ($data['ids'] as $id) {
$this->transaction_delete(['id' => $id]);
@@ -1021,7 +1021,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['ids' => 'IDs were not passed'])]
public function batch_delete_tax($data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_tax');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'manage_tax');
foreach ($data['ids'] as $id) {
$this->tax_delete(['id' => $id]);
@@ -1032,7 +1032,7 @@ class Admin extends \Api_Abstract
public function export_csv($data): Response
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'export');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('invoice', 'export');
$data['headers'] ??= [];
diff --git a/src/modules/Invoice/Api/Client.php b/src/modules/Invoice/Api/Client.php
index 170302adb..70cbd48cb 100644
--- a/src/modules/Invoice/Api/Client.php
+++ b/src/modules/Invoice/Api/Client.php
@@ -32,10 +32,10 @@ class Client extends \Api_Abstract
$data['approved'] = true;
[$sql, $params] = $this->getService()->getSearchQuery($data);
- $pager = $this->di['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
+ $pager = $this->getDi()['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
foreach ($pager['list'] as $key => $item) {
- $invoice = $this->di['db']->getExistingModelById('Invoice', $item['id'], 'Invoice not found');
+ $invoice = $this->getDi()['db']->getExistingModelById('Invoice', $item['id'], 'Invoice not found');
$pager['list'][$key] = $this->getService()->toApiArray($invoice);
}
@@ -53,7 +53,7 @@ class Client extends \Api_Abstract
public function get($data)
{
$identity = $this->getIdentity();
- $model = $this->di['db']->findOne('Invoice', 'hash = :hash AND client_id = :client_id', ['hash' => $data['hash'], 'client_id' => $identity->id]);
+ $model = $this->getDi()['db']->findOne('Invoice', 'hash = :hash AND client_id = :client_id', ['hash' => $data['hash'], 'client_id' => $identity->id]);
if (!$model) {
throw new \FOSSBilling\Exception('Invoice was not found');
}
@@ -73,7 +73,7 @@ class Client extends \Api_Abstract
#[RequiredParams(['order_id' => 'Order ID (order_id) was not passed'])]
public function renewal_invoice($data)
{
- $model = $this->di['db']->findOne('ClientOrder', 'client_id = ? and id = ?', [$this->getIdentity()->id, $data['order_id']]);
+ $model = $this->getDi()['db']->findOne('ClientOrder', 'client_id = ? and id = ?', [$this->getIdentity()->id, $data['order_id']]);
if (!$model instanceof \Model_ClientOrder) {
throw new \FOSSBilling\Exception('Order not found');
}
@@ -83,7 +83,7 @@ class Client extends \Api_Abstract
$service = $this->getService();
$invoice = $service->generateForOrder($model);
$service->approveInvoice($invoice, ['id' => $invoice->id, 'use_credits' => true]);
- $this->di['logger']->info('Generated new renewal invoice #%s', $invoice->id);
+ $this->getDi()['logger']->info('Generated new renewal invoice #%s', $invoice->id);
return $invoice->hash;
}
@@ -104,7 +104,7 @@ class Client extends \Api_Abstract
$service = $this->getService();
$invoice = $service->generateFundsInvoice($this->getIdentity(), $data['amount']);
$service->approveInvoice($invoice, ['id' => $invoice->id]);
- $this->di['logger']->info('Generated add funds invoice #%s', $invoice->id);
+ $this->getDi()['logger']->info('Generated add funds invoice #%s', $invoice->id);
return $invoice->hash;
}
@@ -125,13 +125,13 @@ class Client extends \Api_Abstract
{
$data['client_id'] = $this->getIdentity()->id;
$data['status'] = 'processed';
- $transactionService = $this->di['mod_service']('Invoice', 'Transaction');
+ $transactionService = $this->getDi()['mod_service']('Invoice', 'Transaction');
[$sql, $params] = $transactionService->getSearchQuery($data);
- $pager = $this->di['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
+ $pager = $this->getDi()['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
foreach ($pager['list'] as $key => $item) {
- $transaction = $this->di['db']->getExistingModelById('Transaction', $item['id'], 'Transaction not found');
+ $transaction = $this->getDi()['db']->getExistingModelById('Transaction', $item['id'], 'Transaction not found');
$pager['list'][$key] = $transactionService->toApiArray($transaction);
}
@@ -140,7 +140,7 @@ class Client extends \Api_Abstract
public function get_tax_rate()
{
- $service = $this->di['mod_service']('Invoice', 'Tax');
+ $service = $this->getDi()['mod_service']('Invoice', 'Tax');
return $service->getTaxRateForClient($this->identity);
}
diff --git a/src/modules/Invoice/Api/Guest.php b/src/modules/Invoice/Api/Guest.php
index ac1906d91..fcd7fc6e1 100644
--- a/src/modules/Invoice/Api/Guest.php
+++ b/src/modules/Invoice/Api/Guest.php
@@ -35,10 +35,10 @@ class Guest extends \Api_Abstract
throw new \FOSSBilling\Exception('Invalid invoice hash', null, 4001);
}
- $this->di['rate_limiter']->consumeOrThrow('invoice_get_ip', (string) $this->getIp());
- $this->di['rate_limiter']->consumeOrThrow('invoice_get_hash', (string) $data['hash']);
+ $this->getDi()['rate_limiter']->consumeOrThrow('invoice_get_ip', (string) $this->getIp());
+ $this->getDi()['rate_limiter']->consumeOrThrow('invoice_get_hash', (string) $data['hash']);
- $model = $this->di['db']->findOne('Invoice', 'hash = :hash', ['hash' => $data['hash']]);
+ $model = $this->getDi()['db']->findOne('Invoice', 'hash = :hash', ['hash' => $data['hash']]);
if (!$model) {
throw new \FOSSBilling\Exception('Invoice was not found');
}
@@ -57,7 +57,7 @@ class Guest extends \Api_Abstract
*/
public function gateways($data)
{
- $gatewayService = $this->di['mod_service']('Invoice', 'PayGateway');
+ $gatewayService = $this->getDi()['mod_service']('Invoice', 'PayGateway');
return $gatewayService->getActive($data);
}
@@ -90,8 +90,8 @@ class Guest extends \Api_Abstract
throw new \FOSSBilling\Exception('Payment method not found. Missing param gateway_id', null, 811);
}
- $this->di['rate_limiter']->consumeOrThrow('invoice_payment_ip', (string) $this->getIp());
- $this->di['rate_limiter']->consumeOrThrow('invoice_payment_hash', (string) $data['hash']);
+ $this->getDi()['rate_limiter']->consumeOrThrow('invoice_payment_ip', (string) $this->getIp());
+ $this->getDi()['rate_limiter']->consumeOrThrow('invoice_payment_hash', (string) $data['hash']);
return $this->getService()->processInvoice($data);
}
@@ -108,8 +108,8 @@ class Guest extends \Api_Abstract
throw new \FOSSBilling\Exception('Invalid invoice hash', null, 4001);
}
- $this->di['rate_limiter']->consumeOrThrow('invoice_pdf_ip', (string) $this->getIp());
- $this->di['rate_limiter']->consumeOrThrow('invoice_pdf_hash', (string) $data['hash']);
+ $this->getDi()['rate_limiter']->consumeOrThrow('invoice_pdf_ip', (string) $this->getIp());
+ $this->getDi()['rate_limiter']->consumeOrThrow('invoice_pdf_hash', (string) $data['hash']);
return $this->getService()->generatePDF($data['hash'], $this->getIdentity());
}
diff --git a/src/modules/Invoice/Service.php b/src/modules/Invoice/Service.php
index 577e5f545..58c29ce9c 100644
--- a/src/modules/Invoice/Service.php
+++ b/src/modules/Invoice/Service.php
@@ -408,6 +408,28 @@ class Service implements InjectionAwareInterface
return true;
}
+ public static function onAfterInvoiceCreate(\Box_Event $event): bool
+ {
+ $params = $event->getParameters();
+ $di = $event->getDi();
+ $service = $di['mod_service']('invoice');
+
+ try {
+ $invoiceModel = $di['db']->load('Invoice', $params['id']);
+ $invoice = $service->toApiArray($invoiceModel, true);
+ $email = [];
+ $email['to_client'] = $invoiceModel->client_id;
+ $email['code'] = 'mod_invoice_created';
+ $email['invoice'] = $invoice;
+ $emailService = $di['mod_service']('Email');
+ $emailService->sendTemplate($email);
+ } catch (\Exception $exc) {
+ error_log($exc->getMessage());
+ }
+
+ return true;
+ }
+
public static function onAfterAdminInvoiceApprove(\Box_Event $event): bool
{
$params = $event->getParameters();
@@ -679,7 +701,7 @@ class Service implements InjectionAwareInterface
$currencyCode = $currency->getCode();
$client->currency = $currencyCode;
$this->di['db']->store($client);
- error_log("Client #{$client->id} currency was not defined. Set default currency {$currencyCode}.");
+ $this->di['logger']->warning("Client #{$client->id} currency was not defined. Set default currency {$currencyCode}.");
}
$model = $this->di['db']->dispense('Invoice');
@@ -817,6 +839,7 @@ class Service implements InjectionAwareInterface
$epsilon = 0.01;
if (abs($balance - $required) < $epsilon || $balance - $required > 0.00001) {
+ // @phpstan-ignore if.alwaysFalse
if (DEBUG) {
$this->di['logger']->setChannel('billing')->info("Setting invoice {$invoice->id} as paid with credits for the amount of {$required}.");
}
@@ -838,7 +861,7 @@ class Service implements InjectionAwareInterface
return true;
}
-
+ // @phpstan-ignore if.alwaysFalse (DEBUG is a runtime constant that may be true during debugging)
if (DEBUG) {
$this->di['logger']->setChannel('billing')->info("Invoice {$invoice->id} could not be paid with credits. Money in balance {$balance} Required: {$required}.");
}
@@ -981,6 +1004,7 @@ class Service implements InjectionAwareInterface
break;
case 'manual':
+ // @phpstan-ignore if.alwaysFalse
if (DEBUG) {
error_log('Refunds are managed manually. No actions performed.');
}
@@ -1142,6 +1166,7 @@ class Service implements InjectionAwareInterface
$model = $this->di['db']->getExistingModelById('Invoice', $proforma['id'] ?? null);
$this->tryPayWithCredits($model);
} catch (\Exception $e) {
+ // @phpstan-ignore if.alwaysFalse
if (DEBUG) {
error_log($e->getMessage());
}
@@ -1275,7 +1300,7 @@ class Service implements InjectionAwareInterface
$model = $this->di['db']->getExistingModelById('InvoiceItem', $item['id'] ?? 0);
$invoiceItemService->executeTask($model);
} catch (\Exception $e) {
- error_log($e->getMessage());
+ $this->di['logger']->error($e->getMessage());
}
}
$this->di['logger']->info('Executed action to activate paid invoices.');
diff --git a/src/modules/Invoice/ServicePayGateway.php b/src/modules/Invoice/ServicePayGateway.php
index 6ed3939c5..f7ab5bea6 100644
--- a/src/modules/Invoice/ServicePayGateway.php
+++ b/src/modules/Invoice/ServicePayGateway.php
@@ -22,11 +22,9 @@ use Symfony\Component\Finder\Finder;
class ServicePayGateway implements InjectionAwareInterface
{
protected ?\Pimple\Container $di = null;
- private readonly Filesystem $filesystem;
- public function __construct()
+ public function __construct(private readonly ?Filesystem $filesystem = new Filesystem())
{
- $this->filesystem = new Filesystem();
}
public function setDi(\Pimple\Container $di): void
@@ -401,6 +399,7 @@ class ServicePayGateway implements InjectionAwareInterface
return [];
}
+ // @phpstan-ignore argument.type
return call_user_func([$class, 'getConfig']);
}
diff --git a/src/modules/Invoice/tests/Unit/Api/AdminTest.php b/src/modules/Invoice/tests/Unit/Api/AdminTest.php
new file mode 100644
index 000000000..b2d6b172b
--- /dev/null
+++ b/src/modules/Invoice/tests/Unit/Api/AdminTest.php
@@ -0,0 +1,1269 @@
+setDi($di);
+ $getDi = $api->getDi();
+ expect($getDi)->toBe($di);
+});
+
+test('gets invoice list', function (): void {
+ $api = new Admin();
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('getSearchQuery')
+ ->atLeast()->once()
+ ->andReturn(['SqlString', []]);
+
+ $paginatorMock = Mockery::mock(FOSSBilling\Pagination::class);
+ $paginatorMock->shouldReceive('getDefaultPerPage')
+ ->byDefault()
+ ->andReturn(25);
+ $paginatorMock->shouldReceive('getPaginatedResultSet')
+ ->atLeast()->once()
+ ->andReturn(['list' => []]);
+
+ $di = container();
+ $di['pager'] = $paginatorMock;
+
+ $api->setDi($di);
+ $api->setService($serviceMock);
+ $result = $api->get_list([]);
+ expect($result)->toBeArray();
+});
+
+test('gets an invoice', function (): void {
+ $api = new Admin();
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('toApiArray')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $model = new Model_Invoice();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $api->setDi($di);
+ $api->setService($serviceMock);
+ $api->setIdentity(new Model_Admin());
+
+ $data['id'] = 1;
+ $result = $api->get($data);
+ expect($result)->toBeArray();
+});
+
+test('marks invoice as paid', function (): void {
+ $api = new Admin();
+ $data = [
+ 'id' => 1,
+ 'execute' => true,
+ ];
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('markAsPaidByAdmin')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $gatewayServiceMock = Mockery::mock(ServicePayGateway::class);
+ $gatewayServiceMock->shouldReceive('toApiArray')
+ ->byDefault()
+ ->andReturn(['code' => 'PayPal', 'enabled' => 1]);
+
+ $invoiceModel = new Model_Invoice();
+ $invoiceModel->loadBean(new Tests\Helpers\DummyBean());
+ $invoiceModel->gateway_id = '1';
+
+ $gatewayModel = new Model_PayGateway();
+ $gatewayModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturnUsing(function ($type) use ($invoiceModel, $gatewayModel) {
+ if ($type === 'PayGateway') {
+ return $gatewayModel;
+ }
+
+ return $invoiceModel;
+ });
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(moduleService([
+ 'invoice' => $serviceMock,
+ 'invoice:paygateway' => $gatewayServiceMock,
+ ]));
+ $api->setDi($di);
+ $api->setService($serviceMock);
+
+ $result = $api->mark_as_paid($data);
+ expect($result)->toBeTrue();
+});
+
+test('prepares an invoice', function (): void {
+ $api = new Admin();
+ $data = [
+ 'client_id' => 1,
+ ];
+ $newInvoiceId = 1;
+
+ $invoiceModel = new Model_Invoice();
+ $invoiceModel->loadBean(new Tests\Helpers\DummyBean());
+ $invoiceModel->id = $newInvoiceId;
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('prepareInvoice')
+ ->atLeast()->once()
+ ->andReturn($invoiceModel);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $model = new Model_Client();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $api->setDi($di);
+ $api->setService($serviceMock);
+
+ $result = $api->prepare($data);
+ expect($result)->toBeInt()->toBe($newInvoiceId);
+});
+
+test('approves an invoice', function (): void {
+ $api = new Admin();
+ $data = [
+ 'id' => 1,
+ ];
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('approveInvoice')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $model = new Model_Invoice();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $api->setDi($di);
+ $api->setService($serviceMock);
+
+ $result = $api->approve($data);
+ expect($result)->toBeBool()->toBeTrue();
+});
+
+test('refunds an invoice', function (): void {
+ $api = new Admin();
+ $data = [
+ 'id' => 1,
+ ];
+ $newNegativeInvoiceId = 2;
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('refundInvoice')
+ ->atLeast()->once()
+ ->andReturn($newNegativeInvoiceId);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $model = new Model_Invoice();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $api->setDi($di);
+ $api->setService($serviceMock);
+
+ $result = $api->refund($data);
+ expect($result)->toBeInt()->toBe($newNegativeInvoiceId);
+});
+
+test('updates an invoice', function (): void {
+ $api = new Admin();
+ $data = [
+ 'id' => 1,
+ ];
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('updateInvoice')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $model = new Model_Invoice();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $api->setDi($di);
+ $api->setService($serviceMock);
+
+ $result = $api->update($data);
+ expect($result)->toBeBool()->toBeTrue();
+});
+
+test('deletes an invoice item', function (): void {
+ $api = new Admin();
+ $data = [
+ 'id' => 1,
+ ];
+
+ $invoiceItemService = Mockery::mock(Box\Mod\Invoice\ServiceInvoiceItem::class);
+ $invoiceItemService->shouldReceive('remove')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $model = new Model_InvoiceItem();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(moduleService(['invoice:invoiceitem' => $invoiceItemService]));
+
+ $api->setDi($di);
+
+ $result = $api->item_delete($data);
+ expect($result)->toBeBool()->toBeTrue();
+});
+
+test('deletes an invoice', function (): void {
+ $api = new Admin();
+ $data = [
+ 'id' => 1,
+ ];
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('deleteInvoiceByAdmin')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $model = new Model_Invoice();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $api->setDi($di);
+ $api->setService($serviceMock);
+
+ $result = $api->delete($data);
+ expect($result)->toBeBool()->toBeTrue();
+});
+
+test('creates renewal invoice', function (): void {
+ $api = new Admin();
+ $data = [
+ 'id' => 1,
+ ];
+ $newInvoiceId = 3;
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('renewInvoice')
+ ->atLeast()->once()
+ ->andReturn($newInvoiceId);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $model = new Model_ClientOrder();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $model->price = 10;
+ $dbMock->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $api->setDi($di);
+ $api->setService($serviceMock);
+
+ $result = $api->renewal_invoice($data);
+ expect($result)->toBeInt()->toBe($newInvoiceId);
+});
+
+test('throws exception when creating renewal invoice for free order', function (): void {
+ $api = new Admin();
+ $data = [
+ 'id' => 1,
+ ];
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $model = new Model_ClientOrder();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $model->id = 1;
+ $model->price = 0;
+ $dbMock->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $api->setDi($di);
+
+ expect(fn () => $api->renewal_invoice($data))
+ ->toThrow(FOSSBilling\Exception::class, sprintf('Order %d is free. No need to generate invoice.', $model->id));
+});
+
+test('processes batch pay with credits', function (): void {
+ $api = new Admin();
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('doBatchPayWithCredits')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $api->setService($serviceMock);
+
+ $result = $api->batch_pay_with_credits([]);
+ expect($result)->toBeBool()->toBeTrue();
+});
+
+test('pays invoice with credits', function (): void {
+ $api = new Admin();
+ $data = [
+ 'id' => 1,
+ ];
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('payInvoiceWithCredits')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $model = new Model_Invoice();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $api->setDi($di);
+ $api->setService($serviceMock);
+
+ $result = $api->pay_with_credits($data);
+ expect($result)->toBeBool()->toBeTrue();
+});
+
+test('generates batch invoices', function (): void {
+ $api = new Admin();
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('generateInvoicesForExpiringOrders')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $api->setService($serviceMock);
+
+ $result = $api->batch_generate();
+ expect($result)->toBeBool()->toBeTrue();
+});
+
+test('activates paid invoices in batch', function (): void {
+ $api = new Admin();
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('doBatchPaidInvoiceActivation')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $api->setService($serviceMock);
+
+ $result = $api->batch_activate_paid();
+ expect($result)->toBeBool()->toBeTrue();
+});
+
+test('sends reminders in batch', function (): void {
+ $api = new Admin();
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('doBatchRemindersSend')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $api->setService($serviceMock);
+
+ $result = $api->batch_send_reminders([]);
+ expect($result)->toBeBool()->toBeTrue();
+});
+
+test('invokes due event in batch', function (): void {
+ $api = new Admin();
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('doBatchInvokeDueEvent')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $api->setService($serviceMock);
+
+ $result = $api->batch_invoke_due_event([]);
+ expect($result)->toBeBool()->toBeTrue();
+});
+
+test('sends reminder for an invoice', function (): void {
+ $api = new Admin();
+ $data = [
+ 'id' => 1,
+ ];
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('sendInvoiceReminder')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $model = new Model_Invoice();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $api->setDi($di);
+ $api->setService($serviceMock);
+
+ $result = $api->send_reminder($data);
+ expect($result)->toBeBool()->toBeTrue();
+});
+
+test('gets invoice statuses', function (): void {
+ $api = new Admin();
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('counter')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $api->setService($serviceMock);
+
+ $result = $api->get_statuses([]);
+ expect($result)->toBeArray();
+});
+
+test('processes all transactions', function (): void {
+ $api = new Admin();
+ $transactionService = Mockery::mock(ServiceTransaction::class);
+ $transactionService->shouldReceive('processReceivedATransactions')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(moduleService(['invoice:transaction' => $transactionService]));
+
+ $api->setDi($di);
+ $result = $api->transaction_process_all([]);
+ expect($result)->toBeBool()->toBeTrue();
+});
+
+test('processes a transaction', function (): void {
+ $api = new Admin();
+ $data = [
+ 'id' => 1,
+ ];
+
+ $transactionService = Mockery::mock(ServiceTransaction::class);
+ $transactionService->shouldReceive('preProcessTransaction')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $model = new Model_Transaction();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $eventsMock = Mockery::mock('\Box_EventManager');
+ $eventsMock->shouldReceive('fire')
+ ->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['events_manager'] = $eventsMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $di['mod_service'] = $di->protect(moduleService(['invoice:transaction' => $transactionService]));
+
+ $api->setDi($di);
+
+ $result = $api->transaction_process($data);
+ expect($result)->toBeBool()->toBeTrue();
+});
+
+test('updates a transaction', function (): void {
+ $api = new Admin();
+ $data = [
+ 'id' => 1,
+ ];
+
+ $transactionService = Mockery::mock(ServiceTransaction::class);
+ $transactionService->shouldReceive('update')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $model = new Model_Transaction();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(moduleService(['invoice:transaction' => $transactionService]));
+
+ $api->setDi($di);
+
+ $result = $api->transaction_update($data);
+ expect($result)->toBeBool()->toBeTrue();
+});
+
+test('creates a transaction', function (): void {
+ $api = new Admin();
+ $newTransactionId = 1;
+ $transactionService = Mockery::mock(ServiceTransaction::class);
+ $transactionService->shouldReceive('create')
+ ->atLeast()->once()
+ ->andReturn($newTransactionId);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(moduleService(['invoice:transaction' => $transactionService]));
+ $api->setDi($di);
+
+ $result = $api->transaction_create([]);
+ expect($result)->toBeInt()->toBe($newTransactionId);
+});
+
+test('deletes a transaction', function (): void {
+ $api = new Admin();
+ $data = [
+ 'id' => 1,
+ ];
+
+ $transactionService = Mockery::mock(ServiceTransaction::class);
+ $transactionService->shouldReceive('delete')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $model = new Model_Transaction();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(moduleService(['invoice:transaction' => $transactionService]));
+
+ $api->setDi($di);
+
+ $result = $api->transaction_delete($data);
+ expect($result)->toBeBool()->toBeTrue();
+});
+
+test('gets a transaction', function (): void {
+ $api = new Admin();
+ $data = [
+ 'id' => 1,
+ ];
+
+ $transactionService = Mockery::mock(ServiceTransaction::class);
+ $transactionService->shouldReceive('toApiArray')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $model = new Model_Transaction();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(moduleService(['invoice:transaction' => $transactionService]));
+
+ $api->setDi($di);
+
+ $result = $api->transaction_get($data);
+ expect($result)->toBeArray();
+});
+
+test('gets transaction list', function (): void {
+ $api = new Admin();
+ $transactionService = Mockery::mock(ServiceTransaction::class);
+ $transactionService->shouldReceive('getSearchQuery')
+ ->atLeast()->once()
+ ->andReturn(['SqlString', []]);
+
+ $paginatorMock = Mockery::mock(FOSSBilling\Pagination::class);
+ $paginatorMock->shouldReceive('getDefaultPerPage')
+ ->byDefault()
+ ->andReturn(25);
+ $paginatorMock->shouldReceive('getPaginatedResultSet')
+ ->atLeast()->once()
+ ->andReturn(['list' => []]);
+
+ $di = container();
+ $di['pager'] = $paginatorMock;
+ $di['mod_service'] = $di->protect(moduleService(['invoice:transaction' => $transactionService]));
+
+ $api->setDi($di);
+ $result = $api->transaction_get_list([]);
+ expect($result)->toBeArray();
+});
+
+test('gets transaction statuses', function (): void {
+ $api = new Admin();
+ $transactionService = Mockery::mock(ServiceTransaction::class);
+ $transactionService->shouldReceive('counter')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(moduleService(['invoice:transaction' => $transactionService]));
+
+ $api->setDi($di);
+
+ $result = $api->transaction_get_statuses([]);
+ expect($result)->toBeArray();
+});
+
+test('gets transaction status pairs', function (): void {
+ $api = new Admin();
+ $transactionService = Mockery::mock(ServiceTransaction::class);
+ $transactionService->shouldReceive('getStatusPairs')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(moduleService(['invoice:transaction' => $transactionService]));
+
+ $api->setDi($di);
+
+ $result = $api->transaction_get_statuses_pairs([]);
+ expect($result)->toBeArray();
+});
+
+test('gets transaction statuses list', function (): void {
+ $api = new Admin();
+ $transactionService = Mockery::mock(ServiceTransaction::class);
+ $transactionService->shouldReceive('getStatuses')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(moduleService(['invoice:transaction' => $transactionService]));
+
+ $api->setDi($di);
+
+ $result = $api->transaction_statuses([]);
+ expect($result)->toBeArray();
+});
+
+test('gets transaction gateway statuses', function (): void {
+ $api = new Admin();
+ $transactionService = Mockery::mock(ServiceTransaction::class);
+ $transactionService->shouldReceive('getGatewayStatuses')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(moduleService(['invoice:transaction' => $transactionService]));
+
+ $api->setDi($di);
+
+ $result = $api->transaction_gateway_statuses([]);
+ expect($result)->toBeArray();
+});
+
+test('gets transaction types', function (): void {
+ $api = new Admin();
+ $transactionService = Mockery::mock(ServiceTransaction::class);
+ $transactionService->shouldReceive('getTypes')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(moduleService(['invoice:transaction' => $transactionService]));
+
+ $api->setDi($di);
+
+ $result = $api->transaction_types([]);
+ expect($result)->toBeArray();
+});
+
+test('gets gateway list', function (): void {
+ $api = new Admin();
+ $gatewayService = Mockery::mock(ServicePayGateway::class);
+ $gatewayService->shouldReceive('getSearchQuery')
+ ->atLeast()->once()
+ ->andReturn(['SqlString', []]);
+
+ $paginatorMock = Mockery::mock(FOSSBilling\Pagination::class);
+ $paginatorMock->shouldReceive('getDefaultPerPage')
+ ->byDefault()
+ ->andReturn(25);
+ $paginatorMock->shouldReceive('getPaginatedResultSet')
+ ->atLeast()->once()
+ ->andReturn(['list' => []]);
+
+ $di = container();
+ $di['pager'] = $paginatorMock;
+ $di['mod_service'] = $di->protect(moduleService(['invoice:paygateway' => $gatewayService]));
+
+ $api->setDi($di);
+ $result = $api->gateway_get_list([]);
+ expect($result)->toBeArray();
+});
+
+test('gets gateway pairs', function (): void {
+ $api = new Admin();
+ $gatewayService = Mockery::mock(ServicePayGateway::class);
+ $gatewayService->shouldReceive('getPairs')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(moduleService(['invoice:paygateway' => $gatewayService]));
+ $api->setDi($di);
+
+ $result = $api->gateway_get_pairs([]);
+ expect($result)->toBeArray();
+});
+
+test('gets available gateways', function (): void {
+ $api = new Admin();
+ $gatewayService = Mockery::mock(ServicePayGateway::class);
+ $gatewayService->shouldReceive('getAvailable')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(moduleService(['invoice:paygateway' => $gatewayService]));
+ $api->setDi($di);
+
+ $result = $api->gateway_get_available([]);
+ expect($result)->toBeArray();
+});
+
+test('installs a gateway', function (): void {
+ $api = new Admin();
+ $data = [
+ 'code' => 'PP',
+ ];
+
+ $gatewayService = Mockery::mock(ServicePayGateway::class);
+ $gatewayService->shouldReceive('install')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(moduleService(['invoice:paygateway' => $gatewayService]));
+ $api->setDi($di);
+
+ $result = $api->gateway_install($data);
+ expect($result)->toBeBool()->toBeTrue();
+});
+
+test('gets a gateway', function (): void {
+ $api = new Admin();
+ $data = [
+ 'id' => 1,
+ ];
+
+ $gatewayService = Mockery::mock(ServicePayGateway::class);
+ $gatewayService->shouldReceive('toApiArray')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $model = new Model_PayGateway();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(moduleService(['invoice:paygateway' => $gatewayService]));
+
+ $api->setDi($di);
+
+ $result = $api->gateway_get($data);
+ expect($result)->toBeArray();
+});
+
+test('copies a gateway', function (): void {
+ $api = new Admin();
+ $data = [
+ 'id' => 1,
+ ];
+ $newGatewayId = 1;
+ $gatewayService = Mockery::mock(ServicePayGateway::class);
+ $gatewayService->shouldReceive('copy')
+ ->atLeast()->once()
+ ->andReturn($newGatewayId);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $model = new Model_PayGateway();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(moduleService(['invoice:paygateway' => $gatewayService]));
+
+ $api->setDi($di);
+
+ $result = $api->gateway_copy($data);
+ expect($result)->toBeInt()->toBe($newGatewayId);
+});
+
+test('updates a gateway', function (): void {
+ $api = new Admin();
+ $data = [
+ 'id' => 1,
+ ];
+
+ $gatewayService = Mockery::mock(ServicePayGateway::class);
+ $gatewayService->shouldReceive('update')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $model = new Model_PayGateway();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(moduleService(['invoice:paygateway' => $gatewayService]));
+
+ $api->setDi($di);
+
+ $result = $api->gateway_update($data);
+ expect($result)->toBeBool()->toBeTrue();
+});
+
+test('deletes a gateway', function (): void {
+ $api = new Admin();
+ $data = [
+ 'id' => 1,
+ ];
+
+ $gatewayService = Mockery::mock(ServicePayGateway::class);
+ $gatewayService->shouldReceive('delete')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $model = new Model_PayGateway();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(moduleService(['invoice:paygateway' => $gatewayService]));
+
+ $api->setDi($di);
+
+ $result = $api->gateway_delete($data);
+ expect($result)->toBeBool()->toBeTrue();
+});
+
+test('gets subscription list', function (): void {
+ $api = new Admin();
+ $subscriptionService = Mockery::mock(ServiceSubscription::class);
+ $subscriptionService->shouldReceive('getSearchQuery')
+ ->atLeast()->once()
+ ->andReturn(['SqlString', []]);
+
+ $paginatorMock = Mockery::mock(FOSSBilling\Pagination::class);
+ $paginatorMock->shouldReceive('getDefaultPerPage')
+ ->byDefault()
+ ->andReturn(25);
+ $paginatorMock->shouldReceive('getPaginatedResultSet')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $di = container();
+ $di['pager'] = $paginatorMock;
+ $di['mod_service'] = $di->protect(moduleService(['invoice:subscription' => $subscriptionService]));
+
+ $api->setDi($di);
+ $result = $api->subscription_get_list([]);
+ expect($result)->toBeArray();
+});
+
+test('creates a subscription', function (): void {
+ $api = new Admin();
+ $data = [
+ 'client_id' => 1,
+ 'gateway_id' => 1,
+ 'currency' => 'EU',
+ ];
+ $newSubscriptionId = 1;
+ $subscriptionService = Mockery::mock(ServiceSubscription::class);
+ $subscriptionService->shouldReceive('create')
+ ->atLeast()->once()
+ ->andReturn($newSubscriptionId);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $model = new Model_PayGateway();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $client = new Model_Client();
+ $client->loadBean(new Tests\Helpers\DummyBean());
+ $client->currency = 'EU';
+
+ $dbMock->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($client, $model);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(moduleService(['invoice:subscription' => $subscriptionService]));
+
+ $api->setDi($di);
+
+ $result = $api->subscription_create($data);
+ expect($result)->toBeInt()->toBe($newSubscriptionId);
+});
+
+test('throws exception when creating subscription with currency mismatch', function (): void {
+ $api = new Admin();
+ $data = [
+ 'client_id' => 1,
+ 'gateway_id' => 1,
+ 'currency' => 'EU',
+ ];
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $model = new Model_PayGateway();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $client = new Model_Client();
+ $client->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($client, $model);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $api->setDi($di);
+
+ expect(fn () => $api->subscription_create($data))
+ ->toThrow(FOSSBilling\Exception::class, 'Client currency must match subscription currency. Check if clients currency is defined.');
+});
+
+test('updates a subscription', function (): void {
+ $api = new Admin();
+ $data = [
+ 'id' => 1,
+ ];
+
+ $subscriptionService = Mockery::mock(ServiceSubscription::class);
+ $subscriptionService->shouldReceive('update')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $model = new Model_Subscription();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(moduleService(['invoice:subscription' => $subscriptionService]));
+
+ $api->setDi($di);
+
+ $result = $api->subscription_update($data);
+ expect($result)->toBeBool()->toBeTrue();
+});
+
+test('gets a subscription', function (): void {
+ $api = new Admin();
+ $data = [
+ 'id' => 1,
+ ];
+
+ $subscriptionService = Mockery::mock(ServiceSubscription::class);
+ $subscriptionService->shouldReceive('toApiArray')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $model = new Model_Subscription();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock->shouldReceive('load')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(moduleService(['invoice:subscription' => $subscriptionService]));
+
+ $api->setDi($di);
+
+ $result = $api->subscription_get($data);
+ expect($result)->toBeArray();
+});
+
+test('deletes a subscription', function (): void {
+ $api = new Admin();
+ $data = [
+ 'id' => 1,
+ ];
+
+ $subscriptionService = Mockery::mock(ServiceSubscription::class);
+ $subscriptionService->shouldReceive('delete')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $model = new Model_Subscription();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(moduleService(['invoice:subscription' => $subscriptionService]));
+
+ $api->setDi($di);
+
+ $result = $api->subscription_delete($data);
+ expect($result)->toBeBool()->toBeTrue();
+});
+
+test('deletes a tax', function (): void {
+ $api = new Admin();
+ $data = [
+ 'id' => 1,
+ ];
+
+ $taxService = Mockery::mock(ServiceTax::class);
+ $taxService->shouldReceive('delete')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $model = new Model_Tax();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(moduleService(['invoice:tax' => $taxService]));
+
+ $api->setDi($di);
+
+ $result = $api->tax_delete($data);
+ expect($result)->toBeBool()->toBeTrue();
+});
+
+test('creates a tax', function (): void {
+ $api = new Admin();
+ $data = [
+ 'id' => 1,
+ ];
+ $newTaxId = 1;
+ $taxService = Mockery::mock(ServiceTax::class);
+ $taxService->shouldReceive('create')
+ ->atLeast()->once()
+ ->andReturn($newTaxId);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(moduleService(['invoice:tax' => $taxService]));
+
+ $api->setDi($di);
+
+ $result = $api->tax_create($data);
+ expect($result)->toBeInt()->toBe($newTaxId);
+});
+
+test('gets tax list', function (): void {
+ $api = new Admin();
+ $taxService = Mockery::mock(ServiceTax::class);
+ $taxService->shouldReceive('getSearchQuery')
+ ->atLeast()->once()
+ ->andReturn(['SqlString', []]);
+
+ $paginatorMock = Mockery::mock(FOSSBilling\Pagination::class);
+ $paginatorMock->shouldReceive('getDefaultPerPage')
+ ->byDefault()
+ ->andReturn(25);
+ $paginatorMock->shouldReceive('getPaginatedResultSet')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $di = container();
+ $di['pager'] = $paginatorMock;
+ $di['mod_service'] = $di->protect(moduleService(['invoice:tax' => $taxService]));
+
+ $api->setDi($di);
+
+ $result = $api->tax_get_list([]);
+ expect($result)->toBeArray();
+});
+
+test('deletes invoices in batch', function (): void {
+ $api = new Admin();
+ $activityMock = Mockery::mock(Admin::class)->makePartial();
+ $activityMock->shouldReceive('delete')->atLeast()->once()->andReturn(true);
+
+ $di = container();
+ $activityMock->setDi($di);
+
+ $result = $activityMock->batch_delete(['ids' => [1, 2, 3]]);
+ expect($result)->toBeTrue();
+});
+
+test('deletes subscriptions in batch', function (): void {
+ $api = new Admin();
+ $activityMock = Mockery::mock(Admin::class)->makePartial();
+ $activityMock->shouldReceive('subscription_delete')->atLeast()->once()->andReturn(true);
+
+ $di = container();
+ $activityMock->setDi($di);
+
+ $result = $activityMock->batch_delete_subscription(['ids' => [1, 2, 3]]);
+ expect($result)->toBeTrue();
+});
+
+test('deletes transactions in batch', function (): void {
+ $api = new Admin();
+ $activityMock = Mockery::mock(Admin::class)->makePartial();
+ $activityMock->shouldReceive('transaction_delete')->atLeast()->once()->andReturn(true);
+
+ $di = container();
+ $activityMock->setDi($di);
+
+ $result = $activityMock->batch_delete_transaction(['ids' => [1, 2, 3]]);
+ expect($result)->toBeTrue();
+});
+
+test('deletes taxes in batch', function (): void {
+ $api = new Admin();
+ $activityMock = Mockery::mock(Admin::class)->makePartial();
+ $activityMock->shouldReceive('tax_delete')->atLeast()->once()->andReturn(true);
+
+ $di = container();
+ $activityMock->setDi($di);
+
+ $result = $activityMock->batch_delete_tax(['ids' => [1, 2, 3]]);
+ expect($result)->toBeTrue();
+});
+
+test('gets a tax', function (): void {
+ $api = new Admin();
+ $taxService = Mockery::mock(ServiceTax::class);
+ $taxService->shouldReceive('toApiArray')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $model = new Model_Tax();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(moduleService(['invoice:tax' => $taxService]));
+
+ $api->setDi($di);
+ $api->setService($taxService);
+ $api->setIdentity(new Model_Admin());
+
+ $data['id'] = 1;
+ $result = $api->tax_get($data);
+ expect($result)->toBeArray();
+});
+
+test('updates a tax', function (): void {
+ $api = new Admin();
+ $taxService = Mockery::mock(ServiceTax::class);
+ $taxService->shouldReceive('update')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $model = new Model_Tax();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(moduleService(['invoice:tax' => $taxService]));
+
+ $api->setDi($di);
+ $api->setService($taxService);
+ $api->setIdentity(new Model_Admin());
+
+ $data['id'] = 1;
+ $result = $api->tax_update($data);
+ expect($result)->toBeBool()->toBeTrue();
+});
diff --git a/src/modules/Invoice/tests/Unit/Api/ClientTest.php b/src/modules/Invoice/tests/Unit/Api/ClientTest.php
new file mode 100644
index 000000000..648645ee5
--- /dev/null
+++ b/src/modules/Invoice/tests/Unit/Api/ClientTest.php
@@ -0,0 +1,238 @@
+setDi($di);
+ $getDi = $api->getDi();
+ expect($getDi)->toBe($di);
+});
+
+test('gets an invoice', function (): void {
+ $api = new Client();
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('toApiArray')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $model = new Model_Invoice();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $api->setDi($di);
+ $api->setService($serviceMock);
+ $identity = new Model_Client();
+ $identity->loadBean(new Tests\Helpers\DummyBean());
+ $api->setIdentity($identity);
+
+ $data['hash'] = md5('1');
+ $result = $api->get($data);
+ expect($result)->toBeArray();
+});
+
+test('throws exception when invoice is not found', function (): void {
+ $api = new Client();
+ $dbMock = Mockery::mock('\Box_Database');
+ $model = new Model_Invoice();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn(null);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $api->setDi($di);
+ $identity = new Model_Client();
+ $identity->loadBean(new Tests\Helpers\DummyBean());
+ $api->setIdentity($identity);
+
+ $data['hash'] = md5('1');
+ expect(fn () => $api->get($data))
+ ->toThrow(FOSSBilling\Exception::class, 'Invoice was not found');
+});
+
+test('creates renewal invoice', function (): void {
+ $api = new Client();
+ $generatedHash = 'generatedHashString';
+
+ $serviceMock = Mockery::mock(Service::class);
+ $model = new Model_Invoice();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $model->hash = $generatedHash;
+ $serviceMock->shouldReceive('generateForOrder')
+ ->atLeast()->once()
+ ->andReturn($model);
+ $serviceMock->shouldReceive('approveInvoice');
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $clientOrder = new Model_ClientOrder();
+ $clientOrder->loadBean(new Tests\Helpers\DummyBean());
+ $clientOrder->price = 10;
+ $dbMock->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn($clientOrder);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $api->setDi($di);
+ $api->setService($serviceMock);
+ $identity = new Model_Admin();
+ $identity->loadBean(new Tests\Helpers\DummyBean());
+ $api->setIdentity($identity);
+
+ $data['order_id'] = 1;
+ $result = $api->renewal_invoice($data);
+ expect($result)->toBeString()->toBe($generatedHash);
+});
+
+test('throws exception when creating renewal invoice for free order', function (): void {
+ $api = new Client();
+ $dbMock = Mockery::mock('\Box_Database');
+ $clientOrder = new Model_ClientOrder();
+ $clientOrder->loadBean(new Tests\Helpers\DummyBean());
+ $clientOrder->id = 1;
+ $clientOrder->price = 0;
+
+ $dbMock->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn($clientOrder);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $api->setDi($di);
+ $identity = new Model_Admin();
+ $identity->loadBean(new Tests\Helpers\DummyBean());
+ $api->setIdentity($identity);
+
+ $data['order_id'] = 1;
+
+ expect(fn () => $api->renewal_invoice($data))
+ ->toThrow(FOSSBilling\Exception::class, sprintf('Order %d is free. No need to generate invoice.', $clientOrder->id));
+});
+
+test('throws exception when creating renewal invoice for order not found', function (): void {
+ $api = new Client();
+ $dbMock = Mockery::mock('\Box_Database');
+ $clientOrder = new Model_ClientOrder();
+ $clientOrder->loadBean(new Tests\Helpers\DummyBean());
+ $clientOrder->price = 10;
+
+ $dbMock->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn(null);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $api->setDi($di);
+ $identity = new Model_Admin();
+ $identity->loadBean(new Tests\Helpers\DummyBean());
+ $api->setIdentity($identity);
+
+ $data['order_id'] = 1;
+
+ expect(fn () => $api->renewal_invoice($data))
+ ->toThrow(FOSSBilling\Exception::class, 'Order not found');
+});
+
+test('creates funds invoice', function (): void {
+ $api = new Client();
+ $generatedHash = 'generatedHashString';
+
+ $serviceMock = Mockery::mock(Service::class);
+ $model = new Model_Invoice();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $model->hash = $generatedHash;
+ $serviceMock->shouldReceive('generateFundsInvoice')
+ ->atLeast()->once()
+ ->andReturn($model);
+ $serviceMock->shouldReceive('approveInvoice');
+
+ $di = container();
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $api->setDi($di);
+ $api->setService($serviceMock);
+ $identity = new Model_Client();
+ $identity->loadBean(new Tests\Helpers\DummyBean());
+ $api->setIdentity($identity);
+
+ $data['amount'] = 10;
+ $result = $api->funds_invoice($data);
+ expect($result)->toBeString()->toBe($generatedHash);
+});
+
+test('gets transaction list', function (): void {
+ $api = new Client();
+ $transactionService = Mockery::mock(ServiceTransaction::class);
+ $transactionService->shouldReceive('getSearchQuery')
+ ->atLeast()->once()
+ ->andReturn(['SqlString', []]);
+
+ $paginatorMock = Mockery::mock(FOSSBilling\Pagination::class);
+ $paginatorMock->shouldReceive('getPaginatedResultSet')
+ ->atLeast()->once()
+ ->andReturn(['list' => []]);
+
+ $di = container();
+ $di['pager'] = $paginatorMock;
+ $di['mod_service'] = $di->protect(moduleService(['invoice:transaction' => $transactionService]));
+
+ $api->setDi($di);
+
+ $identity = new Model_Client();
+ $identity->loadBean(new Tests\Helpers\DummyBean());
+ $api->setIdentity($identity);
+ $result = $api->transaction_get_list([]);
+ expect($result)->toBeArray();
+});
+
+test('gets tax rate for client', function (): void {
+ $api = new Client();
+ $client = new Model_Client();
+ $client->loadBean(new Tests\Helpers\DummyBean());
+
+ $taxRate = 20;
+
+ $invoiceTaxService = Mockery::mock(ServiceTax::class);
+ $invoiceTaxService->shouldReceive('getTaxRateForClient')
+ ->atLeast()->once()
+ ->andReturn($taxRate);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(moduleService(['invoice:tax' => $invoiceTaxService]));
+ $api->setDi($di);
+ $api->setIdentity($client);
+
+ $result = $api->get_tax_rate();
+ expect($result)->toBe($taxRate);
+});
diff --git a/src/modules/Invoice/tests/Unit/Api/GuestTest.php b/src/modules/Invoice/tests/Unit/Api/GuestTest.php
new file mode 100644
index 000000000..84aab3f39
--- /dev/null
+++ b/src/modules/Invoice/tests/Unit/Api/GuestTest.php
@@ -0,0 +1,144 @@
+setDi($di);
+ $getDi = $api->getDi();
+ expect($getDi)->toBe($di);
+});
+
+test('gets an invoice', function (): void {
+ $api = new Guest();
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('checkInvoiceAuth')
+ ->atLeast()->once();
+ $serviceMock->shouldReceive('toApiArray')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $model = new Model_Invoice();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $api->setDi($di);
+ $api->setService($serviceMock);
+ $api->setIdentity(new Model_Admin());
+
+ $data['hash'] = md5('1');
+ $result = $api->get($data);
+ expect($result)->toBeArray();
+});
+
+test('throws exception when invoice is not found', function (): void {
+ $api = new Guest();
+ $dbMock = Mockery::mock('\Box_Database');
+ $model = new Model_Invoice();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn(null);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $api->setDi($di);
+ $api->setIdentity(new Model_Admin());
+
+ $data['hash'] = md5('1');
+ expect(fn () => $api->get($data))
+ ->toThrow(FOSSBilling\Exception::class, 'Invoice was not found');
+});
+
+test('gets active gateways', function (): void {
+ $api = new Guest();
+ $gatewayServiceMock = Mockery::mock(ServicePayGateway::class);
+ $gatewayServiceMock->shouldReceive('getActive')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(moduleService(['invoice:paygateway' => $gatewayServiceMock]));
+
+ $api->setDi($di);
+
+ $result = $api->gateways([]);
+ expect($result)->toBeArray();
+});
+
+test('processes payment', function (): void {
+ $api = new Guest();
+ $data = [
+ 'hash' => str_repeat('a', 32),
+ 'gateway_id' => 1,
+ ];
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('processInvoice')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $api->setService($serviceMock);
+
+ $result = $api->payment($data);
+ expect($result)->toBeArray();
+});
+
+test('throws exception when payment hash is missing', function (): void {
+ $api = new Guest();
+ $data = [
+ 'gateway_id' => '',
+ ];
+
+ expect(fn () => $api->payment($data))
+ ->toThrow(FOSSBilling\Exception::class, 'Invoice hash not passed. Missing param hash');
+});
+
+test('throws exception when payment gateway id is missing', function (): void {
+ $api = new Guest();
+ $data = [
+ 'hash' => str_repeat('a', 32),
+ ];
+
+ expect(fn () => $api->payment($data))
+ ->toThrow(FOSSBilling\Exception::class, 'Payment method not found. Missing param gateway_id');
+});
+
+test('generates PDF', function (): void {
+ $api = new Guest();
+ $data = [
+ 'hash' => str_repeat('a', 32),
+ ];
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('generatePDF')
+ ->atLeast()->once();
+
+ $di = container();
+ $api->setDi($di);
+
+ $api->setService($serviceMock);
+
+ $api->pdf($data);
+});
diff --git a/src/modules/Invoice/tests/Unit/ServiceInvoiceItemTest.php b/src/modules/Invoice/tests/Unit/ServiceInvoiceItemTest.php
new file mode 100644
index 000000000..2f85ee6ae
--- /dev/null
+++ b/src/modules/Invoice/tests/Unit/ServiceInvoiceItemTest.php
@@ -0,0 +1,394 @@
+setDi($di);
+ $getDi = $service->getDi();
+ expect($getDi)->toBe($di);
+});
+
+test('marks item as paid', function (): void {
+ $service = new ServiceInvoiceItem();
+ $invoiceItemModel = new Model_InvoiceItem();
+ $invoiceItemModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $serviceMock = Mockery::mock(ServiceInvoiceItem::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('creditInvoiceItem')
+ ->atLeast()->once();
+ $serviceMock->shouldReceive('getOrderId')
+ ->atLeast()->once()
+ ->andReturn(1);
+
+ $clientOrder = new Model_ClientOrder();
+ $clientOrder->loadBean(new Tests\Helpers\DummyBean());
+
+ $orderServiceMock = Mockery::mock(OrderService::class);
+ $orderServiceMock->shouldReceive('unsetUnpaidInvoice')
+ ->with($clientOrder);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once();
+ $dbMock->shouldReceive('load')
+ ->atLeast()->once()
+ ->andReturn($clientOrder);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
+ $serviceMock->setDi($di);
+
+ $serviceMock->markAsPaid($invoiceItemModel);
+});
+
+test('returns true when executing task on already executed item', function (): void {
+ $service = new ServiceInvoiceItem();
+ $invoiceItemModel = new Model_InvoiceItem();
+ $invoiceItemModel->loadBean(new Tests\Helpers\DummyBean());
+ $invoiceItemModel->status = Model_InvoiceItem::STATUS_EXECUTED;
+
+ $result = $service->executeTask($invoiceItemModel);
+ expect($result)->toBeTrue();
+});
+
+test('throws exception when executing task for order type with client order not found', function (): void {
+ $service = new ServiceInvoiceItem();
+ $invoiceItemModel = new Model_InvoiceItem();
+ $invoiceItemModel->loadBean(new Tests\Helpers\DummyBean());
+ $invoiceItemModel->type = Model_InvoiceItem::TYPE_ORDER;
+ $orderId = 22;
+
+ $serviceMock = Mockery::mock(ServiceInvoiceItem::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('getOrderId')
+ ->atLeast()->once()
+ ->andReturn($orderId);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('load')
+ ->atLeast()->once()
+ ->andReturn(null);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $serviceMock->setDi($di);
+
+ expect(fn () => $serviceMock->executeTask($invoiceItemModel))
+ ->toThrow(FOSSBilling\Exception::class, sprintf('Could not activate proforma item. Order %d not found', $orderId));
+});
+
+test('executes task for hook call type', function (): void {
+ $service = new ServiceInvoiceItem();
+ $invoiceItemModel = new Model_InvoiceItem();
+ $invoiceItemModel->loadBean(new Tests\Helpers\DummyBean());
+ $invoiceItemModel->type = Model_InvoiceItem::TYPE_HOOK_CALL;
+ $invoiceItemModel->rel_id = '{}';
+
+ $serviceMock = Mockery::mock(ServiceInvoiceItem::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('markAsExecuted')
+ ->atLeast()->once();
+
+ $eventManagerMock = Mockery::mock('\Box_EventManager');
+ $eventManagerMock->shouldReceive('fire')
+ ->atLeast()->once();
+
+ $di = container();
+ $di['events_manager'] = $eventManagerMock;
+ $serviceMock->setDi($di);
+
+ $serviceMock->executeTask($invoiceItemModel);
+});
+
+test('executes task for deposit type', function (): void {
+ $service = new ServiceInvoiceItem();
+ $invoiceItemModel = new Model_InvoiceItem();
+ $invoiceItemModel->loadBean(new Tests\Helpers\DummyBean());
+ $invoiceItemModel->type = Model_InvoiceItem::TYPE_DEPOSIT;
+
+ $invoiceModel = new Model_Invoice();
+ $invoiceModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $clientModel = new Model_Client();
+ $clientModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $di = container();
+ $dbMock = Mockery::mock('\Box_Database');
+ $di['db'] = $dbMock;
+
+ $clientServiceMock = Mockery::mock(ClientService::class);
+ $di['mod_service'] = $di->protect(function ($serviceName) use ($clientServiceMock) {
+ if ($serviceName == 'Client') {
+ return $clientServiceMock;
+ }
+ });
+
+ $serviceMock = Mockery::mock(ServiceInvoiceItem::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('markAsExecuted')
+ ->atLeast()->once();
+ $serviceMock->setDi($di);
+
+ $serviceMock->executeTask($invoiceItemModel);
+});
+
+test('executes task for custom type', function (): void {
+ $service = new ServiceInvoiceItem();
+ $invoiceItemModel = new Model_InvoiceItem();
+ $invoiceItemModel->loadBean(new Tests\Helpers\DummyBean());
+ $invoiceItemModel->type = Model_InvoiceItem::TYPE_CUSTOM;
+
+ $serviceMock = Mockery::mock(ServiceInvoiceItem::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('markAsExecuted')
+ ->atLeast()->once();
+
+ $serviceMock->executeTask($invoiceItemModel);
+});
+
+test('adds new item', function (): void {
+ $service = new ServiceInvoiceItem();
+ $data = [
+ 'title' => 'Guacamole',
+ ];
+ $invoiceItemModel = new Model_InvoiceItem();
+ $invoiceItemModel->loadBean(new Tests\Helpers\DummyBean());
+ $newId = 1;
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('dispense')
+ ->atLeast()->once()
+ ->andReturn($invoiceItemModel);
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn($newId);
+
+ $periodMock = Mockery::mock('\Box_Period');
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $service->setDi($di);
+
+ $invoiceModel = new Model_Invoice();
+ $invoiceModel->loadBean(new Tests\Helpers\DummyBean());
+ $result = $service->addNew($invoiceModel, $data);
+ expect($result)->toBeInt()->toBe($newId);
+});
+
+test('gets total', function (): void {
+ $service = new ServiceInvoiceItem();
+ $price = 5;
+ $quantity = 3;
+ $invoiceItemModel = new Model_InvoiceItem();
+ $invoiceItemModel->loadBean(new Tests\Helpers\DummyBean());
+ $invoiceItemModel->price = $price;
+ $invoiceItemModel->quantity = $quantity;
+
+ $expected = $price * $quantity;
+
+ $result = $service->getTotal($invoiceItemModel);
+ expect($result)->toBeFloat();
+ expect($result)->toEqual($expected);
+});
+
+test('gets tax', function (): void {
+ $service = new ServiceInvoiceItem();
+ $rate = 0.21;
+ $price = 12;
+ $invoiceItemModel = new Model_InvoiceItem();
+ $invoiceItemModel->loadBean(new Tests\Helpers\DummyBean());
+ $invoiceItemModel->invoice_id = 2;
+ $invoiceItemModel->taxed = true;
+ $invoiceItemModel->price = $price;
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getCell')
+ ->atLeast()->once()
+ ->andReturn($rate);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $result = $service->getTax($invoiceItemModel);
+ $expected = round($price * $rate / 100, 2);
+ expect($result)->toBeFloat();
+ expect($result)->toBe($expected);
+});
+
+test('updates an item', function (): void {
+ $service = new ServiceInvoiceItem();
+ $invoiceItemModel = new Model_InvoiceItem();
+ $invoiceItemModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $data = [
+ 'title' => 'New Engine',
+ 'price' => 12,
+ 'taxed' => true,
+ ];
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $service->setDi($di);
+
+ $service->update($invoiceItemModel, $data);
+});
+
+test('removes an item', function (): void {
+ $service = new ServiceInvoiceItem();
+ $invoiceItemModel = new Model_InvoiceItem();
+ $invoiceItemModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('trash')
+ ->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $service->setDi($di);
+
+ $result = $service->remove($invoiceItemModel);
+ expect($result)->toBeTrue();
+});
+
+test('generates for add funds', function (): void {
+ $service = new ServiceInvoiceItem();
+ $invoiceModel = new Model_Invoice();
+ $invoiceModel->loadBean(new Tests\Helpers\DummyBean());
+ $amount = 11;
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('dispense')
+ ->atLeast()->once()
+ ->andReturn($invoiceModel);
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $service->generateForAddFunds($invoiceModel, $amount);
+});
+
+test('credits invoice item', function (): void {
+ $service = new ServiceInvoiceItem();
+ $serviceMock = Mockery::mock(ServiceInvoiceItem::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('getTotalWithTax')
+ ->atLeast()->once()
+ ->andReturn(11.2);
+
+ $invoiceItemModel = new Model_InvoiceItem();
+ $invoiceItemModel->loadBean(new Tests\Helpers\DummyBean());
+ $invoiceModel = new Model_Invoice();
+ $invoiceModel->loadBean(new Tests\Helpers\DummyBean());
+ $clientModel = new Model_Client();
+ $clientModel->loadBean(new Tests\Helpers\DummyBean());
+ $clientBalanceModel = new Model_Client();
+ $clientBalanceModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $callCount = 0;
+ $dbMock->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturnUsing(function () use ($invoiceModel, $clientModel, &$callCount) {
+ return ++$callCount === 1 ? $invoiceModel : $clientModel;
+ });
+ $dbMock->shouldReceive('dispense')
+ ->atLeast()->once()
+ ->andReturn($clientBalanceModel);
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once();
+
+ $invoiceServiceMock = Mockery::mock(InvoiceService::class);
+ $invoiceServiceMock->shouldReceive('addNote')
+ ->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $invoiceServiceMock);
+
+ $serviceMock->setDi($di);
+ $serviceMock->creditInvoiceItem($invoiceItemModel);
+});
+
+test('gets total with tax', function (): void {
+ $service = new ServiceInvoiceItem();
+ $total = 5.0;
+ $tax = 0.5;
+ $quantity = 3;
+ $invoiceItemModel = new Model_InvoiceItem();
+ $invoiceItemModel->loadBean(new Tests\Helpers\DummyBean());
+ $invoiceItemModel->quantity = $quantity;
+
+ $serviceMock = Mockery::mock(ServiceInvoiceItem::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('getTotal')
+ ->atLeast()->once()
+ ->andReturn($total);
+ $serviceMock->shouldReceive('getTax')
+ ->atLeast()->once()
+ ->andReturn($tax);
+
+ $result = $serviceMock->getTotalWithTax($invoiceItemModel);
+ expect($result)->toBeFloat();
+ $expected = $total + $tax * $quantity;
+ expect($result)->toBe($expected);
+});
+
+test('gets order id', function (): void {
+ $service = new ServiceInvoiceItem();
+ $orderId = 2;
+ $invoiceItemModel = new Model_InvoiceItem();
+ $invoiceItemModel->loadBean(new Tests\Helpers\DummyBean());
+ $invoiceItemModel->rel_id = $orderId;
+ $invoiceItemModel->type = Model_InvoiceItem::TYPE_ORDER;
+
+ $result = $service->getOrderId($invoiceItemModel);
+ expect($result)->toBeInt()->toBe($orderId);
+});
+
+test('returns zero when invoice item type is not order', function (): void {
+ $service = new ServiceInvoiceItem();
+ $invoiceItemModel = new Model_InvoiceItem();
+ $invoiceItemModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $result = $service->getOrderId($invoiceItemModel);
+ expect($result)->toBeInt()->toBe(0);
+});
+
+test('gets all not execute paid items', function (): void {
+ $service = new ServiceInvoiceItem();
+ $di = container();
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getAll')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $result = $service->getAllNotExecutePaidItems();
+ expect($result)->toBeArray();
+});
diff --git a/src/modules/Invoice/tests/Unit/ServicePayGatewayTest.php b/src/modules/Invoice/tests/Unit/ServicePayGatewayTest.php
new file mode 100644
index 000000000..e52b46a86
--- /dev/null
+++ b/src/modules/Invoice/tests/Unit/ServicePayGatewayTest.php
@@ -0,0 +1,483 @@
+setDi($di);
+ $getDi = $service->getDi();
+ expect($getDi)->toBe($di);
+});
+
+test('gets search query', function (): void {
+ $service = new ServicePayGateway();
+ $di = container();
+
+ $service->setDi($di);
+ $data = [];
+ $result = $service->getSearchQuery($data);
+ expect($result)->toBeArray();
+ expect($result[0])->toBeString();
+ expect($result[1])->toBeArray()->toBe([]);
+});
+
+test('gets search query with additional params', function (): void {
+ $service = new ServicePayGateway();
+ $di = container();
+
+ $service->setDi($di);
+ $data = ['search' => 'keyword'];
+ $expectedParams = [':search' => "%$data[search]%"];
+
+ $result = $service->getSearchQuery($data);
+ expect($result)->toBeArray();
+ expect($result[0])->toBeString();
+ expect(strpos((string) $result[0], 'AND (name LIKE :search OR gateway LIKE :search)') > 0)->toBeTrue();
+ expect($result[1])->toBeArray();
+ expect($result[1])->toBe($expectedParams);
+});
+
+test('gets pairs', function (): void {
+ $service = new ServicePayGateway();
+ $expected = [
+ 1 => 'Custom',
+ ];
+
+ $queryResult = [
+ [
+ 'id' => 1,
+ 'name' => 'Custom',
+ ],
+ ];
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getAll')
+ ->atLeast()->once()
+ ->andReturn($queryResult);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $service->setDi($di);
+
+ $result = $service->getPairs();
+ expect($result)->toBeArray();
+ expect($result)->toBe($expected);
+});
+
+test('gets available gateways', function (): void {
+ $service = new ServicePayGateway();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getAll')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $result = $service->getAvailable();
+ expect($result)->toBeArray();
+});
+
+test('installs a pay gateway', function (): void {
+ $service = new ServicePayGateway();
+ $code = 'PP';
+
+ $serviceMock = Mockery::mock(ServicePayGateway::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('getAvailable')
+ ->atLeast()->once()
+ ->andReturn([$code]);
+
+ $payGatewayModel = new Model_PayGateway();
+ $payGatewayModel->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('dispense')
+ ->atLeast()->once()
+ ->andReturn($payGatewayModel);
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $serviceMock->setDi($di);
+
+ $result = $serviceMock->install($code);
+ expect($result)->toBeBool()->toBeTrue();
+});
+
+test('throws exception when installing unavailable gateway', function (): void {
+ $service = new ServicePayGateway();
+ $code = 'PP';
+
+ $serviceMock = Mockery::mock(ServicePayGateway::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('getAvailable')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ expect(fn () => $serviceMock->install($code))
+ ->toThrow(FOSSBilling\Exception::class, 'Payment gateway is not available for installation.');
+});
+
+test('converts to api array', function (): void {
+ $service = new ServicePayGateway();
+ $payGatewayModel = new Model_PayGateway();
+ $payGatewayModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $serviceMock = Mockery::mock(ServicePayGateway::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('getAdapterConfig')
+ ->atLeast()->once()
+ ->andReturn([]);
+ $serviceMock->shouldReceive('getAcceptedCurrencies');
+ $serviceMock->shouldReceive('getFormElements');
+ $serviceMock->shouldReceive('getDescription');
+
+ $expected = [
+ 'id' => null,
+ 'code' => null,
+ 'title' => null,
+ 'allow_single' => null,
+ 'allow_recurrent' => null,
+ 'accepted_currencies' => [],
+ 'supports_one_time_payments' => false,
+ 'supports_subscriptions' => false,
+ 'config' => [],
+ 'form' => [],
+ 'description' => null,
+ 'enabled' => null,
+ 'test_mode' => null,
+ 'callback' => SYSTEM_URL . 'ipn.php?',
+ ];
+
+ $di = container();
+
+ $serviceMock->setDi($di);
+
+ $result = $serviceMock->toApiArray($payGatewayModel, false, new Model_Admin());
+ expect($result)->toBeArray();
+ expect($result)->toBe($expected);
+});
+
+test('copies a gateway', function (): void {
+ $service = new ServicePayGateway();
+ $payGatewayModel = new Model_PayGateway();
+ $payGatewayModel->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('dispense')
+ ->atLeast()->once()
+ ->andReturn($payGatewayModel);
+
+ $expected = 2;
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn($expected);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $service->setDi($di);
+
+ $result = $service->copy($payGatewayModel);
+ expect($result)->toBeInt()->toBe($expected);
+});
+
+test('updates a gateway', function (): void {
+ $service = new ServicePayGateway();
+ $payGatewayModel = new Model_PayGateway();
+ $payGatewayModel->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $service->setDi($di);
+
+ $data = [
+ 'title' => '',
+ 'config' => '',
+ 'accepted_currencies' => [],
+ 'enabled' => '',
+ 'allow_single' => '',
+ 'allow_recurrent' => '',
+ 'test_mode' => '',
+ ];
+ $result = $service->update($payGatewayModel, $data);
+ expect($result)->toBeTrue();
+});
+
+test('deletes a gateway', function (): void {
+ $service = new ServicePayGateway();
+ $payGatewayModel = new Model_PayGateway();
+ $payGatewayModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('trash')
+ ->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $service->setDi($di);
+
+ $result = $service->delete($payGatewayModel);
+ expect($result)->toBeTrue();
+});
+
+test('gets active gateways', function (): void {
+ $service = new ServicePayGateway();
+ $payGatewayModel = new Model_PayGateway();
+ $payGatewayModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('find')
+ ->atLeast()->once()
+ ->andReturn([$payGatewayModel]);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $service->setDi($di);
+
+ $data = ['format' => 'pairs'];
+ $result = $service->getActive($data);
+ expect($result)->toBeArray();
+});
+
+test('checks if can perform recurrent payment', function (): void {
+ $service = new ServicePayGateway();
+ $payGatewayModel = new Model_PayGateway();
+ $payGatewayModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $expected = true;
+ $payGatewayModel->allow_recurrent = $expected;
+
+ $result = $service->canPerformRecurrentPayment($payGatewayModel);
+ expect($result)->toBeBool()->toBe($expected);
+});
+
+test('gets payment adapter', function (): void {
+ $service = new ServicePayGateway();
+ $payGatewayModel = new Model_PayGateway();
+ $payGatewayModel->loadBean(new Tests\Helpers\DummyBean());
+ $invoiceModel = new Model_Invoice();
+ $invoiceModel->loadBean(new Tests\Helpers\DummyBean());
+ $expected = 'Payment_Adapter_Custom';
+
+ $serviceMock = Mockery::mock(ServicePayGateway::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('getAdapterClassName')
+ ->atLeast()->once()
+ ->andReturn($expected);
+
+ $urlMock = Mockery::mock('\Box_Url');
+ $urlMock->shouldReceive('link')
+ ->atLeast()->once();
+
+ $toolsMock = Mockery::mock(FOSSBilling\Tools::class);
+ $toolsMock->shouldReceive('url')
+ ->atLeast()->once()
+ ->andReturn('http://example.com/');
+
+ $di = container();
+ $di['url'] = $urlMock;
+ $di['tools'] = $toolsMock;
+ $serviceMock->setDi($di);
+
+ $optional = [
+ 'auto_redirect' => '',
+ ];
+ $result = $serviceMock->getPaymentAdapter($payGatewayModel, $invoiceModel, $optional);
+ expect($result)->toBeInstanceOf($expected);
+});
+
+test('throws exception when payment gateway is not found', function (): void {
+ $service = new ServicePayGateway();
+ $payGatewayModel = new Model_PayGateway();
+ $payGatewayModel->loadBean(new Tests\Helpers\DummyBean());
+ $invoiceModel = new Model_Invoice();
+ $invoiceModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $serviceMock = Mockery::mock(ServicePayGateway::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('getAdapterClassName')
+ ->atLeast()->once()
+ ->andReturn('');
+
+ $urlMock = Mockery::mock('\Box_Url');
+ $urlMock->shouldReceive('link')
+ ->atLeast()->once();
+
+ $toolsMock = Mockery::mock(FOSSBilling\Tools::class);
+ $toolsMock->shouldReceive('url')
+ ->atLeast()->once()
+ ->andReturn('http://example.com/');
+
+ $di = container();
+ $di['url'] = $urlMock;
+ $di['tools'] = $toolsMock;
+ $serviceMock->setDi($di);
+
+ expect(fn () => $serviceMock->getPaymentAdapter($payGatewayModel, $invoiceModel))
+ ->toThrow(FOSSBilling\Exception::class, 'Payment gateway was not found.');
+});
+
+test('gets adapter config', function (): void {
+ $service = new ServicePayGateway();
+ $payGatewayModel = new Model_PayGateway();
+ $payGatewayModel->loadBean(new Tests\Helpers\DummyBean());
+ $payGatewayModel->gateway = 'Custom';
+
+ $expected = '\Payment_Adapter_Custom';
+ $filesystemMock = Mockery::mock(Symfony\Component\Filesystem\Filesystem::class);
+ $filesystemMock->shouldReceive('exists')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $serviceMock = Mockery::mock(ServicePayGateway::class, [$filesystemMock])->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('getAdapterClassName')
+ ->atLeast()->once()
+ ->andReturn($expected);
+
+ $result = $serviceMock->getAdapterConfig($payGatewayModel);
+ expect($result)->toBeArray();
+});
+
+test('throws exception when adapter class does not exist', function (): void {
+ $service = new ServicePayGateway();
+ $payGatewayModel = new Model_PayGateway();
+ $payGatewayModel->loadBean(new Tests\Helpers\DummyBean());
+ $payGatewayModel->gateway = 'Custom';
+
+ $expected = 'Payment_Adapter_ClassDoesNotExists';
+ $filesystemMock = Mockery::mock(Symfony\Component\Filesystem\Filesystem::class);
+ $filesystemMock->shouldReceive('exists')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $serviceMock = Mockery::mock(ServicePayGateway::class, [$filesystemMock])->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('getAdapterClassName')
+ ->atLeast()->once()
+ ->andReturn($expected);
+
+ expect(fn () => $serviceMock->getAdapterConfig($payGatewayModel))
+ ->toThrow(FOSSBilling\Exception::class, sprintf('Payment gateway class %s was not found', $expected));
+});
+
+test('throws exception when adapter does not exist', function (): void {
+ $service = new ServicePayGateway();
+ $payGatewayModel = new Model_PayGateway();
+ $payGatewayModel->loadBean(new Tests\Helpers\DummyBean());
+ $payGatewayModel->gateway = 'Unknown';
+
+ $filesystemMock = Mockery::mock(Symfony\Component\Filesystem\Filesystem::class);
+ $filesystemMock->shouldReceive('exists')
+ ->atLeast()->once()
+ ->andReturn(false);
+
+ $serviceMock = Mockery::mock(ServicePayGateway::class, [$filesystemMock])->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('getAdapterClassName')
+ ->atLeast()->once();
+
+ expect(fn () => $serviceMock->getAdapterConfig($payGatewayModel))
+ ->toThrow(FOSSBilling\Exception::class, sprintf('Payment gateway %s was not found', $payGatewayModel->gateway));
+});
+
+test('gets adapter class name', function (): void {
+ $service = new ServicePayGateway();
+ $payGatewayModel = new Model_PayGateway();
+ $payGatewayModel->loadBean(new Tests\Helpers\DummyBean());
+ $payGatewayModel->gateway = 'Custom';
+
+ $expected = 'Payment_Adapter_Custom';
+
+ $result = $service->getAdapterClassName($payGatewayModel);
+ expect($result)->toBeString()->toBe($expected);
+});
+
+test('gets accepted currencies', function (): void {
+ $service = new ServicePayGateway();
+ $payGatewayModel = new Model_PayGateway();
+ $payGatewayModel->loadBean(new Tests\Helpers\DummyBean());
+ $payGatewayModel->accepted_currencies = '{}';
+
+ $result = $service->getAcceptedCurrencies($payGatewayModel);
+ expect($result)->toBeArray();
+});
+
+test('gets form elements', function (): void {
+ $service = new ServicePayGateway();
+ $payGatewayModel = new Model_PayGateway();
+ $payGatewayModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $serviceMock = Mockery::mock(ServicePayGateway::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $config = ['form' => []];
+ $serviceMock->shouldReceive('getAdapterConfig')
+ ->atLeast()->once()
+ ->andReturn($config);
+
+ $result = $serviceMock->getFormElements($payGatewayModel);
+ expect($result)->toBeArray();
+});
+
+test('returns empty array when form config is empty', function (): void {
+ $service = new ServicePayGateway();
+ $payGatewayModel = new Model_PayGateway();
+ $payGatewayModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $serviceMock = Mockery::mock(ServicePayGateway::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $config = [];
+ $serviceMock->shouldReceive('getAdapterConfig')
+ ->atLeast()->once()
+ ->andReturn($config);
+
+ $result = $serviceMock->getFormElements($payGatewayModel);
+ expect($result)->toBeArray()->toBe([]);
+});
+
+test('gets description', function (): void {
+ $service = new ServicePayGateway();
+ $payGatewayModel = new Model_PayGateway();
+ $payGatewayModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $serviceMock = Mockery::mock(ServicePayGateway::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $config = ['description' => ''];
+ $serviceMock->shouldReceive('getAdapterConfig')
+ ->atLeast()->once()
+ ->andReturn($config);
+
+ $result = $serviceMock->getDescription($payGatewayModel);
+ expect($result)->toBeString();
+});
+
+test('returns null when description is empty', function (): void {
+ $service = new ServicePayGateway();
+ $payGatewayModel = new Model_PayGateway();
+ $payGatewayModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $serviceMock = Mockery::mock(ServicePayGateway::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $config = [];
+ $serviceMock->shouldReceive('getAdapterConfig')
+ ->atLeast()->once()
+ ->andReturn($config);
+
+ $result = $serviceMock->getDescription($payGatewayModel);
+ expect($result)->toBeNull();
+});
diff --git a/src/modules/Invoice/tests/Unit/ServiceSubscriptionTest.php b/src/modules/Invoice/tests/Unit/ServiceSubscriptionTest.php
new file mode 100644
index 000000000..8cd0aae97
--- /dev/null
+++ b/src/modules/Invoice/tests/Unit/ServiceSubscriptionTest.php
@@ -0,0 +1,288 @@
+setDi($di);
+ $getDi = $service->getDi();
+ expect($getDi)->toBe($di);
+});
+
+test('creates a subscription', function (): void {
+ $service = new ServiceSubscription();
+ $subscriptionModel = new Model_Subscription();
+ $subscriptionModel->loadBean(new Tests\Helpers\DummyBean());
+ $newId = 10;
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('dispense')
+ ->atLeast()->once()
+ ->andReturn($subscriptionModel);
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn($newId);
+
+ $eventsMock = Mockery::mock('\Box_EventManager');
+ $eventsMock->shouldReceive('fire')
+ ->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $di['events_manager'] = $eventsMock;
+
+ $service->setDi($di);
+
+ $data = [
+ 'client_id' => 1,
+ 'gateway_id' => 2,
+ ];
+
+ $result = $service->create(new Model_Client(), new Model_PayGateway(), $data);
+ expect($result)->toBeInt()->toBe($newId);
+});
+
+test('updates a subscription', function (): void {
+ $service = new ServiceSubscription();
+ $subscriptionModel = new Model_Subscription();
+ $subscriptionModel->loadBean(new Tests\Helpers\DummyBean());
+ $data = [
+ 'status' => '',
+ 'sid' => '',
+ 'period' => '',
+ 'amount' => '',
+ 'currency' => '',
+ ];
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $service->setDi($di);
+
+ $result = $service->update($subscriptionModel, $data);
+ expect($result)->toBeTrue();
+});
+
+test('converts to api array', function (): void {
+ $service = new ServiceSubscription();
+ $subscriptionModel = new Model_Subscription();
+ $subscriptionModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $clientModel = new Model_Client();
+ $clientModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $gatewayModel = new Model_PayGateway();
+ $gatewayModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $callCount = 0;
+ $dbMock->shouldReceive('load')
+ ->atLeast()->once()
+ ->andReturnUsing(function () use ($clientModel, $gatewayModel, &$callCount) {
+ return ++$callCount === 1 ? $clientModel : $gatewayModel;
+ });
+
+ $clientServiceMock = Mockery::mock(ClientService::class);
+ $clientServiceMock->shouldReceive('toApiArray')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $payGatewayService = Mockery::mock(ServicePayGateway::class);
+ $payGatewayService->shouldReceive('toApiArray')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(function ($serviceName, $sub = '') use ($clientServiceMock, $payGatewayService) {
+ if ($serviceName == 'Client') {
+ return $clientServiceMock;
+ }
+ if ($sub == 'PayGateway') {
+ return $payGatewayService;
+ }
+ });
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $expected = [
+ 'id' => '',
+ 'sid' => '',
+ 'period' => '',
+ 'amount' => '',
+ 'currency' => '',
+ 'status' => '',
+ 'created_at' => '',
+ 'updated_at' => '',
+ 'client' => [],
+ 'gateway' => [],
+ ];
+
+ $result = $service->toApiArray($subscriptionModel);
+ expect($result)->toBeArray();
+ expect($result)->toHaveKey('id');
+ expect($result)->toHaveKey('client');
+ expect($result)->toHaveKey('gateway');
+ expect($result['client'])->toBeArray();
+ expect($result['gateway'])->toBeArray();
+});
+
+test('deletes a subscription', function (): void {
+ $service = new ServiceSubscription();
+ $subscriptionModel = new Model_Subscription();
+ $subscriptionModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('trash')
+ ->atLeast()->once();
+
+ $eventsMock = Mockery::mock('\Box_EventManager');
+ $eventsMock->shouldReceive('fire')
+ ->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $di['events_manager'] = $eventsMock;
+ $service->setDi($di);
+
+ $result = $service->delete($subscriptionModel);
+ expect($result)->toBeTrue();
+});
+
+test('gets search query with various parameters', function (array $data, string $expectedSqlPart, array $expectedParams): void {
+ $service = new ServiceSubscription();
+ $di = container();
+
+ $service->setDi($di);
+ $result = $service->getSearchQuery($data);
+
+ expect($result)->toBeArray();
+ expect($result[0])->toBeString();
+ expect($result[1])->toBeArray();
+
+ expect($result[1])->toBe($expectedParams);
+ expect(str_contains((string) $result[0], $expectedSqlPart))->toBeTrue();
+})->with([
+ [
+ [], 'FROM subscription', [],
+ ],
+ [
+ ['status' => 'active'], 'AND status = :status', [':status' => 'active'],
+ ],
+ [
+ ['invoice_id' => '1'], 'AND invoice_id = :invoice_id', [':invoice_id' => '1'],
+ ],
+ [
+ ['gateway_id' => '2'], 'AND gateway_id = :gateway_id', [':gateway_id' => '2'],
+ ],
+ [
+ ['client_id' => '3'], 'AND client_id = :client_id', [':client_id' => '3'],
+ ],
+ [
+ ['currency' => 'EUR'], 'AND currency = :currency', [':currency' => 'EUR'],
+ ],
+ [
+ ['date_from' => '1234567'], 'AND UNIX_TIMESTAMP(created_at) >= :date_from', [':date_from' => '1234567'],
+ ],
+ [
+ ['date_to' => '1234567'], 'AND UNIX_TIMESTAMP(created_at) <= :date_to', [':date_to' => '1234567'],
+ ],
+ [
+ ['id' => '10'], 'AND id = :id', [':id' => '10'],
+ ],
+ [
+ ['sid' => '10'], 'AND sid = :sid', [':sid' => '10'],
+ ],
+]);
+
+test('returns false when invoice is not subscribable', function (): void {
+ $service = new ServiceSubscription();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getAll')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $invoice_id = 2;
+ $result = $service->isSubscribable($invoice_id);
+ expect($result)->toBeBool()->toBeFalse();
+});
+
+test('checks if invoice is subscribable', function (): void {
+ $service = new ServiceSubscription();
+ $dbMock = Mockery::mock('\Box_Database');
+
+ $getAllResults = [
+ ['period' => '1W', 'price' => 10, 'quantity' => 1],
+ ];
+ $dbMock->shouldReceive('getAll')
+ ->atLeast()->once()
+ ->andReturn($getAllResults);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $invoice_id = 2;
+ $result = $service->isSubscribable($invoice_id);
+ expect($result)->toBeBool()->toBeTrue();
+});
+
+test('gets subscription period', function (): void {
+ $serviceMock = Mockery::mock(ServiceSubscription::class)->makePartial()->shouldAllowMockingProtectedMethods();
+
+ $period = '1W';
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getAll')
+ ->atLeast()->once()
+ ->andReturn([['period' => $period, 'price' => 10, 'quantity' => 1]]);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $serviceMock->setDi($di);
+
+ $invoiceModel = new Model_Invoice();
+ $invoiceModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $result = $serviceMock->getSubscriptionPeriod($invoiceModel);
+ expect($result)->toBeString()->toBe($period);
+});
+
+test('unsubscribes', function (): void {
+ $service = new ServiceSubscription();
+ $subscriptionModel = new Model_Subscription();
+ $subscriptionModel->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $service->unsubscribe($subscriptionModel);
+});
diff --git a/src/modules/Invoice/tests/Unit/ServiceTaxTest.php b/src/modules/Invoice/tests/Unit/ServiceTaxTest.php
new file mode 100644
index 000000000..b07cccad5
--- /dev/null
+++ b/src/modules/Invoice/tests/Unit/ServiceTaxTest.php
@@ -0,0 +1,319 @@
+setDi($di);
+ $getDi = $service->getDi();
+ expect($getDi)->toBe($di);
+});
+
+test('gets tax rate for client by country and state', function (): void {
+ $service = new ServiceTax();
+ $taxRateExpected = 0.21;
+ $clientModel = new Model_Client();
+ $clientModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $clientServiceMock = Mockery::mock(ClientService::class);
+ $clientServiceMock->shouldReceive('isClientTaxable')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $taxModel = new Model_Tax();
+ $taxModel->loadBean(new Tests\Helpers\DummyBean());
+ $taxModel->taxrate = $taxRateExpected;
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn($taxModel);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $clientServiceMock);
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $result = $service->getTaxRateForClient($clientModel);
+ expect($result)->toBeFloat();
+ expect($result)->toBe($taxRateExpected);
+});
+
+test('gets tax rate for client by country', function (): void {
+ $service = new ServiceTax();
+ $taxRateExpected = 0.21;
+ $clientModel = new Model_Client();
+ $clientModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $clientServiceMock = Mockery::mock(ClientService::class);
+ $clientServiceMock->shouldReceive('isClientTaxable')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $taxModel = new Model_Tax();
+ $taxModel->loadBean(new Tests\Helpers\DummyBean());
+ $taxModel->taxrate = $taxRateExpected;
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $callCount = 0;
+ $dbMock->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturnUsing(function () use (&$callCount, $taxModel) {
+ ++$callCount;
+ if ($callCount == 1) {
+ return null;
+ }
+
+ return $taxModel;
+ });
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $clientServiceMock);
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $result = $service->getTaxRateForClient($clientModel);
+ expect($result)->toBeFloat();
+ expect($result)->toBe($taxRateExpected);
+});
+
+test('gets tax rate for client', function (): void {
+ $service = new ServiceTax();
+ $taxRateExpected = 0.21;
+ $clientModel = new Model_Client();
+ $clientModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $clientServiceMock = Mockery::mock(ClientService::class);
+ $clientServiceMock->shouldReceive('isClientTaxable')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $taxModel = new Model_Tax();
+ $taxModel->loadBean(new Tests\Helpers\DummyBean());
+ $taxModel->taxrate = $taxRateExpected;
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $callCount = 0;
+ $dbMock->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturnUsing(function () use (&$callCount, $taxModel) {
+ ++$callCount;
+ if ($callCount <= 2) {
+ return null;
+ }
+
+ return $taxModel;
+ });
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $clientServiceMock);
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $result = $service->getTaxRateForClient($clientModel);
+ expect($result)->toBeFloat();
+ expect($result)->toBe($taxRateExpected);
+});
+
+test('returns zero tax rate when tax not found', function (): void {
+ $service = new ServiceTax();
+ $clientModel = new Model_Client();
+ $clientModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $clientServiceMock = Mockery::mock(ClientService::class);
+ $clientServiceMock->shouldReceive('isClientTaxable')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn(null);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $clientServiceMock);
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $taxRateExpected = 0;
+ $result = $service->getTaxRateForClient($clientModel);
+ expect($result)->toBeInt();
+ expect($result)->toBe($taxRateExpected);
+});
+
+test('returns zero tax rate when client is not taxable', function (): void {
+ $service = new ServiceTax();
+ $clientModel = new Model_Client();
+ $clientModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $clientServiceMock = Mockery::mock(ClientService::class);
+ $clientServiceMock->shouldReceive('isClientTaxable')
+ ->atLeast()->once()
+ ->andReturn(false);
+
+ $taxModel = new Model_Tax();
+ $taxModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $clientServiceMock);
+ $service->setDi($di);
+
+ $taxRateExpected = 0;
+ $result = $service->getTaxRateForClient($clientModel);
+ expect($result)->toBeInt();
+ expect($result)->toBe($taxRateExpected);
+});
+
+test('returns zero tax when tax rate is zero', function (): void {
+ $service = new ServiceTax();
+ $invoiceModel = new Model_Invoice();
+ $invoiceModel->loadBean(new Tests\Helpers\DummyBean());
+ $invoiceModel->taxrate = 0;
+
+ $result = $service->getTax($invoiceModel);
+ expect($result)->toBeInt();
+ expect($result)->toBe(0);
+});
+
+test('gets tax', function (): void {
+ $service = new ServiceTax();
+ $invoiceModel = new Model_Invoice();
+ $invoiceModel->loadBean(new Tests\Helpers\DummyBean());
+ $invoiceModel->taxrate = 15;
+
+ $invoiceItemModel = new Model_InvoiceItem();
+ $invoiceItemModel->loadBean(new Tests\Helpers\DummyBean());
+ $invoiceItemModel->quantity = 1;
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('find')
+ ->atLeast()->once()
+ ->andReturn([$invoiceItemModel]);
+
+ $invoiceItemService = Mockery::mock(ServiceInvoiceItem::class);
+ $invoiceItemService->shouldReceive('getTax')
+ ->atLeast()->once()
+ ->andReturn(21);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $invoiceItemService);
+ $di['db'] = $dbMock;
+
+ $service->setDi($di);
+ $result = $service->getTax($invoiceModel);
+ expect($result)->toBeInt();
+});
+
+test('deletes a tax', function (): void {
+ $service = new ServiceTax();
+ $taxModel = new Model_Tax();
+ $taxModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('trash')
+ ->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $service->setDi($di);
+
+ $result = $service->delete($taxModel);
+ expect($result)->toBeTrue();
+});
+
+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());
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('dispense')
+ ->atLeast()->once()
+ ->andReturn($taxModel);
+ $newId = 2;
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once()
+ ->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);
+
+ $data = [
+ 'name' => 'tax',
+ 'taxrate' => '0.18',
+ ];
+ $result = $service->create($data);
+ expect($result)->toBeInt()->toBe($newId);
+});
+
+test('updates a tax', function (): void {
+ $service = new ServiceTax();
+ $taxModel = new Model_Tax();
+ $taxModel->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn(2);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $service->setDi($di);
+
+ $data = [
+ 'name' => 'tax',
+ 'taxrate' => '0.18',
+ ];
+ $result = $service->update($taxModel, $data);
+ expect($result)->toBeBool()->toBeTrue();
+});
+
+test('gets search query', function (): void {
+ $service = new ServiceTax();
+ $result = $service->getSearchQuery([]);
+ expect($result[0])->toBeString();
+ expect($result[1])->toBeArray();
+ expect($result[1])->toBe([]);
+});
+
+test('converts to api array', function (): void {
+ $service = new ServiceTax();
+ $taxModel = new Model_Tax();
+ $taxModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('toArray')
+ ->with($taxModel)
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $result = $service->toApiArray($taxModel);
+ expect($result)->toBeArray();
+});
diff --git a/src/modules/Invoice/tests/Unit/ServiceTest.php b/src/modules/Invoice/tests/Unit/ServiceTest.php
new file mode 100644
index 000000000..d41d8aef3
--- /dev/null
+++ b/src/modules/Invoice/tests/Unit/ServiceTest.php
@@ -0,0 +1,1743 @@
+setDi($di);
+ $getDi = $service->getDi();
+ expect($getDi)->toBe($di);
+});
+
+test('gets search query with various parameters', function (array $data, string $expectedStr, array $expectedParams): void {
+ $service = new Service();
+ $di = container();
+
+ $service->setDi($di);
+ $result = $service->getSearchQuery($data);
+ expect($result[0])->toBeString();
+ expect($result[1])->toBeArray();
+
+ expect(str_contains((string) $result[0], $expectedStr))->toBeTrue($result[0]);
+ expect(array_diff_key($result[1], $expectedParams))->toBe([]);
+})->with([
+ [[], 'FROM invoice p', []],
+ [
+ ['order_id' => '1'],
+ 'AND pi.type = :item_type AND pi.rel_id = :order_id',
+ [
+ 'item_type' => Model_InvoiceItem::TYPE_ORDER,
+ 'order_id' => 1,
+ ],
+ ],
+ [
+ ['id' => 1],
+ 'AND p.id = :id',
+ [
+ 'id' => 1,
+ ],
+ ],
+ [
+ ['nr' => 1],
+ 'AND (p.id = :id_nr OR p.nr = :id_nr)',
+ [
+ 'id_nr' => 1,
+ ],
+ ],
+ [
+ ['approved' => true],
+ 'AND p.approved = :approved',
+ [
+ 'approved' => true,
+ ],
+ ],
+ [
+ ['status' => 'unpaid'],
+ 'AND p.status = :status',
+ [
+ 'status' => 'unpaid',
+ ],
+ ],
+ [
+ ['currency' => 'usd'],
+ 'AND p.currency = :currency',
+ [
+ 'currency' => 'usd',
+ ],
+ ],
+ [
+ ['client_id' => 1],
+ 'AND p.client_id = :client_id',
+ [
+ 'client_id' => 1,
+ ],
+ ],
+ [
+ ['client' => 'John'],
+ 'AND (cl.first_name LIKE :client_search OR cl.last_name LIKE :client_search OR cl.id = :client OR cl.email = :client)',
+ [
+ 'client_search' => 'John%',
+ 'client' => 'John',
+ ],
+ ],
+ [
+ ['created_at' => '1353715200'],
+ "AND DATE_FORMAT(p.created_at, '%Y-%m-%d') = :created_at",
+ [
+ 'created_at' => '1353715200',
+ ],
+ ],
+ [
+ ['date_from' => '1353715200'],
+ 'AND UNIX_TIMESTAMP(p.created_at) >= :date_from',
+ [
+ 'date_from' => '1353715200',
+ ],
+ ],
+ [
+ ['date_to' => '1353715200'],
+ 'AND UNIX_TIMESTAMP(p.created_at) <= :date_to',
+ [
+ 'date_to' => '1353715200',
+ ],
+ ],
+ [
+ ['paid_at' => '1353715200'],
+ "AND DATE_FORMAT(p.paid_at, '%Y-%m-%d') = :paid_at",
+ [
+ 'paid_at' => '1353715200',
+ ],
+ ],
+ [
+ ['search' => 'trend'],
+ 'AND (p.id = :search_numeric_id OR p.nr LIKE :search_like OR p.id LIKE :search OR pi.title LIKE :search_like)',
+ [
+ 'search' => 'trend',
+ 'search_like' => '%trend%',
+ 'search_numeric_id' => 0,
+ ],
+ ],
+]);
+
+test('converts to api array', function (): void {
+ $service = new Service();
+ $invoiceModel = new Model_Invoice();
+ $invoiceModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $invoiceItemModel = new Model_InvoiceItem();
+ $invoiceItemModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $systemService = Mockery::mock(SystemService::class);
+ $systemService->shouldReceive('getCompany')
+ ->atLeast()->once();
+ $systemService->shouldReceive('getParamValue')
+ ->atLeast()->once()
+ ->andReturn(5);
+
+ $subscriptionServiceMock = Mockery::mock(ServiceSubscription::class);
+ $subscriptionServiceMock->shouldReceive('getSubscriptionPeriod')
+ ->byDefault()
+ ->andReturn('1W');
+
+ $modelToArrayResult = [
+ 'id' => 1,
+ 'serie' => 'BB',
+ 'nr' => '0001',
+ 'serie_nr' => 'BB0001',
+ 'hash' => 'hashedValue',
+ 'gateway_id' => '',
+ 'taxname' => '',
+ 'taxrate' => '',
+ 'currency' => '',
+ 'currency_rate' => '',
+ 'status' => '',
+ 'notes' => '',
+ 'text_1' => '',
+ 'text_2' => '',
+ 'due_at' => '',
+ 'paid_at' => '',
+ 'created_at' => '',
+ 'updated_at' => '',
+ 'buyer_first_name' => '',
+ 'buyer_last_name' => '',
+ 'buyer_company' => '',
+ 'buyer_company_vat' => '',
+ 'buyer_company_number' => '',
+ 'buyer_address' => '',
+ 'buyer_city' => '',
+ 'buyer_state' => '',
+ 'buyer_country' => '',
+ 'buyer_phone' => '',
+ 'buyer_phone_cc' => '',
+ 'buyer_email' => '',
+ 'buyer_zip' => '',
+ 'seller_company_vat' => '',
+ 'seller_company_number' => '',
+ ];
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('toArray')
+ ->atLeast()->once()
+ ->andReturn($modelToArrayResult);
+ $dbMock->shouldReceive('find')
+ ->atLeast()->once()
+ ->andReturn([$invoiceItemModel]);
+ $dbMock->shouldReceive('getCell')
+ ->byDefault()
+ ->andReturn('1W');
+ $subscriptionServiceMock->shouldReceive('getSubscriptionPeriod')
+ ->byDefault()
+ ->andReturn('1W');
+
+ $periodMock = Mockery::mock('\Box_Period');
+ $periodMock->shouldReceive('getUnit');
+ $periodMock->shouldReceive('getQty');
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(function ($serviceName, $sub = '') use ($systemService, $subscriptionServiceMock) {
+ $service = null;
+ if ($sub == 'InvoiceItem') {
+ }
+ if ($serviceName == 'system' || $serviceName == 'System') {
+ $service = $systemService;
+ }
+ if ($sub == 'Subscription') {
+ $service = $subscriptionServiceMock;
+ }
+
+ return $service;
+ });
+ $di['period'] = $di->protect(fn (): Mockery\MockInterface => $periodMock);
+
+ $service->setDi($di);
+
+ $result = $service->toApiArray($invoiceModel);
+ expect($result)->toBeArray();
+});
+
+test('handles after admin invoice payment received event', function (): void {
+ $service = new Service();
+ $serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $arr = [
+ 'total' => 1,
+ 'client' => [
+ 'id' => 0,
+ ],
+ ];
+ $serviceMock->shouldReceive('toApiArray')
+ ->atLeast()->once()
+ ->andReturn($arr);
+
+ $eventMock = Mockery::mock('\Box_Event');
+ $eventMock->shouldReceive('getParameters')
+ ->atLeast()->once();
+
+ $emailService = Mockery::mock(EmailService::class);
+ $emailService->shouldReceive('sendTemplate')
+ ->atLeast()->once();
+
+ $invoiceModel = new Model_Invoice();
+ $invoiceModel->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('load')
+ ->atLeast()->once()
+ ->andReturn($invoiceModel);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(function ($serviceName) use ($emailService, $serviceMock) {
+ if ($serviceName == 'invoice') {
+ return $serviceMock;
+ }
+ if ($serviceName == 'email') {
+ return $emailService;
+ }
+ });
+ $di['db'] = $dbMock;
+
+ $service->setDi($di);
+ $serviceMock->setDi($di);
+ $eventMock->shouldReceive('getDi')
+ ->atLeast()->once()
+ ->andReturn($di);
+
+ $result = $service->onAfterAdminInvoicePaymentReceived($eventMock);
+ expect($result)->toBeBool()->toBeTrue();
+});
+
+test('handles after admin invoice reminder sent event', function (): void {
+ $service = new Service();
+ $serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $arr = [
+ 'total' => 1,
+ 'client' => [
+ 'id' => 1,
+ ],
+ ];
+ $serviceMock->shouldReceive('toApiArray')
+ ->atLeast()->once()
+ ->andReturn($arr);
+
+ $eventMock = Mockery::mock('\Box_Event');
+ $eventMock->shouldReceive('getParameters')
+ ->atLeast()->once();
+
+ $emailService = Mockery::mock(EmailService::class);
+ $emailService->shouldReceive('sendTemplate')
+ ->atLeast()->once();
+
+ $invoiceModel = new Model_Invoice();
+ $invoiceModel->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('load')
+ ->atLeast()->once()
+ ->andReturn($invoiceModel);
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once();
+
+ $di = container();
+ $di['mod_service'] = $di->protect(function ($serviceName) use ($emailService, $serviceMock) {
+ if ($serviceName == 'invoice') {
+ return $serviceMock;
+ }
+ if ($serviceName == 'system' || $serviceName == 'System') {
+ $systemService = Mockery::mock(SystemService::class);
+ $systemService->shouldReceive('getParamValue')
+ ->with('invoice_hash_lifetime_days', '90')
+ ->andReturn('90');
+
+ return $systemService;
+ }
+ if ($serviceName == 'email' || $serviceName == 'Email') {
+ return $emailService;
+ }
+ });
+ $di['db'] = $dbMock;
+
+ $service->setDi($di);
+ $serviceMock->setDi($di);
+ $eventMock->shouldReceive('getDi')
+ ->atLeast()->once()
+ ->andReturn($di);
+
+ $service->onAfterAdminInvoiceReminderSent($eventMock);
+});
+
+test('handles after admin cron run event', function (): void {
+ $service = new Service();
+ $eventMock = Mockery::mock('\Box_Event');
+
+ $remove_after_days = 64;
+ $systemServiceMock = Mockery::mock(SystemService::class);
+ $systemServiceMock->shouldReceive('getParamValue')
+ ->with('remove_after_days')
+ ->atLeast()->once()
+ ->andReturn($remove_after_days);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('exec')
+ ->atLeast()->once();
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $systemServiceMock);
+ $di['db'] = $dbMock;
+
+ $service->setDi($di);
+ $eventMock->shouldReceive('getDi')
+ ->atLeast()->once()
+ ->andReturn($di);
+
+ $service->onAfterAdminCronRun($eventMock);
+});
+
+test('handles event after invoice is due', function (): void {
+ $service = new Service();
+ $serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $arr = [
+ 'total' => 1,
+ 'client' => [
+ 'id' => 1,
+ ],
+ ];
+ $serviceMock->shouldReceive('toApiArray')
+ ->atLeast()->once()
+ ->andReturn($arr);
+
+ $eventMock = Mockery::mock('\Box_Event');
+ $params = ['days_passed' => 5, 'id' => 1];
+ $eventMock->shouldReceive('getParameters')
+ ->atLeast()->once()
+ ->andReturn($params);
+
+ $emailService = Mockery::mock(EmailService::class);
+ $emailService->shouldReceive('sendTemplate')
+ ->atLeast()->once();
+
+ $invoiceModel = new Model_Invoice();
+ $invoiceModel->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('load')
+ ->atLeast()->once()
+ ->andReturn($invoiceModel);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(function ($serviceName) use ($emailService, $serviceMock) {
+ if ($serviceName == 'invoice') {
+ return $serviceMock;
+ }
+ if ($serviceName == 'email') {
+ return $emailService;
+ }
+ });
+ $di['db'] = $dbMock;
+
+ $serviceMock->setDi($di);
+ $eventMock->shouldReceive('getDi')
+ ->atLeast()->once()
+ ->andReturn($di);
+ $serviceMock->onEventAfterInvoiceIsDue($eventMock);
+});
+
+test('marks invoice as paid', function (): void {
+ $service = new Service();
+ $serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('countIncome')
+ ->atLeast()->once();
+
+ $invoiceModel = new Model_Invoice();
+ $invoiceModel->loadBean(new Tests\Helpers\DummyBean());
+ $invoiceModel->status = Model_Invoice::STATUS_UNPAID;
+
+ $invoiceItemModel = new Model_InvoiceItem();
+ $invoiceItemModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $itemInvoiceServiceMock = Mockery::mock(ServiceInvoiceItem::class);
+ $itemInvoiceServiceMock->shouldReceive('markAsPaid')
+ ->atLeast()->once();
+ $itemInvoiceServiceMock->shouldReceive('executeTask')
+ ->atLeast()->once();
+
+ $systemService = Mockery::mock(SystemService::class);
+ $systemService->shouldReceive('getParamValue')
+ ->atLeast()->once();
+
+ $currencyRepositoryMock = Mockery::mock(CurrencyRepository::class);
+ $currencyRepositoryMock->shouldReceive('getRateByCode')
+ ->atLeast()->once()
+ ->andReturn(1.0);
+
+ $currencyServiceMock = Mockery::mock(CurrencyService::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $currencyServiceMock->shouldReceive('getCurrencyRepository')
+ ->atLeast()->once()
+ ->andReturn($currencyRepositoryMock);
+
+ $eventManagerMock = Mockery::mock('\Box_EventManager');
+ $eventManagerMock->shouldReceive('fire')
+ ->atLeast()->once();
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('find')
+ ->atLeast()->once()
+ ->andReturn([$invoiceItemModel]);
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once();
+
+ $di = container();
+ $di['mod_service'] = $di->protect(function ($serviceName, $sub = '') use ($systemService, $itemInvoiceServiceMock, $currencyServiceMock) {
+ if ($serviceName == 'system') {
+ return $systemService;
+ }
+ if ($sub == 'InvoiceItem') {
+ return $itemInvoiceServiceMock;
+ }
+ if ($serviceName == 'currency') {
+ return $currencyServiceMock;
+ }
+ });
+ $di['db'] = $dbMock;
+ $di['events_manager'] = $eventManagerMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $serviceMock->setDi($di);
+ $result = $serviceMock->markAsPaid($invoiceModel, true, true);
+ expect($result)->toBeBool()->toBeTrue();
+});
+
+test('counts income', function (): void {
+ $service = new Service();
+ $serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
+
+ $invoiceModel = new Model_Invoice();
+ $invoiceModel->loadBean(new Tests\Helpers\DummyBean());
+ $invoiceModel->currency = 'USD';
+ $invoiceModel->refund = 0;
+
+ $currencyService = Mockery::mock(CurrencyService::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $currencyService->shouldReceive('toBaseCurrency')
+ ->atLeast()->once()
+ ->andReturn(0.0);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('find')
+ ->atLeast()->once()
+ ->andReturn([]);
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $currencyService);
+
+ $serviceMock->setDi($di);
+ $serviceMock->countIncome($invoiceModel);
+});
+
+test('prepares invoice with undefined currency', function (): void {
+ $service = new Service();
+ $serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('setInvoiceDefaults')
+ ->atLeast()->once();
+
+ $data = [
+ 'gateway_id' => '',
+ 'text_1' => '',
+ 'text_2' => '',
+ 'items' => [
+ [
+ 'id' => 1,
+ ],
+ ],
+ 'approve',
+ ];
+
+ $clientModel = new Model_Client();
+ $clientModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $invoiceModel = new Model_Invoice();
+ $invoiceModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $currencyModel = Mockery::mock(CurrencyEntity::class);
+ $defaultCurrencyCode = 'USD';
+ $currencyModel->shouldReceive('getCode')
+ ->andReturn($defaultCurrencyCode);
+
+ $currencyRepositoryMock = Mockery::mock(CurrencyRepository::class);
+ $currencyRepositoryMock->shouldReceive('findDefault')
+ ->atLeast()->once()
+ ->andReturn($currencyModel);
+
+ $currencyServiceMock = Mockery::mock(CurrencyService::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $currencyServiceMock->shouldReceive('getCurrencyRepository')
+ ->atLeast()->once()
+ ->andReturn($currencyRepositoryMock);
+
+ $itemInvoiceServiceMock = Mockery::mock(ServiceInvoiceItem::class);
+ $itemInvoiceServiceMock->shouldReceive('addNew')
+ ->atLeast()->once();
+
+ $newRecordId = 1;
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn($newRecordId);
+ $dbMock->shouldReceive('dispense')
+ ->atLeast()->once()
+ ->andReturn($invoiceModel);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(function ($serviceName, $sub = '') use ($currencyServiceMock, $itemInvoiceServiceMock) {
+ if ($serviceName == 'currency' || $serviceName == 'Currency') {
+ return $currencyServiceMock;
+ }
+ if ($sub == 'InvoiceItem') {
+ return $itemInvoiceServiceMock;
+ }
+ });
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $serviceMock->setDi($di);
+ $result = $serviceMock->prepareInvoice($clientModel, $data);
+ expect($result)->toBeInstanceOf(Model_Invoice::class);
+ expect($result->currency)->toBe($defaultCurrencyCode);
+});
+
+test('sets invoice defaults', function (): void {
+ $service = new Service();
+ $invoiceModel = new Model_Invoice();
+ $invoiceModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $clientModel = new Model_Client();
+ $clientModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $buyer = [
+ 'first_name' => '',
+ 'last_name' => '',
+ 'company' => '',
+ 'company_vat' => '',
+ 'company_number' => '',
+ 'address_1' => '',
+ 'address_2' => '',
+ 'city' => '',
+ 'state' => '',
+ 'country' => '',
+ 'phone_cc' => '',
+ 'phone' => '',
+ 'email' => '',
+ 'postcode' => '',
+ ];
+
+ $clientService = Mockery::mock(ClientService::class);
+ $clientService->shouldReceive('toApiArray')
+ ->atLeast()->once()
+ ->andReturn($buyer);
+
+ $systemService = Mockery::mock(SystemService::class);
+ $seller = [
+ 'name' => '',
+ 'vat_number' => '',
+ 'number' => '',
+ 'address_1' => '',
+ 'address_2' => '',
+ 'address_3' => '',
+ 'tel' => '',
+ 'email' => '',
+ ];
+ $systemService->shouldReceive('getCompany')
+ ->atLeast()->once()
+ ->andReturn($seller);
+ $systemService->shouldReceive('getParamValue')
+ ->atLeast()->once()
+ ->andReturn(1);
+ $systemService->shouldReceive('setParamValue')
+ ->atLeast()->once();
+
+ $serviceTaxMock = Mockery::mock(ServiceTax::class);
+ $serviceTaxMock->shouldReceive('getTaxRateForClient');
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('load')
+ ->atLeast()->once()
+ ->andReturn($clientModel);
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(function ($serviceName, $sub = '') use ($clientService, $systemService, $serviceTaxMock) {
+ if ($serviceName == 'Client') {
+ return $clientService;
+ }
+ if ($serviceName == 'system') {
+ return $systemService;
+ }
+ if ($sub == 'Tax') {
+ return $serviceTaxMock;
+ }
+ });
+
+ $service->setDi($di);
+
+ $service->setInvoiceDefaults($invoiceModel);
+});
+
+test('approves an invoice', function (): void {
+ $service = new Service();
+ $serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('tryPayWithCredits')
+ ->atLeast()->once();
+ $serviceMock->shouldReceive('toApiArray')
+ ->atLeast()->once()
+ ->andReturn(['id' => 1]);
+
+ $data['use_credits'] = true;
+
+ $invoiceModel = new Model_Invoice();
+ $invoiceModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $eventManagerMock = Mockery::mock('\Box_EventManager');
+ $eventManagerMock->shouldReceive('fire')
+ ->atLeast()->once();
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['events_manager'] = $eventManagerMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $serviceMock->setDi($di);
+
+ $result = $serviceMock->approveInvoice($invoiceModel, $data);
+ expect($result)->toBeTrue();
+});
+
+test('gets total with tax', function (): void {
+ $service = new Service();
+ $total = 10.0;
+ $tax = 2.2;
+ $expected = $total + $tax;
+ $serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('getTotal')
+ ->once()
+ ->andReturn($total);
+ $serviceMock->shouldReceive('getTax')
+ ->once()
+ ->andReturn($tax);
+
+ $invoiceModel = new Model_Invoice();
+ $invoiceModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $result = $serviceMock->getTotalWithTax($invoiceModel);
+ expect($result)->toBeFloat();
+ expect($result)->toBe($expected);
+});
+
+test('gets total', function (): void {
+ $service = new Service();
+ $invoiceModel = new Model_Invoice();
+ $invoiceModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $invoiceItemModel = new Model_InvoiceItem();
+ $invoiceItemModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('find')
+ ->atLeast()->once()
+ ->andReturn([$invoiceItemModel]);
+
+ $itemInvoiceServiceMock = Mockery::mock(ServiceInvoiceItem::class);
+ $itemTotal = 10.0;
+ $itemInvoiceServiceMock->shouldReceive('getTotal')
+ ->atLeast()->once()
+ ->andReturn($itemTotal);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $itemInvoiceServiceMock);
+
+ $service->setDi($di);
+ $result = $service->getTotal($invoiceModel);
+ expect($result)->toBeFloat();
+ expect($result)->toBe($itemTotal);
+});
+
+test('refunds invoice with negative invoice logic', function (): void {
+ $service = new Service();
+ $newId = 1;
+ $total = 10.0;
+ $tax = 2.2;
+ $serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('getTotal')
+ ->once()
+ ->andReturn($total);
+ $serviceMock->shouldReceive('getTax')
+ ->once()
+ ->andReturn($tax);
+ $serviceMock->shouldReceive('countIncome')
+ ->once();
+ $serviceMock->shouldReceive('addNote')
+ ->times(3);
+ $serviceMock->shouldReceive('toApiArray')
+ ->atLeast()->once()
+ ->andReturn(['id' => $newId]);
+
+ $invoiceModel = new Model_Invoice();
+ $invoiceModel->loadBean(new Tests\Helpers\DummyBean());
+ $invoiceModel->id = $newId;
+
+ $invoiceItemModel = new Model_InvoiceItem();
+ $invoiceItemModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $eventManagerMock = Mockery::mock('\Box_EventManager');
+ $eventManagerMock->shouldReceive('fire')
+ ->atLeast()->once();
+
+ $systemService = Mockery::mock(SystemService::class);
+ $systemService->shouldReceive('getParamValue')
+ ->atLeast()->once()
+ ->andReturn('negative_invoice');
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dispenseCount = 0;
+ $dbMock->shouldReceive('dispense')
+ ->atLeast()->once()
+ ->andReturnUsing(function () use (&$dispenseCount, $invoiceModel, $invoiceItemModel) {
+ return ++$dispenseCount === 1 ? $invoiceModel : $invoiceItemModel;
+ });
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once();
+ $dbMock->shouldReceive('find')
+ ->atLeast()->once()
+ ->andReturn([$invoiceItemModel]);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $systemService);
+ $di['events_manager'] = $eventManagerMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $serviceMock->setDi($di);
+ $result = $serviceMock->refundInvoice($invoiceModel, 'customNote');
+ expect($result)->toBeInt()->toBe($newId);
+});
+
+test('updates an invoice', function (): void {
+ $service = new Service();
+ $data = [
+ 'gateway_id' => '',
+ 'taxname' => '',
+ 'taxrate' => '',
+ 'status' => '',
+ 'notes' => '',
+ 'text_1' => '',
+ 'text_2' => '',
+ 'due_at' => '',
+ 'paid_at' => '',
+ 'buyer_first_name' => '',
+ 'buyer_last_name' => '',
+ 'buyer_company' => '',
+ 'buyer_company_vat' => '',
+ 'buyer_company_number' => '',
+ 'buyer_address' => '',
+ 'buyer_city' => '',
+ 'buyer_state' => '',
+ 'buyer_country' => '',
+ 'buyer_phone' => '',
+ 'buyer_email' => '',
+ 'buyer_zip' => '',
+ 'seller_company' => '',
+ 'seller_address' => '',
+ 'seller_phone' => '',
+ 'seller_email' => '',
+ 'seller_company_vat' => '',
+ 'seller_company_number' => '',
+ 'approved' => '',
+ 'items' => [0 => []],
+ 'new_item' => ['title' => 'new Item'],
+ ];
+
+ $invoiceModel = new Model_Invoice();
+ $invoiceModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $invoiceItemModel = new Model_InvoiceItem();
+ $invoiceItemModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $eventManagerMock = Mockery::mock('\Box_EventManager');
+ $eventManagerMock->shouldReceive('fire')
+ ->atLeast()->once();
+
+ $itemInvoiceServiceMock = Mockery::mock(ServiceInvoiceItem::class);
+ $itemInvoiceServiceMock->shouldReceive('addNew')
+ ->atLeast()->once();
+ $itemInvoiceServiceMock->shouldReceive('update')
+ ->atLeast()->once();
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once();
+ $dbMock->shouldReceive('load')
+ ->atLeast()->once()
+ ->andReturn($invoiceItemModel);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $itemInvoiceServiceMock);
+ $di['events_manager'] = $eventManagerMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('toApiArray')
+ ->atLeast()->once()
+ ->andReturn(['id' => 1]);
+
+ $serviceMock->setDi($di);
+
+ $result = $serviceMock->updateInvoice($invoiceModel, $data);
+ expect($result)->toBeTrue();
+});
+
+test('removes an invoice', function (): void {
+ $service = new Service();
+ $invoiceModel = new Model_Invoice();
+ $invoiceModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $invoiceItemModel = new Model_InvoiceItem();
+ $invoiceItemModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('exec')
+ ->atLeast()->once();
+ $dbMock->shouldReceive('find')
+ ->atLeast()->once()
+ ->andReturn([$invoiceItemModel]);
+ $dbMock->shouldReceive('trash')
+ ->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $service->setDi($di);
+
+ $result = $service->rmInvoice($invoiceModel);
+ expect($result)->toBeTrue();
+});
+
+test('deletes invoice by admin', function (): void {
+ $service = new Service();
+ $serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('rmInvoice')
+ ->once();
+
+ $invoiceModel = new Model_Invoice();
+ $invoiceModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $eventManagerMock = Mockery::mock('\Box_EventManager');
+ $eventManagerMock->shouldReceive('fire')
+ ->atLeast()->once();
+
+ $di = container();
+ $di['events_manager'] = $eventManagerMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $serviceMock->setDi($di);
+
+ $result = $serviceMock->deleteInvoiceByAdmin($invoiceModel);
+ expect($result)->toBeTrue();
+});
+
+test('renews an invoice', function (): void {
+ $service = new Service();
+ $newId = 2;
+ $invoiceModel = new Model_Invoice();
+ $invoiceModel->loadBean(new Tests\Helpers\DummyBean());
+ $invoiceModel->id = $newId;
+
+ $clientOrder = new Model_ClientOrder();
+ $clientOrder->loadBean(new Tests\Helpers\DummyBean());
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('approveInvoice')
+ ->once();
+ $serviceMock->shouldReceive('generateForOrder')
+ ->once()
+ ->andReturn($invoiceModel);
+
+ $eventManagerMock = Mockery::mock('\Box_EventManager');
+ $eventManagerMock->shouldReceive('fire')
+ ->atLeast()->once();
+
+ $di = container();
+ $di['events_manager'] = $eventManagerMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $serviceMock->setDi($di);
+ $result = $serviceMock->renewInvoice($clientOrder, []);
+ expect($result)->toBeInt()->toBe($newId);
+});
+
+test('processes batch pay with credits', function (): void {
+ $service = new Service();
+ $invoiceModel = new Model_Invoice();
+ $invoiceModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('findAllUnpaid')
+ ->atLeast()->once()
+ ->andReturn([[]]);
+ $serviceMock->shouldReceive('tryPayWithCredits')
+ ->atLeast()->once();
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($invoiceModel);
+
+ $di = container();
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $di['db'] = $dbMock;
+
+ $serviceMock->setDi($di);
+ $result = $serviceMock->doBatchPayWithCredits([]);
+ expect($result)->toBeBool()->toBeTrue();
+});
+
+test('pays invoice with credits', function (): void {
+ $service = new Service();
+ $invoiceModel = new Model_Invoice();
+ $invoiceModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('tryPayWithCredits')
+ ->atLeast()->once();
+
+ $di = container();
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $serviceMock->setDi($di);
+ $result = $serviceMock->payInvoiceWithCredits($invoiceModel);
+ expect($result)->toBeBool()->toBeTrue();
+});
+
+test('returns existing invoice when generating for order with unpaid invoice', function (): void {
+ $service = new Service();
+ $clientOrder = new Model_ClientOrder();
+ $clientOrder->loadBean(new Tests\Helpers\DummyBean());
+ $clientOrder->unpaid_invoice_id = 2;
+
+ $invoiceModel = new Model_Invoice();
+ $invoiceModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('load')
+ ->atLeast()->once()
+ ->andReturn($invoiceModel);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $service->setDi($di);
+ $result = $service->generateForOrder($clientOrder);
+ expect($result)->toBeInstanceOf(Model_Invoice::class);
+});
+
+test('generates invoice for order', function (): void {
+ $service = new Service();
+ $serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('setInvoiceDefaults')
+ ->once();
+
+ $orderModel = new Model_ClientOrder();
+ $orderModel->loadBean(new Tests\Helpers\DummyBean());
+ $orderModel->price = 10;
+ $orderModel->promo_recurring = true;
+
+ $clientModel = new Model_Client();
+ $clientModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $invoiceModel = new Model_Invoice();
+ $invoiceModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($clientModel);
+ $dbMock->shouldReceive('dispense')
+ ->atLeast()->once()
+ ->andReturn($invoiceModel);
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once();
+
+ $invoiceItemServiceMock = Mockery::mock(ServiceInvoiceItem::class);
+ $invoiceItemServiceMock->shouldReceive('generateFromOrder')
+ ->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $invoiceItemServiceMock);
+
+ $serviceMock->setDi($di);
+ $result = $serviceMock->generateForOrder($orderModel);
+ expect($result)->toBeInstanceOf(Model_Invoice::class);
+});
+
+test('throws exception when generating invoice for zero amount order', function (): void {
+ $service = new Service();
+ $clientOrder = new Model_ClientOrder();
+ $clientOrder->loadBean(new Tests\Helpers\DummyBean());
+ $clientOrder->price = 0;
+
+ expect(fn () => $service->generateForOrder($clientOrder))
+ ->toThrow(FOSSBilling\Exception::class, 'Invoices are not generated for 0 amount orders');
+});
+
+test('returns true when no expiring orders found', function (): void {
+ $service = new Service();
+ $orderService = Mockery::mock(OrderService::class);
+ $orderService->shouldReceive('getSoonExpiringActiveOrders')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderService);
+
+ $service->setDi($di);
+ $result = $service->generateInvoicesForExpiringOrders();
+ expect($result)->toBeBool()->toBeTrue();
+});
+
+test('generates invoices for expiring orders', function (): void {
+ $service = new Service();
+ $clientOrder = new Model_ClientOrder();
+ $clientOrder->loadBean(new Tests\Helpers\DummyBean());
+
+ $invoiceModel = new Model_Invoice();
+ $invoiceModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $newId = 4;
+ $invoiceModel->id = $newId;
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('approveInvoice')
+ ->once();
+ $serviceMock->shouldReceive('generateForOrder')
+ ->once()
+ ->andReturn($invoiceModel);
+
+ $orderService = Mockery::mock(OrderService::class);
+ $orderService->shouldReceive('getSoonExpiringActiveOrders')
+ ->atLeast()->once()
+ ->andReturn([[]]);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($clientOrder);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderService);
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $di['db'] = $dbMock;
+
+ $serviceMock->setDi($di);
+ $result = $serviceMock->generateInvoicesForExpiringOrders();
+ expect($result)->toBeBool()->toBeTrue();
+});
+
+test('activates paid invoices in batch', function (): void {
+ $service = new Service();
+ $invoiceItemModel = new Model_InvoiceItem();
+ $invoiceItemModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $itemInvoiceServiceMock = Mockery::mock(ServiceInvoiceItem::class);
+ $itemInvoiceServiceMock->shouldReceive('executeTask')
+ ->with($invoiceItemModel);
+ $itemInvoiceServiceMock->shouldReceive('getAllNotExecutePaidItems')
+ ->atLeast()->once()
+ ->andReturn([[]]);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($invoiceItemModel);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $itemInvoiceServiceMock);
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $di['db'] = $dbMock;
+
+ $service->setDi($di);
+ $result = $service->doBatchPaidInvoiceActivation();
+ expect($result)->toBeBool()->toBeTrue();
+});
+
+test('handles exception during batch paid invoice activation', function (): void {
+ $service = new Service();
+ $invoiceItemModel = new Model_InvoiceItem();
+ $invoiceItemModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $itemInvoiceServiceMock = Mockery::mock(ServiceInvoiceItem::class);
+ $itemInvoiceServiceMock->shouldReceive('executeTask')
+ ->with($invoiceItemModel)
+ ->andThrow(new FOSSBilling\Exception('testing exception..'));
+ $itemInvoiceServiceMock->shouldReceive('getAllNotExecutePaidItems')
+ ->atLeast()->once()
+ ->andReturn([[]]);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($invoiceItemModel);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $itemInvoiceServiceMock);
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $di['db'] = $dbMock;
+
+ $service->setDi($di);
+ $result = $service->doBatchPaidInvoiceActivation();
+ expect($result)->toBeBool()->toBeTrue();
+});
+
+test('sends reminders in batch', function (): void {
+ $service = new Service();
+ $invoiceModel = new Model_Invoice();
+ $invoiceModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('sendInvoiceReminder')
+ ->once();
+ $serviceMock->shouldReceive('getUnpaidInvoicesLateFor')
+ ->once()
+ ->andReturn([$invoiceModel]);
+
+ $eventManagerMock = Mockery::mock('\Box_EventManager');
+ $eventManagerMock->shouldReceive('fire')
+ ->atLeast()->once();
+
+ $di = container();
+ $di['events_manager'] = $eventManagerMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $serviceMock->setDi($di);
+ $result = $serviceMock->doBatchRemindersSend();
+ expect($result)->toBeBool()->toBeTrue();
+});
+
+test('invokes due event in batch', function (): void {
+ $service = new Service();
+ $systemService = Mockery::mock(SystemService::class);
+ $systemService->shouldReceive('getParamValue')
+ ->atLeast()->once();
+ $systemService->shouldReceive('setParamValue')
+ ->atLeast()->once();
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getAll')
+ ->atLeast()->once()
+ ->andReturn([[]]);
+
+ $eventManagerMock = Mockery::mock('\Box_EventManager');
+ $eventManagerMock->shouldReceive('fire')
+ ->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['events_manager'] = $eventManagerMock;
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $systemService);
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $service->setDi($di);
+
+ $result = $service->doBatchInvokeDueEvent([]);
+ expect($result)->toBeBool()->toBeTrue();
+});
+
+test('protects from sending reminders to paid invoices', function (): void {
+ $service = new Service();
+ $invoiceModel = new Model_Invoice();
+ $invoiceModel->loadBean(new Tests\Helpers\DummyBean());
+ $invoiceModel->status = Model_Invoice::STATUS_PAID;
+
+ $result = $service->sendInvoiceReminder($invoiceModel);
+ expect($result)->toBeBool()->toBeTrue();
+});
+
+test('sends invoice reminder', function (): void {
+ $service = new Service();
+ $invoiceModel = new Model_Invoice();
+ $invoiceModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $eventManagerMock = Mockery::mock('\Box_EventManager');
+ $eventManagerMock->shouldReceive('fire')
+ ->atLeast()->once();
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['events_manager'] = $eventManagerMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $service->setDi($di);
+
+ $result = $service->sendInvoiceReminder($invoiceModel);
+ expect($result)->toBeBool()->toBeTrue();
+});
+
+test('counts invoices', function (): void {
+ $service = new Service();
+ $sqlResult = [
+ ['status' => Model_Invoice::STATUS_PAID,
+ 'counter' => 2],
+ ];
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getAll')
+ ->atLeast()->once()
+ ->andReturn($sqlResult);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $service->setDi($di);
+ $result = $service->counter();
+ expect($result)->toBeArray();
+});
+
+test('throws exception when generating funds invoice without active order', function (): void {
+ $service = new Service();
+ $clientModel = new Model_Client();
+ $clientModel->loadBean(new Tests\Helpers\DummyBean());
+
+ expect(fn () => $service->generateFundsInvoice($clientModel, 10))
+ ->toThrow(FOSSBilling\Exception::class, 'You must have at least one active order before you can add funds so you cannot proceed at the current time!');
+});
+
+test('throws exception when generating funds invoice below minimum amount', function (): void {
+ $service = new Service();
+ $clientModel = new Model_Client();
+ $clientModel->loadBean(new Tests\Helpers\DummyBean());
+ $clientModel->currency = 'EUR';
+ $fundsAmount = 2;
+
+ $minAmount = 10;
+ $maxAmount = 50;
+ $systemService = Mockery::mock(SystemService::class);
+ $paramCallCount = 0;
+ $systemService->shouldReceive('getParamValue')
+ ->atLeast()->once()
+ ->andReturnUsing(function () use (&$paramCallCount, $minAmount, $maxAmount) {
+ return ++$paramCallCount === 1 ? $minAmount : $maxAmount;
+ });
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $systemService);
+
+ $service->setDi($di);
+
+ expect(fn () => $service->generateFundsInvoice($clientModel, $fundsAmount))
+ ->toThrow(FOSSBilling\Exception::class, 'Amount must be at least ' . $minAmount);
+});
+
+test('throws exception when generating funds invoice above maximum amount', function (): void {
+ $service = new Service();
+ $clientModel = new Model_Client();
+ $clientModel->loadBean(new Tests\Helpers\DummyBean());
+ $clientModel->currency = 'EUR';
+ $fundsAmount = 200;
+
+ $minAmount = 10;
+ $maxAmount = 50;
+ $systemService = Mockery::mock(SystemService::class);
+ $paramCallCount = 0;
+ $systemService->shouldReceive('getParamValue')
+ ->atLeast()->once()
+ ->andReturnUsing(function () use (&$paramCallCount, $minAmount, $maxAmount) {
+ return ++$paramCallCount === 1 ? $minAmount : $maxAmount;
+ });
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $systemService);
+
+ $service->setDi($di);
+
+ expect(fn () => $service->generateFundsInvoice($clientModel, $fundsAmount))
+ ->toThrow(FOSSBilling\Exception::class, 'Amount cannot exceed ' . $maxAmount);
+});
+
+test('generates funds invoice', function (): void {
+ $service = new Service();
+ $invoiceModel = new Model_Invoice();
+ $invoiceModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $clientModel = new Model_Client();
+ $clientModel->loadBean(new Tests\Helpers\DummyBean());
+ $clientModel->currency = 'EUR';
+ $fundsAmount = 20;
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('setInvoiceDefaults')
+ ->atLeast()->once();
+
+ $minAmount = 10;
+ $maxAmount = 50;
+
+ $systemService = Mockery::mock(SystemService::class);
+ $paramCallCount = 0;
+ $systemService->shouldReceive('getParamValue')
+ ->atLeast()->once()
+ ->andReturnUsing(function () use (&$paramCallCount, $minAmount, $maxAmount) {
+ ++$paramCallCount;
+ if ($paramCallCount === 1) {
+ return $minAmount;
+ }
+ if ($paramCallCount === 2) {
+ return $maxAmount;
+ }
+
+ return true;
+ });
+
+ $itemInvoiceServiceMock = Mockery::mock(ServiceInvoiceItem::class);
+ $itemInvoiceServiceMock->shouldReceive('generateForAddFunds')
+ ->atLeast()->once();
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('dispense')
+ ->atLeast()->once()
+ ->andReturn($invoiceModel);
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once();
+
+ $di = container();
+ $di['mod_service'] = $di->protect(function ($serviceName, $sub = '') use ($systemService, $itemInvoiceServiceMock) {
+ if ($serviceName == 'system') {
+ return $systemService;
+ }
+ if ($sub == 'InvoiceItem') {
+ return $itemInvoiceServiceMock;
+ }
+ });
+ $di['db'] = $dbMock;
+
+ $serviceMock->setDi($di);
+
+ $result = $serviceMock->generateFundsInvoice($clientModel, $fundsAmount);
+ expect($result)->toBeInstanceOf(Model_Invoice::class);
+});
+
+test('throws exception when processing invoice not found', function (): void {
+ $service = new Service();
+ $data = [
+ 'hash' => 'hashString',
+ 'gateway_id' => 2,
+ ];
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn(null);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $service->setDi($di);
+
+ expect(fn (): array => $service->processInvoice($data))
+ ->toThrow(FOSSBilling\Exception::class, 'Invoice not found');
+});
+
+test('throws exception when processing invoice with gateway not found', function (): void {
+ $service = new Service();
+ $data = [
+ 'hash' => 'hashString',
+ 'gateway_id' => 2,
+ ];
+
+ $invoiceModel = new Model_Invoice();
+ $invoiceModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn($invoiceModel);
+ $dbMock->shouldReceive('load')
+ ->atLeast()->once()
+ ->andReturn(null);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $service->setDi($di);
+
+ expect(fn (): array => $service->processInvoice($data))
+ ->toThrow(FOSSBilling\Exception::class, 'Payment method not found');
+});
+
+test('throws exception when processing invoice with gateway not enabled', function (): void {
+ $service = new Service();
+ $data = [
+ 'hash' => 'hashString',
+ 'gateway_id' => 2,
+ ];
+
+ $invoiceModel = new Model_Invoice();
+ $invoiceModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $payGatewayModel = new Model_PayGateway();
+ $payGatewayModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn($invoiceModel);
+ $dbMock->shouldReceive('load')
+ ->atLeast()->once()
+ ->andReturn($payGatewayModel);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $service->setDi($di);
+
+ expect(fn (): array => $service->processInvoice($data))
+ ->toThrow(FOSSBilling\Exception::class, 'Payment method not enabled');
+});
+
+test('processes an invoice', function (): void {
+ $service = new Service();
+ $serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('getPaymentInvoice')
+ ->atLeast()->once()
+ ->andReturn(new Payment_Invoice());
+
+ $data = [
+ 'hash' => 'hashString',
+ 'gateway_id' => 2,
+ ];
+
+ $invoiceModel = new Model_Invoice();
+ $invoiceModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $payGatewayModel = new Model_PayGateway();
+ $payGatewayModel->loadBean(new Tests\Helpers\DummyBean());
+ $payGatewayModel->enabled = true;
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn($invoiceModel);
+ $dbMock->shouldReceive('load')
+ ->atLeast()->once()
+ ->andReturn($payGatewayModel);
+
+ $subscribeService = Mockery::mock(ServiceSubscription::class);
+ $subscribeService->shouldReceive('isSubscribable')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $payGatewayService = Mockery::mock(ServicePayGateway::class);
+ $payGatewayService->shouldReceive('canPerformRecurrentPayment')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $adapterMock = Mockery::mock('\Payment_Adapter_Dummy');
+ $adapterMock->shouldReceive('getConfig')
+ ->atLeast()->once()
+ ->andReturn([]);
+ $adapterMock->shouldReceive('recurrentPayment')
+ ->atLeast()->once()
+ ->andReturn(['type' => 'html', 'result' => 'test']);
+ $adapterMock->shouldReceive('getType')
+ ->atLeast()->once()
+ ->andReturn('html');
+ $adapterMock->shouldReceive('getServiceURL')
+ ->atLeast()->once()
+ ->andReturn('http://example.com/payment');
+
+ $payGatewayService->shouldReceive('getPaymentAdapter')
+ ->atLeast()->once()
+ ->andReturn($adapterMock);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(function ($serviceName, $sub = '') use ($payGatewayService, $subscribeService) {
+ if ($sub == 'PayGateway') {
+ return $payGatewayService;
+ }
+ if ($sub == 'Subscription') {
+ return $subscribeService;
+ }
+ });
+ $di['api_admin'] = new Api_Handler(new Model_Admin());
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $serviceMock->setDi($di);
+ $result = $serviceMock->processInvoice($data);
+
+ expect($result)->toBeArray();
+ expect($result)->toHaveKey('type');
+ expect($result)->toHaveKey('service_url');
+ expect($result)->toHaveKey('subscription');
+ expect($result)->toHaveKey('result');
+});
+
+test('adds note to invoice', function (): void {
+ $service = new Service();
+ $note = 'test Note';
+
+ $invoiceModel = new Model_Invoice();
+ $invoiceModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $result = $service->addNote($invoiceModel, $note);
+ expect($result)->toBeTrue();
+});
+
+test('finds all unpaid invoices', function (): void {
+ $service = new Service();
+ $invoiceModel = new Model_Invoice();
+ $invoiceModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $getAllResult = [
+ [
+ 'id' => 1,
+ 'client_id' => 1,
+ 'serie' => 'BB',
+ 'nr' => '00',
+ ],
+ ];
+ $dbMock->shouldReceive('getAll')
+ ->atLeast()->once()
+ ->andReturn($getAllResult);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $result = $service->findAllUnpaid();
+ expect($result)->toBeArray();
+});
+
+test('finds all paid invoices', function (): void {
+ $service = new Service();
+ $invoiceModel = new Model_Invoice();
+ $invoiceModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('find')
+ ->atLeast()->once()
+ ->andReturn([$invoiceModel]);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $result = $service->findAllPaid();
+ expect($result)->toBeArray();
+ expect($result[0])->toBeInstanceOf(Model_Invoice::class);
+});
+
+test('gets unpaid invoices late for', function (): void {
+ $service = new Service();
+ $invoiceModel = new Model_Invoice();
+ $invoiceModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('find')
+ ->atLeast()->once()
+ ->andReturn([$invoiceModel]);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $result = $service->getUnpaidInvoicesLateFor();
+ expect($result)->toBeArray();
+ expect($result[0])->toBeInstanceOf(Model_Invoice::class);
+});
+
+test('gets buyer', function (): void {
+ $service = new Service();
+ $invoiceModel = new Model_Invoice();
+ $invoiceModel->loadBean(new Tests\Helpers\DummyBean());
+ $invoiceModel->buyer_first_name = 'John';
+ $invoiceModel->buyer_last_name = 'Doe';
+ $invoiceModel->buyer_email = 'john@example.com';
+
+ $result = $service->getBuyer($invoiceModel);
+ expect($result)->toBeArray();
+ expect($result)->toHaveKey('first_name');
+ expect($result)->toHaveKey('last_name');
+ expect($result)->toHaveKey('email');
+ expect($result['first_name'])->toBe('John');
+ expect($result['last_name'])->toBe('Doe');
+ expect($result['email'])->toBe('john@example.com');
+});
+
+test('checks if invoice type is deposit', function (): void {
+ $service = new Service();
+ $di = container();
+
+ $modelInvoiceItem = new Model_InvoiceItem();
+ $modelInvoiceItem->loadBean(new Tests\Helpers\DummyBean());
+ $modelInvoiceItem->type = Model_InvoiceItem::TYPE_DEPOSIT;
+
+ $invoiceItems = [$modelInvoiceItem];
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('find')
+ ->atLeast()->once()
+ ->andReturn($invoiceItems);
+
+ $di['db'] = $dbMock;
+
+ $modelInvoice = new Model_Invoice();
+ $modelInvoice->loadBean(new Tests\Helpers\DummyBean());
+
+ $service->setDi($di);
+ $result = $service->isInvoiceTypeDeposit($modelInvoice);
+ expect($result)->toBeTrue();
+});
+
+test('returns false when invoice type is not deposit', function (): void {
+ $service = new Service();
+ $di = container();
+
+ $modelInvoiceItem = new Model_InvoiceItem();
+ $modelInvoiceItem->loadBean(new Tests\Helpers\DummyBean());
+ $modelInvoiceItem->type = Model_InvoiceItem::TYPE_ORDER;
+
+ $invoiceItems = [$modelInvoiceItem];
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('find')
+ ->atLeast()->once()
+ ->andReturn($invoiceItems);
+
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $modelInvoice = new Model_Invoice();
+ $modelInvoice->loadBean(new Tests\Helpers\DummyBean());
+
+ $result = $service->isInvoiceTypeDeposit($modelInvoice);
+ expect($result)->toBeFalse();
+});
+
+test('returns false when checking deposit with empty items', function (): void {
+ $service = new Service();
+ $di = container();
+
+ $invoiceItems = [];
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('find')
+ ->atLeast()->once()
+ ->andReturn($invoiceItems);
+
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $modelInvoice = new Model_Invoice();
+ $modelInvoice->loadBean(new Tests\Helpers\DummyBean());
+
+ $result = $service->isInvoiceTypeDeposit($modelInvoice);
+ expect($result)->toBeFalse();
+});
diff --git a/src/modules/Invoice/tests/Unit/ServiceTransactionTest.php b/src/modules/Invoice/tests/Unit/ServiceTransactionTest.php
new file mode 100644
index 000000000..c01b8d48a
--- /dev/null
+++ b/src/modules/Invoice/tests/Unit/ServiceTransactionTest.php
@@ -0,0 +1,224 @@
+setDi($di);
+ $getDi = $service->getDi();
+ expect($getDi)->toBe($di);
+});
+
+test('updates a transaction', function (): void {
+ $service = new ServiceTransaction();
+ $eventsMock = Mockery::mock('\Box_EventManager');
+ $eventsMock->shouldReceive('fire')
+ ->atLeast()->once();
+
+ $transactionModel = new Model_Transaction();
+ $transactionModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['events_manager'] = $eventsMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $service->setDi($di);
+
+ $data = [
+ 'invoice_id' => 1,
+ 'txn_id' => 2,
+ 'txn_status' => '',
+ 'gateway_id' => 1,
+ 'amount' => '',
+ 'currency' => '',
+ 'type' => '',
+ 'note' => '',
+ 'status' => '',
+ 'validate_ipn' => '',
+ ];
+ $result = $service->update($transactionModel, $data);
+ expect($result)->toBeTrue();
+});
+
+test('throws exception when creating transaction with missing invoice id', function (): void {
+ $service = new ServiceTransaction();
+ $eventsMock = Mockery::mock('\Box_EventManager');
+ $eventsMock->shouldReceive('fire')
+ ->atLeast()->once();
+
+ $di = container();
+ $di['events_manager'] = $eventsMock;
+
+ $service->setDi($di);
+
+ $data = [
+ 'skip_validation' => false,
+ ];
+
+ expect(fn () => $service->create($data))
+ ->toThrow(FOSSBilling\Exception::class, 'Transaction invoice ID is missing');
+});
+
+test('throws exception when creating transaction with missing gateway id', function (): void {
+ $service = new ServiceTransaction();
+ $eventsMock = Mockery::mock('\Box_EventManager');
+ $eventsMock->shouldReceive('fire')
+ ->atLeast()->once();
+
+ $di = container();
+ $di['events_manager'] = $eventsMock;
+
+ $service->setDi($di);
+
+ $data = [
+ 'skip_validation' => false,
+ 'invoice_id' => 2,
+ ];
+
+ expect(fn () => $service->create($data))
+ ->toThrow(FOSSBilling\Exception::class, 'Payment gateway ID is missing');
+});
+
+test('deletes a transaction', function (): void {
+ $service = new ServiceTransaction();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('trash')
+ ->atLeast()->once();
+
+ $di = container();
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $transactionModel = new Model_Transaction();
+ $transactionModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $result = $service->delete($transactionModel);
+ expect($result)->toBeTrue();
+});
+
+test('converts to api array', function (): void {
+ $service = new ServiceTransaction();
+ $dbMock = Mockery::mock('\Box_Database');
+ $payGatewayModel = new Model_PayGateway();
+ $payGatewayModel->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock->shouldReceive('load')
+ ->atLeast()->once()
+ ->andReturn($payGatewayModel);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $expected = [
+ 'id' => null,
+ 'invoice_id' => null,
+ 'txn_id' => null,
+ 'txn_status' => null,
+ 'gateway_id' => 1,
+ 'gateway' => null,
+ 'amount' => null,
+ 'currency' => null,
+ 'type' => null,
+ 'status' => null,
+ 'ip' => null,
+ 'validate_ipn' => null,
+ 'error' => null,
+ 'error_code' => null,
+ 'note' => null,
+ 'created_at' => null,
+ 'updated_at' => null,
+ ];
+
+ $transactionModel = new Model_Transaction();
+ $transactionModel->loadBean(new Tests\Helpers\DummyBean());
+ $transactionModel->gateway_id = 1;
+
+ $result = $service->toApiArray($transactionModel, false);
+ expect($result)->toBeArray();
+ expect($result)->toBe($expected);
+});
+
+test('gets search query with various parameters', function (array $data, array $expectedParams, string $expectedStringPart): void {
+ $service = new ServiceTransaction();
+ $di = container();
+
+ $service->setDi($di);
+ $result = $service->getSearchQuery($data);
+ expect($result[0])->toBeString();
+ expect($result[1])->toBeArray();
+
+ expect(str_contains((string) $result[0], $expectedStringPart))->toBeTrue();
+ expect($result[1])->toBe($expectedParams);
+})->with([
+ [
+ [], [], 'SELECT m.*',
+ ],
+ [
+ ['search' => 'keyword'], ['note' => '%keyword%', 'search_invoice_id' => '%keyword%', 'search_txn_id' => '%keyword%', 'ipn' => '%keyword%'], 'AND (m.note LIKE :note OR m.invoice_id LIKE :search_invoice_id OR m.txn_id LIKE :search_txn_id OR m.ipn LIKE :ipn)',
+ ],
+ [
+ ['invoice_hash' => 'hashString'], ['hash' => 'hashString'], 'AND i.hash = :hash',
+ ],
+ [
+ ['invoice_id' => '1'], ['invoice_id' => '1'], 'AND m.invoice_id = :invoice_id',
+ ],
+ [
+ ['gateway_id' => '2'], ['gateway_id' => '2'], 'AND m.gateway_id = :gateway_id',
+ ],
+ [
+ ['client_id' => '3'], ['client_id' => '3'], 'AND i.client_id = :client_id',
+ ],
+ [
+ ['status' => 'active'], ['status' => 'active'], 'AND m.status = :status',
+ ],
+ [
+ ['currency' => 'Eur'], ['currency' => 'Eur'], 'AND m.currency = :currency',
+ ],
+ [
+ ['type' => 'payment'], ['type' => 'payment'], 'AND m.type = :type',
+ ],
+ [
+ ['txn_id' => 'longTxn_id'], ['txn_id' => 'longTxn_id'], 'AND m.txn_id = :txn_id',
+ ],
+ [
+ ['date_from' => '2012-12-12'], ['date_from' => 1_355_270_400], 'AND UNIX_TIMESTAMP(m.created_at) >= :date_from',
+ ],
+ [
+ ['date_to' => '2012-12-12'], ['date_to' => 1_355_270_400], 'AND UNIX_TIMESTAMP(m.created_at) <= :date_to',
+ ],
+]);
+
+test('counts transactions', function (): void {
+ $service = new ServiceTransaction();
+ $queryResult = [['status' => Model_Transaction::STATUS_RECEIVED, 'counter' => 1]];
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getAll')
+ ->atLeast()->once()
+ ->andReturn($queryResult);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $result = $service->counter();
+ expect($result)->toBeArray();
+});
diff --git a/src/modules/Massmailer/Api/Admin.php b/src/modules/Massmailer/Api/Admin.php
index c98052c55..20d2ac811 100644
--- a/src/modules/Massmailer/Api/Admin.php
+++ b/src/modules/Massmailer/Api/Admin.php
@@ -26,10 +26,10 @@ class Admin extends \Api_Abstract
*/
public function get_list(array $data): array
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('massmailer', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('massmailer', 'view');
$qb = $this->getService()->getSearchQueryBuilder($data);
- $pager = $this->di['pager']->paginateDoctrineQuery($qb, PaginationOptions::fromArray($data));
+ $pager = $this->getDi()['pager']->paginateDoctrineQuery($qb, PaginationOptions::fromArray($data));
foreach ($pager['list'] as $key => $item) {
$item['filter'] = $this->getService()->normalizeFilter($item['filter'] ?? null);
@@ -44,7 +44,7 @@ class Admin extends \Api_Abstract
*/
public function get(array $data): array
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('massmailer', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('massmailer', 'view');
$model = $this->_getMessage($data);
@@ -63,7 +63,7 @@ class Admin extends \Api_Abstract
*/
public function update(array $data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('massmailer', 'create_and_edit');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('massmailer', 'create_and_edit');
$model = $this->_getMessage($data);
@@ -82,14 +82,14 @@ class Admin extends \Api_Abstract
}
if (isset($data['from_email'])) {
- $this->di['tools']->validateAndSanitizeEmail($data['from_email']);
+ $this->getDi()['tools']->validateAndSanitizeEmail($data['from_email']);
$model->setFromEmail($data['from_email']);
}
$model->setUpdatedAt(date('Y-m-d H:i:s'));
- $this->di['em']->flush();
+ $this->getDi()['em']->flush();
- $this->di['logger']->info('Updated mail message #%s', $model->getId());
+ $this->getDi()['logger']->info('Updated mail message #%s', $model->getId());
return true;
}
@@ -102,7 +102,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['subject' => 'Message subject was not passed'])]
public function create(array $data): int
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('massmailer', 'create_and_edit');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('massmailer', 'create_and_edit');
$default_content = '{% apply markdown_to_html %}
Hi {{ c.first_name }} {{ c.last_name }},
@@ -122,7 +122,7 @@ Order our services at {{ "order"|url }}
{{ guest.system_company.name }} - {{ guest.system_company.signature }}
{% endapply %}
';
- $systemService = $this->di['mod_service']('system');
+ $systemService = $this->getDi()['mod_service']('system');
$company = $systemService->getCompany();
$model = (new MassmailerMessage())
@@ -135,15 +135,15 @@ Order our services at {{ "order"|url }}
->setCreatedAt(date('Y-m-d H:i:s'))
->setUpdatedAt(date('Y-m-d H:i:s'));
- $this->di['em']->persist($model);
- $this->di['em']->flush();
+ $this->getDi()['em']->persist($model);
+ $this->getDi()['em']->flush();
$id = $model->getId();
if ($id === null) {
throw new \FOSSBilling\Exception('Failed to retrieve ID of created mail message.');
}
- $this->di['logger']->info('Created mail message #%s', $id);
+ $this->getDi()['logger']->info('Created mail message #%s', $id);
return $id;
}
@@ -153,7 +153,7 @@ Order our services at {{ "order"|url }}
*/
public function send_test(array $data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('massmailer', 'send');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('massmailer', 'send');
$model = $this->_getMessage($data);
$client_id = $this->_getTestClientId();
@@ -164,7 +164,7 @@ Order our services at {{ "order"|url }}
$this->getService()->sendMessage($model, $client_id, true);
- $this->di['logger']->info('Sent test mail message #%s to client ', $model->getId());
+ $this->getDi()['logger']->info('Sent test mail message #%s to client ', $model->getId());
return true;
}
@@ -174,7 +174,7 @@ Order our services at {{ "order"|url }}
*/
public function send(array $data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('massmailer', 'send');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('massmailer', 'send');
$model = $this->_getMessage($data);
@@ -189,9 +189,9 @@ Order our services at {{ "order"|url }}
$model->setStatus(MassmailerMessage::STATUS_SENT);
$model->setSentAt(date('Y-m-d H:i:s'));
- $this->di['em']->flush();
+ $this->getDi()['em']->flush();
- $this->di['logger']->info('Added mass mail messages #%s to queue', $model->getId());
+ $this->getDi()['logger']->info('Added mass mail messages #%s to queue', $model->getId());
return true;
}
@@ -201,7 +201,7 @@ Order our services at {{ "order"|url }}
*/
public function copy(array $data): int
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('massmailer', 'create_and_edit');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('massmailer', 'create_and_edit');
$model = $this->_getMessage($data);
@@ -215,15 +215,15 @@ Order our services at {{ "order"|url }}
->setCreatedAt(date('Y-m-d H:i:s'))
->setUpdatedAt(date('Y-m-d H:i:s'));
- $this->di['em']->persist($copy);
- $this->di['em']->flush();
+ $this->getDi()['em']->persist($copy);
+ $this->getDi()['em']->flush();
$id = $copy->getId();
if ($id === null) {
throw new \FOSSBilling\Exception('Failed to retrieve ID of copied mail message.');
}
- $this->di['logger']->info('Copied mail message #%s to #%s', $model->getId(), $id);
+ $this->getDi()['logger']->info('Copied mail message #%s to #%s', $model->getId(), $id);
return $id;
}
@@ -233,7 +233,7 @@ Order our services at {{ "order"|url }}
*/
public function receivers(array $data): array
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('massmailer', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('massmailer', 'view');
$model = $this->_getMessage($data);
@@ -245,15 +245,15 @@ Order our services at {{ "order"|url }}
*/
public function delete(array $data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('massmailer', 'delete');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('massmailer', 'delete');
$model = $this->_getMessage($data);
$id = $model->getId();
- $this->di['em']->remove($model);
- $this->di['em']->flush();
+ $this->getDi()['em']->remove($model);
+ $this->getDi()['em']->flush();
- $this->di['logger']->info('Removed mail message #%s', $id);
+ $this->getDi()['logger']->info('Removed mail message #%s', $id);
return true;
}
@@ -265,7 +265,7 @@ Order our services at {{ "order"|url }}
*/
public function preview(array $data): array
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('massmailer', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('massmailer', 'view');
$model = $this->_getMessage($data);
$client_id = $this->_getTestClientId();
@@ -276,7 +276,7 @@ Order our services at {{ "order"|url }}
$clients = $this->getService()->getMessageReceivers($model);
if ($getRecipients) {
- $clientService = $this->di['mod_service']('client');
+ $clientService = $this->getDi()['mod_service']('client');
foreach ($clients as $client) {
$clientInfo = $clientService->get(['id' => $client['id']]);
$recipients[] = [
@@ -298,10 +298,10 @@ Order our services at {{ "order"|url }}
*/
public function get_test_client(): string
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('massmailer', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('massmailer', 'view');
try {
- $client = $this->di['mod_service']('client')->get(['id' => $this->_getTestClientId()]);
+ $client = $this->getDi()['mod_service']('client')->get(['id' => $this->_getTestClientId()]);
} catch (\Exception) {
return 'Unknown';
}
@@ -311,13 +311,13 @@ Order our services at {{ "order"|url }}
private function _getTestClientId(): int
{
- $mod = $this->di['mod']('massmailer');
+ $mod = $this->getDi()['mod']('massmailer');
$c = $mod->getConfig();
$required = [
'test_client_id' => 'Client ID needs to be configured in mass mailer settings.',
];
- $this->di['validator']->checkRequiredParamsForArray($required, $c);
+ $this->getDi()['validator']->checkRequiredParamsForArray($required, $c);
return (int) $c['test_client_id'];
}
diff --git a/src/modules/Massmailer/Entity/MassmailerMessage.php b/src/modules/Massmailer/Entity/MassmailerMessage.php
index 0b9fd76a9..14d2ecbdd 100644
--- a/src/modules/Massmailer/Entity/MassmailerMessage.php
+++ b/src/modules/Massmailer/Entity/MassmailerMessage.php
@@ -28,6 +28,11 @@ class MassmailerMessage implements ApiArrayInterface
#[ORM\Column(type: \Doctrine\DBAL\Types\Types::INTEGER)]
private ?int $id = null;
+ public function __construct(?int $id = null)
+ {
+ $this->id = $id;
+ }
+
#[ORM\Column(name: 'from_email', type: \Doctrine\DBAL\Types\Types::STRING, length: 255, nullable: true)]
private ?string $fromEmail = null;
diff --git a/src/modules/Massmailer/Service.php b/src/modules/Massmailer/Service.php
index a2432c7a9..17d70b0d5 100644
--- a/src/modules/Massmailer/Service.php
+++ b/src/modules/Massmailer/Service.php
@@ -247,6 +247,7 @@ class Service implements \FOSSBilling\InjectionAwareInterface
}
if (!Environment::isProduction()) {
+ // @phpstan-ignore if.alwaysFalse
if (DEBUG) {
error_log('Skip email sending. Application ENV: ' . Environment::getCurrentEnvironment());
}
@@ -343,10 +344,6 @@ class Service implements \FOSSBilling\InjectionAwareInterface
$normalized = array_values($normalized);
sort($normalized);
- if ($normalized === []) {
- return [];
- }
-
$existingIds = $this->getExistingIds($table, $normalized);
if (count($existingIds) !== count($normalized)) {
return $this->handleInvalidFilter($field, $strict);
diff --git a/src/modules/Massmailer/tests/Unit/Api/AdminTest.php b/src/modules/Massmailer/tests/Unit/Api/AdminTest.php
new file mode 100644
index 000000000..9ba12d90b
--- /dev/null
+++ b/src/modules/Massmailer/tests/Unit/Api/AdminTest.php
@@ -0,0 +1,79 @@
+shouldReceive('find')->with(1)->once()->andReturn($message);
+
+ $em = Mockery::mock(Doctrine\ORM\EntityManagerInterface::class);
+ $em->shouldReceive('getRepository')->with(MassmailerMessage::class)->andReturn($repo);
+
+ if ($expectFlush) {
+ $em->shouldReceive('flush')->once();
+ } else {
+ $em->shouldNotReceive('flush');
+ }
+
+ $di['em'] = $em;
+ $di['mod_service'] = $di->protect(moduleService());
+
+ return $di;
+}
+
+test('update stores normalized filter', function (): void {
+ $model = (new MassmailerMessage())
+ ->setContent('content')
+ ->setSubject('subject')
+ ->setStatus(MassmailerMessage::STATUS_DRAFT);
+
+ $service = new Box\Mod\Massmailer\Service();
+ $di = createMassmailerAdminDi($model);
+ $di['logger'] = new Box_Log();
+ $service->setDi($di);
+
+ $api = new Box\Mod\Massmailer\Api\Admin();
+ $api->setDi($di);
+ $api->setService($service);
+
+ $result = $api->update([
+ 'id' => 1,
+ 'filter' => [
+ 'client_status' => ['canceled', 'active', 'active'],
+ 'has_order_with_status' => ['suspended', 'active', 'active'],
+ ],
+ ]);
+
+ expect($result)->toBeTrue();
+ expect($model->getFilter())->toBe('{"client_status":["active","canceled"],"has_order_with_status":["active","suspended"]}');
+});
+
+test('update rejects invalid filter', function (): void {
+ $model = (new MassmailerMessage())
+ ->setContent('content')
+ ->setSubject('subject')
+ ->setStatus(MassmailerMessage::STATUS_DRAFT);
+
+ $service = new Box\Mod\Massmailer\Service();
+ $di = createMassmailerAdminDi($model, false);
+ $di['logger'] = new Box_Log();
+ $service->setDi($di);
+
+ $api = new Box\Mod\Massmailer\Api\Admin();
+ $api->setDi($di);
+ $api->setService($service);
+
+ expect(fn () => $api->update([
+ 'id' => 1,
+ 'filter' => ['client_status' => ['active', 'not-valid']],
+ ]))->toThrow(InformationException::class, 'Mass mail filter contains invalid values for "client_status"');
+});
diff --git a/src/modules/Massmailer/tests/Unit/Repository/MassmailerMessageRepositoryTest.php b/src/modules/Massmailer/tests/Unit/Repository/MassmailerMessageRepositoryTest.php
new file mode 100644
index 000000000..4caf81b79
--- /dev/null
+++ b/src/modules/Massmailer/tests/Unit/Repository/MassmailerMessageRepositoryTest.php
@@ -0,0 +1,63 @@
+shouldReceive('andWhere')->twice()->andReturnUsing(function (string $clause) use (&$whereCalls, $queryBuilder) {
+ $whereCalls[] = $clause;
+
+ return $queryBuilder;
+ });
+ $queryBuilder->shouldReceive('setParameter')->twice()->andReturnUsing(function (string $name, mixed $value) use (&$parameters, $queryBuilder) {
+ $parameters[$name] = $value;
+
+ return $queryBuilder;
+ });
+ $queryBuilder->shouldReceive('orderBy')->with('m.createdAt', 'DESC')->once()->andReturn($queryBuilder);
+
+ $repository = Mockery::mock(MassmailerMessageRepository::class)->makePartial();
+ $repository->shouldReceive('createQueryBuilder')->with('m')->once()->andReturn($queryBuilder);
+
+ $result = $repository->getSearchQueryBuilder(['id' => '42', 'status' => 'draft']);
+
+ expect($result)->toBe($queryBuilder);
+ expect($whereCalls)->toBe(['m.id = :id', 'm.status = :status']);
+ expect($parameters)->toBe(['id' => 42, 'status' => 'draft']);
+});
+
+test('get search query builder groups search clause when status filter is present', function (): void {
+ $whereCalls = [];
+ $parameters = [];
+
+ $queryBuilder = Mockery::mock(QueryBuilder::class);
+ $queryBuilder->shouldReceive('andWhere')->twice()->andReturnUsing(function (string $clause) use (&$whereCalls, $queryBuilder) {
+ $whereCalls[] = $clause;
+
+ return $queryBuilder;
+ });
+ $queryBuilder->shouldReceive('setParameter')->twice()->andReturnUsing(function (string $name, mixed $value) use (&$parameters, $queryBuilder) {
+ $parameters[$name] = $value;
+
+ return $queryBuilder;
+ });
+ $queryBuilder->shouldReceive('orderBy')->with('m.createdAt', 'DESC')->once()->andReturn($queryBuilder);
+
+ $repository = Mockery::mock(MassmailerMessageRepository::class)->makePartial();
+ $repository->shouldReceive('createQueryBuilder')->with('m')->once()->andReturn($queryBuilder);
+
+ $result = $repository->getSearchQueryBuilder(['status' => 'draft', 'search' => 'newsletter']);
+
+ expect($result)->toBe($queryBuilder);
+ expect($whereCalls)->toBe([
+ 'm.status = :status',
+ '(m.subject LIKE :search OR m.content LIKE :search OR m.fromEmail LIKE :search OR m.fromName LIKE :search)',
+ ]);
+ expect($parameters)->toBe(['status' => 'draft', 'search' => '%newsletter%']);
+});
diff --git a/src/modules/Massmailer/tests/Unit/ServiceTest.php b/src/modules/Massmailer/tests/Unit/ServiceTest.php
new file mode 100644
index 000000000..ad0a2ffb7
--- /dev/null
+++ b/src/modules/Massmailer/tests/Unit/ServiceTest.php
@@ -0,0 +1,102 @@
+shouldReceive('getRepository')->with(MassmailerMessage::class)->andReturn($repo);
+ $di['em'] = $em;
+ $di['dbal'] = $dbal ?? DriverManager::getConnection(['driver' => 'pdo_sqlite', 'memory' => true]);
+
+ return $di;
+}
+
+function createMassmailerDbal(): Connection
+{
+ return DriverManager::getConnection(['driver' => 'pdo_sqlite', 'memory' => true]);
+}
+
+function seedReceiverTables(Connection $dbal): void
+{
+ $dbal->executeStatement('CREATE TABLE client_group (id INTEGER PRIMARY KEY)');
+ $dbal->executeStatement('CREATE TABLE product (id INTEGER PRIMARY KEY)');
+ $dbal->executeStatement('CREATE TABLE client (id INTEGER PRIMARY KEY, status TEXT, client_group_id INTEGER)');
+ $dbal->executeStatement('CREATE TABLE client_order (id INTEGER PRIMARY KEY, client_id INTEGER, product_id INTEGER, status TEXT)');
+
+ $dbal->executeStatement('INSERT INTO client_group (id) VALUES (1), (2)');
+ $dbal->executeStatement('INSERT INTO product (id) VALUES (10), (11)');
+ $dbal->executeStatement("INSERT INTO client (id, status, client_group_id) VALUES (1, 'active', 1), (2, 'canceled', 1), (3, 'active', 2)");
+ $dbal->executeStatement("INSERT INTO client_order (id, client_id, product_id, status) VALUES (1, 1, 10, 'active'), (2, 2, 10, 'suspended'), (3, 3, 11, 'active')");
+}
+
+test('normalize filter returns canonical enum values', function (): void {
+ $service = new Box\Mod\Massmailer\Service();
+
+ $normalized = $service->normalizeFilter([
+ 'client_status' => ['canceled', 'active', 'active'],
+ 'has_order_with_status' => ['suspended', 'active', 'active'],
+ ], true);
+
+ expect($normalized)->toBe([
+ 'client_status' => ['active', 'canceled'],
+ 'has_order_with_status' => ['active', 'suspended'],
+ ]);
+});
+
+test('normalize filter rejects unexpected keys in strict mode', function (): void {
+ $service = new Box\Mod\Massmailer\Service();
+ $service->setDi(createMassmailerDi());
+
+ expect(fn () => $service->normalizeFilter(['unexpected' => ['anything']], true))
+ ->toThrow(InformationException::class, 'Mass mail filter contains invalid values for "unexpected"');
+});
+
+test('normalize filter rejects unknown IDs in strict mode', function (): void {
+ $dbal = createMassmailerDbal();
+ $dbal->executeStatement('CREATE TABLE client_group (id INTEGER PRIMARY KEY)');
+ $dbal->executeStatement('INSERT INTO client_group (id) VALUES (1)');
+
+ $service = new Box\Mod\Massmailer\Service();
+ $service->setDi(createMassmailerDi($dbal));
+
+ expect(fn () => $service->normalizeFilter(['client_groups' => ['2', '1']], true))
+ ->toThrow(InformationException::class, 'Mass mail filter contains invalid values for "client_groups"');
+});
+
+test('get message receivers builds parameterized query', function (): void {
+ $dbal = createMassmailerDbal();
+ seedReceiverTables($dbal);
+
+ $model = (new MassmailerMessage())->setFilter(json_encode([
+ 'client_status' => ['active'],
+ 'client_groups' => [1],
+ 'has_order' => [10],
+ 'has_order_with_status' => ['active'],
+ ], JSON_THROW_ON_ERROR));
+
+ $service = new Box\Mod\Massmailer\Service();
+ $service->setDi(createMassmailerDi($dbal));
+
+ expect($service->getMessageReceivers($model))->toBe([['id' => 1]]);
+});
+
+test('get message receivers rejects invalid stored filter', function (): void {
+ $model = (new MassmailerMessage())->setFilter(json_encode([
+ 'client_status' => ['active', 'not-valid'],
+ ], JSON_THROW_ON_ERROR));
+
+ $service = new Box\Mod\Massmailer\Service();
+ $service->setDi(createMassmailerDi());
+
+ expect(fn () => $service->getMessageReceivers($model))
+ ->toThrow(InformationException::class, 'Mass mail filter contains invalid values for "client_status"');
+});
diff --git a/src/modules/News/Api/Admin.php b/src/modules/News/Api/Admin.php
index 6de35885f..e4a02e856 100644
--- a/src/modules/News/Api/Admin.php
+++ b/src/modules/News/Api/Admin.php
@@ -27,7 +27,7 @@ class Admin extends \Api_Abstract
*/
public function get_list(array $data): array
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('news', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('news', 'view');
/** @var \Box\Mod\News\Repository\PostRepository $repo */
$repo = $this->getService()->getPostRepository();
@@ -35,7 +35,7 @@ class Admin extends \Api_Abstract
// Repository method returns a QueryBuilder with filters applied
$qb = $repo->getSearchQueryBuilder($data);
- return $this->di['pager']->paginateDoctrineQuery($qb, PaginationOptions::fromArray($data));
+ return $this->getDi()['pager']->paginateDoctrineQuery($qb, PaginationOptions::fromArray($data));
}
/**
@@ -47,7 +47,7 @@ class Admin extends \Api_Abstract
*/
public function get(array $data): array
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('news', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('news', 'view');
$id = $data['id'] ?? null;
$slug = $data['slug'] ?? null;
@@ -71,7 +71,7 @@ class Admin extends \Api_Abstract
}
/** @todo Doctrine: Replace with actual Admin entity once it's migrated to Doctrine. */
- $admin = $this->di['db']->getRow('SELECT name FROM admin WHERE id = :id', ['id' => $post->getAdminId()]);
+ $admin = $this->getDi()['db']->getRow('SELECT name FROM admin WHERE id = :id', ['id' => $post->getAdminId()]);
$post->setAdminData($admin);
@@ -84,7 +84,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Post ID was not passed'])]
public function update(array $data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('news', 'manage');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('news', 'manage');
/** @var \Box\Mod\News\Repository\PostRepository $repo */
$repo = $this->getService()->getPostRepository();
@@ -115,10 +115,10 @@ class Admin extends \Api_Abstract
$post->setAdminId($this->getIdentity()->id);
- $this->di['em']->persist($post);
- $this->di['em']->flush();
+ $this->getDi()['em']->persist($post);
+ $this->getDi()['em']->flush();
- $this->di['logger']->info('Updated news item #%s', $post->getId());
+ $this->getDi()['logger']->info('Updated news item #%s', $post->getId());
return true;
}
@@ -131,19 +131,19 @@ class Admin extends \Api_Abstract
#[RequiredParams(['title' => 'Post title was not passed'])]
public function create(array $data): int
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('news', 'manage');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('news', 'manage');
- $post = new Post($data['title'], $this->di['tools']->slug($data['title']));
+ $post = new Post($data['title'], $this->getDi()['tools']->slug($data['title']));
$post->setAdminId($this->getIdentity()->id)
->setContent($data['content'] ?? null)
->setStatus($data['status'] ?? Post::STATUS_ACTIVE)
->setDescription($data['description'] ?? null);
- $this->di['em']->persist($post);
- $this->di['em']->flush();
+ $this->getDi()['em']->persist($post);
+ $this->getDi()['em']->flush();
- $this->di['logger']->info('Created news item #%s', $post->getId());
+ $this->getDi()['logger']->info('Created news item #%s', $post->getId());
return $post->getId();
}
@@ -154,7 +154,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Post ID was not passed'])]
public function delete(array $data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('news', 'manage');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('news', 'manage');
/** @var \Box\Mod\News\Repository\PostRepository $repo */
$repo = $this->getService()->getPostRepository();
@@ -165,10 +165,10 @@ class Admin extends \Api_Abstract
throw new \FOSSBilling\Exception('News item not found');
}
- $this->di['em']->remove($post);
- $this->di['em']->flush();
+ $this->getDi()['em']->remove($post);
+ $this->getDi()['em']->flush();
- $this->di['logger']->info('Removed news item #%s', $data['id']);
+ $this->getDi()['logger']->info('Removed news item #%s', $data['id']);
return true;
}
@@ -179,14 +179,14 @@ class Admin extends \Api_Abstract
#[RequiredParams(['ids' => 'IDs were not passed'])]
public function batch_delete(array $data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('news', 'manage');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('news', 'manage');
/** @var \Box\Mod\News\Repository\PostRepository $repo */
$repo = $this->getService()->getPostRepository();
$count = $repo->deleteByIds($data['ids']);
- $this->di['logger']->info('Removed %s news items', $count);
+ $this->getDi()['logger']->info('Removed %s news items', $count);
return true;
}
diff --git a/src/modules/News/Api/Guest.php b/src/modules/News/Api/Guest.php
index 54959775c..eaccdca7b 100644
--- a/src/modules/News/Api/Guest.php
+++ b/src/modules/News/Api/Guest.php
@@ -34,7 +34,7 @@ class Guest extends \Api_Abstract
// Repository method returns a QueryBuilder with filters applied
$qb = $repo->getSearchQueryBuilder($data);
- return $this->di['pager']->paginateDoctrineQuery($qb, PaginationOptions::fromArray($data));
+ return $this->getDi()['pager']->paginateDoctrineQuery($qb, PaginationOptions::fromArray($data));
}
/**
@@ -68,7 +68,7 @@ class Guest extends \Api_Abstract
}
/**@todo Doctrine: Replace with actual Admin entity once it's migrated to Doctrine. */
- $admin = $this->di['db']->getRow('SELECT name FROM admin WHERE id = :id', ['id' => $post->getAdminId()]);
+ $admin = $this->getDi()['db']->getRow('SELECT name FROM admin WHERE id = :id', ['id' => $post->getAdminId()]);
$post->setAdminData($admin);
diff --git a/src/modules/News/Entity/Post.php b/src/modules/News/Entity/Post.php
index fdf6b3f79..74ff85996 100644
--- a/src/modules/News/Entity/Post.php
+++ b/src/modules/News/Entity/Post.php
@@ -27,6 +27,7 @@ class Post implements ApiArrayInterface, TimestampInterface
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column(type: \Doctrine\DBAL\Types\Types::INTEGER)]
+ /** @phpstan-ignore property.unusedType (Doctrine entity ID is auto-generated by the database) */
private ?int $id = null;
#[ORM\Column(type: \Doctrine\DBAL\Types\Types::INTEGER)]
@@ -123,7 +124,7 @@ class Post implements ApiArrayInterface, TimestampInterface
$this->updatedAt = new \DateTime();
}
- public function getId(): ?int
+ public function getId(): int
{
return $this->id;
}
@@ -193,7 +194,6 @@ class Post implements ApiArrayInterface, TimestampInterface
return $this->expiresAt;
}
- // --- Setters ---
public function setAdminId(int $adminId): self
{
$this->admin_id = $adminId;
diff --git a/src/modules/News/tests/Unit/Repository/PostRepositoryTest.php b/src/modules/News/tests/Unit/Repository/PostRepositoryTest.php
new file mode 100644
index 000000000..334f656ef
--- /dev/null
+++ b/src/modules/News/tests/Unit/Repository/PostRepositoryTest.php
@@ -0,0 +1,48 @@
+shouldReceive('andWhere')->times(4)->andReturnUsing(function (string $clause) use (&$whereCalls, $queryBuilder) {
+ $whereCalls[] = $clause;
+
+ return $queryBuilder;
+ });
+ $queryBuilder->shouldReceive('setParameter')->times(4)->andReturnUsing(function (string $name, mixed $value) use (&$parameters, $queryBuilder) {
+ $parameters[$name] = $value;
+
+ return $queryBuilder;
+ });
+ $queryBuilder->shouldReceive('orderBy')->with('p.createdAt', 'DESC')->once()->andReturn($queryBuilder);
+
+ $repository = Mockery::mock(PostRepository::class)->makePartial();
+ $repository->shouldReceive('createQueryBuilder')->with('p')->once()->andReturn($queryBuilder);
+
+ $result = $repository->getSearchQueryBuilder([
+ 'id' => '7',
+ 'status' => 'active',
+ 'search' => 'release',
+ 'section' => 'billing',
+ ]);
+
+ expect($result)->toBe($queryBuilder);
+ expect($whereCalls)->toBe([
+ 'p.id = :id',
+ 'p.status = :status',
+ '(p.title LIKE :search OR p.slug LIKE :search OR COALESCE(p.description, \'\') LIKE :search OR COALESCE(p.section, \'\') LIKE :search OR COALESCE(p.content, \'\') LIKE :search)',
+ 'p.section LIKE :section',
+ ]);
+ expect($parameters)->toBe([
+ 'id' => 7,
+ 'status' => 'active',
+ 'search' => '%release%',
+ 'section' => '%billing%',
+ ]);
+});
diff --git a/src/modules/Notification/Api/Admin.php b/src/modules/Notification/Api/Admin.php
index ec4b947cd..c8c09e514 100644
--- a/src/modules/Notification/Api/Admin.php
+++ b/src/modules/Notification/Api/Admin.php
@@ -33,11 +33,11 @@ class Admin extends \Api_Abstract
*/
public function get_list($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('notification', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('notification', 'view');
$queryBuilder = $this->getService()->getSearchQueryBuilder($data);
- return $this->di['pager']->paginateDoctrineQuery($queryBuilder, PaginationOptions::fromArray($data));
+ return $this->getDi()['pager']->paginateDoctrineQuery($queryBuilder, PaginationOptions::fromArray($data));
}
/**
@@ -50,7 +50,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Notification ID was not passed'])]
public function get($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('notification', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('notification', 'view');
return $this->getService()->toApiArray($this->getService()->get((int) $data['id']));
}
@@ -62,7 +62,7 @@ class Admin extends \Api_Abstract
*/
public function add($data): int|false
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('notification', 'manage');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('notification', 'manage');
if (!isset($data['message'])) {
return false;
@@ -81,7 +81,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Notification ID was not passed'])]
public function delete($data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('notification', 'manage');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('notification', 'manage');
return $this->getService()->delete((int) $data['id']);
}
@@ -93,7 +93,7 @@ class Admin extends \Api_Abstract
*/
public function delete_all(): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('notification', 'manage');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('notification', 'manage');
return $this->getService()->deleteAll();
}
diff --git a/src/modules/Notification/tests/Unit/Api/AdminTest.php b/src/modules/Notification/tests/Unit/Api/AdminTest.php
new file mode 100644
index 000000000..70539e82d
--- /dev/null
+++ b/src/modules/Notification/tests/Unit/Api/AdminTest.php
@@ -0,0 +1,61 @@
+shouldReceive('getSearchQueryBuilder')->with(['per_page' => 10])->once()->andReturn($queryBuilder);
+
+ $pager = Mockery::mock(FOSSBilling\Pagination::class);
+ $pager->shouldReceive('paginateDoctrineQuery')->once()->andReturnUsing(
+ function ($qb, PaginationOptions $pagination) use ($queryBuilder) {
+ expect($qb)->toBe($queryBuilder);
+ expect($pagination->perPage)->toBe(10);
+
+ return ['list' => []];
+ },
+ );
+
+ $di = new Pimple\Container();
+ $di['pager'] = $pager;
+ $di['mod_service'] = $di->protect(moduleService());
+
+ $api = new Box\Mod\Notification\Api\Admin();
+ $api->setDi($di);
+ $api->setService($service);
+
+ expect($api->get_list(['per_page' => 10]))->toBe(['list' => []]);
+});
+
+test('get returns mapped notification', function (): void {
+ $meta = (new ExtensionMeta())
+ ->setExtension('mod_notification')
+ ->setMetaKey('message')
+ ->setMetaValue('Test');
+
+ $service = Mockery::mock(Box\Mod\Notification\Service::class);
+ $service->shouldReceive('get')->with(5)->once()->andReturn($meta);
+ $service->shouldReceive('toApiArray')->with($meta)->once()->andReturn(['id' => 5, 'meta_value' => 'Test']);
+
+ $api = new Box\Mod\Notification\Api\Admin();
+ $api->setService($service);
+
+ expect($api->get(['id' => 5]))->toBe(['id' => 5, 'meta_value' => 'Test']);
+});
+
+test('delete delegates to service', function (): void {
+ $service = Mockery::mock(Box\Mod\Notification\Service::class);
+ $service->shouldReceive('delete')->with(9)->once()->andReturn(true);
+
+ $api = new Box\Mod\Notification\Api\Admin();
+ $api->setService($service);
+
+ expect($api->delete(['id' => 9]))->toBeTrue();
+});
diff --git a/src/modules/Notification/tests/Unit/ServiceTest.php b/src/modules/Notification/tests/Unit/ServiceTest.php
new file mode 100644
index 000000000..6db2b5881
--- /dev/null
+++ b/src/modules/Notification/tests/Unit/ServiceTest.php
@@ -0,0 +1,61 @@
+shouldReceive('andWhere')->times(5)->andReturnUsing(function (string $clause) use (&$whereCalls, $queryBuilder) {
+ $whereCalls[] = $clause;
+
+ return $queryBuilder;
+ });
+ $queryBuilder->shouldReceive('setParameter')->times(5)->andReturnUsing(function (string $name, mixed $value) use (&$parameters, $queryBuilder) {
+ $parameters[$name] = $value;
+
+ return $queryBuilder;
+ });
+ $queryBuilder->shouldReceive('orderBy')->with('n.id', 'DESC')->once()->andReturn($queryBuilder);
+
+ $repository = Mockery::mock(ExtensionMetaRepository::class)->makePartial();
+ $repository->shouldReceive('createQueryBuilderForExtension')->with('mod_notification', 'n')->once()->andReturn($queryBuilder);
+
+ $em = Mockery::mock(EntityManagerInterface::class);
+ $em->shouldReceive('getRepository')->with(ExtensionMeta::class)->once()->andReturn($repository);
+
+ $di = new Pimple\Container();
+ $di['em'] = $em;
+
+ $service = new Box\Mod\Notification\Service();
+ $service->setDi($di);
+
+ $result = $service->getSearchQueryBuilder([
+ 'id' => '9',
+ 'search' => 'backup',
+ 'date_from' => '2026-02-10',
+ 'date_to' => '2026-02-11',
+ ]);
+
+ expect($result)->toBe($queryBuilder);
+ expect($whereCalls)->toBe([
+ 'n.metaKey = :metaKey',
+ 'n.id = :id',
+ 'n.metaValue LIKE :search',
+ 'n.createdAt >= :date_from',
+ 'n.createdAt <= :date_to',
+ ]);
+ expect($parameters['metaKey'])->toBe('message');
+ expect($parameters['id'])->toBe(9);
+ expect($parameters['search'])->toBe('%backup%');
+ expect($parameters['date_from'])->toBeInstanceOf(DateTime::class);
+ expect($parameters['date_to'])->toBeInstanceOf(DateTime::class);
+ expect($parameters['date_from']->format('Y-m-d H:i:s'))->toBe('2026-02-10 00:00:00');
+ expect($parameters['date_to']->format('Y-m-d H:i:s'))->toBe('2026-02-11 23:59:59');
+});
diff --git a/src/modules/Order/Api/Admin.php b/src/modules/Order/Api/Admin.php
index c67b1e32f..966e47a7f 100644
--- a/src/modules/Order/Api/Admin.php
+++ b/src/modules/Order/Api/Admin.php
@@ -30,7 +30,7 @@ class Admin extends \Api_Abstract
*/
public function get($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('order', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('order', 'view');
$deep = isset($data['deep']) ? (bool) $data['deep'] : true;
$order = $this->_getOrder($data);
@@ -48,16 +48,16 @@ class Admin extends \Api_Abstract
*/
public function get_list($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('order', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('order', 'view');
- $orderConfig = $this->di['mod']('order')->getConfig();
+ $orderConfig = $this->getDi()['mod']('order')->getConfig();
$data['hide_addons'] = (isset($orderConfig['show_addons']) && $orderConfig['show_addons']) ? 0 : 1;
[$sql, $params] = $this->getService()->getSearchQuery($data);
- $resultSet = $this->di['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
+ $resultSet = $this->getDi()['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
foreach ($resultSet['list'] as $key => $result) {
- $orderObj = $this->di['db']->getExistingModelById('ClientOrder', $result['id'], 'Order not found');
+ $orderObj = $this->getDi()['db']->getExistingModelById('ClientOrder', $result['id'], 'Order not found');
$resultSet['list'][$key] = $this->getService()->toApiArray($orderObj, true, $this->getIdentity());
}
@@ -89,24 +89,24 @@ class Admin extends \Api_Abstract
])]
public function create($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('order', 'manage');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('order', 'manage');
$markInvoicePaid = Tools::normalizeBoolean($data['mark_invoice_paid'] ?? false);
$data['mark_invoice_paid'] = $markInvoicePaid;
if ($markInvoicePaid) {
- $staffService = $this->di['mod_service']('Staff');
+ $staffService = $this->getDi()['mod_service']('Staff');
$staffService->checkPermissionsAndThrowException('invoice');
if (($data['invoice_option'] ?? 'no-invoice') !== 'issue-invoice') {
throw new \FOSSBilling\InformationException('Marking an invoice as paid requires the order to issue an invoice.');
}
- $this->di['mod_service']('Invoice')->validateAdminMarkAsPaidRequest($data);
+ $this->getDi()['mod_service']('Invoice')->validateAdminMarkAsPaidRequest($data);
}
- $client = $this->di['db']->getExistingModelById('Client', $data['client_id'], 'Client not found');
- $product = $this->di['db']->getExistingModelById('Product', $data['product_id'], 'Product not found');
+ $client = $this->getDi()['db']->getExistingModelById('Client', $data['client_id'], 'Client not found');
+ $product = $this->getDi()['db']->getExistingModelById('Product', $data['product_id'], 'Product not found');
return $this->getService()->createOrder($client, $product, $data);
}
@@ -128,7 +128,7 @@ class Admin extends \Api_Abstract
*/
public function update($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('order', 'manage');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('order', 'manage');
$order = $this->_getOrder($data);
@@ -144,7 +144,7 @@ class Admin extends \Api_Abstract
*/
public function activate($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('order', 'manage');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('order', 'manage');
$order = $this->_getOrder($data);
@@ -158,7 +158,7 @@ class Admin extends \Api_Abstract
*/
public function renew($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('order', 'manage');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('order', 'manage');
$order = $this->_getOrder($data);
@@ -179,7 +179,7 @@ class Admin extends \Api_Abstract
*/
public function suspend($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('order', 'manage');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('order', 'manage');
$order = $this->_getOrder($data);
$skip_event = Tools::normalizeBoolean($data['skip_event'] ?? false);
@@ -196,7 +196,7 @@ class Admin extends \Api_Abstract
*/
public function unsuspend($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('order', 'manage');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('order', 'manage');
$order = $this->_getOrder($data);
if ($order->status != \Model_ClientOrder::STATUS_SUSPENDED) {
@@ -215,7 +215,7 @@ class Admin extends \Api_Abstract
*/
public function cancel($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('order', 'manage');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('order', 'manage');
$order = $this->_getOrder($data);
$skip_event = Tools::normalizeBoolean($data['skip_event'] ?? false);
@@ -232,7 +232,7 @@ class Admin extends \Api_Abstract
*/
public function uncancel($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('order', 'manage');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('order', 'manage');
$order = $this->_getOrder($data);
if ($order->status != \Model_ClientOrder::STATUS_CANCELED) {
@@ -251,7 +251,7 @@ class Admin extends \Api_Abstract
*/
public function delete($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('order', 'manage');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('order', 'manage');
$order = $this->_getOrder($data);
$delete_addons = Tools::normalizeBoolean($data['delete_addons'] ?? false);
@@ -274,7 +274,7 @@ class Admin extends \Api_Abstract
*/
public function batch_suspend_expired($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('order', 'manage', null, $this->identity);
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('order', 'manage', null, $this->identity);
return $this->getService()->batchSuspendExpired();
}
@@ -287,7 +287,7 @@ class Admin extends \Api_Abstract
*/
public function batch_cancel_suspended($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('order', 'manage', null, $this->identity);
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('order', 'manage', null, $this->identity);
return $this->getService()->batchCancelSuspended();
}
@@ -300,11 +300,11 @@ class Admin extends \Api_Abstract
#[RequiredParams(['config' => 'Order config not passed'])]
public function update_config($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('order', 'manage');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('order', 'manage');
$order = $this->_getOrder($data);
- if (!is_array($data['config'])) {
+ if (!isset($data['config']) || !is_array($data['config'])) {
throw new \FOSSBilling\Exception('Order config not passed');
}
@@ -320,7 +320,7 @@ class Admin extends \Api_Abstract
*/
public function service($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('order', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('order', 'view');
$order = $this->_getOrder($data);
@@ -334,7 +334,7 @@ class Admin extends \Api_Abstract
*/
public function status_history_get_list($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('order', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('order', 'view');
$order = $this->_getOrder($data);
@@ -342,7 +342,7 @@ class Admin extends \Api_Abstract
[$sql, $bindings] = $this->getService()->getOrderStatusSearchQuery($data);
- return $this->di['pager']->getPaginatedResultSet($sql, $bindings, PaginationOptions::fromArray($data));
+ return $this->getDi()['pager']->getPaginatedResultSet($sql, $bindings, PaginationOptions::fromArray($data));
}
/**
@@ -353,7 +353,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['status' => 'Order status was not passed'])]
public function status_history_add($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('order', 'manage');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('order', 'manage');
$order = $this->_getOrder($data);
@@ -370,7 +370,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Order history line ID was not passed'])]
public function status_history_delete($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('order', 'manage');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('order', 'manage');
return $this->getService()->orderStatusRm($data['id']);
}
@@ -382,7 +382,7 @@ class Admin extends \Api_Abstract
*/
public function get_statuses()
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('order', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('order', 'view');
return $this->getService()->counter();
}
@@ -392,7 +392,7 @@ class Admin extends \Api_Abstract
*/
public function get_invoice_options($data): array
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('order', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('order', 'view');
return [
'issue-invoice' => __trans('Automatically Issue Renewal Invoices'),
@@ -405,7 +405,7 @@ class Admin extends \Api_Abstract
*/
public function get_status_pairs($data): array
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('order', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('order', 'view');
return [
\Model_ClientOrder::STATUS_PENDING_SETUP => 'Pending Setup',
@@ -421,7 +421,7 @@ class Admin extends \Api_Abstract
*/
public function addons($data): array
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('order', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('order', 'view');
$model = $this->_getOrder($data);
$list = $this->getService()->getOrderAddonsList($model);
@@ -438,9 +438,9 @@ class Admin extends \Api_Abstract
$required = [
'id' => 'Order ID was not passed',
];
- $this->di['validator']->checkRequiredParamsForArray($required, $data);
+ $this->getDi()['validator']->checkRequiredParamsForArray($required, $data);
- return $this->di['db']->getExistingModelById('ClientOrder', $data['id'], 'Order Not Found');
+ return $this->getDi()['db']->getExistingModelById('ClientOrder', $data['id'], 'Order Not Found');
}
/**
@@ -451,7 +451,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['ids' => 'Order IDs were not passed'])]
public function batch_delete($data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('order', 'manage');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('order', 'manage');
$delete_addons = Tools::normalizeBoolean($data['delete_addons'] ?? false);
@@ -464,7 +464,7 @@ class Admin extends \Api_Abstract
public function export_csv($data): Response
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('order', 'export');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('order', 'export');
$data['headers'] ??= [];
diff --git a/src/modules/Order/Api/Client.php b/src/modules/Order/Api/Client.php
index dc133ef98..3ad174512 100644
--- a/src/modules/Order/Api/Client.php
+++ b/src/modules/Order/Api/Client.php
@@ -36,10 +36,10 @@ class Client extends \Api_Abstract
[$query, $bindings] = $this->getService()->getSearchQuery($data);
}
- $pager = $this->di['pager']->getPaginatedResultSet($query, $bindings, PaginationOptions::fromArray($data));
+ $pager = $this->getDi()['pager']->getPaginatedResultSet($query, $bindings, PaginationOptions::fromArray($data));
foreach ($pager['list'] as $key => $item) {
- $order = $this->di['db']->getExistingModelById('ClientOrder', $item['id'], 'Client order not found');
+ $order = $this->getDi()['db']->getExistingModelById('ClientOrder', $item['id'], 'Client order not found');
$pager['list'][$key] = $this->getService()->toApiArray($order);
}
@@ -97,8 +97,8 @@ class Client extends \Api_Abstract
public function upgradables($data)
{
$model = $this->_getOrder($data);
- $product = $this->di['db']->getExistingModelById('Product', $model->product_id);
- $productService = $this->di['mod_service']('product');
+ $product = $this->getDi()['db']->getExistingModelById('Product', $model->product_id);
+ $productService = $this->getDi()['mod_service']('product');
return $productService->getUpgradablePairs($product);
}
@@ -121,7 +121,7 @@ class Client extends \Api_Abstract
$required = [
'id' => 'Order id required',
];
- $this->di['validator']->checkRequiredParamsForArray($required, $data);
+ $this->getDi()['validator']->checkRequiredParamsForArray($required, $data);
$order = $this->getService()->findForClientById($this->getIdentity(), $data['id']);
if (!$order instanceof \Model_ClientOrder) {
diff --git a/src/modules/Order/Service.php b/src/modules/Order/Service.php
index 96d4a598b..d825f229a 100644
--- a/src/modules/Order/Service.php
+++ b/src/modules/Order/Service.php
@@ -95,7 +95,7 @@ class Service implements InjectionAwareInterface
$emailService = $di['mod_service']('email');
$emailService->sendTemplate($email);
} catch (\Exception $exc) {
- error_log($exc->getMessage());
+ $di['logger']->err($exc->getMessage());
}
}
@@ -121,7 +121,7 @@ class Service implements InjectionAwareInterface
$emailService = $di['mod_service']('email');
$emailService->sendTemplate($email);
} catch (\Exception $exc) {
- error_log($exc->getMessage());
+ $di['logger']->err($exc->getMessage());
}
}
@@ -147,7 +147,7 @@ class Service implements InjectionAwareInterface
$emailService = $di['mod_service']('email');
$emailService->sendTemplate($email);
} catch (\Exception $exc) {
- error_log($exc->getMessage());
+ $di['logger']->err($exc->getMessage());
}
}
@@ -173,7 +173,7 @@ class Service implements InjectionAwareInterface
$emailService = $di['mod_service']('email');
$emailService->sendTemplate($email);
} catch (\Exception $exc) {
- error_log($exc->getMessage());
+ $di['logger']->err($exc->getMessage());
}
}
@@ -197,7 +197,7 @@ class Service implements InjectionAwareInterface
$emailService = $di['mod_service']('email');
$emailService->sendTemplate($email);
} catch (\Exception $exc) {
- error_log($exc->getMessage());
+ $di['logger']->err($exc->getMessage());
}
}
@@ -223,7 +223,7 @@ class Service implements InjectionAwareInterface
$emailService = $di['mod_service']('email');
$emailService->sendTemplate($email);
} catch (\Exception $exc) {
- error_log($exc->getMessage());
+ $di['logger']->err($exc->getMessage());
}
}
diff --git a/src/modules/Order/tests/Unit/Api/AdminTest.php b/src/modules/Order/tests/Unit/Api/AdminTest.php
new file mode 100644
index 000000000..9f05c83fc
--- /dev/null
+++ b/src/modules/Order/tests/Unit/Api/AdminTest.php
@@ -0,0 +1,629 @@
+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);
+
+ $serviceMock = Mockery::mock(Service::class);
+ $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 {
+ $api = new Admin();
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('getSearchQuery')
+ ->atLeast()->once()
+ ->andReturn(['query', []]);
+
+ $paginatorMock = Mockery::mock(FOSSBilling\Pagination::class);
+ $paginatorMock->shouldReceive('getPaginatedResultSet')
+ ->atLeast()->once()
+ ->andReturn(['list' => []]);
+
+ $modMock = Mockery::mock(FOSSBilling\Module::class);
+ $modMock->shouldReceive('getConfig')
+ ->atLeast()->once()
+ ->andReturn(['show_addons' => 0]);
+
+ $di = container();
+ $di['pager'] = $paginatorMock;
+ $di['mod'] = $di->protect(fn () => $modMock);
+
+ $api->setDi($di);
+ $api->setService($serviceMock);
+
+ $result = $api->get_list([]);
+ 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());
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $api->setDi($di);
+ $api->setService($serviceMock);
+
+ $data = [
+ 'client_id' => 1,
+ 'product_id' => 1,
+ ];
+ $result = $api->create($data);
+ expect($result)->toBeInt();
+});
+
+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);
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('updateOrder')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $apiMock->setService($serviceMock);
+
+ $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);
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('activateOrder')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $apiMock->setService($serviceMock);
+
+ $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);
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('renewOrder')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $apiMock->setService($serviceMock);
+
+ $result = $apiMock->renew([]);
+ expect($result)->toBeTrue();
+});
+
+test('renews pending setup order by activating it', function (): void {
+ $api = new Admin();
+ $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);
+
+ $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);
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('suspendFromOrder')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+ $apiMock->setDi($di);
+ $apiMock->setService($serviceMock);
+
+ $result = $apiMock->suspend([]);
+ expect($result)->toBeTrue();
+});
+
+test('unsuspends an order', function (): void {
+ $api = new Admin();
+ $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);
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('unsuspendFromOrder')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $apiMock->setService($serviceMock);
+
+ $result = $apiMock->unsuspend([]);
+ 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);
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('unsuspendFromOrder')
+ ->never()
+ ->andReturn(true);
+
+ $apiMock->setService($serviceMock);
+
+ expect(fn () => $apiMock->unsuspend([]))
+ ->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);
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('cancelFromOrder')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+ $apiMock->setDi($di);
+ $apiMock->setService($serviceMock);
+
+ $result = $apiMock->cancel([]);
+ expect($result)->toBeTrue();
+});
+
+test('uncancels an order', function (): void {
+ $api = new Admin();
+ $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);
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('uncancelFromOrder')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $apiMock->setService($serviceMock);
+
+ $result = $apiMock->uncancel([]);
+ 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);
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('uncancelFromOrder')
+ ->never()
+ ->andReturn(true);
+
+ $apiMock->setService($serviceMock);
+
+ expect(fn () => $apiMock->uncancel([]))
+ ->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);
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('deleteFromOrder')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $apiMock->setService($serviceMock);
+
+ $result = $apiMock->delete([]);
+ 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);
+
+ $serviceMock = Mockery::mock(Service::class);
+ $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);
+
+ $api->setService($serviceMock);
+
+ $result = $api->batch_suspend_expired([]);
+ 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);
+
+ $api->setService($serviceMock);
+
+ $result = $api->batch_cancel_suspended([]);
+ 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);
+
+ $serviceMock = Mockery::mock(Service::class);
+ $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();
+ $order = new Model_ClientOrder();
+ $order->loadBean(new Tests\Helpers\DummyBean());
+
+ $apiMock = Mockery::mock(Admin::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $apiMock->shouldReceive('_getOrder')
+ ->atLeast()->once()
+ ->andReturn($order);
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('updateOrderConfig')
+ ->never()
+ ->andReturn(true);
+
+ $apiMock->setService($serviceMock);
+
+ expect(fn () => $apiMock->update_config([]))
+ ->toThrow(FOSSBilling\Exception::class);
+});
+
+test('gets order service data', 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);
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('getOrderServiceData')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $admin = new Model_Admin();
+ $admin->loadBean(new RedBeanPHP\OODBBean());
+
+ $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();
+ $order = new Model_ClientOrder();
+ $order->loadBean(new Tests\Helpers\DummyBean());
+
+ $apiMock = Mockery::mock(Admin::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $apiMock->shouldReceive('_getOrder')
+ ->atLeast()->once()
+ ->andReturn($order);
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('getOrderStatusSearchQuery')
+ ->atLeast()->once()
+ ->andReturn(['query', []]);
+
+ $paginatorMock = Mockery::mock(FOSSBilling\Pagination::class);
+ $paginatorMock->shouldReceive('getPaginatedResultSet')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $di = container();
+ $di['pager'] = $paginatorMock;
+
+ $apiMock->setDi($di);
+ $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);
+
+ $order = new Model_ClientOrder();
+ $order->loadBean(new Tests\Helpers\DummyBean());
+
+ $apiMock = Mockery::mock(Admin::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $apiMock->shouldReceive('_getOrder')
+ ->atLeast()->once()
+ ->andReturn($order);
+
+ $di = container();
+ $apiMock->setDi($di);
+ $apiMock->setService($serviceMock);
+
+ $data = ['status' => Model_ClientOrder::STATUS_ACTIVE];
+ $result = $apiMock->status_history_add($data);
+ expect($result)->toBeTrue();
+});
+
+test('deletes 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());
+
+ $di = container();
+ $api->setDi($di);
+ $api->setService($serviceMock);
+
+ $data = ['id' => 1];
+ $result = $api->status_history_delete($data);
+ expect($result)->toBeTrue();
+});
+
+test('gets order statuses', function (): void {
+ $api = new Admin();
+ $serviceMock = Mockery::mock(Service::class);
+ $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([]);
+
+ $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->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 {
+ $api = new Admin();
+ $validatorMock = Mockery::mock(FOSSBilling\Validate::class);
+ $validatorMock->shouldReceive('checkRequiredParamsForArray');
+
+ $serviceMock = Mockery::mock(Service::class);
+ $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);
+
+ $di = container();
+ $di['validator'] = $validatorMock;
+ $di['db'] = $dbMock;
+ $api->setDi($di);
+ $api->setService($serviceMock);
+
+ $data = ['id' => 1];
+ $api->get($data);
+});
+
+test('batch deletes orders', function (): void {
+ $api = new Admin();
+ $activityMock = Mockery::mock(Admin::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $activityMock->shouldReceive('delete')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+ $activityMock->setDi($di);
+
+ $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
new file mode 100644
index 000000000..5e1f23e61
--- /dev/null
+++ b/src/modules/Order/tests/Unit/Api/ClientTest.php
@@ -0,0 +1,311 @@
+setDi($di);
+ $getDi = $api->getDi();
+ expect($getDi)->toBe($di);
+});
+
+test('gets order list', function (): void {
+ $api = new Client();
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('getSearchQuery')
+ ->atLeast()->once()
+ ->andReturn(['query', []]);
+ $serviceMock->shouldReceive('toApiArray')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $resultSet = [
+ 'list' => [
+ 0 => ['id' => 1],
+ ],
+ ];
+ $paginatorMock = Mockery::mock(FOSSBilling\Pagination::class);
+ $paginatorMock->shouldReceive('getPaginatedResultSet')
+ ->atLeast()->once()
+ ->andReturn($resultSet);
+
+ $clientOrderMock = new Model_ClientOrder();
+ $clientOrderMock->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($clientOrderMock);
+
+ $di = container();
+ $di['pager'] = $paginatorMock;
+ $di['db'] = $dbMock;
+
+ $api->setDi($di);
+
+ $client = new Model_Client();
+ $client->loadBean(new Tests\Helpers\DummyBean());
+ $client->id = 1;
+
+ $api->setIdentity($client);
+ $api->setService($serviceMock);
+
+ $result = $api->get_list([]);
+ expect($result)->toBeArray();
+});
+
+test('gets expiring order list', function (): void {
+ $api = new Client();
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('getSoonExpiringActiveOrdersQuery')
+ ->atLeast()->once()
+ ->andReturn(['query', []]);
+
+ $paginatorMock = Mockery::mock(FOSSBilling\Pagination::class);
+ $paginatorMock->shouldReceive('getPaginatedResultSet')
+ ->atLeast()->once()
+ ->andReturn(['list' => []]);
+
+ $di = container();
+ $di['pager'] = $paginatorMock;
+
+ $api->setDi($di);
+
+ $client = new Model_Client();
+ $client->loadBean(new Tests\Helpers\DummyBean());
+ $client->id = 1;
+
+ $api->setIdentity($client);
+ $api->setService($serviceMock);
+
+ $data = ['expiring' => true];
+ $result = $api->get_list($data);
+ expect($result)->toBeArray();
+});
+
+test('gets an order', function (): void {
+ $api = new Client();
+ $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);
+
+ $serviceMock = Mockery::mock(Service::class);
+ $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([]);
+
+ $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->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();
+ $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);
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('getOrderServiceData')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $client = new Model_Client();
+ $client->loadBean(new Tests\Helpers\DummyBean());
+
+ $apiMock->setService($serviceMock);
+ $apiMock->setIdentity($client);
+
+ $data = ['id' => 1];
+ $result = $apiMock->service($data);
+ expect($result)->toBeArray();
+});
+
+test('gets upgradable products', 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);
+
+ $productServiceMock = Mockery::mock(Box\Mod\Product\Service::class);
+ $productServiceMock->shouldReceive('getUpgradablePairs')
+ ->atLeast()->once()
+ ->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);
+ $apiMock->setDi($di);
+
+ $result = $apiMock->upgradables([]);
+ expect($result)->toBeArray();
+});
+
+test('deletes a pending order', function (): void {
+ $api = new Client();
+ $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);
+
+ $serviceMock = Mockery::mock(Service::class);
+ $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);
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('deleteFromOrder')
+ ->never()
+ ->andReturn(true);
+
+ $apiMock->setService($serviceMock);
+
+ $data = ['id' => 1];
+
+ expect(fn () => $apiMock->delete($data))
+ ->toThrow(FOSSBilling\Exception::class);
+});
+
+test('gets order for client', 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([]);
+
+ $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];
+ $api->get($data);
+});
+
+test('throws exception when order not found for client', 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([]);
+
+ $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);
+});
diff --git a/src/modules/Order/tests/Unit/ServiceTest.php b/src/modules/Order/tests/Unit/ServiceTest.php
new file mode 100644
index 000000000..a7a456cda
--- /dev/null
+++ b/src/modules/Order/tests/Unit/ServiceTest.php
@@ -0,0 +1,1973 @@
+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);
+
+ $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)->toHaveKey(Model_ClientOrder::STATUS_PENDING_SETUP);
+ expect($result)->toHaveKey(Model_ClientOrder::STATUS_FAILED_SETUP);
+ expect($result)->toHaveKey(Model_ClientOrder::STATUS_ACTIVE);
+ expect($result)->toHaveKey(Model_ClientOrder::STATUS_SUSPENDED);
+ expect($result)->toHaveKey(Model_ClientOrder::STATUS_CANCELED);
+});
+
+test('fires event after admin activates order', function (): void {
+ $params = ['id' => 1];
+
+ $eventMock = Mockery::mock('\Box_Event');
+ $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);
+
+ $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->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;
+ }
+ });
+
+ $eventMock->shouldReceive('getDi')
+ ->atLeast()->once()
+ ->andReturn($di);
+
+ $serviceMock->setDi($di);
+
+ $serviceMock->onAfterAdminOrderActivate($eventMock);
+});
+
+test('logs exception when email fails on activate', function (): void {
+ $params = ['id' => 1];
+
+ $eventMock = Mockery::mock('\Box_Event');
+ $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);
+
+ $emailServiceMock = Mockery::mock(Box\Mod\Email\Service::class);
+ $emailServiceMock->shouldReceive('sendTemplate')
+ ->atLeast()->once()
+ ->andThrow(new Exception('Email send failure'));
+
+ $orderArr = [
+ 'id' => 1,
+ 'client' => ['id' => 1],
+ 'service_type' => 'domain',
+ ];
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+ $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;
+ $di['mod_service'] = $di->protect(function ($serviceName) use ($emailServiceMock, $serviceMock) {
+ if ($serviceName == 'email') {
+ return $emailServiceMock;
+ }
+ if ($serviceName == 'order') {
+ return $serviceMock;
+ }
+ });
+ $di['logger'] = $loggerMock;
+
+ $eventMock->shouldReceive('getDi')
+ ->atLeast()->once()
+ ->andReturn($di);
+
+ $serviceMock->setDi($di);
+
+ $serviceMock->onAfterAdminOrderActivate($eventMock);
+
+ expect($loggerMock->calls)->toHaveCount(1);
+ expect($loggerMock->calls[0]['method'])->toBe('err');
+ expect($loggerMock->calls[0]['params'][0])->toBe('Email send failure');
+});
+
+test('fires event after admin renews order', function (): void {
+ $params = ['id' => 1];
+
+ $eventMock = Mockery::mock('\Box_Event');
+ $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);
+
+ $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->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->onAfterAdminOrderRenew($eventMock);
+});
+
+test('logs exception when email fails on renew', function (): void {
+ $params = ['id' => 1];
+
+ $eventMock = Mockery::mock('\Box_Event');
+ $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);
+
+ $emailServiceMock = Mockery::mock(Box\Mod\Email\Service::class);
+ $emailServiceMock->shouldReceive('sendTemplate')
+ ->atLeast()->once()
+ ->andThrow(new Exception('Email send failure'));
+
+ $orderArr = [
+ 'id' => 1,
+ 'client' => ['id' => 1],
+ 'service_type' => 'domain',
+ ];
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+ $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;
+ $di['mod_service'] = $di->protect(function ($serviceName) use ($emailServiceMock, $serviceMock) {
+ if ($serviceName == 'email') {
+ return $emailServiceMock;
+ }
+ if ($serviceName == 'order') {
+ return $serviceMock;
+ }
+ });
+ $di['logger'] = $loggerMock;
+ $serviceMock->setDi($di);
+ $eventMock->shouldReceive('getDi')
+ ->atLeast()->once()
+ ->andReturn($di);
+
+ $serviceMock->onAfterAdminOrderRenew($eventMock);
+
+ expect($loggerMock->calls)->toHaveCount(1);
+ expect($loggerMock->calls[0]['method'])->toBe('err');
+ expect($loggerMock->calls[0]['params'][0])->toBe('Email send failure');
+});
+
+test('fires event after admin suspends order', function (): void {
+ $params = ['id' => 1];
+
+ $eventMock = Mockery::mock('\Box_Event');
+ $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);
+
+ $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->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 {
+ $params = ['id' => 1];
+
+ $eventMock = Mockery::mock('\Box_Event');
+ $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);
+
+ $emailServiceMock = Mockery::mock(Box\Mod\Email\Service::class);
+ $emailServiceMock->shouldReceive('sendTemplate')
+ ->atLeast()->once()
+ ->andThrow(new Exception('Email send failure'));
+
+ $orderArr = [
+ 'id' => 1,
+ 'client' => ['id' => 1],
+ 'service_type' => 'domain',
+ ];
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+ $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;
+ $di['mod_service'] = $di->protect(function ($serviceName) use ($emailServiceMock, $serviceMock) {
+ if ($serviceName == 'email') {
+ return $emailServiceMock;
+ }
+ if ($serviceName == 'order') {
+ return $serviceMock;
+ }
+ });
+ $di['logger'] = $loggerMock;
+ $serviceMock->setDi($di);
+ $eventMock->shouldReceive('getDi')
+ ->atLeast()->once()
+ ->andReturn($di);
+
+ $serviceMock->onAfterAdminOrderSuspend($eventMock);
+
+ expect($loggerMock->calls)->toHaveCount(1);
+ expect($loggerMock->calls[0]['method'])->toBe('err');
+ expect($loggerMock->calls[0]['params'][0])->toBe('Email send failure');
+});
+
+test('fires event after admin unsuspends order', function (): void {
+ $params = ['id' => 1];
+
+ $eventMock = Mockery::mock('\Box_Event');
+ $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);
+
+ $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->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->onAfterAdminOrderUnsuspend($eventMock);
+});
+
+test('logs exception when email fails on unsuspend', function (): void {
+ $params = ['id' => 1];
+
+ $eventMock = Mockery::mock('\Box_Event');
+ $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);
+
+ $emailServiceMock = Mockery::mock(Box\Mod\Email\Service::class);
+ $emailServiceMock->shouldReceive('sendTemplate')
+ ->atLeast()->once()
+ ->andThrow(new Exception('Email send failure'));
+
+ $orderArr = [
+ 'id' => 1,
+ 'client' => ['id' => 1],
+ 'service_type' => 'domain',
+ ];
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+ $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;
+ $di['mod_service'] = $di->protect(function ($serviceName) use ($emailServiceMock, $serviceMock) {
+ if ($serviceName == 'email') {
+ return $emailServiceMock;
+ }
+ if ($serviceName == 'order') {
+ return $serviceMock;
+ }
+ });
+ $di['logger'] = $loggerMock;
+ $serviceMock->setDi($di);
+ $eventMock->shouldReceive('getDi')
+ ->atLeast()->once()
+ ->andReturn($di);
+
+ $serviceMock->onAfterAdminOrderUnsuspend($eventMock);
+
+ expect($loggerMock->calls)->toHaveCount(1);
+ expect($loggerMock->calls[0]['method'])->toBe('err');
+ expect($loggerMock->calls[0]['params'][0])->toBe('Email send failure');
+});
+
+test('fires event after admin cancels order', function (): void {
+ $params = ['id' => 1];
+
+ $eventMock = Mockery::mock('\Box_Event');
+ $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);
+
+ $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->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->onAfterAdminOrderCancel($eventMock);
+});
+
+test('logs exception when email fails on cancel', function (): void {
+ $params = ['id' => 1];
+
+ $eventMock = Mockery::mock('\Box_Event');
+ $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);
+
+ $emailServiceMock = Mockery::mock(Box\Mod\Email\Service::class);
+ $emailServiceMock->shouldReceive('sendTemplate')
+ ->atLeast()->once()
+ ->andThrow(new Exception('Email send failure'));
+
+ $orderArr = [
+ 'id' => 1,
+ 'client' => ['id' => 1],
+ 'service_type' => 'domain',
+ ];
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+ $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;
+ $di['mod_service'] = $di->protect(function ($serviceName) use ($emailServiceMock, $serviceMock) {
+ if ($serviceName == 'email') {
+ return $emailServiceMock;
+ }
+ if ($serviceName == 'order') {
+ return $serviceMock;
+ }
+ });
+ $di['logger'] = $loggerMock;
+ $serviceMock->setDi($di);
+ $eventMock->shouldReceive('getDi')
+ ->atLeast()->once()
+ ->andReturn($di);
+
+ $serviceMock->onAfterAdminOrderCancel($eventMock);
+
+ expect($loggerMock->calls)->toHaveCount(1);
+ expect($loggerMock->calls[0]['method'])->toBe('err');
+ expect($loggerMock->calls[0]['params'][0])->toBe('Email send failure');
+});
+
+test('fires event after admin uncancels order', function (): void {
+ $params = ['id' => 1];
+
+ $eventMock = Mockery::mock('\Box_Event');
+ $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);
+
+ $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->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->onAfterAdminOrderUncancel($eventMock);
+});
+
+test('logs exception when email fails on uncancel', function (): void {
+ $params = ['id' => 1];
+
+ $eventMock = Mockery::mock('\Box_Event');
+ $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);
+
+ $emailServiceMock = Mockery::mock(Box\Mod\Email\Service::class);
+ $emailServiceMock->shouldReceive('sendTemplate')
+ ->atLeast()->once()
+ ->andThrow(new Exception('Email send failure'));
+
+ $orderArr = [
+ 'id' => 1,
+ 'client' => ['id' => 1],
+ 'service_type' => 'domain',
+ ];
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+ $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;
+ $di['mod_service'] = $di->protect(function ($serviceName) use ($emailServiceMock, $serviceMock) {
+ if ($serviceName == 'email') {
+ return $emailServiceMock;
+ }
+ if ($serviceName == 'order') {
+ return $serviceMock;
+ }
+ });
+ $di['logger'] = $loggerMock;
+ $serviceMock->setDi($di);
+ $eventMock->shouldReceive('getDi')
+ ->atLeast()->once()
+ ->andReturn($di);
+
+ $serviceMock->onAfterAdminOrderUncancel($eventMock);
+
+ expect($loggerMock->calls)->toHaveCount(1);
+ expect($loggerMock->calls[0]['method'])->toBe('err');
+ expect($loggerMock->calls[0]['params'][0])->toBe('Email send failure');
+});
+
+test('gets order core service', function (): void {
+ $orderService = new Service();
+ $modelService = new Model_ServiceCustom();
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('findOne')
+ ->never();
+ $dbMock->shouldReceive('load')
+ ->atLeast()->once()
+ ->andReturn($modelService);
+
+ $toolsMock = Mockery::mock(FOSSBilling\Tools::class);
+ $toolsMock->shouldReceive('to_camel_case')
+ ->atLeast()->once()
+ ->andReturn('ServiceCustom');
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['tools'] = $toolsMock;
+ $orderService->setDi($di);
+
+ $order = new Model_ClientOrder();
+ $order->loadBean(new Tests\Helpers\DummyBean());
+ $order->service_id = 1;
+ $order->service_type = Model_ProductTable::CUSTOM;
+
+ $result = $orderService->getOrderService($order);
+ expect($result)->toBeInstanceOf('Model_ServiceCustom');
+});
+
+test('gets order non-core service', function (): void {
+ $orderService = new Service();
+ $modelService = new Model_ServiceCustom();
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getExistingModelById')
+ ->never()
+ ->andReturn($modelService);
+ $dbMock->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn($modelService);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $orderService->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');
+});
+
+test('returns null when service id not set', function (): void {
+ $orderService = new Service();
+ $modelService = new Model_ServiceCustom();
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getExistingModelById')
+ ->never()
+ ->andReturn($modelService);
+ $dbMock->shouldReceive('findOne')
+ ->never()
+ ->andReturn($modelService);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $orderService->setDi($di);
+
+ $order = new Model_ClientOrder();
+ $order->loadBean(new Tests\Helpers\DummyBean());
+
+ $result = $orderService->getOrderService($order);
+ expect($result)->toBeNull();
+});
+
+test('gets service order', function (): void {
+ $orderService = new Service();
+ $order = new Model_ClientOrder();
+ $order->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn($order);
+
+ $toolsMock = Mockery::mock(FOSSBilling\Tools::class);
+ $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;
+
+ $result = $orderService->getServiceOrder($modelService);
+ expect($result)->toBeInstanceOf('Model_ClientOrder');
+});
+
+test('gets order config', function (): void {
+ $orderService = new Service();
+ $di = container();
+ $orderService->setDi($di);
+
+ $order = new Model_ClientOrder();
+ $order->loadBean(new Tests\Helpers\DummyBean());
+
+ $result = $orderService->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);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $orderService->setDi($di);
+
+ $product = new Model_Product();
+ $product->loadBean(new Tests\Helpers\DummyBean());
+ $product->id = 1;
+
+ $result = $orderService->productHasOrders($product);
+ expect($result)->toBe($expectedResult);
+})->with([
+ [new Model_ClientOrder(), true],
+ [null, false],
+]);
+
+test('saves status change', function (): void {
+ $orderService = new Service();
+ $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);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $orderService->setDi($di);
+
+ $order = new Model_ClientOrder();
+ $order->loadBean(new Tests\Helpers\DummyBean());
+
+ $result = $orderService->saveStatusChange($order);
+ expect($result)->toBeNull();
+});
+
+test('gets soon expiring active orders', function (): void {
+ $order = new Model_ClientOrder();
+ $order->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getAll')
+ ->atLeast()->once()
+ ->andReturn([[], []]);
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+ $serviceMock->shouldReceive('getSoonExpiringActiveOrdersQuery')
+ ->atLeast()->once()
+ ->andReturn(['query', []]);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $serviceMock->setDi($di);
+
+ $serviceMock->getSoonExpiringActiveOrders();
+});
+
+test('gets soon expiring active orders query', function (): void {
+ $orderService = new Service();
+ $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);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $systemService);
+
+ $orderService->setDi($di);
+
+ $order = new Model_ClientOrder();
+ $order->loadBean(new Tests\Helpers\DummyBean());
+
+ $data = ['client_id' => $randId];
+ $result = $orderService->getSoonExpiringActiveOrdersQuery($data);
+
+ $expectedQuery = 'SELECT *
+ FROM client_order
+ WHERE status = :status
+ AND invoice_option = :invoice_option
+ AND period IS NOT NULL
+ AND expires_at IS NOT NULL
+ AND unpaid_invoice_id IS NULL AND client_id = :client_id HAVING DATEDIFF(expires_at, NOW()) <= :days_until_expiration ORDER BY client_id DESC';
+
+ $expectedBindings = [
+ ':client_id' => $randId,
+ ':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);
+});
+
+test('gets related order id by type', function (): void {
+ $orderService = new Service();
+ $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);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $orderService->setDi($di);
+
+ $result = $orderService->getRelatedOrderIdByType($model, 'domain');
+ expect($result)->toBeInt();
+ expect($result)->toBe($id);
+});
+
+test('returns null when related order not found', function (): void {
+ $orderService = new Service();
+ $model = new Model_ClientOrder();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $model->id = 1;
+
+ $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);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $orderService->setDi($di);
+
+ $result = $orderService->getRelatedOrderIdByType($model, 'domain');
+ expect($result)->toBeNull();
+});
+
+test('gets logger', function (): void {
+ $orderService = new Service();
+ $model = new Model_ClientOrder();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $di = container();
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $orderService->setDi($di);
+
+ $result = $orderService->getLogger($model);
+ expect($result)->toBeInstanceOf('\Box_Log');
+});
+
+test('converts order to api array', function (): void {
+ $orderService = new Service();
+ $model = new Model_ClientOrder();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $model->config = '{}';
+ $model->price = 10;
+ $model->quantity = 1;
+ $model->client_id = 1;
+
+ $clientService = Mockery::mock(Box\Mod\Client\Service::class);
+ $clientService->shouldReceive('toApiArray')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $supportService = Mockery::mock(Box\Mod\Support\Service::class);
+ $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([]);
+
+ $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,
+ });
+
+ $dbMock->shouldReceive('getExistingModelById')
+ ->with('Client', $model->client_id, 'Client not found')
+ ->atLeast()->once()
+ ->andReturn($modelClient);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(function ($serviceName) use ($clientService, $supportService) {
+ if ($serviceName == 'client') {
+ return $clientService;
+ }
+ if ($serviceName == 'support') {
+ return $supportService;
+ }
+ });
+ $di['db'] = $dbMock;
+
+ $orderService->setDi($di);
+ $result = $orderService->toApiArray($model, true, new Model_Admin());
+
+ expect($result)->toHaveKey('config');
+ expect($result)->toHaveKey('total');
+ expect($result)->toHaveKey('title');
+ expect($result)->toHaveKey('meta');
+ expect($result)->toHaveKey('active_tickets');
+ expect($result)->toHaveKey('plugin');
+ expect($result)->toHaveKey('client');
+});
+
+test('gets search query with various filters', function (array $data, string $expectedStr, array $expectedParams): void {
+ $orderService = new Service();
+ $di = container();
+
+ $orderService->setDi($di);
+
+ $result = $orderService->getSearchQuery($data);
+ expect($result[0])->toBeString();
+ expect($result[1])->toBeArray();
+
+ 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('throws exception when creating order with missing currency', function (): void {
+ $orderService = new Service();
+ $modelClient = new Model_Client();
+ $modelClient->loadBean(new Tests\Helpers\DummyBean());
+
+ $modelProduct = new Model_Product();
+ $modelProduct->loadBean(new Tests\Helpers\DummyBean());
+
+ $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);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(function ($serviceName) use ($currencyServiceMock) {
+ if ($serviceName == 'currency') {
+ return $currencyServiceMock;
+ }
+ });
+
+ $orderService->setDi($di);
+
+ expect(fn () => $orderService->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();
+ $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;
+
+ $currencyModel = Mockery::mock(\Box\Mod\Currency\Entity\Currency::class);
+
+ $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')
+ ->with($modelProduct, 1)
+ ->atLeast()->once()
+ ->andReturn(false);
+
+ $eventMock = Mockery::mock('\Box_EventManager');
+ $eventMock->shouldReceive('fire');
+
+ $di = container();
+ $di['mod_service'] = $di->protect(function ($serviceName) use ($currencyServiceMock, $cartServiceMock) {
+ if ($serviceName == 'currency') {
+ return $currencyServiceMock;
+ }
+ if ($serviceName == 'cart') {
+ return $cartServiceMock;
+ }
+ });
+
+ $di['events_manager'] = $eventMock;
+
+ $orderService->setDi($di);
+
+ expect(fn () => $orderService->createOrder($modelClient, $modelProduct, []))
+ ->toThrow(FOSSBilling\InformationException::class, 'Product 1 is out of stock.');
+});
+
+test('throws exception when creating addon order with missing group id', function (): void {
+ $orderService = new Service();
+ $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;
+
+ $currencyModel = Mockery::mock(\Box\Mod\Currency\Entity\Currency::class);
+
+ $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')
+ ->with($modelProduct, 1)
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $eventMock = Mockery::mock('\Box_EventManager');
+ $eventMock->shouldReceive('fire');
+
+ $di = container();
+ $di['mod_service'] = $di->protect(function ($serviceName) use ($currencyServiceMock, $cartServiceMock) {
+ if ($serviceName == 'currency') {
+ return $currencyServiceMock;
+ }
+ if ($serviceName == 'cart') {
+ return $cartServiceMock;
+ }
+ });
+
+ $di['events_manager'] = $eventMock;
+
+ $orderService->setDi($di);
+
+ expect(fn () => $orderService->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();
+ $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;
+
+ $currencyModel = Mockery::mock(\Box\Mod\Currency\Entity\Currency::class);
+
+ $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')
+ ->with($modelProduct, 1)
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $eventMock = Mockery::mock('\Box_EventManager');
+ $eventMock->shouldReceive('fire');
+
+ $di = container();
+ $di['mod_service'] = $di->protect(function ($serviceName) use ($currencyServiceMock, $cartServiceMock) {
+ if ($serviceName == 'currency') {
+ return $currencyServiceMock;
+ }
+ if ($serviceName == 'cart') {
+ return $cartServiceMock;
+ }
+ });
+
+ $di['events_manager'] = $eventMock;
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('getMasterOrderForClient')
+ ->atLeast()->once()
+ ->andReturn(null);
+
+ $serviceMock->setDi($di);
+
+ expect(fn () => $serviceMock->createOrder($modelClient, $modelProduct, ['group_id' => 1]))
+ ->toThrow(FOSSBilling\Exception::class, 'Parent order 1 was not found');
+});
+
+test('creates order', function (): void {
+ $orderService = new Service();
+ $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';
+
+ $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);
+ $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')
+ ->with($modelProduct, 1)
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $eventMock = Mockery::mock('\Box_EventManager');
+ $eventMock->shouldReceive('fire');
+ $productServiceMock = Mockery::mock(Box\Mod\Servicecustom\Service::class);
+
+ $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);
+
+ $periodMock = Mockery::mock('\Box_Period');
+ $periodMock->shouldReceive('getCode')
+ ->atLeast()->once()
+ ->andReturn('1Y');
+
+ $di = container();
+ $di['mod_service'] = $di->protect(function ($serviceName) use ($currencyServiceMock, $cartServiceMock, $productServiceMock) {
+ if ($serviceName == 'currency') {
+ return $currencyServiceMock;
+ }
+ if ($serviceName == 'cart') {
+ return $cartServiceMock;
+ }
+ 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);
+ $dbMock->shouldReceive('transaction')
+ ->once()
+ ->andReturnUsing(fn (callable $callback) => $callback());
+ $di['db'] = $dbMock;
+ $di['period'] = $di->protect(fn (): Mockery\MockInterface => $periodMock);
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $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();
+ $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);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $orderService->setDi($di);
+ $result = $orderService->getMasterOrderForClient($clientModel, 1);
+ expect($result)->toBeInstanceOf('Model_ClientOrder');
+});
+
+test('throws exception when activating non-pending order', function (): void {
+ $orderService = new Service();
+ $clientOrderModel = new Model_ClientOrder();
+ $clientOrderModel->loadBean(new Tests\Helpers\DummyBean());
+ $clientOrderModel->status = Model_ClientOrder::STATUS_CANCELED;
+
+ expect(fn (): bool => $orderService->activateOrder($clientOrderModel))
+ ->toThrow(FOSSBilling\Exception::class, 'Only pending setup or failed orders can be activated');
+});
+
+test('activates 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');
+
+ $di = container();
+ $di['events_manager'] = $eventMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+ $serviceMock->shouldReceive('createFromOrder')
+ ->atLeast()->once()
+ ->andReturn([]);
+ $serviceMock->shouldReceive('activateOrderAddons');
+
+ $serviceMock->setDi($di);
+ $result = $serviceMock->activateOrder($clientOrderModel);
+ expect($result)->toBeTrue();
+});
+
+test('activates order 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([]);
+
+ $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');
+
+ $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();
+ $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()]);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $orderService->setDi($di);
+
+ $result = $orderService->getOrderAddonsList($modelClientOrder);
+ expect($result)->toBeArray();
+ expect($result[0])->toBeInstanceOf('\Model_ClientOrder');
+});
+
+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;
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->with($productModel);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $orderService->setDi($di);
+
+ $result = $orderService->stockSale($productModel, 2);
+ expect($result)->toBeTrue();
+});
+
+test('updates order', function (): void {
+ $orderService = new Service();
+ $clientOrderModel = new Model_ClientOrder();
+ $clientOrderModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $eventMock = Mockery::mock('\Box_EventManager');
+ $eventMock->shouldReceive('fire');
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->with($clientOrderModel);
+
+ $di = container();
+ $di['events_manager'] = $eventMock;
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $data = [
+ 'period' => '1Y',
+ 'created_at' => '2012-12-01',
+ 'activated_at' => '2012-12-01',
+ 'expires_at' => '2013-12-01',
+ 'invoice_option' => 'issue-invoice',
+ 'title' => 'Testing',
+ 'price' => 10,
+ 'status' => 'active',
+ 'notes' => 'Empty note',
+ 'reason' => 'non',
+ 'meta' => [],
+ ];
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+ $serviceMock->shouldReceive('updatePeriod')
+ ->with($clientOrderModel, $data['period']);
+ $serviceMock->shouldReceive('updateOrderMeta')
+ ->with($clientOrderModel, $data['meta']);
+
+ $serviceMock->setDi($di);
+ $result = $serviceMock->updateOrder($clientOrderModel, $data);
+ expect($result)->toBeTrue();
+});
+
+test('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');
+
+ $di = container();
+ $di['events_manager'] = $eventMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+ $serviceMock->shouldReceive('renewFromOrder')
+ ->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();
+ $clientOrderModel = new Model_ClientOrder();
+ $clientOrderModel->loadBean(new Tests\Helpers\DummyBean());
+ $clientOrderModel->period = '1Y';
+
+ $periodMock = Mockery::mock('\Box_Period');
+
+ $dbMock = Mockery::mock('Box_Database');
+
+ $invoiceServiceMock = Mockery::mock(Box\Mod\Invoice\Service::class);
+ $invoiceServiceMock->shouldReceive('findPaidInvoicesForOrder');
+ $periodMock->shouldReceive('getExpirationTime')
+ ->atLeast()->once()
+ ->andReturn(time() + 3600);
+
+ $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);
+});
+
+test('throws exception when suspending non-active order', function (): void {
+ $orderService = new Service();
+ $clientOrderModel = new Model_ClientOrder();
+ $clientOrderModel->loadBean(new Tests\Helpers\DummyBean());
+ $clientOrderModel->status = Model_ClientOrder::STATUS_SUSPENDED;
+
+ $eventMock = Mockery::mock('\Box_EventManager');
+ $eventMock->shouldReceive('fire');
+
+ $di = container();
+ $di['events_manager'] = $eventMock;
+
+ $orderService->setDi($di);
+
+ expect(fn (): bool => $orderService->suspendFromOrder($clientOrderModel))
+ ->toThrow(FOSSBilling\Exception::class, 'Only active orders can be suspended');
+});
+
+test('suspends from 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');
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->with($clientOrderModel);
+
+ $di = container();
+ $di['events_manager'] = $eventMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $di['db'] = $dbMock;
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('_callOnService');
+ $serviceMock->shouldReceive('saveStatusChange');
+
+ $serviceMock->setDi($di);
+ $result = $serviceMock->suspendFromOrder($clientOrderModel);
+ expect($result)->toBeTrue();
+});
+
+test('removes orders by client', function (): void {
+ $orderService = new Service();
+ $clientModel = new Model_Client();
+ $clientModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $queryBuilderMock = new class {
+ private bool $deleteCalled = false;
+ private bool $whereCalled = false;
+ private bool $setParamCalled = false;
+ private mixed $deleteTable = null;
+ private mixed $whereCond = null;
+ private mixed $paramId = null;
+
+ public function delete($table)
+ {
+ $this->deleteCalled = true;
+ $this->deleteTable = $table;
+
+ return $this;
+ }
+
+ public function where($cond)
+ {
+ $this->whereCalled = true;
+ $this->whereCond = $cond;
+
+ return $this;
+ }
+
+ public function setParameter($key, $val)
+ {
+ $this->setParamCalled = true;
+ $this->paramId = $val;
+
+ return $this;
+ }
+
+ public function executeStatement(): int
+ {
+ return 1;
+ }
+
+ public function getDeleteTable()
+ {
+ return $this->deleteTable;
+ }
+
+ public function getWhereCond()
+ {
+ return $this->whereCond;
+ }
+
+ public function getParamId()
+ {
+ return $this->paramId;
+ }
+
+ public function wasDeleteCalled(): bool
+ {
+ return $this->deleteCalled;
+ }
+
+ public function wasWhereCalled(): bool
+ {
+ return $this->whereCalled;
+ }
+
+ public function wasSetParamCalled(): bool
+ {
+ return $this->setParamCalled;
+ }
+ };
+
+ $dbalMock = new class($queryBuilderMock) {
+ public function __construct(private $qb)
+ {
+ }
+
+ public function createQueryBuilder()
+ {
+ return $this->qb;
+ }
+ };
+
+ $di = new Pimple\Container();
+ $di['dbal'] = $dbalMock;
+ $orderService->setDi($di);
+ $orderService->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();
+ $period = '1Y';
+ $di = container();
+
+ $periodMock = Mockery::mock('\Box_Period');
+ $periodMock->shouldReceive('getCode');
+ $di['period'] = $di->protect(fn (): Mockery\MockInterface => $periodMock);
+
+ $orderService->setDi($di);
+ $clientOrder = new Model_ClientOrder();
+ $clientOrder->loadBean(new Tests\Helpers\DummyBean());
+ $result = $orderService->updatePeriod($clientOrder, $period);
+ expect($result)->toBe(1);
+});
+
+test('updates period when empty', function (): void {
+ $orderService = new Service();
+ $period = '';
+ $di = container();
+ $periodMock = Mockery::mock('\Box_Period');
+ $periodMock->shouldReceive('getCode')
+ ->never();
+ $di['period'] = $di->protect(fn (): Mockery\MockInterface => $periodMock);
+
+ $orderService->setDi($di);
+ $clientOrder = new Model_ClientOrder();
+ $clientOrder->loadBean(new Tests\Helpers\DummyBean());
+ $result = $orderService->updatePeriod($clientOrder, $period);
+ expect($result)->toBe(2);
+});
+
+test('updates period when not set', function (): void {
+ $orderService = new Service();
+ $period = null;
+ $di = container();
+ $periodMock = Mockery::mock('\Box_Period');
+ $periodMock->shouldReceive('getCode')
+ ->never();
+ $di['period'] = $di->protect(fn (): Mockery\MockInterface => $periodMock);
+
+ $orderService->setDi($di);
+ $clientOrder = new Model_ClientOrder();
+ $clientOrder->loadBean(new Tests\Helpers\DummyBean());
+ $result = $orderService->updatePeriod($clientOrder, $period);
+ expect($result)->toBe(0);
+});
+
+test('updates order meta when not set', function (): void {
+ $orderService = new Service();
+ $meta = null;
+ $clientOrder = new Model_ClientOrder();
+ $clientOrder->loadBean(new Tests\Helpers\DummyBean());
+ $result = $orderService->updateOrderMeta($clientOrder, $meta);
+ expect($result)->toBe(0);
+});
+
+test('updates order meta when empty', function (): void {
+ $orderService = new Service();
+ $meta = [];
+ $di = container();
+
+ $dBMock = Mockery::mock('\Box_Database');
+ $dBMock->shouldReceive('exec')
+ ->atLeast()->once();
+ $di['db'] = $dBMock;
+
+ $orderService->setDi($di);
+ $clientOrder = new Model_ClientOrder();
+ $clientOrder->loadBean(new Tests\Helpers\DummyBean());
+ $result = $orderService->updateOrderMeta($clientOrder, $meta);
+ expect($result)->toBe(1);
+});
+
+test('updates order meta', function (): void {
+ $orderService = new Service();
+ $meta = ['key' => 'value'];
+ $di = container();
+
+ $dBMock = Mockery::mock('\Box_Database');
+ $dBMock->shouldReceive('findOne')
+ ->with('ClientOrderMeta', 'client_order_id = :id AND name = :n', Mockery::type('array'))
+ ->atLeast()->once()
+ ->andReturn(null);
+
+ $clientOrderMetaModel = new Model_ClientOrderMeta();
+ $clientOrderMetaModel->loadBean(new Tests\Helpers\DummyBean());
+ $dBMock->shouldReceive('dispense')
+ ->with('ClientOrderMeta')
+ ->atLeast()->once()
+ ->andReturn($clientOrderMetaModel);
+ $dBMock->shouldReceive('store')
+ ->atLeast()->once();
+ $di['db'] = $dBMock;
+
+ $orderService->setDi($di);
+ $clientOrder = new Model_ClientOrder();
+ $clientOrder->loadBean(new Tests\Helpers\DummyBean());
+ $result = $orderService->updateOrderMeta($clientOrder, $meta);
+ expect($result)->toBe(2);
+});
diff --git a/src/modules/Page/tests/Unit/Api/AdminTest.php b/src/modules/Page/tests/Unit/Api/AdminTest.php
new file mode 100644
index 000000000..1506182e2
--- /dev/null
+++ b/src/modules/Page/tests/Unit/Api/AdminTest.php
@@ -0,0 +1,36 @@
+setDi($di);
+ $getDi = $api->getDi();
+ expect($getDi)->toEqual($di);
+});
+
+test('getPairs returns page pairs array', function (): void {
+ $api = new Admin();
+ $serviceMock = Mockery::mock(Box\Mod\Page\Service::class);
+ /** @var Mockery\Expectation $expectation */
+ $expectation = $serviceMock->shouldReceive('getPairs');
+ $expectation->atLeast()->once();
+ $expectation->andReturn([]);
+
+ $api->setService($serviceMock);
+ $result = $api->get_pairs();
+ expect($result)->toBeArray();
+});
diff --git a/src/modules/Page/tests/Unit/ServiceTest.php b/src/modules/Page/tests/Unit/ServiceTest.php
new file mode 100644
index 000000000..19ae61bf7
--- /dev/null
+++ b/src/modules/Page/tests/Unit/ServiceTest.php
@@ -0,0 +1,32 @@
+shouldReceive('getCurrentClientAreaThemeCode');
+ $expectation->atLeast()->once();
+ $expectation->andReturn('huraga');
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $themeService);
+
+ $service->setDi($di);
+ $result = $service->getPairs();
+ expect($result)->toBeArray();
+});
diff --git a/src/modules/Product/Api/Admin.php b/src/modules/Product/Api/Admin.php
index 08f91065d..73f0fd8df 100644
--- a/src/modules/Product/Api/Admin.php
+++ b/src/modules/Product/Api/Admin.php
@@ -28,15 +28,15 @@ class Admin extends \Api_Abstract
*/
public function get_list($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('product', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('product', 'view');
$service = $this->getService();
[$sql, $params] = $service->getProductSearchQuery($data);
- $pager = $this->di['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
+ $pager = $this->getDi()['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
foreach ($pager['list'] as $key => $item) {
- $model = $this->di['db']->getExistingModelById('Product', $item['id'], 'Post not found');
+ $model = $this->getDi()['db']->getExistingModelById('Product', $item['id'], 'Post not found');
$pager['list'][$key] = $this->getService()->toApiArray($model, false, $this->getIdentity());
}
@@ -50,7 +50,7 @@ class Admin extends \Api_Abstract
*/
public function get_pairs($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('product', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('product', 'view');
$service = $this->getService();
@@ -64,7 +64,7 @@ class Admin extends \Api_Abstract
*/
public function get($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('product', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('product', 'view');
$model = $this->_getProduct($data);
$service = $this->getService();
@@ -79,7 +79,7 @@ class Admin extends \Api_Abstract
*/
public function get_types()
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('product', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('product', 'view');
return $this->getService()->getTypes();
}
@@ -96,7 +96,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['title' => 'You must specify a title', 'type' => 'Type was not passed'])]
public function prepare($data): int
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('product', 'manage_products');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('product', 'manage_products');
$service = $this->getService();
// allow having only one domain product
@@ -142,7 +142,7 @@ class Admin extends \Api_Abstract
*/
public function update($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('product', 'manage_products');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('product', 'manage_products');
$model = $this->_getProduct($data);
$service = $this->getService();
@@ -160,7 +160,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['priority' => 'priority params is missing'])]
public function update_priority($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('product', 'manage_products');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('product', 'manage_products');
if (!is_array($data['priority'] ?? null)) {
throw new \FOSSBilling\Exception('priority params is missing');
@@ -180,7 +180,7 @@ class Admin extends \Api_Abstract
*/
public function update_config($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('product', 'manage_products');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('product', 'manage_products');
$model = $this->_getProduct($data);
@@ -196,7 +196,7 @@ class Admin extends \Api_Abstract
*/
public function addon_get_pairs($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('product', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('product', 'view');
return $this->getService()->getAddons();
}
@@ -211,7 +211,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['title' => 'You must specify a title'])]
public function addon_create($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('product', 'manage_products');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('product', 'manage_products');
$title = $data['title'];
$status = $data['status'] ?? null;
@@ -234,9 +234,9 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Addon ID was not passed'])]
public function addon_get($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('product', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('product', 'view');
- $model = $this->di['db']->load('Product', $data['id']);
+ $model = $this->getDi()['db']->load('Product', $data['id']);
if (!$model instanceof \Model_Product || !$model->is_addon) {
throw new \FOSSBilling\Exception('Addon not found');
}
@@ -271,13 +271,13 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Addon ID was not passed'])]
public function addon_update($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('product', 'manage_products');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('product', 'manage_products');
- $model = $this->di['db']->load('Product', $data['id']);
+ $model = $this->getDi()['db']->load('Product', $data['id']);
if (!$model instanceof \Model_Product || !$model->is_addon) {
throw new \FOSSBilling\Exception('Addon not found');
}
- $this->di['logger']->info('Updated addon #%s', $model->id);
+ $this->getDi()['logger']->info('Updated addon #%s', $model->id);
return $this->update($data);
}
@@ -289,7 +289,7 @@ class Admin extends \Api_Abstract
*/
public function addon_delete($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('product', 'manage_products');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('product', 'manage_products');
return $this->delete($data);
}
@@ -301,7 +301,7 @@ class Admin extends \Api_Abstract
*/
public function delete($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('product', 'manage_products');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('product', 'manage_products');
$model = $this->_getProduct($data);
$service = $this->getService();
@@ -316,7 +316,7 @@ class Admin extends \Api_Abstract
*/
public function category_get_pairs($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('product', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('product', 'view');
return $this->getService()->getProductCategoryPairs($data);
}
@@ -335,9 +335,9 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Category ID was not passed'])]
public function category_update($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('product', 'manage_categories');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('product', 'manage_categories');
- $model = $this->di['db']->getExistingModelById('ProductCategory', $data['id'], 'Category not found');
+ $model = $this->getDi()['db']->getExistingModelById('ProductCategory', $data['id'], 'Category not found');
$title = $data['title'] ?? null;
$description = $data['description'] ?? null;
@@ -358,9 +358,9 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Category ID was not passed'])]
public function category_get($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('product', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('product', 'view');
- $model = $this->di['db']->getExistingModelById('ProductCategory', $data['id'], 'Category not found');
+ $model = $this->getDi()['db']->getExistingModelById('ProductCategory', $data['id'], 'Category not found');
return $this->getService()->toProductCategoryApiArray($model, true, $this->getIdentity());
}
@@ -378,7 +378,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['title' => 'Category title is required'])]
public function category_create($data): int
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('product', 'manage_categories');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('product', 'manage_categories');
$service = $this->getService();
@@ -399,9 +399,9 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Category ID was not passed'])]
public function category_delete($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('product', 'manage_categories');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('product', 'manage_categories');
- $model = $this->di['db']->getExistingModelById('ProductCategory', $data['id'], 'Category not found');
+ $model = $this->getDi()['db']->getExistingModelById('ProductCategory', $data['id'], 'Category not found');
$service = $this->getService();
return $service->removeProductCategory($model);
@@ -414,15 +414,15 @@ class Admin extends \Api_Abstract
*/
public function promo_get_list($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('product', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('product', 'view');
$service = $this->getService();
[$sql, $params] = $service->getPromoSearchQuery($data);
- $pager = $this->di['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
+ $pager = $this->getDi()['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
foreach ($pager['list'] as $key => $item) {
- $model = $this->di['db']->getExistingModelById('Promo', $item['id'], 'Promo not found');
+ $model = $this->getDi()['db']->getExistingModelById('Promo', $item['id'], 'Promo not found');
$pager['list'][$key] = $this->getService()->toPromoApiArray($model);
}
@@ -453,7 +453,7 @@ class Admin extends \Api_Abstract
])]
public function promo_create($data): int
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('product', 'manage_promos');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('product', 'manage_promos');
$products = [];
if (isset($data['products']) && is_array($data['products'])) {
@@ -483,10 +483,10 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Promo ID was not passed'])]
public function promo_get($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('product', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('product', 'view');
$id = $data['id'] ?? null;
- $model = $this->di['db']->getExistingModelById('Promo', $id, 'Promo not found');
+ $model = $this->getDi()['db']->getExistingModelById('Promo', $id, 'Promo not found');
return $this->getService()->toPromoApiArray($model, true, $this->getIdentity());
}
@@ -515,9 +515,9 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Promo ID was not passed'])]
public function promo_update($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('product', 'manage_promos');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('product', 'manage_promos');
- $model = $this->di['db']->getExistingModelById('Promo', $data['id'], 'Promo not found');
+ $model = $this->getDi()['db']->getExistingModelById('Promo', $data['id'], 'Promo not found');
$service = $this->getService();
@@ -534,9 +534,9 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Promo ID was not passed'])]
public function promo_delete($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('product', 'manage_promos');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('product', 'manage_promos');
- $model = $this->di['db']->getExistingModelById('Promo', $data['id'], 'Promo not found');
+ $model = $this->getDi()['db']->getExistingModelById('Promo', $data['id'], 'Promo not found');
return $this->getService()->deletePromo($model);
}
@@ -544,6 +544,6 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Product ID was not passed'])]
private function _getProduct($data)
{
- return $this->di['db']->getExistingModelById('Product', $data['id'], 'Product not found');
+ return $this->getDi()['db']->getExistingModelById('Product', $data['id'], 'Product not found');
}
}
diff --git a/src/modules/Product/Api/Guest.php b/src/modules/Product/Api/Guest.php
index c82eda69a..af1d04245 100644
--- a/src/modules/Product/Api/Guest.php
+++ b/src/modules/Product/Api/Guest.php
@@ -31,10 +31,10 @@ class Guest extends \Api_Abstract
$data['show_hidden'] = false;
[$sql, $params] = $this->getService()->getProductSearchQuery($data);
- $pager = $this->di['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
+ $pager = $this->getDi()['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
foreach ($pager['list'] as $key => $item) {
- $model = $this->di['db']->getExistingModelById('Product', $item['id'], 'Post not found');
+ $model = $this->getDi()['db']->getExistingModelById('Product', $item['id'], 'Post not found');
$pager['list'][$key] = $this->getService()->toApiArray($model, false);
}
@@ -96,10 +96,10 @@ class Guest extends \Api_Abstract
$service = $this->getService();
[$sql, $params] = $service->getProductCategorySearchQuery($data);
- $pager = $this->di['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
+ $pager = $this->getDi()['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
foreach ($pager['list'] as $key => $item) {
- $category = $this->di['db']->getExistingModelById('ProductCategory', $item['id'], 'Product category not found');
+ $category = $this->getDi()['db']->getExistingModelById('ProductCategory', $item['id'], 'Product category not found');
$pager['list'][$key] = $this->getService()->toProductCategoryApiArray($category);
}
diff --git a/src/modules/Product/tests/Unit/Api/AdminTest.php b/src/modules/Product/tests/Unit/Api/AdminTest.php
new file mode 100644
index 000000000..71f6dcbcc
--- /dev/null
+++ b/src/modules/Product/tests/Unit/Api/AdminTest.php
@@ -0,0 +1,634 @@
+setDi($di);
+ $getDi = $api->getDi();
+ expect($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;
+
+ $api->setService($serviceMock);
+ $api->setDi($di);
+ $result = $api->get_list([]);
+ expect($result)->toBeArray();
+});
+
+test('gets product pairs', function (): void {
+ $api = new Admin();
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('getPairs')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $api->setService($serviceMock);
+ $result = $api->get_pairs([]);
+ expect($result)->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);
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('toApiArray')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $api->setDi($di);
+ $api->setService($serviceMock);
+ $result = $api->get($data);
+ expect($result)->toBeArray();
+});
+
+test('gets product types', function (): void {
+ $api = new Admin();
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('getTypes')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $api->setService($serviceMock);
+ $result = $api->get_types();
+ expect($result)->toBeArray();
+});
+
+test('throws exception when preparing domain product already created', function (): void {
+ $api = new Admin();
+ $data = [
+ 'title' => 'testTitle',
+ 'type' => 'domain',
+ ];
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('getMainDomainProduct')
+ ->atLeast()->once()
+ ->andReturn(new Model_ProductDomain());
+
+ $di = container();
+ $api->setDi($di);
+ $api->setService($serviceMock);
+
+ expect(fn (): int => $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',
+ ];
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('getTypes')
+ ->atLeast()->once()
+ ->andReturn($typeArray);
+
+ $di = container();
+ $api->setDi($di);
+ $api->setService($serviceMock);
+
+ expect(fn (): int => $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',
+ ];
+
+ $newProductId = 1;
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('getTypes')
+ ->atLeast()->once()
+ ->andReturn($typeArray);
+
+ $serviceMock->shouldReceive('createProduct')
+ ->atLeast()->once()
+ ->andReturn($newProductId);
+
+ $di = container();
+ $api->setDi($di);
+ $api->setService($serviceMock);
+
+ $result = $api->prepare($data);
+ expect($result)->toBeInt();
+ expect($result)->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);
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('updateProduct')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $api->setDi($di);
+ $api->setService($serviceMock);
+
+ $result = $api->update($data);
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+});
+
+test('throws exception when updating priority without priority param', function (): void {
+ $api = new Admin();
+ $data = [];
+
+ expect(fn () => $api->update_priority($data))
+ ->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);
+
+ $api->setService($serviceMock);
+
+ $result = $api->update_priority($data);
+ expect($result)->toBeBool();
+ expect($result)->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);
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('updateConfig')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $api->setDi($di);
+ $api->setService($serviceMock);
+
+ $result = $api->update_config($data);
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+});
+
+test('gets addon pairs', function (): void {
+ $api = new Admin();
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('getAddons')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $api->setService($serviceMock);
+ $result = $api->addon_get_pairs([]);
+ expect($result)->toBeArray();
+});
+
+test('creates an addon', function (): void {
+ $api = new Admin();
+ $data = ['title' => 'Title4test'];
+ $newAddonId = 1;
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('createAddon')
+ ->atLeast()->once()
+ ->andReturn($newAddonId);
+
+ $di = container();
+ $api->setDi($di);
+ $api->setService($serviceMock);
+
+ $result = $api->addon_create($data);
+ expect($result)->toBeInt();
+ expect($result)->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);
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('toApiArray')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $api->setDi($di);
+ $api->setService($serviceMock);
+
+ $result = $api->addon_get($data);
+ expect($result)->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([]);
+
+ $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);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $apiMock->setDi($di);
+
+ $result = $apiMock->addon_update($data);
+ expect($result)->toBeArray();
+});
+
+test('deletes an addon', function (): void {
+ $api = new Admin();
+ $apiMock = Mockery::mock(Admin::class)->makePartial();
+ $apiMock->shouldReceive('delete')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $result = $apiMock->addon_delete([]);
+ expect($result)->toBeBool();
+ expect($result)->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);
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('deleteProduct')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $api->setService($serviceMock);
+ $api->setDi($di);
+
+ $result = $api->delete($data);
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+});
+
+test('gets category pairs', function (): void {
+ $api = new Admin();
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('getProductCategoryPairs')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $api->setService($serviceMock);
+ $result = $api->category_get_pairs([]);
+ expect($result)->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);
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('updateCategory')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $api->setService($serviceMock);
+ $api->setDi($di);
+
+ $result = $api->category_update($data);
+ expect($result)->toBeBool();
+ expect($result)->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);
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('toProductCategoryApiArray')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $api->setService($serviceMock);
+ $api->setDi($di);
+
+ $result = $api->category_get($data);
+ expect($result)->toBeArray();
+});
+
+test('creates a category', function (): void {
+ $api = new Admin();
+ $data = ['title' => 'test Title'];
+ $newCategoryId = 1;
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('createCategory')
+ ->atLeast()->once()
+ ->andReturn($newCategoryId);
+
+ $di = container();
+ $api->setDi($di);
+ $api->setService($serviceMock);
+
+ $result = $api->category_create($data);
+ expect($result)->toBeInt();
+ expect($result)->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);
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('removeProductCategory')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $api->setService($serviceMock);
+ $api->setDi($di);
+
+ $result = $api->category_delete($data);
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+});
+
+test('gets promo list', function (): void {
+ $api = new Admin();
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('getPromoSearchQuery')
+ ->atLeast()->once()
+ ->andReturn(['sqlString', []]);
+
+ $pagerMock = Mockery::mock(FOSSBilling\Pagination::class);
+ $pagerMock->shouldReceive('getPaginatedResultSet')
+ ->atLeast()->once()
+ ->andReturn(['list' => []]);
+
+ $di = container();
+ $di['pager'] = $pagerMock;
+
+ $api->setService($serviceMock);
+ $api->setDi($di);
+ $result = $api->promo_get_list([]);
+ expect($result)->toBeArray();
+});
+
+test('creates a promo', function (): void {
+ $api = new Admin();
+ $data = [
+ 'code' => 'test',
+ 'type' => 'addon',
+ 'value' => '10',
+ 'products' => [],
+ 'periods' => [],
+ ];
+ $newPromoId = 1;
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('createPromo')
+ ->atLeast()->once()
+ ->andReturn($newPromoId);
+
+ $di = container();
+ $api->setDi($di);
+ $api->setService($serviceMock);
+
+ $result = $api->promo_create($data);
+ expect($result)->toBeInt();
+ expect($result)->toBe($newPromoId);
+});
+
+test('throws exception when getting promo without id', function (): void {
+ $api = new Admin();
+ $data = [];
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andThrow(new FOSSBilling\InformationException('Promo ID was not passed'));
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $api->setDi($di);
+
+ expect(fn () => $api->promo_get($data))
+ ->toThrow(FOSSBilling\Exception::class, 'Promo ID was not passed');
+});
+
+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;
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('toPromoApiArray')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $api->setService($serviceMock);
+ $api->setDi($di);
+
+ $result = $api->promo_get($data);
+ expect($result)->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);
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('updatePromo')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $api->setDi($di);
+ $api->setService($serviceMock);
+ $result = $api->promo_update($data);
+ expect($result)->toBeBool();
+ expect($result)->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);
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('deletePromo')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $api->setDi($di);
+ $api->setService($serviceMock);
+ $result = $api->promo_delete($data);
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+});
diff --git a/src/modules/Product/tests/Unit/Api/GuestTest.php b/src/modules/Product/tests/Unit/Api/GuestTest.php
new file mode 100644
index 000000000..453c87ef9
--- /dev/null
+++ b/src/modules/Product/tests/Unit/Api/GuestTest.php
@@ -0,0 +1,142 @@
+setDi($di);
+ $getDi = $api->getDi();
+ expect($getDi)->toBe($di);
+});
+
+test('gets product with id', function (): void {
+ $api = new Guest();
+ $data = ['id' => 1];
+
+ $model = new Model_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([]);
+
+ $di = container();
+ $api->setDi($di);
+ $api->setService($serviceMock);
+ $result = $api->get($data);
+ expect($result)->toBeArray();
+});
+
+test('gets product with slug', function (): void {
+ $api = new Guest();
+ $data = ['slug' => 'product/1'];
+
+ $model = new Model_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([]);
+
+ $di = container();
+ $api->setDi($di);
+ $api->setService($serviceMock);
+ $result = $api->get($data);
+ expect($result)->toBeArray();
+});
+
+test('throws exception when product not found', function (): void {
+ $api = new Guest();
+ $data = ['slug' => 'product/1'];
+
+ $serviceMock = Mockery::mock(Service::class);
+ /** @var Mockery\Expectation $expectation */
+ $expectation = $serviceMock->shouldReceive('findOneActiveBySlug');
+ $expectation->atLeast()->once();
+ $expectation->andReturn(null);
+
+ $di = container();
+ $api->setDi($di);
+ $api->setService($serviceMock);
+
+ expect(fn () => $api->get($data))
+ ->toThrow(FOSSBilling\Exception::class, 'Product not found');
+});
+
+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;
+
+ $api->setService($serviceMock);
+ $api->setDi($di);
+ $result = $api->category_get_list([]);
+ expect($result)->toBeArray();
+});
+
+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([]);
+
+ $api->setService($serviceMock);
+ $result = $api->category_get_pairs([]);
+ expect($result)->toBeArray();
+});
diff --git a/src/modules/Product/tests/Unit/ServiceTest.php b/src/modules/Product/tests/Unit/ServiceTest.php
new file mode 100644
index 000000000..9ce9a2d6e
--- /dev/null
+++ b/src/modules/Product/tests/Unit/ServiceTest.php
@@ -0,0 +1,1081 @@
+setDi($di);
+ $getDi = $service->getDi();
+ expect($getDi)->toBe($di);
+});
+
+test('gets product pairs', function (): void {
+ $service = new Service();
+ $data = [
+ 'type' => 'domain',
+ 'products_only' => true,
+ 'active_only' => true,
+ ];
+
+ $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);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $service->setDi($di);
+
+ $result = $service->getPairs($data);
+ expect($result)->toBeArray();
+ expect($result)->toBe($expectArray);
+});
+
+test('converts product 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();
+
+ $productPaymentArray = [
+ 'type' => 'free',
+ Model_ProductPayment::FREE => ['price' => 0, 'setup' => 0],
+ Model_ProductPayment::ONCE => ['price' => 1, 'setup' => 10],
+ Model_ProductPayment::RECURRENT => [],
+ ];
+ /** @var Mockery\Expectation $expectation3 */
+ $expectation3 = $serviceMock->shouldReceive('toProductPaymentApiArray');
+ $expectation3->atLeast()->once();
+ $expectation3->andReturn($productPaymentArray);
+
+ $model = new Model_Product();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $model->product_category_id = 1;
+ $model->product_payment_id = 2;
+ $model->config = '{}';
+
+ $modelProductCategory = new Model_ProductCategory();
+ $modelProductCategory->loadBean(new Tests\Helpers\DummyBean());
+ $modelProductCategory->type = 'free';
+
+ $modelProductPayment = new Model_ProductPayment();
+
+ $dbMock = Mockery::mock('\Box_Database');
+ /** @var Mockery\Expectation $expectation4 */
+ $expectation4 = $dbMock->shouldReceive('load');
+ $expectation4->atLeast()->once();
+ $expectation4->andReturnUsing(fn($type) => match ($type) {
+ 'ProductPayment' => $modelProductPayment,
+ 'ProductCategory' => $modelProductCategory,
+ });
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $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('gets product types', function (): void {
+ $service = new Service();
+ $modArray = [
+ 'service' . 'test',
+ ];
+
+ $expectedArray = [
+ 'custom' => 'Custom',
+ 'license' => 'License',
+ 'downloadable' => 'Downloadable',
+ 'hosting' => 'Hosting',
+ 'domain' => 'Domain',
+ ];
+
+ $expectedArray['test'] = 'Test';
+
+ $extensionServiceMock = Mockery::mock(Box\Mod\Extension\Service::class);
+ /** @var Mockery\Expectation $expectation */
+ $expectation = $extensionServiceMock->shouldReceive('getInstalledMods');
+ $expectation->atLeast()->once();
+ $expectation->andReturn($modArray);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $extensionServiceMock);
+
+ $service->setDi($di);
+ $result = $service->getTypes();
+ expect($result)->toBeArray();
+ expect($result)->toBe($expectedArray);
+});
+
+test('gets main domain product', function (): void {
+ $service = new Service();
+ $model = new Model_Product();
+
+ $dbMock = Mockery::mock('\Box_Database');
+ /** @var Mockery\Expectation $expectation */
+ $expectation = $dbMock->shouldReceive('findOne');
+ $expectation->atLeast()->once();
+ $expectation->andReturn($model);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $service->setDi($di);
+
+ $result = $service->getMainDomainProduct();
+ expect($result)->toBeInstanceOf('\Model_Product');
+});
+
+test('gets payment types', function (): void {
+ $service = new Service();
+ $expected = [
+ 'free' => 'Free',
+ 'once' => 'One Time',
+ 'recurrent' => 'Recurrent',
+ ];
+
+ $result = $service->getPaymentTypes();
+ expect($result)->toBeArray();
+ expect($result)->toBe($expected);
+});
+
+test('creates a 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) => match ($type) {
+ 'ProductPayment' => $modelPayment,
+ 'Product' => $modelProduct,
+ });
+
+ /** @var Mockery\Expectation $expectation3 */
+ $expectation3 = $dbMock->shouldReceive('store');
+ $expectation3->atLeast()->once();
+ $expectation3->andReturn($newProductId);
+
+ $toolMock = Mockery::mock(FOSSBilling\Tools::class);
+ /** @var Mockery\Expectation $expectation4 */
+ $expectation4 = $toolMock->shouldReceive('slug');
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $systemServiceMock);
+ $di['db'] = $dbMock;
+ $di['tools'] = $toolMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $service->setDi($di);
+ $result = $service->createProduct('title', 'domain');
+ expect($result)->toBeInt();
+ expect($result)->toBe($newProductId);
+});
+
+test('throws exception when updating product with missing pricing type', function (): void {
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+
+ $typesArr = [
+ 'free' => 'Free',
+ 'once' => 'One Time',
+ 'recurrent' => 'Recurrent',
+ ];
+ /** @var Mockery\Expectation $expectation */
+ $expectation = $serviceMock->shouldReceive('getPaymentTypes');
+ $expectation->atLeast()->once();
+ $expectation->andReturn($typesArr);
+
+ $data = ['pricing' => []];
+
+ $modelProduct = new Model_Product();
+ $modelProduct->loadBean(new Tests\Helpers\DummyBean());
+
+ 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());
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+
+ $typesArr = [
+ 'free' => 'Free',
+ 'once' => 'One Time',
+ 'recurrent' => 'Recurrent',
+ ];
+ /** @var Mockery\Expectation $expectation1 */
+ $expectation1 = $serviceMock->shouldReceive('getPaymentTypes');
+ $expectation1->atLeast()->once();
+ $expectation1->andReturn($typesArr);
+
+ $data = [
+ 'pricing' => [
+ 'type' => Model_ProductPayment::RECURRENT,
+ Model_ProductPayment::RECURRENT => [
+ [
+ '1W' => [
+ 'setup' => '',
+ 'price' => '',
+ 'enabled' => true,
+ ],
+ ],
+ ],
+ ],
+ 'config' => [],
+ 'product_category_id' => 1,
+ 'form_id' => 10,
+ 'icon_url' => 'http://www.google.com',
+ 'status' => false,
+ 'hidden' => 0,
+ 'slug' => 'product/0',
+ 'setup' => 'test',
+ 'upgrades' => [],
+ 'addons' => [],
+ 'title' => 'new Title',
+ 'stock_control' => false,
+ 'allow_quantity_select' => false,
+ 'quantity_in_stock' => 0,
+ 'description' => 'Product description',
+ 'plugin' => 'plug in',
+ ];
+
+ $modelProductPayment = new Model_ProductPayment();
+ $modelProductPayment->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ /** @var Mockery\Expectation $expectation2 */
+ $expectation2 = $dbMock->shouldReceive('getExistingModelById');
+ $expectation2->atLeast()->once();
+ $expectation2->andReturn($modelProductPayment);
+
+ /** @var Mockery\Expectation $expectation3 */
+ $expectation3 = $dbMock->shouldReceive('store');
+ $expectation3->atLeast()->once();
+ $expectation3->andReturn(1);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $serviceMock->setDi($di);
+
+ $result = $serviceMock->updateProduct($modelProduct, $data);
+ expect($result)->toBeTrue();
+});
+
+test('updates priority', function (): void {
+ $service = new Service();
+ $data = [
+ 'priority' => [
+ 1 => 10,
+ 5 => 1,
+ ],
+ ];
+
+ $modelProduct = new Model_Product();
+ $modelProduct->loadBean(new Tests\Helpers\DummyBean());
+
+ $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');
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $service->setDi($di);
+
+ $result = $service->updatePriority($data);
+ expect($result)->toBeTrue();
+});
+
+test('updates config', function (): void {
+ $service = new Service();
+ $modelProduct = new Model_Product();
+ $modelProduct->loadBean(new Tests\Helpers\DummyBean());
+ $modelProduct->config = '{"settings":5,"max":"10"}';
+
+ $data = [
+ 'config' => [
+ 'settings' => 3,
+ 'max' => '',
+ ],
+ 'new_config_name' => 'newParam',
+ '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();
+
+ $service->setDi($di);
+
+ $result = $service->updateConfig($modelProduct, $data);
+ expect($result)->toBeTrue();
+});
+
+test('gets addons', function (): void {
+ $service = new Service();
+ $addonsRows = [
+ [
+ 'id' => 1,
+ 'title' => 'testTitle',
+ ],
+ ];
+
+ $expected = [
+ 1 => 'testTitle',
+ ];
+
+ $dbMock = Mockery::mock('\Box_Database');
+ /** @var Mockery\Expectation $expectation */
+ $expectation = $dbMock->shouldReceive('getAll');
+ $expectation->atLeast()->once();
+ $expectation->andReturn($addonsRows);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $service->setDi($di);
+
+ $result = $service->getAddons();
+ expect($result)->toBeArray();
+ expect($result)->toBe($expected);
+});
+
+test('creates an 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) => match ($type) {
+ 'ProductPayment' => $modelPayment,
+ 'Product' => $modelProduct,
+ });
+
+ $toolMock = Mockery::mock(FOSSBilling\Tools::class);
+ /** @var Mockery\Expectation $expectation3 */
+ $expectation3 = $toolMock->shouldReceive('slug');
+ $expectation3->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $di['tools'] = $toolMock;
+
+ $service->setDi($di);
+
+ $result = $service->createAddon('title');
+ expect($result)->toBeInt();
+ expect($result)->toBe($newProductId);
+});
+
+test('throws exception when deleting product with active orders', function (): void {
+ $service = new Service();
+ $model = new Model_Product();
+
+ $orderServiceMock = Mockery::mock(Box\Mod\Order\Service::class);
+ /** @var Mockery\Expectation $expectation */
+ $expectation = $orderServiceMock->shouldReceive('productHasOrders');
+ $expectation->atLeast()->once();
+ $expectation->andReturn(true);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
+
+ $service->setDi($di);
+
+ expect(fn (): bool => $service->deleteProduct($model))
+ ->toThrow(FOSSBilling\Exception::class, 'Cannot remove product which has active orders.');
+});
+
+test('gets 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);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $service->setDi($di);
+ $result = $service->getProductCategoryPairs();
+ expect($result)->toBeArray();
+ expect($result)->toBe($expectArray);
+});
+
+test('updates a 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);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $service->setDi($di);
+
+ $result = $service->updateCategory($model, 'title', 'description', 'http://urltoimg.com/img.jpg');
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+});
+
+test('creates a 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();
+
+ $service->setDi($di);
+
+ $result = $service->createCategory('title');
+ expect($result)->toBeInt();
+ expect($result)->toBe($newCategoryId);
+});
+
+test('throws exception when removing category with products', 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);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $service->setDi($di);
+
+ expect(fn (): bool => $service->removeProductCategory($modelProductCategory))
+ ->toThrow(FOSSBilling\Exception::class, 'Cannot remove product category with products');
+});
+
+test('removes a 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();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $service->setDi($di);
+
+ $result = $service->removeProductCategory($modelProductCategory);
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+});
+
+test('gets promo search query', function (): void {
+ $service = new Service();
+ $data = [
+ 'search' => 'keyword',
+ 'id' => 1,
+ 'status' => 'active',
+ ];
+
+ $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();
+
+ $service->setDi($di);
+ $result = $service->createPromo('code', 'percentage', 50, [], [], [], []);
+ expect($result)->toBeInt();
+ expect($result)->toBe($newPromoId);
+});
+
+test('converts promo to api array', function (): void {
+ $service = new Service();
+ $model = new Model_Promo();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $model->products = '{}';
+ $model->periods = '{}';
+
+ $dbMock = Mockery::mock('\Box_Database');
+ /** @var Mockery\Expectation $expectation */
+ $expectation = $dbMock->shouldReceive('toArray');
+ $expectation->atLeast()->once();
+ $expectation->andReturn([]);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['tools'] = Mockery::mock(FOSSBilling\Tools::class);
+
+ $service->setDi($di);
+
+ $result = $service->toPromoApiArray($model);
+ expect($result)->toBeArray();
+});
+
+test('updates a promo', function (): void {
+ $service = new Service();
+ $model = new Model_Promo();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $data = [
+ 'code' => 'GO',
+ 'type' => 'absolute',
+ 'value' => 10,
+ 'active' => true,
+ 'freesetup' => true,
+ 'once_per_client' => true,
+ 'recurring' => false,
+ 'maxuses' => '1',
+ 'used' => '0',
+ 'start_at' => '2012-01-01',
+ 'end_at' => '2012-01-02',
+ 'products' => 'domain',
+ 'periods' => [],
+ ];
+
+ $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();
+
+ $service->setDi($di);
+ $result = $service->updatePromo($model, $data);
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+});
+
+test('deletes a promo', function (): void {
+ $service = new Service();
+ $model = new Model_Promo();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ /** @var Mockery\Expectation $expectation1 */
+ $expectation1 = $dbMock->shouldReceive('exec');
+ $expectation1->atLeast()->once();
+
+ /** @var Mockery\Expectation $expectation2 */
+ $expectation2 = $dbMock->shouldReceive('trash');
+ $expectation2->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $service->setDi($di);
+ $result = $service->deletePromo($model);
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+});
+
+test('gets product search query', function (): void {
+ $service = new Service();
+ $data = [
+ 'search' => 'keyword',
+ 'type' => 'domain',
+ 'status' => 'active',
+ 'show_hidden' => true,
+ ];
+
+ $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([]);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $serviceMock->setDi($di);
+ $result = $serviceMock->toProductCategoryApiArray($model);
+ expect($result)->toBeArray();
+});
+
+test('converts product category to api array with minimum price', 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, $modelProduct, $modelProduct, $modelProduct];
+
+ /** @var Mockery\Expectation $expectation1 */
+ $expectation1 = $serviceMock->shouldReceive('getCategoryProducts');
+ $expectation1->atLeast()->once();
+ $expectation1->andReturn($categoryProductsArr);
+
+ $min = 1;
+
+ /** @var Mockery\Expectation $expectation2 */
+ $expectation2 = $serviceMock->shouldReceive('toApiArray');
+ $expectation2->atLeast()->once();
+ $expectation2->andReturnUsing(function () {
+ static $count = 0;
+ ++$count;
+
+ 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);
+ $result = $serviceMock->toProductCategoryApiArray($model);
+ expect($result)->toBeArray();
+ expect($result['price_starting_from'])->toBe($min);
+});
+
+test('finds one active product by id', function (): void {
+ $service = new Service();
+ $model = new Model_Product();
+
+ $dbMock = Mockery::mock('\Box_Database');
+ /** @var Mockery\Expectation $expectation */
+ $expectation = $dbMock->shouldReceive('findOne');
+ $expectation->atLeast()->once();
+ $expectation->andReturn($model);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $service->setDi($di);
+ $result = $service->findOneActiveById(1);
+ expect($result)->toBeInstanceOf('\Model_Product');
+});
+
+test('finds one active product by slug', function (): void {
+ $service = new Service();
+ $model = new Model_Product();
+
+ $dbMock = Mockery::mock('\Box_Database');
+ /** @var Mockery\Expectation $expectation */
+ $expectation = $dbMock->shouldReceive('findOne');
+ $expectation->atLeast()->once();
+ $expectation->andReturn($model);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $service->setDi($di);
+ $result = $service->findOneActiveBySlug('product/1');
+ expect($result)->toBeInstanceOf('\Model_Product');
+});
+
+test('gets product category search query', 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);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $service->setDi($di);
+ $result = $service->getStartingFromPrice($productModel);
+
+ expect($result)->toBeInt();
+ expect($result)->toBe(0);
+});
+
+test('returns null for starting price when payment not defined', function (): void {
+ $service = new Service();
+ $productModel = new Model_Product();
+ $productModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $result = $service->getStartingFromPrice($productModel);
+
+ expect($result)->toBeNull();
+});
+
+test('gets starting from price for domain type', function (): void {
+ $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();
+
+ $result = $serviceMock->getStartingFromPrice($productModel);
+ expect($result)->not()->toBeNull();
+});
+
+test('gets upgradable pairs', function (): void {
+ $service = new Service();
+ $productModel = new Model_Product();
+ $productModel->loadBean(new Tests\Helpers\DummyBean());
+ $productModel->upgrades = '{}';
+
+ $expected = [];
+
+ $result = $service->getUpgradablePairs($productModel);
+ expect($result)->toBeArray();
+ expect($result)->toBe($expected);
+});
+
+test('gets 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([]);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $service->setDi($di);
+
+ $result = $service->getProductTitlesByIds($ids);
+ expect($result)->toBeArray();
+});
+
+test('gets category products', function (): void {
+ $service = new Service();
+ $productCategoryModel = new Model_ProductCategory();
+ $productCategoryModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $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]);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $service->setDi($di);
+ $result = $service->getCategoryProducts($productCategoryModel);
+ expect($result)->toBeArray();
+});
+
+test('converts product payment to api array', function (): void {
+ $service = new Service();
+ $productPaymentModel = new Model_ProductPayment();
+ $productPaymentModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $result = $service->toProductPaymentApiArray($productPaymentModel);
+ expect($result)->toBeArray();
+});
+
+test('gets starting price', function (): void {
+ $service = new Service();
+ $productPaymentModel = new Model_ProductPayment();
+ $productPaymentModel->loadBean(new Tests\Helpers\DummyBean());
+ $productPaymentModel->type = '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;
+
+ $result = $service->getStartingPrice($productPaymentModel);
+ expect($result)->toBeInt();
+ expect($result)->toBe($minPrice);
+});
+
+test('checks if product can upgrade to another product', function (): void {
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+ /** @var Mockery\Expectation $expectation */
+ $expectation = $serviceMock->shouldReceive('getUpgradablePairs');
+ $expectation->atLeast()->once();
+ $expectation->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;
+
+ $result = $serviceMock->canUpgradeTo($productModel, $newProductModel);
+ expect($result)->toBeTrue();
+});
+
+test('returns false when upgrade is impossible', function (): void {
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+ /** @var Mockery\Expectation $expectation */
+ $expectation = $serviceMock->shouldReceive('getUpgradablePairs');
+ $expectation->atLeast()->once();
+ $expectation->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;
+
+ $result = $serviceMock->canUpgradeTo($productModel, $newProductModel);
+ expect($result)->toBeFalse();
+});
+
+test('returns false when trying to upgrade to same product', 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;
+
+ $result = $service->canUpgradeTo($productModel, $newProductModel);
+ expect($result)->toBeFalse();
+});
diff --git a/src/modules/Profile/Api/Admin.php b/src/modules/Profile/Api/Admin.php
index 1b40af277..57ff2185d 100644
--- a/src/modules/Profile/Api/Admin.php
+++ b/src/modules/Profile/Api/Admin.php
@@ -53,8 +53,8 @@ class Admin extends \Api_Abstract
*/
public function logout(): bool
{
- $this->di['session']->destroy('admin');
- $this->di['logger']->info('Admin logged out');
+ $this->getDi()['session']->destroy('admin');
+ $this->getDi()['logger']->info('Admin logged out');
return true;
}
@@ -73,7 +73,7 @@ class Admin extends \Api_Abstract
public function update($data)
{
if (!is_null($data['email'] ?? null)) {
- $data['email'] = $this->di['tools']->validateAndSanitizeEmail($data['email']);
+ $data['email'] = $this->getDi()['tools']->validateAndSanitizeEmail($data['email']);
}
return $this->getService()->updateAdmin($this->getIdentity(), $data);
@@ -104,7 +104,7 @@ class Admin extends \Api_Abstract
public function change_password($data)
{
$newPassword = $data['new_password'] ?? null;
- $this->di['validator']->isPasswordStrong($newPassword);
+ $this->getDi()['validator']->isPasswordStrong($newPassword);
if ($newPassword != $data['confirm_password']) {
throw new \FOSSBilling\InformationException('Passwords do not match');
@@ -112,10 +112,10 @@ class Admin extends \Api_Abstract
$staff = $this->getIdentity();
- $this->di['rate_limiter']->consumeOrThrow('profile_password_change_ip', (string) $this->getIp());
- $this->di['rate_limiter']->consumeOrThrow('profile_password_change_account', 'admin:' . $staff->id);
+ $this->getDi()['rate_limiter']->consumeOrThrow('profile_password_change_ip', (string) $this->getIp());
+ $this->getDi()['rate_limiter']->consumeOrThrow('profile_password_change_account', 'admin:' . $staff->id);
- if (!$this->di['password']->verify($data['current_password'], $staff->pass)) {
+ if (!$this->getDi()['password']->verify($data['current_password'], $staff->pass)) {
throw new \FOSSBilling\InformationException('Current password incorrect');
}
@@ -140,9 +140,9 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Client ID was not passed'])]
public function api_key_reset($data): string
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('client', 'manage_api_keys');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('client', 'manage_api_keys');
- $client = $this->di['db']->getExistingModelById('Client', $data['id']);
+ $client = $this->getDi()['db']->getExistingModelById('Client', $data['id']);
return $this->getService()->resetApiKey($client);
}
diff --git a/src/modules/Profile/Api/Client.php b/src/modules/Profile/Api/Client.php
index ceb0476c6..5ef6ab182 100644
--- a/src/modules/Profile/Api/Client.php
+++ b/src/modules/Profile/Api/Client.php
@@ -25,7 +25,7 @@ class Client extends \Api_Abstract
*/
public function get()
{
- $clientService = $this->di['mod_service']('client');
+ $clientService = $this->getDi()['mod_service']('client');
return $clientService->toApiArray($this->getIdentity(), true, $this->getIdentity());
}
@@ -72,7 +72,7 @@ class Client extends \Api_Abstract
public function update($data)
{
if (!is_null($data['email'] ?? null)) {
- $data['email'] = $this->di['tools']->validateAndSanitizeEmail($data['email']);
+ $data['email'] = $this->getDi()['tools']->validateAndSanitizeEmail($data['email']);
}
return $this->getService()->updateClient($this->getIdentity(), $data);
@@ -110,15 +110,15 @@ class Client extends \Api_Abstract
])]
public function change_password($data)
{
- $this->di['validator']->isPasswordStrong($data['new_password']);
- $this->di['validator']->passwordsMatch($data, 'new_password', 'confirm_password');
+ $this->getDi()['validator']->isPasswordStrong($data['new_password']);
+ $this->getDi()['validator']->passwordsMatch($data, 'new_password', 'confirm_password');
$client = $this->getIdentity();
- $this->di['rate_limiter']->consumeOrThrow('profile_password_change_ip', (string) $this->getIp());
- $this->di['rate_limiter']->consumeOrThrow('profile_password_change_account', 'client:' . $client->id);
+ $this->getDi()['rate_limiter']->consumeOrThrow('profile_password_change_ip', (string) $this->getIp());
+ $this->getDi()['rate_limiter']->consumeOrThrow('profile_password_change_account', 'client:' . $client->id);
- if (!$this->di['password']->verify($data['current_password'], $client->pass)) {
+ if (!$this->getDi()['password']->verify($data['current_password'], $client->pass)) {
throw new \FOSSBilling\InformationException('Current password incorrect');
}
diff --git a/src/modules/Profile/tests/Unit/Api/AdminTest.php b/src/modules/Profile/tests/Unit/Api/AdminTest.php
new file mode 100644
index 000000000..45ffae313
--- /dev/null
+++ b/src/modules/Profile/tests/Unit/Api/AdminTest.php
@@ -0,0 +1,133 @@
+loadBean(new Tests\Helpers\DummyBean());
+ $model->id = 1;
+ $model->role = 'admin';
+ $model->admin_group_id = 1;
+ $model->email = 'admin@fossbilling.org';
+ $model->name = 'Admin';
+ $model->signature = 'Sincerely';
+ $model->status = 'active';
+ $model->created_at = '2014-01-01';
+ $model->updated_at = '2014-01-01';
+
+ $adminApi = new Admin();
+ $adminApi->setIdentity($model);
+ $adminApi->setService($service);
+ $result = $adminApi->get();
+ $expected = [
+ 'id' => $model->id,
+ 'role' => $model->role,
+ 'admin_group_id' => $model->admin_group_id,
+ 'email' => $model->email,
+ 'name' => $model->name,
+ 'signature' => $model->signature,
+ 'status' => $model->status,
+ 'api_token' => null,
+ 'created_at' => $model->created_at,
+ 'updated_at' => $model->updated_at,
+ ];
+ expect($result)->toBe($expected);
+});
+
+test('logs out admin', function (): void {
+ $sessionMock = Mockery::mock(FOSSBilling\Session::class);
+ $sessionMock->shouldReceive('destroy')
+ ->atLeast()->once();
+
+ $di = container();
+ $di['session'] = $sessionMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $adminApi = new Admin();
+ $adminApi->setDi($di);
+ $result = $adminApi->logout();
+ expect($result)->toBeTrue();
+});
+
+test('updates admin profile', function (): void {
+ $model = new Model_Admin();
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('updateAdmin')
+ ->once()
+ ->andReturn(true);
+
+ $adminApi = new Admin();
+ $adminApi->setIdentity($model);
+ $adminApi->setService($serviceMock);
+ $result = $adminApi->update(['name' => 'Root']);
+ expect($result)->toBeTrue();
+});
+
+test('generates api key', function (): void {
+ $model = new Model_Admin();
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('generateNewApiKey')
+ ->once()
+ ->andReturn(true);
+
+ $adminApi = new Admin();
+ $adminApi->setIdentity($model);
+ $adminApi->setService($serviceMock);
+ $result = $adminApi->generate_api_key([]);
+ expect($result)->toBeTrue();
+});
+
+test('throws exception when changing password without required params', function (): void {
+ $di = container();
+ $di['validator'] = new FOSSBilling\Validate();
+
+ $adminApi = new Admin();
+ $adminApi->setDi($di);
+
+ expect(fn () => $adminApi->change_password([]))
+ ->toThrow(FOSSBilling\Exception::class);
+});
+
+test('changes password', function (): void {
+ $di = container();
+ $di['validator'] = new FOSSBilling\Validate();
+ $di['password'] = new FOSSBilling\PasswordManager();
+
+ $model = new Model_Admin();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $model->pass = $di['password']->hashIt('oldpw');
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('changeAdminPassword')
+ ->once()
+ ->andReturn(true);
+ $serviceMock->shouldReceive('invalidateSessions')
+ ->once();
+
+ $adminApi = new Admin();
+ $adminApi->setDi($di);
+ $adminApi->setIdentity($model);
+ $adminApi->setService($serviceMock);
+ $result = $adminApi->change_password([
+ 'current_password' => 'oldpw',
+ 'new_password' => '84asasd221AS',
+ 'confirm_password' => '84asasd221AS',
+ ]);
+ expect($result)->toBeTrue();
+});
diff --git a/src/modules/Profile/tests/Unit/Api/ClientTest.php b/src/modules/Profile/tests/Unit/Api/ClientTest.php
new file mode 100644
index 000000000..80ac4c232
--- /dev/null
+++ b/src/modules/Profile/tests/Unit/Api/ClientTest.php
@@ -0,0 +1,144 @@
+shouldReceive('toApiArray')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $clientService);
+ $api->setDi($di);
+ $api->setIdentity(new Model_Client());
+
+ $result = $api->get();
+ expect($result)->toBeArray();
+});
+
+test('updates client profile', function (): void {
+ $api = new Client();
+ $service = Mockery::mock(Service::class);
+ $service->shouldReceive('updateClient')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $api->setService($service);
+ $api->setIdentity(new Model_Client());
+
+ $result = $api->update([]);
+ expect($result)->toBeTrue();
+});
+
+test('gets api key', function (): void {
+ $api = new Client();
+ $client = new Model_Client();
+ $client->loadBean(new Tests\Helpers\DummyBean());
+ $client->api_token = '16047a3e69f5245756d73b419348f0c7';
+ $api->setIdentity($client);
+
+ $result = $api->api_key_get([]);
+ expect($result)->toBe($client->api_token);
+});
+
+test('resets api key', function (): void {
+ $api = new Client();
+ $apiKey = '16047a3e69f5245756d73b419348f0c7';
+ $service = Mockery::mock(Service::class);
+ $service->shouldReceive('resetApiKey')
+ ->atLeast()->once()
+ ->andReturn($apiKey);
+
+ $api->setService($service);
+ $api->setIdentity(new Model_Client());
+
+ $result = $api->api_key_reset([]);
+ expect($result)->toBe($apiKey);
+});
+
+test('changes client password', function (): void {
+ $api = new Client();
+ $service = Mockery::mock(Service::class);
+ $service->shouldReceive('changeClientPassword')
+ ->atLeast()->once()
+ ->andReturn(true);
+ $service->shouldReceive('invalidateSessions')
+ ->atLeast()->once();
+
+ $validatorMock = Mockery::mock(FOSSBilling\Validate::class);
+ $validatorMock->shouldReceive('isPasswordStrong')
+ ->atLeast()->once()
+ ->andReturn(true);
+ $validatorMock->shouldReceive('passwordsMatch')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+ $di['validator'] = $validatorMock;
+ $di['password'] = new FOSSBilling\PasswordManager();
+
+ $model = new Model_Client();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $model->pass = $di['password']->hashIt('oldpw');
+
+ $api->setDi($di);
+ $api->setService($service);
+ $api->setIdentity($model);
+
+ $data = [
+ 'current_password' => 'oldpw',
+ 'new_password' => '16047a3e69f5245756d73b419348f0c7',
+ 'confirm_password' => '16047a3e69f5245756d73b419348f0c7',
+ ];
+ $result = $api->change_password($data);
+ expect($result)->toBeTrue();
+});
+
+test('throws exception when passwords do not match', function (): void {
+ $api = new Client();
+ $service = Mockery::mock(Service::class);
+ $service->shouldReceive('changeClientPassword')
+ ->never()
+ ->andReturn(true);
+
+ $di = container();
+
+ $api->setDi($di);
+ $api->setService($service);
+ $api->setIdentity(new Model_Client());
+
+ $data = [
+ 'current_password' => '1234',
+ 'new_password' => '16047a3e69f5245756d73b419348f0c7',
+ 'confirm_password' => '7c0f843914b37d6575425f96e3a74061',
+ ];
+
+ expect(fn () => $api->change_password($data))
+ ->toThrow(Exception::class);
+});
+
+test('logs out client', function (): void {
+ $api = new Client();
+ $service = Mockery::mock(Service::class);
+ $service->shouldReceive('logoutClient')
+ ->atLeast()->once()
+ ->andReturn(true);
+ $api->setService($service);
+
+ $result = $api->logout();
+ expect($result)->toBeTrue();
+});
diff --git a/src/modules/Profile/tests/Unit/ServiceTest.php b/src/modules/Profile/tests/Unit/ServiceTest.php
new file mode 100644
index 000000000..9b22e44b6
--- /dev/null
+++ b/src/modules/Profile/tests/Unit/ServiceTest.php
@@ -0,0 +1,356 @@
+setDi($di);
+ $getDi = $service->getDi();
+ expect($getDi)->toBe($di);
+});
+
+test('gets admin identity array', function (): void {
+ $model = new Model_Admin();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $service = new Service();
+ $result = $service->getAdminIdentityArray($model);
+ expect($result)->toBeArray();
+});
+
+test('updates admin', function (): void {
+ $emMock = Mockery::mock('\Box_EventManager');
+ $emMock->shouldReceive('fire')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $di['events_manager'] = $emMock;
+ $di['db'] = $dbMock;
+
+ $model = new Model_Admin();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $data = [
+ 'signature' => 'new signature',
+ 'email' => 'example@gmail.com',
+ 'name' => 'Admin',
+ ];
+
+ $service = new Service();
+ $service->setDi($di);
+ $result = $service->updateAdmin($model, $data);
+ expect($result)->toBeTrue();
+});
+
+test('generates new api key', function (): void {
+ $emMock = Mockery::mock('\Box_EventManager');
+ $emMock->shouldReceive('fire')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $di['events_manager'] = $emMock;
+ $di['db'] = $dbMock;
+ $di['tools'] = new FOSSBilling\Tools();
+
+ $model = new Model_Admin();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $service = new Service();
+ $service->setDi($di);
+
+ $result = $service->generateNewApiKey($model);
+ expect($result)->toBeTrue();
+});
+
+test('changes admin password', function (): void {
+ $password = 'new_pass';
+ $emMock = Mockery::mock('\Box_EventManager');
+ $emMock->shouldReceive('fire')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $passwordMock = Mockery::mock(FOSSBilling\PasswordManager::class);
+ $passwordMock->shouldReceive('hashIt')
+ ->with($password);
+
+ $di = container();
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $di['events_manager'] = $emMock;
+ $di['db'] = $dbMock;
+ $di['password'] = $passwordMock;
+
+ $model = new Model_Admin();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $service = new Service();
+ $service->setDi($di);
+
+ $result = $service->changeAdminPassword($model, $password);
+ expect($result)->toBeTrue();
+});
+
+test('updates client', function (): void {
+ $emMock = Mockery::mock('\Box_EventManager');
+ $emMock->shouldReceive('fire')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $modMock = Mockery::mock(FOSSBilling\Module::class);
+ $modMock->shouldReceive('getConfig')
+ ->atLeast()->once()
+ ->andReturn([
+ 'disable_change_email' => 0,
+ ]);
+
+ $toolsMock = Mockery::mock(FOSSBilling\Tools::class);
+ $toolsMock->shouldReceive('validateAndSanitizeEmail');
+
+ $clientServiceMock = Mockery::mock(Box\Mod\Client\Service::class);
+ $clientServiceMock->shouldReceive('emailAlreadyRegistered')
+ ->andReturn(false);
+
+ $di = container();
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $di['events_manager'] = $emMock;
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(fn ($name): Mockery\MockInterface => $clientServiceMock);
+ $di['mod'] = $di->protect(fn (): Mockery\MockInterface => $modMock);
+ $di['tools'] = $toolsMock;
+
+ $model = new Model_Client();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $data = [
+ 'email' => 'email@example.com',
+ 'first_name' => 'string',
+ 'last_name' => 'string',
+ 'gender' => 'other',
+ 'birthday' => '1981-01-01',
+ 'company' => 'string',
+ 'company_vat' => 'string',
+ 'company_number' => 'string',
+ 'type' => 'string',
+ 'address_1' => 'string',
+ 'address_2' => 'string',
+ 'phone_cc' => random_int(10, 300),
+ 'phone' => random_int(10000, 90000),
+ 'country' => 'US',
+ 'postcode' => 'string',
+ 'city' => 'string',
+ 'state' => 'string',
+ 'document_type' => 'passport',
+ 'document_nr' => random_int(100000, 900000),
+ 'lang' => 'en_US',
+ 'notes' => 'string',
+ 'custom_1' => 'string',
+ 'custom_2' => 'string',
+ 'custom_3' => 'string',
+ 'custom_4' => 'string',
+ 'custom_5' => 'string',
+ 'custom_6' => 'string',
+ 'custom_7' => 'string',
+ 'custom_8' => 'string',
+ 'custom_9' => 'string',
+ 'custom_10' => 'string',
+ ];
+
+ $service = new Service();
+ $service->setDi($di);
+ $result = $service->updateClient($model, $data);
+ expect($result)->toBeTrue();
+});
+
+test('throws exception when email change is not allowed', function (): void {
+ $emMock = Mockery::mock('\Box_EventManager');
+ $emMock->shouldReceive('fire')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->never()
+ ->andReturn(true);
+
+ $modMock = Mockery::mock(FOSSBilling\Module::class);
+ $modMock->shouldReceive('getConfig')
+ ->atLeast()->once()
+ ->andReturn([
+ 'disable_change_email' => 1,
+ ]);
+
+ $clientServiceMock = Mockery::mock(Box\Mod\Client\Service::class);
+ $clientServiceMock->shouldReceive('emailAlreadyRegistered')
+ ->never()
+ ->andReturn(false);
+
+ $di = container();
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $di['events_manager'] = $emMock;
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(fn ($name): Mockery\MockInterface => $clientServiceMock);
+ $di['mod'] = $di->protect(fn (): Mockery\MockInterface => $modMock);
+
+ $model = new Model_Client();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $data = ['email' => 'email@example.com'];
+
+ $service = new Service();
+ $service->setDi($di);
+
+ expect(fn (): bool => $service->updateClient($model, $data))
+ ->toThrow(FOSSBilling\Exception::class);
+});
+
+test('throws exception when email already registered', function (): void {
+ $emMock = Mockery::mock('\Box_EventManager');
+ $emMock->shouldReceive('fire')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->never()
+ ->andReturn(true);
+
+ $modMock = Mockery::mock(FOSSBilling\Module::class);
+ $modMock->shouldReceive('getConfig')
+ ->atLeast()->once()
+ ->andReturn([
+ 'disable_change_email' => 0,
+ ]);
+
+ $toolsMock = Mockery::mock(FOSSBilling\Tools::class);
+ $toolsMock->shouldReceive('validateAndSanitizeEmail');
+
+ $clientServiceMock = Mockery::mock(Box\Mod\Client\Service::class);
+ $clientServiceMock->shouldReceive('emailAlreadyRegistered')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $di['events_manager'] = $emMock;
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(fn ($name): Mockery\MockInterface => $clientServiceMock);
+ $di['mod'] = $di->protect(fn (): Mockery\MockInterface => $modMock);
+ $di['tools'] = $toolsMock;
+
+ $model = new Model_Client();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $data = ['email' => 'email@example.com'];
+
+ $service = new Service();
+ $service->setDi($di);
+
+ expect(fn (): bool => $service->updateClient($model, $data))
+ ->toThrow(FOSSBilling\Exception::class);
+});
+
+test('resets api key', function (): void {
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $di['db'] = $dbMock;
+ $di['tools'] = new FOSSBilling\Tools();
+
+ $model = new Model_Client();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $service = new Service();
+ $service->setDi($di);
+ $result = $service->resetApiKey($model);
+ expect($result)->toBeString();
+ expect(strlen((string) $result))->toBe(32);
+});
+
+test('changes client password', function (): void {
+ $emMock = Mockery::mock('\Box_EventManager');
+ $emMock->shouldReceive('fire')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $password = 'new password';
+
+ $passwordMock = Mockery::mock(FOSSBilling\PasswordManager::class);
+ $passwordMock->shouldReceive('hashIt')
+ ->with($password);
+
+ $di = container();
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $di['events_manager'] = $emMock;
+ $di['db'] = $dbMock;
+ $di['password'] = $passwordMock;
+
+ $model = new Model_Client();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $service = new Service();
+ $service->setDi($di);
+ $result = $service->changeClientPassword($model, $password);
+ expect($result)->toBeTrue();
+});
+
+test('logs out client', function (): void {
+ $sessionMock = Mockery::mock(FOSSBilling\Session::class);
+ $sessionMock->shouldReceive('destroy')
+ ->atLeast()->once();
+
+ $di = container();
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $di['session'] = $sessionMock;
+
+ $model = new Model_Client();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $service = new Service();
+ $service->setDi($di);
+ $result = $service->logoutClient();
+ expect($result)->toBeTrue();
+});
diff --git a/src/modules/Redirect/Api/Admin.php b/src/modules/Redirect/Api/Admin.php
index 22309b8da..9d4947696 100644
--- a/src/modules/Redirect/Api/Admin.php
+++ b/src/modules/Redirect/Api/Admin.php
@@ -26,7 +26,7 @@ class Admin extends \Api_Abstract
*/
public function get_list()
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('redirect', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('redirect', 'view');
return $this->getService()->getRedirects();
}
@@ -37,7 +37,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Redirect ID was not passed'])]
public function get($data): array
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('redirect', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('redirect', 'view');
return $this->getService()->toApiArray($this->getService()->get((int) $data['id']));
}
@@ -50,14 +50,14 @@ class Admin extends \Api_Abstract
#[RequiredParams(['path' => 'Redirect path was not passed', 'target' => 'Redirect target was not passed'])]
public function create($data): int
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('redirect', 'create_and_edit');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('redirect', 'create_and_edit');
$id = $this->getService()->create(
(string) $data['path'],
(string) $data['target']
);
- $this->di['logger']->info('Created new redirect #%s', $id);
+ $this->getDi()['logger']->info('Created new redirect #%s', $id);
return $id;
}
@@ -73,11 +73,11 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Redirect ID was not passed'])]
public function update($data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('redirect', 'create_and_edit');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('redirect', 'create_and_edit');
$this->getService()->update($this->getService()->get((int) $data['id']), $data);
- $this->di['logger']->info('Updated redirect #%s', $data['id']);
+ $this->getDi()['logger']->info('Updated redirect #%s', $data['id']);
return true;
}
@@ -90,11 +90,11 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Redirect ID was not passed'])]
public function delete($data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('redirect', 'delete');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('redirect', 'delete');
$this->getService()->delete($this->getService()->get((int) $data['id']));
- $this->di['logger']->info('Removed redirect #%s', $data['id']);
+ $this->getDi()['logger']->info('Removed redirect #%s', $data['id']);
return true;
}
diff --git a/src/modules/Redirect/tests/Unit/Api/AdminTest.php b/src/modules/Redirect/tests/Unit/Api/AdminTest.php
new file mode 100644
index 000000000..cb3c68e69
--- /dev/null
+++ b/src/modules/Redirect/tests/Unit/Api/AdminTest.php
@@ -0,0 +1,69 @@
+setExtension('mod_redirect')
+ ->setMetaKey('old-page')
+ ->setMetaValue('new-page');
+
+ $service = Mockery::mock(Box\Mod\Redirect\Service::class);
+ $service->shouldReceive('get')->with(3)->once()->andReturn($redirect);
+ $service->shouldReceive('toApiArray')->with($redirect)->once()->andReturn(['id' => 3, 'path' => 'old-page', 'target' => 'new-page']);
+
+ $api = new Box\Mod\Redirect\Api\Admin();
+ $api->setService($service);
+
+ expect($api->get(['id' => 3]))->toBe(['id' => 3, 'path' => 'old-page', 'target' => 'new-page']);
+});
+
+test('create delegates to service', function (): void {
+ $service = Mockery::mock(Box\Mod\Redirect\Service::class);
+ $service->shouldReceive('create')->with('/old-page/', '/new-page/')->once()->andReturn(7);
+
+ $staffService = Mockery::mock(Box\Mod\Staff\Service::class);
+ $staffService->shouldReceive('checkPermissionsAndThrowException')->with('redirect', 'create_and_edit')->once();
+
+ $di = new Pimple\Container();
+ $di['logger'] = new Box_Log();
+ $di['mod_service'] = $di->protect(fn (string $name): object => match (strtolower($name)) {
+ 'staff' => $staffService,
+ default => throw new RuntimeException("Unexpected mod service: $name"),
+ });
+
+ $api = new Box\Mod\Redirect\Api\Admin();
+ $api->setDi($di);
+ $api->setService($service);
+
+ expect($api->create(['path' => '/old-page/', 'target' => '/new-page/']))->toBe(7);
+});
+
+test('delete delegates to service entity', function (): void {
+ $redirect = (new ExtensionMeta())
+ ->setExtension('mod_redirect')
+ ->setMetaKey('old-page')
+ ->setMetaValue('new-page');
+
+ $service = Mockery::mock(Box\Mod\Redirect\Service::class);
+ $service->shouldReceive('get')->with(4)->once()->andReturn($redirect);
+ $service->shouldReceive('delete')->with($redirect)->once()->andReturn(true);
+
+ $staffService = Mockery::mock(Box\Mod\Staff\Service::class);
+ $staffService->shouldReceive('checkPermissionsAndThrowException')->with('redirect', 'delete')->once();
+
+ $di = new Pimple\Container();
+ $di['logger'] = new Box_Log();
+ $di['mod_service'] = $di->protect(fn (string $name): object => match (strtolower($name)) {
+ 'staff' => $staffService,
+ default => throw new RuntimeException("Unexpected mod service: $name"),
+ });
+
+ $api = new Box\Mod\Redirect\Api\Admin();
+ $api->setDi($di);
+ $api->setService($service);
+
+ expect($api->delete(['id' => 4]))->toBeTrue();
+});
diff --git a/src/modules/Redirect/tests/Unit/ServiceTest.php b/src/modules/Redirect/tests/Unit/ServiceTest.php
new file mode 100644
index 000000000..f74af7a9a
--- /dev/null
+++ b/src/modules/Redirect/tests/Unit/ServiceTest.php
@@ -0,0 +1,62 @@
+ [
+ ['/new-page', '/new-page'],
+ ['new-page', 'new-page'],
+ ['http://example.com/page', 'http://example.com/page'],
+ ['https://example.com/page', 'https://example.com/page'],
+]);
+
+dataset('invalidTargets', fn() => [
+ [''],
+ [' '],
+ ['javascript:alert(1)'],
+ ['JaVaScRiPt:alert(1)'],
+ ['data:text/html,test
'],
+ ['ftp://example.com/file'],
+ ["/new-page\r\nLocation: https://evil.com"],
+ ["/new-page\nLocation: https://evil.com"],
+ ["/new-page\rLocation: https://evil.com"],
+]);
+
+dataset('validPaths', fn() => [
+ ['/old-page/', 'old-page'],
+ ['/some/nested/path/', 'some/nested/path'],
+]);
+
+dataset('invalidPaths', fn() => [
+ [''],
+ ['/'],
+ ['../config'],
+ ['foo/../../etc/passwd'],
+ ["old-page\r\nX-Header: evil"],
+]);
+
+test('validate target allows valid targets', function (string $input, string $expected): void {
+ $service = new Box\Mod\Redirect\Service();
+ expect($service->validateTarget($input))->toBe($expected);
+})->with('validTargets');
+
+test('validate target rejects invalid targets', function (string $input): void {
+ $service = new Box\Mod\Redirect\Service();
+ expect(fn () => $service->validateTarget($input))->toThrow(Exception::class);
+})->with('invalidTargets');
+
+test('validate target trims whitespace', function (): void {
+ $service = new Box\Mod\Redirect\Service();
+ expect($service->validateTarget(' /new-page '))->toBe('/new-page');
+});
+
+test('validate path strips slashes', function (string $input, string $expected): void {
+ $service = new Box\Mod\Redirect\Service();
+ expect($service->validatePath($input))->toBe($expected);
+})->with('validPaths');
+
+test('validate path rejects invalid paths', function (string $input): void {
+ $service = new Box\Mod\Redirect\Service();
+ expect(fn () => $service->validatePath($input))->toThrow(Exception::class);
+})->with('invalidPaths');
diff --git a/src/modules/Security/Api/Admin.php b/src/modules/Security/Api/Admin.php
index 82535c7df..af9412ccb 100644
--- a/src/modules/Security/Api/Admin.php
+++ b/src/modules/Security/Api/Admin.php
@@ -19,14 +19,14 @@ class Admin extends \Api_Abstract
#[RequiredParams(['ip' => 'You must specify an IP address to lookup.'])]
public function ip_lookup(array $data): array
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('security', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('security', 'view');
return $this->getService()->lookupIP($data['ip']);
}
public function list_checks(array $data): array
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('security', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('security', 'view');
$result = [];
$checkInterfaces = $this->getService()->getAllChecks();
@@ -44,14 +44,14 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'You must specify a check ID to run.'])]
public function run_check(array $data): array
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('security', 'run_checks');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('security', 'run_checks');
return $this->getService()->runCheck($data['id']);
}
public function run_checks(array $data): array
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('security', 'run_checks');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('security', 'run_checks');
return $this->getService()->runAllChecks();
}
diff --git a/src/modules/Seo/Api/Admin.php b/src/modules/Seo/Api/Admin.php
index 481d91b72..a81879148 100644
--- a/src/modules/Seo/Api/Admin.php
+++ b/src/modules/Seo/Api/Admin.php
@@ -24,7 +24,7 @@ class Admin extends \Api_Abstract
*/
public function info($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('seo', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('seo', 'view');
return $this->getService()->getInfo();
}
@@ -36,9 +36,9 @@ class Admin extends \Api_Abstract
*/
public function ping_all()
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('seo', 'manage');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('seo', 'manage');
- $extensionService = $this->di['mod_service']('extension');
+ $extensionService = $this->getDi()['mod_service']('extension');
$config = $extensionService->getConfig('mod_seo');
return $this->getService()->pingSitemap($config, true);
diff --git a/src/modules/Serviceapikey/Api/Admin.php b/src/modules/Serviceapikey/Api/Admin.php
index 67d97c70b..76b988466 100644
--- a/src/modules/Serviceapikey/Api/Admin.php
+++ b/src/modules/Serviceapikey/Api/Admin.php
@@ -23,7 +23,7 @@ class Admin extends \Api_Abstract
*/
public function update($data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('serviceapikey', 'manage');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('serviceapikey', 'manage');
return $this->getService()->updateApiKey($data);
}
@@ -37,7 +37,7 @@ class Admin extends \Api_Abstract
*/
public function reset($data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('serviceapikey', 'manage');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('serviceapikey', 'manage');
return $this->getService()->resetApiKey($data);
}
diff --git a/src/modules/Servicecustom/Api/Admin.php b/src/modules/Servicecustom/Api/Admin.php
index 6256c3728..3b37338d0 100644
--- a/src/modules/Servicecustom/Api/Admin.php
+++ b/src/modules/Servicecustom/Api/Admin.php
@@ -25,7 +25,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['order_id' => 'Order ID is required'])]
public function update($data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('servicecustom', 'manage');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('servicecustom', 'manage');
if (!isset($data['order_id'])) {
throw new \FOSSBilling\Exception('Order ID is required');
@@ -46,7 +46,7 @@ class Admin extends \Api_Abstract
*/
public function __call($name, $arguments)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('servicecustom', 'manage');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('servicecustom', 'manage');
if (!isset($arguments[0])) {
throw new \FOSSBilling\Exception('API call is missing arguments', null, 7103);
diff --git a/src/modules/Servicecustom/Api/Client.php b/src/modules/Servicecustom/Api/Client.php
index 7b760f8fb..790fdc2f6 100644
--- a/src/modules/Servicecustom/Api/Client.php
+++ b/src/modules/Servicecustom/Api/Client.php
@@ -28,6 +28,14 @@ class Client extends \Api_Abstract
#[RequiredParams(['order_id' => 'Order ID is required', 'method' => 'Method is required'])]
public function call($data)
{
+ if (!isset($data['order_id'])) {
+ throw new \FOSSBilling\Exception('Order ID is required');
+ }
+
+ if (!isset($data['method'])) {
+ throw new \FOSSBilling\Exception('Method is required');
+ }
+
$identity = $this->getIdentity();
$model = $this->getService()->getServiceCustomByOrderId($data['order_id'], $identity->id);
diff --git a/src/modules/Servicecustom/Service.php b/src/modules/Servicecustom/Service.php
index 00b79ed84..56e693f4d 100644
--- a/src/modules/Servicecustom/Service.php
+++ b/src/modules/Servicecustom/Service.php
@@ -111,7 +111,7 @@ class Service implements \FOSSBilling\InjectionAwareInterface
throw new \FOSSBilling\Exception('Could not activate order. Service was not created', null, 7456);
}
- /* @var \Model_ServiceCustom $model */
+ // @phpstan-ignore argument.type (Model is guaranteed to be Model_ServiceCustom by getOrderService)
$this->callOnAdapter($model, 'activate');
return true;
@@ -289,7 +289,7 @@ class Service implements \FOSSBilling\InjectionAwareInterface
$file = Path::join('Plugin', $plugin, "{$plugin}.php");
if (!Environment::isTesting() && !$this->filesystem->exists(Path::join(PATH_LIBRARY, $file))) {
$e = new \FOSSBilling\Exception('Plugin class file :file was not found', [':file' => $file], 3124);
-
+ // @phpstan-ignore if.alwaysFalse (DEBUG is a runtime constant that may be true during debugging)
if (DEBUG) {
error_log($e->getMessage());
}
diff --git a/src/modules/Servicecustom/tests/Unit/Api/AdminTest.php b/src/modules/Servicecustom/tests/Unit/Api/AdminTest.php
new file mode 100644
index 000000000..5239ea055
--- /dev/null
+++ b/src/modules/Servicecustom/tests/Unit/Api/AdminTest.php
@@ -0,0 +1,136 @@
+shouldReceive('updateConfig')
+ ->atLeast()->once();
+
+ $data = [
+ 'order_id' => 1,
+ 'config' => [
+ 'param1' => 'value1',
+ ],
+ ];
+
+ $api->setService($serviceMock);
+ $api->update($data);
+});
+
+test('throws exception when updating without order_id', function (): void {
+ $api = new Admin();
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('updateConfig')
+ ->never();
+
+ $data = [
+ 'config' => [
+ 'param1' => 'value1',
+ ],
+ ];
+
+ $api->setService($serviceMock);
+
+ expect(fn (): bool => $api->update($data))
+ ->toThrow(Exception::class);
+});
+
+test('returns true when updating without config', function (): void {
+ $api = new Admin();
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('updateConfig')
+ ->never();
+
+ $data = [
+ 'order_id' => 1,
+ ];
+
+ $api->setService($serviceMock);
+ $result = $api->update($data);
+
+ expect($result)->toBeTrue();
+});
+
+test('returns true when config is not an array', function (): void {
+ $api = new Admin();
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('updateConfig')
+ ->never();
+
+ $data = [
+ 'order_id' => 1,
+ 'config' => 'NotArray',
+ ];
+
+ $api->setService($serviceMock);
+ $result = $api->update($data);
+
+ expect($result)->toBeTrue();
+});
+
+test('calls magic method', function (): void {
+ $api = new Admin();
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('getServiceCustomByOrderId')
+ ->atLeast()->once()
+ ->andReturn(new Model_ServiceCustom());
+ $serviceMock->shouldReceive('customCall')
+ ->atLeast()->once()
+ ->andReturn(null);
+
+ $arguments = [
+ 0 => [
+ 'order_id' => 1,
+ ],
+ ];
+
+ $api->setService($serviceMock);
+ $api->__call('delete', $arguments);
+});
+
+test('throws exception when calling magic method without arguments', function (): void {
+ $api = new Admin();
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('getServiceCustomByOrderId')
+ ->never();
+ $serviceMock->shouldReceive('customCall')
+ ->never();
+
+ $arguments = [];
+
+ $api->setService($serviceMock);
+
+ expect(fn () => $api->__call('delete', $arguments))
+ ->toThrow(Exception::class);
+});
+
+test('throws exception when calling magic method without order_id', function (): void {
+ $api = new Admin();
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('getServiceCustomByOrderId')
+ ->never();
+ $serviceMock->shouldReceive('customCall')
+ ->never();
+
+ $arguments = [
+ 0 => [],
+ ];
+
+ $api->setService($serviceMock);
+
+ expect(fn () => $api->__call('delete', $arguments))
+ ->toThrow(Exception::class);
+});
diff --git a/src/modules/Servicecustom/tests/Unit/Api/ClientTest.php b/src/modules/Servicecustom/tests/Unit/Api/ClientTest.php
new file mode 100644
index 000000000..cb5c48cb1
--- /dev/null
+++ b/src/modules/Servicecustom/tests/Unit/Api/ClientTest.php
@@ -0,0 +1,69 @@
+ 1];
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('getServiceCustomByOrderId')
+ ->with(1, 1)
+ ->atLeast()->once()
+ ->andReturn(new Model_ServiceCustom());
+ $serviceMock->shouldReceive('customCall')
+ ->with(Mockery::type(Model_ServiceCustom::class), 'delete', Mockery::type('array'))
+ ->atLeast()->once()
+ ->andReturn(null);
+
+ $data = [
+ 'order_id' => 1,
+ 'method' => 'delete',
+ ];
+
+ $api->setService($serviceMock);
+ $api->setIdentity($identity);
+ $api->call($data);
+});
+
+test('throws exception when calling custom method without order_id', function (): void {
+ $api = new Client();
+ $identity = (object) ['id' => 1];
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('getServiceCustomByOrderId')
+ ->never();
+ $serviceMock->shouldReceive('customCall')
+ ->never();
+
+ $api->setService($serviceMock);
+ $api->setIdentity($identity);
+
+ expect(fn () => $api->call(['method' => 'delete']))
+ ->toThrow(Exception::class);
+});
+
+test('throws exception when calling custom method without method', function (): void {
+ $api = new Client();
+ $identity = (object) ['id' => 1];
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('getServiceCustomByOrderId')
+ ->never();
+ $serviceMock->shouldReceive('customCall')
+ ->never();
+
+ $api->setService($serviceMock);
+ $api->setIdentity($identity);
+
+ expect(fn () => $api->call(['order_id' => 1]))
+ ->toThrow(Exception::class);
+});
diff --git a/src/modules/Servicecustom/tests/Unit/ServiceTest.php b/src/modules/Servicecustom/tests/Unit/ServiceTest.php
new file mode 100644
index 000000000..958e2bf33
--- /dev/null
+++ b/src/modules/Servicecustom/tests/Unit/ServiceTest.php
@@ -0,0 +1,552 @@
+setDi($di);
+ $getDi = $service->getDi();
+ expect($getDi)->toBe($di);
+});
+
+test('validates custom form', function (): void {
+ $service = new Service();
+ $form = [
+ 'fields' => [
+ 0 => [
+ 'required' => 1,
+ 'readonly' => 1,
+ 'name' => 'field_name',
+ 'default_value' => 'FieldName',
+ 'label' => 'label',
+ ],
+ ],
+ ];
+
+ $formbuilderService = Mockery::mock(FormbuilderService::class);
+ $formbuilderService->shouldReceive('getForm')
+ ->atLeast()->once()
+ ->andReturn($form);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $formbuilderService);
+
+ $service->setDi($di);
+
+ $product = [
+ 'form_id' => 1,
+ ];
+ $data = [
+ 'label' => 'label',
+ 'field_name' => 'FieldName',
+ ];
+ $result = $service->validateCustomForm($data, $product);
+ expect($result)->toBeNull();
+});
+
+test('throws exception when validating custom form with missing field name', function (): void {
+ $service = new Service();
+ $form = [
+ 'fields' => [
+ 0 => [
+ 'required' => 1,
+ 'readonly' => 1,
+ 'name' => 'field_name',
+ 'default_value' => 'default',
+ 'label' => 'label',
+ ],
+ ],
+ ];
+
+ $formbuilderService = Mockery::mock(FormbuilderService::class);
+ $formbuilderService->shouldReceive('getForm')
+ ->atLeast()->once()
+ ->andReturn($form);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $formbuilderService);
+
+ $service->setDi($di);
+
+ $product = [
+ 'form_id' => 1,
+ ];
+ $data = [];
+
+ expect(fn () => $service->validateCustomForm($data, $product))
+ ->toThrow(Exception::class);
+});
+
+test('throws exception when validating custom form with readonly field change', function (): void {
+ $service = new Service();
+ $form = [
+ 'fields' => [
+ 0 => [
+ 'required' => 1,
+ 'readonly' => 1,
+ 'name' => 'field_name',
+ 'default_value' => 'default',
+ 'label' => 'label',
+ ],
+ ],
+ ];
+
+ $formbuilderService = Mockery::mock(FormbuilderService::class);
+ $formbuilderService->shouldReceive('getForm')
+ ->atLeast()->once()
+ ->andReturn($form);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $formbuilderService);
+
+ $service->setDi($di);
+
+ $product = [
+ 'form_id' => 1,
+ ];
+ $data = [
+ 'field_name' => 'field_name',
+ ];
+
+ expect(fn () => $service->validateCustomForm($data, $product))
+ ->toThrow(Exception::class);
+});
+
+test('creates action', function (): void {
+ $service = new Service();
+ $order = new Model_ClientOrder();
+ $order->loadBean(new Tests\Helpers\DummyBean());
+ $order->product_id = 1;
+ $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';
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn(1);
+ $dbMock->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($product);
+ $serviceCustomModel = new Model_ServiceCustom();
+ $serviceCustomModel->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock->shouldReceive('dispense')
+ ->atLeast()->once()
+ ->andReturn($serviceCustomModel);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $result = $service->action_create($order);
+ expect($result)->toBeInstanceOf(Model_ServiceCustom::class);
+});
+
+test('activates action', function (): void {
+ $service = new Service();
+ $order = new Model_ClientOrder();
+ $order->loadBean(new Tests\Helpers\DummyBean());
+ $order->client_id = 1;
+ $order->config = 'config';
+
+ $serviceCustomModel = new Model_ServiceCustom();
+ $serviceCustomModel->loadBean(new Tests\Helpers\DummyBean());
+ $serviceCustomModel->plugin = '';
+
+ $orderServiceMock = Mockery::mock(OrderService::class);
+ $orderServiceMock->shouldReceive('getOrderService')
+ ->atLeast()->once()
+ ->andReturn($serviceCustomModel);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
+ $service->setDi($di);
+
+ $result = $service->action_activate($order);
+ expect($result)->toBeTrue();
+});
+
+test('throws exception when activating without order service', 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);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
+ $service->setDi($di);
+
+ expect(fn (): bool => $service->action_activate($order))
+ ->toThrow(Exception::class);
+});
+
+test('renews action', function (): void {
+ $service = new Service();
+ $order = new Model_ClientOrder();
+ $order->loadBean(new Tests\Helpers\DummyBean());
+ $order->client_id = 1;
+ $order->config = 'config';
+
+ $serviceCustomModel = new Model_ServiceCustom();
+ $serviceCustomModel->loadBean(new Tests\Helpers\DummyBean());
+ $serviceCustomModel->plugin = '';
+
+ $orderServiceMock = Mockery::mock(OrderService::class);
+ $orderServiceMock->shouldReceive('getOrderService')
+ ->atLeast()->once()
+ ->andReturn($serviceCustomModel);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn(1);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
+ $service->setDi($di);
+
+ $result = $service->action_renew($order);
+ expect($result)->toBeTrue();
+});
+
+test('throws exception when renewing without active service', function (): void {
+ $service = new Service();
+ $order = new Model_ClientOrder();
+ $order->loadBean(new Tests\Helpers\DummyBean());
+ $order->id = 1;
+ $order->client_id = 1;
+ $order->config = 'config';
+
+ $orderServiceMock = Mockery::mock(OrderService::class);
+ $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_renew($order))
+ ->toThrow(Exception::class);
+});
+
+test('suspends action', function (): void {
+ $service = new Service();
+ $order = new Model_ClientOrder();
+ $order->loadBean(new Tests\Helpers\DummyBean());
+ $order->client_id = 1;
+ $order->config = 'config';
+
+ $serviceCustomModel = new Model_ServiceCustom();
+ $serviceCustomModel->loadBean(new Tests\Helpers\DummyBean());
+ $serviceCustomModel->plugin = '';
+
+ $orderServiceMock = Mockery::mock(OrderService::class);
+ $orderServiceMock->shouldReceive('getOrderService')
+ ->atLeast()->once()
+ ->andReturn($serviceCustomModel);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn(1);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
+ $service->setDi($di);
+
+ $result = $service->action_suspend($order);
+ expect($result)->toBeTrue();
+});
+
+test('unsuspends action', function (): void {
+ $service = new Service();
+ $order = new Model_ClientOrder();
+ $order->loadBean(new Tests\Helpers\DummyBean());
+ $order->client_id = 1;
+ $order->config = 'config';
+
+ $serviceCustomModel = new Model_ServiceCustom();
+ $serviceCustomModel->loadBean(new Tests\Helpers\DummyBean());
+ $serviceCustomModel->plugin = '';
+
+ $orderServiceMock = Mockery::mock(OrderService::class);
+ $orderServiceMock->shouldReceive('getOrderService')
+ ->atLeast()->once()
+ ->andReturn($serviceCustomModel);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn(1);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
+ $service->setDi($di);
+
+ $result = $service->action_unsuspend($order);
+ expect($result)->toBeTrue();
+});
+
+test('cancels action', function (): void {
+ $service = new Service();
+ $order = new Model_ClientOrder();
+ $order->loadBean(new Tests\Helpers\DummyBean());
+ $order->client_id = 1;
+ $order->config = 'config';
+
+ $serviceCustomModel = new Model_ServiceCustom();
+ $serviceCustomModel->loadBean(new Tests\Helpers\DummyBean());
+ $serviceCustomModel->plugin = '';
+
+ $orderServiceMock = Mockery::mock(OrderService::class);
+ $orderServiceMock->shouldReceive('getOrderService')
+ ->atLeast()->once()
+ ->andReturn($serviceCustomModel);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn(1);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
+ $service->setDi($di);
+
+ $result = $service->action_cancel($order);
+ expect($result)->toBeTrue();
+});
+
+test('uncancels action', function (): void {
+ $service = new Service();
+ $order = new Model_ClientOrder();
+ $order->loadBean(new Tests\Helpers\DummyBean());
+ $order->client_id = 1;
+ $order->config = 'config';
+
+ $serviceCustomModel = new Model_ServiceCustom();
+ $serviceCustomModel->loadBean(new Tests\Helpers\DummyBean());
+ $serviceCustomModel->plugin = '';
+
+ $orderServiceMock = Mockery::mock(OrderService::class);
+ $orderServiceMock->shouldReceive('getOrderService')
+ ->atLeast()->once()
+ ->andReturn($serviceCustomModel);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn(1);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
+ $service->setDi($di);
+
+ $result = $service->action_uncancel($order);
+ expect($result)->toBeTrue();
+});
+
+test('deletes action', function (): void {
+ $service = new Service();
+ $order = new Model_ClientOrder();
+ $order->loadBean(new Tests\Helpers\DummyBean());
+ $order->client_id = 1;
+ $order->config = 'config';
+
+ $serviceCustomModel = new Model_ServiceCustom();
+ $serviceCustomModel->loadBean(new Tests\Helpers\DummyBean());
+ $serviceCustomModel->plugin = '';
+
+ $orderServiceMock = Mockery::mock(OrderService::class);
+ $orderServiceMock->shouldReceive('getOrderService')
+ ->atLeast()->once()
+ ->andReturn($serviceCustomModel);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('trash')
+ ->atLeast()->once()
+ ->andReturn(null);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
+ $service->setDi($di);
+
+ $result = $service->action_delete($order);
+ expect($result)->toBeTrue();
+});
+
+test('gets config', function (): void {
+ $service = new Service();
+ $decoded = [
+ 'J' => 5,
+ 0 => 'N',
+ ];
+
+ $di = container();
+ $service->setDi($di);
+
+ $model = new Model_ServiceCustom();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $model->config = json_encode($decoded);
+
+ $result = $service->getConfig($model);
+ expect($result)->toBe($decoded);
+});
+
+test('converts to api array', function (): void {
+ $service = new Service();
+ $di = container();
+ $service->setDi($di);
+
+ $model = new Model_ServiceCustom();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $model->id = 1;
+ $model->client_id = 1;
+ $model->plugin = 'plugin';
+ $model->config = '{"config_param":"config_value"}';
+ $model->updated_at = date('Y-m-d H:i:s');
+ $model->created_at = date('Y-m-d H:i:s');
+
+ $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);
+});
+
+test('throws exception for forbidden custom call method', 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 {
+ $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(new Model_ServiceCustom());
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
+ $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 {
+ $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);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
+ $service->setDi($di);
+
+ expect(fn () => $service->getServiceCustomByOrderId(1))
+ ->toThrow(Exception::class);
+});
+
+test('updates config', function (): void {
+ $service = new Service();
+ $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);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn(1);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $serviceMock->setDi($di);
+
+ $config = ['param1' => 'value1'];
+ $result = $serviceMock->updateConfig(1, $config);
+ expect($result)->toBeNull();
+});
+
+test('throws exception when updating config with non-array', function (): void {
+ $service = new Service();
+ $model = new Model_ServiceCustom();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $model->id = 1;
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+ $serviceMock->shouldReceive('getServiceCustomByOrderId')
+ ->never();
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->never();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $serviceMock->setDi($di);
+
+ $config = '';
+
+ expect(fn () => $serviceMock->updateConfig(1, $config))
+ ->toThrow(Exception::class);
+});
diff --git a/src/modules/Servicedomain/Api/Admin.php b/src/modules/Servicedomain/Api/Admin.php
index ace2913a4..da6c96629 100644
--- a/src/modules/Servicedomain/Api/Admin.php
+++ b/src/modules/Servicedomain/Api/Admin.php
@@ -39,7 +39,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['order_id' => 'Order ID is missing'])]
public function update($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('servicedomain', 'manage_domains');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('servicedomain', 'manage_domains');
$s = $this->_getService($data);
@@ -56,7 +56,7 @@ class Admin extends \Api_Abstract
*/
public function update_nameservers($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('servicedomain', 'manage_domains');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('servicedomain', 'manage_domains');
$s = $this->_getService($data);
@@ -70,7 +70,7 @@ class Admin extends \Api_Abstract
*/
public function update_contacts($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('servicedomain', 'manage_domains');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('servicedomain', 'manage_domains');
$s = $this->_getService($data);
@@ -84,7 +84,7 @@ class Admin extends \Api_Abstract
*/
public function enable_privacy_protection($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('servicedomain', 'manage_domains');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('servicedomain', 'manage_domains');
$s = $this->_getService($data);
@@ -98,7 +98,7 @@ class Admin extends \Api_Abstract
*/
public function disable_privacy_protection($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('servicedomain', 'manage_domains');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('servicedomain', 'manage_domains');
$s = $this->_getService($data);
@@ -112,7 +112,7 @@ class Admin extends \Api_Abstract
*/
public function get_transfer_code($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('servicedomain', 'manage_domains');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('servicedomain', 'manage_domains');
$s = $this->_getService($data);
@@ -126,7 +126,7 @@ class Admin extends \Api_Abstract
*/
public function lock($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('servicedomain', 'manage_domains');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('servicedomain', 'manage_domains');
$s = $this->_getService($data);
@@ -140,7 +140,7 @@ class Admin extends \Api_Abstract
*/
public function unlock($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('servicedomain', 'manage_domains');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('servicedomain', 'manage_domains');
$s = $this->_getService($data);
@@ -154,12 +154,12 @@ class Admin extends \Api_Abstract
*/
public function tld_get_list($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('servicedomain', 'manage_tlds');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('servicedomain', 'manage_tlds');
[$sql, $params] = $this->getService()->tldGetSearchQuery($data);
- $pager = $this->di['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
+ $pager = $this->getDi()['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
foreach ($pager['list'] as $key => $tldArr) {
- $tld = $this->di['db']->getExistingModelById('Tld', $tldArr['id'], sprintf('Tld #%s not found', $tldArr['id']));
+ $tld = $this->getDi()['db']->getExistingModelById('Tld', $tldArr['id'], sprintf('Tld #%s not found', $tldArr['id']));
$pager['list'][$key] = $this->getService()->tldToApiArray($tld, $this->identity);
}
@@ -176,7 +176,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['tld' => 'TLD is missing'])]
public function tld_get($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('servicedomain', 'manage_tlds');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('servicedomain', 'manage_tlds');
$tld = $data['tld'];
if ($tld[0] != '.') {
@@ -201,7 +201,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'ID is missing'])]
public function tld_get_id($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('servicedomain', 'manage_tlds');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('servicedomain', 'manage_tlds');
$model = $this->getService()->tldFindOneById($data['id']);
if (!$model instanceof \Model_Tld) {
@@ -221,7 +221,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['tld' => 'TLD is missing'])]
public function tld_delete($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('servicedomain', 'manage_tlds');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('servicedomain', 'manage_tlds');
$model = $this->getService()->tldFindOneByTld($data['tld']);
@@ -229,7 +229,7 @@ class Admin extends \Api_Abstract
throw new \FOSSBilling\Exception('TLD not found');
}
// check if tld is used by any domain
- $service_domains = $this->di['db']->find('ServiceDomain', 'tld = :tld', [':tld' => $data['tld']]);
+ $service_domains = $this->getDi()['db']->find('ServiceDomain', 'tld = :tld', [':tld' => $data['tld']]);
$count = \FOSSBilling\Tools::safeCount($service_domains);
if ($count > 0) {
throw new \FOSSBilling\InformationException('TLD is used by :count: domains', [':count:' => $count], 707);
@@ -254,7 +254,7 @@ class Admin extends \Api_Abstract
])]
public function tld_create($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('servicedomain', 'manage_tlds');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('servicedomain', 'manage_tlds');
if ($this->getService()->tldAlreadyRegistered($data['tld'])) {
throw new \FOSSBilling\InformationException('TLD already registered');
@@ -278,7 +278,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['tld' => 'TLD is missing'])]
public function tld_update($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('servicedomain', 'manage_tlds');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('servicedomain', 'manage_tlds');
$model = $this->getService()->tldFindOneByTld($data['tld']);
if (!$model instanceof \Model_Tld) {
@@ -295,11 +295,11 @@ class Admin extends \Api_Abstract
*/
public function registrar_get_list($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('servicedomain', 'manage_registrars');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('servicedomain', 'manage_registrars');
[$sql, $params] = $this->getService()->registrarGetSearchQuery($data);
- $pager = $this->di['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
+ $pager = $this->getDi()['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
- $registrars = $this->di['db']->find('TldRegistrar', 'ORDER By name ASC');
+ $registrars = $this->getDi()['db']->find('TldRegistrar', 'ORDER By name ASC');
$registrarsArr = [];
foreach ($registrars as $registrar) {
@@ -318,7 +318,7 @@ class Admin extends \Api_Abstract
*/
public function registrar_get_pairs($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('servicedomain', 'manage_registrars');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('servicedomain', 'manage_registrars');
return $this->getService()->registrarGetPairs();
}
@@ -330,7 +330,7 @@ class Admin extends \Api_Abstract
*/
public function registrar_get_available($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('servicedomain', 'manage_registrars');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('servicedomain', 'manage_registrars');
return $this->getService()->registrarGetAvailable();
}
@@ -343,7 +343,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['code' => 'Registrar code is missing'])]
public function registrar_install($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('servicedomain', 'manage_registrars');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('servicedomain', 'manage_registrars');
$code = $data['code'];
if (!in_array($code, $this->getService()->registrarGetAvailable())) {
@@ -361,9 +361,9 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Registrar ID is missing'])]
public function registrar_delete($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('servicedomain', 'manage_registrars');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('servicedomain', 'manage_registrars');
- $model = $this->di['db']->getExistingModelById('TldRegistrar', $data['id'], 'Registrar not found');
+ $model = $this->getDi()['db']->getExistingModelById('TldRegistrar', $data['id'], 'Registrar not found');
return $this->getService()->registrarRm($model);
}
@@ -376,9 +376,9 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Registrar ID is missing'])]
public function registrar_copy($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('servicedomain', 'manage_registrars');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('servicedomain', 'manage_registrars');
- $model = $this->di['db']->getExistingModelById('TldRegistrar', $data['id'], 'Registrar not found');
+ $model = $this->getDi()['db']->getExistingModelById('TldRegistrar', $data['id'], 'Registrar not found');
return $this->getService()->registrarCopy($model);
}
@@ -391,9 +391,9 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Registrar ID is missing'])]
public function registrar_get($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('servicedomain', 'manage_registrars');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('servicedomain', 'manage_registrars');
- $registrar = $this->di['db']->getExistingModelById('TldRegistrar', $data['id'], 'Registrar not found');
+ $registrar = $this->getDi()['db']->getExistingModelById('TldRegistrar', $data['id'], 'Registrar not found');
return $this->getService()->registrarToApiArray($registrar);
}
@@ -406,7 +406,7 @@ class Admin extends \Api_Abstract
*/
public function batch_sync_expiration_dates($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('servicedomain', 'manage_domains');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('servicedomain', 'manage_domains');
return $this->getService()->batchSyncExpirationDates();
}
@@ -422,9 +422,9 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Registrar ID is missing'])]
public function registrar_update($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('servicedomain', 'manage_registrars');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('servicedomain', 'manage_registrars');
- $model = $this->di['db']->getExistingModelById('TldRegistrar', $data['id'], 'Registrar not found');
+ $model = $this->getDi()['db']->getExistingModelById('TldRegistrar', $data['id'], 'Registrar not found');
return $this->getService()->registrarUpdate($model, $data);
}
@@ -434,9 +434,9 @@ class Admin extends \Api_Abstract
{
$orderId = $data['order_id'];
- $order = $this->di['db']->getExistingModelById('ClientOrder', $orderId, 'Order not found');
+ $order = $this->getDi()['db']->getExistingModelById('ClientOrder', $orderId, 'Order not found');
- $orderService = $this->di['mod_service']('order');
+ $orderService = $this->getDi()['mod_service']('order');
$s = $orderService->getOrderService($order);
if (!$s instanceof \Model_ServiceDomain) {
diff --git a/src/modules/Servicedomain/Api/Client.php b/src/modules/Servicedomain/Api/Client.php
index f67529150..e2bcc4c26 100644
--- a/src/modules/Servicedomain/Api/Client.php
+++ b/src/modules/Servicedomain/Api/Client.php
@@ -29,11 +29,11 @@ class Client extends \Api_Abstract
{
$s = $this->_getService($data);
- $this->di['events_manager']->fire(['event' => 'onBeforeClientChangeNameservers', 'params' => $data]);
+ $this->getDi()['events_manager']->fire(['event' => 'onBeforeClientChangeNameservers', 'params' => $data]);
$this->getService()->updateNameservers($s, $data);
- $this->di['events_manager']->fire(['event' => 'onAfterClientChangeNameservers', 'params' => $data]);
+ $this->getDi()['events_manager']->fire(['event' => 'onAfterClientChangeNameservers', 'params' => $data]);
return true;
}
@@ -115,7 +115,7 @@ class Client extends \Api_Abstract
if (!isset($data['order_id'])) {
throw new \FOSSBilling\Exception('Order ID is required');
}
- $orderService = $this->di['mod_service']('order');
+ $orderService = $this->getDi()['mod_service']('order');
$order = $orderService->findForClientById($this->getIdentity(), $data['order_id']);
if (!$order instanceof \Model_ClientOrder) {
diff --git a/src/modules/Servicedomain/Api/Guest.php b/src/modules/Servicedomain/Api/Guest.php
index 43eb8e0f0..5aff7538b 100644
--- a/src/modules/Servicedomain/Api/Guest.php
+++ b/src/modules/Servicedomain/Api/Guest.php
@@ -45,7 +45,7 @@ class Guest extends \Api_Abstract
$query = implode(' AND ', $where);
- $tlds = $this->di['db']->find('Tld', $query, []);
+ $tlds = $this->getDi()['db']->find('Tld', $query, []);
$result = [];
foreach ($tlds as $model) {
$result[] = $this->getService()->tldToApiArray($model);
@@ -82,10 +82,10 @@ class Guest extends \Api_Abstract
])]
public function check($data): bool
{
- $this->di['rate_limiter']->consumeOrThrow('domain_lookup_ip', (string) $this->getIp());
+ $this->getDi()['rate_limiter']->consumeOrThrow('domain_lookup_ip', (string) $this->getIp());
$sld = htmlspecialchars((string) $data['sld'], ENT_QUOTES | ENT_HTML5, 'UTF-8');
- $validator = $this->di['validator'];
+ $validator = $this->getDi()['validator'];
if (!$validator->isSldValid($sld)) {
throw new \FOSSBilling\InformationException('Domain :domain is invalid', [':domain' => $sld]);
}
@@ -114,7 +114,7 @@ class Guest extends \Api_Abstract
])]
public function can_be_transferred($data): bool
{
- $this->di['rate_limiter']->consumeOrThrow('domain_lookup_ip', (string) $this->getIp());
+ $this->getDi()['rate_limiter']->consumeOrThrow('domain_lookup_ip', (string) $this->getIp());
$tld = $this->getService()->tldFindOneByTld($data['tld']);
if (!$tld instanceof \Model_Tld) {
diff --git a/src/modules/Servicedomain/tests/Unit/Api/AdminTest.php b/src/modules/Servicedomain/tests/Unit/Api/AdminTest.php
new file mode 100644
index 000000000..cd9f07d52
--- /dev/null
+++ b/src/modules/Servicedomain/tests/Unit/Api/AdminTest.php
@@ -0,0 +1,849 @@
+loadBean(new Tests\Helpers\DummyBean());
+
+ $adminApiMock = Mockery::mock(Admin::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $adminApiMock->shouldReceive('_getService')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('updateDomain')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $adminApiMock->setService($serviceMock);
+
+ $data = [];
+ $result = $adminApiMock->update($data);
+
+ expect($result)->toBeTrue();
+});
+
+test('updates nameservers', function (): void {
+ $adminApi = new Admin();
+ $api = new Admin();
+ $model = new Model_ServiceDomain();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $adminApiMock = Mockery::mock(Admin::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $adminApiMock->shouldReceive('_getService')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('updateNameservers')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $adminApiMock->setService($serviceMock);
+
+ $data = [];
+ $result = $adminApiMock->update_nameservers($data);
+
+ expect($result)->toBeTrue();
+});
+
+test('updates contacts', function (): void {
+ $adminApi = new Admin();
+ $api = new Admin();
+ $model = new Model_ServiceDomain();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $adminApiMock = Mockery::mock(Admin::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $adminApiMock->shouldReceive('_getService')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('updateContacts')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $adminApiMock->setService($serviceMock);
+
+ $data = [];
+ $result = $adminApiMock->update_contacts($data);
+
+ expect($result)->toBeTrue();
+});
+
+test('enables privacy protection', function (): void {
+ $adminApi = new Admin();
+ $api = new Admin();
+ $model = new Model_ServiceDomain();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $adminApiMock = Mockery::mock(Admin::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $adminApiMock->shouldReceive('_getService')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('enablePrivacyProtection')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $adminApiMock->setService($serviceMock);
+
+ $data = [];
+ $result = $adminApiMock->enable_privacy_protection($data);
+
+ expect($result)->toBeTrue();
+});
+
+test('disables privacy protection', function (): void {
+ $adminApi = new Admin();
+ $api = new Admin();
+ $model = new Model_ServiceDomain();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $adminApiMock = Mockery::mock(Admin::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $adminApiMock->shouldReceive('_getService')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('disablePrivacyProtection')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $adminApiMock->setService($serviceMock);
+
+ $data = [];
+ $result = $adminApiMock->disable_privacy_protection($data);
+
+ expect($result)->toBeTrue();
+});
+
+test('gets transfer code', function (): void {
+ $adminApi = new Admin();
+ $api = new Admin();
+ $model = new Model_ServiceDomain();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $adminApiMock = Mockery::mock(Admin::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $adminApiMock->shouldReceive('_getService')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('getTransferCode')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $adminApiMock->setService($serviceMock);
+
+ $data = [];
+ $result = $adminApiMock->get_transfer_code($data);
+
+ expect($result)->toBeTrue();
+});
+
+test('locks domain', function (): void {
+ $adminApi = new Admin();
+ $api = new Admin();
+ $model = new Model_ServiceDomain();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $adminApiMock = Mockery::mock(Admin::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $adminApiMock->shouldReceive('_getService')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('lock')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $adminApiMock->setService($serviceMock);
+
+ $data = [];
+ $result = $adminApiMock->lock($data);
+
+ expect($result)->toBeTrue();
+});
+
+test('unlocks domain', function (): void {
+ $adminApi = new Admin();
+ $api = new Admin();
+ $model = new Model_ServiceDomain();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $adminApiMock = Mockery::mock(Admin::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $adminApiMock->shouldReceive('_getService')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('unlock')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $adminApiMock->setService($serviceMock);
+
+ $data = [];
+ $result = $adminApiMock->unlock($data);
+
+ expect($result)->toBeTrue();
+});
+
+test('gets tld list', function (): void {
+ $adminApi = new Admin();
+ $api = new Admin();
+ $paginatorMock = Mockery::mock(Pagination::class);
+ $paginatorMock->shouldReceive('getPaginatedResultSet')
+ ->atLeast()->once()
+ ->andReturn(['list' => []]);
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('tldGetSearchQuery')
+ ->atLeast()->once()
+ ->andReturn(['query', []]);
+
+ $di = container();
+ $di['pager'] = $paginatorMock;
+
+ $adminApi->setDi($di);
+ $adminApi->setService($serviceMock);
+
+ $data = [];
+ $result = $adminApi->tld_get_list($data);
+
+ expect($result)->toBeArray();
+});
+
+test('gets tld', function (): void {
+ $adminApi = new Admin();
+ $api = new Admin();
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('tldFindOneByTld')
+ ->atLeast()->once()
+ ->andReturn(new Model_Tld());
+ $serviceMock->shouldReceive('tldToApiArray')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $di = container();
+ $adminApi->setDi($di);
+ $adminApi->setService($serviceMock);
+
+ $data = [
+ 'tld' => '.com',
+ ];
+ $result = $adminApi->tld_get($data);
+
+ expect($result)->toBeArray();
+});
+
+test('throws exception when getting tld not found', function (): void {
+ $adminApi = new Admin();
+ $api = new Admin();
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('tldFindOneByTld')
+ ->atLeast()->once()
+ ->andReturn(null);
+ $serviceMock->shouldReceive('tldToApiArray')
+ ->never();
+
+ $di = container();
+ $adminApi->setDi($di);
+ $adminApi->setService($serviceMock);
+
+ $data = [
+ 'tld' => '.com',
+ ];
+
+ expect(fn () => $adminApi->tld_get($data))
+ ->toThrow(FOSSBilling\Exception::class);
+});
+
+test('deletes tld', function (): void {
+ $adminApi = new Admin();
+ $api = new Admin();
+ $tldMock = new Model_Tld();
+ $tldMock->loadBean(new Tests\Helpers\DummyBean());
+ $tldMock->tld = '.com';
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('tldFindOneByTld')
+ ->atLeast()->once()
+ ->andReturn($tldMock);
+ $serviceMock->shouldReceive('tldRm')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('find')
+ ->once()
+ ->with('ServiceDomain', 'tld = :tld', [':tld' => $tldMock->tld])
+ ->andReturn([]);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $adminApi->setDi($di);
+ $adminApi->setService($serviceMock);
+
+ $data = [
+ 'tld' => '.com',
+ ];
+ $result = $adminApi->tld_delete($data);
+
+ expect($result)->toBeTrue();
+});
+
+test('throws exception when deleting tld not found', function (): void {
+ $adminApi = new Admin();
+ $api = new Admin();
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('tldFindOneByTld')
+ ->atLeast()->once()
+ ->andReturn(null);
+ $serviceMock->shouldReceive('tldRm')
+ ->never();
+
+ $di = container();
+ $adminApi->setDi($di);
+ $adminApi->setService($serviceMock);
+
+ $data = [
+ 'tld' => '.com',
+ ];
+
+ expect(fn () => $adminApi->tld_delete($data))
+ ->toThrow(FOSSBilling\Exception::class);
+});
+
+test('creates tld', function (): void {
+ $adminApi = new Admin();
+ $api = new Admin();
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('tldAlreadyRegistered')
+ ->atLeast()->once()
+ ->andReturn(false);
+ $serviceMock->shouldReceive('tldCreate')
+ ->atLeast()->once()
+ ->andReturn(1);
+
+ $di = container();
+ $adminApi->setDi($di);
+ $adminApi->setService($serviceMock);
+
+ $data = [
+ 'tld' => '.com',
+ 'tld_registrar_id' => 1,
+ 'price_registration' => 1,
+ 'price_renew' => 1,
+ 'price_transfer' => 1,
+ ];
+
+ $result = $adminApi->tld_create($data);
+ expect($result)->toBeInt();
+});
+
+test('throws exception when creating already registered tld', function (): void {
+ $adminApi = new Admin();
+ $api = new Admin();
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('tldAlreadyRegistered')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+ $adminApi->setDi($di);
+ $adminApi->setService($serviceMock);
+
+ $data = [
+ 'tld' => '.com',
+ ];
+
+ expect(fn () => $adminApi->tld_create($data))
+ ->toThrow(FOSSBilling\Exception::class);
+});
+
+test('updates tld', function (): void {
+ $adminApi = new Admin();
+ $api = new Admin();
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('tldFindOneByTld')
+ ->atLeast()->once()
+ ->andReturn(new Model_Tld());
+ $serviceMock->shouldReceive('tldUpdate')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+ $adminApi->setDi($di);
+ $adminApi->setService($serviceMock);
+
+ $data = [
+ 'tld' => '.com',
+ ];
+ $result = $adminApi->tld_update($data);
+
+ expect($result)->toBeTrue();
+});
+
+test('throws exception when updating tld not found', function (): void {
+ $adminApi = new Admin();
+ $api = new Admin();
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('tldFindOneByTld')
+ ->atLeast()->once()
+ ->andReturn(null);
+ $serviceMock->shouldReceive('tldUpdate')
+ ->never();
+
+ $di = container();
+ $adminApi->setDi($di);
+ $adminApi->setService($serviceMock);
+
+ $data = [
+ 'tld' => '.com',
+ ];
+
+ expect(fn () => $adminApi->tld_update($data))
+ ->toThrow(FOSSBilling\Exception::class);
+});
+
+test('gets registrar list', function (): void {
+ $adminApi = new Admin();
+ $api = new Admin();
+ $paginatorMock = Mockery::mock(Pagination::class);
+ $paginatorMock->shouldReceive('getPaginatedResultSet')
+ ->atLeast()->once()
+ ->andReturn(['list' => []]);
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('registrarGetSearchQuery')
+ ->atLeast()->once()
+ ->andReturn(['query', []]);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('find')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $di = container();
+ $di['pager'] = $paginatorMock;
+ $di['db'] = $dbMock;
+
+ $adminApi->setDi($di);
+ $adminApi->setService($serviceMock);
+
+ $data = [];
+ $result = $adminApi->registrar_get_list($data);
+
+ expect($result)->toBeArray();
+});
+
+test('gets registrar pairs', function (): void {
+ $adminApi = new Admin();
+ $api = new Admin();
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('registrarGetPairs')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $adminApi->setService($serviceMock);
+
+ $result = $adminApi->registrar_get_pairs([]);
+
+ expect($result)->toBeArray();
+});
+
+test('gets available registrars', function (): void {
+ $adminApi = new Admin();
+ $api = new Admin();
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('registrarGetAvailable')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $adminApi->setService($serviceMock);
+
+ $result = $adminApi->registrar_get_available([]);
+
+ expect($result)->toBeArray();
+});
+
+test('installs registrar', function (): void {
+ $adminApi = new Admin();
+ $api = new Admin();
+ $registrars = [
+ 'ResellerClub', 'Custom',
+ ];
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('registrarGetAvailable')
+ ->atLeast()->once()
+ ->andReturn($registrars);
+ $serviceMock->shouldReceive('registrarCreate')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+ $adminApi->setDi($di);
+ $adminApi->setService($serviceMock);
+
+ $data = [
+ 'code' => 'ResellerClub',
+ ];
+ $result = $adminApi->registrar_install($data);
+
+ expect($result)->toBeTrue();
+});
+
+test('throws exception when installing unavailable registrar', function (): void {
+ $adminApi = new Admin();
+ $api = new Admin();
+ $registrars = [
+ 'Custom',
+ ];
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('registrarGetAvailable')
+ ->atLeast()->once()
+ ->andReturn($registrars);
+ $serviceMock->shouldReceive('registrarCreate')
+ ->never();
+
+ $di = container();
+ $adminApi->setDi($di);
+ $adminApi->setService($serviceMock);
+
+ $data = [
+ 'code' => 'ResellerClub',
+ ];
+
+ expect(fn () => $adminApi->registrar_install($data))
+ ->toThrow(FOSSBilling\Exception::class);
+});
+
+test('throws exception when deleting registrar without id', function (): void {
+ $adminApi = new Admin();
+ $api = new Admin();
+ $apiHandler = new Api_Handler(new Model_Admin());
+ $reflection = new ReflectionClass($apiHandler);
+ $method = $reflection->getMethod('validateRequiredParams');
+
+ expect(fn (): mixed => $method->invokeArgs($apiHandler, [$adminApi, 'registrar_delete', []]))
+ ->toThrow(FOSSBilling\InformationException::class);
+});
+
+test('copies registrar', function (): void {
+ $adminApi = new Admin();
+ $api = new Admin();
+ $registrar = new Model_TldRegistrar();
+ $registrar->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($registrar);
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('registrarCopy')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+ $di['validator'] = new FOSSBilling\Validate();
+ $di['db'] = $dbMock;
+
+ $adminApi->setDi($di);
+ $adminApi->setService($serviceMock);
+
+ $data = [
+ 'id' => 1,
+ ];
+ $result = $adminApi->registrar_copy($data);
+
+ expect($result)->toBeTrue();
+});
+
+test('throws exception when copying registrar without id', function (): void {
+ $adminApi = new Admin();
+ $api = new Admin();
+ $apiHandler = new Api_Handler(new Model_Admin());
+ $reflection = new ReflectionClass($apiHandler);
+ $method = $reflection->getMethod('validateRequiredParams');
+
+ expect(fn (): mixed => $method->invokeArgs($apiHandler, [$adminApi, 'registrar_copy', []]))
+ ->toThrow(FOSSBilling\InformationException::class);
+});
+
+test('gets registrar', function (): void {
+ $adminApi = new Admin();
+ $api = new Admin();
+ $registrar = new Model_TldRegistrar();
+ $registrar->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($registrar);
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('registrarToApiArray')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['validator'] = new FOSSBilling\Validate();
+
+ $adminApi->setDi($di);
+ $adminApi->setService($serviceMock);
+
+ $data = [
+ 'id' => 1,
+ ];
+ $result = $adminApi->registrar_get($data);
+
+ expect($result)->toBeArray();
+});
+
+test('throws exception when getting registrar without id', function (): void {
+ $adminApi = new Admin();
+ $api = new Admin();
+ $registrar = new Model_TldRegistrar();
+ $registrar->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('load')
+ ->never();
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('registrarToApiArray')
+ ->never();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['validator'] = new FOSSBilling\Validate();
+
+ $adminApi->setDi($di);
+ $adminApi->setService($serviceMock);
+
+ $data = [];
+
+ $apiHandler = new Api_Handler(new Model_Admin());
+ $reflection = new ReflectionClass($apiHandler);
+ $method = $reflection->getMethod('validateRequiredParams');
+
+ expect(fn (): mixed => $method->invokeArgs($apiHandler, [$adminApi, 'registrar_get', []]))
+ ->toThrow(FOSSBilling\InformationException::class);
+});
+
+test('batch syncs expiration dates', function (): void {
+ $adminApi = new Admin();
+ $api = new Admin();
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('batchSyncExpirationDates')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $adminApi->setService($serviceMock);
+
+ $result = $adminApi->batch_sync_expiration_dates([]);
+
+ expect($result)->toBeTrue();
+});
+
+test('updates registrar', function (): void {
+ $adminApi = new Admin();
+ $api = new Admin();
+ $registrar = new Model_TldRegistrar();
+ $registrar->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($registrar);
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('registrarUpdate')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['validator'] = new FOSSBilling\Validate();
+
+ $adminApi->setDi($di);
+ $adminApi->setService($serviceMock);
+
+ $data = [
+ 'id' => 1,
+ ];
+ $result = $adminApi->registrar_update($data);
+
+ expect($result)->toBeTrue();
+});
+
+test('throws exception when updating registrar without id', function (): void {
+ $adminApi = new Admin();
+ $api = new Admin();
+ $registrar = new Model_TldRegistrar();
+ $registrar->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('load')
+ ->never();
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('registrarUpdate')
+ ->never();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['validator'] = new FOSSBilling\Validate();
+
+ $adminApi->setDi($di);
+ $adminApi->setService($serviceMock);
+
+ $data = [];
+
+ $apiHandler = new Api_Handler(new Model_Admin());
+ $reflection = new ReflectionClass($apiHandler);
+ $method = $reflection->getMethod('validateRequiredParams');
+
+ expect(fn (): mixed => $method->invokeArgs($apiHandler, [$adminApi, 'registrar_update', []]))
+ ->toThrow(FOSSBilling\InformationException::class);
+});
+
+test('gets service', function (): void {
+ $adminApi = new Admin();
+ $api = new Admin();
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('updateDomain')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $adminApi->setService($serviceMock);
+
+ $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(new Model_ServiceDomain());
+ $staffServiceMock = Mockery::mock(Box\Mod\Staff\Service::class)->shouldIgnoreMissing();
+ $staffServiceMock->shouldReceive('checkPermissionsAndThrowException')
+ ->atLeast()->once()
+ ->with('servicedomain', 'manage_domains');
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(fn (string $name = ''): Mockery\MockInterface => strtolower($name) === 'staff' ? $staffServiceMock : $orderServiceMock);
+ $di['validator'] = new FOSSBilling\Validate();
+
+ $adminApi->setDi($di);
+
+ $data = [
+ 'order_id' => 1,
+ ];
+ $result = $adminApi->update($data);
+
+ expect($result)->toBeTrue();
+});
+
+test('throws exception when getting service without order_id', function (): void {
+ $adminApi = new Admin();
+ $api = new Admin();
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('updateDomain')
+ ->never();
+
+ $adminApi->setService($serviceMock);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('load')
+ ->never();
+
+ $orderServiceMock = Mockery::mock(OrderService::class);
+ $orderServiceMock->shouldReceive('getOrderService')
+ ->never();
+ $staffServiceMock = Mockery::mock(Box\Mod\Staff\Service::class)->shouldIgnoreMissing();
+ $staffServiceMock->shouldReceive('checkPermissionsAndThrowException')
+ ->never();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(fn (string $name = ''): Mockery\MockInterface => strtolower($name) === 'staff' ? $staffServiceMock : $orderServiceMock);
+ $di['validator'] = new FOSSBilling\Validate();
+
+ $adminApi->setDi($di);
+
+ $data = [];
+
+ $apiHandler = new Api_Handler(new Model_Admin());
+ $reflection = new ReflectionClass($apiHandler);
+ $method = $reflection->getMethod('validateRequiredParams');
+
+ expect(fn (): mixed => $method->invokeArgs($apiHandler, [$adminApi, 'update', []]))
+ ->toThrow(FOSSBilling\InformationException::class);
+});
+
+test('throws exception when getting service for not activated order', function (): void {
+ $adminApi = new Admin();
+ $api = new Admin();
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('updateDomain')
+ ->never();
+
+ $adminApi->setService($serviceMock);
+
+ $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);
+ $staffServiceMock = Mockery::mock(Box\Mod\Staff\Service::class)->shouldIgnoreMissing();
+ $staffServiceMock->shouldReceive('checkPermissionsAndThrowException')
+ ->atLeast()->once()
+ ->with('servicedomain', 'manage_domains');
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(fn (string $name = ''): Mockery\MockInterface => strtolower($name) === 'staff' ? $staffServiceMock : $orderServiceMock);
+ $di['validator'] = new FOSSBilling\Validate();
+
+ $adminApi->setDi($di);
+
+ $data = [
+ 'order_id' => 1,
+ ];
+
+ expect(fn () => $adminApi->update($data))
+ ->toThrow(FOSSBilling\Exception::class);
+});
diff --git a/src/modules/Servicedomain/tests/Unit/Api/ClientTest.php b/src/modules/Servicedomain/tests/Unit/Api/ClientTest.php
new file mode 100644
index 000000000..edc98799d
--- /dev/null
+++ b/src/modules/Servicedomain/tests/Unit/Api/ClientTest.php
@@ -0,0 +1,316 @@
+loadBean(new Tests\Helpers\DummyBean());
+
+ $clientApiMock = Mockery::mock(Client::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $clientApiMock->shouldReceive('_getService')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('updateNameservers')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $clientApiMock->setService($serviceMock);
+
+ $eventMock = Mockery::mock('\Box_EventManager');
+ $eventMock->shouldReceive('fire')
+ ->atLeast()->once();
+
+ $di = container();
+ $di['events_manager'] = $eventMock;
+ $clientApiMock->setDi($di);
+
+ $data = [];
+ $result = $clientApiMock->update_nameservers($data);
+
+ expect($result)->toBeTrue();
+});
+
+test('updates contacts', function (): void {
+ $clientApi = new Client();
+ $api = new Client();
+ $model = new Model_ServiceDomain();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $clientApiMock = Mockery::mock(Client::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $clientApiMock->shouldReceive('_getService')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('updateContacts')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $clientApiMock->setService($serviceMock);
+
+ $data = [];
+ $result = $clientApiMock->update_contacts($data);
+
+ expect($result)->toBeTrue();
+});
+
+test('enables privacy protection', function (): void {
+ $clientApi = new Client();
+ $api = new Client();
+ $model = new Model_ServiceDomain();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $clientApiMock = Mockery::mock(Client::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $clientApiMock->shouldReceive('_getService')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('enablePrivacyProtection')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $clientApiMock->setService($serviceMock);
+
+ $data = [];
+ $result = $clientApiMock->enable_privacy_protection($data);
+
+ expect($result)->toBeTrue();
+});
+
+test('disables privacy protection', function (): void {
+ $clientApi = new Client();
+ $api = new Client();
+ $model = new Model_ServiceDomain();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $clientApiMock = Mockery::mock(Client::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $clientApiMock->shouldReceive('_getService')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('disablePrivacyProtection')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $clientApiMock->setService($serviceMock);
+
+ $data = [];
+ $result = $clientApiMock->disable_privacy_protection($data);
+
+ expect($result)->toBeTrue();
+});
+
+test('gets transfer code', function (): void {
+ $clientApi = new Client();
+ $api = new Client();
+ $model = new Model_ServiceDomain();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $clientApiMock = Mockery::mock(Client::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $clientApiMock->shouldReceive('_getService')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('getTransferCode')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $clientApiMock->setService($serviceMock);
+
+ $data = [];
+ $result = $clientApiMock->get_transfer_code($data);
+
+ expect($result)->toBeTrue();
+});
+
+test('locks domain', function (): void {
+ $clientApi = new Client();
+ $api = new Client();
+ $model = new Model_ServiceDomain();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $clientApiMock = Mockery::mock(Client::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $clientApiMock->shouldReceive('_getService')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('lock')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $clientApiMock->setService($serviceMock);
+
+ $data = [];
+ $result = $clientApiMock->lock($data);
+
+ expect($result)->toBeTrue();
+});
+
+test('unlocks domain', function (): void {
+ $clientApi = new Client();
+ $api = new Client();
+ $model = new Model_ServiceDomain();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $clientApiMock = Mockery::mock(Client::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $clientApiMock->shouldReceive('_getService')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('unlock')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $clientApiMock->setService($serviceMock);
+
+ $data = [];
+ $result = $clientApiMock->unlock($data);
+
+ expect($result)->toBeTrue();
+});
+
+test('gets service', function (): void {
+ $clientApi = new Client();
+ $api = new Client();
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('lock')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $clientApi->setService($serviceMock);
+
+ $orderServiceMock = Mockery::mock(OrderService::class);
+ $order = new Model_ClientOrder();
+ $order->loadBean(new Tests\Helpers\DummyBean());
+ $order->status = Model_ClientOrder::STATUS_ACTIVE;
+ $orderServiceMock->shouldReceive('findForClientById')
+ ->atLeast()->once()
+ ->andReturn($order);
+ $orderServiceMock->shouldReceive('getOrderService')
+ ->atLeast()->once()
+ ->andReturn(new Model_ServiceDomain());
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
+ $clientApi->setDi($di);
+
+ $clientApi->setIdentity(new Model_Client());
+
+ $data = [
+ 'order_id' => 1,
+ ];
+ $result = $clientApi->lock($data);
+
+ expect($result)->toBeTrue();
+});
+
+test('throws exception when getting service without order_id', function (): void {
+ $clientApi = new Client();
+ $api = new Client();
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('lock')
+ ->never();
+
+ $clientApi->setService($serviceMock);
+
+ $orderServiceMock = Mockery::mock(OrderService::class);
+ $orderServiceMock->shouldReceive('findForClientById')
+ ->never();
+ $orderServiceMock->shouldReceive('getOrderService')
+ ->never();
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
+ $clientApi->setDi($di);
+
+ $clientApi->setIdentity(new Model_Client());
+
+ $data = [];
+
+ expect(fn () => $clientApi->lock($data))
+ ->toThrow(FOSSBilling\Exception::class);
+});
+
+test('throws exception when getting service order not found', function (): void {
+ $clientApi = new Client();
+ $api = new Client();
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('lock')
+ ->never();
+
+ $clientApi->setService($serviceMock);
+
+ $orderServiceMock = Mockery::mock(OrderService::class);
+ $orderServiceMock->shouldReceive('findForClientById')
+ ->atLeast()->once()
+ ->andReturn(null);
+ $orderServiceMock->shouldReceive('getOrderService')
+ ->never();
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
+ $clientApi->setDi($di);
+
+ $clientApi->setIdentity(new Model_Client());
+
+ $data = [
+ 'order_id' => 1,
+ ];
+
+ expect(fn () => $clientApi->lock($data))
+ ->toThrow(FOSSBilling\Exception::class);
+});
+
+test('throws exception when getting service order not activated', function (): void {
+ $clientApi = new Client();
+ $api = new Client();
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('lock')
+ ->never();
+
+ $clientApi->setService($serviceMock);
+
+ $orderServiceMock = Mockery::mock(OrderService::class);
+ $orderServiceMock->shouldReceive('findForClientById')
+ ->atLeast()->once()
+ ->andReturn(new Model_ClientOrder());
+ $orderServiceMock->shouldReceive('getOrderService')
+ ->atLeast()->once()
+ ->andReturn(null);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
+ $clientApi->setDi($di);
+
+ $clientApi->setIdentity(new Model_Client());
+
+ $data = [
+ 'order_id' => 1,
+ ];
+
+ expect(fn () => $clientApi->lock($data))
+ ->toThrow(FOSSBilling\Exception::class);
+});
diff --git a/src/modules/Servicedomain/tests/Unit/Api/GuestTest.php b/src/modules/Servicedomain/tests/Unit/Api/GuestTest.php
new file mode 100644
index 000000000..e12448a10
--- /dev/null
+++ b/src/modules/Servicedomain/tests/Unit/Api/GuestTest.php
@@ -0,0 +1,283 @@
+shouldReceive('tldToApiArray')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $guestApi->setService($serviceMock);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('find')
+ ->atLeast()->once()
+ ->andReturn([new Model_Tld()]);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $guestApi->setDi($di);
+
+ $result = $guestApi->tlds([]);
+ expect($result)->toBeArray();
+ expect($result[0])->toBeArray();
+});
+
+test('gets pricing', function (): void {
+ $guestApi = new Guest();
+ $api = new Guest();
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('tldFindOneByTld')
+ ->atLeast()->once()
+ ->andReturn(new Model_Tld());
+ $serviceMock->shouldReceive('tldToApiArray')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $di = container();
+ $guestApi->setDi($di);
+ $guestApi->setService($serviceMock);
+
+ $data = [
+ 'tld' => '.com',
+ ];
+
+ $result = $guestApi->pricing($data);
+ expect($result)->toBeArray();
+});
+
+test('throws exception when getting pricing for tld not found', function (): void {
+ $guestApi = new Guest();
+ $api = new Guest();
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('tldFindOneByTld')
+ ->atLeast()->once()
+ ->andReturn(null);
+ $serviceMock->shouldReceive('tldToApiArray')
+ ->never();
+
+ $validatorMock = Mockery::mock(FOSSBilling\Validate::class);
+
+ $di = container();
+ $di['validator'] = $validatorMock;
+ $guestApi->setDi($di);
+ $guestApi->setService($serviceMock);
+
+ $data = [
+ 'tld' => '.com',
+ ];
+
+ expect(fn () => $guestApi->pricing($data))
+ ->toThrow(FOSSBilling\Exception::class);
+});
+
+test('checks domain availability', function (): void {
+ $guestApi = new Guest();
+ $api = new Guest();
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('tldFindOneByTld')
+ ->atLeast()->once()
+ ->andReturn(new Model_Tld());
+ $serviceMock->shouldReceive('isDomainAvailable')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $guestApi->setService($serviceMock);
+
+ $validatorMock = Mockery::mock(FOSSBilling\Validate::class);
+ $validatorMock->shouldReceive('isSldValid')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+ $di['validator'] = $validatorMock;
+ $guestApi->setDi($di);
+
+ $data = [
+ 'tld' => '.com',
+ 'sld' => 'example',
+ ];
+
+ $result = $guestApi->check($data);
+ expect($result)->toBeTrue();
+});
+
+test('throws exception when checking sld not valid', function (): void {
+ $guestApi = new Guest();
+ $api = new Guest();
+ $validatorMock = Mockery::mock(FOSSBilling\Validate::class);
+ $validatorMock->shouldReceive('isSldValid')
+ ->atLeast()->once()
+ ->andReturn(false);
+
+ $di = container();
+ $di['validator'] = $validatorMock;
+ $guestApi->setDi($di);
+
+ $data = [
+ 'tld' => '.com',
+ 'sld' => 'example',
+ ];
+
+ expect(fn (): bool => $guestApi->check($data))
+ ->toThrow(FOSSBilling\Exception::class);
+});
+
+test('throws exception when checking tld not found', function (): void {
+ $guestApi = new Guest();
+ $api = new Guest();
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('tldFindOneByTld')
+ ->atLeast()->once()
+ ->andReturn(null);
+ $serviceMock->shouldReceive('isDomainAvailable')
+ ->never();
+
+ $guestApi->setService($serviceMock);
+
+ $validatorMock = Mockery::mock(FOSSBilling\Validate::class);
+ $validatorMock->shouldReceive('isSldValid')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+ $di['validator'] = $validatorMock;
+ $guestApi->setDi($di);
+
+ $data = [
+ 'tld' => '.com',
+ 'sld' => 'example',
+ ];
+
+ expect(fn (): bool => $guestApi->check($data))
+ ->toThrow(FOSSBilling\Exception::class);
+});
+
+test('throws exception when checking domain not available', function (): void {
+ $guestApi = new Guest();
+ $api = new Guest();
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('tldFindOneByTld')
+ ->atLeast()->once()
+ ->andReturn(new Model_Tld());
+ $serviceMock->shouldReceive('isDomainAvailable')
+ ->atLeast()->once()
+ ->andReturn(false);
+
+ $guestApi->setService($serviceMock);
+
+ $validatorMock = Mockery::mock(FOSSBilling\Validate::class);
+ $validatorMock->shouldReceive('isSldValid')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+ $di['validator'] = $validatorMock;
+ $guestApi->setDi($di);
+
+ $data = [
+ 'tld' => '.com',
+ 'sld' => 'example',
+ ];
+
+ expect(fn (): bool => $guestApi->check($data))
+ ->toThrow(FOSSBilling\Exception::class);
+});
+
+test('checks if domain can be transferred', function (): void {
+ $guestApi = new Guest();
+ $api = new Guest();
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('tldFindOneByTld')
+ ->atLeast()->once()
+ ->andReturn(new Model_Tld());
+ $serviceMock->shouldReceive('canBeTransferred')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $validatorMock = Mockery::mock(FOSSBilling\Validate::class);
+
+ $di = container();
+ $di['validator'] = $validatorMock;
+ $guestApi->setDi($di);
+
+ $guestApi->setService($serviceMock);
+
+ $data = [
+ 'tld' => '.com',
+ 'sld' => 'example',
+ ];
+
+ $result = $guestApi->can_be_transferred($data);
+ expect($result)->toBeTrue();
+});
+
+test('throws exception when checking transfer for tld not found', function (): void {
+ $guestApi = new Guest();
+ $api = new Guest();
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('tldFindOneByTld')
+ ->atLeast()->once()
+ ->andReturn(null);
+ $serviceMock->shouldReceive('canBeTransferred')
+ ->never();
+
+ $validatorMock = Mockery::mock(FOSSBilling\Validate::class);
+
+ $di = container();
+ $di['validator'] = $validatorMock;
+ $guestApi->setDi($di);
+ $guestApi->setService($serviceMock);
+
+ $data = [
+ 'tld' => '.com',
+ 'sld' => 'example',
+ ];
+
+ expect(fn (): bool => $guestApi->can_be_transferred($data))
+ ->toThrow(FOSSBilling\Exception::class);
+});
+
+test('throws exception when checking domain cannot be transferred', function (): void {
+ $guestApi = new Guest();
+ $api = new Guest();
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('tldFindOneByTld')
+ ->atLeast()->once()
+ ->andReturn(new Model_Tld());
+ $serviceMock->shouldReceive('canBeTransferred')
+ ->atLeast()->once()
+ ->andReturn(false);
+
+ $validatorMock = Mockery::mock(FOSSBilling\Validate::class);
+
+ $di = container();
+ $di['validator'] = $validatorMock;
+ $guestApi->setDi($di);
+ $guestApi->setService($serviceMock);
+
+ $data = [
+ 'tld' => '.com',
+ 'sld' => 'example',
+ ];
+
+ expect(fn (): bool => $guestApi->can_be_transferred($data))
+ ->toThrow(FOSSBilling\Exception::class);
+});
diff --git a/src/modules/Servicedomain/tests/Unit/ServiceTest.php b/src/modules/Servicedomain/tests/Unit/ServiceTest.php
new file mode 100644
index 000000000..c124ba67d
--- /dev/null
+++ b/src/modules/Servicedomain/tests/Unit/ServiceTest.php
@@ -0,0 +1,1785 @@
+setDi($di);
+ $getDi = $service->getDi();
+ expect($getDi)->toBe($di);
+});
+
+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';
+
+ $result = $service->getCartProductTitle($product, $data);
+
+ expect($result)->toBe($expected);
+})->with([
+ [
+ [
+ 'action' => 'register',
+ 'register_tld' => '.com',
+ 'register_sld' => 'example',
+ ],
+ 'Domain example.com registration',
+ ],
+ [
+ [
+ 'action' => 'transfer',
+ 'transfer_tld' => '.com',
+ 'transfer_sld' => 'example',
+ ],
+ 'Domain example.com transfer',
+ ],
+ [
+ [],
+ 'Example.com Registration',
+ ],
+]);
+
+test('throws exception for invalid order data action', function (): void {
+ $service = new Service();
+ $validatorMock = Mockery::mock(FOSSBilling\Validate::class);
+ $validatorMock->shouldReceive('checkRequiredParamsForArray')
+ ->atLeast()->once();
+
+ $di = container();
+ $di['validator'] = $validatorMock;
+ $service->setDi($di);
+
+ $data = [
+ 'action' => 'NonExistingAction',
+ ];
+
+ expect(fn () => $service->validateOrderData($data))
+ ->toThrow(FOSSBilling\Exception::class);
+});
+
+test('throws exception for transfer order data with invalid tld', function (array $data, array $isSldValidArr, array $tldFindOneByTldArr, array $canBeTransferred): void {
+ $service = new Service();
+ $validatorMock = Mockery::mock(FOSSBilling\Validate::class);
+ $validatorMock->shouldReceive('isSldValid')
+ ->{$isSldValidArr['called']}()
+ ->andReturn($isSldValidArr['returns']);
+ $validatorMock->shouldReceive('checkRequiredParamsForArray')
+ ->zeroOrMoreTimes();
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('tldFindOneByTld')
+ ->{$tldFindOneByTldArr['called']}()
+ ->andReturn($tldFindOneByTldArr['returns']);
+ $serviceMock->shouldReceive('canBeTransferred')
+ ->{$canBeTransferred['called']}()
+ ->andReturn($canBeTransferred['returns']);
+
+ $di = container();
+ $di['validator'] = $validatorMock;
+ $serviceMock->setDi($di);
+
+ expect(fn () => $serviceMock->validateOrderData($data))
+ ->toThrow(FOSSBilling\Exception::class);
+})->with(function () {
+ $tldModel = new Model_Tld();
+ $tldModel->loadBean(new Tests\Helpers\DummyBean());
+ $tldModel->tld = '.com';
+
+ return [
+ [
+ [
+ 'action' => 'transfer',
+ 'transfer_sld' => 'example',
+ 'transfer_tld' => '.com',
+ ],
+ ['called' => 'atLeast', 'returns' => true],
+ ['called' => 'atLeast', 'returns' => null],
+ ['called' => 'never', 'returns' => true],
+ ],
+ [
+ [
+ 'action' => 'transfer',
+ 'transfer_sld' => 'example',
+ 'transfer_tld' => '.com',
+ ],
+ ['called' => 'atLeast', 'returns' => true],
+ ['called' => 'atLeast', 'returns' => $tldModel],
+ ['called' => 'atLeast', 'returns' => false],
+ ],
+ ];
+});
+
+test('throws exception for register order data with invalid tld', function (array $data, array $isSldValidArr, array $tldFindOneByTldArr, array $isDomainAvailable): void {
+ $service = new Service();
+ $validatorMock = Mockery::mock(FOSSBilling\Validate::class);
+ $validatorMock->shouldReceive('isSldValid')
+ ->{$isSldValidArr['called']}()
+ ->andReturn($isSldValidArr['returns']);
+ $validatorMock->shouldReceive('checkRequiredParamsForArray')
+ ->zeroOrMoreTimes();
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('tldFindOneByTld')
+ ->{$tldFindOneByTldArr['called']}()
+ ->andReturn($tldFindOneByTldArr['returns']);
+ $serviceMock->shouldReceive('isDomainAvailable')
+ ->{$isDomainAvailable['called']}()
+ ->andReturn($isDomainAvailable['returns']);
+
+ $di = container();
+ $di['validator'] = $validatorMock;
+ $serviceMock->setDi($di);
+
+ expect(fn () => $serviceMock->validateOrderData($data))
+ ->toThrow(FOSSBilling\Exception::class);
+})->with(function () {
+ $tldModel = new Model_Tld();
+ $tldModel->loadBean(new Tests\Helpers\DummyBean());
+ $tldModel->tld = '.com';
+ $tldModel->min_years = 2;
+
+ return [
+ [
+ [
+ 'action' => 'register',
+ 'register_sld' => 'example',
+ 'register_years' => 2,
+ 'register_tld' => '.com',
+ ],
+ ['called' => 'atLeast', 'returns' => true],
+ ['called' => 'atLeast', 'returns' => null],
+ ['called' => 'never', 'returns' => true],
+ ],
+ [
+ [
+ 'action' => 'register',
+ 'register_sld' => 'example',
+ 'register_years' => $tldModel->min_years - 1,
+ 'register_tld' => '.com',
+ ],
+ ['called' => 'atLeast', 'returns' => true],
+ ['called' => 'atLeast', 'returns' => $tldModel],
+ ['called' => 'never', 'returns' => true],
+ ],
+ [
+ [
+ 'action' => 'register',
+ 'register_sld' => 'example',
+ 'register_tld' => '.com',
+ 'register_years' => 2,
+ ],
+ ['called' => 'atLeast', 'returns' => true],
+ ['called' => 'atLeast', 'returns' => $tldModel],
+ ['called' => 'atLeast', 'returns' => false],
+ ],
+ ];
+});
+
+test('creates action', function (): void {
+ $service = new Service();
+ $tldModel = new Model_Tld();
+ $tldModel->loadBean(new Tests\Helpers\DummyBean());
+ $tldModel->tld_registrar_id = 1;
+
+ $data = [
+ 'action' => 'register',
+ 'register_sld' => 'example',
+ 'register_tld' => '.com',
+ 'register_years' => 2,
+ ];
+
+ $orderServiceMock = Mockery::mock(OrderService::class);
+ $orderServiceMock->shouldReceive('getConfig')
+ ->atLeast()->once()
+ ->andReturn($data);
+
+ $nameservers = [
+ 'nameserver_1' => 'ns1.example.com',
+ 'nameserver_2' => 'ns2.example.com',
+ 'nameserver_3' => 'ns3.example.com',
+ 'nameserver_4' => 'ns4.example.com',
+ ];
+ $systemServiceMock = Mockery::mock(SystemService::class);
+ $systemServiceMock->shouldReceive('getNameservers')
+ ->atLeast()->once()
+ ->andReturn($nameservers);
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('tldFindOneByTld')
+ ->atLeast()->once()
+ ->andReturn($tldModel);
+ $serviceMock->shouldReceive('validateOrderData');
+
+ $client = new Model_Client();
+ $client->loadBean(new Tests\Helpers\DummyBean());
+ $client->first_name = 'first_name';
+ $client->last_name = 'last_name';
+ $client->email = 'email';
+ $client->company = 'company';
+ $client->address_1 = 'address_1';
+ $client->address_2 = 'address_2';
+ $client->country = 'country';
+ $client->city = 'city';
+ $client->state = 'state';
+ $client->postcode = 'postcode';
+ $client->phone_cc = 'phone_cc';
+ $client->phone = 'phone';
+
+ $serviceDomainModel = new Model_ServiceDomain();
+ $serviceDomainModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($client);
+ $dbMock->shouldReceive('dispense')
+ ->atLeast()->once()
+ ->andReturn($serviceDomainModel);
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn(1);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(function ($name) use ($orderServiceMock, $systemServiceMock) {
+ if ($name == 'order') {
+ return $orderServiceMock;
+ }
+
+ return $systemServiceMock;
+ });
+ $di['db'] = $dbMock;
+
+ $serviceMock->setDi($di);
+
+ $order = new Model_ClientOrder();
+ $order->loadBean(new Tests\Helpers\DummyBean());
+ $order->client_id = 1;
+
+ $result = $serviceMock->action_create($order);
+ expect($result)->toBeInstanceOf(Model_ServiceDomain::class);
+});
+
+test('throws exception when creating action with missing nameservers', function (): void {
+ $service = new Service();
+ $tldModel = new Model_Tld();
+ $tldModel->loadBean(new Tests\Helpers\DummyBean());
+ $tldModel->tld_registrar_id = 1;
+
+ $data = [
+ 'action' => 'register',
+ 'register_sld' => 'example',
+ 'register_tld' => '.com',
+ 'register_years' => 2,
+ ];
+
+ $orderServiceMock = Mockery::mock(OrderService::class);
+ $orderServiceMock->shouldReceive('getConfig')
+ ->atLeast()->once()
+ ->andReturn($data);
+
+ $systemServiceMock = Mockery::mock(SystemService::class);
+ $systemServiceMock->shouldReceive('getNameservers')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('validateOrderData')
+ ->atLeast()->once();
+
+ $di = container();
+ $di['mod_service'] = $di->protect(function ($name) use ($orderServiceMock, $systemServiceMock) {
+ if ($name == 'order') {
+ return $orderServiceMock;
+ }
+
+ return $systemServiceMock;
+ });
+ $serviceMock->setDi($di);
+
+ $order = new Model_ClientOrder();
+ $order->loadBean(new Tests\Helpers\DummyBean());
+ $order->client_id = 1;
+
+ expect(fn () => $serviceMock->action_create($order))
+ ->toThrow(FOSSBilling\Exception::class);
+});
+
+test('activates action', function (string $action, string $registerDomainCalled, string $transferDomainCalled): void {
+ $service = new Service();
+ $tldModel = new Model_Tld();
+ $tldModel->loadBean(new Tests\Helpers\DummyBean());
+ $tldModel->tld_registrar_id = 1;
+
+ $domainModel = new Model_ServiceDomain();
+ $domainModel->loadBean(new Tests\Helpers\DummyBean());
+ $domainModel->tld_registrar_id = 1;
+ $domainModel->action = $action;
+
+ $orderServiceMock = Mockery::mock(OrderService::class);
+ $orderServiceMock->shouldReceive('getOrderService')
+ ->atLeast()->once()
+ ->andReturn($domainModel);
+
+ $registrarAdapterMock = Mockery::mock('Registrar_Adapter_Custom');
+ $registrarAdapterMock->shouldReceive('registerDomain')
+ ->{$registerDomainCalled}();
+ $registrarAdapterMock->shouldReceive('transferDomain')
+ ->{$transferDomainCalled}();
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('_getD')
+ ->atLeast()->once()
+ ->andReturn([new Registrar_Domain(), $registrarAdapterMock]);
+ $serviceMock->shouldReceive('syncWhois')
+ ->atLeast()->once()
+ ->andReturn(null);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn(1);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn ($name) => $orderServiceMock);
+ $di['db'] = $dbMock;
+ $serviceMock->setDi($di);
+
+ $order = new Model_ClientOrder();
+ $order->loadBean(new Tests\Helpers\DummyBean());
+ $order->client_id = 1;
+ $result = $serviceMock->action_activate($order);
+ expect($result)->toBeInstanceOf(Model_ServiceDomain::class);
+})->with([
+ ['register', 'atLeast', 'never'],
+ ['transfer', 'never', 'atLeast'],
+]);
+
+test('throws exception when activating without order service', function (): void {
+ $service = new Service();
+ $orderServiceMock = Mockery::mock(OrderService::class);
+ $orderServiceMock->shouldReceive('getOrderService')
+ ->atLeast()->once()
+ ->andReturn(null);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn ($name) => $orderServiceMock);
+ $service->setDi($di);
+
+ $order = new Model_ClientOrder();
+ $order->loadBean(new Tests\Helpers\DummyBean());
+ $order->client_id = 1;
+
+ expect(fn () => $service->action_activate($order))
+ ->toThrow(FOSSBilling\Exception::class);
+});
+
+test('renews action', function (): void {
+ $service = new Service();
+ $domainModel = new Model_ServiceDomain();
+ $domainModel->loadBean(new Tests\Helpers\DummyBean());
+ $domainModel->tld_registrar_id = 1;
+ $domainModel->action = 'register';
+
+ $orderServiceMock = Mockery::mock(OrderService::class);
+ $orderServiceMock->shouldReceive('getOrderService')
+ ->atLeast()->once()
+ ->andReturn($domainModel);
+
+ $registrarAdapterMock = Mockery::mock('Registrar_Adapter_Custom');
+ $registrarAdapterMock->shouldReceive('renewDomain')
+ ->atLeast()->once();
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('_getD')
+ ->atLeast()->once()
+ ->andReturn([new Registrar_Domain(), $registrarAdapterMock]);
+ $serviceMock->shouldReceive('syncWhois')
+ ->atLeast()->once();
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn ($name) => $orderServiceMock);
+ $serviceMock->setDi($di);
+
+ $order = new Model_ClientOrder();
+ $order->loadBean(new Tests\Helpers\DummyBean());
+ $order->client_id = 1;
+ $result = $serviceMock->action_renew($order);
+
+ expect($result)->toBeTrue();
+});
+
+test('throws exception when renewing without order service', function (): void {
+ $service = new Service();
+ $orderServiceMock = Mockery::mock(OrderService::class);
+ $orderServiceMock->shouldReceive('getOrderService')
+ ->atLeast()->once()
+ ->andReturn(null);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn ($name) => $orderServiceMock);
+ $service->setDi($di);
+
+ $order = new Model_ClientOrder();
+ $order->loadBean(new Tests\Helpers\DummyBean());
+ $order->id = 1;
+ $order->client_id = 1;
+
+ expect(fn (): bool => $service->action_renew($order))
+ ->toThrow(FOSSBilling\Exception::class);
+});
+
+test('suspends action', function (): void {
+ $service = new Service();
+ $order = new Model_ClientOrder();
+ $order->loadBean(new Tests\Helpers\DummyBean());
+ $result = $service->action_suspend($order);
+ expect($result)->toBeTrue();
+});
+
+test('unsuspends action', function (): void {
+ $service = new Service();
+ $order = new Model_ClientOrder();
+ $order->loadBean(new Tests\Helpers\DummyBean());
+ $result = $service->action_unsuspend($order);
+ expect($result)->toBeTrue();
+});
+
+test('cancels action', function (): void {
+ $service = new Service();
+ $tldModel = new Model_Tld();
+ $tldModel->loadBean(new Tests\Helpers\DummyBean());
+ $tldModel->tld_registrar_id = 1;
+
+ $domainModel = new Model_ServiceDomain();
+ $domainModel->loadBean(new Tests\Helpers\DummyBean());
+ $domainModel->tld_registrar_id = 1;
+ $domainModel->action = 'register';
+
+ $orderServiceMock = Mockery::mock(OrderService::class);
+ $orderServiceMock->shouldReceive('getOrderService')
+ ->atLeast()->once()
+ ->andReturn($domainModel);
+
+ $registrarAdapterMock = Mockery::mock('Registrar_Adapter_Custom');
+ $registrarAdapterMock->shouldReceive('deleteDomain')
+ ->atLeast()->once();
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('_getD')
+ ->atLeast()->once()
+ ->andReturn([new Registrar_Domain(), $registrarAdapterMock]);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn ($name) => $orderServiceMock);
+ $serviceMock->setDi($di);
+
+ $order = new Model_ClientOrder();
+ $order->loadBean(new Tests\Helpers\DummyBean());
+ $order->client_id = 1;
+ $result = $serviceMock->action_cancel($order);
+
+ expect($result)->toBeTrue();
+});
+
+test('throws exception when canceling without order service', function (): void {
+ $service = new Service();
+ $orderServiceMock = Mockery::mock(OrderService::class);
+ $orderServiceMock->shouldReceive('getOrderService')
+ ->atLeast()->once()
+ ->andReturn(null);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn ($name) => $orderServiceMock);
+ $service->setDi($di);
+
+ $order = new Model_ClientOrder();
+ $order->loadBean(new Tests\Helpers\DummyBean());
+ $order->id = 1;
+ $order->client_id = 1;
+
+ expect(fn (): bool => $service->action_cancel($order))
+ ->toThrow(FOSSBilling\Exception::class);
+});
+
+test('uncancels action', function (): void {
+ $service = new Service();
+ $serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('action_activate')
+ ->atLeast()->once()
+ ->andReturn(null);
+
+ $order = new Model_ClientOrder();
+ $order->loadBean(new Tests\Helpers\DummyBean());
+ $order->client_id = 1;
+ $result = $serviceMock->action_uncancel($order);
+
+ expect($result)->toBeTrue();
+});
+
+test('deletes action', function (): void {
+ $service = new Service();
+ $tldModel = new Model_Tld();
+ $tldModel->loadBean(new Tests\Helpers\DummyBean());
+ $tldModel->tld_registrar_id = 1;
+
+ $domainModel = new Model_ServiceDomain();
+ $domainModel->loadBean(new Tests\Helpers\DummyBean());
+ $domainModel->tld_registrar_id = 1;
+ $domainModel->action = 'register';
+
+ $orderServiceMock = Mockery::mock(OrderService::class);
+ $orderServiceMock->shouldReceive('getOrderService')
+ ->atLeast()->once()
+ ->andReturn($domainModel);
+
+ $registrarAdapterMock = Mockery::mock('Registrar_Adapter_Custom');
+ $registrarAdapterMock->shouldReceive('deleteDomain')
+ ->atLeast()->once();
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('_getD')
+ ->atLeast()->once()
+ ->andReturn([new Registrar_Domain(), $registrarAdapterMock]);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('trash')
+ ->atLeast()->once()
+ ->andReturn(null);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn ($name) => $orderServiceMock);
+ $di['db'] = $dbMock;
+ $serviceMock->setDi($di);
+
+ $order = new Model_ClientOrder();
+ $order->loadBean(new Tests\Helpers\DummyBean());
+ $order->status = Model_ClientOrder::STATUS_ACTIVE;
+ $result = $serviceMock->action_delete($order);
+
+ expect($result)->toBeNull();
+});
+
+test('updates nameservers', function (): void {
+ $service = new Service();
+ $registrarAdapterMock = Mockery::mock('Registrar_Adapter_Custom');
+ $registrarAdapterMock->shouldReceive('modifyNs')
+ ->atLeast()->once();
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('_getD')
+ ->atLeast()->once()
+ ->andReturn([new Registrar_Domain(), $registrarAdapterMock]);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn(1);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $serviceMock->setDi($di);
+
+ $data = [
+ 'ns1' => 'ns1.example.com',
+ 'ns2' => 'ns2.example.com',
+ 'ns3' => 'ns3.example.com',
+ 'ns4' => 'ns4.example.com',
+ ];
+
+ $serviceDomainModel = new Model_ServiceDomain();
+ $serviceDomainModel->loadBean(new Tests\Helpers\DummyBean());
+ $result = $serviceMock->updateNameservers($serviceDomainModel, $data);
+
+ expect($result)->toBeTrue();
+});
+
+test('throws exception when updating nameservers with missing ns1 or ns2', function (array $data): void {
+ $service = new Service();
+ $serviceDomainModel = new Model_ServiceDomain();
+ $serviceDomainModel->loadBean(new Tests\Helpers\DummyBean());
+
+ expect(fn (): bool => $service->updateNameservers($serviceDomainModel, $data))
+ ->toThrow(FOSSBilling\Exception::class);
+})->with([
+ [['ns2' => 'ns2.example.com']],
+ [['ns1' => 'ns1.example.com']],
+]);
+
+test('updates contacts', function (): void {
+ $service = new Service();
+ $registrarAdapterMock = Mockery::mock('Registrar_Adapter_Custom');
+ $registrarAdapterMock->shouldReceive('modifyContact')
+ ->atLeast()->once();
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('_getD')
+ ->atLeast()->once()
+ ->andReturn([new Registrar_Domain(), $registrarAdapterMock]);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn(1);
+
+ $validatorMock = Mockery::mock(FOSSBilling\Validate::class);
+ $validatorMock->shouldReceive('checkRequiredParamsForArray')
+ ->zeroOrMoreTimes();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $di['validator'] = $validatorMock;
+ $serviceMock->setDi($di);
+
+ $data = [
+ 'contact' => [
+ 'first_name' => 'first_name',
+ 'last_name' => 'last_name',
+ 'email' => 'email',
+ 'company' => 'company',
+ 'address1' => 'address1',
+ 'address2' => 'address2',
+ 'country' => 'country',
+ 'city' => 'city',
+ 'state' => 'state',
+ 'postcode' => 'postcode',
+ 'phone_cc' => 'phone_cc',
+ 'phone' => 'phone',
+ ],
+ ];
+ $serviceDomainModel = new Model_ServiceDomain();
+ $serviceDomainModel->loadBean(new Tests\Helpers\DummyBean());
+ $result = $serviceMock->updateContacts($serviceDomainModel, $data);
+
+ expect($result)->toBeTrue();
+});
+
+test('gets transfer code', function (): void {
+ $service = new Service();
+ $epp = 'EPPCODE';
+
+ $registrarAdapterMock = Mockery::mock('Registrar_Adapter_Custom');
+ $registrarAdapterMock->shouldReceive('getEpp')
+ ->atLeast()->once()
+ ->andReturn($epp);
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('_getD')
+ ->atLeast()->once()
+ ->andReturn([new Registrar_Domain(), $registrarAdapterMock]);
+
+ $serviceDomainModel = new Model_ServiceDomain();
+ $serviceDomainModel->loadBean(new Tests\Helpers\DummyBean());
+ $result = $serviceMock->getTransferCode($serviceDomainModel);
+
+ expect($result)->toBeString();
+ expect($result)->toBe($epp);
+});
+
+test('locks domain', function (): void {
+ $service = new Service();
+ $registrarAdapterMock = Mockery::mock('Registrar_Adapter_Custom');
+ $registrarAdapterMock->shouldReceive('lock')
+ ->atLeast()->once();
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('_getD')
+ ->atLeast()->once()
+ ->andReturn([new Registrar_Domain(), $registrarAdapterMock]);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn(1);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $serviceMock->setDi($di);
+
+ $serviceDomainModel = new Model_ServiceDomain();
+ $serviceDomainModel->loadBean(new Tests\Helpers\DummyBean());
+ $result = $serviceMock->lock($serviceDomainModel);
+
+ expect($result)->toBeTrue();
+});
+
+test('unlocks domain', function (): void {
+ $service = new Service();
+ $registrarAdapterMock = Mockery::mock('Registrar_Adapter_Custom');
+ $registrarAdapterMock->shouldReceive('unlock')
+ ->atLeast()->once();
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('_getD')
+ ->atLeast()->once()
+ ->andReturn([new Registrar_Domain(), $registrarAdapterMock]);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn(1);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $serviceMock->setDi($di);
+
+ $serviceDomainModel = new Model_ServiceDomain();
+ $serviceDomainModel->loadBean(new Tests\Helpers\DummyBean());
+ $result = $serviceMock->unlock($serviceDomainModel);
+
+ expect($result)->toBeTrue();
+});
+
+test('enables privacy protection', function (): void {
+ $service = new Service();
+ $registrarAdapterMock = Mockery::mock('Registrar_Adapter_Custom');
+ $registrarAdapterMock->shouldReceive('enablePrivacyProtection')
+ ->atLeast()->once();
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('_getD')
+ ->atLeast()->once()
+ ->andReturn([new Registrar_Domain(), $registrarAdapterMock]);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn(1);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $serviceMock->setDi($di);
+
+ $serviceDomainModel = new Model_ServiceDomain();
+ $serviceDomainModel->loadBean(new Tests\Helpers\DummyBean());
+ $result = $serviceMock->enablePrivacyProtection($serviceDomainModel);
+
+ expect($result)->toBeTrue();
+});
+
+test('disables privacy protection', function (): void {
+ $service = new Service();
+ $registrarAdapterMock = Mockery::mock('Registrar_Adapter_Custom');
+ $registrarAdapterMock->shouldReceive('disablePrivacyProtection')
+ ->atLeast()->once();
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('_getD')
+ ->atLeast()->once()
+ ->andReturn([new Registrar_Domain(), $registrarAdapterMock]);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn(1);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $serviceMock->setDi($di);
+
+ $serviceDomainModel = new Model_ServiceDomain();
+ $serviceDomainModel->loadBean(new Tests\Helpers\DummyBean());
+ $result = $serviceMock->disablePrivacyProtection($serviceDomainModel);
+
+ expect($result)->toBeTrue();
+});
+
+test('checks if domain can be transferred', function (): void {
+ $service = new Service();
+ $registrarAdapterMock = Mockery::mock('Registrar_Adapter_Custom');
+ $registrarAdapterMock->shouldReceive('isDomaincanBeTransferred')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('registrarGetRegistrarAdapter')
+ ->atLeast()->once()
+ ->andReturn($registrarAdapterMock);
+
+ $tldRegistrar = new Model_TldRegistrar();
+ $tldRegistrar->loadBean(new Tests\Helpers\DummyBean());
+ $tldRegistrar->tld_registrar_id = 1;
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('load')
+ ->atLeast()->once()
+ ->andReturn($tldRegistrar);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $serviceMock->setDi($di);
+
+ $tld = new Model_Tld();
+ $tld->loadBean(new Tests\Helpers\DummyBean());
+ $tld->allow_transfer = true;
+ $tld->tld = '.com';
+ $tld->tld_registrar_id = 1;
+
+ $result = $serviceMock->canBeTransferred($tld, 'example');
+
+ expect($result)->toBeTrue();
+});
+
+test('throws exception when checking transfer with empty sld', function (): void {
+ $service = new Service();
+ expect(fn () => $service->canBeTransferred(new Model_Tld(), ''))
+ ->toThrow(FOSSBilling\Exception::class);
+});
+
+test('throws exception when checking transfer not allowed', function (): void {
+ $service = new Service();
+ $tldModel = new Model_Tld();
+ $tldModel->loadBean(new Tests\Helpers\DummyBean());
+ $tldModel->allow_transfer = false;
+
+ expect(fn () => $service->canBeTransferred($tldModel, 'example'))
+ ->toThrow(FOSSBilling\Exception::class);
+});
+
+test('checks if domain is available', function (): void {
+ $service = new Service();
+ $registrarAdapterMock = Mockery::mock('Registrar_Adapter_Custom');
+ $registrarAdapterMock->shouldReceive('isDomainAvailable')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('registrarGetRegistrarAdapter')
+ ->atLeast()->once()
+ ->andReturn($registrarAdapterMock);
+
+ $tldRegistrar = new Model_TldRegistrar();
+ $tldRegistrar->loadBean(new Tests\Helpers\DummyBean());
+ $tldRegistrar->tld_registrar_id = 1;
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('load')
+ ->atLeast()->once()
+ ->andReturn($tldRegistrar);
+
+ $validatorMock = Mockery::mock(FOSSBilling\Validate::class);
+ $validatorMock->shouldReceive('isSldValid')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['validator'] = $validatorMock;
+ $serviceMock->setDi($di);
+
+ $tld = new Model_Tld();
+ $tld->loadBean(new Tests\Helpers\DummyBean());
+ $tld->allow_register = true;
+ $tld->tld = '.com';
+ $tld->tld_registrar_id = 1;
+
+ $result = $serviceMock->isDomainAvailable($tld, 'example');
+
+ expect($result)->toBeTrue();
+});
+
+test('throws exception when checking availability with empty sld', function (): void {
+ $service = new Service();
+ $tldModel = new Model_Tld();
+ $tldModel->loadBean(new Tests\Helpers\DummyBean());
+
+ expect(fn () => $service->isDomainAvailable($tldModel, ''))
+ ->toThrow(FOSSBilling\Exception::class);
+});
+
+test('throws exception when checking availability with invalid sld', function (): void {
+ $service = new Service();
+ $validatorMock = Mockery::mock(FOSSBilling\Validate::class);
+ $validatorMock->shouldReceive('isSldValid')
+ ->atLeast()->once()
+ ->andReturn(false);
+
+ $di = container();
+ $di['validator'] = $validatorMock;
+ $service->setDi($di);
+
+ $tldModel = new Model_Tld();
+ $tldModel->loadBean(new Tests\Helpers\DummyBean());
+
+ expect(fn () => $service->isDomainAvailable($tldModel, 'example'))
+ ->toThrow(FOSSBilling\Exception::class);
+});
+
+test('throws exception when checking availability not allowed to register', function (): void {
+ $service = new Service();
+ $validatorMock = Mockery::mock(FOSSBilling\Validate::class);
+ $validatorMock->shouldReceive('isSldValid')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+ $di['validator'] = $validatorMock;
+ $service->setDi($di);
+
+ $model = new Model_Tld();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $model->allow_register = false;
+
+ expect(fn () => $service->isDomainAvailable($model, 'example'))
+ ->toThrow(FOSSBilling\Exception::class);
+});
+
+test('syncs expiration date', function (): void {
+ $service = new Service();
+ $model = new Model_ServiceDomain();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $result = $service->syncExpirationDate($model);
+
+ expect($result)->toBeNull();
+});
+
+test('converts to api array', function (?Model_Admin $identity, string $dbLoadCalled): void {
+ $service = new Service();
+ $model = new Model_ServiceDomain();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $model->sld = 'sld';
+ $model->tld = 'tld';
+ $model->ns1 = 'ns1.example.com';
+ $model->ns2 = 'ns2.example.com';
+ $model->ns3 = 'ns3.example.com';
+ $model->ns4 = 'ns4.example.com';
+ $model->period = 'period';
+ $model->privacy = 'privacy';
+ $model->locked = 'locked';
+ $model->registered_at = date('Y-m-d H:i:s');
+ $model->expires_at = date('Y-m-d H:i:s');
+
+ $model->contact_first_name = 'first_name';
+ $model->contact_last_name = 'last_name';
+ $model->contact_email = 'email';
+ $model->contact_company = 'company';
+ $model->contact_address1 = 'address1';
+ $model->contact_address2 = 'address2';
+ $model->contact_country = 'country';
+ $model->contact_city = 'city';
+ $model->contact_state = 'state';
+ $model->contact_postcode = 'postcode';
+ $model->contact_phone_cc = 'phone_cc';
+ $model->contact_phone = 'phone';
+ $model->transfer_code = 'EPPCODE';
+ $model->tld_registrar_id = 1;
+
+ $tldRegistrar = new Model_TldRegistrar();
+ $tldRegistrar->loadBean(new Tests\Helpers\DummyBean());
+ $tldRegistrar->name = 'ResellerClub';
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('load')
+ ->{$dbLoadCalled}()
+ ->andReturn($tldRegistrar);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $result = $service->toApiArray($model, true, $identity);
+
+ expect($result)->toBeArray();
+ expect($result)->toHaveKey('domain');
+ expect($result)->toHaveKey('sld');
+ expect($result)->toHaveKey('tld');
+ expect($result)->toHaveKey('ns1');
+ expect($result)->toHaveKey('ns2');
+ expect($result)->toHaveKey('ns3');
+ expect($result)->toHaveKey('ns4');
+ expect($result)->toHaveKey('period');
+ expect($result)->toHaveKey('privacy');
+ expect($result)->toHaveKey('locked');
+ expect($result)->toHaveKey('registered_at');
+ expect($result)->toHaveKey('expires_at');
+ expect($result)->toHaveKey('contact');
+
+ $contact = $result['contact'];
+ expect($contact)->toBeArray();
+ expect($contact)->toHaveKey('first_name');
+ expect($contact)->toHaveKey('last_name');
+ expect($contact)->toHaveKey('email');
+ expect($contact)->toHaveKey('company');
+ expect($contact)->toHaveKey('address1');
+ expect($contact)->toHaveKey('address2');
+ expect($contact)->toHaveKey('country');
+ expect($contact)->toHaveKey('city');
+ expect($contact)->toHaveKey('state');
+ expect($contact)->toHaveKey('postcode');
+ expect($contact)->toHaveKey('phone_cc');
+ expect($contact)->toHaveKey('phone');
+
+ expect($result['domain'])->toBe($model->sld . $model->tld);
+ expect($result['sld'])->toBe($model->sld);
+ expect($result['tld'])->toBe($model->tld);
+ expect($result['ns1'])->toBe($model->ns1);
+ expect($result['ns2'])->toBe($model->ns2);
+ expect($result['ns3'])->toBe($model->ns3);
+ expect($result['ns4'])->toBe($model->ns4);
+ expect($result['period'])->toBe($model->period);
+ expect($result['privacy'])->toBe($model->privacy);
+ expect($result['locked'])->toBe($model->locked);
+ expect($result['registered_at'])->toBe($model->registered_at);
+ expect($result['expires_at'])->toBe($model->expires_at);
+
+ expect($contact['first_name'])->toBe($model->contact_first_name);
+ expect($contact['last_name'])->toBe($model->contact_last_name);
+ expect($contact['email'])->toBe($model->contact_email);
+ expect($contact['company'])->toBe($model->contact_company);
+ expect($contact['address1'])->toBe($model->contact_address1);
+ expect($contact['address2'])->toBe($model->contact_address2);
+ expect($contact['country'])->toBe($model->contact_country);
+ expect($contact['city'])->toBe($model->contact_city);
+ expect($contact['state'])->toBe($model->contact_state);
+ expect($contact['postcode'])->toBe($model->contact_postcode);
+ expect($contact['phone_cc'])->toBe($model->contact_phone_cc);
+ expect($contact['phone'])->toBe($model->contact_phone);
+
+ if ($identity instanceof Model_Admin) {
+ expect($result)->toHaveKey('transfer_code');
+ expect($result)->toHaveKey('registrar');
+ expect($result['transfer_code'])->toBe($model->transfer_code);
+ expect($result['registrar'])->toBe($tldRegistrar->name);
+ }
+})->with([
+ [function () {
+ $model = new Model_Admin();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ return $model;
+ }, 'atLeast'],
+ [null, 'never'],
+]);
+
+test('handles on before admin cron run event', function (): void {
+ $service = new Service();
+ $di = container();
+ $serviceMock = Mockery::mock(Service::class);
+ $serviceMock->shouldReceive('batchSyncExpirationDates')
+ ->atLeast()->once()
+ ->andReturn(true);
+ $di['mod_service'] = $di->protect(fn ($serviceName): Mockery\MockInterface => $serviceMock);
+
+ $boxEventMock = Mockery::mock('\Box_Event');
+ $boxEventMock->shouldReceive('getDi')
+ ->atLeast()->once()
+ ->andReturn($di);
+
+ $result = $service->onBeforeAdminCronRun($boxEventMock);
+
+ expect($result)->toBeTrue();
+});
+
+test('batch syncs expiration dates', function (): void {
+ $service = new Service();
+ $serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('syncExpirationDate')
+ ->atLeast()->once();
+
+ $systemServiceMock = Mockery::mock(SystemService::class);
+ $systemServiceMock->shouldReceive('getParamValue')
+ ->atLeast()->once()
+ ->andReturn(null);
+ $systemServiceMock->shouldReceive('setParamValue')
+ ->atLeast()->once();
+
+ $domains = [
+ 'domain1.com',
+ 'domain2.com',
+ 'domain3.com',
+ 'domain4.com',
+ ];
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('find')
+ ->atLeast()->once()
+ ->andReturn($domains);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn ($name) => $systemServiceMock);
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $serviceMock->setDi($di);
+
+ $result = $serviceMock->batchSyncExpirationDates();
+
+ expect($result)->toBeTrue();
+});
+
+test('returns false when batch sync already run today', function (): void {
+ $service = new Service();
+ $systemServiceMock = Mockery::mock(SystemService::class);
+ $systemServiceMock->shouldReceive('getParamValue')
+ ->atLeast()->once()
+ ->andReturn(date('Y-m-d H:i:s'));
+ $systemServiceMock->shouldReceive('setParamValue')
+ ->never();
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('find')
+ ->never()
+ ->andReturn([]);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn ($name) => $systemServiceMock);
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $result = $service->batchSyncExpirationDates();
+
+ expect($result)->toBeFalse();
+});
+
+test('gets tld search query', function (array $data, string $expectedQuery, array $expectedBindings): void {
+ $service = new Service();
+ $di = container();
+
+ $service->setDi($di);
+ [$query, $bindings] = $service->tldGetSearchQuery($data);
+
+ expect($query)->toBe($expectedQuery);
+ expect($bindings)->toBeArray();
+ expect($bindings)->toBe($expectedBindings);
+})->with([
+ [
+ [],
+ 'SELECT * FROM tld ORDER BY id ASC',
+ [],
+ ],
+ [
+ ['hide_inactive' => true],
+ 'SELECT * FROM tld WHERE active = 1 ORDER BY id ASC',
+ [],
+ ],
+ [
+ ['allow_register' => true],
+ 'SELECT * FROM tld WHERE allow_register = 1 ORDER BY id ASC',
+ [],
+ ],
+ [
+ ['allow_transfer' => true],
+ 'SELECT * FROM tld WHERE allow_transfer = 1 ORDER BY id ASC',
+ [],
+ ],
+ [
+ ['hide_inactive' => true, 'allow_register' => true, 'allow_transfer' => true],
+ 'SELECT * FROM tld WHERE active = 1 AND allow_register = 1 AND allow_transfer = 1 ORDER BY id ASC',
+ [],
+ ],
+]);
+
+test('finds all active tlds', function (): void {
+ $service = new Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('find')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $result = $service->tldFindAllActive();
+
+ expect($result)->toBeArray();
+});
+
+test('finds one active tld by id', function (): void {
+ $service = new Service();
+ $tldModel = new Model_Tld();
+ $tldModel->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn($tldModel);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $result = $service->tldFindOneActiveById(1);
+
+ expect($result)->toBeInstanceOf(Model_Tld::class);
+});
+
+test('gets tld pairs', function (): void {
+ $service = new Service();
+ $returns = [
+ 0 => '.com',
+ ];
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getAssoc')
+ ->atLeast()->once()
+ ->andReturn($returns);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $result = $service->tldGetPairs();
+
+ expect($result)->toBeArray();
+ expect($result)->toBe($returns);
+});
+
+test('checks if tld is already registered', function (): void {
+ $service = new Service();
+ $tldModel = new Model_Tld();
+ $tldModel->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn($tldModel);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $result = $service->tldAlreadyRegistered('.com');
+
+ expect($result)->toBeTrue();
+});
+
+test('checks if tld is not registered', function (): void {
+ $service = new Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn(null);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $result = $service->tldAlreadyRegistered('.com');
+
+ expect($result)->toBeFalse();
+});
+
+test('removes tld', function (): void {
+ $service = new Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('trash')
+ ->atLeast()->once()
+ ->andReturn(null);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $service->setDi($di);
+
+ $model = new Model_Tld();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $model->id = 1;
+
+ $result = $service->tldRm($model);
+
+ expect($result)->toBeTrue();
+});
+
+test('converts tld to api array', function (): void {
+ $service = new Service();
+ $tldRegistrar = new Model_TldRegistrar();
+ $tldRegistrar->loadBean(new Tests\Helpers\DummyBean());
+ $tldRegistrar->name = 'ResellerClub';
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('load')
+ ->atLeast()->once()
+ ->andReturn($tldRegistrar);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $model = new Model_Tld();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $model->tld = '.com';
+ $model->price_registration = 1;
+ $model->price_renew = 1;
+ $model->price_transfer = 1;
+ $model->active = 1;
+ $model->allow_register = 1;
+ $model->allow_transfer = 1;
+ $model->min_years = 2;
+ $model->tld_registrar_id = 1;
+
+ $result = $service->tldToApiArray($model, new Model_Admin());
+ expect($result)->toBeArray();
+
+ expect($result)->toHaveKey('tld');
+ expect($result)->toHaveKey('price_registration');
+ expect($result)->toHaveKey('price_renew');
+ expect($result)->toHaveKey('price_transfer');
+ expect($result)->toHaveKey('active');
+ expect($result)->toHaveKey('allow_register');
+ expect($result)->toHaveKey('allow_transfer');
+ expect($result)->toHaveKey('min_years');
+ expect($result)->toHaveKey('registrar');
+
+ $registrar = $result['registrar'];
+ expect($registrar)->toBeArray();
+ expect($registrar)->toHaveKey('id');
+ expect($registrar)->toHaveKey('title');
+
+ expect($result['tld'])->toBe($model->tld);
+ expect($result['price_registration'])->toBe($model->price_registration);
+ expect($result['price_renew'])->toBe($model->price_renew);
+ expect($result['price_transfer'])->toBe($model->price_transfer);
+ expect($result['active'])->toBe($model->active);
+ expect($result['allow_register'])->toBe($model->allow_register);
+ expect($result['allow_transfer'])->toBe($model->allow_transfer);
+ expect($result['min_years'])->toBe($model->min_years);
+
+ expect($registrar['id'])->toBe($model->tld_registrar_id);
+ expect($registrar['title'])->toBe($tldRegistrar->name);
+});
+
+test('finds one tld by tld', function (): void {
+ $service = new Service();
+ $tldModel = new Model_Tld();
+ $tldModel->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn($tldModel);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $result = $service->tldFindOneByTld('.com');
+
+ expect($result)->toBeInstanceOf(Model_Tld::class);
+});
+
+test('gets registrar search query', function (): void {
+ $service = new Service();
+ [$query, $bindings] = $service->registrarGetSearchQuery([]);
+
+ expect($query)->toBe('SELECT * FROM tld_registrar ORDER BY name ASC');
+ expect($bindings)->toBeArray();
+ expect($bindings)->toBe([]);
+});
+
+test('gets available registrars', function (): void {
+ $service = new Service();
+ $registrars = [
+ 'Resellerclub' => 'Reseller Club',
+ ];
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getAssoc')
+ ->atLeast()->once()
+ ->andReturn($registrars);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $result = $service->registrarGetAvailable();
+ expect($result)->toBeArray();
+});
+
+test('gets registrar pairs', function (): void {
+ $service = new Service();
+ $registrars = [
+ 1 => 'Resellerclub',
+ 2 => 'Email',
+ 3 => 'Custom',
+ ];
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getAssoc')
+ ->atLeast()->once()
+ ->andReturn($registrars);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $result = $service->registrarGetPairs();
+
+ expect($result)->toBeArray();
+ expect($result)->toHaveCount(3);
+});
+
+test('gets active registrar', function (): void {
+ $service = new Service();
+ $tldRegistrarModel = new Model_TldRegistrar();
+ $tldRegistrarModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn($tldRegistrarModel);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $result = $service->registrarGetActiveRegistrar();
+
+ expect($result)->toBeInstanceOf(Model_TldRegistrar::class);
+});
+
+test('gets registrar configuration', function (): void {
+ $service = new Service();
+ $config = [
+ 'config_param' => 'config_value',
+ ];
+
+ $di = container();
+ $service->setDi($di);
+
+ $model = new Model_TldRegistrar();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $model->config = json_encode($config);
+
+ $result = $service->registrarGetConfiguration($model);
+
+ expect($result)->toBeArray();
+ expect($result)->toBe($config);
+});
+
+test('gets registrar adapter config', function (): void {
+ $service = new Service();
+ $model = new Model_TldRegistrar();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $model->registrar = 'Custom';
+
+ $result = $service->registrarGetRegistrarAdapterConfig($model);
+ expect($result)->toBeArray();
+});
+
+test('throws exception when getting registrar adapter config for non-existing registrar', function (): void {
+ $service = new Service();
+ $model = new Model_TldRegistrar();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $model->registrar = 'NonExisting';
+
+ expect(fn () => $service->registrarGetRegistrarAdapterConfig($model))
+ ->toThrow(FOSSBilling\Exception::class);
+});
+
+test('gets registrar adapter', function (): void {
+ $service = new Service();
+ $di = container();
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $service->setDi($di);
+ $model = new Model_TldRegistrar();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $model->registrar = 'Custom';
+
+ $result = $service->registrarGetRegistrarAdapter($model);
+
+ expect($result)->toBeInstanceOf('Registrar_Adapter_' . $model->registrar);
+});
+
+test('throws exception when getting registrar adapter for non-existing registrar', function (): void {
+ $service = new Service();
+ $serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('registrarGetConfiguration')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $model = new Model_TldRegistrar();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $model->registrar = 'NonExisting';
+
+ expect(fn () => $serviceMock->registrarGetRegistrarAdapter($model))
+ ->toThrow(Error::class);
+});
+
+test('removes registrar', function (): void {
+ $service = new Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('find')
+ ->atLeast()->once()
+ ->andReturn([]);
+ $dbMock->shouldReceive('trash')
+ ->atLeast()->once()
+ ->andReturn(null);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $service->setDi($di);
+
+ $model = new Model_TldRegistrar();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $model->id = 1;
+ $model->name = 'ResellerClub';
+
+ $result = $service->registrarRm($model);
+
+ expect($result)->toBeTrue();
+});
+
+test('throws exception when removing registrar with domains', function (): void {
+ $service = new Service();
+ $serviceDomainModel = new Model_ServiceDomain();
+ $serviceDomainModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('find')
+ ->with('ServiceDomain', 'tld_registrar_id = :registrar_id', [':registrar_id' => 1])
+ ->atLeast()->once()
+ ->andReturn([$serviceDomainModel]);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $service->setDi($di);
+
+ $model = new Model_TldRegistrar();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $model->id = 1;
+
+ expect(fn (): bool => $service->registrarRm($model))
+ ->toThrow(FOSSBilling\InformationException::class, 'Registrar is used by 1 domains');
+});
+
+test('converts registrar to api array', function (): void {
+ $service = new Service();
+ $config = [
+ 'label' => 'Label',
+ 'form' => 1,
+ ];
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('registrarGetRegistrarAdapterConfig')
+ ->atLeast()->once()
+ ->andReturn($config);
+ $serviceMock->shouldReceive('registrarGetConfiguration')
+ ->atLeast()->once()
+ ->andReturn(['param1' => 'value1']);
+
+ $model = new Model_TldRegistrar();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $model->id = 1;
+ $model->name = 'ResellerClub';
+ $model->test_mode = true;
+
+ $serviceMock->registrarToApiArray($model);
+});
+
+test('creates tld', function (): void {
+ $service = new Service();
+ $data = [
+ 'tld' => '.com',
+ 'tld_registrar_id' => 1,
+ 'price_registration' => 1,
+ 'price_renew' => 1,
+ 'price_transfer' => 1,
+ 'min_years' => random_int(1, 5),
+ 'allow_register' => 1,
+ 'allow_transfer' => 1,
+ 'updated_at' => date('Y-m-d H:i:s'),
+ 'created_at' => date('Y-m-d H:i:s'),
+ ];
+
+ $randId = 1;
+
+ $tldModel = new Model_Tld();
+ $tldModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn($randId);
+ $dbMock->shouldReceive('dispense')
+ ->atLeast()->once()
+ ->andReturn($tldModel);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $service->setDi($di);
+
+ $result = $service->tldCreate($data);
+
+ expect($result)->toBeInt();
+ expect($result)->toBe($randId);
+});
+
+test('updates tld', function (): void {
+ $service = new Service();
+ $data = [
+ 'tld' => '.com',
+ 'tld_registrar_id' => 1,
+ 'price_registration' => 1,
+ 'price_renew' => 1,
+ 'price_transfer' => 1,
+ 'min_years' => random_int(1, 5),
+ 'allow_register' => true,
+ 'allow_transfer' => true,
+ 'active' => true,
+ 'updated_at' => date('Y-m-d H:i:s'),
+ 'created_at' => date('Y-m-d H:i:s'),
+ ];
+
+ $randId = 1;
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn($randId);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $service->setDi($di);
+
+ $model = new Model_Tld();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $model->tld = '.com';
+
+ $result = $service->tldUpdate($model, $data);
+
+ expect($result)->toBeTrue();
+});
+
+test('creates registrar', function (): void {
+ $service = new Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn(1);
+
+ $model = new Model_TldRegistrar();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock->shouldReceive('dispense')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $service->setDi($di);
+
+ $result = $service->registrarCreate('ResellerClub');
+
+ expect($result)->toBeTrue();
+});
+
+test('copies registrar', function (): void {
+ $service = new Service();
+ $newId = 1;
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn($newId);
+
+ $model = new Model_TldRegistrar();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock->shouldReceive('dispense')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $service->setDi($di);
+
+ $model = new Model_TldRegistrar();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $model->name = 'ResellerClub';
+ $model->registrar = 'ResellerClub';
+ $model->test_mode = 1;
+
+ $result = $service->registrarCopy($model);
+
+ expect($result)->toBeInt();
+ expect($result)->toBe($newId);
+});
+
+test('updates registrar', function (): void {
+ $service = new Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn(1);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $service->setDi($di);
+
+ $data = [
+ 'title' => 'ResellerClub',
+ 'test_mode' => 1,
+ 'config' => [
+ 'param1' => 'value1',
+ ],
+ ];
+
+ $model = new Model_TldRegistrar();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $model->registrar = 'Custom';
+
+ $result = $service->registrarUpdate($model, $data);
+
+ expect($result)->toBeTrue();
+});
+
+test('updates domain', function (): void {
+ $service = new Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn(1);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $service->setDi($di);
+
+ $data = [
+ 'ns1' => 'ns1.example.com',
+ 'ns2' => 'ns2.example.com',
+ 'ns3' => 'ns3.example.com',
+ 'ns4' => 'ns4.example.com',
+ 'period' => 1,
+ 'privacy' => 1,
+ 'locked' => 1,
+ 'transfer_code' => 'EPPCODE',
+ ];
+
+ $model = new Model_ServiceDomain();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $model->id = 1;
+
+ $result = $service->updateDomain($model, $data);
+
+ expect($result)->toBeTrue();
+});
diff --git a/src/modules/Servicedownloadable/Api/Admin.php b/src/modules/Servicedownloadable/Api/Admin.php
index 40dc32250..4e3a1e155 100644
--- a/src/modules/Servicedownloadable/Api/Admin.php
+++ b/src/modules/Servicedownloadable/Api/Admin.php
@@ -29,11 +29,11 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Product ID was not passed'])]
public function upload($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('servicedownloadable', 'manage');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('servicedownloadable', 'manage');
- $model = $this->di['db']->getExistingModelById('Product', $data['id'], 'Product not found');
+ $model = $this->getDi()['db']->getExistingModelById('Product', $data['id'], 'Product not found');
- $request = $this->di['request'];
+ $request = $this->getDi()['request'];
if (!$request->files->has('file_data')) {
throw new \FOSSBilling\Exception('File was not uploaded.');
}
@@ -55,11 +55,11 @@ class Admin extends \Api_Abstract
#[RequiredParams(['order_id' => 'Order ID (order_id) was not passed'])]
public function update($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('servicedownloadable', 'manage');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('servicedownloadable', 'manage');
- $order = $this->di['db']->getExistingModelById('ClientOrder', $data['order_id'], 'Order not found');
+ $order = $this->getDi()['db']->getExistingModelById('ClientOrder', $data['order_id'], 'Order not found');
- $orderService = $this->di['mod_service']('order');
+ $orderService = $this->getDi()['mod_service']('order');
$serviceDownloadable = $orderService->getOrderService($order);
if (!$serviceDownloadable instanceof \Model_ServiceDownloadable) {
throw new \FOSSBilling\Exception('Order is not activated');
@@ -77,9 +77,9 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Product ID was not passed'])]
public function config_save($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('servicedownloadable', 'manage');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('servicedownloadable', 'manage');
- $model = $this->di['db']->getExistingModelById('Product', $data['id'], 'Product not found');
+ $model = $this->getDi()['db']->getExistingModelById('Product', $data['id'], 'Product not found');
$service = $this->getService();
@@ -98,9 +98,9 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Product ID was not passed'])]
public function send_file($data): Response
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('servicedownloadable', 'manage');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('servicedownloadable', 'manage');
- $model = $this->di['db']->getExistingModelById('Product', $data['id'], 'Product not found');
+ $model = $this->getDi()['db']->getExistingModelById('Product', $data['id'], 'Product not found');
$service = $this->getService();
diff --git a/src/modules/Servicedownloadable/Api/Client.php b/src/modules/Servicedownloadable/Api/Client.php
index cb83a2d24..6e2ceb68a 100644
--- a/src/modules/Servicedownloadable/Api/Client.php
+++ b/src/modules/Servicedownloadable/Api/Client.php
@@ -32,12 +32,12 @@ class Client extends \Api_Abstract
}
$identity = $this->getIdentity();
- $order = $this->di['db']->findOne('ClientOrder', 'id = :id AND client_id = :client_id', [':id' => $data['order_id'], ':client_id' => $identity->id]);
+ $order = $this->getDi()['db']->findOne('ClientOrder', 'id = :id AND client_id = :client_id', [':id' => $data['order_id'], ':client_id' => $identity->id]);
if (!$order instanceof \Model_ClientOrder) {
throw new \FOSSBilling\Exception('Order not found');
}
- $orderService = $this->di['mod_service']('order');
+ $orderService = $this->getDi()['mod_service']('order');
$s = $orderService->getOrderService($order);
if (!$s instanceof \Model_ServiceDownloadable || $order->status !== 'active') {
throw new \FOSSBilling\Exception('Order is not activated');
diff --git a/src/modules/Servicedownloadable/Service.php b/src/modules/Servicedownloadable/Service.php
index d87622933..ce968dbd8 100644
--- a/src/modules/Servicedownloadable/Service.php
+++ b/src/modules/Servicedownloadable/Service.php
@@ -153,7 +153,7 @@ class Service implements InjectionAwareInterface
$this->di['validator']->checkRequiredParamsForArray($required, $config);
$data['filename'] = $config['filename'];
- $data[self::STORED_FILENAME_CONFIG_KEY] = $this->validateStoredFilename($config[self::STORED_FILENAME_CONFIG_KEY]);
+ $data[self::STORED_FILENAME_CONFIG_KEY] = $this->validateStoredFilename($config[self::STORED_FILENAME_CONFIG_KEY] ?? null);
return array_merge($config, $data);
}
@@ -165,7 +165,7 @@ class Service implements InjectionAwareInterface
self::STORED_FILENAME_CONFIG_KEY => 'Stored filename is missing in product config',
];
$this->di['validator']->checkRequiredParamsForArray($required, $data);
- $data[self::STORED_FILENAME_CONFIG_KEY] = $this->validateStoredFilename($data[self::STORED_FILENAME_CONFIG_KEY]);
+ $data[self::STORED_FILENAME_CONFIG_KEY] = $this->validateStoredFilename($data[self::STORED_FILENAME_CONFIG_KEY] ?? null);
}
/**
diff --git a/src/modules/Servicedownloadable/tests/Unit/Api/AdminTest.php b/src/modules/Servicedownloadable/tests/Unit/Api/AdminTest.php
new file mode 100644
index 000000000..d667907a3
--- /dev/null
+++ b/src/modules/Servicedownloadable/tests/Unit/Api/AdminTest.php
@@ -0,0 +1,262 @@
+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/Api/ClientTest.php b/src/modules/Servicedownloadable/tests/Unit/Api/ClientTest.php
new file mode 100644
index 000000000..e4c6f622c
--- /dev/null
+++ b/src/modules/Servicedownloadable/tests/Unit/Api/ClientTest.php
@@ -0,0 +1,127 @@
+setDi($di);
+ $getDi = $api->getDi();
+ expect($getDi)->toBe($di);
+});
+
+test('throws exception when sending file with missing order id', function (): void {
+ $api = new Box\Mod\Servicedownloadable\Api\Client();
+ $data = [];
+
+ expect(fn (): bool => $api->send_file($data))
+ ->toThrow(FOSSBilling\Exception::class, 'Order ID is required');
+});
+
+test('throws exception when sending file with order not found', function (): void {
+ $api = new Box\Mod\Servicedownloadable\Api\Client();
+ $data = [
+ 'order_id' => 1,
+ ];
+
+ $modelClient = new Model_Client();
+ $modelClient->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('findOne')->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $api->setIdentity($modelClient);
+ $api->setDi($di);
+
+ expect(fn (): bool => $api->send_file($data))
+ ->toThrow(FOSSBilling\Exception::class, 'Order not found');
+});
+
+test('throws exception when sending file with order not activated', function (): void {
+ $api = new Box\Mod\Servicedownloadable\Api\Client();
+ $data = [
+ 'order_id' => 1,
+ ];
+
+ $modelClient = new Model_Client();
+ $modelClient->loadBean(new Tests\Helpers\DummyBean());
+
+ $orderServiceMock = Mockery::mock(Box\Mod\Order\Service::class);
+ $orderServiceMock->shouldReceive('getOrderService')->atLeast()->once();
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('findOne')
+ ->atLeast()
+ ->once()
+ ->andReturn(new Model_ClientOrder());
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(moduleService(['order' => $orderServiceMock]));
+
+ $api->setDi($di);
+ $api->setIdentity($modelClient);
+
+ expect(fn (): bool => $api->send_file($data))
+ ->toThrow(FOSSBilling\Exception::class, 'Order is not activated');
+});
+
+test('sends file', function (): void {
+ $api = new Box\Mod\Servicedownloadable\Api\Client();
+ $data = [
+ 'order_id' => 1,
+ ];
+
+ $modelClient = new Model_Client();
+ $modelClient->loadBean(new Tests\Helpers\DummyBean());
+
+ $serviceMock = Mockery::mock(Box\Mod\Servicedownloadable\Service::class);
+ $response = new Response('download');
+ $serviceMock->shouldReceive('sendFile')
+ ->atLeast()
+ ->once()
+ ->andReturn($response);
+
+ $orderServiceMock = Mockery::mock(Box\Mod\Order\Service::class);
+ $orderServiceMock->shouldReceive('getOrderService')
+ ->atLeast()
+ ->once()
+ ->andReturn(new Model_ServiceDownloadable());
+
+ $mockOrder = new Model_ClientOrder();
+ $mockOrder->loadBean(new Tests\Helpers\DummyBean());
+ $mockOrder->status = 'active';
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('findOne')
+ ->atLeast()
+ ->once()
+ ->andReturn($mockOrder);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(moduleService(['order' => $orderServiceMock]));
+
+ $api->setDi($di);
+ $api->setIdentity($modelClient);
+ $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
new file mode 100644
index 000000000..7718726dc
--- /dev/null
+++ b/src/modules/Servicedownloadable/tests/Unit/ServiceTest.php
@@ -0,0 +1,201 @@
+setDi($di);
+ $getDi = $service->getDi();
+ expect($getDi)->toBe($di);
+});
+
+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,
+ ]);
+
+ $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 {
+ $service = new Service();
+ $clientOrderModel = new Model_ClientOrder();
+
+ $orderServiceMock = Mockery::mock(OrderService::class);
+ $orderServiceMock->shouldReceive('getOrderService')
+ ->atLeast()->once()
+ ->andReturn(new Model_ServiceDownloadable());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('trash')
+ ->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(moduleService(['order' => $orderServiceMock]));
+
+ $service->setDi($di);
+ $service->action_delete($clientOrderModel);
+});
+
+test('saves 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);
+
+ $di = new Pimple\Container();
+ $di['db'] = $dbMock;
+
+ $service->setDi($di);
+ $result = $service->saveProductConfig($productModel, $data);
+
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+
+ $updatedConfig = json_decode($productModel->config, true);
+ expect($updatedConfig)->toBeArray();
+ expect($updatedConfig['filename'])->toBe('test.txt');
+ expect($updatedConfig['update_orders'])->toBeTrue();
+ expect($productModel->updated_at)->not->toBeNull();
+});
+
+test('saves 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);
+
+ $di = new Pimple\Container();
+ $di['db'] = $dbMock;
+
+ $service->setDi($di);
+ $result = $service->saveProductConfig($productModel, $data);
+
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+
+ $updatedConfig = json_decode($productModel->config, true);
+ expect($updatedConfig)->toBeArray();
+ expect($updatedConfig['filename'])->toBe('existing.txt');
+ expect($updatedConfig['update_orders'])->toBeFalse();
+ expect($productModel->updated_at)->not->toBeNull();
+});
+
+test('saves 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);
+
+ $di = new Pimple\Container();
+ $di['db'] = $dbMock;
+
+ $service->setDi($di);
+ $result = $service->saveProductConfig($productModel, $data);
+
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+
+ $updatedConfig = json_decode((string) $productModel->config, true);
+ expect($updatedConfig)->toBeArray();
+ expect($updatedConfig['update_orders'])->toBeTrue();
+ expect($productModel->updated_at)->not->toBeNull();
+});
diff --git a/src/modules/Servicehosting/Api/Admin.php b/src/modules/Servicehosting/Api/Admin.php
index d6d1e621d..9b1287f5d 100644
--- a/src/modules/Servicehosting/Api/Admin.php
+++ b/src/modules/Servicehosting/Api/Admin.php
@@ -27,10 +27,14 @@ class Admin extends \Api_Abstract
#[RequiredParams(['plan_id' => 'plan_id is missing'])]
public function change_plan($data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('servicehosting', 'manage_accounts');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('servicehosting', 'manage_accounts');
+
+ if (!isset($data['plan_id'])) {
+ throw new \FOSSBilling\Exception('plan_id is missing');
+ }
[$order, $s] = $this->_getService($data);
- $plan = $this->di['db']->getExistingModelById('ServiceHostingHp', $data['plan_id'], 'Hosting plan not found');
+ $plan = $this->getDi()['db']->getExistingModelById('ServiceHostingHp', $data['plan_id'], 'Hosting plan not found');
$service = $this->getService();
@@ -42,7 +46,7 @@ class Admin extends \Api_Abstract
*/
public function change_username($data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('servicehosting', 'manage_accounts');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('servicehosting', 'manage_accounts');
[$order, $s] = $this->_getService($data);
$service = $this->getService();
@@ -55,7 +59,7 @@ class Admin extends \Api_Abstract
*/
public function change_ip($data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('servicehosting', 'manage_accounts');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('servicehosting', 'manage_accounts');
[$order, $s] = $this->_getService($data);
$service = $this->getService();
@@ -68,7 +72,7 @@ class Admin extends \Api_Abstract
*/
public function change_domain($data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('servicehosting', 'manage_accounts');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('servicehosting', 'manage_accounts');
[$order, $s] = $this->_getService($data);
$service = $this->getService();
@@ -81,7 +85,7 @@ class Admin extends \Api_Abstract
*/
public function change_password($data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('servicehosting', 'manage_accounts');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('servicehosting', 'manage_accounts');
[$order, $s] = $this->_getService($data);
$service = $this->getService();
@@ -94,7 +98,7 @@ class Admin extends \Api_Abstract
*/
public function sync($data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('servicehosting', 'manage_accounts');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('servicehosting', 'manage_accounts');
[$order, $s] = $this->_getService($data);
$service = $this->getService();
@@ -111,7 +115,7 @@ class Admin extends \Api_Abstract
*/
public function update($data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('servicehosting', 'manage_accounts');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('servicehosting', 'manage_accounts');
[, $s] = $this->_getService($data);
$service = $this->getService();
@@ -126,7 +130,7 @@ class Admin extends \Api_Abstract
*/
public function manager_get_pairs($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('servicehosting', 'view_servers');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('servicehosting', 'view_servers');
return $this->getService()->getServerManagers();
}
@@ -138,7 +142,7 @@ class Admin extends \Api_Abstract
*/
public function server_get_pairs($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('servicehosting', 'view_servers');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('servicehosting', 'view_servers');
return $this->getService()->getServerPairs();
}
@@ -150,12 +154,12 @@ class Admin extends \Api_Abstract
*/
public function server_get_list($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('servicehosting', 'view_servers');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('servicehosting', 'view_servers');
[$sql, $params] = $this->getService()->getServersSearchQuery($data);
- $result = $this->di['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
+ $result = $this->getDi()['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
foreach ($result['list'] as $key => $server) {
- $bean = $this->di['db']->dispense('ServiceHostingServer')->unbox();
+ $bean = $this->getDi()['db']->dispense('ServiceHostingServer')->unbox();
$bean->import($server);
$model = $bean->box();
@@ -174,17 +178,17 @@ class Admin extends \Api_Abstract
*/
public function account_get_list($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('servicehosting', 'view_servers');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('servicehosting', 'view_servers');
[$sql, $params] = $this->getService()->getAccountsSearchQuery($data);
- $result = $this->di['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
- $orderService = $this->di['mod_service']('order');
+ $result = $this->getDi()['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
+ $orderService = $this->getDi()['mod_service']('order');
foreach ($result['list'] as $key => $account) {
- $bean = $this->di['db']->dispense('ServiceHosting')->unbox();
+ $bean = $this->getDi()['db']->dispense('ServiceHosting')->unbox();
$bean->import($account);
$model = $bean->box();
- $order = $this->di['db']->findOne('ClientOrder', 'service_type = "hosting" AND service_id = :service_id', [':service_id' => $model->id]);
+ $order = $this->getDi()['db']->findOne('ClientOrder', 'service_type = "hosting" AND service_id = :service_id', [':service_id' => $model->id]);
$result['list'][$key] = $this->getService()->toHostingAccountApiArray($model, true, $this->getIdentity());
@@ -229,7 +233,7 @@ class Admin extends \Api_Abstract
])]
public function server_create($data): int
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('servicehosting', 'manage_servers');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('servicehosting', 'manage_servers');
$service = $this->getService();
@@ -251,9 +255,9 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Server ID was not passed'])]
public function server_get($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('servicehosting', 'view_servers');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('servicehosting', 'view_servers');
- $model = $this->di['db']->getExistingModelById('ServiceHostingServer', $data['id'], 'Server not found');
+ $model = $this->getDi()['db']->getExistingModelById('ServiceHostingServer', $data['id'], 'Server not found');
$service = $this->getService();
return $service->toHostingServerApiArray($model, true, $this->getIdentity());
@@ -267,12 +271,12 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Server ID was not passed'])]
public function server_delete($data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('servicehosting', 'manage_servers');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('servicehosting', 'manage_servers');
- $model = $this->di['db']->getExistingModelById('ServiceHostingServer', $data['id'], 'Server not found');
+ $model = $this->getDi()['db']->getExistingModelById('ServiceHostingServer', $data['id'], 'Server not found');
// check if server is not used by any service_hostings
- $hosting_services = $this->di['db']->find('ServiceHosting', 'service_hosting_server_id = :server_id', [':server_id' => $data['id']]);
+ $hosting_services = $this->getDi()['db']->find('ServiceHosting', 'service_hosting_server_id = :server_id', [':server_id' => $data['id']]);
$count = is_array($hosting_services) ? count($hosting_services) : 0; // Handle the case where $hosting_services might be null
if ($count > 0) {
@@ -305,9 +309,9 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Server ID was not passed'])]
public function server_update($data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('servicehosting', 'manage_servers');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('servicehosting', 'manage_servers');
- $model = $this->di['db']->getExistingModelById('ServiceHostingServer', $data['id'], 'Server not found');
+ $model = $this->getDi()['db']->getExistingModelById('ServiceHostingServer', $data['id'], 'Server not found');
$service = $this->getService();
$existingConfig = json_decode($model->config ?? '', true) ?? [];
@@ -327,9 +331,9 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Server ID was not passed'])]
public function server_test_connection($data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('servicehosting', 'manage_servers');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('servicehosting', 'manage_servers');
- $model = $this->di['db']->getExistingModelById('ServiceHostingServer', $data['id'], 'Server not found');
+ $model = $this->getDi()['db']->getExistingModelById('ServiceHostingServer', $data['id'], 'Server not found');
return (bool) $this->getService()->testConnection($model);
}
@@ -341,7 +345,7 @@ class Admin extends \Api_Abstract
*/
public function hp_get_pairs($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('servicehosting', 'manage_plans');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('servicehosting', 'manage_plans');
return $this->getService()->getHpPairs();
}
@@ -353,12 +357,12 @@ class Admin extends \Api_Abstract
*/
public function hp_get_list($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('servicehosting', 'manage_plans');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('servicehosting', 'manage_plans');
[$sql, $params] = $this->getService()->getHpSearchQuery($data);
- $pager = $this->di['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
+ $pager = $this->getDi()['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
foreach ($pager['list'] as $key => $item) {
- $model = $this->di['db']->getExistingModelById('ServiceHostingHp', $item['id'], 'Post not found');
+ $model = $this->getDi()['db']->getExistingModelById('ServiceHostingHp', $item['id'], 'Post not found');
$pager['list'][$key] = $this->getService()->toHostingHpApiArray($model, false, $this->getIdentity());
}
@@ -373,12 +377,12 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Hosting plan ID was not passed'])]
public function hp_delete($data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('servicehosting', 'manage_plans');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('servicehosting', 'manage_plans');
- $model = $this->di['db']->getExistingModelById('ServiceHostingHp', $data['id'], 'Hosting plan not found');
+ $model = $this->getDi()['db']->getExistingModelById('ServiceHostingHp', $data['id'], 'Hosting plan not found');
// check if hosting plan is not used by any service_hostings
- $hosting_services = $this->di['db']->find('ServiceHosting', 'service_hosting_hp_id = :hp_id', [':hp_id' => $data['id']]);
+ $hosting_services = $this->getDi()['db']->find('ServiceHosting', 'service_hosting_hp_id = :hp_id', [':hp_id' => $data['id']]);
// Ensure $hosting_services is an array before counting its elements
$count = is_array($hosting_services) ? count($hosting_services) : 0; // Handle the case where $hosting_services might be null
@@ -399,9 +403,9 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Hosting plan ID was not passed'])]
public function hp_get($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('servicehosting', 'manage_plans');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('servicehosting', 'manage_plans');
- $model = $this->di['db']->getExistingModelById('ServiceHostingHp', $data['id'], 'Hosting plan not found');
+ $model = $this->getDi()['db']->getExistingModelById('ServiceHostingHp', $data['id'], 'Hosting plan not found');
return $this->getService()->toHostingHpApiArray($model, true, $this->getIdentity());
}
@@ -416,9 +420,9 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Hosting plan ID was not passed'])]
public function hp_update($data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('servicehosting', 'manage_plans');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('servicehosting', 'manage_plans');
- $model = $this->di['db']->getExistingModelById('ServiceHostingHp', $data['id'], 'Hosting plan not found');
+ $model = $this->getDi()['db']->getExistingModelById('ServiceHostingHp', $data['id'], 'Hosting plan not found');
$service = $this->getService();
@@ -435,7 +439,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['name' => 'Hosting plan name was not passed'])]
public function hp_create($data): int
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('servicehosting', 'manage_plans');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('servicehosting', 'manage_plans');
$service = $this->getService();
@@ -447,10 +451,10 @@ class Admin extends \Api_Abstract
$required = [
'order_id' => 'Order ID name is missing',
];
- $this->di['validator']->checkRequiredParamsForArray($required, $data);
+ $this->getDi()['validator']->checkRequiredParamsForArray($required, $data);
- $order = $this->di['db']->getExistingModelById('ClientOrder', $data['order_id'], 'Order not found');
- $orderService = $this->di['mod_service']('order');
+ $order = $this->getDi()['db']->getExistingModelById('ClientOrder', $data['order_id'], 'Order not found');
+ $orderService = $this->getDi()['mod_service']('order');
$s = $orderService->getOrderService($order);
if (!$s instanceof \Model_ServiceHosting) {
throw new \FOSSBilling\Exception('Order is not activated');
diff --git a/src/modules/Servicehosting/Api/Client.php b/src/modules/Servicehosting/Api/Client.php
index 29f926d35..4865d838d 100644
--- a/src/modules/Servicehosting/Api/Client.php
+++ b/src/modules/Servicehosting/Api/Client.php
@@ -83,12 +83,12 @@ class Client extends \Api_Abstract
throw new \FOSSBilling\Exception('Order ID is required');
}
$identity = $this->getIdentity();
- $order = $this->di['db']->findOne('ClientOrder', 'id = ? and client_id = ?', [$data['order_id'], $identity->id]);
+ $order = $this->getDi()['db']->findOne('ClientOrder', 'id = ? and client_id = ?', [$data['order_id'], $identity->id]);
if (!$order instanceof \Model_ClientOrder) {
throw new \FOSSBilling\Exception('Order not found');
}
- $orderService = $this->di['mod_service']('order');
+ $orderService = $this->getDi()['mod_service']('order');
$s = $orderService->getOrderService($order);
if (!$s instanceof \Model_ServiceHosting || $order->status !== \Model_ClientOrder::STATUS_ACTIVE) {
throw new \FOSSBilling\Exception('Order is not activated');
diff --git a/src/modules/Servicehosting/Api/Guest.php b/src/modules/Servicehosting/Api/Guest.php
index 6e17bf2d0..e546b5eeb 100644
--- a/src/modules/Servicehosting/Api/Guest.php
+++ b/src/modules/Servicehosting/Api/Guest.php
@@ -30,7 +30,7 @@ class Guest extends \Api_Abstract
public function free_tlds($data = [])
{
$product_id = $data['product_id'] ?? 0;
- $product = $this->di['db']->getExistingModelById('Product', $product_id, 'Product was not found');
+ $product = $this->getDi()['db']->getExistingModelById('Product', $product_id, 'Product was not found');
if ($product->type !== \Model_Product::HOSTING) {
$friendlyName = ucfirst(__trans('Product type'));
diff --git a/src/modules/Servicehosting/Service.php b/src/modules/Servicehosting/Service.php
index 43d34484a..5ee3449ad 100644
--- a/src/modules/Servicehosting/Service.php
+++ b/src/modules/Servicehosting/Service.php
@@ -1102,7 +1102,7 @@ class Service implements InjectionAwareInterface
return [$m->getLoginUrl(null), $m->getResellerLoginUrl(null)];
} catch (\Exception $e) {
- error_log("Error while retrieving control panel url: {$e->getMessage()}.");
+ $this->di['logger']->error("Error while retrieving control panel url: {$e->getMessage()}.");
}
return [false, false];
diff --git a/src/modules/Servicehosting/tests/Unit/Api/AdminTest.php b/src/modules/Servicehosting/tests/Unit/Api/AdminTest.php
new file mode 100644
index 000000000..245a961be
--- /dev/null
+++ b/src/modules/Servicehosting/tests/Unit/Api/AdminTest.php
@@ -0,0 +1,674 @@
+setDi($di);
+ $getDi = $api->getDi();
+ expect($getDi)->toBe($di);
+});
+
+test('testChangePlan', function (): void {
+ $api = new Admin();
+ $data = [
+ 'plan_id' => 1,
+ ];
+
+ $getServiceReturnValue = [new Model_ClientOrder(), new Model_ServiceHosting()];
+ $apiMock = Mockery::mock(Admin::class)->makePartial();
+
+ $apiMock
+ ->shouldReceive('_getService')
+ ->atLeast()->once()
+ ->andReturn($getServiceReturnValue);
+
+ $serviceMock = Mockery::mock(Box\Mod\Servicehosting\Service::class);
+ $serviceMock
+ ->shouldReceive('changeAccountPlan')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn(new Model_ServiceHostingHp());
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $apiMock->setDi($di);
+ $apiMock->setService($serviceMock);
+
+ $result = $apiMock->change_plan($data);
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+});
+
+test('testChangePlanMissingPlanId', function (): void {
+ $api = new Admin();
+ $data = [];
+
+ $di = container();
+ $api->setDi($di);
+
+ $this->expectException(FOSSBilling\Exception::class);
+ $this->expectExceptionMessage('plan_id is missing');
+ $api->change_plan($data);
+});
+
+test('testChangeUsername', function (): void {
+ $api = new Admin();
+ $getServiceReturnValue = [new Model_ClientOrder(), new Model_ServiceHosting()];
+ $apiMock = Mockery::mock(Admin::class)->makePartial();
+
+ $apiMock
+ ->shouldReceive('_getService')
+ ->atLeast()->once()
+ ->andReturn($getServiceReturnValue);
+
+ $serviceMock = Mockery::mock(Box\Mod\Servicehosting\Service::class);
+ $serviceMock
+ ->shouldReceive('changeAccountUsername')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $apiMock->setService($serviceMock);
+
+ $result = $apiMock->change_username([]);
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+});
+
+test('testChangeIp', function (): void {
+ $api = new Admin();
+ $getServiceReturnValue = [new Model_ClientOrder(), new Model_ServiceHosting()];
+ $apiMock = Mockery::mock(Admin::class)->makePartial();
+
+ $apiMock
+ ->shouldReceive('_getService')
+ ->atLeast()->once()
+ ->andReturn($getServiceReturnValue);
+
+ $serviceMock = Mockery::mock(Box\Mod\Servicehosting\Service::class);
+ $serviceMock
+ ->shouldReceive('changeAccountIp')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $apiMock->setService($serviceMock);
+
+ $result = $apiMock->change_ip([]);
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+});
+
+test('testChangeDomain', function (): void {
+ $api = new Admin();
+ $getServiceReturnValue = [new Model_ClientOrder(), new Model_ServiceHosting()];
+ $apiMock = Mockery::mock(Admin::class)->makePartial();
+
+ $apiMock
+ ->shouldReceive('_getService')
+ ->atLeast()->once()
+ ->andReturn($getServiceReturnValue);
+
+ $serviceMock = Mockery::mock(Box\Mod\Servicehosting\Service::class);
+ $serviceMock
+ ->shouldReceive('changeAccountDomain')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $apiMock->setService($serviceMock);
+
+ $result = $apiMock->change_domain([]);
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+});
+
+test('testChangePassword', function (): void {
+ $api = new Admin();
+ $getServiceReturnValue = [new Model_ClientOrder(), new Model_ServiceHosting()];
+ $apiMock = Mockery::mock(Admin::class)->makePartial();
+
+ $apiMock
+ ->shouldReceive('_getService')
+ ->atLeast()->once()
+ ->andReturn($getServiceReturnValue);
+
+ $serviceMock = Mockery::mock(Box\Mod\Servicehosting\Service::class);
+ $serviceMock
+ ->shouldReceive('changeAccountPassword')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $apiMock->setService($serviceMock);
+
+ $result = $apiMock->change_password([]);
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+});
+
+test('testSync', function (): void {
+ $api = new Admin();
+ $getServiceReturnValue = [new Model_ClientOrder(), new Model_ServiceHosting()];
+ $apiMock = Mockery::mock(Admin::class)->makePartial();
+
+ $apiMock
+ ->shouldReceive('_getService')
+ ->atLeast()->once()
+ ->andReturn($getServiceReturnValue);
+
+ $serviceMock = Mockery::mock(Box\Mod\Servicehosting\Service::class);
+ $serviceMock
+ ->shouldReceive('sync')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $apiMock->setService($serviceMock);
+
+ $result = $apiMock->sync([]);
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+});
+
+test('testUpdate', function (): void {
+ $api = new Admin();
+ $getServiceReturnValue = [new Model_ClientOrder(), new Model_ServiceHosting()];
+ $apiMock = Mockery::mock(Admin::class)->makePartial();
+
+ $apiMock
+ ->shouldReceive('_getService')
+ ->atLeast()->once()
+ ->andReturn($getServiceReturnValue);
+
+ $serviceMock = Mockery::mock(Box\Mod\Servicehosting\Service::class);
+ $serviceMock
+ ->shouldReceive('update')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $apiMock->setService($serviceMock);
+
+ $result = $apiMock->update([]);
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+});
+
+test('testManagerGetPairs', function (): void {
+ $api = new Admin();
+ $serviceMock = Mockery::mock(Box\Mod\Servicehosting\Service::class);
+ $serviceMock
+ ->shouldReceive('getServerManagers')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $api->setService($serviceMock);
+
+ $result = $api->manager_get_pairs([]);
+ expect($result)->toBeArray();
+});
+
+test('testServerGetPairs', function (): void {
+ $api = new Admin();
+ $serviceMock = Mockery::mock(Box\Mod\Servicehosting\Service::class);
+ $serviceMock
+ ->shouldReceive('getServerPairs')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $api->setService($serviceMock);
+
+ $result = $api->server_get_pairs([]);
+ expect($result)->toBeArray();
+});
+
+test('testAccountGetList', function (): void {
+ $api = new Admin();
+ $serviceMock = Mockery::mock(Box\Mod\Servicehosting\Service::class);
+ $serviceMock
+ ->shouldReceive('getAccountsSearchQuery')
+ ->atLeast()->once()
+ ->andReturn(['SQLstring', []]);
+
+ $pagerMock = Mockery::mock(FOSSBilling\Pagination::class)->makePartial();
+ $pagerMock
+ ->shouldReceive('getPaginatedResultSet')
+ ->atLeast()->once()
+ ->andReturn(['list' => []]);
+
+ $di = container();
+ $dbStub = Mockery::mock('Box_Database');
+ $di['mod_service'] = $di->protect(moduleService());
+ $di['pager'] = $pagerMock;
+ $di['db'] = $dbStub;
+
+ $api->setDi($di);
+ $api->setService($serviceMock);
+
+ $result = $api->account_get_list([]);
+ expect($result)->toBeArray();
+});
+
+test('testServerGetList', function (): void {
+ $api = new Admin();
+ $serviceMock = Mockery::mock(Box\Mod\Servicehosting\Service::class);
+ $serviceMock
+ ->shouldReceive('getServersSearchQuery')
+ ->atLeast()->once()
+ ->andReturn(['SQLstring', []]);
+
+ $pagerMock = Mockery::mock(FOSSBilling\Pagination::class)->makePartial();
+ $pagerMock
+ ->shouldReceive('getPaginatedResultSet')
+ ->atLeast()->once()
+ ->andReturn(['list' => []]);
+
+ $di = container();
+ $di['pager'] = $pagerMock;
+ $dbStub = Mockery::mock('Box_Database');
+ $di['db'] = $dbStub;
+
+ $api->setDi($di);
+ $api->setService($serviceMock);
+
+ $result = $api->server_get_list([]);
+ expect($result)->toBeArray();
+});
+
+test('testServerCreate', function (): void {
+ $api = new Admin();
+ $data = [
+ 'name' => 'test',
+ 'ip' => '1.1.1.1',
+ 'manager' => 'ServerManagerCode',
+ ];
+
+ $newServerId = 1;
+
+ $serviceMock = Mockery::mock(Box\Mod\Servicehosting\Service::class);
+ $serviceMock
+ ->shouldReceive('createServer')
+ ->atLeast()->once()
+ ->andReturn($newServerId);
+
+ $di = container();
+ $api->setDi($di);
+
+ $api->setService($serviceMock);
+
+ $result = $api->server_create($data);
+ expect($result)->toBeInt();
+ expect($result)->toBe($newServerId);
+});
+
+test('testServerGet', function (): void {
+ $api = new Admin();
+ $data['id'] = 1;
+
+ $serviceMock = Mockery::mock(Box\Mod\Servicehosting\Service::class);
+ $serviceMock
+ ->shouldReceive('toHostingServerApiArray')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn(new Model_ServiceHostingServer());
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $api->setDi($di);
+ $api->setService($serviceMock);
+
+ $result = $api->server_get($data);
+ expect($result)->toBeArray();
+});
+
+test('testServerDelete', function (): void {
+ $api = new Admin();
+ // Test case 1: Server can be deleted
+ $data['id'] = 1;
+
+ $serviceMock = Mockery::mock(Box\Mod\Servicehosting\Service::class);
+ $serviceMock
+ ->shouldReceive('deleteServer')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn(new Model_ServiceHostingServer());
+ $dbMock
+ ->shouldReceive('find')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $api->setDi($di);
+ $api->setService($serviceMock);
+
+ $result = $api->server_delete($data);
+ expect($result)->toBeTrue();
+
+ // Test case 2: Server is used by service_hostings and cannot be deleted
+ $data['id'] = 2;
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn(new Model_ServiceHostingServer());
+
+ // Mock the 'find' method to return a non-empty array, simulating the server being used by service hostings
+ $dbMock
+ ->shouldReceive('find')
+ ->atLeast()->once()
+ ->andReturn(['dummy_data']);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $api->setDi($di);
+
+ // Now, we expect an exception to be thrown because the server is used by service_hostings
+ $this->expectException(FOSSBilling\Exception::class);
+ $this->expectExceptionCode(704);
+
+ $api->server_delete($data);
+});
+
+test('testServerUpdate', function (): void {
+ $api = new Admin();
+ $data['id'] = 1;
+
+ $serviceMock = Mockery::mock(Box\Mod\Servicehosting\Service::class);
+ $serviceMock
+ ->shouldReceive('updateServer')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn(new Model_ServiceHostingServer());
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $api->setDi($di);
+ $api->setService($serviceMock);
+
+ $result = $api->server_update($data);
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+});
+
+test('testServerTestConnection', function (): void {
+ $api = new Admin();
+ $data['id'] = 1;
+
+ $serviceMock = Mockery::mock(Box\Mod\Servicehosting\Service::class);
+ $serviceMock
+ ->shouldReceive('testConnection')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn(new Model_ServiceHostingServer());
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $api->setDi($di);
+ $api->setService($serviceMock);
+
+ $result = $api->server_test_connection($data);
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+});
+
+test('testHpGetPairs', function (): void {
+ $api = new Admin();
+ $serviceMock = Mockery::mock(Box\Mod\Servicehosting\Service::class);
+ $serviceMock
+ ->shouldReceive('getHpPairs')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $api->setService($serviceMock);
+ $result = $api->hp_get_pairs([]);
+ expect($result)->toBeArray();
+});
+
+test('testHpGetList', function (): void {
+ $api = new Admin();
+ $serviceMock = Mockery::mock(Box\Mod\Servicehosting\Service::class);
+ $serviceMock
+ ->shouldReceive('getHpSearchQuery')
+ ->atLeast()->once()
+ ->andReturn(['SQLstring', []]);
+
+ $pagerMock = Mockery::mock(FOSSBilling\Pagination::class)->makePartial();
+ $pagerMock
+ ->shouldReceive('getPaginatedResultSet')
+ ->atLeast()->once()
+ ->andReturn(['list' => []]);
+
+ $di = container();
+ $di['pager'] = $pagerMock;
+
+ $api->setDi($di);
+ $api->setService($serviceMock);
+
+ $result = $api->hp_get_list([]);
+ expect($result)->toBeArray();
+});
+
+test('testHpDelete', function (): void {
+ $api = new Admin();
+ $data = [
+ 'id' => 1,
+ ];
+
+ $model = new Model_ServiceHostingHp();
+
+ $serviceMock = Mockery::mock(Box\Mod\Servicehosting\Service::class);
+ $serviceMock
+ ->shouldReceive('deleteHp')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($model);
+ $dbMock
+ ->shouldReceive('find')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $api->setDi($di);
+ $api->setService($serviceMock);
+
+ // Add a try-catch block to handle the exception thrown in the hp_delete function
+ try {
+ $result = $api->hp_delete($data);
+
+ // If the function doesn't throw an exception, then the test should assert the result
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+ } catch (FOSSBilling\Exception $e) {
+ // If the function throws an exception, the test should fail
+ $this->fail('Exception thrown: ' . $e->getMessage());
+ }
+});
+
+test('testHpGet', function (): void {
+ $api = new Admin();
+ $data = [
+ 'id' => 1,
+ ];
+
+ $model = new Model_ServiceHostingHp();
+
+ $serviceMock = Mockery::mock(Box\Mod\Servicehosting\Service::class);
+ $serviceMock
+ ->shouldReceive('toHostingHpApiArray')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $api->setDi($di);
+ $api->setService($serviceMock);
+
+ $result = $api->hp_get($data);
+ expect($result)->toBeArray();
+});
+
+test('testHpUpdate', function (): void {
+ $api = new Admin();
+ $data = [
+ 'id' => 1,
+ ];
+
+ $model = new Model_ServiceHostingHp();
+
+ $serviceMock = Mockery::mock(Box\Mod\Servicehosting\Service::class);
+ $serviceMock
+ ->shouldReceive('updateHp')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $api->setDi($di);
+ $api->setService($serviceMock);
+
+ $result = $api->hp_update($data);
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+});
+
+test('testHpCreate', function (): void {
+ $api = new Admin();
+ $data = [
+ 'name' => 'test',
+ ];
+
+ $newHpId = 2;
+
+ $serviceMock = Mockery::mock(Box\Mod\Servicehosting\Service::class);
+ $serviceMock
+ ->shouldReceive('createHp')
+ ->atLeast()->once()
+ ->andReturn($newHpId);
+
+ $di = container();
+ $api->setDi($di);
+
+ $api->setService($serviceMock);
+
+ $result = $api->hp_create($data);
+ expect($result)->toBeInt();
+ expect($result)->toBe($newHpId);
+});
+
+test('testGetService', function (): void {
+ $api = new Admin();
+ $data = [
+ 'order_id' => 1,
+ ];
+
+ $clientOrderModel = new Model_ClientOrder();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($clientOrderModel);
+
+ $model = new Model_ServiceHosting();
+ $orderServiceMock = Mockery::mock(Box\Mod\Order\Service::class);
+ $orderServiceMock
+ ->shouldReceive('getOrderService')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
+ $di['db'] = $dbMock;
+
+ $api->setDi($di);
+
+ $result = $api->_getService($data);
+ expect($result)->toBeArray();
+ expect($result[0])->toBeInstanceOf('\Model_ClientOrder');
+ expect($result[1])->toBeInstanceOf('\Model_ServiceHosting');
+});
+
+test('testGetServiceOrderNotActivated', function (): void {
+ $api = new Admin();
+ $data = [
+ 'order_id' => 1,
+ ];
+
+ $clientOrderModel = new Model_ClientOrder();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($clientOrderModel);
+
+ $model = null;
+ $orderServiceMock = Mockery::mock(Box\Mod\Order\Service::class);
+ $orderServiceMock
+ ->shouldReceive('getOrderService')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
+ $di['db'] = $dbMock;
+ $api->setDi($di);
+
+ $this->expectException(FOSSBilling\Exception::class);
+ $this->expectExceptionMessage('Order is not activated');
+ $api->_getService($data);
+});
diff --git a/src/modules/Servicehosting/tests/Unit/Api/ClientTest.php b/src/modules/Servicehosting/tests/Unit/Api/ClientTest.php
new file mode 100644
index 000000000..81f109ce2
--- /dev/null
+++ b/src/modules/Servicehosting/tests/Unit/Api/ClientTest.php
@@ -0,0 +1,216 @@
+setDi($di);
+ $getDi = $api->getDi();
+ expect($getDi)->toBe($di);
+});
+
+test('testChangeUsername', function (): void {
+ $api = new Client();
+ $getServiceReturnValue = [new Model_ClientOrder(), new Model_ServiceHosting()];
+ $apiMock = Mockery::mock(Client::class)->makePartial();
+
+ $apiMock
+ ->shouldReceive('_getService')
+ ->atLeast()->once()
+ ->andReturn($getServiceReturnValue);
+
+ $serviceMock = Mockery::mock(Box\Mod\Servicehosting\Service::class);
+ $serviceMock
+ ->shouldReceive('changeAccountUsername')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $apiMock->setService($serviceMock);
+
+ $result = $apiMock->change_username([]);
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+});
+
+test('testChangeDomain', function (): void {
+ $api = new Client();
+ $getServiceReturnValue = [new Model_ClientOrder(), new Model_ServiceHosting()];
+ $apiMock = Mockery::mock(Client::class)->makePartial();
+
+ $apiMock
+ ->shouldReceive('_getService')
+ ->atLeast()->once()
+ ->andReturn($getServiceReturnValue);
+
+ $serviceMock = Mockery::mock(Box\Mod\Servicehosting\Service::class);
+ $serviceMock
+ ->shouldReceive('changeAccountDomain')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $apiMock->setService($serviceMock);
+
+ $result = $apiMock->change_domain([]);
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+});
+
+test('testChangePassword', function (): void {
+ $api = new Client();
+ $getServiceReturnValue = [new Model_ClientOrder(), new Model_ServiceHosting()];
+ $apiMock = Mockery::mock(Client::class)->makePartial();
+
+ $apiMock
+ ->shouldReceive('_getService')
+ ->atLeast()->once()
+ ->andReturn($getServiceReturnValue);
+
+ $serviceMock = Mockery::mock(Box\Mod\Servicehosting\Service::class);
+ $serviceMock
+ ->shouldReceive('changeAccountPassword')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $apiMock->setService($serviceMock);
+
+ $result = $apiMock->change_password([]);
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+});
+
+test('testHpGetPairs', function (): void {
+ $api = new Client();
+ $serviceMock = Mockery::mock(Box\Mod\Servicehosting\Service::class);
+ $serviceMock
+ ->shouldReceive('getHpPairs')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $api->setService($serviceMock);
+ $result = $api->hp_get_pairs([]);
+ expect($result)->toBeArray();
+});
+
+test('testGetService', function (): void {
+ $api = new Client();
+ $data = [
+ 'order_id' => 1,
+ ];
+
+ $clientOrderModel = new Model_ClientOrder();
+ $clientOrderModel->loadBean(new Tests\Helpers\DummyBean());
+ $clientOrderModel->status = Model_ClientOrder::STATUS_ACTIVE;
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn($clientOrderModel);
+
+ $model = new Model_ServiceHosting();
+ $orderServiceMock = Mockery::mock(Box\Mod\Order\Service::class);
+ $orderServiceMock
+ ->shouldReceive('getOrderService')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
+ $di['db'] = $dbMock;
+
+ $api->setDi($di);
+
+ $clientModel = new Model_Client();
+ $clientModel->loadBean(new Tests\Helpers\DummyBean());
+ $clientModel->id = 1;
+ $api->setIdentity($clientModel);
+ $result = $api->_getService($data);
+ expect($result)->toBeArray();
+ expect($result[0])->toBeInstanceOf('\Model_ClientOrder');
+ expect($result[1])->toBeInstanceOf('\Model_ServiceHosting');
+});
+
+test('testGetServiceOrderNotActivated', function (): void {
+ $api = new Client();
+ $data = [
+ 'order_id' => 1,
+ ];
+
+ $clientOrderModel = new Model_ClientOrder();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn($clientOrderModel);
+
+ $model = null;
+ $orderServiceMock = Mockery::mock(Box\Mod\Order\Service::class);
+ $orderServiceMock
+ ->shouldReceive('getOrderService')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
+ $di['db'] = $dbMock;
+
+ $api->setDi($di);
+
+ $clientModel = new Model_Client();
+ $clientModel->loadBean(new Tests\Helpers\DummyBean());
+ $clientModel->id = 1;
+ $api->setIdentity($clientModel);
+
+ $this->expectException(FOSSBilling\Exception::class);
+ $this->expectExceptionMessage('Order is not activated');
+ $api->_getService($data);
+});
+
+test('testGetServiceOrderNotFound', function (): void {
+ $api = new Client();
+ $data = [
+ 'order_id' => 1,
+ ];
+
+ $clientOrderModel = null;
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn($clientOrderModel);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $api->setDi($di);
+
+ $clientModel = new Model_Client();
+ $clientModel->loadBean(new Tests\Helpers\DummyBean());
+ $clientModel->id = 1;
+ $api->setIdentity($clientModel);
+
+ $this->expectException(FOSSBilling\Exception::class);
+ $this->expectExceptionMessage('Order not found');
+ $api->_getService($data);
+});
+
+test('testGetServiceMissingOrderId', function (): void {
+ $api = new Client();
+ $data = [];
+
+ $this->expectException(FOSSBilling\Exception::class);
+ $this->expectExceptionMessage('Order ID is required');
+ $api->_getService($data);
+});
diff --git a/src/modules/Servicehosting/tests/Unit/Api/GuestTest.php b/src/modules/Servicehosting/tests/Unit/Api/GuestTest.php
new file mode 100644
index 000000000..904b3b364
--- /dev/null
+++ b/src/modules/Servicehosting/tests/Unit/Api/GuestTest.php
@@ -0,0 +1,70 @@
+loadBean(new Tests\Helpers\DummyBean());
+ $model->type = Model_Product::HOSTING;
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $di['db'] = $dbMock;
+
+ $serviceMock = Mockery::mock(Box\Mod\Servicehosting\Service::class);
+ $serviceMock
+ ->shouldReceive('getFreeTlds')
+ ->atLeast()->once()
+ ->with($model)
+ ->andReturn([]);
+ $api->setService($serviceMock);
+ $api->setDi($di);
+
+ $result = $api->free_tlds(['product_id' => 1]);
+ expect($result)->toBeArray();
+});
+
+test('testFreeTldsProductTypeIsNotHosting', 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);
+
+ $validatorStub = $this->createStub(FOSSBilling\Validate::class);
+
+ $di['db'] = $dbMock;
+ $di['validator'] = $validatorStub;
+
+ $serviceMock = Mockery::mock(Box\Mod\Servicehosting\Service::class);
+ $serviceMock->shouldReceive('getFreeTlds');
+ $api->setService($serviceMock);
+ $api->setDi($di);
+
+ $this->expectException(FOSSBilling\Exception::class);
+ $this->expectExceptionMessage('Product type is invalid');
+ $api->free_tlds(['product_id' => 1]);
+});
diff --git a/src/modules/Servicehosting/tests/Unit/ServiceTest.php b/src/modules/Servicehosting/tests/Unit/ServiceTest.php
new file mode 100644
index 000000000..14b968615
--- /dev/null
+++ b/src/modules/Servicehosting/tests/Unit/ServiceTest.php
@@ -0,0 +1,1129 @@
+ [
+ ['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 {
+ $service = new Service();
+ $data = [
+ 'server_id' => 1,
+ 'hosting_plan_id' => 2,
+ 'sld' => 'great',
+ 'tld' => 'com',
+ ];
+
+ unset($data[$field]);
+
+ $this->expectException(FOSSBilling\Exception::class);
+ $this->expectExceptionMessage($exceptionMessage);
+ $service->validateOrderData($data);
+})->with('validateOrderDataProvider');
+
+test('testActionCreate', function (): void {
+ $service = new Service();
+ $orderModel = new Model_ClientOrder();
+ $orderModel->loadBean(new Tests\Helpers\DummyBean());
+ $confArr = [
+ 'server_id' => 1,
+ 'hosting_plan_id' => 2,
+ 'sld' => 'great',
+ 'tld' => 'com',
+ ];
+ $orderServiceMock = Mockery::mock(Box\Mod\Order\Service::class);
+ $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);
+
+ $servhostingModel = new Model_ServiceHosting();
+ $servhostingModel->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock
+ ->shouldReceive('dispense')
+ ->atLeast()->once()
+ ->andReturn($servhostingModel);
+
+ $newserviceHostingId = 4;
+ $dbMock
+ ->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn($newserviceHostingId);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
+
+ $service->setDi($di);
+ $service->action_create($orderModel);
+});
+
+test('testActionRenew', function (): void {
+ $service = new Service();
+ $orderModel = new Model_ClientOrder();
+ $orderModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $model = new Model_ServiceHostingHp();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $orderServiceMock = Mockery::mock(Box\Mod\Order\Service::class);
+ $orderServiceMock
+ ->shouldReceive('getOrderService')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
+
+ $service->setDi($di);
+ $result = $service->action_renew($orderModel);
+ expect($result)->toBeTrue();
+});
+
+test('testActionRenewOrderWithoutActiveService', function (): void {
+ $service = new Service();
+ $orderModel = new Model_ClientOrder();
+ $orderModel->loadBean(new Tests\Helpers\DummyBean());
+ $orderModel->id = 1;
+
+ $orderServiceMock = Mockery::mock(Box\Mod\Order\Service::class);
+ $orderServiceMock->shouldReceive('getOrderService')->atLeast()->once();
+
+ $di = container();
+ $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);
+});
+
+test('testActionSuspend', function (): void {
+ $service = new Service();
+ $orderModel = new Model_ClientOrder();
+ $orderModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $model = new Model_ServiceHosting();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $orderServiceMock = Mockery::mock(Box\Mod\Order\Service::class);
+ $orderServiceMock
+ ->shouldReceive('getOrderService')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+ $serverManagerMock = Mockery::mock('\Server_Manager_Custom');
+ $serverManagerMock->shouldReceive('suspendAccount')->atLeast()->once();
+ $AMresultArray = [$serverManagerMock, new Server_Account()];
+ $serviceMock
+ ->shouldReceive('_getAM')
+ ->atLeast()->once()
+ ->andReturn($AMresultArray);
+
+ $serviceMock->setDi($di);
+ $result = $serviceMock->action_suspend($orderModel);
+ expect($result)->toBeTrue();
+});
+
+test('testActionSuspendOrderWithoutActiveService', function (): void {
+ $service = new Service();
+ $orderModel = new Model_ClientOrder();
+ $orderModel->loadBean(new Tests\Helpers\DummyBean());
+ $orderModel->id = 1;
+
+ $orderServiceMock = Mockery::mock(Box\Mod\Order\Service::class);
+ $orderServiceMock->shouldReceive('getOrderService')->atLeast()->once();
+
+ $di = container();
+ $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);
+});
+
+test('testActionUnsuspend', function (): void {
+ $service = new Service();
+ $orderModel = new Model_ClientOrder();
+ $orderModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $model = new Model_ServiceHosting();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $orderServiceMock = Mockery::mock(Box\Mod\Order\Service::class);
+ $orderServiceMock
+ ->shouldReceive('getOrderService')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+ $serverManagerMock = Mockery::mock('\Server_Manager_Custom');
+ $serverManagerMock->shouldReceive('unsuspendAccount')->atLeast()->once();
+ $AMresultArray = [$serverManagerMock, new Server_Account()];
+ $serviceMock
+ ->shouldReceive('_getAM')
+ ->atLeast()->once()
+ ->andReturn($AMresultArray);
+
+ $serviceMock->setDi($di);
+ $result = $serviceMock->action_unsuspend($orderModel);
+ expect($result)->toBeTrue();
+});
+
+test('testActionUnsuspendOrderWithoutActiveService', function (): void {
+ $service = new Service();
+ $orderModel = new Model_ClientOrder();
+ $orderModel->loadBean(new Tests\Helpers\DummyBean());
+ $orderModel->id = 1;
+
+ $orderServiceMock = Mockery::mock(Box\Mod\Order\Service::class);
+ $orderServiceMock->shouldReceive('getOrderService')->atLeast()->once();
+
+ $di = container();
+ $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);
+});
+
+test('testActionCancel', function (): void {
+ $service = new Service();
+ $orderModel = new Model_ClientOrder();
+ $orderModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $model = new Model_ServiceHosting();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $orderServiceMock = Mockery::mock(Box\Mod\Order\Service::class);
+ $orderServiceMock
+ ->shouldReceive('getOrderService')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+ $serverManagerMock = Mockery::mock('\Server_Manager_Custom');
+ $serverManagerMock->shouldReceive('cancelAccount')->atLeast()->once();
+ $AMresultArray = [$serverManagerMock, new Server_Account()];
+ $serviceMock
+ ->shouldReceive('_getAM')
+ ->atLeast()->once()
+ ->andReturn($AMresultArray);
+
+ $serviceMock->setDi($di);
+ $result = $serviceMock->action_cancel($orderModel);
+ expect($result)->toBeTrue();
+});
+
+test('testActionCancelOrderWithoutActiveService', function (): void {
+ $service = new Service();
+ $orderModel = new Model_ClientOrder();
+ $orderModel->loadBean(new Tests\Helpers\DummyBean());
+ $orderModel->id = 1;
+
+ $orderServiceMock = Mockery::mock(Box\Mod\Order\Service::class);
+ $orderServiceMock->shouldReceive('getOrderService')->atLeast()->once();
+
+ $di = container();
+ $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);
+});
+
+test('testActionDelete', function (): void {
+ $service = new Service();
+ $orderModel = new Model_ClientOrder();
+ $orderModel->loadBean(new Tests\Helpers\DummyBean());
+ $orderModel->status = 'active';
+
+ $model = new Model_ServiceHosting();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $orderServiceMock = Mockery::mock(Box\Mod\Order\Service::class);
+ $orderServiceMock
+ ->shouldReceive('getOrderService')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('trash')->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+ $serviceMock->shouldReceive('action_cancel')->atLeast()->once();
+
+ $serviceMock->setDi($di);
+ $serviceMock->action_delete($orderModel);
+});
+
+test('testChangeAccountPlan', function (): void {
+ $service = new Service();
+ $orderModel = new Model_ClientOrder();
+ $orderModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $model = new Model_ServiceHosting();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $modelHp = new Model_ServiceHostingHp();
+ $modelHp->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $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->setDi($di);
+ $result = $serviceMock->changeAccountPlan($orderModel, $model, $modelHp);
+ expect($result)->toBeTrue();
+});
+
+test('testChangeAccountUsername', function (): void {
+ $service = new Service();
+ $data = [
+ 'username' => 'u123456',
+ ];
+
+ $orderModel = new Model_ClientOrder();
+ $orderModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $model = new Model_ServiceHosting();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+
+ $serverManagerMock = Mockery::mock('\Server_Manager_Custom');
+ $serverManagerMock->shouldReceive('changeAccountUsername')->atLeast()->once();
+
+ $AMresultArray = [$serverManagerMock, new Server_Account()];
+ $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();
+
+ $serviceMock->setDi($di);
+
+ $result = $serviceMock->changeAccountUsername($orderModel, $model, $data);
+ expect($result)->toBeTrue();
+});
+
+test('testChangeAccountUsernameMissingUsername', function (): void {
+ $service = new Service();
+ $orderModel = new Model_ClientOrder();
+ $orderModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $model = new Model_ServiceHosting();
+ $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);
+});
+
+test('testChangeAccountIp', function (): void {
+ $service = new Service();
+ $data = [
+ 'ip' => '1.1.1.1',
+ ];
+
+ $orderModel = new Model_ClientOrder();
+ $orderModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $model = new Model_ServiceHosting();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+
+ $serverManagerMock = Mockery::mock('\Server_Manager_Custom');
+ $serverManagerMock->shouldReceive('changeAccountIp')->atLeast()->once();
+
+ $AMresultArray = [$serverManagerMock, new Server_Account()];
+ $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();
+
+ $serviceMock->setDi($di);
+
+ $result = $serviceMock->changeAccountIp($orderModel, $model, $data);
+ expect($result)->toBeTrue();
+});
+
+test('testChangeAccountIpMissingIp', function (): void {
+ $service = new Service();
+ $data = [];
+ $orderModel = new Model_ClientOrder();
+ $orderModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $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);
+});
+
+test('testChangeAccountDomain', function (): void {
+ $service = new Service();
+ $data = [
+ 'tld' => 'com',
+ 'sld' => 'testingSld',
+ ];
+
+ $orderModel = new Model_ClientOrder();
+ $orderModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $model = new Model_ServiceHosting();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+
+ $serverManagerMock = Mockery::mock('\Server_Manager_Custom');
+ $serverManagerMock->shouldReceive('changeAccountDomain')->atLeast()->once();
+
+ $AMresultArray = [$serverManagerMock, new Server_Account()];
+ $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();
+
+ $serviceMock->setDi($di);
+
+ $result = $serviceMock->changeAccountDomain($orderModel, $model, $data);
+ expect($result)->toBeTrue();
+});
+
+test('testChangeAccountDomainMissingParams', function (): void {
+ $service = new Service();
+ $data = [];
+ $orderModel = new Model_ClientOrder();
+ $orderModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $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);
+});
+
+test('testChangeAccountPassword', function (): void {
+ $service = new Service();
+ $data = [
+ 'password' => 'topsecret',
+ 'password_confirm' => 'topsecret',
+ ];
+
+ $orderModel = new Model_ClientOrder();
+ $orderModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $model = new Model_ServiceHosting();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+
+ $serverManagerMock = Mockery::mock('\Server_Manager_Custom');
+ $serverManagerMock->shouldReceive('changeAccountPassword')->atLeast()->once();
+
+ $AMresultArray = [$serverManagerMock, new Server_Account()];
+ $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();
+
+ $serviceMock->setDi($di);
+
+ $result = $serviceMock->changeAccountPassword($orderModel, $model, $data);
+ expect($result)->toBeTrue();
+});
+
+test('testChangeAccountPasswordMissingParams', function (): void {
+ $service = new Service();
+ $data = [];
+ $orderModel = new Model_ClientOrder();
+ $orderModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $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);
+});
+
+test('testSync', function (): void {
+ $service = new Service();
+ $data = [
+ 'password' => 'topsecret',
+ 'password_confirm' => 'topsecret',
+ ];
+
+ $orderModel = new Model_ClientOrder();
+ $orderModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $model = new Model_ServiceHosting();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+
+ $accountObj = new Server_Account();
+ $accountObj->setUsername('testUser1');
+ $accountObj->setIp('1.1.1.1');
+
+ $accountObj2 = new Server_Account();
+ $accountObj2->setUsername('testUser2');
+ $accountObj2->setIp('2.2.2.2');
+
+ $serverManagerMock = Mockery::mock('\Server_Manager_Custom');
+ $serverManagerMock
+ ->shouldReceive('synchronizeAccount')
+ ->atLeast()->once()
+ ->andReturn($accountObj2);
+
+ $AMresultArray = [$serverManagerMock, $accountObj];
+ $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();
+
+ $serviceMock->setDi($di);
+
+ $result = $serviceMock->sync($orderModel, $model, $data);
+ expect($result)->toBeTrue();
+});
+
+test('testToApiArray', function (): void {
+ $service = new Service();
+ $model = new Model_ServiceHosting();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $hostingServer = new Model_ServiceHostingServer();
+ $hostingServer->loadBean(new Tests\Helpers\DummyBean());
+ $hostingServer->manager = 'Custom';
+ $hostingHp = new Model_ServiceHostingHp();
+ $hostingHp->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('load')
+ ->andReturn($hostingServer, $hostingHp);
+
+ $orderServiceMock = Mockery::mock(Box\Mod\Order\Service::class);
+ $orderServiceMock->shouldReceive('getServiceOrder')->atLeast()->once();
+
+ $serverManagerCustomStub = Mockery::mock('\Server_Manager_Custom');
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
+ $di['server_manager'] = $di->protect(fn ($manager, $config) => $serverManagerCustomStub);
+
+ $service->setDi($di);
+
+ $result = $service->toApiArray($model, false, new Model_Admin());
+ expect($result)->toBeArray();
+});
+
+test('testUpdate', function (): void {
+ $service = new Service();
+ $data = [
+ 'username' => 'testUser',
+ 'ip' => '1.1.1.1',
+ ];
+ $model = new Model_ServiceHosting();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $service->setDi($di);
+
+ $result = $service->update($model, $data);
+ expect($result)->toBeTrue();
+});
+
+test('testGetServerManagers', function (): void {
+ $service = new Service();
+ $result = $service->getServerManagers();
+ expect($result)->toBeArray();
+});
+
+test('testGetServerManagerConfig', function (): void {
+ $service = new Service();
+ $manager = 'Custom';
+
+ $expected = [
+ 'label' => 'Custom Server Manager',
+ ];
+
+ $result = $service->getServerManagerConfig($manager);
+ expect($result)->toBeArray();
+ expect($result)->toBe($expected);
+});
+
+test('testGetServerPairs', function (): void {
+ $service = new Service();
+ $expected = [
+ '1' => 'name',
+ '2' => 'ding',
+ ];
+
+ $queryResult = [
+ [
+ 'id' => 1,
+ 'name' => 'name',
+ ], [
+ 'id' => 2,
+ 'name' => 'ding',
+ ],
+ ];
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getAll')
+ ->atLeast()->once()
+ ->andReturn($queryResult);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $result = $service->getServerPairs();
+ expect($result)->toBeArray();
+ expect($result)->toBe($expected);
+});
+
+test('testGetServerSearchQuery', function (): void {
+ $service = new Service();
+ $result = $service->getServersSearchQuery([]);
+ expect($result[0])->toBeString();
+ expect($result[1])->toBeArray();
+ expect($result[1])->toBe([]);
+});
+
+test('testCreateServer', 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);
+
+ $newId = 1;
+ $dbMock
+ ->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn($newId);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $service->setDi($di);
+
+ $name = 'newSuperFastServer';
+ $ip = '1.1.1.1';
+ $manager = 'Custom';
+ $data = [];
+ $result = $service->createServer($name, $ip, $manager, $data);
+ expect($result)->toBeInt();
+ expect($result)->toBe($newId);
+});
+
+test('testDeleteServer', function (): void {
+ $service = new Service();
+ $hostingServerModel = new Model_ServiceHostingServer();
+ $hostingServerModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('trash')->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $service->setDi($di);
+
+ $result = $service->deleteServer($hostingServerModel);
+ expect($result)->toBeTrue();
+});
+
+test('testUpdateServer', function (): void {
+ $service = new Service();
+ $data = [
+ 'name' => 'newName',
+ 'ip' => '1.1.1.1',
+ 'hostname' => 'unknownStar',
+ 'active' => 1,
+ 'status_url' => 'na',
+ 'ns1' => 'ns1.testserver.eu',
+ 'ns2' => 'ns2.testserver.eu',
+ 'ns3' => 'ns3.testserver.eu',
+ 'ns4' => 'ns4.testserver.eu',
+ 'manager' => 'Custom',
+ 'username' => 'testingJohn',
+ 'password' => 'hardToGuess',
+ 'accesshash' => 'secret',
+ 'port' => '23',
+ 'secure' => 0,
+ ];
+
+ $hostingServerModel = new Model_ServiceHostingServer();
+ $hostingServerModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $service->setDi($di);
+
+ $result = $service->updateServer($hostingServerModel, $data);
+ expect($result)->toBeTrue();
+});
+
+test('testGetServerManager', function (): void {
+ $service = new Service();
+ $hostingServerModel = new Model_ServiceHostingServer();
+ $hostingServerModel->loadBean(new Tests\Helpers\DummyBean());
+ $hostingServerModel->manager = 'Custom';
+
+ $serverManagerCustomStub = Mockery::mock('\Server_Manager_Custom');
+
+ $di = container();
+ $di['server_manager'] = $di->protect(fn ($manager, $config) => $serverManagerCustomStub);
+ $service->setDi($di);
+
+ $result = $service->getServerManager($hostingServerModel);
+ expect($result)->toBeInstanceOf('\Server_Manager_Custom');
+});
+
+test('testGetServerManagerManagerNotDefined', 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);
+});
+
+test('testGetServerManagerServerManagerInvalid', function (): void {
+ $service = new Service();
+ $hostingServerModel = new Model_ServiceHostingServer();
+ $hostingServerModel->loadBean(new Tests\Helpers\DummyBean());
+ $hostingServerModel->manager = 'Custom';
+
+ $di = container();
+ $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);
+});
+
+test('testTestConnection', function (): void {
+ $service = new Service();
+ $serverManagerMock = Mockery::mock('\Server_Manager_Custom');
+ $serverManagerMock
+ ->shouldReceive('testConnection')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+
+ $serviceMock
+ ->shouldReceive('getServerManager')
+ ->atLeast()->once()
+ ->andReturn($serverManagerMock);
+
+ $hostingServerModel = new Model_ServiceHostingServer();
+ $result = $serviceMock->testConnection($hostingServerModel);
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+});
+
+test('testGetHpPairs', function (): void {
+ $service = new Service();
+ $expected = [
+ '1' => 'free',
+ '2' => 'paid',
+ ];
+
+ $queryResult = [
+ [
+ 'id' => 1,
+ 'name' => 'free',
+ ], [
+ 'id' => 2,
+ 'name' => 'paid',
+ ],
+ ];
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getAll')
+ ->atLeast()->once()
+ ->andReturn($queryResult);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $result = $service->getHpPairs();
+ expect($result)->toBeArray();
+ expect($result)->toBe($expected);
+});
+
+test('testGetHpSearchQuery', function (): void {
+ $service = new Service();
+ $result = $service->getServersSearchQuery([]);
+ expect($result[0])->toBeString();
+ expect($result[1])->toBeArray();
+ expect($result[1])->toBe([]);
+});
+
+test('testDeleteHp', 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();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $service->setDi($di);
+
+ $result = $service->deleteHp($model);
+ expect($result)->toBeTrue();
+});
+
+test('testToHostingHpApiArray', function (): void {
+ $service = new Service();
+ $model = new Model_ServiceHostingHp();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $result = $service->toHostingHpApiArray($model);
+ expect($result)->toBeArray();
+});
+
+test('testUpdateHp', function (): void {
+ $service = new Service();
+ $data = [
+ 'name' => 'firstPlan',
+ 'bandwidth' => '100000',
+ 'quota' => '1000',
+ 'max_addon' => '0',
+ 'max_ft' => '1',
+ 'max_sql' => '2',
+ 'max_pop' => '1',
+ 'max_sub' => '2',
+ 'max_park' => '1',
+ ];
+
+ $model = new Model_ServiceHostingHp();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $service->setDi($di);
+
+ $result = $service->updateHp($model, $data);
+ expect($result)->toBeTrue();
+});
+
+test('testCreateHp', 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);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $service->setDi($di);
+
+ $result = $service->createHp('Free Plan', []);
+ expect($result)->toBeInt();
+ expect($result)->toBe($newId);
+});
+
+test('testGetServerPackage', function (): void {
+ $service = new Service();
+ $model = new Model_ServiceHostingHp();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $model->config = '{}';
+
+ $di = container();
+
+ $service->setDi($di);
+ $result = $service->getServerPackage($model);
+ expect($result)->toBeInstanceOf('\Server_Package');
+});
+
+test('testGetServerManagerWithLog', function (): void {
+ $service = new Service();
+ $hostingServerModel = new Model_ServiceHostingServer();
+ $hostingServerModel->loadBean(new Tests\Helpers\DummyBean());
+ $hostingServerModel->manager = 'Custom';
+
+ $clientOrderModel = new Model_ClientOrder();
+ $clientOrderModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $serverManagerMock = Mockery::mock('\Server_Manager_Custom');
+ $serverManagerMock->shouldReceive('setLog')->atLeast()->once();
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+ $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());
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
+
+ $serviceMock->setDi($di);
+ $result = $serviceMock->getServerManagerWithLog($hostingServerModel, $clientOrderModel);
+ expect($result)->toBeInstanceOf('\Server_Manager_Custom');
+});
+
+test('testGetManagerUrls', function (): void {
+ $service = new Service();
+ $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');
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+ $serviceMock
+ ->shouldReceive('getServerManager')
+ ->atLeast()->once()
+ ->andReturn($serverManagerMock);
+
+ $result = $serviceMock->getManagerUrls($hostingServerModel);
+ expect($result)->toBeArray();
+ expect($result[0])->toBeString();
+ expect($result[1])->toBeString();
+});
+
+test('testGetManagerUrlsException', function (): void {
+ $service = new Service();
+ $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);
+
+ $result = $serviceMock->getManagerUrls($hostingServerModel);
+ expect($result)->toBeArray();
+ expect($result[0])->toBeFalse();
+ expect($result[1])->toBeFalse();
+});
+
+test('testGetFreeTldsFreeTldsAreNotSet', 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);
+ $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]);
+ $di['db'] = $dbMock;
+
+ $service->setDi($di);
+ $model = new Model_Product();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $result = $service->getFreeTlds($model);
+ expect($result)->toBeArray();
+});
+
+test('testGetFreeTlds', function (): void {
+ $service = new Service();
+ $config = [
+ 'free_tlds' => ['.com'],
+ ];
+ $di = container();
+
+ $service->setDi($di);
+ $model = new Model_Product();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $model->config = json_encode($config);
+
+ $result = $service->getFreeTlds($model);
+ expect($result)->toBeArray();
+ expect($result)->not->toBeEmpty();
+});
diff --git a/src/modules/Servicelicense/Api/Admin.php b/src/modules/Servicelicense/Api/Admin.php
index f9f388d2a..4a27509ba 100644
--- a/src/modules/Servicelicense/Api/Admin.php
+++ b/src/modules/Servicelicense/Api/Admin.php
@@ -22,7 +22,7 @@ class Admin extends \Api_Abstract
*/
public function plugin_get_pairs(array $data): array
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('servicelicense', 'manage');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('servicelicense', 'manage');
$plugins = $this->getService()->getLicensePlugins();
$result = [];
@@ -52,7 +52,7 @@ class Admin extends \Api_Abstract
*/
public function update($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('servicelicense', 'manage');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('servicelicense', 'manage');
$s = $this->_getService($data);
@@ -66,7 +66,7 @@ class Admin extends \Api_Abstract
*/
public function reset($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('servicelicense', 'manage');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('servicelicense', 'manage');
$s = $this->_getService($data);
@@ -81,11 +81,11 @@ class Admin extends \Api_Abstract
public function _getService(array $data)
{
$required = ['order_id' => 'Order ID is required'];
- $this->di['validator']->checkRequiredParamsForArray($required, $data);
+ $this->getDi()['validator']->checkRequiredParamsForArray($required, $data);
- $order = $this->di['db']->getExistingModelById('clientOrder', $data['order_id'], 'Order not found');
+ $order = $this->getDi()['db']->getExistingModelById('clientOrder', $data['order_id'], 'Order not found');
- $orderService = $this->di['mod_service']('order');
+ $orderService = $this->getDi()['mod_service']('order');
$s = $orderService->getOrderService($order);
if (!$s instanceof \Model_ServiceLicense) {
throw new \FOSSBilling\Exception('Order is not activated');
diff --git a/src/modules/Servicelicense/Api/Client.php b/src/modules/Servicelicense/Api/Client.php
index 8dede26b2..c1885cdc2 100644
--- a/src/modules/Servicelicense/Api/Client.php
+++ b/src/modules/Servicelicense/Api/Client.php
@@ -32,7 +32,7 @@ class Client extends \Api_Abstract
public function _getService(array $data)
{
$required = ['order_id' => 'Order ID is required'];
- $this->di['validator']->checkRequiredParamsForArray($required, $data);
+ $this->getDi()['validator']->checkRequiredParamsForArray($required, $data);
$client = $this->getIdentity();
@@ -41,7 +41,7 @@ class Client extends \Api_Abstract
':client_id' => $client->id,
];
- $order = $this->di['db']->findOne('ClientOrder', 'id = :id AND client_id = :client_id', $bindings);
+ $order = $this->getDi()['db']->findOne('ClientOrder', 'id = :id AND client_id = :client_id', $bindings);
if (!$order instanceof \Model_ClientOrder) {
throw new \FOSSBilling\Exception('Order not found');
@@ -51,7 +51,7 @@ class Client extends \Api_Abstract
throw new \FOSSBilling\InformationException('Order is not activated');
}
- $orderService = $this->di['mod_service']('order');
+ $orderService = $this->getDi()['mod_service']('order');
$s = $orderService->getOrderService($order);
if (!$s instanceof \Model_ServiceLicense) {
throw new \FOSSBilling\Exception('Order is not activated');
diff --git a/src/modules/Servicelicense/Server.php b/src/modules/Servicelicense/Server.php
index 9eaf379b2..92aa0c0e4 100644
--- a/src/modules/Servicelicense/Server.php
+++ b/src/modules/Servicelicense/Server.php
@@ -33,22 +33,6 @@ class Server implements \FOSSBilling\InjectionAwareInterface
return $this->di;
}
- public function __construct(private readonly \Box_Log $_log)
- {
- }
-
- /**
- * @param string $key
- */
- private function getServer($key = null, $default = null)
- {
- if ($key === null) {
- return $_SERVER;
- }
-
- return $_SERVER[$key] ?? $default;
- }
-
public function process($data): array
{
$data = is_array($data) ? $data : (json_decode($data ?? '', true) ?: []);
diff --git a/src/modules/Servicelicense/Service.php b/src/modules/Servicelicense/Service.php
index eac1143ca..35a7ce220 100644
--- a/src/modules/Servicelicense/Service.php
+++ b/src/modules/Servicelicense/Service.php
@@ -382,7 +382,7 @@ class Service implements InjectionAwareInterface
return new $class_name();
}
}
- error_log("License #{$model->id} plugin {$model->plugin} is invalid.");
+ $this->di['logger']->warning("License #{$model->id} plugin {$model->plugin} is invalid.");
return null;
}
@@ -420,7 +420,7 @@ class Service implements InjectionAwareInterface
{
$result = [];
$log = $this->di['logger']->setChannel('license');
-
+ // @phpstan-ignore if.alwaysFalse (DEBUG is a runtime constant that may be true during debugging)
if (DEBUG) {
$log->debug(print_r($data, true));
}
diff --git a/src/modules/Servicelicense/tests/Unit/Api/AdminTest.php b/src/modules/Servicelicense/tests/Unit/Api/AdminTest.php
new file mode 100644
index 000000000..eb36b2872
--- /dev/null
+++ b/src/modules/Servicelicense/tests/Unit/Api/AdminTest.php
@@ -0,0 +1,150 @@
+setDi($di);
+ $getDi = $api->getDi();
+ expect($getDi)->toBe($di);
+});
+
+test('gets plugin pairs', function (): void {
+ $api = new Box\Mod\Servicelicense\Api\Admin();
+ $licensePluginArray[]['filename'] = 'plugin1';
+ $licensePluginArray[]['filename'] = 'plugin2';
+ $licensePluginArray[]['filename'] = 'plugin3';
+
+ $expected = [
+ 'plugin1' => 'plugin1',
+ 'plugin2' => 'plugin2',
+ 'plugin3' => 'plugin3',
+ ];
+
+ $serviceMock = Mockery::mock(Box\Mod\Servicelicense\Service::class);
+ $serviceMock->shouldReceive('getLicensePlugins')
+ ->atLeast()
+ ->once()
+ ->andReturn($licensePluginArray);
+
+ $api->setService($serviceMock);
+
+ $result = $api->plugin_get_pairs([]);
+ expect($result)->toBeArray()
+ ->and($result)->toBe($expected);
+});
+
+test('updates license', function (): void {
+ $api = new Box\Mod\Servicelicense\Api\Admin();
+ $data = [
+ 'order_id' => 1,
+ ];
+
+ $apiMock = Mockery::mock(Box\Mod\Servicelicense\Api\Admin::class)->makePartial();
+ $apiMock->shouldAllowMockingProtectedMethods();
+ $apiMock->shouldReceive('_getService')
+ ->atLeast()
+ ->once()
+ ->andReturn(new Model_ServiceLicense());
+
+ $serviceMock = Mockery::mock(Box\Mod\Servicelicense\Service::class);
+ $serviceMock->shouldReceive('update')
+ ->atLeast()
+ ->once()
+ ->andReturn(true);
+
+ $apiMock->setService($serviceMock);
+ $result = $apiMock->update($data);
+
+ expect($result)->toBeBool()
+ ->and($result)->toBeTrue();
+});
+
+test('resets license', function (): void {
+ $api = new Box\Mod\Servicelicense\Api\Admin();
+ $data = [
+ 'order_id' => 1,
+ ];
+
+ $apiMock = Mockery::mock(Box\Mod\Servicelicense\Api\Admin::class)->makePartial();
+ $apiMock->shouldAllowMockingProtectedMethods();
+ $apiMock->shouldReceive('_getService')
+ ->atLeast()
+ ->once()
+ ->andReturn(new Model_ServiceLicense());
+
+ $serviceMock = Mockery::mock(Box\Mod\Servicelicense\Service::class);
+ $serviceMock->shouldReceive('reset')
+ ->atLeast()
+ ->once()
+ ->andReturn(true);
+
+ $apiMock->setService($serviceMock);
+ $result = $apiMock->reset($data);
+
+ expect($result)->toBeBool()
+ ->and($result)->toBeTrue();
+});
+
+test('gets service', function (): void {
+ $api = new Box\Mod\Servicelicense\Api\Admin();
+ $data['order_id'] = 1;
+
+ $orderServiceMock = Mockery::mock(Box\Mod\Order\Service::class);
+ $orderServiceMock->shouldReceive('getOrderService')
+ ->atLeast()
+ ->once()
+ ->andReturn(new Model_ServiceLicense());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getExistingModelById')
+ ->atLeast()
+ ->once()
+ ->andReturn(new Model_ClientOrder());
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
+
+ $api->setDi($di);
+
+ $result = $api->_getService($data);
+ expect($result)->toBeInstanceOf(Model_ServiceLicense::class);
+});
+
+test('throws exception when order not activated', function (): void {
+ $api = new Box\Mod\Servicelicense\Api\Admin();
+ $data['order_id'] = 1;
+
+ $orderServiceMock = Mockery::mock(Box\Mod\Order\Service::class);
+ $orderServiceMock->shouldReceive('getOrderService')
+ ->atLeast()
+ ->once()
+ ->andReturn(null);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getExistingModelById')
+ ->atLeast()
+ ->once()
+ ->andReturn(new Model_ClientOrder());
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
+
+ $api->setDi($di);
+
+ expect(fn () => $api->_getService($data))
+ ->toThrow(FOSSBilling\Exception::class, 'Order is not activated');
+});
diff --git a/src/modules/Servicelicense/tests/Unit/Api/ClientTest.php b/src/modules/Servicelicense/tests/Unit/Api/ClientTest.php
new file mode 100644
index 000000000..33225f6f5
--- /dev/null
+++ b/src/modules/Servicelicense/tests/Unit/Api/ClientTest.php
@@ -0,0 +1,112 @@
+setDi($di);
+ $getDi = $api->getDi();
+ expect($getDi)->toEqual($di);
+});
+
+test('reset returns true', function (): void {
+ $api = new Box\Mod\Servicelicense\Api\Client();
+ $data = [
+ 'order_id' => 1,
+ ];
+
+ $apiMock = Mockery::mock(Box\Mod\Servicelicense\Api\Client::class)->makePartial();
+ $apiMock->shouldAllowMockingProtectedMethods();
+ $apiMock->shouldReceive('_getService')
+ ->atLeast()
+ ->once()
+ ->andReturn(new Model_ServiceLicense());
+
+ $serviceMock = Mockery::mock(Box\Mod\Servicelicense\Service::class);
+ $serviceMock->shouldReceive('reset')
+ ->atLeast()
+ ->once()
+ ->andReturn(true);
+
+ $apiMock->setService($serviceMock);
+ $result = $apiMock->reset($data);
+
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+});
+
+test('getService returns service license model', function (): void {
+ $api = new Box\Mod\Servicelicense\Api\Client();
+ $data['order_id'] = 1;
+
+ $orderServiceMock = Mockery::mock(Box\Mod\Order\Service::class);
+ $orderServiceMock->shouldReceive('getOrderService')
+ ->atLeast()
+ ->once()
+ ->andReturn(new Model_ServiceLicense());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $clientOrder = new Model_ClientOrder();
+ $clientOrder->loadBean(new Tests\Helpers\DummyBean());
+ $clientOrder->status = Model_ClientOrder::STATUS_ACTIVE;
+
+ $dbMock->shouldReceive('findOne')
+ ->atLeast()
+ ->once()
+ ->andReturn($clientOrder);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
+
+ $api->setDi($di);
+
+ $clientModel = new Model_Client();
+ $clientModel->loadBean(new Tests\Helpers\DummyBean());
+ $api->setIdentity($clientModel);
+
+ $result = $api->_getService($data);
+ expect($result)->toBeInstanceOf(Model_ServiceLicense::class);
+});
+
+test('getService throws exception when order not activated', function (): void {
+ $api = new Box\Mod\Servicelicense\Api\Client();
+ $data['order_id'] = 1;
+
+ $orderServiceMock = Mockery::mock(Box\Mod\Order\Service::class);
+ $orderServiceMock->shouldReceive('getOrderService')
+ ->never()
+ ->andReturn(null);
+
+ $inactiveOrder = new Model_ClientOrder();
+ $inactiveOrder->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('findOne')
+ ->atLeast()
+ ->once()
+ ->andReturn($inactiveOrder);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
+
+ $api->setDi($di);
+
+ $clientModel = new Model_Client();
+ $clientModel->loadBean(new Tests\Helpers\DummyBean());
+ $api->setIdentity($clientModel);
+
+ $api->_getService($data);
+})->throws(FOSSBilling\Exception::class, 'Order is not activated');
diff --git a/src/modules/Servicelicense/tests/Unit/Api/GuestTest.php b/src/modules/Servicelicense/tests/Unit/Api/GuestTest.php
new file mode 100644
index 000000000..33ea7e4aa
--- /dev/null
+++ b/src/modules/Servicelicense/tests/Unit/Api/GuestTest.php
@@ -0,0 +1,49 @@
+setDi($di);
+ $getDi = $api->getDi();
+ expect($getDi)->toEqual($di);
+});
+
+test('check returns license details array', function (): void {
+ $api = new Guest();
+ $data = [
+ 'license' => 'license1234',
+ 'host' => 'fossbilling.org',
+ 'version' => 1,
+ ];
+
+ $licenseResult = [
+ 'licensed_to' => 'fossbilling.org',
+ 'created_at' => '2011-12-31',
+ 'expires_at' => '2020-01+01',
+ 'valid' => true,
+ ];
+ $serviceMock = Mockery::mock(Box\Mod\Servicelicense\Service::class);
+ $serviceMock->shouldReceive('checkLicenseDetails')
+ ->atLeast()
+ ->once()
+ ->andReturn($licenseResult);
+
+ $api->setService($serviceMock);
+ $result = $api->check($data);
+
+ expect($result)->toBeArray();
+});
diff --git a/src/modules/Servicelicense/tests/Unit/ServiceTest.php b/src/modules/Servicelicense/tests/Unit/ServiceTest.php
new file mode 100644
index 000000000..1edc41074
--- /dev/null
+++ b/src/modules/Servicelicense/tests/Unit/ServiceTest.php
@@ -0,0 +1,693 @@
+setDi($di);
+ $getDi = $service->getDi();
+ expect($getDi)->toBe($di);
+});
+
+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 = '{}';
+ $data = [];
+
+ $result = $service->attachOrderConfig($productModel, $data);
+ expect($result)->toBeArray();
+ 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"]';
+ $data = ['testing' => 'phase'];
+ $expected = array_merge(json_decode($productModel->config ?? '', true), $data);
+
+ $result = $service->attachOrderConfig($productModel, $data);
+ expect($result)->toBeArray();
+ expect($result)->toEqual($expected);
+});
+
+test('getLicensePlugins', function (): void {
+ $service = new Box\Mod\Servicelicense\Service();
+ $result = $service->getLicensePlugins();
+ expect($result)->toBeArray();
+});
+
+test('actionCreate', function (): void {
+ $service = new Box\Mod\Servicelicense\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();
+
+ $orderServiceMock = Mockery::mock(Box\Mod\Order\Service::class);
+ $orderServiceMock->shouldReceive('getConfig')
+ ->atLeast()
+ ->once()
+ ->andReturn([]);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
+
+ $service->setDi($di);
+
+ $result = $service->action_create($clientOrderModel);
+ expect($result)->toBeInstanceOf(Model_ServiceLicense::class);
+});
+
+test('actionActivate', function (): void {
+ $service = new Box\Mod\Servicelicense\Service();
+ $clientOrderModel = new Model_ClientOrder();
+ $clientOrderModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $serviceLicenseModel = new Model_ServiceLicense();
+ $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);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')->atLeast()->once();
+ $dbMock->shouldReceive('findOne')->atLeast()->once()->andReturn(null);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
+
+ $service->setDi($di);
+
+ $result = $service->action_activate($clientOrderModel);
+ expect($result)->toBeTrue();
+});
+
+test('actionActivate with license collision', function (): void {
+ $service = new Box\Mod\Servicelicense\Service();
+ $clientOrderModel = new Model_ClientOrder();
+ $clientOrderModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $serviceLicenseModel = new Model_ServiceLicense();
+ $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);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')->atLeast()->once();
+ $dbMock->shouldReceive('findOne')
+ ->times(3)
+ ->andReturnUsing(function () use ($serviceLicenseModel) {
+ static $callCount = 0;
+ ++$callCount;
+
+ return $callCount <= 2 ? $serviceLicenseModel : null;
+ });
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
+
+ $service->setDi($di);
+
+ $result = $service->action_activate($clientOrderModel);
+ expect($result)->toBeTrue();
+});
+
+test('actionActivate with license collision max iterations exception', function (): void {
+ $service = new Box\Mod\Servicelicense\Service();
+ $clientOrderModel = new Model_ClientOrder();
+ $clientOrderModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $serviceLicenseModel = new Model_ServiceLicense();
+ $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);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')->never();
+ $dbMock->shouldReceive('findOne')
+ ->atLeast()
+ ->once()
+ ->andReturn($serviceLicenseModel);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
+
+ $service->setDi($di);
+
+ expect(fn (): bool => $service->action_activate($clientOrderModel))
+ ->toThrow(FOSSBilling\Exception::class);
+});
+
+test('actionActivate with plugin not found', function (): void {
+ $service = new Box\Mod\Servicelicense\Service();
+ $clientOrderModel = new Model_ClientOrder();
+ $clientOrderModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $serviceLicenseModel = new Model_ServiceLicense();
+ $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);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
+
+ $service->setDi($di);
+
+ expect(fn (): bool => $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();
+ $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);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
+
+ $service->setDi($di);
+
+ expect(fn (): bool => $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();
+ $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);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('trash')->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
+
+ $service->setDi($di);
+ $service->action_delete($clientOrderModel);
+});
+
+test('reset', function (): void {
+ $service = new Box\Mod\Servicelicense\Service();
+ $serviceLicenseModel = new Model_ServiceLicense();
+ $serviceLicenseModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $eventMock = Mockery::mock('\Box_EventManager');
+ $eventMock->shouldReceive('fire')->atLeast()->once();
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $di['events_manager'] = $eventMock;
+
+ $service->setDi($di);
+ $result = $service->reset($serviceLicenseModel);
+ expect($result)->toBeTrue();
+});
+
+test('isLicenseActive', function (): void {
+ $service = new Box\Mod\Servicelicense\Service();
+ $clientOrderModel = new Model_ClientOrder();
+ $clientOrderModel->loadBean(new Tests\Helpers\DummyBean());
+ $clientOrderModel->status = Model_ClientOrder::STATUS_ACTIVE;
+
+ $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);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
+
+ $service->setDi($di);
+ $result = $service->isLicenseActive($serviceLicenseModel);
+ expect($result)->toBeTrue();
+});
+
+test('isLicenseNotActive', function (): void {
+ $service = new Box\Mod\Servicelicense\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);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
+
+ $service->setDi($di);
+ $result = $service->isLicenseActive($serviceLicenseModel);
+ expect($result)->toBeFalse();
+});
+
+test('isValidIp', function (): void {
+ $service = new Box\Mod\Servicelicense\Service();
+ $serviceLicenseModel = new Model_ServiceLicense();
+ $serviceLicenseModel->loadBean(new Tests\Helpers\DummyBean());
+ $serviceLicenseModel->ips = '{}';
+ $value = '1.1.1.1';
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $service->setDi($di);
+
+ $result = $service->isValidIp($serviceLicenseModel, $value);
+ expect($result)->toBeTrue();
+});
+
+test('isValidIp test 2', function (): void {
+ $service = new Box\Mod\Servicelicense\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->shouldReceive('store')->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $service->setDi($di);
+
+ $result = $service->isValidIp($serviceLicenseModel, $value);
+ expect($result)->toBeTrue();
+});
+
+test('isValidIp test 3', function (): void {
+ $service = new Box\Mod\Servicelicense\Service();
+ $serviceLicenseModel = new Model_ServiceLicense();
+ $serviceLicenseModel->loadBean(new Tests\Helpers\DummyBean());
+ $serviceLicenseModel->ips = '["2.2.2.2"]';
+ $serviceLicenseModel->validate_ip = '3.3.3.3';
+ $value = '1.1.1.1';
+
+ $result = $service->isValidIp($serviceLicenseModel, $value);
+ expect($result)->toBeFalse();
+});
+
+test('isValidVersion', function (): void {
+ $service = new Box\Mod\Servicelicense\Service();
+ $serviceLicenseModel = new Model_ServiceLicense();
+ $serviceLicenseModel->loadBean(new Tests\Helpers\DummyBean());
+ $serviceLicenseModel->versions = '{}';
+ $value = '1.0';
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $service->setDi($di);
+
+ $result = $service->isValidVersion($serviceLicenseModel, $value);
+ expect($result)->toBeTrue();
+});
+
+test('isValidVersion test 2', function (): void {
+ $service = new Box\Mod\Servicelicense\Service();
+ $serviceLicenseModel = new Model_ServiceLicense();
+ $serviceLicenseModel->loadBean(new Tests\Helpers\DummyBean());
+ $serviceLicenseModel->versions = '["2.0"]';
+ $value = '1.0';
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $service->setDi($di);
+
+ $result = $service->isValidVersion($serviceLicenseModel, $value);
+ expect($result)->toBeTrue();
+});
+
+test('isValidVersion test 3', function (): void {
+ $service = new Box\Mod\Servicelicense\Service();
+ $serviceLicenseModel = new Model_ServiceLicense();
+ $serviceLicenseModel->loadBean(new Tests\Helpers\DummyBean());
+ $serviceLicenseModel->versions = '["2.0"]';
+ $serviceLicenseModel->validate_version = '3.3.3.3';
+ $value = '1.0';
+
+ $result = $service->isValidVersion($serviceLicenseModel, $value);
+ expect($result)->toBeFalse();
+});
+
+test('isValidPath', function (): void {
+ $service = new Box\Mod\Servicelicense\Service();
+ $serviceLicenseModel = new Model_ServiceLicense();
+ $serviceLicenseModel->loadBean(new Tests\Helpers\DummyBean());
+ $serviceLicenseModel->paths = '{}';
+ $value = '/var';
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $service->setDi($di);
+
+ $result = $service->isValidPath($serviceLicenseModel, $value);
+ expect($result)->toBeTrue();
+});
+
+test('isValidPath test 2', function (): void {
+ $service = new Box\Mod\Servicelicense\Service();
+ $serviceLicenseModel = new Model_ServiceLicense();
+ $serviceLicenseModel->loadBean(new Tests\Helpers\DummyBean());
+ $serviceLicenseModel->paths = '["/"]';
+ $value = '/var';
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $service->setDi($di);
+
+ $result = $service->isValidPath($serviceLicenseModel, $value);
+ expect($result)->toBeTrue();
+});
+
+test('isValidPath test 3', function (): void {
+ $service = new Box\Mod\Servicelicense\Service();
+ $serviceLicenseModel = new Model_ServiceLicense();
+ $serviceLicenseModel->loadBean(new Tests\Helpers\DummyBean());
+ $serviceLicenseModel->paths = '["/"]';
+ $serviceLicenseModel->validate_path = '/user';
+ $value = '/var';
+
+ $result = $service->isValidPath($serviceLicenseModel, $value);
+ expect($result)->toBeFalse();
+});
+
+test('isValidHost', function (): void {
+ $service = new Box\Mod\Servicelicense\Service();
+ $serviceLicenseModel = new Model_ServiceLicense();
+ $serviceLicenseModel->loadBean(new Tests\Helpers\DummyBean());
+ $serviceLicenseModel->hosts = '{}';
+ $value = 'site.com';
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $service->setDi($di);
+
+ $result = $service->isValidHost($serviceLicenseModel, $value);
+ expect($result)->toBeTrue();
+});
+
+test('isValidHost test 2', function (): void {
+ $service = new Box\Mod\Servicelicense\Service();
+ $serviceLicenseModel = new Model_ServiceLicense();
+ $serviceLicenseModel->loadBean(new Tests\Helpers\DummyBean());
+ $serviceLicenseModel->hosts = '["fossbilling.org"]';
+ $value = 'site.com';
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $service->setDi($di);
+
+ $result = $service->isValidHost($serviceLicenseModel, $value);
+ expect($result)->toBeTrue();
+});
+
+test('isValidHost test 3', function (): void {
+ $service = new Box\Mod\Servicelicense\Service();
+ $serviceLicenseModel = new Model_ServiceLicense();
+ $serviceLicenseModel->loadBean(new Tests\Helpers\DummyBean());
+ $serviceLicenseModel->hosts = '["fossbilling.org"]';
+ $serviceLicenseModel->validate_host = 'example.com';
+ $value = 'site.com';
+
+ $result = $service->isValidHost($serviceLicenseModel, $value);
+ expect($result)->toBeFalse();
+});
+
+test('getAdditionalParams', function (): void {
+ $service = new Box\Mod\Servicelicense\Service();
+ $serviceLicenseModel = new Model_ServiceLicense();
+ $serviceLicenseModel->loadBean(new Tests\Helpers\DummyBean());
+ $serviceLicenseModel->plugin = 'Simple';
+
+ $result = $service->getAdditionalParams($serviceLicenseModel);
+ expect($result)->toBeArray();
+});
+
+test('getOwnerName', function (): void {
+ $service = new Box\Mod\Servicelicense\Service();
+ $clientModel = new Model_Client();
+ $clientModel->loadBean(new Tests\Helpers\DummyBean());
+ $clientModel->first_name = 'John';
+ $clientModel->last_name = 'Smith';
+
+ $serviceLicenseModel = new Model_ServiceLicense();
+ $serviceLicenseModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $expected = $clientModel->first_name . ' ' . $clientModel->last_name;
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('load')
+ ->atLeast()
+ ->once()
+ ->andReturn($clientModel);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $service->setDi($di);
+
+ $result = $service->getOwnerName($serviceLicenseModel);
+ expect($result)->toBeString();
+ expect($result)->toBe($expected);
+});
+
+test('getExpirationDate', function (): void {
+ $service = new Box\Mod\Servicelicense\Service();
+ $expected = '2004-02-12 15:19:21';
+ $clientOrderModel = new Model_ClientOrder();
+ $clientOrderModel->loadBean(new Tests\Helpers\DummyBean());
+ $clientOrderModel->expires_at = $expected;
+
+ $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);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
+
+ $service->setDi($di);
+
+ $result = $service->getExpirationDate($serviceLicenseModel);
+ expect($result)->toBeString();
+ expect($result)->toBe($expected);
+});
+
+test('toApiArray', function (): void {
+ $service = new Box\Mod\Servicelicense\Service();
+ $serviceLicenseModel = new Model_ServiceLicense();
+ $serviceLicenseModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $expected = [
+ 'license_key' => '',
+ 'validate_ip' => '',
+ 'validate_host' => '',
+ 'validate_version' => '',
+ 'validate_path' => '',
+ 'ips' => '',
+ 'hosts' => '',
+ 'paths' => '',
+ 'versions' => '',
+ 'pinged_at' => '',
+ 'plugin' => '',
+ ];
+
+ $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.');
+});
+
+test('update', function (): void {
+ $service = new Box\Mod\Servicelicense\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',
+ 'pinged_at' => '',
+ 'plugin' => 'Simple',
+ ];
+ $serviceLicenseModel = new Model_ServiceLicense();
+ $serviceLicenseModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $service->setDi($di);
+ $result = $service->update($serviceLicenseModel, $data);
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+});
+
+test('checkLicenseDetails with format eq 2', function (): void {
+ $service = new Box\Mod\Servicelicense\Service();
+
+ $data = [
+ 'format' => 2,
+ ];
+
+ $licenseServerMock = Mockery::mock(Box\Mod\Servicelicense\Server::class);
+ $licenseServerMock->shouldReceive('process')
+ ->atLeast()
+ ->once()
+ ->andReturn([]);
+
+ $di = container();
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $di['license_server'] = $licenseServerMock;
+ $service->setDi($di);
+
+ $result = $service->checkLicenseDetails($data);
+
+ expect($result)->toBeArray();
+ expect($result)->toHaveKey('error');
+ expect($result)->toHaveKey('error_code');
+});
+
+test('checkLicenseDetails', function (): void {
+ $service = new Box\Mod\Servicelicense\Service();
+
+ $data = [];
+
+ $licenseServerMock = Mockery::mock(Box\Mod\Servicelicense\Server::class);
+ $licenseServerMock->shouldReceive('process')
+ ->atLeast()
+ ->once()
+ ->andReturn([]);
+
+ $di = container();
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $di['license_server'] = $licenseServerMock;
+ $service->setDi($di);
+
+ $result = $service->checkLicenseDetails($data);
+
+ expect($result)->toBeArray();
+});
diff --git a/src/modules/Staff/Api/Admin.php b/src/modules/Staff/Api/Admin.php
index d66494532..bc765b21f 100644
--- a/src/modules/Staff/Api/Admin.php
+++ b/src/modules/Staff/Api/Admin.php
@@ -28,15 +28,15 @@ class Admin extends \Api_Abstract
*/
public function get_list($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('staff', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('staff', 'view');
$data['no_cron'] = true;
[$sql, $params] = $this->getService()->getSearchQuery($data);
- $pager = $this->di['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
+ $pager = $this->getDi()['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
foreach ($pager['list'] as $key => $item) {
- $staff = $this->di['db']->getExistingModelById('Admin', $item['id'] ?? 0, 'Admin is not found');
+ $staff = $this->getDi()['db']->getExistingModelById('Admin', $item['id'] ?? 0, 'Admin is not found');
$pager['list'][$key] = $this->getService()->toModel_AdminApiArray($staff);
}
@@ -52,7 +52,7 @@ class Admin extends \Api_Abstract
*/
public function get_pairs(array $data): array
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('staff', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('staff', 'view');
return $this->getService()->getPairs($data);
}
@@ -67,9 +67,9 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'ID was not passed'])]
public function get($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('staff', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('staff', 'view');
- $model = $this->di['db']->getExistingModelById('Admin', $data['id'], 'Staff member not found');
+ $model = $this->getDi()['db']->getExistingModelById('Admin', $data['id'], 'Staff member not found');
return $this->getService()->toModel_AdminApiArray($model);
}
@@ -90,12 +90,12 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'ID was not passed'])]
public function update($data)
{
- $model = $this->di['db']->getExistingModelById('Admin', $data['id'], 'Staff member not found');
+ $model = $this->getDi()['db']->getExistingModelById('Admin', $data['id'], 'Staff member not found');
$role = $model->role === 'admin' ? 'admin' : 'staff';
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('staff', $role === 'admin' ? 'create_and_edit_admin' : 'create_and_edit_staff');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('staff', $role === 'admin' ? 'create_and_edit_admin' : 'create_and_edit_staff');
if (isset($data['email'])) {
- $data['email'] = $this->di['tools']->validateAndSanitizeEmail($data['email']);
+ $data['email'] = $this->getDi()['tools']->validateAndSanitizeEmail($data['email']);
}
return $this->getService()->update($model, $data);
@@ -111,9 +111,9 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'ID was not passed'])]
public function delete($data)
{
- $model = $this->di['db']->getExistingModelById('Admin', $data['id'], 'Staff member not found');
+ $model = $this->getDi()['db']->getExistingModelById('Admin', $data['id'], 'Staff member not found');
$role = $model->role === 'admin' ? 'admin' : 'staff';
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('staff', $role === 'admin' ? 'delete_admin' : 'delete_staff');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('staff', $role === 'admin' ? 'delete_admin' : 'delete_staff');
return $this->getService()->delete($model);
}
@@ -132,13 +132,13 @@ class Admin extends \Api_Abstract
])]
public function change_password($data)
{
- $this->di['validator']->passwordsMatch($data);
+ $this->getDi()['validator']->passwordsMatch($data);
- $this->di['validator']->isPasswordStrong($data['password']);
+ $this->getDi()['validator']->isPasswordStrong($data['password']);
- $model = $this->di['db']->getExistingModelById('Admin', $data['id'], 'Staff member not found');
+ $model = $this->getDi()['db']->getExistingModelById('Admin', $data['id'], 'Staff member not found');
$role = $model->role === 'admin' ? 'admin' : 'staff';
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('staff', $role === 'admin' ? 'reset_admin_password' : 'reset_staff_password');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('staff', $role === 'admin' ? 'reset_admin_password' : 'reset_staff_password');
return $this->getService()->changePassword($model, $data['password']);
}
@@ -161,11 +161,11 @@ class Admin extends \Api_Abstract
public function create($data)
{
$role = $data['role'] ?? 'staff';
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('staff', $role === 'admin' ? 'create_and_edit_admin' : 'create_and_edit_staff');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('staff', $role === 'admin' ? 'create_and_edit_admin' : 'create_and_edit_staff');
- $data['email'] = $this->di['tools']->validateAndSanitizeEmail($data['email']);
+ $data['email'] = $this->getDi()['tools']->validateAndSanitizeEmail($data['email']);
- $this->di['validator']->isPasswordStrong($data['password']);
+ $this->getDi()['validator']->isPasswordStrong($data['password']);
return $this->getService()->create($data);
}
@@ -178,9 +178,9 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'ID was not passed'])]
public function permissions_get($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('staff', 'create_and_edit_staff');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('staff', 'create_and_edit_staff');
- $model = $this->di['db']->getExistingModelById('Admin', $data['id'], 'Staff member not found');
+ $model = $this->getDi()['db']->getExistingModelById('Admin', $data['id'], 'Staff member not found');
return $this->getService()->getPermissions($model->id);
}
@@ -191,9 +191,9 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'ID was not passed', 'permissions' => 'Missing "permissions" parameter'])]
public function permissions_update($data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('staff', 'manage_settings');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('staff', 'manage_settings');
- $model = $this->di['db']->getExistingModelById('Admin', $data['id'], 'Staff member not found');
+ $model = $this->getDi()['db']->getExistingModelById('Admin', $data['id'], 'Staff member not found');
if (!is_array($data['permissions'])) {
throw new \FOSSBilling\InformationException('Parameter "permissions" must be an array');
@@ -201,7 +201,7 @@ class Admin extends \Api_Abstract
$this->getService()->setPermissions($model, $data['permissions']);
- $this->di['logger']->info('Changed staff member %s permissions', $model->id);
+ $this->getDi()['logger']->info('Changed staff member %s permissions', $model->id);
return true;
}
@@ -213,7 +213,7 @@ class Admin extends \Api_Abstract
*/
public function group_get_pairs($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('staff', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('staff', 'view');
return $this->getService()->getAdminGroupPair();
}
@@ -225,13 +225,13 @@ class Admin extends \Api_Abstract
*/
public function group_get_list($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('staff', 'manage_groups');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('staff', 'manage_groups');
[$sql, $params] = $this->getService()->getAdminGroupSearchQuery($data);
- $pager = $this->di['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
+ $pager = $this->getDi()['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
foreach ($pager['list'] as $key => $item) {
- $model = $this->di['db']->getExistingModelById('AdminGroup', $item['id'], 'Post not found');
+ $model = $this->getDi()['db']->getExistingModelById('AdminGroup', $item['id'], 'Post not found');
$pager['list'][$key] = $this->getService()->toAdminGroupApiArray($model, false, $this->getIdentity());
}
@@ -248,7 +248,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['name' => 'Group name was not passed'])]
public function group_create($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('staff', 'manage_groups');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('staff', 'manage_groups');
return $this->getService()->createGroup($data['name']);
}
@@ -263,9 +263,9 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Group ID was not passed'])]
public function group_get($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('staff', 'manage_groups');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('staff', 'manage_groups');
- $model = $this->di['db']->getExistingModelById('AdminGroup', $data['id'], 'Group not found');
+ $model = $this->getDi()['db']->getExistingModelById('AdminGroup', $data['id'], 'Group not found');
return $this->getService()->toAdminGroupApiArray($model, true, $this->getIdentity());
}
@@ -280,9 +280,9 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Group ID was not passed'])]
public function group_delete($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('staff', 'manage_groups');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('staff', 'manage_groups');
- $model = $this->di['db']->getExistingModelById('AdminGroup', $data['id'], 'Group not found');
+ $model = $this->getDi()['db']->getExistingModelById('AdminGroup', $data['id'], 'Group not found');
return $this->getService()->deleteGroup($model);
}
@@ -299,9 +299,9 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Group ID was not passed'])]
public function group_update($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('staff', 'manage_groups');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('staff', 'manage_groups');
- $model = $this->di['db']->getExistingModelById('AdminGroup', $data['id'], 'Group not found');
+ $model = $this->getDi()['db']->getExistingModelById('AdminGroup', $data['id'], 'Group not found');
return $this->getService()->updateGroup($model, $data);
}
@@ -313,13 +313,13 @@ class Admin extends \Api_Abstract
*/
public function login_history_get_list($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('staff', 'manage_settings');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('staff', 'manage_settings');
[$sql, $params] = $this->getService()->getActivityAdminHistorySearchQuery($data);
- $pager = $this->di['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
+ $pager = $this->getDi()['pager']->getPaginatedResultSet($sql, $params, PaginationOptions::fromArray($data));
foreach ($pager['list'] as $key => $item) {
- $activity = $this->di['db']->getExistingModelById('ActivityAdminHistory', $item['id'] ?? 0, sprintf('Staff activity item #%s not found', $item['id'] ?? 'unknown'));
+ $activity = $this->getDi()['db']->getExistingModelById('ActivityAdminHistory', $item['id'] ?? 0, sprintf('Staff activity item #%s not found', $item['id'] ?? 'unknown'));
if ($activity) {
$pager['list'][$key] = $this->getService()->toActivityAdminHistoryApiArray($activity);
}
@@ -336,9 +336,9 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Event ID was not passed'])]
public function login_history_get($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('staff', 'manage_settings');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('staff', 'manage_settings');
- $model = $this->di['db']->getExistingModelById('ActivityAdminHistory', $data['id'], 'Event not found');
+ $model = $this->getDi()['db']->getExistingModelById('ActivityAdminHistory', $data['id'], 'Event not found');
return $this->getService()->toActivityAdminHistoryApiArray($model);
}
diff --git a/src/modules/Staff/Api/Guest.php b/src/modules/Staff/Api/Guest.php
index 84d3b33b8..234c31897 100644
--- a/src/modules/Staff/Api/Guest.php
+++ b/src/modules/Staff/Api/Guest.php
@@ -34,7 +34,7 @@ class Guest extends \Api_Abstract
$startedAt = microtime(true);
try {
- $data['email'] = $this->di['tools']->validateAndSanitizeEmail($data['email'], true, false);
+ $data['email'] = $this->getDi()['tools']->validateAndSanitizeEmail($data['email'], true, false);
$config = $this->getMod()->getConfig();
@@ -48,7 +48,7 @@ class Guest extends \Api_Abstract
}
$result = $this->getService()->login($data['email'], $data['password'], $this->getIp());
- $this->di['session']->delete('redirect_uri');
+ $this->getDi()['session']->delete('redirect_uri');
return $result;
} finally {
@@ -61,60 +61,60 @@ class Guest extends \Api_Abstract
$startedAt = microtime(true);
try {
- $this->di['rate_limiter']->consumeOrThrow('staff_password_reset_confirm_post_ip', (string) $this->getIp());
+ $this->getDi()['rate_limiter']->consumeOrThrow('staff_password_reset_confirm_post_ip', (string) $this->getIp());
$config = $this->getMod()->getConfig();
if (isset($config['public']['reset_pw']) && $config['public']['reset_pw'] == '0') {
throw new \FOSSBilling\InformationException('Password reset has been disabled');
}
- $this->di['events_manager']->fire(['event' => 'onBeforePasswordResetStaff']);
+ $this->getDi()['events_manager']->fire(['event' => 'onBeforePasswordResetStaff']);
$required = [
'code' => 'Code required',
'password' => 'Password required',
'password_confirm' => 'Password confirmation required',
];
- $validator = $this->di['validator'];
+ $validator = $this->getDi()['validator'];
$validator->checkRequiredParamsForArray($required, $data);
$validator->passwordsMatch($data);
$validator->isPasswordStrong($data['password']);
- $reset = $this->di['db']->findOne('AdminPasswordReset', 'hash = ?', [$data['code']]);
+ $reset = $this->getDi()['db']->findOne('AdminPasswordReset', 'hash = ?', [$data['code']]);
if (!$reset instanceof \Model_AdminPasswordReset) {
- $this->di['logger']->setChannel('security')->info('Staff password reset confirmation failed from IP %s: reset token not found', $this->getIp());
+ $this->getDi()['logger']->setChannel('security')->info('Staff password reset confirmation failed from IP %s: reset token not found', $this->getIp());
throw new \FOSSBilling\InformationException('The link has expired or you have already confirmed the password reset.');
}
if (strtotime($reset->created_at) - time() + 900 < 0) {
- $this->di['logger']->setChannel('security')->info('Staff password reset confirmation failed for admin #%s from IP %s: reset token expired', $reset->admin_id, $this->getIp());
+ $this->getDi()['logger']->setChannel('security')->info('Staff password reset confirmation failed for admin #%s from IP %s: reset token expired', $reset->admin_id, $this->getIp());
throw new \FOSSBilling\InformationException('The link has expired or you have already confirmed the password reset.');
}
- $admin = $this->di['db']->getExistingModelById('Admin', $reset->admin_id, 'Admin not found');
+ $admin = $this->getDi()['db']->getExistingModelById('Admin', $reset->admin_id, 'Admin not found');
if ($admin->status !== \Model_Admin::STATUS_ACTIVE || $admin->role === \Model_Admin::ROLE_CRON) {
- $this->di['logger']->setChannel('security')->info('Staff password reset confirmation failed for admin #%s from IP %s: account status %s, role %s', $admin->id, $this->getIp(), $admin->status, $admin->role);
+ $this->getDi()['logger']->setChannel('security')->info('Staff password reset confirmation failed for admin #%s from IP %s: account status %s, role %s', $admin->id, $this->getIp(), $admin->status, $admin->role);
throw new \FOSSBilling\InformationException('The link has expired or you have already confirmed the password reset.');
}
- $admin->pass = $this->di['password']->hashIt($data['password']);
- $this->di['db']->store($admin);
+ $admin->pass = $this->getDi()['password']->hashIt($data['password']);
+ $this->getDi()['db']->store($admin);
- $this->di['logger']->setChannel('security')->info('Staff password reset completed for admin #%s from IP %s', $admin->id, $this->getIp());
+ $this->getDi()['logger']->setChannel('security')->info('Staff password reset completed for admin #%s from IP %s', $admin->id, $this->getIp());
- $this->di['events_manager']->fire(['event' => 'onAfterPasswordResetStaff', 'params' => ['id' => $admin->id]]);
+ $this->getDi()['events_manager']->fire(['event' => 'onAfterPasswordResetStaff', 'params' => ['id' => $admin->id]]);
// send email
$email = [];
$email['to_admin'] = $admin->id;
$email['code'] = 'mod_staff_password_reset_approve';
- $emailService = $this->di['mod_service']('email');
+ $emailService = $this->getDi()['mod_service']('email');
$emailService->sendTemplate($email);
- $this->di['db']->trash($reset);
+ $this->getDi()['db']->trash($reset);
} finally {
RandomizedTimeFloor::apply($startedAt, 300, 450);
}
@@ -130,63 +130,63 @@ class Guest extends \Api_Abstract
$startedAt = microtime(true);
try {
- $this->di['events_manager']->fire(['event' => 'onBeforePasswordResetStaff']);
+ $this->getDi()['events_manager']->fire(['event' => 'onBeforePasswordResetStaff']);
$required = [
'email' => 'Email required',
];
- $validator = $this->di['validator'];
+ $validator = $this->getDi()['validator'];
$validator->checkRequiredParamsForArray($required, $data);
- $data['email'] = $this->di['tools']->validateAndSanitizeEmail($data['email']);
+ $data['email'] = $this->getDi()['tools']->validateAndSanitizeEmail($data['email']);
- $ipLimit = $this->di['rate_limiter']->consume('staff_password_reset_ip', (string) $this->getIp());
+ $ipLimit = $this->getDi()['rate_limiter']->consume('staff_password_reset_ip', (string) $this->getIp());
if ($ipLimit->isLimited()) {
- $this->di['logger']->setChannel('security')->info('Staff password reset rate limited from IP %s: email %s', $this->getIp(), $data['email']);
+ $this->getDi()['logger']->setChannel('security')->info('Staff password reset rate limited from IP %s: email %s', $this->getIp(), $data['email']);
return true;
}
$this->checkPasswordResetCaptcha($data);
- $emailLimit = $this->di['rate_limiter']->consume('staff_password_reset_email', (string) $data['email']);
+ $emailLimit = $this->getDi()['rate_limiter']->consume('staff_password_reset_email', (string) $data['email']);
if ($emailLimit->isLimited()) {
- $this->di['logger']->setChannel('security')->info('Staff password reset rate limited for email %s from IP %s', $data['email'], $this->getIp());
+ $this->getDi()['logger']->setChannel('security')->info('Staff password reset rate limited for email %s from IP %s', $data['email'], $this->getIp());
return true;
}
- $c = $this->di['db']->findOne('Admin', 'email = ?', [$data['email']]);
+ $c = $this->getDi()['db']->findOne('Admin', 'email = ?', [$data['email']]);
if (!$c instanceof \Model_Admin) {
- $this->di['logger']->setChannel('security')->info('Staff password reset requested for unknown email %s from IP %s', $data['email'], $this->getIp());
+ $this->getDi()['logger']->setChannel('security')->info('Staff password reset requested for unknown email %s from IP %s', $data['email'], $this->getIp());
return true;
}
if ($c->status !== \Model_Admin::STATUS_ACTIVE || $c->role === \Model_Admin::ROLE_CRON) {
- $this->di['logger']->setChannel('security')->info('Staff password reset requested for ineligible admin #%s from IP %s: email %s, account status %s, role %s', $c->id, $this->getIp(), $data['email'], $c->status, $c->role);
+ $this->getDi()['logger']->setChannel('security')->info('Staff password reset requested for ineligible admin #%s from IP %s: email %s, account status %s, role %s', $c->id, $this->getIp(), $data['email'], $c->status, $c->role);
return true;
}
$hash = hash('sha256', random_bytes(32));
- $reset = $this->di['db']->dispense('AdminPasswordReset');
+ $reset = $this->getDi()['db']->dispense('AdminPasswordReset');
$reset->admin_id = $c->id;
$reset->ip = $this->ip;
$reset->hash = $hash;
$reset->created_at = date('Y-m-d H:i:s');
$reset->updated_at = date('Y-m-d H:i:s');
- $this->di['db']->store($reset);
+ $this->getDi()['db']->store($reset);
// send email
$email = [];
$email['to_admin'] = $c->id;
$email['code'] = 'mod_staff_password_reset_request';
$email['hash'] = $hash;
- $emailService = $this->di['mod_service']('email');
+ $emailService = $this->getDi()['mod_service']('email');
$emailService->sendTemplate($email);
- $this->di['logger']->setChannel('security')->info('Staff password reset email queued for admin #%s from IP %s: email %s', $c->id, $this->getIp(), $data['email']);
+ $this->getDi()['logger']->setChannel('security')->info('Staff password reset email queued for admin #%s from IP %s: email %s', $c->id, $this->getIp(), $data['email']);
return true;
} finally {
@@ -196,11 +196,11 @@ class Guest extends \Api_Abstract
private function checkPasswordResetCaptcha(array $data): void
{
- $extensionService = $this->di['mod_service']('extension');
+ $extensionService = $this->getDi()['mod_service']('extension');
if (!$extensionService->isExtensionActive('mod', 'antispam')) {
return;
}
- $this->di['mod_service']('Antispam')->checkCaptcha($data);
+ $this->getDi()['mod_service']('Antispam')->checkCaptcha($data);
}
}
diff --git a/src/modules/Staff/Service.php b/src/modules/Staff/Service.php
index 945ef05cc..4668227c3 100644
--- a/src/modules/Staff/Service.php
+++ b/src/modules/Staff/Service.php
@@ -355,7 +355,7 @@ class Service implements InjectionAwareInterface
$emailService = $di['mod_service']('email');
$emailService->sendTemplate($email);
} catch (\Exception $exc) {
- error_log($exc->getMessage());
+ $di['logger']->error($exc->getMessage());
}
}
@@ -387,7 +387,7 @@ class Service implements InjectionAwareInterface
$email['ticket'] = $ticket;
$emailService->sendTemplate($email);
} catch (\Exception $exc) {
- error_log($exc->getMessage());
+ $di['logger']->error($exc->getMessage());
}
}
@@ -409,7 +409,7 @@ class Service implements InjectionAwareInterface
$emailService = $di['mod_service']('email');
$emailService->sendTemplate($email);
} catch (\Exception $exc) {
- error_log($exc->getMessage());
+ $di['logger']->error($exc->getMessage());
}
}
@@ -430,7 +430,7 @@ class Service implements InjectionAwareInterface
$emailService = $di['mod_service']('email');
$emailService->sendTemplate($email);
} catch (\Exception $exc) {
- error_log($exc->getMessage());
+ $di['logger']->error($exc->getMessage());
}
}
@@ -450,7 +450,7 @@ class Service implements InjectionAwareInterface
$emailService = $di['mod_service']('email');
$emailService->sendTemplate($email);
} catch (\Exception $exc) {
- error_log($exc->getMessage());
+ $di['logger']->error($exc->getMessage());
}
}
@@ -469,7 +469,7 @@ class Service implements InjectionAwareInterface
$emailService = $di['mod_service']('email');
$emailService->sendTemplate($email);
} catch (\Exception $exc) {
- error_log($exc->getMessage());
+ $di['logger']->error($exc->getMessage());
}
return true;
@@ -491,7 +491,7 @@ class Service implements InjectionAwareInterface
$emailService = $di['mod_service']('email');
$emailService->sendTemplate($email);
} catch (\Exception $exc) {
- error_log($exc->getMessage());
+ $di['logger']->error($exc->getMessage());
}
}
@@ -511,7 +511,7 @@ class Service implements InjectionAwareInterface
$emailService = $di['mod_service']('email');
$emailService->sendTemplate($email);
} catch (\Exception $exc) {
- error_log($exc->getMessage());
+ $di['logger']->error($exc->getMessage());
}
}
diff --git a/src/modules/Staff/tests/Unit/Api/AdminTest.php b/src/modules/Staff/tests/Unit/Api/AdminTest.php
new file mode 100644
index 000000000..87e06073d
--- /dev/null
+++ b/src/modules/Staff/tests/Unit/Api/AdminTest.php
@@ -0,0 +1,519 @@
+loadBean(new Tests\Helpers\DummyBean());
+ $admin->role = Model_Admin::ROLE_ADMIN;
+
+ return $admin;
+}
+
+test('get di', function (): void {
+ $api = new Box\Mod\Staff\Api\Admin();
+ $api = new Box\Mod\Staff\Api\Admin();
+ $di = container();
+ $api->setDi($di);
+ $getDi = $api->getDi();
+ expect($getDi)->toEqual($di);
+});
+
+test('get list', function (): void {
+ $api = new Box\Mod\Staff\Api\Admin();
+ $data = [];
+
+ $serviceMock = Mockery::mock(Box\Mod\Staff\Service::class);
+ $serviceMock
+ ->shouldReceive('getSearchQuery')
+ ->atLeast()->once()
+ ->andReturn(['sqlString', []]);
+ $serviceMock
+ ->shouldReceive('toModel_AdminApiArray')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $resultSet = [
+ 'list' => ['id' => 1],
+ ];
+ $pagerMock = Mockery::mock(FOSSBilling\Pagination::class)->makePartial();
+ $pagerMock
+ ->shouldReceive('getPaginatedResultSet')
+ ->atLeast()->once()
+ ->andReturn($resultSet);
+
+ $adminModel = new Model_Admin();
+ $adminModel->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($adminModel);
+
+ $di = container();
+ $di['pager'] = $pagerMock;
+ $di['db'] = $dbMock;
+
+ $api->setDi($di);
+ $api->setService($serviceMock);
+
+ $result = $api->get_list($data);
+ expect($result)->toBeArray();
+});
+
+test('get', function (): void {
+ $api = new Box\Mod\Staff\Api\Admin();
+ $data['id'] = 1;
+
+ $serviceMock = Mockery::mock(Box\Mod\Staff\Service::class);
+ $serviceMock
+ ->shouldReceive('toModel_AdminApiArray')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn(staffAdminIdentity());
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $api->setService($serviceMock);
+ $api->setDi($di);
+
+ $result = $api->get($data);
+ expect($result)->toBeArray();
+});
+
+test('update', function (): void {
+ $api = new Box\Mod\Staff\Api\Admin();
+ $data['id'] = 1;
+
+ $serviceMock = Mockery::mock(Box\Mod\Staff\Service::class);
+ $serviceMock
+ ->shouldReceive('update')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn(staffAdminIdentity());
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $api->setDi($di);
+ $api->setService($serviceMock);
+
+ $result = $api->update($data);
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+});
+
+test('delete', function (): void {
+ $api = new Box\Mod\Staff\Api\Admin();
+ $data['id'] = 1;
+
+ $serviceMock = Mockery::mock(Box\Mod\Staff\Service::class);
+ $serviceMock
+ ->shouldReceive('delete')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn(staffAdminIdentity());
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $api->setDi($di);
+ $api->setService($serviceMock);
+
+ $result = $api->delete($data);
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+});
+
+test('change password', function (): void {
+ $api = new Box\Mod\Staff\Api\Admin();
+ $data = [
+ 'id' => '1',
+ 'password' => 'test!23A',
+ 'password_confirm' => 'test!23A',
+ ];
+
+ $validatorMock = Mockery::mock(FOSSBilling\Validate::class);
+ $validatorMock
+ ->shouldReceive('passwordsMatch')
+ ->atLeast()->once();
+ $validatorMock
+ ->shouldReceive('isPasswordStrong')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $serviceMock = Mockery::mock(Box\Mod\Staff\Service::class);
+ $serviceMock
+ ->shouldReceive('changePassword')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn(staffAdminIdentity());
+
+ $di = container();
+ $di['validator'] = $validatorMock;
+ $di['db'] = $dbMock;
+
+ $api->setDi($di);
+ $api->setService($serviceMock);
+ $result = $api->change_password($data);
+
+ expect(true)->toBeTrue();
+});
+
+test('change password password do not match', function (): void {
+ $api = new Box\Mod\Staff\Api\Admin();
+ $data = [
+ 'id' => '1',
+ 'password' => 'test!23A',
+ 'password_confirm' => 'test',
+ ];
+
+ $di = container();
+ $api->setDi($di);
+ expect(fn () => $api->change_password($data))
+ ->toThrow(FOSSBilling\Exception::class, 'Passwords do not match');
+});
+
+test('create', function (): void {
+ $api = new Box\Mod\Staff\Api\Admin();
+ $data = [
+ 'admin_group_id' => '1',
+ 'password' => 'test!23A',
+ 'email' => 'okay@example.com',
+ 'name' => 'OkayTest',
+ ];
+
+ $newStaffId = 1;
+
+ $serviceMock = Mockery::mock(Box\Mod\Staff\Service::class);
+ $serviceMock
+ ->shouldReceive('create')
+ ->atLeast()->once()
+ ->andReturn($newStaffId);
+
+ $validatorMock = Mockery::mock(FOSSBilling\Validate::class);
+ $validatorMock
+ ->shouldReceive('isPasswordStrong')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+ $di['validator'] = $validatorMock;
+
+ $toolsMock = Mockery::mock(FOSSBilling\Tools::class);
+ $toolsMock->shouldReceive('validateAndSanitizeEmail')->atLeast()->once();
+ $di['tools'] = $toolsMock;
+
+ $api->setDi($di);
+ $api->setService($serviceMock);
+
+ $result = $api->create($data);
+ expect($result)->toBeInt();
+ expect($result)->toEqual($newStaffId);
+});
+
+test('permissions get', function (): void {
+ $api = new Box\Mod\Staff\Api\Admin();
+ $data['id'] = 1;
+
+ $staffModel = new Model_Admin();
+ $staffModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $serviceMock = Mockery::mock(Box\Mod\Staff\Service::class);
+ $serviceMock
+ ->shouldReceive('getPermissions')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($staffModel);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $api->setDi($di);
+ $api->setService($serviceMock);
+
+ $result = $api->permissions_get($data);
+ expect($result)->toBeArray();
+});
+
+test('permissions update', function (): void {
+ $api = new Box\Mod\Staff\Api\Admin();
+ $data = [
+ 'id' => '1',
+ 'permissions' => ['default' => ['all' => true]],
+ ];
+
+ $serviceMock = Mockery::mock(Box\Mod\Staff\Service::class);
+ $serviceMock
+ ->shouldReceive('setPermissions')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $staffModel = new Model_Admin();
+ $staffModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($staffModel);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $api->setDi($di);
+ $api->setService($serviceMock);
+
+ $result = $api->permissions_update($data);
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+});
+
+test('group get pairs', function (): void {
+ $api = new Box\Mod\Staff\Api\Admin();
+ $serviceMock = Mockery::mock(Box\Mod\Staff\Service::class);
+ $serviceMock
+ ->shouldReceive('getAdminGroupPair')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $api->setService($serviceMock);
+ $result = $api->group_get_pairs([]);
+ expect($result)->toBeArray();
+});
+
+test('group get list', function (): void {
+ $api = new Box\Mod\Staff\Api\Admin();
+ $data = [];
+
+ $serviceMock = Mockery::mock(Box\Mod\Staff\Service::class);
+ $serviceMock
+ ->shouldReceive('getAdminGroupSearchQuery')
+ ->atLeast()->once()
+ ->andReturn(['sqlString', []]);
+
+ $pagerMock = Mockery::mock(FOSSBilling\Pagination::class)->makePartial();
+ $pagerMock
+ ->shouldReceive('getPaginatedResultSet')
+ ->atLeast()->once()
+ ->andReturn(['list' => []]);
+
+ $di = container();
+ $di['pager'] = $pagerMock;
+
+ $api->setDi($di);
+ $api->setService($serviceMock);
+
+ $result = $api->group_get_list($data);
+ expect($result)->toBeArray();
+});
+
+test('group create', function (): void {
+ $api = new Box\Mod\Staff\Api\Admin();
+ $data['name'] = 'Prime Group';
+ $newGroupId = 1;
+
+ $serviceMock = Mockery::mock(Box\Mod\Staff\Service::class);
+ $serviceMock
+ ->shouldReceive('createGroup')
+ ->atLeast()->once()
+ ->andReturn($newGroupId);
+
+ $di = container();
+ $api->setDi($di);
+ $api->setService($serviceMock);
+
+ $result = $api->group_create($data);
+ expect($result)->toBeInt();
+ expect($result)->toEqual($newGroupId);
+});
+
+test('group get', function (): void {
+ $api = new Box\Mod\Staff\Api\Admin();
+ $data['id'] = '1';
+
+ $serviceMock = Mockery::mock(Box\Mod\Staff\Service::class);
+ $serviceMock
+ ->shouldReceive('toAdminGroupApiArray')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn(new Model_AdminGroup());
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $api->setIdentity(staffAdminIdentity());
+ $api->setDi($di);
+ $api->setService($serviceMock);
+
+ $result = $api->group_get($data);
+ expect($result)->toBeArray();
+});
+
+test('group delete', function (): void {
+ $api = new Box\Mod\Staff\Api\Admin();
+ $data['id'] = '1';
+
+ $serviceMock = Mockery::mock(Box\Mod\Staff\Service::class);
+ $serviceMock
+ ->shouldReceive('deleteGroup')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn(new Model_AdminGroup());
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $api->setIdentity(staffAdminIdentity());
+ $api->setDi($di);
+ $api->setService($serviceMock);
+
+ $result = $api->group_delete($data);
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+});
+
+test('group update', function (): void {
+ $api = new Box\Mod\Staff\Api\Admin();
+ $data['id'] = '1';
+
+ $serviceMock = Mockery::mock(Box\Mod\Staff\Service::class);
+ $serviceMock
+ ->shouldReceive('updateGroup')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn(new Model_AdminGroup());
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $api->setIdentity(staffAdminIdentity());
+ $api->setDi($di);
+ $api->setService($serviceMock);
+
+ $result = $api->group_update($data);
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+});
+
+test('login history get list', function (): void {
+ $api = new Box\Mod\Staff\Api\Admin();
+ $data = [];
+
+ $serviceMock = Mockery::mock(Box\Mod\Staff\Service::class);
+ $serviceMock
+ ->shouldReceive('getActivityAdminHistorySearchQuery')
+ ->atLeast()->once()
+ ->andReturn(['sqlString', []]);
+ $serviceMock
+ ->shouldReceive('toActivityAdminHistoryApiArray')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $resultSet = [
+ 'list' => ['id' => 1],
+ ];
+ $pagerMock = Mockery::mock(FOSSBilling\Pagination::class)->makePartial();
+ $pagerMock
+ ->shouldReceive('getPaginatedResultSet')
+ ->atLeast()->once()
+ ->andReturn($resultSet);
+
+ $model = new Model_ActivityAdminHistory();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $di = container();
+ $di['pager'] = $pagerMock;
+ $di['db'] = $dbMock;
+
+ $api->setDi($di);
+ $api->setService($serviceMock);
+
+ $result = $api->login_history_get_list($data);
+ expect($result)->toBeArray();
+});
+
+test('login history get', function (): void {
+ $api = new Box\Mod\Staff\Api\Admin();
+ $data['id'] = '1';
+
+ $serviceMock = Mockery::mock(Box\Mod\Staff\Service::class);
+ $serviceMock
+ ->shouldReceive('toActivityAdminHistoryApiArray')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn(new Model_ActivityAdminHistory());
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $api->setIdentity(staffAdminIdentity());
+ $api->setDi($di);
+ $api->setService($serviceMock);
+
+ $result = $api->login_history_get($data);
+ expect($result)->toBeArray();
+});
diff --git a/src/modules/Staff/tests/Unit/Api/GuestTest.php b/src/modules/Staff/tests/Unit/Api/GuestTest.php
new file mode 100644
index 000000000..5e1e6ad30
--- /dev/null
+++ b/src/modules/Staff/tests/Unit/Api/GuestTest.php
@@ -0,0 +1,111 @@
+setDi($di);
+ $getDi = $api->getDi();
+ expect($getDi)->toEqual($di);
+});
+
+test('login without email', function (): void {
+ $api = new Box\Mod\Staff\Api\Guest();
+ $guestApi = new Box\Mod\Staff\Api\Guest();
+
+ $apiHandler = new Api_Handler(new Model_Admin());
+ $reflection = new ReflectionClass($apiHandler);
+ $method = $reflection->getMethod('validateRequiredParams');
+
+ expect(fn (): mixed => $method->invokeArgs($apiHandler, [$guestApi, 'login', ['email' => null, 'password' => 'pass']]))
+ ->toThrow(FOSSBilling\InformationException::class);
+});
+
+test('login without password', function (): void {
+ $api = new Box\Mod\Staff\Api\Guest();
+ $guestApi = new Box\Mod\Staff\Api\Guest();
+
+ $di = container();
+ $di['validator'] = new FOSSBilling\Validate();
+
+ $guestApi->setDi($di);
+ expect(fn () => $guestApi->login(['email' => 'email@domain.com']))->toThrow(FOSSBilling\Exception::class);
+});
+
+test('successful login', function (): void {
+ $api = new Box\Mod\Staff\Api\Guest();
+ $modMock = Mockery::mock('\\' . FOSSBilling\Module::class);
+ $modMock
+ ->shouldReceive('getConfig')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $serviceMock = Mockery::mock(Box\Mod\Staff\Service::class);
+ $serviceMock
+ ->shouldReceive('login')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $sessionMock = Mockery::mock(FOSSBilling\Session::class);
+ $sessionMock->shouldReceive('delete')->atLeast()->once();
+
+ $di = container();
+
+ $toolsMock = Mockery::mock(FOSSBilling\Tools::class);
+ $toolsMock->shouldReceive('validateAndSanitizeEmail')->atLeast()->once();
+ $di['tools'] = $toolsMock;
+ $di['session'] = $sessionMock;
+ $di['validator'] = new FOSSBilling\Validate();
+
+ $guestApi = new Box\Mod\Staff\Api\Guest();
+ $guestApi->setMod($modMock);
+ $guestApi->setService($serviceMock);
+ $guestApi->setDi($di);
+ $result = $guestApi->login(['email' => 'email@domain.com', 'password' => 'pass']);
+ expect($result)->toBeArray();
+});
+
+test('login check ip exception', function (): void {
+ $api = new Box\Mod\Staff\Api\Guest();
+ $modMock = Mockery::mock('\\' . FOSSBilling\Module::class);
+ $configArr = [
+ 'allowed_ips' => '1.1.1.1' . PHP_EOL . '2.2.2.2',
+ 'check_ip' => true,
+ ];
+ $modMock
+ ->shouldReceive('getConfig')
+ ->atLeast()->once()
+ ->andReturn($configArr);
+
+ $di = container();
+
+ $toolsMock = Mockery::mock(FOSSBilling\Tools::class);
+ $toolsMock->shouldReceive('validateAndSanitizeEmail')->atLeast()->once();
+ $di['tools'] = $toolsMock;
+ $di['validator'] = new FOSSBilling\Validate();
+
+ $guestApi = new Box\Mod\Staff\Api\Guest();
+ $guestApi->setMod($modMock);
+ $guestApi->setDi($di);
+ $ip = '192.168.0.1';
+ $guestApi->setIp($ip);
+
+ $data = [
+ 'email' => 'email@domain.com',
+ 'password' => 'pass',
+ ];
+ expect(fn () => $guestApi->login($data))
+ ->toThrow(FOSSBilling\Exception::class, 'You are not allowed to login to admin area from this IP address.');
+});
diff --git a/src/modules/Staff/tests/Unit/ServiceTest.php b/src/modules/Staff/tests/Unit/ServiceTest.php
new file mode 100644
index 000000000..97d653f1b
--- /dev/null
+++ b/src/modules/Staff/tests/Unit/ServiceTest.php
@@ -0,0 +1,1448 @@
+stmt;
+ }
+}
+
+class StaffDbalMock
+{
+ public function __construct(private $qb)
+ {
+ }
+
+ public function createQueryBuilder()
+ {
+ return $this->qb;
+ }
+}
+
+class StaffStatementMock
+{
+ public function __construct(private $result = '{}')
+ {
+ }
+
+ public function fetchOne()
+ {
+ return $this->result;
+ }
+}
+
+test('login returns admin details on successful login', function (): void {
+ $email = 'email@domain.com';
+ $password = 'pass';
+ $ip = '127.0.0.1';
+
+ $admin = new Model_Admin();
+ $admin->loadBean(new Tests\Helpers\DummyBean());
+ $admin->id = 1;
+ $admin->email = $email;
+ $admin->name = 'Admin';
+ $admin->role = 'admin';
+
+ $emMock = Mockery::mock('\Box_EventManager');
+ $emMock->shouldReceive('fire')->atLeast()->once()
+ ->andReturn(true);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('findOne')->atLeast()->once()
+ ->andReturn($admin);
+
+ $sessionMock = Mockery::mock(FOSSBilling\Session::class);
+ $sessionMock->shouldReceive('regenerateId')->atLeast()->once();
+ $sessionMock->shouldReceive('set')->atLeast()->once();
+
+ $authMock = Mockery::mock('\Box_Authorization');
+ $authMock->shouldReceive('authorizeUser')->atLeast()->once()
+ ->with($admin, $password)
+ ->andReturn($admin);
+
+ $di = container();
+ $di['events_manager'] = $emMock;
+ $di['db'] = $dbMock;
+ $di['session'] = $sessionMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $di['auth'] = $authMock;
+
+ $service = new Service();
+ $service->setDi($di);
+
+ $result = $service->login($email, $password, $ip);
+
+ $expected = [
+ 'id' => 1,
+ 'email' => $email,
+ 'name' => 'Admin',
+ 'role' => 'admin',
+ ];
+
+ expect($result)->toBe($expected);
+});
+
+test('login throws exception when credentials are invalid', function (): void {
+ $email = 'email@domain.com';
+ $password = 'pass';
+ $ip = '127.0.0.1';
+
+ $emMock = Mockery::mock('\Box_EventManager');
+ $emMock->shouldReceive('fire')->atLeast()->once()
+ ->andReturn(true);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('findOne')->atLeast()->once()
+ ->andReturn(null);
+
+ $authMock = Mockery::mock('\Box_Authorization');
+ $authMock->shouldReceive('authorizeUser')->atLeast()->once()
+ ->with(null, $password)
+ ->andReturn(null);
+
+ $di = container();
+ $di['events_manager'] = $emMock;
+ $di['db'] = $dbMock;
+ $di['auth'] = $authMock;
+
+ $service = new Service();
+ $service->setDi($di);
+
+ expect(fn (): array => $service->login($email, $password, $ip))
+ ->toThrow(FOSSBilling\Exception::class, 'Check your login details');
+});
+
+test('hasPermission returns true for admin role', function (): void {
+ $member = new Model_Admin();
+ $member->loadBean(new Tests\Helpers\DummyBean());
+ $member->role = 'admin';
+
+ $service = new Service();
+
+ $result = $service->hasPermission($member, 'example');
+ expect($result)->toBeTrue();
+});
+
+test('hasPermission returns false for staff with empty permissions', function (): void {
+ $member = new Model_Admin();
+ $member->loadBean(new Tests\Helpers\DummyBean());
+ $member->role = 'staff';
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+
+ $serviceMock->shouldReceive('getPermissions')->atLeast()->once();
+
+ $extensionServiceMock = Mockery::mock(Box\Mod\Extension\Service::class)->makePartial();
+ $extensionServiceMock->shouldReceive('getSpecificModulePermissions')->atLeast()->once()
+ ->andReturn([]);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $extensionServiceMock);
+
+ $serviceMock->setDi($di);
+
+ $result = $serviceMock->hasPermission($member, 'example');
+ expect($result)->toBeFalse();
+});
+
+test('hasPermission returns false for staff without module permission', function (): void {
+ $member = new Model_Admin();
+ $member->loadBean(new Tests\Helpers\DummyBean());
+ $member->role = 'staff';
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+
+ $serviceMock->shouldReceive('getPermissions')->atLeast()->once()
+ ->andReturn(['cart' => [], 'client' => []]);
+
+ $extensionServiceMock = Mockery::mock(Box\Mod\Extension\Service::class)->makePartial();
+ $extensionServiceMock->shouldReceive('getSpecificModulePermissions')->atLeast()->once()
+ ->andReturn([]);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $extensionServiceMock);
+
+ $serviceMock->setDi($di);
+
+ $result = $serviceMock->hasPermission($member, 'example');
+ expect($result)->toBeFalse();
+});
+
+test('hasPermission returns false for staff without method permission', function (): void {
+ $member = new Model_Admin();
+ $member->loadBean(new Tests\Helpers\DummyBean());
+ $member->role = 'staff';
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+
+ $serviceMock->shouldReceive('getPermissions')->atLeast()->once()
+ ->andReturn(['example' => [], 'client' => []]);
+
+ $extensionServiceMock = Mockery::mock(Box\Mod\Extension\Service::class)->makePartial();
+ $extensionServiceMock->shouldReceive('getSpecificModulePermissions')->atLeast()->once()
+ ->andReturn([]);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $extensionServiceMock);
+
+ $serviceMock->setDi($di);
+
+ $result = $serviceMock->hasPermission($member, 'example', 'get_list');
+ expect($result)->toBeFalse();
+});
+
+test('onAfterClientReplyTicket sends email notification', function (): void {
+ $eventMock = Mockery::mock('\Box_Event');
+
+ $supportServiceMock = Mockery::mock(Box\Mod\Support\Service::class);
+ $supportServiceMock->shouldReceive('getTicketById')->atLeast()->once()
+ ->andReturn(new Model_SupportTicket());
+ $supportServiceMock->shouldReceive('toApiArray')->atLeast()->once()
+ ->andReturn([]);
+
+ $emailServiceMock = Mockery::mock(Box\Mod\Email\Service::class);
+ $emailServiceMock->shouldReceive('sendTemplate')->atLeast()->once();
+
+ $eventMock->shouldReceive('getparameters')->atLeast()->once()
+ ->andReturn(['id' => random_int(1, 100)]);
+
+ $service = new Service();
+
+ $di = container();
+ $di['mod_service'] = $di->protect(function ($name) use ($supportServiceMock, $emailServiceMock) {
+ if ($name == 'support') {
+ return $supportServiceMock;
+ }
+ if ($name == 'email') {
+ return $emailServiceMock;
+ }
+ });
+
+ $eventMock->shouldReceive('getDi')->atLeast()->once()
+ ->andReturn($di);
+ $service->setDi($di);
+ $service->onAfterClientReplyTicket($eventMock);
+});
+
+test('onAfterClientReplyTicket handles email exception', function (): void {
+ $eventMock = Mockery::mock('\Box_Event');
+
+ $supportServiceMock = Mockery::mock(Box\Mod\Support\Service::class);
+ $supportServiceMock->shouldReceive('getTicketById')->atLeast()->once()
+ ->andReturn(new Model_SupportTicket());
+ $supportServiceMock->shouldReceive('toApiArray')->atLeast()->once()
+ ->andReturn([]);
+
+ $emailServiceMock = Mockery::mock(Box\Mod\Email\Service::class);
+ $emailServiceMock->shouldReceive('sendTemplate')->atLeast()->once()
+ ->andThrow(new Exception('PHPunit controlled Exception'));
+
+ $eventMock->shouldReceive('getparameters')->atLeast()->once()
+ ->andReturn(['id' => random_int(1, 100)]);
+
+ $service = new Service();
+
+ $di = container();
+ $di['mod_service'] = $di->protect(function ($name) use ($supportServiceMock, $emailServiceMock) {
+ if ($name == 'support') {
+ return $supportServiceMock;
+ }
+ if ($name == 'email') {
+ return $emailServiceMock;
+ }
+ });
+
+ $eventMock->shouldReceive('getDi')->atLeast()->once()
+ ->andReturn($di);
+ $service->setDi($di);
+ $service->onAfterClientReplyTicket($eventMock);
+});
+
+test('onAfterClientCloseTicket sends email notification', function (): void {
+ $eventMock = Mockery::mock('\Box_Event');
+
+ $supportServiceMock = Mockery::mock(Box\Mod\Support\Service::class);
+ $supportServiceMock->shouldReceive('getTicketById')->atLeast()->once()
+ ->andReturn(new Model_SupportTicket());
+ $supportServiceMock->shouldReceive('toApiArray')->atLeast()->once()
+ ->andReturn([]);
+
+ $emailServiceMock = Mockery::mock(Box\Mod\Email\Service::class);
+ $emailServiceMock->shouldReceive('sendTemplate')->atLeast()->once();
+
+ $eventMock->shouldReceive('getparameters')->atLeast()->once()
+ ->andReturn(['id' => random_int(1, 100)]);
+
+ $service = new Service();
+
+ $di = container();
+ $di['mod_service'] = $di->protect(function ($name) use ($supportServiceMock, $emailServiceMock) {
+ if ($name == 'support') {
+ return $supportServiceMock;
+ }
+ if ($name == 'email') {
+ return $emailServiceMock;
+ }
+ });
+
+ $eventMock->shouldReceive('getDi')->atLeast()->once()
+ ->andReturn($di);
+ $service->setDi($di);
+ $service->onAfterClientCloseTicket($eventMock);
+});
+
+test('onAfterClientCloseTicket handles email exception', function (): void {
+ $eventMock = Mockery::mock('\Box_Event');
+
+ $supportServiceMock = Mockery::mock(Box\Mod\Support\Service::class);
+ $supportServiceMock->shouldReceive('getTicketById')->atLeast()->once()
+ ->andReturn(new Model_SupportTicket());
+ $supportServiceMock->shouldReceive('toApiArray')->atLeast()->once()
+ ->andReturn([]);
+
+ $emailServiceMock = Mockery::mock(Box\Mod\Email\Service::class);
+ $emailServiceMock->shouldReceive('sendTemplate')->atLeast()->once()
+ ->andThrow(new Exception('PHPunit controlled Exception'));
+
+ $eventMock->shouldReceive('getparameters')->atLeast()->once()
+ ->andReturn(['id' => random_int(1, 100)]);
+
+ $service = new Service();
+
+ $di = container();
+ $di['mod_service'] = $di->protect(function ($name) use ($supportServiceMock, $emailServiceMock) {
+ if ($name == 'support') {
+ return $supportServiceMock;
+ }
+ if ($name == 'email') {
+ return $emailServiceMock;
+ }
+ });
+
+ $eventMock->shouldReceive('getDi')->atLeast()->once()
+ ->andReturn($di);
+ $service->setDi($di);
+ $service->onAfterClientCloseTicket($eventMock);
+});
+
+test('onAfterGuestPublicTicketOpen sends email notification', function (): void {
+ $eventMock = Mockery::mock('\Box_Event');
+
+ $supportServiceMock = Mockery::mock(Box\Mod\Support\Service::class);
+ $supportServiceMock->shouldReceive('getPublicTicketById')->atLeast()->once()
+ ->andReturn(new Model_SupportPTicket());
+ $supportServiceMock->shouldReceive('publicToApiArray')->atLeast()->once()
+ ->andReturn([]);
+
+ $emailServiceMock = Mockery::mock(Box\Mod\Email\Service::class);
+ $emailServiceMock->shouldReceive('sendTemplate')->atLeast()->once();
+
+ $eventMock->shouldReceive('getparameters')->atLeast()->once()
+ ->andReturn(['id' => random_int(1, 100)]);
+
+ $service = new Service();
+
+ $di = container();
+ $di['mod_service'] = $di->protect(function ($name) use ($supportServiceMock, $emailServiceMock) {
+ if ($name == 'support') {
+ return $supportServiceMock;
+ }
+ if ($name == 'email') {
+ return $emailServiceMock;
+ }
+ });
+
+ $eventMock->shouldReceive('getDi')->atLeast()->once()
+ ->andReturn($di);
+ $service->setDi($di);
+ $service->onAfterGuestPublicTicketOpen($eventMock);
+});
+
+test('onAfterGuestPublicTicketOpen handles email exception', function (): void {
+ $eventMock = Mockery::mock('\Box_Event');
+
+ $supportServiceMock = Mockery::mock(Box\Mod\Support\Service::class);
+ $supportServiceMock->shouldReceive('getPublicTicketById')->atLeast()->once()
+ ->andReturn(new Model_SupportPTicket());
+ $supportServiceMock->shouldReceive('publicToApiArray')->atLeast()->once()
+ ->andReturn([]);
+
+ $emailServiceMock = Mockery::mock(Box\Mod\Email\Service::class);
+ $emailServiceMock->shouldReceive('sendTemplate')->atLeast()->once()
+ ->andThrow(new Exception('PHPunit controlled Exception'));
+
+ $eventMock->shouldReceive('getparameters')->atLeast()->once()
+ ->andReturn(['id' => random_int(1, 100)]);
+
+ $service = new Service();
+
+ $di = container();
+ $di['mod_service'] = $di->protect(function ($name) use ($supportServiceMock, $emailServiceMock) {
+ if ($name == 'support') {
+ return $supportServiceMock;
+ }
+ if ($name == 'email') {
+ return $emailServiceMock;
+ }
+ });
+
+ $eventMock->shouldReceive('getDi')->atLeast()->once()
+ ->andReturn($di);
+ $service->setDi($di);
+ $service->onAfterGuestPublicTicketOpen($eventMock);
+});
+
+test('onAfterGuestPublicTicketReply sends email notification', function (): void {
+ $eventMock = Mockery::mock('\Box_Event');
+
+ $supportServiceMock = Mockery::mock(Box\Mod\Support\Service::class);
+ $supportServiceMock->shouldReceive('getPublicTicketById')->atLeast()->once()
+ ->andReturn(new Model_SupportPTicket());
+ $supportServiceMock->shouldReceive('publicToApiArray')->atLeast()->once()
+ ->andReturn([]);
+
+ $emailServiceMock = Mockery::mock(Box\Mod\Email\Service::class);
+ $emailServiceMock->shouldReceive('sendTemplate')->atLeast()->once();
+
+ $eventMock->shouldReceive('getparameters')->atLeast()->once()
+ ->andReturn(['id' => random_int(1, 100)]);
+
+ $service = new Service();
+
+ $di = container();
+ $di['mod_service'] = $di->protect(function ($name) use ($supportServiceMock, $emailServiceMock) {
+ if ($name == 'support') {
+ return $supportServiceMock;
+ }
+ if ($name == 'email') {
+ return $emailServiceMock;
+ }
+ });
+
+ $eventMock->shouldReceive('getDi')->atLeast()->once()
+ ->andReturn($di);
+ $service->setDi($di);
+ $service->onAfterGuestPublicTicketReply($eventMock);
+});
+
+test('onAfterGuestPublicTicketReply handles email exception', function (): void {
+ $eventMock = Mockery::mock('\Box_Event');
+
+ $supportServiceMock = Mockery::mock(Box\Mod\Support\Service::class);
+ $supportServiceMock->shouldReceive('getPublicTicketById')->atLeast()->once()
+ ->andReturn(new Model_SupportPTicket());
+ $supportServiceMock->shouldReceive('publicToApiArray')->atLeast()->once()
+ ->andReturn([]);
+
+ $emailServiceMock = Mockery::mock(Box\Mod\Email\Service::class);
+ $emailServiceMock->shouldReceive('sendTemplate')->atLeast()->once()
+ ->andThrow(new Exception('PHPunit controlled Exception'));
+
+ $eventMock->shouldReceive('getparameters')->atLeast()->once()
+ ->andReturn(['id' => random_int(1, 100)]);
+
+ $service = new Service();
+
+ $di = container();
+ $di['mod_service'] = $di->protect(function ($name) use ($supportServiceMock, $emailServiceMock) {
+ if ($name == 'support') {
+ return $supportServiceMock;
+ }
+ if ($name == 'email') {
+ return $emailServiceMock;
+ }
+ });
+
+ $eventMock->shouldReceive('getDi')->atLeast()->once()
+ ->andReturn($di);
+ $service->setDi($di);
+ $service->onAfterGuestPublicTicketReply($eventMock);
+});
+
+test('onAfterClientSignUp sends email notification', function (): void {
+ $eventMock = Mockery::mock('\Box_Event');
+
+ $clientMock = Mockery::mock(Box\Mod\Client\Service::class);
+ $clientMock->shouldReceive('get')->atLeast()->once()
+ ->andReturn([]);
+
+ $emailServiceMock = Mockery::mock(Box\Mod\Email\Service::class);
+ $emailServiceMock->shouldReceive('sendTemplate')->atLeast()->once();
+
+ $eventMock->shouldReceive('getparameters')->atLeast()->once()
+ ->andReturn(['id' => random_int(1, 100)]);
+
+ $service = new Service();
+
+ $di = container();
+ $di['mod_service'] = $di->protect(function ($name) use ($clientMock, $emailServiceMock) {
+ if ($name == 'client') {
+ return $clientMock;
+ }
+ if ($name == 'email') {
+ return $emailServiceMock;
+ }
+ });
+
+ $eventMock->shouldReceive('getDi')->atLeast()->once()
+ ->andReturn($di);
+ $service->setDi($di);
+ $service->onAfterClientSignUp($eventMock);
+});
+
+test('onAfterClientSignUp handles email exception', function (): void {
+ $eventMock = Mockery::mock('\Box_Event');
+
+ $clientMock = Mockery::mock(Box\Mod\Client\Service::class);
+ $clientMock->shouldReceive('get')->atLeast()->once()
+ ->andReturn([]);
+
+ $emailServiceMock = Mockery::mock(Box\Mod\Email\Service::class);
+ $emailServiceMock->shouldReceive('sendTemplate')->atLeast()->once()
+ ->andThrow(new Exception('PHPunit controlled Exception'));
+
+ $eventMock->shouldReceive('getparameters')->atLeast()->once()
+ ->andReturn(['id' => random_int(1, 100)]);
+
+ $service = new Service();
+
+ $di = container();
+ $di['mod_service'] = $di->protect(function ($name) use ($clientMock, $emailServiceMock) {
+ if ($name == 'client') {
+ return $clientMock;
+ }
+ if ($name == 'email') {
+ return $emailServiceMock;
+ }
+ });
+
+ $eventMock->shouldReceive('getDi')->atLeast()->once()
+ ->andReturn($di);
+ $service->setDi($di);
+ $service->onAfterClientSignUp($eventMock);
+});
+
+test('onAfterGuestPublicTicketClose handles email exception', function (): void {
+ $eventMock = Mockery::mock('\Box_Event');
+
+ $supportServiceMock = Mockery::mock(Box\Mod\Support\Service::class);
+ $supportServiceMock->shouldReceive('publicToApiArray')->atLeast()->once()
+ ->andReturn([]);
+
+ $emailServiceMock = Mockery::mock(Box\Mod\Email\Service::class);
+ $emailServiceMock->shouldReceive('sendTemplate')->atLeast()->once()
+ ->andThrow(new Exception('PHPunit controlled Exception'));
+
+ $eventMock->shouldReceive('getparameters')->atLeast()->once()
+ ->andReturn(['id' => random_int(1, 100)]);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('load')->atLeast()->once()
+ ->andReturn(new Model_SupportPTicket());
+
+ $service = new Service();
+
+ $di = container();
+ $di['mod_service'] = $di->protect(function ($name) use ($supportServiceMock, $emailServiceMock) {
+ if (strtolower($name) == 'support') {
+ return $supportServiceMock;
+ }
+ if (strtolower($name) == 'email') {
+ return $emailServiceMock;
+ }
+ });
+ $di['db'] = $dbMock;
+
+ $eventMock->shouldReceive('getDi')->atLeast()->once()
+ ->andReturn($di);
+ $service->setDi($di);
+ $service->onAfterGuestPublicTicketClose($eventMock);
+});
+
+test('onAfterClientOpenTicket sends mod_staff_ticket_open email', function (): void {
+ $di = container();
+
+ $ticketModel = new Model_SupportTicket();
+ $ticketModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $supportServiceMock = Mockery::mock(Box\Mod\Support\Service::class);
+ $supportServiceMock->shouldReceive('getTicketById')->atLeast()->once()
+ ->andReturn($ticketModel);
+
+ $supportTicketArray = [];
+ $supportServiceMock->shouldReceive('toApiArray')->atLeast()->once()
+ ->andReturn($supportTicketArray);
+
+ $emailServiceMock = Mockery::mock(Box\Mod\Email\Service::class);
+
+ $emailConfig = [
+ 'to_staff' => true,
+ 'code' => 'mod_staff_ticket_open',
+ 'ticket' => $supportTicketArray,
+ ];
+ $emailServiceMock->shouldReceive('sendTemplate')->atLeast()->once()
+ ->with($emailConfig)
+ ->andReturn(true);
+
+ $di['mod_service'] = $di->protect(function ($name) use ($supportServiceMock, $emailServiceMock) {
+ if ($name == 'support') {
+ return $supportServiceMock;
+ }
+ if ($name == 'email') {
+ return $emailServiceMock;
+ }
+ });
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('load')->atLeast()->once()
+ ->andReturn(null);
+ $di['db'] = $dbMock;
+ $admin = new Model_Admin();
+ $admin->loadBean(new Tests\Helpers\DummyBean());
+ $admin->role = Model_Admin::ROLE_ADMIN;
+ $di['loggedin_admin'] = $admin;
+
+ $eventMock = Mockery::mock('\Box_Event');
+ $eventMock->shouldReceive('getDi')->atLeast()->once()
+ ->andReturn($di);
+
+ $eventMock->shouldReceive('getparameters')->atLeast()->once()
+ ->andReturn(['id' => random_int(1, 100)]);
+
+ $service = new Service();
+ $service->onAfterClientOpenTicket($eventMock);
+});
+
+test('onAfterClientOpenTicket sends mod_support_helpdesk_ticket_open email', function (): void {
+ $di = container();
+
+ $ticketModel = new Model_SupportTicket();
+ $ticketModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $supportServiceMock = Mockery::mock(Box\Mod\Support\Service::class);
+ $supportServiceMock->shouldReceive('getTicketById')->atLeast()->once()
+ ->andReturn($ticketModel);
+
+ $supportTicketArray = [];
+ $supportServiceMock->shouldReceive('toApiArray')->atLeast()->once()
+ ->andReturn($supportTicketArray);
+
+ $helpdeskModel = new Model_SupportHelpdesk();
+ $helpdeskModel->loadBean(new Tests\Helpers\DummyBean());
+ $helpdeskModel->email = 'helpdesk@support.com';
+
+ $emailServiceMock = Mockery::mock(Box\Mod\Email\Service::class);
+ $emailConfig = [
+ 'to' => $helpdeskModel->email,
+ 'code' => 'mod_support_helpdesk_ticket_open',
+ 'ticket' => $supportTicketArray,
+ ];
+ $emailServiceMock->shouldReceive('sendTemplate')->atLeast()->once()
+ ->with($emailConfig)
+ ->andReturn(true);
+
+ $di['mod_service'] = $di->protect(function ($name) use ($supportServiceMock, $emailServiceMock) {
+ if ($name == 'support') {
+ return $supportServiceMock;
+ }
+ if ($name == 'email') {
+ return $emailServiceMock;
+ }
+ });
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('load')->atLeast()->once()
+ ->andReturn($helpdeskModel);
+ $di['db'] = $dbMock;
+ $admin = new Model_Admin();
+ $admin->loadBean(new Tests\Helpers\DummyBean());
+ $admin->role = Model_Admin::ROLE_ADMIN;
+ $di['loggedin_admin'] = $admin;
+
+ $eventMock = Mockery::mock('\Box_Event');
+ $eventMock->shouldReceive('getDi')->atLeast()->once()
+ ->andReturn($di);
+
+ $eventMock->shouldReceive('getparameters')->atLeast()->once()
+ ->andReturn(['id' => random_int(1, 100)]);
+
+ $service = new Service();
+ $service->onAfterClientOpenTicket($eventMock);
+});
+
+test('getList returns paginated result', function (): void {
+ $pagerMock = Mockery::mock(FOSSBilling\Pagination::class)->makePartial();
+ $pagerMock->shouldReceive('getPaginatedResultSet')->atLeast()->once()
+ ->andReturn([]);
+
+ $di = container();
+ $di['pager'] = $pagerMock;
+
+ $service = new Service();
+ $service->setDi($di);
+
+ $result = $service->getList([]);
+ expect($result)->toBeArray();
+});
+
+// Data provider for searchFilters
+dataset('searchFilters', fn() => [
+ 'empty filters' => [
+ [],
+ 'SELECT * FROM admin',
+ [],
+ ],
+ 'search by keyword' => [
+ ['search' => 'keyword'],
+ '(name LIKE :name OR email LIKE :email )',
+ [':name' => '%keyword%', ':email' => '%keyword%'],
+ ],
+ 'filter by status' => [
+ ['status' => 'active'],
+ 'status = :status',
+ [':status' => 'active'],
+ ],
+ 'filter by no_cron' => [
+ ['no_cron' => 'true'],
+ 'role != :role',
+ [':role' => Model_Admin::ROLE_CRON],
+ ],
+]);
+
+test('getSearchQuery returns correct query and params', function (array $data, string $expectedStr, array $expectedParams): void {
+ $di = container();
+
+ $service = new Service();
+ $service->setDi($di);
+ $result = $service->getSearchQuery($data);
+ expect($result[0])->toBeString();
+ expect($result[1])->toBeArray();
+
+ expect(str_contains((string) $result[0], $expectedStr))->toBeTrue($result[0]);
+ expect(array_diff_key($result[1], $expectedParams))->toBe([]);
+})->with('searchFilters');
+
+test('getCronAdmin returns existing cron admin', function (): void {
+ $adminModel = new Model_Admin();
+ $adminModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('findOne')->atLeast()->once()
+ ->andReturn($adminModel);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $service = new Service();
+ $service->setDi($di);
+
+ $result = $service->getCronAdmin();
+ expect($result)->not->toBeEmpty();
+ expect($result)->toBeInstanceOf(Model_Admin::class);
+});
+
+test('getCronAdmin creates and returns new cron admin', function (): void {
+ $adminModel = new Model_Admin();
+ $adminModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('findOne')->atLeast()->once()
+ ->andReturn(null);
+
+ $dbMock->shouldReceive('dispense')->atLeast()->once()
+ ->andReturn($adminModel);
+
+ $dbMock->shouldReceive('store')->atLeast()->once();
+
+ $passwordMock = Mockery::mock(FOSSBilling\PasswordManager::class);
+ $passwordMock->shouldReceive('hashIt')->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['tools'] = new FOSSBilling\Tools();
+ $di['password'] = $passwordMock;
+
+ $service = new Service();
+ $service->setDi($di);
+
+ $result = $service->getCronAdmin();
+ expect($result)->not->toBeEmpty();
+ expect($result)->toBeInstanceOf(Model_Admin::class);
+});
+
+test('toModel_AdminApiArray returns admin array data', function (): void {
+ $adminModel = new Model_Admin();
+ $adminModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $adminGroupModel = new Model_Admin();
+ $adminGroupModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('load')->atLeast()->once()
+ ->andReturn($adminGroupModel);
+
+ $expected =
+ [
+ 'id' => '',
+ 'role' => '',
+ 'admin_group_id' => '',
+ 'email' => '',
+ 'name' => '',
+ 'status' => '',
+ 'signature' => '',
+ 'created_at' => '',
+ 'updated_at' => '',
+ 'protected' => '',
+ 'group' => ['id' => '', 'name' => ''],
+ ];
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $service = new Service();
+ $service->setDi($di);
+ $result = $service->toModel_AdminApiArray($adminModel);
+
+ expect($result)->not->toBeEmpty();
+ expect($result)->toBeArray();
+ expect(count(array_diff(array_keys($expected), array_keys($result))))->toBe(0, 'Missing array key values.');
+});
+
+test('update updates admin details', function (): void {
+ $data = [
+ 'email' => 'test@example.com',
+ 'admin_group_id' => '1',
+ 'name' => 'testJohn',
+ 'status' => 'active',
+ 'signature' => '1345',
+ ];
+
+ $adminModel = new Model_Admin();
+ $adminModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $eventsMock = Mockery::mock('\Box_EventManager');
+ $eventsMock->shouldReceive('fire')->atLeast()->once();
+
+ $logStub = $this->createStub('\Box_Log');
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')->atLeast()->once();
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+
+ $serviceMock->shouldReceive('hasPermission')->atLeast()->once()->andReturn(true);
+
+ $di = container();
+ $di['events_manager'] = $eventsMock;
+ $di['logger'] = $logStub;
+ $di['db'] = $dbMock;
+
+ $serviceMock->setDi($di);
+
+ $result = $serviceMock->update($adminModel, $data);
+ expect($result)->toBeTrue();
+});
+
+test('delete removes admin account', function (): void {
+ $adminModel = new Model_Admin();
+ $adminModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $eventsMock = Mockery::mock('\Box_EventManager');
+ $eventsMock->shouldReceive('fire')->atLeast()->once();
+
+ $logStub = $this->createStub('\Box_Log');
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('trash')->atLeast()->once();
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+
+ $serviceMock->shouldReceive('hasPermission')->atLeast()->once()->andReturn(true);
+
+ $di = container();
+ $di['events_manager'] = $eventsMock;
+ $di['logger'] = $logStub;
+ $di['db'] = $dbMock;
+
+ $serviceMock->setDi($di);
+
+ $result = $serviceMock->delete($adminModel);
+ expect($result)->toBeTrue();
+});
+
+test('delete throws exception for protected account', function (): void {
+ $adminModel = new Model_Admin();
+ $adminModel->loadBean(new Tests\Helpers\DummyBean());
+ $adminModel->protected = 1;
+
+ $service = new Service();
+
+ expect(fn (): bool => $service->delete($adminModel))
+ ->toThrow(FOSSBilling\Exception::class, 'This administrator account is protected and cannot be removed');
+});
+
+test('changePassword updates admin password', function (): void {
+ $plainTextPassword = 'password';
+ $adminModel = new Model_Admin();
+ $adminModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $eventsMock = Mockery::mock('\Box_EventManager');
+ $eventsMock->shouldReceive('fire')->atLeast()->once();
+
+ $logStub = $this->createStub('\Box_Log');
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')->atLeast()->once();
+
+ $passwordMock = Mockery::mock(FOSSBilling\PasswordManager::class);
+ $passwordMock->shouldReceive('hashIt')->atLeast()->once()
+ ->with($plainTextPassword);
+
+ $profileServiceStub = $this->createStub(Box\Mod\Profile\Service::class);
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+
+ $serviceMock->shouldReceive('hasPermission')->atLeast()->once()->andReturn(true);
+
+ $di = container();
+ $di['events_manager'] = $eventsMock;
+ $di['logger'] = $logStub;
+ $di['db'] = $dbMock;
+ $di['password'] = $passwordMock;
+ $di['mod_service'] = $di->protect(fn () => $profileServiceStub);
+
+ $serviceMock->setDi($di);
+
+ $result = $serviceMock->changePassword($adminModel, $plainTextPassword);
+ expect($result)->toBeTrue();
+});
+
+test('create creates new admin account', function (): void {
+ $data = [
+ 'email' => 'test@example.com',
+ 'admin_group_id' => '1',
+ 'name' => 'testJohn',
+ 'status' => 'active',
+ 'password' => '1345',
+ ];
+
+ $newId = 1;
+
+ $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();
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('dispense')->atLeast()->once()
+ ->andReturn($adminModel);
+ $dbMock->shouldReceive('store')->atLeast()->once()
+ ->andReturn($newId);
+
+ $logStub = $this->createStub('\Box_Log');
+
+ $passwordMock = Mockery::mock(FOSSBilling\PasswordManager::class);
+ $passwordMock->shouldReceive('hashIt')->atLeast()->once()
+ ->with($data['password']);
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+
+ $serviceMock->shouldReceive('hasPermission')->atLeast()->once()->andReturn(true);
+
+ $di = container();
+ $di['events_manager'] = $eventsMock;
+ $di['logger'] = $logStub;
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $systemServiceMock);
+
+ $di['password'] = $passwordMock;
+
+ $serviceMock->setDi($di);
+
+ $result = $serviceMock->create($data);
+ expect($result)->toBeInt();
+ expect($result)->toBe($newId);
+});
+
+test('create throws exception for duplicate email', function (): void {
+ $data = [
+ 'email' => 'test@example.com',
+ 'admin_group_id' => '1',
+ 'name' => 'testJohn',
+ 'status' => 'active',
+ 'password' => '1345',
+ ];
+
+ $newId = 1;
+
+ $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();
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('dispense')->atLeast()->once()
+ ->andReturn($adminModel);
+ $dbMock->shouldReceive('store')->atLeast()->once()
+ ->andThrow(new RedBeanPHP\RedException());
+
+ $logStub = $this->createStub('\Box_Log');
+
+ $passwordMock = Mockery::mock(FOSSBilling\PasswordManager::class);
+ $passwordMock->shouldReceive('hashIt')->atLeast()->once()
+ ->with($data['password']);
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+
+ $serviceMock->shouldReceive('hasPermission')->atLeast()->once()->andReturn(true);
+
+ $di = container();
+ $di['events_manager'] = $eventsMock;
+ $di['logger'] = $logStub;
+ $di['db'] = $dbMock;
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $systemServiceMock);
+
+ $di['password'] = $passwordMock;
+
+ $serviceMock->setDi($di);
+
+ expect(fn () => $serviceMock->create($data))
+ ->toThrow(FOSSBilling\Exception::class, "Staff member with email {$data['email']} is already registered.");
+});
+
+test('getAdminGroupPair returns group pairs', function (): void {
+ $rows = [
+ [
+ 'id' => '1',
+ 'name' => 'First Jogh',
+ ],
+ [
+ 'id' => '2',
+ 'name' => 'Another Smith',
+ ],
+ ];
+
+ $expected = [
+ 1 => 'First Jogh',
+ 2 => 'Another Smith',
+ ];
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getAll')->atLeast()->once()
+ ->andReturn($rows);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $service = new Service();
+ $service->setDi($di);
+
+ $result = $service->getAdminGroupPair();
+
+ expect($result)->toBe($expected);
+ expect($result)->toBeArray();
+});
+
+test('getAdminGroupSearchQuery returns query and params', function (): void {
+ $service = new Service();
+
+ $result = $service->getAdminGroupSearchQuery([]);
+
+ expect($result[0])->toBeString();
+ expect($result[1])->toBeArray();
+});
+
+test('createGroup creates new admin group', function (): void {
+ $adminGroupModel = new Model_AdminGroup();
+ $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);
+ $dbMock->shouldReceive('store')->atLeast()->once()
+ ->andReturn($newGroupId);
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+
+ $serviceMock->shouldReceive('hasPermission')->atLeast()->once()->andReturn(true);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $systemServiceMock);
+
+ $serviceMock->setDi($di);
+
+ $result = $serviceMock->createGroup('new_group_name');
+ expect($result)->toBeInt();
+ expect($result)->toBe($newGroupId);
+});
+
+test('toAdminGroupApiArray returns group array data', function (): void {
+ $adminGroupModel = new Model_AdminGroup();
+ $adminGroupModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $expected =
+ [
+ 'id' => '',
+ 'name' => '',
+ 'created_at' => '',
+ 'updated_at' => '',
+ ];
+
+ $service = new Service();
+
+ $result = $service->toAdminGroupApiArray($adminGroupModel);
+
+ expect($result)->toBeArray();
+ expect(count(array_diff(array_keys($expected), array_keys($result))))->toBe(0, 'Missing array key values.');
+});
+
+test('deleteGroup removes admin group', function (): void {
+ $adminGroupModel = new Model_AdminGroup();
+ $adminGroupModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('trash')->atLeast()->once();
+ $dbMock->shouldReceive('getCell')->atLeast()->once()
+ ->andReturn(0);
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+
+ $serviceMock->shouldReceive('hasPermission')->atLeast()->once()->andReturn(true);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $serviceMock->setDi($di);
+
+ $result = $serviceMock->deleteGroup($adminGroupModel);
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+});
+
+test('deleteGroup throws exception for administrators group', function (): void {
+ $adminGroupModel = new Model_AdminGroup();
+ $adminGroupModel->loadBean(new Tests\Helpers\DummyBean());
+ $adminGroupModel->id = 1;
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+
+ $serviceMock->shouldReceive('hasPermission')->atLeast()->once()->andReturn(true);
+
+ expect(fn () => $serviceMock->deleteGroup($adminGroupModel))
+ ->toThrow(FOSSBilling\Exception::class, 'Administrators group cannot be removed');
+});
+
+test('deleteGroup throws exception when group has members', function (): void {
+ $adminGroupModel = new Model_AdminGroup();
+ $adminGroupModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getCell')->atLeast()->once()
+ ->andReturn(2);
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+
+ $serviceMock->shouldReceive('hasPermission')->atLeast()->once()->andReturn(true);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $serviceMock->setDi($di);
+
+ expect(fn () => $serviceMock->deleteGroup($adminGroupModel))
+ ->toThrow(FOSSBilling\Exception::class, 'Cannot remove group which has staff members');
+});
+
+test('updateGroup updates group details', function (): void {
+ $adminGroupModel = new Model_AdminGroup();
+ $adminGroupModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')->atLeast()->once();
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+
+ $serviceMock->shouldReceive('hasPermission')->atLeast()->once()->andReturn(true);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+
+ $serviceMock->setDi($di);
+
+ $data = ['name' => 'OhExampleName'];
+ $result = $serviceMock->updateGroup($adminGroupModel, $data);
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+});
+
+// Data provider for ActivityAdminHistorySearchFilters
+dataset('ActivityAdminHistorySearchFilters', fn() => [
+ 'empty filters' => [
+ [],
+ 'SELECT m.*, a.email, a.name',
+ [],
+ ],
+ 'search by keyword' => [
+ ['search' => 'keyword'],
+ 'a.name LIKE :name OR a.id LIKE :id OR a.email LIKE :email',
+ ['name' => '%keyword%', 'id' => '%keyword%', 'email' => '%keyword%'],
+ ],
+ 'filter by admin_id' => [
+ ['admin_id' => '2'],
+ 'm.admin_id = :admin_id',
+ ['admin_id' => '2'],
+ ],
+]);
+
+test('getActivityAdminHistorySearchQuery returns correct query and params', function (array $data, string $expectedStr, array $expectedParams): void {
+ $di = container();
+
+ $service = new Service();
+ $service->setDi($di);
+ $result = $service->getActivityAdminHistorySearchQuery($data);
+ expect($result[0])->toBeString();
+ expect($result[1])->toBeArray();
+
+ expect(str_contains((string) $result[0], $expectedStr))->toBeTrue($result[0]);
+ expect(array_diff_key($result[1], $expectedParams))->toBe([]);
+})->with('ActivityAdminHistorySearchFilters');
+
+test('toActivityAdminHistoryApiArray returns history array data', function (): void {
+ $adminHistoryModel = new Model_ActivityAdminHistory();
+ $adminHistoryModel->loadBean(new Tests\Helpers\DummyBean());
+ $adminHistoryModel->admin_id = 2;
+
+ $expected = [
+ 'id' => '',
+ 'ip' => '',
+ 'created_at' => '',
+ 'staff' => [
+ 'id' => $adminHistoryModel->admin_id,
+ 'name' => '',
+ 'email' => '',
+ ],
+ ];
+
+ $adminModel = new Model_Admin();
+ $adminModel->loadBean(new Tests\Helpers\DummyBean());
+ $adminModel->id = 2;
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('load')->atLeast()->once()
+ ->andReturn($adminModel);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $service = new Service();
+ $service->setDi($di);
+ $result = $service->toActivityAdminHistoryApiArray($adminHistoryModel);
+
+ expect($result)->not->toBeEmpty();
+ expect($result)->toBeArray();
+ expect(count(array_diff(array_keys($expected), array_keys($result))))->toBe(0, 'Missing array key values.');
+});
+
+test('setPermissions updates staff permissions', function (): void {
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+
+ $serviceMock->shouldReceive('hasPermission')->atLeast()->once()->andReturn(true);
+
+ $queryBuilderMock = new StaffQueryBuilderMock();
+
+ $dbalMock = new StaffDbalMock($queryBuilderMock);
+
+ $admin = new Model_Admin();
+ $admin->loadBean(new Tests\Helpers\DummyBean());
+ $admin->id = 1;
+ $admin->role = Model_Admin::ROLE_STAFF;
+
+ $loggedInAdmin = new Model_Admin();
+ $loggedInAdmin->loadBean(new Tests\Helpers\DummyBean());
+ $loggedInAdmin->id = 2;
+ $loggedInAdmin->role = Model_Admin::ROLE_ADMIN;
+
+ $di = new Pimple\Container();
+ $di['dbal'] = $dbalMock;
+ $di['loggedin_admin'] = $loggedInAdmin;
+ $serviceMock->setDi($di);
+
+ $result = $serviceMock->setPermissions($admin, []);
+ expect($result)->toBeTrue();
+});
+
+test('getPermissions returns empty array when permissions are empty', function (): void {
+ $statementWithFetchOne = new StaffStatementMock('{}');
+
+ $service = new Service();
+
+ $queryBuilderMock = new StaffQueryBuilderMock($statementWithFetchOne);
+
+ $dbalMock = new StaffDbalMock($queryBuilderMock);
+
+ $di = new Pimple\Container();
+ $di['dbal'] = $dbalMock;
+ $service->setDi($di);
+
+ $member_id = 1;
+ $result = $service->getPermissions($member_id);
+ expect($result)->toBeArray();
+ expect($result)->toBe([]);
+});
+
+test('getPermissions returns permissions array', function (): void {
+ $queryResult = '{"id" : "1"}';
+
+ $statementWithFetchOne = new StaffStatementMock($queryResult);
+
+ $service = new Service();
+
+ $queryBuilderMock = new StaffQueryBuilderMock($statementWithFetchOne);
+
+ $dbalMock = new StaffDbalMock($queryBuilderMock);
+
+ $di = new Pimple\Container();
+ $di['dbal'] = $dbalMock;
+ $service->setDi($di);
+
+ $member_id = 1;
+ $expected = json_decode($queryResult ?? '', true);
+ $result = $service->getPermissions($member_id);
+ expect($result)->toBeArray();
+ expect($result)->toBe($expected);
+});
+
+test('authorizeAdmin returns null when email not found', function (): void {
+ $email = 'example@fossbilling.vm';
+ $password = '123456';
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('findOne')->atLeast()->once()
+ ->andReturn(null);
+
+ $authMock = Mockery::mock('\Box_Authorization');
+ $authMock->shouldReceive('authorizeUser')->atLeast()->once()
+ ->with(null, $password)
+ ->andReturn(null);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['auth'] = $authMock;
+
+ $service = new Service();
+ $service->setDi($di);
+
+ $result = $service->authorizeAdmin($email, $password);
+ expect($result)->toBeNull();
+});
+
+test('authorizeAdmin returns admin model on success', function (): void {
+ $email = 'example@fossbilling.vm';
+ $password = '123456';
+
+ $model = new Model_Admin();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('findOne')->atLeast()->once()
+ ->andReturn($model);
+
+ $authMock = Mockery::mock('\Box_Authorization');
+ $authMock->shouldReceive('authorizeUser')->atLeast()->once()
+ ->with($model, $password)
+ ->andReturn($model);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['auth'] = $authMock;
+
+ $service = new Service();
+ $service->setDi($di);
+
+ $result = $service->authorizeAdmin($email, $password);
+ expect($result)->toBeInstanceOf(Model_Admin::class);
+});
diff --git a/src/modules/Stats/Api/Admin.php b/src/modules/Stats/Api/Admin.php
index 2fad226ba..1ffedba6c 100644
--- a/src/modules/Stats/Api/Admin.php
+++ b/src/modules/Stats/Api/Admin.php
@@ -25,7 +25,7 @@ class Admin extends \Api_Abstract
*/
public function get_summary()
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('stats', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('stats', 'view');
return $this->getService()->getSummary();
}
@@ -37,7 +37,7 @@ class Admin extends \Api_Abstract
*/
public function get_summary_income()
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('stats', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('stats', 'view');
return $this->getService()->getSummaryIncome();
}
@@ -49,7 +49,7 @@ class Admin extends \Api_Abstract
*/
public function get_orders_statuses($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('stats', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('stats', 'view');
return $this->getService()->getOrdersStatuses($data);
}
@@ -61,7 +61,7 @@ class Admin extends \Api_Abstract
*/
public function get_product_summary($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('stats', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('stats', 'view');
return $this->getService()->getProductSummary($data);
}
@@ -73,7 +73,7 @@ class Admin extends \Api_Abstract
*/
public function get_product_sales($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('stats', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('stats', 'view');
return $this->getService()->getProductSales($data);
}
@@ -85,7 +85,7 @@ class Admin extends \Api_Abstract
*/
public function get_income_vs_refunds($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('stats', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('stats', 'view');
return $this->getService()->incomeAndRefundStats($data);
}
@@ -101,7 +101,7 @@ class Admin extends \Api_Abstract
*/
public function get_refunds($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('stats', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('stats', 'view');
return $this->getService()->getRefunds($data);
}
@@ -117,7 +117,7 @@ class Admin extends \Api_Abstract
*/
public function get_income($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('stats', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('stats', 'view');
return $this->getService()->getIncome($data);
}
@@ -132,7 +132,7 @@ class Admin extends \Api_Abstract
*/
public function get_orders($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('stats', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('stats', 'view');
return $this->getService()->getTableStats('client_order', $data);
}
@@ -148,7 +148,7 @@ class Admin extends \Api_Abstract
*/
public function get_clients($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('stats', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('stats', 'view');
return $this->getService()->getTableStats('client', $data);
}
@@ -160,7 +160,7 @@ class Admin extends \Api_Abstract
*/
public function client_countries($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('stats', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('stats', 'view');
return $this->getService()->getClientCountries($data);
}
@@ -172,7 +172,7 @@ class Admin extends \Api_Abstract
*/
public function sales_countries($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('stats', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('stats', 'view');
return $this->getService()->getSalesByCountry($data);
}
@@ -188,7 +188,7 @@ class Admin extends \Api_Abstract
*/
public function get_invoices($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('stats', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('stats', 'view');
return $this->getService()->getTableStats('invoice', $data);
}
@@ -204,7 +204,7 @@ class Admin extends \Api_Abstract
*/
public function get_tickets($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('stats', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('stats', 'view');
return $this->getService()->getTableStats('support_ticket', $data);
}
diff --git a/src/modules/Stats/tests/Unit/Api/AdminTest.php b/src/modules/Stats/tests/Unit/Api/AdminTest.php
new file mode 100644
index 000000000..241c905d0
--- /dev/null
+++ b/src/modules/Stats/tests/Unit/Api/AdminTest.php
@@ -0,0 +1,229 @@
+setDi($di);
+ $getDi = $api->getDi();
+ expect($getDi)->toBe($di);
+});
+
+test('gets summary', function (): void {
+ $api = new Box\Mod\Stats\Api\Admin();
+ $serviceMock = Mockery::mock(Box\Mod\Stats\Service::class);
+ /** @var Mockery\Expectation $expectation */
+ $expectation = $serviceMock->shouldReceive('getSummary');
+ $expectation->atLeast()->once();
+ $expectation->andReturn([]);
+
+ $api->setService($serviceMock);
+
+ $result = $api->get_summary();
+ expect($result)->toBeArray();
+});
+
+test('gets summary income', function (): void {
+ $api = new Box\Mod\Stats\Api\Admin();
+ $serviceMock = Mockery::mock(Box\Mod\Stats\Service::class);
+ /** @var Mockery\Expectation $expectation */
+ $expectation = $serviceMock->shouldReceive('getSummaryIncome');
+ $expectation->atLeast()->once();
+ $expectation->andReturn([]);
+
+ $api->setService($serviceMock);
+
+ $result = $api->get_summary_income();
+ expect($result)->toBeArray();
+});
+
+test('gets order statuses', function (): void {
+ $api = new Box\Mod\Stats\Api\Admin();
+ $serviceMock = Mockery::mock(Box\Mod\Stats\Service::class);
+ /** @var Mockery\Expectation $expectation */
+ $expectation = $serviceMock->shouldReceive('getOrdersStatuses');
+ $expectation->atLeast()->once();
+ $expectation->andReturn([]);
+
+ $api->setService($serviceMock);
+
+ $data = [];
+ $result = $api->get_orders_statuses($data);
+ expect($result)->toBeArray();
+});
+
+test('gets product summary', function (): void {
+ $api = new Box\Mod\Stats\Api\Admin();
+ $serviceMock = Mockery::mock(Box\Mod\Stats\Service::class);
+ /** @var Mockery\Expectation $expectation */
+ $expectation = $serviceMock->shouldReceive('getProductSummary');
+ $expectation->atLeast()->once();
+ $expectation->andReturn([]);
+
+ $api->setService($serviceMock);
+
+ $data = [];
+ $result = $api->get_product_summary($data);
+ expect($result)->toBeArray();
+});
+
+test('gets product sales', function (): void {
+ $api = new Box\Mod\Stats\Api\Admin();
+ $serviceMock = Mockery::mock(Box\Mod\Stats\Service::class);
+ /** @var Mockery\Expectation $expectation */
+ $expectation = $serviceMock->shouldReceive('getProductSales');
+ $expectation->atLeast()->once();
+ $expectation->andReturn([]);
+
+ $api->setService($serviceMock);
+
+ $data = [];
+ $result = $api->get_product_sales($data);
+ expect($result)->toBeArray();
+});
+
+test('gets income vs refunds', function (): void {
+ $api = new Box\Mod\Stats\Api\Admin();
+ $serviceMock = Mockery::mock(Box\Mod\Stats\Service::class);
+ /** @var Mockery\Expectation $expectation */
+ $expectation = $serviceMock->shouldReceive('incomeAndRefundStats');
+ $expectation->atLeast()->once();
+ $expectation->andReturn([]);
+
+ $api->setService($serviceMock);
+
+ $data = [];
+ $result = $api->get_income_vs_refunds($data);
+ expect($result)->toBeArray();
+});
+
+test('gets refunds', function (): void {
+ $api = new Box\Mod\Stats\Api\Admin();
+ $serviceMock = Mockery::mock(Box\Mod\Stats\Service::class);
+ /** @var Mockery\Expectation $expectation */
+ $expectation = $serviceMock->shouldReceive('getRefunds');
+ $expectation->atLeast()->once();
+ $expectation->andReturn([]);
+
+ $api->setService($serviceMock);
+
+ $data = [];
+ $result = $api->get_refunds($data);
+ expect($result)->toBeArray();
+});
+
+test('gets income', function (): void {
+ $api = new Box\Mod\Stats\Api\Admin();
+ $serviceMock = Mockery::mock(Box\Mod\Stats\Service::class);
+ /** @var Mockery\Expectation $expectation */
+ $expectation = $serviceMock->shouldReceive('getIncome');
+ $expectation->atLeast()->once();
+ $expectation->andReturn([]);
+
+ $api->setService($serviceMock);
+
+ $data = [];
+ $result = $api->get_income($data);
+ expect($result)->toBeArray();
+});
+
+test('gets orders', function (): void {
+ $api = new Box\Mod\Stats\Api\Admin();
+ $serviceMock = Mockery::mock(Box\Mod\Stats\Service::class);
+ /** @var Mockery\Expectation $expectation */
+ $expectation = $serviceMock->shouldReceive('getTableStats');
+ $expectation->atLeast()->once();
+ $expectation->andReturn([]);
+
+ $api->setService($serviceMock);
+
+ $data = [];
+ $result = $api->get_orders($data);
+ expect($result)->toBeArray();
+});
+
+test('gets clients', function (): void {
+ $api = new Box\Mod\Stats\Api\Admin();
+ $serviceMock = Mockery::mock(Box\Mod\Stats\Service::class);
+ /** @var Mockery\Expectation $expectation */
+ $expectation = $serviceMock->shouldReceive('getTableStats');
+ $expectation->atLeast()->once();
+ $expectation->andReturn([]);
+
+ $api->setService($serviceMock);
+
+ $data = [];
+ $result = $api->get_clients($data);
+ expect($result)->toBeArray();
+});
+
+test('gets client countries', function (): void {
+ $api = new Box\Mod\Stats\Api\Admin();
+ $serviceMock = Mockery::mock(Box\Mod\Stats\Service::class);
+ /** @var Mockery\Expectation $expectation */
+ $expectation = $serviceMock->shouldReceive('getClientCountries');
+ $expectation->atLeast()->once();
+ $expectation->andReturn([]);
+
+ $api->setService($serviceMock);
+
+ $data = [];
+ $result = $api->client_countries($data);
+ expect($result)->toBeArray();
+});
+
+test('gets sales countries', function (): void {
+ $api = new Box\Mod\Stats\Api\Admin();
+ $serviceMock = Mockery::mock(Box\Mod\Stats\Service::class);
+ /** @var Mockery\Expectation $expectation */
+ $expectation = $serviceMock->shouldReceive('getSalesByCountry');
+ $expectation->atLeast()->once();
+ $expectation->andReturn([]);
+
+ $api->setService($serviceMock);
+
+ $data = [];
+ $result = $api->sales_countries($data);
+ expect($result)->toBeArray();
+});
+
+test('gets invoices', function (): void {
+ $api = new Box\Mod\Stats\Api\Admin();
+ $serviceMock = Mockery::mock(Box\Mod\Stats\Service::class);
+ /** @var Mockery\Expectation $expectation */
+ $expectation = $serviceMock->shouldReceive('getTableStats');
+ $expectation->atLeast()->once();
+ $expectation->andReturn([]);
+
+ $api->setService($serviceMock);
+
+ $data = [];
+ $result = $api->get_invoices($data);
+ expect($result)->toBeArray();
+});
+
+test('gets tickets', function (): void {
+ $api = new Box\Mod\Stats\Api\Admin();
+ $serviceMock = Mockery::mock(Box\Mod\Stats\Service::class);
+ /** @var Mockery\Expectation $expectation */
+ $expectation = $serviceMock->shouldReceive('getTableStats');
+ $expectation->atLeast()->once();
+ $expectation->andReturn([]);
+
+ $api->setService($serviceMock);
+
+ $data = [];
+ $result = $api->get_tickets($data);
+ expect($result)->toBeArray();
+});
diff --git a/src/modules/Stats/tests/Unit/ServiceTest.php b/src/modules/Stats/tests/Unit/ServiceTest.php
new file mode 100644
index 000000000..e9daf6efc
--- /dev/null
+++ b/src/modules/Stats/tests/Unit/ServiceTest.php
@@ -0,0 +1,325 @@
+setDi($di);
+ $getDi = $service->getDi();
+ expect($getDi)->toBe($di);
+});
+
+test('gets order statuses', function (): void {
+ $service = new Box\Mod\Stats\Service();
+ $orderServiceMock = Mockery::mock(Box\Mod\Order\Service::class);
+ /** @var Mockery\Expectation $expectation */
+ $expectation = $orderServiceMock->shouldReceive('counter');
+ $expectation->atLeast()->once();
+ $expectation->andReturn([]);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $orderServiceMock);
+
+ $service->setDi($di);
+
+ $result = $service->getOrdersStatuses([]);
+ expect($result)->toBeArray();
+});
+
+test('gets product summary', function (): void {
+ $service = new Box\Mod\Stats\Service();
+ $data = [];
+
+ $resultMock = Mockery::mock(Doctrine\DBAL\Result::class);
+ /** @var Mockery\Expectation $expectation1 */
+ $expectation1 = $resultMock->shouldReceive('fetchAllAssociative');
+ $expectation1->atLeast()->once();
+ $expectation1->andReturn([]);
+
+ $dbalMock = Mockery::mock(Doctrine\DBAL\Connection::class);
+ /** @var Mockery\Expectation $expectation2 */
+ $expectation2 = $dbalMock->shouldReceive('executeQuery');
+ $expectation2->atLeast()->once();
+ $expectation2->andReturn($resultMock);
+
+ $di = container();
+ $di['dbal'] = $dbalMock;
+
+ $service->setDi($di);
+ $result = $service->getProductSummary($data);
+ expect($result)->toBeArray();
+});
+
+test('gets summary', function (): void {
+ $service = new Box\Mod\Stats\Service();
+ $resultMock = Mockery::mock(Doctrine\DBAL\Result::class);
+ /** @var Mockery\Expectation $expectation1 */
+ $expectation1 = $resultMock->shouldReceive('fetchOne');
+ $expectation1->atLeast()->once();
+ $expectation1->andReturn(null);
+
+ $dbalMock = Mockery::mock(Doctrine\DBAL\Connection::class);
+ /** @var Mockery\Expectation $expectation2 */
+ $expectation2 = $dbalMock->shouldReceive('executeQuery');
+ $expectation2->atLeast()->once();
+ $expectation2->andReturn($resultMock);
+
+ $di = container();
+ $di['dbal'] = $dbalMock;
+ $service->setDi($di);
+
+ $expected = [
+ 'clients_total' => null,
+ 'clients_today' => null,
+ 'clients_yesterday' => null,
+ 'clients_this_month' => null,
+ 'clients_last_month' => null,
+
+ 'orders_total' => null,
+ 'orders_today' => null,
+ 'orders_yesterday' => null,
+ 'orders_this_month' => null,
+ 'orders_last_month' => null,
+
+ 'invoices_total' => null,
+ 'invoices_today' => null,
+ 'invoices_yesterday' => null,
+ 'invoices_this_month' => null,
+ 'invoices_last_month' => null,
+
+ 'tickets_total' => null,
+ 'tickets_today' => null,
+ 'tickets_yesterday' => null,
+ 'tickets_this_month' => null,
+ 'tickets_last_month' => null,
+ ];
+
+ $result = $service->getSummary();
+ expect($result)->toBeArray()
+ ->and($result)->toBe($expected);
+});
+
+test('gets summary income', function (): void {
+ $service = new Box\Mod\Stats\Service();
+ $resultMock = Mockery::mock(Doctrine\DBAL\Result::class);
+ /** @var Mockery\Expectation $expectation1 */
+ $expectation1 = $resultMock->shouldReceive('fetchOne');
+ $expectation1->atLeast()->once();
+ $expectation1->andReturn(null);
+
+ $dbalMock = Mockery::mock(Doctrine\DBAL\Connection::class);
+ /** @var Mockery\Expectation $expectation2 */
+ $expectation2 = $dbalMock->shouldReceive('executeQuery');
+ $expectation2->atLeast()->once();
+ $expectation2->andReturn($resultMock);
+
+ $di = container();
+ $di['dbal'] = $dbalMock;
+ $service->setDi($di);
+
+ $expected = [
+ 'total' => null,
+ 'today' => null,
+ 'yesterday' => null,
+ 'this_month' => null,
+ 'last_month' => null,
+ ];
+
+ $result = $service->getSummaryIncome();
+ expect($result)->toBeArray()
+ ->and($result)->toBe($expected);
+});
+
+test('gets product sales', function (): void {
+ $service = new Box\Mod\Stats\Service();
+ $res = ['testProduct' => 1];
+ $resultMock = Mockery::mock(Doctrine\DBAL\Result::class);
+ /** @var Mockery\Expectation $expectation1 */
+ $expectation1 = $resultMock->shouldReceive('fetchAllKeyValue');
+ $expectation1->atLeast()->once();
+ $expectation1->andReturn($res);
+
+ $dbalMock = Mockery::mock(Doctrine\DBAL\Connection::class);
+ /** @var Mockery\Expectation $expectation2 */
+ $expectation2 = $dbalMock->shouldReceive('executeQuery');
+ $expectation2->atLeast()->once();
+ $expectation2->andReturn($resultMock);
+
+ $di = container();
+ $di['dbal'] = $dbalMock;
+ $service->setDi($di);
+
+ $data = [
+ 'date_from' => 'yesterday',
+ 'date_to' => 'now',
+ ];
+ $result = $service->getProductSales($data);
+ expect($result)->toBeArray();
+});
+
+test('gets income and refund stats', function (): void {
+ $service = new Box\Mod\Stats\Service();
+ $res = [
+ [
+ 'refund' => 0,
+ 'income' => 0,
+ ],
+ ];
+ $resultMock = Mockery::mock(Doctrine\DBAL\Result::class);
+ /** @var Mockery\Expectation $expectation1 */
+ $expectation1 = $resultMock->shouldReceive('fetchAllAssociative');
+ $expectation1->atLeast()->once();
+ $expectation1->andReturn($res);
+
+ $dbalMock = Mockery::mock(Doctrine\DBAL\Connection::class);
+ /** @var Mockery\Expectation $expectation2 */
+ $expectation2 = $dbalMock->shouldReceive('executeQuery');
+ $expectation2->atLeast()->once();
+ $expectation2->andReturn($resultMock);
+
+ $di = container();
+ $di['dbal'] = $dbalMock;
+ $service->setDi($di);
+
+ $result = $service->incomeAndRefundStats([]);
+ expect($result)->toBeArray()
+ ->and($result)->toBe($res[0]);
+});
+
+test('gets refunds', function (): void {
+ $service = new Box\Mod\Stats\Service();
+ $resultMock = Mockery::mock(Doctrine\DBAL\Result::class);
+ /** @var Mockery\Expectation $expectation1 */
+ $expectation1 = $resultMock->shouldReceive('fetchAllKeyValue');
+ $expectation1->atLeast()->once();
+ $expectation1->andReturn([]);
+
+ $dbalMock = Mockery::mock(Doctrine\DBAL\Connection::class);
+ /** @var Mockery\Expectation $expectation2 */
+ $expectation2 = $dbalMock->shouldReceive('executeQuery');
+ $expectation2->atLeast()->once();
+ $expectation2->andReturn($resultMock);
+
+ $di = container();
+ $di['dbal'] = $dbalMock;
+
+ $service->setDi($di);
+
+ $data = [
+ 'date_from' => 'yesterday',
+ 'date_to' => 'now',
+ ];
+ $result = $service->getRefunds($data);
+ expect($result)->toBeArray();
+});
+
+test('gets income', function (): void {
+ $service = new Box\Mod\Stats\Service();
+ $resultMock = Mockery::mock(Doctrine\DBAL\Result::class);
+ /** @var Mockery\Expectation $expectation1 */
+ $expectation1 = $resultMock->shouldReceive('fetchAllKeyValue');
+ $expectation1->atLeast()->once();
+ $expectation1->andReturn([]);
+
+ $dbalMock = Mockery::mock(Doctrine\DBAL\Connection::class);
+ /** @var Mockery\Expectation $expectation2 */
+ $expectation2 = $dbalMock->shouldReceive('executeQuery');
+ $expectation2->atLeast()->once();
+ $expectation2->andReturn($resultMock);
+
+ $di = container();
+ $di['dbal'] = $dbalMock;
+
+ $service->setDi($di);
+
+ $data = [
+ 'date_from' => 'yesterday',
+ 'date_to' => 'now',
+ ];
+ $result = $service->getIncome($data);
+ expect($result)->toBeArray();
+});
+
+test('gets client countries', function (): void {
+ $service = new Box\Mod\Stats\Service();
+ $resultMock = Mockery::mock(Doctrine\DBAL\Result::class);
+ /** @var Mockery\Expectation $expectation1 */
+ $expectation1 = $resultMock->shouldReceive('fetchAllKeyValue');
+ $expectation1->atLeast()->once();
+ $expectation1->andReturn([]);
+
+ $dbalMock = Mockery::mock(Doctrine\DBAL\Connection::class);
+ /** @var Mockery\Expectation $expectation2 */
+ $expectation2 = $dbalMock->shouldReceive('executeQuery');
+ $expectation2->atLeast()->once();
+ $expectation2->andReturn($resultMock);
+
+ $di = container();
+ $di['dbal'] = $dbalMock;
+
+ $service->setDi($di);
+
+ $result = $service->getClientCountries([]);
+ expect($result)->toBeArray();
+});
+
+test('gets sales by country', function (): void {
+ $service = new Box\Mod\Stats\Service();
+ $resultMock = Mockery::mock(Doctrine\DBAL\Result::class);
+ /** @var Mockery\Expectation $expectation1 */
+ $expectation1 = $resultMock->shouldReceive('fetchAllKeyValue');
+ $expectation1->atLeast()->once();
+ $expectation1->andReturn([]);
+
+ $dbalMock = Mockery::mock(Doctrine\DBAL\Connection::class);
+ /** @var Mockery\Expectation $expectation2 */
+ $expectation2 = $dbalMock->shouldReceive('executeQuery');
+ $expectation2->atLeast()->once();
+ $expectation2->andReturn($resultMock);
+
+ $di = container();
+ $di['dbal'] = $dbalMock;
+
+ $service->setDi($di);
+
+ $result = $service->getSalesByCountry([]);
+ expect($result)->toBeArray();
+});
+
+test('gets table stats', function (): void {
+ $service = new Box\Mod\Stats\Service();
+ $resultMock = Mockery::mock(Doctrine\DBAL\Result::class);
+ /** @var Mockery\Expectation $expectation1 */
+ $expectation1 = $resultMock->shouldReceive('fetchAllKeyValue');
+ $expectation1->atLeast()->once();
+ $expectation1->andReturn([]);
+
+ $dbalMock = Mockery::mock(Doctrine\DBAL\Connection::class);
+ /** @var Mockery\Expectation $expectation2 */
+ $expectation2 = $dbalMock->shouldReceive('executeQuery');
+ $expectation2->atLeast()->once();
+ $expectation2->andReturn($resultMock);
+
+ $di = container();
+ $di['dbal'] = $dbalMock;
+
+ $service->setDi($di);
+
+ $data = [
+ 'date_from' => 'yesterday',
+ 'date_to' => 'now',
+ ];
+ $result = $service->getTableStats('client', $data);
+ expect($result)->toBeArray();
+});
diff --git a/src/modules/Support/Api/Admin.php b/src/modules/Support/Api/Admin.php
index 90afaeda0..8bdedd0a0 100644
--- a/src/modules/Support/Api/Admin.php
+++ b/src/modules/Support/Api/Admin.php
@@ -30,13 +30,13 @@ class Admin extends \Api_Abstract
*/
public function ticket_get_list(array $data): array
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'view');
[$sql, $bindings] = $this->getService()->getSearchQuery($data);
- $pager = $this->di['pager']->getPaginatedResultSet($sql, $bindings, PaginationOptions::fromArray($data));
+ $pager = $this->getDi()['pager']->getPaginatedResultSet($sql, $bindings, PaginationOptions::fromArray($data));
foreach ($pager['list'] as $key => $ticketArr) {
- $ticket = $this->di['db']->getExistingModelById('SupportTicket', $ticketArr['id'], 'Ticket not found');
+ $ticket = $this->getDi()['db']->getExistingModelById('SupportTicket', $ticketArr['id'], 'Ticket not found');
$pager['list'][$key] = $this->getService()->toApiArray($ticket, true, $this->getIdentity());
}
@@ -49,9 +49,9 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Ticket ID is missing'])]
public function ticket_get(array $data): array
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'view');
- $model = $this->di['db']->getExistingModelById('SupportTicket', $data['id'], 'Ticket not found');
+ $model = $this->getDi()['db']->getExistingModelById('SupportTicket', $data['id'], 'Ticket not found');
return $this->getService()->toApiArray($model, true, $this->getIdentity());
}
@@ -67,9 +67,9 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Ticket ID is missing'])]
public function ticket_update(array $data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_tickets');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_tickets');
- $model = $this->di['db']->getExistingModelById('SupportTicket', $data['id'], 'Ticket not found');
+ $model = $this->getDi()['db']->getExistingModelById('SupportTicket', $data['id'], 'Ticket not found');
// Sanitize subject if provided
if (isset($data['subject'])) {
@@ -85,9 +85,9 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Ticket message ID is missing', 'content' => 'Ticket message content is missing'])]
public function ticket_message_update(array $data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_tickets');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_tickets');
- $model = $this->di['db']->getExistingModelById('SupportTicketMessage', $data['id'], 'Ticket message not found');
+ $model = $this->getDi()['db']->getExistingModelById('SupportTicketMessage', $data['id'], 'Ticket message not found');
return $this->getService()->ticketMessageUpdate($model, $data['content']);
}
@@ -98,9 +98,9 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Ticket ID is missing'])]
public function ticket_delete(array $data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_tickets');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_tickets');
- $model = $this->di['db']->getExistingModelById('SupportTicket', $data['id'], 'Ticket not found');
+ $model = $this->getDi()['db']->getExistingModelById('SupportTicket', $data['id'], 'Ticket not found');
return $this->getService()->rm($model);
}
@@ -113,12 +113,12 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Ticket ID is missing', 'content' => 'Ticket message content is missing'])]
public function ticket_reply(array $data): int
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_tickets');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_tickets');
// Sanitize content to prevent XSS attacks
$data['content'] = \FOSSBilling\Tools::sanitizeContent($data['content'], true);
- $ticket = $this->di['db']->getExistingModelById('SupportTicket', $data['id'], 'Ticket not found');
+ $ticket = $this->getDi()['db']->getExistingModelById('SupportTicket', $data['id'], 'Ticket not found');
return $this->getService()->ticketReply($ticket, $this->getIdentity(), $data['content']);
}
@@ -129,9 +129,9 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Ticket ID is missing'])]
public function ticket_close(array $data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_tickets');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_tickets');
- $ticket = $this->di['db']->getExistingModelById('SupportTicket', $data['id'], 'Ticket not found');
+ $ticket = $this->getDi()['db']->getExistingModelById('SupportTicket', $data['id'], 'Ticket not found');
if ($ticket->status == \Model_SupportTicket::CLOSED) {
return true;
@@ -151,13 +151,13 @@ class Admin extends \Api_Abstract
#[RequiredParams(['client_id' => 'Client ID is missing', 'content' => 'Ticket content required', 'subject' => 'Ticket subject required', 'support_helpdesk_id' => 'Ticket support_helpdesk_id is required'])]
public function ticket_create(array $data): int
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_tickets');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_tickets');
// Sanitize content to prevent XSS attacks
$data['content'] = \FOSSBilling\Tools::sanitizeContent($data['content'], true);
- $client = $this->di['db']->getExistingModelById('Client', $data['client_id'], 'Client not found');
- $helpdesk = $this->di['db']->getExistingModelById('SupportHelpdesk', $data['support_helpdesk_id'], 'Helpdesk invalid');
+ $client = $this->getDi()['db']->getExistingModelById('Client', $data['client_id'], 'Client not found');
+ $helpdesk = $this->getDi()['db']->getExistingModelById('SupportHelpdesk', $data['support_helpdesk_id'], 'Helpdesk invalid');
return $this->getService()->ticketCreateForAdmin($client, $helpdesk, $data, $this->getIdentity());
}
@@ -170,15 +170,15 @@ class Admin extends \Api_Abstract
*/
public function batch_ticket_auto_close($data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_tickets', null, $this->identity);
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_tickets', null, $this->identity);
// Auto close support tickets
$expiredArr = $this->getService()->getExpired();
foreach ($expiredArr as $ticketArr) {
- $ticketModel = $this->di['db']->getExistingModelById('SupportTicket', $ticketArr['id'], 'Ticket not found');
+ $ticketModel = $this->getDi()['db']->getExistingModelById('SupportTicket', $ticketArr['id'], 'Ticket not found');
if (!$this->getService()->autoClose($ticketModel)) {
- $this->di['logger']->info('Ticket %s was not closed', $ticketModel->id);
+ $this->getDi()['logger']->info('Ticket %s was not closed', $ticketModel->id);
}
}
@@ -193,13 +193,13 @@ class Admin extends \Api_Abstract
*/
public function batch_public_ticket_auto_close($data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_tickets', null, $this->identity);
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_tickets', null, $this->identity);
// Auto close public tickets
$expired = $this->getService()->publicGetExpired();
foreach ($expired as $model) {
if (!$this->getService()->publicAutoClose($model)) {
- $this->di['logger']->info('Public Ticket %s was not closed', $model->id);
+ $this->getDi()['logger']->info('Public Ticket %s was not closed', $model->id);
}
}
@@ -211,7 +211,7 @@ class Admin extends \Api_Abstract
*/
public function ticket_get_statuses(array $data): array
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'view');
if (isset($data['titles'])) {
return $this->getService()->getStatuses();
@@ -225,13 +225,13 @@ class Admin extends \Api_Abstract
*/
public function public_ticket_get_list(array $data): array
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'view');
[$sql, $bindings] = $this->getService()->publicGetSearchQuery($data);
- $pager = $this->di['pager']->getPaginatedResultSet($sql, $bindings, PaginationOptions::fromArray($data));
+ $pager = $this->getDi()['pager']->getPaginatedResultSet($sql, $bindings, PaginationOptions::fromArray($data));
foreach ($pager['list'] as $key => $ticketArr) {
- $ticket = $this->di['db']->getExistingModelById('SupportPTicket', $ticketArr['id'], 'Ticket not found');
+ $ticket = $this->getDi()['db']->getExistingModelById('SupportPTicket', $ticketArr['id'], 'Ticket not found');
$pager['list'][$key] = $this->getService()->publicToApiArray($ticket, true, $this->getIdentity());
}
@@ -246,7 +246,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['name' => 'Name is required', 'email' => 'Email is required', 'subject' => 'Subject is required', 'message' => 'Message is required'])]
public function public_ticket_create(array $data): int
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_tickets');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_tickets');
$data['subject'] = \FOSSBilling\Tools::sanitizeContent($data['subject'], false);
$data['message'] = \FOSSBilling\Tools::sanitizeContent($data['message'], true);
@@ -262,9 +262,9 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Ticket ID is missing'])]
public function public_ticket_get(array $data): array
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'view');
- $model = $this->di['db']->getExistingModelById('SupportPTicket', $data['id'], 'Ticket not found');
+ $model = $this->getDi()['db']->getExistingModelById('SupportPTicket', $data['id'], 'Ticket not found');
return $this->getService()->publicToApiArray($model, true, $this->getIdentity());
}
@@ -277,9 +277,9 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Ticket ID is missing'])]
public function public_ticket_delete(array $data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_tickets');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_tickets');
- $model = $this->di['db']->getExistingModelById('SupportPTicket', $data['id'], 'Ticket not found');
+ $model = $this->getDi()['db']->getExistingModelById('SupportPTicket', $data['id'], 'Ticket not found');
return $this->getService()->publicRm($model);
}
@@ -292,9 +292,9 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Ticket ID is missing'])]
public function public_ticket_close(array $data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_tickets');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_tickets');
- $ticket = $this->di['db']->getExistingModelById('SupportPTicket', $data['id'], 'Ticket not found');
+ $ticket = $this->getDi()['db']->getExistingModelById('SupportPTicket', $data['id'], 'Ticket not found');
return $this->getService()->publicCloseTicket($ticket, $this->getIdentity());
}
@@ -310,9 +310,9 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Ticket ID is missing'])]
public function public_ticket_update(array $data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_tickets');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_tickets');
- $model = $this->di['db']->getExistingModelById('SupportPTicket', $data['id'], 'Ticket not found');
+ $model = $this->getDi()['db']->getExistingModelById('SupportPTicket', $data['id'], 'Ticket not found');
return $this->getService()->publicTicketUpdate($model, $data);
}
@@ -325,11 +325,11 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Ticket ID is missing', 'content' => 'Ticket content required'])]
public function public_ticket_reply(array $data): int
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_tickets');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_tickets');
$data['content'] = \FOSSBilling\Tools::sanitizeContent($data['content'], true);
- $ticket = $this->di['db']->getExistingModelById('SupportPTicket', $data['id'], 'Ticket not found');
+ $ticket = $this->getDi()['db']->getExistingModelById('SupportPTicket', $data['id'], 'Ticket not found');
return $this->getService()->publicTicketReply($ticket, $this->getIdentity(), $data['content']);
}
@@ -339,7 +339,7 @@ class Admin extends \Api_Abstract
*/
public function public_ticket_get_statuses(array $data): array
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'view');
if (isset($data['titles'])) {
return $this->getService()->publicGetStatuses();
@@ -353,11 +353,11 @@ class Admin extends \Api_Abstract
*/
public function helpdesk_get_list(array $data): array
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'view');
[$sql, $bindings] = $this->getService()->helpdeskGetSearchQuery($data);
- return $this->di['pager']->getPaginatedResultSet($sql, $bindings, PaginationOptions::fromArray($data));
+ return $this->getDi()['pager']->getPaginatedResultSet($sql, $bindings, PaginationOptions::fromArray($data));
}
/**
@@ -365,7 +365,7 @@ class Admin extends \Api_Abstract
*/
public function helpdesk_get_pairs(array $data): array
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'view');
return $this->getService()->helpdeskGetPairs();
}
@@ -378,9 +378,9 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Help desk ID is missing'])]
public function helpdesk_get(array $data): array
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'view');
- $model = $this->di['db']->getExistingModelById('SupportHelpdesk', $data['id'], 'Help desk not found');
+ $model = $this->getDi()['db']->getExistingModelById('SupportHelpdesk', $data['id'], 'Help desk not found');
return $this->getService()->helpdeskToApiArray($model, $this->getIdentity());
}
@@ -399,9 +399,9 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Help desk ID is missing'])]
public function helpdesk_update(array $data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_helpdesk');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_helpdesk');
- $model = $this->di['db']->getExistingModelById('SupportHelpdesk', $data['id'], 'Help desk not found');
+ $model = $this->getDi()['db']->getExistingModelById('SupportHelpdesk', $data['id'], 'Help desk not found');
return $this->getService()->helpdeskUpdate($model, $data);
}
@@ -421,7 +421,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['name' => 'Help desk title is missing'])]
public function helpdesk_create(array $data): int
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_helpdesk');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_helpdesk');
return $this->getService()->helpdeskCreate($data);
}
@@ -434,9 +434,9 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Help desk ID is missing'])]
public function helpdesk_delete(array $data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_helpdesk');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_helpdesk');
- $model = $this->di['db']->getExistingModelById('SupportHelpdesk', $data['id'], 'Help desk not found');
+ $model = $this->getDi()['db']->getExistingModelById('SupportHelpdesk', $data['id'], 'Help desk not found');
return $this->getService()->helpdeskRm($model);
}
@@ -446,13 +446,13 @@ class Admin extends \Api_Abstract
*/
public function canned_get_list(array $data): array
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'view');
[$sql, $bindings] = $this->getService()->cannedGetSearchQuery($data);
- $pager = $this->di['pager']->getPaginatedResultSet($sql, $bindings, PaginationOptions::fromArray($data));
+ $pager = $this->getDi()['pager']->getPaginatedResultSet($sql, $bindings, PaginationOptions::fromArray($data));
foreach ($pager['list'] as $key => $item) {
- $staff = $this->di['db']->getExistingModelById('SupportPr', $item['id'], 'Canned response not found');
+ $staff = $this->getDi()['db']->getExistingModelById('SupportPr', $item['id'], 'Canned response not found');
$pager['list'][$key] = $this->getService()->cannedToApiArray($staff);
}
@@ -464,12 +464,12 @@ class Admin extends \Api_Abstract
*/
public function canned_pairs(): array
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'view');
- $res = $this->di['db']->getAssoc('SELECT id, title FROM support_pr_category WHERE 1');
+ $res = $this->getDi()['db']->getAssoc('SELECT id, title FROM support_pr_category WHERE 1');
$list = [];
foreach ($res as $id => $title) {
- $list[$title] = $this->di['db']->getAssoc('SELECT id, title FROM support_pr WHERE support_pr_category_id = :id', ['id' => $id]);
+ $list[$title] = $this->getDi()['db']->getAssoc('SELECT id, title FROM support_pr WHERE support_pr_category_id = :id', ['id' => $id]);
}
return $list;
@@ -483,9 +483,9 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Canned reply ID is missing'])]
public function canned_get(array $data): array
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'view');
- $model = $this->di['db']->getExistingModelById('SupportPr', $data['id'], 'Canned reply not found');
+ $model = $this->getDi()['db']->getExistingModelById('SupportPr', $data['id'], 'Canned reply not found');
return $this->getService()->cannedToApiArray($model);
}
@@ -498,9 +498,9 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Canned reply ID is missing'])]
public function canned_delete(array $data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_canned');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_canned');
- $model = $this->di['db']->getExistingModelById('SupportPr', $data['id'], 'Canned reply not found');
+ $model = $this->getDi()['db']->getExistingModelById('SupportPr', $data['id'], 'Canned reply not found');
return $this->getService()->cannedRm($model);
}
@@ -515,7 +515,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['title' => 'Canned reply title is missing', 'category_id' => 'Canned reply category ID is missing'])]
public function canned_create(array $data): int
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_canned');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_canned');
$content = $data['content'] ?? null;
@@ -534,9 +534,9 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Canned reply ID is missing'])]
public function canned_update(array $data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_canned');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_canned');
- $model = $this->di['db']->getExistingModelById('SupportPr', $data['id'], 'Canned reply not found');
+ $model = $this->getDi()['db']->getExistingModelById('SupportPr', $data['id'], 'Canned reply not found');
return $this->getService()->cannedUpdate($model, $data);
}
@@ -546,9 +546,9 @@ class Admin extends \Api_Abstract
*/
public function canned_category_pairs(array $data): array
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'view');
- return $this->di['db']->getAssoc('SELECT id, title FROM support_pr_category WHERE 1');
+ return $this->getDi()['db']->getAssoc('SELECT id, title FROM support_pr_category WHERE 1');
}
/**
@@ -559,9 +559,9 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Canned category ID is missing'])]
public function canned_category_get(array $data): array
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'view');
- $model = $this->di['db']->getExistingModelById('SupportPrCategory', $data['id'], 'Canned category not found');
+ $model = $this->getDi()['db']->getExistingModelById('SupportPrCategory', $data['id'], 'Canned category not found');
return $this->getService()->cannedCategoryToApiArray($model);
}
@@ -576,9 +576,9 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Canned category ID is missing'])]
public function canned_category_update(array $data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_canned');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_canned');
- $model = $this->di['db']->getExistingModelById('SupportPrCategory', $data['id'], 'Canned category not found');
+ $model = $this->getDi()['db']->getExistingModelById('SupportPrCategory', $data['id'], 'Canned category not found');
$title = $data['title'] ?? $model->title;
@@ -593,9 +593,9 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Canned category ID is missing'])]
public function canned_category_delete(array $data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_canned');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_canned');
- $model = $this->di['db']->getExistingModelById('SupportPrCategory', $data['id'], 'Canned category not found');
+ $model = $this->getDi()['db']->getExistingModelById('SupportPrCategory', $data['id'], 'Canned category not found');
return $this->getService()->cannedCategoryRm($model);
}
@@ -610,7 +610,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['title' => 'Canned category title is missing'])]
public function canned_category_create(array $data): int
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_canned');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_canned');
return $this->getService()->cannedCategoryCreate($data['title']);
}
@@ -625,9 +625,9 @@ class Admin extends \Api_Abstract
#[RequiredParams(['ticket_id' => 'ticket_ID is missing', 'note' => 'Note is missing'])]
public function note_create(array $data): int
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_tickets');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_tickets');
- $ticket = $this->di['db']->getExistingModelById('SupportTicket', $data['ticket_id'], 'Ticket not found');
+ $ticket = $this->getDi()['db']->getExistingModelById('SupportTicket', $data['ticket_id'], 'Ticket not found');
return $this->getService()->noteCreate($ticket, $this->getIdentity(), $data['note']);
}
@@ -640,9 +640,9 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Note ID is missing'])]
public function note_delete(array $data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_tickets');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_tickets');
- $model = $this->di['db']->getExistingModelById('SupportTicketNote', $data['id'], 'Note not found');
+ $model = $this->getDi()['db']->getExistingModelById('SupportTicketNote', $data['id'], 'Note not found');
return $this->getService()->noteRm($model);
}
@@ -655,9 +655,9 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Ticket ID is missing'])]
public function task_complete(array $data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_tickets');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_tickets');
- $model = $this->di['db']->getExistingModelById('SupportTicket', $data['id'], 'Ticket not found');
+ $model = $this->getDi()['db']->getExistingModelById('SupportTicket', $data['id'], 'Ticket not found');
return $this->getService()->ticketTaskComplete($model);
}
@@ -668,7 +668,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['ids' => 'IDs were not passed'])]
public function batch_delete($data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_tickets');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_tickets');
foreach ($data['ids'] as $id) {
$this->ticket_delete(['id' => $id]);
@@ -683,7 +683,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['ids' => 'IDs were not passed'])]
public function batch_delete_public($data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_tickets');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_tickets');
foreach ($data['ids'] as $id) {
$this->public_ticket_delete(['id' => $id]);
@@ -700,7 +700,7 @@ class Admin extends \Api_Abstract
*/
public function kb_article_get_list(array $data): array
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'view');
$status = $data['status'] ?? null;
$search = $data['search'] ?? null;
@@ -709,7 +709,7 @@ class Admin extends \Api_Abstract
$pager = $this->getService()->kbSearchArticles($status, $search, $cat, PaginationOptions::fromArray($data));
foreach ($pager['list'] as $key => $item) {
- $article = $this->di['db']->getExistingModelById('SupportKbArticle', $item['id'], 'KB Article not found');
+ $article = $this->getDi()['db']->getExistingModelById('SupportKbArticle', $item['id'], 'KB Article not found');
$pager['list'][$key] = $this->getService()->kbToApiArray($article);
}
@@ -722,9 +722,9 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Article ID was not passed'])]
public function kb_article_get(array $data): array
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'view');
- $model = $this->di['db']->findOne('SupportKbArticle', 'id = ?', [$data['id']]);
+ $model = $this->getDi()['db']->findOne('SupportKbArticle', 'id = ?', [$data['id']]);
if (!$model instanceof \Model_SupportKbArticle) {
throw new \FOSSBilling\InformationException('Article not found');
@@ -742,7 +742,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['kb_article_category_id' => 'Article category ID was not passed', 'title' => 'Article title not passed'])]
public function kb_article_create(array $data): int
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_kb');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_kb');
$articleCategoryId = (int) $data['kb_article_category_id'];
// Sanitize title and content to prevent XSS attacks
@@ -766,7 +766,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Article ID was not passed'])]
public function kb_article_update(array $data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_kb');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_kb');
$articleCategoryId = isset($data['kb_article_category_id']) ? (int) $data['kb_article_category_id'] : null;
// Sanitize title and content to prevent XSS attacks
@@ -785,9 +785,9 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Article ID was not passed'])]
public function kb_article_delete($data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_kb');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_kb');
- $model = $this->di['db']->findOne('SupportKbArticle', 'id = ?', [$data['id']]);
+ $model = $this->getDi()['db']->findOne('SupportKbArticle', 'id = ?', [$data['id']]);
if (!$model instanceof \Model_SupportKbArticle) {
throw new \FOSSBilling\InformationException('Article not found');
@@ -803,13 +803,13 @@ class Admin extends \Api_Abstract
*/
public function kb_category_get_list(array $data): array
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'view');
[$sql, $bindings] = $this->getService()->kbCategoryGetSearchQuery($data);
- $pager = $this->di['pager']->getPaginatedResultSet($sql, $bindings, PaginationOptions::fromArray($data));
+ $pager = $this->getDi()['pager']->getPaginatedResultSet($sql, $bindings, PaginationOptions::fromArray($data));
foreach ($pager['list'] as $key => $item) {
- $category = $this->di['db']->getExistingModelById('SupportKbArticleCategory', $item['id'], 'KB Article not found');
+ $category = $this->getDi()['db']->getExistingModelById('SupportKbArticleCategory', $item['id'], 'KB Article not found');
$pager['list'][$key] = $this->getService()->kbCategoryToApiArray($category, $this->getIdentity());
}
@@ -822,9 +822,9 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Category ID was not passed'])]
public function kb_category_get(array $data): array
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'view');
- $model = $this->di['db']->findOne('SupportKbArticleCategory', 'id = ?', [$data['id']]);
+ $model = $this->getDi()['db']->findOne('SupportKbArticleCategory', 'id = ?', [$data['id']]);
if (!$model instanceof \Model_SupportKbArticleCategory) {
throw new \FOSSBilling\InformationException('Article Category not found');
@@ -841,7 +841,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['title' => 'Category title not passed'])]
public function kb_category_create(array $data): int
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_kb');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_kb');
$title = $data['title'];
$description = $data['description'] ?? null;
@@ -859,9 +859,9 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Category ID was not passed'])]
public function kb_category_update(array $data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_kb');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_kb');
- $model = $this->di['db']->findOne('SupportKbArticleCategory', 'id = ?', [$data['id']]);
+ $model = $this->getDi()['db']->findOne('SupportKbArticleCategory', 'id = ?', [$data['id']]);
if (!$model instanceof \Model_SupportKbArticleCategory) {
throw new \FOSSBilling\InformationException('Article Category not found');
@@ -880,9 +880,9 @@ class Admin extends \Api_Abstract
#[RequiredParams(['id' => 'Category ID was not passed'])]
public function kb_category_delete(array $data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_kb');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'manage_kb');
- $model = $this->di['db']->findOne('SupportKbArticleCategory', 'id = ?', [$data['id']]);
+ $model = $this->getDi()['db']->findOne('SupportKbArticleCategory', 'id = ?', [$data['id']]);
if (!$model instanceof \Model_SupportKbArticleCategory) {
throw new \FOSSBilling\InformationException('Category not found');
@@ -896,7 +896,7 @@ class Admin extends \Api_Abstract
*/
public function kb_category_get_pairs(array $data): array
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('support', 'view');
return $this->getService()->kbCategoryGetPairs();
}
diff --git a/src/modules/Support/Api/Client.php b/src/modules/Support/Api/Client.php
index 478baeb9a..d8cc70ba3 100644
--- a/src/modules/Support/Api/Client.php
+++ b/src/modules/Support/Api/Client.php
@@ -34,10 +34,10 @@ class Client extends \Api_Abstract
$data['client_id'] = $identity->id;
[$sql, $bindings] = $this->getService()->getSearchQuery($data);
- $pager = $this->di['pager']->getPaginatedResultSet($sql, $bindings, PaginationOptions::fromArray($data));
+ $pager = $this->getDi()['pager']->getPaginatedResultSet($sql, $bindings, PaginationOptions::fromArray($data));
foreach ($pager['list'] as $key => $ticketArr) {
- $ticket = $this->di['db']->getExistingModelById('SupportTicket', $ticketArr['id'], 'Ticket not found');
+ $ticket = $this->getDi()['db']->getExistingModelById('SupportTicket', $ticketArr['id'], 'Ticket not found');
$pager['list'][$key] = $this->getService()->toApiArray($ticket, true, $this->getIdentity());
}
@@ -85,7 +85,7 @@ class Client extends \Api_Abstract
// Sanitize content to prevent XSS attacks
$data['content'] = \FOSSBilling\Tools::sanitizeContent($data['content'], true);
- $helpdesk = $this->di['db']->getExistingModelById('SupportHelpdesk', $data['support_helpdesk_id'], 'Helpdesk invalid');
+ $helpdesk = $this->getDi()['db']->getExistingModelById('SupportHelpdesk', $data['support_helpdesk_id'], 'Helpdesk invalid');
$client = $this->getIdentity();
@@ -107,7 +107,7 @@ class Client extends \Api_Abstract
':id' => $data['id'],
':client_id' => $client->id,
];
- $ticket = $this->di['db']->findOne('SupportTicket', 'id = :id AND client_id = :client_id', $bindings);
+ $ticket = $this->getDi()['db']->findOne('SupportTicket', 'id = :id AND client_id = :client_id', $bindings);
if (!$ticket instanceof \Model_SupportTicket) {
throw new \FOSSBilling\InformationException('Ticket not found');
diff --git a/src/modules/Support/Api/Guest.php b/src/modules/Support/Api/Guest.php
index 47d98bcf7..b860ccdb9 100644
--- a/src/modules/Support/Api/Guest.php
+++ b/src/modules/Support/Api/Guest.php
@@ -34,7 +34,7 @@ class Guest extends \Api_Abstract
])]
public function ticket_create(array $data): string
{
- $this->di['rate_limiter']->consumeOrThrow('guest_ticket_create', (string) $this->getIp());
+ $this->getDi()['rate_limiter']->consumeOrThrow('guest_ticket_create', (string) $this->getIp());
if (!is_string($data['message']) || strlen($data['message']) < 4) {
throw new \FOSSBilling\InformationException('Please enter your message');
@@ -121,7 +121,7 @@ class Guest extends \Api_Abstract
$pager = $this->getService()->kbSearchArticles('active', $search, $cat, PaginationOptions::fromArray($data));
foreach ($pager['list'] as $key => $item) {
- $article = $this->di['db']->getExistingModelById('SupportKbArticle', $item['id'], 'KB Article not found');
+ $article = $this->getDi()['db']->getExistingModelById('SupportKbArticle', $item['id'], 'KB Article not found');
$pager['list'][$key] = $this->getService()->kbToApiArray($article);
}
@@ -163,12 +163,12 @@ class Guest extends \Api_Abstract
$data['article_status'] = \Model_SupportKbArticle::ACTIVE;
[$query, $bindings] = $this->getService()->kbCategoryGetSearchQuery($data);
- $pager = $this->di['pager']->getPaginatedResultSet($query, $bindings, PaginationOptions::fromArray($data));
+ $pager = $this->getDi()['pager']->getPaginatedResultSet($query, $bindings, PaginationOptions::fromArray($data));
$q = $data['q'] ?? null;
foreach ($pager['list'] as $key => $item) {
- $category = $this->di['db']->getExistingModelById('SupportKbArticleCategory', $item['id'], 'KB Article not found');
+ $category = $this->getDi()['db']->getExistingModelById('SupportKbArticleCategory', $item['id'], 'KB Article not found');
$pager['list'][$key] = $this->getService()->kbCategoryToApiArray($category, $this->getIdentity(), $q);
}
diff --git a/src/modules/Support/tests/Unit/Api/AdminTest.php b/src/modules/Support/tests/Unit/Api/AdminTest.php
new file mode 100644
index 000000000..0a8de6d5c
--- /dev/null
+++ b/src/modules/Support/tests/Unit/Api/AdminTest.php
@@ -0,0 +1,1690 @@
+ [
+ ['id' => 1],
+ ],
+ ];
+ $paginatorMock = Mockery::mock(FOSSBilling\Pagination::class)->makePartial();
+ $paginatorMock
+ ->shouldReceive('getPaginatedResultSet')
+ ->atLeast()->once()
+ ->andReturn($simpleResultArr);
+
+ $serviceMock = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $serviceMock->shouldReceive('getSearchQuery')->atLeast()->once()
+ ->andReturn(['query', []]);
+ $serviceMock
+ ->shouldReceive('toApiArray')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $model = new Model_SupportTicket();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $di = container();
+ $di['pager'] = $paginatorMock;
+ $di['db'] = $dbMock;
+
+ $api->setDi($di);
+
+ $api->setService($serviceMock);
+
+ $data = [];
+ $result = $api->ticket_get_list($data);
+
+ expect($result)->toBeArray();
+});
+
+test('ticket get', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn(new Model_SupportTicket());
+
+ $serviceMock = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $serviceMock->shouldReceive('toApiArray')->atLeast()->once()
+ ->andReturn([]);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $api->setDi($di);
+
+ $api->setService($serviceMock);
+
+ $data = [
+ 'id' => 1,
+ ];
+ $result = $api->ticket_get($data);
+
+ expect($result)->toBeArray();
+});
+
+test('ticket update', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn(new Model_SupportTicket());
+
+ $serviceMock = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $serviceMock->shouldReceive('ticketUpdate')->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $api->setDi($di);
+
+ $api->setService($serviceMock);
+
+ $data = [
+ 'id' => 1,
+ ];
+ $result = $api->ticket_update($data);
+
+ expect($result)->toBeTrue();
+});
+
+test('ticket message update', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn(new Model_SupportTicketMessage());
+
+ $serviceMock = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $serviceMock->shouldReceive('ticketMessageUpdate')->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $api->setDi($di);
+
+ $api->setService($serviceMock);
+
+ $data = [
+ 'id' => 1,
+ 'content' => 'Content',
+ ];
+ $result = $api->ticket_message_update($data);
+
+ expect($result)->toBeTrue();
+});
+
+test('ticket delete', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn(new Model_SupportTicket());
+
+ $serviceMock = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $serviceMock->shouldReceive('rm')->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $api->setDi($di);
+
+ $api->setService($serviceMock);
+
+ $data = [
+ 'id' => 1,
+ ];
+ $result = $api->ticket_delete($data);
+
+ expect($result)->toBeTrue();
+});
+
+test('ticket reply', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn(new Model_SupportTicket());
+
+ $serviceMock = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $serviceMock->shouldReceive('ticketReply')->atLeast()->once()
+ ->andReturn(1);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $api->setDi($di);
+
+ $api->setService($serviceMock);
+ $api->setIdentity(new Model_Admin());
+
+ $data = [
+ 'id' => 1,
+ 'content' => 'Content',
+ ];
+ $result = $api->ticket_reply($data);
+
+ expect($result)->toBeInt();
+});
+
+test('ticket close', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $ticket = new Model_SupportTicket();
+ $ticket->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($ticket);
+
+ $serviceMock = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $serviceMock->shouldReceive('closeTicket')->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $api->setDi($di);
+
+ $api->setService($serviceMock);
+ $api->setIdentity(new Model_Admin());
+
+ $data = [
+ 'id' => 1,
+ ];
+ $result = $api->ticket_close($data);
+
+ expect($result)->toBeTrue();
+});
+
+test('ticket close already closed', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $ticket = new Model_SupportTicket();
+ $ticket->loadBean(new Tests\Helpers\DummyBean());
+ $ticket->status = Model_SupportTicket::CLOSED;
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($ticket);
+
+ $serviceMock = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $serviceMock->shouldReceive('closeTicket')
+ ;
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $api->setDi($di);
+
+ $api->setService($serviceMock);
+
+ $data = [
+ 'id' => 1,
+ ];
+ $result = $api->ticket_close($data);
+
+ expect($result)->toBeTrue();
+});
+
+test('ticket create', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $clientModel = new Model_Client();
+ $clientModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $supportHelpdeskModel = new Model_SupportHelpdesk();
+ $supportHelpdeskModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($clientModel, $supportHelpdeskModel);
+
+ $randID = 1;
+ $serviceMock = Mockery::mock(Box\Mod\Support\Service::class);
+ $serviceMock->shouldReceive('ticketCreateForAdmin')->atLeast()->once()
+ ->andReturn($randID);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $api->setDi($di);
+
+ $api->setService($serviceMock);
+ $api->setIdentity(new Model_Admin());
+
+ $data = [
+ 'client_id' => 1,
+ 'content' => 'Content',
+ 'subject' => 'Subject',
+ 'support_helpdesk_id' => 1,
+ ];
+ $result = $api->ticket_create($data);
+
+ expect($result)->toBeInt();
+ expect($result)->toEqual($randID);
+});
+
+test('batch ticket auto close', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $serviceMock = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $serviceMock->shouldReceive('getExpired')->atLeast()->once()
+ ->andReturn([['id' => 1], ['id' => 2]]);
+ $serviceMock->shouldReceive('autoClose')->atLeast()->once()
+ ->andReturn(true);
+
+ $ticket = new Model_SupportTicket();
+ $ticket->loadBean(new Tests\Helpers\DummyBean());
+ $ticket->id = 1;
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($ticket);
+
+ $api->setService($serviceMock);
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = $this->createStub('\Box_Log');
+ $api->setDi($di);
+ $api->setService($serviceMock);
+
+ $result = $api->batch_ticket_auto_close([]);
+
+ expect($result)->toBeTrue();
+});
+
+test('batch ticket auto close not closed', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $ticket = new Model_SupportTicket();
+ $ticket->loadBean(new Tests\Helpers\DummyBean());
+ $ticket->id = 1;
+
+ $serviceMock = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $serviceMock->shouldReceive('getExpired')->atLeast()->once()
+ ->andReturn([['id' => 1], ['id' => 2]]);
+ $serviceMock->shouldReceive('autoClose')->atLeast()->once()
+ ;
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($ticket);
+
+ $api->setService($serviceMock);
+ $di = container();
+ $di['logger'] = $this->createStub('\Box_Log');
+ $di['db'] = $dbMock;
+ $api->setDi($di);
+ $result = $api->batch_ticket_auto_close([]);
+
+ expect($result)->toBeTrue();
+});
+
+test('batch public ticket auto close', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $serviceMock = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $serviceMock->shouldReceive('publicGetExpired')->atLeast()->once()
+ ->andReturn([new Model_SupportPTicket(), new Model_SupportPTicket()]);
+ $serviceMock->shouldReceive('publicAutoClose')->atLeast()->once()
+ ->andReturn(true);
+
+ $api->setService($serviceMock);
+
+ $result = $api->batch_public_ticket_auto_close([]);
+
+ expect($result)->toBeTrue();
+});
+
+test('batch public ticket auto close not closed', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $ticket = new Model_SupportPTicket();
+ $ticket->loadBean(new Tests\Helpers\DummyBean());
+ $ticket->id = 1;
+
+ $serviceMock = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $serviceMock->shouldReceive('publicGetExpired')->atLeast()->once()
+ ->andReturn([$ticket, $ticket]);
+ $serviceMock->shouldReceive('publicAutoClose')->atLeast()->once()
+ ;
+
+ $api->setService($serviceMock);
+ $di = container();
+ $di['logger'] = $this->createStub('\Box_Log');
+ $api->setDi($di);
+ $result = $api->batch_public_ticket_auto_close([]);
+
+ expect($result)->toBeTrue();
+});
+
+test('ticket get statuses', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $statuses = [
+ Model_SupportPTicket::OPENED => 'Open',
+ Model_SupportPTicket::ONHOLD => 'On hold',
+ Model_SupportPTicket::CLOSED => 'Closed',
+ ];
+ $serviceMock = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $serviceMock->shouldReceive('getStatuses')
+ ->andReturn($statuses);
+ $serviceMock->shouldReceive('counter')->atLeast()->once()
+ ->andReturn($statuses);
+
+ $api->setService($serviceMock);
+
+ $result = $api->ticket_get_statuses([]);
+
+ expect($result)->toEqual($statuses);
+});
+
+test('ticket get statuses titles set', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $statuses = [
+ Model_SupportPTicket::OPENED => 'Open',
+ Model_SupportPTicket::ONHOLD => 'On hold',
+ Model_SupportPTicket::CLOSED => 'Closed',
+ ];
+ $serviceMock = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $serviceMock->shouldReceive('getStatuses')->atLeast()->once()
+ ->andReturn($statuses);
+ $serviceMock->shouldReceive('counter')
+ ->andReturn($statuses);
+
+ $api->setService($serviceMock);
+
+ $data = [
+ 'titles' => true,
+ ];
+ $result = $api->ticket_get_statuses($data);
+
+ expect($result)->toEqual($statuses);
+});
+
+test('public ticket get list', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $resultSet = [
+ 'list' => [
+ 0 => ['id' => 1],
+ ],
+ ];
+ $paginatorMock = Mockery::mock(FOSSBilling\Pagination::class)->makePartial();
+ $paginatorMock
+ ->shouldReceive('getPaginatedResultSet')
+ ->atLeast()->once()
+ ->andReturn($resultSet);
+
+ $serviceMock = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $serviceMock->shouldReceive('publicGetSearchQuery')->atLeast()->once()
+ ->andReturn(['query', []]);
+ $serviceMock->shouldReceive('publicToApiArray')->atLeast()->once()
+ ->andReturn(['query', []]);
+
+ $model = new Model_SupportPTicket();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock = Mockery::mock('\Box_DAtabase');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $di = container();
+ $di['pager'] = $paginatorMock;
+ $di['db'] = $dbMock;
+
+ $api->setDi($di);
+
+ $api->setService($serviceMock);
+
+ $data = [];
+ $result = $api->public_ticket_get_list($data);
+
+ expect($result)->toBeArray();
+});
+
+test('public ticket create', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $randID = 1;
+ $serviceMock = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $serviceMock->shouldReceive('publicTicketCreate')->atLeast()->once()
+ ->andReturn($randID);
+
+ $di = container();
+ $api->setDi($di);
+
+ $api->setService($serviceMock);
+ $api->setIdentity(new Model_Admin());
+
+ $data = [
+ 'name' => 'Name',
+ 'email' => 'email@example.com',
+ 'subject' => 'Subject',
+ 'message' => 'Message',
+ ];
+
+ $result = $api->public_ticket_create($data);
+
+ expect($result)->toBeInt();
+ expect($result)->toEqual($randID);
+});
+
+test('public ticket get', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn(new Model_SupportPTicket());
+
+ $randID = 1;
+ $serviceMock = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $serviceMock->shouldReceive('publicToApiArray')->atLeast()->once()
+ ->andReturn([]);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $api->setDi($di);
+
+ $api->setService($serviceMock);
+
+ $data = [
+ 'id' => 1,
+ ];
+ $result = $api->public_ticket_get($data);
+
+ expect($result)->toBeArray();
+});
+
+test('public ticket delete', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn(new Model_SupportPTicket());
+
+ $serviceMock = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $serviceMock->shouldReceive('publicRm')->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $api->setDi($di);
+
+ $api->setService($serviceMock);
+
+ $data = [
+ 'id' => 1,
+ ];
+ $result = $api->public_ticket_delete($data);
+
+ expect($result)->toBeTrue();
+});
+
+test('public ticket close', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn(new Model_SupportPTicket());
+
+ $serviceMock = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $serviceMock->shouldReceive('publicCloseTicket')->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $api->setDi($di);
+
+ $api->setService($serviceMock);
+ $api->setIdentity(new Model_Admin());
+
+ $data = [
+ 'id' => 1,
+ ];
+ $result = $api->public_ticket_close($data);
+
+ expect($result)->toBeTrue();
+});
+
+test('public ticket update', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn(new Model_SupportPTicket());
+
+ $serviceMock = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $serviceMock->shouldReceive('publicTicketUpdate')->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $api->setDi($di);
+
+ $api->setService($serviceMock);
+ $api->setIdentity(new Model_Admin());
+
+ $data = [
+ 'id' => 1,
+ ];
+ $result = $api->public_ticket_update($data);
+
+ expect($result)->toBeTrue();
+});
+
+test('public ticket reply', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn(new Model_SupportPTicket());
+
+ $serviceMock = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $serviceMock->shouldReceive('publicTicketReply')->atLeast()->once()
+ ->andReturn(1);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $api->setDi($di);
+
+ $api->setService($serviceMock);
+ $api->setIdentity(new Model_Admin());
+
+ $data = [
+ 'id' => 1,
+ 'content' => 'Content',
+ ];
+ $result = $api->public_ticket_reply($data);
+
+ expect($result)->toBeInt();
+});
+
+test('public ticket get statuses', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $statuses = [
+ Model_SupportPTicket::OPENED => 'Open',
+ Model_SupportPTicket::ONHOLD => 'On hold',
+ Model_SupportPTicket::CLOSED => 'Closed',
+ ];
+ $serviceMock = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $serviceMock->shouldReceive('publicGetStatuses')
+ ->andReturn($statuses);
+ $serviceMock->shouldReceive('publicCounter')->atLeast()->once()
+ ->andReturn($statuses);
+
+ $api->setService($serviceMock);
+
+ $result = $api->public_ticket_get_statuses([]);
+
+ expect($result)->toEqual($statuses);
+});
+
+test('public ticket get statuses titles set', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $statuses = [
+ Model_SupportPTicket::OPENED => 'Open',
+ Model_SupportPTicket::ONHOLD => 'On hold',
+ Model_SupportPTicket::CLOSED => 'Closed',
+ ];
+ $serviceMock = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $serviceMock->shouldReceive('publicGetStatuses')->atLeast()->once()
+ ->andReturn($statuses);
+ $serviceMock->shouldReceive('publicCounter')
+ ->andReturn($statuses);
+
+ $api->setService($serviceMock);
+
+ $data = [
+ 'titles' => true,
+ ];
+ $result = $api->public_ticket_get_statuses($data);
+
+ expect($result)->toEqual($statuses);
+});
+
+test('helpdesk get list', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $paginatorMock = Mockery::mock(FOSSBilling\Pagination::class)->makePartial();
+ $paginatorMock
+ ->shouldReceive('getPaginatedResultSet')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $serviceMock = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $serviceMock->shouldReceive('helpdeskGetSearchQuery')->atLeast()->once()
+ ->andReturn(['query', []]);
+
+ $di = container();
+ $di['pager'] = $paginatorMock;
+
+ $api->setDi($di);
+
+ $api->setService($serviceMock);
+
+ $data = [];
+ $result = $api->helpdesk_get_list($data);
+
+ expect($result)->toBeArray();
+});
+
+test('helpdesk get pairs', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $serviceMock = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $serviceMock->shouldReceive('helpdeskGetPairs')->atLeast()->once()
+ ->andReturn([]);
+
+ $api->setService($serviceMock);
+
+ $data = [];
+ $result = $api->helpdesk_get_pairs($data);
+
+ expect($result)->toBeArray();
+});
+
+test('helpdesk get', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn(new Model_SupportHelpdesk());
+
+ $serviceMock = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $serviceMock->shouldReceive('helpdeskToApiArray')->atLeast()->once()
+ ->andReturn([]);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $api->setDi($di);
+
+ $api->setService($serviceMock);
+ $api->setIdentity(new Model_Admin());
+
+ $data = [
+ 'id' => 1,
+ ];
+ $result = $api->helpdesk_get($data);
+
+ expect($result)->toBeArray();
+});
+
+test('helpdesk update', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn(new Model_SupportHelpdesk());
+
+ $serviceMock = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $serviceMock->shouldReceive('helpdeskUpdate')->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $api->setDi($di);
+
+ $api->setService($serviceMock);
+ $api->setIdentity(new Model_Admin());
+
+ $data = [
+ 'id' => 1,
+ ];
+ $result = $api->helpdesk_update($data);
+
+ expect($result)->toBeTrue();
+});
+
+test('helpdesk create', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $serviceMock = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $serviceMock->shouldReceive('helpdeskCreate')->atLeast()->once()
+ ->andReturn(1);
+
+ $di = container();
+ $api->setDi($di);
+
+ $api->setService($serviceMock);
+ $api->setIdentity(new Model_Admin());
+
+ $data = [
+ 'id' => 1,
+ ];
+ $result = $api->helpdesk_create($data);
+
+ expect($result)->toBeInt();
+});
+
+test('helpdesk delete', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn(new Model_SupportHelpdesk());
+
+ $serviceMock = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $serviceMock->shouldReceive('helpdeskRm')->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $api->setDi($di);
+
+ $api->setService($serviceMock);
+ $api->setIdentity(new Model_Admin());
+
+ $data = [
+ 'id' => 'General',
+ ];
+ $result = $api->helpdesk_delete($data);
+
+ expect($result)->toBeTrue();
+});
+
+test('canned get list', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $resultSet = [
+ 'list' => [
+ 0 => ['id' => 1],
+ ],
+ ];
+ $paginatorMock = Mockery::mock(FOSSBilling\Pagination::class)->makePartial();
+ $paginatorMock
+ ->shouldReceive('getPaginatedResultSet')
+ ->atLeast()->once()
+ ->andReturn($resultSet);
+
+ $serviceMock = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $serviceMock->shouldReceive('cannedGetSearchQuery')->atLeast()->once()
+ ->andReturn(['query', []]);
+ $serviceMock->shouldReceive('cannedToApiArray')->atLeast()->once()
+ ->andReturn([]);
+
+ $model = new Model_SupportPr();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock = Mockery::mock('\Box_DAtabase');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $di = container();
+ $di['pager'] = $paginatorMock;
+ $di['db'] = $dbMock;
+
+ $api->setDi($di);
+
+ $api->setService($serviceMock);
+
+ $data = [];
+ $result = $api->canned_get_list($data);
+
+ expect($result)->toBeArray();
+});
+
+test('canned pairs', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getAssoc')
+ ->atLeast()->once()
+ ->andReturn([1 => 'Title']);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $api->setDi($di);
+
+ $data = [];
+ $result = $api->canned_pairs();
+
+ expect($result)->toBeArray();
+});
+
+test('canned get', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn(new Model_SupportPr());
+
+ $serviceMock = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $serviceMock->shouldReceive('cannedToApiArray')->atLeast()->once()
+ ->andReturn([]);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $api->setDi($di);
+
+ $api->setService($serviceMock);
+ $api->setIdentity(new Model_Admin());
+
+ $data = [
+ 'id' => 1,
+ ];
+ $result = $api->canned_get($data);
+
+ expect($result)->toBeArray();
+});
+
+test('canned delete', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn(new Model_SupportPr());
+
+ $serviceMock = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $serviceMock->shouldReceive('cannedRm')->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $api->setDi($di);
+
+ $api->setService($serviceMock);
+ $api->setIdentity(new Model_Admin());
+
+ $data = [
+ 'id' => 1,
+ ];
+ $result = $api->canned_delete($data);
+
+ expect($result)->toBeTrue();
+});
+
+test('canned create', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $serviceMock = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $serviceMock->shouldReceive('cannedCreate')->atLeast()->once()
+ ->andReturn(1);
+
+ $di = container();
+ $api->setDi($di);
+
+ $api->setService($serviceMock);
+ $api->setIdentity(new Model_Admin());
+
+ $data = [
+ 'title' => 'Title',
+ 'category_id' => random_int(1, 100),
+ 'content' => 'Content',
+ ];
+ $result = $api->canned_create($data);
+
+ expect($result)->toBeInt();
+});
+
+test('canned update', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $serviceMock = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $serviceMock->shouldReceive('cannedUpdate')->atLeast()->once()
+ ->andReturn(true);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn(new Model_SupportPr());
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $api->setDi($di);
+
+ $api->setService($serviceMock);
+ $api->setIdentity(new Model_Admin());
+
+ $data = [
+ 'id' => 'Title',
+ ];
+ $result = $api->canned_update($data);
+
+ expect($result)->toBeTrue();
+});
+
+test('canned category pairs', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getAssoc')
+ ->atLeast()->once()
+ ->andReturn([1 => 'Category 1']);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $api->setDi($di);
+
+ $api->setIdentity(new Model_Admin());
+
+ $data = [
+ 'id' => 'Title',
+ ];
+ $result = $api->canned_category_pairs($data);
+
+ expect($result)->toBeArray();
+});
+
+test('canned category get', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn(new Model_SupportPrCategory());
+
+ $serviceMock = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $serviceMock->shouldReceive('cannedCategoryToApiArray')->atLeast()->once()
+ ->andReturn([]);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $api->setDi($di);
+
+ $api->setService($serviceMock);
+ $api->setIdentity(new Model_Admin());
+
+ $data = [
+ 'id' => 1,
+ ];
+ $result = $api->canned_category_get($data);
+
+ expect($result)->toBeArray();
+});
+
+test('canned category update', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $supportCategory = new Model_SupportPrCategory();
+ $supportCategory->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($supportCategory);
+
+ $serviceMock = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $serviceMock->shouldReceive('cannedCategoryUpdate')->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $api->setDi($di);
+
+ $api->setService($serviceMock);
+ $api->setIdentity(new Model_Admin());
+
+ $data = [
+ 'id' => 1,
+ 'title' => 'Updated Title',
+ ];
+ $result = $api->canned_category_update($data);
+
+ expect($result)->toBeTrue();
+});
+
+test('canned category delete', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $supportCategory = new Model_SupportPrCategory();
+ $supportCategory->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($supportCategory);
+
+ $serviceMock = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $serviceMock->shouldReceive('cannedCategoryRm')->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $api->setDi($di);
+
+ $api->setService($serviceMock);
+ $api->setIdentity(new Model_Admin());
+
+ $data = [
+ 'id' => 1,
+ ];
+ $result = $api->canned_category_delete($data);
+
+ expect($result)->toBeTrue();
+});
+
+test('canned category create', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $serviceMock = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $serviceMock->shouldReceive('cannedCategoryCreate')->atLeast()->once()
+ ->andReturn(1);
+
+ $di = container();
+ $api->setDi($di);
+
+ $api->setService($serviceMock);
+
+ $data = [
+ 'title' => 'Title',
+ ];
+ $result = $api->canned_category_create($data);
+
+ expect($result)->toBeInt();
+});
+
+test('note create', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $serviceMock = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $serviceMock->shouldReceive('noteCreate')->atLeast()->once()
+ ->andReturn(1);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn(new Model_SupportTicket());
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $api->setDi($di);
+
+ $api->setService($serviceMock);
+ $api->setIdentity(new Model_Admin());
+
+ $data = [
+ 'ticket_id' => 1,
+ 'note' => 'Note',
+ ];
+ $result = $api->note_create($data);
+
+ expect($result)->toBeInt();
+});
+
+test('note delete', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $serviceMock = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $serviceMock->shouldReceive('noteRm')->atLeast()->once()
+ ->andReturn(true);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn(new Model_SupportTicketNote());
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $api->setDi($di);
+
+ $api->setService($serviceMock);
+ $api->setIdentity(new Model_Admin());
+
+ $data = [
+ 'id' => 1,
+ ];
+ $result = $api->note_delete($data);
+
+ expect($result)->toBeTrue();
+});
+
+test('task complete', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $serviceMock = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $serviceMock->shouldReceive('ticketTaskComplete')->atLeast()->once()
+ ->andReturn(true);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn(new Model_SupportTicket());
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $api->setDi($di);
+
+ $api->setService($serviceMock);
+
+ $data = [
+ 'id' => 1,
+ ];
+ $result = $api->task_complete($data);
+
+ expect($result)->toBeTrue();
+});
+
+test('batch delete', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $activityMock = Mockery::mock(Box\Mod\Support\Api\Admin::class)->makePartial();
+ $activityMock->shouldReceive('ticket_delete')->atLeast()->once()->andReturn(true);
+
+ $di = container();
+ $activityMock->setDi($di);
+
+ $result = $activityMock->batch_delete(['ids' => [1, 2, 3]]);
+ expect($result)->toBeTrue();
+});
+
+test('batch delete public', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $activityMock = Mockery::mock(Box\Mod\Support\Api\Admin::class)->makePartial();
+ $activityMock->shouldReceive('public_ticket_delete')->atLeast()->once()->andReturn(true);
+
+ $di = container();
+ $activityMock->setDi($di);
+
+ $result = $activityMock->batch_delete_public(['ids' => [1, 2, 3]]);
+ expect($result)->toBeTrue();
+});
+
+/*
+* Knowledge Base Tests.
+*/
+
+test('kb article get list', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $di = container();
+
+ $adminApi = new Box\Mod\Support\Api\Admin();
+ $adminApi->setDi($di);
+
+ $data = [
+ 'status' => 'status',
+ 'search' => 'search',
+ 'cat' => 'category',
+ ];
+
+ $kbService = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $kbService
+ ->shouldReceive('kbSearchArticles')
+ ->atLeast()->once()
+ ->andReturn(['list' => []]);
+
+ $adminApi->setService($kbService);
+
+ $result = $adminApi->kb_article_get_list($data);
+ expect($result)->toBeArray();
+});
+
+test('kb article get', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $adminApi = new Box\Mod\Support\Api\Admin();
+
+ $data = [
+ 'id' => 1,
+ ];
+
+ $db = Mockery::mock('Box_Database');
+ $db
+ ->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn(new Model_SupportKbArticle());
+
+ $admin = new Model_Admin();
+ $admin->loadBean(new Tests\Helpers\DummyBean());
+
+ $admin->id = 5;
+
+ $di = container();
+ $di['loggedin_admin'] = $admin;
+ $di['db'] = $db;
+
+ $adminApi->setDi($di);
+
+ $kbService = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $kbService
+ ->shouldReceive('kbToApiArray')
+ ->atLeast()->once()
+ ->andReturn([]);
+ $adminApi->setService($kbService);
+
+ $result = $adminApi->kb_article_get($data);
+ expect($result)->toBeArray();
+});
+
+test('kb article get not found exception', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $adminApi = new Box\Mod\Support\Api\Admin();
+
+ $data = [
+ 'id' => 1,
+ ];
+
+ $db = Mockery::mock('Box_Database');
+ $db
+ ->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn(false);
+
+ $di = container();
+ $di['db'] = $db;
+
+ $adminApi->setDi($di);
+ expect(fn (): array => $adminApi->kb_article_get($data))->toThrow(FOSSBilling\Exception::class);
+});
+
+test('kb article create', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $adminApi = new Box\Mod\Support\Api\Admin();
+
+ $data = [
+ 'kb_article_category_id' => 1,
+ 'title' => 'Title',
+ ];
+
+ $id = 1;
+
+ $di = container();
+
+ $kbService = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $kbService
+ ->shouldReceive('kbCreateArticle')
+ ->atLeast()->once()
+ ->andReturn($id);
+ $adminApi->setService($kbService);
+
+ $adminApi->setDi($di);
+
+ $result = $adminApi->kb_article_create($data);
+ expect($result)->toBeInt();
+ expect($result)->toEqual($id);
+});
+
+test('kb article update', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $adminApi = new Box\Mod\Support\Api\Admin();
+
+ $data = [
+ 'id' => 1,
+ 'kb_article_category_id' => 1,
+ 'title' => 'Title',
+ 'slug' => 'article-slug',
+ 'status' => 'active',
+ 'content' => 'Content',
+ 'views' => 1,
+ ];
+
+ $kbService = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $kbService
+ ->shouldReceive('kbUpdateArticle')
+ ->atLeast()->once()
+ ->andReturn(true);
+ $di = container();
+
+ $adminApi->setDi($di);
+
+ $adminApi->setService($kbService);
+
+ $result = $adminApi->kb_article_update($data);
+ expect($result)->toBeTrue();
+});
+
+test('kb article delete', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $adminApi = new Box\Mod\Support\Api\Admin();
+
+ $data = [
+ 'id' => 1,
+ ];
+
+ $db = Mockery::mock('Box_Database');
+ $db
+ ->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn(new Model_SupportKbArticle());
+
+ $di = container();
+ $di['db'] = $db;
+
+ $adminApi->setDi($di);
+
+ $kbService = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $kbService->shouldReceive('kbRm')->atLeast()->once();
+ $adminApi->setService($kbService);
+
+ $result = $adminApi->kb_article_delete($data);
+ expect($result)->toBeTrue();
+});
+
+test('kb article delete not found exception', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $adminApi = new Box\Mod\Support\Api\Admin();
+
+ $db = Mockery::mock('Box_Database');
+ $db
+ ->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn(false);
+
+ $di = container();
+ $di['db'] = $db;
+
+ $adminApi->setDi($di);
+
+ $kbService = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $kbService->shouldReceive('kbRm')->never()
+ ;
+ $adminApi->setService($kbService);
+
+ expect(fn (): bool => $adminApi->kb_article_delete(['id' => 1]))->toThrow(FOSSBilling\Exception::class);
+});
+
+test('kb category get list', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $adminApi = new Box\Mod\Support\Api\Admin();
+
+ $willReturn = [
+ 'pages' => 5,
+ 'page' => 2,
+ 'per_page' => 2,
+ 'total' => 10,
+ 'list' => [],
+ ];
+
+ $kbService = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $kbService
+ ->shouldReceive('kbCategoryGetSearchQuery')
+ ->atLeast()->once()
+ ->andReturn(['String', []]);
+
+ $pager = Mockery::mock(FOSSBilling\Pagination::class)->makePartial();
+
+ $pager
+ ->shouldReceive('getPaginatedResultSet')
+ ->atLeast()->once()
+ ->andReturn($willReturn);
+
+ $di = container();
+ $di['pager'] = $pager;
+
+ $adminApi->setDi($di);
+ $adminApi->setService($kbService);
+
+ $result = $adminApi->kb_category_get_list([]);
+ expect($result)->toBeArray();
+ expect($result)->toEqual($willReturn);
+});
+
+test('kb category get', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $adminApi = new Box\Mod\Support\Api\Admin();
+
+ $db = Mockery::mock('Box_Database');
+ $db
+ ->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn(new Model_SupportKbArticleCategory());
+
+ $di = container();
+ $di['db'] = $db;
+ $di['validator'] = new FOSSBilling\Validate();
+
+ $adminApi->setDi($di);
+
+ $kbService = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $kbService
+ ->shouldReceive('kbCategoryToApiArray')
+ ->atLeast()->once()
+ ->andReturn([]);
+ $adminApi->setService($kbService);
+
+ $data = [
+ 'id' => 1,
+ ];
+ $result = $adminApi->kb_category_get($data);
+ expect($result)->toBeArray();
+});
+
+test('kb category get id not set exception', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $adminApi = new Box\Mod\Support\Api\Admin();
+
+ $apiHandler = new Api_Handler(new Model_Admin());
+ $reflection = new ReflectionClass($apiHandler);
+ $method = $reflection->getMethod('validateRequiredParams');
+
+ expect(fn (): mixed => $method->invokeArgs($apiHandler, [$adminApi, 'kb_category_get', []]))
+ ->toThrow(FOSSBilling\InformationException::class);
+});
+
+test('kb category get not found exception', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $adminApi = new Box\Mod\Support\Api\Admin();
+
+ $db = Mockery::mock('Box_Database');
+ $db
+ ->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn(false);
+
+ $di = container();
+
+ $di['db'] = $db;
+ $di['validator'] = new FOSSBilling\Validate();
+ $adminApi->setDi($di);
+
+ $kbService = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $kbService->shouldReceive('kbCategoryToApiArray')->never()
+ ->andReturn([]);
+ $adminApi->setService($kbService);
+
+ $data = [
+ 'id' => 1,
+ ];
+
+ expect(fn (): array => $adminApi->kb_category_get($data))->toThrow(FOSSBilling\Exception::class);
+});
+
+test('kb category create', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $adminApi = new Box\Mod\Support\Api\Admin();
+
+ $kbService = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $kbService
+ ->shouldReceive('kbCreateCategory')
+ ->atLeast()->once()
+ ->andReturn(1);
+ $adminApi->setService($kbService);
+
+ $data = [
+ 'title' => 'Title',
+ 'description' => 'Description',
+ ];
+
+ $di = container();
+
+ $adminApi->setDi($di);
+
+ $result = $adminApi->kb_category_create($data);
+ expect($result)->toBeInt();
+});
+
+test('kb category update', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $adminApi = new Box\Mod\Support\Api\Admin();
+
+ $kbService = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $kbService
+ ->shouldReceive('kbUpdateCategory')
+ ->atLeast()->once()
+ ->andReturn(true);
+ $adminApi->setService($kbService);
+
+ $db = Mockery::mock('Box_Database');
+ $db
+ ->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn(new Model_SupportKbArticleCategory());
+
+ $di = container();
+ $di['db'] = $db;
+ $di['validator'] = new FOSSBilling\Validate();
+
+ $adminApi->setDi($di);
+
+ $data = [
+ 'id' => 1,
+ 'title' => 'Title',
+ 'slug' => 'category-slug',
+ 'description' => 'Description',
+ ];
+
+ $result = $adminApi->kb_category_update($data);
+ expect($result)->toBeTrue();
+});
+
+test('kb category update id not set', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $adminApi = new Box\Mod\Support\Api\Admin();
+
+ $apiHandler = new Api_Handler(new Model_Admin());
+ $reflection = new ReflectionClass($apiHandler);
+ $method = $reflection->getMethod('validateRequiredParams');
+
+ expect(fn (): mixed => $method->invokeArgs($apiHandler, [$adminApi, 'kb_category_update', []]))
+ ->toThrow(FOSSBilling\InformationException::class);
+});
+
+test('kb category update not found', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $adminApi = new Box\Mod\Support\Api\Admin();
+
+ $kbService = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $kbService->shouldReceive('kbUpdateCategory')->never()
+ ->andReturn(true);
+ $adminApi->setService($kbService);
+
+ $db = Mockery::mock('Box_Database');
+ $db
+ ->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn(false);
+
+ $di = container();
+ $di['db'] = $db;
+ $di['validator'] = new FOSSBilling\Validate();
+
+ $adminApi->setDi($di);
+
+ $data = [
+ 'id' => 1,
+ 'title' => 'Title',
+ 'slug' => 'category-slug',
+ 'description' => 'Description',
+ ];
+
+ expect(fn (): bool => $adminApi->kb_category_update($data))->toThrow(FOSSBilling\Exception::class);
+});
+
+test('kb category delete', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $adminApi = new Box\Mod\Support\Api\Admin();
+
+ $kbService = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $kbService
+ ->shouldReceive('kbCategoryRm')
+ ->atLeast()->once()
+ ->andReturn(true);
+ $adminApi->setService($kbService);
+
+ $db = Mockery::mock('Box_Database');
+ $db
+ ->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn(new Model_SupportKbArticleCategory());
+
+ $di = container();
+ $di['db'] = $db;
+ $di['validator'] = new FOSSBilling\Validate();
+
+ $adminApi->setDi($di);
+
+ $data = [
+ 'id' => 1,
+ ];
+ $result = $adminApi->kb_category_delete($data);
+ expect($result)->toBeTrue();
+});
+
+test('kb category delete id not set', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $adminApi = new Box\Mod\Support\Api\Admin();
+
+ $apiHandler = new Api_Handler(new Model_Admin());
+ $reflection = new ReflectionClass($apiHandler);
+ $method = $reflection->getMethod('validateRequiredParams');
+
+ expect(fn (): mixed => $method->invokeArgs($apiHandler, [$adminApi, 'kb_category_delete', []]))
+ ->toThrow(FOSSBilling\InformationException::class);
+});
+
+test('kb category delete not found', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $adminApi = new Box\Mod\Support\Api\Admin();
+
+ $kbService = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $kbService->shouldReceive('kbCategoryRm')->never()
+ ->andReturn(true);
+ $adminApi->setService($kbService);
+
+ $db = Mockery::mock('Box_Database');
+ $db
+ ->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn(false);
+
+ $di = container();
+ $di['db'] = $db;
+ $di['validator'] = new FOSSBilling\Validate();
+
+ $adminApi->setDi($di);
+
+ $data = [
+ 'id' => 1,
+ ];
+
+ expect(fn (): bool => $adminApi->kb_category_delete($data))->toThrow(FOSSBilling\Exception::class);
+});
+
+test('kb category get pairs', function (): void {
+ $api = new Box\Mod\Support\Api\Admin();
+ $adminApi = new Box\Mod\Support\Api\Admin();
+
+ $kbService = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $kbService
+ ->shouldReceive('kbCategoryGetPairs')
+ ->atLeast()->once()
+ ->andReturn([]);
+ $adminApi->setService($kbService);
+
+ $result = $adminApi->kb_category_get_pairs([]);
+ expect($result)->toBeArray();
+});
diff --git a/src/modules/Support/tests/Unit/Api/ClientTest.php b/src/modules/Support/tests/Unit/Api/ClientTest.php
new file mode 100644
index 000000000..7b25180d2
--- /dev/null
+++ b/src/modules/Support/tests/Unit/Api/ClientTest.php
@@ -0,0 +1,229 @@
+ [
+ ['id' => 1],
+ ],
+ ];
+ $paginatorMock = Mockery::mock(FOSSBilling\Pagination::class)->makePartial();
+ $paginatorMock
+ ->shouldReceive('getPaginatedResultSet')
+ ->atLeast()->once()
+ ->andReturn($simpleResultArr);
+
+ $serviceMock = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $serviceMock->shouldReceive('getSearchQuery')->atLeast()->once()
+ ->andReturn(['query', []]);
+ $serviceMock
+ ->shouldReceive('toApiArray')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $model = new Model_SupportTicket();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $di = container();
+ $di['pager'] = $paginatorMock;
+ $di['db'] = $dbMock;
+
+ $clientApi->setDi($di);
+
+ $client = new Model_Client();
+ $client->loadBean(new Tests\Helpers\DummyBean());
+ $client->id = 1;
+
+ $clientApi->setService($serviceMock);
+ $clientApi->setIdentity($client);
+
+ $data = [];
+ $result = $clientApi->ticket_get_list($data);
+
+ expect($result)->toBeArray();
+});
+
+test('ticket get', function (): void {
+ $clientApi = new Box\Mod\Support\Api\Client();
+ $serviceMock = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $serviceMock->shouldReceive('findOneByClient')->atLeast()->once()
+ ->andReturn(new Model_SupportTicket());
+ $serviceMock->shouldReceive('toApiArray')->atLeast()->once()
+ ->andReturn([]);
+
+ $di = container();
+ $clientApi->setDi($di);
+
+ $client = new Model_Client();
+ $client->loadBean(new Tests\Helpers\DummyBean());
+ $client->id = 1;
+
+ $clientApi->setService($serviceMock);
+ $clientApi->setIdentity($client);
+
+ $data = [
+ 'id' => 1,
+ ];
+ $result = $clientApi->ticket_get($data);
+
+ expect($result)->toBeArray();
+});
+
+test('helpdesk get pairs', function (): void {
+ $clientApi = new Box\Mod\Support\Api\Client();
+ $serviceMock = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $serviceMock->shouldReceive('helpdeskGetPairs')->atLeast()->once()
+ ->andReturn([0 => 'General']);
+
+ $clientApi->setService($serviceMock);
+
+ $result = $clientApi->helpdesk_get_pairs();
+
+ expect($result)->toBeArray();
+});
+
+test('ticket create', function (): void {
+ $clientApi = new Box\Mod\Support\Api\Client();
+ $serviceMock = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $serviceMock->shouldReceive('ticketCreateForClient')->atLeast()->once()
+ ->andReturn(1);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn(new Model_SupportHelpdesk());
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $clientApi->setDi($di);
+
+ $client = new Model_Client();
+ $client->loadBean(new Tests\Helpers\DummyBean());
+ $client->id = 1;
+
+ $clientApi->setService($serviceMock);
+ $clientApi->setIdentity($client);
+
+ $data = [
+ 'content' => 'Content',
+ 'subject' => 'Subject',
+ 'support_helpdesk_id' => 1,
+ ];
+ $result = $clientApi->ticket_create($data);
+
+ expect($result)->toBeInt();
+});
+
+test('ticket reply', function (): void {
+ $clientApi = new Box\Mod\Support\Api\Client();
+ $serviceMock = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $serviceMock->shouldReceive('canBeReopened')->atLeast()->once()
+ ->andReturn(true);
+ $serviceMock->shouldReceive('ticketReply')->atLeast()->once()
+ ->andReturn(1);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn(new Model_SupportTicket());
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $clientApi->setDi($di);
+
+ $client = new Model_Client();
+ $client->loadBean(new Tests\Helpers\DummyBean());
+ $client->id = 1;
+
+ $clientApi->setService($serviceMock);
+ $clientApi->setIdentity($client);
+
+ $data = [
+ 'content' => 'Content',
+ 'id' => 1,
+ ];
+ $result = $clientApi->ticket_reply($data);
+
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+});
+
+test('ticket reply can not be reopened exception', function (): void {
+ $clientApi = new Box\Mod\Support\Api\Client();
+ $serviceMock = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $serviceMock->shouldReceive('canBeReopened')->atLeast()->once()
+ ->andReturn(false);
+ $serviceMock->shouldReceive('ticketReply')
+ ->andReturn(1);
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock
+ ->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn(new Model_SupportTicket());
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $clientApi->setDi($di);
+
+ $client = new Model_Client();
+ $client->loadBean(new Tests\Helpers\DummyBean());
+ $client->id = 1;
+
+ $clientApi->setService($serviceMock);
+ $clientApi->setIdentity($client);
+
+ $data = [
+ 'content' => 'Content',
+ 'id' => 1,
+ ];
+ expect(fn (): bool => $clientApi->ticket_reply($data))->toThrow(FOSSBilling\Exception::class);
+});
+
+test('ticket close', function (): void {
+ $clientApi = new Box\Mod\Support\Api\Client();
+ $serviceMock = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $serviceMock->shouldReceive('findOneByClient')->atLeast()->once()
+ ->andReturn(new Model_SupportTicket());
+ $serviceMock->shouldReceive('closeTicket')->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+ $clientApi->setDi($di);
+
+ $client = new Model_Client();
+ $client->loadBean(new Tests\Helpers\DummyBean());
+ $client->id = 1;
+
+ $clientApi->setService($serviceMock);
+ $clientApi->setIdentity($client);
+
+ $data = [
+ 'content' => 'Content',
+ 'id' => 1,
+ ];
+ $result = $clientApi->ticket_close($data);
+
+ expect($result)->toBeTrue();
+});
diff --git a/src/modules/Support/tests/Unit/Api/GuestTest.php b/src/modules/Support/tests/Unit/Api/GuestTest.php
new file mode 100644
index 000000000..d965bb686
--- /dev/null
+++ b/src/modules/Support/tests/Unit/Api/GuestTest.php
@@ -0,0 +1,453 @@
+makePartial();
+ $serviceMock->shouldReceive('ticketCreateForGuest')->atLeast()->once()
+ ->andReturn(bin2hex(random_bytes(random_int(100, 127))));
+
+ $di = container();
+ $guestApi->setDi($di);
+
+ $guestApi->setService($serviceMock);
+
+ $data = [
+ 'name' => 'Name',
+ 'email' => 'email@wxample.com',
+ 'subject' => 'Subject',
+ 'message' => 'Message',
+ ];
+ $result = $guestApi->ticket_create($data);
+
+ expect($result)->toBeString();
+ expect(strlen($result))->toBeGreaterThan(0);
+});
+
+test('ticket create message too short exception', function (): void {
+ $guestApi = new Box\Mod\Support\Api\Guest();
+ $serviceMock = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $serviceMock->shouldReceive('ticketCreateForGuest')
+ ->andReturn(sha1(uniqid()));
+
+ $di = container();
+ $guestApi->setDi($di);
+
+ $guestApi->setService($serviceMock);
+
+ $data = [
+ 'name' => 'Name',
+ 'email' => 'email@wxample.com',
+ 'subject' => 'Subject',
+ 'message' => '',
+ ];
+
+ expect(fn (): string => $guestApi->ticket_create($data))->toThrow(FOSSBilling\Exception::class);
+});
+
+test('ticket get', function (): void {
+ $guestApi = new Box\Mod\Support\Api\Guest();
+ $serviceMock = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $serviceMock->shouldReceive('publicFindOneByHash')->atLeast()->once()
+ ->andReturn(new Model_SupportPTicket());
+ $serviceMock->shouldReceive('publicToApiArray')->atLeast()->once()
+ ->andReturn([]);
+
+ $di = container();
+ $guestApi->setDi($di);
+
+ $guestApi->setService($serviceMock);
+
+ $data = [
+ 'hash' => sha1(uniqid()),
+ ];
+ $result = $guestApi->ticket_get($data);
+
+ expect($result)->toBeArray();
+});
+
+test('ticket close', function (): void {
+ $guestApi = new Box\Mod\Support\Api\Guest();
+ $serviceMock = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $serviceMock->shouldReceive('publicFindOneByHash')->atLeast()->once()
+ ->andReturn(new Model_SupportPTicket());
+ $serviceMock->shouldReceive('publicCloseTicket')->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+ $guestApi->setDi($di);
+
+ $guestApi->setService($serviceMock);
+ $guestApi->setIdentity(new Model_Guest());
+
+ $data = [
+ 'hash' => sha1(uniqid()),
+ ];
+ $result = $guestApi->ticket_close($data);
+
+ expect($result)->toBeTrue();
+});
+
+test('ticket reply', function (): void {
+ $guestApi = new Box\Mod\Support\Api\Guest();
+ $serviceMock = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $serviceMock->shouldReceive('publicFindOneByHash')->atLeast()->once()
+ ->andReturn(new Model_SupportPTicket());
+ $serviceMock->shouldReceive('publicTicketReplyForGuest')->atLeast()->once()
+ ->andReturn(sha1(uniqid()));
+
+ $di = container();
+ $guestApi->setDi($di);
+
+ $guestApi->setService($serviceMock);
+
+ $data = [
+ 'hash' => sha1(uniqid()),
+ 'message' => 'Message',
+ ];
+ $result = $guestApi->ticket_reply($data);
+
+ expect($result)->toBeString();
+ expect(strlen($result))->toEqual(40);
+});
+
+/*
+* Knowledge Base Tests.
+*/
+
+test('kb article get list', function (): void {
+ $guestApi = new Box\Mod\Support\Api\Guest();
+
+ $willReturn = [
+ 'pages' => 5,
+ 'page' => 2,
+ 'per_page' => 2,
+ 'total' => 10,
+ 'list' => [],
+ ];
+
+ $supportService = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $supportService
+ ->shouldReceive('kbSearchArticles')
+ ->atLeast()->once()
+ ->andReturn($willReturn);
+ $guestApi->setService($supportService);
+
+ $di = container();
+
+ $guestApi->setDi($di);
+ $result = $guestApi->kb_article_get_list([]);
+ expect($result)->toBeArray();
+ expect($result)->toEqual($willReturn);
+});
+
+test('kb article get with id', function (): void {
+ $guestApi = new Box\Mod\Support\Api\Guest();
+
+ $di = container();
+
+ $guestApi->setDi($di);
+
+ $supportService = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $supportService
+ ->shouldReceive('kbFindActiveArticleById')
+ ->atLeast()->once()
+ ->andReturn(new Model_SupportKbArticle());
+ $supportService->shouldReceive('kbFindActiveArticleBySlug')->never()
+ ->andReturn(new Model_SupportKbArticle());
+ $supportService->shouldReceive('kbHitView')->atLeast()->once();
+ $supportService
+ ->shouldReceive('kbToApiArray')
+ ->atLeast()->once()
+ ->andReturn([]);
+ $guestApi->setService($supportService);
+
+ $data = [
+ 'id' => 1,
+ ];
+ $result = $guestApi->kb_article_get($data);
+ expect($result)->toBeArray();
+});
+
+test('kb article get with slug', function (): void {
+ $guestApi = new Box\Mod\Support\Api\Guest();
+
+ $di = container();
+
+ $guestApi->setDi($di);
+
+ $supportService = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $supportService->shouldReceive('kbFindActiveArticleById')->never()
+ ->andReturn(new Model_SupportKbArticle());
+ $supportService
+ ->shouldReceive('kbFindActiveArticleBySlug')
+ ->atLeast()->once()
+ ->andReturn(new Model_SupportKbArticle());
+ $supportService->shouldReceive('kbHitView')->atLeast()->once();
+ $supportService
+ ->shouldReceive('kbToApiArray')
+ ->atLeast()->once()
+ ->andReturn([]);
+ $guestApi->setService($supportService);
+
+ $data = [
+ 'slug' => 'article-slug',
+ ];
+ $result = $guestApi->kb_article_get($data);
+ expect($result)->toBeArray();
+});
+
+test('kb article get id and slug not set exception', function (): void {
+ $guestApi = new Box\Mod\Support\Api\Guest();
+
+ $kbService = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $kbService->shouldReceive('kbFindActiveArticleById')->never()
+ ->andReturn(new Model_SupportKbArticle());
+ $kbService->shouldReceive('kbFindActiveArticleBySlug')->never()
+ ->andReturn(new Model_SupportKbArticle());
+ $kbService->shouldReceive('kbHitView')->never()
+ ;
+ $kbService->shouldReceive('kbToApiArray')->never()
+ ->andReturn([]);
+ $guestApi->setService($kbService);
+
+ expect(fn (): array => $guestApi->kb_article_get([]))->toThrow(FOSSBilling\Exception::class);
+});
+
+test('kb article get not found by id', function (): void {
+ $guestApi = new Box\Mod\Support\Api\Guest();
+
+ $kbService = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $kbService
+ ->shouldReceive('kbFindActiveArticleById')
+ ->atLeast()->once()
+ ->andReturn(null);
+ $kbService->shouldReceive('kbFindActiveArticleBySlug')->never()
+ ->andReturn(new Model_SupportKbArticle());
+ $kbService->shouldReceive('kbHitView')->never()
+ ;
+ $kbService->shouldReceive('kbToApiArray')->never()
+ ->andReturn([]);
+ $guestApi->setService($kbService);
+
+ $data = [
+ 'id' => 1,
+ ];
+
+ $di = container();
+
+ $guestApi->setDi($di);
+ expect(fn (): array => $guestApi->kb_article_get($data))->toThrow(FOSSBilling\Exception::class);
+});
+
+test('kb article get not found by slug', function (): void {
+ $guestApi = new Box\Mod\Support\Api\Guest();
+
+ $kbService = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $kbService->shouldReceive('kbFindActiveArticleById')->never()
+ ->andReturn(new Model_SupportKbArticle());
+ $kbService
+ ->shouldReceive('kbFindActiveArticleBySlug')
+ ->atLeast()->once()
+ ->andReturn(null);
+ $kbService->shouldReceive('kbHitView')->never()
+ ;
+ $kbService->shouldReceive('kbToApiArray')->never()
+ ->andReturn([]);
+ $guestApi->setService($kbService);
+
+ $data = [
+ 'slug' => 'article-slug',
+ ];
+
+ $di = container();
+
+ $guestApi->setDi($di);
+
+ expect(fn (): array => $guestApi->kb_article_get($data))->toThrow(FOSSBilling\Exception::class);
+});
+
+test('kb category get list', function (): void {
+ $guestApi = new Box\Mod\Support\Api\Guest();
+
+ $willReturn = [
+ 'pages' => 5,
+ 'page' => 2,
+ 'per_page' => 2,
+ 'total' => 10,
+ 'list' => [],
+ ];
+
+ $kbService = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $kbService
+ ->shouldReceive('kbCategoryGetSearchQuery')
+ ->atLeast()->once()
+ ->andReturn(['String', []]);
+
+ $pager = Mockery::mock(FOSSBilling\Pagination::class)->makePartial();
+
+ $pager
+ ->shouldReceive('getPaginatedResultSet')
+ ->atLeast()->once()
+ ->andReturn($willReturn);
+
+ $di = container();
+ $di['pager'] = $pager;
+
+ $guestApi->setDi($di);
+ $guestApi->setService($kbService);
+
+ $result = $guestApi->kb_category_get_list([]);
+ expect($result)->toBeArray();
+ expect($result)->toEqual($willReturn);
+});
+
+test('kb category get pairs', function (): void {
+ $guestApi = new Box\Mod\Support\Api\Guest();
+
+ $expected = [
+ 1 => 'First Category',
+ 2 => 'Second Category',
+ ];
+
+ $kbService = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $kbService
+ ->shouldReceive('kbCategoryGetPairs')
+ ->atLeast()->once()
+ ->andReturn($expected);
+ $guestApi->setService($kbService);
+
+ $result = $guestApi->kb_category_get_pairs([]);
+ expect($result)->toBeArray();
+ expect($result)->toEqual($expected);
+});
+
+test('kb category get with id', function (): void {
+ $guestApi = new Box\Mod\Support\Api\Guest();
+
+ $kbService = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $kbService
+ ->shouldReceive('kbFindCategoryById')
+ ->atLeast()->once()
+ ->andReturn(new Model_SupportKbArticleCategory());
+ $kbService->shouldReceive('kbFindCategoryBySlug')->never()
+ ->andReturn(new Model_SupportKbArticleCategory());
+ $kbService
+ ->shouldReceive('kbCategoryToApiArray')
+ ->atLeast()->once()
+ ->andReturn([]);
+ $guestApi->setService($kbService);
+
+ $data = [
+ 'id' => 1,
+ ];
+
+ $di = container();
+
+ $guestApi->setDi($di);
+ $result = $guestApi->kb_category_get($data);
+ expect($result)->toBeArray();
+});
+
+test('kb category get with slug', function (): void {
+ $guestApi = new Box\Mod\Support\Api\Guest();
+
+ $kbService = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $kbService->shouldReceive('kbFindCategoryById')->never()
+ ->andReturn(new Model_SupportKbArticleCategory());
+ $kbService
+ ->shouldReceive('kbFindCategoryBySlug')
+ ->atLeast()->once()
+ ->andReturn(new Model_SupportKbArticleCategory());
+ $kbService
+ ->shouldReceive('kbCategoryToApiArray')
+ ->atLeast()->once()
+ ->andReturn([]);
+ $guestApi->setService($kbService);
+
+ $di = container();
+
+ $guestApi->setDi($di);
+
+ $data = [
+ 'slug' => 'category-slug',
+ ];
+ $result = $guestApi->kb_category_get($data);
+ expect($result)->toBeArray();
+});
+
+test('kb category get id and slug not set exception', function (): void {
+ $guestApi = new Box\Mod\Support\Api\Guest();
+
+ $kbService = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $kbService->shouldReceive('kbFindCategoryById')->never()
+ ->andReturn(new Model_SupportKbArticleCategory());
+ $kbService->shouldReceive('kbFindCategoryBySlug')->never()
+ ->andReturn(new Model_SupportKbArticleCategory());
+ $kbService->shouldReceive('kbCategoryToApiArray')->never()
+ ->andReturn([]);
+ $guestApi->setService($kbService);
+
+ expect(fn (): array => $guestApi->kb_category_get([]))->toThrow(FOSSBilling\Exception::class);
+});
+
+test('kb category get not found by id', function (): void {
+ $guestApi = new Box\Mod\Support\Api\Guest();
+
+ $kbService = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $kbService
+ ->shouldReceive('kbFindCategoryById')
+ ->andThrow(new FOSSBilling\Exception('Knowledge Base category not found'));
+ $kbService->shouldReceive('kbFindCategoryBySlug')->never()
+ ->andReturn(new Model_SupportKbArticleCategory());
+ $kbService->shouldReceive('kbCategoryToApiArray')->never()
+ ->andReturn([]);
+ $guestApi->setService($kbService);
+
+ $data = [
+ 'id' => 1,
+ ];
+
+ $di = container();
+
+ $guestApi->setDi($di);
+
+ expect(fn (): array => $guestApi->kb_category_get($data))->toThrow(FOSSBilling\Exception::class);
+});
+
+test('kb category get not found by slug', function (): void {
+ $guestApi = new Box\Mod\Support\Api\Guest();
+
+ $kbService = Mockery::mock(Box\Mod\Support\Service::class)->makePartial();
+ $kbService->shouldReceive('kbFindCategoryById')->never()
+ ->andReturn(new Model_SupportKbArticleCategory());
+ $kbService
+ ->shouldReceive('kbFindCategoryBySlug')
+ ->atLeast()->once()
+ ->andReturn(null);
+ $kbService->shouldReceive('kbCategoryToApiArray')->never()
+ ->andReturn([]);
+ $guestApi->setService($kbService);
+
+ $data = [
+ 'slug' => 'article-slug',
+ ];
+
+ $di = container();
+
+ $guestApi->setDi($di);
+
+ expect(fn (): array => $guestApi->kb_category_get($data))->toThrow(FOSSBilling\Exception::class);
+});
diff --git a/src/modules/Support/tests/Unit/ServiceTest.php b/src/modules/Support/tests/Unit/ServiceTest.php
new file mode 100644
index 000000000..dad6c964a
--- /dev/null
+++ b/src/modules/Support/tests/Unit/ServiceTest.php
@@ -0,0 +1,3006 @@
+loadBean(new Tests\Helpers\DummyBean());
+ $client->id = 1;
+ $client->first_name = 'Client';
+ $client->last_name = 'Name';
+
+ return $client;
+}
+
+/*
+ * Dependency Injection Tests
+ */
+
+test('gets and sets dependency injection container', function (): void {
+ $service = new Service();
+ $di = container();
+ $service->setDi($di);
+ $getDi = $service->getDi();
+ expect($getDi)->toBe($di);
+});
+
+/*
+ * Event Handler Tests
+ */
+
+test('handles after client open ticket event', function (): void {
+ $service = new Service();
+ $toApiArrayReturn = [
+ 'client' => [
+ 'id' => 1,
+ ],
+ ];
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+ $supportTicketModel = new Model_SupportTicket();
+ $supportTicketModel->loadBean(new Tests\Helpers\DummyBean());
+ $serviceMock->shouldReceive('getTicketById')
+ ->atLeast()->once()
+ ->andReturn($supportTicketModel);
+ $serviceMock->shouldReceive('toApiArray')
+ ->atLeast()->once()
+ ->andReturn($toApiArrayReturn);
+
+ $emailServiceMock = Mockery::mock(EmailService::class);
+ $emailServiceMock->shouldReceive('sendTemplate')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(function ($serviceName) use ($emailServiceMock, $serviceMock) {
+ if ($serviceName == 'email') {
+ return $emailServiceMock;
+ }
+ if ($serviceName == 'support') {
+ return $serviceMock;
+ }
+ });
+ $di['loggedin_client'] = new Model_Client();
+ $serviceMock->setDi($di);
+
+ $eventMock = Mockery::mock('\Box_Event');
+ $eventMock->shouldReceive('getDi')
+ ->atLeast()->once()
+ ->andReturn($di);
+ $eventMock->shouldReceive('getParameters')
+ ->atLeast()->once()
+ ->andReturn(['id' => random_int(1, 100)]);
+
+ $result = $serviceMock->onAfterClientOpenTicket($eventMock);
+ expect($result)->toBeNull();
+});
+
+test('handles after admin open ticket event', function (): void {
+ $service = new Service();
+ $toApiArrayReturn = [
+ 'client' => [
+ 'id' => 1,
+ ],
+ ];
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+ $supportTicketModel = new Model_SupportTicket();
+ $supportTicketModel->loadBean(new Tests\Helpers\DummyBean());
+ $serviceMock->shouldReceive('getTicketById')
+ ->atLeast()->once()
+ ->andReturn($supportTicketModel);
+ $serviceMock->shouldReceive('toApiArray')
+ ->atLeast()->once()
+ ->andReturn($toApiArrayReturn);
+
+ $emailServiceMock = Mockery::mock(EmailService::class);
+ $emailServiceMock->shouldReceive('sendTemplate')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(function ($serviceName) use ($emailServiceMock, $serviceMock) {
+ if ($serviceName == 'email') {
+ return $emailServiceMock;
+ }
+ if ($serviceName == 'support') {
+ return $serviceMock;
+ }
+ });
+ $di['loggedin_admin'] = new Model_Admin();
+ $serviceMock->setDi($di);
+
+ $eventMock = Mockery::mock('\Box_Event');
+ $eventMock->shouldReceive('getDi')
+ ->atLeast()->once()
+ ->andReturn($di);
+ $eventMock->shouldReceive('getParameters')
+ ->atLeast()->once()
+ ->andReturn(['id' => random_int(1, 100)]);
+
+ $result = $serviceMock->onAfterAdminOpenTicket($eventMock);
+ expect($result)->toBeNull();
+});
+
+test('handles after admin close ticket event', function (): void {
+ $service = new Service();
+ $toApiArrayReturn = [
+ 'client' => [
+ 'id' => 1,
+ ],
+ ];
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+ $supportTicketModel = new Model_SupportTicket();
+ $supportTicketModel->loadBean(new Tests\Helpers\DummyBean());
+ $serviceMock->shouldReceive('getTicketById')
+ ->atLeast()->once()
+ ->andReturn($supportTicketModel);
+ $serviceMock->shouldReceive('toApiArray')
+ ->atLeast()->once()
+ ->andReturn($toApiArrayReturn);
+
+ $emailServiceMock = Mockery::mock(EmailService::class);
+ $emailServiceMock->shouldReceive('sendTemplate')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(function ($serviceName) use ($emailServiceMock, $serviceMock) {
+ if ($serviceName == 'email') {
+ return $emailServiceMock;
+ }
+ if ($serviceName == 'support') {
+ return $serviceMock;
+ }
+ });
+ $di['loggedin_admin'] = new Model_Admin();
+ $serviceMock->setDi($di);
+
+ $eventMock = Mockery::mock('\Box_Event');
+ $eventMock->shouldReceive('getDi')
+ ->atLeast()->once()
+ ->andReturn($di);
+ $eventMock->shouldReceive('getParameters')
+ ->atLeast()->once()
+ ->andReturn(['id' => random_int(1, 100)]);
+
+ $result = $serviceMock->onAfterAdminCloseTicket($eventMock);
+ expect($result)->toBeNull();
+});
+
+test('handles after admin reply ticket event', function (): void {
+ $service = new Service();
+ $toApiArrayReturn = [
+ 'client' => [
+ 'id' => 1,
+ ],
+ ];
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+ $supportTicketModel = new Model_SupportTicket();
+ $supportTicketModel->loadBean(new Tests\Helpers\DummyBean());
+ $serviceMock->shouldReceive('getTicketById')
+ ->atLeast()->once()
+ ->andReturn($supportTicketModel);
+ $serviceMock->shouldReceive('toApiArray')
+ ->atLeast()->once()
+ ->andReturn($toApiArrayReturn);
+
+ $emailServiceMock = Mockery::mock(EmailService::class);
+ $emailServiceMock->shouldReceive('sendTemplate')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(function ($serviceName) use ($emailServiceMock, $serviceMock) {
+ if ($serviceName == 'email') {
+ return $emailServiceMock;
+ }
+ if ($serviceName == 'support') {
+ return $serviceMock;
+ }
+ });
+ $di['loggedin_admin'] = new Model_Admin();
+ $serviceMock->setDi($di);
+
+ $eventMock = Mockery::mock('\Box_Event');
+ $eventMock->shouldReceive('getDi')
+ ->atLeast()->once()
+ ->andReturn($di);
+ $eventMock->shouldReceive('getParameters')
+ ->atLeast()->once()
+ ->andReturn(['id' => random_int(1, 100)]);
+
+ $result = $serviceMock->onAfterAdminReplyTicket($eventMock);
+ expect($result)->toBeNull();
+});
+
+test('handles after guest public ticket open event', function (): void {
+ $service = new Service();
+ $toApiArrayReturn = [
+ 'author_email' => 'email@example.com',
+ 'author_name' => 'Name',
+ ];
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+ $supportPTicketModel = new Model_SupportPTicket();
+ $supportPTicketModel->loadBean(new Tests\Helpers\DummyBean());
+ $serviceMock->shouldReceive('getPublicTicketById')
+ ->atLeast()->once()
+ ->andReturn($supportPTicketModel);
+ $serviceMock->shouldReceive('publicToApiArray')
+ ->atLeast()->once()
+ ->andReturn($toApiArrayReturn);
+
+ $emailServiceMock = Mockery::mock(EmailService::class);
+ $emailServiceMock->shouldReceive('sendTemplate')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(function ($serviceName) use ($emailServiceMock, $serviceMock) {
+ if ($serviceName == 'email') {
+ return $emailServiceMock;
+ }
+ if ($serviceName == 'support') {
+ return $serviceMock;
+ }
+ });
+ $serviceMock->setDi($di);
+
+ $eventMock = Mockery::mock('\Box_Event');
+ $eventMock->shouldReceive('getDi')
+ ->atLeast()->once()
+ ->andReturn($di);
+ $eventMock->shouldReceive('getParameters')
+ ->atLeast()->once()
+ ->andReturn(['id' => random_int(1, 100)]);
+
+ $result = $serviceMock->onAfterGuestPublicTicketOpen($eventMock);
+ expect($result)->toBeNull();
+});
+
+test('handles after admin public ticket open event', function (): void {
+ $service = new Service();
+ $toApiArrayReturn = [
+ 'author_email' => 'email@example.com',
+ 'author_name' => 'Name',
+ ];
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+ $supportPTicketModel = new Model_SupportPTicket();
+ $supportPTicketModel->loadBean(new Tests\Helpers\DummyBean());
+ $serviceMock->shouldReceive('getPublicTicketById')
+ ->atLeast()->once()
+ ->andReturn($supportPTicketModel);
+ $serviceMock->shouldReceive('publicToApiArray')
+ ->atLeast()->once()
+ ->andReturn($toApiArrayReturn);
+
+ $emailServiceMock = Mockery::mock(EmailService::class);
+ $emailServiceMock->shouldReceive('sendTemplate')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(function ($serviceName) use ($emailServiceMock, $serviceMock) {
+ if ($serviceName == 'email') {
+ return $emailServiceMock;
+ }
+ if ($serviceName == 'support') {
+ return $serviceMock;
+ }
+ });
+ $di['loggedin_admin'] = new Model_Admin();
+ $serviceMock->setDi($di);
+
+ $eventMock = Mockery::mock('\Box_Event');
+ $eventMock->shouldReceive('getDi')
+ ->atLeast()->once()
+ ->andReturn($di);
+ $eventMock->shouldReceive('getParameters')
+ ->atLeast()->once()
+ ->andReturn(['id' => random_int(1, 100)]);
+
+ $result = $serviceMock->onAfterAdminPublicTicketOpen($eventMock);
+ expect($result)->toBeNull();
+});
+
+test('handles after admin public ticket reply event', function (): void {
+ $service = new Service();
+ $toApiArrayReturn = [
+ 'author_email' => 'email@example.com',
+ 'author_name' => 'Name',
+ ];
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+ $supportPTicketModel = new Model_SupportPTicket();
+ $supportPTicketModel->loadBean(new Tests\Helpers\DummyBean());
+ $serviceMock->shouldReceive('getPublicTicketById')
+ ->atLeast()->once()
+ ->andReturn($supportPTicketModel);
+ $serviceMock->shouldReceive('publicToApiArray')
+ ->atLeast()->once()
+ ->andReturn($toApiArrayReturn);
+
+ $emailServiceMock = Mockery::mock(EmailService::class);
+ $emailServiceMock->shouldReceive('sendTemplate')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(function ($serviceName) use ($emailServiceMock, $serviceMock) {
+ if ($serviceName == 'email') {
+ return $emailServiceMock;
+ }
+ if ($serviceName == 'support') {
+ return $serviceMock;
+ }
+ });
+ $di['loggedin_admin'] = new Model_Admin();
+ $serviceMock->setDi($di);
+
+ $eventMock = Mockery::mock('\Box_Event');
+ $eventMock->shouldReceive('getDi')
+ ->atLeast()->once()
+ ->andReturn($di);
+ $eventMock->shouldReceive('getParameters')
+ ->atLeast()->once()
+ ->andReturn(['id' => random_int(1, 100)]);
+
+ $result = $serviceMock->onAfterAdminPublicTicketReply($eventMock);
+ expect($result)->toBeNull();
+});
+
+test('handles after admin public ticket close event', function (): void {
+ $service = new Service();
+ $toApiArrayReturn = [
+ 'author_email' => 'email@example.com',
+ 'author_name' => 'Name',
+ ];
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+ $supportPTicketModel = new Model_SupportPTicket();
+ $supportPTicketModel->loadBean(new Tests\Helpers\DummyBean());
+ $serviceMock->shouldReceive('getPublicTicketById')
+ ->atLeast()->once()
+ ->andReturn($supportPTicketModel);
+ $serviceMock->shouldReceive('publicToApiArray')
+ ->atLeast()->once()
+ ->andReturn($toApiArrayReturn);
+
+ $emailServiceMock = Mockery::mock(EmailService::class);
+ $emailServiceMock->shouldReceive('sendTemplate')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(function ($serviceName) use ($emailServiceMock, $serviceMock) {
+ if ($serviceName == 'email') {
+ return $emailServiceMock;
+ }
+ if ($serviceName == 'support') {
+ return $serviceMock;
+ }
+ });
+ $di['loggedin_admin'] = new Model_Admin();
+ $serviceMock->setDi($di);
+
+ $eventMock = Mockery::mock('\Box_Event');
+ $eventMock->shouldReceive('getDi')
+ ->atLeast()->once()
+ ->andReturn($di);
+ $eventMock->shouldReceive('getParameters')
+ ->atLeast()->once()
+ ->andReturn(['id' => random_int(1, 100)]);
+
+ $result = $serviceMock->onAfterAdminPublicTicketClose($eventMock);
+ expect($result)->toBeNull();
+});
+
+/*
+ * Ticket Tests
+ */
+
+test('gets ticket by id', function (): void {
+ $service = new Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn(new Model_SupportTicket());
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $result = $service->getTicketById(1);
+ expect($result)->toBeInstanceOf(Model_SupportTicket::class);
+});
+
+test('gets public ticket by id', function (): void {
+ $service = new Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $supportPTicketModel = new Model_SupportPTicket();
+ $supportPTicketModel->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($supportPTicketModel);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $result = $service->getPublicTicketById(1);
+ expect($result)->toBeInstanceOf(Model_SupportPTicket::class);
+});
+
+test('gets statuses', function (): void {
+ $service = new Service();
+ $result = $service->getStatuses();
+ expect($result)->toBeArray();
+});
+
+test('finds one by client', function (): void {
+ $service = new Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $supportTicketModel = new Model_SupportTicket();
+ $supportTicketModel->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn($supportTicketModel);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $client = new Model_Client();
+ $client->loadBean(new Tests\Helpers\DummyBean());
+ $client->id = 1;
+
+ $result = $service->findOneByClient($client, 1);
+ expect($result)->toBeInstanceOf(Model_SupportTicket::class);
+});
+
+test('throws exception when ticket not found by client', function (): void {
+ $service = new Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn(null);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $client = new Model_Client();
+ $client->loadBean(new Tests\Helpers\DummyBean());
+ $client->id = 1;
+
+ $service->findOneByClient($client, 1);
+})->throws(FOSSBilling\Exception::class);
+
+dataset('searchQueryData', [
+ [
+ [
+ 'search' => 'query',
+ 'id' => 1,
+ 'status' => 'open',
+ 'client_id' => 1,
+ 'client' => 'Client name',
+ 'order_id' => 1,
+ 'subject' => 'subject',
+ 'content' => 'Content',
+ 'support_helpdesk_id' => 1,
+ 'created_at' => date('Y-m-d H:i:s'),
+ 'date_from' => date('Y-m-d H:i:s'),
+ 'date_to' => date('Y-m-d H:i:s'),
+ 'priority' => 1,
+ ],
+ ],
+ [
+ [
+ 'search' => 1,
+ 'id' => 1,
+ 'status' => 'open',
+ 'client_id' => 1,
+ 'client' => 'Client name',
+ 'order_id' => 1,
+ 'subject' => 'subject',
+ 'content' => 'Content',
+ 'support_helpdesk_id' => 1,
+ 'created_at' => date('Y-m-d H:i:s'),
+ 'date_from' => date('Y-m-d H:i:s'),
+ 'date_to' => date('Y-m-d H:i:s'),
+ 'priority' => 1,
+ ],
+ ],
+]);
+
+test('gets search query', function ($data): void {
+ $service = new Service();
+ $di = container();
+ $service->setDi($di);
+ [$query, $bindings] = $service->getSearchQuery($data);
+ expect($query)->toBeString();
+ expect($bindings)->toBeArray();
+})->with('searchQueryData');
+
+test('counts tickets', function (): void {
+ $service = new Service();
+ $arr = [
+ Model_SupportTicket::OPENED => 1,
+ Model_SupportTicket::ONHOLD => 1,
+ Model_SupportTicket::CLOSED => 1,
+ ];
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getAssoc')
+ ->atLeast()->once()
+ ->andReturn($arr);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $result = $service->counter();
+ expect($result)->toBeArray();
+ expect($result)->toHaveKey('total');
+ expect($result['total'])->toBe(array_sum($arr));
+});
+
+test('gets latest tickets', function (): void {
+ $service = new Service();
+ $ticket = new Model_SupportTicket();
+ $ticket->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('find')
+ ->atLeast()->once()
+ ->andReturn([$ticket, $ticket]);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $result = $service->getLatest();
+ expect($result)->toBeArray();
+ expect($result[0])->toBeInstanceOf(Model_SupportTicket::class);
+});
+
+test('gets expired tickets', function (): void {
+ $service = new Service();
+ $ticket = new Model_SupportTicket();
+ $ticket->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getAll')
+ ->atLeast()->once()
+ ->andReturn([['id' => 1]]);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $result = $service->getExpired();
+ expect($result)->toBeArray();
+ expect($result[0])->toBeArray();
+});
+
+test('counts by status', function (): void {
+ $service = new Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getCell')
+ ->atLeast()->once()
+ ->andReturn(1);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $result = $service->countByStatus('open');
+ expect($result)->toBeInt();
+});
+
+test('gets active tickets count for order', function (): void {
+ $service = new Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getCell')
+ ->atLeast()->once()
+ ->andReturn(1);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $order = new Model_ClientOrder();
+ $order->loadBean(new Tests\Helpers\DummyBean());
+
+ $result = $service->getActiveTicketsCountForOrder($order);
+ expect($result)->toBeInt();
+});
+
+test('checks if task already exists returns true', function (): void {
+ $service = new Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $supportTicketModel = new Model_SupportTicket();
+ $supportTicketModel->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn($supportTicketModel);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $client = new Model_Client();
+ $client->loadBean(new Tests\Helpers\DummyBean());
+
+ $result = $service->checkIfTaskAlreadyExists($client, 1, Model_SupportTicket::REL_TYPE_ORDER, Model_SupportTicket::REL_TASK_UPGRADE);
+ expect($result)->toBeTrue();
+});
+
+test('checks if task already exists returns false', function (): void {
+ $service = new Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn(false);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $client = new Model_Client();
+ $client->loadBean(new Tests\Helpers\DummyBean());
+
+ $result = $service->checkIfTaskAlreadyExists($client, 1, Model_SupportTicket::REL_TYPE_ORDER, Model_SupportTicket::REL_TASK_CANCEL);
+ expect($result)->toBeFalse();
+});
+
+dataset('closeTicketIdentities', [
+ [new Model_Admin()],
+ [new Model_Client()],
+]);
+
+test('closes a ticket', function ($identity): void {
+ $service = new Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn(1);
+
+ $eventMock = Mockery::mock('\Box_EventManager');
+ $eventMock->shouldReceive('fire');
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $di['events_manager'] = $eventMock;
+ $service->setDi($di);
+
+ $ticket = new Model_SupportTicket();
+ $ticket->loadBean(new Tests\Helpers\DummyBean());
+
+ $result = $service->closeTicket($ticket, $identity);
+ expect($result)->toBeTrue();
+})->with('closeTicketIdentities');
+
+test('auto closes a ticket', function (): void {
+ $service = new Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn(1);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $service->setDi($di);
+
+ $ticket = new Model_SupportTicket();
+ $ticket->loadBean(new Tests\Helpers\DummyBean());
+
+ $result = $service->autoClose($ticket);
+ expect($result)->toBeTrue();
+});
+
+test('checks if ticket can be reopened when not closed', function (): void {
+ $service = new Service();
+ $helpdesk = new Model_SupportHelpdesk();
+ $helpdesk->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getExistingModelById')->never();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $service->setDi($di);
+
+ $ticket = new Model_SupportTicket();
+ $ticket->loadBean(new Tests\Helpers\DummyBean());
+
+ $result = $service->canBeReopened($ticket);
+ expect($result)->toBeTrue();
+});
+
+test('checks if ticket can be reopened', function (): void {
+ $service = new Service();
+ $helpdesk = new Model_SupportHelpdesk();
+ $helpdesk->loadBean(new Tests\Helpers\DummyBean());
+ $helpdesk->support_helpdesk_id = 1;
+ $helpdesk->can_reopen = true;
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($helpdesk);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $service->setDi($di);
+
+ $ticket = new Model_SupportTicket();
+ $ticket->loadBean(new Tests\Helpers\DummyBean());
+ $ticket->status = Model_SupportTicket::CLOSED;
+
+ $result = $service->canBeReopened($ticket);
+ expect($result)->toBeTrue();
+});
+
+test('removes tickets by client', function (): void {
+ $service = new Service();
+ $model = new Model_SupportTicket();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $model->id = 1;
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('find')
+ ->atLeast()->once()
+ ->andReturn([$model]);
+ $dbMock->shouldReceive('trash')
+ ->atLeast()->once()
+ ->andReturn(null);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $service->setDi($di);
+
+ $client = new Model_Client();
+ $client->loadBean(new Tests\Helpers\DummyBean());
+
+ $result = $service->rmByClient($client);
+ expect($result)->toBeNull();
+});
+
+test('removes a ticket', function (): void {
+ $service = new Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $callCount = 0;
+ $dbMock->shouldReceive('find')
+ ->twice()
+ ->andReturnUsing(function () use (&$callCount) {
+ ++$callCount;
+
+ return $callCount === 1 ? new Model_SupportTicketNote() : new Model_SupportTicketMessage();
+ });
+
+ $dbMock->shouldReceive('trash')
+ ->atLeast()->once()
+ ->andReturn(null);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $service->setDi($di);
+
+ $ticket = new Model_SupportTicket();
+ $ticket->loadBean(new Tests\Helpers\DummyBean());
+
+ $result = $service->rm($ticket);
+ expect($result)->toBeTrue();
+});
+
+test('converts ticket to api array', function (): void {
+ $service = new Service();
+ $supportTicketMessageModel = new Model_SupportTicketMessage();
+ $supportTicketMessageModel->loadBean(new Tests\Helpers\DummyBean());
+ $helpdesk = new Model_SupportHelpdesk();
+ $helpdesk->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn($supportTicketMessageModel);
+ $dbMock->shouldReceive('load')
+ ->atLeast()->once()
+ ->andReturnUsing(fn($type) => $type === 'SupportHelpdesk' ? $helpdesk : supportClientFixture());
+
+ $dbMock->shouldReceive('find')
+ ->atLeast()->once()
+ ->andReturn([new Model_SupportTicketNote()]);
+
+ $dbMock->shouldReceive('toArray')
+ ->byDefault()
+ ->andReturn([]);
+
+ $ticketMessages = [new Model_SupportTicketMessage(), new Model_SupportTicketMessage()];
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+ $serviceMock->shouldReceive('messageGetRepliesCount')
+ ->atLeast()->once()
+ ->andReturn(1);
+ $serviceMock->shouldReceive('messageToApiArray')
+ ->atLeast()->once()
+ ->andReturn([]);
+ $serviceMock->shouldReceive('helpdeskToApiArray')
+ ->atLeast()->once()
+ ->andReturn([]);
+ $serviceMock->shouldReceive('messageGetTicketMessages')
+ ->atLeast()->once()
+ ->andReturn($ticketMessages);
+ $serviceMock->shouldReceive('noteToApiArray')
+ ->atLeast()->once()
+ ->andReturn([]);
+ $serviceMock->shouldReceive('getClientApiArrayForTicket')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $serviceMock->setDi($di);
+
+ $ticket = new Model_SupportTicket();
+ $ticket->loadBean(new Tests\Helpers\DummyBean());
+
+ $result = $serviceMock->toApiArray($ticket, true, new Model_Admin());
+ expect($result)->toBeArray();
+ expect($result)->toHaveKey('replies');
+ expect($result)->toHaveKey('helpdesk');
+ expect($result)->toHaveKey('messages');
+ expect(count($result['messages']))->toBe(count($ticketMessages));
+});
+
+test('converts ticket to api array with rel details', function (): void {
+ $service = new Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn(new Model_SupportTicketMessage());
+
+ $callCount = 0;
+ $dbMock->shouldReceive('load')
+ ->atLeast()->once()
+ ->andReturnUsing(function () use (&$callCount) {
+ ++$callCount;
+
+ return $callCount === 1 ? new Model_SupportHelpdesk() : supportClientFixture();
+ });
+
+ $dbMock->shouldReceive('find')
+ ->atLeast()->once()
+ ->andReturn([new Model_SupportTicketNote()]);
+
+ $dbMock->shouldReceive('toArray')
+ ->byDefault()
+ ->andReturn([]);
+
+ $ticketMessages = [new Model_SupportTicketMessage(), new Model_SupportTicketMessage()];
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+ $serviceMock->shouldReceive('messageGetRepliesCount')
+ ->atLeast()->once()
+ ->andReturn(1);
+ $serviceMock->shouldReceive('messageToApiArray')
+ ->atLeast()->once()
+ ->andReturn([]);
+ $serviceMock->shouldReceive('helpdeskToApiArray')
+ ->atLeast()->once()
+ ->andReturn([]);
+ $serviceMock->shouldReceive('messageGetTicketMessages')
+ ->atLeast()->once()
+ ->andReturn($ticketMessages);
+ $serviceMock->shouldReceive('noteToApiArray')
+ ->atLeast()->once()
+ ->andReturn([]);
+ $serviceMock->shouldReceive('getClientApiArrayForTicket')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $serviceMock->setDi($di);
+
+ $ticket = new Model_SupportTicket();
+ $ticket->loadBean(new Tests\Helpers\DummyBean());
+ $ticket->rel_id = 1;
+ $ticket->rel_type = 'Type';
+
+ $result = $serviceMock->toApiArray($ticket, true, new Model_Admin());
+ expect($result)->toBeArray();
+ expect($result)->toHaveKey('replies');
+ expect($result)->toHaveKey('helpdesk');
+ expect($result)->toHaveKey('messages');
+ expect(count($result['messages']))->toBe(count($ticketMessages));
+});
+
+test('gets client api array for ticket', function (): void {
+ $service = new Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('load')
+ ->atLeast()->once()
+ ->andReturn(supportClientFixture());
+
+ $clientServiceMock = Mockery::mock(ClientService::class);
+ $clientServiceMock->shouldReceive('toApiArray')
+ ->byDefault()
+ ->andReturn([]);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $di['mod_service'] = $di->protect(fn () => $clientServiceMock);
+ $service->setDi($di);
+
+ $ticket = new Model_SupportTicket();
+ $ticket->loadBean(new Tests\Helpers\DummyBean());
+
+ $result = $service->getClientApiArrayForTicket($ticket);
+ expect($result)->toBeArray();
+});
+
+test('gets client api array for ticket when client not exists', function (): void {
+ $service = new Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('load')
+ ->atLeast()->once()
+ ->andReturn(null);
+
+ $clientServiceMock = Mockery::mock(ClientService::class);
+ $clientServiceMock->shouldReceive('toApiArray')->never();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $di['mod_service'] = $di->protect(fn () => $clientServiceMock);
+ $service->setDi($di);
+
+ $ticket = new Model_SupportTicket();
+ $ticket->loadBean(new Tests\Helpers\DummyBean());
+
+ $result = $service->getClientApiArrayForTicket($ticket);
+ expect($result)->toBeArray();
+});
+
+/*
+ * Canned Response Tests
+ */
+
+test('canned get search query', function (): void {
+ $service = new Service();
+ $di = container();
+ $service->setDi($di);
+
+ $data = [
+ 'search' => 'query',
+ ];
+
+ [$query, $bindings] = $service->cannedGetSearchQuery($data);
+ expect($query)->toBeString();
+ expect($bindings)->toBeArray();
+});
+
+test('canned get grouped pairs', function (): void {
+ $service = new Service();
+ $pairs = [
+ 0 => [
+ 'id' => 1,
+ 'r_title' => 'R Title',
+ 'c_title' => 'General',
+ ],
+ ];
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getAll')
+ ->atLeast()->once()
+ ->andReturn($pairs);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $expected = [
+ 'General' => [
+ 1 => 'R Title',
+ ],
+ ];
+
+ $result = $service->cannedGetGroupedPairs();
+ expect($result)->toBeArray();
+ expect($result)->toEqual($expected);
+});
+
+test('canned rm', function (): void {
+ $service = new Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('trash')
+ ->atLeast()->once()
+ ->andReturn(null);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $service->setDi($di);
+
+ $canned = new Model_SupportPr();
+ $canned->loadBean(new Tests\Helpers\DummyBean());
+
+ $result = $service->cannedRm($canned);
+ expect($result)->toBeTrue();
+});
+
+test('canned to api array', function (): void {
+ $service = new Service();
+ $category = new Model_SupportPrCategory();
+ $category->loadBean(new Tests\Helpers\DummyBean());
+ $category->id = 1;
+ $category->title = 'General';
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('toArray')
+ ->byDefault()
+ ->andReturn([]);
+ $dbMock->shouldReceive('load')
+ ->atLeast()->once()
+ ->andReturn($category);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $canned = new Model_SupportPr();
+ $canned->loadBean(new Tests\Helpers\DummyBean());
+
+ $result = $service->cannedToApiArray($canned);
+ expect($result)->toBeArray();
+ expect($result)->toHaveKey('category');
+ expect($result['category'])->toBeArray();
+ expect($result['category'])->toHaveKey('id');
+ expect($result['category'])->toHaveKey('title');
+});
+
+test('canned to api array category not found', function (): void {
+ $service = new Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('toArray')
+ ->byDefault()
+ ->andReturn([]);
+ $dbMock->shouldReceive('load')
+ ->atLeast()->once()
+ ->andReturn(null);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $canned = new Model_SupportPr();
+ $canned->loadBean(new Tests\Helpers\DummyBean());
+
+ $result = $service->cannedToApiArray($canned);
+ expect($result)->toBeArray();
+ expect($result)->toHaveKey('category');
+ expect($result['category'])->toEqual([]);
+});
+
+test('canned category get pairs', function (): void {
+ $service = new Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getAssoc')
+ ->atLeast()->once()
+ ->andReturn([0 => 'General']);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $result = $service->cannedCategoryGetPairs();
+ expect($result)->toBeArray();
+});
+
+test('canned category rm', function (): void {
+ $service = new Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('trash')
+ ->atLeast()->once()
+ ->andReturn(null);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $service->setDi($di);
+
+ $canned = new Model_SupportPrCategory();
+ $canned->loadBean(new Tests\Helpers\DummyBean());
+
+ $result = $service->cannedCategoryRm($canned);
+ expect($result)->toBeTrue();
+});
+
+test('canned category to api array', function (): void {
+ $service = new Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('toArray')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $service->setDi($di);
+
+ $canned = new Model_SupportPrCategory();
+ $canned->loadBean(new Tests\Helpers\DummyBean());
+
+ $result = $service->cannedCategoryToApiArray($canned);
+ expect($result)->toBeArray();
+});
+
+test('canned create', function (): void {
+ $service = new Service();
+ $randId = 1;
+ $helpDeskModel = new Model_SupportPr();
+ $helpDeskModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('dispense')
+ ->atLeast()->once()
+ ->andReturn($helpDeskModel);
+ $dbMock->shouldReceive('store')
+ ->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);
+
+ $result = $service->cannedCreate('Name', 1, 'Content');
+ expect($result)->toBeInt();
+ expect($result)->toEqual($randId);
+});
+
+test('canned update', function (): void {
+ $service = new Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn(1);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $service->setDi($di);
+
+ $model = new Model_SupportPr();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $data = [
+ 'category_id' => 1,
+ 'title' => 'email@example.com',
+ 'content' => 1,
+ ];
+
+ $result = $service->cannedUpdate($model, $data);
+ expect($result)->toBeTrue();
+});
+
+test('canned category create', function (): void {
+ $service = new Service();
+ $randId = 1;
+ $supportPrCategoryModel = new Model_SupportPrCategory();
+ $supportPrCategoryModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('dispense')
+ ->atLeast()->once()
+ ->andReturn($supportPrCategoryModel);
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn($randId);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $service->setDi($di);
+
+ $result = $service->cannedCategoryCreate('Name');
+ expect($result)->toBeInt();
+ expect($result)->toEqual($randId);
+});
+
+test('canned category update', function (): void {
+ $service = new Service();
+ $randId = 1;
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn($randId);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $service->setDi($di);
+
+ $model = new Model_SupportPrCategory();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $result = $service->cannedCategoryUpdate($model, 'Title');
+ expect($result)->toBeTrue();
+});
+
+/*
+ * Helpdesk Tests
+ */
+
+test('helpdesk get search query', function (): void {
+ $service = new Service();
+ $di = container();
+ $service->setDi($di);
+
+ $data = [
+ 'search' => 'SearchQuery',
+ ];
+ [$query, $bindings] = $service->helpdeskGetSearchQuery($data);
+
+ $expectedBindings = [
+ ':name' => '%SearchQuery%',
+ ':email' => '%SearchQuery%',
+ ':signature' => '%SearchQuery%',
+ ];
+
+ expect($query)->toBeString();
+ expect($bindings)->toBeArray();
+ expect($bindings)->toEqual($expectedBindings);
+});
+
+test('helpdesk get pairs', function (): void {
+ $service = new Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getAssoc')
+ ->atLeast()->once()
+ ->andReturn([0 => 'General']);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $result = $service->helpdeskGetPairs();
+ expect($result)->toBeArray();
+});
+
+test('helpdesk rm', function (): void {
+ $service = new Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('find')
+ ->atLeast()->once()
+ ->andReturn([]);
+ $dbMock->shouldReceive('trash')
+ ->atLeast()->once()
+ ->andReturn(null);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $service->setDi($di);
+
+ $helpdesk = new Model_SupportHelpdesk();
+ $helpdesk->loadBean(new Tests\Helpers\DummyBean());
+ $helpdesk->id = 1;
+
+ $result = $service->helpdeskRm($helpdesk);
+ expect($result)->toBeTrue();
+});
+
+test('helpdesk rm has tickets exception', function (): void {
+ $service = new Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('find')
+ ->atLeast()->once()
+ ->andReturn([new Model_SupportTicket()]);
+ $dbMock->shouldReceive('trash')
+ ->never();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $service->setDi($di);
+
+ $helpdesk = new Model_SupportHelpdesk();
+ $helpdesk->loadBean(new Tests\Helpers\DummyBean());
+ $helpdesk->id = 1;
+
+ $this->expectException(FOSSBilling\Exception::class);
+ $service->helpdeskRm($helpdesk);
+});
+
+test('helpdesk to api array', function (): void {
+ $service = new Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('toArray')
+ ->byDefault()
+ ->andReturn([]);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $helpdesk = new Model_SupportHelpdesk();
+ $helpdesk->loadBean(new Tests\Helpers\DummyBean());
+ $helpdesk->id = 1;
+
+ $result = $service->helpdeskToApiArray($helpdesk);
+ expect($result)->toBeArray();
+});
+
+test('helpdesk update', function (): void {
+ $service = new Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn(1);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $service->setDi($di);
+
+ $helpdesk = new Model_SupportHelpdesk();
+ $helpdesk->loadBean(new Tests\Helpers\DummyBean());
+
+ $data = [
+ 'name' => 'Name',
+ 'email' => 'email@example.com',
+ 'can_reopen' => 1,
+ 'close_after' => 1,
+ 'signature' => 'Signature',
+ ];
+
+ $result = $service->helpdeskUpdate($helpdesk, $data);
+ expect($result)->toBeTrue();
+});
+
+test('helpdesk create', function (): void {
+ $service = new Service();
+ $randId = 1;
+ $helpDeskModel = new Model_SupportHelpdesk();
+ $helpDeskModel->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('dispense')
+ ->atLeast()->once()
+ ->andReturn($helpDeskModel);
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn($randId);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $service->setDi($di);
+
+ $data = [
+ 'name' => 'Name',
+ 'email' => 'email@example.com',
+ 'can_reopen' => 1,
+ 'close_after' => 1,
+ 'signature' => 'Signature',
+ ];
+
+ $result = $service->helpdeskCreate($data);
+ expect($result)->toBeInt();
+ expect($result)->toEqual($randId);
+});
+
+/*
+ * Knowledge Base Tests
+ */
+
+test('kb search articles', function (): void {
+ $service = new Service();
+ $willReturn = [
+ 'pages' => 5,
+ 'page' => 2,
+ 'per_page' => 2,
+ 'total' => 10,
+ 'list' => [],
+ ];
+
+ $pagerMock = Mockery::mock(FOSSBilling\Pagination::class);
+ $pagerMock->shouldReceive('getPaginatedResultSet')
+ ->atLeast()->once()
+ ->andReturn($willReturn);
+
+ $di = container();
+ $di['pager'] = $pagerMock;
+ $service->setDi($di);
+
+ $result = $service->kbSearchArticles('active', 'keyword', 'category', PaginationOptions::fromArray([]));
+ expect($result)->toBeArray();
+ expect($result)->toHaveKey('list');
+ expect($result['list'])->toBeArray();
+ expect($result)->toHaveKey('pages');
+ expect($result)->toHaveKey('page');
+ expect($result)->toHaveKey('per_page');
+ expect($result)->toHaveKey('total');
+});
+
+test('kb find active article by id', function (): void {
+ $service = new Service();
+ $model = new Model_SupportKbArticle();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $result = $service->kbFindActiveArticleById(5);
+ expect($result)->toBeInstanceOf(Model_SupportKbArticle::class);
+ expect($result)->toEqual($model);
+});
+
+test('kb find active article by slug', function (): void {
+ $service = new Service();
+ $model = new Model_SupportKbArticle();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $result = $service->kbFindActiveArticleBySlug('slug');
+ expect($result)->toBeInstanceOf(Model_SupportKbArticle::class);
+ expect($result)->toEqual($model);
+});
+
+test('kb find active', function (): void {
+ $service = new Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('find')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $result = $service->kbFindActive();
+ expect($result)->toBeArray();
+});
+
+test('kb hit view', function (): void {
+ $service = new Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn(5);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $modelKb = new Model_SupportKbArticle();
+ $modelKb->loadBean(new Tests\Helpers\DummyBean());
+ $modelKb->views = 10;
+
+ $result = $service->kbHitView($modelKb);
+ expect($result)->toBeNull();
+});
+
+test('kb rm', function (): void {
+ $service = new Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('trash')
+ ->atLeast()->once()
+ ->andReturn(null);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $service->setDi($di);
+
+ $modelKb = new Model_SupportKbArticle();
+ $modelKb->loadBean(new Tests\Helpers\DummyBean());
+ $modelKb->id = 1;
+ $modelKb->views = 10;
+
+ $result = $service->kbRm($modelKb);
+ expect($result)->toBeNull();
+});
+
+dataset('kbToApiArrayProvider', function () {
+ $model = new Model_SupportKbArticle();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $model->id = 1;
+ $model->slug = 'article-slug';
+ $model->title = 'Title';
+ $model->views = 1;
+ $model->content = 'Content';
+ $model->created_at = '2013-01-01 12:00:00';
+ $model->updated_at = '2014-01-01 12:00:00';
+ $model->status = 'active';
+ $model->kb_article_category_id = 1;
+
+ $category = new Model_SupportKbArticleCategory();
+ $category->loadBean(new Tests\Helpers\DummyBean());
+ $category->id = 1;
+ $category->slug = 'category-slug';
+ $category->title = 'category-title';
+
+ return [
+ 'shallow without admin' => [
+ $model,
+ [
+ 'id' => $model->id,
+ 'slug' => $model->slug,
+ 'title' => $model->title,
+ 'views' => $model->views,
+ 'created_at' => $model->created_at,
+ 'updated_at' => $model->updated_at,
+ 'category' => [
+ 'id' => $category->id,
+ 'slug' => $category->slug,
+ 'title' => $category->title,
+ ],
+ 'status' => $model->status,
+ ],
+ false,
+ null,
+ $category,
+ ],
+ 'deep without admin' => [
+ $model,
+ [
+ 'id' => $model->id,
+ 'slug' => $model->slug,
+ 'title' => $model->title,
+ 'views' => $model->views,
+ 'created_at' => $model->created_at,
+ 'updated_at' => $model->updated_at,
+ 'category' => [
+ 'id' => $category->id,
+ 'slug' => $category->slug,
+ 'title' => $category->title,
+ ],
+ 'content' => $model->content,
+ 'status' => $model->status,
+ ],
+ true,
+ null,
+ $category,
+ ],
+ 'deep with admin' => [
+ $model,
+ [
+ 'id' => $model->id,
+ 'slug' => $model->slug,
+ 'title' => $model->title,
+ 'views' => $model->views,
+ 'created_at' => $model->created_at,
+ 'updated_at' => $model->updated_at,
+ 'category' => [
+ 'id' => $category->id,
+ 'slug' => $category->slug,
+ 'title' => $category->title,
+ ],
+ 'content' => $model->content,
+ 'status' => $model->status,
+ 'kb_article_category_id' => $model->kb_article_category_id,
+ ],
+ true,
+ new Model_Admin(),
+ $category,
+ ],
+ ];
+});
+
+test('kb to api array', function (Model_SupportKbArticle $model, array $expected, bool $deep, ?Model_Admin $identity, Model_SupportKbArticleCategory $category): void {
+ $service = new Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($category);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $result = $service->kbToApiArray($model, $deep, $identity);
+ expect($result)->toEqual($expected);
+})->with('kbToApiArrayProvider');
+
+test('kb create article', function (): void {
+ $service = new Service();
+ $randId = 1;
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn($randId);
+
+ $model = new Model_SupportKbArticle();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock->shouldReceive('dispense')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $toolsMock = Mockery::mock(FOSSBilling\Tools::class);
+ $toolsMock->shouldReceive('slug')
+ ->atLeast()->once()
+ ->andReturn('article-slug');
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['tools'] = $toolsMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $service->setDi($di);
+
+ $result = $service->kbCreateArticle(1, 'Title', 'Active', 'Content');
+ expect($result)->toBeInt();
+ expect($result)->toEqual($randId);
+});
+
+test('kb update article', function (): void {
+ $service = new Service();
+ $randId = 1;
+ $model = new Model_SupportKbArticle();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn($model);
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn($randId);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $service->setDi($di);
+
+ $result = $service->kbUpdateArticle($randId, 1, 'Title', 'article-slug', 'active', 'content', 1);
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+});
+
+test('kb update article not found exception', function (): void {
+ $service = new Service();
+ $randId = 1;
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn(false);
+ $dbMock->shouldReceive('store')
+ ->never();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $service->setDi($di);
+
+ $this->expectException(FOSSBilling\Exception::class);
+ $service->kbUpdateArticle($randId, 1, 'Title', 'article-slug', 'active', 'content', 1);
+});
+
+dataset('kbCategoryGetSearchQueryProvider', fn() => [
+ 'empty data' => [
+ [],
+ 'SELECT kac.* FROM support_kb_article_category kac LEFT JOIN support_kb_article ka ON kac.id = ka.kb_article_category_id GROUP BY kac.id ORDER BY kac.title',
+ [],
+ ],
+ 'with article status' => [
+ ['article_status' => 'active'],
+ 'SELECT kac.* FROM support_kb_article_category kac LEFT JOIN support_kb_article ka ON kac.id = ka.kb_article_category_id WHERE ka.status = :status GROUP BY kac.id ORDER BY kac.title',
+ [':status' => 'active'],
+ ],
+ 'with search query' => [
+ ['q' => 'search query'],
+ 'SELECT kac.* FROM support_kb_article_category kac LEFT JOIN support_kb_article ka ON kac.id = ka.kb_article_category_id WHERE (ka.title LIKE :title OR ka.content LIKE :content) GROUP BY kac.id ORDER BY kac.title',
+ [':title' => '%search query%', ':content' => '%search query%'],
+ ],
+ 'with search query and article status' => [
+ ['q' => 'search query', 'article_status' => 'active'],
+ 'SELECT kac.* FROM support_kb_article_category kac LEFT JOIN support_kb_article ka ON kac.id = ka.kb_article_category_id WHERE ka.status = :status AND (ka.title LIKE :title OR ka.content LIKE :content) GROUP BY kac.id ORDER BY kac.title',
+ [':title' => '%search query%', ':content' => '%search query%', ':status' => 'active'],
+ ],
+]);
+
+test('kb category get search query', function (array $data, string $query, array $bindings): void {
+ $service = new Service();
+ $di = container();
+ $service->setDi($di);
+
+ $result = $service->kbCategoryGetSearchQuery($data);
+
+ expect($result[0])->toBeString();
+ expect($result[1])->toBeArray();
+
+ // Normalize whitespace for comparison
+ $normalizedResult = trim((string) preg_replace('/\s+/', ' ', str_replace("\n", ' ', $result[0])));
+ $normalizedQuery = trim((string) preg_replace('/\s+/', ' ', str_replace("\n", ' ', $query)));
+ expect($normalizedResult)->toEqual($normalizedQuery);
+ expect($result[1])->toEqual($bindings);
+})->with('kbCategoryGetSearchQueryProvider');
+
+test('kb category find all', function (): void {
+ $service = new Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getAll')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $result = $service->kbCategoryFindAll();
+ expect($result)->toBeArray();
+});
+
+test('kb category get pairs', function (): void {
+ $service = new Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getAssoc')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $result = $service->kbCategoryGetPairs();
+ expect($result)->toBeArray();
+});
+
+test('kb category rm', function (): void {
+ $service = new Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getCell')
+ ->atLeast()->once()
+ ->andReturn(0);
+ $dbMock->shouldReceive('trash')
+ ->atLeast()->once()
+ ->andReturn(null);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $service->setDi($di);
+
+ $model = new Model_SupportKbArticleCategory();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $model->id = 1;
+
+ $result = $service->kbCategoryRm($model);
+ expect($result)->toBeTrue();
+});
+
+test('kb category rm has articles exception', function (): void {
+ $service = new Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getCell')
+ ->atLeast()->once()
+ ->andReturn(1);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $service->setDi($di);
+
+ $model = new Model_SupportKbArticleCategory();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $model->id = 1;
+
+ $this->expectException(FOSSBilling\Exception::class);
+ $service->kbCategoryRm($model);
+});
+
+test('kb create category', function (): void {
+ $service = new Service();
+ $randId = 1;
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn($randId);
+
+ $articleCategoryModel = new Model_SupportKbArticleCategory();
+ $articleCategoryModel->loadBean(new Tests\Helpers\DummyBean());
+ $dbMock->shouldReceive('dispense')
+ ->atLeast()->once()
+ ->andReturn($articleCategoryModel);
+
+ $toolsMock = Mockery::mock(FOSSBilling\Tools::class);
+ $toolsMock->shouldReceive('slug')
+ ->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');
+ expect($result)->toBeInt();
+ expect($result)->toEqual($randId);
+});
+
+test('kb update category', function (): void {
+ $service = new Service();
+ $randId = 1;
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn($randId);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $service->setDi($di);
+
+ $model = new Model_SupportKbArticleCategory();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+ $model->id = 1;
+
+ $result = $service->kbUpdateCategory($model, 'New Title', 'new-title', 'Description');
+ expect($result)->toBeTrue();
+});
+
+test('kb find category by id', function (): void {
+ $service = new Service();
+ $model = new Model_SupportKbArticleCategory();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $result = $service->kbFindCategoryById(5);
+ expect($result)->toBeInstanceOf(Model_SupportKbArticleCategory::class);
+ expect($result)->toEqual($model);
+});
+
+test('kb find category by slug', function (): void {
+ $service = new Service();
+ $model = new Model_SupportKbArticleCategory();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn($model);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $result = $service->kbFindCategoryBySlug('slug');
+ expect($result)->toBeInstanceOf(Model_SupportKbArticleCategory::class);
+ expect($result)->toEqual($model);
+});
+
+/*
+ * Public Ticket Tests
+ */
+
+test('public get statuses', function (): void {
+ $service = new Service();
+ $result = $service->publicGetStatuses();
+ expect($result)->toBeArray();
+});
+
+test('public find one by hash', function (): void {
+ $service = new Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn(new Model_SupportPTicket());
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $result = $service->publicFindOneByHash(sha1(uniqid()));
+ expect($result)->toBeInstanceOf(Model_SupportPTicket::class);
+});
+
+test('public find one by hash not found exception', function (): void {
+ $service = new Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn(null);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $this->expectException(FOSSBilling\Exception::class);
+ $service->publicFindOneByHash(sha1(uniqid()));
+});
+
+dataset('publicGetSearchQueryProvider', fn() => [
+ 'with search string' => [
+ [
+ 'search' => 'Query',
+ 'id' => 1,
+ 'status' => Model_SupportPTicket::OPENED,
+ 'name' => 'Name',
+ 'email' => 'email@example.com',
+ 'subject' => 'Subject',
+ 'content' => 'Content',
+ ],
+ ],
+ 'with search int' => [
+ [
+ 'search' => 1,
+ 'id' => 1,
+ 'status' => Model_SupportPTicket::OPENED,
+ 'name' => 'Name',
+ 'email' => 'email@example.com',
+ 'subject' => 'Subject',
+ 'content' => 'Content',
+ ],
+ ],
+]);
+
+test('public get search query', function (array $data): void {
+ $service = new Service();
+ $di = container();
+ $service->setDi($di);
+
+ [$query, $bindings] = $service->publicGetSearchQuery($data);
+ expect($query)->toBeString();
+ expect($bindings)->toBeArray();
+})->with('publicGetSearchQueryProvider');
+
+test('public counter', function (): void {
+ $service = new Service();
+ $arr = [
+ Model_SupportPTicket::OPENED => 1,
+ Model_SupportPTicket::ONHOLD => 1,
+ Model_SupportPTicket::CLOSED => 1,
+ ];
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getAssoc')
+ ->atLeast()->once()
+ ->andReturn($arr);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $result = $service->publicCounter();
+ expect($result)->toBeArray();
+ expect($result)->toHaveKey('total');
+ expect($result['total'])->toEqual(array_sum($arr));
+});
+
+test('public get latest', function (): void {
+ $service = new Service();
+ $ticket = new Model_SupportPTicket();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('find')
+ ->atLeast()->once()
+ ->andReturn([$ticket, $ticket]);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $result = $service->publicGetLatest();
+ expect($result)->toBeArray();
+ expect($result[0])->toBeInstanceOf(Model_SupportPTicket::class);
+});
+
+test('public count by status', function (): void {
+ $service = new Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getCell')
+ ->atLeast()->once()
+ ->andReturn(1);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $result = $service->publicCountByStatus('open');
+ expect($result)->toBeInt();
+});
+
+test('public get expired', function (): void {
+ $service = new Service();
+ $ticket = new Model_SupportPTicket();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('find')
+ ->atLeast()->once()
+ ->andReturn([$ticket, $ticket]);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $result = $service->publicGetExpired();
+ expect($result)->toBeArray();
+ expect($result[0])->toBeInstanceOf(Model_SupportPTicket::class);
+});
+
+dataset('publicCloseTicketProvider', fn() => [
+ 'with admin' => [new Model_Admin()],
+ 'with guest' => [new Model_Guest()],
+]);
+
+test('public close ticket', function (Model_Admin|Model_Guest $identity): void {
+ $service = new Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn(1);
+
+ $eventMock = Mockery::mock('\Box_EventManager');
+ $eventMock->shouldReceive('fire')
+ ->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $di['events_manager'] = $eventMock;
+ $service->setDi($di);
+
+ $ticket = new Model_SupportPTicket();
+ $ticket->loadBean(new Tests\Helpers\DummyBean());
+
+ $result = $service->publicCloseTicket($ticket, $identity);
+ expect($result)->toBeTrue();
+})->with('publicCloseTicketProvider');
+
+test('public auto close', function (): void {
+ $service = new Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn(1);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $service->setDi($di);
+
+ $ticket = new Model_SupportPTicket();
+ $ticket->loadBean(new Tests\Helpers\DummyBean());
+
+ $result = $service->publicAutoClose($ticket);
+ expect($result)->toBeTrue();
+});
+
+test('public rm', function (): void {
+ $service = new Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('trash')
+ ->atLeast()->once()
+ ->andReturn(null);
+ $dbMock->shouldReceive('find')
+ ->atLeast()->once()
+ ->andReturn([new Model_SupportPTicketMessage()]);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $service->setDi($di);
+
+ $ticket = new Model_SupportPTicket();
+ $ticket->loadBean(new Tests\Helpers\DummyBean());
+
+ $result = $service->publicRm($ticket);
+ expect($result)->toBeTrue();
+});
+
+dataset('publicToApiArrayProvider', fn() => [
+ 'with message' => [
+ new Model_SupportPTicketMessage(),
+ 'atLeastOnce',
+ ],
+ 'without message' => [
+ null,
+ 'never',
+ ],
+]);
+
+test('public to api array', function (?Model_SupportPTicketMessage $findOne, string $publicMessageGetAuthorDetailsCalled): void {
+ $service = new Service();
+ $ticketMessages = [new Model_SupportPTicketMessage(), new Model_SupportPTicketMessage()];
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('findOne')
+ ->andReturn($findOne);
+ $dbMock->shouldReceive('toArray')
+ ->byDefault()
+ ->andReturn([]);
+ $dbMock->shouldReceive('find')
+ ->andReturn($ticketMessages);
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('publicMessageToApiArray')
+ ->atLeast()->once()
+ ->andReturn([]);
+ $serviceMock->shouldReceive('publicMessageGetAuthorDetails')
+ ->atLeast()->once()
+ ->andReturn(['name' => 'Name', 'email' => 'email#example.com']);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $serviceMock->setDi($di);
+
+ $ticket = new Model_SupportPTicket();
+ $ticket->loadBean(new Tests\Helpers\DummyBean());
+
+ $result = $serviceMock->publicToApiArray($ticket, true);
+ expect($result)->toBeArray();
+ expect($result)->toHaveKey('author');
+ expect($result)->toHaveKey('messages');
+ expect($result['messages'])->toHaveCount(count($ticketMessages));
+})->with('publicToApiArrayProvider');
+
+test('public message get author details admin', function (): void {
+ $service = new Service();
+ $admin = new Model_Admin();
+ $admin->loadBean(new Tests\Helpers\DummyBean());
+ $admin->id = 1;
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($admin);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $ticketMsg = new Model_SupportPTicketMessage();
+ $ticketMsg->loadBean(new Tests\Helpers\DummyBean());
+ $ticketMsg->admin_id = 1;
+
+ $result = $service->publicMessageGetAuthorDetails($ticketMsg);
+ expect($result)->toBeArray();
+ expect($result)->toHaveKey('name');
+});
+
+test('public message get author details not admin', function (): void {
+ $service = new Service();
+ $ticket = new Model_SupportPTicket();
+ $ticket->loadBean(new Tests\Helpers\DummyBean());
+ $ticket->author_name = 'Name';
+ $ticket->author_email = 'Email@example.com';
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn($ticket);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $ticketMsg = new Model_SupportPTicketMessage();
+ $ticketMsg->loadBean(new Tests\Helpers\DummyBean());
+ $ticketMsg->admin_id = null;
+
+ $result = $service->publicMessageGetAuthorDetails($ticketMsg);
+ expect($result)->toBeArray();
+ expect($result)->toHaveKey('name');
+});
+
+test('public message to api array', function (): void {
+ $service = new Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('toArray')
+ ->byDefault()
+ ->andReturn([]);
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('publicMessageGetAuthorDetails')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $serviceMock->setDi($di);
+
+ $ticketMsg = new Model_SupportPTicketMessage();
+ $ticketMsg->loadBean(new Tests\Helpers\DummyBean());
+ $ticketMsg->id = 1;
+
+ $result = $serviceMock->publicMessageToApiArray($ticketMsg);
+ expect($result)->toBeArray();
+ expect($result)->toHaveKey('author');
+});
+
+test('public ticket create', function (): void {
+ $service = new Service();
+ $message = new Model_SupportTicketMessage();
+ $message->loadBean(new Tests\Helpers\DummyBean());
+
+ $randId = 1;
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('dispense')
+ ->atLeast()->once()
+ ->andReturn($message);
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn($randId);
+
+ $eventMock = Mockery::mock('\Box_EventManager');
+ $eventMock->shouldReceive('fire')
+ ->atLeast()->once();
+
+ $toolsMock = Mockery::mock(FOSSBilling\Tools::class);
+ $toolsMock->shouldReceive('validateAndSanitizeEmail')
+ ->atLeast()->once();
+
+ $requestMock = Mockery::mock(FOSSBilling\Request::class);
+ $requestMock->shouldReceive('getClientIp')
+ ->atLeast()->once()
+ ->andReturn('127.0.0.1');
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $di['events_manager'] = $eventMock;
+ $di['tools'] = $toolsMock;
+ $di['request'] = $requestMock;
+ $service->setDi($di);
+
+ $admin = new Model_Admin();
+ $admin->loadBean(new Tests\Helpers\DummyBean());
+ $admin->id = 1;
+
+ $data = [
+ 'email' => 'email@example.com',
+ 'name' => 'Name',
+ 'message' => 'Message',
+ 'request' => 'Request',
+ 'subject' => 'Subject',
+ ];
+
+ $result = $service->publicTicketCreate($data, $admin);
+ expect($result)->toBeInt();
+ expect($result)->toEqual($randId);
+});
+
+test('public ticket update', function (): void {
+ $service = new Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn(1);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $service->setDi($di);
+
+ $ticket = new Model_SupportPTicket();
+ $ticket->loadBean(new Tests\Helpers\DummyBean());
+
+ $data = [
+ 'support_helpdesk_id' => 1,
+ 'status' => Model_SupportTicket::OPENED,
+ 'subject' => 'Subject',
+ 'priority' => 1,
+ ];
+
+ $result = $service->publicTicketUpdate($ticket, $data);
+ expect($result)->toBeTrue();
+});
+
+test('public ticket reply', function (): void {
+ $service = new Service();
+ $message = new Model_SupportTicketMessage();
+ $message->loadBean(new Tests\Helpers\DummyBean());
+
+ $randId = 1;
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('dispense')
+ ->atLeast()->once()
+ ->andReturn($message);
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn($randId);
+
+ $eventMock = Mockery::mock('\Box_EventManager');
+ $eventMock->shouldReceive('fire')
+ ->atLeast()->once();
+
+ $requestMock = Mockery::mock(FOSSBilling\Request::class);
+ $requestMock->shouldReceive('getClientIp')
+ ->atLeast()->once()
+ ->andReturn('127.0.0.1');
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $di['events_manager'] = $eventMock;
+ $di['request'] = $requestMock;
+ $service->setDi($di);
+
+ $ticket = new Model_SupportPTicket();
+ $ticket->loadBean(new Tests\Helpers\DummyBean());
+
+ $admin = new Model_Admin();
+ $admin->loadBean(new Tests\Helpers\DummyBean());
+
+ $result = $service->publicTicketReply($ticket, $admin, 'Content');
+ expect($result)->toBeInt();
+ expect($result)->toEqual($randId);
+});
+
+test('public ticket reply for guest', function (): void {
+ $service = new Service();
+ $message = new Model_SupportTicketMessage();
+ $message->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('dispense')
+ ->atLeast()->once()
+ ->andReturn($message);
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once();
+
+ $requestMock = Mockery::mock(FOSSBilling\Request::class);
+ $requestMock->shouldReceive('getClientIp')
+ ->atLeast()->once()
+ ->andReturn('127.0.0.1');
+
+ $eventMock = Mockery::mock('\Box_EventManager');
+ $eventMock->shouldReceive('fire')
+ ->atLeast()->once();
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $di['request'] = $requestMock;
+ $di['events_manager'] = $eventMock;
+ $service->setDi($di);
+
+ $ticket = new Model_SupportPTicket();
+ $ticket->loadBean(new Tests\Helpers\DummyBean());
+ $ticket->hash = 'test-hash-123';
+
+ $result = $service->publicTicketReplyForGuest($ticket, 'Content');
+ expect($result)->toBeString();
+ expect($result)->toEqual('test-hash-123');
+});
+
+/*
+ * Ticket Operations Tests
+ */
+
+test('ticket update', function (): void {
+ $service = new Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn(1);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $service->setDi($di);
+
+ $ticket = new Model_SupportTicket();
+ $ticket->loadBean(new Tests\Helpers\DummyBean());
+
+ $data = [
+ 'support_helpdesk_id' => 1,
+ 'status' => Model_SupportTicket::OPENED,
+ 'subject' => 'Subject',
+ 'priority' => 1,
+ ];
+
+ $result = $service->ticketUpdate($ticket, $data);
+ expect($result)->toBeTrue();
+});
+
+test('ticket message update', function (): void {
+ $service = new Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn(1);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $service->setDi($di);
+
+ $message = new Model_SupportTicketMessage();
+ $message->loadBean(new Tests\Helpers\DummyBean());
+
+ $result = $service->ticketMessageUpdate($message, 'Content');
+ expect($result)->toBeTrue();
+});
+
+dataset('ticketReplyProvider', function () {
+ $admin = new Model_Admin();
+ $admin->loadBean(new Tests\Helpers\DummyBean());
+ $admin->id = 1;
+
+ $client = new Model_Client();
+ $client->loadBean(new Tests\Helpers\DummyBean());
+ $client->id = 1;
+
+ return [
+ 'with admin' => [$admin],
+ 'with client' => [$client],
+ ];
+});
+
+test('ticket reply', function (Model_Admin|Model_Client $identity): void {
+ $service = new Service();
+ $message = new Model_SupportTicketMessage();
+ $message->loadBean(new Tests\Helpers\DummyBean());
+
+ $randId = 1;
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('dispense')
+ ->atLeast()->once()
+ ->andReturn($message);
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn($randId);
+
+ $eventMock = Mockery::mock('\Box_EventManager');
+ $eventMock->shouldReceive('fire')
+ ->atLeast()->once();
+
+ $requestMock = Mockery::mock(FOSSBilling\Request::class);
+ $requestMock->shouldReceive('getClientIp')
+ ->atLeast()->once()
+ ->andReturn('127.0.0.1');
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $di['request'] = $requestMock;
+ $di['events_manager'] = $eventMock;
+ $service->setDi($di);
+
+ $ticket = new Model_SupportTicket();
+ $ticket->loadBean(new Tests\Helpers\DummyBean());
+
+ $result = $service->ticketReply($ticket, $identity, 'Content');
+ expect($result)->toBeInt();
+ expect($result)->toEqual($randId);
+})->with('ticketReplyProvider');
+
+test('ticket create for admin', function (): void {
+ $service = new Service();
+ $message = new Model_SupportTicketMessage();
+ $message->loadBean(new Tests\Helpers\DummyBean());
+
+ $randId = 1;
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('dispense')
+ ->atLeast()->once()
+ ->andReturn($message);
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn($randId);
+
+ $eventMock = Mockery::mock('\Box_EventManager');
+ $eventMock->shouldReceive('fire')
+ ->atLeast()->once();
+
+ $requestMock = Mockery::mock(FOSSBilling\Request::class);
+ $requestMock->shouldReceive('getClientIp')
+ ->atLeast()->once()
+ ->andReturn('127.0.0.1');
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $di['request'] = $requestMock;
+ $di['events_manager'] = $eventMock;
+ $service->setDi($di);
+
+ $helpdesk = new Model_SupportHelpdesk();
+ $helpdesk->loadBean(new Tests\Helpers\DummyBean());
+
+ $admin = new Model_Admin();
+ $admin->loadBean(new Tests\Helpers\DummyBean());
+ $admin->id = 1;
+
+ $client = new Model_Client();
+ $client->loadBean(new Tests\Helpers\DummyBean());
+ $client->id = 1;
+
+ $data = [
+ 'subject' => 'Subject',
+ 'content' => 'Content',
+ ];
+
+ $result = $service->ticketCreateForAdmin($client, $helpdesk, $data, $admin);
+ expect($result)->toBeInt();
+ expect($result)->toEqual($randId);
+});
+
+test('ticket create for client', function (): void {
+ $service = new Service();
+ $ticket = new Model_SupportTicket();
+ $ticket->loadBean(new Tests\Helpers\DummyBean());
+
+ $randId = 1;
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('dispense')
+ ->with('SupportTicket')
+ ->atLeast()->once()
+ ->andReturn($ticket);
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn($randId);
+ $dbMock->shouldReceive('getExistingModelById')
+ ->atLeast()->once()
+ ->andReturn(new Model_SupportPr());
+
+ $eventMock = Mockery::mock('\Box_EventManager');
+ $eventMock->shouldReceive('fire')
+ ->atLeast()->once();
+
+ $config = [
+ 'autorespond_enable' => 1,
+ 'autorespond_message_id' => 1,
+ ];
+ $supportModMock = Mockery::mock(FOSSBilling\Module::class);
+ $supportModMock->shouldReceive('getConfig')
+ ->atLeast()->once()
+ ->andReturn($config);
+
+ $staffServiceMock = Mockery::mock(Box\Mod\Staff\Service::class);
+ $staffServiceMock->shouldReceive('getCronAdmin')
+ ->atLeast()->once()
+ ->andReturn(new Model_Admin());
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('ticketReply')
+ ->atLeast()->once()
+ ->andReturn(1);
+ $serviceMock->shouldReceive('messageCreateForTicket')
+ ->atLeast()->once()
+ ->andReturn(1);
+ $serviceMock->shouldReceive('cannedToApiArray')
+ ->atLeast()->once()
+ ->andReturn(['content' => 'Content']);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $di['events_manager'] = $eventMock;
+ $di['mod'] = $di->protect(fn () => $supportModMock);
+ $di['mod_service'] = $di->protect(fn () => $staffServiceMock);
+
+ $serviceMock->setDi($di);
+
+ $helpdesk = new Model_SupportHelpdesk();
+ $helpdesk->loadBean(new Tests\Helpers\DummyBean());
+
+ $client = new Model_Client();
+ $client->loadBean(new Tests\Helpers\DummyBean());
+ $client->id = 1;
+
+ $data = [
+ 'name' => 'Name',
+ 'email' => 'email@example.com',
+ 'subject' => 'Subject',
+ 'content' => 'content',
+ ];
+
+ $result = $serviceMock->ticketCreateForClient($client, $helpdesk, $data);
+ expect($result)->toBeInt();
+ expect($result)->toEqual($randId);
+});
+
+test('ticket create for client task already exists exception', function (): void {
+ $service = new Service();
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+ $serviceMock->shouldReceive('checkIfTaskAlreadyExists')
+ ->byDefault()
+ ->andReturn(true);
+
+ $helpdesk = new Model_SupportHelpdesk();
+ $helpdesk->loadBean(new Tests\Helpers\DummyBean());
+
+ $data = [
+ 'rel_id' => 1,
+ 'rel_type' => 'Type',
+ 'rel_task' => 'Task',
+ 'rel_new_value' => 'New value',
+ ];
+
+ $client = new Model_Client();
+ $client->loadBean(new Tests\Helpers\DummyBean());
+ $client->id = 1;
+
+ $di = container();
+ $serviceMock->setDi($di);
+
+ $this->expectException(FOSSBilling\Exception::class);
+ $serviceMock->ticketCreateForClient($client, $helpdesk, $data);
+});
+
+test('ticket task complete', function (): void {
+ $service = new Service();
+ $randId = 1;
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn($randId);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $service->setDi($di);
+
+ $model = new Model_SupportTicket();
+ $model->loadBean(new Tests\Helpers\DummyBean());
+
+ $result = $service->ticketTaskComplete($model);
+ expect($result)->toBeTrue();
+});
+
+/*
+ * Message Tests
+ */
+
+test('message get ticket messages', function (): void {
+ $service = new Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('find')
+ ->atLeast()->once()
+ ->andReturn([new Model_SupportTicketMessage()]);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $ticket = new Model_SupportTicket();
+ $ticket->loadBean(new Tests\Helpers\DummyBean());
+ $ticket->id = 1;
+
+ $result = $service->messageGetTicketMessages($ticket);
+ expect($result)->toBeArray();
+});
+
+test('message get replies count', function (): void {
+ $service = new Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getCell')
+ ->atLeast()->once()
+ ->andReturn(1);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $ticket = new Model_SupportTicket();
+ $ticket->loadBean(new Tests\Helpers\DummyBean());
+ $ticket->id = 1;
+
+ $result = $service->messageGetRepliesCount($ticket);
+ expect($result)->toBeInt();
+});
+
+test('message get author details admin', function (): void {
+ $service = new Service();
+ $admin = new Model_Admin();
+ $admin->loadBean(new Tests\Helpers\DummyBean());
+ $admin->id = 1;
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('load')
+ ->atLeast()->once()
+ ->andReturn($admin);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $ticketMsg = new Model_SupportTicketMessage();
+ $ticketMsg->loadBean(new Tests\Helpers\DummyBean());
+ $ticketMsg->admin_id = 1;
+
+ $result = $service->messageGetAuthorDetails($ticketMsg);
+ expect($result)->toBeArray();
+ expect($result)->toHaveKey('name');
+});
+
+test('message get author details client', function (): void {
+ $service = new Service();
+ $client = new Model_Client();
+ $client->loadBean(new Tests\Helpers\DummyBean());
+ $client->id = 1;
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('load')
+ ->atLeast()->once()
+ ->andReturn($client);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $ticketMsg = new Model_SupportTicketMessage();
+ $ticketMsg->loadBean(new Tests\Helpers\DummyBean());
+ $ticketMsg->client_id = 1;
+
+ $result = $service->messageGetAuthorDetails($ticketMsg);
+ expect($result)->toBeArray();
+ expect($result)->toHaveKey('name');
+});
+
+test('message to api array', function (): void {
+ $service = new Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('toArray')
+ ->byDefault()
+ ->andReturn([]);
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('messageGetAuthorDetails')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $serviceMock->setDi($di);
+
+ $ticketMsg = new Model_SupportTicketMessage();
+ $ticketMsg->loadBean(new Tests\Helpers\DummyBean());
+ $ticketMsg->id = 1;
+
+ $result = $serviceMock->messageToApiArray($ticketMsg);
+ expect($result)->toBeArray();
+ expect($result)->toHaveKey('author');
+});
+
+dataset('messageCreateForTicketProvider', function () {
+ $admin = new Model_Admin();
+ $admin->loadBean(new Tests\Helpers\DummyBean());
+ $admin->id = 1;
+
+ $client = new Model_Client();
+ $client->loadBean(new Tests\Helpers\DummyBean());
+ $client->id = 1;
+
+ return [
+ 'with admin' => [$admin],
+ 'with client' => [$client],
+ ];
+});
+
+test('message create for ticket', function (Model_Admin|Model_Client $identity): void {
+ $service = new Service();
+ $randId = 1;
+ $supportTicketMessage = new Model_SupportTicketMessage();
+ $supportTicketMessage->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('dispense')
+ ->atLeast()->once()
+ ->andReturn($supportTicketMessage);
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn($randId);
+
+ $requestMock = Mockery::mock(FOSSBilling\Request::class);
+ $requestMock->shouldReceive('getClientIp')
+ ->atLeast()->once()
+ ->andReturn('127.0.0.1');
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $di['request'] = $requestMock;
+ $service->setDi($di);
+
+ $ticket = new Model_SupportTicket();
+ $ticket->loadBean(new Tests\Helpers\DummyBean());
+
+ $result = $service->messageCreateForTicket($ticket, $identity, 'Content');
+ expect($result)->toBeInt();
+ expect($result)->toEqual($randId);
+})->with('messageCreateForTicketProvider');
+
+/*
+ * Note Tests
+ */
+
+test('note get author details', function (): void {
+ $service = new Service();
+ $admin = new Model_Admin();
+ $admin->loadBean(new Tests\Helpers\DummyBean());
+ $admin->name = 'AdminName';
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('load')
+ ->atLeast()->once()
+ ->andReturn($admin);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $note = new Model_SupportTicketNote();
+ $note->loadBean(new Tests\Helpers\DummyBean());
+
+ $result = $service->noteGetAuthorDetails($note);
+ expect($result)->toBeArray();
+});
+
+test('note rm', function (): void {
+ $service = new Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('trash')
+ ->atLeast()->once()
+ ->andReturn(null);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $service->setDi($di);
+
+ $note = new Model_SupportTicketNote();
+ $note->loadBean(new Tests\Helpers\DummyBean());
+
+ $result = $service->noteRm($note);
+ expect($result)->toBeTrue();
+});
+
+test('note to api array', function (): void {
+ $service = new Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('toArray')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $serviceMock->shouldReceive('noteGetAuthorDetails')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $serviceMock->setDi($di);
+
+ $note = new Model_SupportTicketNote();
+ $note->loadBean(new Tests\Helpers\DummyBean());
+
+ $result = $serviceMock->noteToApiArray($note);
+ expect($result)->toBeArray();
+ expect($result)->toHaveKey('author');
+});
+
+test('note create', function (): void {
+ $service = new Service();
+ $randId = 1;
+ $supportTicketNote = new Model_SupportTicketNote();
+ $supportTicketNote->loadBean(new Tests\Helpers\DummyBean());
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('dispense')
+ ->atLeast()->once()
+ ->andReturn($supportTicketNote);
+ $dbMock->shouldReceive('store')
+ ->atLeast()->once()
+ ->andReturn($randId);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $di['logger'] = new Tests\Helpers\TestLogger();
+ $service->setDi($di);
+
+ $admin = new Model_Admin();
+ $admin->loadBean(new Tests\Helpers\DummyBean());
+
+ $ticket = new Model_SupportTicket();
+ $ticket->loadBean(new Tests\Helpers\DummyBean());
+
+ $result = $service->noteCreate($ticket, $admin, 'Note');
+ expect($result)->toBeInt();
+ expect($result)->toEqual($randId);
+});
+
+/*
+ * Other Tests
+ */
+
+dataset('canClientSubmitNewTicketProvider', function () {
+ $ticket = new Model_SupportTicket();
+ $ticket->loadBean(new Tests\Helpers\DummyBean());
+ $ticket->client_id = 5;
+ $ticket->created_at = date('Y-m-d H:i:s');
+
+ $ticket2 = new Model_SupportTicket();
+ $ticket2->loadBean(new Tests\Helpers\DummyBean());
+ $ticket2->client_id = 5;
+ $ticket2->created_at = date('Y-m-d H:i:s', strtotime('-2 days'));
+
+ return [
+ 'ticket created today - cannot submit' => [$ticket, 24, false],
+ 'no previous tickets - can submit' => [null, 24, true],
+ 'last ticket 2 days ago - can submit' => [$ticket2, 24, true],
+ ];
+});
+
+test('can client submit new ticket', function (?Model_SupportTicket $ticket, int $hours, bool $expected): void {
+ $service = new Service();
+ if (!$expected) {
+ $this->expectException(FOSSBilling\Exception::class);
+ }
+
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('findOne')
+ ->atLeast()->once()
+ ->andReturn($ticket);
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $client = new Model_Client();
+ $client->loadBean(new Tests\Helpers\DummyBean());
+ $client->id = 5;
+
+ $config = ['wait_hours' => $hours];
+
+ $result = $service->canClientSubmitNewTicket($client, $config);
+
+ if ($expected) {
+ expect($result)->toBeTrue();
+ }
+})->with('canClientSubmitNewTicketProvider');
diff --git a/src/modules/System/Api/Admin.php b/src/modules/System/Api/Admin.php
index e6f4a48ae..e4aa247e6 100644
--- a/src/modules/System/Api/Admin.php
+++ b/src/modules/System/Api/Admin.php
@@ -29,7 +29,7 @@ class Admin extends \Api_Abstract
*/
public function get_params($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'manage_settings');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'manage_settings');
return $this->getService()->getParams($data);
}
@@ -39,7 +39,7 @@ class Admin extends \Api_Abstract
*/
public function localization_settings(): array
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'manage_settings');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'manage_settings');
return [
'locale' => (string) Config::getProperty('i18n.locale', 'en_US'),
@@ -56,7 +56,7 @@ class Admin extends \Api_Abstract
*/
public function update_params($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'update_params');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'update_params');
return $this->getService()->updateParams($data);
}
@@ -68,7 +68,7 @@ class Admin extends \Api_Abstract
*/
public function update_localization_settings($data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'update_params');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'update_params');
if (isset($data['locale']) && $data['locale'] !== '') {
Config::setProperty('i18n.locale', $data['locale']);
@@ -87,7 +87,7 @@ class Admin extends \Api_Abstract
public function messages($data)
{
try {
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'manage_settings');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'manage_settings');
} catch (\Throwable) {
return [];
}
@@ -105,7 +105,7 @@ class Admin extends \Api_Abstract
public function cas_messages()
{
try {
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'manage_settings');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'manage_settings');
} catch (\Throwable) {
return [];
}
@@ -120,7 +120,7 @@ class Admin extends \Api_Abstract
*/
public function template_exists($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'manage_settings');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'manage_settings');
if (!isset($data['file'])) {
return false;
@@ -136,7 +136,7 @@ class Admin extends \Api_Abstract
*/
public function env($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'manage_settings');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'manage_settings');
$fetchExternalIp = Tools::normalizeBoolean($data['ip'] ?? false);
@@ -156,7 +156,7 @@ class Admin extends \Api_Abstract
public function is_allowed($data)
{
$f = $data['f'] ?? null;
- $service = $this->di['mod_service']('Staff');
+ $service = $this->getDi()['mod_service']('Staff');
return $service->hasPermission($this->getIdentity(), $data['mod'], $f);
}
@@ -168,7 +168,7 @@ class Admin extends \Api_Abstract
*/
public function clear_cache()
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'invalidate_cache');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'invalidate_cache');
return $this->getService()->clearCache();
}
@@ -178,9 +178,9 @@ class Admin extends \Api_Abstract
*/
public function update_available(): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'view');
- $updater = $this->di['updater'];
+ $updater = $this->getDi()['updater'];
return $updater->isUpdateAvailable();
}
@@ -190,9 +190,9 @@ class Admin extends \Api_Abstract
*/
public function update_info(): array
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'view');
- $updater = $this->di['updater'];
+ $updater = $this->getDi()['updater'];
$info = $updater->getLatestVersionInfo();
$requiredPhpVersion = $info['minimum_php_version'] ?? 'unknown';
@@ -203,7 +203,7 @@ class Admin extends \Api_Abstract
$info['minimum_php_version'] = $requiredPhpVersion;
$info['current_php_version'] = PHP_VERSION;
$info['php_version_supported'] = $requiredPhpVersion === 'unknown' || version_compare(PHP_VERSION, $requiredPhpVersion, '>=');
- $info['readiness'] = $this->di['update_readiness']->check();
+ $info['readiness'] = $this->getDi()['update_readiness']->check();
return $info;
}
@@ -213,9 +213,9 @@ class Admin extends \Api_Abstract
*/
public function recheck_update(): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'recheck_update');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'recheck_update');
- $updater = $this->di['updater'];
+ $updater = $this->getDi()['updater'];
$updater->getLatestVersionInfo(null, true);
return true;
@@ -228,54 +228,54 @@ class Admin extends \Api_Abstract
*/
public function update_core($data): bool
{
- $updater = $this->di['updater'];
+ $updater = $this->getDi()['updater'];
if ($updater->getUpdateBranch() !== 'preview' && !$updater->isUpdateAvailable()) {
throw new \FOSSBilling\InformationException('You have the latest version of FOSSBilling. You do not need to update.');
}
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'system_update');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'system_update');
if (function_exists('set_time_limit')) {
set_time_limit(300);
}
$new_version = $updater->getLatestVersion();
- $this->di['events_manager']->fire(['event' => 'onBeforeAdminUpdateCore']);
+ $this->getDi()['events_manager']->fire(['event' => 'onBeforeAdminUpdateCore']);
$updater->performUpdate();
- $this->di['logger']->info('Installed FOSSBilling update files from %s to %s. Update finalization is pending.', \FOSSBilling\Version::VERSION, $new_version);
+ $this->getDi()['logger']->info('Installed FOSSBilling update files from %s to %s. Update finalization is pending.', \FOSSBilling\Version::VERSION, $new_version);
return true;
}
public function update_finalization_status(): array
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'system_update');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'system_update');
- return $this->di['update_finalization']->getStatus();
+ return $this->getDi()['update_finalization']->getStatus();
}
public function finalize_update(): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'system_update');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'system_update');
if (function_exists('set_time_limit')) {
set_time_limit(180);
}
- $this->di['update_finalization']->finalizeUpdate();
- $this->di['events_manager']->fire(['event' => 'onAfterAdminUpdateCore']);
- $this->di['logger']->info('Finalized FOSSBilling update to %s.', \FOSSBilling\Version::VERSION);
+ $this->getDi()['update_finalization']->finalizeUpdate();
+ $this->getDi()['events_manager']->fire(['event' => 'onAfterAdminUpdateCore']);
+ $this->getDi()['logger']->info('Finalized FOSSBilling update to %s.', \FOSSBilling\Version::VERSION);
return true;
}
public function complete_update_finalization(): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'system_update');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'system_update');
- $this->di['update_finalization']->completeFinalization();
- $this->di['logger']->info('Completed FOSSBilling update finalization for %s.', \FOSSBilling\Version::VERSION);
+ $this->getDi()['update_finalization']->completeFinalization();
+ $this->getDi()['logger']->info('Completed FOSSBilling update finalization for %s.', \FOSSBilling\Version::VERSION);
return true;
}
@@ -287,17 +287,17 @@ class Admin extends \Api_Abstract
*/
public function manual_update(): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'system_update');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'system_update');
if (function_exists('set_time_limit')) {
set_time_limit(180);
}
- $updater = $this->di['updater'];
- $this->di['events_manager']->fire(['event' => 'onBeforeAdminManualUpdate']);
+ $updater = $this->getDi()['updater'];
+ $this->getDi()['events_manager']->fire(['event' => 'onBeforeAdminManualUpdate']);
$updater->performManualUpdate();
- $this->di['events_manager']->fire(['event' => 'onAfterAdminManualUpdate']);
- $this->di['logger']->info('Updated FOSSBilling - applied patches and updated configuration file.');
+ $this->getDi()['events_manager']->fire(['event' => 'onAfterAdminManualUpdate']);
+ $this->getDi()['logger']->info('Updated FOSSBilling - applied patches and updated configuration file.');
return true;
}
@@ -307,9 +307,9 @@ class Admin extends \Api_Abstract
*/
public function is_behind_on_patches(): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'view');
- $updater = $this->di['updater'];
+ $updater = $this->getDi()['updater'];
return $updater->isBehindOnDBPatches();
}
@@ -319,7 +319,7 @@ class Admin extends \Api_Abstract
*/
public function instance_id(): string
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'view');
return INSTANCE_ID;
}
@@ -329,7 +329,7 @@ class Admin extends \Api_Abstract
*/
public function error_reporting_enabled(): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'view');
return (bool) Config::getProperty('debug_and_monitoring.report_errors', false);
}
@@ -339,7 +339,7 @@ class Admin extends \Api_Abstract
*/
public function toggle_error_reporting(): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'toggle_error_reporting');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'toggle_error_reporting');
$current = Config::getProperty('debug_and_monitoring.report_errors', false);
Config::setProperty('debug_and_monitoring.report_errors', !$current);
@@ -352,21 +352,21 @@ class Admin extends \Api_Abstract
*/
public function last_error_reporting_change(): string
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'view');
return \FOSSBilling\SentryHelper::last_change;
}
public function get_interface_ips(): array
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'manage_network_interface');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'manage_network_interface');
return Tools::listHttpInterfaces();
}
public function set_interface_ip($data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'manage_network_interface');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('system', 'manage_network_interface');
$config = Config::getConfig();
if (isset($data['interface'])) {
diff --git a/src/modules/System/Api/Guest.php b/src/modules/System/Api/Guest.php
index 38f7e94a5..79232b396 100644
--- a/src/modules/System/Api/Guest.php
+++ b/src/modules/System/Api/Guest.php
@@ -31,7 +31,7 @@ class Guest extends \Api_Abstract
public function company()
{
$companyInfo = $this->getService()->getCompany();
- $auth = $this->di['auth'];
+ $auth = $this->getDi()['auth'];
$hideExtraCompanyInfoFromGuest = $this->getService()->getParamValue('hide_company_public');
if (!$auth->isAdminLoggedIn() && !$auth->isClientLoggedIn() && $hideExtraCompanyInfoFromGuest) {
@@ -56,7 +56,7 @@ class Guest extends \Api_Abstract
*/
public function default_country(): ?string
{
- $mod = $this->di['mod']('system');
+ $mod = $this->getDi()['mod']('system');
$cfg = $mod->getConfig();
return $cfg['default_country'] ?? null;
@@ -69,7 +69,7 @@ class Guest extends \Api_Abstract
*/
public function countries(): array
{
- $mod = $this->di['mod']('system');
+ $mod = $this->getDi()['mod']('system');
$cfg = $mod->getConfig();
$configuredCountries = trim((string) ($cfg['countries'] ?? ''));
@@ -171,7 +171,7 @@ class Guest extends \Api_Abstract
*/
public function current_url()
{
- return $this->di['request']->getRequestUri();
+ return $this->getDi()['request']->getRequestUri();
}
/**
diff --git a/src/modules/System/Service.php b/src/modules/System/Service.php
index 9f59edd45..c587fd191 100644
--- a/src/modules/System/Service.php
+++ b/src/modules/System/Service.php
@@ -31,11 +31,9 @@ class Service
private const int MYSQL_DUPLICATE_ENTRY_ERROR = 23000;
protected ?Container $di = null;
- private readonly Filesystem $filesystem;
- public function __construct()
+ public function __construct(private readonly ?Filesystem $filesystem = new Filesystem())
{
- $this->filesystem = new Filesystem();
}
public function setDi(Container $di): void
@@ -602,7 +600,7 @@ class Service
}
$code = (string) $code;
- if ($code === null || $code === '' || $code === 0 || $code === '0') {
+ if ($code === '' || $code === '0') {
return '-';
}
diff --git a/src/modules/System/tests/E2E/ApiAdminTest.php b/src/modules/System/tests/E2E/ApiAdminTest.php
new file mode 100644
index 000000000..71506492a
--- /dev/null
+++ b/src/modules/System/tests/E2E/ApiAdminTest.php
@@ -0,0 +1,117 @@
+ true,
+ CURLOPT_TIMEOUT => 2,
+ CURLOPT_FAILONERROR => true,
+ CURLOPT_URL => $service,
+ ]);
+ $ip = curl_exec($ch);
+ curl_close($ch);
+ if (filter_var($ip, FILTER_VALIDATE_IP)) {
+ return true;
+ }
+ }
+
+ return false;
+}
+
+test('clear cache', function (): void {
+ $result = Tests\Helpers\ApiClient::request('admin/system/clear_cache');
+ expect($result->wasSuccessful())->toBeTrue($result);
+ expect($result->getResult())->toBeBool();
+});
+
+test('error reporting toggle', function (): void {
+ $before = Tests\Helpers\ApiClient::request('admin/system/error_reporting_enabled')->getResult();
+ expect($before)->toBeBool();
+
+ $result = Tests\Helpers\ApiClient::request('admin/system/toggle_error_reporting');
+ expect($result->wasSuccessful())->toBeTrue($result);
+ expect($result->getResult())->toBeTrue();
+
+ $after = Tests\Helpers\ApiClient::request('admin/system/error_reporting_enabled')->getResult();
+ expect($after)->toBeBool();
+ $this->assertNotEquals($after, $before);
+
+ if ($after) {
+ $result = Tests\Helpers\ApiClient::request('admin/system/toggle_error_reporting');
+ expect($result->wasSuccessful())->toBeTrue($result);
+ expect($result->getResult())->toBeTrue();
+ }
+});
+
+test('get and set network interfaces', function (): void {
+ $result = Tests\Helpers\ApiClient::request('admin/system/get_interface_ips');
+ expect($result->wasSuccessful())->toBeTrue($result);
+ expect($result->getResult())->toBeArray();
+
+ foreach ($result->getResult() as $ip) {
+ expect((bool) filter_var($ip, FILTER_VALIDATE_IP))->toBeTrue();
+ }
+
+ if (systemIpLookupWorking()) {
+ foreach ($result->getResult() as $ip) {
+ $testResult = Tests\Helpers\ApiClient::request('admin/system/set_interface_ip', ['interface' => $ip]);
+ expect($testResult->wasSuccessful())->toBeTrue($result);
+
+ sleep(2);
+
+ $result = Tests\Helpers\ApiClient::request('admin/system/env', ['ip' => true]);
+ expect($result->wasSuccessful())->toBeTrue($result);
+ expect((bool) filter_var($result->getResult(), FILTER_VALIDATE_IP))->toBeTrue();
+ }
+ }
+
+ Tests\Helpers\ApiClient::request('admin/system/set_interface_ip', ['interface' => '0']);
+});
+
+test('interface is ignored when not valid', function (): void {
+ $result = Tests\Helpers\ApiClient::request('admin/system/set_interface_ip', ['interface' => '12345']);
+ expect($result->wasSuccessful())->toBeTrue($result);
+ expect($result->getResult())->toBeTrue();
+
+ if (systemIpLookupWorking()) {
+ sleep(2);
+ $result = Tests\Helpers\ApiClient::request('admin/system/env', ['ip' => true]);
+ expect($result->wasSuccessful())->toBeTrue($result);
+ expect((bool) filter_var($result->getResult(), FILTER_VALIDATE_IP))->toBeTrue();
+ }
+});
+
+test('custom interface', function (): void {
+ $result = Tests\Helpers\ApiClient::request('admin/system/set_interface_ip', ['custom_interface' => '12345']);
+ expect($result->wasSuccessful())->toBeTrue($result);
+ expect($result->getResult())->toBeTrue();
+
+ if (systemIpLookupWorking()) {
+ sleep(2);
+ $result = Tests\Helpers\ApiClient::request('admin/system/env', ['ip' => true]);
+ expect($result->wasSuccessful())->toBeTrue($result);
+ expect($result->getResult())->toBeEmpty();
+ }
+
+ $result = Tests\Helpers\ApiClient::request('admin/system/set_interface_ip', ['custom_interface' => '', 'interface' => '0']);
+ expect($result->wasSuccessful())->toBeTrue($result);
+ expect($result->getResult())->toBeTrue();
+});
diff --git a/src/modules/System/tests/E2E/ApiGuestTest.php b/src/modules/System/tests/E2E/ApiGuestTest.php
new file mode 100644
index 000000000..3840f86f6
--- /dev/null
+++ b/src/modules/System/tests/E2E/ApiGuestTest.php
@@ -0,0 +1,58 @@
+ 'layout_default.html.twig']);
+ expect($result->wasSuccessful())->toBeTrue($result);
+ expect($result->getResult())->toBeTrue();
+});
+
+test('template does not exist', function (): void {
+ $result = Tests\Helpers\ApiClient::request('guest/system/template_exists', ['file' => 'thisfiledoesnotexist.txt']);
+ expect($result->wasSuccessful())->toBeTrue($result);
+ expect($result->getResult())->toBeFalse();
+});
+
+test('periods', function (): void {
+ $result = Tests\Helpers\ApiClient::request('guest/system/periods');
+ expect($result->wasSuccessful())->toBeTrue($result);
+ expect($result->getResult())->toBeArray();
+});
+
+test('countries', function (): void {
+ $result = Tests\Helpers\ApiClient::request('guest/system/countries');
+ expect($result->wasSuccessful())->toBeTrue($result);
+ expect($result->getResult())->toBeArray();
+});
+
+test('countries eunion', function (): void {
+ $result = Tests\Helpers\ApiClient::request('guest/system/countries_eunion');
+ expect($result->wasSuccessful())->toBeTrue($result);
+ expect($result->getResult())->toBeArray();
+});
+
+test('states', function (): void {
+ $result = Tests\Helpers\ApiClient::request('guest/system/states');
+ expect($result->wasSuccessful())->toBeTrue($result);
+ expect($result->getResult())->toBeArray();
+});
+
+test('phone codes', function (): void {
+ $result = Tests\Helpers\ApiClient::request('guest/system/phone_codes');
+ expect($result->wasSuccessful())->toBeTrue($result);
+ expect($result->getResult())->toBeArray();
+});
diff --git a/src/modules/System/tests/Unit/Api/AdminTest.php b/src/modules/System/tests/Unit/Api/AdminTest.php
new file mode 100644
index 000000000..5cce500f4
--- /dev/null
+++ b/src/modules/System/tests/Unit/Api/AdminTest.php
@@ -0,0 +1,142 @@
+setDi($di);
+ $getDi = $api->getDi();
+ expect($getDi)->toEqual($di);
+});
+
+test('get params', function (): void {
+ $api = new Box\Mod\System\Api\Admin();
+ $data = [];
+
+ $serviceMock = Mockery::mock(Box\Mod\System\Service::class);
+ $serviceMock
+ ->shouldReceive('getParams')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $api->setService($serviceMock);
+
+ $result = $api->get_params($data);
+ expect($result)->toBeArray();
+});
+
+test('update params', function (): void {
+ $api = new Box\Mod\System\Api\Admin();
+ $data = [];
+
+ $serviceMock = Mockery::mock(Box\Mod\System\Service::class);
+ $serviceMock
+ ->shouldReceive('updateParams')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $api->setService($serviceMock);
+
+ $result = $api->update_params($data);
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+});
+
+test('messages', function (): void {
+ $api = new Box\Mod\System\Api\Admin();
+ $data = [];
+
+ $di = container();
+
+ $api->setDi($di);
+
+ $serviceMock = Mockery::mock(Box\Mod\System\Service::class);
+ $serviceMock
+ ->shouldReceive('getMessages')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $api->setService($serviceMock);
+
+ $result = $api->messages($data);
+ expect($result)->toBeArray();
+});
+
+test('template exists', function (): void {
+ $api = new Box\Mod\System\Api\Admin();
+ $data = [
+ 'file' => 'testing.txt',
+ ];
+
+ $serviceMock = Mockery::mock(Box\Mod\System\Service::class);
+ $serviceMock
+ ->shouldReceive('templateExists')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $api->setService($serviceMock);
+
+ $result = $api->template_exists($data);
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+});
+
+test('env', function (): void {
+ $api = new Box\Mod\System\Api\Admin();
+ $data = [];
+
+ $serviceMock = Mockery::mock(Box\Mod\System\Service::class);
+ $serviceMock
+ ->shouldReceive('getEnv')
+ ->atLeast()->once()
+ ->andReturn([]);
+
+ $di = container();
+
+ $api->setDi($di);
+ $api->setService($serviceMock);
+
+ $result = $api->env($data);
+ expect($result)->toBeArray();
+});
+
+test('is allowed', function (): void {
+ $api = new Box\Mod\System\Api\Admin();
+ $data = [
+ 'mod' => 'extension',
+ ];
+
+ $staffServiceMock = Mockery::mock(Box\Mod\Staff\Service::class);
+ $staffServiceMock
+ ->shouldReceive('hasPermission')
+ ->atLeast()->once()
+ ->andReturn(true);
+
+ $validatorStub = $this->createStub(FOSSBilling\Validate::class);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(function ($serviceName) use ($staffServiceMock) {
+ if ($serviceName == 'Staff') {
+ return $staffServiceMock;
+ }
+
+ return false;
+ });
+ $di['validator'] = $validatorStub;
+ $api->setDi($di);
+
+ $result = $api->is_allowed($data);
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+});
diff --git a/src/modules/System/tests/Unit/Api/GuestTest.php b/src/modules/System/tests/Unit/Api/GuestTest.php
new file mode 100644
index 000000000..528ae22db
--- /dev/null
+++ b/src/modules/System/tests/Unit/Api/GuestTest.php
@@ -0,0 +1,148 @@
+setDi($di);
+ $getDi = $api->getDi();
+ expect($getDi)->toEqual($di);
+});
+
+test('company returns company data when public display is enabled', function (): void {
+ $api = new Box\Mod\System\Api\Guest();
+ $companyData = ['companyName' => 'TestCo'];
+
+ $authMock = Mockery::mock('\Box_Authorization');
+ $authMock->shouldReceive('isAdminLoggedIn')
+ ->atLeast()->once()
+ ->andReturn(false);
+ $authMock->shouldReceive('isClientLoggedIn')
+ ->atLeast()->once()
+ ->andReturn(false);
+
+ $serviceMock = Mockery::mock(Box\Mod\System\Service::class);
+ $serviceMock
+ ->shouldReceive('getCompany')
+ ->atLeast()->once()
+ ->andReturn($companyData);
+ $serviceMock
+ ->shouldReceive('getParamValue')
+ ->atLeast()->once()
+ ->with('hide_company_public')
+ ->andReturn(0);
+
+ $di = container();
+ $di['auth'] = $authMock;
+ $api->setDi($di);
+ $api->setService($serviceMock);
+ $result = $api->company();
+
+ expect($result)->toBeArray()->not->toBeEmpty();
+});
+
+test('company filters sensitive data when public display is disabled', function (): void {
+ $api = new Box\Mod\System\Api\Guest();
+ $companyData = [
+ 'companyName' => 'TestCo',
+ 'vat_number' => 'Test VAT',
+ 'email' => 'test@email.com',
+ 'tel' => '123456789',
+ 'account_number' => '987654321',
+ 'number' => '123456',
+ 'address_1' => 'Test Address 1',
+ 'address_2' => 'Test Address 2',
+ 'address_3' => 'Test Address 3',
+ ];
+
+ $authMock = Mockery::mock('\Box_Authorization');
+ $authMock->shouldReceive('isAdminLoggedIn')
+ ->atLeast()->once()
+ ->andReturn(false);
+ $authMock->shouldReceive('isClientLoggedIn')
+ ->atLeast()->once()
+ ->andReturn(false);
+
+ $serviceMock = Mockery::mock(Box\Mod\System\Service::class);
+ $serviceMock
+ ->shouldReceive('getCompany')
+ ->atLeast()->once()
+ ->andReturn($companyData);
+ $serviceMock
+ ->shouldReceive('getParamValue')
+ ->atLeast()->once()
+ ->with('hide_company_public')
+ ->andReturn(1);
+
+ $di = container();
+ $di['auth'] = $authMock;
+ $api->setDi($di);
+ $api->setService($serviceMock);
+ $result = $api->company();
+
+ expect($result)->toBeArray();
+ expect($result)->not->toHaveKey('vat_number');
+ expect($result)->not->toHaveKey('email');
+ expect($result)->not->toHaveKey('tel');
+ expect($result)->not->toHaveKey('account_number');
+ expect($result)->not->toHaveKey('number');
+ expect($result)->not->toHaveKey('address_1');
+ expect($result)->not->toHaveKey('address_2');
+ expect($result)->not->toHaveKey('address_3');
+});
+
+test('period_title returns period title string', function (): void {
+ $api = new Box\Mod\System\Api\Guest();
+ $data = ['code' => 'periodCode'];
+
+ $servuceMock = Mockery::mock(Box\Mod\System\Service::class);
+ $servuceMock
+ ->shouldReceive('getPeriod')
+ ->atLeast()->once()
+ ->andReturn('periodTtitleValue');
+ $di = container();
+
+ $api->setDi($di);
+ $api->setService($servuceMock);
+
+ $result = $api->period_title($data);
+ expect($result)->toBeString();
+});
+
+test('period_title returns dash when code is missing', function (): void {
+ $api = new Box\Mod\System\Api\Guest();
+ $data = [];
+ $expected = '-';
+ $di = container();
+
+ $api->setDi($di);
+ $result = $api->period_title($data);
+ expect($result)->toBeString()->toEqual($expected);
+});
+
+test('get_pending_messages returns and clears pending messages', function (): void {
+ $api = new Box\Mod\System\Api\Guest();
+ $serviceMock = Mockery::mock(Box\Mod\System\Service::class);
+ $messageArr = ['Important message to user'];
+ $serviceMock
+ ->shouldReceive('getPendingMessages')
+ ->atLeast()->once()
+ ->andReturn($messageArr);
+
+ $serviceMock->shouldReceive('clearPendingMessages')->atLeast()->once();
+
+ $api->setService($serviceMock);
+ $result = $api->get_pending_messages();
+ expect($result)->toBeArray()->toEqual($messageArr);
+});
diff --git a/src/modules/System/tests/Unit/ServiceTest.php b/src/modules/System/tests/Unit/ServiceTest.php
new file mode 100644
index 000000000..20e3baf9e
--- /dev/null
+++ b/src/modules/System/tests/Unit/ServiceTest.php
@@ -0,0 +1,305 @@
+expectException(FOSSBilling\Exception::class);
+ $this->expectExceptionMessage('Parameter key is missing');
+
+ $service->getParamValue($param);
+});
+
+test('getCompany returns company information', function (): void {
+ $service = new Service();
+ $expected = [
+ 'www' => SYSTEM_URL,
+ 'name' => 'Inc. Test',
+ 'email' => 'work@example.eu',
+ 'tel' => null,
+ 'signature' => null,
+ 'logo_url' => null,
+ 'logo_url_dark' => null,
+ 'favicon_url' => null,
+ 'address_1' => null,
+ 'address_2' => null,
+ 'address_3' => null,
+ 'account_number' => null,
+ 'bank_name' => null,
+ 'bic' => null,
+ 'display_bank_info' => null,
+ 'bank_info_pagebottom' => null,
+ 'number' => null,
+ 'note' => null,
+ 'privacy_policy' => null,
+ 'tos' => null,
+ 'vat_number' => null,
+ ];
+
+ $multParamsResults = [
+ [
+ 'param' => 'company_name',
+ 'value' => 'Inc. Test',
+ ],
+ [
+ 'param' => 'company_email',
+ 'value' => 'work@example.eu',
+ ],
+ ];
+ $resultMock = Mockery::mock(Doctrine\DBAL\Result::class);
+ $resultMock->shouldReceive('fetchAllAssociative')
+ ->once()
+ ->andReturn($multParamsResults);
+
+ $queryBuilderMock = Mockery::mock(Doctrine\DBAL\Query\QueryBuilder::class);
+ $queryBuilderMock->shouldReceive('select')->once()->with('param', 'value')->andReturnSelf();
+ $queryBuilderMock->shouldReceive('from')->once()->with('setting')->andReturnSelf();
+ $queryBuilderMock->shouldReceive('where')->once()->with('param IN (:params)')->andReturnSelf();
+ $queryBuilderMock->shouldReceive('setParameter')->once()->andReturnSelf();
+ $queryBuilderMock->shouldReceive('executeQuery')->once()->andReturn($resultMock);
+
+ $dbalMock = Mockery::mock(Doctrine\DBAL\Connection::class);
+ $dbalMock->shouldReceive('createQueryBuilder')->once()->andReturn($queryBuilderMock);
+
+ $di = container();
+ $di['dbal'] = $dbalMock;
+
+ $service->setDi($di);
+
+ $result = $service->getCompany();
+ expect($result)->toBeArray();
+ expect($result)->toBe($expected);
+});
+
+test('getParams returns system parameters', function (): void {
+ $service = new Service();
+ $expected = [
+ 'company_name' => 'Inc. Test',
+ 'company_email' => 'work@example.eu',
+ ];
+ $multParamsResults = [
+ [
+ 'param' => 'company_name',
+ 'value' => 'Inc. Test',
+ ],
+ [
+ 'param' => 'company_email',
+ 'value' => 'work@example.eu',
+ ],
+ ];
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getAll')->atLeast()->once()
+ ->andReturn($multParamsResults);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $service->setDi($di);
+
+ $result = $service->getParams([]);
+ expect($result)->toBeArray();
+ expect($result)->toBe($expected);
+});
+
+test('updateParams updates system parameters', function (): void {
+ $service = new Service();
+ $data = [
+ 'company_name' => 'newValue',
+ ];
+
+ $eventMock = Mockery::mock('\Box_EventManager');
+ $eventMock->shouldReceive('fire')->atLeast()->once();
+
+ $logStub = $this->createStub('\Box_Log');
+
+ $systemServiceMock = Mockery::mock(Service::class)->makePartial();
+ $systemServiceMock->shouldReceive('setParamValue')->atLeast()->once()
+ ->andReturn(true);
+
+ $di = container();
+ $di['events_manager'] = $eventMock;
+ $di['logger'] = $logStub;
+
+ $systemServiceMock->setDi($di);
+ $result = $systemServiceMock->updateParams($data);
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+});
+
+test('getMessages returns system messages', function (): void {
+ $service = new Service();
+ $latestVersion = '1.0.0';
+ $type = 'info';
+
+ $filesystemMock = Mockery::mock(Symfony\Component\Filesystem\Filesystem::class);
+ $filesystemMock->allows()->exists(Mockery::any())->andReturn(false);
+ $systemServiceMock = Mockery::mock(new Service($filesystemMock))->makePartial();
+ $systemServiceMock->allows()->getParamValue(Mockery::any())->andReturn(false);
+
+ $updaterMock = Mockery::mock(FOSSBilling\Update::class);
+ $updaterMock->allows()->isUpdateAvailable()->andReturn(true);
+ $updaterMock->allows()->getLatestVersion()->andReturn($latestVersion);
+ $updaterMock->allows()->isBehindOnDBPatches()->andReturn(false);
+
+ $urlMock = Mockery::mock(Box\Url::class);
+ $urlMock->allows()->adminLink(Mockery::any())->andReturn('http://example.com');
+
+ $dbalMock = Mockery::mock(Doctrine\DBAL\Connection::class);
+ $queryBuilderMock = Mockery::mock(Doctrine\DBAL\Query\QueryBuilder::class);
+ $resultMock = Mockery::mock(Doctrine\DBAL\Result::class);
+ $dbalMock->allows()->createQueryBuilder()->andReturn($queryBuilderMock);
+ $queryBuilderMock->allows()->select(Mockery::any())->andReturnSelf();
+ $queryBuilderMock->allows()->from(Mockery::any())->andReturnSelf();
+ $queryBuilderMock->allows()->where(Mockery::any())->andReturnSelf();
+ $queryBuilderMock->allows()->setParameter(Mockery::any(), Mockery::any())->andReturnSelf();
+ $queryBuilderMock->allows()->executeQuery()->andReturn($resultMock);
+ $resultMock->allows()->fetchOne()->andReturn(false);
+
+ $di = container();
+ $di['updater'] = $updaterMock;
+ $di['url'] = $urlMock;
+ $di['dbal'] = $dbalMock;
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $systemServiceMock);
+
+ $systemServiceMock->setDi($di);
+
+ $result = $systemServiceMock->getMessages($type);
+ expect($result)->toBeArray();
+});
+
+test('templateExists returns false when paths are empty', function (): void {
+ $service = new Service();
+ $getThemeResults = ['paths' => []];
+ $themeServiceMock = Mockery::mock(Box\Mod\Theme\Service::class)->makePartial();
+ $themeServiceMock->shouldReceive('getThemeConfig')->atLeast()->once()
+ ->andReturn($getThemeResults);
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $themeServiceMock);
+ $service->setDi($di);
+
+ $result = $service->templateExists('defaultFile.cp');
+ expect($result)->toBeBool();
+ expect($result)->toBeFalse();
+});
+
+test('clearCache clears cache directory', function (): void {
+ $service = new Service();
+ // Use a temporary directory for testing instead of PATH_CACHE
+ $cacheDir = sys_get_temp_dir() . '/fossbilling_test_cache_' . uniqid();
+
+ // Create cache directory with .gitkeep
+ if (!is_dir($cacheDir)) {
+ mkdir($cacheDir, 0o755, true);
+ }
+
+ $gitkeepFile = $cacheDir . '/.gitkeep';
+ file_put_contents($gitkeepFile, '');
+
+ // Call clearCache with the temp directory
+ $result = $service->clearCache($cacheDir);
+
+ // Restore .gitkeep file after clearCache removes it
+ file_put_contents($gitkeepFile, '');
+
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+
+ // Cleanup temp directory
+ if (is_dir($cacheDir)) {
+ // Remove .gitkeep file first, then the directory
+ if (file_exists($gitkeepFile)) {
+ unlink($gitkeepFile);
+ }
+ rmdir($cacheDir);
+ }
+});
+
+test('getPeriod returns period description', function (): void {
+ $service = new Service();
+ $code = '1W';
+ $expected = 'Every Week';
+ $result = $service->getPeriod($code);
+
+ expect($result)->toBeString();
+ expect($result)->toBe($expected);
+});
+
+test('getPendingMessages returns pending messages from session', function (): void {
+ $service = new Service();
+ $di = container();
+
+ $sessionMock = Mockery::mock(FOSSBilling\Session::class);
+ $sessionMock->shouldReceive('get')->atLeast()->once()
+ ->with('pending_messages')
+ ->andReturn([]);
+
+ $di['session'] = $sessionMock;
+
+ $service->setDi($di);
+ $result = $service->getPendingMessages();
+ expect($result)->toBeArray();
+});
+
+test('getPendingMessages returns empty array when session returns non-array', function (): void {
+ $service = new Service();
+ $di = container();
+
+ $sessionMock = Mockery::mock(FOSSBilling\Session::class);
+ $sessionMock->shouldReceive('get')->atLeast()->once()
+ ->with('pending_messages')
+ ->andReturn(null);
+
+ $di['session'] = $sessionMock;
+
+ $service->setDi($di);
+ $result = $service->getPendingMessages();
+ expect($result)->toBeArray();
+});
+
+test('setPendingMessage adds message to pending messages', function (): void {
+ $service = new Service();
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+ $serviceMock->shouldReceive('getPendingMessages')->atLeast()->once()
+ ->andReturn([]);
+
+ $di = container();
+
+ $sessionMock = Mockery::mock(FOSSBilling\Session::class);
+ $sessionMock->shouldReceive('set')->atLeast()->once()
+ ->with('pending_messages', Mockery::any());
+
+ $di['session'] = $sessionMock;
+
+ $serviceMock->setDi($di);
+
+ $message = 'Important Message';
+ $result = $serviceMock->setPendingMessage($message);
+ expect($result)->toBeTrue();
+});
+
+test('clearPendingMessages clears pending messages', function (): void {
+ $service = new Service();
+ $di = container();
+
+ $sessionMock = Mockery::mock(FOSSBilling\Session::class);
+ $sessionMock->shouldReceive('delete')->atLeast()->once()
+ ->with('pending_messages');
+ $di['session'] = $sessionMock;
+ $service->setDi($di);
+ $result = $service->clearPendingMessages();
+ expect($result)->toBeTrue();
+});
diff --git a/src/modules/Theme/Api/Admin.php b/src/modules/Theme/Api/Admin.php
index 7723531a8..3047a3191 100644
--- a/src/modules/Theme/Api/Admin.php
+++ b/src/modules/Theme/Api/Admin.php
@@ -22,7 +22,7 @@ class Admin extends \Api_Abstract
*/
public function get_list($data): array
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('theme', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('theme', 'view');
$themes = $this->getService()->getThemes();
@@ -34,7 +34,7 @@ class Admin extends \Api_Abstract
*/
public function get_admin_list($data): array
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('theme', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('theme', 'view');
$themes = $this->getService()->getThemes(false);
@@ -46,7 +46,7 @@ class Admin extends \Api_Abstract
*/
public function get_current(array $data): array
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('theme', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('theme', 'view');
if ($this->isInvalidClientParameter($data['client'] ?? null)) {
throw new \FOSSBilling\InformationException('Invalid "client" parameter.');
@@ -81,7 +81,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['code' => 'Theme code was not passed'])]
public function get($data)
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('theme', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('theme', 'view');
return $this->getService()->loadTheme($data['code']);
}
@@ -92,11 +92,11 @@ class Admin extends \Api_Abstract
#[RequiredParams(['code' => 'Theme code was not passed'])]
public function select($data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('theme', 'manage');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('theme', 'manage');
$theme = $this->getService()->getTheme($data['code']);
- $systemService = $this->di['mod_service']('system');
+ $systemService = $this->getDi()['mod_service']('system');
if ($theme->isAdminAreaTheme()) {
$systemService->setParamValue('admin_theme', $data['code']);
} else {
@@ -106,7 +106,7 @@ class Admin extends \Api_Abstract
// Clear theme cache so subsequent calls get the updated theme
\Box\Mod\Theme\Service::clearThemeCache();
- $this->di['logger']->info('Changed default theme');
+ $this->getDi()['logger']->info('Changed default theme');
return true;
}
@@ -117,7 +117,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['code' => 'Theme code was not passed', 'preset' => 'Preset name is missing'])]
public function preset_delete($data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('theme', 'manage');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('theme', 'manage');
$service = $this->getService();
@@ -133,7 +133,7 @@ class Admin extends \Api_Abstract
#[RequiredParams(['code' => 'Theme code was not passed', 'preset' => 'Preset name is missing'])]
public function preset_select($data): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('theme', 'manage');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('theme', 'manage');
$service = $this->getService();
$theme = $service->getTheme($data['code']);
diff --git a/src/modules/Theme/Service.php b/src/modules/Theme/Service.php
index 4fe0c3384..0353df25d 100644
--- a/src/modules/Theme/Service.php
+++ b/src/modules/Theme/Service.php
@@ -35,7 +35,7 @@ class Service implements InjectionAwareInterface
private static ?string $adminThemeCache = null;
/**
* In-request cache for the current client theme name.
- * This cache is used to avoid repeated lookups during a single request.
+ * This cache is used to store theme information during a single request.
* It is cleared whenever theme settings are changed by calling clearThemeCache().
*/
private static ?string $clientThemeCache = null;
@@ -442,18 +442,20 @@ class Service implements InjectionAwareInterface
public function getCurrentRouteTheme(): string
{
// Runtime check for admin area - uses index.php defined constant
- $isAdmin = defined('ADMIN_AREA') && ADMIN_AREA;
- if ($isAdmin) {
+ // @phpstan-ignore if.alwaysTrue
+ if (ADMIN_AREA) {
return $this->getCurrentAdminAreaTheme()['code'];
}
+ // @phpstan-ignore deadCode.unreachable
return $this->getCurrentClientAreaTheme()->getName();
}
public function getDefaultMarkdownAttributes(): array
{
// Runtime check for admin area - uses index.php defined constant
- $isAdmin = defined('ADMIN_AREA') && ADMIN_AREA;
+ $isAdmin = ADMIN_AREA;
+ // @phpstan-ignore if.alwaysTrue
if ($isAdmin) {
$config = $this->getThemeConfig(false);
} else {
diff --git a/src/modules/Theme/tests/Unit/Api/AdminTest.php b/src/modules/Theme/tests/Unit/Api/AdminTest.php
new file mode 100644
index 000000000..d0c33ba0d
--- /dev/null
+++ b/src/modules/Theme/tests/Unit/Api/AdminTest.php
@@ -0,0 +1,184 @@
+setDi($di);
+ $getDi = $api->getDi();
+ expect($getDi)->toBe($di);
+});
+
+test('testGetList', function (): void {
+ $api = new Admin();
+ $systemServiceMock = Mockery::mock(Box\Mod\Theme\Service::class);
+ $systemServiceMock->shouldReceive('getThemes')
+ ->atLeast()
+ ->once()
+ ->andReturn([]);
+
+ $api->setService($systemServiceMock);
+
+ $result = $api->get_list([]);
+ expect($result)->toBeArray();
+});
+
+test('testGet', function (): void {
+ $api = new Admin();
+ $data = [
+ 'code' => 'themeCode',
+ ];
+
+ $systemServiceMock = Mockery::mock(Box\Mod\Theme\Service::class);
+ $systemServiceMock->shouldReceive('loadTheme')
+ ->atLeast()
+ ->once()
+ ->andReturn([]);
+
+ $di = container();
+ $api->setDi($di);
+ $api->setService($systemServiceMock);
+
+ $result = $api->get($data);
+ expect($result)->toBeArray();
+});
+
+test('testSelectNotAdminTheme', function (): void {
+ $api = new Admin();
+ $data = [
+ 'code' => 'pjw',
+ ];
+
+ $themeMock = Mockery::mock(Box\Mod\Theme\Model\Theme::class);
+ $themeMock->shouldReceive('isAdminAreaTheme')
+ ->atLeast()
+ ->once()
+ ->andReturn(false);
+
+ $serviceMock = Mockery::mock(Box\Mod\Theme\Service::class);
+ $serviceMock->shouldReceive('getTheme')
+ ->atLeast()
+ ->once()
+ ->andReturn($themeMock);
+
+ $systemServiceMock = Mockery::mock(Box\Mod\System\Service::class);
+ $systemServiceMock->shouldReceive('setParamValue')
+ ->with('theme', Mockery::any());
+ $staffServiceMock = Mockery::mock(Box\Mod\Staff\Service::class)->shouldIgnoreMissing();
+ $staffServiceMock->shouldReceive('checkPermissionsAndThrowException')
+ ->atLeast()
+ ->once()
+ ->with('theme', 'manage');
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn (string $name = ''): Mockery\MockInterface => strtolower($name) === 'staff' ? $staffServiceMock : $systemServiceMock);
+ $api->setDi($di);
+ $api->setService($serviceMock);
+
+ $result = $api->select($data);
+ expect($result)->toBeTrue();
+});
+
+test('testSelectAdminTheme', function (): void {
+ $api = new Admin();
+ $data = [
+ 'code' => 'pjw',
+ ];
+
+ $themeMock = Mockery::mock(Box\Mod\Theme\Model\Theme::class);
+ $themeMock->shouldReceive('isAdminAreaTheme')
+ ->atLeast()
+ ->once()
+ ->andReturn(true);
+
+ $serviceMock = Mockery::mock(Box\Mod\Theme\Service::class);
+ $serviceMock->shouldReceive('getTheme')
+ ->atLeast()
+ ->once()
+ ->andReturn($themeMock);
+
+ $systemServiceMock = Mockery::mock(Box\Mod\System\Service::class);
+ $systemServiceMock->shouldReceive('setParamValue')
+ ->with('admin_theme', Mockery::any());
+ $staffServiceMock = Mockery::mock(Box\Mod\Staff\Service::class)->shouldIgnoreMissing();
+ $staffServiceMock->shouldReceive('checkPermissionsAndThrowException')
+ ->atLeast()
+ ->once()
+ ->with('theme', 'manage');
+
+ $di = container();
+ $di['mod_service'] = $di->protect(fn (string $name = ''): Mockery\MockInterface => strtolower($name) === 'staff' ? $staffServiceMock : $systemServiceMock);
+ $api->setDi($di);
+ $api->setService($serviceMock);
+
+ $result = $api->select($data);
+ expect($result)->toBeTrue();
+});
+
+test('testPresetDelete', function (): void {
+ $api = new Admin();
+ $data = [
+ 'code' => 'themeCode',
+ 'preset' => 'themePreset',
+ ];
+
+ $themeMock = Mockery::mock(Box\Mod\Theme\Model\Theme::class);
+
+ $serviceMock = Mockery::mock(Box\Mod\Theme\Service::class);
+ $serviceMock->shouldReceive('getTheme')
+ ->atLeast()
+ ->once()
+ ->andReturn($themeMock);
+ $serviceMock->shouldReceive('deletePreset')
+ ->atLeast()
+ ->once();
+
+ $di = container();
+ $api->setDi($di);
+ $api->setService($serviceMock);
+
+ $result = $api->preset_delete($data);
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+});
+
+test('testPresetSelect', function (): void {
+ $api = new Admin();
+ $data = [
+ 'code' => 'themeCode',
+ 'preset' => 'themePreset',
+ ];
+
+ $themeMock = Mockery::mock(Box\Mod\Theme\Model\Theme::class);
+
+ $serviceMock = Mockery::mock(Box\Mod\Theme\Service::class);
+ $serviceMock->shouldReceive('getTheme')
+ ->atLeast()
+ ->once()
+ ->andReturn($themeMock);
+ $serviceMock->shouldReceive('setCurrentThemePreset')
+ ->atLeast()
+ ->once();
+
+ $di = container();
+ $api->setDi($di);
+
+ $api->setService($serviceMock);
+
+ $result = $api->preset_select($data);
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+});
diff --git a/src/modules/Theme/tests/Unit/Controller/AdminTest.php b/src/modules/Theme/tests/Unit/Controller/AdminTest.php
new file mode 100644
index 000000000..f34837bd5
--- /dev/null
+++ b/src/modules/Theme/tests/Unit/Controller/AdminTest.php
@@ -0,0 +1,103 @@
+setDi($di);
+ $result = $controller->getDi();
+ expect($result)->toEqual($di);
+});
+
+test('register configures routes', function (): void {
+ $controller = new Box\Mod\Theme\Controller\Admin();
+ $boxAppMock = Mockery::mock('\Box_App');
+ $boxAppMock->shouldReceive('get')
+ ->atLeast()
+ ->once();
+ $boxAppMock->shouldReceive('post')
+ ->atLeast()
+ ->once();
+
+ $controller->register($boxAppMock);
+});
+
+test('getTheme renders theme preset', function (): void {
+ $controller = new Box\Mod\Theme\Controller\Admin();
+ $di = container();
+
+ $boxAppMock = Mockery::mock('\Box_App');
+ $boxAppMock->shouldReceive('render')
+ ->atLeast()
+ ->once()
+ ->andReturn('Rendering ...');
+
+ // Create theme mock first
+ $themeMock = Mockery::mock(Box\Mod\Theme\Model\Theme::class);
+ $themeMock->shouldReceive('getName')
+ ->atLeast()
+ ->once()
+ ->andReturn('test_theme');
+ $themeMock->shouldReceive('getUploadedAssets')
+ ->atLeast()
+ ->once()
+ ->andReturn([]);
+ $themeMock->shouldReceive('isAssetsPathWritable')
+ ->atLeast()
+ ->once()
+ ->andReturn(false);
+ $themeMock->shouldReceive('getSettingsPageHtml')
+ ->zeroOrMoreTimes()
+ ->andReturn('');
+ $themeMock->shouldReceive('getPathAssets')
+ ->atLeast()
+ ->once()
+ ->andReturn('/tmp/test');
+
+ // Create service mock that uses theme mock
+ $themeServiceMock = Mockery::mock(Box\Mod\Theme\Service::class);
+ $themeServiceMock->shouldReceive('getTheme')
+ ->atLeast()
+ ->once()
+ ->andReturn($themeMock);
+ $themeServiceMock->shouldReceive('getCurrentThemePreset')
+ ->atLeast()
+ ->once()
+ ->andReturn('default');
+ $themeServiceMock->shouldReceive('getThemeSettings')
+ ->atLeast()
+ ->once()
+ ->andReturn([]);
+ $themeServiceMock->shouldReceive('renderThemeSettingsPageHtml')
+ ->atLeast()
+ ->once()
+ ->andReturn('');
+ $themeServiceMock->shouldReceive('getThemePresets')
+ ->atLeast()
+ ->once()
+ ->andReturn([]);
+
+ // Create a mod mock that returns the service via getService()
+ $modMock = Mockery::mock(FOSSBilling\Module::class);
+ $modMock->shouldReceive('getService')
+ ->atLeast()
+ ->once()
+ ->andReturn($themeServiceMock);
+
+ $di['db'] = $this->createStub('Box_Database');
+ $di['is_admin_logged'] = true;
+ $di['mod'] = $di->protect(fn () => $modMock);
+ $controller->setDi($di);
+ $controller->get_theme($boxAppMock, 'huraga');
+});
diff --git a/src/modules/Theme/tests/Unit/Model/ThemeTest.php b/src/modules/Theme/tests/Unit/Model/ThemeTest.php
new file mode 100644
index 000000000..2c05ba772
--- /dev/null
+++ b/src/modules/Theme/tests/Unit/Model/ThemeTest.php
@@ -0,0 +1,101 @@
+getName())->toEqual($existingTheme);
+});
+
+test('not existing theme', function (): void {
+ $themeName = 'not existing theme';
+ expect(function () use ($themeName): void {
+ new Box\Mod\Theme\Model\Theme($themeName);
+ })->toThrow(FOSSBilling\Exception::class, "Theme '{$themeName}' does not exist.");
+});
+
+test('is admin area theme', function () use ($existingTheme): void {
+ $theme = new Box\Mod\Theme\Model\Theme($existingTheme);
+ $result = $theme->isAdminAreaTheme();
+ expect($result)->toBeBool();
+});
+
+test('is assets path writable', function () use ($existingTheme): void {
+ $theme = new Box\Mod\Theme\Model\Theme($existingTheme);
+ $result = $theme->isAssetsPathWritable();
+ expect($result)->toBeBool();
+});
+
+test('get uploaded assets', function () use ($existingTheme): void {
+ $theme = new Box\Mod\Theme\Model\Theme($existingTheme);
+ $result = $theme->getUploadedAssets();
+ expect($result)->toBeArray();
+});
+
+test('get settings page html', function () use ($existingTheme): void {
+ $theme = new Box\Mod\Theme\Model\Theme($existingTheme);
+ $result = $theme->getSettingsPageHtml();
+ expect($result)->toBeString();
+});
+
+test('get presets from settings data file', function () use ($existingTheme): void {
+ $theme = new Box\Mod\Theme\Model\Theme($existingTheme);
+ $result = $theme->getPresetsFromSettingsDataFile();
+ expect($result)->toBeArray();
+});
+
+test('get current preset', function () use ($existingTheme): void {
+ $theme = new Box\Mod\Theme\Model\Theme($existingTheme);
+ $result = $theme->getCurrentPreset();
+ expect($result)->toBeString();
+});
+
+test('get preset from settings data file', function () use ($existingTheme): void {
+ $theme = new Box\Mod\Theme\Model\Theme($existingTheme);
+ $result = $theme->getPresetFromSettingsDataFile('default');
+ expect($result)->toBeArray();
+});
+
+test('get url', function () use ($existingTheme): void {
+ $theme = new Box\Mod\Theme\Model\Theme($existingTheme);
+ $result = $theme->getUrl();
+ expect($result)->toBeString();
+});
+
+test('get path config', function () use ($existingTheme): void {
+ $theme = new Box\Mod\Theme\Model\Theme($existingTheme);
+ $result = $theme->getPathConfig();
+ expect($result)->toBeString();
+ expect(str_contains($result, 'config'))->toBeTrue();
+});
+
+test('get path assets', function () use ($existingTheme): void {
+ $theme = new Box\Mod\Theme\Model\Theme($existingTheme);
+ $result = $theme->getPathAssets();
+ expect($result)->toBeString();
+ expect(str_contains($result, 'assets'))->toBeTrue();
+});
+
+test('get path html', function () use ($existingTheme): void {
+ $theme = new Box\Mod\Theme\Model\Theme($existingTheme);
+ $result = $theme->getPathHtml();
+ expect($result)->toBeString();
+ expect(str_contains($result, 'html'))->toBeTrue();
+});
+
+test('get path settings data file', function () use ($existingTheme): void {
+ $theme = new Box\Mod\Theme\Model\Theme($existingTheme);
+ $result = $theme->getPathSettingsDataFile();
+ expect($result)->toBeString();
+ expect(str_contains($result, 'settings_data.json'))->toBeTrue();
+});
diff --git a/src/modules/Theme/tests/Unit/ServiceTest.php b/src/modules/Theme/tests/Unit/ServiceTest.php
new file mode 100644
index 000000000..fc83e088f
--- /dev/null
+++ b/src/modules/Theme/tests/Unit/ServiceTest.php
@@ -0,0 +1,424 @@
+shouldIgnoreMissing();
+ $em->shouldReceive('getRepository')
+ ->byDefault()
+ ->andReturn($repository);
+ $di['em'] = $em;
+
+ return $di;
+}
+
+test('getDi returns the dependency injection container', function (): void {
+ $service = new Service();
+ $di = container();
+ $service->setDi($di);
+ $getDi = $service->getDi();
+ expect($getDi)->toBe($di);
+});
+
+test('getTheme returns a Theme model instance', function (): void {
+ $service = new Service();
+ $result = $service->getTheme('huraga');
+ expect($result)->toBeInstanceOf(Model\Theme::class);
+});
+
+test('getCurrentThemePreset sets current theme preset when empty', function (): void {
+ $service = new Service();
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+ $serviceMock->shouldReceive('setCurrentThemePreset')
+ ->atLeast()
+ ->once();
+
+ $repositoryMock = Mockery::mock(Box\Mod\Extension\Repository\ExtensionMetaRepository::class);
+ $repositoryMock->shouldReceive('findOneByExtensionAndScope')
+ ->atLeast()
+ ->once()
+ ->with('mod_theme', 'default', 'preset', 'current')
+ ->andReturn(null);
+
+ $themeMock = Mockery::mock(Model\Theme::class);
+ $themeMock->shouldReceive('getCurrentPreset')
+ ->atLeast()
+ ->once()
+ ->andReturn('CurrentPresetString');
+ $themeMock->shouldReceive('getName')
+ ->atLeast()
+ ->once()
+ ->andReturn('default');
+
+ $di = themeContainerWithRepository($repositoryMock);
+ $di['theme'] = $di->protect(fn (): Mockery\MockInterface => $themeMock);
+
+ $serviceMock->setDi($di);
+ $result = $serviceMock->getCurrentThemePreset($themeMock);
+ expect($result)->toBeString();
+});
+
+test('setCurrentThemePreset updates theme preset', function (): void {
+ $service = new Service();
+ $repositoryMock = Mockery::mock(Box\Mod\Extension\Repository\ExtensionMetaRepository::class);
+ $repositoryMock->shouldReceive('findOneByExtensionAndScope')
+ ->atLeast()
+ ->once()
+ ->andReturn(null);
+ $emMock = Mockery::mock(Doctrine\ORM\EntityManagerInterface::class)->shouldIgnoreMissing();
+ $emMock->shouldReceive('persist')
+ ->atLeast()
+ ->once()
+ ->with(Mockery::type(ExtensionMeta::class));
+ $emMock->shouldReceive('flush')
+ ->atLeast()
+ ->once();
+
+ $themeMock = Mockery::mock(Model\Theme::class);
+ $themeMock->shouldReceive('getName')
+ ->atLeast()
+ ->once()
+ ->andReturn('default');
+
+ $di = themeContainerWithRepository($repositoryMock, $emMock);
+ $di['theme'] = $di->protect(fn (): Mockery\MockInterface => $themeMock);
+
+ $service->setDi($di);
+ $result = $service->setCurrentThemePreset($themeMock, 'dark_blue');
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+});
+
+test('deletePreset removes a theme preset', function (): void {
+ $service = new Service();
+ $repositoryMock = Mockery::mock(Box\Mod\Extension\Repository\ExtensionMetaRepository::class);
+ $repositoryMock->shouldReceive('deleteByExtensionAndScope')
+ ->twice()
+ ->andReturn(1);
+
+ $themeMock = Mockery::mock(Model\Theme::class);
+ $themeMock->shouldReceive('getName')
+ ->atLeast()
+ ->once()
+ ->andReturn('default');
+
+ $di = themeContainerWithRepository($repositoryMock);
+ $di['theme'] = $di->protect(fn (): Mockery\MockInterface => $themeMock);
+
+ $service->setDi($di);
+ $result = $service->deletePreset($themeMock, 'dark_blue');
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+});
+
+test('getThemePresets returns available presets', function (): void {
+ $service = new Service();
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+ $serviceMock->shouldReceive('updateSettings')
+ ->atLeast()
+ ->once();
+
+ $repositoryMock = Mockery::mock(Box\Mod\Extension\Repository\ExtensionMetaRepository::class);
+ $repositoryMock->shouldReceive('findByExtensionAndScope')
+ ->atLeast()
+ ->once()
+ ->andReturn([]);
+
+ $themeMock = Mockery::mock(Model\Theme::class);
+ $themeMock->shouldReceive('getName')
+ ->atLeast()
+ ->once()
+ ->andReturn('default');
+
+ $corePresets = [
+ 'default' => [],
+ 'red_black' => [],
+ ];
+ $themeMock->shouldReceive('getPresetsFromSettingsDataFile')
+ ->atLeast()
+ ->once()
+ ->andReturn($corePresets);
+
+ $di = themeContainerWithRepository($repositoryMock);
+ $di['theme'] = $di->protect(fn (): Mockery\MockInterface => $themeMock);
+
+ $serviceMock->setDi($di);
+ $result = $serviceMock->getThemePresets($themeMock, 'dark_blue');
+ expect($result)->toBeArray();
+
+ $expected = [
+ 'default' => 'default',
+ 'red_black' => 'red_black',
+ ];
+ expect($result)->toBe($expected);
+});
+
+test('getThemePresets returns default when theme has no settings data file', function (): void {
+ $service = new Service();
+ $repositoryMock = Mockery::mock(Box\Mod\Extension\Repository\ExtensionMetaRepository::class);
+ $repositoryMock->shouldReceive('findByExtensionAndScope')
+ ->atLeast()
+ ->once()
+ ->andReturn([]);
+
+ $themeMock = Mockery::mock(Model\Theme::class);
+ $themeMock->shouldReceive('getName')
+ ->atLeast()
+ ->once()
+ ->andReturn('default');
+
+ $themeMock->shouldReceive('getPresetsFromSettingsDataFile')
+ ->atLeast()
+ ->once()
+ ->andReturn([]);
+
+ $di = themeContainerWithRepository($repositoryMock);
+ $di['theme'] = $di->protect(fn (): Mockery\MockInterface => $themeMock);
+ $service->setDi($di);
+
+ $result = $service->getThemePresets($themeMock);
+ expect($result)->toBeArray();
+
+ $expected = [
+ 'Default' => 'Default',
+ ];
+ expect($result)->toBe($expected);
+});
+
+test('getThemeSettings returns theme settings', function (): void {
+ $service = new Service();
+ $extensionMetaModel = (new ExtensionMeta())->setMetaValue('{}');
+
+ $repositoryMock = Mockery::mock(Box\Mod\Extension\Repository\ExtensionMetaRepository::class);
+ $repositoryMock->shouldReceive('findOneByExtensionAndScope')
+ ->atLeast()
+ ->once()
+ ->andReturn($extensionMetaModel);
+
+ $themeMock = Mockery::mock(Model\Theme::class);
+ $themeMock->shouldReceive('getName')
+ ->atLeast()
+ ->once()
+ ->andReturn('default');
+
+ $di = themeContainerWithRepository($repositoryMock);
+
+ $service->setDi($di);
+ $result = $service->getThemeSettings($themeMock, 'default');
+ expect($result)->toBeArray();
+});
+
+test('getThemeSettings with empty presets returns empty array', function (): void {
+ $service = new Service();
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+ $serviceMock->shouldReceive('getCurrentThemePreset')
+ ->atLeast()
+ ->once()
+ ->andReturn('default');
+
+ $repositoryMock = Mockery::mock(Box\Mod\Extension\Repository\ExtensionMetaRepository::class);
+ $repositoryMock->shouldReceive('findOneByExtensionAndScope')
+ ->atLeast()
+ ->once()
+ ->andReturn(null);
+
+ $themeMock = Mockery::mock(Model\Theme::class);
+ $themeMock->shouldReceive('getName')
+ ->atLeast()
+ ->once()
+ ->andReturn('default');
+ $themeMock->shouldReceive('getPresetFromSettingsDataFile')
+ ->atLeast()
+ ->once()
+ ->andReturn([]);
+
+ $di = themeContainerWithRepository($repositoryMock);
+ $serviceMock->setDi($di);
+
+ $result = $serviceMock->getThemeSettings($themeMock);
+ expect($result)->toBeArray();
+ expect($result)->toBe([]);
+});
+
+test('updateSettings updates theme settings', function (): void {
+ $service = new Service();
+ $repositoryMock = Mockery::mock(Box\Mod\Extension\Repository\ExtensionMetaRepository::class);
+ $repositoryMock->shouldReceive('findOneByExtensionAndScope')
+ ->atLeast()
+ ->once()
+ ->andReturn(null);
+ $emMock = Mockery::mock(Doctrine\ORM\EntityManagerInterface::class)->shouldIgnoreMissing();
+ $emMock->shouldReceive('persist')
+ ->atLeast()
+ ->once()
+ ->with(Mockery::type(ExtensionMeta::class));
+ $emMock->shouldReceive('flush')
+ ->atLeast()
+ ->once();
+
+ $themeMock = Mockery::mock(Model\Theme::class);
+ $themeMock->shouldReceive('getName')
+ ->atLeast()
+ ->once()
+ ->andReturn('default');
+
+ $di = themeContainerWithRepository($repositoryMock, $emMock);
+
+ $service->setDi($di);
+ $params = [];
+ $result = $service->updateSettings($themeMock, 'default', $params);
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+});
+
+test('regenerateThemeSettingsDataFile regenerates settings file', function (): void {
+ $service = new Service();
+ $tmpDir = sys_get_temp_dir() . '/fb_test_' . uniqid();
+ mkdir($tmpDir, 0o755, true);
+ $testFile = $tmpDir . '/test_settings.json';
+
+ $presets = [
+ 'default' => 'Defaults',
+ 'red_black' => 'Red Black',
+ ];
+
+ // Create theme mock
+ $themeMock = Mockery::mock(Model\Theme::class);
+ $themeMock->shouldReceive('getName')
+ ->andReturn('test_theme');
+ $themeMock->shouldReceive('getPresetsFromSettingsDataFile')
+ ->andReturn($presets);
+ $themeMock->shouldReceive('getPathSettingsDataFile')
+ ->andReturn($testFile);
+
+ // Create service with mock filesystem injected into the readonly property.
+ $filesystemMock = Mockery::mock(Symfony\Component\Filesystem\Filesystem::class);
+ $filesystemMock->shouldReceive('dumpFile')
+ ->atLeast()
+ ->once();
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+ injectMockFilesystem($serviceMock, $filesystemMock);
+ $serviceMock->shouldReceive('getThemePresets')
+ ->with($themeMock)
+ ->andReturn($presets);
+ $serviceMock->shouldReceive('getThemeSettings')
+ ->with($themeMock, Mockery::any())
+ ->andReturn([]);
+ $serviceMock->shouldReceive('getCurrentThemePreset')
+ ->with($themeMock)
+ ->andReturn('default');
+
+ $di = container();
+ $serviceMock->setDi($di);
+
+ $result = $serviceMock->regenerateThemeSettingsDataFile($themeMock);
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+
+ // Cleanup
+ if (file_exists($testFile)) {
+ unlink($testFile);
+ }
+ if (is_dir($tmpDir)) {
+ rmdir($tmpDir);
+ }
+});
+
+test('regenerateThemeCssAndJsFiles handles empty files', function (): void {
+ $service = new Service();
+ $themeMock = Mockery::mock(Model\Theme::class);
+
+ $tmpDir = sys_get_temp_dir() . '/fb_test_assets_' . uniqid();
+ mkdir($tmpDir, 0o755, true);
+
+ $themeMock->shouldReceive('getPathAssets')
+ ->atLeast()
+ ->once()
+ ->andReturn($tmpDir . '/');
+
+ $di = container();
+ $service->setDi($di);
+
+ $result = $service->regenerateThemeCssAndJsFiles($themeMock, 'default', new Model_Admin());
+
+ // Clean up temp directory
+ if (is_dir($tmpDir)) {
+ rmdir($tmpDir);
+ }
+
+ expect($result)->toBeBool();
+ expect($result)->toBeTrue();
+});
+
+test('getCurrentAdminAreaTheme returns theme configuration', function (): void {
+ Service::clearThemeCache();
+ $service = new Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getCell')
+ ->atLeast()
+ ->once()
+ ->andReturn('');
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $service->setDi($di);
+
+ $result = $service->getCurrentAdminAreaTheme();
+ expect($result)->toBeArray();
+});
+
+test('getCurrentClientAreaTheme returns Theme model', function (): void {
+ $service = new Service();
+ $themeMock = Mockery::mock(Model\Theme::class);
+
+ $serviceMock = Mockery::mock(Service::class)->makePartial();
+
+ $serviceMock->shouldReceive('getCurrentClientAreaThemeCode')
+ ->atLeast()
+ ->once();
+
+ $serviceMock->shouldReceive('getTheme')
+ ->atLeast()
+ ->once()
+ ->andReturn($themeMock);
+
+ $result = $serviceMock->getCurrentClientAreaTheme();
+ expect($result)->toBeInstanceOf(Model\Theme::class);
+});
+
+test('getCurrentClientAreaThemeCode returns theme code', function (): void {
+ Service::clearThemeCache();
+ $service = new Service();
+ $dbMock = Mockery::mock('\Box_Database');
+ $dbMock->shouldReceive('getCell')
+ ->atLeast()
+ ->once()
+ ->andReturn('huraga');
+
+ $di = container();
+ $di['db'] = $dbMock;
+ $service->setDi($di);
+
+ $result = $service->getCurrentClientAreaThemeCode();
+ expect($result)->toBeString();
+ expect($result)->toBe('huraga');
+});
diff --git a/src/modules/Widgets/Api/Admin.php b/src/modules/Widgets/Api/Admin.php
index a646fdd9f..0ce32c0ed 100644
--- a/src/modules/Widgets/Api/Admin.php
+++ b/src/modules/Widgets/Api/Admin.php
@@ -20,7 +20,7 @@ class Admin extends \Api_Abstract
*/
public function list(): array
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('widgets', 'view');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('widgets', 'view');
return $this->getService()->getWidgetList();
}
@@ -31,7 +31,7 @@ class Admin extends \Api_Abstract
*/
public function rebuild(): bool
{
- $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('widgets', 'manage');
+ $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('widgets', 'manage');
$service = $this->getService();
$service->invalidateCache();
diff --git a/src/themes/admin_default/assets/js/fossbilling.js b/src/themes/admin_default/assets/js/fossbilling.js
index e4e7c45da..fbc30134b 100644
--- a/src/themes/admin_default/assets/js/fossbilling.js
+++ b/src/themes/admin_default/assets/js/fossbilling.js
@@ -72,7 +72,6 @@ globalThis.FOSSBilling = Object.assign(globalThis.FOSSBilling || {}, {
}
});
- //===== Global ajax methods =====//
document.addEventListener('DOMContentLoaded', function() {
// Global error handler for unhandled Promise rejections (API-related only)
window.addEventListener('unhandledrejection', function(event) {
@@ -88,7 +87,6 @@ globalThis.FOSSBilling = Object.assign(globalThis.FOSSBilling || {}, {
FOSSBilling.backToTop = backToTop;
FOSSBilling.backToTop();
- //===== Form elements styling =====//
document.addEventListener("click", function(event) {
const target = event.target;
if (target.matches("div.msg span.close") || target.closest("div.msg span.close")) {
diff --git a/tests-legacy/bootstrap.php b/tests-legacy/bootstrap.php
deleted file mode 100644
index ff2402559..000000000
--- a/tests-legacy/bootstrap.php
+++ /dev/null
@@ -1,43 +0,0 @@
- new FOSSBilling\Validate());
-$di['tools'] = (fn (): FOSSBilling\Tools => new FOSSBilling\Tools());
-
-// Setup the autoloader
-$testsLoader = new AntCMS\AntLoader([
- 'mode' => 'filesystem',
-]);
-$testsLoader->addNamespace('', DIRECTORY_SEPARATOR . 'library', 'psr0');
-$testsLoader->register();
diff --git a/tests-legacy/fixtures/admins.xml b/tests-legacy/fixtures/admins.xml
deleted file mode 100644
index caf6cc5d2..000000000
--- a/tests-legacy/fixtures/admins.xml
+++ /dev/null
@@ -1,10 +0,0 @@
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/tests-legacy/fixtures/currencies.xml b/tests-legacy/fixtures/currencies.xml
deleted file mode 100644
index 9e942d163..000000000
--- a/tests-legacy/fixtures/currencies.xml
+++ /dev/null
@@ -1,5 +0,0 @@
-
-
-
-
-
diff --git a/tests-legacy/fixtures/emails.xml b/tests-legacy/fixtures/emails.xml
deleted file mode 100644
index 1297fbbb8..000000000
--- a/tests-legacy/fixtures/emails.xml
+++ /dev/null
@@ -1,10 +0,0 @@
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/tests-legacy/fixtures/example.xml b/tests-legacy/fixtures/example.xml
deleted file mode 100644
index 3c75c68be..000000000
--- a/tests-legacy/fixtures/example.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
-
-
-
-
\ No newline at end of file
diff --git a/tests-legacy/fixtures/extension_news.xml b/tests-legacy/fixtures/extension_news.xml
deleted file mode 100644
index 160c127c4..000000000
--- a/tests-legacy/fixtures/extension_news.xml
+++ /dev/null
@@ -1,7 +0,0 @@
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/tests-legacy/fixtures/extensions.xml b/tests-legacy/fixtures/extensions.xml
deleted file mode 100644
index d8cc39fc2..000000000
--- a/tests-legacy/fixtures/extensions.xml
+++ /dev/null
@@ -1,5 +0,0 @@
-
-
-
-
-
diff --git a/tests-legacy/fixtures/gateway_Custom.xml b/tests-legacy/fixtures/gateway_Custom.xml
deleted file mode 100644
index 72c791ca6..000000000
--- a/tests-legacy/fixtures/gateway_Custom.xml
+++ /dev/null
@@ -1,13 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/tests-legacy/fixtures/gateway_PayPal.xml b/tests-legacy/fixtures/gateway_PayPal.xml
deleted file mode 100644
index 846dc6934..000000000
--- a/tests-legacy/fixtures/gateway_PayPal.xml
+++ /dev/null
@@ -1,16 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/tests-legacy/fixtures/gateway_TwoCheckout.xml b/tests-legacy/fixtures/gateway_TwoCheckout.xml
deleted file mode 100644
index 3f8fc8fde..000000000
--- a/tests-legacy/fixtures/gateway_TwoCheckout.xml
+++ /dev/null
@@ -1,13 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/tests-legacy/fixtures/initial.xml b/tests-legacy/fixtures/initial.xml
deleted file mode 100644
index 19cf61745..000000000
--- a/tests-legacy/fixtures/initial.xml
+++ /dev/null
@@ -1,36 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/tests-legacy/fixtures/licensing-server.xml b/tests-legacy/fixtures/licensing-server.xml
deleted file mode 100644
index a04223f4e..000000000
--- a/tests-legacy/fixtures/licensing-server.xml
+++ /dev/null
@@ -1,10 +0,0 @@
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/tests-legacy/fixtures/mod_affiliate.xml b/tests-legacy/fixtures/mod_affiliate.xml
deleted file mode 100644
index f3b15fef6..000000000
--- a/tests-legacy/fixtures/mod_affiliate.xml
+++ /dev/null
@@ -1,8 +0,0 @@
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/tests-legacy/fixtures/mod_api.xml b/tests-legacy/fixtures/mod_api.xml
deleted file mode 100644
index 1ceb19d42..000000000
--- a/tests-legacy/fixtures/mod_api.xml
+++ /dev/null
@@ -1,5 +0,0 @@
-
-
-
-
-
\ No newline at end of file
diff --git a/tests-legacy/fixtures/mod_cart.xml b/tests-legacy/fixtures/mod_cart.xml
deleted file mode 100644
index 8089ef89b..000000000
--- a/tests-legacy/fixtures/mod_cart.xml
+++ /dev/null
@@ -1,93 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/tests-legacy/fixtures/mod_client.xml b/tests-legacy/fixtures/mod_client.xml
deleted file mode 100644
index 64eed14fb..000000000
--- a/tests-legacy/fixtures/mod_client.xml
+++ /dev/null
@@ -1,9 +0,0 @@
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/tests-legacy/fixtures/mod_example.xml b/tests-legacy/fixtures/mod_example.xml
deleted file mode 100644
index 782495a48..000000000
--- a/tests-legacy/fixtures/mod_example.xml
+++ /dev/null
@@ -1,14 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/tests-legacy/fixtures/mod_formbuilder.xml b/tests-legacy/fixtures/mod_formbuilder.xml
deleted file mode 100644
index f3fb2fc76..000000000
--- a/tests-legacy/fixtures/mod_formbuilder.xml
+++ /dev/null
@@ -1,20 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/tests-legacy/fixtures/mod_hook.xml b/tests-legacy/fixtures/mod_hook.xml
deleted file mode 100644
index 281c8825d..000000000
--- a/tests-legacy/fixtures/mod_hook.xml
+++ /dev/null
@@ -1,10 +0,0 @@
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/tests-legacy/fixtures/mod_invoice.xml b/tests-legacy/fixtures/mod_invoice.xml
deleted file mode 100644
index 4f6954f69..000000000
--- a/tests-legacy/fixtures/mod_invoice.xml
+++ /dev/null
@@ -1,23 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/tests-legacy/fixtures/mod_massmailer.xml b/tests-legacy/fixtures/mod_massmailer.xml
deleted file mode 100644
index 81cb27029..000000000
--- a/tests-legacy/fixtures/mod_massmailer.xml
+++ /dev/null
@@ -1,11 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/tests-legacy/fixtures/mod_notification.xml b/tests-legacy/fixtures/mod_notification.xml
deleted file mode 100644
index 1c005b5f7..000000000
--- a/tests-legacy/fixtures/mod_notification.xml
+++ /dev/null
@@ -1,9 +0,0 @@
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/tests-legacy/fixtures/mod_order.xml b/tests-legacy/fixtures/mod_order.xml
deleted file mode 100644
index 0840cf420..000000000
--- a/tests-legacy/fixtures/mod_order.xml
+++ /dev/null
@@ -1,10 +0,0 @@
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/tests-legacy/fixtures/mod_page.xml b/tests-legacy/fixtures/mod_page.xml
deleted file mode 100644
index 1ceb19d42..000000000
--- a/tests-legacy/fixtures/mod_page.xml
+++ /dev/null
@@ -1,5 +0,0 @@
-
-
-
-
-
\ No newline at end of file
diff --git a/tests-legacy/fixtures/mod_partner.xml b/tests-legacy/fixtures/mod_partner.xml
deleted file mode 100644
index be6424454..000000000
--- a/tests-legacy/fixtures/mod_partner.xml
+++ /dev/null
@@ -1,18 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/tests-legacy/fixtures/mod_redirect.xml b/tests-legacy/fixtures/mod_redirect.xml
deleted file mode 100644
index 64eed14fb..000000000
--- a/tests-legacy/fixtures/mod_redirect.xml
+++ /dev/null
@@ -1,9 +0,0 @@
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/tests-legacy/fixtures/mod_servicedomain.xml b/tests-legacy/fixtures/mod_servicedomain.xml
deleted file mode 100644
index 4150462a3..000000000
--- a/tests-legacy/fixtures/mod_servicedomain.xml
+++ /dev/null
@@ -1,26 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/tests-legacy/fixtures/mod_support.xml b/tests-legacy/fixtures/mod_support.xml
deleted file mode 100644
index db5002216..000000000
--- a/tests-legacy/fixtures/mod_support.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/tests-legacy/fixtures/mod_theme.xml b/tests-legacy/fixtures/mod_theme.xml
deleted file mode 100644
index 5de80248b..000000000
--- a/tests-legacy/fixtures/mod_theme.xml
+++ /dev/null
@@ -1,9 +0,0 @@
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/tests-legacy/fixtures/orders.xml b/tests-legacy/fixtures/orders.xml
deleted file mode 100644
index a54854932..000000000
--- a/tests-legacy/fixtures/orders.xml
+++ /dev/null
@@ -1,84 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/tests-legacy/fixtures/serviceboxbillinglicense.xml b/tests-legacy/fixtures/serviceboxbillinglicense.xml
deleted file mode 100644
index 6d8d09770..000000000
--- a/tests-legacy/fixtures/serviceboxbillinglicense.xml
+++ /dev/null
@@ -1,15 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/tests-legacy/fixtures/servicelicense.xml b/tests-legacy/fixtures/servicelicense.xml
deleted file mode 100644
index 486f1d0a0..000000000
--- a/tests-legacy/fixtures/servicelicense.xml
+++ /dev/null
@@ -1,15 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/tests-legacy/fixtures/services.xml b/tests-legacy/fixtures/services.xml
deleted file mode 100644
index ee8ce6e79..000000000
--- a/tests-legacy/fixtures/services.xml
+++ /dev/null
@@ -1,47 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/tests-legacy/fixtures/settings.xml b/tests-legacy/fixtures/settings.xml
deleted file mode 100644
index b3a1d4f39..000000000
--- a/tests-legacy/fixtures/settings.xml
+++ /dev/null
@@ -1,23 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/tests-legacy/fixtures/transactions.xml b/tests-legacy/fixtures/transactions.xml
deleted file mode 100644
index cc0179f05..000000000
--- a/tests-legacy/fixtures/transactions.xml
+++ /dev/null
@@ -1,49 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/tests-legacy/includes/ApiTestCase.php b/tests-legacy/includes/ApiTestCase.php
deleted file mode 100644
index 24406e3b3..000000000
--- a/tests-legacy/includes/ApiTestCase.php
+++ /dev/null
@@ -1,22 +0,0 @@
-di = $di;
- $this->di['loggedin_client'] = $this->di['db']->load('Client', 1);
- $this->di['loggedin_admin'] = $this->di['db']->load('Admin', 1);
- $this->session = $this->di['session'];
- $this->api_guest = $this->di['api_guest'];
- $this->api_client = $this->di['api_client'];
- $this->api_admin = $this->di['api_admin'];
- }
-}
diff --git a/tests-legacy/includes/BBDatabaseTestCase.php b/tests-legacy/includes/BBDatabaseTestCase.php
deleted file mode 100644
index e96916609..000000000
--- a/tests-legacy/includes/BBDatabaseTestCase.php
+++ /dev/null
@@ -1,48 +0,0 @@
-conn === null) {
- if (self::$pdo == null) {
- self::$pdo = new PDO('mysql:dbname=' . FB_DB_NAME . ';host=127.0.0.1;port=' . FB_DB_PORT, FB_DB_USER, FB_DB_PASSWORD);
- }
- $this->conn = $this->createDefaultDBConnection(self::$pdo, FB_DB_NAME);
- }
-
- return $this->conn;
- }
-
- /**
- * Returns the seed files folder path.
- *
- * @return string
- */
- public function getSeedFilesPath()
- {
- if ($this->_seedFilesPath == null) {
- $this->_seedFilesPath = PATH_TESTS . '/fixtures';
- }
-
- return rtrim((string) $this->_seedFilesPath, '/') . '/';
- }
-
- /**
- * Retrieve from flat XML files data used to populate the database.
- *
- * @return PHPUnit_Extensions_Database_DataSet_IDataSet
- */
- protected function getDataSet()
- {
- return $this->createFlatXmlDataSet($this->getSeedFilesPath() . $this->_initialSeedFile);
- }
-}
diff --git a/tests-legacy/includes/BBDbApiTestCase.php b/tests-legacy/includes/BBDbApiTestCase.php
deleted file mode 100644
index b2e33882c..000000000
--- a/tests-legacy/includes/BBDbApiTestCase.php
+++ /dev/null
@@ -1,57 +0,0 @@
-getMockBuilder('Box_Update')
- ->onlyMethods(['isUpdateAvailable', 'getLatestVersion', 'performUpdate'])
- ->getMock();
- $updatedMock->expects($this->any())
- ->method('isUpdateAvailable')
- ->willReturn(true);
- $updatedMock->expects($this->any())
- ->method('getLatestVersion')
- ->willReturn('10.20.30');
- $updatedMock->expects($this->any())
- ->method('performUpdate')
- ->willReturn(null);
- $this->di['updater'] = $updatedMock;
- }
-
- protected function setUp(): void
- {
- parent::setUp();
-
- global $di;
- $this->di = $di;
- $this->setBoxUpdateMock();
- $this->di['loggedin_client'] = $this->di['db']->load('Client', 1);
- $this->di['loggedin_admin'] = $this->di['db']->load('Admin', 1);
- $this->session = $this->di['session'];
- $this->api_guest = $this->di['api_guest'];
- $this->api_client = $this->di['api_client'];
- $this->api_admin = $this->di['api_admin'];
- $this->api_system = $this->di['api_system'];
- // $this->api_admin->hook_batch_connect();
- }
-
- protected function tearDown(): void
- {
- parent::tearDown();
-
- $refl = new ReflectionObject($this);
- foreach ($refl->getProperties() as $prop) {
- if (!$prop->isStatic() && !str_starts_with($prop->getDeclaringClass()->getName(), 'PHPUnit_')) {
- $prop->setValue($this, null);
- }
- }
- }
-}
diff --git a/tests-legacy/includes/BBModTestCase.php b/tests-legacy/includes/BBModTestCase.php
deleted file mode 100644
index 9c0f97ea4..000000000
--- a/tests-legacy/includes/BBModTestCase.php
+++ /dev/null
@@ -1,22 +0,0 @@
-_mod);
- if (!$mod->isCore()) {
- $mod->install();
- }
-
- parent::setUp();
-
- try {
- $this->api_admin->extension_activate(['id' => $this->_mod, 'type' => 'mod']);
- } catch (Exception) {
- }
- }
-}
diff --git a/tests-legacy/includes/BBTestCase.php b/tests-legacy/includes/BBTestCase.php
deleted file mode 100644
index 5625caecd..000000000
--- a/tests-legacy/includes/BBTestCase.php
+++ /dev/null
@@ -1,124 +0,0 @@
-protect(function (...$args) use ($value) {
- $serviceName = strtolower((string) ($args[0] ?? ''));
- $resolvedService = null;
- $resolutionError = null;
-
- try {
- $resolvedService = $value(...$args);
- } catch (Throwable $resolutionError) {
- }
-
- if ($serviceName === 'staff' && !$this->isStaffLikeService($resolvedService)) {
- return $this->staffService;
- }
-
- if ($resolutionError instanceof Throwable) {
- throw $resolutionError;
- }
-
- return $resolvedService;
- });
- }
-
- parent::offsetSet($id, $value);
- }
-}
-
-class BBTestCase extends PHPUnit\Framework\TestCase
-{
- protected function createStaffServiceMock(): Box\Mod\Staff\Service
- {
- $staffService = $this->createMock(Box\Mod\Staff\Service::class);
- $staffService->expects($this->any())
- ->method('checkPermissionsAndThrowException');
-
- return $staffService;
- }
-
- protected function getDi(): Pimple\Container
- {
- $staffService = $this->createStaffServiceMock();
- $di = new BBTestCaseContainer($staffService);
-
- $di['validator'] = (fn (): FOSSBilling\Validate => new FOSSBilling\Validate());
- $di['tools'] = (fn (): FOSSBilling\Tools => new FOSSBilling\Tools());
- $di['mod_service'] = $di->protect(
- fn (string $service): Box\Mod\Staff\Service => match (strtolower($service)) {
- 'staff' => $staffService,
- default => throw new Pimple\Exception\UnknownIdentifierException(sprintf('Identifier "%s" is not defined.', $service)),
- }
- );
- $di['config'] = [
- 'salt' => 'test_salt',
- 'url' => 'http://localhost/',
- ];
-
- return $di;
- }
-
- protected function createAdminApi(string $className): object
- {
- $api = new $className();
- if ($api instanceof Api_Abstract) {
- $api->setDi($this->getDi());
- }
-
- return $api;
- }
-
- /**
- * Helper method to validate required parameters for API methods with RequiredParams attribute.
- * This simulates the validation that happens in Api_Handler when methods are called through it.
- *
- * @param Api_Abstract $api The API instance
- * @param string $methodName The method name to validate
- * @param array $data The data to validate
- *
- * @throws FOSSBilling\InformationException if validation fails
- */
- protected function validateRequiredParams(Api_Abstract $api, string $methodName, array $data): void
- {
- $handler = new Api_Handler(new Model_Admin());
- $handler->validateRequiredParams($api, $methodName, $data);
- }
-
- protected function tearDown(): void
- {
- parent::tearDown();
- $refl = new ReflectionObject($this);
- foreach ($refl->getProperties() as $prop) {
- if (!$prop->isStatic() && !str_starts_with($prop->getDeclaringClass()->getName(), 'PHPUnit_')) {
- $prop->setValue($this, null);
- }
- }
- }
-}
diff --git a/tests-legacy/includes/DummyBean.php b/tests-legacy/includes/DummyBean.php
deleted file mode 100644
index a1462d85f..000000000
--- a/tests-legacy/includes/DummyBean.php
+++ /dev/null
@@ -1,13 +0,0 @@
-__info['changelist'] = [];
-
- return $bean;
- }
-}
diff --git a/tests-legacy/includes/FakeTemplateWrapper.php b/tests-legacy/includes/FakeTemplateWrapper.php
deleted file mode 100644
index 942c28ec7..000000000
--- a/tests-legacy/includes/FakeTemplateWrapper.php
+++ /dev/null
@@ -1,38 +0,0 @@
-body;
- }
-}
diff --git a/tests-legacy/includes/Payment/Adapter/Dummy.php b/tests-legacy/includes/Payment/Adapter/Dummy.php
deleted file mode 100644
index c161e90e3..000000000
--- a/tests-legacy/includes/Payment/Adapter/Dummy.php
+++ /dev/null
@@ -1,49 +0,0 @@
-di = $di;
- }
-
- public function getConfig(): array
- {
- return [];
- }
-
- public function getType()
- {
- return self::TYPE_FORM;
- }
-
- public function getServiceUrl(): string
- {
- return 'https://www.google.com/?q=dummy';
- }
-
- public function singlePayment(Payment_Invoice $invoice): array
- {
- return [];
- }
-
- public function recurrentPayment(Payment_Invoice $invoice): array
- {
- return [];
- }
-
- public function ipn($data, Payment_Invoice $invoice): Payment_Transaction
- {
- $tx = new Payment_Transaction();
- $tx->setAmount($invoice->getTotal());
- $tx->setCurrency($invoice->getCurrency());
- $tx->setId(md5(uniqid((string) $invoice->getNumber())));
- $tx->setIsValid(true);
- $tx->setStatus(Payment_Transaction::STATUS_COMPLETE);
- $tx->setType(Payment_Transaction::TXTYPE_PAYMENT);
-
- return $tx;
- }
-}
diff --git a/tests-legacy/includes/PhpConsole.php b/tests-legacy/includes/PhpConsole.php
deleted file mode 100644
index b84e03b6a..000000000
--- a/tests-legacy/includes/PhpConsole.php
+++ /dev/null
@@ -1,342 +0,0 @@
-initErrorsHandler();
- }
- if ($handleExceptions) {
- $this->initExceptionsHandler();
- }
- if ($sourceBasePath) {
- $this->sourceBasePath = realpath($sourceBasePath);
- }
- $this->initClient();
- }
-
- public static function start($handleErrors = true, $handleExceptions = true, $sourceBasePath = null): void
- {
- if (self::$instance) {
- exit('PhpConsole already started');
- }
- self::$instance = new PhpConsole($handleErrors, $handleExceptions, $sourceBasePath);
- }
-
- public static function getInstance()
- {
- if (!self::$instance) {
- exit('PhpConsole not started');
- }
-
- return self::$instance;
- }
-
- protected function handle(PhpConsoleEvent $event)
- {
- if (self::$ignoreRepeatedEvents) {
- $eventHash = md5($event->message . $event->file . $event->line);
- if (in_array($eventHash, $this->handledMessagesHashes)) {
- return;
- }
- $this->handledMessagesHashes[] = $eventHash;
- }
- $this->sendEventToClient($event);
- }
-
- public function __destruct()
- {
- self::flushMessagesBuffer();
- }
-
- /***************************************************************
- CLIENT
- **************************************************************/
-
- final public const string clientProtocolCookie = 'phpcslc';
- final public const string serverProtocolCookie = 'phpcsls';
- final public const int serverProtocol = 4;
- final public const string messagesCookiePrefix = 'phpcsl_';
- final public const int cookiesLimit = 50;
- final public const int cookieSizeLimit = 4000;
- final public const int messageLengthLimit = 2500;
-
- protected static $isEnabledOnClient;
- protected static $isDisabled;
- protected static $messagesBuffer = [];
- protected static $bufferLength = 0;
- protected static $messagesSent = 0;
- protected static $cookiesSent = 0;
- protected static $index = 0;
-
- protected function initClient()
- {
- if (self::$isEnabledOnClient === null) {
- self::setEnabledOnServer();
- self::$isEnabledOnClient = self::isEnabledOnClient();
- if (self::$isEnabledOnClient) {
- ob_start();
- }
- }
- }
-
- protected static function isEnabledOnClient(): bool
- {
- return isset($_COOKIE[self::clientProtocolCookie]) && $_COOKIE[self::clientProtocolCookie] == self::serverProtocol;
- }
-
- protected static function setEnabledOnServer()
- {
- if (!isset($_COOKIE[self::serverProtocolCookie]) || $_COOKIE[self::serverProtocolCookie] != self::serverProtocol) {
- self::setCookie(self::serverProtocolCookie, self::serverProtocol);
- }
- }
-
- protected function sendEventToClient(PhpConsoleEvent $event)
- {
- if (!self::$isEnabledOnClient || self::$isDisabled) {
- return;
- }
- $message = [];
- $message['type'] = str_starts_with((string) $event->tags, 'error,') ? 'error' : 'debug';
- $message['subject'] = $event->type;
- $message['text'] = substr((string) $event->message, 0, self::messageLengthLimit);
-
- if ($event->file) {
- $message['source'] = ($this->sourceBasePath ? preg_replace('!^' . preg_quote((string) $this->sourceBasePath, '!') . '!', '', (string) $event->file) : $event->file) . ($event->line ? ':' . $event->line : '');
- }
- if ($event->trace) {
- $traceArray = $this->convertTraceToArray($event->trace, $event->file, $event->line);
- if ($traceArray) {
- $message['trace'] = $traceArray;
- }
- }
-
- self::pushMessageToBuffer($message);
-
- if (strpos((string) $event->tags, ',fatal')) {
- self::flushMessagesBuffer();
- }
- }
-
- protected function convertTraceToArray($traceData, $eventFile = null, $eventLine = null): array
- {
- $trace = [];
- foreach ($traceData as $call) {
- if ((isset($call['class']) && $call['class'] == self::class) || (!$trace && isset($call['file']) && $call['file'] == $eventFile && $call['line'] == $eventLine)) {
- $trace = [];
-
- continue;
- }
- $args = [];
- if (isset($call['args'])) {
- foreach ($call['args'] as $arg) {
- if (is_object($arg)) {
- $args[] = $arg::class;
- } elseif (is_array($arg)) {
- $args[] = 'Array';
- } else {
- $arg = var_export($arg, 1);
- $args[] = strlen((string) $arg) > 12 ? substr((string) $arg, 0, 8) . '...\'' : $arg;
- }
- }
- }
- if (isset($call['file']) && $this->sourceBasePath) {
- $call['file'] = preg_replace('!^' . preg_quote((string) $this->sourceBasePath, '!') . '!', '', $call['file']);
- }
- $trace[] = (isset($call['file']) ? ($call['file'] . ':' . $call['line']) : '[internal call]') . ' - ' . (isset($call['class']) ? $call['class'] . $call['type'] : '') . $call['function'] . '(' . implode(', ', $args) . ')';
- }
- $trace = array_reverse($trace);
- foreach ($trace as $i => &$call) {
- $call = '#' . ($i + 1) . ' ' . $call;
- }
-
- return $trace;
- }
-
- protected static function pushMessageToBuffer($message)
- {
- $encodedMessageLength = strlen(rawurlencode(json_encode($message)));
- if (self::$bufferLength + $encodedMessageLength > self::cookieSizeLimit) {
- self::flushMessagesBuffer();
- }
- self::$messagesBuffer[] = $message;
- self::$bufferLength += $encodedMessageLength;
- }
-
- protected static function getNextIndex()
- {
- return substr(number_format(microtime(1), 3, '', ''), -6) + self::$index++;
- }
-
- public static function flushMessagesBuffer(): void
- {
- if (self::$messagesBuffer) {
- self::sendMessages(self::$messagesBuffer);
- self::$bufferLength = 0;
- self::$messagesSent += count(self::$messagesBuffer);
- self::$messagesBuffer = [];
- ++self::$cookiesSent;
- if (self::$cookiesSent == self::cookiesLimit) {
- self::$isDisabled = true;
- $message = ['type' => 'error', 'subject' => 'PHP CONSOLE', 'text' => 'MESSAGES LIMIT EXCEEDED BECAUSE OF COOKIES STORAGE LIMIT. TOTAL MESSAGES SENT: ' . self::$messagesSent, 'source' => __FILE__, 'notify' => 3];
- self::sendMessages([$message]);
- }
- }
- }
-
- protected static function setCookie($name, $value)
- {
- if (headers_sent($file, $line)) {
- exit('PhpConsole ERROR: setcookie() failed because haders are sent (' . $file . ':' . $line . '). Try to use ob_start()');
- }
- setcookie($name, (string) $value, ['expires' => null, 'path' => '/']);
- }
-
- protected static function sendMessages($messages)
- {
- self::setCookie(self::messagesCookiePrefix . self::getNextIndex(), json_encode($messages));
- }
-
- /***************************************************************
- ERRORS
- **************************************************************/
-
- protected $codesTags = [E_ERROR => 'fatal', E_WARNING => 'warning', E_PARSE => 'fatal', E_NOTICE => 'notice', E_CORE_ERROR => 'fatal', E_CORE_WARNING => 'warning', E_COMPILE_ERROR => 'fatal', E_COMPILE_WARNING => 'warning', E_USER_ERROR => 'fatal', E_USER_WARNING => 'warning', E_USER_NOTICE => 'notice', E_STRICT => 'warning'];
- protected $codesNames = [E_ERROR => 'E_ERROR', E_WARNING => 'E_WARNING', E_PARSE => 'E_PARSE', E_NOTICE => 'E_NOTICE', E_CORE_ERROR => 'E_CORE_ERROR', E_CORE_WARNING => 'E_CORE_WARNING', E_COMPILE_ERROR => 'E_COMPILE_ERROR', E_COMPILE_WARNING => 'E_COMPILE_WARNING', E_USER_ERROR => 'E_USER_ERROR', E_USER_WARNING => 'E_USER_WARNING', E_USER_NOTICE => 'E_USER_NOTICE', E_STRICT => 'E_STRICT'];
- protected $notCompitableCodes = ['E_RECOVERABLE_ERROR' => 'warning', 'E_DEPRECATED' => 'warning'];
- protected $oldErrorHandler;
-
- protected function initErrorsHandler()
- {
- ini_set('display_errors', false);
- ini_set('html_errors', false);
- ini_set('ignore_repeated_errors', self::$ignoreRepeatedEvents);
- ini_set('ignore_repeated_source', self::$ignoreRepeatedEvents);
-
- foreach ($this->notCompitableCodes as $code => $tag) {
- if (defined($code)) {
- $this->codesTags[constant($code)] = $tag;
- $this->codesNames[constant($code)] = $code;
- }
- }
-
- $this->oldErrorHandler = set_error_handler($this->handleError(...));
- register_shutdown_function([$this, 'checkFatalError']);
- }
-
- public function checkFatalError(): void
- {
- $error = error_get_last();
- if ($error) {
- $this->handleError($error['type'], $error['message'], $error['file'], $error['line']);
- }
- }
-
- public function handleError($code = null, $message = null, $file = null, $line = null): void
- {
- if (error_reporting() == 0) { // if error has been supressed with an @
- return;
- }
- if (!$code) {
- $code = E_USER_ERROR;
- }
-
- $event = new PhpConsoleEvent();
- $event->tags = 'error,' . ($this->codesTags[$code] ?? 'warning');
- $event->message = $message;
- $event->type = $this->codesNames[$code] ?? $code;
- $event->file = $file;
- $event->line = $line;
- $event->trace = debug_backtrace();
-
- $this->handle($event);
-
- if (self::$callOldErrorHandler && $this->oldErrorHandler) {
- call_user_func_array($this->oldErrorHandler, [$code, $message, $file, $line]);
- }
- }
-
- /***************************************************************
- EXCEPTIONS
- **************************************************************/
-
- protected $oldExceptionsHandler;
-
- protected function initExceptionsHandler()
- {
- $this->oldExceptionsHandler = set_exception_handler($this->handleException(...));
- }
-
- public function handleException(Throwable $exception): void
- {
- $event = new PhpConsoleEvent();
- $event->message = $exception->getMessage();
- $event->tags = 'error,fatal,exception,' . $exception::class;
- $event->type = $exception::class;
- $event->file = $exception->getFile();
- $event->line = $exception->getLine();
- $event->trace = $exception->getTrace();
-
- $this->handle($event);
-
- // TODO: check if need to throw
- if (self::$callOldExceptionsHandler && $this->oldExceptionsHandler) {
- call_user_func($this->oldExceptionsHandler, $exception);
- }
- }
-
- /***************************************************************
- DEBUG
- **************************************************************/
-
- public static function debug($message, $tags = 'debug'): void
- {
- if (self::$instance) {
- $event = new PhpConsoleEvent();
- $event->message = $message;
- $event->tags = $tags;
- $event->type = $tags;
- self::$instance->handle($event);
- }
- }
-}
-
-class PhpConsoleEvent
-{
- public $message;
- public $type;
- public $tags;
- public $trace;
- public $file;
- public $line;
-}
-
-function debug($message, $tags = 'debug'): void
-{
- PhpConsole::debug($message, $tags);
-}
diff --git a/tests-legacy/includes/Plugin/BblicenseMock.php b/tests-legacy/includes/Plugin/BblicenseMock.php
deleted file mode 100644
index 5e44f091d..000000000
--- a/tests-legacy/includes/Plugin/BblicenseMock.php
+++ /dev/null
@@ -1,29 +0,0 @@
-suspend($service, $order, $params);
- }
-
- public function uncancel($service, $order, $params = [])
- {
- return $this->unsuspend($service, $order, $params);
- }
-
- public function delete($service, $order, $params = [])
- {
- }
-
- public function get_config(): ?array
- {
- return $this->config;
- }
-
- /**
- * Custom function to return passed params.
- *
- * @param type $service
- * @param type $order
- * @param type $params
- *
- * @return type
- */
- public function return_params($service, $order, $params = [])
- {
- return $params;
- }
-}
diff --git a/tests-legacy/includes/QueryDebuggerListener.php b/tests-legacy/includes/QueryDebuggerListener.php
deleted file mode 100644
index 48ee9ca3f..000000000
--- a/tests-legacy/includes/QueryDebuggerListener.php
+++ /dev/null
@@ -1,23 +0,0 @@
-getQuery();
- $params = $event->getParams();
-
- // the below makes some naive assumptions about the queries being logged
- while (sizeof($params) > 0) {
- $param = array_shift($params);
-
- if (!is_numeric($param)) {
- $param = sprintf("'%s'", $param);
- }
-
- $query = substr_replace($query, $param, strpos($query, '?'), 1);
-
- debug($query);
- }
- }
-}
diff --git a/tests-legacy/includes/TagOptional.php b/tests-legacy/includes/TagOptional.php
deleted file mode 100644
index ab036eccf..000000000
--- a/tests-legacy/includes/TagOptional.php
+++ /dev/null
@@ -1,90 +0,0 @@
-_name = 'optional';
- $this->_type = $matches[2];
-
- if (isset($matches[3])) {
- $this->_variableName = $matches[3];
- }
-
- if (isset($matches[4])) {
- $this->_description = preg_replace('#\s+#', ' ', $matches[4]);
- }
- }
-
- /**
- * Get parameter variable type.
- *
- * @return string
- */
- public function getType()
- {
- return $this->_type;
- }
-
- /**
- * Get parameter name.
- *
- * @return string
- */
- public function getVariableName()
- {
- return $this->_variableName;
- }
-}
diff --git a/tests-legacy/library/Box/Box_CryptTest.php b/tests-legacy/library/Box/Box_CryptTest.php
deleted file mode 100644
index bd6c22045..000000000
--- a/tests-legacy/library/Box/Box_CryptTest.php
+++ /dev/null
@@ -1,56 +0,0 @@
-encrypt($text, $key);
- $decoded = $crypt->decrypt($encoded, $key);
- $this->assertEquals($text, $decoded);
- }
-
- public function testDecryptLegacyCiphertext(): void
- {
- $key = 'le password';
- $text = 'foo bar';
-
- $crypt = new Box_Crypt();
-
- $this->assertSame($text, $crypt->decrypt($this->encryptWithLegacyKey($text, $key), $key));
- }
-
- public function testDecryptCurrentUnversionedCiphertext(): void
- {
- $key = 'le password';
- $text = 'foo bar';
-
- $crypt = new Box_Crypt();
-
- $this->assertSame($text, $crypt->decrypt($this->encryptWithCurrentKey($text, $key), $key));
- }
-
- private function encryptWithLegacyKey(string $text, string $pass): string
- {
- return $this->encryptWithKey($text, pack('H*', hash('md5', $pass)));
- }
-
- private function encryptWithCurrentKey(string $text, string $pass): string
- {
- return $this->encryptWithKey($text, hash_pbkdf2('sha256', $pass, 'fossbilling_salt', 100000, 32, true));
- }
-
- private function encryptWithKey(string $text, string $key): string
- {
- $iv = str_repeat("\x01", openssl_cipher_iv_length(Box_Crypt::METHOD));
- $ciphertext = openssl_encrypt($text, Box_Crypt::METHOD, $key, OPENSSL_RAW_DATA, $iv);
-
- return base64_encode($iv . $ciphertext);
- }
-}
diff --git a/tests-legacy/library/Box/Box_EventManagerTest.php b/tests-legacy/library/Box/Box_EventManagerTest.php
deleted file mode 100644
index 7072c00ef..000000000
--- a/tests-legacy/library/Box/Box_EventManagerTest.php
+++ /dev/null
@@ -1,31 +0,0 @@
-fire([]);
- }
-
- public function testFire(): void
- {
- $db_mock = $this->createMock('Box_Database');
- $db_mock->expects($this->atLeastOnce())
- ->method('getAll')
- ->willReturn([]);
-
- $di = $this->getDi();
- $di['logger'] = new Box_Log();
- $di['db'] = $db_mock;
-
- $manager = new Box_EventManager();
- $manager->setDi($di);
-
- $manager->fire(['event' => 'onBeforeClientSignup']);
- }
-}
diff --git a/tests-legacy/library/Box/Box_LogTest.php b/tests-legacy/library/Box/Box_LogTest.php
deleted file mode 100644
index b597aa44d..000000000
--- a/tests-legacy/library/Box/Box_LogTest.php
+++ /dev/null
@@ -1,221 +0,0 @@
-addWriter($writer);
- $log->setChannel('test');
-
- $log->emergency('emerg msg');
- $log->critical('crit msg');
- $log->error('err msg');
- $log->warning('warn msg');
- $log->notice('notice msg');
- $log->info('info msg');
-
- $this->assertCount(6, $writer->events);
-
- $this->assertSame(Box_Log::EMERG, $writer->events[0]['priority']);
- $this->assertSame('EMERGENCY', $writer->events[0]['priorityName']);
- $this->assertSame('emerg msg', $writer->events[0]['message']);
-
- $this->assertSame(Box_Log::CRIT, $writer->events[1]['priority']);
- $this->assertSame('CRITICAL', $writer->events[1]['priorityName']);
- $this->assertSame('crit msg', $writer->events[1]['message']);
-
- $this->assertSame(Box_Log::ERR, $writer->events[2]['priority']);
- $this->assertSame('ERROR', $writer->events[2]['priorityName']);
- $this->assertSame('err msg', $writer->events[2]['message']);
-
- $this->assertSame(Box_Log::WARN, $writer->events[3]['priority']);
- $this->assertSame('WARNING', $writer->events[3]['priorityName']);
- $this->assertSame('warn msg', $writer->events[3]['message']);
-
- $this->assertSame(Box_Log::NOTICE, $writer->events[4]['priority']);
- $this->assertSame('NOTICE', $writer->events[4]['priorityName']);
-
- $this->assertSame(Box_Log::INFO, $writer->events[5]['priority']);
- $this->assertSame('INFO', $writer->events[5]['priorityName']);
- }
-
- public function testLegacyAliasesMapToSamePrioritiesAsPsr3Names(): void
- {
- $writer = new Box_LogTest_CapturingWriter();
-
- $log = new Box_Log();
- $log->addWriter($writer);
- $log->setChannel('test');
-
- $log->emerg('a');
- $log->crit('b');
- $log->err('c');
- $log->warn('d');
-
- $this->assertCount(4, $writer->events);
- $this->assertSame(Box_Log::EMERG, $writer->events[0]['priority']);
- $this->assertSame('EMERGENCY', $writer->events[0]['priorityName']);
- $this->assertSame(Box_Log::CRIT, $writer->events[1]['priority']);
- $this->assertSame('CRITICAL', $writer->events[1]['priorityName']);
- $this->assertSame(Box_Log::ERR, $writer->events[2]['priority']);
- $this->assertSame('ERROR', $writer->events[2]['priorityName']);
- $this->assertSame(Box_Log::WARN, $writer->events[3]['priority']);
- $this->assertSame('WARNING', $writer->events[3]['priorityName']);
- }
-
- public function testLegacyAndPsr3ProduceIdenticalEvents(): void
- {
- $writerA = new Box_LogTest_CapturingWriter();
- $writerB = new Box_LogTest_CapturingWriter();
-
- $logA = new Box_Log();
- $logA->addWriter($writerA);
- $logA->setChannel('test');
-
- $logB = new Box_Log();
- $logB->addWriter($writerB);
- $logB->setChannel('test');
-
- $logA->emergency('payload');
- $logB->emerg('payload');
-
- $this->assertCount(1, $writerA->events);
- $this->assertCount(1, $writerB->events);
- $this->assertSame($writerA->events[0]['priority'], $writerB->events[0]['priority']);
- $this->assertSame($writerA->events[0]['priorityName'], $writerB->events[0]['priorityName']);
- $this->assertSame($writerA->events[0]['message'], $writerB->events[0]['message']);
- }
-
- public function testUnknownLogMethodThrows(): void
- {
- $log = new Box_Log();
-
- $this->expectException(FOSSBilling\Exception::class);
- $this->expectExceptionMessage('Bad log priority');
-
- $log->notARealMethod('msg');
- }
-
- public function testEmptyLogMessageThrows(): void
- {
- $log = new Box_Log();
-
- $this->expectException(FOSSBilling\Exception::class);
- $this->expectExceptionMessage('Missing log message');
-
- $log->info();
- }
-
- public function testPlaceholderFormatSubstitutesArguments(): void
- {
- $writer = new Box_LogTest_CapturingWriter();
-
- $log = new Box_Log();
- $log->addWriter($writer);
- $log->setChannel('test');
-
- $log->info('Hello %s, you are %d', 'Alice', 30);
-
- $this->assertCount(1, $writer->events);
- $this->assertSame('Hello Alice, you are 30', $writer->events[0]['message']);
- }
-
- public function testMaskedKeysAreReplacedInExtras(): void
- {
- $writer = new Box_LogTest_CapturingWriter();
-
- $log = new Box_Log();
- $log->addWriter($writer);
- $log->setChannel('test');
-
- $log->info('Hello %s', 'alice', ['password' => 'secret123', 'token' => 'abc']);
-
- $this->assertCount(1, $writer->events);
- $event = $writer->events[0];
- $this->assertArrayHasKey('info', $event);
- $this->assertSame('alice', $event['info'][0]);
- $this->assertSame('********', $event['info'][1]['password']);
- $this->assertSame('********', $event['info'][1]['token']);
- }
-
- public function testMaskedKeyWithArrayValueIsMasked(): void
- {
- $writer = new Box_LogTest_CapturingWriter();
-
- $log = new Box_Log();
- $log->addWriter($writer);
- $log->setChannel('test');
-
- $log->info('Hello %s', 'alice', ['password' => ['old' => 'a', 'new' => 'b']]);
-
- $this->assertCount(1, $writer->events);
- $this->assertSame('********', $writer->events[0]['info'][1]['password']);
- }
-
- public function testFailingWriterDoesNotPropagateException(): void
- {
- $log = new Box_Log();
- $log->addWriter(new Box_LogTest_FailingWriter());
- $log->setChannel('test');
-
- $log->info('should not throw');
-
- $this->expectNotToPerformAssertions();
- }
-
- public function testLogWithUnknownPriorityThrows(): void
- {
- $log = new Box_Log();
-
- $this->expectException(FOSSBilling\Exception::class);
- $this->expectExceptionMessage('Bad log priority');
-
- $log->log('msg', 999);
- }
-
- public function testLogWithNoWritersIsNoOp(): void
- {
- $log = new Box_Log();
-
- $log->log('msg', Box_Log::INFO);
-
- $this->expectNotToPerformAssertions();
- }
-
- public function testPriorityConstantsMatchDocblockNames(): void
- {
- $this->assertSame(0, Box_Log::EMERG);
- $this->assertSame(1, Box_Log::ALERT);
- $this->assertSame(2, Box_Log::CRIT);
- $this->assertSame(3, Box_Log::ERR);
- $this->assertSame(4, Box_Log::WARN);
- $this->assertSame(5, Box_Log::NOTICE);
- $this->assertSame(6, Box_Log::INFO);
- $this->assertSame(7, Box_Log::DEBUG);
- }
-}
-
-class Box_LogTest_CapturingWriter
-{
- /** @var array> */
- public array $events = [];
-
- public function write(array $event, string $channel = 'application'): void
- {
- $this->events[] = $event;
- }
-}
-
-class Box_LogTest_FailingWriter
-{
- public function write(array $event, string $channel = 'application'): void
- {
- throw new RuntimeException('writer is down');
- }
-}
diff --git a/tests-legacy/library/Box/Box_PeriodTest.php b/tests-legacy/library/Box/Box_PeriodTest.php
deleted file mode 100644
index bdaaf6819..000000000
--- a/tests-legacy/library/Box/Box_PeriodTest.php
+++ /dev/null
@@ -1,47 +0,0 @@
-expectException(FOSSBilling\Exception::class);
- $this->expectExceptionMessage('Invalid period code. Period definition must be 2 chars length');
- $p = new Box_Period('1');
- }
-
- public function testException2(): void
- {
- $this->expectException(FOSSBilling\Exception::class);
- $this->expectExceptionMessage('Period Error. Unit Z is not defined');
- $p = new Box_Period('1Z');
- }
-
- public function testOneMonth(): void
- {
- $p = new Box_Period('1M');
-
- $this->assertEquals('M', $p->getUnit());
- $this->assertEquals(1, $p->getQty());
- $this->assertEquals('1M', $p->getCode());
- $this->assertEquals('Every 1 month', $p->getTitle());
- $this->assertEquals(30, $p->getDays());
- $this->assertEquals(1, $p->getMonths());
- $this->assertEquals(strtotime('+1 month'), $p->getExpirationTime());
- }
-
- public function testTwoMonths(): void
- {
- $p = new Box_Period('2M');
-
- $this->assertEquals('M', $p->getUnit());
- $this->assertEquals(2, $p->getQty());
- $this->assertEquals('2M', $p->getCode());
- $this->assertEquals('Every 2 months', $p->getTitle());
- $this->assertEquals(60, $p->getDays());
- $this->assertEquals(2, $p->getMonths());
- $this->assertEquals(strtotime('+2 month'), $p->getExpirationTime());
- }
-}
diff --git a/tests-legacy/library/Box/Box_TranslateTest.php b/tests-legacy/library/Box/Box_TranslateTest.php
deleted file mode 100644
index 86e06428b..000000000
--- a/tests-legacy/library/Box/Box_TranslateTest.php
+++ /dev/null
@@ -1,38 +0,0 @@
-setLocale($locale);
- $result = $translateObj->getLocale();
-
- $this->assertEquals($locale, $result);
- }
-
- public function testDomainSetterAndGetter(): void
- {
- $translateObj = new Box_Translate();
-
- $default = 'messages';
- $result = $translateObj->getDomain();
- $this->assertEquals($default, $result);
-
- $newDomain = 'admin';
- $result = $translateObj->setDomain($newDomain)->getDomain();
- $this->assertEquals($newDomain, $result);
- }
-
- public function testTranslate(): void
- {
- $text = 'Translate ME';
- $result = __trans($text);
-
- $this->assertEquals($text, $result);
- }
-}
diff --git a/tests-legacy/library/Box/FOSS_ToolsTest.php.disabled b/tests-legacy/library/Box/FOSS_ToolsTest.php.disabled
deleted file mode 100644
index e9ab79ea4..000000000
--- a/tests-legacy/library/Box/FOSS_ToolsTest.php.disabled
+++ /dev/null
@@ -1,48 +0,0 @@
-getMockBuilder('\FOSSBilling\Tools')->getMock();
- $toolsMock->expects($this->atLeastOnce())->method('validateAndSanitizeEmail');
-
- $di = new \Pimple\Container();
- $di['tools'] = $toolsMock;
-
- $result = $this->di['tools']->validateAndSanitizeEmail($testEmail, false);
- $this->assertEquals($testEmail, $result);
- }
-
- public function testValidateAndSanitizeEmailID()
- {
- $testEmail = 'example@example-tést.eu';
-
- $toolsMock = $this->getMockBuilder('\FOSSBilling\Tools')->getMock();
- $toolsMock->expects($this->atLeastOnce())->method('validateAndSanitizeEmail');
-
- $di = new \Pimple\Container();
- $di['tools'] = $toolsMock;
-
- $result = $this->di['tools']->validateAndSanitizeEmail($testEmail, false);
- $this->assertEquals($testEmail, $result);
- }
-
- public function testValidateAndSanitizeEmailInvalid()
- {
- $testEmail = 'Totally an email"';
-
- $toolsMock = $this->getMockBuilder('\FOSSBilling\Tools')->getMock();
- $toolsMock->expects($this->atLeastOnce())->method('validateAndSanitizeEmail');
-
- $di = new \Pimple\Container();
- $di['tools'] = $toolsMock;
-
- $result = $this->di['tools']->validateAndSanitizeEmail($testEmail, false);
- $this->assertFalse($result);
- }
-}
diff --git a/tests-legacy/library/FOSSBilling/CsvResponseFactoryTest.php b/tests-legacy/library/FOSSBilling/CsvResponseFactoryTest.php
deleted file mode 100644
index 18d0fa500..000000000
--- a/tests-legacy/library/FOSSBilling/CsvResponseFactoryTest.php
+++ /dev/null
@@ -1,38 +0,0 @@
- 1,
- 'email' => 'client@example.com',
- 'status' => 'active',
- ];
- }
- };
-
- $database = $this->createMock(Box_Database::class);
- $database->expects($this->once())
- ->method('findAll')
- ->with('client')
- ->willReturn([$bean]);
-
- $responseFactory = new CsvResponseFactory($database);
- $response = $responseFactory->create('client', 'clients.csv', ['id', 'email']);
-
- $this->assertSame(200, $response->getStatusCode());
- $this->assertSame('text/csv; charset=utf-8', $response->headers->get('Content-Type'));
- $this->assertStringContainsString('attachment; filename=clients.csv', (string) $response->headers->get('Content-Disposition'));
- $this->assertSame("id,email\n1,client@example.com\n", $response->getContent());
- }
-}
diff --git a/tests-legacy/library/FOSSBilling/DiApiAccessTest.php b/tests-legacy/library/FOSSBilling/DiApiAccessTest.php
deleted file mode 100644
index a32fa608e..000000000
--- a/tests-legacy/library/FOSSBilling/DiApiAccessTest.php
+++ /dev/null
@@ -1,84 +0,0 @@
-requestBackup = $request instanceof Request ? $request : null;
- }
-
- protected function tearDown(): void
- {
- global $request;
- $request = $this->requestBackup;
- parent::tearDown();
- }
-
- public function testClientApiAllowsUnvalidatedClientProfileRoutes(): void
- {
- $di = $this->createContainerForRoute('/api/client/profile/get');
-
- $api = $di['api']('client');
-
- $this->assertInstanceOf(Api_Handler::class, $api);
- }
-
- public function testClientApiBlocksUnvalidatedClientAccessOutsideAllowedRoutes(): void
- {
- $di = $this->createContainerForRoute('/api/client/invoice/get');
-
- $this->expectException(EmailValidationRequiredException::class);
- $di['api']('client');
- }
-
- public function testClientPageAllowsUnvalidatedClientProfilePage(): void
- {
- $di = $this->createContainerForRoute('/client/profile');
-
- $api = $di['api']('client');
-
- $this->assertInstanceOf(Api_Handler::class, $api);
- }
-
- public function testClientPageAllowsUnvalidatedClientLogoutPage(): void
- {
- $di = $this->createContainerForRoute('/client/logout');
-
- $api = $di['api']('client');
-
- $this->assertInstanceOf(Api_Handler::class, $api);
- }
-
- public function testClientPageBlocksUnvalidatedClientBalancePage(): void
- {
- $di = $this->createContainerForRoute('/client/balance');
-
- $this->expectException(EmailValidationRequiredException::class);
- $di['api']('client');
- }
-
- private function createContainerForRoute(string $routePath): Pimple\Container
- {
- global $request;
-
- $request = Request::create('http://localhost' . $routePath, 'GET', ['_url' => $routePath]);
- RequestFactory::normalizeRoutePath($request);
-
- $di = require PATH_ROOT . '/di.php';
- $di['loggedin_client'] = new Model_Client();
- $di['is_client_email_validated'] = $di->protect(fn (): bool => false);
-
- return $di;
- }
-}
diff --git a/tests-legacy/library/FOSSBilling/FOSSBillingExtensionTest.php b/tests-legacy/library/FOSSBilling/FOSSBillingExtensionTest.php
deleted file mode 100644
index 61d044f15..000000000
--- a/tests-legacy/library/FOSSBilling/FOSSBillingExtensionTest.php
+++ /dev/null
@@ -1,90 +0,0 @@
-extension = new FOSSBillingExtension(new Container());
- }
-
- public function testTransWithoutValues(): void
- {
- $result = $this->extension->trans('Hello World');
-
- $this->assertSame('Hello World', $result);
- }
-
- public function testTransWithPlaceholderReplacement(): void
- {
- $result = $this->extension->trans('Hello %name%', ['%name%' => 'World']);
-
- $this->assertSame('Hello World', $result);
- }
-
- public function testTransWithMultiplePlaceholders(): void
- {
- $result = $this->extension->trans('Dear %title% %name%', ['%title%' => 'Mr.', '%name%' => 'Smith']);
-
- $this->assertSame('Dear Mr. Smith', $result);
- }
-
- public function testTransWithNullValues(): void
- {
- $result = $this->extension->trans('Hello %name%', null);
-
- $this->assertSame('Hello %name%', $result);
- }
-
- public function testAvatarRendersDataUriBackground(): void
- {
- $result = $this->extension->avatar('user@example.org', 32, 'avatar avatar-sm');
-
- $this->assertStringStartsWith('assertStringContainsString('src="js/app".js?', $result);
- }
-
- public function testStylesheetTagEscapesPathAndMedia(): void
- {
- $result = $this->extension->stylesheetTag('css/app".css', 'screen" media');
-
- $this->assertStringContainsString('href="css/app".css?v=', $result);
- $this->assertStringContainsString('media="screen" media"', $result);
- }
-
- public function testTimeagoUsesPluralFormsWithoutSuffixingS(): void
- {
- $result = $this->extension->timeago(date('Y-m-d H:i:s', time() - 120));
-
- $this->assertSame('2 minutes', $result);
- }
-}
diff --git a/tests-legacy/library/FOSSBilling/FOSSBilling_ConfigTest.php b/tests-legacy/library/FOSSBilling/FOSSBilling_ConfigTest.php
deleted file mode 100644
index d1aa4be89..000000000
--- a/tests-legacy/library/FOSSBilling/FOSSBilling_ConfigTest.php
+++ /dev/null
@@ -1,203 +0,0 @@
-originalConfigContents = $configContents;
- }
-
- protected function tearDown(): void
- {
- if ($this->originalConfigContents !== null) {
- file_put_contents(PATH_CONFIG, $this->originalConfigContents);
- clearstatcache(true, PATH_CONFIG);
-
- if (function_exists('opcache_invalidate')) {
- @opcache_invalidate(PATH_CONFIG, true);
- }
- }
-
- parent::tearDown();
- }
-
- public function testPrettyPrintArrayToPhpEscapesInjectedStringValues(): void
- {
- $payload = "x']; \$GLOBALS['config_injection_test'] = true; //";
- $config = [
- 'interface_ip' => $payload,
- ];
-
- $reflection = new ReflectionClass(FOSSBilling\Config::class);
- $method = $reflection->getMethod('prettyPrintArrayToPHP');
-
- $rendered = $method->invoke(null, $config);
- $filePath = tempnam(sys_get_temp_dir(), 'fossbilling_config_test_');
- if ($filePath === false) {
- self::fail('Failed to create temp file for config serialization test.');
- }
-
- try {
- file_put_contents($filePath, $rendered);
-
- unset($GLOBALS['config_injection_test']);
- $result = include $filePath;
-
- $this->assertIsArray($result);
- $this->assertArrayHasKey('interface_ip', $result);
- $this->assertSame($payload, $result['interface_ip']);
- $this->assertArrayNotHasKey('config_injection_test', $GLOBALS);
- } finally {
- @unlink($filePath);
- unset($GLOBALS['config_injection_test']);
- }
- }
-
- public function testSetConfigWithoutCacheClearRefreshesConfigReadsAndPreservesCacheFiles(): void
- {
- $filesystem = new Filesystem();
- $cacheFile = Path::join(PATH_CACHE, 'config-cache-preservation-test.txt');
- $filesystem->dumpFile($cacheFile, 'preserve me');
-
- try {
- $config = FOSSBilling\Config::getConfig();
- $config['maintenance_mode'] = [
- 'enabled' => true,
- 'allowed_urls' => [],
- 'allowed_ips' => [],
- ];
-
- FOSSBilling\Config::setConfig($config, false);
-
- $this->assertFileExists($cacheFile);
- $this->assertTrue(FOSSBilling\Config::getProperty('maintenance_mode.enabled', false));
- } finally {
- $filesystem->remove($cacheFile);
- }
- }
-
- public function testGetConfigThrowsForNonArrayConfigFile(): void
- {
- $this->writeRawConfig("expectException(RuntimeException::class);
- $this->expectExceptionMessage('The FOSSBilling configuration file is empty or invalid.');
-
- FOSSBilling\Config::getConfig();
- }
-
- public function testIsConfigValidReturnsFalseForNonArrayConfigFile(): void
- {
- $this->writeRawConfig("assertFalse(FOSSBilling\Config::isConfigValid());
- }
-
- public function testInstallerTreatsExistingInvalidConfigAsAlreadyInstalled(): void
- {
- $this->writeRawConfig("assertSame('installed', $this->runInstallerInstalledCheck());
- }
-
- public function testInstallerTreatsThrowingConfigAsAlreadyInstalled(): void
- {
- $this->writeRawConfig("assertSame('installed', $this->runInstallerInstalledCheck());
- }
-
- public function testInstallerTreatsExistingConfigAsNotInstalledInDebugMode(): void
- {
- $this->writeRawConfig(" ['debug' => true]];");
-
- $this->assertSame('not-installed', $this->runInstallerInstalledCheck());
- }
-
- public function testInstallerAllowsInstallWhenConfigFileIsMissing(): void
- {
- $this->removeConfig();
-
- $this->assertSame('not-installed', $this->runInstallerInstalledCheck());
- }
-
- private function writeRawConfig(string $contents): void
- {
- $writeResult = file_put_contents(PATH_CONFIG, $contents);
- if ($writeResult === false) {
- self::fail('Failed to write the FOSSBilling config file.');
- }
-
- clearstatcache(true, PATH_CONFIG);
-
- if (function_exists('opcache_invalidate')) {
- @opcache_invalidate(PATH_CONFIG, true);
- }
- }
-
- private function removeConfig(): void
- {
- if (!unlink(PATH_CONFIG)) {
- self::fail('Failed to remove the FOSSBilling config file.');
- }
-
- clearstatcache(true, PATH_CONFIG);
-
- if (function_exists('opcache_invalidate')) {
- @opcache_invalidate(PATH_CONFIG, true);
- }
- }
-
- private function runInstallerInstalledCheck(): string
- {
- $code = <<<'PHP'
- require 'src/install/install.php';
- $request = Symfony\Component\HttpFoundation\Request::create('http://localhost/install/install.php', 'GET');
- $installer = new FOSSBilling_Installer($request);
- echo $installer->isAlreadyInstalled() ? 'installed' : 'not-installed';
- PHP;
-
- $pipes = [];
- $process = proc_open(
- [PHP_BINARY, '-d', 'display_errors=1', '-r', $code],
- [
- 1 => ['pipe', 'w'],
- 2 => ['pipe', 'w'],
- ],
- $pipes,
- dirname(__DIR__, 3)
- );
-
- if (!is_resource($process)) {
- self::fail('Failed to start installer check subprocess.');
- }
-
- $output = stream_get_contents($pipes[1]);
- $errorOutput = stream_get_contents($pipes[2]);
- fclose($pipes[1]);
- fclose($pipes[2]);
-
- $exitCode = proc_close($process);
- if ($exitCode !== 0) {
- self::fail(sprintf('Installer check subprocess failed with exit code %d: %s', $exitCode, $errorOutput));
- }
-
- return trim((string) $output);
- }
-}
diff --git a/tests-legacy/library/FOSSBilling/FOSSBilling_DriverManagerFactoryTest.php b/tests-legacy/library/FOSSBilling/FOSSBilling_DriverManagerFactoryTest.php
deleted file mode 100644
index bf7f35cd9..000000000
--- a/tests-legacy/library/FOSSBilling/FOSSBilling_DriverManagerFactoryTest.php
+++ /dev/null
@@ -1,72 +0,0 @@
-originalConfigContents = $configContents;
- }
-
- public function testLegacyMysqlTypeIsNormalizedBeforeConnecting(): void
- {
- $this->writeDbConfig([
- 'type' => 'mysql',
- 'host' => '127.0.0.1',
- 'name' => 'fossbilling',
- 'user' => 'fossbilling',
- 'password' => 'secret',
- ]);
-
- $dbConfig = DriverManagerFactory::getDatabaseConfig();
- $connection = DriverManagerFactory::getConnection();
-
- self::assertSame('pdo_mysql', $dbConfig['driver']);
- self::assertSame(3306, $dbConfig['port']);
- self::assertSame('pdo_mysql', $connection->getParams()['driver']);
- self::assertSame(3306, $connection->getParams()['port']);
- }
-
- protected function tearDown(): void
- {
- if ($this->originalConfigContents !== null) {
- file_put_contents(PATH_CONFIG, $this->originalConfigContents);
- clearstatcache(true, PATH_CONFIG);
-
- if (function_exists('opcache_invalidate')) {
- @opcache_invalidate(PATH_CONFIG, true);
- }
- }
-
- @unlink(Symfony\Component\Filesystem\Path::changeExtension(PATH_CONFIG, 'old.php'));
- }
-
- private function writeDbConfig(array $dbConfig): void
- {
- $config = FOSSBilling\Config::getConfig();
- $config['db'] = $dbConfig;
-
- $reflection = new ReflectionClass(FOSSBilling\Config::class);
- $method = $reflection->getMethod('prettyPrintArrayToPHP');
- $rendered = $method->invoke(null, $config);
-
- file_put_contents(PATH_CONFIG, $rendered);
- clearstatcache(true, PATH_CONFIG);
-
- if (function_exists('opcache_invalidate')) {
- @opcache_invalidate(PATH_CONFIG, true);
- }
- }
-}
diff --git a/tests-legacy/library/FOSSBilling/FOSSBilling_ModuleTest.php b/tests-legacy/library/FOSSBilling/FOSSBilling_ModuleTest.php
deleted file mode 100644
index 9f356b664..000000000
--- a/tests-legacy/library/FOSSBilling/FOSSBilling_ModuleTest.php
+++ /dev/null
@@ -1,66 +0,0 @@
-createMock('Box_Database');
- $db->expects($this->atLeastOnce())
- ->method('findOne')
- ->willReturn(null);
-
- $di = $this->getDi();
- $di['db'] = $db;
-
- $mod = new Module('api');
- $mod->setDi($di);
- $array = $mod->getConfig();
- $this->assertSame([], $array);
- }
-
- public function testCoreMod(): void
- {
- $mod = new Module('api');
- $this->assertTrue($mod->isCore());
-
- $array = $mod->getCoreModules();
- $this->assertIsArray($array);
-
- $mod = new Module('Cookieconsent');
- $this->assertFalse($mod->isCore());
- }
-
- public function testManifest(): void
- {
- $di = $this->getDi();
- $di['url'] = new \Box_Url();
-
- $mod = new Module('Cookieconsent');
- $mod->setDi($di);
-
- $bool = $mod->hasManifest();
- $this->assertTrue($bool);
-
- $array = $mod->getManifest();
- $this->assertIsArray($array);
- }
-
- public function testGetServiceSub(): void
- {
- $mod = new Module('Invoice');
- $subServiceName = 'transaction';
-
- $di = $this->getDi();
- $mod->setDi($di);
-
- $subService = $mod->getService($subServiceName);
- $this->assertInstanceOf(\Box\Mod\Invoice\ServiceTransaction::class, $subService);
- }
-}
diff --git a/tests-legacy/library/FOSSBilling/FOSSBilling_PaginationTest.php b/tests-legacy/library/FOSSBilling/FOSSBilling_PaginationTest.php
deleted file mode 100644
index 284e1a00a..000000000
--- a/tests-legacy/library/FOSSBilling/FOSSBilling_PaginationTest.php
+++ /dev/null
@@ -1,113 +0,0 @@
-getDi();
- $di['db'] = $db;
-
- $pagination = new Pagination();
- $pagination->setDi($di);
-
- return $pagination;
- }
-
- private function createDbMock(string $paginatedQuery, int $total = 100): Box_Database
- {
- $db = $this->getMockBuilder(Box_Database::class)
- ->disableOriginalConstructor()
- ->getMock();
-
- $db->expects($this->once())
- ->method('getAll')
- ->with($paginatedQuery, [])
- ->willReturn([]);
-
- $db->expects($this->once())
- ->method('getCell')
- ->with('SELECT COUNT(1) FROM (SELECT * FROM example) AS sub', [])
- ->willReturn($total);
-
- return $db;
- }
-
- public function testGetPaginatedResultSetUsesPaginationOptions(): void
- {
- $pagination = $this->createPagination(
- $this->createDbMock('SELECT * FROM example LIMIT 25, 25')
- );
-
- $result = $pagination->getPaginatedResultSet('SELECT * FROM example', [], PaginationOptions::fromArray(['page' => 2, 'per_page' => 25]));
-
- $this->assertSame(2, $result['page']);
- $this->assertSame(25, $result['per_page']);
- $this->assertSame(4, $result['pages']);
- }
-
- public function testGetPaginatedResultSetUsesPaginationOptionsConstructor(): void
- {
- $pagination = $this->createPagination(
- $this->createDbMock('SELECT * FROM example LIMIT 20, 10')
- );
-
- $result = $pagination->getPaginatedResultSet('SELECT * FROM example', [], new PaginationOptions(page: 3, perPage: 10));
-
- $this->assertSame(3, $result['page']);
- $this->assertSame(10, $result['per_page']);
- $this->assertSame(10, $result['pages']);
- }
-
- public function testNonIntegerPaginationOptionsDataUsesDefaults(): void
- {
- $pagination = $this->createPagination(
- $this->createDbMock('SELECT * FROM example LIMIT 0, 100')
- );
-
- $result = $pagination->getPaginatedResultSet('SELECT * FROM example', [], PaginationOptions::fromArray(['page' => 'abc', 'per_page' => '']));
-
- $this->assertSame(1, $result['page']);
- $this->assertSame(100, $result['per_page']);
- $this->assertSame(1, $result['pages']);
- }
-
- public function testPaginationOptionsSupportsCustomParameterNames(): void
- {
- $pagination = PaginationOptions::fromArray(['p' => 3, 'limit' => 15], 'p', 'limit');
-
- $this->assertSame(3, $pagination->page);
- $this->assertSame(15, $pagination->perPage);
- $this->assertSame('p', $pagination->pageParam);
- $this->assertSame('limit', $pagination->perPageParam);
- }
-
- public function testInvalidDataPageThrowsInformationException(): void
- {
- $db = $this->getMockBuilder(Box_Database::class)
- ->disableOriginalConstructor()
- ->getMock();
- $db->expects($this->never())->method('getAll');
-
- $this->expectException(InformationException::class);
- $this->expectExceptionMessage('Page number (page) must be a positive integer.');
-
- $pagination = $this->createPagination($db);
- $pagination->getPaginatedResultSet('SELECT * FROM example', [], PaginationOptions::fromArray(['page' => 0, 'per_page' => 25]));
- }
-
- public function testPerPageAboveMaximumThrowsInformationException(): void
- {
- $this->expectException(InformationException::class);
- $this->expectExceptionMessage('The number of items per page (per_page) is too large. Please specify a smaller number.');
-
- PaginationOptions::fromArray(['per_page' => PaginationOptions::MAX_PER_PAGE + 1]);
- }
-}
diff --git a/tests-legacy/library/FOSSBilling/FOSSBilling_PasswordManagerTest.php b/tests-legacy/library/FOSSBilling/FOSSBilling_PasswordManagerTest.php
deleted file mode 100644
index 3b514fce2..000000000
--- a/tests-legacy/library/FOSSBilling/FOSSBilling_PasswordManagerTest.php
+++ /dev/null
@@ -1,60 +0,0 @@
-setAlgo($algo);
- $result = $boxPassword->getAlgo();
- $this->assertEquals($algo, $result);
- }
-
- public function testSetOptions(): void
- {
- $boxPassword = new FOSSBilling\PasswordManager();
- $options = [
- 'cost' => 12,
- ];
- $boxPassword->setOptions($options);
- $result = $boxPassword->getOptions();
- $this->assertEquals($options, $result);
- }
-
- public function testHashing(): void
- {
- $boxPassword = new FOSSBilling\PasswordManager();
- $password = '123456';
- $hash = $boxPassword->hashIt($password);
- $this->assertIsString($hash);
- $this->assertNotEmpty($hash);
-
- $veryfied = $boxPassword->verify($password, $hash);
- $this->assertIsBool($veryfied);
- $this->assertTrue($veryfied);
-
- $needRehashing = $boxPassword->needsRehash($hash);
- $this->assertIsBool($needRehashing);
- $this->assertFalse($needRehashing);
- }
-
- public function testNeedsRehashing(): void
- {
- $boxPassword = new FOSSBilling\PasswordManager();
- $password = '123456';
- $hash = $boxPassword->hashIt($password);
- $this->assertIsString($hash);
- $this->assertNotEmpty($hash);
-
- $newOptions = ['cost' => 15];
- $boxPassword->setOptions($newOptions);
-
- $needRehashing = $boxPassword->needsRehash($hash);
- $this->assertIsBool($needRehashing);
- $this->assertTrue($needRehashing);
- }
-}
diff --git a/tests-legacy/library/FOSSBilling/FOSSBilling_RateLimiterTest.php b/tests-legacy/library/FOSSBilling/FOSSBilling_RateLimiterTest.php
deleted file mode 100644
index d94a99b30..000000000
--- a/tests-legacy/library/FOSSBilling/FOSSBilling_RateLimiterTest.php
+++ /dev/null
@@ -1,140 +0,0 @@
-createRateLimiter(requestIp: '1.1.1.1');
- $subject = 'subject-' . uniqid('', true);
-
- $first = $limiter->consume('api_guest', $subject, 100);
- $second = $limiter->consume('api_guest', $subject);
-
- $this->assertFalse($first->isLimited());
- $this->assertSame(FOSSBilling\Security\RateLimitResult::REASON_ALLOWED, $first->getReason());
- $this->assertTrue($second->isLimited());
- $this->assertSame(FOSSBilling\Security\RateLimitResult::REASON_LIMITED, $second->getReason());
- }
-
- public function testPasswordResetPolicyReportsLimitedResult(): void
- {
- $limiter = $this->createRateLimiter(requestIp: '1.1.1.1');
- $subject = 'subject-' . uniqid('', true);
-
- $limiter->consume('client_password_reset_email', $subject, 3);
- $second = $limiter->consume('client_password_reset_email', $subject);
-
- $this->assertTrue($second->isLimited());
- $this->assertSame(FOSSBilling\Security\RateLimitResult::REASON_LIMITED, $second->getReason());
- }
-
- public function testConsumeOrThrowReturnsAllowedResult(): void
- {
- $limiter = $this->createRateLimiter(requestIp: '1.1.1.1');
-
- $result = $limiter->consumeOrThrow('api_guest', 'subject-' . uniqid('', true));
-
- $this->assertFalse($result->isLimited());
- $this->assertSame(FOSSBilling\Security\RateLimitResult::REASON_ALLOWED, $result->getReason());
- }
-
- public function testConsumeOrThrowRaisesRateLimitException(): void
- {
- $limiter = $this->createRateLimiter(requestIp: '1.1.1.1');
- $subject = 'subject-' . uniqid('', true);
- $limiter->consume('client_password_reset_email', $subject, 3);
-
- try {
- $limiter->consumeOrThrow('client_password_reset_email', $subject);
- self::fail('Expected rate limit exception was not thrown.');
- } catch (FOSSBilling\Security\RateLimitException $exception) {
- $this->assertSame(429, $exception->getCode());
- $this->assertSame('Rate limit exceeded. Please try again later.', $exception->getMessage());
- $this->assertSame('client_password_reset_email', $exception->getRateLimitResult()->getPolicy());
- $this->assertTrue($exception->hasRetryAfter());
- $this->assertGreaterThan(0, $exception->getRetryAfterSeconds());
- $this->assertLessThanOrEqual(3600, $exception->getRetryAfterSeconds());
- }
- }
-
- public function testUnknownPolicyThrowsException(): void
- {
- $this->expectException(FOSSBilling\Exception::class);
- $this->expectExceptionMessage('Rate limiter policy unknown_policy is not defined or invalid');
-
- $limiter = $this->createRateLimiter(requestIp: '1.1.1.1');
- $limiter->consume('unknown_policy', 'subject');
- }
-
- public function testCidrWhitelistBypassesLimiter(): void
- {
- $limiter = $this->createRateLimiter(requestIp: '10.0.0.5', whitelist: ['10.0.0.0/8']);
-
- $result = $limiter->consume('api_guest', '10.0.0.5');
-
- $this->assertFalse($result->isLimited());
- $this->assertTrue($result->isBypassed());
- $this->assertSame(FOSSBilling\Security\RateLimitResult::REASON_WHITELISTED, $result->getReason());
- }
-
- public function testWhitelistUsesRequestIpForAuthenticatedSubjects(): void
- {
- $limiter = $this->createRateLimiter(requestIp: '10.0.0.5', whitelist: ['10.0.0.0/8']);
-
- $result = $limiter->consume('api_authenticated_account', 'client:123');
-
- $this->assertFalse($result->isLimited());
- $this->assertTrue($result->isBypassed());
- $this->assertSame(FOSSBilling\Security\RateLimitResult::REASON_WHITELISTED, $result->getReason());
- }
-
- public function testNonWhitelistedRequestIpLimitsAuthenticatedSubject(): void
- {
- $limiter = $this->createRateLimiter(requestIp: '1.1.1.1', whitelist: ['10.0.0.0/8']);
-
- $limiter->consume('client_email_verification_resend_account', 'client:123', 3);
- $second = $limiter->consume('client_email_verification_resend_account', 'client:123');
-
- $this->assertTrue($second->isLimited());
- $this->assertFalse($second->isBypassed());
- $this->assertSame(FOSSBilling\Security\RateLimitResult::REASON_LIMITED, $second->getReason());
- }
-
- private function createRateLimiter(string $requestIp, array $whitelist = []): FOSSBilling\Security\RateLimiter
- {
- $di = new Pimple\Container();
- $di['rate_limit_cache'] = new ArrayAdapter();
- $di['request'] = $this->createRequest($requestIp);
-
- $limiter = new class($whitelist) extends FOSSBilling\Security\RateLimiter {
- public function __construct(private readonly array $whitelist)
- {
- }
-
- protected function getConfig(): array
- {
- $config = self::getDefaultConfig();
- $config['whitelist_ips'] = $this->whitelist;
-
- return $config;
- }
- };
- $limiter->setDi($di);
-
- return $limiter;
- }
-
- private function createRequest(string $ip): Request
- {
- $request = $this->createMock(Request::class);
- $request->method('getClientIp')
- ->willReturn($ip);
-
- return $request;
- }
-}
diff --git a/tests-legacy/library/FOSSBilling/FOSSBilling_SessionTest.php b/tests-legacy/library/FOSSBilling/FOSSBilling_SessionTest.php
deleted file mode 100644
index d08b48ebd..000000000
--- a/tests-legacy/library/FOSSBilling/FOSSBilling_SessionTest.php
+++ /dev/null
@@ -1,65 +0,0 @@
-createSession();
-
- $result = $this->invokePrivate($session, 'isObsoleteSession', [[
- 'fb_session_obsolete' => true,
- ]]);
-
- $this->assertTrue($result);
- }
-
- public function testObsoleteSessionWithoutExpiryIsExpired(): void
- {
- $session = $this->createSession();
-
- $result = $this->invokePrivate($session, 'isObsoleteSessionExpired', [[
- 'fb_session_obsolete' => true,
- ], 100]);
-
- $this->assertTrue($result);
- }
-
- public function testObsoleteSessionExpiryHonorsGraceWindow(): void
- {
- $session = $this->createSession();
-
- $active = $this->invokePrivate($session, 'isObsoleteSessionExpired', [[
- 'fb_session_obsolete' => true,
- 'fb_session_obsolete_expires_at' => 150,
- ], 100]);
- $expired = $this->invokePrivate($session, 'isObsoleteSessionExpired', [[
- 'fb_session_obsolete' => true,
- 'fb_session_obsolete_expires_at' => 150,
- ], 151]);
-
- $this->assertFalse($active);
- $this->assertTrue($expired);
- }
-
- private function createSession(): FOSSBilling\Session
- {
- return new FOSSBilling\Session(new SessionHandlerStub());
- }
-
- private function invokePrivate(object $instance, string $method, array $args = []): mixed
- {
- $reflection = new ReflectionClass($instance);
- $methodReflection = $reflection->getMethod($method);
-
- return $methodReflection->invokeArgs($instance, $args);
- }
-}
diff --git a/tests-legacy/library/FOSSBilling/FOSSBilling_ToolsTest.php b/tests-legacy/library/FOSSBilling/FOSSBilling_ToolsTest.php
deleted file mode 100644
index 0e6d9afb5..000000000
--- a/tests-legacy/library/FOSSBilling/FOSSBilling_ToolsTest.php
+++ /dev/null
@@ -1,169 +0,0 @@
-assertSame('', FOSSBilling\Tools::sanitizeContent(''));
- }
-
- public function testSanitizeContentRemovesNullBytes(): void
- {
- $input = "Hello\0World";
- $result = FOSSBilling\Tools::sanitizeContent($input, false);
- $this->assertStringNotContainsString("\0", $result);
- $this->assertSame('HelloWorld', $result);
- }
-
- public function testSanitizeContentStripsAllHtml(): void
- {
- $input = 'Hello World
';
- $result = FOSSBilling\Tools::sanitizeContent($input, false);
- $this->assertSame('Hello World', $result);
- }
-
- public function testSanitizeContentEscapesSpecialChars(): void
- {
- $input = 'Test ';
- $result = FOSSBilling\Tools::sanitizeContent($input, true);
- $this->assertStringNotContainsString('Content
', true)
- )
- ->willReturn(1);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $this->adminApi->setDi($di);
-
- $this->adminApi->setService($serviceMock);
- $this->adminApi->setIdentity(new \Model_Admin());
-
- $data = [
- 'id' => 1,
- 'content' => 'Content
',
- ];
- $result = $this->adminApi->public_ticket_reply($data);
-
- $this->assertIsInt($result);
- }
-
- public function testPublicTicketGetStatuses(): void
- {
- $statuses = [
- \Model_SupportPTicket::OPENED => 'Open',
- \Model_SupportPTicket::ONHOLD => 'On Hold',
- \Model_SupportPTicket::CLOSED => 'Closed',
- ];
- $serviceMock = $this->getMockBuilder(\Box\Mod\Support\Service::class)
- ->onlyMethods(['publicGetStatuses', 'publicCounter'])->getMock();
- $serviceMock->expects($this->never())->method('publicGetStatuses')
- ->willReturn($statuses);
- $serviceMock->expects($this->atLeastOnce())->method('publicCounter')
- ->willReturn($statuses);
-
- $this->adminApi->setService($serviceMock);
-
- $result = $this->adminApi->public_ticket_get_statuses([]);
-
- $this->assertEquals($result, $statuses);
- }
-
- public function testPublicTicketGetStatusesTitlesSet(): void
- {
- $statuses = [
- \Model_SupportPTicket::OPENED => 'Open',
- \Model_SupportPTicket::ONHOLD => 'On Hold',
- \Model_SupportPTicket::CLOSED => 'Closed',
- ];
- $serviceMock = $this->getMockBuilder(\Box\Mod\Support\Service::class)
- ->onlyMethods(['publicGetStatuses', 'publicCounter'])->getMock();
- $serviceMock->expects($this->atLeastOnce())->method('publicGetStatuses')
- ->willReturn($statuses);
- $serviceMock->expects($this->never())->method('publicCounter')
- ->willReturn($statuses);
-
- $this->adminApi->setService($serviceMock);
-
- $data = [
- 'titles' => true,
- ];
- $result = $this->adminApi->public_ticket_get_statuses($data);
-
- $this->assertEquals($result, $statuses);
- }
-
- public function testHelpdeksGetList(): void
- {
- $paginatorMock = $this->getMockBuilder(\FOSSBilling\Pagination::class)
- ->onlyMethods(['getPaginatedResultSet'])
- ->disableOriginalConstructor()
- ->getMock();
- $paginatorMock->expects($this->atLeastOnce())
- ->method('getPaginatedResultSet')
- ->willReturn([]);
-
- $serviceMock = $this->getMockBuilder(\Box\Mod\Support\Service::class)
- ->onlyMethods(['helpdeskGetSearchQuery'])->getMock();
- $serviceMock->expects($this->atLeastOnce())->method('helpdeskGetSearchQuery')
- ->willReturn(['query', []]);
-
- $di = $this->getDi();
- $di['pager'] = $paginatorMock;
-
- $this->adminApi->setDi($di);
-
- $this->adminApi->setService($serviceMock);
-
- $data = [];
- $result = $this->adminApi->helpdesk_get_list($data);
-
- $this->assertIsArray($result);
- }
-
- public function testHelpdeksGetPairs(): void
- {
- $serviceMock = $this->getMockBuilder(\Box\Mod\Support\Service::class)
- ->onlyMethods(['helpdeskGetPairs'])->getMock();
- $serviceMock->expects($this->atLeastOnce())->method('helpdeskGetPairs')
- ->willReturn([]);
-
- $this->adminApi->setService($serviceMock);
-
- $data = [];
- $result = $this->adminApi->helpdesk_get_pairs($data);
-
- $this->assertIsArray($result);
- }
-
- public function testHelpdeskGet(): void
- {
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('getExistingModelById')
- ->willReturn(new \Model_SupportHelpdesk());
-
- $serviceMock = $this->getMockBuilder(\Box\Mod\Support\Service::class)
- ->onlyMethods(['helpdeskToApiArray'])->getMock();
- $serviceMock->expects($this->atLeastOnce())->method('helpdeskToApiArray')
- ->willReturn([]);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $this->adminApi->setDi($di);
-
- $this->adminApi->setService($serviceMock);
- $this->adminApi->setIdentity(new \Model_Admin());
-
- $data = [
- 'id' => 1,
- ];
- $result = $this->adminApi->helpdesk_get($data);
-
- $this->assertIsArray($result);
- }
-
- public function testHelpdeskUpdate(): void
- {
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('getExistingModelById')
- ->willReturn(new \Model_SupportHelpdesk());
-
- $serviceMock = $this->getMockBuilder(\Box\Mod\Support\Service::class)
- ->onlyMethods(['helpdeskUpdate'])->getMock();
- $serviceMock->expects($this->atLeastOnce())->method('helpdeskUpdate')
- ->willReturn(true);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $this->adminApi->setDi($di);
-
- $this->adminApi->setService($serviceMock);
- $this->adminApi->setIdentity(new \Model_Admin());
-
- $data = [
- 'id' => 1,
- ];
- $result = $this->adminApi->helpdesk_update($data);
-
- $this->assertTrue($result);
- }
-
- public function testHelpdeskCreate(): void
- {
- $serviceMock = $this->getMockBuilder(\Box\Mod\Support\Service::class)
- ->onlyMethods(['helpdeskCreate'])->getMock();
- $serviceMock->expects($this->atLeastOnce())->method('helpdeskCreate')
- ->willReturn(1);
-
- $di = $this->getDi();
- $this->adminApi->setDi($di);
-
- $this->adminApi->setService($serviceMock);
- $this->adminApi->setIdentity(new \Model_Admin());
-
- $data = [
- 'id' => 1,
- ];
- $result = $this->adminApi->helpdesk_create($data);
-
- $this->assertIsInt($result);
- }
-
- public function testHelpdeskDelete(): void
- {
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('getExistingModelById')
- ->willReturn(new \Model_SupportHelpdesk());
-
- $serviceMock = $this->getMockBuilder(\Box\Mod\Support\Service::class)
- ->onlyMethods(['helpdeskRm'])->getMock();
- $serviceMock->expects($this->atLeastOnce())->method('helpdeskRm')
- ->willReturn(true);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $this->adminApi->setDi($di);
-
- $this->adminApi->setService($serviceMock);
- $this->adminApi->setIdentity(new \Model_Admin());
-
- $data = [
- 'id' => 'General',
- ];
- $result = $this->adminApi->helpdesk_delete($data);
-
- $this->assertTrue($result);
- }
-
- public function testCannedGetList(): void
- {
- $resultSet = [
- 'list' => [
- 0 => ['id' => 1],
- ],
- ];
- $paginatorMock = $this->getMockBuilder(\FOSSBilling\Pagination::class)
- ->onlyMethods(['getPaginatedResultSet'])
- ->disableOriginalConstructor()
- ->getMock();
- $paginatorMock->expects($this->atLeastOnce())
- ->method('getPaginatedResultSet')
- ->willReturn($resultSet);
-
- $serviceMock = $this->getMockBuilder(\Box\Mod\Support\Service::class)
- ->onlyMethods(['cannedGetSearchQuery', 'cannedToApiArray'])->getMock();
- $serviceMock->expects($this->atLeastOnce())->method('cannedGetSearchQuery')
- ->willReturn(['query', []]);
- $serviceMock->expects($this->atLeastOnce())->method('cannedToApiArray')
- ->willReturn([]);
-
- $model = new \Model_SupportPr();
- $model->loadBean(new \DummyBean());
- $dbMock = $this->createMock('\Box_DAtabase');
- $dbMock->expects($this->atLeastOnce())
- ->method('getExistingModelById')
- ->willReturn($model);
-
- $di = $this->getDi();
- $di['pager'] = $paginatorMock;
- $di['db'] = $dbMock;
-
- $this->adminApi->setDi($di);
-
- $this->adminApi->setService($serviceMock);
-
- $data = [];
- $result = $this->adminApi->canned_get_list($data);
-
- $this->assertIsArray($result);
- }
-
- public function testCannedPairs(): void
- {
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('getAssoc')
- ->willReturn([1 => 'Title']);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $this->adminApi->setDi($di);
-
- $data = [];
- $result = $this->adminApi->canned_pairs();
-
- $this->assertIsArray($result);
- }
-
- public function testCannedGet(): void
- {
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('getExistingModelById')
- ->willReturn(new \Model_SupportPr());
-
- $serviceMock = $this->getMockBuilder(\Box\Mod\Support\Service::class)
- ->onlyMethods(['cannedToApiArray'])->getMock();
- $serviceMock->expects($this->atLeastOnce())->method('cannedToApiArray')
- ->willReturn([]);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $this->adminApi->setDi($di);
-
- $this->adminApi->setService($serviceMock);
- $this->adminApi->setIdentity(new \Model_Admin());
-
- $data = [
- 'id' => 1,
- ];
- $result = $this->adminApi->canned_get($data);
-
- $this->assertIsArray($result);
- }
-
- public function testCannedDelete(): void
- {
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('getExistingModelById')
- ->willReturn(new \Model_SupportPr());
-
- $serviceMock = $this->getMockBuilder(\Box\Mod\Support\Service::class)
- ->onlyMethods(['cannedRm'])->getMock();
- $serviceMock->expects($this->atLeastOnce())->method('cannedRm')
- ->willReturn(true);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $this->adminApi->setDi($di);
-
- $this->adminApi->setService($serviceMock);
- $this->adminApi->setIdentity(new \Model_Admin());
-
- $data = [
- 'id' => 1,
- ];
- $result = $this->adminApi->canned_delete($data);
-
- $this->assertTrue($result);
- }
-
- public function testCannedCreate(): void
- {
- $serviceMock = $this->getMockBuilder(\Box\Mod\Support\Service::class)
- ->onlyMethods(['cannedCreate'])->getMock();
- $serviceMock->expects($this->atLeastOnce())->method('cannedCreate')
- ->willReturn(1);
-
- $di = $this->getDi();
- $this->adminApi->setDi($di);
-
- $this->adminApi->setService($serviceMock);
- $this->adminApi->setIdentity(new \Model_Admin());
-
- $data = [
- 'title' => 'Title',
- 'category_id' => random_int(1, 100),
- 'content' => 'Content',
- ];
- $result = $this->adminApi->canned_create($data);
-
- $this->assertIsInt($result);
- }
-
- public function testCannedUpdate(): void
- {
- $serviceMock = $this->getMockBuilder(\Box\Mod\Support\Service::class)
- ->onlyMethods(['cannedUpdate'])->getMock();
- $serviceMock->expects($this->atLeastOnce())->method('cannedUpdate')
- ->willReturn(true);
-
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('getExistingModelById')
- ->willReturn(new \Model_SupportPr());
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $this->adminApi->setDi($di);
-
- $this->adminApi->setService($serviceMock);
- $this->adminApi->setIdentity(new \Model_Admin());
-
- $data = [
- 'id' => 'Title',
- ];
- $result = $this->adminApi->canned_update($data);
-
- $this->assertTrue($result);
- }
-
- public function testCannedCategoryPairs(): void
- {
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('getAssoc')
- ->willReturn([1 => 'Category 1']);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $this->adminApi->setDi($di);
-
- $this->adminApi->setIdentity(new \Model_Admin());
-
- $data = [
- 'id' => 'Title',
- ];
- $result = $this->adminApi->canned_category_pairs($data);
-
- $this->assertIsArray($result);
- }
-
- public function testCannedCategoryGet(): void
- {
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('getExistingModelById')
- ->willReturn(new \Model_SupportPrCategory());
-
- $serviceMock = $this->getMockBuilder(\Box\Mod\Support\Service::class)
- ->onlyMethods(['cannedCategoryToApiArray'])->getMock();
- $serviceMock->expects($this->atLeastOnce())->method('cannedCategoryToApiArray')
- ->willReturn([]);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $this->adminApi->setDi($di);
-
- $this->adminApi->setService($serviceMock);
- $this->adminApi->setIdentity(new \Model_Admin());
-
- $data = [
- 'id' => 1,
- ];
- $result = $this->adminApi->canned_category_get($data);
-
- $this->assertIsArray($result);
- }
-
- public function testCannedCategoryUpdate(): void
- {
- $supportCategory = new \Model_SupportPrCategory();
- $supportCategory->loadBean(new \DummyBean());
-
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('getExistingModelById')
- ->willReturn($supportCategory);
-
- $serviceMock = $this->getMockBuilder(\Box\Mod\Support\Service::class)
- ->onlyMethods(['cannedCategoryUpdate'])->getMock();
- $serviceMock->expects($this->atLeastOnce())->method('cannedCategoryUpdate')
- ->willReturn(true);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
-
- $this->adminApi->setDi($di);
-
- $this->adminApi->setService($serviceMock);
- $this->adminApi->setIdentity(new \Model_Admin());
-
- $data = [
- 'id' => 1,
- 'title' => 'Updated Title',
- ];
- $result = $this->adminApi->canned_category_update($data);
-
- $this->assertTrue($result);
- }
-
- public function testCannedCategoryDelete(): void
- {
- $supportCategory = new \Model_SupportPrCategory();
- $supportCategory->loadBean(new \DummyBean());
-
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('getExistingModelById')
- ->willReturn($supportCategory);
-
- $serviceMock = $this->getMockBuilder(\Box\Mod\Support\Service::class)
- ->onlyMethods(['cannedCategoryRm'])->getMock();
- $serviceMock->expects($this->atLeastOnce())->method('cannedCategoryRm')
- ->willReturn(true);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $this->adminApi->setDi($di);
-
- $this->adminApi->setService($serviceMock);
- $this->adminApi->setIdentity(new \Model_Admin());
-
- $data = [
- 'id' => 1,
- ];
- $result = $this->adminApi->canned_category_delete($data);
-
- $this->assertTrue($result);
- }
-
- public function testCannedCategoryCreate(): void
- {
- $serviceMock = $this->getMockBuilder(\Box\Mod\Support\Service::class)
- ->onlyMethods(['cannedCategoryCreate'])->getMock();
- $serviceMock->expects($this->atLeastOnce())->method('cannedCategoryCreate')
- ->willReturn(1);
-
- $di = $this->getDi();
- $this->adminApi->setDi($di);
-
- $this->adminApi->setService($serviceMock);
-
- $data = [
- 'title' => 'Title',
- ];
- $result = $this->adminApi->canned_category_create($data);
-
- $this->assertIsInt($result);
- }
-
- public function testCannedNoteCreate(): void
- {
- $serviceMock = $this->getMockBuilder(\Box\Mod\Support\Service::class)
- ->onlyMethods(['noteCreate'])->getMock();
- $serviceMock->expects($this->atLeastOnce())->method('noteCreate')
- ->willReturn(1);
-
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('getExistingModelById')
- ->willReturn(new \Model_SupportTicket());
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $this->adminApi->setDi($di);
-
- $this->adminApi->setService($serviceMock);
- $this->adminApi->setIdentity(new \Model_Admin());
-
- $data = [
- 'ticket_id' => 1,
- 'note' => 'Note',
- ];
- $result = $this->adminApi->note_create($data);
-
- $this->assertIsInt($result);
- }
-
- public function testCannedNoteDelete(): void
- {
- $serviceMock = $this->getMockBuilder(\Box\Mod\Support\Service::class)
- ->onlyMethods(['noteRm'])->getMock();
- $serviceMock->expects($this->atLeastOnce())->method('noteRm')
- ->willReturn(true);
-
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('getExistingModelById')
- ->willReturn(new \Model_SupportTicketNote());
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $this->adminApi->setDi($di);
-
- $this->adminApi->setService($serviceMock);
- $this->adminApi->setIdentity(new \Model_Admin());
-
- $data = [
- 'id' => 1,
- ];
- $result = $this->adminApi->note_delete($data);
-
- $this->assertTrue($result);
- }
-
- public function testTaskComplete(): void
- {
- $serviceMock = $this->getMockBuilder(\Box\Mod\Support\Service::class)
- ->onlyMethods(['ticketTaskComplete'])->getMock();
- $serviceMock->expects($this->atLeastOnce())->method('ticketTaskComplete')
- ->willReturn(true);
-
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('getExistingModelById')
- ->willReturn(new \Model_SupportTicket());
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $this->adminApi->setDi($di);
-
- $this->adminApi->setService($serviceMock);
-
- $data = [
- 'id' => 1,
- ];
- $result = $this->adminApi->task_complete($data);
-
- $this->assertTrue($result);
- }
-
- public function testBatchDelete(): void
- {
- $activityMock = $this->getMockBuilder(\Box\Mod\Support\Api\Admin::class)->onlyMethods(['ticket_delete'])->getMock();
- $activityMock->expects($this->atLeastOnce())->method('ticket_delete')->willReturn(true);
-
- $di = $this->getDi();
- $activityMock->setDi($di);
-
- $result = $activityMock->batch_delete(['ids' => [1, 2, 3]]);
- $this->assertTrue($result);
- }
-
- public function testBatchDeletePublic(): void
- {
- $activityMock = $this->getMockBuilder(\Box\Mod\Support\Api\Admin::class)->onlyMethods(['public_ticket_delete'])->getMock();
- $activityMock->expects($this->atLeastOnce())->method('public_ticket_delete')->willReturn(true);
-
- $di = $this->getDi();
- $activityMock->setDi($di);
-
- $result = $activityMock->batch_delete_public(['ids' => [1, 2, 3]]);
- $this->assertTrue($result);
- }
-
- /*
- * Knowledge Base Tests.
- */
-
- public function testKbArticleGetList(): void
- {
- $di = $this->getDi();
-
- $adminApi = $this->createAdminApi(\Box\Mod\Support\Api\Admin::class);
- $adminApi->setDi($di);
-
- $data = [
- 'status' => 'status',
- 'search' => 'search',
- 'kb_article_category_id' => 'category',
- ];
-
- $kbService = $this->getMockBuilder(\Box\Mod\Support\Service::class)->onlyMethods(['kbSearchArticles'])->getMock();
- $kbService->expects($this->atLeastOnce())
- ->method('kbSearchArticles')
- ->with(
- 'status',
- 'search',
- 'category',
- $this->isInstanceOf(\FOSSBilling\PaginationOptions::class)
- )
- ->willReturn(['list' => []]);
-
- $adminApi->setService($kbService);
-
- $result = $adminApi->kb_article_get_list($data);
- $this->assertIsArray($result);
- }
-
- public function testKbArticleGet(): void
- {
- $adminApi = $this->createAdminApi(\Box\Mod\Support\Api\Admin::class);
-
- $data = [
- 'id' => 1,
- ];
-
- $db = $this->createMock('Box_Database');
- $db->expects($this->atLeastOnce())
- ->method('findOne')
- ->willReturn(new \Model_SupportKbArticle());
-
- $admin = new \Model_Admin();
- $admin->loadBean(new \DummyBean());
-
- $admin->id = 5;
-
- $di = $this->getDi();
- $di['loggedin_admin'] = $admin;
- $di['db'] = $db;
-
- $adminApi->setDi($di);
-
- $kbService = $this->getMockBuilder(\Box\Mod\Support\Service::class)->onlyMethods(['kbToApiArray'])->getMock();
- $kbService->expects($this->atLeastOnce())
- ->method('kbToApiArray')
- ->willReturn([]);
- $adminApi->setService($kbService);
-
- $result = $adminApi->kb_article_get($data);
- $this->assertIsArray($result);
- }
-
- public function testKbArticleGetNotFoundException(): void
- {
- $adminApi = $this->createAdminApi(\Box\Mod\Support\Api\Admin::class);
-
- $data = [
- 'id' => 1,
- ];
-
- $db = $this->createMock('Box_Database');
- $db->expects($this->atLeastOnce())
- ->method('findOne')
- ->willReturn(false);
-
- $di = $this->getDi();
- $di['db'] = $db;
-
- $adminApi->setDi($di);
- $this->expectException(\FOSSBilling\Exception::class);
- $adminApi->kb_article_get($data);
- }
-
- public function testKbArticleCreate(): void
- {
- $adminApi = $this->createAdminApi(\Box\Mod\Support\Api\Admin::class);
-
- $data = [
- 'kb_article_category_id' => 1,
- 'title' => 'Title',
- ];
-
- $id = 1;
-
- $di = $this->getDi();
-
- $kbService = $this->getMockBuilder(\Box\Mod\Support\Service::class)->onlyMethods(['kbCreateArticle'])->getMock();
- $kbService->expects($this->atLeastOnce())
- ->method('kbCreateArticle')
- ->willReturn($id);
- $adminApi->setService($kbService);
-
- $adminApi->setDi($di);
-
- $result = $adminApi->kb_article_create($data);
- $this->assertIsInt($result);
- $this->assertEquals($result, $id);
- }
-
- public function testKbArticleUpdate(): void
- {
- $adminApi = $this->createAdminApi(\Box\Mod\Support\Api\Admin::class);
-
- $data = [
- 'id' => 1,
- 'kb_article_category_id' => 1,
- 'title' => 'Title',
- 'slug' => 'article-slug',
- 'status' => 'active',
- 'content' => 'Content',
- 'views' => 1,
- ];
-
- $kbService = $this->getMockBuilder(\Box\Mod\Support\Service::class)->onlyMethods(['kbUpdateArticle'])->getMock();
- $kbService->expects($this->atLeastOnce())
- ->method('kbUpdateArticle')
- ->willReturn(true);
- $di = $this->getDi();
-
- $adminApi->setDi($di);
-
- $adminApi->setService($kbService);
-
- $result = $adminApi->kb_article_update($data);
- $this->assertTrue($result);
- }
-
- public function testKbArticleDelete(): void
- {
- $adminApi = $this->createAdminApi(\Box\Mod\Support\Api\Admin::class);
-
- $data = [
- 'id' => 1,
- ];
-
- $db = $this->createMock('Box_Database');
- $db->expects($this->atLeastOnce())
- ->method('findOne')
- ->willReturn(new \Model_SupportKbArticle());
-
- $di = $this->getDi();
- $di['db'] = $db;
-
- $adminApi->setDi($di);
-
- $kbService = $this->getMockBuilder(\Box\Mod\Support\Service::class)->onlyMethods(['kbRm'])->getMock();
- $kbService->expects($this->atLeastOnce())
- ->method('kbRm')
- ;
- $adminApi->setService($kbService);
-
- $result = $adminApi->kb_article_delete($data);
- $this->assertTrue($result);
- }
-
- public function testKbArticleDeleteNotFoundException(): void
- {
- $adminApi = $this->createAdminApi(\Box\Mod\Support\Api\Admin::class);
-
- $db = $this->createMock('Box_Database');
- $db->expects($this->atLeastOnce())
- ->method('findOne')
- ->willReturn(false);
-
- $di = $this->getDi();
- $di['db'] = $db;
-
- $adminApi->setDi($di);
-
- $kbService = $this->getMockBuilder(\Box\Mod\Support\Service::class)->onlyMethods(['kbRm'])->getMock();
- $kbService->expects($this->never())
- ->method('kbRm')
- ;
- $adminApi->setService($kbService);
-
- $this->expectException(\FOSSBilling\Exception::class);
- $result = $adminApi->kb_article_delete(['id' => 1]);
- $this->assertTrue($result);
- }
-
- public function testKbCategoryGetList(): void
- {
- $adminApi = $this->createAdminApi(\Box\Mod\Support\Api\Admin::class);
-
- $willReturn = [
- 'pages' => 5,
- 'page' => 2,
- 'per_page' => 2,
- 'total' => 10,
- 'list' => [],
- ];
-
- $kbService = $this->getMockBuilder(\Box\Mod\Support\Service::class)->onlyMethods(['kbCategoryGetSearchQuery'])->getMock();
- $kbService->expects($this->atLeastOnce())
- ->method('kbCategoryGetSearchQuery')
- ->willReturn(['String', []]);
-
- $pager = $this->getMockBuilder(\FOSSBilling\Pagination::class)
- ->onlyMethods(['getPaginatedResultSet'])
- ->getMock();
-
- $pager->expects($this->atLeastOnce())
- ->method('getPaginatedResultSet')
- ->willReturn($willReturn);
-
- $di = $this->getDi();
- $di['pager'] = $pager;
-
- $adminApi->setDi($di);
- $adminApi->setService($kbService);
-
- $result = $adminApi->kb_category_get_list([]);
- $this->assertIsArray($result);
- $this->assertEquals($result, $willReturn);
- }
-
- public function testKbCategoryGet(): void
- {
- $adminApi = $this->createAdminApi(\Box\Mod\Support\Api\Admin::class);
-
- $db = $this->createMock('Box_Database');
- $db->expects($this->atLeastOnce())
- ->method('findOne')
- ->willReturn(new \Model_SupportKbArticleCategory());
-
- $di = $this->getDi();
- $di['db'] = $db;
- $di['validator'] = new \FOSSBilling\Validate();
-
- $adminApi->setDi($di);
-
- $kbService = $this->getMockBuilder(\Box\Mod\Support\Service::class)->onlyMethods(['kbCategoryToApiArray'])->getMock();
- $kbService->expects($this->atLeastOnce())
- ->method('kbCategoryToApiArray')
- ->willReturn([]);
- $adminApi->setService($kbService);
-
- $data = [
- 'id' => 1,
- ];
- $result = $adminApi->kb_category_get($data);
- $this->assertIsArray($result);
- }
-
- public function testKbCategoryGetIdNotSetException(): void
- {
- $adminApi = $this->createAdminApi(\Box\Mod\Support\Api\Admin::class);
-
- $db = $this->createMock('Box_Database');
- $db->expects($this->never())
- ->method('findOne')
- ->willReturn(new \Model_SupportKbArticleCategory());
-
- $di = $this->getDi();
- $di['db'] = $db;
- $di['validator'] = new \FOSSBilling\Validate();
-
- $adminApi->setDi($di);
-
- $kbService = $this->getMockBuilder(\Box\Mod\Support\Service::class)->onlyMethods(['kbCategoryToApiArray'])->getMock();
- $kbService->expects($this->never())
- ->method('kbCategoryToApiArray')
- ->willReturn([]);
- $adminApi->setService($kbService);
-
- $this->expectException(\FOSSBilling\Exception::class);
- $this->validateRequiredParams($adminApi, 'kb_category_get', []);
- $result = $adminApi->kb_category_get([]);
- $this->assertIsArray($result);
- }
-
- public function testKbCategoryGetNotFoundException(): void
- {
- $adminApi = $this->createAdminApi(\Box\Mod\Support\Api\Admin::class);
-
- $db = $this->createMock('Box_Database');
- $db->expects($this->atLeastOnce())
- ->method('findOne')
- ->willReturn(false);
-
- $di = $this->getDi();
-
- $di['db'] = $db;
- $di['validator'] = new \FOSSBilling\Validate();
- $adminApi->setDi($di);
-
- $kbService = $this->getMockBuilder(\Box\Mod\Support\Service::class)->onlyMethods(['kbCategoryToApiArray'])->getMock();
- $kbService->expects($this->never())
- ->method('kbCategoryToApiArray')
- ->willReturn([]);
- $adminApi->setService($kbService);
-
- $data = [
- 'id' => 1,
- ];
-
- $this->expectException(\FOSSBilling\Exception::class);
- $result = $adminApi->kb_category_get($data);
- $this->assertIsArray($result);
- }
-
- public function testKbCategoryCreate(): void
- {
- $adminApi = $this->createAdminApi(\Box\Mod\Support\Api\Admin::class);
-
- $kbService = $this->getMockBuilder(\Box\Mod\Support\Service::class)->onlyMethods(['kbCreateCategory'])->getMock();
- $kbService->expects($this->atLeastOnce())
- ->method('kbCreateCategory')
- ->willReturn(1);
- $adminApi->setService($kbService);
-
- $data = [
- 'title' => 'Title',
- 'description' => 'Description',
- ];
-
- $di = $this->getDi();
-
- $adminApi->setDi($di);
-
- $result = $adminApi->kb_category_create($data);
- $this->assertIsInt($result);
- }
-
- public function testKbCategoryUpdate(): void
- {
- $adminApi = $this->createAdminApi(\Box\Mod\Support\Api\Admin::class);
-
- $kbService = $this->getMockBuilder(\Box\Mod\Support\Service::class)->onlyMethods(['kbUpdateCategory'])->getMock();
- $kbService->expects($this->atLeastOnce())
- ->method('kbUpdateCategory')
- ->willReturn(true);
- $adminApi->setService($kbService);
-
- $db = $this->createMock('Box_Database');
- $db->expects($this->atLeastOnce())
- ->method('findOne')
- ->willReturn(new \Model_SupportKbArticleCategory());
-
- $di = $this->getDi();
- $di['db'] = $db;
- $di['validator'] = new \FOSSBilling\Validate();
-
- $adminApi->setDi($di);
-
- $data = [
- 'id' => 1,
- 'title' => 'Title',
- 'slug' => 'category-slug',
- 'description' => 'Description',
- ];
-
- $result = $adminApi->kb_category_update($data);
- $this->assertTrue($result);
- }
-
- public function testKbCategoryUpdateIdNotSet(): void
- {
- $adminApi = $this->createAdminApi(\Box\Mod\Support\Api\Admin::class);
-
- $kbService = $this->getMockBuilder(\Box\Mod\Support\Service::class)->onlyMethods(['kbUpdateCategory'])->getMock();
- $kbService->expects($this->never())
- ->method('kbUpdateCategory')
- ->willReturn(true);
- $adminApi->setService($kbService);
-
- $db = $this->createMock('Box_Database');
- $db->expects($this->never())
- ->method('findOne')
- ->willReturn(new \Model_SupportKbArticleCategory());
-
- $di = $this->getDi();
- $di['db'] = $db;
- $di['validator'] = new \FOSSBilling\Validate();
-
- $adminApi->setDi($di);
-
- $data = [];
-
- $this->expectException(\FOSSBilling\Exception::class);
- $this->validateRequiredParams($adminApi, 'kb_category_update', $data);
- $result = $adminApi->kb_category_update($data);
- $this->assertIsArray($result);
- }
-
- public function testKbCategoryUpdateNotFound(): void
- {
- $adminApi = $this->createAdminApi(\Box\Mod\Support\Api\Admin::class);
-
- $kbService = $this->getMockBuilder(\Box\Mod\Support\Service::class)->onlyMethods(['kbUpdateCategory'])->getMock();
- $kbService->expects($this->never())
- ->method('kbUpdateCategory')
- ->willReturn(true);
- $adminApi->setService($kbService);
-
- $db = $this->createMock('Box_Database');
- $db->expects($this->atLeastOnce())
- ->method('findOne')
- ->willReturn(false);
-
- $di = $this->getDi();
- $di['db'] = $db;
- $di['validator'] = new \FOSSBilling\Validate();
-
- $adminApi->setDi($di);
-
- $data = [
- 'id' => 1,
- 'title' => 'Title',
- 'slug' => 'category-slug',
- 'description' => 'Description',
- ];
-
- $this->expectException(\FOSSBilling\Exception::class);
- $result = $adminApi->kb_category_update($data);
- $this->assertIsArray($result);
- }
-
- public function testKbCategoryDelete(): void
- {
- $adminApi = $this->createAdminApi(\Box\Mod\Support\Api\Admin::class);
-
- $kbService = $this->getMockBuilder(\Box\Mod\Support\Service::class)->onlyMethods(['kbCategoryRm'])->getMock();
- $kbService->expects($this->atLeastOnce())
- ->method('kbCategoryRm')
- ->willReturn(true);
- $adminApi->setService($kbService);
-
- $db = $this->createMock('Box_Database');
- $db->expects($this->atLeastOnce())
- ->method('findOne')
- ->willReturn(new \Model_SupportKbArticleCategory());
-
- $di = $this->getDi();
- $di['db'] = $db;
- $di['validator'] = new \FOSSBilling\Validate();
-
- $adminApi->setDi($di);
-
- $data = [
- 'id' => 1,
- ];
- $result = $adminApi->kb_category_delete($data);
- $this->assertTrue($result);
- }
-
- public function testKbCategoryDeleteIdNotSet(): void
- {
- $adminApi = $this->createAdminApi(\Box\Mod\Support\Api\Admin::class);
-
- $kbService = $this->getMockBuilder(\Box\Mod\Support\Service::class)->onlyMethods(['kbCategoryRm'])->getMock();
- $kbService->expects($this->never())
- ->method('kbCategoryRm')
- ->willReturn(true);
- $adminApi->setService($kbService);
-
- $db = $this->createMock('Box_Database');
- $db->expects($this->never())
- ->method('findOne')
- ->willReturn(new \Model_SupportKbArticleCategory());
-
- $di = $this->getDi();
- $di['db'] = $db;
- $di['validator'] = new \FOSSBilling\Validate();
-
- $adminApi->setDi($di);
-
- $data = [];
- $this->expectException(\FOSSBilling\Exception::class);
- $this->validateRequiredParams($adminApi, 'kb_category_delete', $data);
- $result = $adminApi->kb_category_delete($data);
- $this->assertIsArray($result);
- }
-
- public function testKbCategoryDeleteNotFound(): void
- {
- $adminApi = $this->createAdminApi(\Box\Mod\Support\Api\Admin::class);
-
- $kbService = $this->getMockBuilder(\Box\Mod\Support\Service::class)->onlyMethods(['kbCategoryRm'])->getMock();
- $kbService->expects($this->never())
- ->method('kbCategoryRm')
- ->willReturn(true);
- $adminApi->setService($kbService);
-
- $db = $this->createMock('Box_Database');
- $db->expects($this->atLeastOnce())
- ->method('findOne')
- ->willReturn(false);
-
- $di = $this->getDi();
- $di['db'] = $db;
- $di['validator'] = new \FOSSBilling\Validate();
-
- $adminApi->setDi($di);
-
- $data = [
- 'id' => 1,
- ];
-
- $this->expectException(\FOSSBilling\Exception::class);
- $result = $adminApi->kb_category_delete($data);
- $this->assertIsArray($result);
- }
-
- public function testKbCategoryGetPairs(): void
- {
- $adminApi = $this->createAdminApi(\Box\Mod\Support\Api\Admin::class);
-
- $kbService = $this->getMockBuilder(\Box\Mod\Support\Service::class)->onlyMethods(['kbCategoryGetPairs'])->getMock();
- $kbService->expects($this->atLeastOnce())
- ->method('kbCategoryGetPairs')
- ->willReturn([]);
- $adminApi->setService($kbService);
-
- $result = $adminApi->kb_category_get_pairs([]);
- $this->assertIsArray($result);
- }
-}
diff --git a/tests-legacy/modules/Support/Api/Api_ClientTest.php b/tests-legacy/modules/Support/Api/Api_ClientTest.php
deleted file mode 100644
index de447464a..000000000
--- a/tests-legacy/modules/Support/Api/Api_ClientTest.php
+++ /dev/null
@@ -1,240 +0,0 @@
-clientApi = new \Box\Mod\Support\Api\Client();
- }
-
- public function testTicketGetList(): void
- {
- $simpleResultArr = [
- 'list' => [
- ['id' => 1],
- ],
- ];
- $paginatorMock = $this->getMockBuilder(\FOSSBilling\Pagination::class)
- ->onlyMethods(['getPaginatedResultSet'])
- ->disableOriginalConstructor()
- ->getMock();
- $paginatorMock->expects($this->atLeastOnce())
- ->method('getPaginatedResultSet')
- ->willReturn($simpleResultArr);
-
- $serviceMock = $this->getMockBuilder(\Box\Mod\Support\Service::class)
- ->onlyMethods(['getSearchQuery', 'toApiArray'])->getMock();
- $serviceMock->expects($this->atLeastOnce())->method('getSearchQuery')
- ->willReturn(['query', []]);
- $serviceMock->expects($this->atLeastOnce())
- ->method('toApiArray')
- ->willReturn([]);
-
- $model = new \Model_SupportTicket();
- $model->loadBean(new \DummyBean());
- $dbMock = $this->createMock('\Box_Database');
- $dbMock->expects($this->atLeastOnce())
- ->method('getExistingModelById')
- ->willReturn($model);
-
- $di = $this->getDi();
- $di['pager'] = $paginatorMock;
- $di['db'] = $dbMock;
-
- $this->clientApi->setDi($di);
-
- $client = new \Model_Client();
- $client->loadBean(new \DummyBean());
- $client->id = 1;
-
- $this->clientApi->setService($serviceMock);
- $this->clientApi->setIdentity($client);
-
- $data = [];
- $result = $this->clientApi->ticket_get_list($data);
-
- $this->assertIsArray($result);
- }
-
- public function testTicketGet(): void
- {
- $serviceMock = $this->getMockBuilder(\Box\Mod\Support\Service::class)
- ->onlyMethods(['findOneByClient', 'toApiArray'])->getMock();
- $serviceMock->expects($this->atLeastOnce())->method('findOneByClient')
- ->willReturn(new \Model_SupportTicket());
- $serviceMock->expects($this->atLeastOnce())->method('toApiArray')
- ->willReturn([]);
-
- $di = $this->getDi();
- $this->clientApi->setDi($di);
-
- $client = new \Model_Client();
- $client->loadBean(new \DummyBean());
- $client->id = 1;
-
- $this->clientApi->setService($serviceMock);
- $this->clientApi->setIdentity($client);
-
- $data = [
- 'id' => 1,
- ];
- $result = $this->clientApi->ticket_get($data);
-
- $this->assertIsArray($result);
- }
-
- public function testHelpdeskGetPairs(): void
- {
- $serviceMock = $this->getMockBuilder(\Box\Mod\Support\Service::class)
- ->onlyMethods(['helpdeskGetPairs'])->getMock();
- $serviceMock->expects($this->atLeastOnce())->method('helpdeskGetPairs')
- ->willReturn([0 => 'General']);
-
- $this->clientApi->setService($serviceMock);
-
- $result = $this->clientApi->helpdesk_get_pairs();
-
- $this->assertIsArray($result);
- }
-
- public function testTicketCreate(): void
- {
- $serviceMock = $this->getMockBuilder(\Box\Mod\Support\Service::class)
- ->onlyMethods(['ticketCreateForClient'])->getMock();
- $serviceMock->expects($this->atLeastOnce())->method('ticketCreateForClient')
- ->willReturn(1);
-
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('getExistingModelById')
- ->willReturn(new \Model_SupportHelpdesk());
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $this->clientApi->setDi($di);
-
- $client = new \Model_Client();
- $client->loadBean(new \DummyBean());
- $client->id = 1;
-
- $this->clientApi->setService($serviceMock);
- $this->clientApi->setIdentity($client);
-
- $data = [
- 'content' => 'Content',
- 'subject' => 'Subject',
- 'support_helpdesk_id' => 1,
- ];
- $result = $this->clientApi->ticket_create($data);
-
- $this->assertIsInt($result);
- }
-
- public function testTicketReply(): void
- {
- $serviceMock = $this->getMockBuilder(\Box\Mod\Support\Service::class)
- ->onlyMethods(['canBeReopened', 'ticketReply'])->getMock();
- $serviceMock->expects($this->atLeastOnce())->method('canBeReopened')
- ->willReturn(true);
- $serviceMock->expects($this->atLeastOnce())->method('ticketReply')
- ->willReturn(1);
-
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('findOne')
- ->willReturn(new \Model_SupportTicket());
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $this->clientApi->setDi($di);
-
- $client = new \Model_Client();
- $client->loadBean(new \DummyBean());
- $client->id = 1;
-
- $this->clientApi->setService($serviceMock);
- $this->clientApi->setIdentity($client);
-
- $data = [
- 'content' => 'Content',
- 'id' => 1,
- ];
- $result = $this->clientApi->ticket_reply($data);
-
- $this->assertIsBool($result);
- $this->assertTrue($result);
- }
-
- public function testTicketReplyCanNotBeReopenedException(): void
- {
- $serviceMock = $this->getMockBuilder(\Box\Mod\Support\Service::class)
- ->onlyMethods(['canBeReopened', 'ticketReply'])->getMock();
- $serviceMock->expects($this->atLeastOnce())->method('canBeReopened')
- ->willReturn(false);
- $serviceMock->expects($this->never())->method('ticketReply')
- ->willReturn(1);
-
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('findOne')
- ->willReturn(new \Model_SupportTicket());
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
-
- $this->clientApi->setDi($di);
-
- $client = new \Model_Client();
- $client->loadBean(new \DummyBean());
- $client->id = 1;
-
- $this->clientApi->setService($serviceMock);
- $this->clientApi->setIdentity($client);
-
- $data = [
- 'content' => 'Content',
- 'id' => 1,
- ];
- $this->expectException(\FOSSBilling\Exception::class);
- $result = $this->clientApi->ticket_reply($data);
-
- $this->assertIsInt($result);
- }
-
- public function testTicketClose(): void
- {
- $serviceMock = $this->getMockBuilder(\Box\Mod\Support\Service::class)
- ->onlyMethods(['findOneByClient', 'closeTicket'])->getMock();
- $serviceMock->expects($this->atLeastOnce())->method('findOneByClient')
- ->willReturn(new \Model_SupportTicket());
- $serviceMock->expects($this->atLeastOnce())->method('closeTicket')
- ->willReturn(true);
-
- $di = $this->getDi();
- $this->clientApi->setDi($di);
-
- $client = new \Model_Client();
- $client->loadBean(new \DummyBean());
- $client->id = 1;
-
- $this->clientApi->setService($serviceMock);
- $this->clientApi->setIdentity($client);
-
- $data = [
- 'content' => 'Content',
- 'id' => 1,
- ];
- $result = $this->clientApi->ticket_close($data);
-
- $this->assertTrue($result);
- }
-}
diff --git a/tests-legacy/modules/Support/Api/Api_GuestTest.php b/tests-legacy/modules/Support/Api/Api_GuestTest.php
deleted file mode 100644
index 738fc7213..000000000
--- a/tests-legacy/modules/Support/Api/Api_GuestTest.php
+++ /dev/null
@@ -1,582 +0,0 @@
-guestApi = new \Box\Mod\Support\Api\Guest();
- }
-
- public function testTicketCreate(): void
- {
- $serviceMock = $this->getMockBuilder(\Box\Mod\Support\Service::class)
- ->onlyMethods(['ticketCreateForGuest'])->getMock();
- $serviceMock->expects($this->atLeastOnce())->method('ticketCreateForGuest')
- ->willReturn(bin2hex(random_bytes(random_int(15, 30))));
-
- $di = $this->getDi();
- $rateLimiterMock = $this->createMock(\FOSSBilling\Security\RateLimiter::class);
- $rateLimiterMock->method('consumeOrThrow')->willReturn(new \FOSSBilling\Security\RateLimitResult('policy', false, 10, 9));
- $di['rate_limiter'] = $rateLimiterMock;
- $this->guestApi->setDi($di);
-
- $this->guestApi->setService($serviceMock);
-
- $data = [
- 'name' => 'Name',
- 'email' => 'email@example.com',
- 'subject' => 'Subject',
- 'message' => 'Message',
- ];
- $result = $this->guestApi->ticket_create($data);
-
- $this->assertIsString($result);
- $this->assertGreaterThan(0, strlen($result));
- }
-
- public function testTicketCreateMessageTooShortException(): void
- {
- $serviceMock = $this->getMockBuilder(\Box\Mod\Support\Service::class)
- ->onlyMethods(['ticketCreateForGuest'])->getMock();
- $serviceMock->expects($this->never())->method('ticketCreateForGuest')
- ->willReturn(sha1(uniqid()));
-
- $di = $this->getDi();
- $rateLimiterMock = $this->createMock(\FOSSBilling\Security\RateLimiter::class);
- $rateLimiterMock->method('consumeOrThrow')->willReturn(new \FOSSBilling\Security\RateLimitResult('policy', false, 10, 9));
- $di['rate_limiter'] = $rateLimiterMock;
- $this->guestApi->setDi($di);
-
- $this->guestApi->setService($serviceMock);
-
- $data = [
- 'name' => 'Name',
- 'email' => 'email@example.com',
- 'subject' => 'Subject',
- 'message' => '',
- ];
-
- $this->expectException(\FOSSBilling\Exception::class);
- $result = $this->guestApi->ticket_create($data);
-
- $this->assertIsString($result);
- $this->assertEquals(40, strlen($result));
- }
-
- public function testTicketCreateMessageArrayException(): void
- {
- $serviceMock = $this->getMockBuilder(\Box\Mod\Support\Service::class)
- ->onlyMethods(['ticketCreateForGuest'])->getMock();
- $serviceMock->expects($this->never())->method('ticketCreateForGuest');
-
- $di = $this->getDi();
- $rateLimiterMock = $this->createMock(\FOSSBilling\Security\RateLimiter::class);
- $rateLimiterMock->method('consumeOrThrow')->willReturn(new \FOSSBilling\Security\RateLimitResult('policy', false, 10, 9));
- $di['rate_limiter'] = $rateLimiterMock;
- $this->guestApi->setDi($di);
-
- $this->guestApi->setService($serviceMock);
-
- $data = [
- 'name' => 'Name',
- 'email' => 'email@example.com',
- 'subject' => 'Subject',
- 'message' => ['invalid'],
- ];
-
- $this->expectException(\FOSSBilling\Exception::class);
- $this->guestApi->ticket_create($data);
- }
-
- public function testTicketGet(): void
- {
- $serviceMock = $this->getMockBuilder(\Box\Mod\Support\Service::class)
- ->onlyMethods(['publicFindOneByHash', 'publicToApiArray'])->getMock();
- $serviceMock->expects($this->atLeastOnce())->method('publicFindOneByHash')
- ->willReturn(new \Model_SupportPTicket());
- $serviceMock->expects($this->atLeastOnce())->method('publicToApiArray')
- ->willReturn([]);
-
- $di = $this->getDi();
- $rateLimiterMock = $this->createMock(\FOSSBilling\Security\RateLimiter::class);
- $rateLimiterMock->method('consumeOrThrow')->willReturn(new \FOSSBilling\Security\RateLimitResult('policy', false, 10, 9));
- $di['rate_limiter'] = $rateLimiterMock;
- $this->guestApi->setDi($di);
-
- $this->guestApi->setService($serviceMock);
-
- $data = [
- 'hash' => sha1(uniqid()),
- ];
- $result = $this->guestApi->ticket_get($data);
-
- $this->assertIsArray($result);
- }
-
- public function testTicketClose(): void
- {
- $serviceMock = $this->getMockBuilder(\Box\Mod\Support\Service::class)
- ->onlyMethods(['publicFindOneByHash', 'publicCloseTicket'])->getMock();
- $serviceMock->expects($this->atLeastOnce())->method('publicFindOneByHash')
- ->willReturn(new \Model_SupportPTicket());
- $serviceMock->expects($this->atLeastOnce())->method('publicCloseTicket')
- ->willReturn(true);
-
- $di = $this->getDi();
- $rateLimiterMock = $this->createMock(\FOSSBilling\Security\RateLimiter::class);
- $rateLimiterMock->method('consumeOrThrow')->willReturn(new \FOSSBilling\Security\RateLimitResult('policy', false, 10, 9));
- $di['rate_limiter'] = $rateLimiterMock;
- $this->guestApi->setDi($di);
-
- $this->guestApi->setService($serviceMock);
- $this->guestApi->setIdentity(new \Model_Guest());
-
- $data = [
- 'hash' => sha1(uniqid()),
- ];
- $result = $this->guestApi->ticket_close($data);
-
- $this->assertTrue($result);
- }
-
- public function testTicketReply(): void
- {
- $serviceMock = $this->getMockBuilder(\Box\Mod\Support\Service::class)
- ->onlyMethods(['publicFindOneByHash', 'publicTicketReplyForGuest'])->getMock();
- $serviceMock->expects($this->atLeastOnce())->method('publicFindOneByHash')
- ->willReturn(new \Model_SupportPTicket());
- $serviceMock->expects($this->atLeastOnce())->method('publicTicketReplyForGuest')
- ->willReturn(sha1(uniqid()));
-
- $di = $this->getDi();
- $rateLimiterMock = $this->createMock(\FOSSBilling\Security\RateLimiter::class);
- $rateLimiterMock->method('consumeOrThrow')->willReturn(new \FOSSBilling\Security\RateLimitResult('policy', false, 10, 9));
- $di['rate_limiter'] = $rateLimiterMock;
- $this->guestApi->setDi($di);
-
- $this->guestApi->setService($serviceMock);
-
- $data = [
- 'hash' => sha1(uniqid()),
- 'message' => 'Message',
- ];
- $result = $this->guestApi->ticket_reply($data);
-
- $this->assertIsString($result);
- $this->assertEquals(40, strlen($result));
- }
-
- public function testTicketReplyMessageArrayException(): void
- {
- $serviceMock = $this->getMockBuilder(\Box\Mod\Support\Service::class)
- ->onlyMethods(['publicFindOneByHash', 'publicTicketReplyForGuest'])->getMock();
- $serviceMock->expects($this->atLeastOnce())->method('publicFindOneByHash')
- ->willReturn(new \Model_SupportPTicket());
- $serviceMock->expects($this->never())->method('publicTicketReplyForGuest');
-
- $di = $this->getDi();
- $rateLimiterMock = $this->createMock(\FOSSBilling\Security\RateLimiter::class);
- $rateLimiterMock->method('consumeOrThrow')->willReturn(new \FOSSBilling\Security\RateLimitResult('policy', false, 10, 9));
- $di['rate_limiter'] = $rateLimiterMock;
- $this->guestApi->setDi($di);
-
- $this->guestApi->setService($serviceMock);
-
- $data = [
- 'hash' => sha1(uniqid()),
- 'message' => ['invalid'],
- ];
-
- $this->expectException(\FOSSBilling\Exception::class);
- $this->guestApi->ticket_reply($data);
- }
-
- public function testPublicTicketsEnabled(): void
- {
- $serviceMock = $this->getMockBuilder(\Box\Mod\Support\Service::class)
- ->onlyMethods(['publicTicketsEnabled'])->getMock();
- $serviceMock->expects($this->once())->method('publicTicketsEnabled')
- ->willReturn(true);
-
- $this->guestApi->setService($serviceMock);
-
- $result = $this->guestApi->public_tickets_enabled();
-
- $this->assertTrue($result);
- }
-
- /*
- * Knowledge Base Tests.
- */
-
- public function testKbArticleGetList(): void
- {
- $guestApi = new \Box\Mod\Support\Api\Guest();
-
- $willReturn = [
- 'pages' => 5,
- 'page' => 2,
- 'per_page' => 2,
- 'total' => 10,
- 'list' => [],
- ];
-
- $supportService = $this->getMockBuilder(\Box\Mod\Support\Service::class)->onlyMethods(['kbSearchArticles'])->getMock();
- $supportService->expects($this->atLeastOnce())
- ->method('kbSearchArticles')
- ->willReturn($willReturn);
- $guestApi->setService($supportService);
-
- $di = $this->getDi();
-
- $guestApi->setDi($di);
- $result = $guestApi->kb_article_get_list([]);
- $this->assertIsArray($result);
- $this->assertEquals($result, $willReturn);
- }
-
- public function testKbArticleGetWithId(): void
- {
- $guestApi = new \Box\Mod\Support\Api\Guest();
-
- $di = $this->getDi();
-
- $guestApi->setDi($di);
-
- $supportService = $this->getMockBuilder(\Box\Mod\Support\Service::class)->onlyMethods(['kbFindActiveArticleById', 'kbHitView', 'kbToApiArray', 'kbFindActiveArticleBySlug'])->getMock();
- $supportService->expects($this->atLeastOnce())
- ->method('kbFindActiveArticleById')
- ->willReturn(new \Model_SupportKbArticle());
- $supportService->expects($this->never())
- ->method('kbFindActiveArticleBySlug')
- ->willReturn(new \Model_SupportKbArticle());
- $supportService->expects($this->atLeastOnce())
- ->method('kbHitView')
- ;
- $supportService->expects($this->atLeastOnce())
- ->method('kbToApiArray')
- ->willReturn([]);
- $guestApi->setService($supportService);
-
- $data = [
- 'id' => 1,
- ];
- $result = $guestApi->kb_article_get($data);
- $this->assertIsArray($result);
- }
-
- public function testKbArticleGetWithSlug(): void
- {
- $guestApi = new \Box\Mod\Support\Api\Guest();
-
- $di = $this->getDi();
-
- $guestApi->setDi($di);
-
- $supportService = $this->getMockBuilder(\Box\Mod\Support\Service::class)->onlyMethods(['kbFindActiveArticleById', 'kbHitView', 'kbToApiArray', 'kbFindActiveArticleBySlug'])->getMock();
- $supportService->expects($this->never())
- ->method('kbFindActiveArticleById')
- ->willReturn(new \Model_SupportKbArticle());
- $supportService->expects($this->atLeastOnce())
- ->method('kbFindActiveArticleBySlug')
- ->willReturn(new \Model_SupportKbArticle());
- $supportService->expects($this->atLeastOnce())
- ->method('kbHitView')
- ;
- $supportService->expects($this->atLeastOnce())
- ->method('kbToApiArray')
- ->willReturn([]);
- $guestApi->setService($supportService);
-
- $data = [
- 'slug' => 'article-slug',
- ];
- $result = $guestApi->kb_article_get($data);
- $this->assertIsArray($result);
- }
-
- public function testKbArticleGetIdAndSlugNotSetException(): void
- {
- $guestApi = new \Box\Mod\Support\Api\Guest();
-
- $kbService = $this->getMockBuilder(\Box\Mod\Support\Service::class)->onlyMethods(['kbFindActiveArticleById', 'kbHitView', 'kbToApiArray', 'kbFindActiveArticleBySlug'])->getMock();
- $kbService->expects($this->never())
- ->method('kbFindActiveArticleById')
- ->willReturn(new \Model_SupportKbArticle());
- $kbService->expects($this->never())
- ->method('kbFindActiveArticleBySlug')
- ->willReturn(new \Model_SupportKbArticle());
- $kbService->expects($this->never())
- ->method('kbHitView')
- ;
- $kbService->expects($this->never())
- ->method('kbToApiArray')
- ->willReturn([]);
- $guestApi->setService($kbService);
-
- $this->expectException(\FOSSBilling\Exception::class);
- $result = $guestApi->kb_article_get([]);
- $this->assertIsArray($result);
- }
-
- public function testKbArticleGetNotFoundById(): void
- {
- $guestApi = new \Box\Mod\Support\Api\Guest();
-
- $kbService = $this->getMockBuilder(\Box\Mod\Support\Service::class)->onlyMethods(['kbFindActiveArticleById', 'kbHitView', 'kbToApiArray', 'kbFindActiveArticleBySlug'])->getMock();
- $kbService->expects($this->atLeastOnce())
- ->method('kbFindActiveArticleById')
- ->willReturn(null);
- $kbService->expects($this->never())
- ->method('kbFindActiveArticleBySlug')
- ->willReturn(new \Model_SupportKbArticle());
- $kbService->expects($this->never())
- ->method('kbHitView')
- ;
- $kbService->expects($this->never())
- ->method('kbToApiArray')
- ->willReturn([]);
- $guestApi->setService($kbService);
-
- $data = [
- 'id' => 1,
- ];
-
- $di = $this->getDi();
-
- $guestApi->setDi($di);
- $this->expectException(\FOSSBilling\Exception::class);
- $result = $guestApi->kb_article_get($data);
- $this->assertIsArray($result);
- }
-
- public function testKbArticleGetNotFoundBySlug(): void
- {
- $guestApi = new \Box\Mod\Support\Api\Guest();
-
- $kbService = $this->getMockBuilder(\Box\Mod\Support\Service::class)->onlyMethods(['kbFindActiveArticleById', 'kbHitView', 'kbToApiArray', 'kbFindActiveArticleBySlug'])->getMock();
- $kbService->expects($this->never())
- ->method('kbFindActiveArticleById')
- ->willReturn(new \Model_SupportKbArticle());
- $kbService->expects($this->atLeastOnce())
- ->method('kbFindActiveArticleBySlug')
- ->willReturn(null);
- $kbService->expects($this->never())
- ->method('kbHitView')
- ;
- $kbService->expects($this->never())
- ->method('kbToApiArray')
- ->willReturn([]);
- $guestApi->setService($kbService);
-
- $data = [
- 'slug' => 'article-slug',
- ];
-
- $di = $this->getDi();
-
- $guestApi->setDi($di);
-
- $this->expectException(\FOSSBilling\Exception::class);
- $result = $guestApi->kb_article_get($data);
- $this->assertIsArray($result);
- }
-
- public function testKbCategoryGetList(): void
- {
- $guestApi = new \Box\Mod\Support\Api\Guest();
-
- $willReturn = [
- 'pages' => 5,
- 'page' => 2,
- 'per_page' => 2,
- 'total' => 10,
- 'list' => [],
- ];
-
- $kbService = $this->getMockBuilder(\Box\Mod\Support\Service::class)->onlyMethods(['kbCategoryGetSearchQuery'])->getMock();
- $kbService->expects($this->atLeastOnce())
- ->method('kbCategoryGetSearchQuery')
- ->willReturn(['String', []]);
-
- $pager = $this->getMockBuilder(\FOSSBilling\Pagination::class)
- ->onlyMethods(['getPaginatedResultSet'])
- ->getMock();
-
- $pager->expects($this->atLeastOnce())
- ->method('getPaginatedResultSet')
- ->willReturn($willReturn);
-
- $di = $this->getDi();
- $di['pager'] = $pager;
-
- $guestApi->setDi($di);
- $guestApi->setService($kbService);
-
- $result = $guestApi->kb_category_get_list([]);
- $this->assertIsArray($result);
- $this->assertEquals($result, $willReturn);
- }
-
- public function testKbCategoryGetPairs(): void
- {
- $guestApi = new \Box\Mod\Support\Api\Guest();
-
- $expected = [
- 1 => 'First Category',
- 2 => 'Second Category',
- ];
-
- $kbService = $this->getMockBuilder(\Box\Mod\Support\Service::class)->onlyMethods(['kbCategoryGetPairs'])->getMock();
- $kbService->expects($this->atLeastOnce())
- ->method('kbCategoryGetPairs')
- ->willReturn($expected);
- $guestApi->setService($kbService);
-
- $result = $guestApi->kb_category_get_pairs([]);
- $this->assertIsArray($result);
- $this->assertEquals($result, $expected);
- }
-
- public function testKbCategoryGetWithId(): void
- {
- $guestApi = new \Box\Mod\Support\Api\Guest();
-
- $kbService = $this->getMockBuilder(\Box\Mod\Support\Service::class)->onlyMethods(['kbFindCategoryById', 'kbHitView', 'kbCategoryToApiArray', 'kbFindCategoryBySlug'])->getMock();
- $kbService->expects($this->atLeastOnce())
- ->method('kbFindCategoryById')
- ->willReturn(new \Model_SupportKbArticleCategory());
- $kbService->expects($this->never())
- ->method('kbFindCategoryBySlug')
- ->willReturn(new \Model_SupportKbArticleCategory());
- $kbService->expects($this->atLeastOnce())
- ->method('kbCategoryToApiArray')
- ->willReturn([]);
- $guestApi->setService($kbService);
-
- $data = [
- 'id' => 1,
- ];
-
- $di = $this->getDi();
-
- $guestApi->setDi($di);
- $result = $guestApi->kb_category_get($data);
- $this->assertIsArray($result);
- }
-
- public function testKbCategoryGetWithSlug(): void
- {
- $guestApi = new \Box\Mod\Support\Api\Guest();
-
- $kbService = $this->getMockBuilder(\Box\Mod\Support\Service::class)->onlyMethods(['kbFindCategoryById', 'kbHitView', 'kbCategoryToApiArray', 'kbFindCategoryBySlug'])->getMock();
- $kbService->expects($this->never())
- ->method('kbFindCategoryById')
- ->willReturn(new \Model_SupportKbArticleCategory());
- $kbService->expects($this->atLeastOnce())
- ->method('kbFindCategoryBySlug')
- ->willReturn(new \Model_SupportKbArticleCategory());
- $kbService->expects($this->atLeastOnce())
- ->method('kbCategoryToApiArray')
- ->willReturn([]);
- $guestApi->setService($kbService);
-
- $di = $this->getDi();
-
- $guestApi->setDi($di);
-
- $data = [
- 'slug' => 'category-slug',
- ];
- $result = $guestApi->kb_category_get($data);
- $this->assertIsArray($result);
- }
-
- public function testKbCategoryGetIdAndSlugNotSetException(): void
- {
- $guestApi = new \Box\Mod\Support\Api\Guest();
-
- $kbService = $this->getMockBuilder(\Box\Mod\Support\Service::class)->onlyMethods(['kbFindCategoryById', 'kbHitView', 'kbCategoryToApiArray', 'kbFindCategoryBySlug'])->getMock();
- $kbService->expects($this->never())
- ->method('kbFindCategoryById')
- ->willReturn(new \Model_SupportKbArticleCategory());
- $kbService->expects($this->never())
- ->method('kbFindCategoryBySlug')
- ->willReturn(new \Model_SupportKbArticleCategory());
- $kbService->expects($this->never())
- ->method('kbCategoryToApiArray')
- ->willReturn([]);
- $guestApi->setService($kbService);
-
- $this->expectException(\FOSSBilling\Exception::class);
- $result = $guestApi->kb_category_get([]);
- $this->assertIsArray($result);
- }
-
- public function testKbCategoryGetNotFoundById(): void
- {
- $guestApi = new \Box\Mod\Support\Api\Guest();
-
- $kbService = $this->getMockBuilder(\Box\Mod\Support\Service::class)->onlyMethods(['kbFindCategoryById', 'kbHitView', 'kbCategoryToApiArray', 'kbFindCategoryBySlug'])->getMock();
- $kbService->expects($this->atLeastOnce())
- ->method('kbFindCategoryById')
- ->willThrowException(new \FOSSBilling\Exception('Knowledge Base category not found'));
- $kbService->expects($this->never())
- ->method('kbFindCategoryBySlug')
- ->willReturn(new \Model_SupportKbArticleCategory());
- $kbService->expects($this->never())
- ->method('kbCategoryToApiArray')
- ->willReturn([]);
- $guestApi->setService($kbService);
-
- $data = [
- 'id' => 1,
- ];
-
- $di = $this->getDi();
-
- $guestApi->setDi($di);
-
- $this->expectException(\FOSSBilling\Exception::class);
- $result = $guestApi->kb_category_get($data);
- $this->assertIsArray($result);
- }
-
- public function testKbCategoryGetNotFoundBySlug(): void
- {
- $guestApi = new \Box\Mod\Support\Api\Guest();
-
- $kbService = $this->getMockBuilder(\Box\Mod\Support\Service::class)->onlyMethods(['kbFindCategoryById', 'kbHitView', 'kbCategoryToApiArray', 'kbFindCategoryBySlug'])->getMock();
- $kbService->expects($this->never())
- ->method('kbFindCategoryById')
- ->willReturn(new \Model_SupportKbArticleCategory());
- $kbService->expects($this->atLeastOnce())
- ->method('kbFindCategoryBySlug')
- ->willReturn(null);
- $kbService->expects($this->never())
- ->method('kbCategoryToApiArray')
- ->willReturn([]);
- $guestApi->setService($kbService);
-
- $data = [
- 'slug' => 'article-slug',
- ];
-
- $di = $this->getDi();
-
- $guestApi->setDi($di);
-
- $this->expectException(\FOSSBilling\Exception::class);
- $result = $guestApi->kb_category_get($data);
- $this->assertIsArray($result);
- }
-}
diff --git a/tests-legacy/modules/Support/ServiceTest.php b/tests-legacy/modules/Support/ServiceTest.php
deleted file mode 100644
index 5a1c1c59f..000000000
--- a/tests-legacy/modules/Support/ServiceTest.php
+++ /dev/null
@@ -1,3309 +0,0 @@
-service = new \Box\Mod\Support\Service();
- }
-
- public function testDi(): void
- {
- $di = $this->getDi();
- $this->service->setDi($di);
- $getDi = $this->service->getDi();
- $this->assertEquals($di, $getDi);
- }
-
- public function testOnAfterClientOpenTicket(): void
- {
- $toApiArrayReturn = [
- 'client' => [
- 'id' => 1,
- ],
- ];
- $serviceMock = $this->getMockBuilder(\Box\Mod\Support\Service::class)
- ->onlyMethods(['getTicketById', 'toApiArray'])->getMock();
- $supportTicketModel = new \Model_SupportTicket();
- $supportTicketModel->loadBean(new \DummyBean());
- $serviceMock->expects($this->atLeastOnce())->method('getTicketById')
- ->willReturn($supportTicketModel);
- $serviceMock->expects($this->atLeastOnce())->method('toApiArray')
- ->willReturn($toApiArrayReturn);
-
- $emailServiceMock = $this->getMockBuilder(\Box\Mod\Email\Service::class)
- ->onlyMethods(['sendTemplate'])->getMock();
- $emailServiceMock->expects($this->atLeastOnce())->method('sendTemplate')
- ->willReturn(true);
-
- $di = $this->getDi();
- $di['mod_service'] = $di->protect(function ($serviceName) use ($emailServiceMock, $serviceMock) {
- if ($serviceName == 'email') {
- return $emailServiceMock;
- }
- if ($serviceName == 'support') {
- return $serviceMock;
- }
- });
- $di['loggedin_client'] = new \Model_Client();
- $serviceMock->setDi($di);
-
- $eventMock = $this->getMockBuilder('\Box_Event')->disableOriginalConstructor()
- ->getMock();
- $eventMock->expects($this->atLeastOnce())
- ->method('getDi')
- ->willReturn($di);
- $eventMock->expects($this->atLeastOnce())
- ->method('getParameters')
- ->willReturn(['id' => random_int(1, 100)]);
-
- $result = $serviceMock->onAfterClientOpenTicket($eventMock);
- $this->assertNull($result);
- }
-
- public function testOnAfterAdminOpenTicket(): void
- {
- $toApiArrayReturn = [
- 'client' => [
- 'id' => 1,
- ],
- ];
- $serviceMock = $this->getMockBuilder(\Box\Mod\Support\Service::class)
- ->onlyMethods(['getTicketById', 'toApiArray'])->getMock();
- $supportTicketModel = new \Model_SupportTicket();
- $supportTicketModel->loadBean(new \DummyBean());
- $serviceMock->expects($this->atLeastOnce())->method('getTicketById')
- ->willReturn($supportTicketModel);
- $serviceMock->expects($this->atLeastOnce())->method('toApiArray')
- ->willReturn($toApiArrayReturn);
-
- $emailServiceMock = $this->getMockBuilder(\Box\Mod\Email\Service::class)
- ->onlyMethods(['sendTemplate'])->getMock();
- $emailServiceMock->expects($this->atLeastOnce())->method('sendTemplate')
- ->willReturn(true);
-
- $di = $this->getDi();
- $di['mod_service'] = $di->protect(function ($serviceName) use ($emailServiceMock, $serviceMock) {
- if ($serviceName == 'email') {
- return $emailServiceMock;
- }
- if ($serviceName == 'support') {
- return $serviceMock;
- }
- });
- $di['loggedin_admin'] = new \Model_Admin();
- $serviceMock->setDi($di);
-
- $eventMock = $this->getMockBuilder('\Box_Event')->disableOriginalConstructor()
- ->getMock();
- $eventMock->expects($this->atLeastOnce())
- ->method('getDi')
- ->willReturn($di);
- $eventMock->expects($this->atLeastOnce())
- ->method('getParameters')
- ->willReturn(['id' => random_int(1, 100)]);
-
- $result = $serviceMock->onAfterAdminOpenTicket($eventMock);
- $this->assertNull($result);
- }
-
- public function testOnAfterAdminCloseTicket(): void
- {
- $toApiArrayReturn = [
- 'client' => [
- 'id' => 1,
- ],
- ];
- $serviceMock = $this->getMockBuilder(\Box\Mod\Support\Service::class)
- ->onlyMethods(['getTicketById', 'toApiArray'])->getMock();
- $supportTicketModel = new \Model_SupportTicket();
- $supportTicketModel->loadBean(new \DummyBean());
- $serviceMock->expects($this->atLeastOnce())->method('getTicketById')
- ->willReturn($supportTicketModel);
- $serviceMock->expects($this->atLeastOnce())->method('toApiArray')
- ->willReturn($toApiArrayReturn);
-
- $emailServiceMock = $this->getMockBuilder(\Box\Mod\Email\Service::class)
- ->onlyMethods(['sendTemplate'])->getMock();
- $emailServiceMock->expects($this->atLeastOnce())->method('sendTemplate')
- ->willReturn(true);
-
- $di = $this->getDi();
- $di['mod_service'] = $di->protect(function ($serviceName) use ($emailServiceMock, $serviceMock) {
- if ($serviceName == 'email') {
- return $emailServiceMock;
- }
- if ($serviceName == 'support') {
- return $serviceMock;
- }
- });
- $di['loggedin_admin'] = new \Model_Admin();
- $serviceMock->setDi($di);
-
- $eventMock = $this->getMockBuilder('\Box_Event')->disableOriginalConstructor()
- ->getMock();
- $eventMock->expects($this->atLeastOnce())
- ->method('getDi')
- ->willReturn($di);
- $eventMock->expects($this->atLeastOnce())
- ->method('getParameters')
- ->willReturn(['id' => random_int(1, 100)]);
-
- $result = $serviceMock->onAfterAdminCloseTicket($eventMock);
- $this->assertNull($result);
- }
-
- public function testOnAfterAdminReplyTicket(): void
- {
- $toApiArrayReturn = [
- 'client' => [
- 'id' => 1,
- ],
- ];
- $serviceMock = $this->getMockBuilder(\Box\Mod\Support\Service::class)
- ->onlyMethods(['getTicketById', 'toApiArray'])->getMock();
- $supportTicketModel = new \Model_SupportTicket();
- $supportTicketModel->loadBean(new \DummyBean());
- $serviceMock->expects($this->atLeastOnce())->method('getTicketById')
- ->willReturn($supportTicketModel);
- $serviceMock->expects($this->atLeastOnce())->method('toApiArray')
- ->willReturn($toApiArrayReturn);
-
- $emailServiceMock = $this->getMockBuilder(\Box\Mod\Email\Service::class)
- ->onlyMethods(['sendTemplate'])->getMock();
- $emailServiceMock->expects($this->atLeastOnce())->method('sendTemplate')
- ->willReturn(true);
-
- $di = $this->getDi();
- $di['mod_service'] = $di->protect(function ($serviceName) use ($emailServiceMock, $serviceMock) {
- if ($serviceName == 'email') {
- return $emailServiceMock;
- }
- if ($serviceName == 'support') {
- return $serviceMock;
- }
- });
- $di['loggedin_admin'] = new \Model_Admin();
- $serviceMock->setDi($di);
-
- $eventMock = $this->getMockBuilder('\Box_Event')->disableOriginalConstructor()
- ->getMock();
- $eventMock->expects($this->atLeastOnce())
- ->method('getDi')
- ->willReturn($di);
- $eventMock->expects($this->atLeastOnce())
- ->method('getParameters')
- ->willReturn(['id' => random_int(1, 100)]);
-
- $result = $serviceMock->onAfterAdminReplyTicket($eventMock);
- $this->assertNull($result);
- }
-
- public function testOnAfterGuestPublicTicketOpen(): void
- {
- $toApiArrayReturn = [
- 'author_email' => 'email@example.com',
- 'author_name' => 'Name',
- ];
- $serviceMock = $this->getMockBuilder(\Box\Mod\Support\Service::class)
- ->onlyMethods(['getPublicTicketById', 'publicToApiArray'])->getMock();
- $supportPTicketModel = new \Model_SupportPTicket();
- $supportPTicketModel->loadBean(new \DummyBean());
- $serviceMock->expects($this->atLeastOnce())->method('getPublicTicketById')
- ->willReturn($supportPTicketModel);
- $serviceMock->expects($this->atLeastOnce())->method('publicToApiArray')
- ->willReturn($toApiArrayReturn);
-
- $emailServiceMock = $this->getMockBuilder(\Box\Mod\Email\Service::class)
- ->onlyMethods(['sendTemplate'])->getMock();
- $emailServiceMock->expects($this->atLeastOnce())->method('sendTemplate')
- ->willReturn(true);
-
- $di = $this->getDi();
- $di['mod_service'] = $di->protect(function ($serviceName) use ($emailServiceMock, $serviceMock) {
- if ($serviceName == 'email') {
- return $emailServiceMock;
- }
- if ($serviceName == 'support') {
- return $serviceMock;
- }
- });
- $serviceMock->setDi($di);
-
- $eventMock = $this->getMockBuilder('\Box_Event')->disableOriginalConstructor()
- ->getMock();
- $eventMock->expects($this->atLeastOnce())
- ->method('getDi')
- ->willReturn($di);
- $eventMock->expects($this->atLeastOnce())
- ->method('getParameters')
- ->willReturn(['id' => random_int(1, 100)]);
-
- $result = $serviceMock->onAfterGuestPublicTicketOpen($eventMock);
- $this->assertNull($result);
- }
-
- public function testOnAfterAdminPublicTicketOpen(): void
- {
- $toApiArrayReturn = [
- 'author_email' => 'email@example.com',
- 'author_name' => 'Name',
- ];
- $serviceMock = $this->getMockBuilder(\Box\Mod\Support\Service::class)
- ->onlyMethods(['getPublicTicketById', 'publicToApiArray'])->getMock();
- $supportPTicketModel = new \Model_SupportPTicket();
- $supportPTicketModel->loadBean(new \DummyBean());
- $serviceMock->expects($this->atLeastOnce())->method('getPublicTicketById')
- ->willReturn($supportPTicketModel);
- $serviceMock->expects($this->atLeastOnce())->method('publicToApiArray')
- ->willReturn($toApiArrayReturn);
-
- $emailServiceMock = $this->getMockBuilder(\Box\Mod\Email\Service::class)
- ->onlyMethods(['sendTemplate'])->getMock();
- $emailServiceMock->expects($this->atLeastOnce())->method('sendTemplate')
- ->willReturn(true);
-
- $di = $this->getDi();
- $di['mod_service'] = $di->protect(function ($serviceName) use ($emailServiceMock, $serviceMock) {
- if ($serviceName == 'email') {
- return $emailServiceMock;
- }
- if ($serviceName == 'support') {
- return $serviceMock;
- }
- });
- $di['loggedin_admin'] = new \Model_Admin();
- $serviceMock->setDi($di);
-
- $eventMock = $this->getMockBuilder('\Box_Event')->disableOriginalConstructor()
- ->getMock();
- $eventMock->expects($this->atLeastOnce())
- ->method('getDi')
- ->willReturn($di);
- $eventMock->expects($this->atLeastOnce())
- ->method('getParameters')
- ->willReturn(['id' => random_int(1, 100)]);
-
- $result = $serviceMock->onAfterAdminPublicTicketOpen($eventMock);
- $this->assertNull($result);
- }
-
- public function testOnAfterAdminPublicTicketReply(): void
- {
- $toApiArrayReturn = [
- 'author_email' => 'email@example.com',
- 'author_name' => 'Name',
- ];
- $serviceMock = $this->getMockBuilder(\Box\Mod\Support\Service::class)
- ->onlyMethods(['getPublicTicketById', 'publicToApiArray'])->getMock();
- $supportPTicketModel = new \Model_SupportPTicket();
- $supportPTicketModel->loadBean(new \DummyBean());
- $serviceMock->expects($this->atLeastOnce())->method('getPublicTicketById')
- ->willReturn($supportPTicketModel);
- $serviceMock->expects($this->atLeastOnce())->method('publicToApiArray')
- ->willReturn($toApiArrayReturn);
-
- $emailServiceMock = $this->getMockBuilder(\Box\Mod\Email\Service::class)
- ->onlyMethods(['sendTemplate'])->getMock();
- $emailServiceMock->expects($this->atLeastOnce())->method('sendTemplate')
- ->willReturn(true);
-
- $di = $this->getDi();
- $di['mod_service'] = $di->protect(function ($serviceName) use ($emailServiceMock, $serviceMock) {
- if ($serviceName == 'email') {
- return $emailServiceMock;
- }
- if ($serviceName == 'support') {
- return $serviceMock;
- }
- });
- $di['loggedin_admin'] = new \Model_Admin();
- $serviceMock->setDi($di);
-
- $eventMock = $this->getMockBuilder('\Box_Event')->disableOriginalConstructor()
- ->getMock();
- $eventMock->expects($this->atLeastOnce())
- ->method('getDi')
- ->willReturn($di);
- $eventMock->expects($this->atLeastOnce())
- ->method('getParameters')
- ->willReturn(['id' => random_int(1, 100)]);
-
- $result = $serviceMock->onAfterAdminPublicTicketReply($eventMock);
- $this->assertNull($result);
- }
-
- public function testOnAfterAdminPublicTicketClose(): void
- {
- $toApiArrayReturn = [
- 'author_email' => 'email@example.com',
- 'author_name' => 'Name',
- ];
- $serviceMock = $this->getMockBuilder(\Box\Mod\Support\Service::class)
- ->onlyMethods(['getPublicTicketById', 'publicToApiArray'])->getMock();
- $supportPTicketModel = new \Model_SupportPTicket();
- $supportPTicketModel->loadBean(new \DummyBean());
- $serviceMock->expects($this->atLeastOnce())->method('getPublicTicketById')
- ->willReturn($supportPTicketModel);
- $serviceMock->expects($this->atLeastOnce())->method('publicToApiArray')
- ->willReturn($toApiArrayReturn);
-
- $emailServiceMock = $this->getMockBuilder(\Box\Mod\Email\Service::class)
- ->onlyMethods(['sendTemplate'])->getMock();
- $emailServiceMock->expects($this->atLeastOnce())->method('sendTemplate')
- ->willReturn(true);
-
- $di = $this->getDi();
- $di['mod_service'] = $di->protect(function ($serviceName) use ($emailServiceMock, $serviceMock) {
- if ($serviceName == 'email') {
- return $emailServiceMock;
- }
- if ($serviceName == 'support') {
- return $serviceMock;
- }
- });
- $di['loggedin_admin'] = new \Model_Admin();
- $serviceMock->setDi($di);
-
- $eventMock = $this->getMockBuilder('\Box_Event')->disableOriginalConstructor()
- ->getMock();
- $eventMock->expects($this->atLeastOnce())
- ->method('getDi')
- ->willReturn($di);
- $eventMock->expects($this->atLeastOnce())
- ->method('getParameters')
- ->willReturn(['id' => random_int(1, 100)]);
-
- $result = $serviceMock->onAfterAdminPublicTicketClose($eventMock);
- $this->assertNull($result);
- }
-
- public function testGetTicketById(): void
- {
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('getExistingModelById')
- ->willReturn(new \Model_SupportTicket());
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $this->service->setDi($di);
-
- $result = $this->service->getTicketById(1);
- $this->assertInstanceOf('Model_SupportTicket', $result);
- }
-
- public function testGetPublicTicketById(): void
- {
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $supportPTicketModel = new \Model_SupportPTicket();
- $supportPTicketModel->loadBean(new \DummyBean());
- $dbMock->expects($this->atLeastOnce())
- ->method('getExistingModelById')
- ->willReturn($supportPTicketModel);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $this->service->setDi($di);
-
- $result = $this->service->getPublicTicketById(1);
- $this->assertInstanceOf('Model_SupportPTicket', $result);
- }
-
- public function testGetStatuses(): void
- {
- $result = $this->service->getStatuses();
- $this->assertIsArray($result);
- }
-
- public function testFindOneByClient(): void
- {
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $supportTicketModel = new \Model_SupportTicket();
- $supportTicketModel->loadBean(new \DummyBean());
- $dbMock->expects($this->atLeastOnce())
- ->method('findOne')
- ->willReturn($supportTicketModel);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $this->service->setDi($di);
-
- $client = new \Model_Client();
- $client->loadBean(new \DummyBean());
- $client->id = 1;
-
- $result = $this->service->findOneByClient($client, 1);
- $this->assertInstanceOf('Model_SupportTicket', $result);
- }
-
- public function testFindOneByClientNotFoundException(): void
- {
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('findOne')
- ->willReturn(null);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $this->service->setDi($di);
-
- $client = new \Model_Client();
- $client->loadBean(new \DummyBean());
- $client->id = 1;
-
- $this->expectException(\FOSSBilling\Exception::class);
- $result = $this->service->findOneByClient($client, 1);
- $this->assertInstanceOf('Model_SupportTicket', $result);
- }
-
- public static function getSearchQueryProvider(): array
- {
- return [
- [
- [
- 'search' => 'query',
- 'id' => 1,
- 'status' => 'open',
- 'client_id' => 1,
- 'client' => 'Client name',
- 'order_id' => 1,
- 'subject' => 'subject',
- 'content' => 'Content',
- 'support_helpdesk_id' => 1,
- 'created_at' => date('Y-m-d H:i:s'),
- 'date_from' => date('Y-m-d H:i:s'),
- 'date_to' => date('Y-m-d H:i:s'),
- 'priority' => 1,
- ],
- ],
- [
- [
- 'search' => 1,
- 'id' => 1,
- 'status' => 'open',
- 'client_id' => 1,
- 'client' => 'Client name',
- 'order_id' => 1,
- 'subject' => 'subject',
- 'content' => 'Content',
- 'support_helpdesk_id' => 1,
- 'created_at' => date('Y-m-d H:i:s'),
- 'date_from' => date('Y-m-d H:i:s'),
- 'date_to' => date('Y-m-d H:i:s'),
- 'priority' => 1,
- ],
- ],
- ];
- }
-
- #[DataProvider('getSearchQueryProvider')]
- public function testGetSearchQuery(array $data): void
- {
- $di = $this->getDi();
-
- $this->service->setDi($di);
- [$query, $bindings] = $this->service->getSearchQuery($data);
- $this->assertIsString($query);
- $this->assertIsArray($bindings);
- }
-
- public function testCounter(): void
- {
- $arr = [
- \Model_SupportTicket::OPENED => 1,
- \Model_SupportTicket::ONHOLD => 1,
- \Model_SupportTicket::CLOSED => 1,
- ];
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('getAssoc')
- ->willReturn($arr);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
-
- $this->service->setDi($di);
-
- $result = $this->service->counter();
- $this->assertIsArray($result);
- $this->assertArrayHasKey('total', $result);
- $this->assertEquals(array_sum($arr), $result['total']);
- }
-
- public function testGetLatest(): void
- {
- $ticket = new \Model_SupportTicket();
- $ticket->loadBean(new \DummyBean());
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('find')
- ->willReturn([$ticket, $ticket]);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $this->service->setDi($di);
-
- $result = $this->service->getLatest();
- $this->assertIsArray($result);
- $this->assertInstanceOf('Model_SupportTicket', $result[0]);
- }
-
- public function testGetExpired(): void
- {
- $ticket = new \Model_SupportTicket();
- $ticket->loadBean(new \DummyBean());
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('getAll')
- ->willReturn([['id' => 1]]);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $this->service->setDi($di);
-
- $result = $this->service->getExpired();
- $this->assertIsArray($result);
- $this->assertIsArray($result[0]);
- }
-
- public function testCountByStatus(): void
- {
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('getCell')
- ->willReturn(1);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $this->service->setDi($di);
-
- $result = $this->service->countByStatus('open');
- $this->assertIsInt($result);
- }
-
- public function testGetActiveTicketsCountForOrder(): void
- {
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('getCell')
- ->willReturn(1);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $this->service->setDi($di);
-
- $order = new \Model_ClientOrder();
- $order->loadBean(new \DummyBean());
-
- $result = $this->service->getActiveTicketsCountForOrder($order);
- $this->assertIsInt($result);
- }
-
- public function testCheckIfTaskAlreadyExistsTrue(): void
- {
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $supportTicketModel = new \Model_SupportTicket();
- $supportTicketModel->loadBean(new \DummyBean());
- $dbMock->expects($this->atLeastOnce())
- ->method('findOne')
- ->willReturn($supportTicketModel);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $this->service->setDi($di);
-
- $client = new \Model_Client();
- $client->loadBean(new \DummyBean());
-
- $result = $this->service->checkIfTaskAlreadyExists($client, 1, \Model_SupportTicket::REL_TYPE_ORDER, \Model_SupportTicket::REL_TASK_UPGRADE);
- $this->assertTrue($result);
- }
-
- public function testCheckIfTaskAlreadyExistsFalse(): void
- {
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('findOne')
- ->willReturn(false);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $this->service->setDi($di);
-
- $client = new \Model_Client();
- $client->loadBean(new \DummyBean());
-
- $result = $this->service->checkIfTaskAlreadyExists($client, 1, \Model_SupportTicket::REL_TYPE_ORDER, \Model_SupportTicket::REL_TASK_CANCEL);
- $this->assertFalse($result);
- }
-
- public static function closeTicketProvider(): array
- {
- return [
- [new \Model_Admin()],
- [new \Model_Client()],
- ];
- }
-
- #[DataProvider('closeTicketProvider')]
- public function testCloseTicket(\Model_Admin|\Model_Client $identity): void
- {
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('store')
- ->willReturn(1);
-
- $eventMock = $this->createMock('\Box_EventManager');
- $eventMock->expects($this->atLeastOnce())->method('fire');
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $di['logger'] = $this->createMock('Box_Log');
- $di['events_manager'] = $eventMock;
- $this->service->setDi($di);
-
- $ticket = new \Model_SupportTicket();
- $ticket->loadBean(new \DummyBean());
-
- $result = $this->service->closeTicket($ticket, $identity);
- $this->assertTrue($result);
- }
-
- public function testAutoClose(): void
- {
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('store')
- ->willReturn(1);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $di['logger'] = $this->createMock('Box_Log');
- $this->service->setDi($di);
-
- $ticket = new \Model_SupportTicket();
- $ticket->loadBean(new \DummyBean());
-
- $result = $this->service->autoClose($ticket);
- $this->assertTrue($result);
- }
-
- public function testCanBeReopenedNotClosed(): void
- {
- $helpdesk = new \Model_SupportHelpdesk();
- $helpdesk->loadBean(new \DummyBean());
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->never())
- ->method('getExistingModelById')
- ->willReturn($helpdesk);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $di['logger'] = $this->createMock('Box_Log');
- $this->service->setDi($di);
-
- $ticket = new \Model_SupportTicket();
- $ticket->loadBean(new \DummyBean());
-
- $result = $this->service->canBeReopened($ticket);
- $this->assertTrue($result);
- }
-
- public function testCanBeReopened(): void
- {
- $helpdesk = new \Model_SupportHelpdesk();
- $helpdesk->loadBean(new \DummyBean());
- $helpdesk->support_helpdesk_id = 1;
- $helpdesk->can_reopen = true;
-
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('getExistingModelById')
- ->willReturn($helpdesk);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $di['logger'] = $this->createMock('Box_Log');
- $this->service->setDi($di);
-
- $ticket = new \Model_SupportTicket();
- $ticket->loadBean(new \DummyBean());
- $ticket->status = \Model_SupportTicket::CLOSED;
-
- $result = $this->service->canBeReopened($ticket);
- $this->assertTrue($result);
- }
-
- public function testRmByClient(): void
- {
- $model = new \Model_SupportTicket();
- $model->loadBean(new \DummyBean());
- $model->id = 1;
-
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('find')
- ->willReturn([$model]);
- $dbMock->expects($this->atLeastOnce())
- ->method('trash')
- ->willReturn(null);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $di['logger'] = $this->createMock('Box_Log');
- $this->service->setDi($di);
-
- $client = new \Model_Client();
- $client->loadBean(new \DummyBean());
-
- $result = $this->service->rmByClient($client);
- $this->assertNull($result);
- }
-
- public function testRm(): void
- {
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->exactly(2))
- ->method('find')
- ->willReturnCallback(fn (...$args): \Model_SupportTicketNote|\Model_SupportTicketMessage => match ($args[0]) {
- 'SupportTicketNote' => new \Model_SupportTicketNote(),
- 'SupportTicketMessage' => new \Model_SupportTicketMessage(),
- });
-
- $dbMock->expects($this->atLeastOnce())
- ->method('trash')
- ->willReturn(null);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $di['logger'] = $this->createMock('Box_Log');
- $this->service->setDi($di);
-
- $ticket = new \Model_SupportTicket();
- $ticket->loadBean(new \DummyBean());
-
- $result = $this->service->rm($ticket);
- $this->assertTrue($result);
- }
-
- public function testToApiArray(): void
- {
- $supportTicketMessageModel = new \Model_SupportTicketMessage();
- $supportTicketMessageModel->loadBean(new \DummyBean());
- $helpdesk = new \Model_SupportHelpdesk();
- $helpdesk->loadBean(new \DummyBean());
-
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('findOne')
- ->willReturn($supportTicketMessageModel);
- $dbMock->expects($this->atLeastOnce())
- ->method('toArray')
- ->willReturn([]);
- $dbMock->expects($this->atleastOnce())
- ->method('load')
- ->willReturnCallback(fn (...$args): \Model_SupportHelpdesk|\Model_Client => match ($args[0]) {
- 'SupportHelpdesk' => $helpdesk,
- 'Client' => new \Model_Client(),
- });
-
- $dbMock->expects($this->atLeastOnce())
- ->method('find')
- ->willReturn([new \Model_SupportTicketNote()]);
-
- $ticketMessages = [new \Model_SupportTicketMessage(), new \Model_SupportTicketMessage()];
- $serviceMock = $this->getMockBuilder(\Box\Mod\Support\Service::class)
- ->onlyMethods(['messageGetRepliesCount', 'messageToApiArray', 'helpdeskToApiArray', 'messageGetTicketMessages', 'noteToApiArray', 'getClientApiArrayForTicket'])->getMock();
- $serviceMock->expects($this->atLeastOnce())->method('messageGetRepliesCount')
- ->willReturn(1);
- $serviceMock->expects($this->atLeastOnce())->method('messageToApiArray')
- ->willReturn([]);
- $serviceMock->expects($this->atLeastOnce())->method('helpdeskToApiArray')
- ->willReturn([]);
- $serviceMock->expects($this->atLeastOnce())->method('messageGetTicketMessages')
- ->willReturn($ticketMessages);
- $serviceMock->expects($this->atLeastOnce())->method('noteToApiArray')
- ->willReturn([]);
- $serviceMock->expects($this->atLeastOnce())->method('getClientApiArrayForTicket')
- ->willReturn([]);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $di['logger'] = $this->createMock('Box_Log');
- $serviceMock->setDi($di);
-
- $ticket = new \Model_SupportTicket();
- $ticket->loadBean(new \DummyBean());
-
- $result = $serviceMock->toApiArray($ticket, true, new \Model_Admin());
- $this->assertIsArray($result);
- $this->assertArrayHasKey('replies', $result);
- $this->assertArrayHasKey('helpdesk', $result);
- $this->assertArrayHasKey('messages', $result);
-
- $this->assertCount(count($ticketMessages), $result['messages']);
- }
-
- public function testToApiArrayWithRelDetails(): void
- {
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('findOne')
- ->willReturn(new \Model_SupportTicketMessage());
- $dbMock->expects($this->atLeastOnce())
- ->method('toArray')
- ->willReturn([]);
- $dbMock->expects($this->atleastOnce())
- ->method('load')
- ->willReturnCallback(function (...$args) {
- static $series = [
- ['SupportHelpdesk', new \Model_SupportHelpdesk()],
- ['Client', new \Model_Client()],
- ];
-
- [$expectedArgs, $return] = array_shift($series);
-
- return $return;
- });
-
- $dbMock->expects($this->atLeastOnce())
- ->method('find')
- ->willReturn([new \Model_SupportTicketNote()]);
-
- $ticketMessages = [new \Model_SupportTicketMessage(), new \Model_SupportTicketMessage()];
- $serviceMock = $this->getMockBuilder(\Box\Mod\Support\Service::class)
- ->onlyMethods(['messageGetRepliesCount', 'messageToApiArray', 'helpdeskToApiArray', 'messageGetTicketMessages', 'noteToApiArray', 'getClientApiArrayForTicket'])->getMock();
- $serviceMock->expects($this->atLeastOnce())->method('messageGetRepliesCount')
- ->willReturn(1);
- $serviceMock->expects($this->atLeastOnce())->method('messageToApiArray')
- ->willReturn([]);
- $serviceMock->expects($this->atLeastOnce())->method('helpdeskToApiArray')
- ->willReturn([]);
- $serviceMock->expects($this->atLeastOnce())->method('messageGetTicketMessages')
- ->willReturn($ticketMessages);
- $serviceMock->expects($this->atLeastOnce())->method('noteToApiArray')
- ->willReturn([]);
- $serviceMock->expects($this->atLeastOnce())->method('getClientApiArrayForTicket')
- ->willReturn([]);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $di['logger'] = $this->createMock('Box_Log');
- $serviceMock->setDi($di);
-
- $ticket = new \Model_SupportTicket();
- $ticket->loadBean(new \DummyBean());
- $ticket->rel_id = 1;
- $ticket->rel_type = 'Type';
-
- $result = $serviceMock->toApiArray($ticket, true, new \Model_Admin());
- $this->assertIsArray($result);
- $this->assertArrayHasKey('replies', $result);
- $this->assertArrayHasKey('helpdesk', $result);
- $this->assertArrayHasKey('messages', $result);
-
- $this->assertCount(count($ticketMessages), $result['messages']);
- }
-
- public function testGetClientApiArrayForTicket(): void
- {
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('load')
- ->willReturn(new \Model_Client());
-
- $clientServiceMock = $this->getMockBuilder(\Box\Mod\Client\Service::class)
- ->onlyMethods(['toApiArray'])->getMock();
- $clientServiceMock->expects($this->atLeastOnce())->method('toApiArray')
- ->willReturn([]);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $di['logger'] = $this->createMock('Box_Log');
- $di['mod_service'] = $di->protect(fn (): \PHPUnit\Framework\MockObject\MockObject => $clientServiceMock);
- $this->service->setDi($di);
-
- $ticket = new \Model_SupportTicket();
- $ticket->loadBean(new \DummyBean());
-
- $result = $this->service->getClientApiArrayForTicket($ticket, new \Model_Admin());
-
- $this->assertIsArray($result);
- }
-
- public function testGetClientApiArrayForTicketClientNotExists(): void
- {
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('load')
- ->willReturn(null);
-
- $clientServiceMock = $this->getMockBuilder(\Box\Mod\Client\Service::class)
- ->onlyMethods(['toApiArray'])->getMock();
- $clientServiceMock->expects($this->never())->method('toApiArray')
- ->willReturn([]);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $di['logger'] = $this->createMock('Box_Log');
- $di['mod_service'] = $di->protect(fn (): \PHPUnit\Framework\MockObject\MockObject => $clientServiceMock);
- $this->service->setDi($di);
-
- $ticket = new \Model_SupportTicket();
- $ticket->loadBean(new \DummyBean());
-
- $result = $this->service->getClientApiArrayForTicket($ticket);
-
- $this->assertIsArray($result);
- }
-
- public function testNoteGetAuthorDetails(): void
- {
- $admin = new \Model_Admin();
- $admin->loadBean(new \DummyBean());
- $admin->name = 'AdminName';
-
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('load')
- ->willReturn($admin);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $this->service->setDi($di);
-
- $note = new \Model_SupportTicketNote();
- $note->loadBean(new \DummyBean());
-
- $this->service->noteGetAuthorDetails($note);
- }
-
- public function testNoteRm(): void
- {
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('trash')
- ->willReturn(null);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $di['logger'] = $this->createMock('Box_Log');
- $this->service->setDi($di);
-
- $note = new \Model_SupportTicketNote();
- $note->loadBean(new \DummyBean());
-
- $result = $this->service->noteRm($note);
- $this->assertTrue($result);
- }
-
- public function testNoteToApiArray(): void
- {
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('toArray')
- ->willReturn([]);
-
- $serviceMock = $this->getMockBuilder(\Box\Mod\Support\Service::class)
- ->onlyMethods(['noteGetAuthorDetails'])->getMock();
- $serviceMock->expects($this->atLeastOnce())->method('noteGetAuthorDetails')
- ->willReturn([]);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $this->service->setDi($di);
-
- $serviceMock->setDi($di);
-
- $note = new \Model_SupportTicketNote();
- $note->loadBean(new \DummyBean());
-
- $result = $serviceMock->noteToApiArray($note);
- $this->assertArrayHasKey('author', $result);
- $this->assertIsArray($result['author']);
- }
-
- public function testHelpdeskGetSearchQuery(): void
- {
- $di = $this->getDi();
-
- $this->service->setDi($di);
-
- $data = [
- 'search' => 'SearchQuery',
- ];
- [$query, $bindings] = $this->service->helpdeskGetSearchQuery($data);
-
- $expectedBindings = [
- ':name' => '%SearchQuery%',
- ':email' => '%SearchQuery%',
- ':signature' => '%SearchQuery%',
- ];
-
- $this->assertIsString($query);
- $this->assertIsArray($bindings);
-
- $this->assertEquals($expectedBindings, $bindings);
- }
-
- public function testHelpdeskGetPairs(): void
- {
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('getAssoc')
- ->willReturn([0 => 'General']);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $this->service->setDi($di);
-
- $this->service->setDi($di);
-
- $note = new \Model_SupportTicketNote();
- $note->loadBean(new \DummyBean());
-
- $result = $this->service->helpdeskGetPairs();
- $this->assertIsArray($result);
- }
-
- public function testHelpdeskRm(): void
- {
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('find')
- ->willReturn([]);
-
- $dbMock->expects($this->atLeastOnce())
- ->method('trash')
- ->willReturn(null);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $di['logger'] = $this->createMock('Box_Log');
- $this->service->setDi($di);
-
- $helpdesk = new \Model_SupportHelpdesk();
- $helpdesk->loadBean(new \DummyBean());
- $helpdesk->id = 1;
- $result = $this->service->helpdeskRm($helpdesk);
- $this->assertTrue($result);
- }
-
- public function testHelpdeskRmHAsTicketsException(): void
- {
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('find')
- ->willReturn([new \Model_SupportTicket()]);
-
- $dbMock->expects($this->never())
- ->method('trash')
- ->willReturn(null);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $di['logger'] = $this->createMock('Box_Log');
- $this->service->setDi($di);
-
- $helpdesk = new \Model_SupportHelpdesk();
- $helpdesk->loadBean(new \DummyBean());
- $helpdesk->id = 1;
- $this->expectException(\FOSSBilling\Exception::class);
- $result = $this->service->helpdeskRm($helpdesk);
- $this->assertTrue($result);
- }
-
- public function testHelpdeskToApiArray(): void
- {
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('toArray')
- ->willReturn([]);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $this->service->setDi($di);
-
- $helpdesk = new \Model_SupportHelpdesk();
- $helpdesk->loadBean(new \DummyBean());
- $helpdesk->id = 1;
- $result = $this->service->helpdeskToApiArray($helpdesk, new \Model_Admin());
- $this->assertIsArray($result);
- }
-
- public function testMessageGetTicketMessages(): void
- {
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('find')
- ->willReturn([new \Model_SupportTicketMessage()]);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $this->service->setDi($di);
-
- $ticket = new \Model_SupportTicket();
- $ticket->loadBean(new \DummyBean());
- $ticket->id = 1;
-
- $result = $this->service->messageGetTicketMessages($ticket);
- $this->assertIsArray($result);
- }
-
- public function testMessageGetRepliesCount(): void
- {
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('getCell')
- ->willReturn(1);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $this->service->setDi($di);
-
- $ticket = new \Model_SupportTicket();
- $ticket->loadBean(new \DummyBean());
- $ticket->id = 1;
-
- $result = $this->service->messageGetRepliesCount($ticket);
- $this->assertIsInt($result);
- }
-
- public function testMessageGetAuthorDetailsAdmin(): void
- {
- $admin = new \Model_Admin();
- $admin->loadBean(new \DummyBean());
- $admin->id = 1;
-
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('load')
- ->willReturn($admin);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $this->service->setDi($di);
-
- $ticketMsg = new \Model_SupportTicketMessage();
- $ticketMsg->loadBean(new \DummyBean());
- $ticketMsg->admin_id = 1;
-
- $result = $this->service->messageGetAuthorDetails($ticketMsg, new \Model_Admin());
- $this->assertIsArray($result);
- $this->assertArrayHasKey('name', $result);
- $this->assertSame('admin', $result['role']);
- $this->assertArrayHasKey('email', $result);
- }
-
- public function testMessageGetAuthorDetailsClient(): void
- {
- $client = new \Model_Client();
- $client->loadBean(new \DummyBean());
- $client->id = 1;
-
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('load')
- ->willReturn($client);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $this->service->setDi($di);
-
- $ticketMsg = new \Model_SupportTicketMessage();
- $ticketMsg->loadBean(new \DummyBean());
- $ticketMsg->client_id = 1;
-
- $result = $this->service->messageGetAuthorDetails($ticketMsg, new \Model_Admin());
- $this->assertIsArray($result);
- $this->assertArrayHasKey('name', $result);
- $this->assertSame('client', $result['role']);
- $this->assertArrayHasKey('email', $result);
- }
-
- public function testMessageGetAuthorDetailsRedactsEmailForClient(): void
- {
- $admin = new \Model_Admin();
- $admin->loadBean(new \DummyBean());
- $admin->id = 1;
- $admin->name = 'Support Agent';
- $admin->email = 'agent@example.test';
-
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('load')
- ->willReturn($admin);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $this->service->setDi($di);
-
- $ticketMsg = new \Model_SupportTicketMessage();
- $ticketMsg->loadBean(new \DummyBean());
- $ticketMsg->admin_id = 1;
-
- $result = $this->service->messageGetAuthorDetails($ticketMsg, new \Model_Client());
-
- $this->assertSame('Support Agent', $result['name']);
- $this->assertSame('admin', $result['role']);
- $this->assertArrayNotHasKey('email', $result);
- }
-
- public function testMessageToApiArray(): void
- {
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('toArray')
- ->willReturn([]);
-
- $serviceMock = $this->getMockBuilder(\Box\Mod\Support\Service::class)
- ->onlyMethods(['messageGetAuthorDetails'])->getMock();
- $serviceMock->expects($this->atLeastOnce())->method('messageGetAuthorDetails')
- ->willReturn([]);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $serviceMock->setDi($di);
-
- $ticketMsg = new \Model_SupportTicketMessage();
- $ticketMsg->loadBean(new \DummyBean());
- $ticketMsg->id = 1;
-
- $result = $serviceMock->messageToApiArray($ticketMsg, true, new \Model_Admin());
- $this->assertIsArray($result);
- $this->assertArrayHasKey('author', $result);
- }
-
- public function testTicketUpdate(): void
- {
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('store')
- ->willReturn(1);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $di['logger'] = $this->createMock('Box_Log');
-
- $this->service->setDi($di);
-
- $ticket = new \Model_SupportTicket();
- $ticket->loadBean(new \DummyBean());
-
- $data = [
- 'support_helpdesk_id' => 1,
- 'status' => \Model_SupportTicket::OPENED,
- 'subject' => 'Subject',
- 'priority' => 1,
- ];
-
- $result = $this->service->ticketUpdate($ticket, $data);
- $this->assertTrue($result);
- }
-
- public function testTicketMessageUpdate(): void
- {
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('store')
- ->willReturn(1);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $di['logger'] = $this->createMock('Box_Log');
- $this->service->setDi($di);
-
- $message = new \Model_SupportTicketMessage();
- $message->loadBean(new \DummyBean());
-
- $result = $this->service->ticketMessageUpdate($message, 'Content');
- $this->assertTrue($result);
- }
-
- public static function ticketReplyProvider(): array
- {
- $admin = new \Model_Admin();
- $admin->loadBean(new \DummyBean());
- $admin->id = 1;
-
- $client = new \Model_Client();
- $client->loadBean(new \DummyBean());
- $client->id = 1;
-
- return [
- [$admin],
- [$client],
- ];
- }
-
- #[DataProvider('ticketReplyProvider')]
- public function testTicketReply(\Model_Admin|\Model_Client $identity): void
- {
- $message = new \Model_SupportTicketMessage();
- $message->loadBean(new \DummyBean());
-
- $randId = 1;
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('dispense')
- ->willReturn($message);
- $dbMock->expects($this->atLeastOnce())
- ->method('store')
- ->willReturn($randId);
-
- $eventMock = $this->createMock('\Box_EventManager');
- $eventMock->expects($this->atLeastOnce())->method('fire');
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $di['logger'] = $this->createMock('Box_Log');
- $di['request'] = Request::createFromGlobals();
- $di['events_manager'] = $eventMock;
- $this->service->setDi($di);
-
- $ticket = new \Model_SupportTicket();
- $ticket->loadBean(new \DummyBean());
-
- $result = $this->service->ticketReply($ticket, $identity, 'Content');
- $this->assertIsInt($result);
- $this->assertEquals($result, $randId);
- }
-
- public function testTicketCreateForAdmin(): void
- {
- $message = new \Model_SupportTicketMessage();
- $message->loadBean(new \DummyBean());
-
- $randId = 1;
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('dispense')
- ->willReturn($message);
- $dbMock->expects($this->atLeastOnce())
- ->method('store')
- ->willReturn($randId);
-
- $eventMock = $this->createMock('\Box_EventManager');
- $eventMock->expects($this->atLeastOnce())->method('fire');
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $di['logger'] = $this->createMock('Box_Log');
- $di['request'] = Request::createFromGlobals();
- $di['events_manager'] = $eventMock;
-
- $this->service->setDi($di);
-
- $helpdesk = new \Model_SupportHelpdesk();
- $helpdesk->loadBean(new \DummyBean());
-
- $admin = new \Model_Admin();
- $admin->loadBean(new \DummyBean());
- $admin->id = 1;
-
- $client = new \Model_Client();
- $client->loadBean(new \DummyBean());
- $client->id = 1;
-
- $data = [
- 'subject' => 'Subject',
- 'content' => 'Content',
- ];
-
- $result = $this->service->ticketCreateForAdmin($client, $helpdesk, $data, $admin);
- $this->assertIsInt($result);
- $this->assertEquals($result, $randId);
- }
-
- public function testTicketCreateForClient(): void
- {
- $ticket = new \Model_SupportTicket();
- $ticket->loadBean(new \DummyBean());
-
- $randId = 1;
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('dispense')
- ->with('SupportTicket')
- ->willReturn($ticket);
- $dbMock->expects($this->atLeastOnce())
- ->method('store')
- ->willReturn($randId);
- $dbMock->expects($this->atLeastOnce())
- ->method('getExistingModelById')
- ->willReturn(new \Model_SupportPr());
-
- $eventMock = $this->createMock('\Box_EventManager');
- $eventMock->expects($this->atLeastOnce())->method('fire');
-
- $config = [
- 'autorespond_enable' => 1,
- 'autorespond_message_id' => 1,
- ];
- $supportModMock = $this->getMockBuilder('\\' . \FOSSBilling\Module::class)
- ->disableOriginalConstructor()->onlyMethods(['getConfig'])->getMock();
- $supportModMock->expects($this->atLeastOnce())->method('getConfig')
- ->willReturn($config);
-
- $staffServiceMock = $this->getMockBuilder(\Box\Mod\Staff\Service::class)
- ->onlyMethods(['getCronAdmin'])->getMock();
- $staffServiceMock->expects($this->atLeastOnce())->method('getCronAdmin')
- ->willReturn(new \Model_Admin());
-
- $serviceMock = $this->getMockBuilder(\Box\Mod\Support\Service::class)
- ->onlyMethods(['ticketReply', 'messageCreateForTicket', 'cannedToApiArray'])->getMock();
- $serviceMock->expects($this->atLeastOnce())->method('ticketReply')
- ->willReturn(1);
- $serviceMock->expects($this->atLeastOnce())->method('messageCreateForTicket')
- ->willReturn(1);
- $serviceMock->expects($this->atLeastOnce())->method('cannedToApiArray')
- ->willReturn(['content' => 'Content']);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $di['logger'] = $this->createMock('Box_Log');
- $di['request'] = $this->getMockBuilder(Request::class)->getMock();
- $di['events_manager'] = $eventMock;
- $di['mod'] = $di->protect(fn (): \PHPUnit\Framework\MockObject\MockObject => $supportModMock);
- $di['mod_service'] = $di->protect(fn (): \PHPUnit\Framework\MockObject\MockObject => $staffServiceMock);
-
- $serviceMock->setDi($di);
-
- $helpdesk = new \Model_SupportHelpdesk();
- $helpdesk->loadBean(new \DummyBean());
-
- $guest = new \Model_Guest();
- $guest->id = 1;
-
- $data = [
- 'name' => 'Name',
- 'email' => 'email@example.com',
- 'subject' => 'Subject',
- 'content' => 'content',
- ];
-
- $helpdesk = new \Model_SupportHelpdesk();
- $helpdesk->loadBean(new \DummyBean());
-
- $client = new \Model_Client();
- $client->loadBean(new \DummyBean());
- $client->id = 1;
-
- $result = $serviceMock->ticketCreateForClient($client, $helpdesk, $data);
- $this->assertIsInt($result);
- $this->assertEquals($result, $randId);
- }
-
- public function testTicketCreateForClientUpgradeAllowsNumericUpgradeIdsStoredAsIntegers(): void
- {
- $randId = 1;
- $ticket = new \Model_SupportTicket();
- $ticket->loadBean(new \DummyBean());
-
- $currentProduct = new \Model_Product();
- $currentProduct->loadBean(new \DummyBean());
- $currentProduct->title = 'Starter';
- $currentProduct->upgrades = '[2]';
-
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()
- ->onlyMethods(['getExistingModelById', 'dispense', 'store'])->getMock();
- $dbMock->expects($this->once())
- ->method('getExistingModelById')
- ->with('Product', 1)
- ->willReturn($currentProduct);
- $dbMock->expects($this->once())
- ->method('dispense')
- ->with('SupportTicket')
- ->willReturn($ticket);
- $dbMock->expects($this->once())
- ->method('store')
- ->with($ticket)
- ->willReturn($randId);
-
- $order = new \Model_ClientOrder();
- $order->loadBean(new \DummyBean());
- $order->product_id = 1;
-
- $orderServiceMock = $this->getMockBuilder(\Box\Mod\Order\Service::class)
- ->onlyMethods(['findForClientById'])->getMock();
- $orderServiceMock->expects($this->once())
- ->method('findForClientById')
- ->willReturn($order);
-
- $modMock = $this->getMockBuilder('\\' . \FOSSBilling\Module::class)
- ->disableOriginalConstructor()->onlyMethods(['getConfig'])->getMock();
- $modMock->expects($this->once())->method('getConfig')->willReturn([]);
-
- $eventMock = $this->createMock('\Box_EventManager');
- $eventMock->expects($this->exactly(2))->method('fire');
-
- $serviceMock = $this->getMockBuilder(\Box\Mod\Support\Service::class)
- ->onlyMethods(['checkIfTaskAlreadyExists', 'messageCreateForTicket'])->getMock();
- $serviceMock->expects($this->once())->method('checkIfTaskAlreadyExists')->willReturn(false);
- $serviceMock->expects($this->once())->method('messageCreateForTicket')->willReturn(1);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $di['events_manager'] = $eventMock;
- $di['logger'] = $this->createMock('Box_Log');
- $di['mod'] = $di->protect(fn (): \PHPUnit\Framework\MockObject\MockObject => $modMock);
- $di['mod_service'] = $di->protect(fn (string $serviceName): ?\PHPUnit\Framework\MockObject\MockObject => match ($serviceName) {
- 'order' => $orderServiceMock,
- default => null,
- });
- $serviceMock->setDi($di);
-
- $helpdesk = new \Model_SupportHelpdesk();
- $helpdesk->loadBean(new \DummyBean());
- $helpdesk->id = 1;
-
- $client = new \Model_Client();
- $client->loadBean(new \DummyBean());
- $client->id = 1;
-
- $data = [
- 'subject' => 'Upgrade request',
- 'content' => 'Please upgrade my plan.',
- 'rel_id' => 10,
- 'rel_type' => \Model_SupportTicket::REL_TYPE_ORDER,
- 'rel_task' => \Model_SupportTicket::REL_TASK_UPGRADE,
- 'rel_new_value' => '2',
- ];
-
- $result = $serviceMock->ticketCreateForClient($client, $helpdesk, $data);
- $this->assertSame($randId, $result);
- }
-
- public function testTicketCreateForClientTaskAlreadyExistsException(): void
- {
- $message = new \Model_SupportTicketMessage();
- $message->loadBean(new \DummyBean());
-
- $serviceMock = $this->getMockBuilder(\Box\Mod\Support\Service::class)
- ->onlyMethods(['checkIfTaskAlreadyExists'])->getMock();
- $serviceMock->expects($this->atLeastOnce())->method('checkIfTaskAlreadyExists')
- ->willReturn(true);
-
- $order = new \Model_ClientOrder();
- $order->loadBean(new \DummyBean());
-
- $orderServiceMock = $this->getMockBuilder(\Box\Mod\Order\Service::class)
- ->onlyMethods(['findForClientById'])->getMock();
- $orderServiceMock->expects($this->atLeastOnce())->method('findForClientById')
- ->willReturn($order);
-
- $helpdesk = new \Model_SupportHelpdesk();
- $helpdesk->loadBean(new \DummyBean());
-
- $guest = new \Model_Guest();
- $guest->id = 1;
-
- $data = [
- 'rel_id' => 1,
- 'rel_type' => \Model_SupportTicket::REL_TYPE_ORDER,
- 'rel_task' => \Model_SupportTicket::REL_TASK_CANCEL,
- 'rel_new_value' => 'New value',
- ];
-
- $helpdesk = new \Model_SupportHelpdesk();
- $helpdesk->loadBean(new \DummyBean());
-
- $client = new \Model_Client();
- $client->loadBean(new \DummyBean());
- $client->id = 1;
-
- $di = $this->getDi();
- $di['mod_service'] = $di->protect(fn (string $serviceName): ?\PHPUnit\Framework\MockObject\MockObject => match ($serviceName) {
- 'order' => $orderServiceMock,
- default => null,
- });
-
- $serviceMock->setDi($di);
-
- $this->expectException(\FOSSBilling\Exception::class);
- $serviceMock->ticketCreateForClient($client, $helpdesk, $data);
- }
-
- public static function messageCreateForTicketProvider(): array
- {
- $admin = new \Model_Admin();
- $admin->loadBean(new \DummyBean());
- $admin->id = 1;
-
- $client = new \Model_Client();
- $client->loadBean(new \DummyBean());
- $client->id = 1;
-
- return [
- [
- $admin,
- ],
- [
- $client,
- ],
- ];
- }
-
- #[DataProvider('messageCreateForTicketProvider')]
- public function testMessageCreateForTicket(\Model_Admin|\Model_Client $identity): void
- {
- $randId = 1;
- $supportTicketMessage = new \Model_SupportTicketMessage();
- $supportTicketMessage->loadBean(new \DummyBean());
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('dispense')
- ->willReturn($supportTicketMessage);
- $dbMock->expects($this->atLeastOnce())
- ->method('store')
- ->willReturn($randId);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $di['logger'] = $this->createMock('Box_Log');
- $di['request'] = Request::createFromGlobals();
- $this->service->setDi($di);
-
- $ticket = new \Model_SupportTicket();
- $ticket->loadBean(new \DummyBean());
-
- $result = $this->service->messageCreateForTicket($ticket, $identity, 'Content');
- $this->assertIsInt($result);
- $this->assertEquals($result, $randId);
- }
-
- public function testPublicGetStatuses(): void
- {
- $result = $this->service->publicGetStatuses();
- $this->assertIsArray($result);
- }
-
- public function testPublicFindOneByHash(): void
- {
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('findOne')
- ->willReturn(new \Model_SupportPTicket());
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $this->service->setDi($di);
-
- $client = new \Model_Client();
- $client->loadBean(new \DummyBean());
- $client->id = 1;
-
- $result = $this->service->publicFindOneByHash(sha1(uniqid()));
- $this->assertInstanceOf('Model_SupportPTicket', $result);
- }
-
- public function testPublicFindOneByHashNotFoundException(): void
- {
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('findOne')
- ->willReturn(null);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $this->service->setDi($di);
-
- $client = new \Model_Client();
- $client->loadBean(new \DummyBean());
- $client->id = 1;
-
- $this->expectException(\FOSSBilling\Exception::class);
- $result = $this->service->publicFindOneByHash(sha1(uniqid()));
- $this->assertInstanceOf('Model_SupportPTicket', $result);
- }
-
- public static function publicGetSearchQueryProvider(): array
- {
- return [
- [
- [
- 'search' => 'Query',
- 'id' => 1,
- 'status' => \Model_SupportPTicket::OPENED,
- 'name' => 'Name',
- 'email' => 'email@example.com',
- 'subject' => 'Subject',
- 'content' => 'Content',
- ],
- ],
- [
- [
- 'search' => 1,
- 'id' => 1,
- 'status' => \Model_SupportPTicket::OPENED,
- 'name' => 'Name',
- 'email' => 'email@example.com',
- 'subject' => 'Subject',
- 'content' => 'Content',
- ],
- ],
- ];
- }
-
- #[DataProvider('publicGetSearchQueryProvider')]
- public function testPublicGetSearchQuery(array $data): void
- {
- $di = $this->getDi();
-
- $this->service->setDi($di);
-
- [$query, $bindings] = $this->service->publicgetSearchQuery($data);
- $this->assertIsString($query);
- $this->assertIsArray($bindings);
- }
-
- public function testPublicCounter(): void
- {
- $arr = [
- \Model_SupportPTicket::OPENED => 1,
- \Model_SupportPTicket::ONHOLD => 1,
- \Model_SupportPTicket::CLOSED => 1,
- ];
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('getAssoc')
- ->willReturn($arr);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $this->service->setDi($di);
-
- $result = $this->service->publicCounter();
- $this->assertIsArray($result);
- $this->assertArrayHasKey('total', $result);
- $this->assertEquals(array_sum($arr), $result['total']);
- }
-
- public function testPublicGetLatest(): void
- {
- $ticket = new \Model_SupportPTicket();
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('find')
- ->willReturn([$ticket, $ticket]);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $this->service->setDi($di);
-
- $result = $this->service->publicGetLatest();
- $this->assertIsArray($result);
- $this->assertInstanceOf('Model_SupportPTicket', $result[0]);
- }
-
- public function testPublicCountByStatus(): void
- {
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('getCell')
- ->willReturn(1);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $this->service->setDi($di);
-
- $result = $this->service->publicCountByStatus('open');
- $this->assertIsInt($result);
- }
-
- public function testPublicGetExpired(): void
- {
- $ticket = new \Model_SupportPTicket();
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('find')
- ->willReturn([$ticket, $ticket]);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $this->service->setDi($di);
-
- $result = $this->service->publicGetExpired();
- $this->assertIsArray($result);
- $this->assertInstanceOf('Model_SupportPTicket', $result[0]);
- }
-
- public static function publicCloseTicketProvider(): array
- {
- return [
- [new \Model_Admin()],
- [new \Model_Guest()],
- ];
- }
-
- #[DataProvider('publicCloseTicketProvider')]
- public function testPublicCloseTicket(\Model_Admin|\Model_Guest $identity): void
- {
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('store')
- ->willReturn(1);
-
- $eventMock = $this->createMock('\Box_EventManager');
- $eventMock->expects($this->atLeastOnce())->method('fire');
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $di['logger'] = $this->createMock('Box_Log');
- $di['events_manager'] = $eventMock;
- $this->service->setDi($di);
-
- $ticket = new \Model_SupportPTicket();
- $ticket->loadBean(new \DummyBean());
-
- $result = $this->service->publicCloseTicket($ticket, $identity);
- $this->assertTrue($result);
- }
-
- public function testPublicAutoClose(): void
- {
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('store')
- ->willReturn(1);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $di['logger'] = $this->createMock('Box_Log');
- $this->service->setDi($di);
-
- $ticket = new \Model_SupportPTicket();
- $ticket->loadBean(new \DummyBean());
-
- $result = $this->service->publicAutoClose($ticket);
- $this->assertTrue($result);
- }
-
- public function testPublicRm(): void
- {
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('trash')
- ->willReturn(null);
- $dbMock->expects($this->atLeastOnce())
- ->method('find')
- ->willReturn([new \Model_SupportPTicketMessage()]);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $di['logger'] = $this->createMock('Box_Log');
- $this->service->setDi($di);
-
- $canned = new \Model_SupportPTicket();
- $canned->loadBean(new \DummyBean());
-
- $result = $this->service->publicRm($canned);
- $this->assertTrue($result);
- }
-
- public static function publicToApiArrayProvider(): array
- {
- return [
- [
- new \Model_SupportPTicketMessage(),
- 'atLeastOnce',
- ],
- [
- null,
- 'never',
- ],
- ];
- }
-
- #[DataProvider('publicToApiArrayProvider')]
- public function testPublicToApiArray(?\Model_SupportPTicketMessage $findOne, string $publicMessageGetAuthorDetailsCalled): void
- {
- $ticketMessages = [new \Model_SupportPTicketMessage(), new \Model_SupportPTicketMessage()];
-
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->any())
- ->method('findOne')
- ->willReturn($findOne);
- $dbMock->expects($this->atLeastOnce())
- ->method('toArray')
- ->willReturn([]);
- $dbMock->expects($this->any())
- ->method('find')
- ->willReturn($ticketMessages);
-
- $serviceMock = $this->getMockBuilder(\Box\Mod\Support\Service::class)
- ->onlyMethods(['publicMessageToApiArray', 'publicMessageGetAuthorDetails'])->getMock();
- $serviceMock->expects($this->atLeastOnce())->method('publicMessageToApiArray')
- ->willReturn([]);
- $serviceMock->expects($this->atLeastOnce())->method('publicMessageGetAuthorDetails')
- ->willReturn(['name' => 'Name', 'email' => 'email#example.com']);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $di['logger'] = $this->createMock('Box_Log');
- $serviceMock->setDi($di);
-
- $ticket = new \Model_SupportPTicket();
- $ticket->loadBean(new \DummyBean());
-
- $result = $serviceMock->publicToApiArray($ticket, true);
- $this->assertIsArray($result);
- $this->assertArrayHasKey('author', $result);
- $this->assertArrayHasKey('messages', $result);
-
- $this->assertCount(count($ticketMessages), $result['messages']);
- }
-
- public function testPublicMessageGetAuthorDetailsAdmin(): void
- {
- $admin = new \Model_Admin();
- $admin->loadBean(new \DummyBean());
- $admin->id = 1;
-
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('getExistingModelById')
- ->willReturn($admin);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $this->service->setDi($di);
-
- $ticketMsg = new \Model_SupportPTicketMessage();
- $ticketMsg->loadBean(new \DummyBean());
- $ticketMsg->admin_id = 1;
-
- $result = $this->service->publicMessageGetAuthorDetails($ticketMsg, new \Model_Admin());
- $this->assertIsArray($result);
- $this->assertArrayHasKey('name', $result);
- $this->assertArrayHasKey('email', $result);
- }
-
- public function testPublicMessageGetAuthorDetailsNotAdmin(): void
- {
- $ticket = new \Model_SupportPTicket();
- $ticket->loadBean(new \DummyBean());
- $ticket->author_name = 'Name';
- $ticket->author_email = 'Email@example.com';
-
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('getExistingModelById')
- ->willReturn($ticket);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $this->service->setDi($di);
-
- $ticketMsg = new \Model_SupportPTicketMessage();
- $ticketMsg->loadBean(new \DummyBean());
- $ticketMsg->admin_id = null;
-
- $result = $this->service->publicMessageGetAuthorDetails($ticketMsg);
- $this->assertIsArray($result);
- $this->assertArrayHasKey('name', $result);
- $this->assertArrayNotHasKey('email', $result);
- }
-
- public function testPublicMessageToApiArray(): void
- {
- $serviceMock = $this->getMockBuilder(\Box\Mod\Support\Service::class)
- ->onlyMethods(['publicMessageGetAuthorDetails'])->getMock();
- $serviceMock->expects($this->atLeastOnce())->method('publicMessageGetAuthorDetails')
- ->willReturn([]);
-
- $di = $this->getDi();
- $serviceMock->setDi($di);
-
- $ticketMsg = new \Model_SupportPTicketMessage();
- $ticketMsg->loadBean(new \DummyBean());
- $ticketMsg->id = 1;
- $ticketMsg->support_p_ticket_id = 10;
- $ticketMsg->admin_id = 20;
- $ticketMsg->content = 'Public reply';
- $ticketMsg->ip = '192.0.2.1';
- $ticketMsg->created_at = '2026-01-01 00:00:00';
- $ticketMsg->updated_at = '2026-01-01 00:00:01';
-
- $result = $serviceMock->publicMessageToApiArray($ticketMsg);
- $this->assertIsArray($result);
- $this->assertSame(1, $result['id']);
- $this->assertSame('Public reply', $result['content']);
- $this->assertSame('2026-01-01 00:00:00', $result['created_at']);
- $this->assertSame('2026-01-01 00:00:01', $result['updated_at']);
- $this->assertArrayHasKey('author', $result);
- $this->assertArrayNotHasKey('ip', $result);
- $this->assertArrayNotHasKey('support_p_ticket_id', $result);
- $this->assertArrayNotHasKey('admin_id', $result);
- }
-
- public function testPublicMessageToApiArrayIncludesIpForAdmin(): void
- {
- $serviceMock = $this->getMockBuilder(\Box\Mod\Support\Service::class)
- ->onlyMethods(['publicMessageGetAuthorDetails'])->getMock();
- $serviceMock->expects($this->atLeastOnce())->method('publicMessageGetAuthorDetails')
- ->willReturn([]);
-
- $di = $this->getDi();
- $serviceMock->setDi($di);
-
- $ticketMsg = new \Model_SupportPTicketMessage();
- $ticketMsg->loadBean(new \DummyBean());
- $ticketMsg->id = 1;
- $ticketMsg->support_p_ticket_id = 10;
- $ticketMsg->admin_id = 20;
- $ticketMsg->content = 'Admin reply';
- $ticketMsg->ip = '192.0.2.1';
- $ticketMsg->created_at = '2024-01-01 00:00:00';
- $ticketMsg->updated_at = '2024-01-01 00:00:01';
-
- $result = $serviceMock->publicMessageToApiArray($ticketMsg, true, new \Model_Admin());
- $this->assertIsArray($result);
- $this->assertSame(10, $result['support_p_ticket_id']);
- $this->assertSame(20, $result['admin_id']);
- $this->assertSame('192.0.2.1', $result['ip']);
- $this->assertArrayHasKey('ip', $result);
- }
-
- public function testPublicToApiArrayHidesAuthorEmailForGuests(): void
- {
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('toArray')
- ->willReturn(['author_email' => 'customer@example.com']);
- $dbMock->expects($this->atLeastOnce())
- ->method('find')
- ->willReturn([]);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $this->service->setDi($di);
-
- $ticket = new \Model_SupportPTicket();
- $ticket->loadBean(new \DummyBean());
-
- $result = $this->service->publicToApiArray($ticket);
- $this->assertArrayNotHasKey('author_email', $result);
- }
-
- public function testPublicToApiArrayIncludesAuthorEmailForAdmin(): void
- {
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('toArray')
- ->willReturn(['author_email' => 'customer@example.com']);
- $dbMock->expects($this->atLeastOnce())
- ->method('find')
- ->willReturn([]);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $this->service->setDi($di);
-
- $ticket = new \Model_SupportPTicket();
- $ticket->loadBean(new \DummyBean());
-
- $result = $this->service->publicToApiArray($ticket, true, new \Model_Admin());
- $this->assertArrayHasKey('author_email', $result);
- }
-
- public function testPublicTicketCreate(): void
- {
- $message = new \Model_SupportTicketMessage();
- $message->loadBean(new \DummyBean());
-
- $randId = 1;
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('dispense')
- ->willReturn($message);
- $dbMock->expects($this->atLeastOnce())
- ->method('store')
- ->willReturn($randId);
-
- $eventMock = $this->createMock('\Box_EventManager');
- $eventMock->expects($this->atLeastOnce())->method('fire');
-
- $toolsMock = $this->createMock(\FOSSBilling\Tools::class);
- $toolsMock->expects($this->atLeastOnce())->method('validateAndSanitizeEmail');
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $di['logger'] = $this->createMock('Box_Log');
- $di['events_manager'] = $eventMock;
- $di['tools'] = $toolsMock;
- $di['request'] = Request::createFromGlobals();
- $this->service->setDi($di);
-
- $admin = new \Model_Admin();
- $admin->loadBean(new \DummyBean());
- $admin->id = 1;
-
- $data = [
- 'email' => 'email@example.com',
- 'name' => 'Name',
- 'message' => 'Message',
- 'request' => 'Request',
- 'subject' => 'Subject',
- ];
-
- $result = $this->service->publicTicketCreate($data, $admin);
- $this->assertIsInt($result);
- $this->assertEquals($result, $randId);
- }
-
- public function testPublicTicketUpdate(): void
- {
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('store')
- ->willReturn(1);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $di['logger'] = $this->createMock('Box_Log');
-
- $this->service->setDi($di);
-
- $ticket = new \Model_SupportPTicket();
- $ticket->loadBean(new \DummyBean());
-
- $data = [
- 'support_helpdesk_id' => 1,
- 'status' => \Model_SupportTicket::OPENED,
- 'subject' => 'Subject',
- 'priority' => 1,
- ];
-
- $result = $this->service->publicTicketUpdate($ticket, $data);
- $this->assertTrue($result);
- }
-
- public function testPublicTicketReply(): void
- {
- $message = new \Model_SupportTicketMessage();
- $message->loadBean(new \DummyBean());
-
- $randId = 1;
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('dispense')
- ->willReturn($message);
- $dbMock->expects($this->atLeastOnce())
- ->method('store')
- ->willReturn($randId);
-
- $eventMock = $this->createMock('\Box_EventManager');
- $eventMock->expects($this->atLeastOnce())->method('fire');
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $di['logger'] = $this->createMock('Box_Log');
- $di['events_manager'] = $eventMock;
- $di['request'] = Request::createFromGlobals();
- $this->service->setDi($di);
-
- $ticket = new \Model_SupportPTicket();
- $ticket->loadBean(new \DummyBean());
-
- $admin = new \Model_Admin();
- $admin->loadBean(new \DummyBean());
-
- $result = $this->service->publicTicketReply($ticket, $admin, 'Content');
- $this->assertIsInt($result);
- $this->assertEquals($result, $randId);
- }
-
- public function testPublicTicketReplyForGuest(): void
- {
- $message = new \Model_SupportTicketMessage();
- $message->loadBean(new \DummyBean());
-
- $randId = 1;
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('dispense')
- ->willReturn($message);
- $dbMock->expects($this->atLeastOnce())
- ->method('store')
- ->willReturn($randId);
-
- $eventMock = $this->createMock('\Box_EventManager');
- $eventMock->expects($this->atLeastOnce())->method('fire');
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $di['logger'] = $this->createMock('Box_Log');
- $di['events_manager'] = $eventMock;
- $di['request'] = Request::createFromGlobals();
- $this->service->setDi($di);
-
- $ticket = new \Model_SupportPTicket();
- $ticket->loadBean(new \DummyBean());
- $ticket->hash = sha1(uniqid());
-
- $admin = new \Model_Admin();
- $admin->loadBean(new \DummyBean());
-
- $result = $this->service->publicTicketReplyForGuest($ticket, 'Message');
- $this->assertIsString($result);
- $this->assertEquals(strlen($result), 40);
- }
-
- public function testHelpdeskUpdate(): void
- {
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('store')
- ->willReturn(1);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $di['logger'] = $this->createMock('Box_Log');
-
- $this->service->setDi($di);
-
- $helpdesk = new \Model_SupportHelpdesk();
- $helpdesk->loadBean(new \DummyBean());
-
- $data = [
- 'name' => 'Name',
- 'email' => 'email@example.com',
- 'can_reopen' => 1,
- 'close_after' => 1,
- 'signature' => 'Signature',
- ];
-
- $result = $this->service->helpdeskUpdate($helpdesk, $data);
- $this->assertTrue($result);
- }
-
- public function testHelpdeskCreate(): void
- {
- $randId = 1;
- $helpDeskModel = new \Model_SupportHelpdesk();
- $helpDeskModel->loadBean(new \DummyBean());
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('dispense')
- ->willReturn($helpDeskModel);
- $dbMock->expects($this->atLeastOnce())
- ->method('store')
- ->willReturn($randId);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $di['logger'] = $this->createMock('Box_Log');
-
- $this->service->setDi($di);
-
- $ticket = new \Model_SupportHelpdesk();
- $ticket->loadBean(new \DummyBean());
-
- $data = [
- 'name' => 'Name',
- 'email' => 'email@example.com',
- 'can_reopen' => 1,
- 'close_after' => 1,
- 'signature' => 'Signature',
- ];
-
- $result = $this->service->helpdeskCreate($data);
- $this->assertIsInt($result);
- $this->assertEquals($result, $randId);
- }
-
- public function testCannedGetSearchQuery(): void
- {
- $di = $this->getDi();
-
- $this->service->setDi($di);
-
- $data = [
- 'search' => 'query',
- ];
-
- [$query, $bindings] = $this->service->cannedGetSearchQuery($data);
- $this->assertIsString($query);
- $this->assertIsArray($bindings);
- }
-
- public function testCannedGetSearchQueryWithCategoryAndIdFilters(): void
- {
- $di = $this->getDi();
-
- $this->service->setDi($di);
-
- $data = [
- 'id' => '3',
- 'category_id' => '7',
- ];
-
- [$query, $bindings] = $this->service->cannedGetSearchQuery($data);
-
- $this->assertStringContainsString('sp.id = :id', $query);
- $this->assertStringContainsString('sp.support_pr_category_id = :category_id', $query);
- $this->assertSame([
- ':id' => 3,
- ':category_id' => 7,
- ], $bindings);
- }
-
- public function testCannedGetGroupedPairs(): void
- {
- $pairs = [
- 0 => [
- 'id' => 1,
- 'r_title' => 'R Title',
- 'c_title' => 'General',
- ],
- ];
-
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('getAll')
- ->willReturn($pairs);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $this->service->setDi($di);
-
- $expected = [
- 'General' => [
- 1 => 'R Title',
- ],
- ];
-
- $result = $this->service->cannedGetGroupedPairs();
- $this->assertIsArray($result);
- $this->assertEquals($result, $expected);
- }
-
- public function testCannedRm(): void
- {
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('trash')
- ->willReturn(null);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $di['logger'] = $this->createMock('Box_Log');
- $this->service->setDi($di);
-
- $canned = new \Model_SupportPr();
- $canned->loadBean(new \DummyBean());
-
- $result = $this->service->cannedRm($canned);
- $this->assertTrue($result);
- }
-
- public function testCannedToApiArray(): void
- {
- $category = new \Model_SupportPrCategory();
- $category->loadBean(new \DummyBean());
- $category->id = 1;
- $category->title = 'General';
-
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('toArray')
- ->willReturn([]);
- $dbMock->expects($this->atLeastOnce())
- ->method('load')
- ->willReturn($category);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $this->service->setDi($di);
-
- $canned = new \Model_SupportPr();
- $canned->loadBean(new \DummyBean());
-
- $result = $this->service->cannedToApiArray($canned);
- $this->assertIsArray($result);
- $this->assertArrayHasKey('category', $result);
- $this->assertIsArray($result['category']);
- $this->assertArrayHasKey('id', $result['category']);
- $this->assertArrayHasKey('title', $result['category']);
- }
-
- public function testCannedToApiArrayCategotyNotFound(): void
- {
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('toArray')
- ->willReturn([]);
- $dbMock->expects($this->atLeastOnce())
- ->method('load')
- ->willReturn(null);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $this->service->setDi($di);
-
- $canned = new \Model_SupportPr();
- $canned->loadBean(new \DummyBean());
-
- $result = $this->service->cannedToApiArray($canned);
- $this->assertIsArray($result);
- $this->assertArrayHasKey('category', $result);
- $this->assertSame([], $result['category']);
- }
-
- public function testCannedCategoryGetPairs(): void
- {
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('getAssoc')
- ->willReturn([0 => 'General']);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $this->service->setDi($di);
-
- $this->service->setDi($di);
-
- $note = new \Model_SupportTicketNote();
- $note->loadBean(new \DummyBean());
-
- $result = $this->service->cannedCategoryGetPairs();
- $this->assertIsArray($result);
- }
-
- public function testCannedCategoryRm(): void
- {
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('trash')
- ->willReturn(null);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $di['logger'] = $this->createMock('Box_Log');
- $this->service->setDi($di);
-
- $canned = new \Model_SupportPrCategory();
- $canned->loadBean(new \DummyBean());
-
- $result = $this->service->cannedCategoryRm($canned);
- $this->assertTrue($result);
- }
-
- public function testCannedCategoryToApiArray(): void
- {
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('toArray')
- ->willReturn([]);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $di['logger'] = $this->createMock('Box_Log');
- $this->service->setDi($di);
-
- $canned = new \Model_SupportPrCategory();
- $canned->loadBean(new \DummyBean());
-
- $result = $this->service->cannedCategoryToApiArray($canned);
- $this->assertIsArray($result);
- }
-
- public function testCannedCreate(): void
- {
- $randId = 1;
- $helpDeskModel = new \Model_SupportHelpdesk();
- $helpDeskModel->loadBean(new \DummyBean());
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('dispense')
- ->willReturn($helpDeskModel);
- $dbMock->expects($this->atLeastOnce())
- ->method('store')
- ->willReturn($randId);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $di['logger'] = $this->createMock('Box_Log');
- $this->service->setDi($di);
-
- $ticket = new \Model_SupportHelpdesk();
- $ticket->loadBean(new \DummyBean());
-
- $result = $this->service->cannedCreate('Name', 1, 'Content');
- $this->assertIsInt($result);
- $this->assertEquals($result, $randId);
- }
-
- public function testCannedUpdate(): void
- {
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('store')
- ->willReturn(1);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $di['logger'] = $this->createMock('Box_Log');
-
- $this->service->setDi($di);
-
- $model = new \Model_SupportPr();
- $model->loadBean(new \DummyBean());
-
- $data = [
- 'category_id' => 1,
- 'title' => 'email@example.com',
- 'content' => 1,
- ];
-
- $result = $this->service->cannedUpdate($model, $data);
- $this->assertTrue($result);
- }
-
- public function testCannedCategoryCreate(): void
- {
- $randId = 1;
- $supportPrCategoryModel = new \Model_SupportPrCategory();
- $supportPrCategoryModel->loadBean(new \DummyBean());
-
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('dispense')
- ->willReturn($supportPrCategoryModel);
- $dbMock->expects($this->atLeastOnce())
- ->method('store')
- ->willReturn($randId);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $di['logger'] = $this->createMock('Box_Log');
- $this->service->setDi($di);
-
- $result = $this->service->cannedCategoryCreate('Name');
- $this->assertIsInt($result);
- $this->assertEquals($result, $randId);
- }
-
- public function testCannedCategoryUpdate(): void
- {
- $randId = 1;
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('store')
- ->willReturn($randId);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $di['logger'] = $this->createMock('Box_Log');
- $this->service->setDi($di);
-
- $model = new \Model_SupportPrCategory();
- $model->loadBean(new \DummyBean());
-
- $result = $this->service->cannedCategoryUpdate($model, 'Title');
- $this->assertTrue($result);
- }
-
- public function testNoteCreate(): void
- {
- $randId = 1;
- $supportPrCategoryModel = new \Model_SupportPrCategory();
- $supportPrCategoryModel->loadBean(new \DummyBean());
-
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('dispense')
- ->willReturn($supportPrCategoryModel);
- $dbMock->expects($this->atLeastOnce())
- ->method('store')
- ->willReturn($randId);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $di['logger'] = $this->createMock('Box_Log');
- $this->service->setDi($di);
-
- $data = [
- 'name' => 'Name',
- 'email' => 'email@example.com',
- 'can_reopen' => 1,
- 'close_after' => 1,
- 'signature' => 'Signature',
- ];
-
- $admin = new \Model_Admin();
- $admin->loadBean(new \DummyBean());
-
- $ticket = new \Model_SupportTicket();
- $ticket->loadBean(new \DummyBean());
-
- $result = $this->service->noteCreate($ticket, $admin, 'Note');
- $this->assertIsInt($result);
- $this->assertEquals($result, $randId);
- }
-
- public function testTicketTaskComplete(): void
- {
- $randId = 1;
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('store')
- ->willReturn($randId);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $di['logger'] = $this->createMock('Box_Log');
- $this->service->setDi($di);
-
- $model = new \Model_SupportTicket();
- $model->loadBean(new \DummyBean());
-
- $result = $this->service->ticketTaskComplete($model);
- $this->assertTrue($result);
- }
-
- public static function canClientSubmitNewTicketProvider(): array
- {
- $ticket = new \Model_SupportTicket();
- $ticket->loadBean(new \DummyBean());
- $ticket->client_id = 5;
- $ticket->created_at = date('Y-m-d H:i:s');
-
- $ticket2 = new \Model_SupportTicket();
- $ticket2->loadBean(new \DummyBean());
- $ticket2->client_id = 5;
- $ticket2->created_at = date('Y-m-d H:i:s', strtotime('-2 days'));
-
- return [
- [$ticket, 24, false], // Ticket is created today, exception should be thrown
- [null, 24, true], // No previously created tickets found, can submit a ticket
- [$ticket2, 24, true], // Last ticket submitted 2 days ago, can submit a ticket
- ];
- }
-
- #[DataProvider('canClientSubmitNewTicketProvider')]
- public function testCanClientSubmitNewTicket(?\Model_SupportTicket $ticket, int $hours, bool $expected): void
- {
- if (!$expected) {
- $this->expectException(\FOSSBilling\Exception::class);
- }
- $dbMock = $this->getMockBuilder('\Box_Database')->disableOriginalConstructor()->getMock();
- $dbMock->expects($this->atLeastOnce())
- ->method('findOne')
- ->willReturn($ticket);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $this->service->setDi($di);
- $client = new \Model_Client();
- $client->loadBean(new \DummyBean());
- $client->id = 5;
-
- $config = ['wait_hours' => $hours];
-
- $result = $this->service->canClientSubmitNewTicket($client, $config);
- $this->assertTrue($result);
- }
-
- /*
- * Knowledge Base Tests.
- */
-
- public function testKbSearchArticles(): void
- {
- $service = new \Box\Mod\Support\Service();
-
- $willReturn = [
- 'pages' => 5,
- 'page' => 2,
- 'per_page' => 2,
- 'total' => 10,
- 'list' => [],
- ];
-
- $di = $this->getDi();
-
- $pager = $this->getMockBuilder(\FOSSBilling\Pagination::class)
- ->onlyMethods(['getPaginatedResultSet'])
- ->disableOriginalConstructor()
- ->getMock();
- $pager->expects($this->atLeastOnce())
- ->method('getPaginatedResultSet')
- ->willReturn($willReturn);
-
- $client = new \Model_Client();
- $client->loadBean(new \DummyBean());
- $client->id = 5;
- $di['pager'] = $pager;
- $service->setDi($di);
-
- $result = $service->kbSearchArticles('active', 'keyword', 'category', PaginationOptions::fromArray([]));
- $this->assertIsArray($result);
-
- $this->assertArrayHasKey('list', $result);
- $this->assertIsArray($result['list']);
-
- $this->assertArrayHasKey('pages', $result);
- $this->assertArrayHasKey('page', $result);
- $this->assertArrayHasKey('per_page', $result);
- $this->assertArrayHasKey('total', $result);
- }
-
- public function testKbFindActiveArticleById(): void
- {
- $service = new \Box\Mod\Support\Service();
-
- $model = new \Model_SupportKbArticle();
- $model->loadBean(new \DummyBean());
- $db = $this->createMock('Box_Database');
- $db->expects($this->atLeastOnce())
- ->method('findOne')
- ->willReturn($model);
-
- $di = $this->getDi();
- $di['db'] = $db;
- $service->setDi($di);
-
- $result = $service->kbFindActiveArticleById(5);
- $this->assertInstanceOf('Model_SupportKbArticle', $result);
- $this->assertEquals($result, $model);
- }
-
- public function testKbFindActiveArticleBySlug(): void
- {
- $service = new \Box\Mod\Support\Service();
-
- $model = new \Model_SupportKbArticle();
- $db = $this->createMock('Box_Database');
- $db->expects($this->atLeastOnce())
- ->method('findOne')
- ->willReturn($model);
-
- $di = $this->getDi();
- $di['db'] = $db;
- $service->setDi($di);
-
- $result = $service->kbFindActiveArticleBySlug('slug');
- $this->assertInstanceOf('Model_SupportKbArticle', $result);
- $this->assertEquals($result, $model);
- }
-
- public function testKbFindActive(): void
- {
- $service = new \Box\Mod\Support\Service();
-
- $db = $this->createMock('Box_Database');
- $db->expects($this->atLeastOnce())
- ->method('find')
- ->willReturn([]);
- $di = $this->getDi();
- $di['db'] = $db;
- $service->setDi($di);
-
- $result = $service->kbFindActive();
- $this->assertIsArray($result);
- }
-
- public function testKbHitView(): void
- {
- $service = new \Box\Mod\Support\Service();
-
- $db = $this->createMock('Box_Database');
- $db->expects($this->atLeastOnce())
- ->method('store')
- ->willReturn(5);
-
- $di = $this->getDi();
- $di['db'] = $db;
- $service->setDi($di);
-
- $modelKb = new \Model_SupportKbArticle();
- $modelKb->loadBean(new \DummyBean());
- $modelKb->views = 10;
-
- $result = $service->kbHitView($modelKb);
- $this->assertNull($result);
- }
-
- public function testKbRm(): void
- {
- $service = new \Box\Mod\Support\Service();
-
- $db = $this->createMock('Box_Database');
- $db->expects($this->atLeastOnce())
- ->method('trash')
- ->willReturn(null);
-
- $di = $this->getDi();
- $di['db'] = $db;
- $di['logger'] = $di['logger'] = $this->createMock('Box_Log');
- $service->setDi($di);
-
- $modelKb = new \Model_SupportKbArticle();
- $modelKb->loadBean(new \DummyBean());
- $modelKb->id = 1;
- $modelKb->views = 10;
-
- $result = $service->kbRm($modelKb);
- $this->assertNull($result);
- }
-
- public static function kbToApiArrayProvider(): array
- {
- $model = new \Model_SupportKbArticle();
- $model->loadBean(new \DummyBean());
- $model->id = 1;
- $model->slug = 'article-slug';
- $model->title = 'Title';
- $model->views = 1;
- $model->content = 'Content';
- $model->created_at = '2013-01-01 12:00:00';
- $model->updated_at = '2014-01-01 12:00:00';
- $model->status = 'active';
- $model->kb_article_category_id = 1;
-
- $category = new \Model_SupportKbArticleCategory();
- $category->loadBean(new \DummyBean());
- $category->id = 1;
- $category->slug = 'category-slug';
- $category->title = 'category-title';
-
- return [
- [
- $model,
- [
- 'id' => $model->id,
- 'slug' => $model->slug,
- 'title' => $model->title,
- 'views' => $model->views,
- 'created_at' => $model->created_at,
- 'updated_at' => $model->updated_at,
- 'category' => [
- 'id' => $category->id,
- 'slug' => $category->slug,
- 'title' => $category->title,
- ],
- 'status' => $model->status,
- ],
- false,
- null,
- $category,
- ],
- [
- $model,
- [
- 'id' => $model->id,
- 'slug' => $model->slug,
- 'title' => $model->title,
- 'views' => $model->views,
- 'created_at' => $model->created_at,
- 'updated_at' => $model->updated_at,
- 'category' => [
- 'id' => $category->id,
- 'slug' => $category->slug,
- 'title' => $category->title,
- ],
- 'content' => $model->content,
- 'status' => $model->status,
- ],
- true,
- null,
- $category,
- ],
- [
- $model,
- [
- 'id' => $model->id,
- 'slug' => $model->slug,
- 'title' => $model->title,
- 'views' => $model->views,
- 'created_at' => $model->created_at,
- 'updated_at' => $model->updated_at,
- 'category' => [
- 'id' => $category->id,
- 'slug' => $category->slug,
- 'title' => $category->title,
- ],
- 'content' => $model->content,
- 'status' => $model->status,
- 'kb_article_category_id' => $model->kb_article_category_id,
- ],
- true,
- new \Model_Admin(),
- $category,
- ],
- ];
- }
-
- #[DataProvider('kbToApiArrayProvider')]
- public function testKbToApiArray(\Model_SupportKbArticle $model, array $expected, bool $deep, ?\Model_Admin $identity, \Model_SupportKbArticleCategory $category): void
- {
- $service = new \Box\Mod\Support\Service();
-
- $db = $this->createMock('Box_Database');
- $db->expects($this->atLeastOnce())
- ->method('getExistingModelById')
- ->willReturn($category);
- $di = $this->getDi();
- $di['db'] = $db;
- $service->setDi($di);
-
- $result = $service->kbToApiArray($model, $deep, $identity);
- $this->assertEquals($result, $expected);
- }
-
- public function testKbCreateArticle(): void
- {
- $service = new \Box\Mod\Support\Service();
- $randId = 1;
- $db = $this->createMock('Box_Database');
- $db->expects($this->atLeastOnce())
- ->method('store')
- ->willReturn($randId);
- $model = new \Model_SupportKbArticle();
- $model->loadBean(new \DummyBean());
- $db->expects($this->atLeastOnce())
- ->method('dispense')
- ->willReturn($model);
-
- $tools = $this->getMockBuilder(\FOSSBilling\Tools::class)->onlyMethods(['slug'])->getMock();
- $tools->expects($this->atLeastOnce())
- ->method('slug')
- ->willReturn('article-slug');
-
- $di = $this->getDi();
- $di['db'] = $db;
- $di['tools'] = $tools;
- $di['logger'] = $this->createMock('Box_Log');
-
- $service->setDi($di);
- $result = $service->kbCreateArticle(1, 'Title', 'Active', 'Content');
- $this->assertIsInt($result);
- $this->assertEquals($result, $randId);
- }
-
- public function testKbUpdateArticle(): void
- {
- $service = new \Box\Mod\Support\Service();
- $randId = 1;
-
- $model = new \Model_SupportKbArticle();
- $model->loadBean(new \DummyBean());
-
- $kb_article_category_id = 1;
- $title = 'Title';
- $slug = 'article-slug';
- $status = 'active';
- $content = 'content';
- $views = 1;
-
- $db = $this->createMock('Box_Database');
- $db->expects($this->atLeastOnce())
- ->method('findOne')
- ->willReturn($model);
- $db->expects($this->atLeastOnce())
- ->method('store')
- ->willReturn($randId);
-
- $di = $this->getDi();
- $di['db'] = $db;
- $di['logger'] = $this->createMock('Box_Log');
-
- $service->setDi($di);
- $result = $service->kbUpdateArticle($randId, $kb_article_category_id, $title, $slug, $status, $content, $views);
- $this->assertIsBool($result);
- $this->assertTrue($result);
- }
-
- public function testKbUpdateArticleNotFoundException(): void
- {
- $service = new \Box\Mod\Support\Service();
- $randId = 1;
-
- $kb_article_category_id = 1;
- $title = 'Title';
- $slug = 'article-slug';
- $status = 'active';
- $content = 'content';
- $views = 1;
-
- $db = $this->createMock('Box_Database');
- $db->expects($this->atLeastOnce())
- ->method('findOne')
- ->willReturn(false);
- $db->expects($this->never())
- ->method('store')
- ->willReturn($randId);
-
- $di = $this->getDi();
- $di['db'] = $db;
- $di['logger'] = $this->createMock('Box_Log');
-
- $service->setDi($di);
- $this->expectException(\FOSSBilling\Exception::class);
- $result = $service->kbUpdateArticle($randId, $kb_article_category_id, $title, $slug, $status, $content, $views);
- $this->assertIsBool($result);
- $this->assertTrue($result);
- }
-
- public static function kbCategoryGetSearchQueryProvider(): array
- {
- return [
- [
- [],
- 'SELECT kac.*
- FROM support_kb_article_category kac
- LEFT JOIN support_kb_article ka ON kac.id = ka.kb_article_category_id GROUP BY kac.id ORDER BY kac.title',
- [],
- ],
- [
- [
- 'article_status' => 'active',
- ],
- 'SELECT kac.*
- FROM support_kb_article_category kac
- LEFT JOIN support_kb_article ka ON kac.id = ka.kb_article_category_id
- WHERE ka.status = :status GROUP BY kac.id ORDER BY kac.title',
- [
- ':status' => 'active',
- ],
- ],
- [
- [
- 'q' => 'search query',
- ],
- 'SELECT kac.*
- FROM support_kb_article_category kac
- LEFT JOIN support_kb_article ka ON kac.id = ka.kb_article_category_id
- WHERE (ka.title LIKE :title OR ka.content LIKE :content) GROUP BY kac.id ORDER BY kac.title',
- [
- ':title' => '%search query%',
- ':content' => '%search query%',
- ],
- ],
- [
- [
- 'q' => 'search query',
- 'article_status' => 'active',
- ],
- 'SELECT kac.*
- FROM support_kb_article_category kac
- LEFT JOIN support_kb_article ka ON kac.id = ka.kb_article_category_id
- WHERE ka.status = :status AND (ka.title LIKE :title OR ka.content LIKE :content) GROUP BY kac.id ORDER BY kac.title',
- [
- ':title' => '%search query%',
- ':content' => '%search query%',
- ':status' => 'active',
- ],
- ],
- ];
- }
-
- #[DataProvider('kbCategoryGetSearchQueryProvider')]
- public function testKbCategoryGetSearchQuery(array $data, string $query, array $bindings): void
- {
- $service = new \Box\Mod\Support\Service();
-
- $di = $this->getDi();
-
- $service->setDi($di);
-
- $result = $service->kbCategoryGetSearchQuery($data);
-
- $this->assertIsString($result[0]);
- $this->assertIsArray($result[1]);
-
- $this->assertEquals(trim((string) preg_replace('/\s+/', '', str_replace("\n", ' ', $result[0]))), trim((string) preg_replace('/\s+/', '', str_replace("\n", ' ', $query))));
- $this->assertEquals($result[1], $bindings);
- }
-
- public function testKbCategoryFindAll(): void
- {
- $service = new \Box\Mod\Support\Service();
-
- $db = $this->createMock('Box_Database');
- $db->expects($this->atLeastOnce())
- ->method('getAll')
- ->willReturn([]);
-
- $di = $this->getDi();
- $di['db'] = $db;
- $service->setDi($di);
-
- $result = $service->kbCategoryFindAll();
- $this->assertIsArray($result);
- }
-
- public function testKbCategoryGetPairs(): void
- {
- $service = new \Box\Mod\Support\Service();
-
- $db = $this->createMock('Box_Database');
- $db->expects($this->atLeastOnce())
- ->method('getAssoc')
- ->willReturn([]);
-
- $di = $this->getDi();
- $di['db'] = $db;
- $service->setDi($di);
-
- $result = $service->kbCategoryGetPairs();
- $this->assertIsArray($result);
- }
-
- public function testKbCategoryRm(): void
- {
- $service = new \Box\Mod\Support\Service();
-
- $db = $this->createMock('Box_Database');
- $db->expects($this->atLeastOnce())
- ->method('getCell')
- ->willReturn(0);
-
- $di = $this->getDi();
- $di['db'] = $db;
- $di['logger'] = $di['logger'] = $this->createMock('Box_Log');
- $service->setDi($di);
-
- $model = new \Model_SupportKbArticleCategory();
- $model->loadBean(new \DummyBean());
- $model->id = 1;
- $model->KbArticle = new \Model_SupportKbArticleCategory();
- $model->KbArticle->loadBean(new \DummyBean());
-
- $result = $service->kbCategoryRm($model);
- $this->assertTrue($result);
- }
-
- public function testKbCategoryRmHasArticlesException(): void
- {
- $service = new \Box\Mod\Support\Service();
-
- $db = $this->createMock('Box_Database');
- $db->expects($this->atLeastOnce())
- ->method('getCell')
- ->willReturn(1);
-
- $di = $this->getDi();
- $di['db'] = $db;
- $di['logger'] = $di['logger'] = $this->createMock('Box_Log');
- $service->setDi($di);
-
- $model = new \Model_SupportKbArticleCategory();
- $model->loadBean(new \DummyBean());
- $model->id = 1;
- $model->KbArticle = new \Model_SupportKbArticle();
- $model->KbArticle->loadBean(new \DummyBean());
-
- $this->expectException(\FOSSBilling\Exception::class);
- $result = $service->kbCategoryRm($model);
- $this->assertNull($result);
- }
-
- public function testKbCreateCategory(): void
- {
- $service = new \Box\Mod\Support\Service();
-
- $randId = 1;
-
- $db = $this->createMock('Box_Database');
- $db->expects($this->atLeastOnce())
- ->method('store')
- ->willReturn($randId);
- $articleCategoryModel = new \Model_SupportKbArticleCategory();
- $articleCategoryModel->loadBean(new \DummyBean());
-
- $db->expects($this->atLeastOnce())
- ->method('dispense')
- ->willReturn($articleCategoryModel);
-
- $tools = $this->getMockBuilder(\FOSSBilling\Tools::class)->onlyMethods(['slug'])->getMock();
- $tools->expects($this->atLeastOnce())
- ->method('slug')
- ->willReturn('article-slug');
-
- $di = $this->getDi();
- $di['db'] = $db;
- $di['tools'] = $tools;
- $di['logger'] = $di['logger'] = $this->createMock('Box_Log');
- $service->setDi($di);
-
- $result = $service->kbCreateCategory('Title', 'Description');
- $this->assertIsInt($result);
- $this->assertEquals($result, $randId);
- }
-
- public function testKbUpdateCategory(): void
- {
- $service = new \Box\Mod\Support\Service();
- $randId = 1;
- $db = $this->createMock('Box_Database');
- $db->expects($this->atLeastOnce())
- ->method('store')
- ->willReturn($randId);
-
- $di = $this->getDi();
- $di['db'] = $db;
- $di['logger'] = $di['logger'] = $this->createMock('Box_Log');
- $service->setDi($di);
-
- $model = new \Model_SupportKbArticleCategory();
- $model->loadBean(new \DummyBean());
- $model->id = 1;
-
- $result = $service->kbUpdateCategory($model, 'New Title', 'new-title', 'Description');
- $this->assertTrue($result);
- }
-
- public function testKbFindCategoryById(): void
- {
- $service = new \Box\Mod\Support\Service();
-
- $model = new \Model_SupportKbArticleCategory();
- $db = $this->createMock('Box_Database');
- $db->expects($this->atLeastOnce())
- ->method('getExistingModelById')
- ->willReturn($model);
-
- $di = $this->getDi();
- $di['db'] = $db;
- $service->setDi($di);
-
- $result = $service->kbFindCategoryById(5);
- $this->assertInstanceOf('Model_SupportKbArticleCategory', $result);
- $this->assertEquals($result, $model);
- }
-
- public function testKbFindCategoryBySlug(): void
- {
- $service = new \Box\Mod\Support\Service();
-
- $model = new \Model_SupportKbArticleCategory();
- $db = $this->createMock('Box_Database');
- $db->expects($this->atLeastOnce())
- ->method('findOne')
- ->willReturn($model);
-
- $di = $this->getDi();
- $di['db'] = $db;
- $service->setDi($di);
-
- $result = $service->kbFindCategoryBySlug('slug');
- $this->assertInstanceOf('Model_SupportKbArticleCategory', $result);
- $this->assertEquals($result, $model);
- }
-}
diff --git a/tests-legacy/modules/System/Api/AdminTest.php b/tests-legacy/modules/System/Api/AdminTest.php
deleted file mode 100644
index 64a228598..000000000
--- a/tests-legacy/modules/System/Api/AdminTest.php
+++ /dev/null
@@ -1,360 +0,0 @@
-api = $this->createAdminApi(Admin::class);
-
- $configContents = file_get_contents(PATH_CONFIG);
- if ($configContents === false) {
- self::fail('Failed to read the FOSSBilling config file.');
- }
-
- $this->originalConfigContents = $configContents;
- }
-
- public function testGetParams(): void
- {
- $data = [
- ];
-
- $serviceMock = $this->createMock(\Box\Mod\System\Service::class);
- $serviceMock->expects($this->atLeastOnce())
- ->method('getParams')
- ->willReturn([]);
-
- $staffServiceMock = $this->createMock(\Box\Mod\Staff\Service::class);
- $staffServiceMock->expects($this->once())
- ->method('checkPermissionsAndThrowException')
- ->with('system', 'manage_settings');
-
- $di = $this->getDi();
- $di['mod_service'] = $di->protect(function ($serviceName) use ($staffServiceMock) {
- if ($serviceName == 'Staff') {
- return $staffServiceMock;
- }
-
- return false;
- });
- $this->api->setDi($di);
- $this->api->setService($serviceMock);
-
- $result = $this->api->get_params($data);
- $this->assertIsArray($result);
- }
-
- public function testUpdateParams(): void
- {
- $data = [
- ];
-
- $serviceMock = $this->createMock(\Box\Mod\System\Service::class);
- $serviceMock->expects($this->atLeastOnce())
- ->method('updateParams')
- ->willReturn(true);
-
- $staffServiceMock = $this->createMock(\Box\Mod\Staff\Service::class);
- $staffServiceMock->expects($this->once())
- ->method('checkPermissionsAndThrowException')
- ->with('system', 'update_params');
-
- $di = $this->getDi();
- $di['mod_service'] = $di->protect(function ($serviceName) use ($staffServiceMock) {
- if ($serviceName == 'Staff') {
- return $staffServiceMock;
- }
-
- return false;
- });
- $this->api->setDi($di);
-
- $this->api->setService($serviceMock);
-
- $result = $this->api->update_params($data);
- $this->assertIsBool($result);
- $this->assertTrue($result);
- }
-
- public function testLocalizationSettings(): void
- {
- $staffServiceMock = $this->createMock(\Box\Mod\Staff\Service::class);
- $staffServiceMock->expects($this->once())
- ->method('checkPermissionsAndThrowException')
- ->with('system', 'manage_settings');
-
- $di = $this->getDi();
- $di['mod_service'] = $di->protect(function ($serviceName) use ($staffServiceMock) {
- if ($serviceName == 'Staff') {
- return $staffServiceMock;
- }
-
- return false;
- });
- $this->api->setDi($di);
-
- $result = $this->api->localization_settings();
-
- $this->assertIsArray($result);
- $this->assertArrayHasKey('locale', $result);
- $this->assertArrayHasKey('auto_detect_locale', $result);
- $this->assertIsString($result['locale']);
- $this->assertIsBool($result['auto_detect_locale']);
- }
-
- public function testUpdateLocalizationSettings(): void
- {
- $before = (bool) \FOSSBilling\Config::getProperty('i18n.auto_detect_locale', true);
-
- $staffServiceMock = $this->createMock(\Box\Mod\Staff\Service::class);
- $staffServiceMock->expects($this->once())
- ->method('checkPermissionsAndThrowException')
- ->with('system', 'update_params');
-
- $di = $this->getDi();
- $di['mod_service'] = $di->protect(function ($serviceName) use ($staffServiceMock) {
- if ($serviceName == 'Staff') {
- return $staffServiceMock;
- }
-
- return false;
- });
- $this->api->setDi($di);
-
- $result = $this->api->update_localization_settings([
- 'auto_detect_locale' => $before ? '0' : '1',
- ]);
-
- $this->assertTrue($result);
- $this->assertSame(!$before, \FOSSBilling\Config::getProperty('i18n.auto_detect_locale', $before));
- }
-
- public function testMessages(): void
- {
- $data = [
- ];
-
- $serviceMock = $this->createMock(\Box\Mod\System\Service::class);
- $serviceMock->expects($this->atLeastOnce())
- ->method('getMessages')
- ->willReturn([]);
-
- $staffServiceMock = $this->createMock(\Box\Mod\Staff\Service::class);
- $staffServiceMock->expects($this->once())
- ->method('checkPermissionsAndThrowException')
- ->with('system', 'manage_settings');
-
- $di = $this->getDi();
- $di['mod_service'] = $di->protect(function ($serviceName) use ($staffServiceMock) {
- if ($serviceName == 'Staff') {
- return $staffServiceMock;
- }
-
- return false;
- });
- $this->api->setDi($di);
- $this->api->setService($serviceMock);
-
- $result = $this->api->messages($data);
- $this->assertIsArray($result);
- }
-
- public function testCasMessagesReturnsEmptyListWithoutManageSettingsPermission(): void
- {
- $serviceMock = $this->createMock(\Box\Mod\System\Service::class);
- $serviceMock->expects($this->never())
- ->method('getCasMessages');
-
- $staffServiceMock = $this->createMock(\Box\Mod\Staff\Service::class);
- $staffServiceMock->expects($this->once())
- ->method('checkPermissionsAndThrowException')
- ->with('system', 'manage_settings')
- ->willThrowException(new \FOSSBilling\InformationException('You do not have permission to perform this action', [], 403));
-
- $di = $this->getDi();
- $di['mod_service'] = $di->protect(function ($serviceName) use ($staffServiceMock) {
- if ($serviceName == 'Staff') {
- return $staffServiceMock;
- }
-
- return false;
- });
- $this->api->setDi($di);
- $this->api->setService($serviceMock);
-
- $this->assertSame([], $this->api->cas_messages());
- }
-
- public function testTemplateExists(): void
- {
- $data = [
- 'file' => 'testing.txt',
- ];
-
- $serviceMock = $this->createMock(\Box\Mod\System\Service::class);
- $serviceMock->expects($this->atLeastOnce())
- ->method('templateExists')
- ->willReturn(true);
-
- $this->api->setService($serviceMock);
-
- $result = $this->api->template_exists($data);
- $this->assertIsBool($result);
- $this->assertTrue($result);
- }
-
- public function testEnv(): void
- {
- $data = [];
-
- $serviceMock = $this->createMock(\Box\Mod\System\Service::class);
- $serviceMock->expects($this->atLeastOnce())
- ->method('getEnv')
- ->willReturn([]);
-
- $staffServiceMock = $this->createMock(\Box\Mod\Staff\Service::class);
- $staffServiceMock->expects($this->once())
- ->method('checkPermissionsAndThrowException')
- ->with('system', 'manage_settings');
-
- $di = $this->getDi();
- $di['mod_service'] = $di->protect(function ($serviceName) use ($staffServiceMock) {
- if ($serviceName == 'Staff') {
- return $staffServiceMock;
- }
-
- return false;
- });
- $this->api->setDi($di);
- $this->api->setService($serviceMock);
-
- $result = $this->api->env($data);
- $this->assertIsArray($result);
- }
-
- public function testIsAllowed(): void
- {
- $data = [
- 'mod' => 'extension',
- ];
-
- $staffServiceMock = $this->createMock(\Box\Mod\Staff\Service::class);
- $staffServiceMock->expects($this->atLeastOnce())
- ->method('hasPermission')
- ->willReturn(true);
-
- $di = $this->getDi();
- $di['mod_service'] = $di->protect(function ($serviceName) use ($staffServiceMock) {
- if ($serviceName == 'Staff') {
- return $staffServiceMock;
- }
-
- return false;
- });
- $this->api->setDi($di);
-
- $result = $this->api->is_allowed($data);
- $this->assertIsBool($result);
- $this->assertTrue($result);
- }
-
- public function testRecheckUpdate(): void
- {
- $staffServiceMock = $this->createMock(\Box\Mod\Staff\Service::class);
- $staffServiceMock->expects($this->once())
- ->method('checkPermissionsAndThrowException')
- ->with('system', 'recheck_update');
-
- $updaterMock = $this->getMockBuilder(\FOSSBilling\Update::class)
- ->disableOriginalConstructor()
- ->onlyMethods(['getLatestVersionInfo'])
- ->getMock();
- $updaterMock->expects($this->once())
- ->method('getLatestVersionInfo')
- ->with(null, true);
-
- $di = $this->getDi();
- $di['updater'] = $updaterMock;
- $di['mod_service'] = $di->protect(function ($serviceName) use ($staffServiceMock) {
- if ($serviceName == 'Staff') {
- return $staffServiceMock;
- }
-
- return false;
- });
- $this->api->setDi($di);
-
- $result = $this->api->recheck_update();
- $this->assertTrue($result);
- }
-
- public function testToggleErrorReportingRequiresPermission(): void
- {
- $staffServiceMock = $this->createMock(\Box\Mod\Staff\Service::class);
- $staffServiceMock->expects($this->once())
- ->method('checkPermissionsAndThrowException')
- ->with('system', 'toggle_error_reporting')
- ->willThrowException(new \FOSSBilling\InformationException('denied'));
-
- $di = $this->getDi();
- $di['mod_service'] = $di->protect(function ($serviceName) use ($staffServiceMock) {
- if ($serviceName == 'Staff') {
- return $staffServiceMock;
- }
-
- return false;
- });
- $this->api->setDi($di);
-
- $this->expectException(\FOSSBilling\InformationException::class);
- $this->api->toggle_error_reporting();
- }
-
- public function testGetInterfaceIpsRequiresPermission(): void
- {
- $staffServiceMock = $this->createMock(\Box\Mod\Staff\Service::class);
- $staffServiceMock->expects($this->once())
- ->method('checkPermissionsAndThrowException')
- ->with('system', 'manage_network_interface')
- ->willThrowException(new \FOSSBilling\InformationException('denied'));
-
- $di = $this->getDi();
- $di['mod_service'] = $di->protect(function ($serviceName) use ($staffServiceMock) {
- if ($serviceName == 'Staff') {
- return $staffServiceMock;
- }
-
- return false;
- });
- $this->api->setDi($di);
-
- $this->expectException(\FOSSBilling\InformationException::class);
- $this->api->get_interface_ips();
- }
-
- protected function tearDown(): void
- {
- if ($this->originalConfigContents !== null) {
- file_put_contents(PATH_CONFIG, $this->originalConfigContents);
- clearstatcache(true, PATH_CONFIG);
-
- if (function_exists('opcache_invalidate')) {
- @opcache_invalidate(PATH_CONFIG, true);
- }
- }
-
- @unlink(\Symfony\Component\Filesystem\Path::changeExtension(PATH_CONFIG, 'old.php'));
-
- parent::tearDown();
- }
-}
diff --git a/tests-legacy/modules/System/Api/GuestTest.php b/tests-legacy/modules/System/Api/GuestTest.php
deleted file mode 100644
index 89eb3e6b6..000000000
--- a/tests-legacy/modules/System/Api/GuestTest.php
+++ /dev/null
@@ -1,199 +0,0 @@
-api = new Guest();
- }
-
- public function testCompanyShowPublicOn(): void
- {
- $companyData = ['companyName' => 'TestCo'];
-
- $authMock = $this->getMockBuilder('\Box_Authorization')->disableOriginalConstructor()->getMock();
- $authMock->method('isAdminLoggedIn')->willReturn(false);
- $authMock->method('isClientLoggedIn')->willReturn(false);
-
- $serviceMock = $this->createMock(\Box\Mod\System\Service::class);
- $serviceMock->expects($this->atLeastOnce())
- ->method('getCompany')
- ->willReturn($companyData);
- $serviceMock->expects($this->atLeastOnce())
- ->method('getParamValue')
- ->with('hide_company_public')
- ->willReturn(0);
-
- $di = $this->getDi();
- $di['auth'] = $authMock;
- $this->api->setDi($di);
- $this->api->setService($serviceMock);
- $result = $this->api->company();
-
- $this->assertIsArray($result);
- $this->assertNotEmpty($result);
- }
-
- public function testCompanyShowPublicOff(): void
- {
- $companyData = [
- 'companyName' => 'TestCo',
- 'vat_number' => 'Test VAT',
- 'email' => 'test@email.com',
- 'tel' => '123456789',
- 'account_number' => '987654321',
- 'number' => '123456',
- 'address_1' => 'Test Address 1',
- 'address_2' => 'Test Address 2',
- 'address_3' => 'Test Address 3',
- ];
-
- $authMock = $this->getMockBuilder('\Box_Authorization')->disableOriginalConstructor()->getMock();
- $authMock->method('isAdminLoggedIn')->willReturn(false);
- $authMock->method('isClientLoggedIn')->willReturn(false);
-
- $serviceMock = $this->createMock(\Box\Mod\System\Service::class);
- $serviceMock->expects($this->atLeastOnce())
- ->method('getCompany')
- ->willReturn($companyData);
- $serviceMock->expects($this->atLeastOnce())
- ->method('getParamValue')
- ->with('hide_company_public')
- ->willReturn(1);
-
- $di = $this->getDi();
- $di['auth'] = $authMock;
- $this->api->setDi($di);
- $this->api->setService($serviceMock);
- $result = $this->api->company();
-
- $this->assertIsArray($result);
- $this->assertArrayNotHasKey('vat_number', $result);
- $this->assertArrayNotHasKey('email', $result);
- $this->assertArrayNotHasKey('tel', $result);
- $this->assertArrayNotHasKey('account_number', $result);
- $this->assertArrayNotHasKey('number', $result);
- $this->assertArrayNotHasKey('address_1', $result);
- $this->assertArrayNotHasKey('address_2', $result);
- $this->assertArrayNotHasKey('address_3', $result);
- }
-
- public function testPeriodTitle(): void
- {
- $data = ['code' => 'periodCode'];
-
- $serviceMock = $this->createMock(\Box\Mod\System\Service::class);
- $serviceMock->expects($this->atLeastOnce())
- ->method('getPeriod')
- ->willReturn('periodTitleValue');
- $di = $this->getDi();
-
- $this->api->setDi($di);
- $this->api->setService($serviceMock);
-
- $result = $this->api->period_title($data);
- $this->assertIsString($result);
- }
-
- public function testPeriodTitleMissingCode(): void
- {
- $data = [];
- $expected = '-';
- $di = $this->getDi();
-
- $this->api->setDi($di);
- $result = $this->api->period_title($data);
- $this->assertIsString($result);
- $this->assertEquals($expected, $result);
- }
-
- public function testPeriodTitleLegacyZeroCodeReturnsDash(): void
- {
- $di = $this->getDi();
-
- $this->api->setDi($di);
- $result = $this->api->period_title(['code' => '0']);
-
- $this->assertSame('-', $result);
- }
-
- public function testCountriesReturnsConfiguredAllowList(): void
- {
- $di = new \Pimple\Container();
- $di['mod'] = $di->protect(fn (string $module): object => new class {
- public function getConfig(): array
- {
- return [
- 'countries' => "US=United States\njp=Japan\nINVALID\nZZ=Invalid Country\nDE=",
- ];
- }
- });
-
- $this->api->setDi($di);
-
- $this->assertSame([
- 'US' => 'United States',
- 'JP' => 'Japan',
- ], $this->api->countries());
- }
-
- public function testCountriesFallsBackToSymfonyCountriesWhenNotConfigured(): void
- {
- $di = new \Pimple\Container();
- $di['mod'] = $di->protect(fn (string $module): object => new class {
- public function getConfig(): array
- {
- return [];
- }
- });
-
- $this->api->setDi($di);
-
- $countries = $this->api->countries();
- $this->assertArrayHasKey('US', $countries);
- $this->assertArrayHasKey('JP', $countries);
- }
-
- public function testCountriesDoesNotExpandInvalidConfigurationToEveryCountry(): void
- {
- $di = new \Pimple\Container();
- $di['mod'] = $di->protect(fn (string $module): object => new class {
- public function getConfig(): array
- {
- return [
- 'countries' => "INVALID\nZZ=Invalid Country",
- ];
- }
- });
-
- $this->api->setDi($di);
-
- $this->assertSame([], $this->api->countries());
- }
-
- public function testGetPendingMessages(): void
- {
- $serviceMock = $this->createMock(\Box\Mod\System\Service::class);
- $messageArr = ['Important message to user'];
- $serviceMock->expects($this->atLeastOnce())
- ->method('getPendingMessages')
- ->willReturn($messageArr);
-
- $serviceMock->expects($this->atLeastOnce())
- ->method('clearPendingMessages');
-
- $this->api->setService($serviceMock);
- $result = $this->api->get_pending_messages();
- $this->assertIsArray($result);
- $this->assertEquals($messageArr, $result);
- }
-}
diff --git a/tests-legacy/modules/System/ServiceTest.php b/tests-legacy/modules/System/ServiceTest.php
deleted file mode 100644
index 641660853..000000000
--- a/tests-legacy/modules/System/ServiceTest.php
+++ /dev/null
@@ -1,1213 +0,0 @@
-service = new Service();
- }
-
- protected function tearDown(): void
- {
- Request::setTrustedProxies([], 0);
- parent::tearDown();
- }
-
- public function testGetParamValueMissingKeyParam(): void
- {
- $param = '';
- $this->expectException(\FOSSBilling\Exception::class);
- $this->expectExceptionMessage('Parameter key is missing');
-
- $this->service->getParamValue($param);
- }
-
- public function testGetCompany(): void
- {
- $expected = [
- 'www' => SYSTEM_URL,
- 'name' => 'Inc. Test',
- 'email' => 'work@example.eu',
- 'tel' => null,
- 'signature' => null,
- 'logo_url' => null,
- 'logo_url_dark' => null,
- 'favicon_url' => null,
- 'address_1' => null,
- 'address_2' => null,
- 'address_3' => null,
- 'account_number' => null,
- 'bank_name' => null,
- 'bic' => null,
- 'display_bank_info' => null,
- 'bank_info_pagebottom' => null,
- 'number' => null,
- 'note' => null,
- 'privacy_policy' => null,
- 'tos' => null,
- 'vat_number' => null,
- ];
-
- $multParamsResults = [
- [
- 'param' => 'company_name',
- 'value' => 'Inc. Test',
- ],
- [
- 'param' => 'company_email',
- 'value' => 'work@example.eu',
- ],
- ];
- $dbalConnectionStub = new readonly class($multParamsResults) {
- public function __construct(private array $rows)
- {
- }
-
- public function createQueryBuilder(): object
- {
- return new readonly class($this->rows) {
- public function __construct(private array $rows)
- {
- }
-
- public function select(string ...$columns): self
- {
- return $this;
- }
-
- public function from(string $table, ?string $alias = null): self
- {
- return $this;
- }
-
- public function where(string $predicate): self
- {
- return $this;
- }
-
- public function setParameter(string $key, mixed $value, mixed $type = null): self
- {
- return $this;
- }
-
- public function executeQuery(): object
- {
- return new readonly class($this->rows) {
- public function __construct(private array $rows)
- {
- }
-
- public function fetchAllAssociative(): array
- {
- return $this->rows;
- }
- };
- }
- };
- }
- };
-
- $di = $this->getDi();
- $di['dbal'] = $dbalConnectionStub;
-
- $this->service->setDi($di);
-
- $result = $this->service->getCompany();
- $this->assertIsArray($result);
- $this->assertEquals($expected, $result);
- }
-
- public function testGetParams(): void
- {
- $expected = [
- 'company_name' => 'Inc. Test',
- 'company_email' => 'work@example.eu',
- ];
- $multParamsResults = [
- [
- 'param' => 'company_name',
- 'value' => 'Inc. Test',
- ],
- [
- 'param' => 'company_email',
- 'value' => 'work@example.eu',
- ],
- ];
- $dbMock = $this->createMock('\Box_Database');
- $dbMock->expects($this->atLeastOnce())
- ->method('getAll')
- ->willReturn($multParamsResults);
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
-
- $this->service->setDi($di);
-
- $result = $this->service->getParams([]);
- $this->assertIsArray($result);
- $this->assertEquals($expected, $result);
- }
-
- public function testUpdateParams(): void
- {
- $data = [
- 'company_name' => 'newValue',
- ];
-
- $eventMock = $this->createMock('\Box_EventManager');
- $eventMock->expects($this->atLeastOnce())
- ->method('fire');
-
- $logMock = $this->createStub('\Box_Log');
-
- $staffServiceMock = $this->createStub(\Box\Mod\Staff\Service::class);
- $staffServiceMock->method('hasPermission')->willReturn(true);
-
- $systemServiceMock = $this->getMockBuilder(Service::class)->onlyMethods(['setParamValue'])->getMock();
- $systemServiceMock->expects($this->atLeastOnce())
- ->method('setParamValue')
- ->willReturn(true);
-
- $di = $this->getDi();
- $di['events_manager'] = $eventMock;
- $di['logger'] = $logMock;
- $di['mod_service'] = $di->protect(fn (string $name): \PHPUnit\Framework\MockObject\Stub => match ($name) {
- 'Staff' => $staffServiceMock,
- default => throw new \RuntimeException("Unexpected mod_service request: $name"),
- });
-
- $systemServiceMock->setDi($di);
- $result = $systemServiceMock->updateParams($data);
- $this->assertIsBool($result);
- $this->assertTrue($result);
- }
-
- public function testGetMessages(): void
- {
- $latestVersion = '1.0.0';
-
- $systemServiceMock = new class extends Service {
- public function getParamValue(string $param, $default = null): bool
- {
- return false;
- }
- };
-
- $updaterMock = $this->createMock(\FOSSBilling\Update::class);
- $updaterMock->expects($this->atLeastOnce())
- ->method('isUpdateAvailable')
- ->willReturn(true);
- $updaterMock->expects($this->atLeastOnce())
- ->method('getLatestVersion')
- ->willReturn($latestVersion);
- $updaterMock->expects($this->atLeastOnce())
- ->method('isBehindOnDBPatches')
- ->willReturn(false);
-
- $urlStub = new class {
- public function adminLink(string $path): string
- {
- return '/admin/' . ltrim($path, '/');
- }
- };
-
- $di = $this->getDi();
- $di['updater'] = $updaterMock;
- $di['url'] = $urlStub;
- $di['mod_service'] = $di->protect(fn (): \PHPUnit\Framework\MockObject\MockObject => $systemServiceMock);
-
- $systemServiceMock->setDi($di);
-
- $result = $systemServiceMock->getMessages('info');
- $this->assertIsArray($result);
- $this->assertCount(1, $result);
- $this->assertSame('info', $result[0]['type']);
- $this->assertSame('Update Available', $result[0]['title']);
- $this->assertSame("FOSSBilling {$latestVersion} is available for download.", $result[0]['message']);
- $this->assertSame('Review Update', $result[0]['buttons'][0]['text']);
- $this->assertArrayHasKey('link', $result[0]['buttons'][0]);
- $this->assertTrue($result[0]['dismissible']);
- }
-
- public function testGetMessagesReturnsAllTypesWhenNoFilterProvided(): void
- {
- $latestVersion = '1.0.0';
-
- $systemServiceMock = new class extends Service {
- public function getParamValue(string $param, $default = null): bool
- {
- return false;
- }
- };
-
- $updaterMock = $this->createMock(\FOSSBilling\Update::class);
- $updaterMock->expects($this->atLeastOnce())
- ->method('isUpdateAvailable')
- ->willReturn(true);
- $updaterMock->expects($this->atLeastOnce())
- ->method('getLatestVersion')
- ->willReturn($latestVersion);
- $updaterMock->expects($this->atLeastOnce())
- ->method('isBehindOnDBPatches')
- ->willReturn(false);
-
- $urlStub = new class {
- public function adminLink(string $path): string
- {
- return '/admin/' . ltrim($path, '/');
- }
- };
-
- $di = $this->getDi();
- $di['updater'] = $updaterMock;
- $di['url'] = $urlStub;
- $di['mod_service'] = $di->protect(fn (): \PHPUnit\Framework\MockObject\MockObject => $systemServiceMock);
-
- $systemServiceMock->setDi($di);
-
- $result = $systemServiceMock->getMessages();
- $this->assertIsArray($result);
- $this->assertContains('info', array_column($result, 'type'));
- }
-
- public function testGetCurrentUrlUsesTrustedRequestContext(): void
- {
- $request = Request::create('http://internal.example/admin/settings?tab=general', 'GET', [], [], [], [
- 'REMOTE_ADDR' => '198.51.100.10',
- 'HTTP_X_FORWARDED_PROTO' => 'https',
- 'HTTP_X_FORWARDED_HOST' => 'billing.example.com',
- ]);
- RequestFactory::configure($request, [
- 'enabled' => true,
- 'proxies' => ['198.51.100.10'],
- 'headers' => 'x_forwarded',
- ]);
-
- $di = $this->getDi();
- $di['request'] = $request;
- $this->service->setDi($di);
-
- $result = $this->service->getCurrentUrl();
-
- $this->assertSame('https://billing.example.com/admin/settings', $result);
- }
-
- public function testTemplateExistsEmptyPaths(): void
- {
- $getThemeResults = ['paths' => []];
- $themeServiceMock = $this->getMockBuilder(\Box\Mod\Theme\Service::class)->onlyMethods(['getThemeConfig'])->getMock();
- $themeServiceMock->expects($this->atLeastOnce())->method('getThemeConfig')
- ->willReturn($getThemeResults);
-
- $di = $this->getDi();
- $di['mod_service'] = $di->protect(fn (): \PHPUnit\Framework\MockObject\MockObject => $themeServiceMock);
- $this->service->setDi($di);
-
- $result = $this->service->templateExists('defaultFile.html.twig');
- $this->assertIsBool($result);
- $this->assertFalse($result);
- }
-
- public function testRenderAdapterTplString(): void
- {
- $apiGuest = new class {
- public function system_company(): array
- {
- return ['name' => 'FOSSBilling'];
- }
- };
-
- $di = $this->getDi();
- $di['api_guest'] = $apiGuest;
-
- $reflection = new \ReflectionClass(\FOSSBilling\Twig\TwigFactory::class);
- $twigFactory = $reflection->newInstanceWithoutConstructor();
-
- $diProperty = $reflection->getProperty('di');
- $diProperty->setValue($twigFactory, $di);
-
- $baseConfigProperty = $reflection->getProperty('baseConfig');
- $baseConfigProperty->setValue($twigFactory, ['cache' => false]);
-
- $di['twig_factory'] = $twigFactory;
- $this->service->setDi($di);
-
- $vars = ['invoice' => ['id' => 1, 'total' => 100]];
- $result = $this->service->renderAdapterTplString('Invoice #{{ invoice.id }} - {{ invoice.total }}', $vars);
- $this->assertEquals('Invoice #1 - 100', $result);
- }
-
- public function testCreateBaseEnvironmentProvidesNormalizedRequestUrl(): void
- {
- $di = $this->getDi();
- $request = Request::create('/admin/product', 'GET', [
- 'search' => 'query',
- ]);
- $di['request'] = $request;
- $di['session'] = $this->mockSession();
- $di['api_guest'] = new class {
- };
-
- $twig = $this->createBaseTwigEnvironment($di);
-
- $result = $twig->createTemplate('{{ request_path }}|{{ request.search }}|{{ request_query.search }}|{{ request_has_filters ? "1" : "0" }}')->render();
- $this->assertSame('product|query|query|0', $result);
- }
-
- public function testCreateBaseEnvironmentTreatsAdvancedFiltersSeparatelyFromSearch(): void
- {
- $di = $this->getDi();
- $request = Request::create('/admin/product', 'GET', [
- 'search' => 'query',
- 'status' => 'active',
- ]);
- $di['request'] = $request;
- $di['session'] = $this->mockSession();
- $di['api_guest'] = new class {
- };
-
- $twig = $this->createBaseTwigEnvironment($di);
-
- $result = $twig->createTemplate('{{ request_path }}|{{ request_query.search }}|{{ request_query.status }}|{{ request_has_filters ? "1" : "0" }}')->render();
- $this->assertSame('product|query|active|1', $result);
- }
-
- public function testCreateBaseEnvironmentProvidesDefaultCurrencyGlobal(): void
- {
- $di = $this->getDi();
- $di['request'] = Request::create('/');
- $di['session'] = $this->mockSession();
- $di['api_guest'] = new class {
- };
- $di['em'] = $this->createEntityManagerWithDefaultCurrency('EUR');
-
- $twig = $this->createBaseTwigEnvironment($di);
- $result = $twig->createTemplate('{{ default_currency }}')->render();
-
- $this->assertSame('EUR', $result);
- }
-
- public function testRenderAdapterTplStringSandboxViolation(): void
- {
- $apiGuest = new class {
- public function system_company(): array
- {
- return ['name' => 'FOSSBilling'];
- }
- };
-
- $di = $this->getDi();
- $di['api_guest'] = $apiGuest;
-
- $reflection = new \ReflectionClass(\FOSSBilling\Twig\TwigFactory::class);
- $twigFactory = $reflection->newInstanceWithoutConstructor();
-
- $diProperty = $reflection->getProperty('di');
- $diProperty->setValue($twigFactory, $di);
-
- $baseConfigProperty = $reflection->getProperty('baseConfig');
- $baseConfigProperty->setValue($twigFactory, ['cache' => false]);
-
- $di['twig_factory'] = $twigFactory;
- $di['logger'] = new class {
- public function setChannel(string $channel): self
- {
- return $this;
- }
-
- public function warning(string $message, array $context = []): void
- {
- }
- };
- $this->service->setDi($di);
-
- $this->expectException(\FOSSBilling\InformationException::class);
- $this->service->renderAdapterTplString('{{ range(1, 5) }}', []);
- }
-
- public function testRenderAdapterTplStringBlocksMethodCalls(): void
- {
- $object = new class {
- public function dangerousMethod(): string
- {
- return 'pwned';
- }
- };
-
- $this->expectException(\FOSSBilling\InformationException::class);
- $this->renderAdapterTemplate('{{ obj.dangerousMethod() }}', ['obj' => $object]);
- }
-
- public function testRenderAdapterTplStringBlocksPropertyAccess(): void
- {
- $object = new class {
- public string $secret = 'leaked';
- };
-
- $this->expectException(\FOSSBilling\InformationException::class);
- $this->renderAdapterTemplate('{{ obj.secret }}', ['obj' => $object]);
- }
-
- public function testRenderAdapterTplStringBlocksIncludeTag(): void
- {
- $this->expectException(\FOSSBilling\InformationException::class);
- $this->renderAdapterTemplate("{% include 'some_file.html' %}");
- }
-
- public function testRenderAdapterTplStringBlocksImportTag(): void
- {
- $this->expectException(\FOSSBilling\InformationException::class);
- $this->renderAdapterTemplate("{% import 'macros.html' as macros %}");
- }
-
- public function testRenderAdapterTplStringBlocksExtendsTag(): void
- {
- $this->expectException(\FOSSBilling\InformationException::class);
- $this->renderAdapterTemplate("{% extends 'base.html' %}");
- }
-
- public function testRenderAdapterTplStringStripsScriptTags(): void
- {
- $result = $this->renderAdapterTemplate('Hello
World');
- $this->assertSame('Hello
World', $result);
- }
-
- public function testRenderAdapterTplStringStripsSelfClosingScriptTags(): void
- {
- $result = $this->renderAdapterTemplate('Hello
World');
- $this->assertSame('Hello
World', $result);
- }
-
- public function testRenderAdapterTplStringStripsEventHandlers(): void
- {
- $result = $this->renderAdapterTemplate('text
');
- $this->assertSame('text
', $result);
- }
-
- public function testRenderAdapterTplStringStripsSingleQuotedEventHandlers(): void
- {
- $result = $this->renderAdapterTemplate("text
");
- $this->assertSame('text
', $result);
- }
-
- public function testRenderAdapterTplStringAllowsHtmlFormatting(): void
- {
- $html = 'Pay to:
Bank XYZ
Account: 12345';
- $result = $this->renderAdapterTemplate($html);
- $this->assertMatchesRegularExpression(
- '#^Pay to:
Bank XYZ
Account: 12345$#',
- $result
- );
- }
-
- public function testRenderAdapterTplStringAllowedFiltersWork(): void
- {
- $result = $this->renderAdapterTemplate('{{ 3.14159|number_format(2) }}');
- $this->assertSame('3.14', $result);
- }
-
- public function testRenderAdapterTplStringDateFilterWorks(): void
- {
- $result = $this->renderAdapterTemplate('{{ "2026-03-02"|date("Y-m-d") }}');
- $this->assertStringContainsString('2026-03-02', $result);
- }
-
- public function testRenderAdapterTplStringTransFilterWorks(): void
- {
- $result = $this->renderAdapterTemplate("{{ 'Hello'|trans }}");
- $this->assertSame('Hello', $result);
- }
-
- public function testSanitizeAdapterOutputStripsScriptTags(): void
- {
- $result = BrowserHtmlSanitizer::sanitizeAdapterHtml('Safe
');
- $this->assertSame('Safe
', $result);
- }
-
- public function testSanitizeAdapterOutputStripsScriptWithAttributes(): void
- {
- $result = BrowserHtmlSanitizer::sanitizeAdapterHtml('');
- $this->assertSame('', $result);
- }
-
- public function testSanitizeAdapterOutputStripsEventHandlers(): void
- {
- $result = BrowserHtmlSanitizer::sanitizeAdapterHtml('
');
- $this->assertSame('
', $result);
- }
-
- public function testSanitizeAdapterOutputPreservesSafeHtml(): void
- {
- $html = 'Title
Text bold
link';
- $result = BrowserHtmlSanitizer::sanitizeAdapterHtml($html);
- $this->assertSame($html, $result);
- }
-
- public function testSanitizeAdapterOutputStripsJavascriptHref(): void
- {
- $result = BrowserHtmlSanitizer::sanitizeAdapterHtml('Pay');
- $this->assertSame('Pay', $result);
- }
-
- public function testSanitizeAdapterOutputStripsEncodedJavascriptHref(): void
- {
- $result = BrowserHtmlSanitizer::sanitizeAdapterHtml('Pay');
- $this->assertSame('Pay', $result);
- }
-
- public function testSanitizeAdapterOutputStripsWhitespaceObfuscatedJavascriptHref(): void
- {
- $result = BrowserHtmlSanitizer::sanitizeAdapterHtml("Pay");
- $this->assertSame('Pay', $result);
- }
-
- public function testSanitizeAdapterOutputStripsDataUriSrc(): void
- {
- $result = BrowserHtmlSanitizer::sanitizeAdapterHtml('');
- $this->assertSame('', $result);
- }
-
- public function testSanitizeAdapterOutputHandlesEmptyString(): void
- {
- $result = BrowserHtmlSanitizer::sanitizeAdapterHtml('');
- $this->assertSame('', $result);
- }
-
- public function testRenderEmailTemplateSupportsPeriodTitleInSandbox(): void
- {
- $apiGuest = new class {
- public function system_company(): array
- {
- return ['name' => 'FOSSBilling'];
- }
-
- public function system_period_title(array $data): string
- {
- return match ($data['code'] ?? null) {
- '1M' => 'Every month',
- default => 'Unknown period',
- };
- }
- };
-
- $di = $this->getDi();
- $di['api_guest'] = $apiGuest;
-
- $reflection = new \ReflectionClass(\FOSSBilling\Twig\TwigFactory::class);
- $twigFactory = $reflection->newInstanceWithoutConstructor();
-
- $diProperty = $reflection->getProperty('di');
- $diProperty->setValue($twigFactory, $di);
-
- $baseConfigProperty = $reflection->getProperty('baseConfig');
- $baseConfigProperty->setValue($twigFactory, ['cache' => false]);
-
- $twig = $twigFactory->createEmailEnvironment();
- $result = $twig->createTemplate('{{ "1M"|period_title }}')->render([]);
-
- $this->assertSame('Every month', $result);
- }
-
- public function testRenderEmailTemplateSupportsMarkdownAndDateInSandbox(): void
- {
- $apiGuest = new class {
- public function system_company(): array
- {
- return ['name' => 'FOSSBilling'];
- }
- };
- $themeService = new class {
- public function getDefaultMarkdownAttributes(): array
- {
- return [];
- }
- };
-
- $di = $this->getDi();
- $di['api_guest'] = $apiGuest;
- $di['mod_service'] = $di->protect(fn (string $service): object => match ($service) {
- 'theme' => $themeService,
- default => throw new \RuntimeException(sprintf('Unexpected mod_service request: %s', $service)),
- });
-
- $reflection = new \ReflectionClass(\FOSSBilling\Twig\TwigFactory::class);
- $twigFactory = $reflection->newInstanceWithoutConstructor();
-
- $diProperty = $reflection->getProperty('di');
- $diProperty->setValue($twigFactory, $di);
-
- $baseConfigProperty = $reflection->getProperty('baseConfig');
- $baseConfigProperty->setValue($twigFactory, ['cache' => false]);
-
- $twig = $twigFactory->createEmailEnvironment();
- $result = $twig->createTemplate('{% apply markdown_to_html %}**Bolded**{% endapply %} {{ "2026-03-02"|date("Y-m-d") }}')->render([]);
-
- $this->assertStringContainsString('Bolded', $result);
- $this->assertStringContainsString('2026-03-02', $result);
- }
-
- public function testRenderEmailTemplateFallsBackToDefaultCurrencyInSandbox(): void
- {
- $di = $this->getDi();
- $di['api_guest'] = new class {
- public function system_company(): array
- {
- return ['name' => 'FOSSBilling'];
- }
- };
- $di['em'] = $this->createEntityManagerWithDefaultCurrency('EUR');
-
- $result = $this->renderEmailTemplateWithSandbox(
- '{{ invoice.total|format_currency(invoice.currency ?? default_currency) }}',
- ['invoice' => ['total' => 10]],
- $di
- );
-
- $this->assertNotSame('', $result);
- $this->assertStringContainsString('10', $result);
- }
-
- public function testBaseTwigEnvironmentSupportsHasPermissionFunction(): void
- {
- $authMock = new class {
- public function isAdminLoggedIn(): bool
- {
- return true;
- }
- };
-
- $staffService = new class {
- public function hasPermission($admin, string $module, ?string $permission = null): bool
- {
- return $admin->id === 42 && $module === 'system' && $permission === 'update_params';
- }
- };
-
- $di = $this->getDi();
- $di['auth'] = $authMock;
- $di['api_guest'] = new \stdClass();
- $di['loggedin_admin'] = (object) ['id' => 42];
- $di['session'] = $this->mockSession();
- $di['mod_service'] = $di->protect(fn (string $service): object => match ($service) {
- 'Staff' => $staffService,
- default => throw new \RuntimeException(sprintf('Unexpected mod_service request: %s', $service)),
- });
-
- $twig = $this->createBaseTwigEnvironment($di);
- $result = $twig->createTemplate("{{ has_permission('system', 'update_params') ? 'yes' : 'no' }}")->render([]);
-
- $this->assertSame('yes', $result);
- }
-
- public function testBaseTwigEnvironmentFbApiLinkDoesNotIncludeHrefInPayload(): void
- {
- $di = $this->getDi();
- $di['api_guest'] = new \stdClass();
- $di['session'] = $this->mockSession();
-
- $twig = $this->createBaseTwigEnvironment($di);
- $result = $twig->createTemplate("{{ fb_api_link({ href: '/admin/test', reload: true }) }}")->render([]);
-
- $this->assertSame('href="/admin/test" data-fb-api="{"reload":true,"type":"link"}"', $result);
- $this->assertStringNotContainsString('"href"', $result);
- }
-
- public function testBaseTwigEnvironmentFbApiEscapesAttributeJson(): void
- {
- $di = $this->getDi();
- $di['api_guest'] = new \stdClass();
- $di['session'] = $this->mockSession();
-
- $twig = $this->createBaseTwigEnvironment($di);
- $result = $twig->createTemplate("{{ fb_api_link({ modal: {type: 'confirm', content: content} }) }}")->render([
- 'content' => 'Block IP 127.0.0.1\' autofocus onfocus=alert(1) x=\'',
- ]);
-
- $this->assertStringContainsString('data-fb-api="{"modal":', $result);
- $this->assertStringContainsString('\u0027 autofocus', $result);
- $this->assertStringNotContainsString("' autofocus", $result);
- $this->assertStringNotContainsString("x='", $result);
- }
-
- public function testRenderEmailTemplateBlocksSetTag(): void
- {
- $this->expectException(\Twig\Sandbox\SecurityNotAllowedTagError::class);
- $this->expectExceptionMessage('Tag "set" is not allowed');
-
- $this->renderEmailTemplateWithSandbox("{% set x = 'malicious' %}{{ x }}");
- }
-
- public function testRenderEmailTemplateBlocksFunctionCalls(): void
- {
- $this->expectException(\Twig\Sandbox\SecurityNotAllowedFunctionError::class);
- $this->expectExceptionMessage('Function "max" is not allowed');
-
- $this->renderEmailTemplateWithSandbox('{{ max(1, 2, 3) }}');
- }
-
- public function testRenderEmailTemplateBlocksMethodCalls(): void
- {
- $this->expectException(\Twig\Sandbox\SecurityNotAllowedMethodError::class);
- $this->expectExceptionMessage('is not allowed');
-
- $object = new class {
- public function dangerousMethod(): string
- {
- return 'pwned';
- }
- };
- $this->renderEmailTemplateWithSandbox('{{ obj.dangerousMethod() }}', ['obj' => $object]);
- }
-
- public function testRenderEmailTemplateGuestGlobalIsRestricted(): void
- {
- $apiGuest = new class {
- public function system_company(): array
- {
- return ['name' => 'Test Company'];
- }
-
- public function system_params(): array
- {
- return ['secret' => 'value'];
- }
- };
-
- $di = $this->getDi();
- $di['api_guest'] = $apiGuest;
-
- $result = $this->renderEmailTemplateWithSandbox('{{ guest.system_company.name }}', [], $di);
- $this->assertSame('Test Company', $result);
- }
-
- public function testRenderEmailTemplateBlocksIncludeTag(): void
- {
- $this->expectException(\Twig\Sandbox\SecurityNotAllowedTagError::class);
- $this->expectExceptionMessage('Tag "include" is not allowed');
-
- $this->renderEmailTemplateWithSandbox("{% include 'some_file.html' %}");
- }
-
- public function testRenderEmailTemplateBlocksImportTag(): void
- {
- $this->expectException(\Twig\Sandbox\SecurityNotAllowedTagError::class);
- $this->expectExceptionMessage('Tag "import" is not allowed');
-
- $this->renderEmailTemplateWithSandbox("{% import 'macros.html' as macros %}");
- }
-
- public function testRenderEmailTemplateBlocksExtendsTag(): void
- {
- // Extends is blocked by the ArrayLoader not having the template,
- // but the sandbox would also block it if it got that far
- $this->expectException(\Twig\Error\LoaderError::class);
-
- $this->renderEmailTemplateWithSandbox("{% extends 'base.html' %}");
- }
-
- public function testRenderEmailTemplateUrlFilterWithClientAreaNamedArgument(): void
- {
- $apiGuest = new class {
- public function system_company(): array
- {
- return ['name' => 'Test'];
- }
- };
-
- $urlMock = $this->createStub(\Box_Url::class);
- $urlMock->method('link')
- ->willReturn('http://example.com/login?email=test%40example.com');
-
- $di = $this->getDi();
- $di['api_guest'] = $apiGuest;
- $di['url'] = $urlMock;
-
- $result = $this->renderEmailTemplateWithSandbox(
- "{{ 'login'|url(query: { 'email': 'test@example.com' }, area: 'client') }}",
- [],
- $di
- );
-
- $this->assertSame('http://example.com/login?email=test%40example.com', $result);
- }
-
- public function testRenderEmailTemplateUrlFilterWithAdminAreaNamedArgument(): void
- {
- $apiGuest = new class {
- public function system_company(): array
- {
- return ['name' => 'Test'];
- }
- };
-
- $urlMock = $this->createMock(\Box_Url::class);
- $urlMock->expects($this->once())
- ->method('adminLink')
- ->with('staff/login', ['email' => 'staff@example.com'])
- ->willReturn('http://example.com/admin/staff/login?email=staff%40example.com');
-
- $di = $this->getDi();
- $di['api_guest'] = $apiGuest;
- $di['url'] = $urlMock;
-
- $result = $this->renderEmailTemplateWithSandbox(
- "{{ 'staff/login'|url(query: { 'email': 'staff@example.com' }, area: 'admin') }}",
- [],
- $di
- );
-
- $this->assertSame('http://example.com/admin/staff/login?email=staff%40example.com', $result);
- }
-
- private function renderEmailTemplateWithSandbox(string $template, array $vars = [], ?\Pimple\Container $di = null): string
- {
- $di ??= $this->getDi();
- if (!isset($di['api_guest'])) {
- $di['api_guest'] = new class {
- public function system_company(): array
- {
- return ['name' => 'Test'];
- }
- };
- }
- if (!isset($di['logger'])) {
- $di['logger'] = $this->createStub(\Box_Log::class);
- }
-
- $reflection = new \ReflectionClass(\FOSSBilling\Twig\TwigFactory::class);
- $twigFactory = $reflection->newInstanceWithoutConstructor();
-
- $diProperty = $reflection->getProperty('di');
- $diProperty->setValue($twigFactory, $di);
-
- $baseConfigProperty = $reflection->getProperty('baseConfig');
- $baseConfigProperty->setValue($twigFactory, ['cache' => false]);
-
- $twig = $twigFactory->createEmailEnvironment();
-
- return $twig->createTemplate($template)->render($vars);
- }
-
- private function renderAdapterTemplate(string $template, array $vars = []): string
- {
- $apiGuest = new class {
- public function system_company(): array
- {
- return ['name' => 'Test'];
- }
- };
-
- $di = $this->getDi();
- $di['api_guest'] = $apiGuest;
-
- if (!isset($di['logger'])) {
- $di['logger'] = new class {
- public function setChannel(string $channel): self
- {
- return $this;
- }
-
- public function warning(string $message, array $context = []): void
- {
- }
- };
- }
-
- $reflection = new \ReflectionClass(\FOSSBilling\Twig\TwigFactory::class);
- $twigFactory = $reflection->newInstanceWithoutConstructor();
-
- $diProperty = $reflection->getProperty('di');
- $diProperty->setValue($twigFactory, $di);
-
- $baseConfigProperty = $reflection->getProperty('baseConfig');
- $baseConfigProperty->setValue($twigFactory, ['cache' => false]);
-
- $di['twig_factory'] = $twigFactory;
- $this->service->setDi($di);
-
- return $this->service->renderAdapterTplString($template, $vars);
- }
-
- private function createBaseTwigEnvironment(\Pimple\Container $di): \Twig\Environment
- {
- if (!$di->offsetExists('request')) {
- $di['request'] = Request::create('/');
- }
-
- $reflection = new \ReflectionClass(\FOSSBilling\Twig\TwigFactory::class);
- $twigFactory = $reflection->newInstanceWithoutConstructor();
-
- $diProperty = $reflection->getProperty('di');
- $diProperty->setValue($twigFactory, $di);
-
- $baseConfigProperty = $reflection->getProperty('baseConfig');
- $baseConfigProperty->setValue($twigFactory, ['cache' => false]);
-
- return $twigFactory->createBaseEnvironment();
- }
-
- private function createEntityManagerWithDefaultCurrency(string $code): object
- {
- $defaultCurrency = new \Box\Mod\Currency\Entity\Currency($code);
-
- $repository = new readonly class($defaultCurrency) {
- public function __construct(private \Box\Mod\Currency\Entity\Currency $currency)
- {
- }
-
- public function findDefault(): \Box\Mod\Currency\Entity\Currency
- {
- return $this->currency;
- }
- };
-
- return new readonly class($repository) {
- public function __construct(private object $repository)
- {
- }
-
- public function getRepository(string $class): object
- {
- return $this->repository;
- }
- };
- }
-
- private function mockSession(): \FOSSBilling\Session
- {
- $sessionMock = $this->createStub(\FOSSBilling\Session::class);
- $sessionMock->method('get')->willReturn('test_csrf_token');
-
- return $sessionMock;
- }
-
- public function testClearCache(): void
- {
- // Use a temporary directory for testing instead of PATH_CACHE
- $cacheDir = sys_get_temp_dir() . '/fossbilling_test_cache_' . uniqid();
-
- // Create cache directory with .gitkeep
- if (!is_dir($cacheDir)) {
- mkdir($cacheDir, 0o755, true);
- }
-
- $gitkeepFile = $cacheDir . '/.gitkeep';
- file_put_contents($gitkeepFile, '');
-
- // Call clearCache with the temp directory
- $result = $this->service->clearCache($cacheDir);
-
- $this->assertIsBool($result);
- $this->assertTrue($result);
- $this->assertFileDoesNotExist($gitkeepFile);
-
- // Cleanup temp directory
- if (is_dir($cacheDir) && !(new \FilesystemIterator($cacheDir))->valid()) {
- rmdir($cacheDir);
- }
- }
-
- public function testGetPeriod(): void
- {
- $code = '1W';
- $expected = 'Every Week';
- $result = $this->service->getPeriod($code);
-
- $this->assertIsString($result);
- $this->assertEquals($expected, $result);
- }
-
- public function testGetPeriodLegacyZeroSentinelReturnsDash(): void
- {
- $result = $this->service->getPeriod('0');
-
- $this->assertSame('-', $result);
- }
-
- public function testGetPeriodBooleanFalseReturnsDash(): void
- {
- $result = $this->service->getPeriod(false);
-
- $this->assertSame('-', $result);
- }
-
- public function testGetPeriodArrayReturnsDash(): void
- {
- $result = $this->service->getPeriod([]);
-
- $this->assertSame('-', $result);
- }
-
- public function testGetPendingMessages(): void
- {
- $di = $this->getDi();
-
- $sessionMock = $this->getMockBuilder(\FOSSBilling\Session::class)->disableOriginalConstructor()->getMock();
- $sessionMock->expects($this->atLeastOnce())
- ->method('get')
- ->with('pending_messages')
- ->willReturn([]);
-
- $di['session'] = $sessionMock;
-
- $this->service->setDi($di);
- $result = $this->service->getPendingMessages();
- $this->assertIsArray($result);
- }
-
- public function testGetPendingMessagesGetReturnsNotArray(): void
- {
- $di = $this->getDi();
-
- $sessionMock = $this->getMockBuilder(\FOSSBilling\Session::class)->disableOriginalConstructor()->getMock();
- $sessionMock->expects($this->atLeastOnce())
- ->method('get')
- ->with('pending_messages')
- ->willReturn(null);
-
- $di['session'] = $sessionMock;
-
- $this->service->setDi($di);
- $result = $this->service->getPendingMessages();
- $this->assertIsArray($result);
- }
-
- public function testSetPendingMessage(): void
- {
- $serviceMock = $this->getMockBuilder(Service::class)
- ->onlyMethods(['getPendingMessages'])
- ->getMock();
- $serviceMock->expects($this->atLeastOnce())
- ->method('getPendingMessages')
- ->willReturn([]);
-
- $di = $this->getDi();
-
- $sessionMock = $this->getMockBuilder(\FOSSBilling\Session::class)->disableOriginalConstructor()->getMock();
- $sessionMock->expects($this->atLeastOnce())
- ->method('set')
- ->with('pending_messages');
-
- $di['session'] = $sessionMock;
-
- $serviceMock->setDi($di);
-
- $message = 'Important Message';
- $result = $serviceMock->setPendingMessage($message);
- $this->assertTrue($result);
- }
-
- public function testClearPendingMessages(): void
- {
- $di = $this->getDi();
-
- $sessionMock = $this->getMockBuilder(\FOSSBilling\Session::class)->disableOriginalConstructor()->getMock();
- $sessionMock->expects($this->atLeastOnce())
- ->method('delete')
- ->with('pending_messages');
- $di['session'] = $sessionMock;
- $this->service->setDi($di);
- $result = $this->service->clearPendingMessages();
- $this->assertTrue($result);
- }
-
- public function testUpdateParamsRejectsBankFieldsWithoutPermission(): void
- {
- $data = [
- 'company_bank_name' => 'Malicious Bank',
- ];
-
- $eventMock = $this->createMock('\Box_EventManager');
- $eventMock->expects($this->atLeastOnce())
- ->method('fire');
-
- $staffServiceMock = $this->createStub(\Box\Mod\Staff\Service::class);
- $staffServiceMock->method('hasPermission')->willReturn(false);
-
- $di = $this->getDi();
- $di['events_manager'] = $eventMock;
- $di['mod_service'] = $di->protect(fn (string $name): \PHPUnit\Framework\MockObject\Stub => match ($name) {
- 'Staff' => $staffServiceMock,
- default => throw new \RuntimeException("Unexpected mod_service request: $name"),
- });
-
- $this->service->setDi($di);
-
- $this->expectException(\FOSSBilling\InformationException::class);
- $this->expectExceptionMessage('You do not have permission to update the parameter company_bank_name');
- $this->service->updateParams($data);
- }
-
- public function testUpdateParamsRejectsBicWithoutPermission(): void
- {
- $data = [
- 'company_bic' => 'MALICUS33',
- ];
-
- $eventMock = $this->createMock('\Box_EventManager');
- $eventMock->expects($this->atLeastOnce())
- ->method('fire');
-
- $staffServiceMock = $this->createStub(\Box\Mod\Staff\Service::class);
- $staffServiceMock->method('hasPermission')->willReturn(false);
-
- $di = $this->getDi();
- $di['events_manager'] = $eventMock;
- $di['mod_service'] = $di->protect(fn (string $name): \PHPUnit\Framework\MockObject\Stub => match ($name) {
- 'Staff' => $staffServiceMock,
- default => throw new \RuntimeException("Unexpected mod_service request: $name"),
- });
-
- $this->service->setDi($di);
-
- $this->expectException(\FOSSBilling\InformationException::class);
- $this->expectExceptionMessage('You do not have permission to update the parameter company_bic');
- $this->service->updateParams($data);
- }
-
- public function testUpdateParamsAllowsBankFieldsWithPermission(): void
- {
- $data = [
- 'company_bank_name' => 'Safe Bank',
- 'company_bic' => 'SAFEUS33',
- ];
-
- $eventMock = $this->createMock('\Box_EventManager');
- $eventMock->expects($this->atLeastOnce())
- ->method('fire');
-
- $logMock = $this->createStub('\Box_Log');
-
- $staffServiceMock = $this->createStub(\Box\Mod\Staff\Service::class);
- $staffServiceMock->method('hasPermission')->willReturn(true);
-
- $systemServiceMock = $this->getMockBuilder(Service::class)->onlyMethods(['setParamValue'])->getMock();
- $systemServiceMock->expects($this->exactly(2))
- ->method('setParamValue')
- ->willReturn(true);
-
- $di = $this->getDi();
- $di['events_manager'] = $eventMock;
- $di['logger'] = $logMock;
- $di['mod_service'] = $di->protect(fn (string $name): \PHPUnit\Framework\MockObject\Stub => match ($name) {
- 'Staff' => $staffServiceMock,
- default => throw new \RuntimeException("Unexpected mod_service request: $name"),
- });
-
- $systemServiceMock->setDi($di);
- $result = $systemServiceMock->updateParams($data);
- $this->assertTrue($result);
- }
-}
diff --git a/tests-legacy/modules/Theme/Api/AdminTest.php b/tests-legacy/modules/Theme/Api/AdminTest.php
deleted file mode 100644
index b1a32598d..000000000
--- a/tests-legacy/modules/Theme/Api/AdminTest.php
+++ /dev/null
@@ -1,182 +0,0 @@
-api = $this->createAdminApi(Admin::class);
- }
-
- public function testGetList(): void
- {
- $systemServiceMock = $this->createMock(\Box\Mod\Theme\Service::class);
- $systemServiceMock->expects($this->atLeastOnce())
- ->method('getThemes')
- ->willReturn([]);
-
- $this->api->setService($systemServiceMock);
-
- $result = $this->api->get_list([]);
- $this->assertIsArray($result);
- }
-
- public function testGet(): void
- {
- $data = [
- 'code' => 'themeCode',
- ];
-
- $systemServiceMock = $this->createMock(\Box\Mod\Theme\Service::class);
- $systemServiceMock->expects($this->atLeastOnce())
- ->method('loadTheme')
- ->willReturn([]);
-
- $validatorMock = $this->getMockBuilder(\FOSSBilling\Validate::class)->disableOriginalConstructor()->getMock();
- $validatorMock->expects($this->any())->method('checkRequiredParamsForArray');
-
- $di = $this->getDi();
- $this->api->setDi($di);
- $this->api->setService($systemServiceMock);
-
- $result = $this->api->get($data);
- $this->assertIsArray($result);
- }
-
- public function testSelectNotAdminTheme(): void
- {
- $data = [
- 'code' => 'pjw',
- ];
-
- $themeMock = $this->getMockBuilder(\Box\Mod\Theme\Model\Theme::class)->disableOriginalConstructor()->getMock();
- $themeMock->expects($this->atLeastOnce())
- ->method('isAdminAreaTheme')
- ->willReturn(false);
-
- $serviceMock = $this->createMock(\Box\Mod\Theme\Service::class);
- $serviceMock->expects($this->atLeastOnce())
- ->method('getTheme')
- ->willReturn($themeMock);
-
- $systemServiceMock = $this->createMock(\Box\Mod\System\Service::class);
- $systemServiceMock->expects($this->atLeastOnce())
- ->method('setParamValue')
- ->with($this->equalTo('theme'));
-
- $validatorMock = $this->getMockBuilder(\FOSSBilling\Validate::class)->disableOriginalConstructor()->getMock();
- $validatorMock->expects($this->any())->method('checkRequiredParamsForArray');
-
- $loggerMock = $this->createMock('\Box_Log');
-
- $di = $this->getDi();
- $di['mod_service'] = $di->protect(fn (): \PHPUnit\Framework\MockObject\MockObject => $systemServiceMock);
- $di['logger'] = $loggerMock;
- $this->api->setDi($di);
- $this->api->setService($serviceMock);
-
- $result = $this->api->select($data);
- $this->assertTrue($result);
- }
-
- public function testSelectAdminTheme(): void
- {
- $data = [
- 'code' => 'pjw',
- ];
-
- $themeMock = $this->getMockBuilder(\Box\Mod\Theme\Model\Theme::class)->disableOriginalConstructor()->getMock();
- $themeMock->expects($this->atLeastOnce())
- ->method('isAdminAreaTheme')
- ->willReturn(true);
-
- $serviceMock = $this->createMock(\Box\Mod\Theme\Service::class);
- $serviceMock->expects($this->atLeastOnce())
- ->method('getTheme')
- ->willReturn($themeMock);
-
- $systemServiceMock = $this->createMock(\Box\Mod\System\Service::class);
- $systemServiceMock->expects($this->atLeastOnce())
- ->method('setParamValue')
- ->with($this->equalTo('admin_theme'));
-
- $validatorMock = $this->getMockBuilder(\FOSSBilling\Validate::class)->disableOriginalConstructor()->getMock();
- $validatorMock->expects($this->any())->method('checkRequiredParamsForArray');
-
- $loggerMock = $this->createMock('\Box_Log');
-
- $di = $this->getDi();
- $di['mod_service'] = $di->protect(fn (): \PHPUnit\Framework\MockObject\MockObject => $systemServiceMock);
- $di['logger'] = $loggerMock;
- $this->api->setDi($di);
- $this->api->setService($serviceMock);
-
- $result = $this->api->select($data);
- $this->assertTrue($result);
- }
-
- public function testPresetDelete(): void
- {
- $data = [
- 'code' => 'themeCode',
- 'preset' => 'themePreset',
- ];
-
- $themeMock = $this->getMockBuilder(\Box\Mod\Theme\Model\Theme::class)->disableOriginalConstructor()->getMock();
-
- $serviceMock = $this->createMock(\Box\Mod\Theme\Service::class);
- $serviceMock->expects($this->atLeastOnce())
- ->method('getTheme')
- ->willReturn($themeMock);
- $serviceMock->expects($this->atLeastOnce())
- ->method('deletePreset');
-
- $validatorMock = $this->getMockBuilder(\FOSSBilling\Validate::class)->disableOriginalConstructor()->getMock();
- $validatorMock->expects($this->any())->method('checkRequiredParamsForArray');
-
- $di = $this->getDi();
- $this->api->setDi($di);
- $this->api->setService($serviceMock);
-
- $result = $this->api->preset_delete($data);
- $this->assertIsBool($result);
- $this->assertTrue($result);
- }
-
- public function testPresetSelect(): void
- {
- $data = [
- 'code' => 'themeCode',
- 'preset' => 'themePreset',
- ];
-
- $themeMock = $this->getMockBuilder(\Box\Mod\Theme\Model\Theme::class)->disableOriginalConstructor()->getMock();
-
- $serviceMock = $this->createMock(\Box\Mod\Theme\Service::class);
- $serviceMock->expects($this->atLeastOnce())
- ->method('getTheme')
- ->willReturn($themeMock);
- $serviceMock->expects($this->atLeastOnce())
- ->method('setCurrentThemePreset');
-
- $validatorMock = $this->getMockBuilder(\FOSSBilling\Validate::class)->disableOriginalConstructor()->getMock();
- $validatorMock->expects($this->any())->method('checkRequiredParamsForArray');
-
- $di = $this->getDi();
- $this->api->setDi($di);
-
- $this->api->setService($serviceMock);
-
- $result = $this->api->preset_select($data);
- $this->assertIsBool($result);
- $this->assertTrue($result);
- }
-}
diff --git a/tests-legacy/modules/Theme/Controller/AdminTest.php b/tests-legacy/modules/Theme/Controller/AdminTest.php
deleted file mode 100644
index f8fb8a215..000000000
--- a/tests-legacy/modules/Theme/Controller/AdminTest.php
+++ /dev/null
@@ -1,93 +0,0 @@
-getDi();
- $db = $this->createMock('Box_Database');
-
- $di['db'] = $db;
- $controller->setDi($di);
- $result = $controller->getDi();
- $this->assertEquals($di, $result);
- }
-
- public function testRegister(): void
- {
- $boxAppMock = $this->getMockBuilder('\Box_App')->disableOriginalConstructor()->getMock();
- $boxAppMock->expects($this->exactly(1))
- ->method('get');
-
- $controller = new Admin();
- $controller->register($boxAppMock);
- }
-
- public function testGetTheme(): void
- {
- $boxAppMock = $this->getMockBuilder('\Box_App')->disableOriginalConstructor()->getMock();
- $boxAppMock->expects($this->atLeastOnce())
- ->method('render')
- ->with(
- 'mod_theme_preset',
- $this->callback(function (array $data): bool {
- $this->assertInstanceOf(\Twig\Markup::class, $data['settings_html']);
-
- return true;
- })
- )
- ->willReturn('Rendering ...');
-
- $themeMock = $this->getMockBuilder(\Box\Mod\Theme\Model\Theme::class)->disableOriginalConstructor()->getMock();
- $themeMock->expects($this->atLeastOnce())
- ->method('getName');
- $themeMock->expects($this->atLeastOnce())
- ->method('getUploadedAssets');
- $themeMock->expects($this->atLeastOnce())
- ->method('isAssetsPathWritable')
- ->willReturn(false);
-
- $themeServiceMock = $this->createMock(\Box\Mod\Theme\Service::class);
- $themeServiceMock->expects($this->atLeastOnce())
- ->method('getTheme')
- ->willReturn($themeMock);
- $themeServiceMock->expects($this->atLeastOnce())
- ->method('getCurrentThemePreset')
- ->willReturn('default');
- $themeServiceMock->expects($this->atLeastOnce())
- ->method('renderThemeSettingsPageHtml')
- ->willReturn('');
- $themeServiceMock->expects($this->atLeastOnce())
- ->method('getThemeSettings')
- ->willReturn([]);
- $themeServiceMock->expects($this->atLeastOnce())
- ->method('getThemePresets');
-
- $modMock = $this->getMockBuilder('\\' . \FOSSBilling\Module::class)->disableOriginalConstructor()->getMock();
- $modMock->expects($this->atLeastOnce())
- ->method('getService')
- ->willReturn($themeServiceMock);
-
- $di = $this->getDi();
- $di['mod'] = $di->protect(function ($name) use ($modMock) {
- if ($name == 'theme') {
- return $modMock;
- }
- });
-
- $di['is_admin_logged'] = true;
-
- $controller = new Admin();
- $controller->setDi($di);
- $controller->get_theme($boxAppMock, 'huraga');
- }
-}
diff --git a/tests-legacy/modules/Theme/Model/ThemeTest.php b/tests-legacy/modules/Theme/Model/ThemeTest.php
deleted file mode 100644
index 756bf592e..000000000
--- a/tests-legacy/modules/Theme/Model/ThemeTest.php
+++ /dev/null
@@ -1,115 +0,0 @@
-existingTheme);
- $this->assertEquals($this->existingTheme, $themeModel->getName());
- }
-
- public function testNotExistingTheme(): void
- {
- $themeName = 'not existing theme';
- $this->expectException(\FOSSBilling\Exception::class);
- $this->expectExceptionMessage("Theme '{$themeName}' does not exist.");
- new Theme($themeName);
- }
-
- public function testIsAdminAreaTheme(): void
- {
- $theme = new Theme($this->existingTheme);
- $result = $theme->isAdminAreaTheme();
- $this->assertIsBool($result);
- }
-
- public function testIsAssetsPathWritable(): void
- {
- $theme = new Theme($this->existingTheme);
- $result = $theme->isAssetsPathWritable();
- $this->assertIsBool($result);
- }
-
- public function testGetUploadedAssets(): void
- {
- $theme = new Theme($this->existingTheme);
- $result = $theme->getUploadedAssets();
- $this->assertIsArray($result);
- }
-
- public function testGetSettingsPageHtml(): void
- {
- $theme = new Theme($this->existingTheme);
- $result = $theme->getSettingsPageHtml();
- $this->assertIsString($result);
- }
-
- public function testGetPresetsFromSettingsDataFile(): void
- {
- $theme = new Theme($this->existingTheme);
- $result = $theme->getPresetsFromSettingsDataFile();
- $this->assertIsArray($result);
- }
-
- public function testGetCurrentPreset(): void
- {
- $theme = new Theme($this->existingTheme);
- $result = $theme->getCurrentPreset();
- $this->assertIsString($result);
- }
-
- public function testGetPresetFromSettingsDataFile(): void
- {
- $theme = new Theme($this->existingTheme);
- $result = $theme->getPresetFromSettingsDataFile('default');
- $this->assertIsArray($result);
- }
-
- public function testGetUrl(): void
- {
- $theme = new Theme($this->existingTheme);
- $result = $theme->getUrl();
- $this->assertIsString($result);
- }
-
- public function testGetPathConfig(): void
- {
- $theme = new Theme($this->existingTheme);
- $result = $theme->getPathConfig();
- $this->assertIsString($result);
- $this->assertTrue(str_contains($result, 'config'));
- }
-
- public function testGetPathAssets(): void
- {
- $theme = new Theme($this->existingTheme);
- $result = $theme->getPathAssets();
- $this->assertIsString($result);
- $this->assertTrue(str_contains($result, 'assets'));
- }
-
- public function testGetPathHtml(): void
- {
- $theme = new Theme($this->existingTheme);
- $result = $theme->getPathHtml();
- $this->assertIsString($result);
- $this->assertTrue(str_contains($result, 'html'));
- }
-
- public function testGetPathSettingsDataFile(): void
- {
- $theme = new Theme($this->existingTheme);
- $result = $theme->getPathSettingsDataFile();
- $this->assertIsString($result);
- $this->assertTrue(str_contains($result, 'settings_data.json'));
- }
-}
diff --git a/tests-legacy/modules/Theme/ServiceTest.php b/tests-legacy/modules/Theme/ServiceTest.php
deleted file mode 100644
index 38d5a6de5..000000000
--- a/tests-legacy/modules/Theme/ServiceTest.php
+++ /dev/null
@@ -1,573 +0,0 @@
-service = new Service();
- }
-
- public function testGetTheme(): void
- {
- $result = $this->service->getTheme('huraga');
- $this->assertInstanceOf('\\' . Model\Theme::class, $result);
- $this->assertSame('huraga', $result->getName());
- }
-
- public function testGetCurrentThemePreset(): void
- {
- $serviceMock = $this->getMockBuilder(Service::class)
- ->onlyMethods(['setCurrentThemePreset'])
- ->getMock();
- $serviceMock->expects($this->atLeastOnce())
- ->method('setCurrentThemePreset');
-
- $repositoryMock = $this->getMockBuilder(\Box\Mod\Extension\Repository\ExtensionMetaRepository::class)
- ->disableOriginalConstructor()
- ->getMock();
- $repositoryMock->expects($this->atLeastOnce())
- ->method('findOneByExtensionAndScope')
- ->willReturn(null);
-
- $emMock = $this->getMockBuilder(\Doctrine\ORM\EntityManager::class)
- ->disableOriginalConstructor()
- ->getMock();
- $emMock->expects($this->atLeastOnce())
- ->method('getRepository')
- ->willReturn($repositoryMock);
-
- $themeMock = $this->getMockBuilder(Model\Theme::class)->disableOriginalConstructor()->getMock();
- $themeMock->expects($this->atLeastOnce())
- ->method('getCurrentPreset')
- ->willReturn('CurrentPresetString');
-
- $di = $this->getDi();
-
- $di['theme'] = $di->protect(fn (): \PHPUnit\Framework\MockObject\MockObject => $themeMock);
- $di['em'] = $emMock;
-
- $serviceMock->setDi($di);
- $result = $serviceMock->getCurrentThemePreset($themeMock);
- $this->assertIsString($result);
- }
-
- public function testSetCurrentThemePreset(): void
- {
- $repositoryMock = $this->getMockBuilder(\Box\Mod\Extension\Repository\ExtensionMetaRepository::class)
- ->disableOriginalConstructor()
- ->getMock();
- $repositoryMock->expects($this->atLeastOnce())
- ->method('findOneByExtensionAndScope')
- ->willReturn(null);
-
- $emMock = $this->getMockBuilder(\Doctrine\ORM\EntityManager::class)
- ->disableOriginalConstructor()
- ->getMock();
- $emMock->expects($this->atLeastOnce())
- ->method('getRepository')
- ->willReturn($repositoryMock);
- $emMock->expects($this->atLeastOnce())
- ->method('persist');
- $emMock->expects($this->atLeastOnce())
- ->method('flush');
-
- $themeMock = $this->getMockBuilder(Model\Theme::class)->disableOriginalConstructor()->getMock();
- $themeMock->expects($this->atLeastOnce())
- ->method('getName')
- ->willReturn('default');
-
- $di = $this->getDi();
-
- $di['theme'] = $di->protect(fn (): \PHPUnit\Framework\MockObject\MockObject => $themeMock);
- $di['em'] = $emMock;
-
- $this->service->setDi($di);
- $result = $this->service->setCurrentThemePreset($themeMock, 'dark_blue');
- $this->assertIsBool($result);
- $this->assertTrue($result);
- }
-
- public function testDeletePreset(): void
- {
- $repositoryMock = $this->getMockBuilder(\Box\Mod\Extension\Repository\ExtensionMetaRepository::class)
- ->disableOriginalConstructor()
- ->getMock();
- $repositoryMock->expects($this->exactly(2))
- ->method('deleteByExtensionAndScope');
-
- $emMock = $this->getMockBuilder(\Doctrine\ORM\EntityManager::class)
- ->disableOriginalConstructor()
- ->getMock();
- $emMock->expects($this->atLeastOnce())
- ->method('getRepository')
- ->willReturn($repositoryMock);
-
- $themeMock = $this->getMockBuilder(Model\Theme::class)->disableOriginalConstructor()->getMock();
- $themeMock->expects($this->atLeastOnce())
- ->method('getName')
- ->willReturn('default');
-
- $di = $this->getDi();
-
- $di['theme'] = $di->protect(fn (): \PHPUnit\Framework\MockObject\MockObject => $themeMock);
- $di['em'] = $emMock;
-
- $this->service->setDi($di);
- $result = $this->service->deletePreset($themeMock, 'dark_blue');
- $this->assertIsBool($result);
- $this->assertTrue($result);
- }
-
- public function testGetThemePresets(): void
- {
- $serviceMock = $this->getMockBuilder(Service::class)
- ->onlyMethods(['updateSettings'])
- ->getMock();
- $serviceMock->expects($this->atLeastOnce())
- ->method('updateSettings');
-
- $repositoryMock = $this->getMockBuilder(\Box\Mod\Extension\Repository\ExtensionMetaRepository::class)
- ->disableOriginalConstructor()
- ->getMock();
- $repositoryMock->expects($this->atLeastOnce())
- ->method('findByExtensionAndScope')
- ->willReturn([]);
-
- $emMock = $this->getMockBuilder(\Doctrine\ORM\EntityManager::class)
- ->disableOriginalConstructor()
- ->getMock();
- $emMock->expects($this->atLeastOnce())
- ->method('getRepository')
- ->willReturn($repositoryMock);
-
- $themeMock = $this->getMockBuilder(Model\Theme::class)->disableOriginalConstructor()->getMock();
- $themeMock->expects($this->atLeastOnce())
- ->method('getName')
- ->willReturn('default');
-
- $corePresets = [
- 'default' => [],
- 'red_black' => [],
- ];
- $themeMock->expects($this->atLeastOnce())
- ->method('getPresetsFromSettingsDataFile')
- ->willReturn($corePresets);
-
- $di = $this->getDi();
-
- $di['theme'] = $di->protect(fn (): \PHPUnit\Framework\MockObject\MockObject => $themeMock);
- $di['em'] = $emMock;
-
- $serviceMock->setDi($di);
- $result = $serviceMock->getThemePresets($themeMock, 'dark_blue');
- $this->assertIsArray($result);
-
- $expected = [
- 'default' => 'default',
- 'red_black' => 'red_black',
- ];
- $this->assertEquals($expected, $result);
- }
-
- public function testGetThemePresetsThemeDoNotHaveSettingsDataFile(): void
- {
- $repositoryMock = $this->getMockBuilder(\Box\Mod\Extension\Repository\ExtensionMetaRepository::class)
- ->disableOriginalConstructor()
- ->getMock();
- $repositoryMock->expects($this->atLeastOnce())
- ->method('findByExtensionAndScope')
- ->willReturn([]);
-
- $emMock = $this->getMockBuilder(\Doctrine\ORM\EntityManager::class)
- ->disableOriginalConstructor()
- ->getMock();
- $emMock->expects($this->atLeastOnce())
- ->method('getRepository')
- ->willReturn($repositoryMock);
-
- $themeMock = $this->getMockBuilder(Model\Theme::class)->disableOriginalConstructor()->getMock();
- $themeMock->expects($this->atLeastOnce())
- ->method('getName')
- ->willReturn('default');
-
- $themeMock->expects($this->atLeastOnce())
- ->method('getPresetsFromSettingsDataFile')
- ->willReturn([]);
-
- $di = $this->getDi();
-
- $di['theme'] = $di->protect(fn (): \PHPUnit\Framework\MockObject\MockObject => $themeMock);
- $di['em'] = $emMock;
- $this->service->setDi($di);
-
- $result = $this->service->getThemePresets($themeMock);
- $this->assertIsArray($result);
-
- $expected = [
- 'Default' => 'Default',
- ];
- $this->assertEquals($expected, $result);
- }
-
- public function testGetThemeSettings(): void
- {
- $extensionMeta = (new \Box\Mod\Extension\Entity\ExtensionMeta())
- ->setMetaValue('{}');
-
- $repositoryMock = $this->getMockBuilder(\Box\Mod\Extension\Repository\ExtensionMetaRepository::class)
- ->disableOriginalConstructor()
- ->getMock();
- $repositoryMock->expects($this->atLeastOnce())
- ->method('findOneByExtensionAndScope')
- ->willReturn($extensionMeta);
-
- $emMock = $this->getMockBuilder(\Doctrine\ORM\EntityManager::class)
- ->disableOriginalConstructor()
- ->getMock();
- $emMock->expects($this->atLeastOnce())
- ->method('getRepository')
- ->willReturn($repositoryMock);
-
- $themeMock = $this->getMockBuilder(Model\Theme::class)->disableOriginalConstructor()->getMock();
- $themeMock->expects($this->atLeastOnce())
- ->method('getName')
- ->willReturn('default');
-
- $di = $this->getDi();
-
- $di['em'] = $emMock;
-
- $this->service->setDi($di);
- $result = $this->service->getThemeSettings($themeMock, 'default');
- $this->assertIsArray($result);
- }
-
- public function testGetThemeSettingsWithEmptyPresets(): void
- {
- $serviceMock = $this->getMockBuilder(Service::class)
- ->onlyMethods(['getCurrentThemePreset'])
- ->getMock();
- $serviceMock->expects($this->atLeastOnce())
- ->method('getCurrentThemePreset')
- ->willReturn('default');
-
- $repositoryMock = $this->getMockBuilder(\Box\Mod\Extension\Repository\ExtensionMetaRepository::class)
- ->disableOriginalConstructor()
- ->getMock();
- $repositoryMock->expects($this->atLeastOnce())
- ->method('findOneByExtensionAndScope')
- ->willReturn(null);
-
- $emMock = $this->getMockBuilder(\Doctrine\ORM\EntityManager::class)
- ->disableOriginalConstructor()
- ->getMock();
- $emMock->expects($this->atLeastOnce())
- ->method('getRepository')
- ->willReturn($repositoryMock);
-
- $themeMock = $this->getMockBuilder(Model\Theme::class)->disableOriginalConstructor()->getMock();
- $themeMock->expects($this->atLeastOnce())
- ->method('getName')
- ->willReturn('default');
- $themeMock->expects($this->atLeastOnce())
- ->method('getPresetFromSettingsDataFile')
- ->willReturn([]);
-
- $di = $this->getDi();
-
- $di['em'] = $emMock;
- $serviceMock->setDi($di);
-
- $result = $serviceMock->getThemeSettings($themeMock);
- $this->assertIsArray($result);
- $this->assertSame([], $result);
- }
-
- public function testUpdateSettings(): void
- {
- $repositoryMock = $this->getMockBuilder(\Box\Mod\Extension\Repository\ExtensionMetaRepository::class)
- ->disableOriginalConstructor()
- ->getMock();
- $repositoryMock->expects($this->atLeastOnce())
- ->method('findOneByExtensionAndScope')
- ->willReturn(null);
-
- $emMock = $this->getMockBuilder(\Doctrine\ORM\EntityManager::class)
- ->disableOriginalConstructor()
- ->getMock();
- $emMock->expects($this->atLeastOnce())
- ->method('getRepository')
- ->willReturn($repositoryMock);
- $emMock->expects($this->atLeastOnce())
- ->method('persist');
- $emMock->expects($this->atLeastOnce())
- ->method('flush');
-
- $themeMock = $this->getMockBuilder(Model\Theme::class)->disableOriginalConstructor()->getMock();
- $themeMock->expects($this->atLeastOnce())
- ->method('getName')
- ->willReturn('default');
-
- $di = $this->getDi();
-
- $di['em'] = $emMock;
-
- $this->service->setDi($di);
- $params = [];
- $result = $this->service->updateSettings($themeMock, 'default', $params);
- $this->assertIsBool($result);
- $this->assertTrue($result);
- }
-
- public function testRegenerateThemeSettingsDataFile(): void
- {
- $serviceMock = $this->getMockBuilder(Service::class)
- ->onlyMethods(['getThemePresets', 'getThemeSettings', 'getCurrentThemePreset'])
- ->getMock();
-
- $presets = [
- 'default' => 'Defaults',
- 'red_black' => 'Red Black',
- ];
- $serviceMock->expects($this->atLeastOnce())
- ->method('getThemePresets')
- ->willReturn($presets);
-
- $serviceMock->expects($this->atLeastOnce())
- ->method('getThemeSettings')
- ->willReturn([]);
-
- $serviceMock->expects($this->atLeastOnce())
- ->method('getCurrentThemePreset')
- ->willReturn('default');
-
- $themeMock = $this->getMockBuilder(Model\Theme::class)->disableOriginalConstructor()->getMock();
- $tmpDir = sys_get_temp_dir() . '/fb_test_' . uniqid('', true);
- mkdir($tmpDir, 0o755, true);
- $testFile = $tmpDir . '/test_settings.json';
-
- $themeMock->expects($this->atLeastOnce())
- ->method('getPathSettingsDataFile')
- ->willReturn($testFile);
-
- $di = $this->getDi();
-
- $serviceMock->setDi($di);
- $result = $serviceMock->regenerateThemeSettingsDataFile($themeMock);
-
- // Clean up temp file
- if (file_exists($testFile)) {
- unlink($testFile);
- }
- if (is_dir($tmpDir)) {
- rmdir($tmpDir);
- }
-
- $this->assertIsBool($result);
- $this->assertTrue($result);
- }
-
- public function testRegenerateThemeCssAndJsFilesEmptyFiles(): void
- {
- $themeMock = $this->getMockBuilder(Model\Theme::class)->disableOriginalConstructor()->getMock();
-
- $tmpDir = sys_get_temp_dir() . '/' . uniqid('fb_test_assets_', true);
- mkdir($tmpDir, 0o755, true);
-
- $themeMock->expects($this->atLeastOnce())
- ->method('getPathAssets')
- ->willReturn($tmpDir . '/');
-
- $di = $this->getDi();
- $this->service->setDi($di);
-
- $result = $this->service->regenerateThemeCssAndJsFiles($themeMock, 'default', new \Model_Admin());
-
- // Clean up temp directory
- if (is_dir($tmpDir)) {
- rmdir($tmpDir);
- }
-
- $this->assertIsBool($result);
- $this->assertTrue($result);
- }
-
- public function testRenderThemeSettingsPageHtmlSupportsSandboxedTwigRendering(): void
- {
- $themeMock = $this->getMockBuilder(Model\Theme::class)->disableOriginalConstructor()->getMock();
- $themeMock->expects($this->once())
- ->method('getSettingsPageHtml')
- ->willReturn("{{ 'Hello'|trans }}");
-
- $di = $this->getDi();
- $di['twig_factory'] = $this->createTwigFactory($di);
- $di['logger'] = $this->createMock(\Box_Log::class);
-
- $this->service->setDi($di);
-
- $result = $this->service->renderThemeSettingsPageHtml($themeMock, []);
- $this->assertSame('Hello', $result);
- }
-
- public function testRenderThemeSettingsPageHtmlDoesNotExposePrivilegedGlobals(): void
- {
- $themeMock = $this->getMockBuilder(Model\Theme::class)->disableOriginalConstructor()->getMock();
- $themeMock->expects($this->once())
- ->method('getSettingsPageHtml')
- ->willReturn('{{ admin is defined ? "yes" : "no" }}|{{ guest is defined ? "yes" : "no" }}|{{ CSRFToken is defined ? "yes" : "no" }}|{{ request is defined ? "yes" : "no" }}');
-
- $di = $this->getDi();
- $di['twig_factory'] = $this->createTwigFactory($di);
- $di['logger'] = $this->createMock(\Box_Log::class);
-
- $this->service->setDi($di);
-
- $result = $this->service->renderThemeSettingsPageHtml($themeMock, []);
- $this->assertSame('no|no|no|no', $result);
- }
-
- public function testRenderThemeSettingsPageHtmlBlocksDisallowedFunctions(): void
- {
- $themeMock = $this->getMockBuilder(Model\Theme::class)->disableOriginalConstructor()->getMock();
- $themeMock->expects($this->once())
- ->method('getSettingsPageHtml')
- ->willReturn('{{ max(1, 2) }}');
- $themeMock->expects($this->once())
- ->method('getName')
- ->willReturn('huraga');
-
- $logger = new class {
- public function setChannel(string $channel): self
- {
- return $this;
- }
-
- public function warning(string $message, array $context = []): void
- {
- }
- };
-
- $di = $this->getDi();
- $di['twig_factory'] = $this->createTwigFactory($di);
- $di['logger'] = $logger;
-
- $this->service->setDi($di);
-
- $this->expectException(\FOSSBilling\InformationException::class);
- $this->expectExceptionMessage('Theme settings template contains disallowed Twig syntax');
- $this->service->renderThemeSettingsPageHtml($themeMock, []);
- }
-
- public function testRenderThemeSettingsPageHtmlSanitizesRenderedHtml(): void
- {
- $themeMock = $this->getMockBuilder(Model\Theme::class)->disableOriginalConstructor()->getMock();
- $themeMock->expects($this->once())
- ->method('getSettingsPageHtml')
- ->willReturn('Pay');
-
- $di = $this->getDi();
- $di['twig_factory'] = $this->createTwigFactory($di);
- $di['logger'] = $this->createMock(\Box_Log::class);
-
- $this->service->setDi($di);
-
- $result = $this->service->renderThemeSettingsPageHtml($themeMock, []);
- $this->assertSame('Pay', $result);
- }
-
- public function testThemeSettingsSanitizerPreservesSafeHtml(): void
- {
- $html = '';
- $result = BrowserHtmlSanitizer::sanitizeThemeSettingsHtml($html);
-
- $this->assertSame($html, $result);
- }
-
- public function testThemeSettingsSanitizerPreservesFormControls(): void
- {
- $html = '';
- $result = BrowserHtmlSanitizer::sanitizeThemeSettingsHtml($html);
-
- $this->assertStringContainsString('input type="checkbox"', $result);
- $this->assertStringContainsString('name="enabled"', $result);
- $this->assertStringContainsString('class="toggle"', $result);
- $this->assertStringContainsString('select name="theme" class="page"', $result);
- $this->assertStringContainsString('option value="light" selected', $result);
- $this->assertStringContainsString('textarea name="notes"', $result);
- }
-
- public function testGetCurrentAdminAreaTheme(): void
- {
- $dbMock = $this->createMock('\Box_Database');
- $dbMock->expects($this->atLeastOnce())
- ->method('getCell')
- ->willReturn('');
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
-
- $this->service->setDi($di);
-
- $result = $this->service->getCurrentAdminAreaTheme();
- $this->assertIsArray($result);
- }
-
- public function testGetCurrentClientAreaTheme(): void
- {
- $themeMock = $this->getMockBuilder(Model\Theme::class)->disableOriginalConstructor()->getMock();
-
- $serviceMock = $this->getMockBuilder(Service::class)
- ->onlyMethods(['getCurrentClientAreaThemeCode', 'getTheme'])
- ->getMock();
-
- $serviceMock->expects($this->atLeastOnce())
- ->method('getCurrentClientAreaThemeCode');
-
- $serviceMock->expects($this->atLeastOnce())
- ->method('getTheme')
- ->willReturn($themeMock);
-
- $result = $serviceMock->getCurrentClientAreaTheme();
- $this->assertInstanceOf('\\' . Model\Theme::class, $result);
- }
-
- public function testGetCurrentClientAreaThemeCode(): void
- {
- $dbMock = $this->createMock('\Box_Database');
- $dbMock->expects($this->atLeastOnce())
- ->method('getCell')
- ->willReturn('');
-
- $di = $this->getDi();
- $di['db'] = $dbMock;
- $this->service->setDi($di);
-
- $result = $this->service->getCurrentClientAreaThemeCode();
- $this->assertIsString($result);
- $this->assertEquals('huraga', $result);
- }
-
- private function createTwigFactory(\Pimple\Container $di): \FOSSBilling\Twig\TwigFactory
- {
- $reflection = new \ReflectionClass(\FOSSBilling\Twig\TwigFactory::class);
- $twigFactory = $reflection->newInstanceWithoutConstructor();
-
- $diProperty = $reflection->getProperty('di');
- $diProperty->setValue($twigFactory, $di);
-
- $baseConfigProperty = $reflection->getProperty('baseConfig');
- $baseConfigProperty->setValue($twigFactory, ['cache' => false]);
-
- return $twigFactory;
- }
-}
diff --git a/tests/APIHelper.php b/tests/APIHelper.php
deleted file mode 100644
index 0dcb6f227..000000000
--- a/tests/APIHelper.php
+++ /dev/null
@@ -1,136 +0,0 @@
-remove(Path::join(sys_get_temp_dir(), 'cookie.txt'));
- }
-}
-
-class Response
-{
- private array $decodedResponse;
-
- public function __construct(private readonly int $code, private readonly string $rawResponse)
- {
- $decoded = json_decode($this->rawResponse, true);
- if (json_last_error() !== JSON_ERROR_NONE || !is_array($decoded)) {
- $preview = strlen($this->rawResponse) > 500 ? substr($this->rawResponse, 0, 500) . '...' : $this->rawResponse;
-
- throw new \RuntimeException('Invalid JSON response: ' . json_last_error_msg() . ' (HTTP ' . $this->code . '). Response: ' . $preview);
- }
- $this->decodedResponse = $decoded;
- }
-
- public function getHttpCode(): int
- {
- return $this->code;
- }
-
- public function getStatusCode(): int
- {
- return $this->code;
- }
-
- public function getResponse(): array
- {
- return $this->decodedResponse;
- }
-
- public function getRawResponse(): string
- {
- return $this->rawResponse;
- }
-
- public function wasSuccessful(): bool
- {
- return !empty($this->decodedResponse)
- && array_key_exists('error', $this->decodedResponse)
- && empty($this->decodedResponse['error']);
- }
-
- public function getErrorMessage(): string
- {
- return $this->decodedResponse['error']['message'] ?? 'None';
- }
-
- public function getErrorCode(): int
- {
- return intval($this->decodedResponse['error']['code'] ?? 0);
- }
-
- public function getError(): string
- {
- return $this->getErrorMessage() . ' (Code ' . $this->getErrorCode() . ')';
- }
-
- public function generatePHPUnitMessage(): string
- {
- return 'The API request failed with the following message: ' . $this->getError();
- }
-
- public function getResult(): mixed
- {
- return $this->decodedResponse['result'] ?? '';
- }
-}
diff --git a/tests/Bootstrap.php b/tests/Bootstrap.php
deleted file mode 100644
index 695891e05..000000000
--- a/tests/Bootstrap.php
+++ /dev/null
@@ -1,3 +0,0 @@
-
+ */
+function countryCodes(): array
+{
+ return [
+ 'US', // United States
+ 'GB', // United Kingdom
+ 'CA', // Canada
+ 'AU', // Australia
+ 'DE', // Germany
+ 'FR', // France
+ 'ES', // Spain
+ 'IT', // Italy
+ 'NL', // Netherlands
+ 'JP', // Japan
+ 'CN', // China
+ 'IN', // India
+ 'BR', // Brazil
+ 'MX', // Mexico
+ 'RU', // Russia
+ 'ZA', // South Africa
+ ];
+}
+
+/**
+ * Common currency codes (ISO 4217).
+ *
+ * @return array
+ */
+function currencyCodes(): array
+{
+ return [
+ 'USD', // US Dollar
+ 'EUR', // Euro
+ 'GBP', // British Pound
+ 'JPY', // Japanese Yen
+ 'CAD', // Canadian Dollar
+ 'AUD', // Australian Dollar
+ 'CHF', // Swiss Franc
+ 'CNY', // Chinese Yuan
+ 'INR', // Indian Rupee
+ 'BRL', // Brazilian Real
+ 'MXN', // Mexican Peso
+ 'RUB', // Russian Ruble
+ 'ZAR', // South African Rand
+ ];
+}
+
+/**
+ * Currency data with code and rate pairs.
+ *
+ * @return array
+ */
+function currencyRates(): array
+{
+ return [
+ ['USD', 1.0],
+ ['EUR', 0.85],
+ ['GBP', 0.73],
+ ['JPY', 110.0],
+ ['CAD', 1.25],
+ ['AUD', 1.35],
+ ['CHF', 0.92],
+ ];
+}
diff --git a/tests/Datasets/PeriodCodes.php b/tests/Datasets/PeriodCodes.php
new file mode 100644
index 000000000..47c802582
--- /dev/null
+++ b/tests/Datasets/PeriodCodes.php
@@ -0,0 +1,31 @@
+
+ */
+function periodCodes(): array
+{
+ return [
+ ['1D', 'D', 1, 1.0],
+ ['7D', 'D', 7, 7.0],
+ ['2W', 'W', 2, 15.0], // (2/4) * 30 = 15 days
+ ['1M', 'M', 1, 30.0],
+ ['3M', 'M', 3, 90.0],
+ ['1Y', 'Y', 1, 360.0], // 12 * 30 = 360 days
+ ['2Y', 'Y', 2, 720.0], // 24 * 30 = 720 days
+ ];
+}
diff --git a/tests/Datasets/ValidationData.php b/tests/Datasets/ValidationData.php
new file mode 100644
index 000000000..cba2fc51a
--- /dev/null
+++ b/tests/Datasets/ValidationData.php
@@ -0,0 +1,69 @@
+
+ */
+function emailProvider(): array
+{
+ return [
+ // Valid emails
+ ['test@example.com', true],
+ ['test.user@example.com', true],
+ ['test+tag@example.com', true],
+ ['test@subdomain.example.com', true],
+ ['test@example.co.uk', true],
+ ['user@domain.org', true],
+ ['user123@domain.com', true],
+ ['first.last@domain.io', true],
+ // Invalid emails
+ ['invalid', false],
+ ['test@', false],
+ ['@example.com', false],
+ ['test example.com', false],
+ ['test@@example.com', false],
+ ['test@.com', false],
+ ['', false],
+ ];
+}
+
+/**
+ * Second-level domain validation test data.
+ *
+ * @return array
+ */
+function domainProvider(): array
+{
+ return [
+ // Valid SLDs
+ ['google', true],
+ ['example-domain', true],
+ ['a1', true],
+ ['123', true],
+ ['xn--bcher-kva', true], // Internationalized domain
+ ['subdomain', true],
+ ['my-domain', true],
+ // Invalid SLDs
+ ['qqq45%%%', false],
+ ['()1google', false],
+ ['//asdasd()()', false],
+ ['--asdasd()()', false],
+ ['', false],
+ ['sub.domain.example', false], // SLD cannot contain dots
+ ['-invalid', false],
+ ['invalid-', false],
+ ];
+}
diff --git a/tests/e2e/cypress/e2e/admin/admin-auth-api.cy.js b/tests/E2E/Cypress/specs/admin/admin-auth-api.cy.js
similarity index 100%
rename from tests/e2e/cypress/e2e/admin/admin-auth-api.cy.js
rename to tests/E2E/Cypress/specs/admin/admin-auth-api.cy.js
diff --git a/tests/e2e/cypress/e2e/admin/admin-login.cy.js b/tests/E2E/Cypress/specs/admin/admin-login.cy.js
similarity index 100%
rename from tests/e2e/cypress/e2e/admin/admin-login.cy.js
rename to tests/E2E/Cypress/specs/admin/admin-login.cy.js
diff --git a/tests/e2e/cypress/e2e/admin/admin-smoke.cy.js b/tests/E2E/Cypress/specs/admin/admin-smoke.cy.js
similarity index 100%
rename from tests/e2e/cypress/e2e/admin/admin-smoke.cy.js
rename to tests/E2E/Cypress/specs/admin/admin-smoke.cy.js
diff --git a/tests/e2e/cypress/e2e/client/client-auth-protection.cy.js b/tests/E2E/Cypress/specs/client/client-auth-protection.cy.js
similarity index 100%
rename from tests/e2e/cypress/e2e/client/client-auth-protection.cy.js
rename to tests/E2E/Cypress/specs/client/client-auth-protection.cy.js
diff --git a/tests/e2e/cypress/e2e/client/client-auth.cy.js b/tests/E2E/Cypress/specs/client/client-auth.cy.js
similarity index 100%
rename from tests/e2e/cypress/e2e/client/client-auth.cy.js
rename to tests/E2E/Cypress/specs/client/client-auth.cy.js
diff --git a/tests/e2e/cypress/e2e/client/client-profile.cy.js b/tests/E2E/Cypress/specs/client/client-profile.cy.js
similarity index 100%
rename from tests/e2e/cypress/e2e/client/client-profile.cy.js
rename to tests/E2E/Cypress/specs/client/client-profile.cy.js
diff --git a/tests/e2e/cypress/e2e/client/client-smoke.cy.js b/tests/E2E/Cypress/specs/client/client-smoke.cy.js
similarity index 100%
rename from tests/e2e/cypress/e2e/client/client-smoke.cy.js
rename to tests/E2E/Cypress/specs/client/client-smoke.cy.js
diff --git a/tests/e2e/cypress/e2e/client/client-support.cy.js b/tests/E2E/Cypress/specs/client/client-support.cy.js
similarity index 100%
rename from tests/e2e/cypress/e2e/client/client-support.cy.js
rename to tests/E2E/Cypress/specs/client/client-support.cy.js
diff --git a/tests/e2e/cypress/e2e/guest/public-pages.cy.js b/tests/E2E/Cypress/specs/guest/public-pages.cy.js
similarity index 100%
rename from tests/e2e/cypress/e2e/guest/public-pages.cy.js
rename to tests/E2E/Cypress/specs/guest/public-pages.cy.js
diff --git a/tests/e2e/cypress/support/e2e.js b/tests/E2E/Cypress/support/e2e.js
similarity index 100%
rename from tests/e2e/cypress/support/e2e.js
rename to tests/E2E/Cypress/support/e2e.js
diff --git a/tests/E2E/HealthChecks/ApiTest.php b/tests/E2E/HealthChecks/ApiTest.php
new file mode 100644
index 000000000..c1d3dbb72
--- /dev/null
+++ b/tests/E2E/HealthChecks/ApiTest.php
@@ -0,0 +1,57 @@
+ 200,
+ 'order' => 200,
+ 'news' => 200,
+ 'privacy-policy' => 200,
+ 'sitemap.xml' => 200,
+ 'contact-us' => 200,
+ 'login' => 200,
+ 'signup' => 200,
+ 'password-reset' => 200,
+];
+
+test('urls return ok status', function () use ($testUrls): void {
+ $baseUrl = getenv('APP_URL') ?: 'http://localhost';
+ $baseUrl = rtrim($baseUrl, '/');
+
+ foreach ($testUrls as $url => $expectedCode) {
+ $ch = curl_init($baseUrl . '/' . $url);
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+ curl_exec($ch);
+ $responseCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
+ curl_close($ch);
+
+ expect($responseCode)->toEqual($expectedCode, "URL '{$url}' should return {$expectedCode}");
+ }
+});
+
+test('api is functional', function (): void {
+ $result = Tests\Helpers\ApiClient::request('guest/system/company');
+ assertApiSuccess($result);
+ expect($result->getResult())->toBeArray();
+});
+
+test('system is up to date', function (): void {
+ $result = Tests\Helpers\ApiClient::request('admin/system/is_behind_on_patches');
+ assertApiSuccess($result);
+ expect($result->getResult())->toBeFalse();
+});
diff --git a/tests/HealthChecks/HealthTest.php b/tests/HealthChecks/HealthTest.php
deleted file mode 100644
index 77824bc0c..000000000
--- a/tests/HealthChecks/HealthTest.php
+++ /dev/null
@@ -1,49 +0,0 @@
- 200,
- 'order' => 200,
- 'news' => 200,
- 'privacy-policy' => 200,
- 'sitemap.xml' => 200,
- 'contact-us' => 200,
- 'login' => 200,
- 'signup' => 200,
- 'password-reset' => 200,
- ];
-
- public function testUrls(): void
- {
- $baseUrl = getenv('APP_URL');
- foreach ($this->test_urls as $url => $code) {
- $ch = curl_init($baseUrl . $url);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_exec($ch);
- $responseCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
- curl_close($ch);
-
- $this->assertEquals($code, $responseCode, "Failed asserting that the URL '{$url}' returned a {$code} response code.");
- }
- }
-
- public function testIsFOSSBillingWorking(): void
- {
- $result = Request::makeRequest('guest/system/company');
- $this->assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
- $this->assertIsArray($result->getResult());
- }
-
- public function testStartingPatchNotBehind(): void
- {
- $result = Request::makeRequest('admin/system/is_behind_on_patches');
- $this->assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
- $this->assertFalse($result->getResult()); // This should return false to indicate there are no patches available, meaning the `last_patch` number is correct for fresh installs.
- }
-}
diff --git a/tests/Helpers/Api.php b/tests/Helpers/Api.php
new file mode 100644
index 000000000..33b54dc59
--- /dev/null
+++ b/tests/Helpers/Api.php
@@ -0,0 +1,234 @@
+ $url,
+ CURLOPT_RETURNTRANSFER => true,
+ CURLOPT_TIMEOUT => 30,
+ CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
+ CURLOPT_COOKIEJAR => self::getCookiePath(),
+ CURLOPT_COOKIEFILE => self::getCookiePath(),
+ CURLOPT_USERPWD => "$role:$apiKey",
+ ]);
+
+ if (strcasecmp($method, 'POST') === 0) {
+ curl_setopt($ch, CURLOPT_POST, true);
+ curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($payload));
+ }
+
+ $output = curl_exec($ch);
+ if ($output === false) {
+ $error = curl_error($ch);
+ $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
+ curl_close($ch);
+
+ throw new \RuntimeException('cURL request failed: ' . $error . ' (HTTP ' . $httpCode . ')');
+ }
+
+ $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
+ curl_close($ch);
+
+ return new ApiResponse($httpCode, $output);
+ }
+
+ public static function resetCookies(): void
+ {
+ $filesystem = new Filesystem();
+ $filesystem->remove(self::getCookiePath());
+ }
+
+ public static function get(string $endpoint, array $payload = [], ?string $role = null): ApiResponse
+ {
+ return self::request($endpoint, $payload, $role ?? 'admin', null, 'GET');
+ }
+
+ public static function post(string $endpoint, array $payload = [], ?string $role = null): ApiResponse
+ {
+ return self::request($endpoint, $payload, $role ?? 'admin', null, 'POST');
+ }
+}
+
+/**
+ * API Response wrapper for E2E tests.
+ */
+class ApiResponse
+{
+ private array $decodedResponse = [];
+
+ public function __construct(
+ private readonly int $code,
+ private readonly string $rawResponse,
+ ) {
+ $decoded = json_decode($this->rawResponse, true);
+ if (json_last_error() !== JSON_ERROR_NONE || !is_array($decoded)) {
+ $preview = strlen($this->rawResponse) > 500 ? substr($this->rawResponse, 0, 500) . '...' : $this->rawResponse;
+
+ throw new \RuntimeException('Invalid JSON response: ' . json_last_error_msg() . ' (HTTP ' . $this->code . '). Response: ' . $preview);
+ }
+ $this->decodedResponse = $decoded;
+ }
+
+ public function getHttpCode(): int
+ {
+ return $this->code;
+ }
+
+ public function getStatusCode(): int
+ {
+ return $this->code;
+ }
+
+ public function getResponse(): array
+ {
+ return $this->decodedResponse;
+ }
+
+ public function getRawResponse(): string
+ {
+ return $this->rawResponse;
+ }
+
+ public function wasSuccessful(): bool
+ {
+ return !empty($this->decodedResponse)
+ && array_key_exists('error', $this->decodedResponse)
+ && empty($this->decodedResponse['error']);
+ }
+
+ public function getErrorMessage(): string
+ {
+ return $this->decodedResponse['error']['message'] ?? 'None';
+ }
+
+ public function getErrorCode(): int
+ {
+ return (int) ($this->decodedResponse['error']['code'] ?? 0);
+ }
+
+ public function getError(): string
+ {
+ return $this->getErrorMessage() . ' (Code ' . $this->getErrorCode() . ')';
+ }
+
+ public function getResult(): mixed
+ {
+ return $this->decodedResponse['result'] ?? null;
+ }
+
+ public function hasResult(): bool
+ {
+ return array_key_exists('result', $this->decodedResponse);
+ }
+
+ public function isArrayResult(): bool
+ {
+ return is_array($this->decodedResponse['result'] ?? null);
+ }
+
+ public function isIntResult(): bool
+ {
+ return is_int($this->decodedResponse['result'] ?? null);
+ }
+
+ public function isBoolResult(): bool
+ {
+ return is_bool($this->decodedResponse['result'] ?? null);
+ }
+
+ public function isStringResult(): bool
+ {
+ return is_string($this->decodedResponse['result'] ?? null);
+ }
+}
+
+/**
+ * Helper function for API requests.
+ */
+function api(string $endpoint, array $payload = [], ?string $role = null): ApiResponse
+{
+ return ApiClient::request($endpoint, $payload, $role);
+}
+
+/**
+ * Assert that an API response was successful.
+ */
+function assertApiSuccess(ApiResponse $response): void
+{
+ expect($response->wasSuccessful())
+ ->toBeTrue($response->getError());
+}
+
+/**
+ * Assert that an API response has an integer result.
+ */
+function assertApiResultIsInt(ApiResponse $response): void
+{
+ expect($response->isIntResult())
+ ->toBeTrue('Expected integer result, got: ' . gettype($response->getResult()));
+}
+
+/**
+ * Assert that an API response has an array result.
+ */
+function assertApiResultIsArray(ApiResponse $response): void
+{
+ expect($response->isArrayResult())
+ ->toBeTrue('Expected array result, got: ' . gettype($response->getResult()));
+}
diff --git a/tests/Helpers/Container.php b/tests/Helpers/Container.php
new file mode 100644
index 000000000..a8dafb3f4
--- /dev/null
+++ b/tests/Helpers/Container.php
@@ -0,0 +1,270 @@
+ 'test_salt_' . uniqid(),
+ 'url' => 'http://localhost/',
+ ];
+ $di['validator'] = fn (): \FOSSBilling\Validate => new \FOSSBilling\Validate();
+ $di['tools'] = fn (): \FOSSBilling\Tools => new \FOSSBilling\Tools();
+ $di['logger'] = fn (): \Psr\Log\LoggerInterface => new class extends AbstractLogger {
+ public array $calls = [];
+
+ public function log($level, string|\Stringable $message, array $context = []): void
+ {
+ $this->calls[] = ['method' => $level, 'params' => [$message, $context]];
+ }
+
+ public function setChannel(string $channel): self
+ {
+ $this->calls[] = ['method' => 'setChannel', 'params' => [$channel]];
+
+ return $this;
+ }
+ };
+ $di['request'] = fn (): Request => Request::create('http://localhost/');
+ $di['session'] = static function (): object {
+ $session = \Mockery::mock(\FOSSBilling\Session::class)->shouldIgnoreMissing();
+ $session->shouldReceive('regenerateId')->byDefault()->andReturnNull();
+ $session->shouldReceive('set')->byDefault()->andReturnNull();
+ $session->shouldReceive('get')->byDefault()->andReturnNull();
+ $session->shouldReceive('delete')->byDefault()->andReturnNull();
+
+ return $session;
+ };
+ $di['db'] = static function (): object {
+ $db = \Mockery::mock(\Box_Database::class)->shouldIgnoreMissing();
+ $db->shouldReceive('find')->byDefault()->andReturn([]);
+ $db->shouldReceive('getAll')->byDefault()->andReturn([]);
+ $db->shouldReceive('getAssoc')->byDefault()->andReturn([]);
+ $db->shouldReceive('toArray')->byDefault()->andReturn([]);
+ $db->shouldReceive('exec')->byDefault()->andReturn(1);
+ $db->shouldReceive('transaction')->byDefault()->andReturnUsing(static fn (callable $callback): mixed => $callback());
+
+ return $db;
+ };
+ $di['dbal'] = static function (): object {
+ $dbal = \Mockery::mock(\Doctrine\DBAL\Connection::class)->shouldIgnoreMissing();
+ $result = \Mockery::mock(\Doctrine\DBAL\Result::class)->shouldIgnoreMissing();
+ $result->shouldReceive('fetchAssociative')->byDefault()->andReturn(false);
+ $result->shouldReceive('fetchAllAssociative')->byDefault()->andReturn([]);
+ $result->shouldReceive('fetchOne')->byDefault()->andReturn(false);
+
+ $queryBuilder = \Mockery::mock(\Doctrine\DBAL\Query\QueryBuilder::class)->shouldIgnoreMissing();
+ foreach ([
+ 'select',
+ 'addSelect',
+ 'from',
+ 'leftJoin',
+ 'innerJoin',
+ 'where',
+ 'andWhere',
+ 'orWhere',
+ 'orderBy',
+ 'addOrderBy',
+ 'setFirstResult',
+ 'setMaxResults',
+ 'setParameter',
+ 'setParameters',
+ 'insert',
+ 'update',
+ 'delete',
+ 'values',
+ 'setValue',
+ 'set',
+ ] as $method) {
+ $queryBuilder->shouldReceive($method)->byDefault()->andReturn($queryBuilder);
+ }
+ $queryBuilder->shouldReceive('executeQuery')->byDefault()->andReturn($result);
+ $queryBuilder->shouldReceive('executeStatement')->byDefault()->andReturn(1);
+ $queryBuilder->shouldReceive('fetchAssociative')->byDefault()->andReturn(false);
+ $queryBuilder->shouldReceive('fetchAllAssociative')->byDefault()->andReturn([]);
+ $queryBuilder->shouldReceive('fetchOne')->byDefault()->andReturn(false);
+
+ $dbal->shouldReceive('fetchAssociative')->byDefault()->andReturn([]);
+ $dbal->shouldReceive('fetchAllAssociative')->byDefault()->andReturn([]);
+ $dbal->shouldReceive('fetchOne')->byDefault()->andReturn(null);
+ $dbal->shouldReceive('executeQuery')->byDefault()->andReturn($result);
+ $dbal->shouldReceive('executeStatement')->byDefault()->andReturn(1);
+ $dbal->shouldReceive('insert')->byDefault()->andReturn(1);
+ $dbal->shouldReceive('update')->byDefault()->andReturn(1);
+ $dbal->shouldReceive('lastInsertId')->byDefault()->andReturn(1);
+ $dbal->shouldReceive('createQueryBuilder')->byDefault()->andReturn($queryBuilder);
+
+ return $dbal;
+ };
+ $di['events_manager'] = fn (): object => new class {
+ public array $events = [];
+
+ public function fire(array|string $event): void
+ {
+ $this->events[] = $event;
+ }
+ };
+ $di['auth'] = fn (): object => \Mockery::mock()->shouldIgnoreMissing();
+ $di['pager'] = fn (): object => new class {
+ public function getDefaultPerPage(): int
+ {
+ return 20;
+ }
+
+ public function getAdvancedSearch(array $data, array $fields = [], string $table = ''): array
+ {
+ return ['', []];
+ }
+
+ public function getSimpleResultSet(string $query, array $params = [], int $perPage = 20): array
+ {
+ return ['list' => [], 'total' => 0, 'pages' => 0, 'page' => 1, 'per_page' => $perPage];
+ }
+
+ public function getPaginatedResultSet(string $query, array $params = [], mixed $pagination = null): array
+ {
+ return ['list' => [], 'total' => 0, 'pages' => 0, 'page' => 1, 'per_page' => 20];
+ }
+ };
+ $di['rate_limiter'] = fn (): object => new class {
+ public function consume(string $policyName, string $subject, int $tokens = 1): \FOSSBilling\Security\RateLimitResult
+ {
+ return new \FOSSBilling\Security\RateLimitResult($policyName, false, null, null);
+ }
+
+ public function consumeOrThrow(string $policyName, string $subject, int $tokens = 1): \FOSSBilling\Security\RateLimitResult
+ {
+ return $this->consume($policyName, $subject, $tokens);
+ }
+ };
+ $di['mod_config'] = $di->protect(fn (string $name): array => []);
+ $di['em'] = static function (): object {
+ $extensionMetaRepository = \Mockery::mock(\Box\Mod\Extension\Repository\ExtensionMetaRepository::class)->shouldIgnoreMissing();
+ $extensionMetaRepository->shouldReceive('findOneByExtensionAndScope')->byDefault()->andReturn(null);
+ $extensionMetaRepository->shouldReceive('findByExtensionAndScope')->byDefault()->andReturn([]);
+ $extensionMetaRepository->shouldReceive('deleteByExtensionAndScope')->byDefault()->andReturn(0);
+
+ $emailTemplateRepository = \Mockery::mock(\Box\Mod\Email\Repository\EmailTemplateRepository::class)->shouldIgnoreMissing();
+ $templateQueryBuilder = \Mockery::mock(\Doctrine\ORM\QueryBuilder::class)->shouldIgnoreMissing();
+ $emailTemplateRepository->shouldReceive('find')->byDefault()->andReturn(null);
+ $emailTemplateRepository->shouldReceive('findOneByActionCode')->byDefault()->andReturn(null);
+ $emailTemplateRepository->shouldReceive('getSearchQueryBuilder')->byDefault()->andReturn($templateQueryBuilder);
+
+ $em = \Mockery::mock(\Doctrine\ORM\EntityManagerInterface::class)->shouldIgnoreMissing();
+ $em->shouldReceive('getRepository')->byDefault()->andReturnUsing(static function (string $class) use ($extensionMetaRepository, $emailTemplateRepository): object {
+ return match ($class) {
+ \Box\Mod\Email\Entity\EmailTemplate::class => $emailTemplateRepository,
+ default => $extensionMetaRepository,
+ };
+ });
+
+ return $em;
+ };
+
+ $staffService = \Mockery::mock(\Box\Mod\Staff\Service::class)->shouldIgnoreMissing();
+ $staffService->shouldReceive('hasPermission')->byDefault()->andReturn(true);
+ $staffService->shouldReceive('checkPermissionsAndThrowException')->byDefault()->andReturn(true);
+ $di['mod_service'] = $di->protect(static function (string $name = '', string $sub = '') use ($staffService): object {
+ if (strtolower($name) === 'staff') {
+ return $staffService;
+ }
+
+ return \Mockery::mock()->shouldIgnoreMissing();
+ });
+
+ return $di;
+}
+
+/**
+ * Create a module service resolver with staff permissions enabled by default.
+ *
+ * @param array $services
+ */
+function moduleService(array $services = []): \Closure
+{
+ $staffService = $services['staff'] ?? \Mockery::mock(\Box\Mod\Staff\Service::class)->shouldIgnoreMissing();
+ $staffService->shouldReceive('hasPermission')->byDefault()->andReturn(true);
+ $staffService->shouldReceive('checkPermissionsAndThrowException')->byDefault()->andReturn(true);
+
+ return static function (string $name = '', string $sub = '') use ($services, $staffService): object {
+ if (strtolower($name) === 'staff') {
+ return $staffService;
+ }
+
+ $module = strtolower($name);
+ $moduleWithSub = $sub === '' ? $module : $module . ':' . strtolower($sub);
+
+ return $services[$moduleWithSub] ?? $services[$module] ?? \Mockery::mock()->shouldIgnoreMissing();
+ };
+}
+
+/**
+ * Access a private property on an object using reflection.
+ *
+ * @return mixed The property value when getting, null when setting
+ */
+function accessPrivate(object $instance, string $property, mixed $value = null): mixed
+{
+ $refl = new \ReflectionClass($instance);
+ $prop = null;
+
+ if ($refl->hasProperty($property)) {
+ $prop = $refl->getProperty($property);
+ } else {
+ $parentClass = $refl->getParentClass();
+ if ($parentClass && $parentClass->hasProperty($property)) {
+ $prop = $parentClass->getProperty($property);
+ }
+ }
+
+ if ($prop === null || $prop->isStatic()) {
+ return null;
+ }
+
+ // If value is provided, set the property
+ if (func_num_args() > 2) {
+ $prop->setValue($instance, $value);
+
+ return null;
+ }
+
+ // Otherwise, get the property value
+ return $prop->getValue($instance);
+}
+
+/**
+ * Inject a mock filesystem into a service that has a private filesystem property.
+ */
+function injectMockFilesystem(object $service, \Mockery\MockInterface $filesystemMock): void
+{
+ $refl = new \ReflectionClass($service);
+ while (!$refl->hasProperty('filesystem')) {
+ $parent = $refl->getParentClass();
+ if ($parent === false) {
+ throw new \ReflectionException(sprintf('Property %s::$filesystem does not exist', $service::class));
+ }
+
+ $refl = $parent;
+ }
+
+ $prop = $refl->getProperty('filesystem');
+ $prop->setValue($service, $filesystemMock);
+}
diff --git a/tests/Helpers/DummyBean.php b/tests/Helpers/DummyBean.php
new file mode 100644
index 000000000..ca697b297
--- /dev/null
+++ b/tests/Helpers/DummyBean.php
@@ -0,0 +1,24 @@
+__info['changelist'] = [];
+ }
+}
diff --git a/tests/Helpers/Factories.php b/tests/Helpers/Factories.php
new file mode 100644
index 000000000..2fb989e0a
--- /dev/null
+++ b/tests/Helpers/Factories.php
@@ -0,0 +1,100 @@
+loadBean(new DummyBean());
+ }
+
+ foreach ($attributes as $key => $value) {
+ $instance->$key = $value;
+ }
+
+ return $instance;
+}
+
+/**
+ * Create a client order model.
+ */
+function order(array $attributes = []): object
+{
+ $defaults = [
+ 'id' => random_int(1, 10000),
+ 'client_id' => random_int(1, 10000),
+ 'product_id' => random_int(1, 10000),
+ 'status' => \Model_ClientOrder::STATUS_ACTIVE,
+ 'created_at' => date('Y-m-d H:i:s'),
+ 'updated_at' => date('Y-m-d H:i:s'),
+ ];
+
+ return model(\Model_ClientOrder::class, array_merge($defaults, $attributes));
+}
+
+/**
+ * Create a product model.
+ */
+function product(array $attributes = []): object
+{
+ $defaults = [
+ 'id' => random_int(1, 10000),
+ 'title' => 'Test Product',
+ 'type' => \Model_ProductTable::CUSTOM,
+ 'status' => \Model_Product::STATUS_ENABLED,
+ 'created_at' => date('Y-m-d H:i:s'),
+ 'updated_at' => date('Y-m-d H:i:s'),
+ ];
+
+ return model(\Model_Product::class, array_merge($defaults, $attributes));
+}
+
+/**
+ * Create a client model.
+ */
+function client(array $attributes = []): object
+{
+ $defaults = [
+ 'id' => random_int(1, 10000),
+ 'email' => 'test' . uniqid() . '@example.com',
+ 'first_name' => 'Test',
+ 'last_name' => 'User',
+ 'status' => \Model_Client::ACTIVE,
+ 'created_at' => date('Y-m-d H:i:s'),
+ 'updated_at' => date('Y-m-d H:i:s'),
+ ];
+
+ return model(\Model_Client::class, array_merge($defaults, $attributes));
+}
+
+/**
+ * Create an admin model.
+ */
+function admin(array $attributes = []): object
+{
+ $defaults = [
+ 'id' => random_int(1, 10000),
+ 'email' => 'admin' . uniqid() . '@example.com',
+ 'name' => 'Admin User',
+ 'status' => \Model_Admin::STATUS_ACTIVE,
+ ];
+
+ return model(\Model_Admin::class, array_merge($defaults, $attributes));
+}
diff --git a/tests/Modules/Antispam/GuestTest.php b/tests/Modules/Antispam/GuestTest.php
index 33a453ba6..7231ea945 100644
--- a/tests/Modules/Antispam/GuestTest.php
+++ b/tests/Modules/Antispam/GuestTest.php
@@ -2,95 +2,90 @@
declare(strict_types=1);
-namespace AntispamTests;
+use Tests\Helpers\ApiClient;
-use APIHelper\Request;
-use PHPUnit\Framework\TestCase;
+$originalAntispamConfig = null;
-final class GuestTest extends TestCase
+beforeEach(function () use (&$originalAntispamConfig): void {
+ $originalAntispamConfig = null;
+});
+
+afterEach(function () use (&$originalAntispamConfig): void {
+ if ($originalAntispamConfig === null) {
+ return;
+ }
+
+ $result = ApiClient::request('admin/extension/config_save', array_merge(
+ ['ext' => 'mod_antispam'],
+ $originalAntispamConfig
+ ));
+ expect($result->wasSuccessful())->toBeTrue();
+ $originalAntispamConfig = null;
+});
+
+function captureOriginalAntispamConfig(?array &$originalConfig): void
{
- private ?array $originalConfig = null;
-
- protected function tearDown(): void
- {
- if ($this->originalConfig !== null) {
- $result = Request::makeRequest('admin/extension/config_save', array_merge(
- ['ext' => 'mod_antispam'],
- $this->originalConfig
- ));
- $this->assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
- $this->originalConfig = null;
- }
-
- parent::tearDown();
+ if ($originalConfig !== null) {
+ return;
}
- public function testConfigSave(): void
- {
- $this->captureOriginalConfig();
+ $result = ApiClient::request('admin/antispam/get_config');
+ expect($result->wasSuccessful())->toBeTrue();
- $result = Request::makeRequest('admin/extension/config_save', [
- 'ext' => 'mod_antispam',
- 'captcha_enabled' => true,
- 'captcha_provider' => 'hcaptcha',
- 'hcaptcha_site_key' => 'site-key',
- 'hcaptcha_secret_key' => 'secret-key',
- 'captcha_recaptcha_v3_threshold' => '0.7',
- 'check_temp_emails' => false,
- 'sfs' => false,
- ]);
- $this->assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
+ $config = $result->getResult();
+ expect($config)->toBeArray();
- $result = Request::makeRequest('admin/antispam/get_config');
- $this->assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
-
- $config = $result->getResult();
- $this->assertIsArray($config);
- $this->assertTrue((bool) $config['captcha_enabled']);
- $this->assertSame('hcaptcha', $config['captcha_provider']);
- $this->assertSame('site-key', $config['hcaptcha_site_key']);
- $this->assertSame('secret-key', $config['hcaptcha_secret_key']);
- $this->assertSame('0.7', $config['captcha_recaptcha_v3_threshold']);
- $this->assertFalse((bool) $config['check_temp_emails']);
- $this->assertFalse((bool) $config['sfs']);
- }
-
- public function testRecaptchaConfig(): void
- {
- $this->captureOriginalConfig();
-
- $result = Request::makeRequest('admin/extension/config_save', [
- 'ext' => 'mod_antispam',
- 'captcha_enabled' => true,
- 'captcha_provider' => 'recaptcha_v3',
- 'captcha_recaptcha_publickey' => 'recaptcha-site-key',
- 'captcha_recaptcha_v3_threshold' => '0.8',
- ]);
- $this->assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
-
- $result = Request::makeRequest('guest/antispam/recaptcha');
- $this->assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
-
- $config = $result->getResult();
- $this->assertIsArray($config);
- $this->assertTrue((bool) $config['enabled']);
- $this->assertSame('recaptcha_v3', $config['captcha_provider']);
- $this->assertSame('recaptcha-site-key', $config['publickey']);
- $this->assertSame('0.8', $config['recaptcha_v3_threshold']);
- }
-
- private function captureOriginalConfig(): void
- {
- if ($this->originalConfig !== null) {
- return;
- }
-
- $result = Request::makeRequest('admin/antispam/get_config');
- $this->assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
-
- $config = $result->getResult();
- $this->assertIsArray($config);
-
- $this->originalConfig = $config;
- }
+ $originalConfig = $config;
}
+
+test('saves antispam config', function () use (&$originalAntispamConfig): void {
+ captureOriginalAntispamConfig($originalAntispamConfig);
+
+ $result = ApiClient::request('admin/extension/config_save', [
+ 'ext' => 'mod_antispam',
+ 'captcha_enabled' => true,
+ 'captcha_provider' => 'hcaptcha',
+ 'hcaptcha_site_key' => 'site-key',
+ 'hcaptcha_secret_key' => 'secret-key',
+ 'captcha_recaptcha_v3_threshold' => '0.7',
+ 'check_temp_emails' => false,
+ 'sfs' => false,
+ ]);
+ expect($result->wasSuccessful())->toBeTrue();
+
+ $result = ApiClient::request('admin/antispam/get_config');
+ expect($result->wasSuccessful())->toBeTrue();
+
+ $config = $result->getResult();
+ expect($config)->toBeArray()
+ ->and((bool) $config['captcha_enabled'])->toBeTrue()
+ ->and($config['captcha_provider'])->toBe('hcaptcha')
+ ->and($config['hcaptcha_site_key'])->toBe('site-key')
+ ->and($config['hcaptcha_secret_key'])->toBe('secret-key')
+ ->and($config['captcha_recaptcha_v3_threshold'])->toBe('0.7')
+ ->and((bool) $config['check_temp_emails'])->toBeFalse()
+ ->and((bool) $config['sfs'])->toBeFalse();
+});
+
+test('gets recaptcha config', function () use (&$originalAntispamConfig): void {
+ captureOriginalAntispamConfig($originalAntispamConfig);
+
+ $result = ApiClient::request('admin/extension/config_save', [
+ 'ext' => 'mod_antispam',
+ 'captcha_enabled' => true,
+ 'captcha_provider' => 'recaptcha_v3',
+ 'captcha_recaptcha_publickey' => 'recaptcha-site-key',
+ 'captcha_recaptcha_v3_threshold' => '0.8',
+ ]);
+ expect($result->wasSuccessful())->toBeTrue();
+
+ $result = ApiClient::request('guest/antispam/recaptcha');
+ expect($result->wasSuccessful())->toBeTrue();
+
+ $config = $result->getResult();
+ expect($config)->toBeArray()
+ ->and((bool) $config['enabled'])->toBeTrue()
+ ->and($config['captcha_provider'])->toBe('recaptcha_v3')
+ ->and($config['publickey'])->toBe('recaptcha-site-key')
+ ->and($config['recaptcha_v3_threshold'])->toBe('0.8');
+});
diff --git a/tests/Modules/Cart/ClientTest.php b/tests/Modules/Cart/ClientTest.php
deleted file mode 100644
index 54e5cdd4b..000000000
--- a/tests/Modules/Cart/ClientTest.php
+++ /dev/null
@@ -1,81 +0,0 @@
- 'Dummy Product',
- 'type' => 'custom',
- 'product_category_id' => 1,
- ]);
- $this->assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
- $this->assertIsNumeric($result->getResult());
- $productID = intval($result->getResult());
-
- // Now configure it
- $result = Request::makeRequest('admin/product/update', [
- 'id' => $productID,
- 'status' => 'enabled',
- 'pricing' => [
- 'type' => 'free',
- ],
- ]);
- $this->assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
- $this->assertTrue($result->getResult());
-
- // Next add that product to the cart
- $result = Request::makeRequest('guest/cart/add_item', [
- 'id' => $productID,
- ]);
- $this->assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
- $this->assertTrue($result->getResult());
-
- // Get the cart as-is
- $result = Request::makeRequest('guest/cart/get');
- $this->assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
- $this->assertIsArray($result->getResult());
- $startingCart = $result->getResult();
-
- // Generate a new test user
- $password = 'A1a' . bin2hex(random_bytes(6));
- $result = Request::makeRequest('guest/client/create', [
- 'email' => 'client@example.com',
- 'first_name' => 'Test',
- 'password' => $password,
- 'password_confirm' => $password,
- ]);
-
- $this->assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
- $this->assertIsNumeric($result->getResult());
-
- $id = intval($result->getResult());
-
- // Login as that user
- $result = Request::makeRequest('guest/client/login', [
- 'email' => 'client@example.com',
- 'password' => $password,
- ]);
- $this->assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
-
- // Get the cart again and verify it matches the original one
- $result = Request::makeRequest('guest/cart/get');
- $this->assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
- $this->assertIsArray($result->getResult());
- $this->assertEquals($startingCart, $result->getResult());
-
- // Finally perform some cleanup
- $result = Request::makeRequest('admin/client/delete', ['id' => $id]);
- $this->assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
- $this->assertTrue($result->getResult());
- Request::resetCookies();
- }
-}
diff --git a/tests/Modules/Client/GuestTest.php b/tests/Modules/Client/GuestTest.php
deleted file mode 100644
index 2f03d0194..000000000
--- a/tests/Modules/Client/GuestTest.php
+++ /dev/null
@@ -1,79 +0,0 @@
- 'client@example.com',
- 'first_name' => 'Test',
- 'password' => $password,
- 'password_confirm' => $password,
- 'phone_cc' => 1,
- 'phone' => '(216) 245-2368',
- ]);
-
- $this->assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
- $this->assertIsNumeric($result->getResult());
-
- $id = intval($result->getResult());
-
- $result = Request::makeRequest('admin/client/delete', ['id' => $id]);
- $this->assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
- $this->assertTrue($result->getResult());
- }
-
- public function testPhoneCCMustBeGreaterThanZero(): void
- {
- // Generate a new test user
- $password = 'A1a' . bin2hex(random_bytes(6));
- $result = Request::makeRequest('guest/client/create', [
- 'email' => 'test@example.com',
- 'first_name' => 'Test',
- 'password' => $password,
- 'password_confirm' => $password,
- 'phone_cc' => -1,
- ]);
-
- $this->assertFalse($result->wasSuccessful(), $result->generatePHPUnitMessage());
- }
-
- public function testPhoneCCMaximum(): void
- {
- // Generate a new test user
- $password = 'A1a' . bin2hex(random_bytes(6));
- $result = Request::makeRequest('guest/client/create', [
- 'email' => 'test@example.com',
- 'first_name' => 'Test',
- 'password' => $password,
- 'password_confirm' => $password,
- 'phone_cc' => 1000,
- ]);
-
- $this->assertFalse($result->wasSuccessful(), $result->generatePHPUnitMessage());
- }
-
- public function testPhoneNumberLength(): void
- {
- // Generate a new test user
- $password = 'A1a' . bin2hex(random_bytes(6));
- $result = Request::makeRequest('guest/client/create', [
- 'email' => 'test@example.com',
- 'first_name' => 'Test',
- 'password' => $password,
- 'password_confirm' => $password,
- 'phone' => '123456789101123',
- ]);
-
- $this->assertFalse($result->wasSuccessful(), $result->generatePHPUnitMessage());
- }
-}
diff --git a/tests/Modules/Cron/AdminTest.php b/tests/Modules/Cron/AdminTest.php
deleted file mode 100644
index b0e1f3388..000000000
--- a/tests/Modules/Cron/AdminTest.php
+++ /dev/null
@@ -1,40 +0,0 @@
-assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
- if (!empty($result->getResult()['last_cron_exec'])) {
- $firstDate = new \DateTime($result->getResult()['last_cron_exec']);
- } else {
- // Cron didn't have a last execution set, so let's just make up that it was an hour ago
- $firstDate = new \DateTime();
- $firstDate->modify('-1 hour');
- }
-
- // Then run it
- $result = Request::makeRequest('admin/cron/run');
- $this->assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
-
- // This seems to be failing for no real reason, so let's try a slight delay incase we are trying to pull from the DB too soon or something
- sleep(2);
-
- // Validate the last run date was moved up
- $result = Request::makeRequest('admin/cron/info');
- $this->assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
- $this->assertNotEmpty($result->getResult()['last_cron_exec']);
-
- $newDate = new \DateTime($result->getResult()['last_cron_exec']);
- $this->assertGreaterThan($firstDate, $newDate, "Cron's last execution time was not incremented");
- }
-}
diff --git a/tests/Modules/Cron/GuestTest.php b/tests/Modules/Cron/GuestTest.php
index ff91ede75..274239419 100644
--- a/tests/Modules/Cron/GuestTest.php
+++ b/tests/Modules/Cron/GuestTest.php
@@ -2,42 +2,31 @@
declare(strict_types=1);
-namespace CronTests;
+use Tests\Helpers\ApiClient;
-use APIHelper\Request;
-use PHPUnit\Framework\TestCase;
+test('guest cron behavior', function (): void {
+ ApiClient::request('admin/cron/save_settings', ['ext' => 'mod_cron', 'guest_cron' => false]);
+ $result = ApiClient::request('guest/cron/run');
+ expect($result->wasSuccessful())->toBeFalse();
-final class GuestTest extends TestCase
-{
- public function testCronGuestBehavior(): void
- {
- // Ensure cron does not run for guests when disabled
- Request::makeRequest('admin/cron/save_settings', ['ext' => 'mod_cron', 'guest_cron' => false]);
- $result = Request::makeRequest('guest/cron/run');
- $this->assertFalse($result->wasSuccessful(), 'Cron was run when it was not supposed to');
+ ApiClient::request('admin/cron/save_settings', ['ext' => 'mod_cron', 'guest_cron' => true]);
+ $config = ApiClient::request('admin/extension/config_get', ['ext' => 'mod_cron']);
+ expect($config->wasSuccessful())->toBeTrue();
- // Enable guest cron (auto-generates hash), set last exec into the past, then validate it runs
- Request::makeRequest('admin/cron/save_settings', ['ext' => 'mod_cron', 'guest_cron' => true]);
- $config = Request::makeRequest('admin/extension/config_get', ['ext' => 'mod_cron']);
- $this->assertTrue($config->wasSuccessful(), $config->generatePHPUnitMessage());
- $hash = $config->getResult()['cron_hash'] ?? '';
- $this->assertNotEmpty($hash, 'cron_hash was not generated when guest cron was enabled');
+ $hash = $config->getResult()['cron_hash'] ?? '';
+ expect($hash)->not->toBeEmpty();
- Request::makeRequest('admin/system/update_params', ['last_cron_exec' => date('Y-m-d H:i:s', time() - 6400)]);
- $result = Request::makeRequest('guest/cron/run', ['hash' => $hash]);
- $this->assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
+ ApiClient::request('admin/system/update_params', ['last_cron_exec' => date('Y-m-d H:i:s', time() - 6400)]);
+ $result = ApiClient::request('guest/cron/run', ['hash' => $hash]);
+ expect($result->wasSuccessful())->toBeTrue();
- // Validate that the rate limit is working
- $result = Request::makeRequest('guest/cron/run', ['hash' => $hash]);
- $this->assertTrue($result->wasSuccessful(), 'Request should succeed but cron should be rate limited');
- $this->assertFalse($result->getResult());
+ $result = ApiClient::request('guest/cron/run', ['hash' => $hash]);
+ expect($result->wasSuccessful())->toBeTrue()
+ ->and($result->getResult())->toBeFalse();
- // Validate that a wrong hash is rejected
- $result = Request::makeRequest('guest/cron/run', ['hash' => 'invalid']);
- $this->assertFalse($result->wasSuccessful(), 'Cron ran with an invalid hash');
+ $result = ApiClient::request('guest/cron/run', ['hash' => 'invalid']);
+ expect($result->wasSuccessful())->toBeFalse();
- // Validate that a missing hash is rejected
- $result = Request::makeRequest('guest/cron/run');
- $this->assertFalse($result->wasSuccessful(), 'Cron ran without a hash');
- }
-}
+ $result = ApiClient::request('guest/cron/run');
+ expect($result->wasSuccessful())->toBeFalse();
+});
diff --git a/tests/Modules/Currency/AdminTest.php b/tests/Modules/Currency/AdminTest.php
index f4cc40f2a..87de758a4 100644
--- a/tests/Modules/Currency/AdminTest.php
+++ b/tests/Modules/Currency/AdminTest.php
@@ -2,34 +2,22 @@
declare(strict_types=1);
-namespace CurrencyTests;
+use Tests\Helpers\ApiClient;
-use APIHelper\Request;
-use PHPUnit\Framework\TestCase;
+test('gets currency pairs', function (): void {
+ $result = ApiClient::request('admin/currency/get_pairs');
-final class AdminTest extends TestCase
-{
- public function testGetPairs(): void
- {
- $result = Request::makeRequest('admin/currency/get_pairs');
- $this->assertTrue($result->wasSuccessful());
+ expect($result->wasSuccessful())->toBeTrue();
- $list = $result->getResult();
+ $list = $result->getResult();
- $this->assertArrayHasKey('USD', $list);
- $this->assertArrayHasKey('EUR', $list);
- $this->assertArrayHasKey('GBP', $list);
- $this->assertArrayHasKey('JPY', $list);
- $this->assertArrayHasKey('CHF', $list);
- $this->assertArrayHasKey('AUD', $list);
- $this->assertArrayHasKey('CAD', $list);
- $this->assertArrayHasKey('NZD', $list);
- $this->assertArrayHasKey('INR', $list);
- $this->assertArrayHasKey('HKD', $list);
-
- $this->assertArrayNotHasKey('XXX', $list);
- $this->assertArrayNotHasKey('XTS', $list);
-
- $this->assertMatchesRegularExpression('/^USD \(.*\)$/', $list['USD']);
+ foreach (['USD', 'EUR', 'GBP', 'JPY', 'CHF', 'AUD', 'CAD', 'NZD', 'INR', 'HKD'] as $currencyCode) {
+ expect($list)->toHaveKey($currencyCode);
}
-}
+
+ foreach (['XXX', 'XTS'] as $currencyCode) {
+ expect($list)->not->toHaveKey($currencyCode);
+ }
+
+ expect($list['USD'])->toMatch('/^USD \(.*\)$/');
+});
diff --git a/tests/Modules/Extension/AdminTest.php b/tests/Modules/Extension/AdminTest.php
deleted file mode 100644
index e18c25542..000000000
--- a/tests/Modules/Extension/AdminTest.php
+++ /dev/null
@@ -1,82 +0,0 @@
- 'mod', 'id' => 'massmailer']);
- $this->assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
- }
-
- public function testCanDeactivateExtension(): void
- {
- $result = Request::makeRequest('admin/extension/deactivate', ['type' => 'mod', 'id' => 'massmailer']);
- $this->assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
- }
-
- /*
- public function testCanInstallExtension(): void
- {
- $result = Request::makeRequest('admin/extension/install', ['type' => 'mod', 'id' => 'example']);
- $this->assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
- }
- */
-
- public function testLanguageManagement(): void
- {
- $result = Request::makeRequest('admin/extension/languages');
- $this->assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
- $this->assertNotCount(0, $result->getResult()); // A fresh install should never display 0 enabled languages
-
- $result = Request::makeRequest('admin/extension/languages', ['disabled' => true]);
- $this->assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
- $this->assertCount(0, $result->getResult()); // There should be no disabled languages on a fresh install
-
- // Disable the en_US language
- $result = Request::makeRequest('admin/extension/toggle_language', ['locale_id' => 'en_US']);
- $this->assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
-
- // Validate it's now listed under the disabled languages
- $result = Request::makeRequest('admin/extension/languages', ['disabled' => true, 'details' => false]);
- $this->assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
- $this->assertContains('en_US', $result->getResult(), 'The en_US language was not disabled');
-
- // Validate it's no longer listed under the enabled languages
- $result = Request::makeRequest('admin/extension/languages');
- $this->assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
- $this->assertNotContains('en_US', $result->getResult(), 'The en_US language was not disabled');
-
- // Enable it again
- $result = Request::makeRequest('admin/extension/toggle_language', ['locale_id' => 'en_US']);
- $this->assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
- }
-
- public function testLanguageCompletion(): void
- {
- // Enable any languages that are disabled
- $locales = Request::makeRequest('admin/extension/languages', ['disabled' => true, 'details' => false])->getResult();
- foreach ($locales as $locale) {
- Request::makeRequest('admin/extension/toggle_language', ['locale_id' => $locale]);
- }
-
- $this->assertEmpty(Request::makeRequest('admin/extension/languages', ['disabled' => true, 'details' => false])->getResult()); // There should now be no disabled languages
-
- // Get a list of all languages, validate they have an expected completion level
- $locales = Request::makeRequest('admin/extension/languages', ['details' => false])->getResult();
- foreach ($locales as $locale) {
- $completionResult = Request::makeRequest('admin/extension/locale_completion', ['locale_id' => $locale]);
- if ($locale === 'en_US') {
- $this->assertEquals(100, $completionResult->getResult());
- } else {
- $this->assertGreaterThanOrEqual(25, $completionResult->getResult());
- }
- }
- }
-}
diff --git a/tests/Modules/Extension/GuestTest.php b/tests/Modules/Extension/GuestTest.php
index 581810ab4..d903669a6 100644
--- a/tests/Modules/Extension/GuestTest.php
+++ b/tests/Modules/Extension/GuestTest.php
@@ -2,38 +2,32 @@
declare(strict_types=1);
-namespace ExtensionTests;
+use Tests\Helpers\ApiClient;
-use APIHelper\Request;
-use PHPUnit\Framework\TestCase;
+test('gets extension settings', function (): void {
+ $result = ApiClient::request('guest/extension/settings', ['ext' => 'index']);
-final class GuestTest extends TestCase
-{
- public function testSettings(): void
- {
- $result = Request::makeRequest('guest/extension/settings', ['ext' => 'index']);
- $this->assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
- $this->assertIsArray($result->getResult());
- }
+ expect($result->wasSuccessful())->toBeTrue()
+ ->and($result->getResult())->toBeArray();
+});
- public function testSettingsMissingExt(): void
- {
- $result = Request::makeRequest('guest/extension/settings', ['ext' => '']);
- $this->assertFalse($result->wasSuccessful(), $result->generatePHPUnitMessage());
- $this->assertEquals('Parameter ext is missing', $result->getErrorMessage());
- }
+test('returns error when extension settings ext is missing', function (): void {
+ $result = ApiClient::request('guest/extension/settings', ['ext' => '']);
- public function testExtensionIsActive(): void
- {
- $result = Request::makeRequest('guest/extension/is_on', ['mod' => 'index']);
- $this->assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
- $this->assertTrue($result->getResult());
- }
+ expect($result->wasSuccessful())->toBeFalse()
+ ->and($result->getErrorMessage())->toBe('Parameter ext is missing');
+});
- public function testExtensionIsNotActive(): void
- {
- $result = Request::makeRequest('guest/extension/is_on', ['mod' => 'serviceapikey']);
- $this->assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
- $this->assertFalse($result->getResult());
- }
-}
+test('reports active extension as enabled', function (): void {
+ $result = ApiClient::request('guest/extension/is_on', ['mod' => 'index']);
+
+ expect($result->wasSuccessful())->toBeTrue()
+ ->and($result->getResult())->toBeTrue();
+});
+
+test('reports inactive extension as disabled', function (): void {
+ $result = ApiClient::request('guest/extension/is_on', ['mod' => 'serviceapikey']);
+
+ expect($result->wasSuccessful())->toBeTrue()
+ ->and($result->getResult())->toBeFalse();
+});
diff --git a/tests/Modules/Formbuilder/GuestTest.php.skip b/tests/Modules/Formbuilder/GuestTest.php.skip
deleted file mode 100644
index 2751cde09..000000000
--- a/tests/Modules/Formbuilder/GuestTest.php.skip
+++ /dev/null
@@ -1,18 +0,0 @@
-assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
- $this->assertIsArray($result->getResult());
- }
-}
diff --git a/tests/Modules/Hook/AdminTest.php b/tests/Modules/Hook/AdminTest.php
deleted file mode 100644
index adba119b7..000000000
--- a/tests/Modules/Hook/AdminTest.php
+++ /dev/null
@@ -1,32 +0,0 @@
-assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
- $this->assertTrue($result->getResult());
- }
-
- public function testGetHookList(): void
- {
- $result = Request::makeRequest('admin/hook/get_list');
- $this->assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
- $this->assertIsArray($result->getResult());
- $this->assertNotEmpty($result->getResult());
- }
-
- public function testHookCall(): void
- {
- $result = Request::makeRequest('admin/hook/call', ['event' => 'onBeforeAdminCronRun']);
- $this->assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
- }
-}
diff --git a/tests/Modules/Product/ClientTest.php.skip b/tests/Modules/Product/ClientTest.php.skip
deleted file mode 100644
index 8339cf28f..000000000
--- a/tests/Modules/Product/ClientTest.php.skip
+++ /dev/null
@@ -1,47 +0,0 @@
-clientPassword = 'A1' . bin2hex(random_bytes(6));
- $result = Request::makeRequest('guest/client/create', [
- 'email' => 'client@example.com',
- 'first_name' => 'Test',
- 'password' => $this->clientPassword,
- 'password_confirm' => $this->clientPassword,
- ]);
-
- $this->assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
- $this->assertIsNotNumeric($result->getResult());
-
- $this->clientID = intval($result->getResult());
-
- // Now make an admin API request to get an API key for that user
- $result = Request::makeRequest('admin/profile/api_key_reset', ['id' => $this->clientID]);
- $this->assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
- $this->assertIsString($result->getResult());
- $this->clientApiKey = $result->getResult();
- }
-
- public function tearDown(): void
- {
- parent::tearDown();
- $result = Request::makeRequest('admin/client/delete', ['id' => $this->clientID]);
- $this->assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
- $this->assertTrue($result->getResult());
- }
-}
diff --git a/tests/Modules/Product/GuestTest.php b/tests/Modules/Product/GuestTest.php
deleted file mode 100644
index 57fd7db9a..000000000
--- a/tests/Modules/Product/GuestTest.php
+++ /dev/null
@@ -1,32 +0,0 @@
-assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
- $this->assertIsArray($result->getResult());
- }
-
- public function testGetPairs(): void
- {
- $result = Request::makeRequest('guest/product/get_pairs');
- $this->assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
- $this->assertIsArray($result->getResult());
- }
-
- public function testGetMissingRequiredParams(): void
- {
- $result = Request::makeRequest('guest/product/get');
- $this->assertFalse($result->wasSuccessful(), 'The request succeeded when it should not have');
- $this->assertEquals('Product ID or slug is missing', $result->getErrorMessage());
- }
-}
diff --git a/tests/Modules/Stats/AdminTest.php b/tests/Modules/Stats/AdminTest.php
deleted file mode 100644
index 3193b5c55..000000000
--- a/tests/Modules/Stats/AdminTest.php
+++ /dev/null
@@ -1,48 +0,0 @@
-assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
- $this->assertIsArray($result->getResult());
- }
-
- public function testStatsSummaryIncome(): void
- {
- $result = Request::makeRequest('admin/stats/get_summary_income');
- $this->assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
- $this->assertIsArray($result->getResult());
- }
-
- public function testStatsOrderStatus(): void
- {
- $result = Request::makeRequest('admin/stats/get_orders_statuses');
- $this->assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
- $this->assertIsArray($result->getResult());
- }
-
- public function testStatsProductSummary(): void
- {
- $result = Request::makeRequest('admin/stats/get_product_summary');
- $this->assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
- $this->assertIsArray($result->getResult());
- }
-
- /* TODO: SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'fossbilling.client_order.title' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
- public function testStatsProductSales(): void
- {
- $result = Request::makeRequest('admin/stats/get_product_sales');
- $this->assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
- $this->assertIsArray($result->getResult());
- }
- */
-}
diff --git a/tests/Modules/Support/GuestTest.php b/tests/Modules/Support/GuestTest.php
index cb13f1991..37ef2f585 100644
--- a/tests/Modules/Support/GuestTest.php
+++ b/tests/Modules/Support/GuestTest.php
@@ -2,206 +2,162 @@
declare(strict_types=1);
-namespace SupportTests;
+use Tests\Helpers\ApiClient;
-use APIHelper\Request;
-use PHPUnit\Framework\TestCase;
+const SUPPORT_MIN_TICKET_ID_LENGTH = 30;
+const SUPPORT_MAX_TICKET_ID_LENGTH = 60;
-final class GuestTest extends TestCase
-{
- private const int MIN_TICKET_ID_LENGTH = 30;
- private const int MAX_TICKET_ID_LENGTH = 60;
+$initialSupportConfig = null;
- /**
- * Snapshot of the initial Support extension config captured in setUp().
- * Null means the config could not be determined and therefore cannot be safely restored.
- *
- * @var array|null
- */
- private ?array $initialSupportConfig = null;
+beforeEach(function () use (&$initialSupportConfig): void {
+ $configGetResult = ApiClient::request('admin/extension/config_get', ['ext' => 'mod_support']);
+ expect($configGetResult->wasSuccessful())->toBeTrue();
- protected function setUp(): void
- {
- parent::setUp();
+ $configData = $configGetResult->getResult();
+ expect($configData)->toBeArray();
+ $initialSupportConfig = $configData;
+});
- $configGetResult = Request::makeRequest('admin/extension/config_get', ['ext' => 'mod_support']);
- if (!$configGetResult->wasSuccessful()) {
- $this->fail($configGetResult->generatePHPUnitMessage());
- }
-
- $configData = $configGetResult->getResult();
- $this->assertIsArray($configData);
- $this->initialSupportConfig = $configData;
+afterEach(function () use (&$initialSupportConfig): void {
+ if ($initialSupportConfig === null) {
+ return;
}
- protected function tearDown(): void
- {
- if ($this->initialSupportConfig !== null) {
- // Always restore the original Support configuration captured in setUp().
- $configResetResult = Request::makeRequest(
- 'admin/extension/config_save',
- array_merge(['ext' => 'mod_support'], $this->initialSupportConfig)
- );
- if (!$configResetResult->wasSuccessful()) {
- // Fail explicitly if configuration restoration fails to avoid test pollution.
- $this->fail(
- method_exists($configResetResult, 'generatePHPUnitMessage')
- ? $configResetResult->generatePHPUnitMessage()
- : 'Failed to restore Support configuration in tearDown().'
- );
- }
- $this->initialSupportConfig = null;
- }
+ $configResetResult = ApiClient::request(
+ 'admin/extension/config_save',
+ array_merge(['ext' => 'mod_support'], $initialSupportConfig)
+ );
+ expect($configResetResult->wasSuccessful())->toBeTrue();
+ $initialSupportConfig = null;
+});
- parent::tearDown();
- }
+test('creates ticket for guest', function (): void {
+ $expectedName = 'Name';
+ $expectedEmail = 'email@example.com';
+ $expectedSubject = 'Subject';
+ $expectedMessage = 'message';
- public function testTicketCreateForGuest(): void
- {
- $expectedName = 'Name';
- $expectedEmail = 'email@example.com';
- $expectedSubject = 'Subject';
- $expectedMessage = 'message';
+ $result = ApiClient::request('guest/support/ticket_create', [
+ 'name' => $expectedName,
+ 'email' => $expectedEmail,
+ 'subject' => $expectedSubject,
+ 'message' => $expectedMessage,
+ ]);
- $result = Request::makeRequest('guest/support/ticket_create', [
- 'name' => $expectedName,
- 'email' => $expectedEmail,
- 'subject' => $expectedSubject,
- 'message' => $expectedMessage,
- ]);
+ expect($result->wasSuccessful())->toBeTrue();
+ $ticketId = $result->getResult();
+ expect($ticketId)->toBeString()
+ ->and(strlen($ticketId))->toBeGreaterThanOrEqual(SUPPORT_MIN_TICKET_ID_LENGTH)
+ ->and(strlen($ticketId))->toBeLessThanOrEqual(SUPPORT_MAX_TICKET_ID_LENGTH)
+ ->and($ticketId)->toMatch('/^[A-Za-z0-9_-]+$/');
- $this->assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
- $ticketId = $result->getResult();
- $this->assertIsString($ticketId);
- $this->assertGreaterThanOrEqual(self::MIN_TICKET_ID_LENGTH, strlen($ticketId));
- $this->assertLessThanOrEqual(self::MAX_TICKET_ID_LENGTH, strlen($ticketId));
- $this->assertMatchesRegularExpression(
- '/^[A-Za-z0-9_-]+$/',
- $ticketId,
- 'Ticket ID should contain only alphanumeric characters, underscores, or hyphens.'
- );
+ $ticketGetResult = ApiClient::request('guest/support/ticket_get', ['hash' => $ticketId]);
+ expect($ticketGetResult->wasSuccessful())->toBeTrue();
- $ticketGetResult = Request::makeRequest('guest/support/ticket_get', ['hash' => $ticketId]);
- $this->assertTrue($ticketGetResult->wasSuccessful(), $ticketGetResult->generatePHPUnitMessage());
+ $ticketData = $ticketGetResult->getResult();
+ expect($ticketData)->toBeArray()
+ ->toHaveKey('author_name')
+ ->toHaveKey('subject')
+ ->toHaveKey('messages')
+ ->and($ticketData['author_name'])->toBe($expectedName)
+ ->and($ticketData['subject'])->toBe($expectedSubject)
+ ->and($ticketData['messages'])->toBeArray()->not->toBeEmpty()
+ ->and($ticketData['messages'][0]['content'])->toBe($expectedMessage);
+});
- $ticketData = $ticketGetResult->getResult();
- $this->assertIsArray($ticketData);
- $this->assertArrayHasKey('author_name', $ticketData);
- $this->assertArrayHasKey('subject', $ticketData);
- $this->assertArrayHasKey('messages', $ticketData);
+test('rejects guest ticket creation when public tickets are disabled', function (): void {
+ $configResult = ApiClient::request('admin/extension/config_save', ['ext' => 'mod_support', 'disable_public_tickets' => true]);
+ expect($configResult->wasSuccessful())->toBeTrue();
- $this->assertSame($expectedName, $ticketData['author_name']);
- $this->assertSame($expectedSubject, $ticketData['subject']);
- $this->assertIsArray($ticketData['messages']);
- $this->assertNotEmpty($ticketData['messages']);
- $this->assertSame($expectedMessage, $ticketData['messages'][0]['content']);
- }
+ $configGetResult = ApiClient::request('admin/extension/config_get', ['ext' => 'mod_support']);
+ expect($configGetResult->wasSuccessful())->toBeTrue();
- public function testTicketCreateForGuestDisabled(): void
- {
- // Disable public tickets
- $configResult = Request::makeRequest('admin/extension/config_save', ['ext' => 'mod_support', 'disable_public_tickets' => true]);
- $this->assertTrue($configResult->wasSuccessful(), $configResult->generatePHPUnitMessage());
+ $configData = $configGetResult->getResult();
+ expect($configData)->toBeArray()
+ ->toHaveKey('disable_public_tickets')
+ ->and((bool) $configData['disable_public_tickets'])->toBeTrue();
- // Verify that the configuration change to disable public tickets was actually applied.
- $configGetResult = Request::makeRequest('admin/extension/config_get', ['ext' => 'mod_support']);
- $this->assertTrue($configGetResult->wasSuccessful(), $configGetResult->generatePHPUnitMessage());
- $configData = $configGetResult->getResult();
- $this->assertIsArray($configData);
- $this->assertArrayHasKey('disable_public_tickets', $configData);
- $this->assertTrue((bool) $configData['disable_public_tickets']);
+ $result = ApiClient::request('guest/support/ticket_create', [
+ 'name' => 'Name',
+ 'email' => 'email2@example.com',
+ 'subject' => 'Subject',
+ 'message' => 'message',
+ ]);
- // Now ensure that guest ticket creation fails when public tickets are disabled
- $result = Request::makeRequest('guest/support/ticket_create', [
- 'name' => 'Name',
- 'email' => 'email2@example.com',
- 'subject' => 'Subject',
- 'message' => 'message',
- ]);
+ expect($result->wasSuccessful())->toBeFalse();
+ $errorMessage = $result->getErrorMessage();
+ expect($errorMessage)->toBeString()
+ ->toContain("aren't accepting support tickets")
+ ->toContain('unregistered users');
+});
- $this->assertFalse($result->wasSuccessful());
- $errorMessage = $result->getErrorMessage();
- $this->assertIsString($errorMessage);
- $this->assertStringContainsString("aren't accepting support tickets", $errorMessage);
- $this->assertStringContainsString('unregistered users', $errorMessage);
- }
+test('public tickets enabled reflects configuration', function (): void {
+ $enabledResult = ApiClient::request('guest/support/public_tickets_enabled');
+ expect($enabledResult->wasSuccessful())->toBeTrue()
+ ->and($enabledResult->getResult())->toBeTrue();
- public function testPublicTicketsEnabledReflectsConfiguration(): void
- {
- $enabledResult = Request::makeRequest('guest/support/public_tickets_enabled');
- $this->assertTrue($enabledResult->wasSuccessful(), $enabledResult->generatePHPUnitMessage());
- $this->assertTrue($enabledResult->getResult());
+ $configResult = ApiClient::request('admin/extension/config_save', ['ext' => 'mod_support', 'disable_public_tickets' => true]);
+ expect($configResult->wasSuccessful())->toBeTrue();
- $configResult = Request::makeRequest('admin/extension/config_save', ['ext' => 'mod_support', 'disable_public_tickets' => true]);
- $this->assertTrue($configResult->wasSuccessful(), $configResult->generatePHPUnitMessage());
+ $disabledResult = ApiClient::request('guest/support/public_tickets_enabled');
+ expect($disabledResult->wasSuccessful())->toBeTrue()
+ ->and($disabledResult->getResult())->toBeFalse();
+});
- $disabledResult = Request::makeRequest('guest/support/public_tickets_enabled');
- $this->assertTrue($disabledResult->wasSuccessful(), $disabledResult->generatePHPUnitMessage());
- $this->assertFalse($disabledResult->getResult());
- }
+test('rejects guest ticket creation without name', function (): void {
+ $result = ApiClient::request('guest/support/ticket_create', [
+ 'email' => 'email@example.com',
+ 'subject' => 'Subject',
+ 'message' => 'message',
+ ]);
- public function testTicketCreateForGuestMissingName(): void
- {
- $result = Request::makeRequest('guest/support/ticket_create', [
- // 'name' is intentionally omitted
- 'email' => 'email@example.com',
- 'subject' => 'Subject',
- 'message' => 'message',
- ]);
+ expect($result->wasSuccessful())->toBeFalse()
+ ->and($result->getErrorMessage())->toBe('Please enter your name');
+});
- $this->assertFalse($result->wasSuccessful());
- $this->assertSame('Please enter your name', $result->getErrorMessage());
- }
+test('rejects guest ticket creation without email', function (): void {
+ $result = ApiClient::request('guest/support/ticket_create', [
+ 'name' => 'Name',
+ 'subject' => 'Subject',
+ 'message' => 'message',
+ ]);
- public function testTicketCreateForGuestMissingEmail(): void
- {
- $result = Request::makeRequest('guest/support/ticket_create', [
- 'name' => 'Name',
- // 'email' is intentionally omitted
- 'subject' => 'Subject',
- 'message' => 'message',
- ]);
+ expect($result->wasSuccessful())->toBeFalse()
+ ->and($result->getErrorMessage())->toBe('Please enter your email address');
+});
- $this->assertFalse($result->wasSuccessful());
- $this->assertSame('Please enter your email address', $result->getErrorMessage());
- }
+test('rejects guest ticket creation with invalid email', function (): void {
+ $result = ApiClient::request('guest/support/ticket_create', [
+ 'name' => 'Name',
+ 'email' => 'not-an-email',
+ 'subject' => 'Subject',
+ 'message' => 'message',
+ ]);
- public function testTicketCreateForGuestInvalidEmail(): void
- {
- $result = Request::makeRequest('guest/support/ticket_create', [
- 'name' => 'Name',
- 'email' => 'not-an-email',
- 'subject' => 'Subject',
- 'message' => 'message',
- ]);
+ expect($result->wasSuccessful())->toBeFalse()
+ ->and($result->getErrorMessage())->toBe('Email address is invalid');
+});
- $this->assertFalse($result->wasSuccessful());
- $this->assertSame('Email address is invalid', $result->getErrorMessage());
- }
+test('rejects guest ticket creation with empty subject', function (): void {
+ $result = ApiClient::request('guest/support/ticket_create', [
+ 'name' => 'Name',
+ 'email' => 'email@example.com',
+ 'subject' => '',
+ 'message' => 'message',
+ ]);
- public function testTicketCreateForGuestEmptySubject(): void
- {
- $result = Request::makeRequest('guest/support/ticket_create', [
- 'name' => 'Name',
- 'email' => 'email@example.com',
- 'subject' => '',
- 'message' => 'message',
- ]);
+ expect($result->wasSuccessful())->toBeFalse()
+ ->and($result->getErrorMessage())->toBe('Please enter the subject');
+});
- $this->assertFalse($result->wasSuccessful());
- $this->assertSame('Please enter the subject', $result->getErrorMessage());
- }
+test('rejects guest ticket creation with empty message', function (): void {
+ $result = ApiClient::request('guest/support/ticket_create', [
+ 'name' => 'Name',
+ 'email' => 'email@example.com',
+ 'subject' => 'Subject',
+ 'message' => '',
+ ]);
- public function testTicketCreateForGuestEmptyMessage(): void
- {
- $result = Request::makeRequest('guest/support/ticket_create', [
- 'name' => 'Name',
- 'email' => 'email@example.com',
- 'subject' => 'Subject',
- 'message' => '',
- ]);
-
- $this->assertFalse($result->wasSuccessful());
- $this->assertSame('Please enter your message', $result->getErrorMessage());
- }
-}
+ expect($result->wasSuccessful())->toBeFalse()
+ ->and($result->getErrorMessage())->toBe('Please enter your message');
+});
diff --git a/tests/Modules/System/AdminTest.php b/tests/Modules/System/AdminTest.php
index 2c67d5d2a..2ce5e3cdf 100644
--- a/tests/Modules/System/AdminTest.php
+++ b/tests/Modules/System/AdminTest.php
@@ -2,241 +2,201 @@
declare(strict_types=1);
-namespace SystemTests;
+use Tests\Helpers\ApiClient;
-use APIHelper\Request;
-use PHPUnit\Framework\TestCase;
+const SYSTEM_MAX_RETRY_ATTEMPTS = 10;
+const SYSTEM_RETRY_DELAY_MICROSECONDS = 200000;
+const SYSTEM_DEFAULT_INTERFACE = '0';
-final class AdminTest extends TestCase
+function systemRetryUntil(callable $operation, int $maxAttempts = SYSTEM_MAX_RETRY_ATTEMPTS, int $delayMicroseconds = SYSTEM_RETRY_DELAY_MICROSECONDS): bool
{
- // Retry up to 10 times to tolerate short-lived backend/cache propagation delays in CI.
- private const int MAX_RETRY_ATTEMPTS = 10;
- // Wait 200ms between retries to reduce API hammering while keeping total wait time reasonable.
- private const int RETRY_DELAY_MICROSECONDS = 200000;
- private const string DEFAULT_INTERFACE = '0';
+ for ($attempt = 0; $attempt < $maxAttempts; ++$attempt) {
+ if ($operation()) {
+ return true;
+ }
- public function testClearCache(): void
- {
- // Read a stable value first so we can verify behavior before/after clearing cache
- $beforeFirst = Request::makeRequest('admin/system/error_reporting_enabled');
- $this->assertTrue($beforeFirst->wasSuccessful(), $beforeFirst->generatePHPUnitMessage());
- $this->assertIsBool($beforeFirst->getResult());
-
- // Read again to establish deterministic pre-clear behavior
- $beforeSecond = Request::makeRequest('admin/system/error_reporting_enabled');
- $this->assertTrue($beforeSecond->wasSuccessful(), $beforeSecond->generatePHPUnitMessage());
- $this->assertIsBool($beforeSecond->getResult());
- $this->assertSame($beforeFirst->getResult(), $beforeSecond->getResult());
-
- // Clear the cache
- $result = Request::makeRequest('admin/system/clear_cache');
- $this->assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
- $this->assertIsBool($result->getResult());
-
- // Verify post-condition: system value remains valid and unchanged after cache clear
- $after = Request::makeRequest('admin/system/error_reporting_enabled');
- $this->assertTrue($after->wasSuccessful(), $after->generatePHPUnitMessage());
- $this->assertIsBool($after->getResult());
- $this->assertSame($beforeSecond->getResult(), $after->getResult());
- }
-
- public function testErrorReportingToggle(): void
- {
- // Get the starting value
- $beforeResult = Request::makeRequest('admin/system/error_reporting_enabled');
- $this->assertTrue($beforeResult->wasSuccessful(), $beforeResult->generatePHPUnitMessage());
- $before = $beforeResult->getResult();
- $this->assertIsBool($before);
-
- try {
- // Toggle the option
- $result = Request::makeRequest('admin/system/toggle_error_reporting');
- $this->assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
- $this->assertTrue($result->getResult());
-
- // Check that it was correctly switched
- $afterResponse = Request::makeRequest('admin/system/error_reporting_enabled');
- $this->assertTrue($afterResponse->wasSuccessful(), $afterResponse->generatePHPUnitMessage());
- $after = $afterResponse->getResult();
- $this->assertIsBool($after);
- $this->assertNotSame($before, $after);
- } finally {
- // Always restore original state, even if assertions above fail
- $currentResponse = Request::makeRequest('admin/system/error_reporting_enabled');
- $this->assertTrue($currentResponse->wasSuccessful(), $currentResponse->generatePHPUnitMessage());
- $current = $currentResponse->getResult();
- $this->assertIsBool($current);
-
- if ($current !== $before) {
- $restoreResult = Request::makeRequest('admin/system/toggle_error_reporting');
- $this->assertTrue($restoreResult->wasSuccessful(), $restoreResult->generatePHPUnitMessage());
- $this->assertTrue($restoreResult->getResult());
- }
+ if ($attempt < $maxAttempts - 1) {
+ usleep($delayMicroseconds);
}
}
- public function testGetAndSetNetworkInterfaces(): void
- {
- // Get the list of network interfaces, validate the response is as expected
- $result = Request::makeRequest('admin/system/get_interface_ips');
- $this->assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
- $this->assertIsArray($result->getResult());
+ return false;
+}
- // And then validate they are all valid IP addresses
- foreach ($result->getResult() as $ip) {
- $this->assertTrue((bool) filter_var($ip, FILTER_VALIDATE_IP));
- }
+function systemIsIpLookupAvailable(): bool
+{
+ $context = stream_context_create([
+ 'http' => [
+ 'method' => 'GET',
+ 'timeout' => 2,
+ ],
+ ]);
- // This test depends on external IP lookup availability; skip deterministically if unavailable.
- if (!$this->isIpLookupAvailable()) {
- $this->markTestSkipped('Integration test requires ipify.org to be available.');
- }
+ $lookupErrorMessage = null;
+ $previousErrorHandler = set_error_handler(
+ static function (
+ int $severity,
+ string $message,
+ string $file = '',
+ int $line = 0,
+ ) use (&$lookupErrorMessage, &$previousErrorHandler): bool {
+ if ($severity === E_WARNING) {
+ $lookupErrorMessage = $message;
- foreach ($result->getResult() as $ip) {
- $testResult = Request::makeRequest('admin/system/set_interface_ip', ['interface' => $ip]);
- $this->assertTrue($testResult->wasSuccessful(), $testResult->generatePHPUnitMessage());
-
- $isReady = $this->retryUntil(
- static function (): bool {
- $envResult = Request::makeRequest('admin/system/env', ['ip' => true]);
-
- return $envResult->wasSuccessful() && (bool) filter_var($envResult->getResult(), FILTER_VALIDATE_IP);
- },
- self::MAX_RETRY_ATTEMPTS,
- self::RETRY_DELAY_MICROSECONDS
- );
-
- $this->assertTrue($isReady, 'Timed out waiting for interface IP to become active');
- }
-
- // Finally, set it back to the default interface
- $cleanupResult = Request::makeRequest('admin/system/set_interface_ip', ['interface' => self::DEFAULT_INTERFACE]);
- $this->assertTrue($cleanupResult->wasSuccessful(), $cleanupResult->generatePHPUnitMessage());
- }
-
- public function testInvalidInterfaceIsRejected(): void
- {
- $result = Request::makeRequest('admin/system/set_interface_ip', ['interface' => '12345']);
- $this->assertFalse($result->wasSuccessful(), 'An invalid interface IP was accepted when it should have been rejected');
- }
-
- public function testInvalidCustomInterfaceIsRejected(): void
- {
- $result = Request::makeRequest('admin/system/set_interface_ip', ['custom_interface' => '!@#$%']);
- $this->assertFalse($result->wasSuccessful(), 'An invalid custom interface was accepted when it should have been rejected');
- }
-
- #[\PHPUnit\Framework\Attributes\DataProvider('maliciousInterfacePayloadProvider')]
- public function testMaliciousInterfaceIsRejected(string $payload): void
- {
- $result = Request::makeRequest('admin/system/set_interface_ip', ['interface' => $payload]);
- $this->assertFalse(
- $result->wasSuccessful(),
- "A malicious interface value was accepted when it should have been rejected: {$payload}"
- );
- }
-
- public static function maliciousInterfacePayloadProvider(): array
- {
- return [
- 'quote-escape' => ["x\"; echo 'pwned'; //"],
- 'pipe-command' => ['eth0|id'],
- 'backticks' => ['eth0`id`'],
- 'sub-shell' => ['eth0$(id)'],
- 'and-command' => ['eth0 && whoami'],
- 'redirect' => ['eth0 > /tmp/pwned'],
- 'path-traversal-unix' => ['../etc/passwd'],
- 'path-traversal-windows' => ['..\\..\\windows\\system32\\drivers\\etc\\hosts'],
- 'null-byte' => ["eth0\0evil"],
- 'long-string' => [str_repeat('a', 1024)],
- 'newline-injection' => ["eth0\nwhoami"],
- 'leading-trailing-space' => [' eth0 '],
- ];
- }
-
- public function testMaliciousCustomInterfaceIsRejected(): void
- {
- $result = Request::makeRequest('admin/system/set_interface_ip', ['custom_interface' => "x\"; passthru('id'); //"]);
- $this->assertFalse($result->wasSuccessful(), 'A malicious custom interface value was accepted when it should have been rejected');
- }
-
- public function testCustomInterfaceAcceptsValidHostname(): void
- {
- try {
- $result = Request::makeRequest('admin/system/set_interface_ip', ['custom_interface' => 'eth0']);
- $this->assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
- } finally {
- $this->resetInterfaceConfiguration();
- }
- }
-
- private function resetInterfaceConfiguration(): void
- {
- $resetResult = Request::makeRequest(
- 'admin/system/set_interface_ip',
- ['custom_interface' => '', 'interface' => self::DEFAULT_INTERFACE]
- );
- $this->assertTrue($resetResult->wasSuccessful(), $resetResult->generatePHPUnitMessage());
- }
-
- private function isIpLookupAvailable(): bool
- {
- $context = stream_context_create([
- 'http' => [
- 'method' => 'GET',
- 'timeout' => 2,
- ],
- ]);
-
- $lookupErrorMessage = null;
- $previousErrorHandler = set_error_handler(
- static function (
- int $severity,
- string $message,
- string $file = '',
- int $line = 0,
- ) use (&$lookupErrorMessage, &$previousErrorHandler): bool {
- if ($severity === E_WARNING) {
- $lookupErrorMessage = $message;
-
- return true;
- }
-
- if (is_callable($previousErrorHandler)) {
- return (bool) $previousErrorHandler($severity, $message, $file, $line);
- }
-
- // No previous user handler; allow PHP internal handling.
- return false;
- }
- );
-
- try {
- $response = file_get_contents('https://api.ipify.org', false, $context);
- } finally {
- restore_error_handler();
- }
-
- if ($response === false && $lookupErrorMessage !== null) {
- $singleLineLookupErrorMessage = str_replace(["\r", "\n"], ' ', $lookupErrorMessage);
- error_log('IP lookup availability check failed: ' . $singleLineLookupErrorMessage);
- }
-
- return $response !== false;
- }
-
- private function retryUntil(callable $operation, int $maxAttempts, int $delayMicroseconds): bool
- {
- for ($attempt = 0; $attempt < $maxAttempts; ++$attempt) {
- if ($operation()) {
return true;
}
- if ($attempt < $maxAttempts - 1) {
- usleep($delayMicroseconds);
+ if (is_callable($previousErrorHandler)) {
+ return (bool) $previousErrorHandler($severity, $message, $file, $line);
}
- }
- return false;
+ return false;
+ }
+ );
+
+ try {
+ $response = file_get_contents('https://api.ipify.org', false, $context);
+ } finally {
+ restore_error_handler();
}
+
+ if ($response === false && $lookupErrorMessage !== null) {
+ $singleLineLookupErrorMessage = str_replace(["\r", "\n"], ' ', $lookupErrorMessage);
+ error_log('IP lookup availability check failed: ' . $singleLineLookupErrorMessage);
+ }
+
+ return $response !== false;
}
+
+function systemResetInterfaceConfiguration(): void
+{
+ $resetResult = ApiClient::request(
+ 'admin/system/set_interface_ip',
+ ['custom_interface' => '', 'interface' => SYSTEM_DEFAULT_INTERFACE]
+ );
+ expect($resetResult->wasSuccessful())->toBeTrue();
+}
+
+test('clears cache', function (): void {
+ $beforeFirst = ApiClient::request('admin/system/error_reporting_enabled');
+ expect($beforeFirst->wasSuccessful())->toBeTrue()
+ ->and($beforeFirst->getResult())->toBeBool();
+
+ $beforeSecond = ApiClient::request('admin/system/error_reporting_enabled');
+ expect($beforeSecond->wasSuccessful())->toBeTrue()
+ ->and($beforeSecond->getResult())->toBeBool()
+ ->and($beforeSecond->getResult())->toBe($beforeFirst->getResult());
+
+ $result = ApiClient::request('admin/system/clear_cache');
+ expect($result->wasSuccessful())->toBeTrue()
+ ->and($result->getResult())->toBeBool();
+
+ $after = ApiClient::request('admin/system/error_reporting_enabled');
+ expect($after->wasSuccessful())->toBeTrue()
+ ->and($after->getResult())->toBeBool()
+ ->and($after->getResult())->toBe($beforeSecond->getResult());
+});
+
+test('toggles error reporting', function (): void {
+ $beforeResult = ApiClient::request('admin/system/error_reporting_enabled');
+ expect($beforeResult->wasSuccessful())->toBeTrue();
+ $before = $beforeResult->getResult();
+ expect($before)->toBeBool();
+
+ try {
+ $result = ApiClient::request('admin/system/toggle_error_reporting');
+ expect($result->wasSuccessful())->toBeTrue()
+ ->and($result->getResult())->toBeTrue();
+
+ $afterResponse = ApiClient::request('admin/system/error_reporting_enabled');
+ expect($afterResponse->wasSuccessful())->toBeTrue();
+ $after = $afterResponse->getResult();
+ expect($after)->toBeBool()
+ ->not->toBe($before);
+ } finally {
+ $currentResponse = ApiClient::request('admin/system/error_reporting_enabled');
+ expect($currentResponse->wasSuccessful())->toBeTrue();
+ $current = $currentResponse->getResult();
+ expect($current)->toBeBool();
+
+ if ($current !== $before) {
+ $restoreResult = ApiClient::request('admin/system/toggle_error_reporting');
+ expect($restoreResult->wasSuccessful())->toBeTrue()
+ ->and($restoreResult->getResult())->toBeTrue();
+ }
+ }
+});
+
+test('gets and sets network interfaces', function (): void {
+ $result = ApiClient::request('admin/system/get_interface_ips');
+ expect($result->wasSuccessful())->toBeTrue()
+ ->and($result->getResult())->toBeArray();
+
+ foreach ($result->getResult() as $ip) {
+ expect((bool) filter_var($ip, FILTER_VALIDATE_IP))->toBeTrue();
+ }
+
+ if (!systemIsIpLookupAvailable()) {
+ $this->markTestSkipped('Integration test requires ipify.org to be available.');
+ }
+
+ foreach ($result->getResult() as $ip) {
+ $testResult = ApiClient::request('admin/system/set_interface_ip', ['interface' => $ip]);
+ expect($testResult->wasSuccessful())->toBeTrue();
+
+ $isReady = systemRetryUntil(
+ static function (): bool {
+ $envResult = ApiClient::request('admin/system/env', ['ip' => true]);
+
+ return $envResult->wasSuccessful() && (bool) filter_var($envResult->getResult(), FILTER_VALIDATE_IP);
+ }
+ );
+
+ expect($isReady)->toBeTrue();
+ }
+
+ $cleanupResult = ApiClient::request('admin/system/set_interface_ip', ['interface' => SYSTEM_DEFAULT_INTERFACE]);
+ expect($cleanupResult->wasSuccessful())->toBeTrue();
+});
+
+test('rejects invalid interface', function (): void {
+ $result = ApiClient::request('admin/system/set_interface_ip', ['interface' => '12345']);
+ expect($result->wasSuccessful())->toBeFalse();
+});
+
+test('rejects invalid custom interface', function (): void {
+ $result = ApiClient::request('admin/system/set_interface_ip', ['custom_interface' => '!@#$%']);
+ expect($result->wasSuccessful())->toBeFalse();
+});
+
+test('rejects malicious interface values', function (string $payload): void {
+ $result = ApiClient::request('admin/system/set_interface_ip', ['interface' => $payload]);
+ expect($result->wasSuccessful())->toBeFalse();
+})->with([
+ 'quote-escape' => ["x\"; echo 'pwned'; //"],
+ 'pipe-command' => ['eth0|id'],
+ 'backticks' => ['eth0`id`'],
+ 'sub-shell' => ['eth0$(id)'],
+ 'and-command' => ['eth0 && whoami'],
+ 'redirect' => ['eth0 > /tmp/pwned'],
+ 'path-traversal-unix' => ['../etc/passwd'],
+ 'path-traversal-windows' => ['..\\..\\windows\\system32\\drivers\\etc\\hosts'],
+ 'null-byte' => ["eth0\0evil"],
+ 'long-string' => [str_repeat('a', 1024)],
+ 'newline-injection' => ["eth0\nwhoami"],
+ 'leading-trailing-space' => [' eth0 '],
+]);
+
+test('rejects malicious custom interface', function (): void {
+ $result = ApiClient::request('admin/system/set_interface_ip', ['custom_interface' => "x\"; passthru('id'); //"]);
+ expect($result->wasSuccessful())->toBeFalse();
+});
+
+test('accepts valid custom interface hostname', function (): void {
+ try {
+ $result = ApiClient::request('admin/system/set_interface_ip', ['custom_interface' => 'eth0']);
+ expect($result->wasSuccessful())->toBeTrue();
+ } finally {
+ systemResetInterfaceConfiguration();
+ }
+});
diff --git a/tests/Modules/System/GuestTest.php b/tests/Modules/System/GuestTest.php
index ef8230307..b789db4d7 100644
--- a/tests/Modules/System/GuestTest.php
+++ b/tests/Modules/System/GuestTest.php
@@ -2,38 +2,32 @@
declare(strict_types=1);
-namespace SystemTests;
+use Tests\Helpers\ApiClient;
-use APIHelper\Request;
-use PHPUnit\Framework\TestCase;
+test('template exists', function (): void {
+ $result = ApiClient::request('guest/system/template_exists', ['file' => 'layout_default.html.twig']);
-final class GuestTest extends TestCase
-{
- public function testTemplateExists(): void
- {
- $result = Request::makeRequest('guest/system/template_exists', ['file' => 'layout_default.html.twig']);
- $this->assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
- $this->assertTrue($result->getResult());
- }
+ expect($result->wasSuccessful())->toBeTrue()
+ ->and($result->getResult())->toBeTrue();
+});
- public function testTemplateDoesNotExist(): void
- {
- $result = Request::makeRequest('guest/system/template_exists', ['file' => 'thisfiledoesnotexist.txt']);
- $this->assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
- $this->assertFalse($result->getResult());
- }
+test('template does not exist', function (): void {
+ $result = ApiClient::request('guest/system/template_exists', ['file' => 'thisfiledoesnotexist.txt']);
- public function testPeriods(): void
- {
- $result = Request::makeRequest('guest/system/periods');
- $this->assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
- $this->assertIsArray($result->getResult());
- }
+ expect($result->wasSuccessful())->toBeTrue()
+ ->and($result->getResult())->toBeFalse();
+});
- public function testPhoneCodes(): void
- {
- $result = Request::makeRequest('guest/system/phone_codes');
- $this->assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
- $this->assertIsArray($result->getResult());
- }
-}
+test('gets periods', function (): void {
+ $result = ApiClient::request('guest/system/periods');
+
+ expect($result->wasSuccessful())->toBeTrue()
+ ->and($result->getResult())->toBeArray();
+});
+
+test('gets phone codes', function (): void {
+ $result = ApiClient::request('guest/system/phone_codes');
+
+ expect($result->wasSuccessful())->toBeTrue()
+ ->and($result->getResult())->toBeArray();
+});
diff --git a/tests/Modules/Theme/AdminTest.php b/tests/Modules/Theme/AdminTest.php
index c57bb21dc..46ec8a035 100644
--- a/tests/Modules/Theme/AdminTest.php
+++ b/tests/Modules/Theme/AdminTest.php
@@ -2,119 +2,94 @@
declare(strict_types=1);
-namespace ThemeTests;
+use Tests\Helpers\ApiClient;
-use APIHelper\Request;
-use PHPUnit\Framework\TestCase;
+const THEME_SEMANTIC_VERSION_PATTERN = '/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/';
-final class AdminTest extends TestCase
+function expectValidThemePayload(array $data): void
{
- private const string SEMANTIC_VERSION_PATTERN = '/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/';
-
- public function testGetCurrentClientTheme(): void
- {
- $result = Request::makeRequest('admin/theme/get_current');
- $this->assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
- $data = $result->getResult();
- $this->assertIsArray($data);
-
- $this->assertValidThemePayload($data);
+ foreach (['author', 'name', 'version', 'code', 'paths', 'hasSettings', 'url'] as $requiredKey) {
+ expect($data)->toHaveKey($requiredKey);
}
- public function testGetCurrentAdminTheme(): void
- {
- $result = Request::makeRequest('admin/theme/get_current', ['client' => false]);
- $this->assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
- $data = $result->getResult();
- $this->assertIsArray($data);
+ expect($data['name'])->toBeString()->not->toBe('')
+ ->and($data['version'])->toBeString()->not->toBe('')
+ ->and($data['version'])->toMatch(THEME_SEMANTIC_VERSION_PATTERN)
+ ->and($data['author'])->toBeString()->not->toBe('')
+ ->and($data['code'])->toBeString()->not->toBe('')
+ ->and($data['url'])->toBeString()->not->toBe('')
+ ->and($data['hasSettings'])->toBeBool()
+ ->and($data['paths'])->toBeArray()->not->toBeEmpty();
- $this->assertValidThemePayload($data);
+ foreach ($data['paths'] as $path) {
+ expect($path)->toBeString()->not->toBe('');
}
- public function testGetCurrentThemeWithInvalidClientParameterReturnsError(): void
- {
- $result = Request::makeRequest('admin/theme/get_current', ['client' => 'invalid']);
-
- $this->assertFalse($result->wasSuccessful(), 'Request should fail for an invalid "client" parameter type.');
-
- $errorMessage = $result->getErrorMessage();
- $this->assertIsString($errorMessage, 'Error message should be a string.');
- $this->assertNotSame('', trim($errorMessage), 'Error message should not be empty.');
+ if (array_key_exists('author_url', $data)) {
+ expect($data['author_url'])->toBeString()->not->toBe('');
}
- public function testAdminThemeRequestWithClientFalseFailureReturnsError(): void
- {
- $result = Request::makeRequest('admin/theme/non_existing_action', ['client' => false]);
- $this->assertSame(404, $result->getStatusCode(), 'Invalid admin theme action with client=false should return HTTP 404.');
- $this->assertFalse($result->wasSuccessful(), 'Invalid admin theme action with client=false should not be successful.');
- // API not-found actions/endpoints are mapped to error code 740 (see src/library/Api/Handler.php).
- $expectedNotFoundErrorCode = 740;
- $this->assertSame($expectedNotFoundErrorCode, $result->getErrorCode(), 'Invalid admin theme action with client=false should return the API not-found error code.');
-
- $errorMessage = $result->getErrorMessage();
- $this->assertIsString($errorMessage, 'Error message should be a string.');
- $this->assertNotSame('', trim($errorMessage), 'Error message should not be empty.');
+ if (array_key_exists('description', $data)) {
+ expect($data['description'])->toBeString();
}
- public function testInvalidThemeActionReturnsError(): void
- {
- $result = Request::makeRequest('admin/theme/non_existing_action');
- $this->assertSame(404, $result->getStatusCode(), 'Invalid theme action should return HTTP 404.');
- $this->assertFalse($result->wasSuccessful(), 'Invalid theme action should not be successful.');
- // API not-found actions/endpoints are mapped to error code 740 (see src/library/Api/Handler.php).
- $expectedNotFoundErrorCode = 740;
- $this->assertSame($expectedNotFoundErrorCode, $result->getErrorCode(), 'Invalid theme action should return the API not-found error code.');
-
- $errorMessage = $result->getErrorMessage();
- $this->assertIsString($errorMessage, 'Error message should be a string.');
- $this->assertNotSame('', trim($errorMessage), 'Error message should not be empty.');
+ if (array_key_exists('icon', $data)) {
+ expect($data['icon'])->toBeString();
}
- private function assertValidThemePayload(array $data): void
- {
- $requiredKeys = ['author', 'name', 'version', 'code', 'paths', 'hasSettings', 'url'];
- foreach ($requiredKeys as $requiredKey) {
- $this->assertArrayHasKey($requiredKey, $data, sprintf('Theme payload should contain the "%s" key.', $requiredKey));
- }
-
- $this->assertIsString($data['name']);
- $this->assertNotSame('', trim($data['name']), 'Theme name should not be empty.');
- $this->assertIsString($data['version']);
- $this->assertNotSame('', trim($data['version']), 'Theme version should not be empty.');
- $this->assertMatchesRegularExpression(
- self::SEMANTIC_VERSION_PATTERN,
- $data['version'],
- 'Theme version should follow semantic versioning (e.g., 1.2.3).'
- );
- $this->assertIsString($data['author']);
- $this->assertNotSame('', trim($data['author']), 'Theme author should not be empty.');
- $this->assertIsString($data['code']);
- $this->assertNotSame('', trim($data['code']), 'Theme code should not be empty.');
- $this->assertIsString($data['url']);
- $this->assertNotSame('', trim($data['url']), 'Theme URL should not be empty.');
- $this->assertIsBool($data['hasSettings']);
- $this->assertIsArray($data['paths']);
- $this->assertNotEmpty($data['paths'], 'Theme paths should not be empty.');
- foreach ($data['paths'] as $path) {
- $this->assertIsString($path);
- $this->assertNotSame('', trim($path), 'Theme paths should contain non-empty strings.');
- }
-
- if (array_key_exists('author_url', $data)) {
- $this->assertIsString($data['author_url']);
- $this->assertNotSame('', trim($data['author_url']), 'Theme author URL should not be empty when present.');
- }
-
- if (array_key_exists('description', $data)) {
- $this->assertIsString($data['description']);
- }
-
- if (array_key_exists('icon', $data)) {
- $this->assertIsString($data['icon']);
- }
-
- if (array_key_exists('markdown_attributes', $data)) {
- $this->assertIsArray($data['markdown_attributes']);
- }
+ if (array_key_exists('markdown_attributes', $data)) {
+ expect($data['markdown_attributes'])->toBeArray();
}
}
+
+test('gets current client theme', function (): void {
+ $result = ApiClient::request('admin/theme/get_current');
+ expect($result->wasSuccessful())->toBeTrue();
+
+ $data = $result->getResult();
+ expect($data)->toBeArray();
+ expectValidThemePayload($data);
+});
+
+test('gets current admin theme', function (): void {
+ $result = ApiClient::request('admin/theme/get_current', ['client' => false]);
+ expect($result->wasSuccessful())->toBeTrue();
+
+ $data = $result->getResult();
+ expect($data)->toBeArray();
+ expectValidThemePayload($data);
+});
+
+test('returns error when current theme client parameter is invalid', function (): void {
+ $result = ApiClient::request('admin/theme/get_current', ['client' => 'invalid']);
+
+ expect($result->wasSuccessful())->toBeFalse();
+
+ $errorMessage = $result->getErrorMessage();
+ expect($errorMessage)->toBeString()
+ ->and(trim($errorMessage))->not->toBe('');
+});
+
+test('returns not found for invalid admin theme action with client false', function (): void {
+ $result = ApiClient::request('admin/theme/non_existing_action', ['client' => false]);
+
+ expect($result->getStatusCode())->toBe(404)
+ ->and($result->wasSuccessful())->toBeFalse()
+ ->and($result->getErrorCode())->toBe(740);
+
+ $errorMessage = $result->getErrorMessage();
+ expect($errorMessage)->toBeString()
+ ->and(trim($errorMessage))->not->toBe('');
+});
+
+test('returns not found for invalid theme action', function (): void {
+ $result = ApiClient::request('admin/theme/non_existing_action');
+
+ expect($result->getStatusCode())->toBe(404)
+ ->and($result->wasSuccessful())->toBeFalse()
+ ->and($result->getErrorCode())->toBe(740);
+
+ $errorMessage = $result->getErrorMessage();
+ expect($errorMessage)->toBeString()
+ ->and(trim($errorMessage))->not->toBe('');
+});
diff --git a/tests/Pest.php b/tests/Pest.php
new file mode 100644
index 000000000..58655a4e8
--- /dev/null
+++ b/tests/Pest.php
@@ -0,0 +1,166 @@
+calls = [];
+ }
+
+ public function __call($method, $params): void
+ {
+ $this->calls[] = ["method" => $method, "params" => $params];
+ }
+ }
+ ');
+}
+
+// Redirect error_log to /dev/null during tests to prevent "PHPUnit controlled exception" clutter
+ini_set('error_log', '/dev/null');
+
+// Configure Unit tests base with Mockery integration
+uses(MockeryPHPUnitIntegration::class)
+ ->beforeEach(function (): void {
+ // Unit test setup
+ })
+->in('Unit');
+
+
+// Configure E2E tests - requires live instance with API access
+// Run with: ./vendor/bin/pest --testsuite=E2E
+// Requires APP_URL and TEST_API_KEY environment variables
+$appUrl = getenv('APP_URL');
+$testApiKey = getenv('TEST_API_KEY');
+
+if ($appUrl && $testApiKey) {
+ uses()
+ ->beforeEach(function () use ($appUrl, $testApiKey): void {
+ Tests\Helpers\ApiClient::setBaseUrl($appUrl);
+ Tests\Helpers\ApiClient::setApiKey($testApiKey);
+ })
+ ->in('E2E');
+}
+
+uses()
+ ->beforeEach(function (): void {
+ if (!getenv('APP_URL') || !getenv('TEST_API_KEY')) {
+ $this->markTestSkipped('API tests require APP_URL and TEST_API_KEY.');
+ }
+
+ Tests\Helpers\ApiClient::resetCookies();
+ })
+ ->in('Modules');
+
+/*
+|--------------------------------------------------------------------------
+| Expectations
+|--------------------------------------------------------------------------
+|
+| When you're writing tests, you often need to check that values meet certain
+| conditions. The "expect()" function gives you access to a set of useful
+| expectation methods.
+|
+*/
+
+expect()->extend('toBeDomain', function (): void {
+ $this->not->toBeEmpty();
+ expect($this->value)->toBeString();
+ expect(filter_var($this->value, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME))->not->toBeFalse();
+});
+
+expect()->extend('toBeEmail', function (): void {
+ $this->not->toBeEmpty();
+ expect($this->value)->toBeString();
+ expect(filter_var($this->value, FILTER_VALIDATE_EMAIL))->not->toBeFalse();
+});
+
+expect()->extend('toBeUrl', function (): void {
+ $this->not->toBeEmpty();
+ expect($this->value)->toBeString();
+ expect(filter_var($this->value, FILTER_VALIDATE_URL))->not->toBeFalse();
+});
+
+expect()->extend('toBeUuid', function (): void {
+ $this->not->toBeEmpty();
+ expect($this->value)->toBeString();
+ expect(preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i', $this->value))->toBe(1);
+});
+
+/*
+|--------------------------------------------------------------------------
+| Functions
+|--------------------------------------------------------------------------
+|
+| While Pest is very powerful out-of-the-box, you may have some testing code
+| specific to your project that you don't want to repeat in every file.
+| Here you can define custom helper functions and expect() extensions.
+|
+*/
diff --git a/tests/Unit/Box/CryptTest.php b/tests/Unit/Box/CryptTest.php
new file mode 100644
index 000000000..78dd9b783
--- /dev/null
+++ b/tests/Unit/Box/CryptTest.php
@@ -0,0 +1,21 @@
+encrypt($text, $key);
+ $decoded = $crypt->decrypt($encoded, $key);
+ expect($decoded)->toEqual($text);
+});
diff --git a/tests/Unit/Box/EventManagerTest.php b/tests/Unit/Box/EventManagerTest.php
new file mode 100644
index 000000000..ba463ef10
--- /dev/null
+++ b/tests/Unit/Box/EventManagerTest.php
@@ -0,0 +1,35 @@
+fire([]))->toBeFalse();
+});
+
+test('fire', function (): void {
+ $dbMock = Mockery::mock('Box_Database');
+ /** @var Mockery\Expectation $expectation */
+ $expectation = $dbMock->shouldReceive('getAll');
+ $expectation->atLeast()->once();
+ $expectation->andReturn([]);
+
+ $di = container();
+ $di['logger'] = new Box_Log();
+ $di['db'] = $dbMock;
+
+ $manager = new Box_EventManager();
+ $manager->setDi($di);
+
+ $manager->fire(['event' => 'onBeforeClientSignup']);
+});
diff --git a/tests/Unit/Box/PeriodTest.php b/tests/Unit/Box/PeriodTest.php
new file mode 100644
index 000000000..ef8773bdd
--- /dev/null
+++ b/tests/Unit/Box/PeriodTest.php
@@ -0,0 +1,62 @@
+getUnit())->toBe($expectedUnit);
+ expect($period->getQty())->toBe($expectedQty);
+ expect($period->getDays())->toEqual($expectedDays);
+ expect($period->getCode())->toBe($code);
+})->with(periodCodes());
+
+test('contains the quantity in period titles', function (): void {
+ expect((new Box_Period('1D'))->getCode())->toContain('1');
+ expect((new Box_Period('7D'))->getCode())->toContain('7');
+ expect((new Box_Period('1W'))->getCode())->toContain('1');
+ expect((new Box_Period('1M'))->getCode())->toContain('1');
+ expect((new Box_Period('1Y'))->getCode())->toContain('1');
+});
+
+test('calculates months correctly', function (): void {
+ expect((new Box_Period('1M'))->getMonths())->toBe(1);
+ expect((new Box_Period('3M'))->getMonths())->toBe(3);
+ expect((new Box_Period('6M'))->getMonths())->toBe(6);
+ expect((new Box_Period('1Y'))->getMonths())->toBe(12);
+});
+
+test('has expiration time in the future', function (): void {
+ $now = time();
+ $period = new Box_Period('1M');
+
+ $expiration = $period->getExpirationTime();
+ expect($expiration)->toBeGreaterThanOrEqual($now);
+ expect($expiration)->toBeLessThan($now + 35 * 24 * 60 * 60); // Should be less than 35 days
+});
+
+test('throws exception for invalid period code length', function (): void {
+ expect(fn (): \Box_Period => new Box_Period('1'))->toThrow(FOSSBilling\Exception::class, 'Invalid period code. Period definition must be 2 chars length');
+});
+
+test('throws exception for invalid period unit', function (): void {
+ expect(fn (): \Box_Period => new Box_Period('1Z'))->toThrow(FOSSBilling\Exception::class, 'Period Error. Unit Z is not defined');
+});
+
+test('throws exception for empty period code', function (): void {
+ expect(fn (): \Box_Period => new Box_Period(''))->toThrow(FOSSBilling\Exception::class, 'Invalid period code. Period definition must be 2 chars length');
+});
+
+test('throws exception for period code that is too long', function (): void {
+ expect(fn (): \Box_Period => new Box_Period('123'))->toThrow(FOSSBilling\Exception::class, 'Invalid period code. Period definition must be 2 chars length');
+});
diff --git a/tests/Unit/Box/TranslateTest.php b/tests/Unit/Box/TranslateTest.php
new file mode 100644
index 000000000..4f2514074
--- /dev/null
+++ b/tests/Unit/Box/TranslateTest.php
@@ -0,0 +1,41 @@
+setLocale($locale);
+ $result = $translateObj->getLocale();
+
+ expect($result)->toEqual($locale);
+});
+
+test('domain setter and getter', function (): void {
+ $translateObj = new Box_Translate();
+
+ $default = 'messages';
+ $result = $translateObj->getDomain();
+ expect($result)->toEqual($default);
+
+ $newDomain = 'admin';
+ $result = $translateObj->setDomain($newDomain)->getDomain();
+ expect($result)->toEqual($newDomain);
+});
+
+test('translate', function (): void {
+ $text = 'Translate ME';
+ $translateObj = new Box_Translate();
+ $translateObj->setup();
+ $result = __trans($text);
+
+ expect($result)->toEqual($text);
+});
diff --git a/tests/Unit/Box/TwigLoaderTest.php b/tests/Unit/Box/TwigLoaderTest.php
new file mode 100644
index 000000000..496fa9639
--- /dev/null
+++ b/tests/Unit/Box/TwigLoaderTest.php
@@ -0,0 +1,31 @@
+getSourceContext('mod_page_login.html.twig');
+ $test2 = $loader->getSourceContext('error.html.twig');
+
+ expect($test)->toBeObject();
+ expect($test2)->toBeObject();
+});
+
+test('exception', function (): void {
+ $loader = new TwigLoader(AppArea::CLIENT, PATH_THEMES . DIRECTORY_SEPARATOR . 'huraga');
+
+ expect(fn (): \Twig\Source => $loader->getSourceContext('mod_non_existing_settings.html.twig'))
+ ->toThrow(LoaderError::class);
+});
diff --git a/tests/Unit/FOSSBilling/FingerprintTest.php b/tests/Unit/FOSSBilling/FingerprintTest.php
new file mode 100644
index 000000000..13237f769
--- /dev/null
+++ b/tests/Unit/FOSSBilling/FingerprintTest.php
@@ -0,0 +1,69 @@
+getProperty('fingerprintProperties');
+ $prop->setAccessible(true);
+ $prop->setValue($stub, $properties);
+
+ return $stub;
+}
+
+test('matching fingerprints pass', function (): void {
+ $properties = [
+ 'browser' => ['source' => 'Chrome', 'weight' => 100],
+ 'os' => ['source' => 'Linux', 'weight' => 100],
+ 'ip' => ['source' => '10.0.0.1', 'weight' => 2],
+ ];
+ $stored = ['browser' => md5('Chrome'), 'os' => md5('Linux'), 'ip' => md5('10.0.0.1')];
+
+ expect(createFingerprint($properties)->checkFingerprint($stored))->toBeTrue();
+});
+
+test('properties absent in both fingerprints do not penalize the score', function (): void {
+ $currentProperties = [
+ 'browser' => ['source' => 'Chrome', 'weight' => 100],
+ 'os' => ['source' => 'Linux', 'weight' => 100],
+ 'ip' => ['source' => '10.0.0.1', 'weight' => 2],
+ 'platform' => ['source' => '', 'weight' => 100],
+ 'mobile' => ['source' => '', 'weight' => 2],
+ ];
+ $stored = [
+ 'browser' => md5('Chrome'),
+ 'os' => md5('Linux'),
+ 'ip' => md5('10.0.0.1'),
+ ];
+
+ expect(createFingerprint($currentProperties)->checkFingerprint($stored))->toBeTrue();
+});
+
+test('mismatched high-weight property rejects the fingerprint', function (): void {
+ $properties = [
+ 'browser' => ['source' => 'Chrome', 'weight' => 100],
+ ];
+ $stored = ['browser' => md5('Firefox')];
+
+ expect(createFingerprint($properties)->checkFingerprint($stored))->toBeFalse();
+});
+
+test('XOR property present only in stored fingerprint counts as differing', function (): void {
+ $properties = [
+ 'browser' => ['source' => 'Chrome', 'weight' => 100],
+ 'platform' => ['source' => '', 'weight' => 1],
+ ];
+ $stored = [
+ 'browser' => md5('Chrome'),
+ 'platform' => md5('"macOS"'),
+ ];
+
+ expect(createFingerprint($properties)->checkFingerprint($stored))->toBeFalse();
+});
diff --git a/tests/Unit/FOSSBilling/ModuleTest.php b/tests/Unit/FOSSBilling/ModuleTest.php
new file mode 100644
index 000000000..52725e707
--- /dev/null
+++ b/tests/Unit/FOSSBilling/ModuleTest.php
@@ -0,0 +1,67 @@
+shouldReceive('findOne');
+ $expectation->atLeast()->once();
+ $expectation->andReturn(null);
+
+ $di = container();
+ $di['db'] = $dbMock;
+
+ $mod = new Module('api');
+ $mod->setDi($di);
+ $array = $mod->getConfig();
+ expect($array)->toBe([]);
+});
+
+test('core mod', function (): void {
+ $mod = new Module('api');
+ expect($mod->isCore())->toBeTrue();
+
+ $array = $mod->getCoreModules();
+ expect($array)->toBeArray();
+
+ $mod = new Module('Cookieconsent');
+ expect($mod->isCore())->toBeFalse();
+});
+
+test('manifest', function (): void {
+ $di = container();
+ $di['url'] = new Box_Url();
+
+ $mod = new Module('Cookieconsent');
+ $mod->setDi($di);
+
+ $bool = $mod->hasManifest();
+ expect($bool)->toBeTrue();
+
+ $array = $mod->getManifest();
+ expect($array)->toBeArray();
+});
+
+test('get service sub', function (): void {
+ $mod = new Module('Invoice');
+ $subServiceName = 'transaction';
+
+ $di = container();
+ $mod->setDi($di);
+
+ $subService = $mod->getService($subServiceName);
+ expect($subService)->toBeInstanceOf(Box\Mod\Invoice\ServiceTransaction::class);
+});
diff --git a/tests/Unit/FOSSBilling/PasswordManagerTest.php b/tests/Unit/FOSSBilling/PasswordManagerTest.php
new file mode 100644
index 000000000..dc0b8416b
--- /dev/null
+++ b/tests/Unit/FOSSBilling/PasswordManagerTest.php
@@ -0,0 +1,62 @@
+setAlgo($algo);
+ $result = $boxPassword->getAlgo();
+ expect($result)->toEqual($algo);
+});
+
+test('set options', function (): void {
+ $boxPassword = new PasswordManager();
+ $options = [
+ 'cost' => 12,
+ ];
+ $boxPassword->setOptions($options);
+ $result = $boxPassword->getOptions();
+ expect($result)->toEqual($options);
+});
+
+test('hashing', function (): void {
+ $boxPassword = new PasswordManager();
+ $password = '123456';
+ $hash = $boxPassword->hashIt($password);
+ expect($hash)->toBeString();
+ expect($hash)->not->toBeEmpty();
+
+ $veryfied = $boxPassword->verify($password, $hash);
+ expect($veryfied)->toBeBool();
+ expect($veryfied)->toBeTrue();
+
+ $needRehashing = $boxPassword->needsRehash($hash);
+ expect($needRehashing)->toBeBool();
+ expect($needRehashing)->toBeFalse();
+});
+
+test('needs rehashing', function (): void {
+ $boxPassword = new PasswordManager();
+ $password = '123456';
+ $hash = $boxPassword->hashIt($password);
+ expect($hash)->toBeString();
+ expect($hash)->not->toBeEmpty();
+
+ $newOptions = ['cost' => 15];
+ $boxPassword->setOptions($newOptions);
+
+ $needRehashing = $boxPassword->needsRehash($hash);
+ expect($needRehashing)->toBeBool();
+ expect($needRehashing)->toBeTrue();
+});
diff --git a/tests/Unit/FOSSBilling/RateLimiterTest.php b/tests/Unit/FOSSBilling/RateLimiterTest.php
new file mode 100644
index 000000000..d9a76a1ee
--- /dev/null
+++ b/tests/Unit/FOSSBilling/RateLimiterTest.php
@@ -0,0 +1,122 @@
+shouldReceive('getClientIp')->andReturn($requestIp);
+ $di['request'] = $request;
+
+ $limiter = new class($whitelist) extends FOSSBilling\Security\RateLimiter {
+ public function __construct(private readonly array $whitelist)
+ {
+ }
+
+ protected function getConfig(): array
+ {
+ $config = self::getDefaultConfig();
+ $config['whitelist_ips'] = $this->whitelist;
+
+ return $config;
+ }
+ };
+ $limiter->setDi($di);
+
+ return $limiter;
+}
+
+test('consume allows until limit is reached', function (): void {
+ $limiter = createRateLimiter(requestIp: '1.1.1.1');
+ $subject = 'subject-' . uniqid('', true);
+
+ $first = $limiter->consume('api_guest', $subject, 100);
+ $second = $limiter->consume('api_guest', $subject);
+
+ expect($first->isLimited())->toBeFalse();
+ expect($first->getReason())->toBe(RateLimitResult::REASON_ALLOWED);
+ expect($second->isLimited())->toBeTrue();
+ expect($second->getReason())->toBe(RateLimitResult::REASON_LIMITED);
+});
+
+test('password reset policy reports limited result', function (): void {
+ $limiter = createRateLimiter(requestIp: '1.1.1.1');
+ $subject = 'subject-' . uniqid('', true);
+
+ $limiter->consume('client_password_reset_email', $subject, 3);
+ $second = $limiter->consume('client_password_reset_email', $subject);
+
+ expect($second->isLimited())->toBeTrue();
+ expect($second->getReason())->toBe(RateLimitResult::REASON_LIMITED);
+});
+
+test('consume or throw returns allowed result', function (): void {
+ $limiter = createRateLimiter(requestIp: '1.1.1.1');
+
+ $result = $limiter->consumeOrThrow('api_guest', 'subject-' . uniqid('', true));
+
+ expect($result->isLimited())->toBeFalse();
+ expect($result->getReason())->toBe(RateLimitResult::REASON_ALLOWED);
+});
+
+test('consume or throw raises rate limit exception', function (): void {
+ $limiter = createRateLimiter(requestIp: '1.1.1.1');
+ $subject = 'subject-' . uniqid('', true);
+ $limiter->consume('client_password_reset_email', $subject, 3);
+
+ try {
+ $limiter->consumeOrThrow('client_password_reset_email', $subject);
+ expect(true)->toBeFalse('Expected rate limit exception was not thrown.');
+ } catch (FOSSBilling\Security\RateLimitException $exception) {
+ expect($exception->getCode())->toBe(429);
+ expect($exception->getMessage())->toBe('Rate limit exceeded. Please try again later.');
+ expect($exception->getRateLimitResult()->getPolicy())->toBe('client_password_reset_email');
+ expect($exception->hasRetryAfter())->toBeTrue();
+ expect($exception->getRetryAfterSeconds())->toBeGreaterThan(0);
+ expect($exception->getRetryAfterSeconds())->toBeLessThanOrEqual(3600);
+ }
+});
+
+test('unknown policy throws exception', function (): void {
+ $limiter = createRateLimiter(requestIp: '1.1.1.1');
+
+ expect(fn () => $limiter->consume('unknown_policy', 'subject'))
+ ->toThrow(FOSSBilling\Exception::class, 'Rate limiter policy unknown_policy is not defined or invalid');
+});
+
+test('CIDR whitelist bypasses limiter', function (): void {
+ $limiter = createRateLimiter(requestIp: '10.0.0.5', whitelist: ['10.0.0.0/8']);
+
+ $result = $limiter->consume('api_guest', '10.0.0.5');
+
+ expect($result->isLimited())->toBeFalse();
+ expect($result->isBypassed())->toBeTrue();
+ expect($result->getReason())->toBe(RateLimitResult::REASON_WHITELISTED);
+});
+
+test('whitelist uses request IP for authenticated subjects', function (): void {
+ $limiter = createRateLimiter(requestIp: '10.0.0.5', whitelist: ['10.0.0.0/8']);
+
+ $result = $limiter->consume('api_authenticated_account', 'client:123');
+
+ expect($result->isLimited())->toBeFalse();
+ expect($result->isBypassed())->toBeTrue();
+ expect($result->getReason())->toBe(RateLimitResult::REASON_WHITELISTED);
+});
+
+test('non-whitelisted request IP limits authenticated subject', function (): void {
+ $limiter = createRateLimiter(requestIp: '1.1.1.1', whitelist: ['10.0.0.0/8']);
+
+ $limiter->consume('client_email_verification_resend_account', 'client:123', 3);
+ $second = $limiter->consume('client_email_verification_resend_account', 'client:123');
+
+ expect($second->isLimited())->toBeTrue();
+ expect($second->isBypassed())->toBeFalse();
+ expect($second->getReason())->toBe(RateLimitResult::REASON_LIMITED);
+});
diff --git a/tests/Unit/FOSSBilling/RequestFactoryTest.php b/tests/Unit/FOSSBilling/RequestFactoryTest.php
new file mode 100644
index 000000000..6d4fd4886
--- /dev/null
+++ b/tests/Unit/FOSSBilling/RequestFactoryTest.php
@@ -0,0 +1,211 @@
+afterEach(function (): void {
+ Request::setTrustedProxies([], 0);
+});
+
+test('configure does not trust forwarded proto without trusted proxy configuration', function (): void {
+ $request = Request::create('http://billing.example.com/admin', 'GET', [], [], [], [
+ 'REMOTE_ADDR' => '198.51.100.10',
+ 'HTTP_X_FORWARDED_PROTO' => 'https',
+ ]);
+
+ RequestFactory::configure($request);
+
+ expect($request->isSecure())->toBeFalse();
+});
+
+test('pre-config proxy config does not infer trust from local network forwarded headers', function (): void {
+ $proxyConfig = RequestFactory::getPreConfigProxyConfig([
+ 'REMOTE_ADDR' => '172.18.0.5',
+ 'HTTP_X_FORWARDED_PROTO' => 'https',
+ 'HTTP_X_FORWARDED_HOST' => 'billing.example.com',
+ ]);
+ $request = Request::create('http://internal.example/install/install.php', 'GET', [], [], [], [
+ 'REMOTE_ADDR' => '172.18.0.5',
+ 'HTTP_X_FORWARDED_PROTO' => 'https',
+ 'HTTP_X_FORWARDED_HOST' => 'billing.example.com',
+ ]);
+
+ RequestFactory::configure($request, $proxyConfig);
+
+ expect($proxyConfig)->toBe([]);
+ expect($request->isSecure())->toBeFalse();
+ expect($request->getHost())->toBe('internal.example');
+});
+
+test('pre-config proxy candidate reports forwarded header details without trusting them', function (): void {
+ $proxyCandidate = RequestFactory::getPreConfigProxyCandidate([
+ 'REMOTE_ADDR' => '172.18.0.5',
+ 'HTTP_X_FORWARDED_FOR' => '203.0.113.10',
+ 'HTTP_X_FORWARDED_PROTO' => 'https',
+ 'HTTP_X_FORWARDED_HOST' => 'billing.example.com',
+ ]);
+
+ expect($proxyCandidate)->toBe([
+ 'detected' => true,
+ 'remote_addr' => '172.18.0.5',
+ 'remote_addr_is_private' => true,
+ 'proxies' => ['172.18.0.5'],
+ 'headers' => 'x_forwarded',
+ 'header_values' => [
+ 'X-Forwarded-For' => '203.0.113.10',
+ 'X-Forwarded-Host' => 'billing.example.com',
+ 'X-Forwarded-Proto' => 'https',
+ ],
+ 'suggested_url' => 'https://billing.example.com/',
+ ]);
+});
+
+test('pre-config proxy candidate ignores empty forwarded headers', function (): void {
+ $proxyCandidate = RequestFactory::getPreConfigProxyCandidate([
+ 'REMOTE_ADDR' => '172.18.0.5',
+ 'HTTP_FORWARDED' => '',
+ ]);
+
+ expect($proxyCandidate)->toBe([]);
+});
+
+test('pre-config proxy config does not trust forwarded headers from public address', function (): void {
+ $proxyConfig = RequestFactory::getPreConfigProxyConfig([
+ 'REMOTE_ADDR' => '198.51.100.10',
+ 'HTTP_X_FORWARDED_PROTO' => 'https',
+ 'HTTP_X_FORWARDED_HOST' => 'billing.example.com',
+ ]);
+ $request = Request::create('http://internal.example/install/install.php', 'GET', [], [], [], [
+ 'REMOTE_ADDR' => '198.51.100.10',
+ 'HTTP_X_FORWARDED_PROTO' => 'https',
+ 'HTTP_X_FORWARDED_HOST' => 'billing.example.com',
+ ]);
+
+ RequestFactory::configure($request, $proxyConfig);
+
+ expect($proxyConfig)->toBe([]);
+ expect($request->isSecure())->toBeFalse();
+ expect($request->getHost())->toBe('internal.example');
+});
+
+test('configure trusts forwarded proto from configured trusted proxy', function (): void {
+ $request = Request::create('http://billing.example.com/admin', 'GET', [], [], [], [
+ 'REMOTE_ADDR' => '198.51.100.10',
+ 'HTTP_X_FORWARDED_PROTO' => 'https',
+ 'HTTP_X_FORWARDED_HOST' => 'billing.example.com',
+ ]);
+
+ RequestFactory::configure($request, [
+ 'enabled' => true,
+ 'proxies' => ['198.51.100.10'],
+ 'headers' => 'x_forwarded',
+ ]);
+
+ expect($request->isSecure())->toBeTrue();
+ expect($request->getHost())->toBe('billing.example.com');
+});
+
+test('configure ignores forwarded proto from untrusted proxy', function (): void {
+ $request = Request::create('http://billing.example.com/admin', 'GET', [], [], [], [
+ 'REMOTE_ADDR' => '198.51.100.99',
+ 'HTTP_X_FORWARDED_PROTO' => 'https',
+ ]);
+
+ RequestFactory::configure($request, [
+ 'enabled' => true,
+ 'proxies' => ['198.51.100.10'],
+ 'headers' => 'x_forwarded',
+ ]);
+
+ expect($request->isSecure())->toBeFalse();
+});
+
+test('configure supports forwarded header mode', function (): void {
+ $request = Request::create('http://internal.example/admin', 'GET', [], [], [], [
+ 'REMOTE_ADDR' => '198.51.100.10',
+ 'HTTP_FORWARDED' => 'for=203.0.113.9;host=billing.example.com;proto=https',
+ ]);
+
+ RequestFactory::configure($request, [
+ 'enabled' => true,
+ 'proxies' => ['198.51.100.10'],
+ 'headers' => 'forwarded',
+ ]);
+
+ expect($request->isSecure())->toBeTrue();
+ expect($request->getHost())->toBe('billing.example.com');
+});
+
+test('configure supports AWS ELB header mode', function (): void {
+ $request = Request::create('http://internal.example/admin', 'GET', [], [], [], [
+ 'REMOTE_ADDR' => '198.51.100.10',
+ 'HTTP_X_FORWARDED_FOR' => '203.0.113.9',
+ 'HTTP_X_FORWARDED_HOST' => 'billing.example.com',
+ 'HTTP_X_FORWARDED_PORT' => '443',
+ 'HTTP_X_FORWARDED_PROTO' => 'https',
+ ]);
+
+ RequestFactory::configure($request, [
+ 'enabled' => true,
+ 'proxies' => ['198.51.100.10'],
+ 'headers' => 'aws_elb',
+ ]);
+
+ expect($request->getClientIp())->toBe('203.0.113.9');
+ expect($request->isSecure())->toBeTrue();
+ expect($request->getHost())->toBe('internal.example');
+});
+
+test('configure supports Traefik header mode', function (): void {
+ $request = Request::create('http://internal.example/admin', 'GET', [], [], [], [
+ 'REMOTE_ADDR' => '198.51.100.10',
+ 'HTTP_X_FORWARDED_FOR' => '203.0.113.9',
+ 'HTTP_X_FORWARDED_HOST' => 'billing.example.com',
+ 'HTTP_X_FORWARDED_PORT' => '443',
+ 'HTTP_X_FORWARDED_PREFIX' => '/billing',
+ 'HTTP_X_FORWARDED_PROTO' => 'https',
+ ]);
+
+ RequestFactory::configure($request, [
+ 'enabled' => true,
+ 'proxies' => ['198.51.100.10'],
+ 'headers' => 'traefik',
+ ]);
+
+ expect($request->getClientIp())->toBe('203.0.113.9');
+ expect($request->isSecure())->toBeTrue();
+ expect($request->getHost())->toBe('billing.example.com');
+ expect($request->getBaseUrl())->toBe('/billing');
+});
+
+test('configure rejects unknown trusted proxy header mode', function (): void {
+ $request = Request::create('http://billing.example.com/admin');
+
+ expect(fn () => RequestFactory::configure($request, [
+ 'enabled' => true,
+ 'proxies' => ['198.51.100.10'],
+ 'headers' => 'custom',
+ ]))->toThrow(InvalidArgumentException::class, 'Invalid trusted proxy header configuration.');
+});
+
+test('normalize route path rewrites legacy custom page route', function (): void {
+ $request = Request::create('http://billing.example.com/page/about-us');
+
+ $path = RequestFactory::normalizeRoutePath($request);
+
+ expect($path)->toBe('/custompages/about-us');
+ expect(RequestFactory::getRoutePath($request))->toBe('/custompages/about-us');
+});
+
+test('normalize route path rejects invalid path and falls back to root', function (): void {
+ $request = Request::create('http://billing.example.com/admin', 'GET', [
+ '_url' => "invalid\x00path",
+ ]);
+
+ $path = RequestFactory::normalizeRoutePath($request);
+
+ expect($path)->toBe('/');
+ expect(RequestFactory::getRoutePath($request))->toBe('/');
+});
diff --git a/tests/Unit/FOSSBilling/SessionTest.php b/tests/Unit/FOSSBilling/SessionTest.php
new file mode 100644
index 000000000..13ea4265a
--- /dev/null
+++ b/tests/Unit/FOSSBilling/SessionTest.php
@@ -0,0 +1,59 @@
+getMethod($method);
+
+ return $methodReflection->invokeArgs($instance, $args);
+}
+
+test('obsolete session is detected', function (): void {
+ $session = createSession();
+
+ $result = invokePrivate($session, 'isObsoleteSession', [[
+ 'fb_session_obsolete' => true,
+ ]]);
+
+ expect($result)->toBeTrue();
+});
+
+test('obsolete session without expiry is expired', function (): void {
+ $session = createSession();
+
+ $result = invokePrivate($session, 'isObsoleteSessionExpired', [[
+ 'fb_session_obsolete' => true,
+ ], 100]);
+
+ expect($result)->toBeTrue();
+});
+
+test('obsolete session expiry honors grace window', function (): void {
+ $session = createSession();
+
+ $active = invokePrivate($session, 'isObsoleteSessionExpired', [[
+ 'fb_session_obsolete' => true,
+ 'fb_session_obsolete_expires_at' => 150,
+ ], 100]);
+
+ $expired = invokePrivate($session, 'isObsoleteSessionExpired', [[
+ 'fb_session_obsolete' => true,
+ 'fb_session_obsolete_expires_at' => 150,
+ ], 151]);
+
+ expect($active)->toBeFalse();
+ expect($expired)->toBeTrue();
+});
diff --git a/tests/Unit/FOSSBilling/ToolsTest.php b/tests/Unit/FOSSBilling/ToolsTest.php
new file mode 100644
index 000000000..70ac207ad
--- /dev/null
+++ b/tests/Unit/FOSSBilling/ToolsTest.php
@@ -0,0 +1,115 @@
+ [
+ // [input, expected_output, allowSafeHtml]
+ ['', '', false],
+ ["Hello\0World", 'HelloWorld', false],
+ ['', 'alert("xss")', false], // Text content HTML-encoded
+ ['Hello
', 'Hello', false],
+ ['Hello
', 'Hello
', true], // Safe HTML preserved
+ ['Test
', 'Test
', true], // img converted to self-closing
+]);
+
+test('sanitize content', function (string $input, string $expected, bool $allowSafeHtml): void {
+ $result = FOSSBilling\Tools::sanitizeContent($input, $allowSafeHtml);
+ expect($result)->toEqual($expected);
+})->with('sanitizeContentProvider');
+
+test('sanitize content removes null bytes', function (): void {
+ $input = "Hello\0World";
+ $result = FOSSBilling\Tools::sanitizeContent($input, false);
+ expect($result)->not->toContain("\0");
+ expect($result)->toBe('HelloWorld');
+});
+
+test('sanitize content removes script tags', function (): void {
+ $input = 'Hello
';
+ $result = FOSSBilling\Tools::sanitizeContent($input, true);
+ expect($result)->not->toContain('