Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
fix: Onboarding / redirect fixes for payment (webhooks)
Richie McIlroy2b8c404aa04d
diff --git a/apps/web/app/api/settings/billing/subscribe/route.ts b/apps/web/app/api/settings/billing/subscribe/route.tsindex 52da04f9d..bc56d8d44 100644--- a/apps/web/app/api/settings/billing/subscribe/route.ts+++ b/apps/web/app/api/settings/billing/subscribe/route.ts@@ -6,90 +6,89 @@ import { db } from "@cap/database";import { users } from "@cap/database/schema";export async function POST(request: NextRequest) {+ console.log("Starting subscription process");const user = await getCurrentUser();let customerId = user?.stripeCustomerId;const { priceId } = await request.json();+ console.log("Received request with priceId:", priceId);+ console.log("Current user:", user?.id);+if (!priceId) {console.error("Price ID not found");-return new Response(JSON.stringify({ error: true }), {status: 400,- headers: {- "Content-Type": "application/json",- },+ headers: { "Content-Type": "application/json" },});}if (!user) {console.error("User not found");-return new Response(JSON.stringify({ error: true, auth: false }), {status: 401,- headers: {- "Content-Type": "application/json",- },+ headers: { "Content-Type": "application/json" },});}-- if (- isUserOnProPlan({- subscriptionStatus: user.stripeSubscriptionStatus as string,- })- ) {++ if (isUserOnProPlan({ subscriptionStatus: user.stripeSubscriptionStatus as string })) {+ console.error("User already has pro plan");return new Response(JSON.stringify({ error: true, subscription: true }), {status: 400,- headers: {- "Content-Type": "application/json",- },+ headers: { "Content-Type": "application/json" },});}- if (!user.stripeCustomerId) {- const customer = await stripe.customers.create({- email: user.email,- metadata: {- userId: user.id,- },- });+ try {+ if (!user.stripeCustomerId) {+ console.log("Creating new Stripe customer for user:", user.id);+ const customer = await stripe.customers.create({+ email: user.email,+ metadata: {+ userId: user.id,+ },+ });- await db- .update(users)- .set({- stripeCustomerId: customer.id,- })- .where(eq(users.id, user.id));+ console.log("Created Stripe customer:", customer.id);- customerId = customer.id;- }+ await db+ .update(users)+ .set({+ stripeCustomerId: customer.id,+ })+ .where(eq(users.id, user.id));- const checkoutSession = await stripe.checkout.sessions.create({- customer: customerId as string,- line_items: [- {- price: priceId,- quantity: 1,- },- ],- mode: "subscription",- success_url: `${process.env.NEXT_PUBLIC_URL}/dashboard/caps?upgrade=true`,- cancel_url: `${process.env.NEXT_PUBLIC_URL}/pricing`,- allow_promotion_codes: true,- });+ console.log("Updated user with Stripe customer ID");+ customerId = customer.id;+ }- if (checkoutSession.url) {- return new Response(JSON.stringify({ url: checkoutSession.url }), {- status: 200,- headers: {- "Content-Type": "application/json",- },+ console.log("Creating checkout session for customer:", customerId);+ const checkoutSession = await stripe.checkout.sessions.create({+ customer: customerId as string,+ line_items: [{ price: priceId, quantity: 1 }],+ mode: "subscription",+ success_url: `${process.env.NEXT_PUBLIC_URL}/dashboard/caps?upgrade=true`,+ cancel_url: `${process.env.NEXT_PUBLIC_URL}/pricing`,+ allow_promotion_codes: true,});- }- return new Response(JSON.stringify({ error: true }), {- status: 400,- headers: {- "Content-Type": "application/json",- },- });+ if (checkoutSession.url) {+ console.log("Successfully created checkout session");+ return new Response(JSON.stringify({ url: checkoutSession.url }), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ });+ }++ console.error("Checkout session created but no URL returned");+ return new Response(JSON.stringify({ error: true }), {+ status: 400,+ headers: { "Content-Type": "application/json" },+ });+ } catch (error) {+ console.error("Error creating checkout session:", error);+ return new Response(JSON.stringify({ error: true }), {+ status: 500,+ headers: { "Content-Type": "application/json" },+ });+ }}diff --git a/apps/web/app/dashboard/caps/Caps.tsx b/apps/web/app/dashboard/caps/Caps.tsxindex f4605f631..5c482ce3d 100644--- a/apps/web/app/dashboard/caps/Caps.tsx+++ b/apps/web/app/dashboard/caps/Caps.tsx@@ -35,10 +35,6 @@ export const Caps = ({const limit = 15;const totalPages = Math.ceil(count / limit);- if (!activeSpace && (user?.name === undefined || user?.name === "")) {- replace("/onboarding");- }-useEffect(() => {const fetchAnalytics = async () => {const analyticsData: Record<string, number> = {};diff --git a/apps/web/app/dashboard/caps/page.tsx b/apps/web/app/dashboard/caps/page.tsxindex 798512506..272bec771 100644--- a/apps/web/app/dashboard/caps/page.tsx+++ b/apps/web/app/dashboard/caps/page.tsx@@ -11,6 +11,7 @@ import {import { desc, eq, sql, count, or } from "drizzle-orm";import { getCurrentUser } from "@cap/database/auth/session";import { Metadata } from "next";+import { redirect } from "next/navigation";export const metadata: Metadata = {title: "My Caps — Cap",@@ -23,10 +24,19 @@ export default async function CapsPage({}: {searchParams: { [key: string]: string | string[] | undefined };}) {+ const user = await getCurrentUser();++ if (!user || !user.id) {+ redirect("/login");+ }++ if (!user.name || user.name.length <= 1) {+ redirect("/onboarding");+ }++ const userId = user.id;const page = Number(searchParams.page) || 1;const limit = Number(searchParams.limit) || 15;- const user = await getCurrentUser();- const userId = user?.id as string;const offset = (page - 1) * limit;const totalCountResult = await db@@ -86,6 +96,7 @@ export default async function CapsPage({const processedVideoData = videoData.map((video) => ({...video,sharedSpaces: video.sharedSpaces.filter((space) => space.id !== null),+ ownerName: video.ownerName ?? "",}));return (diff --git a/apps/web/app/dashboard/layout.tsx b/apps/web/app/dashboard/layout.tsxindex 942776f5b..ccd898d19 100644--- a/apps/web/app/dashboard/layout.tsx+++ b/apps/web/app/dashboard/layout.tsx@@ -32,6 +32,10 @@ export default async function DashboardLayout({redirect("/login");}+ if (!user.name || user.name.length <= 1) {+ redirect("/onboarding");+ }+const spacesWithMembers = await db.select({space: spaces,diff --git a/apps/web/app/login/form.tsx b/apps/web/app/login/form.tsxindex 886e97b6e..40023264a 100644--- a/apps/web/app/login/form.tsx+++ b/apps/web/app/login/form.tsx@@ -18,6 +18,30 @@ export function LoginForm() {error && toast.error(error);}, [searchParams]);+ useEffect(() => {+ const pendingPriceId = localStorage.getItem("pendingPriceId");+ if (emailSent && pendingPriceId) {+ // Clear the pending price ID+ localStorage.removeItem("pendingPriceId");++ // Wait a bit to ensure the user is created+ setTimeout(async () => {+ const response = await fetch(`/api/settings/billing/subscribe`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({ priceId: pendingPriceId }),+ });+ const data = await response.json();++ if (data.url) {+ window.location.href = data.url;+ }+ }, 2000); // Wait 2 seconds after email is sent+ }+ }, [emailSent]);+return (<><formdiff --git a/apps/web/components/pages/PricingPage.tsx b/apps/web/components/pages/PricingPage.tsxindex 650960d26..9cc8e07cd 100644--- a/apps/web/components/pages/PricingPage.tsx+++ b/apps/web/components/pages/PricingPage.tsx@@ -50,7 +50,9 @@ export const PricingPage = () => {const data = await response.json();if (data.auth === false) {- push(`/login?next=/pricing?plan=${planId}`);+ localStorage.setItem("pendingPriceId", planId);+ push(`/login?next=/pricing`);+ return;}if (data.subscription === true) {