Skip to content

Commit

Permalink
Revert "Update page.tsx"
Browse files Browse the repository at this point in the history
  • Loading branch information
ArhanAnsari authored Oct 8, 2024
1 parent e7b0017 commit 7de7cc4
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 115 deletions.
55 changes: 28 additions & 27 deletions app/dashboard/upgrade/page.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
//app/dashboard/upgrade/page.tsx
"use client";
import React, { useEffect, useState } from "react";
import getStripe from "@/lib/stripe-js"; // Ensure this utility is set up correctly
Expand Down Expand Up @@ -37,37 +38,37 @@ const UpgradePage: React.FC = () => {
}, [session]);

const getPriceFn = async (plan: string) => {
if (plan === "free") {
// Redirect to dashboard if user selects the Free plan
router.push("/dashboard");
return;
}
if (plan === "free") {
// Redirect to dashboard if user selects the Free plan
router.push("/dashboard");
return;
}

try {
const response = await fetch(`/api/checkout?plan=${plan}`);
if (!response.ok) {
throw new Error(`Failed to initiate checkout for plan: ${plan}`);
}
const body = await response.json();
const sessionId = body.sessionId;
try {
const response = await fetch(`/api/checkout?plan=${plan}`);
if (!response.ok) {
throw new Error(`Failed to initiate checkout for plan: ${plan}`);
}
const body = await response.json();
const sessionId = body.sessionId;

const stripe = await getStripe();
if (!stripe) {
throw new Error("Stripe initialization failed");
}
const stripe = await getStripe();
if (!stripe) {
throw new Error("Stripe initialization failed");
}

await stripe.redirectToCheckout({ sessionId });
} catch (error) {
// Check if the error is an instance of Error
if (error instanceof Error) {
console.error("Error during checkout process:", error); // Log the error to the console
alert(`Error during checkout process: ${error.message}`); // Show the error to the user
} else {
console.error("Unknown error during checkout process:", error); // Log unknown error
alert("An unknown error occurred during checkout.");
}
await stripe.redirectToCheckout({ sessionId });
} catch (error) {
// Check if the error is an instance of Error
if (error instanceof Error) {
console.error("Error during checkout process:", error); // Log the error to the console
alert(`Error during checkout process: ${error.message}`); // Show the error to the user
} else {
console.error("Unknown error during checkout process:", error); // Log unknown error
alert("An unknown error occurred during checkout.");
}
};
}
};

const isCurrentPlan = (plan: string) => userPlan === plan; // Helper function to check if the user is on the current plan

