feat: implement feature gating with persistent usage tracking and a reactive upgrade dialog for plan management.

This commit is contained in:
Paulo Castellano 2026-05-03 16:52:28 -03:00
parent fe0d432f05
commit 488d4a41e5
31 changed files with 597 additions and 94 deletions

View file

@ -8,6 +8,8 @@
class AiImagesLimit
{
public string $name = 'ai-images-limit';
public function resolve(Account $scope): int
{
return $scope->plan?->ai_images_limit ?? 50;

View file

@ -8,6 +8,8 @@
class MemberLimit
{
public string $name = 'member-limit';
public function resolve(Account $scope): int
{
return $scope->plan?->member_limit ?? 1;

View file

@ -8,6 +8,8 @@
class SocialAccountLimit
{
public string $name = 'social-account-limit';
public function resolve(Account $scope): int
{
return $scope->plan?->social_account_limit ?? 5;

View file

@ -8,6 +8,8 @@
class WorkspaceLimit
{
public string $name = 'workspace-limit';
public function resolve(Account $scope): int
{
return $scope->plan?->workspace_limit ?? 1;

View file

@ -141,6 +141,7 @@ public function swap(Request $request, Plan $plan): RedirectResponse
]);
$priceId = $request->input('price_id');
$subscription = $account->subscription(Account::SUBSCRIPTION_NAME);
abort_unless(
$priceId === $plan->stripe_monthly_price_id || $priceId === $plan->stripe_yearly_price_id,
@ -148,10 +149,21 @@ public function swap(Request $request, Plan $plan): RedirectResponse
'Invalid price for this plan',
);
$account->subscription(Account::SUBSCRIPTION_NAME)->swap($priceId);
$currentPlan = $account->plan;
$isOnYearly = $currentPlan && $subscription->stripe_price === $currentPlan->stripe_yearly_price_id;
$isTargetMonthly = $priceId === $plan->stripe_monthly_price_id;
abort_if(
$isOnYearly && $isTargetMonthly,
422,
'Cannot downgrade from yearly to monthly billing.',
);
$subscription->swap($priceId);
$account->update(['plan_id' => $plan->id]);
return redirect()->route('app.billing.index');
return redirect()->route('app.billing.index')
->with('flash.success', __('billing.flash.plan_changed', ['plan' => $plan->name]));
}
public function portal(Request $request): RedirectResponse

View file

@ -8,7 +8,6 @@
use App\Actions\Workspace\CreateWorkspace;
use App\Actions\Workspace\DeleteWorkspace;
use App\Enums\Workspace\BrandFont;
use App\Features\WorkspaceLimit;
use App\Http\Requests\App\Workspace\StoreWorkspaceRequest;
use App\Http\Requests\App\Workspace\UpdateWorkspaceRequest;
use App\Http\Resources\App\WorkspaceMemberResource;
@ -22,7 +21,6 @@
use Illuminate\Support\Facades\Log;
use Inertia\Inertia;
use Inertia\Response;
use Laravel\Pennant\Feature;
use RuntimeException;
use Symfony\Component\HttpFoundation\Response as SymfonyResponse;
use Throwable;
@ -75,8 +73,7 @@ public function create(Request $request): Response|RedirectResponse
}
if ($this->hasReachedWorkspaceLimit($user->account)) {
return redirect()->route('app.calendar')
->with('error', __('workspaces.limit_reached'));
return back()->with('flash.error', __('workspaces.limit_reached'));
}
return Inertia::render('workspaces/Create');
@ -187,10 +184,7 @@ public function uploadLogo(Request $request): RedirectResponse
$workspace->addMedia($request->file('photo'), 'logo');
$workspace->unsetRelation('media');
session()->flash('flash.banner', __('settings.flash.logo_updated'));
session()->flash('flash.bannerStyle', 'success');
return back();
return back()->with('flash.success', __('settings.flash.logo_updated'));
}
public function deleteLogo(Request $request): RedirectResponse
@ -202,10 +196,7 @@ public function deleteLogo(Request $request): RedirectResponse
$workspace->clearMediaCollection('logo');
$workspace->unsetRelation('media');
session()->flash('flash.banner', __('settings.flash.logo_deleted'));
session()->flash('flash.bannerStyle', 'success');
return back();
return back()->with('flash.success', __('settings.flash.logo_deleted'));
}
public function updateSettings(UpdateWorkspaceRequest $request): RedirectResponse
@ -221,10 +212,7 @@ public function updateSettings(UpdateWorkspaceRequest $request): RedirectRespons
$workspace->update($request->validated());
session()->flash('flash.banner', __('settings.flash.workspace_updated'));
session()->flash('flash.bannerStyle', 'success');
return back();
return back()->with('flash.success', __('settings.flash.workspace_updated'));
}
public function destroy(Request $request, Workspace $workspace): RedirectResponse
@ -236,7 +224,7 @@ public function destroy(Request $request, Workspace $workspace): RedirectRespons
DeleteWorkspace::execute($user, $workspace);
return redirect()->route('app.workspaces.index')
->with('success', 'Workspace deleted successfully!');
->with('flash.success', __('workspaces.flash.deleted'));
}
/**
@ -253,7 +241,7 @@ private function hasReachedWorkspaceLimit(?Account $account): bool
return false;
}
$limit = (int) Feature::for($account)->value(WorkspaceLimit::class);
$limit = (int) ($account->plan?->workspace_limit ?? 1);
return $account->workspaces()->count() >= $limit;
}

View file

@ -6,6 +6,8 @@
use App\Http\Resources\App\HandleInertiaRequests\AuthUserResource;
use App\Http\Resources\App\HandleInertiaRequests\AuthWorkspaceResource;
use App\Models\Account;
use App\Models\Plan;
use Illuminate\Http\Request;
use Inertia\Middleware;
@ -26,6 +28,8 @@ public function share(Request $request): array
$user = $request->user();
$currentWorkspace = $user?->currentWorkspace?->load('media');
$account = $user?->account;
$isSelfHosted = (bool) config('trypost.self_hosted');
return [
...parent::share($request),
@ -36,7 +40,13 @@ public function share(Request $request): array
'workspaces' => $user
? $user->workspaces()->with('media')->get()->map(fn ($ws) => AuthWorkspaceResource::summary($ws))
: [],
'plan' => $account?->plan,
'hasActiveSubscription' => $account ? $account->hasActiveSubscription() : false,
'currentPriceId' => $account?->subscription(Account::SUBSCRIPTION_NAME)?->stripe_price,
],
'usage' => $account && ! $isSelfHosted ? $account->usage() : null,
'features' => $account && ! $isSelfHosted ? $account->featureLimits() : null,
'plans' => $isSelfHosted ? [] : Plan::active()->orderBy('sort')->get(),
'sidebarOpen' => ! $request->hasCookie('sidebar_state') || $request->cookie('sidebar_state') === 'true',
'flash' => $request->session()->get('flash', []),
'applicationUrl' => config('app.url'),
@ -47,8 +57,9 @@ public function share(Request $request): array
'name' => $name,
])->values()->all(),
'aiEnabled' => ! empty(config('services.gemini.api_key')) || ! empty(config('services.openai.api_key')),
'selfHosted' => config('trypost.self_hosted'),
'selfHosted' => $isSelfHosted,
'googleAuthEnabled' => config('trypost.google_auth_enabled'),
'trialDays' => config('cashier.trial_days'),
];
}
}

View file

@ -4,6 +4,11 @@
namespace App\Models;
use App\Features\AiImagesLimit;
use App\Features\MemberLimit;
use App\Features\SocialAccountLimit;
use App\Features\WorkspaceLimit;
use App\Models\Traits\HasUsage;
use Database\Factories\AccountFactory;
use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Factories\HasFactory;
@ -11,11 +16,12 @@
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Laravel\Cashier\Billable;
use Laravel\Pennant\Feature;
class Account extends Model
{
/** @use HasFactory<AccountFactory> */
use Billable, HasFactory, HasUuids;
use Billable, HasFactory, HasUsage, HasUuids;
public const SUBSCRIPTION_NAME = 'default';
@ -26,6 +32,20 @@ class Account extends Model
'plan_id',
];
protected static function booted(): void
{
static::updated(function (Account $account): void {
if ($account->wasChanged('plan_id')) {
Feature::for($account)->forget([
WorkspaceLimit::class,
SocialAccountLimit::class,
MemberLimit::class,
AiImagesLimit::class,
]);
}
});
}
public function owner(): BelongsTo
{
return $this->belongsTo(User::class, 'owner_id');

View file

@ -0,0 +1,53 @@
<?php
declare(strict_types=1);
namespace App\Models\Traits;
use App\Features\AiImagesLimit;
use App\Features\MemberLimit;
use App\Features\SocialAccountLimit;
use App\Features\WorkspaceLimit;
use App\Models\Invite;
use Laravel\Pennant\Feature;
/**
* Provides account-level usage counts and plan-resolved feature limits.
*
* The `featureLimits()` call resolves Pennant features for the account,
* which writes to the features cache table on first access. Pennant cache
* is invalidated automatically when `plan_id` changes (see Account::booted).
*/
trait HasUsage
{
/**
* @return array{workspaceCount: int, socialAccountCount: int, memberCount: int, pendingInviteCount: int}
*/
public function usage(): array
{
return [
'workspaceCount' => $this->workspaces()->count(),
'socialAccountCount' => $this->workspaces()
->withCount('socialAccounts')
->get()
->sum('social_accounts_count'),
'memberCount' => $this->users()->count(),
'pendingInviteCount' => Invite::where('account_id', $this->id)
->whereNull('accepted_at')
->count(),
];
}
/**
* @return array{workspaceLimit: int, socialAccountLimit: int, memberLimit: int, aiImagesLimit: int}
*/
public function featureLimits(): array
{
return [
'workspaceLimit' => Feature::for($this)->value(WorkspaceLimit::class),
'socialAccountLimit' => Feature::for($this)->value(SocialAccountLimit::class),
'memberLimit' => Feature::for($this)->value(MemberLimit::class),
'aiImagesLimit' => Feature::for($this)->value(AiImagesLimit::class),
];
}
}

View file

@ -20,6 +20,7 @@
use App\Listeners\StripeEventListener;
use App\Models\Account;
use App\Models\AiUsageLog;
use App\Models\ApiToken;
use App\Models\Invite;
use App\Models\Media;
use App\Models\Notification;
@ -33,6 +34,7 @@
use App\Models\SubscriptionItem;
use App\Models\User;
use App\Models\Workspace;
use App\Models\WorkspaceInvite;
use App\Models\WorkspaceLabel;
use App\Models\WorkspaceSignature;
use App\Services\PostTemplate\Registry as PostTemplateRegistry;
@ -149,11 +151,12 @@ protected function configureMorphMap(): void
Relation::enforceMorphMap([
'account' => Account::class,
'aiUsageLog' => AiUsageLog::class,
'apiToken' => ApiToken::class,
'invite' => Invite::class,
'media' => Media::class,
'notification' => Notification::class,
'plan' => Plan::class,
'notificationPreference' => NotificationPreference::class,
'plan' => Plan::class,
'post' => Post::class,
'postComment' => PostComment::class,
'postPlatform' => PostPlatform::class,
@ -162,8 +165,9 @@ protected function configureMorphMap(): void
'subscriptionItem' => SubscriptionItem::class,
'user' => User::class,
'workspace' => Workspace::class,
'workspaceSignature' => WorkspaceSignature::class,
'workspaceInvite' => WorkspaceInvite::class,
'workspaceLabel' => WorkspaceLabel::class,
'workspaceSignature' => WorkspaceSignature::class,
]);
}

