Skip to content

Open-source social media scheduler built for AI agents and the teams behind them. Create, schedule and publish posts to every network through MCP or the REST API, or write them yourself in a composer your team will love.

feat: move Billable from User to Workspace with plan support

Paulo Castellano1ff2f93c37c8
diff --git a/app/Actions/Workspace/CreateWorkspace.php b/app/Actions/Workspace/CreateWorkspace.php
index 1bf6f4401..9fe381318 100644
--- a/app/Actions/Workspace/CreateWorkspace.php
+++ b/app/Actions/Workspace/CreateWorkspace.php
@@ -21,10 +21,6 @@ class CreateWorkspace
$workspace->members()->attach($user->id, ['role' => Role::Owner->value]);
$user->switchWorkspace($workspace);
- if ($user->hasActiveSubscription()) {
- $user->incrementWorkspaceQuantity();
- }
-
return $workspace;
}
}
diff --git a/app/Actions/Workspace/DeleteWorkspace.php b/app/Actions/Workspace/DeleteWorkspace.php
index 67f55e377..b9bf224f4 100644
--- a/app/Actions/Workspace/DeleteWorkspace.php
+++ b/app/Actions/Workspace/DeleteWorkspace.php
@@ -14,9 +14,5 @@ class DeleteWorkspace
User::where('current_workspace_id', $workspace->id)->update(['current_workspace_id' => null]);
$workspace->delete();
-
- if ($user->hasActiveSubscription()) {
- $user->decrementWorkspaceQuantity();
- }
}
}
diff --git a/app/Events/SubscriptionCreated.php b/app/Events/SubscriptionCreated.php
index 074778618..3ed17e46f 100644
--- a/app/Events/SubscriptionCreated.php
+++ b/app/Events/SubscriptionCreated.php
@@ -4,7 +4,7 @@ declare(strict_types=1);
namespace App\Events;
-use App\Models\User;
+use App\Models\Workspace;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
@@ -15,12 +15,12 @@ class SubscriptionCreated implements ShouldBroadcastNow
{
use Dispatchable, InteractsWithSockets, SerializesModels;
- public function __construct(public User $user) {}
+ public function __construct(public Workspace $workspace) {}
public function broadcastOn(): array
{
return [
- new PrivateChannel('users.'.$this->user->id),
+ new PrivateChannel('users.'.$this->workspace->user_id),
];
}
diff --git a/app/Http/Controllers/App/BillingController.php b/app/Http/Controllers/App/BillingController.php
index 17520fd3c..d510f1f73 100644
--- a/app/Http/Controllers/App/BillingController.php
+++ b/app/Http/Controllers/App/BillingController.php
@@ -4,7 +4,8 @@ declare(strict_types=1);
namespace App\Http\Controllers\App;
-use App\Models\User;
+use App\Models\Plan;
+use App\Models\Workspace;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
@@ -15,77 +16,55 @@ class BillingController extends Controller
{
public function subscribe(Request $request): Response|RedirectResponse
{
- $user = $request->user();
-
- $this->authorizeBilling($request);
+ $workspace = $request->user()->currentWorkspace;
- if ($user->subscribed(User::SUBSCRIPTION_NAME)) {
+ if ($workspace && $workspace->hasActiveSubscription()) {
return redirect()->route('app.billing.index');
}
return Inertia::render('billing/Subscribe', [
+ 'plans' => Plan::active()->orderBy('sort')->get(),
'trialDays' => config('cashier.trial_days'),
]);
}
- public function index(Request $request): Response|RedirectResponse
+ public function checkout(Request $request, Plan $plan): SymfonyResponse
{
- $this->authorizeBilling($request);
+ $workspace = $request->user()->currentWorkspace;
- $user = $request->user();
- $subscription = $user->subscription(User::SUBSCRIPTION_NAME);
+ $this->authorize('manageBilling', $workspace);
- return Inertia::render('billing/Index', [
- 'hasSubscription' => $user->subscribed(User::SUBSCRIPTION_NAME),
- 'onTrial' => $subscription?->onTrial() ?? false,
- 'trialEndsAt' => $subscription?->trial_ends_at?->toFormattedDateString(),
- 'subscription' => $subscription?->only([
- 'stripe_status',
- 'quantity',
- 'ends_at',
- ]),
- 'workspacesCount' => $user->ownedWorkspacesCount(),
- 'invoices' => $user->invoices()->map(fn ($invoice) => [
- 'id' => $invoice->id,
- 'date' => $invoice->date()->toFormattedDateString(),
- 'total' => $invoice->total(),
- 'status' => $invoice->status,
- 'invoice_pdf' => $invoice->invoice_pdf,
- ]),
- 'defaultPaymentMethod' => $user->defaultPaymentMethod()?->card?->only([
- 'brand',
- 'last4',
- 'exp_month',
- 'exp_year',
- ]),
- ]);
- }
+ $priceId = $request->input('interval', 'monthly') === 'yearly'
+ ? $plan->stripe_yearly_price_id
+ : $plan->stripe_monthly_price_id;
- public function checkout(Request $request): SymfonyResponse
- {
- $this->authorizeBilling($request);
+ abort_if(! $priceId, 422, 'Plan price not configured');
- $user = $request->user();
+ $workspace->createOrGetStripeCustomer([
+ 'email' => $workspace->stripeEmail(),
+ 'name' => $workspace->stripeName(),
+ ]);
- $subscription = $user->newSubscription(User::SUBSCRIPTION_NAME, config('cashier.plans.monthly.price_id'))
+ $subscription = $workspace->newSubscription(Workspace::SUBSCRIPTION_NAME, $priceId)
->allowPromotionCodes()
- ->trialDays(config('cashier.trial_days'))
- ->quantity(1);
+ ->trialDays(config('cashier.trial_days'));
$checkoutSession = $subscription->checkout([
'success_url' => route('app.billing.processing').'?status=success',
'cancel_url' => route('app.billing.processing').'?status=cancelled',
]);
+ $workspace->update(['plan_id' => $plan->id]);
+
return Inertia::location($checkoutSession->url);
}
public function processing(Request $request): Response|RedirectResponse
{
- $user = $request->user();
+ $workspace = $request->user()->currentWorkspace;
$status = $request->query('status', 'processing');
- if ($user->subscribed(User::SUBSCRIPTION_NAME)) {
+ if ($workspace && $workspace->subscribed(Workspace::SUBSCRIPTION_NAME)) {
return redirect()->route('app.calendar');
}
@@ -94,26 +73,73 @@ class BillingController extends Controller
}
return Inertia::render('billing/Processing', [
- 'userId' => $user->id,
+ 'workspaceId' => $workspace?->id,
'status' => $status,
]);
}
- public function portal(Request $request): RedirectResponse
+ public function index(Request $request): Response
{
- $this->authorizeBilling($request);
+ $workspace = $request->user()->currentWorkspace;
- return $request->user()->redirectToBillingPortal(
- route('app.billing.index')
- );
+ $this->authorize('manageBilling', $workspace);
+
+ $subscription = $workspace->subscription(Workspace::SUBSCRIPTION_NAME);
+
+ return Inertia::render('billing/Index', [
+ 'hasSubscription' => $workspace->subscribed(Workspace::SUBSCRIPTION_NAME),
+ 'onTrial' => $subscription?->onTrial() ?? false,
+ 'trialEndsAt' => $subscription?->trial_ends_at?->toFormattedDateString(),
+ 'subscription' => $subscription?->only([
+ 'stripe_status',
+ 'ends_at',
+ ]),
+ 'plan' => $workspace->plan,
+ 'plans' => Plan::active()->orderBy('sort')->get(),
+ 'invoices' => $workspace->invoices()->map(fn ($invoice) => [
+ 'id' => $invoice->id,
+ 'date' => $invoice->date()->toFormattedDateString(),
+ 'total' => $invoice->total(),
+ 'status' => $invoice->status,
+ 'invoice_pdf' => $invoice->invoice_pdf,
+ ]),
+ 'defaultPaymentMethod' => $workspace->defaultPaymentMethod()?->card?->only([
+ 'brand',
+ 'last4',
+ 'exp_month',
+ 'exp_year',
+ ]),
+ ]);
}
- private function authorizeBilling(Request $request): void
+ public function swap(Request $request, Plan $plan): RedirectResponse
{
$workspace = $request->user()->currentWorkspace;
- if ($workspace) {
- $this->authorize('manageBilling', $workspace);
- }
+ $this->authorize('manageBilling', $workspace);
+
+ abort_unless($workspace->subscribed(Workspace::SUBSCRIPTION_NAME), 422, 'No active subscription');
+
+ $priceId = $request->input('interval', 'monthly') === 'yearly'
+ ? $plan->stripe_yearly_price_id
+ : $plan->stripe_monthly_price_id;
+
+ abort_if(! $priceId, 422, 'Plan price not configured');
+
+ $workspace->subscription(Workspace::SUBSCRIPTION_NAME)->swap($priceId);
+ $workspace->update(['plan_id' => $plan->id]);
+
+ return redirect()->route('app.billing.index');
+ }
+
+ public function portal(Request $request): RedirectResponse
+ {
+ $workspace = $request->user()->currentWorkspace;
+
+ $this->authorize('manageBilling', $workspace);
+
+ return $workspace->redirectToBillingPortal(
+ route('app.billing.index')
+ );
}
}
diff --git a/app/Http/Controllers/App/OnboardingController.php b/app/Http/Controllers/App/OnboardingController.php
index 29f619ebe..c4563d0a7 100644
--- a/app/Http/Controllers/App/OnboardingController.php
+++ b/app/Http/Controllers/App/OnboardingController.php
@@ -4,10 +4,13 @@ declare(strict_types=1);
namespace App\Http\Controllers\App;
+use App\Enums\Plan\Slug as PlanSlug;
use App\Enums\SocialAccount\Platform as SocialPlatform;
use App\Enums\User\Persona;
use App\Enums\User\Setup;
+use App\Models\Plan;
use App\Models\User;
+use App\Models\Workspace;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
@@ -76,11 +79,10 @@ class OnboardingController extends Controller
public function storeConnect(Request $request): SymfonyResponse|RedirectResponse
{
$user = $request->user();
+ $workspace = $user->currentWorkspace;
if (config('trypost.self_hosted')) {
- $user->update([
- 'setup' => Setup::Completed,
- ]);
+ $user->update(['setup' => Setup::Completed]);
session()->flash('flash.banner', __('auth.flash.welcome'));
session()->flash('flash.bannerStyle', 'success');
@@ -88,20 +90,26 @@ class OnboardingController extends Controller
return redirect()->route('app.calendar');
}
- $user->update([
- 'setup' => Setup::Subscription,
+ $user->update(['setup' => Setup::Subscription]);
+
+ $defaultPlan = Plan::where('slug', PlanSlug::Starter)->first();
+
+ $workspace->createOrGetStripeCustomer([
+ 'email' => $workspace->stripeEmail(),
+ 'name' => $workspace->stripeName(),
]);
- $subscription = $user->newSubscription(User::SUBSCRIPTION_NAME, config('cashier.plans.monthly.price_id'))
+ $subscription = $workspace->newSubscription(Workspace::SUBSCRIPTION_NAME, $defaultPlan->stripe_monthly_price_id)
->allowPromotionCodes()
- ->trialDays(config('cashier.trial_days'))
- ->quantity(1);
+ ->trialDays(config('cashier.trial_days'));
$checkoutSession = $subscription->checkout([
'success_url' => route('app.onboarding.complete').'?session_id={CHECKOUT_SESSION_ID}',
'cancel_url' => route('app.onboarding.connect'),
]);
+ $workspace->update(['plan_id' => $defaultPlan->id]);
+
return Inertia::location($checkoutSession->url);
}
diff --git a/app/Http/Controllers/App/Settings/ProfileController.php b/app/Http/Controllers/App/Settings/ProfileController.php
index 58d626303..22c6a1cf2 100644
--- a/app/Http/Controllers/App/Settings/ProfileController.php
+++ b/app/Http/Controllers/App/Settings/ProfileController.php
@@ -8,7 +8,7 @@ use App\Enums\UserWorkspace\Role;
use App\Http\Controllers\Controller;
use App\Http\Requests\App\Settings\ProfileDeleteRequest;
use App\Http\Requests\App\Settings\ProfileUpdateRequest;
-use App\Models\User;
+use App\Models\Workspace;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
@@ -91,15 +91,16 @@ class ProfileController extends Controller
$user = $request->user();
DB::transaction(function () use ($user) {
- if ($user->subscribed(User::SUBSCRIPTION_NAME)) {
- $user->subscription(User::SUBSCRIPTION_NAME)->cancelNow();
- }
- $user->subscriptions()->delete();
$user->update(['current_workspace_id' => null]);
$ownedWorkspaces = $user->workspaces()->wherePivot('role', Role::Owner->value)->get();
foreach ($ownedWorkspaces as $workspace) {
+ if ($workspace->subscribed(Workspace::SUBSCRIPTION_NAME)) {
+ $workspace->subscription(Workspace::SUBSCRIPTION_NAME)->cancelNow();
+ }
+ $workspace->subscriptions()->delete();
+
foreach ($workspace->members as $member) {
if ($member->id !== $user->id && $member->current_workspace_id === $workspace->id) {
$otherWorkspace = $member->workspaces()
diff --git a/app/Http/Controllers/App/WorkspaceController.php b/app/Http/Controllers/App/WorkspaceController.php
index a4c437213..29d9169c2 100644
--- a/app/Http/Controllers/App/WorkspaceController.php
+++ b/app/Http/Controllers/App/WorkspaceController.php
@@ -37,7 +37,9 @@ class WorkspaceController extends Controller
{
$user = $request->user();
- if ($user->ownedWorkspacesCount() > 0 && ! $user->hasActiveSubscription()) {
+ $workspace = $user->currentWorkspace;
+
+ if ($user->ownedWorkspacesCount() > 0 && (! $workspace || ! $workspace->hasActiveSubscription())) {
return redirect()->route('app.billing.index')
->with('message', 'Subscribe to create more workspaces.');
}
@@ -49,7 +51,9 @@ class WorkspaceController extends Controller
{
$user = $request->user();
- if ($user->ownedWorkspacesCount() > 0 && ! $user->hasActiveSubscription()) {
+ $workspace = $user->currentWorkspace;
+
+ if ($user->ownedWorkspacesCount() > 0 && (! $workspace || ! $workspace->hasActiveSubscription())) {
return redirect()->route('app.billing.index')
->with('message', 'Subscribe to create more workspaces.');
}
diff --git a/app/Http/Middleware/Api/AuthenticateApiToken.php b/app/Http/Middleware/Api/AuthenticateApiToken.php
index 0f5f71a49..7ec29a68e 100644
--- a/app/Http/Middleware/Api/AuthenticateApiToken.php
+++ b/app/Http/Middleware/Api/AuthenticateApiToken.php
@@ -5,7 +5,6 @@ declare(strict_types=1);
namespace App\Http\Middleware\Api;
use App\Models\ApiToken;
-use App\Models\User;
use App\Models\Workspace;
use Closure;
use Illuminate\Http\Request;
@@ -55,12 +54,6 @@ class AuthenticateApiToken
private function hasActiveSubscription(Workspace $workspace): bool
{
- $owner = $workspace->owner;
-
- if (! $owner) {
- return false;
- }
-
- return $owner->subscribed(User::SUBSCRIPTION_NAME) || $owner->onTrial(User::SUBSCRIPTION_NAME);
+ return $workspace->hasActiveSubscription();
}
}
diff --git a/app/Http/Middleware/App/EnsureSubscribed.php b/app/Http/Middleware/App/EnsureSubscribed.php
index cbe1817ff..0a8896a90 100644
--- a/app/Http/Middleware/App/EnsureSubscribed.php
+++ b/app/Http/Middleware/App/EnsureSubscribed.php
@@ -4,21 +4,14 @@ declare(strict_types=1);
namespace App\Http\Middleware\App;
-use App\Models\User;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class EnsureSubscribed
{
- /**
- * Handle an incoming request.
- *
- * @param Closure(Request): (Response) $next
- */
public function handle(Request $request, Closure $next): Response
{
- // Skip subscription check for self-hosted mode
if (config('trypost.self_hosted')) {
return $next($request);
}
@@ -29,23 +22,12 @@ class EnsureSubscribed
return redirect()->route('login');
}
- // Allow access if user has active subscription or is on trial
- if ($user->subscribed(User::SUBSCRIPTION_NAME) || $user->onTrial(User::SUBSCRIPTION_NAME)) {
- return $next($request);
- }
-
- // Allow access if user belongs to a workspace owned by a subscribed user
- $currentWorkspace = $user->currentWorkspace;
+ $workspace = $user->currentWorkspace;
- if ($currentWorkspace && $currentWorkspace->owner && $currentWorkspace->owner->id !== $user->id) {
- $owner = $currentWorkspace->owner;
-
- if ($owner->subscribed(User::SUBSCRIPTION_NAME) || $owner->onTrial(User::SUBSCRIPTION_NAME)) {
- return $next($request);
- }
+ if ($workspace && $workspace->hasActiveSubscription()) {
+ return $next($request);
}
- // Redirect to subscription page
return redirect()->route('app.subscribe');
}
}
diff --git a/app/Http/Middleware/Mcp/AuthenticateMcpToken.php b/app/Http/Middleware/Mcp/AuthenticateMcpToken.php
index 1dee934d6..1c885dfe6 100644
--- a/app/Http/Middleware/Mcp/AuthenticateMcpToken.php
+++ b/app/Http/Middleware/Mcp/AuthenticateMcpToken.php
@@ -5,7 +5,6 @@ declare(strict_types=1);
namespace App\Http\Middleware\Mcp;
use App\Models\ApiToken;
-use App\Models\User;
use App\Models\Workspace;
use Closure;
use Illuminate\Http\Request;
@@ -59,12 +58,6 @@ class AuthenticateMcpToken
private function hasActiveSubscription(Workspace $workspace): bool
{
- $owner = $workspace->owner;
-
- if (! $owner) {
- return false;
- }
-
- return $owner->subscribed(User::SUBSCRIPTION_NAME) || $owner->onTrial(User::SUBSCRIPTION_NAME);
+ return $workspace->hasActiveSubscription();
}
}
diff --git a/app/Listeners/StripeEventListener.php b/app/Listeners/StripeEventListener.php
index 82ea79cc4..0fb6bbb10 100644
--- a/app/Listeners/StripeEventListener.php
+++ b/app/Listeners/StripeEventListener.php
@@ -6,15 +6,12 @@ namespace App\Listeners;
use App\Enums\User\Setup;
use App\Events\SubscriptionCreated;
-use App\Models\User;
+use App\Models\Workspace;
use Illuminate\Support\Facades\Log;
use Laravel\Cashier\Events\WebhookReceived;
class StripeEventListener
{
- /**
- * Handle received Stripe webhooks.
- */
public function handle(WebhookReceived $event): void
{
try {
@@ -25,16 +22,16 @@ class StripeEventListener
return;
}
- $user = User::where('stripe_id', $stripeCustomerId)->first();
+ $workspace = Workspace::where('stripe_id', $stripeCustomerId)->first();
- if (! $user) {
+ if (! $workspace) {
return;
}
match ($type) {
- 'customer.subscription.created' => $this->handleSubscriptionCreated($user, $event->payload),
- 'customer.subscription.updated' => $this->handleSubscriptionUpdated($user, $event->payload),
- 'customer.subscription.deleted' => $this->handleSubscriptionDeleted($user, $event->payload),
+ 'customer.subscription.created' => $this->handleSubscriptionCreated($workspace, $event->payload),
+ 'customer.subscription.updated' => $this->handleSubscriptionUpdated($workspace, $event->payload),
+ 'customer.subscription.deleted' => $this->handleSubscriptionDeleted($workspace, $event->payload),
default => null,
};
} catch (\Exception $e) {
@@ -45,22 +42,24 @@ class StripeEventListener
}
}
- protected function handleSubscriptionCreated(User $user, array $payload): void
+ protected function handleSubscriptionCreated(Workspace $workspace, array $payload): void
{
- if ($user->setup === Setup::Subscription) {
- $user->update(['setup' => Setup::Completed]);
+ $owner = $workspace->owner;
+
+ if ($owner && $owner->setup === Setup::Subscription) {
+ $owner->update(['setup' => Setup::Completed]);
}
- SubscriptionCreated::dispatch($user);
+ SubscriptionCreated::dispatch($workspace);
}
- protected function handleSubscriptionUpdated(User $user, array $payload): void
+ protected function handleSubscriptionUpdated(Workspace $workspace, array $payload): void
{
- // Future: dispatch SubscriptionUpdated event if needed
+ //
}
- protected function handleSubscriptionDeleted(User $user, array $payload): void
+ protected function handleSubscriptionDeleted(Workspace $workspace, array $payload): void
{
- // Future: dispatch SubscriptionDeleted event if needed
+ //
}
}
diff --git a/app/Models/Traits/HasWorkspace.php b/app/Models/Traits/HasWorkspace.php
index 451d2689b..76cc2e242 100644
--- a/app/Models/Traits/HasWorkspace.php
+++ b/app/Models/Traits/HasWorkspace.php
@@ -5,7 +5,6 @@ declare(strict_types=1);
namespace App\Models\Traits;
use App\Enums\UserWorkspace\Role;
-use App\Models\User;
use App\Models\Workspace;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
@@ -53,76 +52,4 @@ trait HasWorkspace
{
return $this->workspaces()->wherePivot('role', Role::Owner->value)->count();
}
-
- /**
- * Check if user can create more workspaces based on subscription.
- * In self-hosted mode, users can create unlimited workspaces.
- */
- public function canCreateWorkspace(): bool
- {
- if (config('trypost.self_hosted')) {
- return true;
- }
-
- if (! $this->hasActiveSubscription()) {
- return $this->ownedWorkspacesCount() === 0;
- }
-
- $subscription = $this->subscription(User::SUBSCRIPTION_NAME);
-
- return $subscription && $this->ownedWorkspacesCount() < $subscription->quantity;
- }
-
- /**
- * Increment workspace quantity on subscription.
- * Skipped in self-hosted mode (no Stripe subscription).
- */
- public function incrementWorkspaceQuantity(): void
- {
- if (config('trypost.self_hosted')) {
- return;
- }
-
- if ($this->hasActiveSubscription()) {
- $this->subscription(User::SUBSCRIPTION_NAME)->incrementQuantity();
- }
- }
-
- /**
- * Decrement workspace quantity on subscription.
- * Skipped in self-hosted mode (no Stripe subscription).
- */
- public function decrementWorkspaceQuantity(): void
- {
- if (config('trypost.self_hosted')) {
- return;
- }
-
- if ($this->hasActiveSubscription()) {
- $subscription = $this->subscription(User::SUBSCRIPTION_NAME);
-
- if ($subscription->quantity > 1) {
- $subscription->decrementQuantity();
- }
- }
- }
-
- /**
- * Sync subscription quantity with actual workspace count.
- * Skipped in self-hosted mode (no Stripe subscription).
- */
- public function syncWorkspaceQuantity(): void
- {
- if (config('trypost.self_hosted')) {
- return;
- }
-
- if ($this->hasActiveSubscription()) {
- $count = $this->ownedWorkspacesCount();
-
- if ($count > 0) {
- $this->subscription(User::SUBSCRIPTION_NAME)->updateQuantity($count);
- }
- }
- }
}
diff --git a/app/Models/User.php b/app/Models/User.php
index 4b9c00e54..8dd9647d3 100644
--- a/app/Models/User.php
+++ b/app/Models/User.php
@@ -17,14 +17,11 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
-use Laravel\Cashier\Billable;
class User extends Authenticatable implements MustVerifyEmail
{
/** @use HasFactory<UserFactory> */
- use Billable, HasFactory, HasMedia, HasUuids, HasWorkspace, Notifiable;
-
- public const SUBSCRIPTION_NAME = 'default';
+ use HasFactory, HasMedia, HasUuids, HasWorkspace, Notifiable;
/**
* The attributes that are mass assignable.
@@ -112,25 +109,4 @@ class User extends Authenticatable implements MustVerifyEmail
default => true,
};
}
-
- /**
- * Check if user has an active subscription.
- * In self-hosted mode, always returns true (no subscription required).
- */
- public function hasActiveSubscription(): bool
- {
- if (config('trypost.self_hosted')) {
- return true;
- }
-
- return $this->subscribed(self::SUBSCRIPTION_NAME);
- }
-
- /**
- * Check if user has ever had a subscription (for trial eligibility).
- */
- public function hasEverSubscribed(): bool
- {
- return $this->subscriptions()->exists();
- }
}
diff --git a/app/Models/Workspace.php b/app/Models/Workspace.php
index c6d76c297..c5baeae5c 100644
--- a/app/Models/Workspace.php
+++ b/app/Models/Workspace.php
@@ -12,15 +12,22 @@ use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
+use Laravel\Cashier\Billable;
class Workspace extends Model
{
/** @use HasFactory<WorkspaceFactory> */
- use HasFactory, HasMedia, HasUuids;
+ use Billable, HasFactory, HasMedia, HasUuids;
+
+ public const SUBSCRIPTION_NAME = 'default';
protected $fillable = [
'user_id',
'plan_id',
+ 'stripe_id',
+ 'pm_type',
+ 'pm_last_four',
+ 'trial_ends_at',
'name',
'timezone',
];
@@ -103,4 +110,41 @@ class Workspace extends Model
{
return $this->socialAccounts()->where('platform', $platform)->first();
}
+
+ /**
+ * Check if the workspace has an active subscription.
+ * In self-hosted mode, always returns true.
+ */
+ public function hasActiveSubscription(): bool
+ {
+ if (config('trypost.self_hosted')) {
+ return true;
+ }
+
+ return $this->subscribed(self::SUBSCRIPTION_NAME);
+ }
+
+ /**
+ * Check if the workspace is on a trial period.
+ */
+ public function isOnTrial(): bool
+ {
+ return $this->subscription(self::SUBSCRIPTION_NAME)?->onTrial() ?? false;
+ }
+
+ /**
+ * Get the email address for Stripe.
+ */
+ public function stripeEmail(): string
+ {
+ return $this->owner?->email ?? '';
+ }
+
+ /**
+ * Get the name for Stripe.
+ */
+ public function stripeName(): string
+ {
+ return $this->name;
+ }
}
diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php
index acc177d4a..725cd8301 100644
--- a/app/Providers/AppServiceProvider.php
+++ b/app/Providers/AppServiceProvider.php
@@ -75,6 +75,7 @@ class AppServiceProvider extends ServiceProvider
$this->configureSocialite();
$this->configureStripeWebhooks();
+ Cashier::useCustomerModel(Workspace::class);
Cashier::useSubscriptionModel(Subscription::class);
Cashier::useSubscriptionItemModel(SubscriptionItem::class);
}
diff --git a/config/cashier.php b/config/cashier.php
index f4b415bb7..44c302309 100644
--- a/config/cashier.php
+++ b/config/cashier.php
@@ -126,30 +126,6 @@ return [
'logger' => env('CASHIER_LOGGER'),
- /*
- |--------------------------------------------------------------------------
- | Subscription Plans
- |--------------------------------------------------------------------------
- |
- | Define the available subscription plans with their Stripe price IDs.
- | The 'monthly' plan bills at $25/workspace/month.
- | The 'yearly' plan bills at $20/workspace/month (20% discount).
- |
- */
-
- 'plans' => [
- 'monthly' => [
- 'price_id' => env('STRIPE_PRICE_MONTHLY'),
- 'price' => 20,
- 'interval' => 'month',
- ],
- 'yearly' => [
- 'price_id' => env('STRIPE_PRICE_YEARLY'),
- 'price' => 16,
- 'interval' => 'year',
- ],
- ],
-
/*
|--------------------------------------------------------------------------
| Trial Period
diff --git a/database/factories/UserFactory.php b/database/factories/UserFactory.php
index 7c5fff22b..76b58ff5d 100644
--- a/database/factories/UserFactory.php
+++ b/database/factories/UserFactory.php
@@ -33,10 +33,6 @@ class UserFactory extends Factory
'password' => static::$password ??= Hash::make('password'),
'remember_token' => Str::random(10),
'current_workspace_id' => null,
- 'stripe_id' => null,
- 'pm_type' => null,
- 'pm_last_four' => null,
- 'trial_ends_at' => null,
'two_factor_secret' => null,
'two_factor_recovery_codes' => null,
'two_factor_confirmed_at' => null,
diff --git a/database/factories/WorkspaceFactory.php b/database/factories/WorkspaceFactory.php
index c698e81ed..217c43106 100644
--- a/database/factories/WorkspaceFactory.php
+++ b/database/factories/WorkspaceFactory.php
@@ -22,6 +22,7 @@ class WorkspaceFactory extends Factory
{
return [
'user_id' => User::factory(),
+ 'plan_id' => null,
'name' => fake()->company(),
'timezone' => fake()->timezone(),
];
diff --git a/database/migrations/2026_04_14_210719_add_billing_columns_to_workspaces_table.php b/database/migrations/2026_04_14_210719_add_billing_columns_to_workspaces_table.php
new file mode 100644
index 000000000..183225beb
--- /dev/null
+++ b/database/migrations/2026_04_14_210719_add_billing_columns_to_workspaces_table.php
@@ -0,0 +1,34 @@
+<?php
+
+declare(strict_types=1);
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+
+return new class extends Migration
+{
+ /**
+ * Run the migrations.
+ */
+ public function up(): void
+ {
+ Schema::table('workspaces', function (Blueprint $table) {
+ $table->string('stripe_id')->nullable()->after('plan_id')->index();
+ $table->string('pm_type')->nullable()->after('stripe_id');
+ $table->string('pm_last_four')->nullable()->after('pm_type');
+ $table->timestamp('trial_ends_at')->nullable()->after('pm_last_four');
+ });
+ }
+
+ /**
+ * Reverse the migrations.
+ */
+ public function down(): void
+ {
+ Schema::table('workspaces', function (Blueprint $table) {
+ $table->dropIndex(['stripe_id']);
+ $table->dropColumn(['stripe_id', 'pm_type', 'pm_last_four', 'trial_ends_at']);
+ });
+ }
+};
diff --git a/database/migrations/2026_04_14_210720_migrate_subscriptions_to_workspace.php b/database/migrations/2026_04_14_210720_migrate_subscriptions_to_workspace.php
new file mode 100644
index 000000000..7b4238cbb
--- /dev/null
+++ b/database/migrations/2026_04_14_210720_migrate_subscriptions_to_workspace.php
@@ -0,0 +1,44 @@
+<?php
+
+declare(strict_types=1);
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+
+return new class extends Migration
+{
+ /**
+ * Run the migrations.
+ */
+ public function up(): void
+ {
+ Schema::table('subscriptions', function (Blueprint $table) {
+ $table->dropIndex(['user_id', 'stripe_status']);
+ $table->dropForeign(['user_id']);
+ $table->dropColumn('user_id');
+ });
+
+ Schema::table('subscriptions', function (Blueprint $table) {
+ $table->foreignUuid('workspace_id')->after('id')->constrained()->cascadeOnDelete();
+ $table->index(['workspace_id', 'stripe_status']);
+ });
+ }
+
+ /**
+ * Reverse the migrations.
+ */
+ public function down(): void
+ {
+ Schema::table('subscriptions', function (Blueprint $table) {
+ $table->dropIndex(['workspace_id', 'stripe_status']);
+ $table->dropForeign(['workspace_id']);
+ $table->dropColumn('workspace_id');
+ });
+
+ Schema::table('subscriptions', function (Blueprint $table) {
+ $table->foreignUuid('user_id')->after('id')->constrained()->cascadeOnDelete();
+ $table->index(['user_id', 'stripe_status']);
+ });
+ }
+};
diff --git a/database/migrations/2026_04_14_210720_remove_billing_columns_from_users_table.php b/database/migrations/2026_04_14_210720_remove_billing_columns_from_users_table.php
new file mode 100644
index 000000000..3c3cdeba6
--- /dev/null
+++ b/database/migrations/2026_04_14_210720_remove_billing_columns_from_users_table.php
@@ -0,0 +1,34 @@
+<?php
+
+declare(strict_types=1);
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+
+return new class extends Migration
+{
+ /**
+ * Run the migrations.
+ */
+ public function up(): void
+ {
+ Schema::table('users', function (Blueprint $table) {
+ $table->dropIndex(['stripe_id']);
+ $table->dropColumn(['stripe_id', 'pm_type', 'pm_last_four', 'trial_ends_at']);
+ });
+ }
+
+ /**
+ * Reverse the migrations.
+ */
+ public function down(): void
+ {
+ Schema::table('users', function (Blueprint $table) {
+ $table->string('stripe_id')->nullable()->index();
+ $table->string('pm_type')->nullable();
+ $table->string('pm_last_four', 4)->nullable();
+ $table->timestamp('trial_ends_at')->nullable();
+ });
+ }
+};
diff --git a/routes/app.php b/routes/app.php
index 7affb1f55..45997af98 100644
--- a/routes/app.php
+++ b/routes/app.php
@@ -40,7 +40,7 @@ Route::get('/', function () {
// Subscription selection (requires auth but not subscription)
Route::middleware(['auth', 'verified'])->group(function () {
Route::get('subscribe', [BillingController::class, 'subscribe'])->name('app.subscribe');
- Route::post('billing/checkout', [BillingController::class, 'checkout'])->name('app.billing.checkout');
+ Route::post('billing/checkout/{plan}', [BillingController::class, 'checkout'])->name('app.billing.checkout');
Route::get('billing/processing', [BillingController::class, 'processing'])->name('app.billing.processing');
});
@@ -178,6 +178,7 @@ Route::middleware(['auth', 'verified', 'subscribed', EnsureUserSetupIsComplete::
// Billing
Route::get('settings/billing', [BillingController::class, 'index'])->name('app.billing.index');
Route::get('settings/billing/portal', [BillingController::class, 'portal'])->name('app.billing.portal');
+ Route::post('settings/billing/swap/{plan}', [BillingController::class, 'swap'])->name('app.billing.swap');
});
diff --git a/tests/Feature/Api/AuthenticateApiTokenTest.php b/tests/Feature/Api/AuthenticateApiTokenTest.php
index 9cdd456b6..3303a23e7 100644
--- a/tests/Feature/Api/AuthenticateApiTokenTest.php
+++ b/tests/Feature/Api/AuthenticateApiTokenTest.php
@@ -134,13 +134,12 @@ test('returns 402 when workspace owner has no subscription', function () {
$response->assertJson(['message' => 'Active subscription required.']);
});
-test('allows access when workspace owner has active subscription', function () {
+test('allows access when workspace has active subscription', function () {
config(['trypost.self_hosted' => false]);
$result = createApiToken();
- $owner = $result['workspace']->owner;
- $owner->subscriptions()->create([
+ $result['workspace']->subscriptions()->create([
'type' => 'default',
'stripe_id' => 'sub_test_123',
'stripe_status' => 'active',
@@ -157,13 +156,12 @@ test('allows access when workspace owner has active subscription', function () {
$response->assertOk();
});
-test('allows access when workspace owner is on trial', function () {
+test('allows access when workspace is on trial', function () {
config(['trypost.self_hosted' => false]);
$result = createApiToken();
- $owner = $result['workspace']->owner;
- $owner->subscriptions()->create([
+ $result['workspace']->subscriptions()->create([
'type' => 'default',
'stripe_id' => 'sub_trial_123',
'stripe_status' => 'trialing',
diff --git a/tests/Feature/BillingControllerTest.php b/tests/Feature/BillingControllerTest.php
index 78489fdbf..8fcc93b8d 100644
--- a/tests/Feature/BillingControllerTest.php
+++ b/tests/Feature/BillingControllerTest.php
@@ -4,6 +4,7 @@ declare(strict_types=1);
use App\Enums\User\Setup;
use App\Enums\UserWorkspace\Role;
+use App\Models\Plan;
use App\Models\User;
use App\Models\Workspace;
@@ -22,15 +23,31 @@ test('subscribe requires authentication', function () {
});
test('subscribe shows subscription page', function () {
+ config(['trypost.self_hosted' => false]);
+
$response = $this->actingAs($this->user)->get(route('app.subscribe'));
$response->assertOk();
$response->assertInertia(fn ($page) => $page
->component('billing/Subscribe', false)
+ ->has('plans')
->has('trialDays')
);
});
+test('subscribe redirects to billing index when workspace has active subscription', function () {
+ $this->workspace->subscriptions()->create([
+ 'type' => Workspace::SUBSCRIPTION_NAME,
+ 'stripe_id' => 'sub_test_'.fake()->uuid(),
+ 'stripe_status' => 'active',
+ 'stripe_price' => 'price_123',
+ ]);
+
+ $response = $this->actingAs($this->user)->get(route('app.subscribe'));
+
+ $response->assertRedirect(route('app.billing.index'));
+});
+
// Index tests
test('billing index requires authentication', function () {
$response = $this->get(route('app.billing.index'));
@@ -39,13 +56,21 @@ test('billing index requires authentication', function () {
});
test('billing index shows billing dashboard', function () {
+ $this->workspace->subscriptions()->create([
+ 'type' => Workspace::SUBSCRIPTION_NAME,
+ 'stripe_id' => 'sub_test_'.fake()->uuid(),
+ 'stripe_status' => 'active',
+ 'stripe_price' => 'price_123',
+ ]);
+
$response = $this->actingAs($this->user)->get(route('app.billing.index'));
$response->assertOk();
$response->assertInertia(fn ($page) => $page
->component('billing/Index', false)
->has('hasSubscription')
- ->has('workspacesCount')
+ ->has('plan')
+ ->has('plans')
);
});
@@ -62,7 +87,7 @@ test('billing processing shows processing page', function () {
$response->assertOk();
$response->assertInertia(fn ($page) => $page
->component('billing/Processing', false)
- ->has('userId')
+ ->has('workspaceId')
->has('status')
);
});
@@ -87,7 +112,8 @@ test('billing processing validates status parameter', function () {
// Checkout tests
test('checkout requires authentication', function () {
- $response = $this->post(route('app.billing.checkout'));
+ $plan = Plan::first();
+ $response = $this->post(route('app.billing.checkout', $plan));
$response->assertRedirect(route('login'));
});
@@ -100,27 +126,18 @@ test('portal requires authentication', function () {
});
// Authorization tests
-test('admin cannot access subscribe page', function () {
- $admin = User::factory()->create(['setup' => Setup::Completed]);
- $this->workspace->members()->attach($admin->id, ['role' => Role::Admin->value]);
- $admin->update(['current_workspace_id' => $this->workspace->id]);
-
- $this->actingAs($admin)->get(route('app.subscribe'))->assertForbidden();
-});
-
-test('member cannot access subscribe page', function () {
- $member = User::factory()->create(['setup' => Setup::Completed]);
- $this->workspace->members()->attach($member->id, ['role' => Role::Member->value]);
- $member->update(['current_workspace_id' => $this->workspace->id]);
-
- $this->actingAs($member)->get(route('app.subscribe'))->assertForbidden();
-});
-
test('admin cannot access billing index', function () {
$admin = User::factory()->create(['setup' => Setup::Completed]);
$this->workspace->members()->attach($admin->id, ['role' => Role::Admin->value]);
$admin->update(['current_workspace_id' => $this->workspace->id]);
+ $this->workspace->subscriptions()->create([
+ 'type' => Workspace::SUBSCRIPTION_NAME,
+ 'stripe_id' => 'sub_test_'.fake()->uuid(),
+ 'stripe_status' => 'active',
+ 'stripe_price' => 'price_123',
+ ]);
+
$this->actingAs($admin)->get(route('app.billing.index'))->assertForbidden();
});
@@ -129,5 +146,12 @@ test('member cannot access billing index', function () {
$this->workspace->members()->attach($member->id, ['role' => Role::Member->value]);
$member->update(['current_workspace_id' => $this->workspace->id]);
+ $this->workspace->subscriptions()->create([
+ 'type' => Workspace::SUBSCRIPTION_NAME,
+ 'stripe_id' => 'sub_test_'.fake()->uuid(),
+ 'stripe_status' => 'active',
+ 'stripe_price' => 'price_123',
+ ]);
+
$this->actingAs($member)->get(route('app.billing.index'))->assertForbidden();
});
diff --git a/tests/Feature/Controllers/ChunkedUploadTest.php b/tests/Feature/Controllers/ChunkedUploadTest.php
index ddcc6a592..dd48a9bb5 100644
--- a/tests/Feature/Controllers/ChunkedUploadTest.php
+++ b/tests/Feature/Controllers/ChunkedUploadTest.php
@@ -13,14 +13,13 @@ beforeEach(function () {
$this->user = User::factory()->create([
'setup' => Setup::Completed,
]);
- $this->user->subscriptions()->create([
+ $this->workspace = Workspace::factory()->create(['user_id' => $this->user->id]);
+ $this->workspace->subscriptions()->create([
'type' => 'default',
'stripe_id' => 'sub_123',
'stripe_status' => 'active',
'stripe_price' => 'price_123',
- 'quantity' => 1,
]);
- $this->workspace = Workspace::factory()->create(['user_id' => $this->user->id]);
$this->user->update(['current_workspace_id' => $this->workspace->id]);
});
diff --git a/tests/Feature/Listeners/StripeEventListenerTest.php b/tests/Feature/Listeners/StripeEventListenerTest.php
index f40022f8f..ce378a125 100644
--- a/tests/Feature/Listeners/StripeEventListenerTest.php
+++ b/tests/Feature/Listeners/StripeEventListenerTest.php
@@ -6,12 +6,15 @@ use App\Enums\User\Setup;
use App\Events\SubscriptionCreated;
use App\Listeners\StripeEventListener;
use App\Models\User;
+use App\Models\Workspace;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Log;
use Laravel\Cashier\Events\WebhookReceived;
beforeEach(function () {
- $this->user = User::factory()->create([
+ $this->user = User::factory()->create();
+ $this->workspace = Workspace::factory()->create([
+ 'user_id' => $this->user->id,
'stripe_id' => 'cus_test123',
]);
@@ -30,7 +33,7 @@ test('subscription created dispatches event', function () {
'data' => ['object' => ['customer' => 'cus_test123', 'id' => 'sub_123']],
]));
- Event::assertDispatched(SubscriptionCreated::class, fn ($e) => $e->user->id === $this->user->id);
+ Event::assertDispatched(SubscriptionCreated::class, fn ($e) => $e->workspace->id === $this->workspace->id);
});
test('subscription created marks setup as completed when on subscription step', function () {
diff --git a/tests/Feature/Middleware/AuthenticateMcpTokenTest.php b/tests/Feature/Middleware/AuthenticateMcpTokenTest.php
index 0cc3a2f36..75e78a625 100644
--- a/tests/Feature/Middleware/AuthenticateMcpTokenTest.php
+++ b/tests/Feature/Middleware/AuthenticateMcpTokenTest.php
@@ -139,8 +139,8 @@ test('allows access when owner has active subscription', function () {
config(['trypost.self_hosted' => false]);
$result = createMcpToken();
- $result['user']->subscriptions()->create([
- 'type' => User::SUBSCRIPTION_NAME,
+ $result['workspace']->subscriptions()->create([
+ 'type' => Workspace::SUBSCRIPTION_NAME,
'stripe_id' => 'sub_test',
'stripe_status' => 'active',
'stripe_price' => 'price_123',
@@ -155,8 +155,8 @@ test('allows access when owner is on trial', function () {
config(['trypost.self_hosted' => false]);
$result = createMcpToken();
- $result['user']->subscriptions()->create([
- 'type' => User::SUBSCRIPTION_NAME,
+ $result['workspace']->subscriptions()->create([
+ 'type' => Workspace::SUBSCRIPTION_NAME,
'stripe_id' => 'sub_trial',
'stripe_status' => 'trialing',
'stripe_price' => 'price_123',
diff --git a/tests/Feature/Middleware/EnsureSubscribedTest.php b/tests/Feature/Middleware/EnsureSubscribedTest.php
index 9bba05b94..c72f791a0 100644
--- a/tests/Feature/Middleware/EnsureSubscribedTest.php
+++ b/tests/Feature/Middleware/EnsureSubscribedTest.php
@@ -35,7 +35,7 @@ test('user with active subscription can access protected route', function () {
$workspace->members()->attach($user->id, ['role' => Role::Owner->value]);
$user->update(['current_workspace_id' => $workspace->id]);
- $user->subscriptions()->create([
+ $workspace->subscriptions()->create([
'type' => 'default',
'stripe_id' => 'sub_123',
'stripe_status' => 'active',
@@ -56,7 +56,7 @@ test('user on trial subscription can access protected route', function () {
$user->update(['current_workspace_id' => $workspace->id]);
// Create a subscription with trial
- $user->subscriptions()->create([
+ $workspace->subscriptions()->create([
'type' => 'default',
'stripe_id' => 'sub_trial_123',
'stripe_status' => 'trialing',
@@ -91,7 +91,7 @@ test('user with expired trial subscription is redirected to subscribe page', fun
$user->update(['current_workspace_id' => $workspace->id]);
// Create an expired trial subscription
- $user->subscriptions()->create([
+ $workspace->subscriptions()->create([
'type' => 'default',
'stripe_id' => 'sub_expired_trial',
'stripe_status' => 'canceled',
@@ -113,7 +113,7 @@ test('user with cancelled subscription is redirected to subscribe page', functio
$workspace->members()->attach($user->id, ['role' => Role::Owner->value]);
$user->update(['current_workspace_id' => $workspace->id]);
- $user->subscriptions()->create([
+ $workspace->subscriptions()->create([
'type' => 'default',
'stripe_id' => 'sub_123',
'stripe_status' => 'canceled',
@@ -133,7 +133,7 @@ test('invited member can access workspace when owner has active subscription', f
$workspace = Workspace::factory()->create(['user_id' => $owner->id]);
$workspace->members()->attach($owner->id, ['role' => Role::Owner->value]);
- $owner->subscriptions()->create([
+ $workspace->subscriptions()->create([
'type' => 'default',
'stripe_id' => 'sub_owner_123',
'stripe_status' => 'active',
@@ -172,7 +172,7 @@ test('invited member on own workspace without subscription is redirected to subs
$ownerWorkspace = Workspace::factory()->create(['user_id' => $owner->id]);
$ownerWorkspace->members()->attach($owner->id, ['role' => Role::Owner->value]);
- $owner->subscriptions()->create([
+ $ownerWorkspace->subscriptions()->create([
'type' => 'default',
'stripe_id' => 'sub_owner_123',
'stripe_status' => 'active',
diff --git a/tests/Feature/WorkspaceBillingTest.php b/tests/Feature/WorkspaceBillingTest.php
new file mode 100644
index 000000000..bc0518703
--- /dev/null
+++ b/tests/Feature/WorkspaceBillingTest.php
@@ -0,0 +1,111 @@
+<?php
+
+declare(strict_types=1);
+
+use App\Enums\Plan\Slug as PlanSlug;
+use App\Enums\User\Setup;
+use App\Enums\UserWorkspace\Role;
+use App\Models\Plan;
+use App\Models\User;
+use App\Models\Workspace;
+
+beforeEach(function () {
+ config(['trypost.self_hosted' => true]);
+
+ $this->user = User::factory()->create(['setup' => Setup::Completed]);
+ $this->workspace = Workspace::factory()->create(['user_id' => $this->user->id]);
+ $this->workspace->members()->attach($this->user->id, ['role' => Role::Owner->value]);
+ $this->user->update(['current_workspace_id' => $this->workspace->id]);
+});
+
+test('workspace has active subscription in self hosted mode', function () {
+ config(['trypost.self_hosted' => true]);
+
+ expect($this->workspace->hasActiveSubscription())->toBeTrue();
+});
+
+test('workspace without subscription is not active in saas mode', function () {
+ config(['trypost.self_hosted' => false]);
+
+ expect($this->workspace->hasActiveSubscription())->toBeFalse();
+});
+
+test('workspace belongs to plan', function () {
+ $plan = Plan::where('slug', PlanSlug::Starter)->first();
+ $this->workspace->update(['plan_id' => $plan->id]);
+
+ expect($this->workspace->fresh()->plan->id)->toBe($plan->id);
+});
+
+test('ensure subscribed middleware passes in self hosted mode', function () {
+ config(['trypost.self_hosted' => true]);
+
+ $response = $this->actingAs($this->user)->get(route('app.calendar'));
+
+ $response->assertOk();
+});
+
+test('ensure subscribed middleware redirects without subscription in saas mode', function () {
+ config(['trypost.self_hosted' => false]);
+
+ $response = $this->actingAs($this->user)->get(route('app.calendar'));
+
+ $response->assertRedirect(route('app.subscribe'));
+});
+
+test('billing page is accessible by workspace owner', function () {
+ config(['trypost.self_hosted' => false]);
+
+ $this->workspace->subscriptions()->create([
+ 'type' => Workspace::SUBSCRIPTION_NAME,
+ 'stripe_id' => 'sub_test_'.fake()->uuid(),
+ 'stripe_status' => 'active',
+ 'stripe_price' => 'price_123',
+ ]);
+
+ $response = $this->actingAs($this->user)->get(route('app.billing.index'));
+
+ $response->assertOk();
+});
+
+test('billing page is not accessible by workspace member', function () {
+ config(['trypost.self_hosted' => false]);
+
+ $member = User::factory()->create(['setup' => Setup::Completed]);
+ $this->workspace->members()->attach($member->id, ['role' => Role::Member->value]);
+ $member->update(['current_workspace_id' => $this->workspace->id]);
+
+ $this->workspace->subscriptions()->create([
+ 'type' => Workspace::SUBSCRIPTION_NAME,
+ 'stripe_id' => 'sub_test_'.fake()->uuid(),
+ 'stripe_status' => 'active',
+ 'stripe_price' => 'price_123',
+ ]);
+
+ $response = $this->actingAs($member)->get(route('app.billing.index'));
+
+ $response->assertForbidden();
+});
+
+test('subscribe page shows plans', function () {
+ config(['trypost.self_hosted' => false]);
+
+ $activePlanCount = Plan::active()->count();
+
+ $response = $this->actingAs($this->user)->get(route('app.subscribe'));
+
+ $response->assertOk();
+ $response->assertInertia(fn ($page) => $page
+ ->component('billing/Subscribe', false)
+ ->has('plans', $activePlanCount)
+ ->has('trialDays')
+ );
+});
+
+test('stripe email returns workspace owner email', function () {
+ expect($this->workspace->stripeEmail())->toBe($this->user->email);
+});
+
+test('stripe name returns workspace name', function () {
+ expect($this->workspace->stripeName())->toBe($this->workspace->name);
+});
diff --git a/tests/Unit/Events/SubscriptionCreatedTest.php b/tests/Unit/Events/SubscriptionCreatedTest.php
index e647df6be..670285323 100644
--- a/tests/Unit/Events/SubscriptionCreatedTest.php
+++ b/tests/Unit/Events/SubscriptionCreatedTest.php
@@ -4,11 +4,13 @@ declare(strict_types=1);
use App\Events\SubscriptionCreated;
use App\Models\User;
+use App\Models\Workspace;
use Illuminate\Broadcasting\PrivateChannel;
test('event broadcasts on correct channel', function () {
$user = User::factory()->create();
- $event = new SubscriptionCreated($user);
+ $workspace = Workspace::factory()->create(['user_id' => $user->id]);
+ $event = new SubscriptionCreated($workspace);
$channels = $event->broadcastOn();
expect($channels)->toHaveCount(1);
@@ -18,7 +20,8 @@ test('event broadcasts on correct channel', function () {
test('event broadcasts with correct data', function () {
$user = User::factory()->create();
- $event = new SubscriptionCreated($user);
+ $workspace = Workspace::factory()->create(['user_id' => $user->id]);
+ $event = new SubscriptionCreated($workspace);
$data = $event->broadcastWith();
expect($data)->toHaveKey('status');
diff --git a/tests/Unit/Traits/HasWorkspaceTest.php b/tests/Unit/Traits/HasWorkspaceTest.php
index 8332e7c36..e2881b1d1 100644
--- a/tests/Unit/Traits/HasWorkspaceTest.php
+++ b/tests/Unit/Traits/HasWorkspaceTest.php
@@ -83,164 +83,3 @@ test('user can get owned workspaces count', function () {
expect($user->ownedWorkspacesCount())->toBe(3);
});
-
-test('user without subscription can create first workspace in SaaS mode', function () {
- config(['trypost.self_hosted' => false]);
-
- $user = User::factory()->create();
-
- expect($user->canCreateWorkspace())->toBeTrue();
-});
-
-test('user without subscription cannot create second workspace in SaaS mode', function () {
- config(['trypost.self_hosted' => false]);
-
- $user = User::factory()->create();
- $workspace = Workspace::factory()->create(['user_id' => $user->id]);
- $workspace->members()->attach($user->id, ['role' => Role::Owner->value]);
-
- expect($user->canCreateWorkspace())->toBeFalse();
-});
-
-test('user can create unlimited workspaces in self-hosted mode', function () {
- config(['trypost.self_hosted' => true]);
-
- $user = User::factory()->create();
- $workspaces = Workspace::factory()->count(5)->create(['user_id' => $user->id]);
-
- foreach ($workspaces as $workspace) {
- $workspace->members()->attach($user->id, ['role' => Role::Owner->value]);
- }
-
- expect($user->canCreateWorkspace())->toBeTrue();
-});
-
-test('user with subscription can create workspaces up to quantity in SaaS mode', function () {
- config(['trypost.self_hosted' => false]);
-
- $user = User::factory()->create();
- $user->subscriptions()->create([
- 'type' => 'default',
- 'stripe_id' => 'sub_123',
- 'stripe_status' => 'active',
- 'stripe_price' => 'price_123',
- 'quantity' => 3,
- ]);
-
- $workspace = Workspace::factory()->create(['user_id' => $user->id]);
- $workspace->members()->attach($user->id, ['role' => Role::Owner->value]);
-
- expect($user->canCreateWorkspace())->toBeTrue();
-});
-
-test('user with subscription cannot exceed workspace quantity in SaaS mode', function () {
- config(['trypost.self_hosted' => false]);
-
- $user = User::factory()->create();
- $user->subscriptions()->create([
- 'type' => 'default',
- 'stripe_id' => 'sub_123',
- 'stripe_status' => 'active',
- 'stripe_price' => 'price_123',
- 'quantity' => 2,
- ]);
-
- $workspaces = Workspace::factory()->count(2)->create(['user_id' => $user->id]);
-
- foreach ($workspaces as $workspace) {
- $workspace->members()->attach($user->id, ['role' => Role::Owner->value]);
- }
-
- expect($user->canCreateWorkspace())->toBeFalse();
-});
-
-test('increment workspace quantity does nothing without subscription in SaaS mode', function () {
- config(['trypost.self_hosted' => false]);
-
- $user = User::factory()->create();
-
- $user->incrementWorkspaceQuantity();
-
- expect($user->subscription(User::SUBSCRIPTION_NAME))->toBeNull();
-});
-
-test('increment workspace quantity is skipped in self-hosted mode', function () {
- config(['trypost.self_hosted' => true]);
-
- $user = User::factory()->create();
-
- // Should not throw any errors even without subscription
- $user->incrementWorkspaceQuantity();
-
- expect($user->subscription(User::SUBSCRIPTION_NAME))->toBeNull();
-});
-
-test('decrement workspace quantity does nothing without subscription in SaaS mode', function () {
- config(['trypost.self_hosted' => false]);
-
- $user = User::factory()->create();
-
- $user->decrementWorkspaceQuantity();
-
- expect($user->subscription(User::SUBSCRIPTION_NAME))->toBeNull();
-});
-
-test('decrement workspace quantity is skipped in self-hosted mode', function () {
- config(['trypost.self_hosted' => true]);
-
- $user = User::factory()->create();
-
- // Should not throw any errors even without subscription
- $user->decrementWorkspaceQuantity();
-
- expect($user->subscription(User::SUBSCRIPTION_NAME))->toBeNull();
-});
-
-test('sync workspace quantity does nothing without subscription in SaaS mode', function () {
- config(['trypost.self_hosted' => false]);
-
- $user = User::factory()->create();
- $workspaces = Workspace::factory()->count(2)->create(['user_id' => $user->id]);
-
- foreach ($workspaces as $workspace) {
- $workspace->members()->attach($user->id, ['role' => Role::Owner->value]);
- }
-
- $user->syncWorkspaceQuantity();
-
- expect($user->subscription(User::SUBSCRIPTION_NAME))->toBeNull();
-});
-
-test('sync workspace quantity is skipped in self-hosted mode', function () {
- config(['trypost.self_hosted' => true]);
-
- $user = User::factory()->create();
- $workspaces = Workspace::factory()->count(2)->create(['user_id' => $user->id]);
-
- foreach ($workspaces as $workspace) {
- $workspace->members()->attach($user->id, ['role' => Role::Owner->value]);
- }
-
- // Should not throw any errors even without subscription
- $user->syncWorkspaceQuantity();
-
- expect($user->subscription(User::SUBSCRIPTION_NAME))->toBeNull();
-});
-
-test('sync workspace quantity does nothing with zero workspaces', function () {
- config(['trypost.self_hosted' => false]);
-
- $user = User::factory()->create();
- $user->subscriptions()->create([
- 'type' => 'default',
- 'stripe_id' => 'sub_123',
- 'stripe_status' => 'active',
- 'stripe_price' => 'price_123',
- 'quantity' => 5,
- ]);
-
- $user->syncWorkspaceQuantity();
-
- // Quantity remains unchanged because there are no workspaces
- expect($user->subscription(User::SUBSCRIPTION_NAME)->quantity)->toBe(5);
-});