Skip to content

Commit

Permalink
finish first version with membership and Stripegit add .
Browse files Browse the repository at this point in the history
  • Loading branch information
dokmy committed Jan 12, 2024
1 parent 9f9c81f commit 75a5d05
Show file tree
Hide file tree
Showing 20 changed files with 239 additions and 84 deletions.
73 changes: 27 additions & 46 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@
"react-markdown": "^8.0.7",
"react-spinners": "^0.13.8",
"sswr": "^2.0.0",
"stripe": "^14.11.0",
"svelte": "^4.2.0",
"tailwind-merge": "^2.1.0",
"tailwindcss": "3.3.2",
Expand All @@ -62,7 +63,6 @@
"vue": "^3.3.4"
},
"devDependencies": {
"@playwright/test": "^1.38.0",
"@types/md5": "^2.3.2",
"prisma": "^5.7.1"
}
Expand Down
4 changes: 3 additions & 1 deletion src/app/(auth)/(routes)/sign-up/[[...sign-up]]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ import { SignUp } from "@clerk/nextjs";
export default function Page() {
return (
<div className="bg-gradient-to-r from-gray-700 via-gray-900 to-black w-screen h-screen">
<SignUp />;
<div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2">
<SignUp />
</div>
</div>
);
}
2 changes: 1 addition & 1 deletion src/app/(root)/(routes)/results/[searchId]/page.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { auth } from "@clerk/nextjs";
import { redirect } from "next/navigation";
import prismadb from "../../../../../lib/prismadb";
import prismadb from "../../../../lib/prismadb";
import ChatComponent from "../components/chat-component";

type Props = {
Expand Down
12 changes: 10 additions & 2 deletions src/app/(root)/(routes)/settings/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,16 @@ const settingsPage = async () => {
const hasSubscription = await checkSubscription();

return (
<div className="items-center">
<SubscriptionButton hasSubscription={hasSubscription} />
<div className="h-full p-4 space-y-2">
<h3 className="text-lg font-medium">Settings</h3>
<div className="text-muted-foreground text-sm">
{hasSubscription
? "You are currently on a pro plan."
: "You are currently on a free plan."}
</div>
<div>
<SubscriptionButton hasSubscription={hasSubscription} />
</div>
</div>
);
};
Expand Down
2 changes: 1 addition & 1 deletion src/app/api/chat/route.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Configuration, OpenAIApi } from 'openai-edge'
import { Message, OpenAIStream, StreamingTextResponse } from 'ai'
import { getContext } from '@/utils/context'
import prismadb from '../../../lib/prismadb'
import prismadb from '../../lib/prismadb'
import { auth, currentUser } from "@clerk/nextjs";
import { NextResponse } from 'next/server';
import { Role } from '@prisma/client';
Expand Down
2 changes: 1 addition & 1 deletion src/app/api/get-messages/route.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import prismadb from "../../../lib/prismadb";
import prismadb from "../../lib/prismadb";
import { NextResponse } from "next/server";