View file

@ -3,6 +3,24 @@
return [
'title' => 'Billing',
'upgrade_dialog' => [
'title' => 'Upgrade your plan',
'description' => 'Pick a plan that fits your needs.',
'current_plan' => 'Current plan',
'current_short' => 'Current',
'current_badge' => 'Current',
'subscribe' => 'Subscribe',
'switch' => 'Switch to this plan',
'switch_short' => 'Switch',
'switch_to_yearly' => 'Switch to yearly',
'switch_to_monthly' => 'Switch to monthly',
'reasons' => [
'workspace_limit' => 'You\'ve reached the workspace limit on your current plan. Upgrade to create more workspaces.',
'social_account_limit' => 'You\'ve reached the social account limit on your current plan. Upgrade to connect more accounts.',
'member_limit' => 'You\'ve reached the team member limit on your current plan. Upgrade to invite more people.',
],
],
'subscribe' => [
'page_title' => 'Choose your plan',
'title' => 'Choose the right plan for you',
@ -62,6 +80,10 @@
'paid' => 'Paid',
],
'flash' => [
'plan_changed' => 'You are now on the :plan plan.',
],
'processing' => [
'page_title' => 'Processing...',
'title' => 'Processing your subscription',

View file

@ -54,4 +54,8 @@
],
'limit_reached' => 'You have reached your plan limit for workspaces.',
'flash' => [
'deleted' => 'Workspace deleted successfully.',
],
];

