Allow granting more plans and picking which active subscription to extend.
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
9f658f9cf6
commit
990c92c78a
|
|
@ -1,4 +1,4 @@
|
|||
import { useEffect, useState } from "react"
|
||||
import { useEffect, useMemo, useState } from "react"
|
||||
import { RefreshCw } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
import { adminApplySubscription } from "../../../api/admin-subscriptions.api"
|
||||
|
|
@ -23,7 +23,10 @@ type ExtendSubscriptionDialogProps = {
|
|||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
userId: number
|
||||
subscription: UserSubscriptionRecord | null
|
||||
/** Active, non-lifetime subscriptions the admin can extend. */
|
||||
subscriptions: UserSubscriptionRecord[]
|
||||
/** Preferred subscription id when opening (e.g. from a specific card). */
|
||||
initialSubscriptionId?: number | null
|
||||
onExtended: () => void
|
||||
}
|
||||
|
||||
|
|
@ -40,13 +43,23 @@ function formatDateTime(value?: string | null): string {
|
|||
})
|
||||
}
|
||||
|
||||
function subscriptionOptionLabel(subscription: UserSubscriptionRecord): string {
|
||||
const name = subscription.plan_name?.trim() || `Plan #${subscription.plan_id}`
|
||||
const category = subscription.plan_category
|
||||
? ` · ${formatPlanCategory(subscription.plan_category)}`
|
||||
: ""
|
||||
return `${name}${category} (#${subscription.id})`
|
||||
}
|
||||
|
||||
export function ExtendSubscriptionDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
userId,
|
||||
subscription,
|
||||
subscriptions,
|
||||
initialSubscriptionId = null,
|
||||
onExtended,
|
||||
}: ExtendSubscriptionDialogProps) {
|
||||
const [selectedSubscriptionId, setSelectedSubscriptionId] = useState<string>("")
|
||||
const [recordPayment, setRecordPayment] = useState(true)
|
||||
const [confirmOpen, setConfirmOpen] = useState(false)
|
||||
const [saving, setSaving] = useState(false)
|
||||
|
|
@ -56,8 +69,26 @@ export function ExtendSubscriptionDialog({
|
|||
setSaving(false)
|
||||
setConfirmOpen(false)
|
||||
setRecordPayment(true)
|
||||
setSelectedSubscriptionId("")
|
||||
return
|
||||
}
|
||||
}, [open, subscription?.id])
|
||||
|
||||
const preferred =
|
||||
(initialSubscriptionId != null &&
|
||||
subscriptions.find((subscription) => subscription.id === initialSubscriptionId)) ||
|
||||
subscriptions[0] ||
|
||||
null
|
||||
setSelectedSubscriptionId(preferred ? String(preferred.id) : "")
|
||||
setRecordPayment(true)
|
||||
setConfirmOpen(false)
|
||||
setSaving(false)
|
||||
}, [open, initialSubscriptionId, subscriptions])
|
||||
|
||||
const subscription = useMemo(
|
||||
() =>
|
||||
subscriptions.find((item) => String(item.id) === selectedSubscriptionId) ?? null,
|
||||
[subscriptions, selectedSubscriptionId],
|
||||
)
|
||||
|
||||
const handleContinue = (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
|
|
@ -99,10 +130,12 @@ export function ExtendSubscriptionDialog({
|
|||
})
|
||||
: "the plan price"
|
||||
|
||||
const showPlanPicker = subscriptions.length > 1
|
||||
|
||||
return (
|
||||
<>
|
||||
<Dialog
|
||||
open={open && subscription != null && !confirmOpen}
|
||||
open={open && subscriptions.length > 0 && !confirmOpen}
|
||||
onOpenChange={(next) => {
|
||||
if (saving) return
|
||||
if (!next) {
|
||||
|
|
@ -119,12 +152,36 @@ export function ExtendSubscriptionDialog({
|
|||
Extend subscription
|
||||
</DialogTitle>
|
||||
<DialogDescription className="text-sm text-grayScale-500">
|
||||
Extend by one plan period. Choose whether to record a payment at the plan
|
||||
price.
|
||||
Extend by one plan period
|
||||
{showPlanPicker ? ". Choose which active subscription to extend" : ""}
|
||||
. Choose whether to record a payment at the plan price.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4 px-6 py-5">
|
||||
{showPlanPicker ? (
|
||||
<div className="space-y-1.5">
|
||||
<label
|
||||
htmlFor="extend-subscription-plan"
|
||||
className="text-[11px] font-bold uppercase tracking-wider text-grayScale-400"
|
||||
>
|
||||
Active subscription <span className="text-destructive">*</span>
|
||||
</label>
|
||||
<select
|
||||
id="extend-subscription-plan"
|
||||
className="h-11 w-full rounded-[6px] border border-input bg-grayScale-50 px-3 text-sm text-grayScale-700 shadow-sm focus:outline-none focus-visible:border-brand-400 focus-visible:ring-2 focus-visible:ring-brand-200"
|
||||
value={selectedSubscriptionId}
|
||||
onChange={(e) => setSelectedSubscriptionId(e.target.value)}
|
||||
>
|
||||
{subscriptions.map((item) => (
|
||||
<option key={item.id} value={String(item.id)}>
|
||||
{subscriptionOptionLabel(item)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{subscription ? (
|
||||
<div className="rounded-xl border border-grayScale-100 bg-grayScale-50 px-4 py-3 text-sm text-grayScale-700">
|
||||
<p>
|
||||
|
|
|
|||
|
|
@ -32,6 +32,8 @@ type GrantSubscriptionDialogProps = {
|
|||
userId: number
|
||||
userName?: string
|
||||
activeByCategory: Record<string, boolean>
|
||||
/** Plan IDs the learner already has an active subscription for. */
|
||||
activePlanIds?: Set<number> | number[]
|
||||
onGranted: () => void
|
||||
}
|
||||
|
||||
|
|
@ -45,6 +47,7 @@ export function GrantSubscriptionDialog({
|
|||
userId,
|
||||
userName,
|
||||
activeByCategory,
|
||||
activePlanIds,
|
||||
onGranted,
|
||||
}: GrantSubscriptionDialogProps) {
|
||||
const [plans, setPlans] = useState<SubscriptionPlan[]>([])
|
||||
|
|
@ -57,6 +60,11 @@ export function GrantSubscriptionDialog({
|
|||
const [saving, setSaving] = useState(false)
|
||||
const [formError, setFormError] = useState<string | null>(null)
|
||||
|
||||
const activePlanIdSet = useMemo(() => {
|
||||
if (!activePlanIds) return new Set<number>()
|
||||
return activePlanIds instanceof Set ? activePlanIds : new Set(activePlanIds)
|
||||
}, [activePlanIds])
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
setPlanId("")
|
||||
|
|
@ -87,8 +95,11 @@ export function GrantSubscriptionDialog({
|
|||
[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 q = planSearch.trim().toLowerCase()
|
||||
|
|
@ -117,6 +128,12 @@ export function GrantSubscriptionDialog({
|
|||
setFormError("Select a subscription plan.")
|
||||
return
|
||||
}
|
||||
if (planAlreadyActive) {
|
||||
setFormError(
|
||||
"This learner already has an active subscription for that plan. Extend it instead.",
|
||||
)
|
||||
return
|
||||
}
|
||||
if (categoryBlocked) {
|
||||
setFormError(
|
||||
"This learner already has an active subscription in that category. Extend the existing plan or cancel it first.",
|
||||
|
|
@ -129,7 +146,7 @@ export function GrantSubscriptionDialog({
|
|||
|
||||
const handleConfirmGrant = async () => {
|
||||
const id = Number(planId)
|
||||
if (!Number.isFinite(id) || id < 1 || categoryBlocked) return
|
||||
if (!Number.isFinite(id) || id < 1 || grantBlocked) return
|
||||
|
||||
setSaving(true)
|
||||
try {
|
||||
|
|
@ -227,7 +244,9 @@ export function GrantSubscriptionDialog({
|
|||
role="listbox"
|
||||
>
|
||||
{filteredPlans.map((plan) => {
|
||||
const blocked = activeByCategory[plan.category] === true
|
||||
const alreadyActive = activePlanIdSet.has(plan.id)
|
||||
const blocked =
|
||||
alreadyActive || activeByCategory[plan.category] === true
|
||||
const selected = String(plan.id) === planId
|
||||
return (
|
||||
<button
|
||||
|
|
@ -255,7 +274,11 @@ export function GrantSubscriptionDialog({
|
|||
<span className="block text-xs text-grayScale-400">
|
||||
{formatPlanCategory(plan.category)} · {formatPlanDuration(plan)} ·{" "}
|
||||
{formatPlanPrice(plan)}
|
||||
{blocked ? " — category active" : ""}
|
||||
{alreadyActive
|
||||
? " — already active"
|
||||
: activeByCategory[plan.category] === true
|
||||
? " — category active"
|
||||
: ""}
|
||||
</span>
|
||||
</button>
|
||||
)
|
||||
|
|
@ -270,10 +293,11 @@ export function GrantSubscriptionDialog({
|
|||
) : null}
|
||||
</div>
|
||||
)}
|
||||
{selectedPlan && categoryBlocked ? (
|
||||
{selectedPlan && grantBlocked ? (
|
||||
<p className="text-xs text-amber-700">
|
||||
An active {formatPlanCategory(selectedPlan.category)} subscription already
|
||||
exists. Extend or cancel it instead.
|
||||
{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>
|
||||
|
|
@ -354,7 +378,7 @@ export function GrantSubscriptionDialog({
|
|||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={saving || plansLoading || !planId || categoryBlocked}
|
||||
disabled={saving || plansLoading || !planId || grantBlocked}
|
||||
className="rounded-[6px] bg-brand-500 font-semibold text-white hover:bg-brand-600"
|
||||
>
|
||||
Continue
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { useMemo, useState } from "react"
|
||||
import { useEffect, useMemo, useState } from "react"
|
||||
import { ChevronDown, ChevronRight, RefreshCw } from "lucide-react"
|
||||
import { getSubscriptionPlans } from "../../../api/subscription-plans.api"
|
||||
import { Button } from "../../../components/ui/button"
|
||||
import { Card, CardContent } from "../../../components/ui/card"
|
||||
import { SpinnerIcon } from "../../../components/ui/spinner-icon"
|
||||
|
|
@ -12,7 +13,7 @@ import {
|
|||
TableRow,
|
||||
} from "../../../components/ui/table"
|
||||
import { useTeamPermissions } from "../../../hooks/useTeamPermissions"
|
||||
import { DisplayValue, NOT_ASSIGNED_LABEL, displayValue } from "../../../lib/displayValue"
|
||||
import { DisplayValue, NOT_ASSIGNED_LABEL } from "../../../lib/displayValue"
|
||||
import {
|
||||
formatAdminPaymentMethod,
|
||||
hasSubscriptionAdminPermission,
|
||||
|
|
@ -21,6 +22,7 @@ import {
|
|||
} from "../../../lib/subscriptionAdminPermissions"
|
||||
import { formatPlanCategory, isLifetimeExpiry } from "../../../lib/subscriptionPlans"
|
||||
import { cn } from "../../../lib/utils"
|
||||
import type { SubscriptionPlan } from "../../../types/subscription.types"
|
||||
import type { UserSubscriptionRecord, UserSubscriptionsData } from "../../../types/userAdmin.types"
|
||||
import { CancelSubscriptionDialog } from "./CancelSubscriptionDialog"
|
||||
import { ExtendSubscriptionDialog } from "./ExtendSubscriptionDialog"
|
||||
|
|
@ -137,7 +139,7 @@ function SubscriptionManageCard({
|
|||
canExtend,
|
||||
canGrant,
|
||||
canCancel,
|
||||
hasActiveSubscription,
|
||||
grantEnabled,
|
||||
onExtend,
|
||||
onGrant,
|
||||
onCancel,
|
||||
|
|
@ -146,7 +148,7 @@ function SubscriptionManageCard({
|
|||
canExtend: boolean
|
||||
canGrant: boolean
|
||||
canCancel: boolean
|
||||
hasActiveSubscription: boolean
|
||||
grantEnabled: boolean
|
||||
onExtend: () => void
|
||||
onGrant: () => void
|
||||
onCancel: () => void
|
||||
|
|
@ -156,9 +158,8 @@ function SubscriptionManageCard({
|
|||
const isActive = subscription.is_currently_active || statusUpper === "ACTIVE"
|
||||
const statusTone = isActive ? "active" : statusUpper === "PENDING" ? "pending" : "inactive"
|
||||
const isLifetime = !canExtendSubscription(subscription)
|
||||
const extendEnabled = canExtend && hasActiveSubscription && isActive && !isLifetime
|
||||
const cancelEnabled = canCancel && hasActiveSubscription && isActive && statusUpper !== "CANCELLED"
|
||||
const markAsPaidEnabled = canGrant && !hasActiveSubscription
|
||||
const extendEnabled = canExtend && isActive && !isLifetime
|
||||
const cancelEnabled = canCancel && isActive && statusUpper !== "CANCELLED"
|
||||
|
||||
return (
|
||||
<div className="rounded-2xl border border-grayScale-200 bg-white p-5 shadow-sm sm:p-6">
|
||||
|
|
@ -211,7 +212,7 @@ function SubscriptionManageCard({
|
|||
disabled={!extendEnabled}
|
||||
title={
|
||||
!extendEnabled
|
||||
? "Extend is only available when this learner has an active subscription."
|
||||
? "Extend is only available for an active, non-lifetime subscription."
|
||||
: undefined
|
||||
}
|
||||
onClick={onExtend}
|
||||
|
|
@ -227,10 +228,10 @@ function SubscriptionManageCard({
|
|||
<Button
|
||||
type="button"
|
||||
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"
|
||||
disabled={!markAsPaidEnabled}
|
||||
disabled={!grantEnabled}
|
||||
title={
|
||||
!markAsPaidEnabled
|
||||
? "Grant is unavailable while this learner already has an active subscription."
|
||||
!grantEnabled
|
||||
? "Grant is unavailable because this learner already has an active subscription for every available plan."
|
||||
: undefined
|
||||
}
|
||||
onClick={onGrant}
|
||||
|
|
@ -246,7 +247,7 @@ function SubscriptionManageCard({
|
|||
disabled={!cancelEnabled}
|
||||
title={
|
||||
!cancelEnabled
|
||||
? "Cancel is only available when this learner has an active subscription."
|
||||
? "Cancel is only available when this subscription is active."
|
||||
: undefined
|
||||
}
|
||||
onClick={onCancel}
|
||||
|
|
@ -266,12 +267,14 @@ function EmptySubscriptionCard({
|
|||
canGrant,
|
||||
canExtend,
|
||||
canCancel,
|
||||
grantEnabled,
|
||||
onGrant,
|
||||
}: {
|
||||
displayStatus: string
|
||||
canGrant: boolean
|
||||
canExtend: boolean
|
||||
canCancel: boolean
|
||||
grantEnabled: boolean
|
||||
onGrant: () => void
|
||||
}) {
|
||||
const upper = displayStatus.toUpperCase()
|
||||
|
|
@ -307,7 +310,13 @@ function EmptySubscriptionCard({
|
|||
{canGrant ? (
|
||||
<Button
|
||||
type="button"
|
||||
className="h-10 min-w-0 flex-1 rounded-xl bg-brand-500 text-sm font-semibold text-white hover:bg-brand-600"
|
||||
className="h-10 min-w-0 flex-1 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={!grantEnabled}
|
||||
title={
|
||||
!grantEnabled
|
||||
? "No active subscription plans are available to grant."
|
||||
: undefined
|
||||
}
|
||||
onClick={onGrant}
|
||||
>
|
||||
Grant Subscription
|
||||
|
|
@ -351,8 +360,12 @@ export function UserSubscriptionsSection({
|
|||
const { permissions } = useTeamPermissions()
|
||||
const [detailsOpen, setDetailsOpen] = useState(false)
|
||||
const [grantOpen, setGrantOpen] = useState(false)
|
||||
const [extendTarget, setExtendTarget] = useState<UserSubscriptionRecord | null>(null)
|
||||
const [extendOpen, setExtendOpen] = useState(false)
|
||||
const [extendInitialSubscriptionId, setExtendInitialSubscriptionId] = useState<number | null>(
|
||||
null,
|
||||
)
|
||||
const [cancelTarget, setCancelTarget] = useState<UserSubscriptionRecord | null>(null)
|
||||
const [catalogPlans, setCatalogPlans] = useState<SubscriptionPlan[]>([])
|
||||
|
||||
const canApply = hasSubscriptionAdminPermission(
|
||||
SUBSCRIPTION_ADMIN_PERMISSIONS.apply,
|
||||
|
|
@ -365,11 +378,62 @@ export function UserSubscriptionsSection({
|
|||
)
|
||||
const learner = isLearnerRole(userRole)
|
||||
const showGrant = canApply && learner
|
||||
const hasActiveSubscription =
|
||||
Boolean(subscriptions?.has_active_subscription) ||
|
||||
(subscriptions?.active_subscriptions.length ?? 0) > 0
|
||||
|
||||
const activePlans = subscriptions?.active_subscriptions ?? []
|
||||
const extendableActivePlans = useMemo(
|
||||
() =>
|
||||
activePlans.filter(
|
||||
(subscription) =>
|
||||
(subscription.is_currently_active ||
|
||||
subscription.status.toUpperCase() === "ACTIVE") &&
|
||||
canExtendSubscription(subscription),
|
||||
),
|
||||
[activePlans],
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
;(async () => {
|
||||
try {
|
||||
const res = await getSubscriptionPlans()
|
||||
if (!cancelled) {
|
||||
setCatalogPlans(res.data.filter((plan) => plan.is_active))
|
||||
}
|
||||
} catch {
|
||||
if (!cancelled) setCatalogPlans([])
|
||||
}
|
||||
})()
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [userId])
|
||||
|
||||
const subscribedPlanIds = useMemo(() => {
|
||||
return new Set(
|
||||
activePlans
|
||||
.filter(
|
||||
(subscription) =>
|
||||
subscription.is_currently_active ||
|
||||
subscription.status.toUpperCase() === "ACTIVE",
|
||||
)
|
||||
.map((subscription) => subscription.plan_id),
|
||||
)
|
||||
}, [activePlans])
|
||||
|
||||
// Disable grant only when every available active plan already has an active subscription.
|
||||
const allActivePlansSubscribed =
|
||||
catalogPlans.length > 0 &&
|
||||
catalogPlans.every((plan) => subscribedPlanIds.has(plan.id))
|
||||
const grantEnabled = showGrant && !allActivePlansSubscribed
|
||||
|
||||
const openExtend = (preferred?: UserSubscriptionRecord) => {
|
||||
const preferredId =
|
||||
preferred && canExtendSubscription(preferred) ? preferred.id : extendableActivePlans[0]?.id
|
||||
if (preferredId == null) return
|
||||
setExtendInitialSubscriptionId(preferredId)
|
||||
setExtendOpen(true)
|
||||
}
|
||||
|
||||
const recentPayments = subscriptions?.payments.slice(0, 12) ?? []
|
||||
const history = useMemo(() => {
|
||||
if (!subscriptions) return []
|
||||
|
|
@ -406,8 +470,8 @@ export function UserSubscriptionsSection({
|
|||
canExtend={canExtend}
|
||||
canGrant={showGrant}
|
||||
canCancel={canCancel}
|
||||
hasActiveSubscription={hasActiveSubscription}
|
||||
onExtend={() => setExtendTarget(subscription)}
|
||||
grantEnabled={grantEnabled}
|
||||
onExtend={() => openExtend(subscription)}
|
||||
onGrant={() => setGrantOpen(true)}
|
||||
onCancel={() => setCancelTarget(subscription)}
|
||||
/>
|
||||
|
|
@ -419,6 +483,7 @@ export function UserSubscriptionsSection({
|
|||
canGrant={showGrant}
|
||||
canExtend={canExtend}
|
||||
canCancel={canCancel}
|
||||
grantEnabled={grantEnabled}
|
||||
onGrant={() => setGrantOpen(true)}
|
||||
/>
|
||||
)}
|
||||
|
|
@ -501,13 +566,13 @@ export function UserSubscriptionsSection({
|
|||
variant="outline"
|
||||
size="sm"
|
||||
className="h-8 rounded-lg text-xs disabled:pointer-events-auto disabled:cursor-not-allowed disabled:opacity-50"
|
||||
disabled={!hasActiveSubscription || !subscription.is_currently_active}
|
||||
disabled={!subscription.is_currently_active}
|
||||
title={
|
||||
!hasActiveSubscription || !subscription.is_currently_active
|
||||
!subscription.is_currently_active
|
||||
? "Extend is only available for an active subscription."
|
||||
: undefined
|
||||
}
|
||||
onClick={() => setExtendTarget(subscription)}
|
||||
onClick={() => openExtend(subscription)}
|
||||
>
|
||||
Extend
|
||||
</Button>
|
||||
|
|
@ -519,12 +584,11 @@ export function UserSubscriptionsSection({
|
|||
size="sm"
|
||||
className="h-8 rounded-lg text-xs text-destructive disabled:pointer-events-auto disabled:cursor-not-allowed disabled:opacity-50"
|
||||
disabled={
|
||||
!hasActiveSubscription ||
|
||||
!subscription.is_currently_active ||
|
||||
subscription.status.toUpperCase() === "CANCELLED"
|
||||
}
|
||||
title={
|
||||
!hasActiveSubscription || !subscription.is_currently_active
|
||||
!subscription.is_currently_active
|
||||
? "Cancel is only available for an active subscription."
|
||||
: undefined
|
||||
}
|
||||
|
|
@ -602,16 +666,19 @@ export function UserSubscriptionsSection({
|
|||
userId={userId}
|
||||
userName={userName}
|
||||
activeByCategory={subscriptions?.active_by_category ?? {}}
|
||||
activePlanIds={subscribedPlanIds}
|
||||
onGranted={onRefresh}
|
||||
/>
|
||||
|
||||
<ExtendSubscriptionDialog
|
||||
open={extendTarget != null}
|
||||
open={extendOpen}
|
||||
onOpenChange={(next) => {
|
||||
if (!next) setExtendTarget(null)
|
||||
setExtendOpen(next)
|
||||
if (!next) setExtendInitialSubscriptionId(null)
|
||||
}}
|
||||
userId={userId}
|
||||
subscription={extendTarget}
|
||||
subscriptions={extendableActivePlans}
|
||||
initialSubscriptionId={extendInitialSubscriptionId}
|
||||
onExtended={onRefresh}
|
||||
/>
|
||||
|
||||
|
|
|
|||
Loading…
Reference in New Issue
Block a user