Beautiful Open-Source Form Builder
Add yearly subscription upgrade functionality (#999)
Chirag Chhatrala2a5e51c5be64
diff --git a/api/app/Http/Controllers/SubscriptionController.php b/api/app/Http/Controllers/SubscriptionController.phpindex f3e9ca225..e6302bfbc 100644--- a/api/app/Http/Controllers/SubscriptionController.php+++ b/api/app/Http/Controllers/SubscriptionController.php@@ -3,10 +3,11 @@namespace App\Http\Controllers;use App\Http\Requests\Subscriptions\UpdateStripeDetailsRequest;+use App\Models\Workspace;use App\Service\BillingHelper;use App\Service\UserHelper;+use Illuminate\Http\Request;use Illuminate\Support\Facades\Auth;-use Laravel\Cashier\Subscription;class SubscriptionController extends Controller{@@ -103,4 +104,54 @@ class SubscriptionController extends Controller'portal_url' => Auth::user()->billingPortalUrl(front_url('/home')),]);}++ public function upgradeToYearly(Request $request)+ {+ $request->validate([+ 'workspace_id' => 'required|exists:workspaces,id',+ ]);++ $user = Auth::user();+ if (!$user->is_subscribed) {+ return $this->error([+ "message" => "Please subscribe before upgrading to yearly plan.",+ ]);+ }++ $workspace = Workspace::findOrFail($request->get("workspace_id"));+ if (!$workspace->isAdminUser($user)) {+ return $this->error([+ "message" => "Please ask an admin to upgrade the workspace to yearly plan.",+ ]);+ }++ // Verify the user's subscription is actually tied to this workspace (user must be an owner)+ if (!$workspace->owners()->where('users.id', $user->id)->exists()) {+ return $this->error([+ "message" => "You must be an owner of this workspace to upgrade its subscription.",+ ]);+ }++ if ($workspace->is_yearly_plan) {+ return $this->error([+ "message" => "The workspace is already on yearly plan.",+ ]);+ }++ // Upgrade the subscription to yearly plan+ try {+ $subscription = $user->subscription();+ $yearlyPriceId = BillingHelper::getPricing('default')['yearly'];+ $subscription->swap($yearlyPriceId);++ // Invalidate cached is_yearly_plan attribute+ $workspace->forgetCachedAttribute('is_yearly_plan');+ } catch (\Exception $e) {+ return $this->error([+ "message" => $e?->getMessage() ?? "Failed to upgrade the subscription to yearly plan.",+ ]);+ }++ return $this->success(['message' => 'Congratulations! Your plan has been upgraded to yearly.']);+ }}diff --git a/api/app/Models/Workspace.php b/api/app/Models/Workspace.phpindex 7ea432723..a5cd359ac 100644--- a/api/app/Models/Workspace.php+++ b/api/app/Models/Workspace.php@@ -5,6 +5,7 @@ namespace App\Models;use App\Models\Forms\Form;use App\Models\Traits\CachableAttributes;use App\Models\Traits\CachesAttributes;+use App\Service\BillingHelper;use Illuminate\Database\Eloquent\Factories\HasFactory;use Illuminate\Database\Eloquent\Model;use Illuminate\Support\Collection;@@ -37,6 +38,7 @@ class Workspace extends Model implements CachableAttributes'is_trialing','is_enterprise','users_count',+ 'is_yearly_plan',];protected function casts(): array@@ -52,6 +54,7 @@ class Workspace extends Model implements CachableAttributes'is_trialing','is_enterprise','is_risky',+ 'is_yearly_plan','submissions_count','max_file_size','custom_domain_count',@@ -182,6 +185,30 @@ class Workspace extends Model implements CachableAttributes});}+ public function getIsYearlyPlanAttribute()+ {+ if (!pricing_enabled()) {+ return false;+ }++ return $this->remember('is_yearly_plan', 15 * 60, function (): bool {+ $owners = $this->relationLoaded('users')+ ? $this->users->where('pivot.role', 'admin')+ : $this->owners()->get();++ foreach ($owners as $owner) {+ if ($owner->is_subscribed) {+ $subscription = $owner->subscription();+ if ($subscription && BillingHelper::getSubscriptionInterval($subscription) === 'yearly') {+ return true;+ }+ }+ }++ return false;+ });+ }+public function getSubmissionsCountAttribute(){return $this->remember('submissions_count', 15 * 60, function (): int {diff --git a/api/app/Service/BillingHelper.php b/api/app/Service/BillingHelper.phpindex c872c431c..fea15cdb4 100644--- a/api/app/Service/BillingHelper.php+++ b/api/app/Service/BillingHelper.php@@ -3,6 +3,7 @@namespace App\Service;use Illuminate\Support\Facades\App;+use Laravel\Cashier\Subscription;use Stripe\SubscriptionItem;class BillingHelper@@ -24,6 +25,33 @@ class BillingHelperpublic static function getLineItemInterval(SubscriptionItem $item){return $item->price->recurring->interval === 'year' ? 'yearly' : 'monthly';- ;+ }++ public static function getSubscriptionInterval(Subscription $subscription)+ {+ try {+ $stripeSub = $subscription->asStripeSubscription();+ $lineItems = collect($stripeSub->items);+ $productId = self::getProductId('default');++ if (!$productId) {+ return null;+ }++ // Find the main subscription line item for the default product+ $mainItem = $lineItems->first(function ($lineItem) use ($productId) {+ return $lineItem->price->product === $productId;+ });++ if (!$mainItem) {+ return null;+ }++ // Check the actual billing interval from Stripe+ return self::getLineItemInterval($mainItem);+ } catch (\Exception $e) {+ // If we can't fetch from Stripe, fall back to false+ return null;+ }}}diff --git a/api/database/migrations/2025_12_29_093413_add_metered_billing_columns_to_subscription_items_table.php b/api/database/migrations/2025_12_29_093413_add_metered_billing_columns_to_subscription_items_table.phpnew file mode 100644index 000000000..628d2b84c--- /dev/null+++ b/api/database/migrations/2025_12_29_093413_add_metered_billing_columns_to_subscription_items_table.php@@ -0,0 +1,28 @@+<?php++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('subscription_items', function (Blueprint $table) {+ $table->string('meter_id')->nullable();+ $table->string('meter_event_name')->nullable();+ });+ }++ /**+ * Reverse the migrations.+ */+ public function down(): void+ {+ Schema::table('subscription_items', function (Blueprint $table) {+ $table->dropColumn(['meter_id', 'meter_event_name']);+ });+ }+};diff --git a/api/routes/api.php b/api/routes/api.phpindex 9f3222de6..dad74f349 100644--- a/api/routes/api.php+++ b/api/routes/api.php@@ -86,6 +86,7 @@ Route::group(['middleware' => 'auth.multi'], function () {->where('plan', '(' . implode('|', SubscriptionController::SUBSCRIPTION_PLANS) . ')');Route::get('/billing-portal', [SubscriptionController::class, 'billingPortal'])->name('billing-portal');Route::get('/users-count', [SubscriptionController::class, 'getUsersCount'])->name('users-count');+ Route::post('/upgrade-to-yearly', [SubscriptionController::class, 'upgradeToYearly'])->name('upgrade-to-yearly');});Route::prefix('open')->name('open.')->group(function () {diff --git a/client/components/global/YearlyUpgradeModal.vue b/client/components/global/YearlyUpgradeModal.vuenew file mode 100644index 000000000..0ed5c6ff1--- /dev/null+++ b/client/components/global/YearlyUpgradeModal.vue@@ -0,0 +1,287 @@+<template>+ <UModal+ v-model:open="isModalOpen"+ :close="false"+ :dismissible="false"+ :ui="{ content: 'sm:max-w-2xl' }"+ >+ <template #body>+ <div class="text-center py-2">+ <Transition+ appear+ enter-active-class="transition-all duration-500 ease-out"+ enter-from-class="opacity-0 scale-75 -translate-y-4"+ enter-to-class="opacity-100 scale-100 translate-y-0"+ >+ <div+ class="inline-flex items-center gap-1.5 bg-gradient-to-r from-green-100 to-emerald-100 text-green-700 px-4 py-1.5 rounded-full text-xs font-semibold mb-6 shadow-sm border border-green-200/50 animate-pulse-subtle"+ >+ <Icon name="mdi:gift" class="w-4 h-4 animate-bounce-subtle" />+ <span>Special Offer</span>+ </div>+ </Transition>++ <Transition+ appear+ enter-active-class="transition-all duration-600 ease-out delay-100"+ enter-from-class="opacity-0 translate-y-4"+ enter-to-class="opacity-100 translate-y-0"+ >+ <h2+ class="text-3xl font-bold text-neutral-900 mb-3"+ >+ Upgrade to <span class="text-primary bg-gradient-to-r bg-clip-text">Yearly</span> and Save Big+ </h2>+ </Transition>++ <Transition+ appear+ enter-active-class="transition-all duration-600 ease-out delay-200"+ enter-from-class="opacity-0 translate-y-4"+ enter-to-class="opacity-100 translate-y-0"+ >+ <p+ class="text-sm text-neutral-600 mb-8"+ >+ Get <span class="text-primary font-bold">2 months for free</span> when you switch to annual billing+ </p>+ </Transition>++ <Transition+ appear+ enter-active-class="transition-all duration-700 ease-out delay-300"+ enter-from-class="opacity-0 scale-95"+ enter-to-class="opacity-100 scale-100"+ >+ <div+ class="flex items-center justify-center gap-8 mb-8 pb-8 border-b border-neutral-200"+ >+ <div class="text-center transform transition-all duration-300 hover:scale-105">+ <p class="text-neutral-500 mb-2 text-sm">Monthly plan</p>+ <p class="text-3xl font-semibold text-neutral-900">$19<span class="text-lg">/month</span></p>+ </div>++ <div class="h-16 w-px bg-gradient-to-b from-transparent via-neutral-200 to-transparent"></div>++ <div class="text-center transform transition-all duration-300 hover:scale-105 relative">+ <div class="absolute -top-4 -right-2 bg-green-500 text-white text-[10px] font-bold px-2 py-0.5 rounded-full animate-bounce-subtle">+ BEST+ </div>+ <p class="text-primary mb-2 text-sm font-medium">Yearly plan</p>+ <p class="text-4xl font-bold text-primary bg-gradient-to-r bg-clip-text">$16<span class="text-lg">/month</span></p>+ <p class="text-xs text-neutral-500 mt-1">$192 billed annually</p>+ </div>+ </div>+ </Transition>++ <div class="w-1/2 mx-auto">+ <div class="space-y-3 mb-8 text-left max-w-md mx-auto">+ <TransitionGroup+ appear+ enter-active-class="transition-all duration-500 ease-out"+ enter-from-class="opacity-0 translate-x-[-20px]"+ enter-to-class="opacity-100 translate-x-0"+ tag="div"+ >+ <div+ v-for="(benefit, index) in benefits"+ :key="benefit"+ :style="{ transitionDelay: `${400 + index * 100}ms` }"+ class="flex items-center gap-3 group"+ >+ <div class="relative">+ <Icon+ name="heroicons:check-circle"+ class="w-5 h-5 text-primary flex-shrink-0 transform transition-all duration-300 group-hover:scale-110"+ />+ <div class="absolute inset-0 bg-primary/20 rounded-full blur-md opacity-0 group-hover:opacity-50 transition-opacity duration-300"></div>+ </div>+ <span class="text-sm text-neutral-700 font-medium">{{ benefit }}</span>+ </div>+ </TransitionGroup>+ </div>++ <Transition+ appear+ enter-active-class="transition-all duration-600 ease-out delay-700"+ enter-from-class="opacity-0 translate-y-6 scale-95"+ enter-to-class="opacity-100 translate-y-0 scale-100"+ >+ <div class="mb-2">+ <UButton+ color="primary"+ size="lg"+ class="transform transition-all duration-300 hover:scale-105 hover:shadow-lg shadow-md"+ trailing-icon="i-heroicons-arrow-right"+ :loading="loading"+ @click="handleUpgrade"+ >+ Upgrade to Yearly Now+ </UButton>+ </div>+ </Transition>++ <Transition+ appear+ enter-active-class="transition-all duration-500 ease-out delay-800"+ enter-from-class="opacity-0"+ enter-to-class="opacity-100"+ >+ <p+ class="text-xs text-neutral-500 mb-2"+ >+ By clicking, you'll be charged <span class="font-bold">$192 annually</span>.+ </p>+ </Transition>+ </div>+ </div>+ </template>+ <template #footer>+ <Transition+ appear+ enter-active-class="transition-all duration-400 ease-out delay-900"+ enter-from-class="opacity-0"+ enter-to-class="opacity-100"+ >+ <div class="flex justify-end w-full">+ <UButton+ color="neutral"+ variant="link"+ class="underline transition-colors duration-200 hover:text-neutral-700"+ :loading="loading"+ @click="closeModal"+ >+ No thanks+ </UButton>+ </div>+ </Transition>+ </template>+ </UModal>+</template>++<script setup>+import { useStorage } from '@vueuse/core'++const amplitude = useAmplitude()+const auth = useAuth()+const { data: user } = auth.user()+const { current: workspace } = useCurrentWorkspace()++const alert = useAlert()+const loading = ref(false)+const upgradeForm = useForm({})++// Use VueUse's useStorage for reactive localStorage+const lastShownDate = useStorage(+ 'yearly_upgrade_modal_last_shown',+ null,+ import.meta.server ? undefined : localStorage+)++// Check if enough time has passed since last shown (non-reactive check)+const hasEnoughTimePassed = () => {+ if (!import.meta.client) return false+ if (!lastShownDate.value) return true // Never shown before++ const lastShown = new Date(lastShownDate.value)+ const now = new Date()+ const daysSinceLastShown = Math.floor((now - lastShown) / (1000 * 60 * 60 * 24))++ // Show if 30 days (1 month) have passed+ return daysSinceLastShown >= 30+}++// Helper function to save the current date when modal is shown+const markModalAsShown = () => {+ lastShownDate.value = new Date().toISOString()+}++// Determine if user is eligible for the modal (without time check)+const isSelfHosted = computed(() => useFeatureFlag('self_hosted'))+const isEligibleForModal = computed(() => {+ return import.meta.client &&+ !isSelfHosted.value &&+ workspace.value?.is_admin &&+ workspace.value?.is_pro &&+ !workspace.value?.is_yearly_plan+})++// Modal state - controlled internally+const isModalOpen = ref(false)++// Watch for eligibility - check time only once when becoming eligible+watch(isEligibleForModal, (isEligible) => {+ if (isEligible && hasEnoughTimePassed()) {+ isModalOpen.value = true+ markModalAsShown()+ amplitude.logEvent('yearly_upgrade_modal_viewed', {+ user_id: user.value?.id,+ })+ }+}, { immediate: true })++const benefits = [+ 'Save 20% compared to monthly billing',+ 'Lock in current pricing for a full year',+ 'Keep access to the same features'+]++const closeModal = () => {+ isModalOpen.value = false+}++const handleUpgrade = async () => {+ loading.value = true+ amplitude.logEvent('yearly_upgrade_button_clicked', {+ user_id: user.value?.id,+ })+ // Set workspace_id at call time to ensure it's current+ upgradeForm.workspace_id = workspace.value?.id+ upgradeForm.post('/subscription/upgrade-to-yearly').then(async (response) => {+ alert.success(response.message)++ // Refetch the user+ await auth.invalidateUser()++ loading.value = false+ closeModal()+ }).catch((error) => {+ loading.value = false+ let message = error.data?.message || 'Failed to upgrade to yearly plan. Please try again later.'+ let actions = [{+ label: 'Manage Billing',+ icon: 'i-heroicons-arrow-top-right-on-square',+ onclick: () => { window.open('/home?user-settings=billing', '_blank') }+ }]+ alert.error(message, 10000, { actions })+ })+}+</script>++<style scoped>+@keyframes pulse-subtle {+ 0%, 100% {+ opacity: 1;+ }+ 50% {+ opacity: 0.8;+ }+}++@keyframes bounce-subtle {+ 0%, 100% {+ transform: translateY(0);+ }+ 50% {+ transform: translateY(-3px);+ }+}++.animate-pulse-subtle {+ animation: pulse-subtle 2s ease-in-out infinite;+}++.animate-bounce-subtle {+ animation: bounce-subtle 2s ease-in-out infinite;+}+</style>\ No newline at end of filediff --git a/client/pages/home.vue b/client/pages/home.vueindex 9431e510b..beec96257 100644--- a/client/pages/home.vue+++ b/client/pages/home.vue@@ -125,6 +125,8 @@</div></div><div id="home-portals" class="z-20" />++ <YearlyUpgradeModal /></div></template>