Beautiful Open-Source Form Builder
Apply AppSumo entitlements to new workspaces (#1161)
Julien Nahum47cce1a287be
diff --git a/api/app/Console/Commands/Billing/BackfillLifetimeLicenseWorkspaceEntitlements.php b/api/app/Console/Commands/Billing/BackfillLifetimeLicenseWorkspaceEntitlements.phpnew file mode 100644index 000000000..13fa18e3c--- /dev/null+++ b/api/app/Console/Commands/Billing/BackfillLifetimeLicenseWorkspaceEntitlements.php@@ -0,0 +1,75 @@+<?php++namespace App\Console\Commands\Billing;++use App\Models\License;+use App\Models\Workspace;+use App\Service\Billing\LifetimeLicenseWorkspaceEntitlements;+use Illuminate\Console\Command;+use Illuminate\Database\Eloquent\Builder;++class BackfillLifetimeLicenseWorkspaceEntitlements extends Command+{+ protected $signature = 'billing:backfill-lifetime-license-workspace-entitlements+ {--apply : Persist the missing overrides. Without this option the command only reports what would change.}+ {--user-id= : Restrict to workspaces where this user is an admin.}+ {--workspace-id= : Restrict to one workspace.}';++ protected $description = 'Apply legacy AppSumo lifetime workspace entitlements to eligible workspaces.';++ public function handle(LifetimeLicenseWorkspaceEntitlements $entitlements): int+ {+ $apply = (bool) $this->option('apply');+ $updated = 0;+ $skipped = 0;++ $query = Workspace::query()+ ->whereHas('owners', function (Builder $query) {+ $query->whereHas('licenses', function (Builder $licenseQuery) {+ $licenseQuery+ ->where('license_provider', 'appsumo')+ ->where('status', License::STATUS_ACTIVE);+ });+ })+ ->with(['users' => function ($query) {+ $query->withPivot('role');+ }])+ ->orderBy('id');++ if ($workspaceId = $this->option('workspace-id')) {+ $query->whereKey($workspaceId);+ }++ if ($userId = $this->option('user-id')) {+ $query->whereHas('owners', fn (Builder $query) => $query->whereKey($userId));+ }++ $query->chunkById(100, function ($workspaces) use ($apply, $entitlements, &$updated, &$skipped) {+ foreach ($workspaces as $workspace) {+ if ($entitlements->isComplete($workspace)) {+ $this->line("skipped workspace={$workspace->id} reason=already_complete");+ $skipped++;+ continue;+ }++ if (!$apply) {+ $this->line("would_update workspace={$workspace->id}");+ $updated++;+ continue;+ }++ if ($entitlements->applyForEligibleWorkspace($workspace)) {+ $this->line("updated workspace={$workspace->id}");+ $updated++;+ } else {+ $this->line("skipped workspace={$workspace->id} reason=no_eligible_owner");+ $skipped++;+ }+ }+ });++ $this->info(($apply ? 'Updated' : 'Would update') . " {$updated} workspace(s). Skipped {$skipped} workspace(s).");++ return self::SUCCESS;+ }+}diff --git a/api/app/Events/Models/UserWorkspaceCreated.php b/api/app/Events/Models/UserWorkspaceCreated.phpnew file mode 100644index 000000000..3fea2e30b--- /dev/null+++ b/api/app/Events/Models/UserWorkspaceCreated.php@@ -0,0 +1,17 @@+<?php++namespace App\Events\Models;++use App\Models\UserWorkspace;+use Illuminate\Foundation\Events\Dispatchable;+use Illuminate\Queue\SerializesModels;++class UserWorkspaceCreated+{+ use Dispatchable;+ use SerializesModels;++ public function __construct(public UserWorkspace $userWorkspace)+ {+ }+}diff --git a/api/app/Http/Controllers/WorkspaceController.php b/api/app/Http/Controllers/WorkspaceController.phpindex 6fd6d0583..f7851c8f0 100644--- a/api/app/Http/Controllers/WorkspaceController.php+++ b/api/app/Http/Controllers/WorkspaceController.php@@ -6,6 +6,8 @@ use App\Http\Requests\Workspace\CustomDomainRequest;use App\Http\Requests\Workspace\CustomCodeSettingsRequest;use App\Http\Requests\Workspace\EmailSettingsRequest;use App\Http\Resources\WorkspaceResource;+use App\Models\User;+use App\Models\UserWorkspace;use App\Models\Workspace;use App\Service\Billing\Feature;use Illuminate\Http\Request;@@ -108,12 +110,14 @@ class WorkspaceController extends Controller'icon' => ($request->emoji) ? $request->emoji : '',]);- // Add relation with user- $user->workspaces()->sync([- $workspace->id => [- 'role' => 'admin',- ],- ], false);+ // Add relation with user. Use the pivot model so workspace entitlement listeners run.+ UserWorkspace::create([+ 'workspace_id' => $workspace->id,+ 'user_id' => $user->id,+ 'role' => User::ROLE_ADMIN,+ ]);++ $workspace->refresh();return $this->success(['message' => 'Workspace created.',diff --git a/api/app/Listeners/Billing/ApplyLifetimeLicenseWorkspaceEntitlements.php b/api/app/Listeners/Billing/ApplyLifetimeLicenseWorkspaceEntitlements.phpnew file mode 100644index 000000000..4141dc24e--- /dev/null+++ b/api/app/Listeners/Billing/ApplyLifetimeLicenseWorkspaceEntitlements.php@@ -0,0 +1,31 @@+<?php++namespace App\Listeners\Billing;++use App\Events\Models\UserWorkspaceCreated;+use App\Models\User;+use App\Service\Billing\LifetimeLicenseWorkspaceEntitlements;++class ApplyLifetimeLicenseWorkspaceEntitlements+{+ public function __construct(+ protected LifetimeLicenseWorkspaceEntitlements $entitlements,+ ) {+ }++ public function handle(UserWorkspaceCreated $event): void+ {+ if ($event->userWorkspace->role !== User::ROLE_ADMIN) {+ return;+ }++ $user = $event->userWorkspace->user;+ $workspace = $event->userWorkspace->workspace;++ if (!$user || !$workspace) {+ return;+ }++ $this->entitlements->applyForUser($workspace, $user);+ }+}diff --git a/api/app/Models/UserWorkspace.php b/api/app/Models/UserWorkspace.phpindex c2fd71d30..4547ff6f5 100644--- a/api/app/Models/UserWorkspace.php+++ b/api/app/Models/UserWorkspace.php@@ -2,6 +2,7 @@namespace App\Models;+use App\Events\Models\UserWorkspaceCreated;use App\Traits\EnsureUserHasWorkspace;use Illuminate\Database\Eloquent\Factories\HasFactory;use Illuminate\Database\Eloquent\Model;@@ -19,6 +20,10 @@ class UserWorkspace extends Model'role',];+ protected $dispatchesEvents = [+ 'created' => UserWorkspaceCreated::class,+ ];+public function user(){return $this->belongsTo(User::class);diff --git a/api/app/Providers/EventServiceProvider.php b/api/app/Providers/EventServiceProvider.phpindex ee93d3662..858f1ce74 100644--- a/api/app/Providers/EventServiceProvider.php+++ b/api/app/Providers/EventServiceProvider.php@@ -11,7 +11,9 @@ use App\Events\Models\FormCreated;use App\Events\Models\FormIntegrationCreated;use App\Events\Models\FormIntegrationSaved;use App\Events\Models\FormIntegrationsEventCreated;+use App\Events\Models\UserWorkspaceCreated;use App\Listeners\Billing\HandleSubscriptionCreated;+use App\Listeners\Billing\ApplyLifetimeLicenseWorkspaceEntitlements;use App\Listeners\Billing\RemoveWorkspaceGuestsIfNeeded;use App\Listeners\Forms\FormCreationConfirmation;use App\Listeners\Forms\FormIntegrationCreatedHandler;@@ -62,7 +64,10 @@ class EventServiceProvider extends ServiceProvider],SubscriptionUpdated::class => [RemoveWorkspaceGuestsIfNeeded::class- ]+ ],+ UserWorkspaceCreated::class => [+ ApplyLifetimeLicenseWorkspaceEntitlements::class,+ ],];/**diff --git a/api/app/Service/Billing/LifetimeLicenseWorkspaceEntitlements.php b/api/app/Service/Billing/LifetimeLicenseWorkspaceEntitlements.phpnew file mode 100644index 000000000..7ae4d63ee--- /dev/null+++ b/api/app/Service/Billing/LifetimeLicenseWorkspaceEntitlements.php@@ -0,0 +1,110 @@+<?php++namespace App\Service\Billing;++use App\Models\License;+use App\Models\User;+use App\Models\Workspace;+use Illuminate\Database\Eloquent\Builder;++class LifetimeLicenseWorkspaceEntitlements+{+ public const SOURCE_LIFETIME_LICENSE = 'lifetime_license';++ public const MARKER_KEY = 'legacy_pro_grandfathering';++ private const LEGACY_PRO_FEATURES = [+ 'branding.advanced',+ 'multi_user.roles',+ 'partial_submissions',+ 'enable_partial_submissions',+ 'database_fields_update',+ 'enable_ip_tracking',+ 'custom_code',+ 'custom_css',+ 'seo_meta',+ 'sso.oidc',+ ];++ public function features(): array+ {+ return self::LEGACY_PRO_FEATURES;+ }++ public function applyForUser(Workspace $workspace, User $user): bool+ {+ $license = $user->activeLicense();+ if (!$license || $license->license_provider !== 'appsumo') {+ return false;+ }++ return $this->apply($workspace);+ }++ public function applyForEligibleWorkspace(Workspace $workspace): bool+ {+ $admin = $workspace->owners()+ ->whereHas('licenses', function (Builder $query) {+ $query+ ->where('license_provider', 'appsumo')+ ->where('status', License::STATUS_ACTIVE);+ })+ ->first();++ if (!$admin) {+ return false;+ }++ return $this->apply($workspace);+ }++ public function isComplete(Workspace $workspace): bool+ {+ $features = $this->normalizeStringList($workspace->plan_overrides['features'] ?? []);++ return array_diff($this->features(), $features) === [];+ }++ private function apply(Workspace $workspace): bool+ {+ $overrides = is_array($workspace->plan_overrides) ? $workspace->plan_overrides : [];+ $features = $this->normalizeStringList($overrides['features'] ?? []);+ $featuresToAdd = array_values(array_diff($this->features(), $features));++ if ($featuresToAdd === [] && is_array($overrides[self::MARKER_KEY] ?? null)) {+ return false;+ }++ $marker = is_array($overrides[self::MARKER_KEY] ?? null)+ ? $overrides[self::MARKER_KEY]+ : [];++ $overrides['features'] = array_values(array_unique(array_merge($features, $featuresToAdd)));+ $overrides[self::MARKER_KEY] = [+ 'source' => self::SOURCE_LIFETIME_LICENSE,+ 'subscription_id' => null,+ 'features' => array_values(array_unique(array_merge(+ $this->normalizeStringList($marker['features'] ?? []),+ $this->features(),+ ))),+ ];++ $workspace->forceFill([+ 'plan_overrides' => $overrides,+ 'plan_overrides_subscription_id' => null,+ ])->save();++ $workspace->flushWithOwners();++ return true;+ }++ private function normalizeStringList(mixed $value): array+ {+ if (!is_array($value)) {+ return [];+ }++ return array_values(array_unique(array_filter($value, 'is_string')));+ }+}diff --git a/api/tests/Feature/Billing/LifetimeLicenseWorkspaceEntitlementsTest.php b/api/tests/Feature/Billing/LifetimeLicenseWorkspaceEntitlementsTest.phpnew file mode 100644index 000000000..aaba34413--- /dev/null+++ b/api/tests/Feature/Billing/LifetimeLicenseWorkspaceEntitlementsTest.php@@ -0,0 +1,82 @@+<?php++use App\Models\Workspace;+use App\Service\Billing\Feature;+use App\Service\Billing\LifetimeLicenseWorkspaceEntitlements;+use App\Service\Billing\PlanAccessService;+use App\Service\Billing\PlanTier;++it('applies legacy AppSumo entitlements when a licensed user creates a workspace', function () {+ $user = $this->createAppSumoLicensedUser(tier: 3);+ $this->actingAsUser($user);++ $response = $this->postJson(route('open.workspaces.create'), [+ 'name' => 'Market',+ 'icon' => 'M',+ ])->assertSuccessful();++ $workspace = Workspace::findOrFail($response->json('workspace_id'));+ $features = app(LifetimeLicenseWorkspaceEntitlements::class)->features();++ expect($workspace->plan_overrides['features'])->toEqualCanonicalizing($features)+ ->and($workspace->plan_overrides['legacy_pro_grandfathering']['source'])->toBe('lifetime_license')+ ->and($workspace->plan_overrides_subscription_id)->toBeNull()+ ->and(app(PlanAccessService::class)->getTier($workspace))->toBe(PlanTier::PRO)+ ->and(app(PlanAccessService::class)->hasFeature($workspace, Feature::CUSTOM_CODE))->toBeTrue()+ ->and($response->json('workspace.features'))->toContain(Feature::CUSTOM_CODE, Feature::SSO_OIDC);+});++it('does not apply legacy entitlements for regular users creating a workspace', function () {+ $user = $this->actingAsProUser();++ $response = $this->postJson(route('open.workspaces.create'), [+ 'name' => 'Regular Workspace',+ 'icon' => 'R',+ ])->assertSuccessful();++ $workspace = Workspace::findOrFail($response->json('workspace_id'));++ expect($workspace->plan_overrides)->toBeNull();+});++it('merges AppSumo legacy entitlements with existing workspace overrides', function () {+ $user = $this->createAppSumoLicensedUser(tier: 3);+ $workspace = $this->createUserWorkspace($user);+ $workspace->update([+ 'plan_overrides' => [+ 'features' => [Feature::FORM_VERSIONING],+ 'limits' => ['custom_domain_count' => 50],+ ],+ ]);++ app(LifetimeLicenseWorkspaceEntitlements::class)->applyForUser($workspace->fresh(), $user);++ $workspace = $workspace->fresh();++ expect($workspace->plan_overrides['features'])+ ->toContain(Feature::FORM_VERSIONING, Feature::CUSTOM_CODE, Feature::SSO_OIDC)+ ->and($workspace->plan_overrides['limits']['custom_domain_count'])->toBe(50);+});++it('backfills missing AppSumo lifetime workspace entitlements only when applied', function () {+ $user = $this->createAppSumoLicensedUser(tier: 3);+ $workspace = $this->createUserWorkspace($user);++ $this->artisan('billing:backfill-lifetime-license-workspace-entitlements', [+ '--workspace-id' => $workspace->id,+ ])+ ->expectsOutput("would_update workspace={$workspace->id}")+ ->assertSuccessful();++ expect($workspace->fresh()->plan_overrides)->toBeNull();++ $this->artisan('billing:backfill-lifetime-license-workspace-entitlements', [+ '--workspace-id' => $workspace->id,+ '--apply' => true,+ ])+ ->expectsOutput("updated workspace={$workspace->id}")+ ->assertSuccessful();++ expect($workspace->fresh()->plan_overrides['features'])+ ->toContain(Feature::CUSTOM_CODE, Feature::SSO_OIDC);+});