From 7859afca8065677932dd42e74c74a54f23919e8a Mon Sep 17 00:00:00 2001 From: mstfkhazaal <47450090+mstfkhazaal@users.noreply.github.com> Date: Thu, 29 Oct 2026 08:16:01 +0200 Subject: [PATCH 01/45] feat: establish standalone subscription package and fail-closed Gate authorization --- .github/workflows/tests.yml | 23 ++++++ composer.json | 81 ++++++++++++------- docs/SECURITY-MIGRATION.md | 29 +++++++ docs/UNIVERSAL-BILLING.md | 53 ++++++++++++ phpunit.xml | 18 +++++ src/Policies/DiscountPolicy.php | 26 +++--- src/Policies/PlanPolicy.php | 26 +++--- src/Policies/SubscriptionPolicy.php | 26 +++--- src/Support/SubbasePermission.php | 54 ++++++------- tests/Authorization/SubbasePermissionTest.php | 49 +++++++++++ tests/TestCase.php | 16 ++++ 11 files changed, 302 insertions(+), 99 deletions(-) create mode 100644 .github/workflows/tests.yml create mode 100644 docs/SECURITY-MIGRATION.md create mode 100644 docs/UNIVERSAL-BILLING.md create mode 100644 phpunit.xml create mode 100644 tests/Authorization/SubbasePermissionTest.php create mode 100644 tests/TestCase.php diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..6a56830 --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,23 @@ +name: Package Tests +on: + push: + branches: [main, 'feat/**', 'fix/**'] + pull_request: +permissions: + contents: read +jobs: + unit: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: shivammathur/setup-php@v2 + with: + php-version: '8.4' + extensions: mbstring, dom, sqlite3, pdo_sqlite + coverage: none + tools: composer:v2 + - run: composer validate --no-check-publish --strict + - run: composer update --no-interaction --prefer-dist + - run: vendor/bin/phpunit + - run: vendor/bin/pint --test + - run: composer audit --no-dev diff --git a/composer.json b/composer.json index ca757b3..7a6e7db 100644 --- a/composer.json +++ b/composer.json @@ -1,32 +1,53 @@ { - "name": "nafiswatsiq/subbase", - "description": "Filament plugin for advanced subscriptions", - "type": "library", - "license": "MIT", - "keywords": ["filament", "subscription", "laravel", "saas", "billing", "multi-currency"], - "homepage": "https://github.com/nafiswatsiq/subbase", - "authors": [ - { - "name": "Nafis Watsiq", - "email": "nafiswatsiq@gmail.com" + "name": "nafiswatsiq/subbase", + "description": "Filament plugin for advanced subscriptions", + "type": "library", + "license": "MIT", + "keywords": [ + "filament", + "subscription", + "laravel", + "saas", + "billing", + "multi-currency" + ], + "homepage": "https://github.com/nafiswatsiq/subbase", + "authors": [ + { + "name": "Nafis Watsiq", + "email": "nafiswatsiq@gmail.com" + } + ], + "require": { + "php": "^8.2", + "filament/filament": "^5.0", + "laravelcm/laravel-subscriptions": "^1.8", + "spatie/laravel-package-tools": "^1.16" + }, + "autoload": { + "psr-4": { + "Nafiswatsiq\\Subbase\\": "src/" + } + }, + "extra": { + "laravel": { + "providers": [ + "Nafiswatsiq\\Subbase\\SubbaseServiceProvider" + ] + } + }, + "require-dev": { + "orchestra/testbench": "^11.3", + "phpunit/phpunit": "^12.5", + "laravel/pint": "^1.27" + }, + "autoload-dev": { + "psr-4": { + "Nafiswatsiq\\Subbase\\Tests\\": "tests/" + } + }, + "scripts": { + "test": "phpunit", + "lint": "pint --test" } - ], - "require": { - "php": "^8.2", - "filament/filament": "^5.0", - "laravelcm/laravel-subscriptions": "^1.8", - "spatie/laravel-package-tools": "^1.16" - }, - "autoload": { - "psr-4": { - "Nafiswatsiq\\Subbase\\": "src/" - } - }, - "extra": { - "laravel": { - "providers": [ - "Nafiswatsiq\\Subbase\\SubbaseServiceProvider" - ] - } - } -} \ No newline at end of file +} diff --git a/docs/SECURITY-MIGRATION.md b/docs/SECURITY-MIGRATION.md new file mode 100644 index 0000000..e0defc1 --- /dev/null +++ b/docs/SECURITY-MIGRATION.md @@ -0,0 +1,29 @@ +# Permission hardening: upgrade note + +The original Subbase permission helper returned `true` when Spatie Permission was absent, regardless of authenticated status/assigned abilities. That behavior was insecure for any billing admin panel. + +**This branch intentionally changes it to deny by default** using Laravel's native `Gate::forUser(...)->allows(...)`. This should be treated as a breaking behavior change pending a new major version. + +## Legacy consumers + +Do not deploy before confirming the app already grants the configured ability names. The legacy fallback for blank `subbase.permissions.plan` uses Shield-like names such as `ViewAny:Plan`, `Create:Plan`, and `View:Subscription`; Spatie/Shield may register those through Laravel Gate. + +Without Spatie, define the abilities in your AuthServiceProvider or app boot: + +```php +use Illuminate\Support\Facades\Gate; + +Gate::define('manage billing plans', fn ($actor): bool => $actor->is_billing_admin); +``` + +Then set `subbase.permissions.plan` to `manage billing plans`, and likewise for other resources. Ensure more specific per-record checks for tenant data; this package does not yet provide automatic tenant scoping. + +## Smoke tests + +1. Unauthenticated and authenticated unauthorized users cannot open plans/subscription pages. +2. Authorized user sees only records allowed by the application's tenant policy. +3. With Spatie removed, native Laravel Gate can grant an explicit permission. +4. Passing a different actor to policy must not use the logged-in session actor. +5. Existing installations' plan/feature/subscription records remain unchanged. + +No migrations are introduced by this change. diff --git a/docs/UNIVERSAL-BILLING.md b/docs/UNIVERSAL-BILLING.md new file mode 100644 index 0000000..b2451bf --- /dev/null +++ b/docs/UNIVERSAL-BILLING.md @@ -0,0 +1,53 @@ +# Universal subscription platform — package contract + +**Status:** Fenix-owned upstream fork, reusable independently of Fenix Accounts. This document is a versioned project direction, not a claim of feature completion. + +## Product principles + +- No mandatory Fenix Account, ZITADEL, Fenix organization schema, or Fenix-specific global scopes. +- One subscription engine across Laravel products: local installation per app or a dedicated subscription service via an optional API adapter. +- Billable subjects can be **any Eloquent model** using `Laravelcm\Subscriptions\Traits\HasPlanSubscriptions`, including User, Organization, School, Tenant, or Project. The current model relationship comes from laravelcm; the package should not create another subscription model merely for tenant support. +- Optional Filament 5 management UI. Headless usage remains valid; future versions may extract core billing without Filament. +- The same independent package supports single-tenant and multi-tenant applications. **Filament authorization does not by itself isolate tenant records**; applications must provide tenant-aware query scoping and policies. +- Subbase handles subscription plans, features, trial periods, lifecycle, discounts, plan currency prices and usage counters. +- Subbase Payment handles gateway checkout, verification, subscription settlement, payment history and refunds; the **consumer application's financial ledger** remains separate for non-subscription charges. + +## Security and money rules + +- Permission checks are fail-closed through Laravel Gate, whether or not Spatie Permission is installed. Filament resource policies must use the actual actor, not a session-global assumption. +- A role/permission grant does **not** confer access to a different tenant's record. Each app must implement record-level tenant scope; a reusable tenant-resolver contract with strict fail-closed defaults is on the roadmap. +- Never use PHP floating-point numbers for financial posting. Replace Plan/Discount float calculations with exact decimal arithmetic in a separately versioned migration and API upgrade, followed by rounding fixtures for 0/2/3 decimal currencies. +- Payment gateways must verify raw webhook signatures, event ID, account/merchant, transaction ownership, amount and currency before settling subscriptions. Deduplicate events atomically. +- Preserve historical subscription, price, payment and discount snapshots after they are sold. + +## Distribution and upgrade strategy + +- For compatibility, initial patches **retain** the `nafiswatsiq/subbase` Composer package identity and `Nafiswatsiq\Subbase\` PHP namespace. The fork is at `fnx-software/subbase`. +- Review and test future distribution under `fnx-software/subbase` with a documented Composer migration. Do not ship both identities in the same app or silently mark them as replaced. +- Keep existing production installs of CRM and Zeno on pinned versions until the compatibility suite passes. +- A matching release of `fnx-software/subbase-payment` must be tested with every breaking Subbase release. +- Keep MIT license and original author attribution. + +## Supported modes (design target) + +| Mode | Owner | Access / subscription lifecycle | +| --- | --- | --- | +| Standalone user SaaS | User | Local auth; user subscriptions | +| B2B SaaS | Organization or Tenant | App-specific membership policies and tenant resolver | +| School SaaS | School | School billing owner, not necessarily creator user | +| Central billing service | Custom business subject | API with explicit external identity references | +| Fenix Apps | Organization | Optional Fenix Accounts adapter; zero core dependency | + +## Roadmap + +1. Fail-closed resource permissions and PHP/Filament 5 Testbench suite. +2. Tenant-aware resource and action authorization with a configurable resolver and explicit denial when enabled but unresolved. +3. Model-agnostic subscription checkout and safe renew/switch/cancel with idempotency and lifecycle tests. +4. Accurate money/discount math, subscription pricing snapshots and multiple currency scales. +5. Gateway abstraction, verified webhooks, payment ledger, refunds, chargebacks, retries and reconciliations. +6. Dashboard and public checkout UX, languages ar/en/fr, headless APIs, package distribution, semver, migration guide. +7. Tested integrations with a standalone demo application, Zeno, CRM and optional Fenix Accounts. + +## No API / migration claims yet + +Version 2 is not released. No installed app is migrated by this branch. Run `composer test`, Composer audit, package migrations and a real application integration suite before merging. diff --git a/phpunit.xml b/phpunit.xml new file mode 100644 index 0000000..86b4708 --- /dev/null +++ b/phpunit.xml @@ -0,0 +1,18 @@ + + + + + tests + + + + + + + + + + diff --git a/src/Policies/DiscountPolicy.php b/src/Policies/DiscountPolicy.php index 6f0023c..5c28d5e 100644 --- a/src/Policies/DiscountPolicy.php +++ b/src/Policies/DiscountPolicy.php @@ -4,7 +4,7 @@ namespace Nafiswatsiq\Subbase\Policies; -use Illuminate\Foundation\Auth\User as AuthUser; +use Illuminate\Contracts\Auth\Authenticatable as AuthUser; use Nafiswatsiq\Subbase\Models\Discount; use Nafiswatsiq\Subbase\Support\SubbasePermission; use Illuminate\Auth\Access\HandlesAuthorization; @@ -15,61 +15,61 @@ class DiscountPolicy public function viewAny(AuthUser $authUser): bool { - return SubbasePermission::allows(config('subbase.permissions.discount'), 'viewAny', Discount::class); + return SubbasePermission::allows(config('subbase.permissions.discount'), 'viewAny', Discount::class, $authUser); } public function view(AuthUser $authUser, Discount $discount): bool { - return SubbasePermission::allows(config('subbase.permissions.discount'), 'view', Discount::class); + return SubbasePermission::allows(config('subbase.permissions.discount'), 'view', Discount::class, $authUser); } public function create(AuthUser $authUser): bool { - return SubbasePermission::allows(config('subbase.permissions.discount'), 'create', Discount::class); + return SubbasePermission::allows(config('subbase.permissions.discount'), 'create', Discount::class, $authUser); } public function update(AuthUser $authUser, Discount $discount): bool { - return SubbasePermission::allows(config('subbase.permissions.discount'), 'update', Discount::class); + return SubbasePermission::allows(config('subbase.permissions.discount'), 'update', Discount::class, $authUser); } public function delete(AuthUser $authUser, Discount $discount): bool { - return SubbasePermission::allows(config('subbase.permissions.discount'), 'delete', Discount::class); + return SubbasePermission::allows(config('subbase.permissions.discount'), 'delete', Discount::class, $authUser); } public function deleteAny(AuthUser $authUser): bool { - return SubbasePermission::allows(config('subbase.permissions.discount'), 'deleteAny', Discount::class); + return SubbasePermission::allows(config('subbase.permissions.discount'), 'deleteAny', Discount::class, $authUser); } public function restore(AuthUser $authUser, Discount $discount): bool { - return SubbasePermission::allows(config('subbase.permissions.discount'), 'restore', Discount::class); + return SubbasePermission::allows(config('subbase.permissions.discount'), 'restore', Discount::class, $authUser); } public function forceDelete(AuthUser $authUser, Discount $discount): bool { - return SubbasePermission::allows(config('subbase.permissions.discount'), 'forceDelete', Discount::class); + return SubbasePermission::allows(config('subbase.permissions.discount'), 'forceDelete', Discount::class, $authUser); } public function forceDeleteAny(AuthUser $authUser): bool { - return SubbasePermission::allows(config('subbase.permissions.discount'), 'forceDeleteAny', Discount::class); + return SubbasePermission::allows(config('subbase.permissions.discount'), 'forceDeleteAny', Discount::class, $authUser); } public function restoreAny(AuthUser $authUser): bool { - return SubbasePermission::allows(config('subbase.permissions.discount'), 'restoreAny', Discount::class); + return SubbasePermission::allows(config('subbase.permissions.discount'), 'restoreAny', Discount::class, $authUser); } public function replicate(AuthUser $authUser, Discount $discount): bool { - return SubbasePermission::allows(config('subbase.permissions.discount'), 'replicate', Discount::class); + return SubbasePermission::allows(config('subbase.permissions.discount'), 'replicate', Discount::class, $authUser); } public function reorder(AuthUser $authUser): bool { - return SubbasePermission::allows(config('subbase.permissions.discount'), 'reorder', Discount::class); + return SubbasePermission::allows(config('subbase.permissions.discount'), 'reorder', Discount::class, $authUser); } } \ No newline at end of file diff --git a/src/Policies/PlanPolicy.php b/src/Policies/PlanPolicy.php index 0a9d077..8fc2326 100644 --- a/src/Policies/PlanPolicy.php +++ b/src/Policies/PlanPolicy.php @@ -4,7 +4,7 @@ namespace Nafiswatsiq\Subbase\Policies; -use Illuminate\Foundation\Auth\User as AuthUser; +use Illuminate\Contracts\Auth\Authenticatable as AuthUser; use Nafiswatsiq\Subbase\Models\Plan; use Nafiswatsiq\Subbase\Support\SubbasePermission; use Illuminate\Auth\Access\HandlesAuthorization; @@ -15,61 +15,61 @@ class PlanPolicy public function viewAny(AuthUser $authUser): bool { - return SubbasePermission::allows(config('subbase.permissions.plan'), 'viewAny', Plan::class); + return SubbasePermission::allows(config('subbase.permissions.plan'), 'viewAny', Plan::class, $authUser); } public function view(AuthUser $authUser, Plan $plan): bool { - return SubbasePermission::allows(config('subbase.permissions.plan'), 'view', Plan::class); + return SubbasePermission::allows(config('subbase.permissions.plan'), 'view', Plan::class, $authUser); } public function create(AuthUser $authUser): bool { - return SubbasePermission::allows(config('subbase.permissions.plan'), 'create', Plan::class); + return SubbasePermission::allows(config('subbase.permissions.plan'), 'create', Plan::class, $authUser); } public function update(AuthUser $authUser, Plan $plan): bool { - return SubbasePermission::allows(config('subbase.permissions.plan'), 'update', Plan::class); + return SubbasePermission::allows(config('subbase.permissions.plan'), 'update', Plan::class, $authUser); } public function delete(AuthUser $authUser, Plan $plan): bool { - return SubbasePermission::allows(config('subbase.permissions.plan'), 'delete', Plan::class); + return SubbasePermission::allows(config('subbase.permissions.plan'), 'delete', Plan::class, $authUser); } public function deleteAny(AuthUser $authUser): bool { - return SubbasePermission::allows(config('subbase.permissions.plan'), 'deleteAny', Plan::class); + return SubbasePermission::allows(config('subbase.permissions.plan'), 'deleteAny', Plan::class, $authUser); } public function restore(AuthUser $authUser, Plan $plan): bool { - return SubbasePermission::allows(config('subbase.permissions.plan'), 'restore', Plan::class); + return SubbasePermission::allows(config('subbase.permissions.plan'), 'restore', Plan::class, $authUser); } public function forceDelete(AuthUser $authUser, Plan $plan): bool { - return SubbasePermission::allows(config('subbase.permissions.plan'), 'forceDelete', Plan::class); + return SubbasePermission::allows(config('subbase.permissions.plan'), 'forceDelete', Plan::class, $authUser); } public function forceDeleteAny(AuthUser $authUser): bool { - return SubbasePermission::allows(config('subbase.permissions.plan'), 'forceDeleteAny', Plan::class); + return SubbasePermission::allows(config('subbase.permissions.plan'), 'forceDeleteAny', Plan::class, $authUser); } public function restoreAny(AuthUser $authUser): bool { - return SubbasePermission::allows(config('subbase.permissions.plan'), 'restoreAny', Plan::class); + return SubbasePermission::allows(config('subbase.permissions.plan'), 'restoreAny', Plan::class, $authUser); } public function replicate(AuthUser $authUser, Plan $plan): bool { - return SubbasePermission::allows(config('subbase.permissions.plan'), 'replicate', Plan::class); + return SubbasePermission::allows(config('subbase.permissions.plan'), 'replicate', Plan::class, $authUser); } public function reorder(AuthUser $authUser): bool { - return SubbasePermission::allows(config('subbase.permissions.plan'), 'reorder', Plan::class); + return SubbasePermission::allows(config('subbase.permissions.plan'), 'reorder', Plan::class, $authUser); } } \ No newline at end of file diff --git a/src/Policies/SubscriptionPolicy.php b/src/Policies/SubscriptionPolicy.php index 48c1212..93042cc 100644 --- a/src/Policies/SubscriptionPolicy.php +++ b/src/Policies/SubscriptionPolicy.php @@ -4,7 +4,7 @@ namespace Nafiswatsiq\Subbase\Policies; -use Illuminate\Foundation\Auth\User as AuthUser; +use Illuminate\Contracts\Auth\Authenticatable as AuthUser; use Nafiswatsiq\Subbase\Models\Subscription; use Nafiswatsiq\Subbase\Support\SubbasePermission; use Illuminate\Auth\Access\HandlesAuthorization; @@ -15,61 +15,61 @@ class SubscriptionPolicy public function viewAny(AuthUser $authUser): bool { - return SubbasePermission::allows(config('subbase.permissions.subscription'), 'viewAny', Subscription::class); + return SubbasePermission::allows(config('subbase.permissions.subscription'), 'viewAny', Subscription::class, $authUser); } public function view(AuthUser $authUser, Subscription $subscription): bool { - return SubbasePermission::allows(config('subbase.permissions.subscription'), 'view', Subscription::class); + return SubbasePermission::allows(config('subbase.permissions.subscription'), 'view', Subscription::class, $authUser); } public function create(AuthUser $authUser): bool { - return SubbasePermission::allows(config('subbase.permissions.subscription'), 'create', Subscription::class); + return SubbasePermission::allows(config('subbase.permissions.subscription'), 'create', Subscription::class, $authUser); } public function update(AuthUser $authUser, Subscription $subscription): bool { - return SubbasePermission::allows(config('subbase.permissions.subscription'), 'update', Subscription::class); + return SubbasePermission::allows(config('subbase.permissions.subscription'), 'update', Subscription::class, $authUser); } public function delete(AuthUser $authUser, Subscription $subscription): bool { - return SubbasePermission::allows(config('subbase.permissions.subscription'), 'delete', Subscription::class); + return SubbasePermission::allows(config('subbase.permissions.subscription'), 'delete', Subscription::class, $authUser); } public function deleteAny(AuthUser $authUser): bool { - return SubbasePermission::allows(config('subbase.permissions.subscription'), 'deleteAny', Subscription::class); + return SubbasePermission::allows(config('subbase.permissions.subscription'), 'deleteAny', Subscription::class, $authUser); } public function restore(AuthUser $authUser, Subscription $subscription): bool { - return SubbasePermission::allows(config('subbase.permissions.subscription'), 'restore', Subscription::class); + return SubbasePermission::allows(config('subbase.permissions.subscription'), 'restore', Subscription::class, $authUser); } public function forceDelete(AuthUser $authUser, Subscription $subscription): bool { - return SubbasePermission::allows(config('subbase.permissions.subscription'), 'forceDelete', Subscription::class); + return SubbasePermission::allows(config('subbase.permissions.subscription'), 'forceDelete', Subscription::class, $authUser); } public function forceDeleteAny(AuthUser $authUser): bool { - return SubbasePermission::allows(config('subbase.permissions.subscription'), 'forceDeleteAny', Subscription::class); + return SubbasePermission::allows(config('subbase.permissions.subscription'), 'forceDeleteAny', Subscription::class, $authUser); } public function restoreAny(AuthUser $authUser): bool { - return SubbasePermission::allows(config('subbase.permissions.subscription'), 'restoreAny', Subscription::class); + return SubbasePermission::allows(config('subbase.permissions.subscription'), 'restoreAny', Subscription::class, $authUser); } public function replicate(AuthUser $authUser, Subscription $subscription): bool { - return SubbasePermission::allows(config('subbase.permissions.subscription'), 'replicate', Subscription::class); + return SubbasePermission::allows(config('subbase.permissions.subscription'), 'replicate', Subscription::class, $authUser); } public function reorder(AuthUser $authUser): bool { - return SubbasePermission::allows(config('subbase.permissions.subscription'), 'reorder', Subscription::class); + return SubbasePermission::allows(config('subbase.permissions.subscription'), 'reorder', Subscription::class, $authUser); } } \ No newline at end of file diff --git a/src/Support/SubbasePermission.php b/src/Support/SubbasePermission.php index 108d151..1e1a2d2 100644 --- a/src/Support/SubbasePermission.php +++ b/src/Support/SubbasePermission.php @@ -4,47 +4,41 @@ namespace Nafiswatsiq\Subbase\Support; +use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Support\Facades\Auth; +use Illuminate\Support\Facades\Gate; use Illuminate\Support\Str; +/** + * Deny by default. Authentication does not imply permission to manage billing. + * + * Works with native Laravel Gate, Spatie Permission, Shield, or application + * Gate::before() logic. Spatie is optional and never disables authorization. + */ final class SubbasePermission { - public static function allows(?string $permission, ?string $ability = null, ?string $subject = null): bool - { + public static function allows( + ?string $permission, + ?string $ability = null, + ?string $subject = null, + ?Authenticatable $actor = null, + ): bool { + $actor ??= Auth::user(); + + if (! $actor instanceof Authenticatable) { + return false; + } + $permission = trim((string) $permission); if ($permission === '') { - if (! class_exists('Spatie\\Permission\\PermissionRegistrar')) { - return true; - } - - if ($ability === null || $subject === null) { - return true; + if (blank($ability) || blank($subject)) { + return false; } - $permission = static::buildShieldPermissionName($ability, $subject); - } - - if (! class_exists('Spatie\\Permission\\PermissionRegistrar')) { - return true; + $permission = Str::studly($ability).':'.class_basename($subject); } - return static::can($permission); - } - - private static function can(string $permission): bool - { - $user = Auth::user(); - - if ($user === null) { - return false; - } - - return (bool) $user->can($permission); - } - - private static function buildShieldPermissionName(string $ability, string $subject): string - { - return Str::studly($ability).':'.class_basename($subject); + return Gate::forUser($actor)->allows($permission); } } diff --git a/tests/Authorization/SubbasePermissionTest.php b/tests/Authorization/SubbasePermissionTest.php new file mode 100644 index 0000000..8b2277f --- /dev/null +++ b/tests/Authorization/SubbasePermissionTest.php @@ -0,0 +1,49 @@ +assertFalse(SubbasePermission::allows(null, 'viewAny', Plan::class, $actor)); + } + + public function test_an_explicit_native_laravel_gate_can_authorize_the_actor(): void + { + Gate::define('ViewAny:Plan', fn (User $user): bool => true); + + $this->assertTrue(SubbasePermission::allows(null, 'viewAny', Plan::class, new User())); + } + + public function test_a_configured_permission_is_used_without_requiring_spatie(): void + { + Gate::define('manage billing plans', fn (User $user): bool => true); + + $this->assertTrue( + SubbasePermission::allows('manage billing plans', 'viewAny', Plan::class, new User()), + ); + } + + public function test_no_context_is_never_implicitly_authorized(): void + { + $this->assertFalse(SubbasePermission::allows(null, actor: new User())); + } + + public function test_different_actor_is_not_implicitly_authorized(): void + { + Gate::define('ViewAny:Plan', fn (User $user): bool => $user->name === 'allowed'); + + $this->assertFalse(SubbasePermission::allows(null, 'viewAny', Plan::class, new User(['name' => 'other']))); + } +} diff --git a/tests/TestCase.php b/tests/TestCase.php new file mode 100644 index 0000000..c6dcf07 --- /dev/null +++ b/tests/TestCase.php @@ -0,0 +1,16 @@ + Date: Thu, 29 Oct 2026 08:18:12 +0200 Subject: [PATCH 02/45] test: avoid mass assigning Illuminate base User fixture --- tests/Authorization/SubbasePermissionTest.php | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/Authorization/SubbasePermissionTest.php b/tests/Authorization/SubbasePermissionTest.php index 8b2277f..a9cf19d 100644 --- a/tests/Authorization/SubbasePermissionTest.php +++ b/tests/Authorization/SubbasePermissionTest.php @@ -44,6 +44,9 @@ public function test_different_actor_is_not_implicitly_authorized(): void { Gate::define('ViewAny:Plan', fn (User $user): bool => $user->name === 'allowed'); - $this->assertFalse(SubbasePermission::allows(null, 'viewAny', Plan::class, new User(['name' => 'other']))); + $user = new User(); + $user->name = 'other'; + + $this->assertFalse(SubbasePermission::allows(null, 'viewAny', Plan::class, $user)); } } From 9e14702fa16f6c240b9ba5669b4f4949df0af81b Mon Sep 17 00:00:00 2001 From: mstfkhazaal <47450090+mstfkhazaal@users.noreply.github.com> Date: Thu, 29 Oct 2026 08:19:18 +0200 Subject: [PATCH 03/45] ci: scope initial style check to new files and track upstream style debt --- .github/workflows/tests.yml | 3 ++- docs/UNIVERSAL-BILLING.md | 4 ++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 6a56830..a142b5d 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -19,5 +19,6 @@ jobs: - run: composer validate --no-check-publish --strict - run: composer update --no-interaction --prefer-dist - run: vendor/bin/phpunit - - run: vendor/bin/pint --test + # The upstream fork has pre-existing style drift. Format existing files in a separate PR. + - run: vendor/bin/pint --test src/Support/SubbasePermission.php tests/TestCase.php tests/Authorization/SubbasePermissionTest.php - run: composer audit --no-dev diff --git a/docs/UNIVERSAL-BILLING.md b/docs/UNIVERSAL-BILLING.md index b2451bf..fb9e613 100644 --- a/docs/UNIVERSAL-BILLING.md +++ b/docs/UNIVERSAL-BILLING.md @@ -51,3 +51,7 @@ ## No API / migration claims yet Version 2 is not released. No installed app is migrated by this branch. Run `composer test`, Composer audit, package migrations and a real application integration suite before merging. + +### Legacy styling gate + +The upstream fork currently has 64 pre-existing Pint style violations across 152 PHP files. This feature branch lints only new helper + tests; a separate formatting-only PR will make full-repo `pint --test` mandatory before the first Fenix major release. Formatting has no semantic intent. From 740e914747f666d35da29165f3b4726c566b6871 Mon Sep 17 00:00:00 2001 From: mstfkhazaal <47450090+mstfkhazaal@users.noreply.github.com> Date: Thu, 29 Oct 2026 08:19:45 +0200 Subject: [PATCH 04/45] style: conform new permission tests to Laravel Pint constructor syntax --- tests/Authorization/SubbasePermissionTest.php | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/tests/Authorization/SubbasePermissionTest.php b/tests/Authorization/SubbasePermissionTest.php index a9cf19d..6bd544b 100644 --- a/tests/Authorization/SubbasePermissionTest.php +++ b/tests/Authorization/SubbasePermissionTest.php @@ -14,7 +14,7 @@ final class SubbasePermissionTest extends TestCase { public function test_authenticated_user_without_any_permission_is_denied(): void { - $actor = new User(); + $actor = new User; $this->assertFalse(SubbasePermission::allows(null, 'viewAny', Plan::class, $actor)); } @@ -23,7 +23,7 @@ public function test_an_explicit_native_laravel_gate_can_authorize_the_actor(): { Gate::define('ViewAny:Plan', fn (User $user): bool => true); - $this->assertTrue(SubbasePermission::allows(null, 'viewAny', Plan::class, new User())); + $this->assertTrue(SubbasePermission::allows(null, 'viewAny', Plan::class, new User)); } public function test_a_configured_permission_is_used_without_requiring_spatie(): void @@ -31,20 +31,20 @@ public function test_a_configured_permission_is_used_without_requiring_spatie(): Gate::define('manage billing plans', fn (User $user): bool => true); $this->assertTrue( - SubbasePermission::allows('manage billing plans', 'viewAny', Plan::class, new User()), + SubbasePermission::allows('manage billing plans', 'viewAny', Plan::class, new User), ); } public function test_no_context_is_never_implicitly_authorized(): void { - $this->assertFalse(SubbasePermission::allows(null, actor: new User())); + $this->assertFalse(SubbasePermission::allows(null, actor: new User)); } public function test_different_actor_is_not_implicitly_authorized(): void { Gate::define('ViewAny:Plan', fn (User $user): bool => $user->name === 'allowed'); - $user = new User(); + $user = new User; $user->name = 'other'; $this->assertFalse(SubbasePermission::allows(null, 'viewAny', Plan::class, $user)); From 3e1c10964552d11277791024b856301df44939c0 Mon Sep 17 00:00:00 2001 From: mstfkhazaal <47450090+mstfkhazaal@users.noreply.github.com> Date: Thu, 29 Oct 2026 08:21:01 +0200 Subject: [PATCH 05/45] docs: codify universal subscriptions product spec and safe continuation guide --- AGENTS.md | 16 +++++++++++ Changelog.md | 14 ++++++++++ docs/PRODUCT-SPEC.md | 65 ++++++++++++++++++++++++++++++++++++++++++++ docs/PROGRESS.md | 32 ++++++++++++++++++++++ 4 files changed, 127 insertions(+) create mode 100644 AGENTS.md create mode 100644 Changelog.md create mode 100644 docs/PRODUCT-SPEC.md create mode 100644 docs/PROGRESS.md diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..88609ea --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,16 @@ +# Subbase package contribution rules + +Goal: one reusable subscription engine for standalone Laravel and all organization/tenant SaaS apps, **without mandatory Fenix Accounts dependencies**. + +- Read `docs/PRODUCT-SPEC.md`, `docs/PROGRESS.md`, `docs/UNIVERSAL-BILLING.md`, `docs/SECURITY-MIGRATION.md` before modifying business rules. +- Detect actual PHP, Laravel, Filament and laravelcm/laravel-subscriptions versions before using version-specific APIs. +- Keep existing Composer and PHP namespaces stable until a coordinated versioned migration; no silent renames or destructive data conversion. +- Keep subscription business operations in tested actions/services; UI and API delegate. Prefer Eloquent relations, explicit indexes, transactions and locking. +- Never conflate authorization with authentication. Explicitly scope both the selected billable and all record/read-model queries to the permitted tenant. +- Use exact decimal / integer-scaled monetary computations and currency scales, never float for financial truth. +- Keep any model-translations package choice an internal implementation detail; do not make all host apps use Spatie or Astrotomic. +- No dependencies on Fenix, ZITADEL, a particular tenancy package or a fixed `User` model. +- Every important change needs tests: unauthenticated, unauthorized, cross-tenant, concurrency, invoice/payment consistency and migration compatibility. +- PHP: strict types for new files, Laravel Pint, PSR-12 where compatible. Legacy file formatting is a separate mechanical PR. +- Preserve MIT license and original upstream authorship. Maintain `docs/PROGRESS.md` and `Changelog.md` per PR. +- No release or main-branch merge without a green CI, a compatibility demo and clearly identified breaking changes. diff --git a/Changelog.md b/Changelog.md new file mode 100644 index 0000000..4580cd2 --- /dev/null +++ b/Changelog.md @@ -0,0 +1,14 @@ +# Changelog + +## Unreleased (2026-10-29) — Universal billing foundation + +- Kept Subbase independent of Fenix Accounts for all Laravel applications. +- Hardened SubbasePermission: no implicit allow when Spatie is absent; native Laravel Gate is always checked. +- Passed the requesting authorization actor into Plan, Subscription and Discount policies (no Auth global mismatch). +- Added Testbench/PHPUnit authorization regression tests (5 passing on PHP 8.4 / Laravel 13). +- Added initial CI with Composer validation, scoped Pint and dependency audit. +- Documented broad product requirements, independent subscriber models, upgrade strategy and roadmap. + +### Breaking behavior and outstanding work + +Existing apps that relied on permissive missing-Spatie access will be denied until they grant explicit Laravel Gate abilities. No existing app has been upgraded. Tenant record scoping and financial decimal precision are **not yet implemented**. A stable release and new Composer name are pending. diff --git a/docs/PRODUCT-SPEC.md b/docs/PRODUCT-SPEC.md new file mode 100644 index 0000000..79b1a5e --- /dev/null +++ b/docs/PRODUCT-SPEC.md @@ -0,0 +1,65 @@ +# Universal Subscription Platform — product requirements + +Date: 2026-10-29. Approved owner intent: **one maintainable subscription system for every Laravel project** (inside or outside Fenix). The canonical implementation is this Subbase fork paired with `fnx-software/subbase-payment` for optional checkout. + +## Definition of done + +A supported Laravel app can install the packages, select an Eloquent billable model and a billing policy, create plans, subscribe, invoice, charge, renew, upgrade, downgrade, cancel, pause, resume, refund and reconcile — **without any Fenix dependency**. A Filament UI is optional for operating the service; API and background processing remain reusable. + +### Plan catalog and pricing +- Free, paid, trial, recurring, fixed-term, lifetime and manually granted plans. +- Plan features, quotas, unlimited vs finite limits, per-organization seat counts, usage counters and time-period metering with atomic consumption. +- Plan variants per currency and billing interval; effective-dated price versions and locked price snapshots after purchase. +- Upgrades, downgrades, scheduled switches, renewal, cancellation at period end, grace periods and proration (explicit calculation and rounding policy). +- Promotions/coupons: percentage, fixed amount, redemption caps, date ranges, allowed plans/currencies, per-customer limits and concurrency safety. +- Use exact decimal/integer money representations; ISO 4217 scales; **locale must never determine the customer's currency automatically without an explicitly chosen policy**. + +### Subscribers and tenancy +- Subject is any persisted Eloquent model (`User`, `Team`, `Organization`, `School`, `Tenant`, custom). +- Permit multiple named subscriptions per subject; no hidden global-subscriber assumption. +- Resource permissions, relationship queries, URL binding, aggregates, files, jobs, events, callbacks and plan changes must be tenant-safe. +- Support shared database, database-per-tenant and single-tenant apps through host-defined adapters. Do not require a particular tenancy package. +- One application may run local subscriptions. Another may call a central billing service with explicit external ID mappings and signed API; centralization is opt-in, not a hard dependency. + +### Payments and invoicing +- Gateway-neutral checkout and verified payment lifecycle, customer portal, invoice/receipt emails, webhook logs, refunds, disputes/chargebacks, retries and backoff. +- Hosted gateways (Stripe, PayPal, Paddle, Midtrans, Xendit) with explicit supported country/currency checks and plug-in custom drivers. +- Offline payments: record/approve and audit; no false provider capture. +- Idempotent, asynchronous payment confirmation must control subscription activation. Do not grant paid entitlements on frontend redirect. +- Scheduled billing and recurring mandate collection only when gateway policy permits; dunning, retry schedules, customer notice, tax and FX accounting snapshots. +- Never store full payment card information; preserve compliance and receipt/credit-note history. + +### UI, localization and APIs +- Laravel 13 / PHP 8.4 reference baseline, Filament 5 operational panel, optional checkout Blade/Flux UI presentation, headless API adapters. +- RTL/LTR, many locales, initial ar/en/fr. Prices are data, not locale-derived guesses. Format dates/timezones and numbers per user separately from billing currency. +- Tenant and admin dashboards: plan CRUD, subscribers, usage/limits, payments, subscriptions, disputes, reconciliation, audit and provider health. +- Signed webhooks or authenticated APIs for cross-service entitlement checks; TTL/caching with fail-closed revocation behavior. + +### Operational guarantees +- Postgres and MySQL supported after integration tests; SQLite only for lightweight package tests. +- No `float` for posting; no destructive rewrite of invoices or money; scoped unique indexes; transactional row locking; event/outbox/retry guarantees. +- Package semantic versioning, real migrations and upgrade/rollback plans, CI compatibility suite, Composer audit, Pint and Laravel tests. +- Stable releases must be tested with a standalone demo app and existing real consumers CRM and Zeno before rollout. +- Configuration defaults must be safe. Explicit permissions and billable membership authorization. No default admin user/password. + +## Boundary between the two packages + +**Subbase:** plans, features, subscriptions, entitlements, usage, discounts and lifecycle. + +**Subbase Payment:** checkout, provider drivers, signed webhooks, payment history, refunds, settlement and receipts. The gateway plugin must never become an untrusted shortcut to marking subscriptions paid. + +External business applications (POS, ERP, school finance, Invoice customer collections) retain **their own financial ledgers and domain records**; do not double-count those as SaaS subscription payments. + +## Delivery stages + +| Stage | Scope | Acceptance gate | +| --- | --- | --- | +| 0 — Stabilize | permissions, precise package test harness, documented APIs | tests, audit, explicit denials | +| 1 — Generic billable | user/organization/school/tenant, scoping, adapter contracts | two-tenant isolation tests and checkout owner tests | +| 2 — Financial precision | money, price snapshots, discounts, taxes and proration | currency-specific reference calculations | +| 3 — Full lifecycle | renewal, switch, cancellation, pauses, trials, seats and usage | lifecycle/concurrency integration tests | +| 4 — Payment production | idempotent payment ledger, refunds, disputes, gateway sandbox | end-to-end confirmed settlements and failed-payment recovery | +| 5 — Distribution | Composer package identity, upgrade from upstream, releases | CRM/Zeno migration + demo app verified | +| 6 — UX and internationalization | Filament and optional checkout UI, 100+ locale architecture | ar/en/fr and RTL visual/functional QA | + +**No stage is complete because its specification exists.** Status is tracked separately in `docs/PROGRESS.md`. diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md new file mode 100644 index 0000000..1f67bc0 --- /dev/null +++ b/docs/PROGRESS.md @@ -0,0 +1,32 @@ +# Subbase fork — progress + +Date: 2026-10-29. Product target: one standalone billing package across all Laravel applications, with an optional companion Subbase Payment package. + +## Current milestone: Stage 0 / Stabilize + +- [x] Identified `fnx-software/subbase` fork; original upstream `nafiswatsiq/subbase` (MIT). +- [x] Created `feat/universal-billing-foundation` feature branch; no modifications to `main`. +- [x] Implemented a fail-closed native Laravel Gate authorization helper with optional Spatie integration. +- [x] Policy methods use the provided actor and accept generic `Authenticatable` contracts. +- [x] PHPUnit/Testbench tests added for permission denial and explicit grant; PHP 8.4 Laravel 13 tests observed passing (5/5). +- [x] Composer audit and scoped new-file formatting checked in the feature branch's CI run; this is **not** a full-repo audit of business behavior. +- [x] Documented independent Eloquent subscription owners and the no-Fenix-dependency decision. +- [ ] Complete reusable tenant-aware resource scoping and signed API adapters. +- [ ] Verified installation + upgrade in CRM and Zeno; do not change their installed packages yet. +- [ ] Full exact-decimal money and currency-scale refactor; currently original Plan/Discount floats are a known problem. +- [ ] Lifecycle/proration/usage/seat plans and end-to-end payment integration. +- [ ] Stable Composer identity as `fnx-software/subbase` and coordinated upgrade of the companion package. +- [ ] Full Pint baseline; 64 pre-existing style issues in upstream repo require a formatting-only PR. +- [ ] Multi-version PHP/Laravel/Filament test matrix, release and production readiness. + +## Integration principles + +1. Standalone app: `User` or any custom Eloquent model with `HasPlanSubscriptions`. +2. Organization SaaS: use an authorized `Organization`/Tenant model; no user-as-tenant fallback. +3. Fenix Apps: Fenix Accounts adapter is optional and lives outside package core. +4. Payment plugin adds checkout; no paid entitlement until server-verified settlement. +5. Do not merge a breaking authorization or financial migration change until consumer apps and update guides are tested. + +## Continue next + +Read `AGENTS.md`, `docs/PRODUCT-SPEC.md`, `docs/UNIVERSAL-BILLING.md`, `docs/SECURITY-MIGRATION.md` and this document. Add tests for each feature, link issues/PRs and update Changelog and this file with actual verification. Keep `main` unchanged until reviewed. From a790550f974a7afe701f210185cdfbbb3452da54 Mon Sep 17 00:00:00 2001 From: mstfkhazaal <47450090+mstfkhazaal@users.noreply.github.com> Date: Thu, 29 Oct 2026 08:21:52 +0200 Subject: [PATCH 06/45] docs: mark fork distribution status, verified CI and draft PR --- README.md | 2 ++ docs/PROGRESS.md | 6 +++++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 2774742..c549135 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,5 @@ +> **FNX Software universal billing fork:** This repository is being developed as a reusable Laravel package for standalone and multi-tenant projects, with **no mandatory Fenix Accounts dependency**. Development is on [draft PR #2](https://github.com/fnx-software/subbase/pull/2), not on the stable `main` branch. The Composer package name and PHP namespace **still use the upstream `nafiswatsiq/*` identity** pending a coordinated major upgrade. Do not mistake `composer require nafiswatsiq/...` from Packagist for an installation of this fork. For current goals and implementation status, see [Progress](docs/PROGRESS.md) and [architecture](docs/UNIVERSAL-BILLING.md). + header # Subbase - Filament Subscription Management Plugin diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 1f67bc0..9166a38 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -9,7 +9,7 @@ Date: 2026-10-29. Product target: one standalone billing package across all Lara - [x] Implemented a fail-closed native Laravel Gate authorization helper with optional Spatie integration. - [x] Policy methods use the provided actor and accept generic `Authenticatable` contracts. - [x] PHPUnit/Testbench tests added for permission denial and explicit grant; PHP 8.4 Laravel 13 tests observed passing (5/5). -- [x] Composer audit and scoped new-file formatting checked in the feature branch's CI run; this is **not** a full-repo audit of business behavior. +- [x] [Green CI](https://github.com/fnx-software/subbase/actions/runs/40828540923): 5 PHPUnit tests / 5 assertions; Composer audit and scoped new-file Pint succeeded. This is **not** a full business-behavior or legacy-formatting audit. - [x] Documented independent Eloquent subscription owners and the no-Fenix-dependency decision. - [ ] Complete reusable tenant-aware resource scoping and signed API adapters. - [ ] Verified installation + upgrade in CRM and Zeno; do not change their installed packages yet. @@ -30,3 +30,7 @@ Date: 2026-10-29. Product target: one standalone billing package across all Lara ## Continue next Read `AGENTS.md`, `docs/PRODUCT-SPEC.md`, `docs/UNIVERSAL-BILLING.md`, `docs/SECURITY-MIGRATION.md` and this document. Add tests for each feature, link issues/PRs and update Changelog and this file with actual verification. Keep `main` unchanged until reviewed. + +## Review + +- [Draft pull request #2](https://github.com/fnx-software/subbase/pull/2) — branch remains separate from `main` pending consumer integration, full financial verification and release preparation. From 33f25be851c2acada0b378c94af5827dc517c6e8 Mon Sep 17 00:00:00 2001 From: mstfkhazaal <47450090+mstfkhazaal@users.noreply.github.com> Date: Thu, 29 Oct 2026 08:23:26 +0200 Subject: [PATCH 07/45] docs: track complete subscription platform backlog and contributor continuity --- docs/BACKLOG.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 docs/BACKLOG.md diff --git a/docs/BACKLOG.md b/docs/BACKLOG.md new file mode 100644 index 0000000..37037a6 --- /dev/null +++ b/docs/BACKLOG.md @@ -0,0 +1,28 @@ +# Implementation backlog (Issues disabled on this GitHub fork) + +Last updated: 2026-10-29. This is the durable backlog while GitHub Issues cannot be created. The active draft PR is https://github.com/fnx-software/subbase/pull/2. + +## P0 — Ship a secure, generic subscription core + +- [ ] Tenant resolver that scopes **queries and record actions**, and fails closed if explicitly enabled but unresolved. +- [ ] Model-agnostic Eloquent billable owner and named subscriptions; no mandatory Fenix identity. +- [ ] Tenant/actor authorization integration tests for Filament resource, relation managers and API. +- [ ] Exact money arithmetic replacing float, ISO 4217 currency scale, plan/discount/FX snapshots. +- [ ] Concurrent discount redemption and subscription usage quota locking. + +## P1 — Full product lifecycle + +- [ ] Trial, grace, renewal, scheduled switch, pause, resume, cancel, subscriptions per seat or metered usage. +- [ ] Plans, add-ons, bundles, featured/discounted pricing, promotions and tax configuration per country. +- [ ] Full event/audit history, job retries and safe reconciliation with Subbase Payment. +- [ ] Localization ar/en/fr, RTL, headless APIs and optional Filament/Flux checkout. + +## P2 — Distribution and adoption + +- [ ] Maintenance release policy and new Composer identity `fnx-software/subbase`; preserve old aliases with tested upgrade guide. +- [ ] Full Pint baseline cleanup (upstream 64 issues) and end-to-end multi-database compatibility suite. +- [ ] Test existing CRM and Zeno records without changing their installed package until adoption approved. +- [ ] Standalone demo app (User), B2B demo app (Organization), school app (School), central service optional. +- [ ] Tag stable release only after the critical security/financial gates pass. + +See `docs/PRODUCT-SPEC.md` for full acceptance criteria. From 3c8e93bd42ca40d92ec41c4c1dd4c6e45f36d732 Mon Sep 17 00:00:00 2001 From: mstfkhazaal <47450090+mstfkhazaal@users.noreply.github.com> Date: Thu, 29 Oct 2026 09:42:12 +0200 Subject: [PATCH 08/45] feat: exact decimal money arithmetic with ISO currency scales and regression tests --- .github/workflows/tests.yml | 4 +- composer.json | 3 +- config/subbase.php | 4 + src/Support/Money.php | 180 ++++++++++++++++++++++++++++++++++++ tests/Money/MoneyTest.php | 65 +++++++++++++ 5 files changed, 253 insertions(+), 3 deletions(-) create mode 100644 src/Support/Money.php create mode 100644 tests/Money/MoneyTest.php diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index a142b5d..0af8fd6 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -13,12 +13,12 @@ jobs: - uses: shivammathur/setup-php@v2 with: php-version: '8.4' - extensions: mbstring, dom, sqlite3, pdo_sqlite + extensions: mbstring, dom, sqlite3, pdo_sqlite, bcmath coverage: none tools: composer:v2 - run: composer validate --no-check-publish --strict - run: composer update --no-interaction --prefer-dist - run: vendor/bin/phpunit # The upstream fork has pre-existing style drift. Format existing files in a separate PR. - - run: vendor/bin/pint --test src/Support/SubbasePermission.php tests/TestCase.php tests/Authorization/SubbasePermissionTest.php + - run: vendor/bin/pint --test src/Support/SubbasePermission.php tests/TestCase.php tests/Authorization/SubbasePermissionTest.php src/Support/Money.php tests/Money/MoneyTest.php - run: composer audit --no-dev diff --git a/composer.json b/composer.json index 7a6e7db..03ca2f0 100644 --- a/composer.json +++ b/composer.json @@ -22,7 +22,8 @@ "php": "^8.2", "filament/filament": "^5.0", "laravelcm/laravel-subscriptions": "^1.8", - "spatie/laravel-package-tools": "^1.16" + "spatie/laravel-package-tools": "^1.16", + "ext-bcmath": "*" }, "autoload": { "psr-4": { diff --git a/config/subbase.php b/config/subbase.php index 07c2e08..6733bf7 100644 --- a/config/subbase.php +++ b/config/subbase.php @@ -22,6 +22,10 @@ 'default_currency' => 'USD', + // ISO 4217 minor unit scales; overrides for special pricing/accounting cases. + // Monetary posting requires canonical decimal strings, not PHP floats. + 'currency_scales' => [], + 'theme' => env('SUBBASE_THEME', 'default'), 'locale_currency_map' => [ diff --git a/src/Support/Money.php b/src/Support/Money.php new file mode 100644 index 0000000..aff4c1b --- /dev/null +++ b/src/Support/Money.php @@ -0,0 +1,180 @@ +currency = $currency; + $this->scale = self::currencyScale($currency); + $this->amount = self::roundPositive(trim($amount), $this->scale); + } + + public static function zero(string $currency): self + { + return new self('0', $currency); + } + + public static function fromMinorUnits(int|string $minor, string $currency): self + { + $digits = (string) $minor; + if (! preg_match('/^(?:0|[1-9][0-9]{0,17})$/D', $digits)) { + throw new InvalidArgumentException('Minor units must be a nonnegative integer.'); + } + + $scale = self::currencyScale(strtoupper($currency)); + $base = '1'.str_repeat('0', $scale); + + return new self(bcdiv($digits, $base, $scale), $currency); + } + + public function amount(): string + { + return $this->amount; + } + + public function currency(): string + { + return $this->currency; + } + + public function scale(): int + { + return $this->scale; + } + + public function isZero(): bool + { + return bccomp($this->amount, '0', $this->scale) === 0; + } + + public function equals(self $other): bool + { + $this->assertSameCurrency($other); + + return bccomp($this->amount, $other->amount, $this->scale) === 0; + } + + public function plus(self $other): self + { + $this->assertSameCurrency($other); + + return new self(bcadd($this->amount, $other->amount, $this->scale), $this->currency); + } + + public function minus(self $other): self + { + $this->assertSameCurrency($other); + + if (bccomp($this->amount, $other->amount, $this->scale) < 0) { + throw new InvalidArgumentException('Money cannot become negative.'); + } + + return new self(bcsub($this->amount, $other->amount, $this->scale), $this->currency); + } + + /** Percentage amount, with exact decimal rate and HALF_UP rounding. */ + public function percent(string $rate): self + { + if (! preg_match('/^(?:0|[1-9][0-9]{0,2})(?:\.[0-9]{1,8})?$/D', $rate) + || bccomp($rate, '100', 8) > 0 + ) { + throw new InvalidArgumentException('Percentage must be between 0 and 100.'); + } + + $workScale = $this->scale + 12; + $unrounded = bcdiv(bcmul($this->amount, $rate, $workScale), '100', $workScale); + + return new self($unrounded, $this->currency); + } + + /** + * For gateways requiring exact minor-unit integers. Raises before integer overflow. + */ + public function toMinorUnits(): int + { + $value = bcmul($this->amount, '1'.str_repeat('0', $this->scale), 0); + + if (bccomp($value, (string) PHP_INT_MAX, 0) > 0) { + throw new OverflowException('Money amount exceeds integer minor-unit capacity.'); + } + + return (int) $value; + } + + public static function currencyScale(string $currency): int + { + $code = strtoupper($currency); + if (! preg_match('/^[A-Z]{3}$/D', $code)) { + throw new InvalidArgumentException('Invalid currency code.'); + } + + $overrides = config('subbase.currency_scales', []); + + if (array_key_exists($code, $overrides)) { + $scale = $overrides[$code]; + if (! is_int($scale) || $scale < 0 || $scale > 4) { + throw new InvalidArgumentException('Currency scale override must be an integer between zero and four.'); + } + + return $scale; + } + + if (in_array($code, [ + 'BIF', 'CLP', 'DJF', 'GNF', 'ISK', 'JPY', 'KMF', 'KRW', 'PYG', + 'RWF', 'UGX', 'VND', 'VUV', 'XAF', 'XOF', 'XPF', + ], true)) { + return 0; + } + + if (in_array($code, ['BHD', 'IQD', 'JOD', 'KWD', 'LYD', 'OMR', 'TND'], true)) { + return 3; + } + + if (in_array($code, ['CLF', 'UYW'], true)) { + return 4; + } + + return 2; + } + + private static function roundPositive(string $value, int $scale): string + { + $half = $scale === 0 ? '0.5' : '0.'.str_repeat('0', $scale).'5'; + + return bcadd($value, $half, $scale); + } + + private function assertSameCurrency(self $other): void + { + if ($this->currency !== $other->currency) { + throw new InvalidArgumentException('Arithmetic across currencies requires an explicit exchange rate.'); + } + } +} diff --git a/tests/Money/MoneyTest.php b/tests/Money/MoneyTest.php new file mode 100644 index 0000000..606d641 --- /dev/null +++ b/tests/Money/MoneyTest.php @@ -0,0 +1,65 @@ +assertSame('0.30', (new Money('0.10', 'USD'))->plus(new Money('0.20', 'USD'))->amount()); + $this->assertSame('2.35', (new Money('2.345', 'USD'))->amount()); + $this->assertSame('2.34', (new Money('2.344', 'USD'))->amount()); + } + + public function test_currency_specific_minor_unit_scales(): void + { + $this->assertSame('100', (new Money('99.6', 'JPY'))->amount()); + $this->assertSame('1.235', (new Money('1.2345', 'KWD'))->amount()); + $this->assertSame('1.2346', (new Money('1.23456', 'CLF'))->amount()); + $this->assertSame(1235, (new Money('1.235', 'KWD'))->toMinorUnits()); + $this->assertSame('1.235', Money::fromMinorUnits('1235', 'KWD')->amount()); + } + + public function test_percentage_discount_calculates_exact_half_up(): void + { + $this->assertSame('0.05', (new Money('0.10', 'USD'))->percent('50')->amount()); + $this->assertSame('0.01', (new Money('0.05', 'USD'))->percent('10')->amount()); + $this->assertSame('0.000', (new Money('0.001', 'KWD'))->percent('40')->amount()); + } + + public function test_negative_money_is_not_accepted(): void + { + $this->expectException(InvalidArgumentException::class); + new Money('-1', 'USD'); + } + + public function test_scientific_notation_is_not_accepted(): void + { + $this->expectException(InvalidArgumentException::class); + new Money('1e4', 'USD'); + } + + public function test_cross_currency_subtraction_is_not_accepted(): void + { + $this->expectException(InvalidArgumentException::class); + (new Money('10', 'USD'))->minus(new Money('1', 'JPY')); + } + + public function test_percentage_above_one_hundred_is_rejected(): void + { + $this->expectException(InvalidArgumentException::class); + (new Money('10', 'USD'))->percent('100.1'); + } + + public function test_zero_amount_and_integer_conversion(): void + { + $this->assertTrue(Money::zero('EUR')->isZero()); + $this->assertSame(10001, (new Money('100.01', 'EUR'))->toMinorUnits()); + } +} From 9a31709b945141463e53a2908d9692c7177338ef Mon Sep 17 00:00:00 2001 From: mstfkhazaal <47450090+mstfkhazaal@users.noreply.github.com> Date: Thu, 29 Oct 2026 09:42:33 +0200 Subject: [PATCH 09/45] feat: add exact subscription pricing quote API beside legacy display functions --- src/Helpers/PlanPriceHelper.php | 61 +++++++++++++++++++++++++++++++++ src/Models/Plan.php | 26 ++++++++++++++ 2 files changed, 87 insertions(+) diff --git a/src/Helpers/PlanPriceHelper.php b/src/Helpers/PlanPriceHelper.php index f930384..5c7a9c6 100644 --- a/src/Helpers/PlanPriceHelper.php +++ b/src/Helpers/PlanPriceHelper.php @@ -3,6 +3,7 @@ namespace Nafiswatsiq\Subbase\Helpers; use Nafiswatsiq\Subbase\Models\Plan; +use Nafiswatsiq\Subbase\Support\Money; class PlanPriceHelper { @@ -63,6 +64,66 @@ public static function resolveWithDiscounts(Plan $plan, ?string $currency = null ]; } + /** + * Canonical quote for financial settlement; all amounts are decimal strings. + * Existing float-returning methods remain as presentation compatibility APIs. + * + * @return array{original_amount:string,discount_amount:string,final_amount:string,currency:string,best_discount:mixed} + */ + public static function resolveExactWithDiscounts(Plan $plan, ?string $currency = null): array + { + $code = static::currency($plan, $currency); + $original = new Money($plan->getPriceDecimalForCurrency($code), $code); + $final = $original; + $selected = null; + + foreach ($plan->activeDiscounts()->get() as $discount) { + if (! $discount->isValid()) { + continue; + } + + $discountCurrency = strtoupper((string) ($discount->currency ?? '')); + if ($discountCurrency !== '' && $discountCurrency !== $code) { + continue; + } + + $min = $discount->getRawOriginal('min_amount'); + if ($min !== null && $min !== '' && bccomp($original->amount(), (new Money((string) $min, $code))->amount(), $original->scale()) < 0) { + continue; + } + + $value = (string) ($discount->getRawOriginal('value') ?? '0'); + if ($discount->type === 'percentage') { + $deduction = $original->percent($value); + } elseif ($discount->type === 'fixed') { + $deduction = new Money($value, $code); + } else { + continue; + } + + if (bccomp($deduction->amount(), $original->amount(), $original->scale()) > 0) { + $deduction = $original; + } + + if ($deduction->isZero()) { + continue; + } + + $final = $original->minus($deduction); + $selected = $discount; + + break; + } + + return [ + 'original_amount' => $original->amount(), + 'discount_amount' => $original->minus($final)->amount(), + 'final_amount' => $final->amount(), + 'currency' => $code, + 'best_discount' => $selected, + ]; + } + public static function formatWithDiscounts(Plan $plan, ?string $currency = null, int $decimals = 2): array { $resolved = static::resolveWithDiscounts($plan, $currency); diff --git a/src/Models/Plan.php b/src/Models/Plan.php index 6f1ccd5..e76e4ec 100644 --- a/src/Models/Plan.php +++ b/src/Models/Plan.php @@ -67,6 +67,32 @@ public function getPriceForCurrency(?string $currency = null, bool $fallbackToBa return (float) ($this->price ?? 0.0); } + /** + * Exact financial accessor: no binary float conversion. Existing float API + * remains for legacy presentation calls, not financial posting. + */ + public function getPriceDecimalForCurrency(?string $currency = null, bool $fallbackToBase = true): string + { + $target = strtoupper((string) ($currency ?: $this->currency)); + $raw = $this->getRawOriginal('prices'); + $prices = is_string($raw) ? json_decode($raw, true) : $raw; + if (! is_array($prices)) { + $prices = []; + } + + if (array_key_exists($target, $prices) && is_numeric($prices[$target])) { + return (new \Nafiswatsiq\Subbase\Support\Money((string) $prices[$target], $target))->amount(); + } + + if (! $fallbackToBase) { + return \Nafiswatsiq\Subbase\Support\Money::zero($target)->amount(); + } + + $base = $this->getRawOriginal('price') ?? '0'; + + return (new \Nafiswatsiq\Subbase\Support\Money((string) $base, $target))->amount(); + } + public function getPriceForLocale(?string $locale = null, bool $fallbackToBase = true): float { return $this->getPriceForCurrency(static::currencyFromLocale($locale), $fallbackToBase); From 9336a923c9a89f662b2024ee7842ebdfc3e9bfdb Mon Sep 17 00:00:00 2001 From: mstfkhazaal <47450090+mstfkhazaal@users.noreply.github.com> Date: Thu, 29 Oct 2026 09:42:54 +0200 Subject: [PATCH 10/45] fix: accept internal high-precision BCMath fractional values before rounding --- src/Support/Money.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Support/Money.php b/src/Support/Money.php index aff4c1b..cd385d5 100644 --- a/src/Support/Money.php +++ b/src/Support/Money.php @@ -27,7 +27,7 @@ public function __construct(string $amount, string $currency) throw new InvalidArgumentException('Currency must be a three-letter ISO 4217 code.'); } - if (! preg_match('/^(?:0|[1-9][0-9]{0,15})(?:\.[0-9]{1,12})?$/D', trim($amount))) { + if (! preg_match('/^(?:0|[1-9][0-9]{0,15})(?:\.[0-9]{1,18})?$/D', trim($amount))) { throw new InvalidArgumentException('Money must be a nonnegative plain decimal string.'); } From 09abd3e39a0ed30fabab61eaf55aed282005f3f8 Mon Sep 17 00:00:00 2001 From: mstfkhazaal <47450090+mstfkhazaal@users.noreply.github.com> Date: Thu, 29 Oct 2026 09:46:11 +0200 Subject: [PATCH 11/45] feat: preserve canonical decimal plan/discount prices and add forward-only precision migration --- .../upgrade_billing_decimal_columns.php | 38 +++++++++++++++++++ docs/PRECISION-MIGRATION.md | 13 +++++++ src/Models/Discount.php | 4 +- src/Models/Plan.php | 20 +++++----- 4 files changed, 63 insertions(+), 12 deletions(-) create mode 100644 database/migrations/upgrade_billing_decimal_columns.php create mode 100644 docs/PRECISION-MIGRATION.md diff --git a/database/migrations/upgrade_billing_decimal_columns.php b/database/migrations/upgrade_billing_decimal_columns.php new file mode 100644 index 0000000..1bbe6eb --- /dev/null +++ b/database/migrations/upgrade_billing_decimal_columns.php @@ -0,0 +1,38 @@ +decimal('price', 20, 4)->change(); + $table->decimal('signup_fee', 20, 4)->change(); + }); + + Schema::table(config('subbase.tables.discounts', 'discounts'), function (Blueprint $table): void { + $table->decimal('value', 20, 4)->change(); + $table->decimal('min_amount', 20, 4)->nullable()->change(); + }); + + Schema::table('discount_subscription', function (Blueprint $table): void { + $table->decimal('discounted_amount', 20, 4)->nullable()->change(); + $table->decimal('original_amount', 20, 4)->nullable()->change(); + }); + } + + public function down(): void + { + // Decreasing precision would silently destroy 3/4-decimal amounts. + // Roll back via an explicitly reviewed data-safe migration. + } +}; diff --git a/docs/PRECISION-MIGRATION.md b/docs/PRECISION-MIGRATION.md new file mode 100644 index 0000000..ef48652 --- /dev/null +++ b/docs/PRECISION-MIGRATION.md @@ -0,0 +1,13 @@ +# Exact currency precision upgrade — safety rules + +The fork now stores canonical currency price strings in JSON and offers `Plan::getPriceDecimalForCurrency` and `PlanPriceHelper::resolveExactWithDiscounts`. Legacy float-returning public methods remain for presentation/backward compatibility, **not payment posting**. + +A new widening migration `database/migrations/upgrade_billing_decimal_columns.php` increases Plan/Discount/Pivot numeric columns to decimal(20,4). It must run **after laravelcm and the existing Subbase migrations**. If this package publishes migrations manually, publish this new migration after existing ones. Do not execute it until schema/migration integration tests prove its order, table names, indexes and running data. + +After rollout, all priced JSON values are canonical decimal strings; existing historical float JSON remains readable but may have been rounded when originally stored. Never silently rewrite financial history. Confirm two-tenant isolation and a backup before migration. + +**No destructive down migration**: narrowing precision would truncate live KWD/CLF values. A rollback requires an explicit data-preserving migration and backup. + +UI and legacy `calculateDiscount(float,...)` still use floats for display; checkout must use the new exact quote method and must block checkout when the matching billing package isn't installed. + +This migration is not yet verified on production PostgreSQL or MySQL. diff --git a/src/Models/Discount.php b/src/Models/Discount.php index a59c321..7275f95 100644 --- a/src/Models/Discount.php +++ b/src/Models/Discount.php @@ -35,8 +35,8 @@ class Discount extends Model ]; protected $casts = [ - 'value' => 'float', - 'min_amount' => 'float', + 'value' => 'decimal:4', + 'min_amount' => 'decimal:4', 'starts_at' => 'datetime', 'expires_at' => 'datetime', 'is_active' => 'boolean', diff --git a/src/Models/Plan.php b/src/Models/Plan.php index e76e4ec..d2ad1d4 100644 --- a/src/Models/Plan.php +++ b/src/Models/Plan.php @@ -37,8 +37,8 @@ class Plan extends BasePlan protected $casts = [ 'is_active' => 'boolean', 'featured' => 'boolean', - 'price' => 'float', - 'signup_fee' => 'float', + 'price' => 'decimal:4', + 'signup_fee' => 'decimal:4', 'prices' => 'array', 'deleted_at' => 'datetime', ]; @@ -160,7 +160,7 @@ public function setPriceForCurrency(string $currency, int|float|string $price): { $targetCurrency = strtoupper($currency); $prices = $this->normalizedPrices(); - $prices[$targetCurrency] = (float) $price; + $prices[$targetCurrency] = (new \Nafiswatsiq\Subbase\Support\Money((string) $price, $targetCurrency))->amount(); $this->prices = $prices; $this->syncBasePriceFromCurrency(); @@ -177,7 +177,7 @@ public function syncBasePriceFromCurrency(?string $currency = null): self $firstCurrency = array_key_first($prices); if ($firstCurrency === null) { - $this->price = 0.0; + $this->price = '0'; return $this; } @@ -186,7 +186,7 @@ public function syncBasePriceFromCurrency(?string $currency = null): self $this->currency = $targetCurrency; } - $this->price = (float) $prices[$targetCurrency]; + $this->price = $prices[$targetCurrency]; return $this; } @@ -203,7 +203,7 @@ public function setPricesAttribute($value): void $targetCurrency = strtoupper((string) ($this->attributes['currency'] ?? $this->currency ?? '')); if ($targetCurrency !== '' && array_key_exists($targetCurrency, $normalized)) { - $this->attributes['price'] = (float) $normalized[$targetCurrency]; + $this->attributes['price'] = $normalized[$targetCurrency]; return; } @@ -215,7 +215,7 @@ public function setPricesAttribute($value): void } $this->attributes['currency'] = $firstCurrency; - $this->attributes['price'] = (float) $normalized[$firstCurrency]; + $this->attributes['price'] = $normalized[$firstCurrency]; } protected static function booted(): void @@ -223,7 +223,7 @@ protected static function booted(): void static::saving(function (self $plan): void { if (empty($plan->prices) && ! empty($plan->currency)) { $plan->prices = [ - strtoupper((string) $plan->currency) => (float) $plan->price, + strtoupper((string) $plan->currency) => (string) $plan->price, ]; return; @@ -290,7 +290,7 @@ protected function normalizePrices(array $prices): array continue; } - $normalized[$currencyCode] = (float) $amount; + $normalized[$currencyCode] = (new \Nafiswatsiq\Subbase\Support\Money((string) $amount, $currencyCode))->amount(); } ksort($normalized); @@ -396,7 +396,7 @@ public static function pricesFromRepeaterRows(array $rows): array continue; } - $merged[$currencyCode] = (float) $rawPrice; + $merged[$currencyCode] = (new \Nafiswatsiq\Subbase\Support\Money((string) $rawPrice, $currencyCode))->amount(); } ksort($merged); From a6caa467256bb705edbff1717516bc5cf241a0b4 Mon Sep 17 00:00:00 2001 From: mstfkhazaal <47450090+mstfkhazaal@users.noreply.github.com> Date: Thu, 29 Oct 2026 09:46:26 +0200 Subject: [PATCH 12/45] chore: publish widening monetary migration in Subbase installer --- docs/PRECISION-MIGRATION.md | 2 +- src/SubbaseServiceProvider.php | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/PRECISION-MIGRATION.md b/docs/PRECISION-MIGRATION.md index ef48652..7fe0499 100644 --- a/docs/PRECISION-MIGRATION.md +++ b/docs/PRECISION-MIGRATION.md @@ -2,7 +2,7 @@ The fork now stores canonical currency price strings in JSON and offers `Plan::getPriceDecimalForCurrency` and `PlanPriceHelper::resolveExactWithDiscounts`. Legacy float-returning public methods remain for presentation/backward compatibility, **not payment posting**. -A new widening migration `database/migrations/upgrade_billing_decimal_columns.php` increases Plan/Discount/Pivot numeric columns to decimal(20,4). It must run **after laravelcm and the existing Subbase migrations**. If this package publishes migrations manually, publish this new migration after existing ones. Do not execute it until schema/migration integration tests prove its order, table names, indexes and running data. +A new widening migration `database/migrations/upgrade_billing_decimal_columns.php` increases Plan/Discount/Pivot numeric columns to decimal(20,4). It must run **after laravelcm and the existing Subbase migrations**. The package's `subbase:install` command now publishes it after existing migrations; run it on a staged copy before production. Do not execute it until schema/migration integration tests prove its order, table names, indexes and running data. After rollout, all priced JSON values are canonical decimal strings; existing historical float JSON remains readable but may have been rounded when originally stored. Never silently rewrite financial history. Confirm two-tenant isolation and a backup before migration. diff --git a/src/SubbaseServiceProvider.php b/src/SubbaseServiceProvider.php index 7b55704..6185839 100644 --- a/src/SubbaseServiceProvider.php +++ b/src/SubbaseServiceProvider.php @@ -48,6 +48,7 @@ public function configurePackage(Package $package): void 'add_prices_to_plans_table.php', 'add_featured_to_plans_table.php', 'create_discounts_table.php', + 'upgrade_billing_decimal_columns.php', ]; foreach ($migrations as $migration) { From b32b1fcadf1eaaca0160a184dcda69a6800c8138 Mon Sep 17 00:00:00 2001 From: mstfkhazaal <47450090+mstfkhazaal@users.noreply.github.com> Date: Thu, 29 Oct 2026 09:48:35 +0200 Subject: [PATCH 13/45] feat: add optional fail-closed tenant isolation contract for subscription packages --- .github/workflows/tests.yml | 2 +- config/subbase.php | 4 ++ src/Contracts/TenantAccess.php | 20 +++++++++ src/Support/SubbasePermission.php | 5 ++- src/Support/SubbaseTenancy.php | 57 ++++++++++++++++++++++++ tests/Tenancy/SubbaseTenancyTest.php | 66 ++++++++++++++++++++++++++++ 6 files changed, 152 insertions(+), 2 deletions(-) create mode 100644 src/Contracts/TenantAccess.php create mode 100644 src/Support/SubbaseTenancy.php create mode 100644 tests/Tenancy/SubbaseTenancyTest.php diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 0af8fd6..a7c1c9e 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -20,5 +20,5 @@ jobs: - run: composer update --no-interaction --prefer-dist - run: vendor/bin/phpunit # The upstream fork has pre-existing style drift. Format existing files in a separate PR. - - run: vendor/bin/pint --test src/Support/SubbasePermission.php tests/TestCase.php tests/Authorization/SubbasePermissionTest.php src/Support/Money.php tests/Money/MoneyTest.php + - run: vendor/bin/pint --test src/Support/SubbasePermission.php tests/TestCase.php tests/Authorization/SubbasePermissionTest.php src/Support/Money.php tests/Money/MoneyTest.php src/Support/SubbaseTenancy.php src/Contracts/TenantAccess.php tests/Tenancy/SubbaseTenancyTest.php - run: composer audit --no-dev diff --git a/config/subbase.php b/config/subbase.php index 6733bf7..7eea653 100644 --- a/config/subbase.php +++ b/config/subbase.php @@ -26,6 +26,10 @@ // Monetary posting requires canonical decimal strings, not PHP floats. 'currency_scales' => [], + // Opt-in: host application defines record- and query-level isolation. + // If enabled without a resolver, every tenant query and action is denied. + 'tenancy' => ['enabled' => false, 'access' => null], + 'theme' => env('SUBBASE_THEME', 'default'), 'locale_currency_map' => [ diff --git a/src/Contracts/TenantAccess.php b/src/Contracts/TenantAccess.php new file mode 100644 index 0000000..d7a67a8 --- /dev/null +++ b/src/Contracts/TenantAccess.php @@ -0,0 +1,20 @@ +allows($permission); + return SubbaseTenancy::allows($record, (string) $ability, $actor) + && Gate::forUser($actor)->allows($permission); } } diff --git a/src/Support/SubbaseTenancy.php b/src/Support/SubbaseTenancy.php new file mode 100644 index 0000000..65a360a --- /dev/null +++ b/src/Support/SubbaseTenancy.php @@ -0,0 +1,57 @@ +whereRaw('1 = 0'); + } + + return $resolver->scope($query, $actor); + } + + public static function allows(?Model $record, string $ability, Authenticatable $actor): bool + { + if (!self::enabled()) { + return true; + } + + $resolver = self::resolver(); + + return $resolver !== null && $resolver->allows($record, $ability, $actor); + } + + private static function resolver(): ?TenantAccess + { + $class = config('subbase.tenancy.access'); + if (!is_string($class) || !is_a($class, TenantAccess::class, true)) { + return null; + } + + $service = app($class); + + return $service instanceof TenantAccess ? $service : null; + } +} diff --git a/tests/Tenancy/SubbaseTenancyTest.php b/tests/Tenancy/SubbaseTenancyTest.php new file mode 100644 index 0000000..0f77a0a --- /dev/null +++ b/tests/Tenancy/SubbaseTenancyTest.php @@ -0,0 +1,66 @@ +where('tenant_id', 5); + } + + public function allows(?Model $record, string $ability, Authenticatable $actor): bool + { + return $record === null || (int) $record->getAttribute('tenant_id') === 5; + } +} + +final class SubbaseTenancyTest extends TestCase +{ + public function test_multitenant_mode_without_resolver_denies_all_queries(): void + { + config(['subbase.tenancy.enabled' => true, 'subbase.tenancy.access' => null]); + + $this->assertFalse(SubbaseTenancy::allows(new TenantRecord, 'view', new User)); + $this->assertStringContainsString('1 = 0', SubbaseTenancy::scope(TenantRecord::query())->toSql()); + } + + public function test_tenant_resolver_scopes_queries_and_record_access(): void + { + config(['subbase.tenancy.enabled' => true, 'subbase.tenancy.access' => FakeTenantAccess::class]); + + Auth::setUser(new User); + + $this->assertStringContainsString('"tenant_id" = ?', SubbaseTenancy::scope(TenantRecord::query())->toSql()); + $allowed = new TenantRecord; + $allowed->tenant_id = 5; + $denied = new TenantRecord; + $denied->tenant_id = 6; + + $this->assertTrue(SubbaseTenancy::allows($allowed, 'view', new User)); + $this->assertFalse(SubbaseTenancy::allows($denied, 'view', new User)); + } + + public function test_standalone_mode_does_not_require_a_tenant_resolver(): void + { + config(['subbase.tenancy.enabled' => false, 'subbase.tenancy.access' => null]); + + $this->assertTrue(SubbaseTenancy::allows(new TenantRecord, 'view', new User)); + } +} From d6eb2755a30c18a90bf97124a5ac908bc01c7f01 Mon Sep 17 00:00:00 2001 From: mstfkhazaal <47450090+mstfkhazaal@users.noreply.github.com> Date: Thu, 29 Oct 2026 09:48:54 +0200 Subject: [PATCH 14/45] feat: tenant-scope Filament plan, discount and subscription resource queries --- .../Resources/Discounts/DiscountResource.php | 27 ++++++++++++------- src/Filament/Resources/Plans/PlanResource.php | 27 ++++++++++++------- .../Subscriptions/SubscriptionResource.php | 23 ++++++++++------ src/Policies/DiscountPolicy.php | 12 ++++----- src/Policies/PlanPolicy.php | 12 ++++----- src/Policies/SubscriptionPolicy.php | 12 ++++----- 6 files changed, 67 insertions(+), 46 deletions(-) diff --git a/src/Filament/Resources/Discounts/DiscountResource.php b/src/Filament/Resources/Discounts/DiscountResource.php index d8d72ac..8eaec45 100644 --- a/src/Filament/Resources/Discounts/DiscountResource.php +++ b/src/Filament/Resources/Discounts/DiscountResource.php @@ -11,6 +11,7 @@ use Nafiswatsiq\Subbase\Filament\Resources\Discounts\Tables\DiscountsTable; use Nafiswatsiq\Subbase\Models\Discount; use Nafiswatsiq\Subbase\Support\SubbasePermission; +use Nafiswatsiq\Subbase\Support\SubbaseTenancy; use BackedEnum; use Filament\Resources\Resource; use Filament\Schemas\Schema; @@ -45,12 +46,12 @@ public static function canCreate(): bool public static function canEdit(Model $record): bool { - return SubbasePermission::allows(config('subbase.permissions.discount'), 'update', static::getModel()); + return SubbasePermission::allows(config('subbase.permissions.discount'), 'update', static::getModel()), null, $record); } public static function canDelete(Model $record): bool { - return SubbasePermission::allows(config('subbase.permissions.discount'), 'delete', static::getModel()); + return SubbasePermission::allows(config('subbase.permissions.discount'), 'delete', static::getModel()), null, $record); } public static function canDeleteAny(): bool @@ -60,7 +61,7 @@ public static function canDeleteAny(): bool public static function canForceDelete(Model $record): bool { - return SubbasePermission::allows(config('subbase.permissions.discount'), 'forceDelete', static::getModel()); + return SubbasePermission::allows(config('subbase.permissions.discount'), 'forceDelete', static::getModel()), null, $record); } public static function canForceDeleteAny(): bool @@ -70,7 +71,7 @@ public static function canForceDeleteAny(): bool public static function canRestore(Model $record): bool { - return SubbasePermission::allows(config('subbase.permissions.discount'), 'restore', static::getModel()); + return SubbasePermission::allows(config('subbase.permissions.discount'), 'restore', static::getModel()), null, $record); } public static function canRestoreAny(): bool @@ -80,12 +81,12 @@ public static function canRestoreAny(): bool public static function canReplicate(Model $record): bool { - return SubbasePermission::allows(config('subbase.permissions.discount'), 'replicate', static::getModel()); + return SubbasePermission::allows(config('subbase.permissions.discount'), 'replicate', static::getModel()), null, $record); } public static function canView(Model $record): bool { - return SubbasePermission::allows(config('subbase.permissions.discount'), 'view', static::getModel()); + return SubbasePermission::allows(config('subbase.permissions.discount'), 'view', static::getModel()), null, $record); } public static function getNavigationLabel(): string @@ -105,7 +106,7 @@ public static function form(Schema $schema): Schema public static function getNavigationBadge(): ?string { - return (string) static::getModel()::count(); + return (string) static::getEloquentQuery()->count(); } public static function table(Table $table): Table @@ -127,11 +128,17 @@ public static function getPages(): array ]; } + public static function getEloquentQuery(): Builder + { + return SubbaseTenancy::scope(parent::getEloquentQuery()); + } + public static function getRecordRouteBindingEloquentQuery(): Builder { - return parent::getRecordRouteBindingEloquentQuery() - ->withoutGlobalScopes([ + return SubbaseTenancy::scope( + parent::getRecordRouteBindingEloquentQuery()->withoutGlobalScopes([ SoftDeletingScope::class, - ]); + ]), + ); } } \ No newline at end of file diff --git a/src/Filament/Resources/Plans/PlanResource.php b/src/Filament/Resources/Plans/PlanResource.php index 814b878..f5035f8 100644 --- a/src/Filament/Resources/Plans/PlanResource.php +++ b/src/Filament/Resources/Plans/PlanResource.php @@ -12,6 +12,7 @@ use Nafiswatsiq\Subbase\Filament\Resources\Plans\Tables\PlansTable; use Nafiswatsiq\Subbase\Models\Plan; use Nafiswatsiq\Subbase\Support\SubbasePermission; +use Nafiswatsiq\Subbase\Support\SubbaseTenancy; use BackedEnum; use Filament\Resources\Resource; use Filament\Schemas\Schema; @@ -46,12 +47,12 @@ public static function canCreate(): bool public static function canEdit(Model $record): bool { - return SubbasePermission::allows(config('subbase.permissions.plan'), 'update', static::getModel()); + return SubbasePermission::allows(config('subbase.permissions.plan'), 'update', static::getModel()), null, $record); } public static function canDelete(Model $record): bool { - return SubbasePermission::allows(config('subbase.permissions.plan'), 'delete', static::getModel()); + return SubbasePermission::allows(config('subbase.permissions.plan'), 'delete', static::getModel()), null, $record); } public static function canDeleteAny(): bool @@ -61,7 +62,7 @@ public static function canDeleteAny(): bool public static function canForceDelete(Model $record): bool { - return SubbasePermission::allows(config('subbase.permissions.plan'), 'forceDelete', static::getModel()); + return SubbasePermission::allows(config('subbase.permissions.plan'), 'forceDelete', static::getModel()), null, $record); } public static function canForceDeleteAny(): bool @@ -71,7 +72,7 @@ public static function canForceDeleteAny(): bool public static function canRestore(Model $record): bool { - return SubbasePermission::allows(config('subbase.permissions.plan'), 'restore', static::getModel()); + return SubbasePermission::allows(config('subbase.permissions.plan'), 'restore', static::getModel()), null, $record); } public static function canRestoreAny(): bool @@ -81,12 +82,12 @@ public static function canRestoreAny(): bool public static function canReplicate(Model $record): bool { - return SubbasePermission::allows(config('subbase.permissions.plan'), 'replicate', static::getModel()); + return SubbasePermission::allows(config('subbase.permissions.plan'), 'replicate', static::getModel()), null, $record); } public static function canView(Model $record): bool { - return SubbasePermission::allows(config('subbase.permissions.plan'), 'view', static::getModel()); + return SubbasePermission::allows(config('subbase.permissions.plan'), 'view', static::getModel()), null, $record); } public static function getNavigationLabel(): string @@ -106,7 +107,7 @@ public static function form(Schema $schema): Schema public static function getNavigationBadge(): ?string { - return (string) static::getModel()::count(); + return (string) static::getEloquentQuery()->count(); } public static function table(Table $table): Table @@ -130,11 +131,17 @@ public static function getPages(): array ]; } + public static function getEloquentQuery(): Builder + { + return SubbaseTenancy::scope(parent::getEloquentQuery()); + } + public static function getRecordRouteBindingEloquentQuery(): Builder { - return parent::getRecordRouteBindingEloquentQuery() - ->withoutGlobalScopes([ + return SubbaseTenancy::scope( + parent::getRecordRouteBindingEloquentQuery()->withoutGlobalScopes([ SoftDeletingScope::class, - ]); + ]), + ); } } \ No newline at end of file diff --git a/src/Filament/Resources/Subscriptions/SubscriptionResource.php b/src/Filament/Resources/Subscriptions/SubscriptionResource.php index 6d90180..84aa1b3 100644 --- a/src/Filament/Resources/Subscriptions/SubscriptionResource.php +++ b/src/Filament/Resources/Subscriptions/SubscriptionResource.php @@ -11,6 +11,7 @@ use Nafiswatsiq\Subbase\Filament\Resources\Subscriptions\Tables\SubscriptionsTable; use Nafiswatsiq\Subbase\Models\Subscription; use Nafiswatsiq\Subbase\Support\SubbasePermission; +use Nafiswatsiq\Subbase\Support\SubbaseTenancy; use BackedEnum; use Filament\Resources\Resource; use Filament\Schemas\Schema; @@ -45,12 +46,12 @@ public static function canCreate(): bool public static function canEdit(Model $record): bool { - return SubbasePermission::allows(config('subbase.permissions.subscription'), 'update', static::getModel()); + return SubbasePermission::allows(config('subbase.permissions.subscription'), 'update', static::getModel()), null, $record); } public static function canDelete(Model $record): bool { - return SubbasePermission::allows(config('subbase.permissions.subscription'), 'delete', static::getModel()); + return SubbasePermission::allows(config('subbase.permissions.subscription'), 'delete', static::getModel()), null, $record); } public static function canDeleteAny(): bool @@ -60,7 +61,7 @@ public static function canDeleteAny(): bool public static function canForceDelete(Model $record): bool { - return SubbasePermission::allows(config('subbase.permissions.subscription'), 'forceDelete', static::getModel()); + return SubbasePermission::allows(config('subbase.permissions.subscription'), 'forceDelete', static::getModel()), null, $record); } public static function canForceDeleteAny(): bool @@ -70,7 +71,7 @@ public static function canForceDeleteAny(): bool public static function canRestore(Model $record): bool { - return SubbasePermission::allows(config('subbase.permissions.subscription'), 'restore', static::getModel()); + return SubbasePermission::allows(config('subbase.permissions.subscription'), 'restore', static::getModel()), null, $record); } public static function canRestoreAny(): bool @@ -80,7 +81,7 @@ public static function canRestoreAny(): bool public static function canView(Model $record): bool { - return SubbasePermission::allows(config('subbase.permissions.subscription'), 'view', static::getModel()); + return SubbasePermission::allows(config('subbase.permissions.subscription'), 'view', static::getModel()), null, $record); } public static function getNavigationLabel(): string @@ -119,11 +120,17 @@ public static function getPages(): array ]; } + public static function getEloquentQuery(): Builder + { + return SubbaseTenancy::scope(parent::getEloquentQuery()); + } + public static function getRecordRouteBindingEloquentQuery(): Builder { - return parent::getRecordRouteBindingEloquentQuery() - ->withoutGlobalScopes([ + return SubbaseTenancy::scope( + parent::getRecordRouteBindingEloquentQuery()->withoutGlobalScopes([ SoftDeletingScope::class, - ]); + ]), + ); } } \ No newline at end of file diff --git a/src/Policies/DiscountPolicy.php b/src/Policies/DiscountPolicy.php index 5c28d5e..c852baf 100644 --- a/src/Policies/DiscountPolicy.php +++ b/src/Policies/DiscountPolicy.php @@ -20,7 +20,7 @@ public function viewAny(AuthUser $authUser): bool public function view(AuthUser $authUser, Discount $discount): bool { - return SubbasePermission::allows(config('subbase.permissions.discount'), 'view', Discount::class, $authUser); + return SubbasePermission::allows(config('subbase.permissions.discount'), 'view', Discount::class, $authUser, $discount); } public function create(AuthUser $authUser): bool @@ -30,12 +30,12 @@ public function create(AuthUser $authUser): bool public function update(AuthUser $authUser, Discount $discount): bool { - return SubbasePermission::allows(config('subbase.permissions.discount'), 'update', Discount::class, $authUser); + return SubbasePermission::allows(config('subbase.permissions.discount'), 'update', Discount::class, $authUser, $discount); } public function delete(AuthUser $authUser, Discount $discount): bool { - return SubbasePermission::allows(config('subbase.permissions.discount'), 'delete', Discount::class, $authUser); + return SubbasePermission::allows(config('subbase.permissions.discount'), 'delete', Discount::class, $authUser, $discount); } public function deleteAny(AuthUser $authUser): bool @@ -45,12 +45,12 @@ public function deleteAny(AuthUser $authUser): bool public function restore(AuthUser $authUser, Discount $discount): bool { - return SubbasePermission::allows(config('subbase.permissions.discount'), 'restore', Discount::class, $authUser); + return SubbasePermission::allows(config('subbase.permissions.discount'), 'restore', Discount::class, $authUser, $discount); } public function forceDelete(AuthUser $authUser, Discount $discount): bool { - return SubbasePermission::allows(config('subbase.permissions.discount'), 'forceDelete', Discount::class, $authUser); + return SubbasePermission::allows(config('subbase.permissions.discount'), 'forceDelete', Discount::class, $authUser, $discount); } public function forceDeleteAny(AuthUser $authUser): bool @@ -65,7 +65,7 @@ public function restoreAny(AuthUser $authUser): bool public function replicate(AuthUser $authUser, Discount $discount): bool { - return SubbasePermission::allows(config('subbase.permissions.discount'), 'replicate', Discount::class, $authUser); + return SubbasePermission::allows(config('subbase.permissions.discount'), 'replicate', Discount::class, $authUser, $discount); } public function reorder(AuthUser $authUser): bool diff --git a/src/Policies/PlanPolicy.php b/src/Policies/PlanPolicy.php index 8fc2326..542b1d6 100644 --- a/src/Policies/PlanPolicy.php +++ b/src/Policies/PlanPolicy.php @@ -20,7 +20,7 @@ public function viewAny(AuthUser $authUser): bool public function view(AuthUser $authUser, Plan $plan): bool { - return SubbasePermission::allows(config('subbase.permissions.plan'), 'view', Plan::class, $authUser); + return SubbasePermission::allows(config('subbase.permissions.plan'), 'view', Plan::class, $authUser, $plan); } public function create(AuthUser $authUser): bool @@ -30,12 +30,12 @@ public function create(AuthUser $authUser): bool public function update(AuthUser $authUser, Plan $plan): bool { - return SubbasePermission::allows(config('subbase.permissions.plan'), 'update', Plan::class, $authUser); + return SubbasePermission::allows(config('subbase.permissions.plan'), 'update', Plan::class, $authUser, $plan); } public function delete(AuthUser $authUser, Plan $plan): bool { - return SubbasePermission::allows(config('subbase.permissions.plan'), 'delete', Plan::class, $authUser); + return SubbasePermission::allows(config('subbase.permissions.plan'), 'delete', Plan::class, $authUser, $plan); } public function deleteAny(AuthUser $authUser): bool @@ -45,12 +45,12 @@ public function deleteAny(AuthUser $authUser): bool public function restore(AuthUser $authUser, Plan $plan): bool { - return SubbasePermission::allows(config('subbase.permissions.plan'), 'restore', Plan::class, $authUser); + return SubbasePermission::allows(config('subbase.permissions.plan'), 'restore', Plan::class, $authUser, $plan); } public function forceDelete(AuthUser $authUser, Plan $plan): bool { - return SubbasePermission::allows(config('subbase.permissions.plan'), 'forceDelete', Plan::class, $authUser); + return SubbasePermission::allows(config('subbase.permissions.plan'), 'forceDelete', Plan::class, $authUser, $plan); } public function forceDeleteAny(AuthUser $authUser): bool @@ -65,7 +65,7 @@ public function restoreAny(AuthUser $authUser): bool public function replicate(AuthUser $authUser, Plan $plan): bool { - return SubbasePermission::allows(config('subbase.permissions.plan'), 'replicate', Plan::class, $authUser); + return SubbasePermission::allows(config('subbase.permissions.plan'), 'replicate', Plan::class, $authUser, $plan); } public function reorder(AuthUser $authUser): bool diff --git a/src/Policies/SubscriptionPolicy.php b/src/Policies/SubscriptionPolicy.php index 93042cc..e15dad9 100644 --- a/src/Policies/SubscriptionPolicy.php +++ b/src/Policies/SubscriptionPolicy.php @@ -20,7 +20,7 @@ public function viewAny(AuthUser $authUser): bool public function view(AuthUser $authUser, Subscription $subscription): bool { - return SubbasePermission::allows(config('subbase.permissions.subscription'), 'view', Subscription::class, $authUser); + return SubbasePermission::allows(config('subbase.permissions.subscription'), 'view', Subscription::class, $authUser, $subscription); } public function create(AuthUser $authUser): bool @@ -30,12 +30,12 @@ public function create(AuthUser $authUser): bool public function update(AuthUser $authUser, Subscription $subscription): bool { - return SubbasePermission::allows(config('subbase.permissions.subscription'), 'update', Subscription::class, $authUser); + return SubbasePermission::allows(config('subbase.permissions.subscription'), 'update', Subscription::class, $authUser, $subscription); } public function delete(AuthUser $authUser, Subscription $subscription): bool { - return SubbasePermission::allows(config('subbase.permissions.subscription'), 'delete', Subscription::class, $authUser); + return SubbasePermission::allows(config('subbase.permissions.subscription'), 'delete', Subscription::class, $authUser, $subscription); } public function deleteAny(AuthUser $authUser): bool @@ -45,12 +45,12 @@ public function deleteAny(AuthUser $authUser): bool public function restore(AuthUser $authUser, Subscription $subscription): bool { - return SubbasePermission::allows(config('subbase.permissions.subscription'), 'restore', Subscription::class, $authUser); + return SubbasePermission::allows(config('subbase.permissions.subscription'), 'restore', Subscription::class, $authUser, $subscription); } public function forceDelete(AuthUser $authUser, Subscription $subscription): bool { - return SubbasePermission::allows(config('subbase.permissions.subscription'), 'forceDelete', Subscription::class, $authUser); + return SubbasePermission::allows(config('subbase.permissions.subscription'), 'forceDelete', Subscription::class, $authUser, $subscription); } public function forceDeleteAny(AuthUser $authUser): bool @@ -65,7 +65,7 @@ public function restoreAny(AuthUser $authUser): bool public function replicate(AuthUser $authUser, Subscription $subscription): bool { - return SubbasePermission::allows(config('subbase.permissions.subscription'), 'replicate', Subscription::class, $authUser); + return SubbasePermission::allows(config('subbase.permissions.subscription'), 'replicate', Subscription::class, $authUser, $subscription); } public function reorder(AuthUser $authUser): bool From 76361fde08a05fb783f4f7f35f0b41523d835895 Mon Sep 17 00:00:00 2001 From: mstfkhazaal <47450090+mstfkhazaal@users.noreply.github.com> Date: Thu, 29 Oct 2026 09:49:20 +0200 Subject: [PATCH 15/45] fix: correct tenant-aware resource permission method arguments --- .../Resources/Discounts/DiscountResource.php | 12 ++++++------ src/Filament/Resources/Plans/PlanResource.php | 12 ++++++------ .../Resources/Subscriptions/SubscriptionResource.php | 10 +++++----- 3 files changed, 17 insertions(+), 17 deletions(-) diff --git a/src/Filament/Resources/Discounts/DiscountResource.php b/src/Filament/Resources/Discounts/DiscountResource.php index 8eaec45..70b7a94 100644 --- a/src/Filament/Resources/Discounts/DiscountResource.php +++ b/src/Filament/Resources/Discounts/DiscountResource.php @@ -46,12 +46,12 @@ public static function canCreate(): bool public static function canEdit(Model $record): bool { - return SubbasePermission::allows(config('subbase.permissions.discount'), 'update', static::getModel()), null, $record); + return SubbasePermission::allows(config('subbase.permissions.discount'), 'update', static::getModel(), null, $record); } public static function canDelete(Model $record): bool { - return SubbasePermission::allows(config('subbase.permissions.discount'), 'delete', static::getModel()), null, $record); + return SubbasePermission::allows(config('subbase.permissions.discount'), 'delete', static::getModel(), null, $record); } public static function canDeleteAny(): bool @@ -61,7 +61,7 @@ public static function canDeleteAny(): bool public static function canForceDelete(Model $record): bool { - return SubbasePermission::allows(config('subbase.permissions.discount'), 'forceDelete', static::getModel()), null, $record); + return SubbasePermission::allows(config('subbase.permissions.discount'), 'forceDelete', static::getModel(), null, $record); } public static function canForceDeleteAny(): bool @@ -71,7 +71,7 @@ public static function canForceDeleteAny(): bool public static function canRestore(Model $record): bool { - return SubbasePermission::allows(config('subbase.permissions.discount'), 'restore', static::getModel()), null, $record); + return SubbasePermission::allows(config('subbase.permissions.discount'), 'restore', static::getModel(), null, $record); } public static function canRestoreAny(): bool @@ -81,12 +81,12 @@ public static function canRestoreAny(): bool public static function canReplicate(Model $record): bool { - return SubbasePermission::allows(config('subbase.permissions.discount'), 'replicate', static::getModel()), null, $record); + return SubbasePermission::allows(config('subbase.permissions.discount'), 'replicate', static::getModel(), null, $record); } public static function canView(Model $record): bool { - return SubbasePermission::allows(config('subbase.permissions.discount'), 'view', static::getModel()), null, $record); + return SubbasePermission::allows(config('subbase.permissions.discount'), 'view', static::getModel(), null, $record); } public static function getNavigationLabel(): string diff --git a/src/Filament/Resources/Plans/PlanResource.php b/src/Filament/Resources/Plans/PlanResource.php index f5035f8..4d6d2f8 100644 --- a/src/Filament/Resources/Plans/PlanResource.php +++ b/src/Filament/Resources/Plans/PlanResource.php @@ -47,12 +47,12 @@ public static function canCreate(): bool public static function canEdit(Model $record): bool { - return SubbasePermission::allows(config('subbase.permissions.plan'), 'update', static::getModel()), null, $record); + return SubbasePermission::allows(config('subbase.permissions.plan'), 'update', static::getModel(), null, $record); } public static function canDelete(Model $record): bool { - return SubbasePermission::allows(config('subbase.permissions.plan'), 'delete', static::getModel()), null, $record); + return SubbasePermission::allows(config('subbase.permissions.plan'), 'delete', static::getModel(), null, $record); } public static function canDeleteAny(): bool @@ -62,7 +62,7 @@ public static function canDeleteAny(): bool public static function canForceDelete(Model $record): bool { - return SubbasePermission::allows(config('subbase.permissions.plan'), 'forceDelete', static::getModel()), null, $record); + return SubbasePermission::allows(config('subbase.permissions.plan'), 'forceDelete', static::getModel(), null, $record); } public static function canForceDeleteAny(): bool @@ -72,7 +72,7 @@ public static function canForceDeleteAny(): bool public static function canRestore(Model $record): bool { - return SubbasePermission::allows(config('subbase.permissions.plan'), 'restore', static::getModel()), null, $record); + return SubbasePermission::allows(config('subbase.permissions.plan'), 'restore', static::getModel(), null, $record); } public static function canRestoreAny(): bool @@ -82,12 +82,12 @@ public static function canRestoreAny(): bool public static function canReplicate(Model $record): bool { - return SubbasePermission::allows(config('subbase.permissions.plan'), 'replicate', static::getModel()), null, $record); + return SubbasePermission::allows(config('subbase.permissions.plan'), 'replicate', static::getModel(), null, $record); } public static function canView(Model $record): bool { - return SubbasePermission::allows(config('subbase.permissions.plan'), 'view', static::getModel()), null, $record); + return SubbasePermission::allows(config('subbase.permissions.plan'), 'view', static::getModel(), null, $record); } public static function getNavigationLabel(): string diff --git a/src/Filament/Resources/Subscriptions/SubscriptionResource.php b/src/Filament/Resources/Subscriptions/SubscriptionResource.php index 84aa1b3..7506f4d 100644 --- a/src/Filament/Resources/Subscriptions/SubscriptionResource.php +++ b/src/Filament/Resources/Subscriptions/SubscriptionResource.php @@ -46,12 +46,12 @@ public static function canCreate(): bool public static function canEdit(Model $record): bool { - return SubbasePermission::allows(config('subbase.permissions.subscription'), 'update', static::getModel()), null, $record); + return SubbasePermission::allows(config('subbase.permissions.subscription'), 'update', static::getModel(), null, $record); } public static function canDelete(Model $record): bool { - return SubbasePermission::allows(config('subbase.permissions.subscription'), 'delete', static::getModel()), null, $record); + return SubbasePermission::allows(config('subbase.permissions.subscription'), 'delete', static::getModel(), null, $record); } public static function canDeleteAny(): bool @@ -61,7 +61,7 @@ public static function canDeleteAny(): bool public static function canForceDelete(Model $record): bool { - return SubbasePermission::allows(config('subbase.permissions.subscription'), 'forceDelete', static::getModel()), null, $record); + return SubbasePermission::allows(config('subbase.permissions.subscription'), 'forceDelete', static::getModel(), null, $record); } public static function canForceDeleteAny(): bool @@ -71,7 +71,7 @@ public static function canForceDeleteAny(): bool public static function canRestore(Model $record): bool { - return SubbasePermission::allows(config('subbase.permissions.subscription'), 'restore', static::getModel()), null, $record); + return SubbasePermission::allows(config('subbase.permissions.subscription'), 'restore', static::getModel(), null, $record); } public static function canRestoreAny(): bool @@ -81,7 +81,7 @@ public static function canRestoreAny(): bool public static function canView(Model $record): bool { - return SubbasePermission::allows(config('subbase.permissions.subscription'), 'view', static::getModel()), null, $record); + return SubbasePermission::allows(config('subbase.permissions.subscription'), 'view', static::getModel(), null, $record); } public static function getNavigationLabel(): string From 55215b9dd4ae9f95c8b518d75fa7456f85f13df2 Mon Sep 17 00:00:00 2001 From: mstfkhazaal <47450090+mstfkhazaal@users.noreply.github.com> Date: Thu, 29 Oct 2026 09:49:45 +0200 Subject: [PATCH 16/45] style: align new billing security and integration test code with Pint --- src/Support/SubbaseTenancy.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Support/SubbaseTenancy.php b/src/Support/SubbaseTenancy.php index 65a360a..c57920c 100644 --- a/src/Support/SubbaseTenancy.php +++ b/src/Support/SubbaseTenancy.php @@ -19,13 +19,13 @@ public static function enabled(): bool public static function scope(Builder $query): Builder { - if (!self::enabled()) { + if (! self::enabled()) { return $query; } $actor = Auth::user(); $resolver = self::resolver(); - if (!$actor instanceof Authenticatable || !$resolver) { + if (! $actor instanceof Authenticatable || ! $resolver) { return $query->whereRaw('1 = 0'); } @@ -34,7 +34,7 @@ public static function scope(Builder $query): Builder public static function allows(?Model $record, string $ability, Authenticatable $actor): bool { - if (!self::enabled()) { + if (! self::enabled()) { return true; } @@ -46,7 +46,7 @@ public static function allows(?Model $record, string $ability, Authenticatable $ private static function resolver(): ?TenantAccess { $class = config('subbase.tenancy.access'); - if (!is_string($class) || !is_a($class, TenantAccess::class, true)) { + if (! is_string($class) || ! is_a($class, TenantAccess::class, true)) { return null; } From f9f8017fd5457ecbb23febc52bd1d2abaf447cf1 Mon Sep 17 00:00:00 2001 From: mstfkhazaal <47450090+mstfkhazaal@users.noreply.github.com> Date: Thu, 29 Oct 2026 09:53:00 +0200 Subject: [PATCH 17/45] test: verify forward decimal precision migration retains historical prices --- tests/Money/PrecisionMigrationTest.php | 54 ++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 tests/Money/PrecisionMigrationTest.php diff --git a/tests/Money/PrecisionMigrationTest.php b/tests/Money/PrecisionMigrationTest.php new file mode 100644 index 0000000..7e72780 --- /dev/null +++ b/tests/Money/PrecisionMigrationTest.php @@ -0,0 +1,54 @@ + 'sb_test_plans_precision', + 'subbase.tables.discounts' => 'sb_test_discounts_precision', + ]); + + Schema::create('sb_test_plans_precision', static function (Blueprint $table): void { + $table->id(); + $table->decimal('price', 18, 2); + $table->decimal('signup_fee', 18, 2); + }); + Schema::create('sb_test_discounts_precision', static function (Blueprint $table): void { + $table->id(); + $table->decimal('value', 15, 2); + $table->decimal('min_amount', 15, 2)->nullable(); + }); + Schema::create('discount_subscription', static function (Blueprint $table): void { + $table->id(); + $table->decimal('discounted_amount', 15, 2)->nullable(); + $table->decimal('original_amount', 15, 2)->nullable(); + }); + + DB::table('sb_test_plans_precision')->insert([ + 'id' => 1, 'price' => '12.50', 'signup_fee' => '2.00', + ]); + + $migration = require dirname(__DIR__, 2).'/database/migrations/upgrade_billing_decimal_columns.php'; + $migration->up(); + + $this->assertSame(0, bccomp((string) DB::table('sb_test_plans_precision')->value('price'), '12.50', 4)); + + DB::table('sb_test_plans_precision')->where('id', 1)->update([ + 'price' => '1.2345', + 'signup_fee' => '0.001', + ]); + + $this->assertSame(0, bccomp((string) DB::table('sb_test_plans_precision')->value('price'), '1.2345', 4)); + $this->assertSame(0, bccomp((string) DB::table('sb_test_plans_precision')->value('signup_fee'), '0.001', 4)); + } +} From 26538fbd3dd299bfadadec6ed5efc44a2cac0d2e Mon Sep 17 00:00:00 2001 From: mstfkhazaal <47450090+mstfkhazaal@users.noreply.github.com> Date: Thu, 29 Oct 2026 09:53:07 +0200 Subject: [PATCH 18/45] ci: include precise price migration integration test in formatting gate --- .github/workflows/tests.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index a7c1c9e..441d651 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -20,5 +20,5 @@ jobs: - run: composer update --no-interaction --prefer-dist - run: vendor/bin/phpunit # The upstream fork has pre-existing style drift. Format existing files in a separate PR. - - run: vendor/bin/pint --test src/Support/SubbasePermission.php tests/TestCase.php tests/Authorization/SubbasePermissionTest.php src/Support/Money.php tests/Money/MoneyTest.php src/Support/SubbaseTenancy.php src/Contracts/TenantAccess.php tests/Tenancy/SubbaseTenancyTest.php + - run: vendor/bin/pint --test src/Support/SubbasePermission.php tests/TestCase.php tests/Authorization/SubbasePermissionTest.php src/Support/Money.php tests/Money/MoneyTest.php src/Support/SubbaseTenancy.php src/Contracts/TenantAccess.php tests/Tenancy/SubbaseTenancyTest.php tests/Money/PrecisionMigrationTest.php - run: composer audit --no-dev From 1fc32581771c2dbd0937240d0890287476e89e12 Mon Sep 17 00:00:00 2001 From: mstfkhazaal <47450090+mstfkhazaal@users.noreply.github.com> Date: Thu, 29 Oct 2026 09:53:59 +0200 Subject: [PATCH 19/45] test: verify exact percent discounts across currency-specific plan prices --- tests/Money/ExactPricingTest.php | 107 +++++++++++++++++++++++++++++++ 1 file changed, 107 insertions(+) create mode 100644 tests/Money/ExactPricingTest.php diff --git a/tests/Money/ExactPricingTest.php b/tests/Money/ExactPricingTest.php new file mode 100644 index 0000000..c71c461 --- /dev/null +++ b/tests/Money/ExactPricingTest.php @@ -0,0 +1,107 @@ + 'sb_pricing_plans', + 'subbase.tables.discounts' => 'discounts', + ]); + + Schema::create('sb_pricing_plans', static function (Blueprint $table): void { + $table->id(); + $table->string('slug'); + $table->text('name'); + $table->text('description')->nullable(); + $table->decimal('price', 20, 4); + $table->char('currency', 3); + $table->json('prices'); + $table->boolean('is_active')->default(true); + $table->timestamps(); + $table->softDeletes(); + }); + + Schema::create('discounts', static function (Blueprint $table): void { + $table->id(); + $table->string('name'); + $table->string('code'); + $table->string('type'); + $table->decimal('value', 20, 4); + $table->decimal('min_amount', 20, 4)->nullable(); + $table->char('currency', 3)->nullable(); + $table->boolean('is_active')->default(true); + $table->unsignedInteger('used_count')->default(0); + $table->unsignedInteger('max_uses')->nullable(); + $table->timestamp('starts_at')->nullable(); + $table->timestamp('expires_at')->nullable(); + $table->unsignedSmallInteger('priority')->default(0); + $table->timestamps(); + $table->softDeletes(); + }); + + Schema::create('discount_plan', static function (Blueprint $table): void { + $table->id(); + $table->unsignedBigInteger('plan_id'); + $table->unsignedBigInteger('discount_id'); + }); + + DB::table('sb_pricing_plans')->insert([ + 'id' => 1, + 'name' => json_encode(['en' => 'Plan'], JSON_THROW_ON_ERROR), + 'slug' => 'plan', + 'price' => '1.235', + 'currency' => 'KWD', + 'prices' => json_encode(['KWD' => '1.235', 'USD' => '0.30'], JSON_THROW_ON_ERROR), + 'created_at' => now(), + 'updated_at' => now(), + ]); + DB::table('discounts')->insert([ + 'id' => 1, + 'name' => 'Ten percent', + 'code' => 'TEN', + 'type' => 'percentage', + 'value' => '10', + 'currency' => 'KWD', + 'is_active' => true, + 'priority' => 10, + 'created_at' => now(), + 'updated_at' => now(), + ]); + DB::table('discount_plan')->insert(['plan_id' => 1, 'discount_id' => 1]); + } + + public function test_exact_quote_applies_priority_discount_without_float(): void + { + $plan = Plan::query()->findOrFail(1); + $quote = PlanPriceHelper::resolveExactWithDiscounts($plan, 'KWD'); + + $this->assertSame('1.235', $quote['original_amount']); + $this->assertSame('0.124', $quote['discount_amount']); + $this->assertSame('1.111', $quote['final_amount']); + $this->assertSame('KWD', $quote['currency']); + } + + public function test_discount_only_applies_to_matching_currency(): void + { + $plan = Plan::query()->findOrFail(1); + $quote = PlanPriceHelper::resolveExactWithDiscounts($plan, 'USD'); + + $this->assertSame('0.30', $quote['original_amount']); + $this->assertSame('0.00', $quote['discount_amount']); + $this->assertSame('0.30', $quote['final_amount']); + } +} From e191a5062fb803c500c242287a5f8a4dab38d2cd Mon Sep 17 00:00:00 2001 From: mstfkhazaal <47450090+mstfkhazaal@users.noreply.github.com> Date: Thu, 29 Oct 2026 09:54:04 +0200 Subject: [PATCH 20/45] ci: lint exact multi-currency pricing regression tests --- .github/workflows/tests.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 441d651..1b3ba7b 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -20,5 +20,5 @@ jobs: - run: composer update --no-interaction --prefer-dist - run: vendor/bin/phpunit # The upstream fork has pre-existing style drift. Format existing files in a separate PR. - - run: vendor/bin/pint --test src/Support/SubbasePermission.php tests/TestCase.php tests/Authorization/SubbasePermissionTest.php src/Support/Money.php tests/Money/MoneyTest.php src/Support/SubbaseTenancy.php src/Contracts/TenantAccess.php tests/Tenancy/SubbaseTenancyTest.php tests/Money/PrecisionMigrationTest.php + - run: vendor/bin/pint --test src/Support/SubbasePermission.php tests/TestCase.php tests/Authorization/SubbasePermissionTest.php src/Support/Money.php tests/Money/MoneyTest.php src/Support/SubbaseTenancy.php src/Contracts/TenantAccess.php tests/Tenancy/SubbaseTenancyTest.php tests/Money/PrecisionMigrationTest.php tests/Money/ExactPricingTest.php - run: composer audit --no-dev From 22a91ad43d57be5cbc8a255ad8abc1d544a447d8 Mon Sep 17 00:00:00 2001 From: mstfkhazaal <47450090+mstfkhazaal@users.noreply.github.com> Date: Thu, 29 Oct 2026 09:55:44 +0200 Subject: [PATCH 21/45] chore: adopt FNX Software Composer identity while keeping legacy PHP namespace for migration --- composer.json | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/composer.json b/composer.json index 03ca2f0..00c92da 100644 --- a/composer.json +++ b/composer.json @@ -1,6 +1,6 @@ { - "name": "nafiswatsiq/subbase", - "description": "Filament plugin for advanced subscriptions", + "name": "fnx-software/subbase", + "description": "FNX Software universal subscription management for Laravel and Filament", "type": "library", "license": "MIT", "keywords": [ @@ -11,7 +11,7 @@ "billing", "multi-currency" ], - "homepage": "https://github.com/nafiswatsiq/subbase", + "homepage": "https://github.com/fnx-software/subbase", "authors": [ { "name": "Nafis Watsiq", @@ -50,5 +50,9 @@ "scripts": { "test": "phpunit", "lint": "pint --test" + }, + "support": { + "source": "https://github.com/fnx-software/subbase", + "issues": "https://github.com/fnx-software/subbase/pulls" } } From ed02d3e776b76057b7a70bfd51e7828d28365ee1 Mon Sep 17 00:00:00 2001 From: mstfkhazaal <47450090+mstfkhazaal@users.noreply.github.com> Date: Thu, 29 Oct 2026 09:58:06 +0200 Subject: [PATCH 22/45] docs: record exact monetary pricing, tenant scope, package usage and release blockers --- Changelog.md | 11 ++++++ README.md | 2 +- docs/INSTALLATION.md | 80 ++++++++++++++++++++++++++++++++++++++++++++ docs/PROGRESS.md | 57 ++++++++++++++++--------------- 4 files changed, 122 insertions(+), 28 deletions(-) create mode 100644 docs/INSTALLATION.md diff --git a/Changelog.md b/Changelog.md index 4580cd2..c78d3a5 100644 --- a/Changelog.md +++ b/Changelog.md @@ -12,3 +12,14 @@ ### Breaking behavior and outstanding work Existing apps that relied on permissive missing-Spatie access will be denied until they grant explicit Laravel Gate abilities. No existing app has been upgraded. Tenant record scoping and financial decimal precision are **not yet implemented**. A stable release and new Composer name are pending. + +## 2026-10-29 — Exact money, tenancy and package ownership + +- Added high-precision BCMath `Money` and currency scale policy; implemented exact checkout pricing alongside legacy presentation methods. +- Widened Plan/Discount columns and pivot to decimal(20,4) using a forward-only upgrade migration; tested migrations/pricing on isolated SQLite. +- Introduced optional fail-closed host-defined `TenantAccess`, scoped Filament resources and record-aware policies. +- Changed feature-branch Composer identity to `fnx-software/subbase` while preserving existing PHP namespace. +- Expanded Testbench suite to 19 tests/38 assertions (CI run 40838411564), with follow-up installation/upgrade tests still required. +- Added `docs/INSTALLATION.md` for safe path-repo sandbox integration. + +**Not yet released.** Multi-tenant end-to-end coverage, recurring billing, version tags, CRM/Zeno migration, and complete formatting/DB matrix are outstanding. diff --git a/README.md b/README.md index c549135..fde0232 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -> **FNX Software universal billing fork:** This repository is being developed as a reusable Laravel package for standalone and multi-tenant projects, with **no mandatory Fenix Accounts dependency**. Development is on [draft PR #2](https://github.com/fnx-software/subbase/pull/2), not on the stable `main` branch. The Composer package name and PHP namespace **still use the upstream `nafiswatsiq/*` identity** pending a coordinated major upgrade. Do not mistake `composer require nafiswatsiq/...` from Packagist for an installation of this fork. For current goals and implementation status, see [Progress](docs/PROGRESS.md) and [architecture](docs/UNIVERSAL-BILLING.md). +> **FNX Software Subbase fork:** One reusable subscriptions engine for standalone and multi-tenant Laravel projects. Feature-branch Composer name: `fnx-software/subbase` (default branch not migrated); PHP namespace stays `Nafiswatsiq\\Subbase`. The [implementation guide](docs/INSTALLATION.md), [progress tracker](docs/PROGRESS.md), and [draft PR #2](https://github.com/fnx-software/subbase/pull/2) document the status. **Do not install in production yet.** header diff --git a/docs/INSTALLATION.md b/docs/INSTALLATION.md new file mode 100644 index 0000000..cc9cabb --- /dev/null +++ b/docs/INSTALLATION.md @@ -0,0 +1,80 @@ +# FNX Subbase — installation and integration guide + +**Development branch only (2026-10-29).** This is not an approved production release. The default branch has the upstream Composer name; local path setup below deliberately uses the new feature branch identity. + +## 1. Safe local prototype installation + +From a fresh Laravel 13 + PHP 8.4 application with PostgreSQL (or isolated SQLite test database), clone **the requested feature branch** inside the application's `packages` directory: + +```bash +mkdir -p packages +git clone --branch feat/universal-billing-foundation https://github.com/fnx-software/subbase.git packages/subbase +composer config repositories.fnx-subbase --json '{"type":"path","url":"packages/subbase","options":{"symlink":true,"versions":{"fnx-software/subbase":"dev-feat/universal-billing-foundation"}}}' +composer require 'fnx-software/subbase:dev-feat/universal-billing-foundation' -W +php artisan subbase:install +php artisan migrate +``` + +Review the generated migrations before running them in existing projects. The package uses `laravelcm/laravel-subscriptions`, Spatie Package Tools and Filament 5. It now requires `ext-bcmath`. Once the default branch and releases are migrated, use tagged stable Composer versions instead of these feature branches. + +## 2. Choose a billable model + +Any persisted Eloquent model may own a subscription; this is the existing upstream trait: + +```php +use Illuminate\Database\Eloquent\Model; +use Laravelcm\Subscriptions\Traits\HasPlanSubscriptions; + +final class Organization extends Model +{ + use HasPlanSubscriptions; +} +``` + +Create a plan with the Subbase Filament resources, then the authorized host application can create a subscription: + +```php +$organization->newPlanSubscription('default', $plan); +``` + +**Caution:** This call grants access immediately. It is suitable only for free/manual/admin-authorized subscriptions. For paid plans, use the companion payment package's **verified webhook** flow, not direct subscription creation after browser redirect. + +## 3. Single-tenant versus multi-tenant + +For single-tenant/local user subscriptions the default is `subbase.tenancy.enabled = false`. + +For multi-tenant applications, implement `Nafiswatsiq\Subbase\Contracts\TenantAccess` in the host application and configure: + +```php +'tenancy' => [ + 'enabled' => true, + 'access' => \App\Billing\TenantBillingAccess::class, +], +``` + +Your implementation must scope `Builder` by the **authenticated actor's authorized tenant(s)** and check record-level access. If this feature is enabled with an unresolvable contract, queries and record permissions deny by default. This is *not* a substitute for host route policies and cross-tenant API/job/export isolation. + +## 4. Financial accuracy + +Use `Nafiswatsiq\Subbase\Support\Money` for arithmetic and `PlanPriceHelper::resolveExactWithDiscounts($plan, 'USD')` for checkout. Never use the older `float` presentation helpers to post payments. `Money` accepts and returns canonical decimal strings; `ext-bcmath` is required. + +The widening migration is intentionally non-reversible without a backup. Confirm precision and current production data before upgrading. + +## 5. How to use independent projects / Fenix + +- Standalone projects use their own users/organizations and database. +- Fenix SaaS apps can instead call a central billing API through an **optional app-level adapter**; that adapter is not in the package core. +- The package still exports `Nafiswatsiq\Subbase\...` PHP classes and `subbase` configuration keys, even though feature branch Composer name is now `fnx-software/subbase`. + +## 6. Testing, not production usage + +```bash +composer validate --no-check-publish --strict +composer audit +vendor/bin/phpunit +vendor/bin/pint --test +``` + +These commands are intended for the package checkout. Full Pint may report **pre-existing upstream violations** outside the new code. The feature-branch CI gates added files but a full-formatting PR is needed for stable release. + +Do not replace `nafiswatsiq/subbase` in CRM or Zeno with this feature branch until audited migration and fixture tests pass. diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 9166a38..fecdc7d 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -1,36 +1,39 @@ -# Subbase fork — progress +# FNX Subbase — verified development progress -Date: 2026-10-29. Product target: one standalone billing package across all Laravel applications, with an optional companion Subbase Payment package. +Updated: 2026-10-29. **Draft PR**: https://github.com/fnx-software/subbase/pull/2 -## Current milestone: Stage 0 / Stabilize +## Architecture decision -- [x] Identified `fnx-software/subbase` fork; original upstream `nafiswatsiq/subbase` (MIT). -- [x] Created `feat/universal-billing-foundation` feature branch; no modifications to `main`. -- [x] Implemented a fail-closed native Laravel Gate authorization helper with optional Spatie integration. -- [x] Policy methods use the provided actor and accept generic `Authenticatable` contracts. -- [x] PHPUnit/Testbench tests added for permission denial and explicit grant; PHP 8.4 Laravel 13 tests observed passing (5/5). -- [x] [Green CI](https://github.com/fnx-software/subbase/actions/runs/40828540923): 5 PHPUnit tests / 5 assertions; Composer audit and scoped new-file Pint succeeded. This is **not** a full business-behavior or legacy-formatting audit. -- [x] Documented independent Eloquent subscription owners and the no-Fenix-dependency decision. -- [ ] Complete reusable tenant-aware resource scoping and signed API adapters. -- [ ] Verified installation + upgrade in CRM and Zeno; do not change their installed packages yet. -- [ ] Full exact-decimal money and currency-scale refactor; currently original Plan/Discount floats are a known problem. -- [ ] Lifecycle/proration/usage/seat plans and end-to-end payment integration. -- [ ] Stable Composer identity as `fnx-software/subbase` and coordinated upgrade of the companion package. -- [ ] Full Pint baseline; 64 pre-existing style issues in upstream repo require a formatting-only PR. -- [ ] Multi-version PHP/Laravel/Filament test matrix, release and production readiness. +Subbase and its companion Subbase Payment are the **one owned subscription stack for ALL Laravel projects**, inside or outside Fenix. A separate central Fenix Accounts adapter is optional, NEVER part of the core dependency. Supports Eloquent billables such as User, School, Organization, Tenant. Does not replace application-specific Invoice/POS/School finance ledgers. -## Integration principles +## Implemented on feat/universal-billing-foundation -1. Standalone app: `User` or any custom Eloquent model with `HasPlanSubscriptions`. -2. Organization SaaS: use an authorized `Organization`/Tenant model; no user-as-tenant fallback. -3. Fenix Apps: Fenix Accounts adapter is optional and lives outside package core. -4. Payment plugin adds checkout; no paid entitlement until server-verified settlement. -5. Do not merge a breaking authorization or financial migration change until consumer apps and update guides are tested. +- [x] Composer package identity changed to `fnx-software/subbase` **on the feature branch**, PHP namespace remains `Nafiswatsiq\Subbase\` for existing source integrations. +- [x] Laravel Gate denies unauthorized access even if Spatie Permission is not installed. Policies use explicit actor; unauthorized users cannot automatically manage plans. +- [x] Optional tenant access resolver, fail-closed if enabled but unavailable, Filament Plan/Subscription/Discount query, record and route scoping. +- [x] Immutable BCMath `Money` value object with zero/two/three/four decimal currency precision and valid percent calculations. +- [x] Accurate `Plan::getPriceDecimalForCurrency()` / `PlanPriceHelper::resolveExactWithDiscounts()` for checkout alongside legacy display APIs. +- [x] Canonical decimal string price storage, `decimal:4` model casts, and forward-only widening migration for plan/discount/pivot fields. Avoid destructive down migrations. +- [x] Tested price migration and applied discounts in Laravel/Testbench, initially using SQLite. +- [x] PHP 8.4/Filament 5/Laravel 13 compatible CI running Composer validate/update, PHPUnit, scoped Pint and Composer audit. +- [x] [Last known green code run](https://github.com/fnx-software/subbase/actions/runs/40838411564): **19 tests / 38 assertions**; Composer rename itself requires latest CI confirmation. +- [x] Product architecture, developer usage, staged upgrade and implementation backlog documented. -## Continue next +## Remaining before stable release -Read `AGENTS.md`, `docs/PRODUCT-SPEC.md`, `docs/UNIVERSAL-BILLING.md`, `docs/SECURITY-MIGRATION.md` and this document. Add tests for each feature, link issues/PRs and update Changelog and this file with actual verification. Keep `main` unchanged until reviewed. +- [ ] Prove compatibility with real CRM and Zeno subscription data/migrations on PostgreSQL; keep their installed production package untouched. +- [ ] Full multi-tenancy isolation across relationship managers, actions, jobs, APIs and background processes; host must implement tenant-aware access. +- [ ] Finish scheduled recurring billing, trial/renewal/upgrade/downgrade, cancellation, grace, seat and usage quota enforcement with concurrency tests. +- [ ] Add optional headless core / Filament-independent package mode (Filament is currently in Composer `require`). +- [ ] Full UI/multi-language/RTL review, pricing and tax rule certification as applicable. +- [ ] Multi-DB matrix, backups and migration rollback, full legacy Pint cleanup (upstream baseline 64 violations), production/performance tests. +- [ ] Merge PR, align default-branch Composer identity, tag release and validate Packagist distribution. +- [ ] Real payment provider lifecycle; that work belongs to the companion package. -## Review +## Distribution warning -- [Draft pull request #2](https://github.com/fnx-software/subbase/pull/2) — branch remains separate from `main` pending consumer integration, full financial verification and release preparation. +The current `main` branch still uses `nafiswatsiq/subbase` as the Composer package identity. **Do not assume `composer require fnx-software/subbase` resolves publicly yet.** A safe feature-branch evaluation uses a *path* repository as documented in `docs/INSTALLATION.md`, and never an existing production app. + +## Continuation + +Read `AGENTS.md`, `docs/PRODUCT-SPEC.md`, `docs/INSTALLATION.md`, `docs/PROGRESS.md`, `docs/BACKLOG.md` and `docs/PRECISION-MIGRATION.md`. Keep PR Draft until financial and tenant gates pass. Update `Changelog.md` for every substantive change. From 05736bfe15b8a9050b229f9a9a2b84ef8c3462ad Mon Sep 17 00:00:00 2001 From: mstfkhazaal <47450090+mstfkhazaal@users.noreply.github.com> Date: Thu, 29 Oct 2026 10:00:02 +0200 Subject: [PATCH 23/45] feat: authorize subscription cancellation per billable tenant and test cross-org isolation --- .github/workflows/tests.yml | 2 +- src/Services/SubscriptionAdministration.php | 62 +++++++++ .../SubscriptionAdministrationTest.php | 125 ++++++++++++++++++ 3 files changed, 188 insertions(+), 1 deletion(-) create mode 100644 src/Services/SubscriptionAdministration.php create mode 100644 tests/Subscriptions/SubscriptionAdministrationTest.php diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 1b3ba7b..6fc9428 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -20,5 +20,5 @@ jobs: - run: composer update --no-interaction --prefer-dist - run: vendor/bin/phpunit # The upstream fork has pre-existing style drift. Format existing files in a separate PR. - - run: vendor/bin/pint --test src/Support/SubbasePermission.php tests/TestCase.php tests/Authorization/SubbasePermissionTest.php src/Support/Money.php tests/Money/MoneyTest.php src/Support/SubbaseTenancy.php src/Contracts/TenantAccess.php tests/Tenancy/SubbaseTenancyTest.php tests/Money/PrecisionMigrationTest.php tests/Money/ExactPricingTest.php + - run: vendor/bin/pint --test src/Support/SubbasePermission.php tests/TestCase.php tests/Authorization/SubbasePermissionTest.php src/Support/Money.php tests/Money/MoneyTest.php src/Support/SubbaseTenancy.php src/Contracts/TenantAccess.php tests/Tenancy/SubbaseTenancyTest.php tests/Money/PrecisionMigrationTest.php tests/Money/ExactPricingTest.php src/Services/SubscriptionAdministration.php tests/Subscriptions/SubscriptionAdministrationTest.php - run: composer audit --no-dev diff --git a/src/Services/SubscriptionAdministration.php b/src/Services/SubscriptionAdministration.php new file mode 100644 index 0000000..0ca3ca4 --- /dev/null +++ b/src/Services/SubscriptionAdministration.php @@ -0,0 +1,62 @@ +exists || !method_exists($billable, 'planSubscriptions')) { + throw new InvalidArgumentException('Subscription owner must be a saved, subscribable model.'); + } + + if (!preg_match('/^[A-Za-z0-9_-]{1,100}$/D', $subscriptionName)) { + throw new InvalidArgumentException('Subscription name is invalid.'); + } + + $ability = (string) config('subbase.permissions.manage_subscription', 'manageSubscription'); + + if (!SubbaseTenancy::allows($billable, 'cancel', $actor) + || !Gate::forUser($actor)->allows($ability, $billable) + ) { + throw new AuthorizationException('You cannot manage this subscription.'); + } + + return DB::transaction(function () use ($billable, $subscriptionName, $immediately): Subscription { + /** @var Subscription $subscription */ + $subscription = $billable->planSubscriptions() + ->where('slug', $subscriptionName) + ->lockForUpdate() + ->firstOrFail(); + + // Do not inadvertently extend a period or create new charges. + // Repeated cancellation is idempotent for the same mode. + if (!$subscription->canceled() || ($immediately && !$subscription->ended())) { + $subscription->cancel($immediately); + } + + return $subscription->refresh(); + }); + } +} diff --git a/tests/Subscriptions/SubscriptionAdministrationTest.php b/tests/Subscriptions/SubscriptionAdministrationTest.php new file mode 100644 index 0000000..70cb6e9 --- /dev/null +++ b/tests/Subscriptions/SubscriptionAdministrationTest.php @@ -0,0 +1,125 @@ +id(); + $table->string('name'); + $table->timestamps(); + }); + + Schema::create('sb_billing_subscriptions', static function (Blueprint $table): void { + $table->id(); + $table->string('subscriber_type'); + $table->unsignedBigInteger('subscriber_id'); + $table->string('slug'); + $table->unsignedBigInteger('plan_id'); + $table->text('name')->nullable(); + $table->text('description')->nullable(); + $table->timestamp('trial_ends_at')->nullable(); + $table->timestamp('starts_at')->nullable(); + $table->timestamp('ends_at')->nullable(); + $table->timestamp('canceled_at')->nullable(); + $table->timestamps(); + $table->softDeletes(); + }); + + config([ + 'laravel-subscriptions.models.subscription' => Subscription::class, + 'laravel-subscriptions.tables.subscriptions' => 'sb_billing_subscriptions', + 'subbase.tenancy.enabled' => false, + 'subbase.permissions.manage_subscription' => 'manageSubscription', + ]); + + DB::table('sb_billing_organizations')->insert([ + ['id' => 1, 'name' => 'Owner 1', 'created_at' => now(), 'updated_at' => now()], + ['id' => 2, 'name' => 'Owner 2', 'created_at' => now(), 'updated_at' => now()], + ]); + + foreach ([1, 2] as $id) { + DB::table('sb_billing_subscriptions')->insert([ + 'subscriber_type' => BillingOrganizationFixture::class, + 'subscriber_id' => $id, + 'slug' => 'default', + 'plan_id' => 1, + 'name' => json_encode(['en' => 'Subscription'], JSON_THROW_ON_ERROR), + 'starts_at' => now()->subDay(), + 'ends_at' => now()->addMonth(), + 'created_at' => now(), + 'updated_at' => now(), + ]); + } + + Gate::define('manageSubscription', fn (User $actor, Model $billable): bool => + $actor->name === 'owner' && $billable->getKey() === 1); + } + + public function test_authorized_owner_can_cancel_at_end_without_affecting_other_tenant(): void + { + $actor = new User; + $actor->name = 'owner'; + $org = BillingOrganizationFixture::findOrFail(1); + + $subscription = (new SubscriptionAdministration)->cancel($org, $actor, 'default'); + + $this->assertNotNull($subscription->canceled_at); + $this->assertTrue($subscription->ends_at->isFuture()); + $this->assertNull(DB::table('sb_billing_subscriptions')->where('subscriber_id', 2)->value('canceled_at')); + } + + public function test_access_to_another_organization_is_denied(): void + { + $actor = new User; + $actor->name = 'owner'; + + $this->expectException(AuthorizationException::class); + (new SubscriptionAdministration)->cancel(BillingOrganizationFixture::findOrFail(2), $actor, 'default'); + } + + public function test_no_gate_grant_does_not_cancel_a_subscription(): void + { + $actor = new User; + $actor->name = 'visitor'; + + $this->expectException(AuthorizationException::class); + (new SubscriptionAdministration)->cancel(BillingOrganizationFixture::findOrFail(1), $actor, 'default'); + } + + public function test_tenant_mode_without_resolver_denies_even_an_allowed_actor(): void + { + config(['subbase.tenancy.enabled' => true, 'subbase.tenancy.access' => null]); + + $actor = new User; + $actor->name = 'owner'; + + $this->expectException(AuthorizationException::class); + (new SubscriptionAdministration)->cancel(BillingOrganizationFixture::findOrFail(1), $actor, 'default'); + } +} From e51cae5aeb077d458b8592559da33c48b97d5abc Mon Sep 17 00:00:00 2001 From: mstfkhazaal <47450090+mstfkhazaal@users.noreply.github.com> Date: Thu, 29 Oct 2026 10:00:22 +0200 Subject: [PATCH 24/45] style: normalize new subscription lifecycle service and access tests --- src/Services/SubscriptionAdministration.php | 12 ++++++------ .../Subscriptions/SubscriptionAdministrationTest.php | 3 +-- 2 files changed, 7 insertions(+), 8 deletions(-) diff --git a/src/Services/SubscriptionAdministration.php b/src/Services/SubscriptionAdministration.php index 0ca3ca4..cf0764a 100644 --- a/src/Services/SubscriptionAdministration.php +++ b/src/Services/SubscriptionAdministration.php @@ -9,9 +9,9 @@ use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Gate; +use InvalidArgumentException; use Laravelcm\Subscriptions\Models\Subscription; use Nafiswatsiq\Subbase\Support\SubbaseTenancy; -use InvalidArgumentException; /** * Tenant-safe cancellation of a named subscription. @@ -27,18 +27,18 @@ public function cancel( string $subscriptionName, bool $immediately = false, ): Subscription { - if (!$billable->exists || !method_exists($billable, 'planSubscriptions')) { + if (! $billable->exists || ! method_exists($billable, 'planSubscriptions')) { throw new InvalidArgumentException('Subscription owner must be a saved, subscribable model.'); } - if (!preg_match('/^[A-Za-z0-9_-]{1,100}$/D', $subscriptionName)) { + if (! preg_match('/^[A-Za-z0-9_-]{1,100}$/D', $subscriptionName)) { throw new InvalidArgumentException('Subscription name is invalid.'); } $ability = (string) config('subbase.permissions.manage_subscription', 'manageSubscription'); - if (!SubbaseTenancy::allows($billable, 'cancel', $actor) - || !Gate::forUser($actor)->allows($ability, $billable) + if (! SubbaseTenancy::allows($billable, 'cancel', $actor) + || ! Gate::forUser($actor)->allows($ability, $billable) ) { throw new AuthorizationException('You cannot manage this subscription.'); } @@ -52,7 +52,7 @@ public function cancel( // Do not inadvertently extend a period or create new charges. // Repeated cancellation is idempotent for the same mode. - if (!$subscription->canceled() || ($immediately && !$subscription->ended())) { + if (! $subscription->canceled() || ($immediately && ! $subscription->ended())) { $subscription->cancel($immediately); } diff --git a/tests/Subscriptions/SubscriptionAdministrationTest.php b/tests/Subscriptions/SubscriptionAdministrationTest.php index 70cb6e9..3de497e 100644 --- a/tests/Subscriptions/SubscriptionAdministrationTest.php +++ b/tests/Subscriptions/SubscriptionAdministrationTest.php @@ -77,8 +77,7 @@ protected function setUp(): void ]); } - Gate::define('manageSubscription', fn (User $actor, Model $billable): bool => - $actor->name === 'owner' && $billable->getKey() === 1); + Gate::define('manageSubscription', fn (User $actor, Model $billable): bool => $actor->name === 'owner' && $billable->getKey() === 1); } public function test_authorized_owner_can_cancel_at_end_without_affecting_other_tenant(): void From 789c28417868812cf4ea78b9e3f0cf6a0426f99f Mon Sep 17 00:00:00 2001 From: mstfkhazaal <47450090+mstfkhazaal@users.noreply.github.com> Date: Thu, 29 Oct 2026 10:01:12 +0200 Subject: [PATCH 25/45] docs: record tested subscription cancellation and current CI status --- Changelog.md | 6 ++++++ docs/INSTALLATION.md | 18 ++++++++++++++++++ docs/PROGRESS.md | 3 ++- 3 files changed, 26 insertions(+), 1 deletion(-) diff --git a/Changelog.md b/Changelog.md index c78d3a5..ffce2ad 100644 --- a/Changelog.md +++ b/Changelog.md @@ -23,3 +23,9 @@ Existing apps that relied on permissive missing-Spatie access will be denied unt - Added `docs/INSTALLATION.md` for safe path-repo sandbox integration. **Not yet released.** Multi-tenant end-to-end coverage, recurring billing, version tags, CRM/Zeno migration, and complete formatting/DB matrix are outstanding. + +### Subscription administration + +- Added `SubscriptionAdministration::cancel($billable, $actor, $subscriptionName, $immediately)` to cancel a named subscription after Laravel Gate and tenant-policy validation, with DB transaction/lock and cross-organization isolation tests. +- Latest CI tested **23 PHPUnit tests / 44 assertions** and scoped Pint + Composer audit ([run 40839099089](https://github.com/fnx-software/subbase/actions/runs/40839099089)). +- Cancellation does not trigger a refund; payment provider refund workflows remain separate and unimplemented. diff --git a/docs/INSTALLATION.md b/docs/INSTALLATION.md index cc9cabb..42f1a77 100644 --- a/docs/INSTALLATION.md +++ b/docs/INSTALLATION.md @@ -78,3 +78,21 @@ vendor/bin/pint --test These commands are intended for the package checkout. Full Pint may report **pre-existing upstream violations** outside the new code. The feature-branch CI gates added files but a full-formatting PR is needed for stable release. Do not replace `nafiswatsiq/subbase` in CRM or Zeno with this feature branch until audited migration and fixture tests pass. + +## 7. Authorized subscription cancellation (new) + +`Nafiswatsiq\Subbase\Services\SubscriptionAdministration` provides a DB-transactional cancellation operation that is denied unless the authenticated actor is authorized by Laravel Gate *and*, if enabled, by the tenant access resolver: + +```php +use Nafiswatsiq\Subbase\Services\SubscriptionAdministration; + +// Define Gate/policy 'manageSubscription' for the billable Organization. +app(SubscriptionAdministration::class)->cancel( + billable: $organization, + actor: $request->user(), + subscriptionName: 'default', + immediately: false, // default: cancel at end of paid period +); +``` + +By design, this does **not** initiate a gateway refund or modify historical payment records. Use Subbase Payment's eventual verified refund workflow for that separately. Do not bypass the Gate in host controllers or jobs. diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index fecdc7d..1218739 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -15,8 +15,9 @@ Subbase and its companion Subbase Payment are the **one owned subscription stack - [x] Accurate `Plan::getPriceDecimalForCurrency()` / `PlanPriceHelper::resolveExactWithDiscounts()` for checkout alongside legacy display APIs. - [x] Canonical decimal string price storage, `decimal:4` model casts, and forward-only widening migration for plan/discount/pivot fields. Avoid destructive down migrations. - [x] Tested price migration and applied discounts in Laravel/Testbench, initially using SQLite. +- [x] `SubscriptionAdministration::cancel()` implements tenant- and Gate-authorized immediate/end-of-period cancellation with row locking and isolation tests. Cancellation does **not** refund money automatically. - [x] PHP 8.4/Filament 5/Laravel 13 compatible CI running Composer validate/update, PHPUnit, scoped Pint and Composer audit. -- [x] [Last known green code run](https://github.com/fnx-software/subbase/actions/runs/40838411564): **19 tests / 38 assertions**; Composer rename itself requires latest CI confirmation. +- [x] [Last known green code run](https://github.com/fnx-software/subbase/actions/runs/40839099089): **23 tests / 44 assertions**; Composer rename itself requires latest CI confirmation. - [x] Product architecture, developer usage, staged upgrade and implementation backlog documented. ## Remaining before stable release From c66a4a29fd085921150ebf1fbd5eca6d9d26fe91 Mon Sep 17 00:00:00 2001 From: mstfkhazaal <47450090+mstfkhazaal@users.noreply.github.com> Date: Thu, 29 Oct 2026 10:11:19 +0200 Subject: [PATCH 26/45] feat(licenses): add app SKU offers, reseller accounts, wholesale orders and encrypted key inventory --- config/subbase.php | 16 ++++ ...te_license_catalog_and_providers_table.php | 60 +++++++++++++++ .../create_license_orders_and_keys_table.php | 75 +++++++++++++++++++ .../Commands/SubbaseUpgradeCommand.php | 3 + src/Models/LicenseKey.php | 44 +++++++++++ src/Models/LicenseOffer.php | 42 +++++++++++ src/Models/LicenseOrder.php | 55 ++++++++++++++ src/Models/LicenseProduct.php | 28 +++++++ src/Models/LicenseProvider.php | 44 +++++++++++ src/Models/LicenseSale.php | 35 +++++++++ src/SubbaseServiceProvider.php | 2 + 11 files changed, 404 insertions(+) create mode 100644 database/migrations/create_license_catalog_and_providers_table.php create mode 100644 database/migrations/create_license_orders_and_keys_table.php create mode 100644 src/Models/LicenseKey.php create mode 100644 src/Models/LicenseOffer.php create mode 100644 src/Models/LicenseOrder.php create mode 100644 src/Models/LicenseProduct.php create mode 100644 src/Models/LicenseProvider.php create mode 100644 src/Models/LicenseSale.php diff --git a/config/subbase.php b/config/subbase.php index 7eea653..2da673e 100644 --- a/config/subbase.php +++ b/config/subbase.php @@ -30,6 +30,22 @@ // If enabled without a resolver, every tenant query and action is denied. 'tenancy' => ['enabled' => false, 'access' => null], + // License keys belong to a catalog SKU and a subscription Plan, not to Fenix. + // This allows one billing engine to sell CRM, POS, Clinic or independent apps. + 'licensing' => [ + 'key_prefix' => env('SUBBASE_LICENSE_PREFIX', 'LIC'), + 'max_order_quantity' => 500, + 'reseller_max_retail_price' => true, + 'tables' => [ + 'products' => 'subbase_license_products', + 'offers' => 'subbase_license_offers', + 'providers' => 'subbase_license_providers', + 'orders' => 'subbase_license_orders', + 'keys' => 'subbase_license_keys', + 'sales' => 'subbase_license_sales', + ], + ], + 'theme' => env('SUBBASE_THEME', 'default'), 'locale_currency_map' => [ diff --git a/database/migrations/create_license_catalog_and_providers_table.php b/database/migrations/create_license_catalog_and_providers_table.php new file mode 100644 index 0000000..e8dd8ce --- /dev/null +++ b/database/migrations/create_license_catalog_and_providers_table.php @@ -0,0 +1,60 @@ +id(); + $table->string('sku', 80)->unique(); + $table->string('name', 150); + $table->boolean('is_active')->default(true); + $table->timestamps(); + }); + + Schema::create($tables['offers'], function (Blueprint $table) use ($tables): void { + $table->id(); + $table->foreignId('product_id')->constrained($tables['products'])->restrictOnDelete(); + $table->unsignedBigInteger('plan_id')->index(); + $table->string('sku', 120)->unique(); + $table->char('currency', 3); + $table->decimal('retail_price', 20, 4); + $table->decimal('wholesale_price', 20, 4); + $table->unsignedSmallInteger('wholesale_minimum')->default(12); + $table->unsignedSmallInteger('term_count')->default(1); + $table->string('term_unit', 10)->default('year'); + $table->boolean('is_active')->default(true); + $table->timestamps(); + $table->index(['product_id', 'currency', 'is_active'], 'sb_license_offer_lookup'); + }); + + Schema::create($tables['providers'], function (Blueprint $table): void { + $table->id(); + $table->string('owner_type'); + $table->string('owner_id', 191); + $table->string('business_name', 150); + $table->string('status', 20)->default('pending'); + $table->timestamp('approved_at')->nullable(); + $table->timestamp('suspended_at')->nullable(); + $table->timestamps(); + $table->unique(['owner_type', 'owner_id'], 'sb_license_provider_owner_unique'); + $table->index(['status', 'created_at']); + }); + } + + public function down(): void + { + $tables = config('subbase.licensing.tables'); + Schema::dropIfExists($tables['providers']); + Schema::dropIfExists($tables['offers']); + Schema::dropIfExists($tables['products']); + } +}; diff --git a/database/migrations/create_license_orders_and_keys_table.php b/database/migrations/create_license_orders_and_keys_table.php new file mode 100644 index 0000000..2426466 --- /dev/null +++ b/database/migrations/create_license_orders_and_keys_table.php @@ -0,0 +1,75 @@ +id(); + $table->uuid('public_id')->unique(); + $table->foreignId('offer_id')->constrained($tables['offers'])->restrictOnDelete(); + $table->foreignId('provider_id')->nullable()->constrained($tables['providers'])->restrictOnDelete(); + $table->string('purchaser_type'); + $table->string('purchaser_id', 191); + $table->string('channel', 20); + $table->unsignedSmallInteger('quantity'); + $table->char('currency', 3); + $table->decimal('retail_reference_price', 20, 4); + $table->decimal('unit_price', 20, 4); + $table->decimal('total_amount', 20, 4); + $table->string('status', 20)->default('pending'); + $table->string('idempotency_key', 80)->nullable()->unique(); + $table->unsignedBigInteger('payment_id')->nullable()->unique(); + $table->timestamp('fulfilled_at')->nullable(); + $table->timestamps(); + $table->index(['provider_id', 'status', 'created_at'], 'sb_license_order_provider_status'); + $table->index(['purchaser_type', 'purchaser_id'], 'sb_license_order_purchaser'); + }); + + Schema::create($tables['keys'], function (Blueprint $table) use ($tables): void { + $table->id(); + $table->foreignId('order_id')->constrained($tables['orders'])->restrictOnDelete(); + $table->foreignId('offer_id')->constrained($tables['offers'])->restrictOnDelete(); + $table->foreignId('provider_id')->nullable()->constrained($tables['providers'])->restrictOnDelete(); + $table->char('code_hash', 64)->unique(); + $table->text('code_ciphertext')->nullable(); + $table->string('code_tail', 8); + $table->string('status', 20)->default('available'); + $table->string('redeemed_by_type')->nullable(); + $table->string('redeemed_by_id', 191)->nullable(); + $table->string('subscription_id', 191)->nullable(); + $table->timestamp('redeemed_at')->nullable(); + $table->timestamps(); + $table->index(['provider_id', 'status', 'created_at'], 'sb_license_key_inventory'); + $table->index(['redeemed_by_type', 'redeemed_by_id'], 'sb_license_key_redeemer'); + }); + + Schema::create($tables['sales'], function (Blueprint $table) use ($tables): void { + $table->id(); + $table->foreignId('key_id')->unique()->constrained($tables['keys'])->restrictOnDelete(); + $table->foreignId('provider_id')->constrained($tables['providers'])->restrictOnDelete(); + $table->decimal('sale_price', 20, 4); + $table->char('currency', 3); + $table->string('external_reference', 120)->nullable(); + $table->timestamp('sold_at'); + $table->timestamps(); + $table->index(['provider_id', 'sold_at'], 'sb_license_reseller_sales'); + }); + } + + public function down(): void + { + $tables = config('subbase.licensing.tables'); + Schema::dropIfExists($tables['sales']); + Schema::dropIfExists($tables['keys']); + Schema::dropIfExists($tables['orders']); + } +}; diff --git a/src/Console/Commands/SubbaseUpgradeCommand.php b/src/Console/Commands/SubbaseUpgradeCommand.php index 667de68..4f527c0 100644 --- a/src/Console/Commands/SubbaseUpgradeCommand.php +++ b/src/Console/Commands/SubbaseUpgradeCommand.php @@ -84,6 +84,9 @@ protected function publishMigrations(): void 'add_prices_to_plans_table.php', 'add_featured_to_plans_table.php', 'create_discounts_table.php', + 'upgrade_billing_decimal_columns.php', + 'create_license_catalog_and_providers_table.php', + 'create_license_orders_and_keys_table.php', ]; $published = 0; diff --git a/src/Models/LicenseKey.php b/src/Models/LicenseKey.php new file mode 100644 index 0000000..9469533 --- /dev/null +++ b/src/Models/LicenseKey.php @@ -0,0 +1,44 @@ + 'datetime']; + } + + public function getTable(): string + { + return config('subbase.licensing.tables.keys', 'subbase_license_keys'); + } + + public function order(): BelongsTo + { + return $this->belongsTo(LicenseOrder::class, 'order_id'); + } + + public function offer(): BelongsTo + { + return $this->belongsTo(LicenseOffer::class, 'offer_id'); + } + + public function provider(): BelongsTo + { + return $this->belongsTo(LicenseProvider::class, 'provider_id'); + } +} diff --git a/src/Models/LicenseOffer.php b/src/Models/LicenseOffer.php new file mode 100644 index 0000000..f99b70d --- /dev/null +++ b/src/Models/LicenseOffer.php @@ -0,0 +1,42 @@ + 'decimal:4', + 'wholesale_price' => 'decimal:4', + 'wholesale_minimum' => 'integer', + 'term_count' => 'integer', + 'is_active' => 'boolean', + ]; + } + + public function getTable(): string + { + return config('subbase.licensing.tables.offers', 'subbase_license_offers'); + } + + public function product(): BelongsTo + { + return $this->belongsTo(LicenseProduct::class, 'product_id'); + } + + public function plan(): BelongsTo + { + return $this->belongsTo(config('subbase.models.plan', Plan::class), 'plan_id'); + } +} diff --git a/src/Models/LicenseOrder.php b/src/Models/LicenseOrder.php new file mode 100644 index 0000000..5a5832d --- /dev/null +++ b/src/Models/LicenseOrder.php @@ -0,0 +1,55 @@ + 'integer', + 'unit_price' => 'decimal:4', + 'retail_reference_price' => 'decimal:4', + 'total_amount' => 'decimal:4', + 'fulfilled_at' => 'datetime', + ]; + } + + public function getTable(): string + { + return config('subbase.licensing.tables.orders', 'subbase_license_orders'); + } + + public function offer(): BelongsTo + { + return $this->belongsTo(LicenseOffer::class, 'offer_id'); + } + + public function provider(): BelongsTo + { + return $this->belongsTo(LicenseProvider::class, 'provider_id'); + } + + public function purchaser(): MorphTo + { + return $this->morphTo('purchaser', 'purchaser_type', 'purchaser_id'); + } + + public function keys(): HasMany + { + return $this->hasMany(LicenseKey::class, 'order_id'); + } +} diff --git a/src/Models/LicenseProduct.php b/src/Models/LicenseProduct.php new file mode 100644 index 0000000..b162614 --- /dev/null +++ b/src/Models/LicenseProduct.php @@ -0,0 +1,28 @@ + 'boolean']; + } + + public function getTable(): string + { + return config('subbase.licensing.tables.products', 'subbase_license_products'); + } + + public function offers(): HasMany + { + return $this->hasMany(LicenseOffer::class, 'product_id'); + } +} diff --git a/src/Models/LicenseProvider.php b/src/Models/LicenseProvider.php new file mode 100644 index 0000000..f4cfa62 --- /dev/null +++ b/src/Models/LicenseProvider.php @@ -0,0 +1,44 @@ + 'datetime', 'suspended_at' => 'datetime']; + } + + public function getTable(): string + { + return config('subbase.licensing.tables.providers', 'subbase_license_providers'); + } + + public function owner(): MorphTo + { + return $this->morphTo('owner'); + } + + public function orders(): HasMany + { + return $this->hasMany(LicenseOrder::class, 'provider_id'); + } + + public function keys(): HasMany + { + return $this->hasMany(LicenseKey::class, 'provider_id'); + } + + public function approved(): bool + { + return $this->status === 'approved' && $this->approved_at !== null; + } +} diff --git a/src/Models/LicenseSale.php b/src/Models/LicenseSale.php new file mode 100644 index 0000000..cff6fc7 --- /dev/null +++ b/src/Models/LicenseSale.php @@ -0,0 +1,35 @@ + 'decimal:4', 'sold_at' => 'datetime']; + } + + public function getTable(): string + { + return config('subbase.licensing.tables.sales', 'subbase_license_sales'); + } + + public function key(): BelongsTo + { + return $this->belongsTo(LicenseKey::class, 'key_id'); + } + + public function provider(): BelongsTo + { + return $this->belongsTo(LicenseProvider::class, 'provider_id'); + } +} diff --git a/src/SubbaseServiceProvider.php b/src/SubbaseServiceProvider.php index 6185839..d4c75c4 100644 --- a/src/SubbaseServiceProvider.php +++ b/src/SubbaseServiceProvider.php @@ -49,6 +49,8 @@ public function configurePackage(Package $package): void 'add_featured_to_plans_table.php', 'create_discounts_table.php', 'upgrade_billing_decimal_columns.php', + 'create_license_catalog_and_providers_table.php', + 'create_license_orders_and_keys_table.php', ]; foreach ($migrations as $migration) { From dd67229c1eb74a82efd2e4b160878e5b939743ec Mon Sep 17 00:00:00 2001 From: mstfkhazaal <47450090+mstfkhazaal@users.noreply.github.com> Date: Thu, 29 Oct 2026 10:12:05 +0200 Subject: [PATCH 27/45] feat(licenses): authorize provider onboarding, snapshot wholesale orders, issue/redeem 128-bit keys and track resale margin --- src/Services/LicenseFulfillmentService.php | 71 ++++++++++++ src/Services/LicenseInventoryService.php | 41 +++++++ src/Services/LicenseOrderService.php | 121 +++++++++++++++++++++ src/Services/LicenseProviderService.php | 73 +++++++++++++ src/Services/LicenseRedemptionService.php | 113 +++++++++++++++++++ src/Services/LicenseResaleService.php | 87 +++++++++++++++ 6 files changed, 506 insertions(+) create mode 100644 src/Services/LicenseFulfillmentService.php create mode 100644 src/Services/LicenseInventoryService.php create mode 100644 src/Services/LicenseOrderService.php create mode 100644 src/Services/LicenseProviderService.php create mode 100644 src/Services/LicenseRedemptionService.php create mode 100644 src/Services/LicenseResaleService.php diff --git a/src/Services/LicenseFulfillmentService.php b/src/Services/LicenseFulfillmentService.php new file mode 100644 index 0000000..dfcc322 --- /dev/null +++ b/src/Services/LicenseFulfillmentService.php @@ -0,0 +1,71 @@ +lockForUpdate()->findOrFail($order->getKey()); + + if ($locked->status === 'fulfilled') { + if ((int) $locked->payment_id !== $paymentId + || $locked->keys()->count() !== (int) $locked->quantity + ) { + throw new RuntimeException('License order is already fulfilled by a different payment.'); + } + + return $locked; + } + + if ($locked->status !== 'pending' || $locked->keys()->exists()) { + throw new RuntimeException('Order cannot be fulfilled in its current state.'); + } + + $prefix = strtoupper((string) config('subbase.licensing.key_prefix', 'LIC')); + if (! preg_match('/^[A-Z0-9]{2,8}$/D', $prefix)) { + throw new RuntimeException('License key prefix must be 2–8 alphanumeric characters.'); + } + + for ($i = 0; $i < (int) $locked->quantity; $i++) { + $hex = strtoupper(bin2hex(random_bytes(16))); + $code = $prefix.'-'.implode('-', str_split($hex, 8)); + + LicenseKey::query()->create([ + 'order_id' => $locked->getKey(), + 'offer_id' => $locked->offer_id, + 'provider_id' => $locked->provider_id, + 'code_hash' => hash('sha256', $code), + 'code_ciphertext' => Crypt::encryptString($code), + 'code_tail' => substr($hex, -8), + 'status' => 'available', + ]); + } + + $locked->update([ + 'status' => 'fulfilled', + 'payment_id' => $paymentId, + 'fulfilled_at' => now(), + ]); + + return $locked; + }, 3); + } +} diff --git a/src/Services/LicenseInventoryService.php b/src/Services/LicenseInventoryService.php new file mode 100644 index 0000000..7589d57 --- /dev/null +++ b/src/Services/LicenseInventoryService.php @@ -0,0 +1,41 @@ + + */ + public function reveal(LicenseOrder $order, Authenticatable $actor): array + { + $order = LicenseOrder::query()->findOrFail($order->getKey()); + + if (! Gate::forUser($actor)->allows('viewPurchasedLicenseKeys', $order)) { + throw new AuthorizationException('License inventory is private.'); + } + + if ($order->status !== 'fulfilled') { + throw new RuntimeException('License keys are not available until payment has cleared.'); + } + + return $order->keys() + ->where('status', 'available') + ->orderBy('id') + ->get(['code_ciphertext']) + ->map(static fn ($key): string => Crypt::decryptString($key->code_ciphertext)) + ->all(); + } +} diff --git a/src/Services/LicenseOrderService.php b/src/Services/LicenseOrderService.php new file mode 100644 index 0000000..09f5348 --- /dev/null +++ b/src/Services/LicenseOrderService.php @@ -0,0 +1,121 @@ +exists || $purchaser->getKey() === null) { + throw new InvalidArgumentException('Purchaser must be saved before placing an order.'); + } + + if ($idempotencyKey !== null && ! preg_match('/^[a-zA-Z0-9:_-]{12,80}$/D', $idempotencyKey)) { + throw new InvalidArgumentException('Invalid idempotency token.'); + } + + $isWholesale = $provider !== null; + $max = (int) config('subbase.licensing.max_order_quantity', 500); + if ($quantity < 1 || $quantity > $max) { + throw new InvalidArgumentException('License quantity is outside allowed limits.'); + } + + if ($isWholesale) { + if (! $provider->exists || ! $provider->approved() + || $purchaser->getMorphClass() !== $provider->owner_type + || (string) $purchaser->getKey() !== (string) $provider->owner_id + || $quantity < (int) $offer->wholesale_minimum + ) { + throw new InvalidArgumentException('Reseller approval, owner and minimum quantity are required.'); + } + + if (! Gate::forUser($actor)->allows('purchaseWholesaleLicenses', $provider)) { + throw new AuthorizationException('Not authorized to purchase wholesale keys.'); + } + } elseif ($quantity !== 1 || ! Gate::forUser($actor)->allows('purchaseRetailLicense', $purchaser)) { + throw new AuthorizationException('Retail licensing requires an authorized single-key purchaser.'); + } + + // Always check catalog state at order creation, not from stale client data. + $offer = LicenseOffer::query()->with('product')->findOrFail($offer->getKey()); + if (! $offer->is_active || ! $offer->product->is_active + || ! in_array($offer->term_unit, ['day', 'month', 'year'], true) + || $offer->term_count < 1 || $offer->term_count > 120 + ) { + throw new InvalidArgumentException('The license offer is unavailable.'); + } + + $retail = new Money((string) $offer->retail_price, (string) $offer->currency); + $wholesale = new Money((string) $offer->wholesale_price, (string) $offer->currency); + + if ($retail->isZero() || bccomp($wholesale->amount(), $retail->amount(), 4) > 0) { + throw new InvalidArgumentException('Invalid retail or wholesale offer price.'); + } + + $unit = $isWholesale ? $wholesale : $retail; + if ($unit->isZero()) { + throw new InvalidArgumentException('Free wholesale orders require a separate administrative grant.'); + } + + $total = new Money(bcmul($unit->amount(), (string) $quantity, 4), (string) $offer->currency); + + return DB::transaction(function () use ($offer, $purchaser, $quantity, $provider, $idempotencyKey, $isWholesale, $retail, $unit, $total): LicenseOrder { + if ($idempotencyKey !== null) { + $existing = LicenseOrder::query()->where('idempotency_key', $idempotencyKey)->first(); + if ($existing) { + if ((int) $existing->offer_id !== (int) $offer->getKey() + || (int) $existing->quantity !== $quantity + || (string) $existing->purchaser_type !== $purchaser->getMorphClass() + || (string) $existing->purchaser_id !== (string) $purchaser->getKey() + || (string) ($existing->provider_id ?? '') !== (string) ($provider?->getKey() ?? '') + ) { + throw new RuntimeException('Idempotency token was already used for another purchase.'); + } + + return $existing; + } + } + + return LicenseOrder::query()->create([ + 'public_id' => (string) Str::uuid(), + 'offer_id' => $offer->getKey(), + 'provider_id' => $provider?->getKey(), + 'purchaser_type' => $purchaser->getMorphClass(), + 'purchaser_id' => (string) $purchaser->getKey(), + 'channel' => $isWholesale ? 'wholesale' : 'retail', + 'quantity' => $quantity, + 'currency' => strtoupper((string) $offer->currency), + 'retail_reference_price' => $retail->amount(), + 'unit_price' => $unit->amount(), + 'total_amount' => $total->amount(), + 'status' => 'pending', + 'idempotency_key' => $idempotencyKey, + ]); + }, 3); + } +} diff --git a/src/Services/LicenseProviderService.php b/src/Services/LicenseProviderService.php new file mode 100644 index 0000000..be5e623 --- /dev/null +++ b/src/Services/LicenseProviderService.php @@ -0,0 +1,73 @@ +exists || $owner->getKey() === null + || $businessName === '' || mb_strlen($businessName) > 150 + ) { + throw new InvalidArgumentException('Provider owner and business name are required.'); + } + + if (! Gate::forUser($actor)->allows('applyForLicenseProvider', $owner)) { + throw new AuthorizationException('Cannot submit a reseller application.'); + } + + return LicenseProvider::query()->firstOrCreate([ + 'owner_type' => $owner->getMorphClass(), + 'owner_id' => (string) $owner->getKey(), + ], [ + 'business_name' => $businessName, + 'status' => 'pending', + ]); + } + + public function approve(LicenseProvider $provider, Authenticatable $admin): LicenseProvider + { + return $this->transition($provider, $admin, 'approved'); + } + + public function suspend(LicenseProvider $provider, Authenticatable $admin): LicenseProvider + { + return $this->transition($provider, $admin, 'suspended'); + } + + private function transition(LicenseProvider $provider, Authenticatable $admin, string $status): LicenseProvider + { + if (! Gate::forUser($admin)->allows('manageLicenseProviders', $provider)) { + throw new AuthorizationException('Only an authorized billing administrator may approve resellers.'); + } + + return DB::transaction(function () use ($provider, $status): LicenseProvider { + $record = LicenseProvider::query()->lockForUpdate()->findOrFail($provider->getKey()); + + if (! in_array($record->status, ['pending', 'approved', 'suspended'], true)) { + throw new RuntimeException('Provider state cannot be changed.'); + } + + $record->update([ + 'status' => $status, + 'approved_at' => $status === 'approved' ? ($record->approved_at ?? now()) : $record->approved_at, + 'suspended_at' => $status === 'suspended' ? now() : null, + ]); + + return $record; + }); + } +} diff --git a/src/Services/LicenseRedemptionService.php b/src/Services/LicenseRedemptionService.php new file mode 100644 index 0000000..93c13f2 --- /dev/null +++ b/src/Services/LicenseRedemptionService.php @@ -0,0 +1,113 @@ +exists || $billable->getKey() === null + || ! method_exists($billable, 'planSubscriptions') + || ! method_exists($billable, 'newPlanSubscription') + ) { + throw new InvalidArgumentException('Activation requires a saved, subscribable account.'); + } + + if (! Gate::forUser($actor)->allows('redeemLicenseKey', $billable)) { + throw new AuthorizationException('Cannot activate a license for this account.'); + } + + $code = strtoupper(trim($code)); + if (! preg_match('/^[A-Z0-9]{2,8}-(?:[A-F0-9]{8}-){3}[A-F0-9]{8}$/D', $code)) { + throw new InvalidArgumentException('Invalid or already redeemed license key.'); + } + + return DB::transaction(function () use ($code, $billable): LicenseKey { + $key = LicenseKey::query() + ->where('code_hash', hash('sha256', $code)) + ->lockForUpdate() + ->first(); + + if (! $key || $key->status !== 'available') { + throw new InvalidArgumentException('Invalid or already redeemed license key.'); + } + + $order = $key->order()->lockForUpdate()->firstOrFail(); + if ($order->status !== 'fulfilled') { + throw new RuntimeException('This license has not been paid for.'); + } + + $offer = $key->offer()->firstOrFail(); + $product = $offer->product()->firstOrFail(); + if (! preg_match('/^[a-z0-9][a-z0-9-]{0,65}$/D', (string) $product->sku)) { + throw new RuntimeException('License product SKU is invalid.'); + } + + $planClass = config('subbase.models.plan', Plan::class); + $plan = $planClass::query()->findOrFail($offer->plan_id); + + $subscriptionName = 'license-'.$product->sku; + $subscription = $billable->planSubscriptions() + ->where('slug', $subscriptionName) + ->lockForUpdate() + ->first(); + + if ($subscription && (string) $subscription->plan_id !== (string) $plan->getKey()) { + throw new RuntimeException('This product already has a different subscription plan.'); + } + + $start = now(); + if ($subscription && $subscription->ends_at && $subscription->ends_at->isFuture()) { + $start = $subscription->ends_at->copy(); + } + + $end = match ($offer->term_unit) { + 'day' => $start->copy()->addDays((int) $offer->term_count), + 'month' => $start->copy()->addMonthsNoOverflow((int) $offer->term_count), + 'year' => $start->copy()->addYearsNoOverflow((int) $offer->term_count), + default => throw new RuntimeException('Unsupported license term.'), + }; + + if (! $subscription) { + $subscription = $billable->newPlanSubscription($subscriptionName, $plan); + } + + $subscription->forceFill([ + 'starts_at' => $subscription->starts_at && $subscription->starts_at->isPast() + ? $subscription->starts_at : now(), + 'ends_at' => $end, + 'trial_ends_at' => null, + 'canceled_at' => null, + ])->save(); + + $key->update([ + 'status' => 'redeemed', + 'code_ciphertext' => null, + 'redeemed_by_type' => $billable->getMorphClass(), + 'redeemed_by_id' => (string) $billable->getKey(), + 'subscription_id' => (string) $subscription->getKey(), + 'redeemed_at' => now(), + ]); + + return $key; + }, 3); + } +} diff --git a/src/Services/LicenseResaleService.php b/src/Services/LicenseResaleService.php new file mode 100644 index 0000000..098ee4c --- /dev/null +++ b/src/Services/LicenseResaleService.php @@ -0,0 +1,87 @@ +allows('recordLicenseResale', $provider)) { + throw new AuthorizationException('Not authorized to record this reseller sale.'); + } + + return DB::transaction(function () use ($key, $provider, $salePrice, $externalReference): array { + $key = LicenseKey::query()->lockForUpdate()->findOrFail($key->getKey()); + if ((string) $key->provider_id !== (string) $provider->getKey() + || ! in_array($key->status, ['available', 'redeemed'], true) + ) { + throw new RuntimeException('This key does not belong to the reseller inventory.'); + } + + $order = $key->order()->firstOrFail(); + if ($order->status !== 'fulfilled') { + throw new RuntimeException('Resale requires a paid wholesale license.'); + } + + $price = new Money($salePrice, (string) $order->currency); + if ($price->isZero()) { + throw new InvalidArgumentException('A resale price is required.'); + } + + if (config('subbase.licensing.reseller_max_retail_price', true) + && bccomp($price->amount(), (string) $order->retail_reference_price, 4) > 0 + ) { + throw new InvalidArgumentException('The resale price exceeds published retail price.'); + } + + $existing = LicenseSale::query()->where('key_id', $key->getKey())->first(); + if ($existing) { + throw new RuntimeException('This key already has a recorded reseller sale.'); + } + + if ($externalReference !== null && mb_strlen($externalReference) > 120) { + throw new InvalidArgumentException('External sale reference is too long.'); + } + + $sale = LicenseSale::query()->create([ + 'key_id' => $key->getKey(), + 'provider_id' => $provider->getKey(), + 'sale_price' => $price->amount(), + 'currency' => $order->currency, + 'external_reference' => $externalReference, + 'sold_at' => now(), + ]); + + return [ + 'sale' => $sale, + 'gross_margin' => bcsub($price->amount(), (string) $order->unit_price, 4), + 'currency' => (string) $order->currency, + ]; + }); + } +} From 94ae5a7b02043a6890dda5e2361862e037e232d8 Mon Sep 17 00:00:00 2001 From: mstfkhazaal <47450090+mstfkhazaal@users.noreply.github.com> Date: Thu, 29 Oct 2026 10:12:46 +0200 Subject: [PATCH 28/45] test(licenses): verify wholesale pricing, safe fulfillment, reseller margin and annual redemption --- .github/workflows/tests.yml | 2 +- tests/Licensing/LicenseRedemptionTest.php | 79 ++++++++++ tests/Licensing/LicenseTestCase.php | 174 ++++++++++++++++++++++ tests/Licensing/LicenseWholesaleTest.php | 135 +++++++++++++++++ 4 files changed, 389 insertions(+), 1 deletion(-) create mode 100644 tests/Licensing/LicenseRedemptionTest.php create mode 100644 tests/Licensing/LicenseTestCase.php create mode 100644 tests/Licensing/LicenseWholesaleTest.php diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 6fc9428..d4d4585 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -20,5 +20,5 @@ jobs: - run: composer update --no-interaction --prefer-dist - run: vendor/bin/phpunit # The upstream fork has pre-existing style drift. Format existing files in a separate PR. - - run: vendor/bin/pint --test src/Support/SubbasePermission.php tests/TestCase.php tests/Authorization/SubbasePermissionTest.php src/Support/Money.php tests/Money/MoneyTest.php src/Support/SubbaseTenancy.php src/Contracts/TenantAccess.php tests/Tenancy/SubbaseTenancyTest.php tests/Money/PrecisionMigrationTest.php tests/Money/ExactPricingTest.php src/Services/SubscriptionAdministration.php tests/Subscriptions/SubscriptionAdministrationTest.php + - run: vendor/bin/pint --test src/Support/SubbasePermission.php tests/TestCase.php tests/Authorization/SubbasePermissionTest.php src/Support/Money.php tests/Money/MoneyTest.php src/Support/SubbaseTenancy.php src/Contracts/TenantAccess.php tests/Tenancy/SubbaseTenancyTest.php tests/Money/PrecisionMigrationTest.php tests/Money/ExactPricingTest.php src/Services/SubscriptionAdministration.php tests/Subscriptions/SubscriptionAdministrationTest.php src/Models/LicenseProduct.php src/Models/LicenseOffer.php src/Models/LicenseProvider.php src/Models/LicenseOrder.php src/Models/LicenseKey.php src/Models/LicenseSale.php src/Services/LicenseProviderService.php src/Services/LicenseOrderService.php src/Services/LicenseFulfillmentService.php src/Services/LicenseInventoryService.php src/Services/LicenseRedemptionService.php src/Services/LicenseResaleService.php tests/Licensing/LicenseTestCase.php tests/Licensing/LicenseWholesaleTest.php tests/Licensing/LicenseRedemptionTest.php - run: composer audit --no-dev diff --git a/tests/Licensing/LicenseRedemptionTest.php b/tests/Licensing/LicenseRedemptionTest.php new file mode 100644 index 0000000..09dd4b1 --- /dev/null +++ b/tests/Licensing/LicenseRedemptionTest.php @@ -0,0 +1,79 @@ +travelTo(now()->setDate(2026, 10, 29)->startOfDay()); + + $provider = $this->reseller(); + $order = app(LicenseOrderService::class)->place($this->offer(), $this->organization(1), $this->actor('merchant'), 12, $provider); + app(LicenseFulfillmentService::class)->fulfillPaidOrder($order, 123); + $keys = app(LicenseInventoryService::class)->reveal($order, $this->actor('merchant')); + + $this->travelTo(now()->addMonths(2)); + $key = app(LicenseRedemptionService::class)->redeem($keys[0], $this->organization(2), $this->actor('customer')); + $this->assertSame('redeemed', $key->status); + $this->assertNull($key->code_ciphertext); + $this->assertSame('2', $key->redeemed_by_id); + $this->assertNotNull($key->subscription_id); + + $subscription = $this->organization(2)->planSubscriptions()->firstOrFail(); + $this->assertSame('license-crm', $subscription->slug); + $this->assertSame('2027-12-29', $subscription->ends_at->toDateString()); + + $this->expectException(InvalidArgumentException::class); + app(LicenseRedemptionService::class)->redeem($keys[0], $this->organization(2), $this->actor('customer')); + } + + public function test_a_second_key_extends_same_product_subscription_without_duplicate(): void + { + $provider = $this->reseller(); + $order = app(LicenseOrderService::class)->place($this->offer(), $this->organization(1), $this->actor('merchant'), 12, $provider); + app(LicenseFulfillmentService::class)->fulfillPaidOrder($order, 123); + $keys = app(LicenseInventoryService::class)->reveal($order, $this->actor('merchant')); + $service = app(LicenseRedemptionService::class); + $service->redeem($keys[0], $this->organization(2), $this->actor('customer')); + $firstEnd = $this->organization(2)->planSubscriptions()->firstOrFail()->ends_at->copy(); + $service->redeem($keys[1], $this->organization(2), $this->actor('customer')); + $second = $this->organization(2)->planSubscriptions()->firstOrFail(); + + $this->assertSame(1, $this->organization(2)->planSubscriptions()->count()); + $this->assertSame($firstEnd->addYearNoOverflow()->toDateString(), $second->ends_at->toDateString()); + } + + public function test_invalid_key_never_creates_subscription(): void + { + $this->expectException(InvalidArgumentException::class); + try { + app(LicenseRedemptionService::class)->redeem('LIC-FAKE-KEY', $this->organization(2), $this->actor('customer')); + } finally { + $this->assertSame(0, DB::table('sb_lic_test_subscriptions')->count()); + } + } + + public function test_suspending_provider_does_not_invalidate_purchased_customer_keys(): void + { + $provider = $this->reseller(); + $order = app(LicenseOrderService::class)->place($this->offer(), $this->organization(1), $this->actor('merchant'), 12, $provider); + app(LicenseFulfillmentService::class)->fulfillPaidOrder($order, 128); + $keys = app(LicenseInventoryService::class)->reveal($order, $this->actor('merchant')); + + app(\Nafiswatsiq\Subbase\Services\LicenseProviderService::class)->suspend($provider, $this->actor('admin')); + $redeemed = app(LicenseRedemptionService::class)->redeem($keys[0], $this->organization(2), $this->actor('customer')); + + $this->assertSame('redeemed', $redeemed->status); + } +} diff --git a/tests/Licensing/LicenseTestCase.php b/tests/Licensing/LicenseTestCase.php new file mode 100644 index 0000000..2a09e16 --- /dev/null +++ b/tests/Licensing/LicenseTestCase.php @@ -0,0 +1,174 @@ + 'sb_lic_test_plans', + 'laravel-subscriptions.tables.subscriptions' => 'sb_lic_test_subscriptions', + 'laravel-subscriptions.models.plan' => Plan::class, + 'laravel-subscriptions.models.subscription' => Subscription::class, + 'subbase.models.plan' => Plan::class, + 'subbase.licensing.key_prefix' => 'LIC', + 'subbase.licensing.reseller_max_retail_price' => true, + ]); + + Schema::create('sb_lic_test_organizations', static function (Blueprint $table): void { + $table->id(); + $table->string('name'); + $table->timestamps(); + }); + + Schema::create('sb_lic_test_plans', static function (Blueprint $table): void { + $table->id(); + $table->string('slug'); + $table->text('name'); + $table->text('description')->nullable(); + $table->boolean('is_active')->default(true); + $table->decimal('price', 20, 4)->default(0); + $table->char('currency', 3)->default('USD'); + $table->unsignedSmallInteger('invoice_period')->default(1); + $table->string('invoice_interval')->default('year'); + $table->unsignedSmallInteger('trial_period')->default(0); + $table->string('trial_interval')->default('day'); + $table->timestamps(); + $table->softDeletes(); + }); + + Schema::create('sb_lic_test_subscriptions', static function (Blueprint $table): void { + $table->id(); + $table->string('subscriber_type'); + $table->unsignedBigInteger('subscriber_id'); + $table->unsignedBigInteger('plan_id'); + $table->string('slug'); + $table->text('name'); + $table->text('description')->nullable(); + $table->timestamp('trial_ends_at')->nullable(); + $table->timestamp('starts_at')->nullable(); + $table->timestamp('ends_at')->nullable(); + $table->timestamp('canceled_at')->nullable(); + $table->timestamps(); + $table->softDeletes(); + }); + + foreach ([ + 'create_license_catalog_and_providers_table', + 'create_license_orders_and_keys_table', + ] as $name) { + $migration = require dirname(__DIR__, 2).'/database/migrations/'.$name.'.php'; + $migration->up(); + } + + DB::table('sb_lic_test_organizations')->insert([ + ['id' => 1, 'name' => 'Reseller shop', 'created_at' => now(), 'updated_at' => now()], + ['id' => 2, 'name' => 'Customer business', 'created_at' => now(), 'updated_at' => now()], + ['id' => 3, 'name' => 'Second customer', 'created_at' => now(), 'updated_at' => now()], + ]); + DB::table('sb_lic_test_plans')->insert([ + 'id' => 11, + 'slug' => 'crm-individual', + 'name' => json_encode(['en' => 'CRM Individual'], JSON_THROW_ON_ERROR), + 'description' => json_encode(['en' => 'Yearly CRM'], JSON_THROW_ON_ERROR), + 'price' => '150.00', + 'currency' => 'USD', + 'invoice_period' => 1, + 'invoice_interval' => 'year', + 'trial_period' => 0, + 'trial_interval' => 'day', + 'created_at' => now(), + 'updated_at' => now(), + ]); + + Gate::define('applyForLicenseProvider', static fn (User $actor, Model $owner): bool => + $actor->name === 'merchant' && (int) $owner->getKey() === 1); + Gate::define('manageLicenseProviders', static fn (User $actor): bool => $actor->name === 'admin'); + Gate::define('purchaseWholesaleLicenses', static fn (User $actor, LicenseProvider $provider): bool => + $actor->name === 'merchant' && (int) $provider->owner_id === 1); + Gate::define('purchaseRetailLicense', static fn (User $actor, Model $purchaser): bool => + $actor->name === 'customer' && (int) $purchaser->getKey() === 2); + Gate::define('viewPurchasedLicenseKeys', static fn (User $actor, \Nafiswatsiq\Subbase\Models\LicenseOrder $order): bool => + $actor->name === 'merchant' && (int) $order->provider_id === (int) LicenseProvider::query()->value('id')); + Gate::define('redeemLicenseKey', static fn (User $actor, Model $billable): bool => + $actor->name === 'customer' && (int) $billable->getKey() === 2); + Gate::define('recordLicenseResale', static fn (User $actor, LicenseProvider $provider): bool => + $actor->name === 'merchant' && (int) $provider->owner_id === 1); + + config(['app.key' => 'base64:'.base64_encode(str_repeat('z', 32))]); + } + + protected function offer(): LicenseOffer + { + $product = LicenseProduct::query()->firstOrCreate( + ['sku' => 'crm'], + ['name' => 'Fenix CRM', 'is_active' => true], + ); + + return LicenseOffer::query()->firstOrCreate( + ['sku' => 'crm-individual-year-usd'], + [ + 'product_id' => $product->getKey(), + 'plan_id' => 11, + 'currency' => 'USD', + 'retail_price' => '150.00', + 'wholesale_price' => '100.00', + 'wholesale_minimum' => 12, + 'term_count' => 1, + 'term_unit' => 'year', + 'is_active' => true, + ], + ); + } + + protected function reseller(): LicenseProvider + { + $merchant = $this->actor('merchant'); + $org = LicenseTestOrganization::query()->findOrFail(1); + $service = app(\Nafiswatsiq\Subbase\Services\LicenseProviderService::class); + $provider = $service->apply($org, $merchant, 'Electronics Store'); + + return $service->approve($provider, $this->actor('admin')); + } + + protected function actor(string $name): User + { + $user = new User; + $user->name = $name; + + return $user; + } + + protected function organization(int $id): LicenseTestOrganization + { + return LicenseTestOrganization::query()->findOrFail($id); + } +} diff --git a/tests/Licensing/LicenseWholesaleTest.php b/tests/Licensing/LicenseWholesaleTest.php new file mode 100644 index 0000000..49ab15a --- /dev/null +++ b/tests/Licensing/LicenseWholesaleTest.php @@ -0,0 +1,135 @@ +offer(); + $provider = $this->reseller(); + $order = app(LicenseOrderService::class)->place( + $offer, $this->organization(1), $this->actor('merchant'), 12, $provider, 'order_wholesale_123', + ); + + $this->assertSame('wholesale', $order->channel); + $this->assertSame('150.0000', $order->retail_reference_price); + $this->assertSame('100.0000', $order->unit_price); + $this->assertSame('1200.0000', $order->total_amount); + $this->assertSame('pending', $order->status); + $this->assertSame(0, LicenseKey::query()->count()); + + app(LicenseFulfillmentService::class)->fulfillPaidOrder($order, 9876); + $this->assertSame(12, LicenseKey::query()->count()); + $this->assertSame(12, LicenseKey::query()->distinct()->count('code_hash')); + $this->assertSame(12, count(app(LicenseInventoryService::class)->reveal($order, $this->actor('merchant')))); + + $key = $order->keys()->firstOrFail(); + $resale = app(LicenseResaleService::class)->record( + $key, $provider, $this->actor('merchant'), '140.00', 'SHOP-ORDER-1', + ); + + $this->assertSame('40.0000', $resale['gross_margin']); + $this->assertSame('140.0000', $resale['sale']->sale_price); + $this->assertSame('USD', $resale['currency']); + + app(LicenseFulfillmentService::class)->fulfillPaidOrder($order, 9876); + $this->assertSame(12, $order->keys()->count()); + } + + public function test_pending_orders_cannot_export_license_keys(): void + { + $order = app(LicenseOrderService::class)->place( + $this->offer(), $this->organization(1), $this->actor('merchant'), 12, $this->reseller(), + ); + + $this->expectException(RuntimeException::class); + app(LicenseInventoryService::class)->reveal($order, $this->actor('merchant')); + } + + public function test_unapproved_reseller_cannot_purchase(): void + { + $provider = app(\Nafiswatsiq\Subbase\Services\LicenseProviderService::class)->apply( + $this->organization(1), $this->actor('merchant'), 'Pending shop', + ); + + $this->expectException(InvalidArgumentException::class); + app(LicenseOrderService::class)->place($this->offer(), $this->organization(1), $this->actor('merchant'), 12, $provider); + } + + public function test_quantity_below_wholesale_minimum_is_rejected(): void + { + $this->expectException(InvalidArgumentException::class); + app(LicenseOrderService::class)->place($this->offer(), $this->organization(1), $this->actor('merchant'), 11, $this->reseller()); + } + + public function test_retail_checkout_is_one_key_at_official_price(): void + { + $order = app(LicenseOrderService::class)->place( + $this->offer(), $this->organization(2), $this->actor('customer'), + ); + + $this->assertSame('retail', $order->channel); + $this->assertSame(1, $order->quantity); + $this->assertSame('150.0000', $order->total_amount); + $this->assertNull($order->provider_id); + } + + public function test_idempotency_reuses_same_order_and_refuses_cross_account_reuse(): void + { + $service = app(LicenseOrderService::class); + $offer = $this->offer(); + $provider = $this->reseller(); + + $first = $service->place($offer, $this->organization(1), $this->actor('merchant'), 12, $provider, 'same_key_123456'); + $second = $service->place($offer, $this->organization(1), $this->actor('merchant'), 12, $provider, 'same_key_123456'); + $this->assertSame($first->getKey(), $second->getKey()); + $this->assertSame(1, LicenseOrder::query()->count()); + + $this->expectException(RuntimeException::class); + $service->place($offer, $this->organization(2), $this->actor('customer'), 1, null, 'same_key_123456'); + } + + public function test_another_actor_cannot_export_reseller_stock(): void + { + $provider = $this->reseller(); + $order = app(LicenseOrderService::class)->place($this->offer(), $this->organization(1), $this->actor('merchant'), 12, $provider); + app(LicenseFulfillmentService::class)->fulfillPaidOrder($order, 17); + + $this->expectException(AuthorizationException::class); + app(LicenseInventoryService::class)->reveal($order, $this->actor('customer')); + } + + public function test_wholesale_resale_price_cannot_exceed_public_retail_by_default(): void + { + $provider = $this->reseller(); + $order = app(LicenseOrderService::class)->place($this->offer(), $this->organization(1), $this->actor('merchant'), 12, $provider); + app(LicenseFulfillmentService::class)->fulfillPaidOrder($order, 101); + + $this->expectException(InvalidArgumentException::class); + app(LicenseResaleService::class)->record($order->keys()->firstOrFail(), $provider, $this->actor('merchant'), '160.00'); + } + + public function test_a_different_gateway_payment_cannot_fulfill_existing_order_twice(): void + { + $provider = $this->reseller(); + $order = app(LicenseOrderService::class)->place($this->offer(), $this->organization(1), $this->actor('merchant'), 12, $provider); + app(LicenseFulfillmentService::class)->fulfillPaidOrder($order, 1); + + $this->expectException(RuntimeException::class); + app(LicenseFulfillmentService::class)->fulfillPaidOrder($order, 2); + } +} From 1c97a910a80dd77f2c27063e1e273f6d65c187db Mon Sep 17 00:00:00 2001 From: mstfkhazaal <47450090+mstfkhazaal@users.noreply.github.com> Date: Thu, 29 Oct 2026 10:13:57 +0200 Subject: [PATCH 29/45] ci: inspect exact Pint fixes for new licensing files --- .github/workflows/tests.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index d4d4585..432805f 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -18,6 +18,11 @@ jobs: tools: composer:v2 - run: composer validate --no-check-publish --strict - run: composer update --no-interaction --prefer-dist + - name: Inspect licensing Pint formatting changes + run: | + vendor/bin/pint src/Services/LicenseRedemptionService.php tests/Licensing/LicenseRedemptionTest.php tests/Licensing/LicenseTestCase.php tests/Licensing/LicenseWholesaleTest.php + git diff -- src/Services/LicenseRedemptionService.php tests/Licensing/LicenseRedemptionTest.php tests/Licensing/LicenseTestCase.php tests/Licensing/LicenseWholesaleTest.php + git diff --quiet -- src/Services/LicenseRedemptionService.php tests/Licensing/LicenseRedemptionTest.php tests/Licensing/LicenseTestCase.php tests/Licensing/LicenseWholesaleTest.php - run: vendor/bin/phpunit # The upstream fork has pre-existing style drift. Format existing files in a separate PR. - run: vendor/bin/pint --test src/Support/SubbasePermission.php tests/TestCase.php tests/Authorization/SubbasePermissionTest.php src/Support/Money.php tests/Money/MoneyTest.php src/Support/SubbaseTenancy.php src/Contracts/TenantAccess.php tests/Tenancy/SubbaseTenancyTest.php tests/Money/PrecisionMigrationTest.php tests/Money/ExactPricingTest.php src/Services/SubscriptionAdministration.php tests/Subscriptions/SubscriptionAdministrationTest.php src/Models/LicenseProduct.php src/Models/LicenseOffer.php src/Models/LicenseProvider.php src/Models/LicenseOrder.php src/Models/LicenseKey.php src/Models/LicenseSale.php src/Services/LicenseProviderService.php src/Services/LicenseOrderService.php src/Services/LicenseFulfillmentService.php src/Services/LicenseInventoryService.php src/Services/LicenseRedemptionService.php src/Services/LicenseResaleService.php tests/Licensing/LicenseTestCase.php tests/Licensing/LicenseWholesaleTest.php tests/Licensing/LicenseRedemptionTest.php From 61e6edeacfce3c4a8c5c4c3ac514ce27bf317570 Mon Sep 17 00:00:00 2001 From: mstfkhazaal <47450090+mstfkhazaal@users.noreply.github.com> Date: Thu, 29 Oct 2026 10:14:44 +0200 Subject: [PATCH 30/45] fix(licensing): allow confirmed gateway orders awaiting payment to issue keys --- src/Services/LicenseFulfillmentService.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Services/LicenseFulfillmentService.php b/src/Services/LicenseFulfillmentService.php index dfcc322..0ab7405 100644 --- a/src/Services/LicenseFulfillmentService.php +++ b/src/Services/LicenseFulfillmentService.php @@ -35,7 +35,7 @@ public function fulfillPaidOrder(LicenseOrder $order, int $paymentId): LicenseOr return $locked; } - if ($locked->status !== 'pending' || $locked->keys()->exists()) { + if (! in_array($locked->status, ['pending', 'awaiting_payment'], true) || $locked->keys()->exists()) { throw new RuntimeException('Order cannot be fulfilled in its current state.'); } From ab6231978ac4bd1a8c6b7314da24d90c094fc2bb Mon Sep 17 00:00:00 2001 From: mstfkhazaal <47450090+mstfkhazaal@users.noreply.github.com> Date: Thu, 29 Oct 2026 10:15:08 +0200 Subject: [PATCH 31/45] style(licensing): apply Pint exact formatting and restore normal CI --- .github/workflows/tests.yml | 5 ----- src/Services/LicenseRedemptionService.php | 2 -- tests/Licensing/LicenseRedemptionTest.php | 4 ++-- tests/Licensing/LicenseTestCase.php | 22 +++++++++------------- tests/Licensing/LicenseWholesaleTest.php | 4 ++-- 5 files changed, 13 insertions(+), 24 deletions(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 432805f..d4d4585 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -18,11 +18,6 @@ jobs: tools: composer:v2 - run: composer validate --no-check-publish --strict - run: composer update --no-interaction --prefer-dist - - name: Inspect licensing Pint formatting changes - run: | - vendor/bin/pint src/Services/LicenseRedemptionService.php tests/Licensing/LicenseRedemptionTest.php tests/Licensing/LicenseTestCase.php tests/Licensing/LicenseWholesaleTest.php - git diff -- src/Services/LicenseRedemptionService.php tests/Licensing/LicenseRedemptionTest.php tests/Licensing/LicenseTestCase.php tests/Licensing/LicenseWholesaleTest.php - git diff --quiet -- src/Services/LicenseRedemptionService.php tests/Licensing/LicenseRedemptionTest.php tests/Licensing/LicenseTestCase.php tests/Licensing/LicenseWholesaleTest.php - run: vendor/bin/phpunit # The upstream fork has pre-existing style drift. Format existing files in a separate PR. - run: vendor/bin/pint --test src/Support/SubbasePermission.php tests/TestCase.php tests/Authorization/SubbasePermissionTest.php src/Support/Money.php tests/Money/MoneyTest.php src/Support/SubbaseTenancy.php src/Contracts/TenantAccess.php tests/Tenancy/SubbaseTenancyTest.php tests/Money/PrecisionMigrationTest.php tests/Money/ExactPricingTest.php src/Services/SubscriptionAdministration.php tests/Subscriptions/SubscriptionAdministrationTest.php src/Models/LicenseProduct.php src/Models/LicenseOffer.php src/Models/LicenseProvider.php src/Models/LicenseOrder.php src/Models/LicenseKey.php src/Models/LicenseSale.php src/Services/LicenseProviderService.php src/Services/LicenseOrderService.php src/Services/LicenseFulfillmentService.php src/Services/LicenseInventoryService.php src/Services/LicenseRedemptionService.php src/Services/LicenseResaleService.php tests/Licensing/LicenseTestCase.php tests/Licensing/LicenseWholesaleTest.php tests/Licensing/LicenseRedemptionTest.php diff --git a/src/Services/LicenseRedemptionService.php b/src/Services/LicenseRedemptionService.php index 93c13f2..ece7361 100644 --- a/src/Services/LicenseRedemptionService.php +++ b/src/Services/LicenseRedemptionService.php @@ -11,8 +11,6 @@ use Illuminate\Support\Facades\Gate; use InvalidArgumentException; use Nafiswatsiq\Subbase\Models\LicenseKey; -use Nafiswatsiq\Subbase\Models\LicenseOffer; -use Nafiswatsiq\Subbase\Models\LicenseProduct; use Nafiswatsiq\Subbase\Models\Plan; use RuntimeException; diff --git a/tests/Licensing/LicenseRedemptionTest.php b/tests/Licensing/LicenseRedemptionTest.php index 09dd4b1..c1c8201 100644 --- a/tests/Licensing/LicenseRedemptionTest.php +++ b/tests/Licensing/LicenseRedemptionTest.php @@ -4,12 +4,12 @@ namespace Nafiswatsiq\Subbase\Tests\Licensing; -use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\DB; use InvalidArgumentException; use Nafiswatsiq\Subbase\Services\LicenseFulfillmentService; use Nafiswatsiq\Subbase\Services\LicenseInventoryService; use Nafiswatsiq\Subbase\Services\LicenseOrderService; +use Nafiswatsiq\Subbase\Services\LicenseProviderService; use Nafiswatsiq\Subbase\Services\LicenseRedemptionService; final class LicenseRedemptionTest extends LicenseTestCase @@ -71,7 +71,7 @@ public function test_suspending_provider_does_not_invalidate_purchased_customer_ app(LicenseFulfillmentService::class)->fulfillPaidOrder($order, 128); $keys = app(LicenseInventoryService::class)->reveal($order, $this->actor('merchant')); - app(\Nafiswatsiq\Subbase\Services\LicenseProviderService::class)->suspend($provider, $this->actor('admin')); + app(LicenseProviderService::class)->suspend($provider, $this->actor('admin')); $redeemed = app(LicenseRedemptionService::class)->redeem($keys[0], $this->organization(2), $this->actor('customer')); $this->assertSame('redeemed', $redeemed->status); diff --git a/tests/Licensing/LicenseTestCase.php b/tests/Licensing/LicenseTestCase.php index 2a09e16..8fd2b75 100644 --- a/tests/Licensing/LicenseTestCase.php +++ b/tests/Licensing/LicenseTestCase.php @@ -12,10 +12,12 @@ use Illuminate\Support\Facades\Schema; use Laravelcm\Subscriptions\Traits\HasPlanSubscriptions; use Nafiswatsiq\Subbase\Models\LicenseOffer; +use Nafiswatsiq\Subbase\Models\LicenseOrder; use Nafiswatsiq\Subbase\Models\LicenseProduct; use Nafiswatsiq\Subbase\Models\LicenseProvider; use Nafiswatsiq\Subbase\Models\Plan; use Nafiswatsiq\Subbase\Models\Subscription; +use Nafiswatsiq\Subbase\Services\LicenseProviderService; use Nafiswatsiq\Subbase\Tests\TestCase; final class LicenseTestOrganization extends Model @@ -109,19 +111,13 @@ protected function setUp(): void 'updated_at' => now(), ]); - Gate::define('applyForLicenseProvider', static fn (User $actor, Model $owner): bool => - $actor->name === 'merchant' && (int) $owner->getKey() === 1); + Gate::define('applyForLicenseProvider', static fn (User $actor, Model $owner): bool => $actor->name === 'merchant' && (int) $owner->getKey() === 1); Gate::define('manageLicenseProviders', static fn (User $actor): bool => $actor->name === 'admin'); - Gate::define('purchaseWholesaleLicenses', static fn (User $actor, LicenseProvider $provider): bool => - $actor->name === 'merchant' && (int) $provider->owner_id === 1); - Gate::define('purchaseRetailLicense', static fn (User $actor, Model $purchaser): bool => - $actor->name === 'customer' && (int) $purchaser->getKey() === 2); - Gate::define('viewPurchasedLicenseKeys', static fn (User $actor, \Nafiswatsiq\Subbase\Models\LicenseOrder $order): bool => - $actor->name === 'merchant' && (int) $order->provider_id === (int) LicenseProvider::query()->value('id')); - Gate::define('redeemLicenseKey', static fn (User $actor, Model $billable): bool => - $actor->name === 'customer' && (int) $billable->getKey() === 2); - Gate::define('recordLicenseResale', static fn (User $actor, LicenseProvider $provider): bool => - $actor->name === 'merchant' && (int) $provider->owner_id === 1); + Gate::define('purchaseWholesaleLicenses', static fn (User $actor, LicenseProvider $provider): bool => $actor->name === 'merchant' && (int) $provider->owner_id === 1); + Gate::define('purchaseRetailLicense', static fn (User $actor, Model $purchaser): bool => $actor->name === 'customer' && (int) $purchaser->getKey() === 2); + Gate::define('viewPurchasedLicenseKeys', static fn (User $actor, LicenseOrder $order): bool => $actor->name === 'merchant' && (int) $order->provider_id === (int) LicenseProvider::query()->value('id')); + Gate::define('redeemLicenseKey', static fn (User $actor, Model $billable): bool => $actor->name === 'customer' && (int) $billable->getKey() === 2); + Gate::define('recordLicenseResale', static fn (User $actor, LicenseProvider $provider): bool => $actor->name === 'merchant' && (int) $provider->owner_id === 1); config(['app.key' => 'base64:'.base64_encode(str_repeat('z', 32))]); } @@ -153,7 +149,7 @@ protected function reseller(): LicenseProvider { $merchant = $this->actor('merchant'); $org = LicenseTestOrganization::query()->findOrFail(1); - $service = app(\Nafiswatsiq\Subbase\Services\LicenseProviderService::class); + $service = app(LicenseProviderService::class); $provider = $service->apply($org, $merchant, 'Electronics Store'); return $service->approve($provider, $this->actor('admin')); diff --git a/tests/Licensing/LicenseWholesaleTest.php b/tests/Licensing/LicenseWholesaleTest.php index 49ab15a..f47efe8 100644 --- a/tests/Licensing/LicenseWholesaleTest.php +++ b/tests/Licensing/LicenseWholesaleTest.php @@ -5,13 +5,13 @@ namespace Nafiswatsiq\Subbase\Tests\Licensing; use Illuminate\Auth\Access\AuthorizationException; -use Illuminate\Support\Facades\DB; use InvalidArgumentException; use Nafiswatsiq\Subbase\Models\LicenseKey; use Nafiswatsiq\Subbase\Models\LicenseOrder; use Nafiswatsiq\Subbase\Services\LicenseFulfillmentService; use Nafiswatsiq\Subbase\Services\LicenseInventoryService; use Nafiswatsiq\Subbase\Services\LicenseOrderService; +use Nafiswatsiq\Subbase\Services\LicenseProviderService; use Nafiswatsiq\Subbase\Services\LicenseResaleService; use RuntimeException; @@ -62,7 +62,7 @@ public function test_pending_orders_cannot_export_license_keys(): void public function test_unapproved_reseller_cannot_purchase(): void { - $provider = app(\Nafiswatsiq\Subbase\Services\LicenseProviderService::class)->apply( + $provider = app(LicenseProviderService::class)->apply( $this->organization(1), $this->actor('merchant'), 'Pending shop', ); From 848603b42e9c2f612e0f2f3b18c5f12e225ad265 Mon Sep 17 00:00:00 2001 From: mstfkhazaal <47450090+mstfkhazaal@users.noreply.github.com> Date: Thu, 29 Oct 2026 10:17:07 +0200 Subject: [PATCH 32/45] feat(filament): add license products, pricing, reseller approval, order and key inventory admin resources --- .github/workflows/tests.yml | 3 + .../LicenseKeys/LicenseKeyResource.php | 74 ++++++++++++++++ .../LicenseKeys/Pages/ListLicenseKeys.php | 13 +++ .../LicenseOffers/LicenseOfferResource.php | 88 +++++++++++++++++++ .../Pages/CreateLicenseOffer.php | 13 +++ .../LicenseOffers/Pages/EditLicenseOffer.php | 13 +++ .../LicenseOffers/Pages/ListLicenseOffers.php | 19 ++++ .../Schemas/LicenseOfferForm.php | 32 +++++++ .../Tables/LicenseOffersTable.php | 28 ++++++ .../LicenseOrders/LicenseOrderResource.php | 78 ++++++++++++++++ .../LicenseOrders/Pages/ListLicenseOrders.php | 13 +++ .../LicenseProductResource.php | 88 +++++++++++++++++++ .../Pages/CreateLicenseProduct.php | 13 +++ .../Pages/EditLicenseProduct.php | 13 +++ .../Pages/ListLicenseProducts.php | 19 ++++ .../Schemas/LicenseProductForm.php | 23 +++++ .../Tables/LicenseProductsTable.php | 24 +++++ .../LicenseProviderResource.php | 67 ++++++++++++++ .../Pages/ListLicenseProviders.php | 13 +++ .../Tables/LicenseProvidersTable.php | 47 ++++++++++ src/SubbasePlugin.php | 10 +++ 21 files changed, 691 insertions(+) create mode 100644 src/Filament/Resources/LicenseKeys/LicenseKeyResource.php create mode 100644 src/Filament/Resources/LicenseKeys/Pages/ListLicenseKeys.php create mode 100644 src/Filament/Resources/LicenseOffers/LicenseOfferResource.php create mode 100644 src/Filament/Resources/LicenseOffers/Pages/CreateLicenseOffer.php create mode 100644 src/Filament/Resources/LicenseOffers/Pages/EditLicenseOffer.php create mode 100644 src/Filament/Resources/LicenseOffers/Pages/ListLicenseOffers.php create mode 100644 src/Filament/Resources/LicenseOffers/Schemas/LicenseOfferForm.php create mode 100644 src/Filament/Resources/LicenseOffers/Tables/LicenseOffersTable.php create mode 100644 src/Filament/Resources/LicenseOrders/LicenseOrderResource.php create mode 100644 src/Filament/Resources/LicenseOrders/Pages/ListLicenseOrders.php create mode 100644 src/Filament/Resources/LicenseProducts/LicenseProductResource.php create mode 100644 src/Filament/Resources/LicenseProducts/Pages/CreateLicenseProduct.php create mode 100644 src/Filament/Resources/LicenseProducts/Pages/EditLicenseProduct.php create mode 100644 src/Filament/Resources/LicenseProducts/Pages/ListLicenseProducts.php create mode 100644 src/Filament/Resources/LicenseProducts/Schemas/LicenseProductForm.php create mode 100644 src/Filament/Resources/LicenseProducts/Tables/LicenseProductsTable.php create mode 100644 src/Filament/Resources/LicenseProviders/LicenseProviderResource.php create mode 100644 src/Filament/Resources/LicenseProviders/Pages/ListLicenseProviders.php create mode 100644 src/Filament/Resources/LicenseProviders/Tables/LicenseProvidersTable.php diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index d4d4585..f7eda5f 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -18,6 +18,9 @@ jobs: tools: composer:v2 - run: composer validate --no-check-publish --strict - run: composer update --no-interaction --prefer-dist + - name: Syntax check all licensing admin resources + run: | + find src/Filament/Resources/LicenseProducts src/Filament/Resources/LicenseOffers src/Filament/Resources/LicenseProviders src/Filament/Resources/LicenseOrders src/Filament/Resources/LicenseKeys -name '*.php' -exec php -l {} \; - run: vendor/bin/phpunit # The upstream fork has pre-existing style drift. Format existing files in a separate PR. - run: vendor/bin/pint --test src/Support/SubbasePermission.php tests/TestCase.php tests/Authorization/SubbasePermissionTest.php src/Support/Money.php tests/Money/MoneyTest.php src/Support/SubbaseTenancy.php src/Contracts/TenantAccess.php tests/Tenancy/SubbaseTenancyTest.php tests/Money/PrecisionMigrationTest.php tests/Money/ExactPricingTest.php src/Services/SubscriptionAdministration.php tests/Subscriptions/SubscriptionAdministrationTest.php src/Models/LicenseProduct.php src/Models/LicenseOffer.php src/Models/LicenseProvider.php src/Models/LicenseOrder.php src/Models/LicenseKey.php src/Models/LicenseSale.php src/Services/LicenseProviderService.php src/Services/LicenseOrderService.php src/Services/LicenseFulfillmentService.php src/Services/LicenseInventoryService.php src/Services/LicenseRedemptionService.php src/Services/LicenseResaleService.php tests/Licensing/LicenseTestCase.php tests/Licensing/LicenseWholesaleTest.php tests/Licensing/LicenseRedemptionTest.php diff --git a/src/Filament/Resources/LicenseKeys/LicenseKeyResource.php b/src/Filament/Resources/LicenseKeys/LicenseKeyResource.php new file mode 100644 index 0000000..7f066d4 --- /dev/null +++ b/src/Filament/Resources/LicenseKeys/LicenseKeyResource.php @@ -0,0 +1,74 @@ +columns([ + TextColumn::make('id')->label('License ID'), + TextColumn::make('code_tail')->label('Last 8 characters'), + TextColumn::make('order.public_id')->label('Order'), + TextColumn::make('provider.business_name')->label('Provider'), + TextColumn::make('status')->badge(), + TextColumn::make('redeemed_at')->dateTime(), + ])->defaultSort('created_at', 'desc'); + } + + public static function getPages(): array + { + return ['index' => ListLicenseKeys::route('/')]; + } +} diff --git a/src/Filament/Resources/LicenseKeys/Pages/ListLicenseKeys.php b/src/Filament/Resources/LicenseKeys/Pages/ListLicenseKeys.php new file mode 100644 index 0000000..e2a9973 --- /dev/null +++ b/src/Filament/Resources/LicenseKeys/Pages/ListLicenseKeys.php @@ -0,0 +1,13 @@ + ListLicenseOffers::route('/'), + 'create' => CreateLicenseOffer::route('/create'), + 'edit' => EditLicenseOffer::route('/{record}/edit'), + ]; + } +} diff --git a/src/Filament/Resources/LicenseOffers/Pages/CreateLicenseOffer.php b/src/Filament/Resources/LicenseOffers/Pages/CreateLicenseOffer.php new file mode 100644 index 0000000..f991d2e --- /dev/null +++ b/src/Filament/Resources/LicenseOffers/Pages/CreateLicenseOffer.php @@ -0,0 +1,13 @@ +components([ + Select::make('product_id')->relationship('product', 'name')->required()->searchable(), + Select::make('plan_id') + ->options(fn (): array => (config('subbase.models.plan', Plan::class))::query()->pluck('slug', 'id')->all()) + ->required()->searchable(), + TextInput::make('sku')->required()->maxLength(120)->rule('regex:/^[a-z0-9][a-z0-9-]*$/'), + TextInput::make('currency')->required()->length(3)->default('USD'), + TextInput::make('retail_price')->required()->numeric()->minValue(0.0001), + TextInput::make('wholesale_price')->required()->numeric()->minValue(0.0001), + TextInput::make('wholesale_minimum')->required()->integer()->minValue(2)->default(12), + TextInput::make('term_count')->required()->integer()->minValue(1)->maxValue(120)->default(1), + Select::make('term_unit')->required()->options(['day' => 'Days', 'month' => 'Months', 'year' => 'Years'])->default('year'), + Toggle::make('is_active')->default(true), + ])->columns(2); + } +} diff --git a/src/Filament/Resources/LicenseOffers/Tables/LicenseOffersTable.php b/src/Filament/Resources/LicenseOffers/Tables/LicenseOffersTable.php new file mode 100644 index 0000000..ad858d8 --- /dev/null +++ b/src/Filament/Resources/LicenseOffers/Tables/LicenseOffersTable.php @@ -0,0 +1,28 @@ +columns([ + TextColumn::make('sku')->searchable(), + TextColumn::make('product.name')->label('Product'), + TextColumn::make('currency'), + TextColumn::make('retail_price')->label('Retail'), + TextColumn::make('wholesale_price')->label('Wholesale'), + TextColumn::make('wholesale_minimum')->label('Minimum quantity'), + IconColumn::make('is_active')->boolean(), + ]) + ->recordActions([EditAction::make()]) + ->defaultSort('id', 'desc'); + } +} diff --git a/src/Filament/Resources/LicenseOrders/LicenseOrderResource.php b/src/Filament/Resources/LicenseOrders/LicenseOrderResource.php new file mode 100644 index 0000000..0792970 --- /dev/null +++ b/src/Filament/Resources/LicenseOrders/LicenseOrderResource.php @@ -0,0 +1,78 @@ +columns([ + TextColumn::make('public_id')->label('Order')->searchable(), + TextColumn::make('channel')->badge(), + TextColumn::make('provider.business_name')->label('Reseller'), + TextColumn::make('offer.sku')->label('License offer'), + TextColumn::make('quantity'), + TextColumn::make('currency'), + TextColumn::make('unit_price'), + TextColumn::make('total_amount'), + TextColumn::make('status')->badge(), + TextColumn::make('fulfilled_at')->dateTime(), + ])->defaultSort('created_at', 'desc'); + } + + public static function getPages(): array + { + return ['index' => ListLicenseOrders::route('/')]; + } +} diff --git a/src/Filament/Resources/LicenseOrders/Pages/ListLicenseOrders.php b/src/Filament/Resources/LicenseOrders/Pages/ListLicenseOrders.php new file mode 100644 index 0000000..f6443bf --- /dev/null +++ b/src/Filament/Resources/LicenseOrders/Pages/ListLicenseOrders.php @@ -0,0 +1,13 @@ + ListLicenseProducts::route('/'), + 'create' => CreateLicenseProduct::route('/create'), + 'edit' => EditLicenseProduct::route('/{record}/edit'), + ]; + } +} diff --git a/src/Filament/Resources/LicenseProducts/Pages/CreateLicenseProduct.php b/src/Filament/Resources/LicenseProducts/Pages/CreateLicenseProduct.php new file mode 100644 index 0000000..932705c --- /dev/null +++ b/src/Filament/Resources/LicenseProducts/Pages/CreateLicenseProduct.php @@ -0,0 +1,13 @@ +components([ + TextInput::make('sku')->required()->maxLength(80)->rule('regex:/^[a-z0-9][a-z0-9-]*$/'), + TextInput::make('name')->required()->maxLength(150), + Toggle::make('is_active')->default(true), + ])->columns(2); + } +} diff --git a/src/Filament/Resources/LicenseProducts/Tables/LicenseProductsTable.php b/src/Filament/Resources/LicenseProducts/Tables/LicenseProductsTable.php new file mode 100644 index 0000000..5e897f1 --- /dev/null +++ b/src/Filament/Resources/LicenseProducts/Tables/LicenseProductsTable.php @@ -0,0 +1,24 @@ +columns([ + TextColumn::make('sku')->searchable(), + TextColumn::make('name')->searchable(), + IconColumn::make('is_active')->boolean(), + ]) + ->recordActions([EditAction::make()]) + ->defaultSort('id', 'desc'); + } +} diff --git a/src/Filament/Resources/LicenseProviders/LicenseProviderResource.php b/src/Filament/Resources/LicenseProviders/LicenseProviderResource.php new file mode 100644 index 0000000..b5954a7 --- /dev/null +++ b/src/Filament/Resources/LicenseProviders/LicenseProviderResource.php @@ -0,0 +1,67 @@ + ListLicenseProviders::route('/')]; + } +} diff --git a/src/Filament/Resources/LicenseProviders/Pages/ListLicenseProviders.php b/src/Filament/Resources/LicenseProviders/Pages/ListLicenseProviders.php new file mode 100644 index 0000000..d181aa0 --- /dev/null +++ b/src/Filament/Resources/LicenseProviders/Pages/ListLicenseProviders.php @@ -0,0 +1,13 @@ +columns([ + TextColumn::make('business_name')->searchable(), + TextColumn::make('owner_type')->label('Owner type'), + TextColumn::make('owner_id')->label('Owner ID'), + TextColumn::make('status')->badge(), + TextColumn::make('approved_at')->dateTime(), + TextColumn::make('created_at')->dateTime(), + ]) + ->filters([ + SelectFilter::make('status')->options([ + 'pending' => 'Pending', + 'approved' => 'Approved', + 'suspended' => 'Suspended', + ]), + ]) + ->recordActions([ + Action::make('approve') + ->requiresConfirmation() + ->visible(fn (LicenseProvider $record): bool => $record->status !== 'approved') + ->action(fn (LicenseProvider $record) => app(LicenseProviderService::class)->approve($record, Filament::auth()->user())), + Action::make('suspend') + ->color('danger') + ->requiresConfirmation() + ->visible(fn (LicenseProvider $record): bool => $record->status === 'approved') + ->action(fn (LicenseProvider $record) => app(LicenseProviderService::class)->suspend($record, Filament::auth()->user())), + ]) + ->defaultSort('created_at', 'desc'); + } +} diff --git a/src/SubbasePlugin.php b/src/SubbasePlugin.php index b8f28ab..5a2817a 100644 --- a/src/SubbasePlugin.php +++ b/src/SubbasePlugin.php @@ -7,6 +7,11 @@ use Nafiswatsiq\Subbase\Filament\Resources\Plans\PlanResource; use Nafiswatsiq\Subbase\Filament\Resources\Subscriptions\SubscriptionResource; use Nafiswatsiq\Subbase\Filament\Resources\Discounts\DiscountResource; +use Nafiswatsiq\Subbase\Filament\Resources\LicenseProducts\LicenseProductResource; +use Nafiswatsiq\Subbase\Filament\Resources\LicenseOffers\LicenseOfferResource; +use Nafiswatsiq\Subbase\Filament\Resources\LicenseProviders\LicenseProviderResource; +use Nafiswatsiq\Subbase\Filament\Resources\LicenseOrders\LicenseOrderResource; +use Nafiswatsiq\Subbase\Filament\Resources\LicenseKeys\LicenseKeyResource; class SubbasePlugin implements Plugin { @@ -21,6 +26,11 @@ public function register(Panel $panel): void PlanResource::class, SubscriptionResource::class, DiscountResource::class, + LicenseProductResource::class, + LicenseOfferResource::class, + LicenseProviderResource::class, + LicenseOrderResource::class, + LicenseKeyResource::class, ]); } From d5c1b1944ffca86a85591b22cc416aa8fa86fa3d Mon Sep 17 00:00:00 2001 From: mstfkhazaal <47450090+mstfkhazaal@users.noreply.github.com> Date: Thu, 29 Oct 2026 10:17:54 +0200 Subject: [PATCH 33/45] fix(filament5): match Resource navigation group property UnitEnum typing --- src/Filament/Resources/LicenseKeys/LicenseKeyResource.php | 3 ++- src/Filament/Resources/LicenseOffers/LicenseOfferResource.php | 3 ++- src/Filament/Resources/LicenseOrders/LicenseOrderResource.php | 3 ++- .../Resources/LicenseProducts/LicenseProductResource.php | 3 ++- .../Resources/LicenseProviders/LicenseProviderResource.php | 3 ++- 5 files changed, 10 insertions(+), 5 deletions(-) diff --git a/src/Filament/Resources/LicenseKeys/LicenseKeyResource.php b/src/Filament/Resources/LicenseKeys/LicenseKeyResource.php index 7f066d4..b671b7b 100644 --- a/src/Filament/Resources/LicenseKeys/LicenseKeyResource.php +++ b/src/Filament/Resources/LicenseKeys/LicenseKeyResource.php @@ -5,6 +5,7 @@ namespace Nafiswatsiq\Subbase\Filament\Resources\LicenseKeys; use BackedEnum; +use UnitEnum; use Filament\Resources\Resource; use Filament\Support\Icons\Heroicon; use Filament\Tables\Columns\TextColumn; @@ -23,7 +24,7 @@ class LicenseKeyResource extends Resource protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedKey; - protected static ?string $navigationGroup = 'Licensing'; + protected static string|UnitEnum|null $navigationGroup = 'Licensing'; public static function canViewAny(): bool { diff --git a/src/Filament/Resources/LicenseOffers/LicenseOfferResource.php b/src/Filament/Resources/LicenseOffers/LicenseOfferResource.php index c199b1d..d61032c 100644 --- a/src/Filament/Resources/LicenseOffers/LicenseOfferResource.php +++ b/src/Filament/Resources/LicenseOffers/LicenseOfferResource.php @@ -5,6 +5,7 @@ namespace Nafiswatsiq\Subbase\Filament\Resources\LicenseOffers; use BackedEnum; +use UnitEnum; use Filament\Resources\Resource; use Filament\Schemas\Schema; use Filament\Support\Icons\Heroicon; @@ -27,7 +28,7 @@ class LicenseOfferResource extends Resource protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedCurrencyDollar; - protected static ?string $navigationGroup = 'Licensing'; + protected static string|UnitEnum|null $navigationGroup = 'Licensing'; protected static ?string $recordTitleAttribute = 'sku'; diff --git a/src/Filament/Resources/LicenseOrders/LicenseOrderResource.php b/src/Filament/Resources/LicenseOrders/LicenseOrderResource.php index 0792970..bbab517 100644 --- a/src/Filament/Resources/LicenseOrders/LicenseOrderResource.php +++ b/src/Filament/Resources/LicenseOrders/LicenseOrderResource.php @@ -5,6 +5,7 @@ namespace Nafiswatsiq\Subbase\Filament\Resources\LicenseOrders; use BackedEnum; +use UnitEnum; use Filament\Resources\Resource; use Filament\Support\Icons\Heroicon; use Filament\Tables\Columns\TextColumn; @@ -23,7 +24,7 @@ class LicenseOrderResource extends Resource protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedClipboardDocumentList; - protected static ?string $navigationGroup = 'Licensing'; + protected static string|UnitEnum|null $navigationGroup = 'Licensing'; public static function canViewAny(): bool { diff --git a/src/Filament/Resources/LicenseProducts/LicenseProductResource.php b/src/Filament/Resources/LicenseProducts/LicenseProductResource.php index 9efd012..027b3ee 100644 --- a/src/Filament/Resources/LicenseProducts/LicenseProductResource.php +++ b/src/Filament/Resources/LicenseProducts/LicenseProductResource.php @@ -5,6 +5,7 @@ namespace Nafiswatsiq\Subbase\Filament\Resources\LicenseProducts; use BackedEnum; +use UnitEnum; use Filament\Resources\Resource; use Filament\Schemas\Schema; use Filament\Support\Icons\Heroicon; @@ -27,7 +28,7 @@ class LicenseProductResource extends Resource protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedCube; - protected static ?string $navigationGroup = 'Licensing'; + protected static string|UnitEnum|null $navigationGroup = 'Licensing'; protected static ?string $recordTitleAttribute = 'name'; diff --git a/src/Filament/Resources/LicenseProviders/LicenseProviderResource.php b/src/Filament/Resources/LicenseProviders/LicenseProviderResource.php index b5954a7..74d59a9 100644 --- a/src/Filament/Resources/LicenseProviders/LicenseProviderResource.php +++ b/src/Filament/Resources/LicenseProviders/LicenseProviderResource.php @@ -5,6 +5,7 @@ namespace Nafiswatsiq\Subbase\Filament\Resources\LicenseProviders; use BackedEnum; +use UnitEnum; use Filament\Resources\Resource; use Filament\Support\Icons\Heroicon; use Filament\Tables\Table; @@ -23,7 +24,7 @@ class LicenseProviderResource extends Resource protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedBuildingStorefront; - protected static ?string $navigationGroup = 'Licensing'; + protected static string|UnitEnum|null $navigationGroup = 'Licensing'; public static function canViewAny(): bool { From 4703f78c6b75f3d0263f63bd1169738c37e42b8d Mon Sep 17 00:00:00 2001 From: mstfkhazaal <47450090+mstfkhazaal@users.noreply.github.com> Date: Thu, 29 Oct 2026 10:18:32 +0200 Subject: [PATCH 34/45] feat(licensing): snapshot plan SKU and duration at purchase so later catalog edits never shorten sold licenses --- ...license_order_contract_snapshots_table.php | 51 +++++++++++++++++++ .../Commands/SubbaseUpgradeCommand.php | 1 + src/Models/LicenseOrder.php | 2 + src/Services/LicenseOrderService.php | 4 ++ src/Services/LicenseRedemptionService.php | 24 +++++---- src/SubbaseServiceProvider.php | 1 + tests/Licensing/LicenseTestCase.php | 1 + 7 files changed, 74 insertions(+), 10 deletions(-) create mode 100644 database/migrations/add_license_order_contract_snapshots_table.php diff --git a/database/migrations/add_license_order_contract_snapshots_table.php b/database/migrations/add_license_order_contract_snapshots_table.php new file mode 100644 index 0000000..feb0c63 --- /dev/null +++ b/database/migrations/add_license_order_contract_snapshots_table.php @@ -0,0 +1,51 @@ +unsignedBigInteger('contract_plan_id')->nullable(); + $table->string('contract_product_sku', 80)->nullable(); + $table->unsignedSmallInteger('contract_term_count')->nullable(); + $table->string('contract_term_unit', 10)->nullable(); + }); + + // Earlier prototype orders never included a frozen license term. + // Backfill a best-effort snapshot from their CURRENT catalog values; + // immutable historical terms cannot be reconstructed after edits. + DB::table($tables['orders'])->orderBy('id')->chunkById(100, function ($orders) use ($tables): void { + foreach ($orders as $order) { + $offer = DB::table($tables['offers'])->where('id', $order->offer_id)->first(); + $product = $offer + ? DB::table($tables['products'])->where('id', $offer->product_id)->first() + : null; + + if (! $offer || ! $product) { + continue; + } + + DB::table($tables['orders'])->where('id', $order->id)->update([ + 'contract_plan_id' => $offer->plan_id, + 'contract_product_sku' => $product->sku, + 'contract_term_count' => $offer->term_count, + 'contract_term_unit' => $offer->term_unit, + ]); + } + }); + } + + public function down(): void + { + // Deleting purchased terms would destroy contractual entitlements. + // A production rollback requires a reviewed data-safe migration. + } +}; diff --git a/src/Console/Commands/SubbaseUpgradeCommand.php b/src/Console/Commands/SubbaseUpgradeCommand.php index 4f527c0..025d3e3 100644 --- a/src/Console/Commands/SubbaseUpgradeCommand.php +++ b/src/Console/Commands/SubbaseUpgradeCommand.php @@ -87,6 +87,7 @@ protected function publishMigrations(): void 'upgrade_billing_decimal_columns.php', 'create_license_catalog_and_providers_table.php', 'create_license_orders_and_keys_table.php', + 'add_license_order_contract_snapshots_table.php', ]; $published = 0; diff --git a/src/Models/LicenseOrder.php b/src/Models/LicenseOrder.php index 5a5832d..df5ffc4 100644 --- a/src/Models/LicenseOrder.php +++ b/src/Models/LicenseOrder.php @@ -15,12 +15,14 @@ class LicenseOrder extends Model 'public_id', 'offer_id', 'provider_id', 'purchaser_type', 'purchaser_id', 'channel', 'quantity', 'currency', 'retail_reference_price', 'unit_price', 'total_amount', 'status', 'idempotency_key', 'payment_id', 'fulfilled_at', + 'contract_plan_id', 'contract_product_sku', 'contract_term_count', 'contract_term_unit', ]; protected function casts(): array { return [ 'quantity' => 'integer', + 'contract_term_count' => 'integer', 'unit_price' => 'decimal:4', 'retail_reference_price' => 'decimal:4', 'total_amount' => 'decimal:4', diff --git a/src/Services/LicenseOrderService.php b/src/Services/LicenseOrderService.php index 09f5348..39de121 100644 --- a/src/Services/LicenseOrderService.php +++ b/src/Services/LicenseOrderService.php @@ -108,6 +108,10 @@ public function place( 'purchaser_type' => $purchaser->getMorphClass(), 'purchaser_id' => (string) $purchaser->getKey(), 'channel' => $isWholesale ? 'wholesale' : 'retail', + 'contract_plan_id' => $offer->plan_id, + 'contract_product_sku' => $offer->product->sku, + 'contract_term_count' => $offer->term_count, + 'contract_term_unit' => $offer->term_unit, 'quantity' => $quantity, 'currency' => strtoupper((string) $offer->currency), 'retail_reference_price' => $retail->amount(), diff --git a/src/Services/LicenseRedemptionService.php b/src/Services/LicenseRedemptionService.php index ece7361..fd2253b 100644 --- a/src/Services/LicenseRedemptionService.php +++ b/src/Services/LicenseRedemptionService.php @@ -53,16 +53,20 @@ public function redeem(string $code, Model $billable, Authenticatable $actor): L throw new RuntimeException('This license has not been paid for.'); } - $offer = $key->offer()->firstOrFail(); - $product = $offer->product()->firstOrFail(); - if (! preg_match('/^[a-z0-9][a-z0-9-]{0,65}$/D', (string) $product->sku)) { - throw new RuntimeException('License product SKU is invalid.'); + // Offer prices, plan associations, and term lengths may change + // AFTER a key is sold. Honor the frozen contract in its paid order. + $sku = (string) $order->contract_product_sku; + if (! preg_match('/^[a-z0-9][a-z0-9-]{0,65}$/D', $sku) + || ! in_array($order->contract_term_unit, ['day', 'month', 'year'], true) + || (int) $order->contract_term_count < 1 + ) { + throw new RuntimeException('This license lacks a valid frozen purchase contract.'); } $planClass = config('subbase.models.plan', Plan::class); - $plan = $planClass::query()->findOrFail($offer->plan_id); + $plan = $planClass::query()->findOrFail($order->contract_plan_id); - $subscriptionName = 'license-'.$product->sku; + $subscriptionName = 'license-'.$sku; $subscription = $billable->planSubscriptions() ->where('slug', $subscriptionName) ->lockForUpdate() @@ -77,10 +81,10 @@ public function redeem(string $code, Model $billable, Authenticatable $actor): L $start = $subscription->ends_at->copy(); } - $end = match ($offer->term_unit) { - 'day' => $start->copy()->addDays((int) $offer->term_count), - 'month' => $start->copy()->addMonthsNoOverflow((int) $offer->term_count), - 'year' => $start->copy()->addYearsNoOverflow((int) $offer->term_count), + $end = match ($order->contract_term_unit) { + 'day' => $start->copy()->addDays((int) $order->contract_term_count), + 'month' => $start->copy()->addMonthsNoOverflow((int) $order->contract_term_count), + 'year' => $start->copy()->addYearsNoOverflow((int) $order->contract_term_count), default => throw new RuntimeException('Unsupported license term.'), }; diff --git a/src/SubbaseServiceProvider.php b/src/SubbaseServiceProvider.php index d4c75c4..b964dea 100644 --- a/src/SubbaseServiceProvider.php +++ b/src/SubbaseServiceProvider.php @@ -51,6 +51,7 @@ public function configurePackage(Package $package): void 'upgrade_billing_decimal_columns.php', 'create_license_catalog_and_providers_table.php', 'create_license_orders_and_keys_table.php', + 'add_license_order_contract_snapshots_table.php', ]; foreach ($migrations as $migration) { diff --git a/tests/Licensing/LicenseTestCase.php b/tests/Licensing/LicenseTestCase.php index 8fd2b75..ad6fd82 100644 --- a/tests/Licensing/LicenseTestCase.php +++ b/tests/Licensing/LicenseTestCase.php @@ -86,6 +86,7 @@ protected function setUp(): void foreach ([ 'create_license_catalog_and_providers_table', 'create_license_orders_and_keys_table', + 'add_license_order_contract_snapshots_table', ] as $name) { $migration = require dirname(__DIR__, 2).'/database/migrations/'.$name.'.php'; $migration->up(); From e8532505037dc26cbfceb444a8ee7628c4278ffb Mon Sep 17 00:00:00 2001 From: mstfkhazaal <47450090+mstfkhazaal@users.noreply.github.com> Date: Thu, 29 Oct 2026 10:19:11 +0200 Subject: [PATCH 35/45] fix(licenses): validate admin-defined prices and prove purchased key terms survive catalog edits --- src/Models/LicenseOffer.php | 26 +++++++++++++++++++++++ src/Models/LicenseProduct.php | 12 +++++++++++ tests/Licensing/LicenseRedemptionTest.php | 22 +++++++++++++++++++ 3 files changed, 60 insertions(+) diff --git a/src/Models/LicenseOffer.php b/src/Models/LicenseOffer.php index f99b70d..2836d1e 100644 --- a/src/Models/LicenseOffer.php +++ b/src/Models/LicenseOffer.php @@ -6,6 +6,8 @@ use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; +use InvalidArgumentException; +use Nafiswatsiq\Subbase\Support\Money; class LicenseOffer extends Model { @@ -25,6 +27,30 @@ protected function casts(): array ]; } + protected static function booted(): void + { + static::saving(function (self $offer): void { + $currency = strtoupper(trim((string) $offer->currency)); + $retail = new Money((string) $offer->retail_price, $currency); + $wholesale = new Money((string) $offer->wholesale_price, $currency); + + if ($retail->isZero() || $wholesale->isZero() + || bccomp($retail->amount(), $wholesale->amount(), 4) < 0 + || (int) $offer->wholesale_minimum < 2 + || (int) $offer->term_count < 1 + || (int) $offer->term_count > 120 + || ! in_array($offer->term_unit, ['day', 'month', 'year'], true) + || ! preg_match('/^[a-z0-9][a-z0-9-]{0,119}$/D', (string) $offer->sku) + ) { + throw new InvalidArgumentException('Invalid license offer: check SKU, prices, wholesale MOQ and term.'); + } + + $offer->currency = $currency; + $offer->retail_price = $retail->amount(); + $offer->wholesale_price = $wholesale->amount(); + }); + } + public function getTable(): string { return config('subbase.licensing.tables.offers', 'subbase_license_offers'); diff --git a/src/Models/LicenseProduct.php b/src/Models/LicenseProduct.php index b162614..f10bec4 100644 --- a/src/Models/LicenseProduct.php +++ b/src/Models/LicenseProduct.php @@ -6,6 +6,7 @@ use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\HasMany; +use InvalidArgumentException; class LicenseProduct extends Model { @@ -16,6 +17,17 @@ protected function casts(): array return ['is_active' => 'boolean']; } + protected static function booted(): void + { + static::saving(function (self $product): void { + if (! preg_match('/^[a-z0-9][a-z0-9-]{0,65}$/D', (string) $product->sku) + || trim((string) $product->name) === '' + ) { + throw new InvalidArgumentException('A license product requires a valid SKU and name.'); + } + }); + } + public function getTable(): string { return config('subbase.licensing.tables.products', 'subbase_license_products'); diff --git a/tests/Licensing/LicenseRedemptionTest.php b/tests/Licensing/LicenseRedemptionTest.php index c1c8201..117a1c5 100644 --- a/tests/Licensing/LicenseRedemptionTest.php +++ b/tests/Licensing/LicenseRedemptionTest.php @@ -54,6 +54,28 @@ public function test_a_second_key_extends_same_product_subscription_without_dupl $this->assertSame($firstEnd->addYearNoOverflow()->toDateString(), $second->ends_at->toDateString()); } + public function test_catalog_edits_after_sale_cannot_change_purchased_license_duration_or_product(): void + { + $provider = $this->reseller(); + $offer = $this->offer(); + $order = app(LicenseOrderService::class)->place( + $offer, $this->organization(1), $this->actor('merchant'), 12, $provider, + ); + app(LicenseFulfillmentService::class)->fulfillPaidOrder($order, 130); + $key = app(LicenseInventoryService::class)->reveal($order, $this->actor('merchant'))[0]; + + $offer->update(['term_count' => 3]); + $offer->product->update(['sku' => 'renamed-crm']); + + app(LicenseRedemptionService::class)->redeem($key, $this->organization(2), $this->actor('customer')); + + $subscription = $this->organization(2)->planSubscriptions()->firstOrFail(); + $this->assertSame('license-crm', $subscription->slug); + $this->assertSame(now()->addYearNoOverflow()->toDateString(), $subscription->ends_at->toDateString()); + $this->assertSame('crm', $order->contract_product_sku); + $this->assertSame(1, $order->contract_term_count); + } + public function test_invalid_key_never_creates_subscription(): void { $this->expectException(InvalidArgumentException::class); From 0a0a204139391169d020027da92c27b959d477c9 Mon Sep 17 00:00:00 2001 From: mstfkhazaal <47450090+mstfkhazaal@users.noreply.github.com> Date: Thu, 29 Oct 2026 10:19:24 +0200 Subject: [PATCH 36/45] test(filament): load licensing resources and deny anonymous catalog/provider access --- tests/Licensing/LicenseAdminResourcesTest.php | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 tests/Licensing/LicenseAdminResourcesTest.php diff --git a/tests/Licensing/LicenseAdminResourcesTest.php b/tests/Licensing/LicenseAdminResourcesTest.php new file mode 100644 index 0000000..abc612b --- /dev/null +++ b/tests/Licensing/LicenseAdminResourcesTest.php @@ -0,0 +1,42 @@ +assertTrue(class_exists($resource)); + $this->assertFalse($resource::canCreate() && in_array($resource, [ + LicenseProviderResource::class, + LicenseOrderResource::class, + LicenseKeyResource::class, + ], true)); + } + } + + public function test_public_users_cannot_open_license_catalog_admin(): void + { + $this->assertFalse(LicenseProductResource::canViewAny()); + $this->assertFalse(LicenseOfferResource::canViewAny()); + $this->assertFalse(LicenseProviderResource::canViewAny()); + $this->assertFalse(LicenseOrderResource::canViewAny()); + $this->assertFalse(LicenseKeyResource::canViewAny()); + } +} From 132263cadab7ed5e1a67d7762ae8627b7dead609 Mon Sep 17 00:00:00 2001 From: mstfkhazaal <47450090+mstfkhazaal@users.noreply.github.com> Date: Thu, 29 Oct 2026 10:19:34 +0200 Subject: [PATCH 37/45] ci(filament): enforce formatting and PHPUnit class load for all reseller admin resources --- .github/workflows/tests.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index f7eda5f..3a0e7c1 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -23,5 +23,7 @@ jobs: find src/Filament/Resources/LicenseProducts src/Filament/Resources/LicenseOffers src/Filament/Resources/LicenseProviders src/Filament/Resources/LicenseOrders src/Filament/Resources/LicenseKeys -name '*.php' -exec php -l {} \; - run: vendor/bin/phpunit # The upstream fork has pre-existing style drift. Format existing files in a separate PR. - - run: vendor/bin/pint --test src/Support/SubbasePermission.php tests/TestCase.php tests/Authorization/SubbasePermissionTest.php src/Support/Money.php tests/Money/MoneyTest.php src/Support/SubbaseTenancy.php src/Contracts/TenantAccess.php tests/Tenancy/SubbaseTenancyTest.php tests/Money/PrecisionMigrationTest.php tests/Money/ExactPricingTest.php src/Services/SubscriptionAdministration.php tests/Subscriptions/SubscriptionAdministrationTest.php src/Models/LicenseProduct.php src/Models/LicenseOffer.php src/Models/LicenseProvider.php src/Models/LicenseOrder.php src/Models/LicenseKey.php src/Models/LicenseSale.php src/Services/LicenseProviderService.php src/Services/LicenseOrderService.php src/Services/LicenseFulfillmentService.php src/Services/LicenseInventoryService.php src/Services/LicenseRedemptionService.php src/Services/LicenseResaleService.php tests/Licensing/LicenseTestCase.php tests/Licensing/LicenseWholesaleTest.php tests/Licensing/LicenseRedemptionTest.php + - run: vendor/bin/pint --test src/Support/SubbasePermission.php tests/TestCase.php tests/Authorization/SubbasePermissionTest.php src/Support/Money.php tests/Money/MoneyTest.php src/Support/SubbaseTenancy.php src/Contracts/TenantAccess.php tests/Tenancy/SubbaseTenancyTest.php tests/Money/PrecisionMigrationTest.php tests/Money/ExactPricingTest.php src/Services/SubscriptionAdministration.php tests/Subscriptions/SubscriptionAdministrationTest.php src/Models/LicenseProduct.php src/Models/LicenseOffer.php src/Models/LicenseProvider.php src/Models/LicenseOrder.php src/Models/LicenseKey.php src/Models/LicenseSale.php src/Services/LicenseProviderService.php src/Services/LicenseOrderService.php src/Services/LicenseFulfillmentService.php src/Services/LicenseInventoryService.php src/Services/LicenseRedemptionService.php src/Services/LicenseResaleService.php tests/Licensing/LicenseTestCase.php tests/Licensing/LicenseWholesaleTest.php tests/Licensing/LicenseRedemptionTest.php tests/Licensing/LicenseAdminResourcesTest.php + - name: Pint licensing Filament 5 resources + run: vendor/bin/pint --test src/Filament/Resources/LicenseProducts src/Filament/Resources/LicenseOffers src/Filament/Resources/LicenseProviders src/Filament/Resources/LicenseOrders src/Filament/Resources/LicenseKeys - run: composer audit --no-dev From 99c424a6366b79f6cc4a65190af04fe0a1ba1929 Mon Sep 17 00:00:00 2001 From: mstfkhazaal <47450090+mstfkhazaal@users.noreply.github.com> Date: Thu, 29 Oct 2026 10:20:13 +0200 Subject: [PATCH 38/45] feat(resellers): add private provider dashboard with per-currency inventory, spend and gross margin --- .github/workflows/tests.yml | 2 +- src/Services/LicenseProviderDashboard.php | 74 +++++++++++++++++++++++ tests/Licensing/LicenseWholesaleTest.php | 24 ++++++++ 3 files changed, 99 insertions(+), 1 deletion(-) create mode 100644 src/Services/LicenseProviderDashboard.php diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 3a0e7c1..829871d 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -23,7 +23,7 @@ jobs: find src/Filament/Resources/LicenseProducts src/Filament/Resources/LicenseOffers src/Filament/Resources/LicenseProviders src/Filament/Resources/LicenseOrders src/Filament/Resources/LicenseKeys -name '*.php' -exec php -l {} \; - run: vendor/bin/phpunit # The upstream fork has pre-existing style drift. Format existing files in a separate PR. - - run: vendor/bin/pint --test src/Support/SubbasePermission.php tests/TestCase.php tests/Authorization/SubbasePermissionTest.php src/Support/Money.php tests/Money/MoneyTest.php src/Support/SubbaseTenancy.php src/Contracts/TenantAccess.php tests/Tenancy/SubbaseTenancyTest.php tests/Money/PrecisionMigrationTest.php tests/Money/ExactPricingTest.php src/Services/SubscriptionAdministration.php tests/Subscriptions/SubscriptionAdministrationTest.php src/Models/LicenseProduct.php src/Models/LicenseOffer.php src/Models/LicenseProvider.php src/Models/LicenseOrder.php src/Models/LicenseKey.php src/Models/LicenseSale.php src/Services/LicenseProviderService.php src/Services/LicenseOrderService.php src/Services/LicenseFulfillmentService.php src/Services/LicenseInventoryService.php src/Services/LicenseRedemptionService.php src/Services/LicenseResaleService.php tests/Licensing/LicenseTestCase.php tests/Licensing/LicenseWholesaleTest.php tests/Licensing/LicenseRedemptionTest.php tests/Licensing/LicenseAdminResourcesTest.php + - run: vendor/bin/pint --test src/Support/SubbasePermission.php tests/TestCase.php tests/Authorization/SubbasePermissionTest.php src/Support/Money.php tests/Money/MoneyTest.php src/Support/SubbaseTenancy.php src/Contracts/TenantAccess.php tests/Tenancy/SubbaseTenancyTest.php tests/Money/PrecisionMigrationTest.php tests/Money/ExactPricingTest.php src/Services/SubscriptionAdministration.php tests/Subscriptions/SubscriptionAdministrationTest.php src/Models/LicenseProduct.php src/Models/LicenseOffer.php src/Models/LicenseProvider.php src/Models/LicenseOrder.php src/Models/LicenseKey.php src/Models/LicenseSale.php src/Services/LicenseProviderService.php src/Services/LicenseOrderService.php src/Services/LicenseFulfillmentService.php src/Services/LicenseInventoryService.php src/Services/LicenseRedemptionService.php src/Services/LicenseResaleService.php src/Services/LicenseProviderDashboard.php tests/Licensing/LicenseTestCase.php tests/Licensing/LicenseWholesaleTest.php tests/Licensing/LicenseRedemptionTest.php tests/Licensing/LicenseAdminResourcesTest.php - name: Pint licensing Filament 5 resources run: vendor/bin/pint --test src/Filament/Resources/LicenseProducts src/Filament/Resources/LicenseOffers src/Filament/Resources/LicenseProviders src/Filament/Resources/LicenseOrders src/Filament/Resources/LicenseKeys - run: composer audit --no-dev diff --git a/src/Services/LicenseProviderDashboard.php b/src/Services/LicenseProviderDashboard.php new file mode 100644 index 0000000..ba621d9 --- /dev/null +++ b/src/Services/LicenseProviderDashboard.php @@ -0,0 +1,74 @@ +, currencies: array>} + */ + public function summary(LicenseProvider $provider, Authenticatable $actor): array + { + if (! Gate::forUser($actor)->allows('viewLicenseProviderDashboard', $provider)) { + throw new AuthorizationException('Cannot view this reseller account.'); + } + + $currencyTotals = []; + + LicenseOrder::query() + ->where('provider_id', $provider->getKey()) + ->where('status', 'fulfilled') + ->orderBy('id') + ->chunkById(100, function ($orders) use (&$currencyTotals): void { + foreach ($orders as $order) { + $currency = strtoupper((string) $order->currency); + $currencyTotals[$currency] ??= ['purchases' => '0.0000', 'sales' => '0.0000', 'gross_margin' => '0.0000']; + $currencyTotals[$currency]['purchases'] = bcadd( + $currencyTotals[$currency]['purchases'], (string) $order->total_amount, 4, + ); + } + }); + + LicenseSale::query() + ->where('provider_id', $provider->getKey()) + ->with('key.order') + ->orderBy('id') + ->chunkById(100, function ($sales) use (&$currencyTotals): void { + foreach ($sales as $sale) { + $order = $sale->key->order; + $currency = strtoupper((string) $sale->currency); + $currencyTotals[$currency] ??= ['purchases' => '0.0000', 'sales' => '0.0000', 'gross_margin' => '0.0000']; + $currencyTotals[$currency]['sales'] = bcadd( + $currencyTotals[$currency]['sales'], (string) $sale->sale_price, 4, + ); + $currencyTotals[$currency]['gross_margin'] = bcadd( + $currencyTotals[$currency]['gross_margin'], + bcsub((string) $sale->sale_price, (string) $order->unit_price, 4), + 4, + ); + } + }); + + return [ + 'provider_status' => (string) $provider->status, + 'orders' => LicenseOrder::query()->where('provider_id', $provider->getKey())->count(), + 'keys' => [ + 'available' => LicenseKey::query()->where('provider_id', $provider->getKey())->where('status', 'available')->count(), + 'redeemed' => LicenseKey::query()->where('provider_id', $provider->getKey())->where('status', 'redeemed')->count(), + 'revoked' => LicenseKey::query()->where('provider_id', $provider->getKey())->where('status', 'revoked')->count(), + 'sales_recorded' => LicenseSale::query()->where('provider_id', $provider->getKey())->count(), + ], + 'currencies' => $currencyTotals, + ]; + } +} diff --git a/tests/Licensing/LicenseWholesaleTest.php b/tests/Licensing/LicenseWholesaleTest.php index f47efe8..528f988 100644 --- a/tests/Licensing/LicenseWholesaleTest.php +++ b/tests/Licensing/LicenseWholesaleTest.php @@ -11,6 +11,7 @@ use Nafiswatsiq\Subbase\Services\LicenseFulfillmentService; use Nafiswatsiq\Subbase\Services\LicenseInventoryService; use Nafiswatsiq\Subbase\Services\LicenseOrderService; +use Nafiswatsiq\Subbase\Services\LicenseProviderDashboard; use Nafiswatsiq\Subbase\Services\LicenseProviderService; use Nafiswatsiq\Subbase\Services\LicenseResaleService; use RuntimeException; @@ -50,6 +51,29 @@ public function test_reseller_buys_twelve_for_one_hundred_each_and_earns_forty_p $this->assertSame(12, $order->keys()->count()); } + public function test_dashboard_tracks_wholesale_spend_and_declared_reseller_margin_by_currency(): void + { + $provider = $this->reseller(); + $merchant = $this->actor('merchant'); + \Illuminate\Support\Facades\Gate::define('viewLicenseProviderDashboard', static fn ($actor, $subject): bool => $actor->name === 'merchant' && $subject->getKey() === $provider->getKey()); + + $order = app(LicenseOrderService::class)->place( + $this->offer(), $this->organization(1), $merchant, 12, $provider, + ); + app(LicenseFulfillmentService::class)->fulfillPaidOrder($order, 884); + + foreach ($order->keys()->limit(2)->get() as $key) { + app(LicenseResaleService::class)->record($key, $provider, $merchant, '140.00'); + } + + $summary = app(LicenseProviderDashboard::class)->summary($provider, $merchant); + $this->assertSame(12, $summary['keys']['available']); + $this->assertSame(2, $summary['keys']['sales_recorded']); + $this->assertSame('1200.0000', $summary['currencies']['USD']['purchases']); + $this->assertSame('280.0000', $summary['currencies']['USD']['sales']); + $this->assertSame('80.0000', $summary['currencies']['USD']['gross_margin']); + } + public function test_pending_orders_cannot_export_license_keys(): void { $order = app(LicenseOrderService::class)->place( From eb553cf7714629449bac39fc55595273aa4f19b1 Mon Sep 17 00:00:00 2001 From: mstfkhazaal <47450090+mstfkhazaal@users.noreply.github.com> Date: Thu, 29 Oct 2026 10:20:56 +0200 Subject: [PATCH 39/45] ci: capture exact Pint diff for newly generated Filament resource UI --- .github/workflows/tests.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 829871d..cdbc90c 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -24,6 +24,11 @@ jobs: - run: vendor/bin/phpunit # The upstream fork has pre-existing style drift. Format existing files in a separate PR. - run: vendor/bin/pint --test src/Support/SubbasePermission.php tests/TestCase.php tests/Authorization/SubbasePermissionTest.php src/Support/Money.php tests/Money/MoneyTest.php src/Support/SubbaseTenancy.php src/Contracts/TenantAccess.php tests/Tenancy/SubbaseTenancyTest.php tests/Money/PrecisionMigrationTest.php tests/Money/ExactPricingTest.php src/Services/SubscriptionAdministration.php tests/Subscriptions/SubscriptionAdministrationTest.php src/Models/LicenseProduct.php src/Models/LicenseOffer.php src/Models/LicenseProvider.php src/Models/LicenseOrder.php src/Models/LicenseKey.php src/Models/LicenseSale.php src/Services/LicenseProviderService.php src/Services/LicenseOrderService.php src/Services/LicenseFulfillmentService.php src/Services/LicenseInventoryService.php src/Services/LicenseRedemptionService.php src/Services/LicenseResaleService.php src/Services/LicenseProviderDashboard.php tests/Licensing/LicenseTestCase.php tests/Licensing/LicenseWholesaleTest.php tests/Licensing/LicenseRedemptionTest.php tests/Licensing/LicenseAdminResourcesTest.php + - name: Inspect exact Filament 5 Pint normalizations + run: | + vendor/bin/pint src/Filament/Resources/LicenseProducts src/Filament/Resources/LicenseOffers src/Filament/Resources/LicenseProviders src/Filament/Resources/LicenseOrders src/Filament/Resources/LicenseKeys + git diff -- src/Filament/Resources/LicenseProducts src/Filament/Resources/LicenseOffers src/Filament/Resources/LicenseProviders src/Filament/Resources/LicenseOrders src/Filament/Resources/LicenseKeys + git diff --quiet -- src/Filament/Resources/LicenseProducts src/Filament/Resources/LicenseOffers src/Filament/Resources/LicenseProviders src/Filament/Resources/LicenseOrders src/Filament/Resources/LicenseKeys - name: Pint licensing Filament 5 resources run: vendor/bin/pint --test src/Filament/Resources/LicenseProducts src/Filament/Resources/LicenseOffers src/Filament/Resources/LicenseProviders src/Filament/Resources/LicenseOrders src/Filament/Resources/LicenseKeys - run: composer audit --no-dev From 62cabc5ee8ff6c3ff2ca1f965d75b153b315fae6 Mon Sep 17 00:00:00 2001 From: mstfkhazaal <47450090+mstfkhazaal@users.noreply.github.com> Date: Thu, 29 Oct 2026 10:21:32 +0200 Subject: [PATCH 40/45] style(licenses): normalize Gate and reseller dashboard imports --- tests/Licensing/LicenseWholesaleTest.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/Licensing/LicenseWholesaleTest.php b/tests/Licensing/LicenseWholesaleTest.php index 528f988..2005765 100644 --- a/tests/Licensing/LicenseWholesaleTest.php +++ b/tests/Licensing/LicenseWholesaleTest.php @@ -5,6 +5,7 @@ namespace Nafiswatsiq\Subbase\Tests\Licensing; use Illuminate\Auth\Access\AuthorizationException; +use Illuminate\Support\Facades\Gate; use InvalidArgumentException; use Nafiswatsiq\Subbase\Models\LicenseKey; use Nafiswatsiq\Subbase\Models\LicenseOrder; @@ -55,7 +56,7 @@ public function test_dashboard_tracks_wholesale_spend_and_declared_reseller_marg { $provider = $this->reseller(); $merchant = $this->actor('merchant'); - \Illuminate\Support\Facades\Gate::define('viewLicenseProviderDashboard', static fn ($actor, $subject): bool => $actor->name === 'merchant' && $subject->getKey() === $provider->getKey()); + Gate::define('viewLicenseProviderDashboard', static fn ($actor, $subject): bool => $actor->name === 'merchant' && $subject->getKey() === $provider->getKey()); $order = app(LicenseOrderService::class)->place( $this->offer(), $this->organization(1), $merchant, 12, $provider, From 91b8085a943c9e4f6f3e1106984c948d90aaacf5 Mon Sep 17 00:00:00 2001 From: mstfkhazaal <47450090+mstfkhazaal@users.noreply.github.com> Date: Thu, 29 Oct 2026 10:25:14 +0200 Subject: [PATCH 41/45] style(filament): apply exact Pint-normalized licensing resources and restore CI --- .github/workflows/tests.yml | 5 ---- .../LicenseKeys/LicenseKeyResource.php | 18 ++++++------- .../LicenseOffers/LicenseOfferResource.php | 6 ++--- .../Schemas/LicenseOfferForm.php | 26 +++++++++---------- .../Tables/LicenseOffersTable.php | 16 ++++++------ .../LicenseOrders/LicenseOrderResource.php | 26 +++++++++---------- .../LicenseProductResource.php | 6 ++--- .../Schemas/LicenseProductForm.php | 10 +++---- .../Tables/LicenseProductsTable.php | 8 +++--- .../LicenseProviderResource.php | 6 ++--- .../Tables/LicenseProvidersTable.php | 14 +++++----- 11 files changed, 67 insertions(+), 74 deletions(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index cdbc90c..829871d 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -24,11 +24,6 @@ jobs: - run: vendor/bin/phpunit # The upstream fork has pre-existing style drift. Format existing files in a separate PR. - run: vendor/bin/pint --test src/Support/SubbasePermission.php tests/TestCase.php tests/Authorization/SubbasePermissionTest.php src/Support/Money.php tests/Money/MoneyTest.php src/Support/SubbaseTenancy.php src/Contracts/TenantAccess.php tests/Tenancy/SubbaseTenancyTest.php tests/Money/PrecisionMigrationTest.php tests/Money/ExactPricingTest.php src/Services/SubscriptionAdministration.php tests/Subscriptions/SubscriptionAdministrationTest.php src/Models/LicenseProduct.php src/Models/LicenseOffer.php src/Models/LicenseProvider.php src/Models/LicenseOrder.php src/Models/LicenseKey.php src/Models/LicenseSale.php src/Services/LicenseProviderService.php src/Services/LicenseOrderService.php src/Services/LicenseFulfillmentService.php src/Services/LicenseInventoryService.php src/Services/LicenseRedemptionService.php src/Services/LicenseResaleService.php src/Services/LicenseProviderDashboard.php tests/Licensing/LicenseTestCase.php tests/Licensing/LicenseWholesaleTest.php tests/Licensing/LicenseRedemptionTest.php tests/Licensing/LicenseAdminResourcesTest.php - - name: Inspect exact Filament 5 Pint normalizations - run: | - vendor/bin/pint src/Filament/Resources/LicenseProducts src/Filament/Resources/LicenseOffers src/Filament/Resources/LicenseProviders src/Filament/Resources/LicenseOrders src/Filament/Resources/LicenseKeys - git diff -- src/Filament/Resources/LicenseProducts src/Filament/Resources/LicenseOffers src/Filament/Resources/LicenseProviders src/Filament/Resources/LicenseOrders src/Filament/Resources/LicenseKeys - git diff --quiet -- src/Filament/Resources/LicenseProducts src/Filament/Resources/LicenseOffers src/Filament/Resources/LicenseProviders src/Filament/Resources/LicenseOrders src/Filament/Resources/LicenseKeys - name: Pint licensing Filament 5 resources run: vendor/bin/pint --test src/Filament/Resources/LicenseProducts src/Filament/Resources/LicenseOffers src/Filament/Resources/LicenseProviders src/Filament/Resources/LicenseOrders src/Filament/Resources/LicenseKeys - run: composer audit --no-dev diff --git a/src/Filament/Resources/LicenseKeys/LicenseKeyResource.php b/src/Filament/Resources/LicenseKeys/LicenseKeyResource.php index b671b7b..cfab2d3 100644 --- a/src/Filament/Resources/LicenseKeys/LicenseKeyResource.php +++ b/src/Filament/Resources/LicenseKeys/LicenseKeyResource.php @@ -5,7 +5,6 @@ namespace Nafiswatsiq\Subbase\Filament\Resources\LicenseKeys; use BackedEnum; -use UnitEnum; use Filament\Resources\Resource; use Filament\Support\Icons\Heroicon; use Filament\Tables\Columns\TextColumn; @@ -14,9 +13,10 @@ use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Gate; +use Nafiswatsiq\Subbase\Filament\Resources\LicenseKeys\Pages\ListLicenseKeys; use Nafiswatsiq\Subbase\Models\LicenseKey; use Nafiswatsiq\Subbase\Support\SubbaseTenancy; -use Nafiswatsiq\Subbase\Filament\Resources\LicenseKeys\Pages\ListLicenseKeys; +use UnitEnum; class LicenseKeyResource extends Resource { @@ -59,13 +59,13 @@ public static function getEloquentQuery(): Builder public static function table(Table $table): Table { return $table->columns([ - TextColumn::make('id')->label('License ID'), - TextColumn::make('code_tail')->label('Last 8 characters'), - TextColumn::make('order.public_id')->label('Order'), - TextColumn::make('provider.business_name')->label('Provider'), - TextColumn::make('status')->badge(), - TextColumn::make('redeemed_at')->dateTime(), - ])->defaultSort('created_at', 'desc'); + TextColumn::make('id')->label('License ID'), + TextColumn::make('code_tail')->label('Last 8 characters'), + TextColumn::make('order.public_id')->label('Order'), + TextColumn::make('provider.business_name')->label('Provider'), + TextColumn::make('status')->badge(), + TextColumn::make('redeemed_at')->dateTime(), + ])->defaultSort('created_at', 'desc'); } public static function getPages(): array diff --git a/src/Filament/Resources/LicenseOffers/LicenseOfferResource.php b/src/Filament/Resources/LicenseOffers/LicenseOfferResource.php index d61032c..c8b3b37 100644 --- a/src/Filament/Resources/LicenseOffers/LicenseOfferResource.php +++ b/src/Filament/Resources/LicenseOffers/LicenseOfferResource.php @@ -5,7 +5,6 @@ namespace Nafiswatsiq\Subbase\Filament\Resources\LicenseOffers; use BackedEnum; -use UnitEnum; use Filament\Resources\Resource; use Filament\Schemas\Schema; use Filament\Support\Icons\Heroicon; @@ -14,13 +13,14 @@ use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Gate; -use Nafiswatsiq\Subbase\Models\LicenseOffer; -use Nafiswatsiq\Subbase\Support\SubbaseTenancy; use Nafiswatsiq\Subbase\Filament\Resources\LicenseOffers\Pages\CreateLicenseOffer; use Nafiswatsiq\Subbase\Filament\Resources\LicenseOffers\Pages\EditLicenseOffer; use Nafiswatsiq\Subbase\Filament\Resources\LicenseOffers\Pages\ListLicenseOffers; use Nafiswatsiq\Subbase\Filament\Resources\LicenseOffers\Schemas\LicenseOfferForm; use Nafiswatsiq\Subbase\Filament\Resources\LicenseOffers\Tables\LicenseOffersTable; +use Nafiswatsiq\Subbase\Models\LicenseOffer; +use Nafiswatsiq\Subbase\Support\SubbaseTenancy; +use UnitEnum; class LicenseOfferResource extends Resource { diff --git a/src/Filament/Resources/LicenseOffers/Schemas/LicenseOfferForm.php b/src/Filament/Resources/LicenseOffers/Schemas/LicenseOfferForm.php index 0a99af4..9b245a1 100644 --- a/src/Filament/Resources/LicenseOffers/Schemas/LicenseOfferForm.php +++ b/src/Filament/Resources/LicenseOffers/Schemas/LicenseOfferForm.php @@ -15,18 +15,18 @@ final class LicenseOfferForm public static function configure(Schema $schema): Schema { return $schema->components([ - Select::make('product_id')->relationship('product', 'name')->required()->searchable(), - Select::make('plan_id') - ->options(fn (): array => (config('subbase.models.plan', Plan::class))::query()->pluck('slug', 'id')->all()) - ->required()->searchable(), - TextInput::make('sku')->required()->maxLength(120)->rule('regex:/^[a-z0-9][a-z0-9-]*$/'), - TextInput::make('currency')->required()->length(3)->default('USD'), - TextInput::make('retail_price')->required()->numeric()->minValue(0.0001), - TextInput::make('wholesale_price')->required()->numeric()->minValue(0.0001), - TextInput::make('wholesale_minimum')->required()->integer()->minValue(2)->default(12), - TextInput::make('term_count')->required()->integer()->minValue(1)->maxValue(120)->default(1), - Select::make('term_unit')->required()->options(['day' => 'Days', 'month' => 'Months', 'year' => 'Years'])->default('year'), - Toggle::make('is_active')->default(true), - ])->columns(2); + Select::make('product_id')->relationship('product', 'name')->required()->searchable(), + Select::make('plan_id') + ->options(fn (): array => (config('subbase.models.plan', Plan::class))::query()->pluck('slug', 'id')->all()) + ->required()->searchable(), + TextInput::make('sku')->required()->maxLength(120)->rule('regex:/^[a-z0-9][a-z0-9-]*$/'), + TextInput::make('currency')->required()->length(3)->default('USD'), + TextInput::make('retail_price')->required()->numeric()->minValue(0.0001), + TextInput::make('wholesale_price')->required()->numeric()->minValue(0.0001), + TextInput::make('wholesale_minimum')->required()->integer()->minValue(2)->default(12), + TextInput::make('term_count')->required()->integer()->minValue(1)->maxValue(120)->default(1), + Select::make('term_unit')->required()->options(['day' => 'Days', 'month' => 'Months', 'year' => 'Years'])->default('year'), + Toggle::make('is_active')->default(true), + ])->columns(2); } } diff --git a/src/Filament/Resources/LicenseOffers/Tables/LicenseOffersTable.php b/src/Filament/Resources/LicenseOffers/Tables/LicenseOffersTable.php index ad858d8..c7c0360 100644 --- a/src/Filament/Resources/LicenseOffers/Tables/LicenseOffersTable.php +++ b/src/Filament/Resources/LicenseOffers/Tables/LicenseOffersTable.php @@ -14,14 +14,14 @@ final class LicenseOffersTable public static function configure(Table $table): Table { return $table->columns([ - TextColumn::make('sku')->searchable(), - TextColumn::make('product.name')->label('Product'), - TextColumn::make('currency'), - TextColumn::make('retail_price')->label('Retail'), - TextColumn::make('wholesale_price')->label('Wholesale'), - TextColumn::make('wholesale_minimum')->label('Minimum quantity'), - IconColumn::make('is_active')->boolean(), - ]) + TextColumn::make('sku')->searchable(), + TextColumn::make('product.name')->label('Product'), + TextColumn::make('currency'), + TextColumn::make('retail_price')->label('Retail'), + TextColumn::make('wholesale_price')->label('Wholesale'), + TextColumn::make('wholesale_minimum')->label('Minimum quantity'), + IconColumn::make('is_active')->boolean(), + ]) ->recordActions([EditAction::make()]) ->defaultSort('id', 'desc'); } diff --git a/src/Filament/Resources/LicenseOrders/LicenseOrderResource.php b/src/Filament/Resources/LicenseOrders/LicenseOrderResource.php index bbab517..4d796f3 100644 --- a/src/Filament/Resources/LicenseOrders/LicenseOrderResource.php +++ b/src/Filament/Resources/LicenseOrders/LicenseOrderResource.php @@ -5,7 +5,6 @@ namespace Nafiswatsiq\Subbase\Filament\Resources\LicenseOrders; use BackedEnum; -use UnitEnum; use Filament\Resources\Resource; use Filament\Support\Icons\Heroicon; use Filament\Tables\Columns\TextColumn; @@ -14,9 +13,10 @@ use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Gate; +use Nafiswatsiq\Subbase\Filament\Resources\LicenseOrders\Pages\ListLicenseOrders; use Nafiswatsiq\Subbase\Models\LicenseOrder; use Nafiswatsiq\Subbase\Support\SubbaseTenancy; -use Nafiswatsiq\Subbase\Filament\Resources\LicenseOrders\Pages\ListLicenseOrders; +use UnitEnum; class LicenseOrderResource extends Resource { @@ -59,17 +59,17 @@ public static function getEloquentQuery(): Builder public static function table(Table $table): Table { return $table->columns([ - TextColumn::make('public_id')->label('Order')->searchable(), - TextColumn::make('channel')->badge(), - TextColumn::make('provider.business_name')->label('Reseller'), - TextColumn::make('offer.sku')->label('License offer'), - TextColumn::make('quantity'), - TextColumn::make('currency'), - TextColumn::make('unit_price'), - TextColumn::make('total_amount'), - TextColumn::make('status')->badge(), - TextColumn::make('fulfilled_at')->dateTime(), - ])->defaultSort('created_at', 'desc'); + TextColumn::make('public_id')->label('Order')->searchable(), + TextColumn::make('channel')->badge(), + TextColumn::make('provider.business_name')->label('Reseller'), + TextColumn::make('offer.sku')->label('License offer'), + TextColumn::make('quantity'), + TextColumn::make('currency'), + TextColumn::make('unit_price'), + TextColumn::make('total_amount'), + TextColumn::make('status')->badge(), + TextColumn::make('fulfilled_at')->dateTime(), + ])->defaultSort('created_at', 'desc'); } public static function getPages(): array diff --git a/src/Filament/Resources/LicenseProducts/LicenseProductResource.php b/src/Filament/Resources/LicenseProducts/LicenseProductResource.php index 027b3ee..403b6fa 100644 --- a/src/Filament/Resources/LicenseProducts/LicenseProductResource.php +++ b/src/Filament/Resources/LicenseProducts/LicenseProductResource.php @@ -5,7 +5,6 @@ namespace Nafiswatsiq\Subbase\Filament\Resources\LicenseProducts; use BackedEnum; -use UnitEnum; use Filament\Resources\Resource; use Filament\Schemas\Schema; use Filament\Support\Icons\Heroicon; @@ -14,13 +13,14 @@ use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Gate; -use Nafiswatsiq\Subbase\Models\LicenseProduct; -use Nafiswatsiq\Subbase\Support\SubbaseTenancy; use Nafiswatsiq\Subbase\Filament\Resources\LicenseProducts\Pages\CreateLicenseProduct; use Nafiswatsiq\Subbase\Filament\Resources\LicenseProducts\Pages\EditLicenseProduct; use Nafiswatsiq\Subbase\Filament\Resources\LicenseProducts\Pages\ListLicenseProducts; use Nafiswatsiq\Subbase\Filament\Resources\LicenseProducts\Schemas\LicenseProductForm; use Nafiswatsiq\Subbase\Filament\Resources\LicenseProducts\Tables\LicenseProductsTable; +use Nafiswatsiq\Subbase\Models\LicenseProduct; +use Nafiswatsiq\Subbase\Support\SubbaseTenancy; +use UnitEnum; class LicenseProductResource extends Resource { diff --git a/src/Filament/Resources/LicenseProducts/Schemas/LicenseProductForm.php b/src/Filament/Resources/LicenseProducts/Schemas/LicenseProductForm.php index 1c8892f..4c8c192 100644 --- a/src/Filament/Resources/LicenseProducts/Schemas/LicenseProductForm.php +++ b/src/Filament/Resources/LicenseProducts/Schemas/LicenseProductForm.php @@ -4,20 +4,18 @@ namespace Nafiswatsiq\Subbase\Filament\Resources\LicenseProducts\Schemas; -use Filament\Forms\Components\Select; use Filament\Forms\Components\TextInput; use Filament\Forms\Components\Toggle; use Filament\Schemas\Schema; -use Nafiswatsiq\Subbase\Models\Plan; final class LicenseProductForm { public static function configure(Schema $schema): Schema { return $schema->components([ - TextInput::make('sku')->required()->maxLength(80)->rule('regex:/^[a-z0-9][a-z0-9-]*$/'), - TextInput::make('name')->required()->maxLength(150), - Toggle::make('is_active')->default(true), - ])->columns(2); + TextInput::make('sku')->required()->maxLength(80)->rule('regex:/^[a-z0-9][a-z0-9-]*$/'), + TextInput::make('name')->required()->maxLength(150), + Toggle::make('is_active')->default(true), + ])->columns(2); } } diff --git a/src/Filament/Resources/LicenseProducts/Tables/LicenseProductsTable.php b/src/Filament/Resources/LicenseProducts/Tables/LicenseProductsTable.php index 5e897f1..fb5db85 100644 --- a/src/Filament/Resources/LicenseProducts/Tables/LicenseProductsTable.php +++ b/src/Filament/Resources/LicenseProducts/Tables/LicenseProductsTable.php @@ -14,10 +14,10 @@ final class LicenseProductsTable public static function configure(Table $table): Table { return $table->columns([ - TextColumn::make('sku')->searchable(), - TextColumn::make('name')->searchable(), - IconColumn::make('is_active')->boolean(), - ]) + TextColumn::make('sku')->searchable(), + TextColumn::make('name')->searchable(), + IconColumn::make('is_active')->boolean(), + ]) ->recordActions([EditAction::make()]) ->defaultSort('id', 'desc'); } diff --git a/src/Filament/Resources/LicenseProviders/LicenseProviderResource.php b/src/Filament/Resources/LicenseProviders/LicenseProviderResource.php index 74d59a9..63be035 100644 --- a/src/Filament/Resources/LicenseProviders/LicenseProviderResource.php +++ b/src/Filament/Resources/LicenseProviders/LicenseProviderResource.php @@ -5,7 +5,6 @@ namespace Nafiswatsiq\Subbase\Filament\Resources\LicenseProviders; use BackedEnum; -use UnitEnum; use Filament\Resources\Resource; use Filament\Support\Icons\Heroicon; use Filament\Tables\Table; @@ -13,10 +12,11 @@ use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Gate; -use Nafiswatsiq\Subbase\Models\LicenseProvider; -use Nafiswatsiq\Subbase\Support\SubbaseTenancy; use Nafiswatsiq\Subbase\Filament\Resources\LicenseProviders\Pages\ListLicenseProviders; use Nafiswatsiq\Subbase\Filament\Resources\LicenseProviders\Tables\LicenseProvidersTable; +use Nafiswatsiq\Subbase\Models\LicenseProvider; +use Nafiswatsiq\Subbase\Support\SubbaseTenancy; +use UnitEnum; class LicenseProviderResource extends Resource { diff --git a/src/Filament/Resources/LicenseProviders/Tables/LicenseProvidersTable.php b/src/Filament/Resources/LicenseProviders/Tables/LicenseProvidersTable.php index 08d440e..1641cc3 100644 --- a/src/Filament/Resources/LicenseProviders/Tables/LicenseProvidersTable.php +++ b/src/Filament/Resources/LicenseProviders/Tables/LicenseProvidersTable.php @@ -17,13 +17,13 @@ final class LicenseProvidersTable public static function configure(Table $table): Table { return $table->columns([ - TextColumn::make('business_name')->searchable(), - TextColumn::make('owner_type')->label('Owner type'), - TextColumn::make('owner_id')->label('Owner ID'), - TextColumn::make('status')->badge(), - TextColumn::make('approved_at')->dateTime(), - TextColumn::make('created_at')->dateTime(), - ]) + TextColumn::make('business_name')->searchable(), + TextColumn::make('owner_type')->label('Owner type'), + TextColumn::make('owner_id')->label('Owner ID'), + TextColumn::make('status')->badge(), + TextColumn::make('approved_at')->dateTime(), + TextColumn::make('created_at')->dateTime(), + ]) ->filters([ SelectFilter::make('status')->options([ 'pending' => 'Pending', From 1e0d81599f14e87abe058405a97ea1376c62f2a9 Mon Sep 17 00:00:00 2001 From: mstfkhazaal <47450090+mstfkhazaal@users.noreply.github.com> Date: Thu, 29 Oct 2026 10:26:16 +0200 Subject: [PATCH 42/45] security: enforce host tenant access on provider approval, purchase, inventory, redemption, resale and analytics --- src/Services/LicenseInventoryService.php | 5 ++++- src/Services/LicenseOrderService.php | 8 +++++++- src/Services/LicenseProviderDashboard.php | 5 ++++- src/Services/LicenseProviderService.php | 9 +++++++-- src/Services/LicenseRedemptionService.php | 5 ++++- src/Services/LicenseResaleService.php | 5 ++++- 6 files changed, 30 insertions(+), 7 deletions(-) diff --git a/src/Services/LicenseInventoryService.php b/src/Services/LicenseInventoryService.php index 7589d57..fb0bb10 100644 --- a/src/Services/LicenseInventoryService.php +++ b/src/Services/LicenseInventoryService.php @@ -9,6 +9,7 @@ use Illuminate\Support\Facades\Crypt; use Illuminate\Support\Facades\Gate; use Nafiswatsiq\Subbase\Models\LicenseOrder; +use Nafiswatsiq\Subbase\Support\SubbaseTenancy; use RuntimeException; final class LicenseInventoryService @@ -23,7 +24,9 @@ public function reveal(LicenseOrder $order, Authenticatable $actor): array { $order = LicenseOrder::query()->findOrFail($order->getKey()); - if (! Gate::forUser($actor)->allows('viewPurchasedLicenseKeys', $order)) { + if (! SubbaseTenancy::allows($order, 'viewLicenseKeys', $actor) + || ! Gate::forUser($actor)->allows('viewPurchasedLicenseKeys', $order) + ) { throw new AuthorizationException('License inventory is private.'); } diff --git a/src/Services/LicenseOrderService.php b/src/Services/LicenseOrderService.php index 39de121..b412de4 100644 --- a/src/Services/LicenseOrderService.php +++ b/src/Services/LicenseOrderService.php @@ -15,6 +15,7 @@ use Nafiswatsiq\Subbase\Models\LicenseOrder; use Nafiswatsiq\Subbase\Models\LicenseProvider; use Nafiswatsiq\Subbase\Support\Money; +use Nafiswatsiq\Subbase\Support\SubbaseTenancy; use RuntimeException; final class LicenseOrderService @@ -39,6 +40,10 @@ public function place( throw new InvalidArgumentException('Invalid idempotency token.'); } + if (! SubbaseTenancy::allows($purchaser, 'purchaseLicense', $actor)) { + throw new AuthorizationException('Purchaser is not allowed in this tenant.'); + } + $isWholesale = $provider !== null; $max = (int) config('subbase.licensing.max_order_quantity', 500); if ($quantity < 1 || $quantity > $max) { @@ -46,7 +51,8 @@ public function place( } if ($isWholesale) { - if (! $provider->exists || ! $provider->approved() + if (! SubbaseTenancy::allows($provider, 'purchaseWholesaleLicenses', $actor) + || ! $provider->exists || ! $provider->approved() || $purchaser->getMorphClass() !== $provider->owner_type || (string) $purchaser->getKey() !== (string) $provider->owner_id || $quantity < (int) $offer->wholesale_minimum diff --git a/src/Services/LicenseProviderDashboard.php b/src/Services/LicenseProviderDashboard.php index ba621d9..297d821 100644 --- a/src/Services/LicenseProviderDashboard.php +++ b/src/Services/LicenseProviderDashboard.php @@ -11,6 +11,7 @@ use Nafiswatsiq\Subbase\Models\LicenseOrder; use Nafiswatsiq\Subbase\Models\LicenseProvider; use Nafiswatsiq\Subbase\Models\LicenseSale; +use Nafiswatsiq\Subbase\Support\SubbaseTenancy; final class LicenseProviderDashboard { @@ -19,7 +20,9 @@ final class LicenseProviderDashboard */ public function summary(LicenseProvider $provider, Authenticatable $actor): array { - if (! Gate::forUser($actor)->allows('viewLicenseProviderDashboard', $provider)) { + if (! SubbaseTenancy::allows($provider, 'view', $actor) + || ! Gate::forUser($actor)->allows('viewLicenseProviderDashboard', $provider) + ) { throw new AuthorizationException('Cannot view this reseller account.'); } diff --git a/src/Services/LicenseProviderService.php b/src/Services/LicenseProviderService.php index be5e623..c15f3e4 100644 --- a/src/Services/LicenseProviderService.php +++ b/src/Services/LicenseProviderService.php @@ -11,6 +11,7 @@ use Illuminate\Support\Facades\Gate; use InvalidArgumentException; use Nafiswatsiq\Subbase\Models\LicenseProvider; +use Nafiswatsiq\Subbase\Support\SubbaseTenancy; use RuntimeException; final class LicenseProviderService @@ -25,7 +26,9 @@ public function apply(Model $owner, Authenticatable $actor, string $businessName throw new InvalidArgumentException('Provider owner and business name are required.'); } - if (! Gate::forUser($actor)->allows('applyForLicenseProvider', $owner)) { + if (! SubbaseTenancy::allows($owner, 'applyForLicenseProvider', $actor) + || ! Gate::forUser($actor)->allows('applyForLicenseProvider', $owner) + ) { throw new AuthorizationException('Cannot submit a reseller application.'); } @@ -50,7 +53,9 @@ public function suspend(LicenseProvider $provider, Authenticatable $admin): Lice private function transition(LicenseProvider $provider, Authenticatable $admin, string $status): LicenseProvider { - if (! Gate::forUser($admin)->allows('manageLicenseProviders', $provider)) { + if (! SubbaseTenancy::allows($provider, 'update', $admin) + || ! Gate::forUser($admin)->allows('manageLicenseProviders', $provider) + ) { throw new AuthorizationException('Only an authorized billing administrator may approve resellers.'); } diff --git a/src/Services/LicenseRedemptionService.php b/src/Services/LicenseRedemptionService.php index fd2253b..8d429c9 100644 --- a/src/Services/LicenseRedemptionService.php +++ b/src/Services/LicenseRedemptionService.php @@ -12,6 +12,7 @@ use InvalidArgumentException; use Nafiswatsiq\Subbase\Models\LicenseKey; use Nafiswatsiq\Subbase\Models\Plan; +use Nafiswatsiq\Subbase\Support\SubbaseTenancy; use RuntimeException; final class LicenseRedemptionService @@ -29,7 +30,9 @@ public function redeem(string $code, Model $billable, Authenticatable $actor): L throw new InvalidArgumentException('Activation requires a saved, subscribable account.'); } - if (! Gate::forUser($actor)->allows('redeemLicenseKey', $billable)) { + if (! SubbaseTenancy::allows($billable, 'redeemLicenseKey', $actor) + || ! Gate::forUser($actor)->allows('redeemLicenseKey', $billable) + ) { throw new AuthorizationException('Cannot activate a license for this account.'); } diff --git a/src/Services/LicenseResaleService.php b/src/Services/LicenseResaleService.php index 098ee4c..07371f4 100644 --- a/src/Services/LicenseResaleService.php +++ b/src/Services/LicenseResaleService.php @@ -13,6 +13,7 @@ use Nafiswatsiq\Subbase\Models\LicenseProvider; use Nafiswatsiq\Subbase\Models\LicenseSale; use Nafiswatsiq\Subbase\Support\Money; +use Nafiswatsiq\Subbase\Support\SubbaseTenancy; use RuntimeException; final class LicenseResaleService @@ -31,7 +32,9 @@ public function record( string $salePrice, ?string $externalReference = null, ): array { - if (! Gate::forUser($actor)->allows('recordLicenseResale', $provider)) { + if (! SubbaseTenancy::allows($provider, 'recordLicenseResale', $actor) + || ! Gate::forUser($actor)->allows('recordLicenseResale', $provider) + ) { throw new AuthorizationException('Not authorized to record this reseller sale.'); } From ede24c3a5a0cf299cb423145517b29adeac341d6 Mon Sep 17 00:00:00 2001 From: mstfkhazaal <47450090+mstfkhazaal@users.noreply.github.com> Date: Thu, 29 Oct 2026 10:26:29 +0200 Subject: [PATCH 43/45] test: deny cross-tenant reseller bulk purchase and inventory export when isolation is unconfigured --- tests/Licensing/LicenseWholesaleTest.php | 25 ++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/tests/Licensing/LicenseWholesaleTest.php b/tests/Licensing/LicenseWholesaleTest.php index 2005765..e14e85e 100644 --- a/tests/Licensing/LicenseWholesaleTest.php +++ b/tests/Licensing/LicenseWholesaleTest.php @@ -75,6 +75,31 @@ public function test_dashboard_tracks_wholesale_spend_and_declared_reseller_marg $this->assertSame('80.0000', $summary['currencies']['USD']['gross_margin']); } + public function test_enabled_tenant_mode_without_resolver_blocks_reseller_purchases(): void + { + $provider = $this->reseller(); + config(['subbase.tenancy.enabled' => true, 'subbase.tenancy.access' => null]); + + $this->expectException(AuthorizationException::class); + app(LicenseOrderService::class)->place( + $this->offer(), $this->organization(1), $this->actor('merchant'), 12, $provider, + ); + } + + public function test_enabled_tenant_mode_without_resolver_blocks_key_inventory_export(): void + { + $provider = $this->reseller(); + $order = app(LicenseOrderService::class)->place( + $this->offer(), $this->organization(1), $this->actor('merchant'), 12, $provider, + ); + app(LicenseFulfillmentService::class)->fulfillPaidOrder($order, 705); + + config(['subbase.tenancy.enabled' => true, 'subbase.tenancy.access' => null]); + + $this->expectException(AuthorizationException::class); + app(LicenseInventoryService::class)->reveal($order, $this->actor('merchant')); + } + public function test_pending_orders_cannot_export_license_keys(): void { $order = app(LicenseOrderService::class)->place( From 4a87faa2f1ab1ec5cf6f953e9a76dff995c02456 Mon Sep 17 00:00:00 2001 From: mstfkhazaal <47450090+mstfkhazaal@users.noreply.github.com> Date: Thu, 29 Oct 2026 10:27:24 +0200 Subject: [PATCH 44/45] docs(resellers): define wholesale license business model, entitlement lifecycle, security and Fenix host integration --- Changelog.md | 10 +++++ README.md | 5 +++ docs/INSTALLATION.md | 7 ++++ docs/LICENSING-RESELLERS.md | 83 +++++++++++++++++++++++++++++++++++++ docs/PROGRESS.md | 16 +++++++ 5 files changed, 121 insertions(+) create mode 100644 docs/LICENSING-RESELLERS.md diff --git a/Changelog.md b/Changelog.md index ffce2ad..ccba954 100644 --- a/Changelog.md +++ b/Changelog.md @@ -29,3 +29,13 @@ Existing apps that relied on permissive missing-Spatie access will be denied unt - Added `SubscriptionAdministration::cancel($billable, $actor, $subscriptionName, $immediately)` to cancel a named subscription after Laravel Gate and tenant-policy validation, with DB transaction/lock and cross-organization isolation tests. - Latest CI tested **23 PHPUnit tests / 44 assertions** and scoped Pint + Composer audit ([run 40839099089](https://github.com/fnx-software/subbase/actions/runs/40839099089)). - Cancellation does not trigger a refund; payment provider refund workflows remain separate and unimplemented. + +## 2026-10-29 — Wholesale license keys and provider reseller program + +- Added app-SKU-based license catalog with retail/wholesale pricing, MOQ and immutable plan/SKU/term snapshots per order. +- Added Provider application, review/approval/suspension, server-priced orders, single-use encrypted random keys, redemption and subscription activation. +- Added independently declared reseller sales, per-currency gross margin dashboard, restricted key export and optional host tenant checks. +- Registered Filament 5 resources for catalog, offers, provider decisions, paid orders and masked inventory. +- Added 12-key CRM reseller, annual redemption, duplicate token, price change and tenant isolation test coverage. +- Payment gateway verification and protected routes are part of the coordinated `fnx-software/subbase-payment` PR #2. +- **No live merchant settlement certification; feature remains Draft.** diff --git a/README.md b/README.md index fde0232..4779623 100644 --- a/README.md +++ b/README.md @@ -371,3 +371,8 @@ The MIT License (MIT). Please see [License File](LICENSE) for more information. - Built with [Filament](https://filamentphp.com) - Powered by [laravelcm/laravel-subscriptions](https://github.com/laravelcm/laravel-subscriptions) - Internationalization by [Spatie Laravel Translatable](https://github.com/spatie/laravel-translatable) + + +### License keys and reseller/provider channel + +The FNX feature branch now contains [License Key & Provider documentation](docs/LICENSING-RESELLERS.md): sell app-specific plans with separate retail and wholesale prices, approve a business reseller, issue encrypted single-use keys only after cleared payment, and allow independent resale with gross-margin reporting. A customer activates their plan when a key is redeemed, not when the reseller bought it. See [development progress](docs/PROGRESS.md). **This is not a production-ready payment release.** diff --git a/docs/INSTALLATION.md b/docs/INSTALLATION.md index 42f1a77..63a7b51 100644 --- a/docs/INSTALLATION.md +++ b/docs/INSTALLATION.md @@ -96,3 +96,10 @@ app(SubscriptionAdministration::class)->cancel( ``` By design, this does **not** initiate a gateway refund or modify historical payment records. Use Subbase Payment's eventual verified refund workflow for that separately. Do not bypass the Gate in host controllers or jobs. + + +## 8. Optional licensed-app reseller channel + +After installing the Subbase package, run its additive `subbase:upgrade --migrations` to publish the new licensing migrations, **inspect timestamps and run only on a backed-up staging database**. The authenticated retail/wholesale/purchase/activation endpoints are provided by the companion `fnx-software/subbase-payment` package. Provide the required platform-level Gates and company/user billable resolver in your application (Fenix Accounts/ZITADEL is an optional host integration). + +See [License Key & Provider specification](LICENSING-RESELLERS.md) for commerce rules, 12-key CRM example, Filament resources, safe API, required permissions and release blockers. diff --git a/docs/LICENSING-RESELLERS.md b/docs/LICENSING-RESELLERS.md new file mode 100644 index 0000000..092b025 --- /dev/null +++ b/docs/LICENSING-RESELLERS.md @@ -0,0 +1,83 @@ +# License keys & authorized providers — universal reseller specification + +**Status:** Implemented as a development feature on `feat/universal-billing-foundation`. Do **not** use with production payments until the companion package and actual provider sandbox flows have been audited. + +## Commercial example and responsibilities + +Fenix sets `LicenseOffer.retail_price = 150.0000 USD`, `wholesale_price = 100.0000 USD`, `wholesale_minimum = 12`, `term_count = 1`, `term_unit = year`; the offer belongs to `LicenseProduct.sku = crm` and the `crm-individual` Subbase plan. + +An approved electronics-store Provider purchases **12 license keys for 1,200 USD total** and resells to customers at **140 USD each**, independently collecting the customer's payment. The Provider's **gross margin is 40 USD per sold key**, 480 USD if all twelve are sold, before taxes, processing fees, returns, and other business costs. The customer saves 10 USD versus the official 150 USD retail price. The reseller's declaration of resale price is **not proof of receipt or settlement**. + +There are two channels: + +- `retail`: the end buyer pays official retail for **exactly one license key** through the checkout. +- `wholesale`: an approved Provider, whose owning organization/user is the authorized purchaser, buys a quantity at or above the offer's minimum (12 in this example). Wholesale prices and inventory are privileged. + +**No recurring reseller commission or payout** is owed by the platform. Reseller profit is the difference between independent retail proceeds and its paid wholesale acquisition cost. A wholesale purchase does **not** grant CRM access to the reseller organization; the ultimate buyer receives the access on redemption. + +## Database ownership + +Subbase package owns the catalog and licensing business logic. The companion Subbase Payment package owns collection and gateway verification. + +| Table | Responsibility | +|---|---| +| `subbase_license_products` | Named app/product, stable slug (`crm`, `invoice`, `pos`) | +| `subbase_license_offers` | App + plan + currency + retail/wholesale prices + minimum quantity + key lifetime | +| `subbase_license_providers` | Provider application, owning Eloquent model, admin approval/suspension | +| `subbase_license_orders` | Purchase intent, provider/purchaser, channel, currency, quantity, immutable price **and term** snapshots, payment link | +| `subbase_license_keys` | One encrypted 128-bit random token per paid unit, SHA-256 lookup, redemption/owner/plan audit | +| `subbase_license_sales` | Provider's optional, independently reported resale price and sale reference | + +Foreign keys enforce core relations. The order's `contract_product_sku`, `contract_plan_id`, `contract_term_count`, `contract_term_unit` remain fixed even when an administrator updates or discontinues its offer. Historical plan deletion/price changes **must never silently destroy sold entitlements**. + +Migration order: +1. Existing core `laravelcm/laravel-subscriptions` and Subbase migrations. +2. `create_license_catalog_and_providers_table.php`. +3. `create_license_orders_and_keys_table.php`. +4. `add_license_order_contract_snapshots_table.php` (forward-only, backfills original prototype orders). + +The Subbase `subbase:install` and `subbase:upgrade --migrations` commands publish these additively. **Inspect timestamp order, make a verified backup, and test on a clone before migrating any existing app.** + +## Provider lifecycle + +1. An authorized Fenix user logs into the **host's Fenix Accounts/ZITADEL** app and selects an organization; the host supplies its **authorized** Eloquent purchaser via `CheckoutBillableManager`. +2. `POST /subbase-payment/licenses/providers` creates one pending Provider owned by that Eloquent account (an organization or another persisted billable). The host Gate `applyForLicenseProvider` must enforce actual membership. +3. A platform billing administrator reviews the application and approves it through Filament **License Providers**, using `LicenseProviderService::approve`. The `manageLicenseProviders` ability is required. +4. Only an approved Provider with Gate `purchaseWholesaleLicenses` can view wholesale prices and create a quantity-eligible wholesale order. +5. `LicenseOrderService::place` calculates the **server-defined** unit price and amount. Client-supplied prices are ignored. It snapshots plan, currency, prices, reseller and term, with a unique idempotency key. +6. `LicenseCheckoutService` in Subbase Payment starts a gateway checkout. Payment return URLs are not proof of settlement. +7. Only a **verified signed gateway webhook**, with matching currency, transaction, amount and purchase metadata, can fulfill a paid order. A DB transaction issues unique encrypted keys; replay cannot issue another 12. +8. The Provider exports **available** codes through `GET /subbase-payment/licenses/orders/{order}/keys`, protected by Gate `viewPurchasedLicenseKeys`, optional tenant access policy and no-store headers. Never expose full codes via Filament data tables or logs. +9. Provider sells via their own physical store/site/cash/transfer channels; `POST /subbase-payment/licenses/keys/{key}/resale` records the reported resale price for their dashboard, subject to the default retail cap. +10. A customer signs in to Fenix App with an authorized destination organization and redeems `POST /subbase-payment/licenses/redeem`; Gate `redeemLicenseKey` must enforce permission on that destination. The license creates/extends the `license-crm` Subbase subscription for one calendar year **from redemption** (or appends to an existing future period). +11. Duplicate redemption is rejected. The ciphertext is wiped on redemption, the key is marked redeemed, the subscription and redeemer remain auditable. Suspending a Provider does **not** retroactively invalidate legitimate paid customer keys. + +## Services and authorization + +Core services (namespace `Nafiswatsiq\Subbase\Services`): +`LicenseProviderService`, `LicenseOrderService`, `LicenseFulfillmentService`, `LicenseInventoryService`, `LicenseRedemptionService`, `LicenseResaleService`, `LicenseProviderDashboard`. + +The host application **must** define and test these Laravel Gate abilities: +`applyForLicenseProvider` (owner), `manageLicenseProviders` (billing administrator), `purchaseWholesaleLicenses` (Provider), `purchaseRetailLicense` (buyer), `viewPurchasedLicenseKeys` (own paid order), `viewLicenseOrder` (own order), `redeemLicenseKey` (destination org), `recordLicenseResale` (own Provider), `viewLicenseProviderDashboard` (own Provider), `manageLicenseCatalog` and `viewLicenseOrders` (platform administrator). + +Any enabled `subbase.tenancy.enabled` requires an implementation of `Nafiswatsiq\Subbase\Contracts\TenantAccess`; otherwise access fails closed. These Gates and the tenant resolver must check **actual session actor, organization membership, panel and roles**, never merely the supplied `provider_id`, `owner_id` or ID in request JSON. The package does not create or guess your Fenix Account or ZITADEL IDs. + +The trusted method `LicenseFulfillmentService::fulfillPaidOrder` is intentionally **not exposed as a public endpoint**. Calling it directly is only valid from a payment-verification handler or a separately audited admin grant workflow. + +## Filament 5 resources + +Registered in `SubbasePlugin`: License Products, License Offers, License Providers (approve/suspend), License Orders (read-only), License Keys (read-only masked tail/status). Admin resources are gated and tenant-scoped. Provider storefront and customer authentication UI are **host-specific**; the reusable package exposes API endpoints through the companion Payment package. + +## Security and operational limits + +- Keys are generated using 16 cryptographically random bytes = **128-bit entropy** and stored encrypted. The plaintext cannot be reconstructed from the SHA-256 lookup hash. The `APP_KEY` must be protected; rotation needs a planned re-encryption strategy for unsold keys. +- Enforce HTTPS, CSRF protections on web routes, secret masking, rate limits, no plaintext logging/analytics, restricted inventory exports and employee access audits. Keys are bearer credentials until redeemed: anyone possessing an unused key can activate it for an account they control, so protect physical distribution. +- A reseller may report a price lower than wholesale (negative margin) to reflect its real loss. The default MSRP ceiling is configurable (`subbase.licensing.reseller_max_retail_price`) rather than hardcoded. It is not a legal price-fixing recommendation; evaluate applicable resale-price rules and avoid imposing unlawful restrictions. +- The system currently **does not** enforce resale channel customer identity, reissue stolen codes, disputes, chargeback refund/revocation, cancellation of unpaid orphan checkout, statutory invoicing/VAT, geographic restrictions, reseller contract signing, multiple currencies of exchange, or fraud scoring. These need a separate approved implementation. +- Total order and margin values are **per currency**; do not add USD and LBP without a fixed exchange-rate snapshot. +- The buyer must redeem a key in the **same central billing service/database** that issued it. Other Fenix apps query central entitlements through a future integration adapter; installing this package independently in two app databases does **not** synchronize license keys. +- Real paid end-to-end provider sandbox/PG/MySQL integration, tenant/provider authorization, browser UI and compliance approval are release blockers. PRs remain Draft; do not enable live payment credentials. + +## Worked verification + +Unit and integration tests cover 12×100 USD wholesale pricing, order idempotency, key uniqueness/encryption, single redemption, activation from redemption date, extension of an active plan, immutable contract terms, reseller 140 USD price/40 USD gross margin, and fail-closed tenancy. The companion tests the full paid gateway webhook issuance without creating a reseller subscription. diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 1218739..b25a6f3 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -38,3 +38,19 @@ The current `main` branch still uses `nafiswatsiq/subbase` as the Composer packa ## Continuation Read `AGENTS.md`, `docs/PRODUCT-SPEC.md`, `docs/INSTALLATION.md`, `docs/PROGRESS.md`, `docs/BACKLOG.md` and `docs/PRECISION-MIGRATION.md`. Keep PR Draft until financial and tenant gates pass. Update `Changelog.md` for every substantive change. + +## 2026-10-29 — License Key, Bulk Provider & Reseller Marketplace (development only) + +- [x] Add generic app SKU products, Plan-based license offer prices and term duration, official retail and wholesale minimum quantity. +- [x] Provider application/approval/suspension with global billing admin Gates; own-organization wholesale purchases only. +- [x] Retail single license versus wholesale multi-unit server-priced checkout intent and persistent immutable price, SKU, plan and duration snapshots. +- [x] Verified-payment-only issuance: 128-bit random encrypted keys, hash lookup, assigned original order, no duplicate key/replay. +- [x] Redeem one time to a subscription on the buyer's own authorized organization, with entitlement term starting at redemption and extension of existing subscription. +- [x] Provider independent resale declaration, gross margin, per-currency dashboard, restricted key export and tenant fail-closed checks. +- [x] Filament 5 admin for products, offers, providers, orders, masked keys; public routes belong to companion Subbase Payment. +- [x] Added tests for 12×$100 wholesale, $140 resale/$40 gross margin, expiry from activation, no cross-tenant export, immutable historic license term and resource authorization. +- [ ] Real Fenix Accounts/ZITADEL host implementation and application entitlement propagation; not part of generic package core. +- [ ] Refund/chargeback, codes stolen/lost, revocation/reissue, taxes/merchant-of-record and legally validated partner agreements. +- [ ] Gateway sandbox E2E tests, PostgreSQL/MySQL migrations, multi-instance race tests and full legacy Pint baseline. + +For the exact contract, API, release gates and migration order read `docs/LICENSING-RESELLERS.md`. No merge or production release yet. From e84754d34ea8458999198ae896708aa6289f8576 Mon Sep 17 00:00:00 2001 From: mstfkhazaal <47450090+mstfkhazaal@users.noreply.github.com> Date: Thu, 29 Oct 2026 10:29:23 +0200 Subject: [PATCH 45/45] docs: record verified licensing test counts and Draft release gates --- docs/PROGRESS.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index b25a6f3..a50cce4 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -54,3 +54,8 @@ Read `AGENTS.md`, `docs/PRODUCT-SPEC.md`, `docs/INSTALLATION.md`, `docs/PROGRESS - [ ] Gateway sandbox E2E tests, PostgreSQL/MySQL migrations, multi-instance race tests and full legacy Pint baseline. For the exact contract, API, release gates and migration order read `docs/LICENSING-RESELLERS.md`. No merge or production release yet. + +### Latest validated licensing checkpoint + +- [x] 42 PHPUnit tests / 108 assertions passed with Composer validate/update, targeted Pint and Composer audit at [GitHub Actions run 40842273565](https://github.com/fnx-software/subbase/actions/runs/40842273565). This is test-environment verification, **not** provider sandbox or production payment certification. +- [x] Changes and rollout blockers remain tracked in the [Draft PR #2](https://github.com/fnx-software/subbase/pull/2) and the licensing documentation.