View file

@ -4,6 +4,24 @@
'title' => 'Suscripción',
'description' => 'Administra tu suscripción y método de pago',
'upgrade_dialog' => [
'title' => 'Actualiza tu plan',
'description' => 'Elige un plan que se adapte a tus necesidades.',
'current_plan' => 'Plan actual',
'current_short' => 'Actual',
'current_badge' => 'Actual',
'subscribe' => 'Suscribirse',
'switch' => 'Cambiar a este plan',
'switch_short' => 'Cambiar',
'switch_to_yearly' => 'Cambiar a anual',
'switch_to_monthly' => 'Cambiar a mensual',
'reasons' => [
'workspace_limit' => 'Has alcanzado el límite de workspaces de tu plan. Actualiza para crear más.',
'social_account_limit' => 'Has alcanzado el límite de cuentas sociales de tu plan. Actualiza para conectar más.',
'member_limit' => 'Has alcanzado el límite de miembros de tu plan. Actualiza para invitar a más personas.',
],
],
'subscribe' => [
'page_title' => 'Elige tu plan',
'title' => 'Elige el plan ideal para ti',
@ -56,6 +74,10 @@
'paid' => 'Pagado',
],
'flash' => [
'plan_changed' => 'Ahora estás en el plan :plan.',
],
'processing' => [
'page_title' => 'Procesando...',
'title' => 'Procesando tu suscripción',

View file

@ -54,4 +54,8 @@
],
'limit_reached' => 'Has alcanzado el límite de workspaces de tu plan.',
'flash' => [
'deleted' => 'Workspace eliminado correctamente.',
],
];

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -4,6 +4,24 @@
'title' => 'Assinatura',
'description' => 'Gerencie sua assinatura e método de pagamento',
'upgrade_dialog' => [
'title' => 'Faça upgrade do seu plano',
'description' => 'Escolha um plano que se encaixe nas suas necessidades.',
'current_plan' => 'Plano atual',
'current_short' => 'Atual',
'current_badge' => 'Atual',
'subscribe' => 'Assinar',
'switch' => 'Mudar para este plano',
'switch_short' => 'Mudar',
'switch_to_yearly' => 'Mudar para anual',
'switch_to_monthly' => 'Mudar para mensal',
'reasons' => [
'workspace_limit' => 'Você atingiu o limite de workspaces do seu plano. Faça upgrade pra criar mais.',
'social_account_limit' => 'Você atingiu o limite de contas sociais do seu plano. Faça upgrade pra conectar mais.',
'member_limit' => 'Você atingiu o limite de membros do seu plano. Faça upgrade pra convidar mais pessoas.',
],
],
'subscribe' => [
'page_title' => 'Escolha seu plano',
'title' => 'Escolha o plano ideal pra você',
@ -56,6 +74,10 @@
'paid' => 'Pago',
],
'flash' => [
'plan_changed' => 'Você está agora no plano :plan.',
],
'processing' => [
'page_title' => 'Processando...',
'title' => 'Processando sua assinatura',

View file

@ -54,4 +54,8 @@
],
'limit_reached' => 'Você atingiu o limite de workspaces do seu plano.',
'flash' => [
'deleted' => 'Workspace excluído com sucesso.',
],
];

