parent
f5927f2e76
commit
bfedd5fdaa
@ -0,0 +1,123 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { stripe } from "@/lib/stripe";
|
||||||
|
import { formatAmountForStripe } from "@/lib/stripe";
|
||||||
|
import { getPool } from "@/lib/database";
|
||||||
|
|
||||||
|
// Define pricing tiers
|
||||||
|
const PRICING_TIERS = {
|
||||||
|
basic: {
|
||||||
|
name: "Basic",
|
||||||
|
amount: 9.99,
|
||||||
|
storageLimit: 5,
|
||||||
|
},
|
||||||
|
standard: {
|
||||||
|
name: "Standard",
|
||||||
|
amount: 19.99,
|
||||||
|
storageLimit: 20,
|
||||||
|
},
|
||||||
|
premium: {
|
||||||
|
name: "Premium",
|
||||||
|
amount: 39.99,
|
||||||
|
storageLimit: 100,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function POST(request: NextRequest) {
|
||||||
|
try {
|
||||||
|
// Check if Stripe is configured
|
||||||
|
if (!process.env.STRIPE_SECRET_KEY) {
|
||||||
|
console.error("Stripe secret key is not configured");
|
||||||
|
return NextResponse.json(
|
||||||
|
{
|
||||||
|
error:
|
||||||
|
"Stripe is not configured. Please add STRIPE_SECRET_KEY to your environment variables.",
|
||||||
|
},
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const { tier, userId } = await request.json();
|
||||||
|
|
||||||
|
// Validate tier
|
||||||
|
const selectedTier = PRICING_TIERS[tier as keyof typeof PRICING_TIERS];
|
||||||
|
if (!selectedTier) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Invalid tier selected" },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate user
|
||||||
|
if (!userId) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "User ID is required" },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if user already has an active subscription
|
||||||
|
const pool = getPool();
|
||||||
|
const client = await pool.connect();
|
||||||
|
|
||||||
|
try {
|
||||||
|
const existingSub = await client.query(
|
||||||
|
`SELECT id, status FROM subscriptions WHERE user_id = $1 AND status = 'ACTIVE'`,
|
||||||
|
[userId]
|
||||||
|
);
|
||||||
|
|
||||||
|
if (existingSub.rows.length > 0) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{
|
||||||
|
error:
|
||||||
|
"You already have an active subscription. Please cancel your current subscription before purchasing a new one.",
|
||||||
|
},
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} catch (dbError) {
|
||||||
|
console.error("Database error checking existing subscription:", dbError);
|
||||||
|
// Continue with payment creation even if check fails
|
||||||
|
} finally {
|
||||||
|
client.release();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get the base URL
|
||||||
|
const origin = request.headers.get("origin") || "http://localhost:3000";
|
||||||
|
|
||||||
|
// Create checkout session
|
||||||
|
const session = await stripe.checkout.sessions.create({
|
||||||
|
mode: "subscription",
|
||||||
|
payment_method_types: ["card"],
|
||||||
|
line_items: [
|
||||||
|
{
|
||||||
|
price_data: {
|
||||||
|
currency: "usd",
|
||||||
|
product_data: {
|
||||||
|
name: selectedTier.name,
|
||||||
|
description: `${selectedTier.storageLimit}GB storage limit`,
|
||||||
|
},
|
||||||
|
unit_amount: formatAmountForStripe(selectedTier.amount),
|
||||||
|
recurring: {
|
||||||
|
interval: "month",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
quantity: 1,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
success_url: `${origin}/?success=true&session_id={CHECKOUT_SESSION_ID}`,
|
||||||
|
cancel_url: `${origin}/?canceled=true`,
|
||||||
|
metadata: {
|
||||||
|
userId: userId,
|
||||||
|
tier: tier,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json({ sessionId: session.id, url: session.url });
|
||||||
|
} catch (error: any) {
|
||||||
|
console.error("Error creating checkout session:", error);
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: error.message || "Failed to create checkout session" },
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,42 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { getPool } from "@/lib/database";
|
||||||
|
|
||||||
|
export async function POST(request: NextRequest) {
|
||||||
|
try {
|
||||||
|
// Get user ID from auth token or session
|
||||||
|
const userId = request.headers.get("user-id");
|
||||||
|
|
||||||
|
if (!userId) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "User not authenticated" },
|
||||||
|
{ status: 401 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const pool = getPool();
|
||||||
|
const client = await pool.connect();
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Cancel the subscription
|
||||||
|
await client.query(
|
||||||
|
`UPDATE subscriptions
|
||||||
|
SET status = 'CANCELLED', updated_at = CURRENT_TIMESTAMP
|
||||||
|
WHERE user_id = $1 AND status = 'ACTIVE'`,
|
||||||
|
[userId]
|
||||||
|
);
|
||||||
|
|
||||||
|
return NextResponse.json({
|
||||||
|
success: true,
|
||||||
|
message: "Subscription cancelled",
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
client.release();
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error cancelling subscription:", error);
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Failed to cancel subscription" },
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,53 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { getPool } from "@/lib/database";
|
||||||
|
|
||||||
|
export async function GET(request: NextRequest) {
|
||||||
|
try {
|
||||||
|
// Get user ID from auth token or session
|
||||||
|
const userId = request.headers.get("user-id");
|
||||||
|
|
||||||
|
if (!userId) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "User not authenticated" },
|
||||||
|
{ status: 401 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const pool = getPool();
|
||||||
|
const client = await pool.connect();
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Try to get active subscription first, otherwise get the most recent one
|
||||||
|
const result = await client.query(
|
||||||
|
`SELECT id, tier, status, storage_limit_gb, current_usage_gb, created_at, updated_at
|
||||||
|
FROM subscriptions
|
||||||
|
WHERE user_id = $1
|
||||||
|
ORDER BY
|
||||||
|
CASE WHEN status = 'ACTIVE' THEN 0 ELSE 1 END,
|
||||||
|
created_at DESC
|
||||||
|
LIMIT 1`,
|
||||||
|
[userId]
|
||||||
|
);
|
||||||
|
|
||||||
|
console.log(
|
||||||
|
`Found ${result.rows.length} subscriptions for user ${userId}`
|
||||||
|
);
|
||||||
|
|
||||||
|
if (result.rows.length === 0) {
|
||||||
|
console.log("No subscriptions found");
|
||||||
|
return NextResponse.json({ subscription: null });
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log("Returning subscription:", result.rows[0]);
|
||||||
|
return NextResponse.json({ subscription: result.rows[0] });
|
||||||
|
} finally {
|
||||||
|
client.release();
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error fetching subscription:", error);
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Failed to fetch subscription" },
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,124 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { stripe } from "@/lib/stripe";
|
||||||
|
import { getPool } from "@/lib/database";
|
||||||
|
import Stripe from "stripe";
|
||||||
|
|
||||||
|
export async function POST(request: NextRequest) {
|
||||||
|
const body = await request.text();
|
||||||
|
const signature = request.headers.get("stripe-signature");
|
||||||
|
|
||||||
|
if (!signature) {
|
||||||
|
return NextResponse.json({ error: "No signature" }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET;
|
||||||
|
if (!webhookSecret) {
|
||||||
|
console.error("Missing STRIPE_WEBHOOK_SECRET");
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Webhook secret not configured" },
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
let event: Stripe.Event;
|
||||||
|
|
||||||
|
try {
|
||||||
|
event = stripe.webhooks.constructEvent(body, signature, webhookSecret);
|
||||||
|
} catch (err: any) {
|
||||||
|
console.error(`Webhook signature verification failed: ${err.message}`);
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: `Webhook Error: ${err.message}` },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const pool = getPool();
|
||||||
|
const client = await pool.connect();
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Handle different event types
|
||||||
|
switch (event.type) {
|
||||||
|
case "checkout.session.completed": {
|
||||||
|
const session = event.data.object as Stripe.Checkout.Session;
|
||||||
|
const userId = session.metadata?.userId;
|
||||||
|
const tier = session.metadata?.tier;
|
||||||
|
|
||||||
|
console.log("Webhook received - userId:", userId, "tier:", tier);
|
||||||
|
|
||||||
|
if (!userId || !tier) {
|
||||||
|
console.error("Missing user or tier in session metadata");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if subscription exists
|
||||||
|
const existing = await client.query(
|
||||||
|
`SELECT id FROM subscriptions WHERE user_id = $1`,
|
||||||
|
[userId]
|
||||||
|
);
|
||||||
|
|
||||||
|
// Normalize tier name
|
||||||
|
const tierName = tier.toUpperCase();
|
||||||
|
console.log("Processing tier:", tierName);
|
||||||
|
const storageLimit =
|
||||||
|
tierName === "BASIC"
|
||||||
|
? 5
|
||||||
|
: tierName === "STANDARD"
|
||||||
|
? 20
|
||||||
|
: tierName === "PREMIUM"
|
||||||
|
? 100
|
||||||
|
: 5;
|
||||||
|
|
||||||
|
if (existing.rows.length > 0) {
|
||||||
|
// Update existing subscription
|
||||||
|
await client.query(
|
||||||
|
`UPDATE subscriptions
|
||||||
|
SET status = 'ACTIVE', tier = $1, storage_limit_gb = $2, updated_at = CURRENT_TIMESTAMP
|
||||||
|
WHERE user_id = $3`,
|
||||||
|
[tierName, storageLimit, userId]
|
||||||
|
);
|
||||||
|
console.log(`Subscription updated for user ${userId}`);
|
||||||
|
} else {
|
||||||
|
// Create new subscription
|
||||||
|
await client.query(
|
||||||
|
`INSERT INTO subscriptions (user_id, tier, status, storage_limit_gb, current_usage_gb)
|
||||||
|
VALUES ($1, $2, 'ACTIVE', $3, 0)`,
|
||||||
|
[userId, tierName, storageLimit]
|
||||||
|
);
|
||||||
|
console.log(`Subscription created for user ${userId}`);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
case "customer.subscription.deleted":
|
||||||
|
case "customer.subscription.updated": {
|
||||||
|
const subscription = event.data.object as Stripe.Subscription;
|
||||||
|
const customerId = subscription.customer as string;
|
||||||
|
|
||||||
|
// Find user by customer ID and update subscription status
|
||||||
|
const status = subscription.status === "active" ? "ACTIVE" : "INACTIVE";
|
||||||
|
await client.query(
|
||||||
|
`UPDATE subscriptions
|
||||||
|
SET status = $1, updated_at = CURRENT_TIMESTAMP
|
||||||
|
WHERE stripe_customer_id = $2`,
|
||||||
|
[status, customerId]
|
||||||
|
);
|
||||||
|
|
||||||
|
console.log(`Subscription ${event.type} for customer ${customerId}`);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
default:
|
||||||
|
console.log(`Unhandled event type: ${event.type}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return NextResponse.json({ received: true });
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error processing webhook:", error);
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Webhook processing failed" },
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
client.release();
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,303 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import { useAuth } from "@/lib/auth-context";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
|
||||||
|
interface Subscription {
|
||||||
|
id: string;
|
||||||
|
tier: string;
|
||||||
|
status: string;
|
||||||
|
storage_limit_gb: number;
|
||||||
|
current_usage_gb: number;
|
||||||
|
created_at: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function SubscriptionsPage() {
|
||||||
|
const { isAuthenticated, user, logout, token } = useAuth();
|
||||||
|
const router = useRouter();
|
||||||
|
const [subscription, setSubscription] = useState<Subscription | null>(null);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [authInitialized, setAuthInitialized] = useState(false);
|
||||||
|
|
||||||
|
// Wait for auth to initialize from localStorage
|
||||||
|
useEffect(() => {
|
||||||
|
// Small delay to let auth context initialize
|
||||||
|
const timer = setTimeout(() => {
|
||||||
|
setAuthInitialized(true);
|
||||||
|
}, 100);
|
||||||
|
return () => clearTimeout(timer);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!authInitialized) return;
|
||||||
|
|
||||||
|
// Check if user is authenticated
|
||||||
|
if (user && token) {
|
||||||
|
// User is authenticated, fetch subscription
|
||||||
|
fetchSubscription();
|
||||||
|
} else {
|
||||||
|
// Not authenticated, redirect to login
|
||||||
|
router.push("/login?redirect=/subscriptions");
|
||||||
|
}
|
||||||
|
}, [authInitialized, user, token, router]);
|
||||||
|
|
||||||
|
const fetchSubscription = async () => {
|
||||||
|
if (!user?.id) return;
|
||||||
|
|
||||||
|
setLoading(true);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch("/api/subscriptions/me", {
|
||||||
|
headers: {
|
||||||
|
"user-id": user.id,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (response.ok) {
|
||||||
|
const data = await response.json();
|
||||||
|
setSubscription(data.subscription);
|
||||||
|
} else {
|
||||||
|
setError("Failed to fetch subscription data");
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
setError("Error loading subscription");
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleCancelSubscription = async () => {
|
||||||
|
if (!confirm("Are you sure you want to cancel your subscription?")) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch("/api/subscriptions/cancel", {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"user-id": user?.id || "",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (response.ok) {
|
||||||
|
alert("Subscription cancelled successfully");
|
||||||
|
fetchSubscription(); // Refresh data
|
||||||
|
} else {
|
||||||
|
const data = await response.json();
|
||||||
|
alert(data.error || "Failed to cancel subscription");
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
alert("Error cancelling subscription");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Don't show content until auth has initialized
|
||||||
|
if (!authInitialized) {
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen flex items-center justify-center">
|
||||||
|
Loading...
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isAuthenticated) {
|
||||||
|
return null; // Will redirect to login
|
||||||
|
}
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen flex items-center justify-center">
|
||||||
|
Loading subscription...
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen flex items-center justify-center text-red-500">
|
||||||
|
{error}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const getTierDisplayName = (tier: string) => {
|
||||||
|
const tierMap: Record<string, string> = {
|
||||||
|
BASIC: "Basic",
|
||||||
|
STANDARD: "Standard",
|
||||||
|
PREMIUM: "Premium",
|
||||||
|
};
|
||||||
|
return tierMap[tier.toUpperCase()] || tier;
|
||||||
|
};
|
||||||
|
|
||||||
|
const getTierPrice = (tier: string) => {
|
||||||
|
const priceMap: Record<string, string> = {
|
||||||
|
BASIC: "$9.99",
|
||||||
|
STANDARD: "$19.99",
|
||||||
|
PREMIUM: "$39.99",
|
||||||
|
};
|
||||||
|
return priceMap[tier.toUpperCase()] || "N/A";
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen bg-gray-50 py-12">
|
||||||
|
<div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
|
||||||
|
{/* Header */}
|
||||||
|
<div className="mb-8">
|
||||||
|
<h1 className="text-4xl font-bold text-gray-900 mb-2">
|
||||||
|
My Subscriptions
|
||||||
|
</h1>
|
||||||
|
<p className="text-gray-600">
|
||||||
|
Manage your subscription and billing information
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{!subscription ? (
|
||||||
|
// No subscription
|
||||||
|
<div className="bg-white rounded-lg shadow-lg p-8 text-center">
|
||||||
|
<div className="mb-6">
|
||||||
|
<div className="w-20 h-20 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-4">
|
||||||
|
<span className="text-3xl">📦</span>
|
||||||
|
</div>
|
||||||
|
<h2 className="text-2xl font-bold text-gray-900 mb-2">
|
||||||
|
No Active Subscription
|
||||||
|
</h2>
|
||||||
|
<p className="text-gray-600 mb-6">
|
||||||
|
You don't have an active subscription. Subscribe to a plan to
|
||||||
|
start using our services.
|
||||||
|
</p>
|
||||||
|
<Button
|
||||||
|
onClick={() => router.push("/")}
|
||||||
|
className="bg-orange-500 hover:bg-orange-600 text-white font-medium px-6 py-3 rounded-md"
|
||||||
|
>
|
||||||
|
Browse Plans
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
// Active subscription
|
||||||
|
<div className="space-y-6">
|
||||||
|
{/* Subscription Card */}
|
||||||
|
<div className="bg-white rounded-lg shadow-lg p-8 border-2 border-gray-200">
|
||||||
|
<div className="flex justify-between items-start mb-6">
|
||||||
|
<div>
|
||||||
|
<h2 className="text-2xl font-bold text-gray-900 mb-2">
|
||||||
|
{getTierDisplayName(subscription.tier)} Plan
|
||||||
|
</h2>
|
||||||
|
<p className="text-gray-600">Current subscription details</p>
|
||||||
|
</div>
|
||||||
|
<div className="text-right">
|
||||||
|
<span
|
||||||
|
className={`px-3 py-1 rounded-full text-sm font-semibold ${
|
||||||
|
subscription.status === "ACTIVE"
|
||||||
|
? "bg-green-100 text-green-800"
|
||||||
|
: "bg-red-100 text-red-800"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{subscription.status}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Subscription Details */}
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
|
||||||
|
<div>
|
||||||
|
<p className="text-sm text-gray-500 mb-1">Plan</p>
|
||||||
|
<p className="text-lg font-semibold text-gray-900">
|
||||||
|
{getTierDisplayName(subscription.tier)}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p className="text-sm text-gray-500 mb-1">Monthly Price</p>
|
||||||
|
<p className="text-lg font-semibold text-gray-900">
|
||||||
|
{getTierPrice(subscription.tier)}/month
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p className="text-sm text-gray-500 mb-1">Storage Limit</p>
|
||||||
|
<p className="text-lg font-semibold text-gray-900">
|
||||||
|
{subscription.storage_limit_gb} GB
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p className="text-sm text-gray-500 mb-1">Current Usage</p>
|
||||||
|
<p className="text-lg font-semibold text-gray-900">
|
||||||
|
{parseFloat(subscription.current_usage_gb).toFixed(2)} GB
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Storage Usage Bar */}
|
||||||
|
<div className="mb-6">
|
||||||
|
<p className="text-sm text-gray-500 mb-2">Storage Usage</p>
|
||||||
|
<div className="w-full bg-gray-200 rounded-full h-4">
|
||||||
|
<div
|
||||||
|
className="bg-orange-500 h-4 rounded-full"
|
||||||
|
style={{
|
||||||
|
width: `${Math.min(
|
||||||
|
(parseFloat(subscription.current_usage_gb) /
|
||||||
|
subscription.storage_limit_gb) *
|
||||||
|
100,
|
||||||
|
100
|
||||||
|
)}%`,
|
||||||
|
}}
|
||||||
|
></div>
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-gray-500 mt-2">
|
||||||
|
{parseFloat(subscription.current_usage_gb).toFixed(2)} GB of{" "}
|
||||||
|
{subscription.storage_limit_gb} GB used
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Billing Info */}
|
||||||
|
<div className="border-t pt-4">
|
||||||
|
<p className="text-sm text-gray-500 mb-1">Member Since</p>
|
||||||
|
<p className="text-gray-900">
|
||||||
|
{new Date(subscription.created_at).toLocaleDateString(
|
||||||
|
"en-US",
|
||||||
|
{
|
||||||
|
year: "numeric",
|
||||||
|
month: "long",
|
||||||
|
day: "numeric",
|
||||||
|
}
|
||||||
|
)}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Actions */}
|
||||||
|
{subscription.status === "ACTIVE" && (
|
||||||
|
<div className="mt-6 pt-6 border-t">
|
||||||
|
<Button
|
||||||
|
onClick={handleCancelSubscription}
|
||||||
|
variant="outline"
|
||||||
|
className="border-red-300 text-red-600 hover:bg-red-50 hover:border-red-400"
|
||||||
|
>
|
||||||
|
Cancel Subscription
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Upgrade/Downgrade Options */}
|
||||||
|
<div className="bg-white rounded-lg shadow-lg p-6">
|
||||||
|
<h3 className="text-xl font-bold text-gray-900 mb-4">
|
||||||
|
Change Plan
|
||||||
|
</h3>
|
||||||
|
<p className="text-gray-600 mb-4">
|
||||||
|
Looking to upgrade or downgrade? Cancel your current
|
||||||
|
subscription and choose a new plan.
|
||||||
|
</p>
|
||||||
|
<Button
|
||||||
|
onClick={() => router.push("/")}
|
||||||
|
className="bg-orange-500 hover:bg-orange-600 text-white font-medium px-6 py-3 rounded-md"
|
||||||
|
>
|
||||||
|
Browse All Plans
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@ -0,0 +1,144 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect } from "react";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
import { useAuth } from "@/lib/auth-context";
|
||||||
|
import { useState } from "react";
|
||||||
|
import UploadArea from "@/components/UploadArea";
|
||||||
|
|
||||||
|
export default function UploadPage() {
|
||||||
|
const { isAuthenticated, user } = useAuth();
|
||||||
|
const router = useRouter();
|
||||||
|
const [userSubscription, setUserSubscription] = useState<any>(null);
|
||||||
|
const [authInitialized, setAuthInitialized] = useState(false);
|
||||||
|
|
||||||
|
// Wait for auth to initialize from localStorage
|
||||||
|
useEffect(() => {
|
||||||
|
const timer = setTimeout(() => {
|
||||||
|
setAuthInitialized(true);
|
||||||
|
}, 100);
|
||||||
|
return () => clearTimeout(timer);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// Check authentication and fetch subscription
|
||||||
|
useEffect(() => {
|
||||||
|
if (!authInitialized) return;
|
||||||
|
|
||||||
|
if (!isAuthenticated || !user) {
|
||||||
|
router.push("/login?redirect=/upload");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fetch user subscription
|
||||||
|
const fetchSubscription = async () => {
|
||||||
|
if (!user?.id) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch("/api/subscriptions/me", {
|
||||||
|
headers: {
|
||||||
|
"user-id": user.id,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (response.ok) {
|
||||||
|
const data = await response.json();
|
||||||
|
setUserSubscription(data.subscription);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error fetching subscription:", error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
fetchSubscription();
|
||||||
|
}, [authInitialized, isAuthenticated, user, router]);
|
||||||
|
|
||||||
|
// Show loading while auth initializes
|
||||||
|
if (!authInitialized || !isAuthenticated) {
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen flex items-center justify-center">
|
||||||
|
Loading...
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// If no subscription found after loading, treat it as no subscription
|
||||||
|
// Don't block the page from showing
|
||||||
|
const hasActiveSubscription =
|
||||||
|
userSubscription && userSubscription.status === "ACTIVE";
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen bg-gray-50 py-12">
|
||||||
|
<div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
|
||||||
|
{/* Header */}
|
||||||
|
<div className="mb-8">
|
||||||
|
<h1 className="text-4xl font-bold text-gray-900 mb-2">
|
||||||
|
Upload Files
|
||||||
|
</h1>
|
||||||
|
{/* <p className="text-gray-600">
|
||||||
|
Upload your .blend files to start rendering
|
||||||
|
</p> */}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Subscription Warning */}
|
||||||
|
{!hasActiveSubscription && (
|
||||||
|
<div className="bg-red-50 border-2 border-red-500 rounded-lg p-6 mb-8">
|
||||||
|
<p className="text-red-800 font-semibold text-lg">
|
||||||
|
Subscribe to use our services
|
||||||
|
</p>
|
||||||
|
<p className="text-red-700 text-sm mt-2">
|
||||||
|
You need an active subscription to upload files. Subscribe to a
|
||||||
|
plan to continue.
|
||||||
|
</p>
|
||||||
|
<button
|
||||||
|
onClick={() => router.push("/")}
|
||||||
|
className="mt-4 bg-red-600 hover:bg-red-700 text-white px-6 py-2 rounded-md text-sm font-medium"
|
||||||
|
>
|
||||||
|
Browse Plans
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Subscription Info - Only show if active */}
|
||||||
|
{hasActiveSubscription && userSubscription && (
|
||||||
|
<div className="bg-white rounded-lg shadow-md p-6 mb-8">
|
||||||
|
<h2 className="text-lg font-semibold text-gray-900 mb-2">
|
||||||
|
Your {userSubscription.tier} Plan
|
||||||
|
</h2>
|
||||||
|
<p className="text-sm text-gray-600">
|
||||||
|
Storage:{" "}
|
||||||
|
{parseFloat(userSubscription.current_usage_gb).toFixed(2)} GB /{" "}
|
||||||
|
{userSubscription.storage_limit_gb} GB used
|
||||||
|
</p>
|
||||||
|
<div className="mt-3 w-full bg-gray-200 rounded-full h-2">
|
||||||
|
<div
|
||||||
|
className="bg-orange-500 h-2 rounded-full"
|
||||||
|
style={{
|
||||||
|
width: `${Math.min(
|
||||||
|
(parseFloat(userSubscription.current_usage_gb) /
|
||||||
|
userSubscription.storage_limit_gb) *
|
||||||
|
100,
|
||||||
|
100
|
||||||
|
)}%`,
|
||||||
|
}}
|
||||||
|
></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Upload Area */}
|
||||||
|
<div className="bg-white rounded-lg shadow-lg p-8">
|
||||||
|
<h2 className="text-2xl font-bold text-gray-900 mb-6">
|
||||||
|
Start by uploading at least one .blend file
|
||||||
|
</h2>
|
||||||
|
<div
|
||||||
|
className={
|
||||||
|
!hasActiveSubscription ? "pointer-events-none opacity-50" : ""
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<UploadArea className="w-full shadow-sm" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@ -0,0 +1,79 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { useAuth } from "@/lib/auth-context";
|
||||||
|
|
||||||
|
interface StripePaymentButtonProps {
|
||||||
|
tier: "basic" | "pro" | "enterprise";
|
||||||
|
amount: number;
|
||||||
|
storageLimit: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function StripePaymentButton({
|
||||||
|
tier,
|
||||||
|
amount,
|
||||||
|
storageLimit,
|
||||||
|
}: StripePaymentButtonProps) {
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const { user } = useAuth();
|
||||||
|
const router = useRouter();
|
||||||
|
|
||||||
|
const handlePayment = async () => {
|
||||||
|
if (!user) {
|
||||||
|
// Redirect to login page
|
||||||
|
router.push("/login?redirect=/pricing");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setLoading(true);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch("/api/create-checkout-session", {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
tier,
|
||||||
|
userId: user.id,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
// Check if response is JSON before parsing
|
||||||
|
const contentType = response.headers.get("content-type");
|
||||||
|
if (!contentType || !contentType.includes("application/json")) {
|
||||||
|
throw new Error(
|
||||||
|
"Invalid response from server. Please check your Stripe configuration."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(data.error || "Failed to create checkout session");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Redirect to Stripe Checkout
|
||||||
|
if (data.url) {
|
||||||
|
window.location.href = data.url;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Payment error:", error);
|
||||||
|
alert("Failed to start payment process. Please try again.");
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Button
|
||||||
|
onClick={handlePayment}
|
||||||
|
disabled={loading}
|
||||||
|
className="w-full bg-orange-500 hover:bg-orange-600 text-white font-medium px-6 py-3 rounded-md transition-colors"
|
||||||
|
>
|
||||||
|
{loading ? "Processing..." : `Subscribe - $${amount}/month`}
|
||||||
|
</Button>
|
||||||
|
);
|
||||||
|
}
|
||||||
@ -0,0 +1,23 @@
|
|||||||
|
import Stripe from "stripe";
|
||||||
|
|
||||||
|
// Initialize Stripe with your secret key from environment variables
|
||||||
|
export const stripe = new Stripe(process.env.STRIPE_SECRET_KEY || "", {
|
||||||
|
apiVersion: "2024-11-20.acacia",
|
||||||
|
typescript: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Helper function to format amount for Stripe (convert to cents)
|
||||||
|
export function formatAmountForStripe(
|
||||||
|
amount: number,
|
||||||
|
currency: string = "usd"
|
||||||
|
): number {
|
||||||
|
return Math.round(amount * 100);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Helper function to format amount from Stripe (convert from cents)
|
||||||
|
export function formatAmountFromStripe(
|
||||||
|
amount: number,
|
||||||
|
currency: string = "usd"
|
||||||
|
): number {
|
||||||
|
return Math.round(amount) / 100;
|
||||||
|
}
|
||||||
|
After Width: | Height: | Size: 197 KiB |
Loading…
Reference in new issue