Beautiful Open-Source Form Builder
Apply extra pro workspace entitlements (#1212)
Julien Nahum333657aa197c
diff --git a/api/app/Console/Commands/Billing/BackfillLifetimeLicenseWorkspaceEntitlements.php b/api/app/Console/Commands/Billing/BackfillLifetimeLicenseWorkspaceEntitlements.phpindex 13fa18e3c..7b9d2f178 100644--- a/api/app/Console/Commands/Billing/BackfillLifetimeLicenseWorkspaceEntitlements.php+++ b/api/app/Console/Commands/Billing/BackfillLifetimeLicenseWorkspaceEntitlements.php@@ -15,7 +15,7 @@ class BackfillLifetimeLicenseWorkspaceEntitlements extends Command{--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.';+ protected $description = 'Apply legacy lifetime and extra-pro workspace entitlements to eligible workspaces.';public function handle(LifetimeLicenseWorkspaceEntitlements $entitlements): int{@@ -23,13 +23,19 @@ class BackfillLifetimeLicenseWorkspaceEntitlements extends Command$updated = 0;$skipped = 0;+ $extraProEmails = $entitlements->extraProEmails();+$query = Workspace::query()- ->whereHas('owners', function (Builder $query) {+ ->whereHas('owners', function (Builder $query) use ($extraProEmails) {$query->whereHas('licenses', function (Builder $licenseQuery) {$licenseQuery->where('license_provider', 'appsumo')->where('status', License::STATUS_ACTIVE);});++ if ($extraProEmails !== []) {+ $query->orWhereIn('email', $extraProEmails);+ }})->with(['users' => function ($query) {$query->withPivot('role');diff --git a/api/app/Http/Controllers/Auth/RegisterController.php b/api/app/Http/Controllers/Auth/RegisterController.phpindex 6839f415b..576830a3d 100644--- a/api/app/Http/Controllers/Auth/RegisterController.php+++ b/api/app/Http/Controllers/Auth/RegisterController.php@@ -5,12 +5,14 @@ namespace App\Http\Controllers\Auth;use App\Http\Controllers\Controller;use App\Http\Resources\UserResource;use App\Models\User;+use App\Models\UserWorkspace;use App\Service\License\SelfHostedSeatLimitService;use App\Service\WorkspaceInviteService;use Illuminate\Contracts\Auth\MustVerifyEmail;use Illuminate\Foundation\Auth\RegistersUsers;use Illuminate\Http\Request;use Illuminate\Support\Facades\Auth;+use Illuminate\Support\Facades\DB;use Illuminate\Support\Facades\Validator;use Illuminate\Validation\Rule;use App\Rules\ValidReCaptcha;@@ -114,25 +116,29 @@ class RegisterController extends Controllerapp(SelfHostedSeatLimitService::class)->assertCanCreateUser($data['email']);}- [$workspace, $role] = app(WorkspaceInviteService::class)->getWorkspaceAndRole($data);+ $user = DB::transaction(function () use ($data) {+ [$workspace, $role] = app(WorkspaceInviteService::class)->getWorkspaceAndRole($data);- $user = User::create([- 'name' => $data['name'],- 'email' => strtolower($data['email']),- 'password' => bcrypt($data['password']),- 'hear_about_us' => $data['hear_about_us'],- 'utm_data' => array_key_exists('utm_data', $data) ? $data['utm_data'] : null,- 'meta' => ['registration_ip' => request()->ip()],- ]);+ $user = User::create([+ 'name' => $data['name'],+ 'email' => strtolower($data['email']),+ 'password' => bcrypt($data['password']),+ 'hear_about_us' => $data['hear_about_us'],+ 'utm_data' => array_key_exists('utm_data', $data) ? $data['utm_data'] : null,+ 'meta' => ['registration_ip' => request()->ip()],+ ]);++ $this->appsumoLicense = AppSumoAuthController::registerWithLicense($user, $data['appsumo_license'] ?? null);- // Add relation with user- $user->workspaces()->sync([- $workspace->id => [+ // Use the pivot model so workspace entitlement listeners run.+ UserWorkspace::create([+ 'workspace_id' => $workspace->id,+ 'user_id' => $user->id,'role' => $role,- ],- ], false);+ ]);- $this->appsumoLicense = AppSumoAuthController::registerWithLicense($user, $data['appsumo_license'] ?? null);+ return $user;+ });// Clear feature flags cache when first user is created (affects setup_required flag)if (config('app.self_hosted') && $user->id === 1) {diff --git a/api/app/Service/Billing/LifetimeLicenseWorkspaceEntitlements.php b/api/app/Service/Billing/LifetimeLicenseWorkspaceEntitlements.phpindex 7ae4d63ee..53b42eec8 100644--- a/api/app/Service/Billing/LifetimeLicenseWorkspaceEntitlements.php+++ b/api/app/Service/Billing/LifetimeLicenseWorkspaceEntitlements.php@@ -11,6 +11,8 @@ class LifetimeLicenseWorkspaceEntitlements{public const SOURCE_LIFETIME_LICENSE = 'lifetime_license';+ public const SOURCE_EXTRA_PRO_USER = 'extra_pro_user';+public const MARKER_KEY = 'legacy_pro_grandfathering';private const LEGACY_PRO_FEATURES = [@@ -33,21 +35,43 @@ class LifetimeLicenseWorkspaceEntitlementspublic function applyForUser(Workspace $workspace, User $user): bool{- $license = $user->activeLicense();- if (!$license || $license->license_provider !== 'appsumo') {+ $source = $this->sourceForUser($user);+ if (!$source) {return false;}- return $this->apply($workspace);+ return $this->apply($workspace, $source);+ }++ public function sourceForUser(User $user): ?string+ {+ $license = $user->activeLicense();+ if ($license && $license->license_provider === 'appsumo') {+ return self::SOURCE_LIFETIME_LICENSE;+ }++ if ($this->isExtraProUser($user)) {+ return self::SOURCE_EXTRA_PRO_USER;+ }++ return null;}public function applyForEligibleWorkspace(Workspace $workspace): bool{+ $extraProEmails = $this->extraProEmails();+$admin = $workspace->owners()- ->whereHas('licenses', function (Builder $query) {- $query- ->where('license_provider', 'appsumo')- ->where('status', License::STATUS_ACTIVE);+ ->where(function (Builder $query) use ($extraProEmails) {+ $query->whereHas('licenses', function (Builder $licenseQuery) {+ $licenseQuery+ ->where('license_provider', 'appsumo')+ ->where('status', License::STATUS_ACTIVE);+ });++ if ($extraProEmails !== []) {+ $query->orWhereIn('email', $extraProEmails);+ }})->first();@@ -55,7 +79,7 @@ class LifetimeLicenseWorkspaceEntitlementsreturn false;}- return $this->apply($workspace);+ return $this->applyForUser($workspace, $admin);}public function isComplete(Workspace $workspace): bool@@ -65,7 +89,15 @@ class LifetimeLicenseWorkspaceEntitlementsreturn array_diff($this->features(), $features) === [];}- private function apply(Workspace $workspace): bool+ public function extraProEmails(): array+ {+ return array_values(array_unique(array_filter(array_map(+ fn (mixed $email) => is_string($email) ? strtolower(trim($email)) : '',+ (array) config('opnform.extra_pro_users_emails', []),+ ))));+ }++ private function apply(Workspace $workspace, string $source): bool{$overrides = is_array($workspace->plan_overrides) ? $workspace->plan_overrides : [];$features = $this->normalizeStringList($overrides['features'] ?? []);@@ -81,7 +113,7 @@ class LifetimeLicenseWorkspaceEntitlements$overrides['features'] = array_values(array_unique(array_merge($features, $featuresToAdd)));$overrides[self::MARKER_KEY] = [- 'source' => self::SOURCE_LIFETIME_LICENSE,+ 'source' => $source,'subscription_id' => null,'features' => array_values(array_unique(array_merge($this->normalizeStringList($marker['features'] ?? []),@@ -99,6 +131,11 @@ class LifetimeLicenseWorkspaceEntitlementsreturn true;}+ private function isExtraProUser(User $user): bool+ {+ return in_array(strtolower($user->email), $this->extraProEmails(), true);+ }+private function normalizeStringList(mixed $value): array{if (!is_array($value)) {diff --git a/api/app/Service/OAuth/OAuthUserService.php b/api/app/Service/OAuth/OAuthUserService.phpindex 460d989da..527a914fa 100644--- a/api/app/Service/OAuth/OAuthUserService.php+++ b/api/app/Service/OAuth/OAuthUserService.php@@ -4,6 +4,7 @@ namespace App\Service\OAuth;use App\Integrations\OAuth\OAuthProviderService;use App\Models\User;+use App\Models\UserWorkspace;use App\Enterprise\Oidc\ExternalUserFactory;use App\Service\WorkspaceInviteService;use Illuminate\Http\Exceptions\HttpResponseException;@@ -92,11 +93,11 @@ class OAuthUserService'invite_token' => $inviteToken]);- $user->workspaces()->sync([- $workspace->id => [- 'role' => $role,- ],- ], false);+ UserWorkspace::create([+ 'workspace_id' => $workspace->id,+ 'user_id' => $user->id,+ 'role' => $role,+ ]);$user->new_user = true;diff --git a/api/app/Traits/EnsureUserHasWorkspace.php b/api/app/Traits/EnsureUserHasWorkspace.phpindex 32f907729..361b1a749 100644--- a/api/app/Traits/EnsureUserHasWorkspace.php+++ b/api/app/Traits/EnsureUserHasWorkspace.php@@ -3,6 +3,7 @@namespace App\Traits;use App\Models\User;+use App\Models\UserWorkspace;use App\Models\Workspace;use Illuminate\Support\Facades\Log;@@ -24,11 +25,11 @@ trait EnsureUserHasWorkspace'name' => 'My Workspace',]);- $user->workspaces()->sync([- $newWorkspace->id => [- 'role' => 'admin',- ],- ], false);+ UserWorkspace::create([+ 'workspace_id' => $newWorkspace->id,+ 'user_id' => $user->id,+ 'role' => User::ROLE_ADMIN,+ ]);}}}diff --git a/api/tests/Feature/Billing/LifetimeLicenseWorkspaceEntitlementsTest.php b/api/tests/Feature/Billing/LifetimeLicenseWorkspaceEntitlementsTest.phpindex aaba34413..dd1b3277b 100644--- a/api/tests/Feature/Billing/LifetimeLicenseWorkspaceEntitlementsTest.php+++ b/api/tests/Feature/Billing/LifetimeLicenseWorkspaceEntitlementsTest.php@@ -26,6 +26,25 @@ it('applies legacy AppSumo entitlements when a licensed user creates a workspace->and($response->json('workspace.features'))->toContain(Feature::CUSTOM_CODE, Feature::SSO_OIDC);});+it('applies legacy entitlements when an extra pro user creates a workspace', function () {+ $user = $this->createUser(['email' => '[email protected]']);+ config(['opnform.extra_pro_users_emails' => [$user->email]]);+ $this->actingAsUser($user);++ $response = $this->postJson(route('open.workspaces.create'), [+ 'name' => 'Embedded Product',+ 'icon' => 'E',+ ])->assertSuccessful();++ $workspace = Workspace::findOrFail($response->json('workspace_id'));++ expect($workspace->plan_overrides['features'])+ ->toContain(Feature::CUSTOM_CODE, Feature::SSO_OIDC)+ ->and($workspace->plan_overrides['legacy_pro_grandfathering']['source'])->toBe('extra_pro_user')+ ->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();@@ -80,3 +99,30 @@ it('backfills missing AppSumo lifetime workspace entitlements only when applied'expect($workspace->fresh()->plan_overrides['features'])->toContain(Feature::CUSTOM_CODE, Feature::SSO_OIDC);});++it('backfills missing extra pro user workspace entitlements only when applied', function () {+ $user = $this->createUser(['email' => '[email protected]']);+ config(['opnform.extra_pro_users_emails' => [$user->email]]);+ $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();++ $workspace = $workspace->fresh();++ expect($workspace->plan_overrides['features'])+ ->toContain(Feature::CUSTOM_CODE, Feature::SSO_OIDC)+ ->and($workspace->plan_overrides['legacy_pro_grandfathering']['source'])->toBe('extra_pro_user');+});diff --git a/api/tests/Feature/RegisterTest.php b/api/tests/Feature/RegisterTest.phpindex 9aad24b22..a0190c4d3 100644--- a/api/tests/Feature/RegisterTest.php+++ b/api/tests/Feature/RegisterTest.php@@ -1,7 +1,9 @@<?phpuse App\Models\User;+use App\Models\Workspace;use App\Rules\ValidReCaptcha;+use Illuminate\Contracts\Encryption\DecryptException;use Illuminate\Support\Facades\Http;it('can register', function () {@@ -52,6 +54,25 @@ it('cannot register with existing email', function () {->assertJsonValidationErrors(['email']);});+it('rolls back registration when the AppSumo license token is invalid', function () {+ $workspaceCount = Workspace::count();++ $this->withoutExceptionHandling();++ expect(fn () => $this->postJson('/register', [+ 'name' => 'Test User',+ 'email' => '[email protected]',+ 'hear_about_us' => 'google',+ 'password' => 'Abcd@1234',+ 'password_confirmation' => 'Abcd@1234',+ 'agree_terms' => true,+ 'appsumo_license' => 'invalid-license-token',+ ]))->toThrow(DecryptException::class);++ expect(User::where('email', '[email protected]')->exists())->toBeFalse()+ ->and(Workspace::count())->toBe($workspaceCount);+});+it('blocks registering a third user on a free self-hosted instance', function () {config(['app.self_hosted' => true]);config(['cashier.key' => null]);