Skip to content

Commit

Permalink
Added popup while cancel subscription and fixed subscription status
Browse files Browse the repository at this point in the history
  • Loading branch information
ravirajput10 committed Mar 18, 2024
1 parent f474dbd commit 511fa68
Show file tree
Hide file tree
Showing 7 changed files with 97 additions and 63 deletions.
11 changes: 6 additions & 5 deletions apps/web/app/account/billing/action.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import UserModel from "@/models/user";
import { LEMONSQUEEZY_API_KEY } from "@/lib/constants";
import { error } from "@/utils/logger";
import { auth } from "@/auth";
import { User } from "@medialit/models";

export async function cancelSubscription(
prevState: Record<string, unknown>,
Expand All @@ -26,7 +27,7 @@ export async function cancelSubscription(

await connectToDatabase();

const user = await UserModel.findOne({
const user: User | null = await UserModel.findOne({
email: session.user.email,
});

Expand All @@ -35,7 +36,7 @@ export async function cancelSubscription(
}

const response = await fetch(
`https://api.lemonsqueezy.com/v1/subscriptions/${user.userId}`,
`https://api.lemonsqueezy.com/v1/subscriptions/${user.subscriptionId}`,
{
method: "DELETE",
headers: {
Expand Down Expand Up @@ -75,7 +76,7 @@ export async function resumeSubscription(

await connectToDatabase();

const user = await UserModel.findOne({
const user: User | null = await UserModel.findOne({
email: session.user.email,
});

Expand All @@ -84,7 +85,7 @@ export async function resumeSubscription(
}

const response = await fetch(
`https://api.lemonsqueezy.com/v1/subscriptions/${user.userId}`,
`https://api.lemonsqueezy.com/v1/subscriptions/${user.subscriptionId}`,
{
method: "PATCH",
headers: {
Expand All @@ -95,7 +96,7 @@ export async function resumeSubscription(
body: JSON.stringify({
data: {
type: "subscriptions",
id: user.userId,
id: user.subscriptionId,
attributes: {
cancelled: false,
},
Expand Down
80 changes: 68 additions & 12 deletions apps/web/app/account/billing/cancel-subscription-button.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,19 @@
import { Button } from "@/components/ui/button";
import { useFormState, useFormStatus } from "react-dom";
import { cancelSubscription } from "./action";
import { useEffect } from "react";
import { useEffect, useState } from "react";
import { useToast } from "@/components/ui/use-toast";
import { useRouter } from "next/navigation";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
DialogClose,
} from "@/components/ui/dialog";

export default function CancelSubscriptionButton({
subscriptionStatus,
Expand All @@ -20,8 +30,11 @@ export default function CancelSubscriptionButton({
const { toast } = useToast();
const router = useRouter();

const [open, setOpen] = useState(false);

useEffect(() => {
if (formState.success) {
setOpen(false);
toast({
title: "We are sorry to see you go",
description: "Your subscription has been cancelled",
Expand All @@ -37,14 +50,57 @@ export default function CancelSubscriptionButton({
}, [formState]);

return (
<form action={formAction}>
<Submit
currentPlan={currentPlan}
subscriptionStatus={subscriptionStatus}
>
Cancel subscription
</Submit>
</form>
<>
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
{currentPlan === "Basic" &&
subscriptionStatus === "subscribed" ? (
<Button className="bg-primary hover:bg-[#333333]">
Downgrade to free
</Button>
) : (
<Button className="bg-red-600 hover:bg-red-700">
Cancel subscription
</Button>
)}
</DialogTrigger>
<DialogContent className="sm:max-w-[425px]">
{currentPlan === "Basic" &&
subscriptionStatus === "subscribed" ? (
<>
<DialogHeader>
<DialogTitle>Downgrade to free</DialogTitle>
</DialogHeader>
Are you sure, you want to cancel your current
subscription?
</>
) : (
<>
<DialogHeader>
<DialogTitle>Cancel subscription</DialogTitle>
</DialogHeader>
Are you sure, you want to Cancel subscription?
</>
)}

<form action={formAction}>
<DialogFooter>
<DialogClose asChild>
<Button>Nevermind</Button>
</DialogClose>
<DialogClose asChild>
<Submit
currentPlan={currentPlan}
subscriptionStatus={subscriptionStatus}
>
Yes! Cancel
</Submit>
</DialogClose>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
</>
);
}

Expand All @@ -63,13 +119,13 @@ function Submit({
let className;

if (currentPlan === "Basic" && subscriptionStatus === "subscribed") {
buttonText = "Downgrade to free";
className = "bg-primary hover:bg-[#333333]";
buttonText = "Yes! Cancel";
className = "bg-red-500 hover:bg-red-700";
}

return (
<Button
className={`bg-red-500 hover:bg-red-700 w-full text-white ${className}`}
className={`bg-red-500 hover:bg-red-700 text-white ${className}`}
type="submit"
variant="secondary"
disabled={status.pending}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ export default function LemonSqueezyStartSubscriptionButton({
if (!session) {
router.push("/login");
} else {
const url = `https://${storeId}.lemonsqueezy.com/checkout/buy/${productId}?checkout[email]=${session.user?.email}&checkout[custom][subscriberId]=${userId}&embed=1`;
const url = `https://${storeId}.lemonsqueezy.com/checkout/buy/${productId}?checkout[email]=${session.user?.email}&checkout[custom][userId]=${userId}&embed=1`;
(window as any).LemonSqueezy.Url.Open(url);
}
}}
Expand Down
27 changes: 2 additions & 25 deletions apps/web/app/account/billing/page.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import React, { ReactNode } from "react";
import { CheckIcon } from "@radix-ui/react-icons";
import { Button } from "@/components/ui/button";
import {
LEMONSQUEEZY_STORE_ID,
LEMONSQUEEZY_PRODUCT_ID,
Expand All @@ -11,6 +10,7 @@ import ResumeSubscriptionButton from "./resume-subscription-button";
import { auth } from "@/auth";
import { getSubscriber } from "@/app/actions";
import { redirect } from "next/navigation";
import { User } from "@medialit/models";

const pricingPlans = [
{
Expand Down Expand Up @@ -53,7 +53,7 @@ export const PricingPane = async ({
isSecondary = false,
}: PricingPaneProps) => {
const session = await auth();
const user: any = await getSubscriber();
const user: User | null = await getSubscriber();

if (!user) {
return redirect("/404");
Expand Down Expand Up @@ -100,7 +100,6 @@ export const PricingPane = async ({
: "w-full"
}
>
{/* {user.subscriptionStatus === "subscribed" ? "Downgrade to free" : "Current plan"} */}
{user.subscriptionStatus === "not-subscribed"
? "Current plan "
: "Downgrade to free"}
Expand Down Expand Up @@ -140,28 +139,6 @@ export const PricingPane = async ({
expiresAt={user.subscriptionEndsAfter}
/>
)}

{/* {name === "Basic" ? (
<Button
className={
isSecondary
? " w-full bg-white hover:bg-white !text-primary border border-muted-foreground mt-6 justify-center"
: "w-full"
}
>
Current Plan
</Button>
) : (
<Button
className={
isSecondary
? " w-full bg-white hover:bg-white !text-primary border border-muted-foreground mt-6 justify-center"
: "w-full"
}
>
Subscribe
</Button>
)} */}
</div>
);
};
Expand Down
24 changes: 13 additions & 11 deletions apps/web/app/account/billing/resume-subscription-button.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -47,14 +47,16 @@ export default function ResumeSubscriptionButton({
Resume subscription
</Submit>

<p className="text-center text-sm text-slate-500">
Expires at{" "}
{new Date(expiresAt).toLocaleDateString(undefined, {
day: "numeric",
month: "long",
year: "numeric",
})}
</p>
{currentPlan !== "Basic" && subscriptionStatus === "cancelled" && (
<p className="text-center text-sm text-slate-500">
Expires at{" "}
{new Date(expiresAt).toLocaleDateString(undefined, {
day: "numeric",
month: "long",
year: "numeric",
})}
</p>
)}
</form>
);
}
Expand All @@ -73,8 +75,9 @@ function Submit({
let className;

if (currentPlan === "Basic" && subscriptionStatus === "cancelled") {
buttonText = "Downgrade to free";
className = "bg-primary hover:bg-[#333333]";
buttonText = "Current plan";
className =
"pointer-events-none w-full mb-6 bg-white hover:bg-white !text-muted-foreground border border-muted-foreground";
}

return (
Expand All @@ -84,7 +87,6 @@ function Submit({
variant="secondary"
disabled={status.pending}
>
{/* {children} */}
{buttonText}
</Button>
);
Expand Down
7 changes: 3 additions & 4 deletions apps/web/app/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import {
import { getUserFromSession } from "@/lib/user-handlers";
import { Apikey } from "@medialit/models";
import UserModel from "@/models/user";
import User from "@medialit/models";
import { User } from "@medialit/models";

export async function authenticate(
prevState: Record<string, unknown>,
Expand Down Expand Up @@ -104,14 +104,13 @@ export async function getUser(): Promise<any | null> {
}

export async function getSubscriber(): Promise<Pick<
// User,
any,
User,
| "email"
| "active"
| "userId"
| "email"
| "subscriptionEndsAfter"
| "subscriptionStatus"
| "subscribedToUpdates"
> | null> {
const session: Session | null = await auth();
if (!session || !session.user) {
Expand Down
9 changes: 4 additions & 5 deletions apps/web/app/payment/webhook/lemonsqueezy/route.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { LEMONSQUEEZY_WEBHOOK_SECRET } from "@/lib/constants";
import UserModel from "@/models/user";
import User from "@medialit/models";
import { User } from "@medialit/models";
import { cookies } from "next/headers";

export async function GET() {
Expand All @@ -16,9 +16,8 @@ export async function POST(request: Request, response: Response) {
return Response.json({ success: false });
}

const user: any = await UserModel.findOne({
// userId: event.meta.custom_data.subscriberId
userId: event.data.id,
const user: User | null = await UserModel.findOne({
userId: event.meta.custom_data.userId,
});

if (!user) {
Expand All @@ -32,7 +31,7 @@ export async function POST(request: Request, response: Response) {
) {
user.subscriptionMethod = "lemon";
user.customerId = event.data.attributes.customer_id;
user.userId = event.data.id;
user.subscriptionId = event.data.id;
}
user.subscriptionStatus = getSubscripiontStatus(event);

Expand Down

0 comments on commit 511fa68

Please sign in to comment.