diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..829871d --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,29 @@ +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, bcmath + coverage: none + 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 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/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..ccba954 --- /dev/null +++ b/Changelog.md @@ -0,0 +1,41 @@ +# 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. + +## 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. + +### 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. + +## 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 2774742..4779623 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,5 @@ +> **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 # Subbase - Filament Subscription Management Plugin @@ -369,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/composer.json b/composer.json index ca757b3..00c92da 100644 --- a/composer.json +++ b/composer.json @@ -1,32 +1,58 @@ { - "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": "fnx-software/subbase", + "description": "FNX Software universal subscription management for Laravel and Filament", + "type": "library", + "license": "MIT", + "keywords": [ + "filament", + "subscription", + "laravel", + "saas", + "billing", + "multi-currency" + ], + "homepage": "https://github.com/fnx-software/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", + "ext-bcmath": "*" + }, + "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" + }, + "support": { + "source": "https://github.com/fnx-software/subbase", + "issues": "https://github.com/fnx-software/subbase/pulls" } - ], - "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/config/subbase.php b/config/subbase.php index 07c2e08..2da673e 100644 --- a/config/subbase.php +++ b/config/subbase.php @@ -22,6 +22,30 @@ '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' => [], + + // 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], + + // 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/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/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/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/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. diff --git a/docs/INSTALLATION.md b/docs/INSTALLATION.md new file mode 100644 index 0000000..63a7b51 --- /dev/null +++ b/docs/INSTALLATION.md @@ -0,0 +1,105 @@ +# 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. + +## 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. + + +## 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/PRECISION-MIGRATION.md b/docs/PRECISION-MIGRATION.md new file mode 100644 index 0000000..7fe0499 --- /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**. 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. + +**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/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..a50cce4 --- /dev/null +++ b/docs/PROGRESS.md @@ -0,0 +1,61 @@ +# FNX Subbase — verified development progress + +Updated: 2026-10-29. **Draft PR**: https://github.com/fnx-software/subbase/pull/2 + +## Architecture decision + +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. + +## Implemented on feat/universal-billing-foundation + +- [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] `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/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 + +- [ ] 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. + +## Distribution warning + +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. + +## 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. + +### 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. 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..fb9e613 --- /dev/null +++ b/docs/UNIVERSAL-BILLING.md @@ -0,0 +1,57 @@ +# 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. + +### 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. 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/Console/Commands/SubbaseUpgradeCommand.php b/src/Console/Commands/SubbaseUpgradeCommand.php index 667de68..025d3e3 100644 --- a/src/Console/Commands/SubbaseUpgradeCommand.php +++ b/src/Console/Commands/SubbaseUpgradeCommand.php @@ -84,6 +84,10 @@ 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', + 'add_license_order_contract_snapshots_table.php', ]; $published = 0; 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 @@ +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/LicenseKeys/LicenseKeyResource.php b/src/Filament/Resources/LicenseKeys/LicenseKeyResource.php new file mode 100644 index 0000000..cfab2d3 --- /dev/null +++ b/src/Filament/Resources/LicenseKeys/LicenseKeyResource.php @@ -0,0 +1,75 @@ +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..c7c0360 --- /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..4d796f3 --- /dev/null +++ b/src/Filament/Resources/LicenseOrders/LicenseOrderResource.php @@ -0,0 +1,79 @@ +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..fb5db85 --- /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..63be035 --- /dev/null +++ b/src/Filament/Resources/LicenseProviders/LicenseProviderResource.php @@ -0,0 +1,68 @@ + 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/Filament/Resources/Plans/PlanResource.php b/src/Filament/Resources/Plans/PlanResource.php index 814b878..4d6d2f8 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..7506f4d 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/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/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/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..2836d1e --- /dev/null +++ b/src/Models/LicenseOffer.php @@ -0,0 +1,68 @@ + 'decimal:4', + 'wholesale_price' => 'decimal:4', + 'wholesale_minimum' => 'integer', + 'term_count' => 'integer', + 'is_active' => 'boolean', + ]; + } + + 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'); + } + + 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..df5ffc4 --- /dev/null +++ b/src/Models/LicenseOrder.php @@ -0,0 +1,57 @@ + 'integer', + 'contract_term_count' => '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..f10bec4 --- /dev/null +++ b/src/Models/LicenseProduct.php @@ -0,0 +1,40 @@ + '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'); + } + + 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/Models/Plan.php b/src/Models/Plan.php index 6f1ccd5..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', ]; @@ -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); @@ -134,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(); @@ -151,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; } @@ -160,7 +186,7 @@ public function syncBasePriceFromCurrency(?string $currency = null): self $this->currency = $targetCurrency; } - $this->price = (float) $prices[$targetCurrency]; + $this->price = $prices[$targetCurrency]; return $this; } @@ -177,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; } @@ -189,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 @@ -197,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; @@ -264,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); @@ -370,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); diff --git a/src/Policies/DiscountPolicy.php b/src/Policies/DiscountPolicy.php index 6f0023c..c852baf 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, $discount); } 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, $discount); } 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, $discount); } 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, $discount); } 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, $discount); } 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, $discount); } 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..542b1d6 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, $plan); } 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, $plan); } 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, $plan); } 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, $plan); } 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, $plan); } 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, $plan); } 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..e15dad9 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, $subscription); } 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, $subscription); } 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, $subscription); } 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, $subscription); } 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, $subscription); } 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, $subscription); } 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/Services/LicenseFulfillmentService.php b/src/Services/LicenseFulfillmentService.php new file mode 100644 index 0000000..0ab7405 --- /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 (! in_array($locked->status, ['pending', 'awaiting_payment'], true) || $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..fb0bb10 --- /dev/null +++ b/src/Services/LicenseInventoryService.php @@ -0,0 +1,44 @@ + + */ + public function reveal(LicenseOrder $order, Authenticatable $actor): array + { + $order = LicenseOrder::query()->findOrFail($order->getKey()); + + if (! SubbaseTenancy::allows($order, 'viewLicenseKeys', $actor) + || ! 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..b412de4 --- /dev/null +++ b/src/Services/LicenseOrderService.php @@ -0,0 +1,131 @@ +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.'); + } + + 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) { + throw new InvalidArgumentException('License quantity is outside allowed limits.'); + } + + if ($isWholesale) { + 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 + ) { + 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', + '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(), + 'unit_price' => $unit->amount(), + 'total_amount' => $total->amount(), + 'status' => 'pending', + 'idempotency_key' => $idempotencyKey, + ]); + }, 3); + } +} diff --git a/src/Services/LicenseProviderDashboard.php b/src/Services/LicenseProviderDashboard.php new file mode 100644 index 0000000..297d821 --- /dev/null +++ b/src/Services/LicenseProviderDashboard.php @@ -0,0 +1,77 @@ +, currencies: array>} + */ + public function summary(LicenseProvider $provider, Authenticatable $actor): array + { + if (! SubbaseTenancy::allows($provider, 'view', $actor) + || ! 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/src/Services/LicenseProviderService.php b/src/Services/LicenseProviderService.php new file mode 100644 index 0000000..c15f3e4 --- /dev/null +++ b/src/Services/LicenseProviderService.php @@ -0,0 +1,78 @@ +exists || $owner->getKey() === null + || $businessName === '' || mb_strlen($businessName) > 150 + ) { + throw new InvalidArgumentException('Provider owner and business name are required.'); + } + + if (! SubbaseTenancy::allows($owner, 'applyForLicenseProvider', $actor) + || ! 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 (! SubbaseTenancy::allows($provider, 'update', $admin) + || ! 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..8d429c9 --- /dev/null +++ b/src/Services/LicenseRedemptionService.php @@ -0,0 +1,118 @@ +exists || $billable->getKey() === null + || ! method_exists($billable, 'planSubscriptions') + || ! method_exists($billable, 'newPlanSubscription') + ) { + throw new InvalidArgumentException('Activation requires a saved, subscribable account.'); + } + + if (! SubbaseTenancy::allows($billable, 'redeemLicenseKey', $actor) + || ! 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 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($order->contract_plan_id); + + $subscriptionName = 'license-'.$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 ($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.'), + }; + + 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..07371f4 --- /dev/null +++ b/src/Services/LicenseResaleService.php @@ -0,0 +1,90 @@ +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, + ]; + }); + } +} diff --git a/src/Services/SubscriptionAdministration.php b/src/Services/SubscriptionAdministration.php new file mode 100644 index 0000000..cf0764a --- /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/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, ]); } diff --git a/src/SubbaseServiceProvider.php b/src/SubbaseServiceProvider.php index 7b55704..b964dea 100644 --- a/src/SubbaseServiceProvider.php +++ b/src/SubbaseServiceProvider.php @@ -48,6 +48,10 @@ 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', + '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/src/Support/Money.php b/src/Support/Money.php new file mode 100644 index 0000000..cd385d5 --- /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/src/Support/SubbasePermission.php b/src/Support/SubbasePermission.php index 108d151..6577dd2 100644 --- a/src/Support/SubbasePermission.php +++ b/src/Support/SubbasePermission.php @@ -4,47 +4,44 @@ namespace Nafiswatsiq\Subbase\Support; +use Illuminate\Contracts\Auth\Authenticatable; +use Illuminate\Database\Eloquent\Model; 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, + ?Model $record = 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 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..c57920c --- /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/Authorization/SubbasePermissionTest.php b/tests/Authorization/SubbasePermissionTest.php new file mode 100644 index 0000000..6bd544b --- /dev/null +++ b/tests/Authorization/SubbasePermissionTest.php @@ -0,0 +1,52 @@ +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'); + + $user = new User; + $user->name = 'other'; + + $this->assertFalse(SubbasePermission::allows(null, 'viewAny', Plan::class, $user)); + } +} 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()); + } +} diff --git a/tests/Licensing/LicenseRedemptionTest.php b/tests/Licensing/LicenseRedemptionTest.php new file mode 100644 index 0000000..117a1c5 --- /dev/null +++ b/tests/Licensing/LicenseRedemptionTest.php @@ -0,0 +1,101 @@ +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_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); + 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(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..ad6fd82 --- /dev/null +++ b/tests/Licensing/LicenseTestCase.php @@ -0,0 +1,171 @@ + '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', + 'add_license_order_contract_snapshots_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, 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(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..e14e85e --- /dev/null +++ b/tests/Licensing/LicenseWholesaleTest.php @@ -0,0 +1,185 @@ +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_dashboard_tracks_wholesale_spend_and_declared_reseller_margin_by_currency(): void + { + $provider = $this->reseller(); + $merchant = $this->actor('merchant'); + 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_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( + $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(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); + } +} 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']); + } +} 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()); + } +} 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)); + } +} diff --git a/tests/Subscriptions/SubscriptionAdministrationTest.php b/tests/Subscriptions/SubscriptionAdministrationTest.php new file mode 100644 index 0000000..3de497e --- /dev/null +++ b/tests/Subscriptions/SubscriptionAdministrationTest.php @@ -0,0 +1,124 @@ +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'); + } +} 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)); + } +} 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 @@ +