View file

@ -9,9 +9,7 @@ import {
IconFileCheck,
IconFileText,
IconHash,
IconLifebuoy,
IconPhoto,
IconMessageCircle,
IconPencil,
IconPlus,
IconSettings,
@ -21,6 +19,8 @@ import { trans } from 'laravel-vue-i18n';
import { computed } from 'vue';
import { create as createPost, index as postsIndex } from '@/actions/App/Http/Controllers/App/PostController';
import { useFeatureAccess } from '@/composables/useFeatureAccess';
import { useUpgradeDialog } from '@/composables/useUpgradeDialog';
import NavMain from '@/components/NavMain.vue';
import NavUser from '@/components/NavUser.vue';
import { Avatar } from '@/components/ui/avatar';
@ -45,8 +45,8 @@ import {
} from '@/components/ui/sidebar';
import { accounts, analytics, calendar, settings as settingsHub } from '@/routes/app';
import { index as assets } from '@/routes/app/assets';
import { index as signatures } from '@/routes/app/signatures';
import { index as labels } from '@/routes/app/labels';
import { index as signatures } from '@/routes/app/signatures';
import { create as createWorkspaceRoute, switchMethod } from '@/routes/app/workspaces';
import type { NavItem } from '@/types';
@ -127,6 +127,17 @@ const switchWorkspace = (workspaceId: string) => {
preserveScroll: true,
});
};
const { canCreateWorkspace } = useFeatureAccess();
const { openUpgrade } = useUpgradeDialog();
const handleCreateWorkspace = () => {
if (!canCreateWorkspace.value) {
openUpgrade(trans('billing.upgrade_dialog.reasons.workspace_limit'));
return;
}
router.visit(createWorkspaceRoute.url());
};
</script>
<template>
@ -164,11 +175,9 @@ const switchWorkspace = (workspaceId: string) => {
</DropdownMenuItem>
</div>
<DropdownMenuSeparator />
<DropdownMenuItem as-child>
<Link :href="createWorkspaceRoute.url()">
<IconPlus class="size-4" />
{{ $t('sidebar.create_workspace') }}
</Link>
<DropdownMenuItem class="gap-2" @click="handleCreateWorkspace">
<IconPlus class="size-4" />
{{ $t('sidebar.create_workspace') }}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
@ -202,23 +211,6 @@ const switchWorkspace = (workspaceId: string) => {
</Link>
</SidebarMenuButton>
</SidebarMenuItem>
<SidebarMenuItem>
<SidebarMenuButton as-child :tooltip="trans('sidebar.support.share_feedback')">
<a href="https://github.com/trypost-it/trypost/discussions" target="_blank"
rel="noopener noreferrer">
<IconMessageCircle />
<span>{{ $t('sidebar.support.share_feedback') }}</span>
</a>
</SidebarMenuButton>
</SidebarMenuItem>
<SidebarMenuItem>
<SidebarMenuButton as-child :tooltip="trans('sidebar.support.docs')">
<a href="https://trypost.it/docs" target="_blank" rel="noopener noreferrer">
<IconLifebuoy />
<span>{{ $t('sidebar.support.docs') }}</span>
</a>
</SidebarMenuButton>
</SidebarMenuItem>
</SidebarMenu>
<NavUser />
</SidebarFooter>

View file

@ -1,46 +1,56 @@
<script setup lang="ts">
import { usePage } from '@inertiajs/vue3';
import { computed, onMounted, watch } from 'vue';
import { onMounted, watch } from 'vue';
import { toast } from 'vue-sonner';
import { Toaster } from '@/components/ui/sonner';
const page = usePage();
const style = computed(() => (page.props.flash as Record<string, string>)?.bannerStyle || 'success');
const message = computed(() => (page.props.flash as Record<string, string>)?.banner || '');
interface Flash {
banner?: string;
bannerStyle?: 'success' | 'danger' | 'warning' | 'info';
success?: string;
error?: string;
warning?: string;
info?: string;
}
const showToast = (msg: string) => {
switch (style.value) {
case 'success':
toast.success(msg);
break;
case 'danger':
toast.error(msg);
break;
case 'warning':
toast.warning(msg);
break;
case 'info':
toast.info(msg);
break;
default:
toast(msg);
const page = usePage();
const showFlash = (flash: Flash | undefined) => {
if (!flash) return;
if (flash.banner) {
switch (flash.bannerStyle) {
case 'danger':
toast.error(flash.banner);
break;
case 'warning':
toast.warning(flash.banner);
break;
case 'info':
toast.info(flash.banner);
break;
case 'success':
default:
toast.success(flash.banner);
}
}
if (flash.success) toast.success(flash.success);
if (flash.error) toast.error(flash.error);
if (flash.warning) toast.warning(flash.warning);
if (flash.info) toast.info(flash.info);
};
// Show flash on initial page load (after Toaster is mounted)
onMounted(() => {
if (message.value) {
showToast(message.value);
}
showFlash(page.props.flash as Flash | undefined);
});
// Show flash on SPA navigation (Inertia visits)
watch(() => page.props.flash, () => {
if (message.value) {
showToast(message.value);
}
}, { deep: true });
watch(
() => page.props.flash,
(flash) => showFlash(flash as Flash | undefined),
{ deep: true },
);
</script>
<template>

View file

@ -0,0 +1,178 @@
<script setup lang="ts">
import { router, usePage } from '@inertiajs/vue3';
import { IconCheck } from '@tabler/icons-vue';
import { trans } from 'laravel-vue-i18n';
import { computed, ref, watch } from 'vue';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogDescription, DialogTitle } from '@/components/ui/dialog';
import { Switch } from '@/components/ui/switch';
import { useUpgradeDialog } from '@/composables/useUpgradeDialog';
import { checkout, swap } from '@/routes/app/billing';
interface Plan {
id: string;
slug: string;
name: string;
stripe_monthly_price_id: string | null;
stripe_yearly_price_id: string | null;
social_account_limit: number;
member_limit: number;
workspace_limit: number;
ai_images_limit: number;
}
const { open, reason, closeUpgrade } = useUpgradeDialog();
const page = usePage();
const plans = computed<Plan[]>(() => (page.props.plans as Plan[]) ?? []);
const currentPlan = computed<Plan | null>(() => (page.props.auth as { plan: Plan | null }).plan ?? null);
const currentPriceId = computed<string | null>(() => (page.props.auth as { currentPriceId?: string | null }).currentPriceId ?? null);
const hasActiveSubscription = computed<boolean>(() => Boolean((page.props.auth as { hasActiveSubscription?: boolean }).hasActiveSubscription));
const isOnYearly = computed(() => {
if (!currentPriceId.value || !currentPlan.value) return false;
return currentPriceId.value === currentPlan.value.stripe_yearly_price_id;
});
const isYearly = ref(false);
const processing = ref<string | null>(null);
watch(open, (isOpen) => {
if (isOpen) {
isYearly.value = isOnYearly.value;
}
});
const getPrice = (plan: Plan): string => {
const key = `billing.subscribe.prices.${plan.slug}.${isYearly.value ? 'yearly' : 'monthly'}`;
return trans(key);
};
const isSamePlan = (plan: Plan): boolean => currentPlan.value?.id === plan.id;
const isCurrent = (plan: Plan): boolean => {
if (!isSamePlan(plan)) return false;
return isYearly.value === isOnYearly.value;
};
const isPopular = (plan: Plan): boolean => plan.slug === 'pro';
const features = (plan: Plan): string[] => [
trans('billing.subscribe.features.social_accounts', { count: String(plan.social_account_limit) }),
trans('billing.subscribe.features.workspaces', { count: String(plan.workspace_limit) }),
trans('billing.subscribe.features.members', { count: String(plan.member_limit) }),
trans('billing.subscribe.features.ai_images', { count: String(plan.ai_images_limit) }),
];
const ctaLabel = (plan: Plan): string => {
if (isCurrent(plan)) return trans('billing.upgrade_dialog.current_plan');
if (isSamePlan(plan)) {
return isYearly.value
? trans('billing.upgrade_dialog.switch_to_yearly')
: trans('billing.upgrade_dialog.switch_to_monthly');
}
if (hasActiveSubscription.value) return trans('billing.upgrade_dialog.switch');
return trans('billing.upgrade_dialog.subscribe');
};
const handleSelect = (plan: Plan) => {
if (isCurrent(plan)) return;
processing.value = plan.id;
const priceId = isYearly.value ? plan.stripe_yearly_price_id : plan.stripe_monthly_price_id;
const url = hasActiveSubscription.value ? swap.url(plan.id) : checkout.url(plan.id);
router.post(url, { price_id: priceId }, {
onSuccess: () => {
closeUpgrade();
},
onFinish: () => {
processing.value = null;
},
});
};
const onOpenChange = (value: boolean) => {
if (!value) closeUpgrade();
};
</script>
<template>
<Dialog :open="open" @update:open="onOpenChange">
<DialogContent class="w-[95vw] gap-0 p-0 sm:max-w-4xl">
<div class="px-6 pt-6 pb-4">
<DialogTitle class="text-2xl font-semibold">
{{ $t('billing.upgrade_dialog.title') }}
</DialogTitle>
<DialogDescription class="mt-1">
{{ reason ?? $t('billing.upgrade_dialog.description') }}
</DialogDescription>
</div>
<div v-if="!isOnYearly" class="border-t px-6 py-4">
<div class="flex items-center justify-center gap-3">
<span class="text-sm" :class="!isYearly ? 'font-medium' : 'text-muted-foreground'">
{{ $t('billing.subscribe.monthly') }}
</span>
<Switch v-model="isYearly" />
<span class="flex items-center gap-2 text-sm" :class="isYearly ? 'font-medium' : 'text-muted-foreground'">
{{ $t('billing.subscribe.yearly') }}
<Badge variant="secondary" class="whitespace-nowrap">
{{ $t('billing.subscribe.save_months') }}
</Badge>
</span>
</div>
</div>
<div class="grid grid-cols-1 gap-4 border-t px-6 pt-8 pb-6 sm:grid-cols-2 lg:grid-cols-4">
<div
v-for="plan in plans"
:key="plan.id"
class="relative flex flex-col rounded-xl border bg-card p-5"
:class="[
isPopular(plan) ? 'border-primary ring-1 ring-primary' : '',
isCurrent(plan) && !isPopular(plan) ? 'border-foreground/40' : '',
]"
>
<Badge v-if="isPopular(plan)" class="absolute -top-3 left-1/2 -translate-x-1/2 whitespace-nowrap">
{{ $t('billing.subscribe.popular') }}
</Badge>
<Badge v-else-if="isCurrent(plan)" variant="secondary" class="absolute -top-3 left-1/2 -translate-x-1/2 whitespace-nowrap">
{{ $t('billing.upgrade_dialog.current_badge') }}
</Badge>
<h3 class="text-lg font-semibold">{{ plan.name }}</h3>
<div class="mt-2 flex items-baseline gap-1">
<span class="text-3xl font-bold tracking-tight">{{ getPrice(plan) }}</span>
<span class="text-sm text-muted-foreground">
/{{ isYearly ? $t('billing.subscribe.per_year') : $t('billing.subscribe.per_month') }}
</span>
</div>
<ul class="my-5 flex-1 space-y-2">
<li
v-for="feature in features(plan)"
:key="feature"
class="flex items-start gap-2 text-sm"
>
<IconCheck class="mt-0.5 size-4 shrink-0 text-primary" />
<span>{{ feature }}</span>
</li>
</ul>
<Button
class="w-full"
:variant="isCurrent(plan) ? 'secondary' : isPopular(plan) ? 'default' : 'outline'"
:loading="processing === plan.id"
:disabled="(processing !== null && processing !== plan.id) || isCurrent(plan)"
@click="handleSelect(plan)"
>
{{ ctaLabel(plan) }}
</Button>
</div>
</div>
</DialogContent>
</Dialog>
</template>

View file

@ -4,7 +4,9 @@ import {
IconBrightnessUp,
IconDeviceDesktop,
IconLanguage,
IconLifebuoy,
IconLogout,
IconMessageCircle,
IconMoon,
IconUser,
} from '@tabler/icons-vue';
@ -144,6 +146,31 @@ const handleLogout = () => {
</DropdownMenuSub>
</DropdownMenuGroup>
<DropdownMenuSeparator />
<DropdownMenuGroup>
<DropdownMenuItem :as-child="true">
<a
class="block w-full cursor-pointer"
href="https://github.com/trypost-it/trypost/discussions"
target="_blank"
rel="noopener noreferrer"
>
<IconMessageCircle class="size-4" />
{{ $t('sidebar.support.share_feedback') }}
</a>
</DropdownMenuItem>
<DropdownMenuItem :as-child="true">
<a
class="block w-full cursor-pointer"
href="https://trypost.it/docs"
target="_blank"
rel="noopener noreferrer"
>
<IconLifebuoy class="size-4" />
{{ $t('sidebar.support.docs') }}
</a>
</DropdownMenuItem>
</DropdownMenuGroup>
<DropdownMenuSeparator />
<DropdownMenuItem :as-child="true">
<Link
class="block w-full cursor-pointer"

View file

@ -1,6 +1,7 @@
<script setup lang="ts">
import { router } from '@inertiajs/vue3';
import { IconClock, IconDots, IconShield, IconTrash, IconUser } from '@tabler/icons-vue';
import { trans } from 'laravel-vue-i18n';
import { ref } from 'vue';
import ConfirmDeleteModal from '@/components/ConfirmDeleteModal.vue';
@ -22,6 +23,8 @@ import {
TableHeader,
TableRow,
} from '@/components/ui/table';
import { useFeatureAccess } from '@/composables/useFeatureAccess';
import { useUpgradeDialog } from '@/composables/useUpgradeDialog';
import { WorkspaceRole } from '@/enums/workspace-role';
import { destroy as destroyInvite } from '@/routes/app/invites';
import { remove as removeMemberRoute, updateRole } from '@/routes/app/members';
@ -48,6 +51,17 @@ const inviteDialogOpen = ref(false);
const removeMemberModal = ref<InstanceType<typeof ConfirmDeleteModal> | null>(null);
const cancelInvitationModal = ref<InstanceType<typeof ConfirmDeleteModal> | null>(null);
const { canInviteMember } = useFeatureAccess();
const { openUpgrade } = useUpgradeDialog();
const handleInviteClick = () => {
if (!canInviteMember.value) {
openUpgrade(trans('billing.upgrade_dialog.reasons.member_limit'));
return;
}
inviteDialogOpen.value = true;
};
const changeRole = (member: Member, role: string) => {
router.put(updateRole.url(member.id), { role });
};
@ -61,7 +75,7 @@ const changeRole = (member: Member, role: string) => {
:description="$t('settings.workspace.members_description')"
/>
<Button variant="secondary" @click="inviteDialogOpen = true">
<Button variant="secondary" @click="handleInviteClick">
{{ $t('settings.members.invite.submit') }}
</Button>
</div>

View file

@ -5,11 +5,13 @@ import type { ButtonVariants } from "."
import { Primitive } from "reka-ui"
import { cn } from "@/lib/utils"
import { buttonVariants } from "."
import { IconLoader } from "@tabler/icons-vue"
interface Props extends PrimitiveProps {
variant?: ButtonVariants["variant"]
size?: ButtonVariants["size"]
class?: HTMLAttributes["class"]
loading?: boolean
}
const props = withDefaults(defineProps<Props>(), {
@ -18,12 +20,10 @@ const props = withDefaults(defineProps<Props>(), {
</script>
<template>
<Primitive
data-slot="button"
:as="as"
:as-child="asChild"
:class="cn(buttonVariants({ variant, size }), props.class)"
>
<slot />
<Primitive data-slot="button" :as="as" :as-child="asChild"
:class="cn(buttonVariants({ variant, size }), props.class, { 'opacity-25 cursor-not-allowed': loading })"
:disabled="loading">
<IconLoader v-if="loading" class="size-5 mx-4 animate-spin" />
<slot v-else />
</Primitive>
</template>

View file

@ -0,0 +1,68 @@
import { usePage } from '@inertiajs/vue3';
import { computed } from 'vue';
interface Plan {
id: string;
slug: string;
name: string;
}
interface Usage {
workspaceCount: number;
socialAccountCount: number;
memberCount: number;
pendingInviteCount: number;
}
interface Features {
workspaceLimit: number;
socialAccountLimit: number;
memberLimit: number;
aiImagesLimit: number;
}
export const useFeatureAccess = () => {
const page = usePage();
const isSelfHosted = computed(() => page.props.selfHosted as boolean);
const plan = computed<Plan | null>(() => (page.props.auth as { plan: Plan | null }).plan ?? null);
const usage = computed<Usage | null>(() => (page.props.usage as Usage | null) ?? null);
const features = computed<Features | null>(() => (page.props.features as Features | null) ?? null);
const workspaceLimit = computed(() => features.value?.workspaceLimit ?? 1);
const socialAccountLimit = computed(() => features.value?.socialAccountLimit ?? 1);
const memberLimit = computed(() => features.value?.memberLimit ?? 1);
const aiImagesLimit = computed(() => features.value?.aiImagesLimit ?? 0);
const canCreateWorkspace = computed(() => {
if (isSelfHosted.value) return true;
if (!usage.value) return true;
return usage.value.workspaceCount < workspaceLimit.value;
});
const canConnectSocialAccount = computed(() => {
if (isSelfHosted.value) return true;
if (!usage.value) return true;
return usage.value.socialAccountCount < socialAccountLimit.value;
});
const canInviteMember = computed(() => {
if (isSelfHosted.value) return true;
if (!usage.value) return true;
return usage.value.memberCount + usage.value.pendingInviteCount < memberLimit.value;
});
return {
plan,
usage,
features,
isSelfHosted,
workspaceLimit,
socialAccountLimit,
memberLimit,
aiImagesLimit,
canCreateWorkspace,
canConnectSocialAccount,
canInviteMember,
};
};

View file

@ -0,0 +1,17 @@
import { ref } from 'vue';
const open = ref(false);
const reason = ref<string | null>(null);
export const useUpgradeDialog = () => ({
open,
reason,
openUpgrade: (cause?: string) => {
reason.value = cause ?? null;
open.value = true;
},
closeUpgrade: () => {
open.value = false;
reason.value = null;
},
});

View file

@ -3,6 +3,7 @@ import { useHttp, usePage } from '@inertiajs/vue3';
import { onBeforeUnmount, onMounted } from 'vue';
import AppHeader from '@/components/AppHeader.vue';
import UpgradeDialog from '@/components/UpgradeDialog.vue';
import AppSidebar from '@/components/AppSidebar.vue';
import Toast from '@/components/Toast.vue';
import { SidebarInset, SidebarProvider } from '@/components/ui/sidebar';
@ -78,5 +79,6 @@ onBeforeUnmount(() => {
</div>
</SidebarInset>
</SidebarProvider>
<UpgradeDialog />
<Toast />
</template>

View file

@ -38,7 +38,9 @@ import {
TableLoadMore,
TableRow,
} from '@/components/ui/table';
import { useFeatureAccess } from '@/composables/useFeatureAccess';
import { getPlatformLabel, getPlatformLogo } from '@/composables/usePlatformLogo';
import { useUpgradeDialog } from '@/composables/useUpgradeDialog';
import date from '@/date';
import debounce from '@/debounce';
import AppLayout from '@/layouts/AppLayout.vue';
@ -79,6 +81,17 @@ const isAddDialogOpen = ref(false);
const deleteModal = ref<InstanceType<typeof ConfirmDeleteModal> | null>(null);
const searchQuery = ref(props.filters.search);
const { canConnectSocialAccount } = useFeatureAccess();
const { openUpgrade } = useUpgradeDialog();
const handleAddClick = () => {
if (!canConnectSocialAccount.value) {
openUpgrade(trans('billing.upgrade_dialog.reasons.social_account_limit'));
return;
}
isAddDialogOpen.value = true;
};
const search = debounce(() => {
router.get(
accountsIndex.url(),
@ -129,7 +142,7 @@ const handleDisconnect = (accountId: string) => {
/>
</div>
<Button @click="isAddDialogOpen = true">
<Button @click="handleAddClick">
{{ $t('accounts.add_social') }}
</Button>
</div>

View file

@ -15,10 +15,16 @@ import YouTubeAnalytics from '@/components/analytics/YouTubeAnalytics.vue';
import { DateRangePicker } from '@/components/ui/date-range-picker';
import dayjs from '@/dayjs';
import AppLayout from '@/layouts/AppLayout.vue';
import type { BreadcrumbItem } from '@/types';
const props = defineProps<{
accounts: AnalyticsAccount[];
}>();
const breadcrumbs = computed<BreadcrumbItem[]>(() => [
{ title: trans('sidebar.analytics') },
]);
const selectedAccountId = ref<string | null>(props.accounts[0]?.id ?? null);
const dateRange = ref({
@ -37,7 +43,7 @@ const platformSupportsDateRange = computed(() => {
</script>
<template>
<AppLayout :title="$t('sidebar.analytics')" :full-width="true">
<AppLayout :breadcrumbs="breadcrumbs" :full-width="true">
<template #header-actions>
<DateRangePicker v-if="platformSupportsDateRange" v-model="dateRange" />
</template>

View file

@ -132,10 +132,12 @@
]);
// Starter plan: workspace_limit = 1; the user already owns 1 workspace (from beforeEach).
$response = $this->actingAs($this->user)->get(route('app.workspaces.create'));
$response = $this->actingAs($this->user)
->from(route('app.calendar'))
->get(route('app.workspaces.create'));
$response->assertRedirect(route('app.calendar'))
->assertSessionHas('error', __('workspaces.limit_reached'));
->assertSessionHas('flash.error', __('workspaces.limit_reached'));
});
test('create workspace is allowed when below plan limit in saas mode', function () {