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 { RefreshCw } from "lucide-react"
|
||||||
import { toast } from "sonner"
|
import { toast } from "sonner"
|
||||||
import { adminApplySubscription } from "../../../api/admin-subscriptions.api"
|
import { adminApplySubscription } from "../../../api/admin-subscriptions.api"
|
||||||
|
|
@ -23,7 +23,10 @@ type ExtendSubscriptionDialogProps = {
|
||||||
open: boolean
|
open: boolean
|
||||||
onOpenChange: (open: boolean) => void
|
onOpenChange: (open: boolean) => void
|
||||||
userId: number
|
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
|
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({
|
export function ExtendSubscriptionDialog({
|
||||||
open,
|
open,
|
||||||
onOpenChange,
|
onOpenChange,
|
||||||
userId,
|
userId,
|
||||||
subscription,
|
subscriptions,
|
||||||
|
initialSubscriptionId = null,
|
||||||
onExtended,
|
onExtended,
|
||||||
}: ExtendSubscriptionDialogProps) {
|
}: ExtendSubscriptionDialogProps) {
|
||||||
|
const [selectedSubscriptionId, setSelectedSubscriptionId] = useState<string>("")
|
||||||
const [recordPayment, setRecordPayment] = useState(true)
|
const [recordPayment, setRecordPayment] = useState(true)
|
||||||
const [confirmOpen, setConfirmOpen] = useState(false)
|
const [confirmOpen, setConfirmOpen] = useState(false)
|
||||||
const [saving, setSaving] = useState(false)
|
const [saving, setSaving] = useState(false)
|
||||||
|
|
@ -56,8 +69,26 @@ export function ExtendSubscriptionDialog({
|
||||||
setSaving(false)
|
setSaving(false)
|
||||||
setConfirmOpen(false)
|
setConfirmOpen(false)
|
||||||
setRecordPayment(true)
|
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) => {
|
const handleContinue = (e: React.FormEvent) => {
|
||||||
e.preventDefault()
|
e.preventDefault()
|
||||||
|
|
@ -99,10 +130,12 @@ export function ExtendSubscriptionDialog({
|
||||||
})
|
})
|
||||||
: "the plan price"
|
: "the plan price"
|
||||||
|
|
||||||
|
const showPlanPicker = subscriptions.length > 1
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<Dialog
|
<Dialog
|
||||||
open={open && subscription != null && !confirmOpen}
|
open={open && subscriptions.length > 0 && !confirmOpen}
|
||||||
onOpenChange={(next) => {
|
onOpenChange={(next) => {
|
||||||
if (saving) return
|
if (saving) return
|
||||||
if (!next) {
|
if (!next) {
|
||||||
|
|
@ -119,12 +152,36 @@ 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. Choose whether to record a payment at the plan
|
Extend by one plan period
|
||||||
price.
|
{showPlanPicker ? ". Choose which active subscription to extend" : ""}
|
||||||
|
. Choose whether to record a payment at the plan price.
|
||||||
</DialogDescription>
|
</DialogDescription>
|
||||||
</DialogHeader>
|
</DialogHeader>
|
||||||
|
|
||||||
<div className="space-y-4 px-6 py-5">
|
<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 ? (
|
{subscription ? (
|
||||||
<div className="rounded-xl border border-grayScale-100 bg-grayScale-50 px-4 py-3 text-sm text-grayScale-700">
|
<div className="rounded-xl border border-grayScale-100 bg-grayScale-50 px-4 py-3 text-sm text-grayScale-700">
|
||||||
<p>
|
<p>
|
||||||
|
|
|
||||||
|
|
@ -32,6 +32,8 @@ type GrantSubscriptionDialogProps = {
|
||||||
userId: number
|
userId: number
|
||||||
userName?: string
|
userName?: string
|
||||||
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
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -45,6 +47,7 @@ export function GrantSubscriptionDialog({
|
||||||
userId,
|
userId,
|
||||||
userName,
|
userName,
|
||||||
activeByCategory,
|
activeByCategory,
|
||||||
|
activePlanIds,
|
||||||
onGranted,
|
onGranted,
|
||||||
}: GrantSubscriptionDialogProps) {
|
}: GrantSubscriptionDialogProps) {
|
||||||
const [plans, setPlans] = useState<SubscriptionPlan[]>([])
|
const [plans, setPlans] = useState<SubscriptionPlan[]>([])
|
||||||
|
|
@ -57,6 +60,11 @@ 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(() => {
|
||||||
|
if (!activePlanIds) return new Set<number>()
|
||||||
|
return activePlanIds instanceof Set ? activePlanIds : new Set(activePlanIds)
|
||||||
|
}, [activePlanIds])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!open) return
|
if (!open) return
|
||||||
setPlanId("")
|
setPlanId("")
|
||||||
|
|
@ -87,8 +95,11 @@ export function GrantSubscriptionDialog({
|
||||||
[plans, planId],
|
[plans, planId],
|
||||||
)
|
)
|
||||||
|
|
||||||
|
const planAlreadyActive =
|
||||||
|
selectedPlan != null && activePlanIdSet.has(selectedPlan.id)
|
||||||
const categoryBlocked =
|
const categoryBlocked =
|
||||||
selectedPlan != null && activeByCategory[selectedPlan.category] === true
|
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()
|
||||||
|
|
@ -117,6 +128,12 @@ export function GrantSubscriptionDialog({
|
||||||
setFormError("Select a subscription plan.")
|
setFormError("Select a subscription plan.")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if (planAlreadyActive) {
|
||||||
|
setFormError(
|
||||||
|
"This learner already has an active subscription for that plan. Extend it instead.",
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
if (categoryBlocked) {
|
if (categoryBlocked) {
|
||||||
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.",
|
||||||
|
|
@ -129,7 +146,7 @@ export function GrantSubscriptionDialog({
|
||||||
|
|
||||||
const handleConfirmGrant = async () => {
|
const handleConfirmGrant = async () => {
|
||||||
const id = Number(planId)
|
const id = Number(planId)
|
||||||
if (!Number.isFinite(id) || id < 1 || categoryBlocked) return
|
if (!Number.isFinite(id) || id < 1 || grantBlocked) return
|
||||||
|
|
||||||
setSaving(true)
|
setSaving(true)
|
||||||
try {
|
try {
|
||||||
|
|
@ -227,7 +244,9 @@ export function GrantSubscriptionDialog({
|
||||||
role="listbox"
|
role="listbox"
|
||||||
>
|
>
|
||||||
{filteredPlans.map((plan) => {
|
{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
|
const selected = String(plan.id) === planId
|
||||||
return (
|
return (
|
||||||
<button
|
<button
|
||||||
|
|
@ -255,7 +274,11 @@ 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)}
|
||||||
{blocked ? " — category active" : ""}
|
{alreadyActive
|
||||||
|
? " — already active"
|
||||||
|
: activeByCategory[plan.category] === true
|
||||||
|
? " — category active"
|
||||||
|
: ""}
|
||||||
</span>
|
</span>
|
||||||
</button>
|
</button>
|
||||||
)
|
)
|
||||||
|
|
@ -270,10 +293,11 @@ export function GrantSubscriptionDialog({
|
||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
{selectedPlan && categoryBlocked ? (
|
{selectedPlan && grantBlocked ? (
|
||||||
<p className="text-xs text-amber-700">
|
<p className="text-xs text-amber-700">
|
||||||
An active {formatPlanCategory(selectedPlan.category)} subscription already
|
{planAlreadyActive
|
||||||
exists. Extend or cancel it instead.
|
? "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>
|
</p>
|
||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
|
|
@ -354,7 +378,7 @@ export function GrantSubscriptionDialog({
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
type="submit"
|
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"
|
className="rounded-[6px] bg-brand-500 font-semibold text-white hover:bg-brand-600"
|
||||||
>
|
>
|
||||||
Continue
|
Continue
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
import { useMemo, useState } from "react"
|
import { useEffect, useMemo, useState } from "react"
|
||||||
import { ChevronDown, ChevronRight, RefreshCw } from "lucide-react"
|
import { ChevronDown, ChevronRight, RefreshCw } from "lucide-react"
|
||||||
|
import { getSubscriptionPlans } from "../../../api/subscription-plans.api"
|
||||||
import { Button } from "../../../components/ui/button"
|
import { Button } from "../../../components/ui/button"
|
||||||
import { Card, CardContent } from "../../../components/ui/card"
|
import { Card, CardContent } from "../../../components/ui/card"
|
||||||
import { SpinnerIcon } from "../../../components/ui/spinner-icon"
|
import { SpinnerIcon } from "../../../components/ui/spinner-icon"
|
||||||
|
|
@ -12,7 +13,7 @@ import {
|
||||||
TableRow,
|
TableRow,
|
||||||
} from "../../../components/ui/table"
|
} from "../../../components/ui/table"
|
||||||
import { useTeamPermissions } from "../../../hooks/useTeamPermissions"
|
import { useTeamPermissions } from "../../../hooks/useTeamPermissions"
|
||||||
import { DisplayValue, NOT_ASSIGNED_LABEL, displayValue } from "../../../lib/displayValue"
|
import { DisplayValue, NOT_ASSIGNED_LABEL } from "../../../lib/displayValue"
|
||||||
import {
|
import {
|
||||||
formatAdminPaymentMethod,
|
formatAdminPaymentMethod,
|
||||||
hasSubscriptionAdminPermission,
|
hasSubscriptionAdminPermission,
|
||||||
|
|
@ -21,6 +22,7 @@ import {
|
||||||
} from "../../../lib/subscriptionAdminPermissions"
|
} from "../../../lib/subscriptionAdminPermissions"
|
||||||
import { formatPlanCategory, isLifetimeExpiry } from "../../../lib/subscriptionPlans"
|
import { formatPlanCategory, isLifetimeExpiry } from "../../../lib/subscriptionPlans"
|
||||||
import { cn } from "../../../lib/utils"
|
import { cn } from "../../../lib/utils"
|
||||||
|
import type { SubscriptionPlan } from "../../../types/subscription.types"
|
||||||
import type { UserSubscriptionRecord, UserSubscriptionsData } from "../../../types/userAdmin.types"
|
import type { UserSubscriptionRecord, UserSubscriptionsData } from "../../../types/userAdmin.types"
|
||||||
import { CancelSubscriptionDialog } from "./CancelSubscriptionDialog"
|
import { CancelSubscriptionDialog } from "./CancelSubscriptionDialog"
|
||||||
import { ExtendSubscriptionDialog } from "./ExtendSubscriptionDialog"
|
import { ExtendSubscriptionDialog } from "./ExtendSubscriptionDialog"
|
||||||
|
|
@ -137,7 +139,7 @@ function SubscriptionManageCard({
|
||||||
canExtend,
|
canExtend,
|
||||||
canGrant,
|
canGrant,
|
||||||
canCancel,
|
canCancel,
|
||||||
hasActiveSubscription,
|
grantEnabled,
|
||||||
onExtend,
|
onExtend,
|
||||||
onGrant,
|
onGrant,
|
||||||
onCancel,
|
onCancel,
|
||||||
|
|
@ -146,7 +148,7 @@ function SubscriptionManageCard({
|
||||||
canExtend: boolean
|
canExtend: boolean
|
||||||
canGrant: boolean
|
canGrant: boolean
|
||||||
canCancel: boolean
|
canCancel: boolean
|
||||||
hasActiveSubscription: boolean
|
grantEnabled: boolean
|
||||||
onExtend: () => void
|
onExtend: () => void
|
||||||
onGrant: () => void
|
onGrant: () => void
|
||||||
onCancel: () => void
|
onCancel: () => void
|
||||||
|
|
@ -156,9 +158,8 @@ function SubscriptionManageCard({
|
||||||
const isActive = subscription.is_currently_active || statusUpper === "ACTIVE"
|
const isActive = subscription.is_currently_active || statusUpper === "ACTIVE"
|
||||||
const statusTone = isActive ? "active" : statusUpper === "PENDING" ? "pending" : "inactive"
|
const statusTone = isActive ? "active" : statusUpper === "PENDING" ? "pending" : "inactive"
|
||||||
const isLifetime = !canExtendSubscription(subscription)
|
const isLifetime = !canExtendSubscription(subscription)
|
||||||
const extendEnabled = canExtend && hasActiveSubscription && isActive && !isLifetime
|
const extendEnabled = canExtend && isActive && !isLifetime
|
||||||
const cancelEnabled = canCancel && hasActiveSubscription && isActive && statusUpper !== "CANCELLED"
|
const cancelEnabled = canCancel && isActive && statusUpper !== "CANCELLED"
|
||||||
const markAsPaidEnabled = canGrant && !hasActiveSubscription
|
|
||||||
|
|
||||||
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">
|
||||||
|
|
@ -211,7 +212,7 @@ function SubscriptionManageCard({
|
||||||
disabled={!extendEnabled}
|
disabled={!extendEnabled}
|
||||||
title={
|
title={
|
||||||
!extendEnabled
|
!extendEnabled
|
||||||
? "Extend is only available when this learner has an active subscription."
|
? "Extend is only available for an active, non-lifetime subscription."
|
||||||
: undefined
|
: undefined
|
||||||
}
|
}
|
||||||
onClick={onExtend}
|
onClick={onExtend}
|
||||||
|
|
@ -227,10 +228,10 @@ function SubscriptionManageCard({
|
||||||
<Button
|
<Button
|
||||||
type="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"
|
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={
|
title={
|
||||||
!markAsPaidEnabled
|
!grantEnabled
|
||||||
? "Grant is unavailable while this learner already has an active subscription."
|
? "Grant is unavailable because this learner already has an active subscription for every available plan."
|
||||||
: undefined
|
: undefined
|
||||||
}
|
}
|
||||||
onClick={onGrant}
|
onClick={onGrant}
|
||||||
|
|
@ -246,7 +247,7 @@ function SubscriptionManageCard({
|
||||||
disabled={!cancelEnabled}
|
disabled={!cancelEnabled}
|
||||||
title={
|
title={
|
||||||
!cancelEnabled
|
!cancelEnabled
|
||||||
? "Cancel is only available when this learner has an active subscription."
|
? "Cancel is only available when this subscription is active."
|
||||||
: undefined
|
: undefined
|
||||||
}
|
}
|
||||||
onClick={onCancel}
|
onClick={onCancel}
|
||||||
|
|
@ -266,12 +267,14 @@ function EmptySubscriptionCard({
|
||||||
canGrant,
|
canGrant,
|
||||||
canExtend,
|
canExtend,
|
||||||
canCancel,
|
canCancel,
|
||||||
|
grantEnabled,
|
||||||
onGrant,
|
onGrant,
|
||||||
}: {
|
}: {
|
||||||
displayStatus: string
|
displayStatus: string
|
||||||
canGrant: boolean
|
canGrant: boolean
|
||||||
canExtend: boolean
|
canExtend: boolean
|
||||||
canCancel: boolean
|
canCancel: boolean
|
||||||
|
grantEnabled: boolean
|
||||||
onGrant: () => void
|
onGrant: () => void
|
||||||
}) {
|
}) {
|
||||||
const upper = displayStatus.toUpperCase()
|
const upper = displayStatus.toUpperCase()
|
||||||
|
|
@ -307,7 +310,13 @@ function EmptySubscriptionCard({
|
||||||
{canGrant ? (
|
{canGrant ? (
|
||||||
<Button
|
<Button
|
||||||
type="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}
|
onClick={onGrant}
|
||||||
>
|
>
|
||||||
Grant Subscription
|
Grant Subscription
|
||||||
|
|
@ -351,8 +360,12 @@ export function UserSubscriptionsSection({
|
||||||
const { permissions } = useTeamPermissions()
|
const { permissions } = useTeamPermissions()
|
||||||
const [detailsOpen, setDetailsOpen] = useState(false)
|
const [detailsOpen, setDetailsOpen] = useState(false)
|
||||||
const [grantOpen, setGrantOpen] = 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 [cancelTarget, setCancelTarget] = useState<UserSubscriptionRecord | null>(null)
|
||||||
|
const [catalogPlans, setCatalogPlans] = useState<SubscriptionPlan[]>([])
|
||||||
|
|
||||||
const canApply = hasSubscriptionAdminPermission(
|
const canApply = hasSubscriptionAdminPermission(
|
||||||
SUBSCRIPTION_ADMIN_PERMISSIONS.apply,
|
SUBSCRIPTION_ADMIN_PERMISSIONS.apply,
|
||||||
|
|
@ -365,11 +378,62 @@ export function UserSubscriptionsSection({
|
||||||
)
|
)
|
||||||
const learner = isLearnerRole(userRole)
|
const learner = isLearnerRole(userRole)
|
||||||
const showGrant = canApply && learner
|
const showGrant = canApply && learner
|
||||||
const hasActiveSubscription =
|
|
||||||
Boolean(subscriptions?.has_active_subscription) ||
|
|
||||||
(subscriptions?.active_subscriptions.length ?? 0) > 0
|
|
||||||
|
|
||||||
const activePlans = subscriptions?.active_subscriptions ?? []
|
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 recentPayments = subscriptions?.payments.slice(0, 12) ?? []
|
||||||
const history = useMemo(() => {
|
const history = useMemo(() => {
|
||||||
if (!subscriptions) return []
|
if (!subscriptions) return []
|
||||||
|
|
@ -406,8 +470,8 @@ export function UserSubscriptionsSection({
|
||||||
canExtend={canExtend}
|
canExtend={canExtend}
|
||||||
canGrant={showGrant}
|
canGrant={showGrant}
|
||||||
canCancel={canCancel}
|
canCancel={canCancel}
|
||||||
hasActiveSubscription={hasActiveSubscription}
|
grantEnabled={grantEnabled}
|
||||||
onExtend={() => setExtendTarget(subscription)}
|
onExtend={() => openExtend(subscription)}
|
||||||
onGrant={() => setGrantOpen(true)}
|
onGrant={() => setGrantOpen(true)}
|
||||||
onCancel={() => setCancelTarget(subscription)}
|
onCancel={() => setCancelTarget(subscription)}
|
||||||
/>
|
/>
|
||||||
|
|
@ -419,6 +483,7 @@ export function UserSubscriptionsSection({
|
||||||
canGrant={showGrant}
|
canGrant={showGrant}
|
||||||
canExtend={canExtend}
|
canExtend={canExtend}
|
||||||
canCancel={canCancel}
|
canCancel={canCancel}
|
||||||
|
grantEnabled={grantEnabled}
|
||||||
onGrant={() => setGrantOpen(true)}
|
onGrant={() => setGrantOpen(true)}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
@ -501,13 +566,13 @@ export function UserSubscriptionsSection({
|
||||||
variant="outline"
|
variant="outline"
|
||||||
size="sm"
|
size="sm"
|
||||||
className="h-8 rounded-lg text-xs disabled:pointer-events-auto disabled:cursor-not-allowed disabled:opacity-50"
|
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={
|
title={
|
||||||
!hasActiveSubscription || !subscription.is_currently_active
|
!subscription.is_currently_active
|
||||||
? "Extend is only available for an active subscription."
|
? "Extend is only available for an active subscription."
|
||||||
: undefined
|
: undefined
|
||||||
}
|
}
|
||||||
onClick={() => setExtendTarget(subscription)}
|
onClick={() => openExtend(subscription)}
|
||||||
>
|
>
|
||||||
Extend
|
Extend
|
||||||
</Button>
|
</Button>
|
||||||
|
|
@ -519,12 +584,11 @@ export function UserSubscriptionsSection({
|
||||||
size="sm"
|
size="sm"
|
||||||
className="h-8 rounded-lg text-xs text-destructive disabled:pointer-events-auto disabled:cursor-not-allowed disabled:opacity-50"
|
className="h-8 rounded-lg text-xs text-destructive disabled:pointer-events-auto disabled:cursor-not-allowed disabled:opacity-50"
|
||||||
disabled={
|
disabled={
|
||||||
!hasActiveSubscription ||
|
|
||||||
!subscription.is_currently_active ||
|
!subscription.is_currently_active ||
|
||||||
subscription.status.toUpperCase() === "CANCELLED"
|
subscription.status.toUpperCase() === "CANCELLED"
|
||||||
}
|
}
|
||||||
title={
|
title={
|
||||||
!hasActiveSubscription || !subscription.is_currently_active
|
!subscription.is_currently_active
|
||||||
? "Cancel is only available for an active subscription."
|
? "Cancel is only available for an active subscription."
|
||||||
: undefined
|
: undefined
|
||||||
}
|
}
|
||||||
|
|
@ -602,16 +666,19 @@ 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}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<ExtendSubscriptionDialog
|
<ExtendSubscriptionDialog
|
||||||
open={extendTarget != null}
|
open={extendOpen}
|
||||||
onOpenChange={(next) => {
|
onOpenChange={(next) => {
|
||||||
if (!next) setExtendTarget(null)
|
setExtendOpen(next)
|
||||||
|
if (!next) setExtendInitialSubscriptionId(null)
|
||||||
}}
|
}}
|
||||||
userId={userId}
|
userId={userId}
|
||||||
subscription={extendTarget}
|
subscriptions={extendableActivePlans}
|
||||||
|
initialSubscriptionId={extendInitialSubscriptionId}
|
||||||
onExtended={onRefresh}
|
onExtended={onRefresh}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue
Block a user