Expand Down
2 changes: 1 addition & 1 deletion app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export default function HomePage() {
Leverage the power of AI with Google Gemini to create amazing content effortlessly. Whether you need help generating stories, articles, or creative ideas, InspireGem is here to assist you.
</p>
<Link
href="/plans"
href="/dashboard/upgrade"
className="inline-block bg-blue-500 text-white font-bold py-3 px-6 rounded-lg shadow-md hover:bg-blue-600 transition-transform transform hover:scale-105"
>
View Plans
Expand Down
75 changes: 14 additions & 61 deletions app/plans/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,11 @@ import SEO from "@/components/SEO"; // Import the SEO component
import { getUserData } from "@/firebaseFunctions"; // Import function to fetch user data
import { useSession } from "next-auth/react"; // Session management
import { useRouter } from "next/navigation"; // Router for redirection
import { Chart } from "react-chartjs-2"; // Chart.js for plan benefits
import { Tooltip } from "react-tooltip"; // Tooltips

export default function PlansPage() {
const [userPlan, setUserPlan] = useState<string>("free"); // State to hold user's current plan
const { data: session, status } = useSession(); // Get session from NextAuth
const router = useRouter(); // Router instance for redirecting
const [usageData, setUsageData] = useState<number>(0); // User's current usage

useEffect(() => {
const fetchUserPlan = async () => {
Expand All @@ -22,7 +19,6 @@ export default function PlansPage() {
const userData = await getUserData(session.user.email);
if (userData) {
setUserPlan(userData.plan); // Update state with the user's plan
setUsageData(userData.usage); // Fetch usage data
}
} catch (error) {
console.error("Error fetching user data:", error);
Expand All @@ -37,7 +33,8 @@ export default function PlansPage() {

const getPriceFn = (plan: string) => {
if (plan === userPlan) {
return; // If the selected plan is already the user's plan, do nothing
// If the selected plan is already the user's plan, do nothing
return;
}

fetch("/api/checkout?plan=" + plan)
Expand All @@ -51,44 +48,37 @@ export default function PlansPage() {

const isCurrentPlan = (plan: string) => userPlan === plan; // Helper function to check if the user is on the current plan

// Display loading state if session is being fetched
if (status === "loading") {
return <div>Loading...</div>;
}

// If session is null (user not logged in), redirect to login page
if (!session) {
router.push("/auth/signin");
return null;
}

return (
<div className="min-h-screen bg-gray-50 py-10 px-4">
{/* Add SEO Component */}
<SEO
title="Plans - InspireGem"
description="Explore the available plans on InspireGem and choose the one that fits your content generation needs."
/>
<h1 className="text-4xl font-bold text-center mb-10">
Welcome {session?.user?.name}!
</h1>

<div className="text-center mb-8">
<p className="text-lg text-gray-600">Your current usage: {usageData} requests.</p>
</div>

<div className="max-w-6xl mx-auto grid grid-cols-1 md:grid-cols-3 gap-8">
{/* Free Plan */}
<div className="bg-white rounded-lg shadow-lg p-6 hover:shadow-xl transition-transform transform-gpu hover:scale-105">
<h2 className="text-3xl font-bold text-blue-600 mb-4">
Free Plan <span className="text-xs bg-blue-100 text-blue-600 p-1 rounded">Basic</span>
</h2>
<div className="bg-white rounded-lg shadow-lg p-6 hover:shadow-xl transition duration-300 transform hover:scale-105">
<h2 className="text-3xl font-bold text-blue-600 mb-4">Free Plan</h2>
<p className="text-gray-600 mb-4">Up to 50 requests per month.</p>
<Tooltip content="Access basic AI tools" />
<p className="text-gray-600 mb-4">Basic AI content generation.</p>
<p className="text-gray-600 mb-6">Community support.</p>
<button
type="button"
className={`w-full text-center text-white ${
isCurrentPlan("free") ? "bg-gray-400" : "bg-blue-500 hover:bg-blue-600"
} font-bold py-3 rounded-lg transition duration-300`}
} font-bold py-3 rounded-lg transition duration-300 transform hover:scale-105`}
onClick={() => getPriceFn("free")}
disabled={isCurrentPlan("free")}
>
Expand All @@ -97,19 +87,16 @@ export default function PlansPage() {
</div>

{/* Pro Plan */}
<div className="bg-white rounded-lg shadow-lg p-6 hover:shadow-xl transition-transform transform-gpu hover:scale-105">
<h2 className="text-3xl font-bold text-green-600 mb-4">
Pro Plan <span className="text-xs bg-green-100 text-green-600 p-1 rounded">Popular</span>
</h2>
<div className="bg-white rounded-lg shadow-lg p-6 hover:shadow-xl transition duration-300 transform hover:scale-105">
<h2 className="text-3xl font-bold text-green-600 mb-4">Pro Plan</h2>
<p className="text-gray-600 mb-4">500 requests per month.</p>
<Tooltip content="Advanced tools for more powerful AI." />
<p className="text-gray-600 mb-4">Advanced AI content generation.</p>
<p className="text-gray-600 mb-6">Priority email support.</p>
<button
type="button"
className={`w-full text-center text-white ${
isCurrentPlan("pro") ? "bg-gray-400" : "bg-green-500 hover:bg-green-600"
} font-bold py-3 rounded-lg transition duration-300`}
} font-bold py-3 rounded-lg transition duration-300 transform hover:scale-105`}
onClick={() => getPriceFn("pro")}
disabled={isCurrentPlan("pro")}
>
Expand All @@ -118,19 +105,16 @@ export default function PlansPage() {
</div>

{/* Enterprise Plan */}
<div className="bg-white rounded-lg shadow-lg p-6 hover:shadow-xl transition-transform transform-gpu hover:scale-105">
<h2 className="text-3xl font-bold text-red-600 mb-4">
Enterprise Plan <span className="text-xs bg-red-100 text-red-600 p-1 rounded">Best Value</span>
</h2>
<div className="bg-white rounded-lg shadow-lg p-6 hover:shadow-xl transition duration-300 transform hover:scale-105">
<h2 className="text-3xl font-bold text-red-600 mb-4">Enterprise Plan</h2>
<p className="text-gray-600 mb-4">Unlimited requests.</p>
<Tooltip content="Premium access to all AI tools." />
<p className="text-gray-600 mb-4">Access to all AI features.</p>
<p className="text-gray-600 mb-6">24/7 premium support.</p>
<button
type="button"
className={`w-full text-center text-white ${
isCurrentPlan("enterprise") ? "bg-gray-400" : "bg-red-500 hover:bg-red-600"
} font-bold py-3 rounded-lg transition duration-300`}
} font-bold py-3 rounded-lg transition duration-300 transform hover:scale-105`}
onClick={() => getPriceFn("enterprise")}
disabled={isCurrentPlan("enterprise")}
>
Expand All @@ -140,37 +124,6 @@ export default function PlansPage() {
</button>
</div>
</div>

{/* Add testimonial section */}
<div className="mt-10">
<h3 className="text-2xl font-bold text-center mb-4">What our users are saying:</h3>
{/* Testimonials Grid */}
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
<div className="bg-white p-6 shadow-md rounded-lg">
<p>&quot;The Pro Plan gave my content a boost, worth every penny!&quot;</p>
<span className="block mt-2 text-gray-600">- John Doe</span>
</div>
{/* Add more testimonials */}
</div>
</div>

{/* Plan benefits chart */}
<div className="mt-10">
<h3 className="text-2xl font-bold text-center mb-6">Compare Plan Benefits</h3>
<Chart
type="bar"
data={{
labels: ["Free", "Pro", "Enterprise"],
datasets: [
{
label: "Requests",
data: [50, 500, Infinity],
backgroundColor: ["#3b82f6", "#10b981", "#ef4444"],
},
],
}}
/>
</div>
</div>
);
}
29 changes: 3 additions & 26 deletions firebaseFunctions.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
// /firebaseFunctions.ts
import { db } from "./firebaseConfig";
import {
doc,
Expand All @@ -25,7 +24,6 @@ type Plan = "free" | "pro" | "enterprise";
interface UserData {
plan: Plan;
requestCount: number;
usage: number; // Add the usage field to track usage
}

// Define allowed plans and request limits
Expand All @@ -44,7 +42,6 @@ export const initializeUserData = async (email: string): Promise<void> => {
await setDoc(userDocRef, {
plan: "free", // Default to the free plan
requestCount: 0, // Start with 0 requests
usage: 0, // Initialize usage to 0
});
}
};
Expand All @@ -60,13 +57,7 @@ export const getUserData = async (email: string): Promise<UserData | null> => {
return await getUserData(email); // Fetch the newly created data
}

const data = userDoc.data() as UserData;

// Ensure 'usage' is returned (can be handled if missing)
return {
...data,
usage: data.usage ?? 0, // Fallback to 0 if usage is undefined
};
return userDoc.data() as UserData;
} catch (error) {
console.error(`Error fetching user data for ${email}:`, error);
return null; // Return null if an error occurs
Expand Down Expand Up @@ -105,20 +96,6 @@ export const incrementRequestCount = async (email: string): Promise<void> => {
}
};

// Function to increment both request count and usage
export const incrementRequestAndUsage = async (email: string): Promise<void> => {
try {
const userDocRef = doc(db, "users", email);
await updateDoc(userDocRef, {
requestCount: increment(1),
usage: increment(1), // Increment usage by 1
});
} catch (error) {
console.error(`Error incrementing request count and usage for ${email}:`, error);
throw new Error("Unable to increment request count and usage.");
}
};

// Function to handle content generation and limit checking
export const handleContentGeneration = async (email: string, generatedContent: string): Promise<void> => {
const canGenerate = await checkUserPlanLimit(email);
Expand All @@ -127,8 +104,8 @@ export const handleContentGeneration = async (email: string, generatedContent: s
throw new Error("You have reached your content generation limit for this month.");
}

// If user is allowed to generate content, increment both request count and usage
await incrementRequestAndUsage(email);
// If user is allowed to generate content, increment request count
await incrementRequestCount(email);

// Save the newly generated content
await saveGeneratedContent(email, generatedContent);
Expand Down

0 comments on commit 7de7cc4

Please sign in to comment.