Unify active subscriptions into one card with plan pickers for grant and extend.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Yared Yemane 2026-08-10 14:01:57 +03:00
parent 990c92c78a
commit 9720daea05
3 changed files with 175 additions and 162 deletions

View File

@ -130,7 +130,7 @@ export function ExtendSubscriptionDialog({
}) })
: "the plan price" : "the plan price"
const showPlanPicker = subscriptions.length > 1 const showPlanPicker = subscriptions.length > 0
return ( return (
<> <>
@ -152,9 +152,8 @@ export function ExtendSubscriptionDialog({
Extend subscription Extend subscription
</DialogTitle> </DialogTitle>
<DialogDescription className="text-sm text-grayScale-500"> <DialogDescription className="text-sm text-grayScale-500">
Extend by one plan period Extend by one plan period. Select which active subscription to extend, then
{showPlanPicker ? ". Choose which active subscription to extend" : ""} choose whether to record a payment at the plan price.
. Choose whether to record a payment at the plan price.
</DialogDescription> </DialogDescription>
</DialogHeader> </DialogHeader>

View File

@ -31,9 +31,8 @@ type GrantSubscriptionDialogProps = {
onOpenChange: (open: boolean) => void onOpenChange: (open: boolean) => void
userId: number userId: number
userName?: string userName?: string
/** Categories that already have an active subscription for this learner. */
activeByCategory: Record<string, boolean> activeByCategory: Record<string, boolean>
/** Plan IDs the learner already has an active subscription for. */
activePlanIds?: Set<number> | number[]
onGranted: () => void onGranted: () => void
} }
@ -41,13 +40,19 @@ function planLabel(plan: SubscriptionPlan): string {
return `${plan.name} · ${formatPlanCategory(plan.category)} · ${formatPlanDuration(plan)} · ${formatPlanPrice(plan)}` return `${plan.name} · ${formatPlanCategory(plan.category)} · ${formatPlanDuration(plan)} · ${formatPlanPrice(plan)}`
} }
function isCategoryActive(
category: string,
activeByCategory: Record<string, boolean>,
): boolean {
return activeByCategory[category] === true
}
export function GrantSubscriptionDialog({ export function GrantSubscriptionDialog({
open, open,
onOpenChange, onOpenChange,
userId, userId,
userName, userName,
activeByCategory, activeByCategory,
activePlanIds,
onGranted, onGranted,
}: GrantSubscriptionDialogProps) { }: GrantSubscriptionDialogProps) {
const [plans, setPlans] = useState<SubscriptionPlan[]>([]) const [plans, setPlans] = useState<SubscriptionPlan[]>([])
@ -60,10 +65,15 @@ export function GrantSubscriptionDialog({
const [saving, setSaving] = useState(false) const [saving, setSaving] = useState(false)
const [formError, setFormError] = useState<string | null>(null) const [formError, setFormError] = useState<string | null>(null)
const activePlanIdSet = useMemo(() => { const activeCategoryKey = useMemo(
if (!activePlanIds) return new Set<number>() () =>
return activePlanIds instanceof Set ? activePlanIds : new Set(activePlanIds) Object.entries(activeByCategory)
}, [activePlanIds]) .filter(([, active]) => active)
.map(([category]) => category)
.sort()
.join("|"),
[activeByCategory],
)
useEffect(() => { useEffect(() => {
if (!open) return if (!open) return
@ -79,7 +89,12 @@ export function GrantSubscriptionDialog({
setPlansLoading(true) setPlansLoading(true)
try { try {
const res = await getSubscriptionPlans() const res = await getSubscriptionPlans()
setPlans(res.data.filter((plan) => plan.is_active)) setPlans(
res.data.filter(
(plan) =>
plan.is_active && !isCategoryActive(plan.category, activeByCategory),
),
)
} catch (err) { } catch (err) {
setPlans([]) setPlans([])
notifyApiError(err, "Failed to load subscription plans") notifyApiError(err, "Failed to load subscription plans")
@ -88,19 +103,15 @@ export function GrantSubscriptionDialog({
} }
} }
void loadPlans() void loadPlans()
}, [open]) // activeCategoryKey captures category coverage; activeByCategory is read for filtering.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [open, activeCategoryKey])
const selectedPlan = useMemo( const selectedPlan = useMemo(
() => plans.find((p) => String(p.id) === planId) ?? null, () => plans.find((p) => String(p.id) === planId) ?? null,
[plans, planId], [plans, planId],
) )
const planAlreadyActive =
selectedPlan != null && activePlanIdSet.has(selectedPlan.id)
const categoryBlocked =
selectedPlan != null && activeByCategory[selectedPlan.category] === true
const grantBlocked = planAlreadyActive || categoryBlocked
const filteredPlans = useMemo(() => { const filteredPlans = useMemo(() => {
const q = planSearch.trim().toLowerCase() const q = planSearch.trim().toLowerCase()
if (!q) return plans if (!q) return plans
@ -128,13 +139,11 @@ export function GrantSubscriptionDialog({
setFormError("Select a subscription plan.") setFormError("Select a subscription plan.")
return return
} }
if (planAlreadyActive) { if (!selectedPlan) {
setFormError( setFormError("Select a subscription plan.")
"This learner already has an active subscription for that plan. Extend it instead.",
)
return return
} }
if (categoryBlocked) { if (isCategoryActive(selectedPlan.category, activeByCategory)) {
setFormError( setFormError(
"This learner already has an active subscription in that category. Extend the existing plan or cancel it first.", "This learner already has an active subscription in that category. Extend the existing plan or cancel it first.",
) )
@ -146,7 +155,8 @@ export function GrantSubscriptionDialog({
const handleConfirmGrant = async () => { const handleConfirmGrant = async () => {
const id = Number(planId) const id = Number(planId)
if (!Number.isFinite(id) || id < 1 || grantBlocked) return if (!Number.isFinite(id) || id < 1 || !selectedPlan) return
if (isCategoryActive(selectedPlan.category, activeByCategory)) return
setSaving(true) setSaving(true)
try { try {
@ -189,8 +199,9 @@ export function GrantSubscriptionDialog({
</DialogTitle> </DialogTitle>
<DialogDescription className="text-sm text-grayScale-500"> <DialogDescription className="text-sm text-grayScale-500">
Grant plan access Grant plan access
{userName ? ` to ${userName}` : ""}. Choose whether to record a {userName ? ` to ${userName}` : ""}. Only plans in categories without an
payment at the plan price. active subscription are listed. Choose whether to record a payment at the
plan price.
</DialogDescription> </DialogDescription>
</DialogHeader> </DialogHeader>
@ -204,6 +215,11 @@ export function GrantSubscriptionDialog({
<SpinnerIcon className="h-4 w-4" /> <SpinnerIcon className="h-4 w-4" />
Loading plans… Loading plans…
</div> </div>
) : plans.length === 0 ? (
<p className="text-sm text-grayScale-500">
No grantable plans left — every available category already has an
active subscription.
</p>
) : ( ) : (
<div className="space-y-2"> <div className="space-y-2">
<button <button
@ -244,9 +260,6 @@ export function GrantSubscriptionDialog({
role="listbox" role="listbox"
> >
{filteredPlans.map((plan) => { {filteredPlans.map((plan) => {
const alreadyActive = activePlanIdSet.has(plan.id)
const blocked =
alreadyActive || activeByCategory[plan.category] === true
const selected = String(plan.id) === planId const selected = String(plan.id) === planId
return ( return (
<button <button
@ -254,16 +267,13 @@ export function GrantSubscriptionDialog({
type="button" type="button"
role="option" role="option"
aria-selected={selected} aria-selected={selected}
disabled={blocked}
className={cn( className={cn(
"w-full rounded-md px-2 py-2 text-left text-sm transition", "w-full rounded-md px-2 py-2 text-left text-sm transition",
blocked && "cursor-not-allowed opacity-50",
selected selected
? "bg-brand-100/50 text-brand-700" ? "bg-brand-100/50 text-brand-700"
: "text-grayScale-600 hover:bg-grayScale-100", : "text-grayScale-600 hover:bg-grayScale-100",
)} )}
onClick={() => { onClick={() => {
if (blocked) return
setPlanId(String(plan.id)) setPlanId(String(plan.id))
setPlanMenuOpen(false) setPlanMenuOpen(false)
setPlanSearch("") setPlanSearch("")
@ -274,11 +284,6 @@ export function GrantSubscriptionDialog({
<span className="block text-xs text-grayScale-400"> <span className="block text-xs text-grayScale-400">
{formatPlanCategory(plan.category)} · {formatPlanDuration(plan)} ·{" "} {formatPlanCategory(plan.category)} · {formatPlanDuration(plan)} ·{" "}
{formatPlanPrice(plan)} {formatPlanPrice(plan)}
{alreadyActive
? " — already active"
: activeByCategory[plan.category] === true
? " — category active"
: ""}
</span> </span>
</button> </button>
) )
@ -293,13 +298,6 @@ export function GrantSubscriptionDialog({
) : null} ) : null}
</div> </div>
)} )}
{selectedPlan && grantBlocked ? (
<p className="text-xs text-amber-700">
{planAlreadyActive
? "This plan is already active for the learner. Extend it instead."
: `An active ${formatPlanCategory(selectedPlan.category)} subscription already exists. Extend or cancel it instead.`}
</p>
) : null}
</div> </div>
<div className="space-y-2"> <div className="space-y-2">
@ -378,7 +376,7 @@ export function GrantSubscriptionDialog({
</Button> </Button>
<Button <Button
type="submit" type="submit"
disabled={saving || plansLoading || !planId || grantBlocked} disabled={saving || plansLoading || !planId || plans.length === 0}
className="rounded-[6px] bg-brand-500 font-semibold text-white hover:bg-brand-600" className="rounded-[6px] bg-brand-500 font-semibold text-white hover:bg-brand-600"
> >
Continue Continue

View File

@ -134,85 +134,116 @@ function ActiveStatusBadge({
) )
} }
function SubscriptionManageCard({ function ActiveSubscriptionsCard({
subscription, subscriptions,
canExtend, canExtend,
canGrant, canGrant,
canCancel, canCancel,
grantEnabled, grantEnabled,
extendEnabled,
onExtend, onExtend,
onGrant, onGrant,
onCancel, onCancel,
}: { }: {
subscription: UserSubscriptionRecord subscriptions: UserSubscriptionRecord[]
canExtend: boolean canExtend: boolean
canGrant: boolean canGrant: boolean
canCancel: boolean canCancel: boolean
grantEnabled: boolean grantEnabled: boolean
extendEnabled: boolean
onExtend: () => void onExtend: () => void
onGrant: () => void onGrant: () => void
onCancel: () => void onCancel: (subscription: UserSubscriptionRecord) => void
}) { }) {
const daysLeft = getDaysLeft(subscription) const anyActive = subscriptions.some(
const statusUpper = subscription.status.toUpperCase() (subscription) =>
const isActive = subscription.is_currently_active || statusUpper === "ACTIVE" subscription.is_currently_active || subscription.status.toUpperCase() === "ACTIVE",
const statusTone = isActive ? "active" : statusUpper === "PENDING" ? "pending" : "inactive" )
const isLifetime = !canExtendSubscription(subscription)
const extendEnabled = canExtend && isActive && !isLifetime
const cancelEnabled = canCancel && isActive && statusUpper !== "CANCELLED"
return ( return (
<div className="rounded-2xl border border-grayScale-200 bg-white p-5 shadow-sm sm:p-6"> <div className="rounded-2xl border border-grayScale-200 bg-white p-5 shadow-sm sm:p-6">
<div className="flex items-start justify-between gap-3"> <div className="flex items-start justify-between gap-3">
<h3 className="text-base font-bold text-grayScale-900">Subscription</h3> <div>
<ActiveStatusBadge label={formatStatusLabel(subscription.status)} tone={statusTone} /> <h3 className="text-base font-bold text-grayScale-900">Subscriptions</h3>
<p className="mt-0.5 text-xs text-grayScale-500">
{subscriptions.length} active plan{subscriptions.length === 1 ? "" : "s"}
</p>
</div>
<ActiveStatusBadge
label={anyActive ? "Active" : formatStatusLabel(subscriptions[0]?.status || "Inactive")}
tone={anyActive ? "active" : "inactive"}
/>
</div> </div>
<div className="mt-4 border-t border-grayScale-100 pt-4"> <div className="mt-4 space-y-3 border-t border-grayScale-100 pt-4">
<div className="grid gap-5 sm:grid-cols-2"> {subscriptions.map((subscription) => {
<div> const daysLeft = getDaysLeft(subscription)
<p className="text-xs font-medium text-grayScale-400">Current Plan</p> const statusUpper = subscription.status.toUpperCase()
<p className="mt-1 text-lg font-bold tracking-tight text-grayScale-900"> const isActive =
{formatPlanTitle(subscription)} subscription.is_currently_active || statusUpper === "ACTIVE"
</p> const cancelEnabled =
<p className="mt-0.5 text-xs text-grayScale-500"> canCancel && isActive && statusUpper !== "CANCELLED"
{formatPlanCategory(subscription.plan_category)}
</p> return (
</div> <div
<div> key={subscription.id}
<p className="text-xs font-medium text-grayScale-400">Expires On</p> className="rounded-xl border border-grayScale-100 bg-grayScale-50/70 px-4 py-3"
<div className="mt-1 flex flex-wrap items-center gap-2"> >
<p className="text-lg font-bold tracking-tight text-grayScale-900"> <div className="flex flex-wrap items-start justify-between gap-3">
{formatExpiryDate(subscription)} <div className="min-w-0 flex-1">
</p> <p className="text-sm font-bold text-grayScale-900">
{daysLeft != null ? ( {formatPlanTitle(subscription)}
<span </p>
className={cn( <p className="mt-0.5 text-xs text-grayScale-500">
"inline-flex rounded-full px-2 py-0.5 text-[11px] font-semibold", {formatPlanCategory(subscription.plan_category)} · Expires{" "}
daysLeft <= 0 {formatExpiryDate(subscription)}
? "bg-destructive/10 text-destructive" {daysLeft != null ? ` · ${formatDaysLeftLabel(daysLeft)}` : ""}
: daysLeft <= 14 </p>
? "bg-orange-50 text-orange-600" </div>
: "bg-emerald-50 text-emerald-700", <div className="flex flex-wrap items-center gap-2">
)} <ActiveStatusBadge
> label={formatStatusLabel(subscription.status)}
{formatDaysLeftLabel(daysLeft)} tone={
</span> isActive
) : null} ? "active"
: statusUpper === "PENDING"
? "pending"
: "inactive"
}
/>
{canCancel ? (
<Button
type="button"
variant="outline"
size="sm"
className="h-8 rounded-lg text-xs text-destructive disabled:pointer-events-auto disabled:cursor-not-allowed disabled:opacity-50"
disabled={!cancelEnabled}
title={
!cancelEnabled
? "Cancel is only available when this subscription is active."
: undefined
}
onClick={() => onCancel(subscription)}
>
Cancel
</Button>
) : null}
</div>
</div>
</div> </div>
</div> )
</div> })}
</div> </div>
<div className="mt-6 flex flex-col gap-2"> <div className="mt-6 flex flex-col gap-2">
{canExtend && !isLifetime ? ( {canExtend ? (
<Button <Button
type="button" type="button"
className="h-10 w-full rounded-xl bg-brand-500 text-sm font-semibold text-white hover:bg-brand-600 disabled:pointer-events-auto disabled:cursor-not-allowed disabled:opacity-50" className="h-10 w-full rounded-xl bg-brand-500 text-sm font-semibold text-white hover:bg-brand-600 disabled:pointer-events-auto disabled:cursor-not-allowed disabled:opacity-50"
disabled={!extendEnabled} disabled={!extendEnabled}
title={ title={
!extendEnabled !extendEnabled
? "Extend is only available for an active, non-lifetime subscription." ? "Extend is only available when this learner has an active, non-lifetime subscription."
: undefined : undefined
} }
onClick={onExtend} onClick={onExtend}
@ -222,41 +253,21 @@ function SubscriptionManageCard({
</Button> </Button>
) : null} ) : null}
{(canGrant || canCancel) && ( {canGrant ? (
<div className="flex flex-wrap gap-2"> <Button
{canGrant ? ( type="button"
<Button className="h-10 w-full rounded-xl bg-grayScale-100 text-sm font-semibold text-grayScale-700 hover:bg-grayScale-200 disabled:pointer-events-auto disabled:cursor-not-allowed disabled:opacity-50"
type="button" disabled={!grantEnabled}
className="h-10 min-w-0 flex-1 rounded-xl bg-grayScale-100 text-sm font-semibold text-grayScale-700 hover:bg-grayScale-200 disabled:pointer-events-auto disabled:cursor-not-allowed disabled:opacity-50" title={
disabled={!grantEnabled} !grantEnabled
title={ ? "Grant is unavailable because every plan category already has an active subscription."
!grantEnabled : undefined
? "Grant is unavailable because this learner already has an active subscription for every available plan." }
: undefined onClick={onGrant}
} >
onClick={onGrant} Grant Subscription
> </Button>
Grant Subscription ) : null}
</Button>
) : null}
{canCancel ? (
<Button
type="button"
variant="outline"
className="h-10 min-w-0 flex-1 rounded-xl border-grayScale-200 bg-white text-sm font-semibold text-grayScale-700 hover:bg-grayScale-50 disabled:pointer-events-auto disabled:cursor-not-allowed disabled:opacity-50"
disabled={!cancelEnabled}
title={
!cancelEnabled
? "Cancel is only available when this subscription is active."
: undefined
}
onClick={onCancel}
>
Cancel
</Button>
) : null}
</div>
)}
</div> </div>
</div> </div>
) )
@ -284,7 +295,7 @@ function EmptySubscriptionCard({
return ( return (
<div className="rounded-2xl border border-grayScale-200 bg-white p-5 shadow-sm sm:p-6"> <div className="rounded-2xl border border-grayScale-200 bg-white p-5 shadow-sm sm:p-6">
<div className="flex items-start justify-between gap-3"> <div className="flex items-start justify-between gap-3">
<h3 className="text-base font-bold text-grayScale-900">Subscription</h3> <h3 className="text-base font-bold text-grayScale-900">Subscriptions</h3>
<ActiveStatusBadge <ActiveStatusBadge
label={formatStatusLabel(displayStatus || "Unsubscribed")} label={formatStatusLabel(displayStatus || "Unsubscribed")}
tone={tone} tone={tone}
@ -408,23 +419,33 @@ export function UserSubscriptionsSection({
} }
}, [userId]) }, [userId])
const subscribedPlanIds = useMemo(() => { const activeCategories = useMemo(() => {
return new Set( const fromSubs = activePlans
activePlans .filter(
.filter( (subscription) =>
(subscription) => subscription.is_currently_active ||
subscription.is_currently_active || subscription.status.toUpperCase() === "ACTIVE",
subscription.status.toUpperCase() === "ACTIVE", )
) .map((subscription) => subscription.plan_category)
.map((subscription) => subscription.plan_id), .filter((category) => Boolean(category?.trim()))
)
}, [activePlans])
// Disable grant only when every available active plan already has an active subscription. const categories = new Set(fromSubs)
const allActivePlansSubscribed = for (const [category, active] of Object.entries(
catalogPlans.length > 0 && subscriptions?.active_by_category ?? {},
catalogPlans.every((plan) => subscribedPlanIds.has(plan.id)) )) {
const grantEnabled = showGrant && !allActivePlansSubscribed if (active) categories.add(category)
}
return categories
}, [activePlans, subscriptions?.active_by_category])
// Grant is available when at least one active catalog plan is in a category
// the learner does not already have covered.
const hasGrantablePlan =
catalogPlans.length === 0
? true
: catalogPlans.some((plan) => !activeCategories.has(plan.category))
const grantEnabled = showGrant && hasGrantablePlan
const extendEnabled = canExtend && extendableActivePlans.length > 0
const openExtend = (preferred?: UserSubscriptionRecord) => { const openExtend = (preferred?: UserSubscriptionRecord) => {
const preferredId = const preferredId =
@ -462,21 +483,17 @@ export function UserSubscriptionsSection({
{!loading && !error && subscriptions ? ( {!loading && !error && subscriptions ? (
<> <>
{activePlans.length > 0 ? ( {activePlans.length > 0 ? (
<div className="space-y-4"> <ActiveSubscriptionsCard
{activePlans.map((subscription) => ( subscriptions={activePlans}
<SubscriptionManageCard canExtend={canExtend}
key={subscription.id} canGrant={showGrant}
subscription={subscription} canCancel={canCancel}
canExtend={canExtend} grantEnabled={grantEnabled}
canGrant={showGrant} extendEnabled={extendEnabled}
canCancel={canCancel} onExtend={() => openExtend()}
grantEnabled={grantEnabled} onGrant={() => setGrantOpen(true)}
onExtend={() => openExtend(subscription)} onCancel={(subscription) => setCancelTarget(subscription)}
onGrant={() => setGrantOpen(true)} />
onCancel={() => setCancelTarget(subscription)}
/>
))}
</div>
) : ( ) : (
<EmptySubscriptionCard <EmptySubscriptionCard
displayStatus={subscriptions.display_status} displayStatus={subscriptions.display_status}
@ -666,7 +683,6 @@ export function UserSubscriptionsSection({
userId={userId} userId={userId}
userName={userName} userName={userName}
activeByCategory={subscriptions?.active_by_category ?? {}} activeByCategory={subscriptions?.active_by_category ?? {}}
activePlanIds={subscribedPlanIds}
onGranted={onRefresh} onGranted={onRefresh}
/> />