export const POST = async (req: Request) => {
Expand Down
9 changes: 4 additions & 5 deletions src/app/api/get-searches/route.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import prismadb from "../../../lib/prismadb";
import prismadb from "../../lib/prismadb";
import { NextResponse } from "next/server";

export const POST = async (req: Request) => {
Expand All @@ -10,10 +10,9 @@ export const POST = async (req: Request) => {
orderBy: {
createdAt: 'desc'
},

include: {
searchResults: true,
},
include: {
searchResults: true,
},
});

return NextResponse.json(_searches);
Expand Down
11 changes: 5 additions & 6 deletions src/app/api/search/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,9 @@ import { Configuration, OpenAIApi } from 'openai-edge'
import { getEmbeddings } from '@/utils/embeddings'
import { getMatchesFromEmbeddings } from '@/utils/pinecone'
import dayjs from "dayjs";
import prismadb from '../../../lib/prismadb';
import prismadb from '../../lib/prismadb';
import { auth, currentUser } from "@clerk/nextjs";
import { NextResponse } from 'next/server';
import { checkSubscription } from '@/lib/subscriptions';
import { checkSearchCredits, deductSearchCredit, getSearchCreditCount, incrementSearchCredit } from '@/lib/searchCredits';


Expand Down Expand Up @@ -51,13 +50,13 @@ export async function POST(req: Request) {
return new NextResponse("Unauthorized", {status: 401})
}

const inSearchCreditsDb = await checkSearchCredits()
const inSearchCreditsDb = await checkSearchCredits(userId)

if (!inSearchCreditsDb) {
incrementSearchCredit(5)
incrementSearchCredit(userId, 5)
}

const creditsLeft = await getSearchCreditCount()
const creditsLeft = await getSearchCreditCount(userId)

if (creditsLeft == 0) {
return new NextResponse("No more credits. Please upgrade or buy more credits." , {status:403})
Expand All @@ -70,7 +69,7 @@ export async function POST(req: Request) {


if (creditsLeft > 0) {
deductSearchCredit()
deductSearchCredit(userId)
}


Expand Down
67 changes: 67 additions & 0 deletions src/app/api/stripe/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { auth, currentUser } from "@clerk/nextjs";
import { NextResponse } from "next/server";

import prismadb from "../../lib/prismadb";
import { stripe } from "../../lib/stripe";
import { absoluteUrl } from "@/lib/utils";

const settingsUrl = absoluteUrl("/settings");

export async function GET() {
try {
const { userId } = auth();
const user = await currentUser();

if (!userId || !user) {
return new NextResponse("Unauthorized", { status: 401 });
}

const userSubscription = await prismadb.userSubscription.findUnique({
where: {
userId
}
})

if (userSubscription && userSubscription.stripeCustomerId) {
const stripeSession = await stripe.billingPortal.sessions.create({
customer: userSubscription.stripeCustomerId,
return_url: settingsUrl,
})

return new NextResponse(JSON.stringify({ url: stripeSession.url }))
}

const stripeSession = await stripe.checkout.sessions.create({
success_url: settingsUrl,
cancel_url: settingsUrl,
payment_method_types: ["card"],
mode: "subscription",
billing_address_collection: "auto",
customer_email: user.emailAddresses[0].emailAddress,
line_items: [
{
price_data: {
currency: "HKD",
product_data: {
name: "FastLegal Pro",
description: "Supercharge your legal research"
},
unit_amount: 150000,
recurring: {
interval: "month"
}
},
quantity: 1,
},
],
metadata: {
userId,
},
})

return new NextResponse(JSON.stringify({ url: stripeSession.url }))
} catch (error) {
console.log("[STRIPE]", error);
return new NextResponse("Internal Error", { status: 500 });
}
};
83 changes: 83 additions & 0 deletions src/app/api/webhook/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import Stripe from "stripe"
import { headers } from "next/headers"
import { NextResponse } from "next/server"

import prismadb from "@/lib/prismadb"
import { stripe } from "@/lib/stripe"

import { incrementSearchCredit } from '@/lib/searchCredits';

export async function POST(req: Request) {
const body = await req.text()
const signature = headers().get("Stripe-Signature") as string

let event: Stripe.Event

try {
event = stripe.webhooks.constructEvent(
body,
signature,
process.env.STRIPE_WEBHOOK_SECRET!
)
} catch (error: any) {
return new NextResponse(`Webhook Error: ${error.message}`, { status: 400 })
}

const session = event.data.object as Stripe.Checkout.Session

if (event.type === "checkout.session.completed") {
const userId = session?.metadata?.userId;
if (!userId) {
return new NextResponse("User id is required", { status: 400 });
}
const subscription = await stripe.subscriptions.retrieve(
session.subscription as string
)

if (!session?.metadata?.userId) {
return new NextResponse("User id is required", { status: 400 });
}

await prismadb.userSubscription.create({
data: {
userId: session?.metadata?.userId,
stripeSubscriptionId: subscription.id,
stripeCustomerId: subscription.customer as string,
stripePriceId: subscription.items.data[0].price.id,
stripeCurrentPeriodEnd: new Date(
subscription.current_period_end * 1000
),
},
})

await incrementSearchCredit(userId, 50)

}

if (event.type === "invoice.payment_succeeded") {
const userId = session?.metadata?.userId;
if (!userId) {
return new NextResponse("User id is required", { status: 400 });
}
const subscription = await stripe.subscriptions.retrieve(
session.subscription as string
)

await prismadb.userSubscription.update({
where: {
stripeSubscriptionId: subscription.id,
},
data: {
stripePriceId: subscription.items.data[0].price.id,
stripeCurrentPeriodEnd: new Date(
subscription.current_period_end * 1000
),
},
})

await incrementSearchCredit(userId, 50)

}

return new NextResponse(null, { status: 200 })
};
Loading

0 comments on commit 75a5d05

Please sign in to comment.