Skip to content

Instantly share code, notes, and snippets.

@feliche93
Created June 26, 2023 09:19
Show Gist options
  • Save feliche93/6c4b34485030e0f199bf4a883c942d5b to your computer and use it in GitHub Desktop.
Save feliche93/6c4b34485030e0f199bf4a883c942d5b to your computer and use it in GitHub Desktop.
Account Button to cancel or resume lemon squeezy subscription
'use client'
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from '@components/ui/alert-dialog'
import { buttonVariants } from '@components/ui/button'
import { deleteSubscription, updateSubscription } from '@lib/lemon-squeezy'
import Link from 'next/link'
import { useSelectedLayoutSegment } from 'next/navigation'
import { useTransition } from 'react'
import { SubscriptionType } from './header'
import { cn } from '@lib/utils'
export const AccountButtons = ({ subscription }: { subscription: SubscriptionType }) => {
let [isPending, startTransition] = useTransition()
const segment = useSelectedLayoutSegment()
if (segment !== 'billing') return null
if (!subscription) return null
let title = ''
let description = ''
let action = async () => {}
let subStatus = ''
let variant = buttonVariants({
variant: 'errorOutline',
})
// console.log(subscription.status)
switch (subscription.status) {
case 'active':
case 'on_trial':
title = 'Cancel Subscription'
description = 'Are you sure you want to cancel the subscription?'
subStatus = 'Subscription'
action = () => deleteSubscription({ subscriptionId: subscription.id })
break
case 'paused':
case 'past_due':
case 'unpaid':
case 'cancelled':
title = 'Resume Subscription'
description = 'Are you sure you want to resume the subscription?'
subStatus = 'Subscription'
action = async () =>
await updateSubscription({ subscriptionId: subscription.id, cancelled: false })
variant = buttonVariants({
variant: 'primary',
})
break
case 'expired':
return null
default:
return null
}
return (
<>
<AlertDialog>
<AlertDialogTrigger className={cn(variant, isPending && 'loading cursor-not-allowed')}>
{title}
</AlertDialogTrigger>
<AlertDialogContent className="bg-base-200">
<AlertDialogHeader>
<AlertDialogTitle>{title}</AlertDialogTitle>
<AlertDialogDescription>{description}</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Go Back</AlertDialogCancel>
<AlertDialogAction onClick={() => startTransition(() => action())} className={variant}>
{title}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
{typeof subscription.urls?.updatePaymentMethod === 'string' && (
<Link
target="_blank"
rel="noopener noreferrer"
href={subscription.urls.updatePaymentMethod}
className={buttonVariants({
variant: 'primaryOutline',
})}
>
Update Payment Method
</Link>
)}
</>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment