Add admin grant/extend/cancel for learner subscriptions.
Wire user-detail subscription actions with searchable plan picker and type-to-confirm modals, and mask sensitive revenue values on the dashboard. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
4f3a49da35
commit
042df899e1
74
src/api/admin-subscriptions.api.ts
Normal file
74
src/api/admin-subscriptions.api.ts
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
import http from "./http"
|
||||
import type {
|
||||
AdminApplySubscriptionBody,
|
||||
AdminSubscriptionMutationResponse,
|
||||
AdminSubscriptionRes,
|
||||
} from "../types/adminSubscription.types"
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value)
|
||||
}
|
||||
|
||||
function normalizeSubscriptionRes(raw: unknown): AdminSubscriptionRes | null {
|
||||
if (!isRecord(raw)) return null
|
||||
const id = Number(raw.id)
|
||||
const userId = Number(raw.user_id)
|
||||
const planId = Number(raw.plan_id)
|
||||
if (!Number.isFinite(id) || !Number.isFinite(userId) || !Number.isFinite(planId)) return null
|
||||
|
||||
return {
|
||||
id,
|
||||
user_id: userId,
|
||||
plan_id: planId,
|
||||
plan_name: raw.plan_name != null ? String(raw.plan_name) : undefined,
|
||||
starts_at: String(raw.starts_at ?? ""),
|
||||
expires_at: String(raw.expires_at ?? ""),
|
||||
status: String(raw.status ?? ""),
|
||||
payment_reference:
|
||||
raw.payment_reference != null ? String(raw.payment_reference) : undefined,
|
||||
payment_method: raw.payment_method != null ? String(raw.payment_method) : undefined,
|
||||
auto_renew: Boolean(raw.auto_renew),
|
||||
duration_value:
|
||||
raw.duration_value != null && Number.isFinite(Number(raw.duration_value))
|
||||
? Number(raw.duration_value)
|
||||
: undefined,
|
||||
duration_unit: raw.duration_unit != null ? String(raw.duration_unit) : undefined,
|
||||
price:
|
||||
raw.price != null && Number.isFinite(Number(raw.price)) ? Number(raw.price) : undefined,
|
||||
currency: raw.currency != null ? String(raw.currency) : undefined,
|
||||
created_at: String(raw.created_at ?? ""),
|
||||
}
|
||||
}
|
||||
|
||||
function mutationResult(res: { data: unknown; status?: number }) {
|
||||
const body = isRecord(res.data) ? res.data : null
|
||||
const plan = normalizeSubscriptionRes(body?.data ?? body)
|
||||
return {
|
||||
...res,
|
||||
data: plan,
|
||||
message: body ? String(body.message ?? "") : undefined,
|
||||
httpStatus: res.status,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /admin/users/:user_id/subscriptions/extend
|
||||
* Unified grant-or-extend: no active sub in plan category → grant (201);
|
||||
* active in category → extend one period of selected plan (200).
|
||||
*/
|
||||
export const adminApplySubscription = (userId: number, body: AdminApplySubscriptionBody) =>
|
||||
http
|
||||
.post<AdminSubscriptionMutationResponse>(
|
||||
`/admin/users/${userId}/subscriptions/extend`,
|
||||
body,
|
||||
)
|
||||
.then(mutationResult)
|
||||
|
||||
/** @deprecated Use adminApplySubscription */
|
||||
export const adminGrantSubscription = adminApplySubscription
|
||||
|
||||
/** POST /admin/subscriptions/:id/cancel — admin cancel (not learner self-cancel). */
|
||||
export const adminCancelSubscription = (subscriptionId: number) =>
|
||||
http
|
||||
.post<AdminSubscriptionMutationResponse>(`/admin/subscriptions/${subscriptionId}/cancel`)
|
||||
.then(mutationResult)
|
||||
|
|
@ -50,14 +50,18 @@ export function parseSubscriptionPlanMutation(body: unknown): SubscriptionPlan |
|
|||
}
|
||||
|
||||
export interface GetSubscriptionPlansOptions {
|
||||
/** When false, returns active and inactive plans. Defaults to false for admin views. */
|
||||
/**
|
||||
* When true or omitted, returns active plans only (`GET /subscription-plans`).
|
||||
* Pass false for admin settings/dashboard to include inactive plans.
|
||||
*/
|
||||
active_only?: boolean
|
||||
}
|
||||
|
||||
export const getSubscriptionPlans = (options?: GetSubscriptionPlansOptions) =>
|
||||
http
|
||||
export const getSubscriptionPlans = (options?: GetSubscriptionPlansOptions) => {
|
||||
const activeOnly = options?.active_only ?? true
|
||||
return http
|
||||
.get<SubscriptionPlansListResponse | SubscriptionPlan[]>("/subscription-plans", {
|
||||
params: { active_only: options?.active_only ?? false },
|
||||
params: activeOnly ? undefined : { active_only: false },
|
||||
})
|
||||
.then((res) => {
|
||||
const plans = parseSubscriptionPlansList(res.data)
|
||||
|
|
@ -66,6 +70,7 @@ export const getSubscriptionPlans = (options?: GetSubscriptionPlansOptions) =>
|
|||
data: plans,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function mutationResult(res: { data: unknown }) {
|
||||
const plan = parseSubscriptionPlanMutation(res.data)
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import { getDashboard } from "../../api/analytics.api"
|
|||
import { getYearOptions } from "../analytics/AnalyticsTimeRangeFilter"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "../ui/card"
|
||||
import { Select } from "../ui/select"
|
||||
import { SensitiveChart, SensitiveRevealToggle, SensitiveValue } from "../ui/sensitive-value"
|
||||
import { aggregateRevenueByMonth, formatRevenueAxisTick } from "../../lib/analytics"
|
||||
import type { DateRevenue } from "../../types/analytics.types"
|
||||
import spinnerSrc from "../../assets/Circular-indeterminate progress indicator.svg"
|
||||
|
|
@ -63,9 +64,12 @@ export function RevenueTrendCard() {
|
|||
<CardHeader className="pb-2">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div>
|
||||
<CardTitle>Revenue Trend</CardTitle>
|
||||
<div className="flex items-center gap-1">
|
||||
<CardTitle>Revenue Trend</CardTitle>
|
||||
<SensitiveRevealToggle />
|
||||
</div>
|
||||
<div className="mt-2 text-2xl font-semibold tracking-tight">
|
||||
ETB {totalRevenue.toLocaleString()}
|
||||
<SensitiveValue showToggle={false}>ETB {totalRevenue.toLocaleString()}</SensitiveValue>
|
||||
</div>
|
||||
<div className="text-xs font-medium text-grayScale-500">Monthly · {year} (ETB)</div>
|
||||
</div>
|
||||
|
|
@ -89,40 +93,42 @@ export function RevenueTrendCard() {
|
|||
<img src={spinnerSrc} alt="" className="h-8 w-8 animate-spin" />
|
||||
</div>
|
||||
) : (
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<ComposedChart data={chartData} margin={{ left: 4, right: 8, top: 8, bottom: 0 }} barGap={-28}>
|
||||
<CartesianGrid vertical={false} stroke="#E0E0E0" strokeDasharray="4 4" />
|
||||
<XAxis dataKey="month" tickLine={false} axisLine={false} fontSize={12} />
|
||||
<YAxis
|
||||
tickLine={false}
|
||||
axisLine={false}
|
||||
fontSize={12}
|
||||
width={44}
|
||||
tickFormatter={formatRevenueAxisTick}
|
||||
/>
|
||||
<Tooltip
|
||||
formatter={(value, name) => {
|
||||
if (name !== "revenue") return null
|
||||
return [`ETB ${Number(value).toLocaleString()}`, "Revenue"]
|
||||
}}
|
||||
contentStyle={{
|
||||
borderRadius: 12,
|
||||
border: "1px solid #E0E0E0",
|
||||
boxShadow: "0 10px 30px rgba(0,0,0,0.08)",
|
||||
}}
|
||||
/>
|
||||
<Bar dataKey="track" barSize={28} radius={[8, 8, 0, 0]} isAnimationActive={false}>
|
||||
{chartData.map((entry) => (
|
||||
<Cell key={`track-${entry.month}`} fill={TRACK_COLOR} />
|
||||
))}
|
||||
</Bar>
|
||||
<Bar dataKey="revenue" barSize={28} radius={[8, 8, 0, 0]}>
|
||||
{chartData.map((entry) => (
|
||||
<Cell key={`revenue-${entry.month}`} fill={BAR_COLOR} />
|
||||
))}
|
||||
</Bar>
|
||||
</ComposedChart>
|
||||
</ResponsiveContainer>
|
||||
<SensitiveChart>
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<ComposedChart data={chartData} margin={{ left: 4, right: 8, top: 8, bottom: 0 }} barGap={-28}>
|
||||
<CartesianGrid vertical={false} stroke="#E0E0E0" strokeDasharray="4 4" />
|
||||
<XAxis dataKey="month" tickLine={false} axisLine={false} fontSize={12} />
|
||||
<YAxis
|
||||
tickLine={false}
|
||||
axisLine={false}
|
||||
fontSize={12}
|
||||
width={44}
|
||||
tickFormatter={formatRevenueAxisTick}
|
||||
/>
|
||||
<Tooltip
|
||||
formatter={(value, name) => {
|
||||
if (name !== "revenue") return null
|
||||
return [`ETB ${Number(value).toLocaleString()}`, "Revenue"]
|
||||
}}
|
||||
contentStyle={{
|
||||
borderRadius: 12,
|
||||
border: "1px solid #E0E0E0",
|
||||
boxShadow: "0 10px 30px rgba(0,0,0,0.08)",
|
||||
}}
|
||||
/>
|
||||
<Bar dataKey="track" barSize={28} radius={[8, 8, 0, 0]} isAnimationActive={false}>
|
||||
{chartData.map((entry) => (
|
||||
<Cell key={`track-${entry.month}`} fill={TRACK_COLOR} />
|
||||
))}
|
||||
</Bar>
|
||||
<Bar dataKey="revenue" barSize={28} radius={[8, 8, 0, 0]}>
|
||||
{chartData.map((entry) => (
|
||||
<Cell key={`revenue-${entry.month}`} fill={BAR_COLOR} />
|
||||
))}
|
||||
</Bar>
|
||||
</ComposedChart>
|
||||
</ResponsiveContainer>
|
||||
</SensitiveChart>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import type { LucideIcon } from "lucide-react"
|
||||
import type { ReactNode } from "react"
|
||||
import { cn } from "../../lib/utils"
|
||||
import { Card, CardContent } from "../ui/card"
|
||||
|
||||
|
|
@ -11,7 +12,7 @@ export function StatCard({
|
|||
}: {
|
||||
icon: LucideIcon
|
||||
label: string
|
||||
value: string
|
||||
value: ReactNode
|
||||
deltaLabel: string
|
||||
deltaPositive: boolean
|
||||
}) {
|
||||
|
|
|
|||
|
|
@ -38,8 +38,8 @@ const DialogContent = React.forwardRef<
|
|||
{...props}
|
||||
>
|
||||
{children}
|
||||
<DialogPrimitive.Close className="absolute right-6 top-10 rounded-sm opacity-60 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
|
||||
<X className="h-6 w-6" />
|
||||
<DialogPrimitive.Close className="absolute right-4 top-4 z-10 rounded-sm opacity-60 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
|
||||
<X className="h-5 w-5" />
|
||||
<span className="sr-only">Close</span>
|
||||
</DialogPrimitive.Close>
|
||||
</DialogPrimitive.Content>
|
||||
|
|
@ -53,7 +53,7 @@ const DialogHeader = ({
|
|||
}: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div
|
||||
className={cn(
|
||||
"flex flex-col space-y-1.5 text-center sm:text-left",
|
||||
"flex flex-col space-y-1.5 pr-10 text-center sm:text-left",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
|
|
|
|||
126
src/components/ui/sensitive-value.tsx
Normal file
126
src/components/ui/sensitive-value.tsx
Normal file
|
|
@ -0,0 +1,126 @@
|
|||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from "react"
|
||||
import { Eye, EyeOff } from "lucide-react"
|
||||
import { cn } from "../../lib/utils"
|
||||
|
||||
type SensitiveRevealContextValue = {
|
||||
revealed: boolean
|
||||
toggle: () => void
|
||||
}
|
||||
|
||||
const SensitiveRevealContext = createContext<SensitiveRevealContextValue | null>(null)
|
||||
|
||||
export function SensitiveRevealProvider({ children }: { children: ReactNode }) {
|
||||
const [revealed, setRevealed] = useState(false)
|
||||
const toggle = useCallback(() => setRevealed((v) => !v), [])
|
||||
|
||||
return (
|
||||
<SensitiveRevealContext.Provider value={{ revealed, toggle }}>
|
||||
{children}
|
||||
</SensitiveRevealContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
export function useSensitiveReveal() {
|
||||
const ctx = useContext(SensitiveRevealContext)
|
||||
const [localRevealed, setLocalRevealed] = useState(false)
|
||||
const toggleLocal = useCallback(() => setLocalRevealed((v) => !v), [])
|
||||
|
||||
if (ctx) return ctx
|
||||
|
||||
return {
|
||||
revealed: localRevealed,
|
||||
toggle: toggleLocal,
|
||||
}
|
||||
}
|
||||
|
||||
export function SensitiveRevealToggle({
|
||||
className,
|
||||
label = "revenue",
|
||||
}: {
|
||||
className?: string
|
||||
label?: string
|
||||
}) {
|
||||
const { revealed, toggle } = useSensitiveReveal()
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={toggle}
|
||||
className={cn(
|
||||
"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-lg text-grayScale-500 transition-colors hover:bg-grayScale-100 hover:text-grayScale-800",
|
||||
className,
|
||||
)}
|
||||
aria-label={revealed ? `Hide ${label}` : `Show ${label}`}
|
||||
title={revealed ? `Hide ${label}` : `Show ${label}`}
|
||||
>
|
||||
{revealed ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
export function SensitiveValue({
|
||||
children,
|
||||
className,
|
||||
showToggle = true,
|
||||
}: {
|
||||
children: ReactNode
|
||||
className?: string
|
||||
showToggle?: boolean
|
||||
}) {
|
||||
const { revealed } = useSensitiveReveal()
|
||||
|
||||
return (
|
||||
<span className={cn("inline-flex items-center gap-1.5", className)}>
|
||||
<span
|
||||
className={cn(
|
||||
"transition-[filter] duration-200",
|
||||
!revealed && "select-none blur-[6px]",
|
||||
)}
|
||||
aria-hidden={!revealed}
|
||||
>
|
||||
{children}
|
||||
</span>
|
||||
{showToggle ? <SensitiveRevealToggle /> : null}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
export function SensitiveChart({
|
||||
children,
|
||||
className,
|
||||
}: {
|
||||
children: ReactNode
|
||||
className?: string
|
||||
}) {
|
||||
const { revealed, toggle } = useSensitiveReveal()
|
||||
|
||||
return (
|
||||
<div className={cn("relative h-full w-full", className)}>
|
||||
<div
|
||||
className={cn(
|
||||
"h-full w-full transition-[filter] duration-200",
|
||||
!revealed && "pointer-events-none select-none blur-md",
|
||||
)}
|
||||
aria-hidden={!revealed}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
{!revealed ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={toggle}
|
||||
className="absolute inset-0 z-10 flex flex-col items-center justify-center gap-2 rounded-lg bg-white/40 text-sm font-medium text-grayScale-600 backdrop-blur-[1px] transition-colors hover:bg-white/55 hover:text-grayScale-800"
|
||||
>
|
||||
<Eye className="h-5 w-5" />
|
||||
Show revenue
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
@ -50,6 +50,9 @@ const ACTION_LABELS: Record<string, string> = {
|
|||
PAYMENT_VERIFIED: "Payment verified",
|
||||
PAYMENT_CANCELLED: "Payment cancelled",
|
||||
PAYMENT_WEBHOOK_RECEIVED: "Payment webhook received",
|
||||
SUBSCRIPTION_CREATED: "Subscription created",
|
||||
SUBSCRIPTION_EXTENDED: "Subscription extended",
|
||||
SUBSCRIPTION_CANCELLED: "Subscription cancelled",
|
||||
NOTIFICATION_BULK_SENT: "Bulk notification sent",
|
||||
NOTIFICATION_CREATED: "Notification created",
|
||||
NOTIFICATION_UPDATED: "Notification updated",
|
||||
|
|
@ -80,6 +83,7 @@ const ACTION_CATEGORY: Record<string, ActionBadgeTone> = {
|
|||
PAYMENT_CANCELLED: "billing",
|
||||
PAYMENT_WEBHOOK_RECEIVED: "billing",
|
||||
SUBSCRIPTION_CREATED: "billing",
|
||||
SUBSCRIPTION_EXTENDED: "billing",
|
||||
SUBSCRIPTION_CANCELLED: "billing",
|
||||
}
|
||||
|
||||
|
|
@ -166,6 +170,7 @@ export const ACTION_FILTER_GROUPS: { label: string; actions: string[] }[] = [
|
|||
"SUBSCRIPTION_PLAN_CREATED",
|
||||
"SUBSCRIPTION_PLAN_UPDATED",
|
||||
"SUBSCRIPTION_CREATED",
|
||||
"SUBSCRIPTION_EXTENDED",
|
||||
"SUBSCRIPTION_CANCELLED",
|
||||
"PAYMENT_INITIATED",
|
||||
"PAYMENT_VERIFIED",
|
||||
|
|
|
|||
44
src/lib/subscriptionAdminPermissions.ts
Normal file
44
src/lib/subscriptionAdminPermissions.ts
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
import { getNormalizedSessionTeamRole } from "./teamRole"
|
||||
|
||||
export const SUBSCRIPTION_ADMIN_PERMISSIONS = {
|
||||
/** Unified grant-or-extend (admin_grant removed from API seeds). */
|
||||
apply: "subscriptions.admin_extend",
|
||||
extend: "subscriptions.admin_extend",
|
||||
cancel: "subscriptions.admin_cancel",
|
||||
getByUser: "subscriptions.get_by_user",
|
||||
} as const
|
||||
|
||||
const ALL_ADMIN_SUBSCRIPTION_PERMISSIONS = [
|
||||
SUBSCRIPTION_ADMIN_PERMISSIONS.apply,
|
||||
SUBSCRIPTION_ADMIN_PERMISSIONS.cancel,
|
||||
SUBSCRIPTION_ADMIN_PERMISSIONS.getByUser,
|
||||
] as const
|
||||
|
||||
/** Default access by team role (matches API RBAC seeds for ADMIN). */
|
||||
const ROLE_PERMISSIONS: Record<string, readonly string[]> = {
|
||||
SUPER_ADMIN: ALL_ADMIN_SUBSCRIPTION_PERMISSIONS,
|
||||
ADMIN: ALL_ADMIN_SUBSCRIPTION_PERMISSIONS,
|
||||
}
|
||||
|
||||
export function hasSubscriptionAdminPermission(
|
||||
permission: string,
|
||||
permissions: string[],
|
||||
): boolean {
|
||||
if (permissions.includes(permission)) return true
|
||||
const rolePerms = ROLE_PERMISSIONS[getNormalizedSessionTeamRole()]
|
||||
return rolePerms?.includes(permission) ?? false
|
||||
}
|
||||
|
||||
const LEARNER_ROLES = new Set(["STUDENT", "OPEN_LEARNER"])
|
||||
|
||||
export function isLearnerRole(role: string | null | undefined): boolean {
|
||||
return LEARNER_ROLES.has(String(role ?? "").trim().toUpperCase())
|
||||
}
|
||||
|
||||
export function formatAdminPaymentMethod(method: string | null | undefined): string {
|
||||
const value = String(method ?? "").trim().toUpperCase()
|
||||
if (value === "ADMIN_GRANT") return "Admin grant"
|
||||
if (value === "ADMIN_EXTEND") return "Admin extend"
|
||||
if (!value) return "—"
|
||||
return method!.trim()
|
||||
}
|
||||
146
src/lib/typeToConfirm.tsx
Normal file
146
src/lib/typeToConfirm.tsx
Normal file
|
|
@ -0,0 +1,146 @@
|
|||
import { useEffect, useState, type ReactNode } from "react"
|
||||
import { Button } from "../components/ui/button"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "../components/ui/dialog"
|
||||
import { Input } from "../components/ui/input"
|
||||
import { SpinnerIcon } from "../components/ui/spinner-icon"
|
||||
import { cn } from "./utils"
|
||||
|
||||
type TypeToConfirmFieldProps = {
|
||||
labelWord: string
|
||||
value: string
|
||||
onChange: (value: string) => void
|
||||
disabled?: boolean
|
||||
className?: string
|
||||
}
|
||||
|
||||
/** Requires the admin to type an exact confirmation word (case-insensitive). */
|
||||
export function TypeToConfirmField({
|
||||
labelWord,
|
||||
value,
|
||||
onChange,
|
||||
disabled,
|
||||
className,
|
||||
}: TypeToConfirmFieldProps) {
|
||||
const expected = labelWord.trim().toUpperCase()
|
||||
|
||||
return (
|
||||
<div className={cn("space-y-1.5", className)}>
|
||||
<label className="block text-sm text-grayScale-600">
|
||||
Type <span className="font-bold text-grayScale-900">{expected}</span> to confirm
|
||||
</label>
|
||||
<Input
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
disabled={disabled}
|
||||
placeholder={expected}
|
||||
autoComplete="off"
|
||||
spellCheck={false}
|
||||
onCopy={(e) => e.preventDefault()}
|
||||
onCut={(e) => e.preventDefault()}
|
||||
onPaste={(e) => e.preventDefault()}
|
||||
onDrop={(e) => e.preventDefault()}
|
||||
className="rounded-[6px] font-mono uppercase tracking-wide"
|
||||
aria-label={`Type ${expected} to confirm`}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function matchesConfirmWord(value: string, expectedWord: string): boolean {
|
||||
return value.trim().toUpperCase() === expectedWord.trim().toUpperCase()
|
||||
}
|
||||
|
||||
type TypeToConfirmDialogProps = {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
title: string
|
||||
description?: ReactNode
|
||||
confirmWord: string
|
||||
confirmLabel?: string
|
||||
cancelLabel?: string
|
||||
confirming?: boolean
|
||||
variant?: "default" | "destructive"
|
||||
onConfirm: () => void | Promise<void>
|
||||
}
|
||||
|
||||
/** Separate “Are you sure?” modal that requires typing a confirmation word. */
|
||||
export function TypeToConfirmDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
title,
|
||||
description,
|
||||
confirmWord,
|
||||
confirmLabel = "Confirm",
|
||||
cancelLabel = "Cancel",
|
||||
confirming = false,
|
||||
variant = "default",
|
||||
onConfirm,
|
||||
}: TypeToConfirmDialogProps) {
|
||||
const [confirmText, setConfirmText] = useState("")
|
||||
const confirmMatched = matchesConfirmWord(confirmText, confirmWord)
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
setConfirmText("")
|
||||
}, [open, confirmWord])
|
||||
|
||||
const handleConfirm = async () => {
|
||||
if (!confirmMatched || confirming) return
|
||||
await onConfirm()
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={(next) => !confirming && onOpenChange(next)}>
|
||||
<DialogContent className="max-w-md rounded-[12px] border border-grayScale-100 sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-lg font-bold text-grayScale-900">{title}</DialogTitle>
|
||||
{description ? (
|
||||
<DialogDescription className="text-left text-grayScale-600">
|
||||
{description}
|
||||
</DialogDescription>
|
||||
) : null}
|
||||
</DialogHeader>
|
||||
|
||||
<TypeToConfirmField
|
||||
labelWord={confirmWord}
|
||||
value={confirmText}
|
||||
onChange={setConfirmText}
|
||||
disabled={confirming}
|
||||
/>
|
||||
|
||||
<DialogFooter className="gap-2 sm:gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="rounded-[6px]"
|
||||
disabled={confirming}
|
||||
onClick={() => onOpenChange(false)}
|
||||
>
|
||||
{cancelLabel}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant={variant === "destructive" ? "destructive" : "default"}
|
||||
className={cn(
|
||||
"rounded-[6px]",
|
||||
variant === "default" &&
|
||||
"bg-brand-500 font-semibold text-white hover:bg-brand-600",
|
||||
)}
|
||||
disabled={confirming || !confirmMatched}
|
||||
onClick={() => void handleConfirm()}
|
||||
>
|
||||
{confirming ? <SpinnerIcon className="h-4 w-4" /> : null}
|
||||
{confirming ? "Working…" : confirmLabel}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
|
@ -33,6 +33,7 @@ import { StatCard } from "../components/dashboard/StatCard"
|
|||
import alertSrc from "../assets/Alert.svg"
|
||||
import { Badge } from "../components/ui/badge"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "../components/ui/card"
|
||||
import { SensitiveRevealProvider, SensitiveValue } from "../components/ui/sensitive-value"
|
||||
import { cn } from "../lib/utils"
|
||||
import { getTeamMemberById } from "../api/team.api"
|
||||
import { getDashboard } from "../api/analytics.api"
|
||||
|
|
@ -175,6 +176,7 @@ export function DashboardPage() {
|
|||
: null
|
||||
|
||||
return (
|
||||
<SensitiveRevealProvider>
|
||||
<div className="mx-auto w-full min-w-0 max-w-6xl">
|
||||
<div className="mb-2 flex flex-wrap items-center justify-between gap-3">
|
||||
<div className="text-sm font-semibold text-grayScale-500">Dashboard</div>
|
||||
|
|
@ -252,7 +254,11 @@ export function DashboardPage() {
|
|||
<StatCard
|
||||
icon={DollarSign}
|
||||
label="Total Revenue (ETB)"
|
||||
value={dashboard.payments.total_revenue.toLocaleString()}
|
||||
value={
|
||||
<SensitiveValue>
|
||||
{dashboard.payments.total_revenue.toLocaleString()}
|
||||
</SensitiveValue>
|
||||
}
|
||||
deltaLabel={`${dashboard.payments.total_payments} payments`}
|
||||
deltaPositive={dashboard.payments.total_revenue > 0}
|
||||
/>
|
||||
|
|
@ -596,5 +602,6 @@ export function DashboardPage() {
|
|||
</>
|
||||
)}
|
||||
</div>
|
||||
</SensitiveRevealProvider>
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { useEffect, useState } from "react"
|
||||
import { useEffect, useState, type ElementType, type ReactNode } from "react"
|
||||
import spinnerSrc from "../../assets/Circular-indeterminate progress indicator.svg"
|
||||
import {
|
||||
Area,
|
||||
|
|
@ -38,6 +38,12 @@ import {
|
|||
CheckCircle2,
|
||||
} from "lucide-react"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card"
|
||||
import {
|
||||
SensitiveChart,
|
||||
SensitiveRevealProvider,
|
||||
SensitiveRevealToggle,
|
||||
SensitiveValue,
|
||||
} from "../../components/ui/sensitive-value"
|
||||
import { Badge } from "../../components/ui/badge"
|
||||
import { Button } from "../../components/ui/button"
|
||||
import { cn } from "../../lib/utils"
|
||||
|
|
@ -74,10 +80,10 @@ function KpiCard({
|
|||
trend,
|
||||
className,
|
||||
}: {
|
||||
icon: React.ElementType
|
||||
icon: ElementType
|
||||
label: string
|
||||
value: string
|
||||
sub?: string
|
||||
value: ReactNode
|
||||
sub?: ReactNode
|
||||
trend?: "up" | "down" | "neutral"
|
||||
className?: string
|
||||
}) {
|
||||
|
|
@ -430,6 +436,7 @@ export function AnalyticsPage() {
|
|||
})
|
||||
|
||||
return (
|
||||
<SensitiveRevealProvider>
|
||||
<div className="mx-auto w-full max-w-[1280px] px-2 pb-6 sm:px-4">
|
||||
{/* Header */}
|
||||
<div className="mb-7 flex flex-wrap items-end justify-between gap-4">
|
||||
|
|
@ -521,8 +528,19 @@ export function AnalyticsPage() {
|
|||
<KpiCard
|
||||
icon={DollarSign}
|
||||
label="Total Revenue"
|
||||
value={`ETB ${formatNumber(payments.total_revenue)}`}
|
||||
sub={`${payments.successful_payments}/${payments.total_payments} successful · Avg ETB ${payments.avg_transaction_value.toLocaleString()}`}
|
||||
value={
|
||||
<SensitiveValue>
|
||||
{`ETB ${formatNumber(payments.total_revenue)}`}
|
||||
</SensitiveValue>
|
||||
}
|
||||
sub={
|
||||
<>
|
||||
{payments.successful_payments}/{payments.total_payments} successful · Avg{" "}
|
||||
<SensitiveValue showToggle={false}>
|
||||
ETB {payments.avg_transaction_value.toLocaleString()}
|
||||
</SensitiveValue>
|
||||
</>
|
||||
}
|
||||
trend={payments.total_revenue > 0 ? "up" : "neutral"}
|
||||
/>
|
||||
<KpiCard
|
||||
|
|
@ -784,9 +802,14 @@ export function AnalyticsPage() {
|
|||
<CardHeader className="pb-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<CardTitle>Revenue</CardTitle>
|
||||
<div className="flex items-center gap-1">
|
||||
<CardTitle>Revenue</CardTitle>
|
||||
<SensitiveRevealToggle />
|
||||
</div>
|
||||
<div className="mt-1 text-2xl font-semibold tracking-tight">
|
||||
ETB {payments.total_revenue.toLocaleString()}
|
||||
<SensitiveValue showToggle={false}>
|
||||
ETB {payments.total_revenue.toLocaleString()}
|
||||
</SensitiveValue>
|
||||
</div>
|
||||
<div className="text-xs text-grayScale-400">Daily revenue over last 30 days</div>
|
||||
</div>
|
||||
|
|
@ -794,23 +817,25 @@ export function AnalyticsPage() {
|
|||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="h-[240px] p-6 pt-2">
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<BarChart data={revenueData} margin={{ left: 8, right: 8, top: 8 }}>
|
||||
<CartesianGrid vertical={false} stroke="#E0E0E0" strokeDasharray="4 4" />
|
||||
<XAxis dataKey="date" tickLine={false} axisLine={false} fontSize={11} />
|
||||
<YAxis tickLine={false} axisLine={false} fontSize={11} width={42} />
|
||||
<Tooltip
|
||||
formatter={(v) => [`ETB ${Number(v).toLocaleString()}`, "Revenue"]}
|
||||
contentStyle={{
|
||||
borderRadius: 12,
|
||||
border: "1px solid #E0E0E0",
|
||||
boxShadow: "0 10px 30px rgba(0,0,0,0.08)",
|
||||
fontSize: 12,
|
||||
}}
|
||||
/>
|
||||
<Bar dataKey="revenue" radius={[6, 6, 0, 0]} fill="#9E2891" />
|
||||
</BarChart>
|
||||
</ResponsiveContainer>
|
||||
<SensitiveChart>
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<BarChart data={revenueData} margin={{ left: 8, right: 8, top: 8 }}>
|
||||
<CartesianGrid vertical={false} stroke="#E0E0E0" strokeDasharray="4 4" />
|
||||
<XAxis dataKey="date" tickLine={false} axisLine={false} fontSize={11} />
|
||||
<YAxis tickLine={false} axisLine={false} fontSize={11} width={42} />
|
||||
<Tooltip
|
||||
formatter={(v) => [`ETB ${Number(v).toLocaleString()}`, "Revenue"]}
|
||||
contentStyle={{
|
||||
borderRadius: 12,
|
||||
border: "1px solid #E0E0E0",
|
||||
boxShadow: "0 10px 30px rgba(0,0,0,0.08)",
|
||||
fontSize: 12,
|
||||
}}
|
||||
/>
|
||||
<Bar dataKey="revenue" radius={[6, 6, 0, 0]} fill="#9E2891" />
|
||||
</BarChart>
|
||||
</ResponsiveContainer>
|
||||
</SensitiveChart>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
|
@ -1062,5 +1087,6 @@ export function AnalyticsPage() {
|
|||
</Section>
|
||||
</div>
|
||||
</div>
|
||||
</SensitiveRevealProvider>
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -137,16 +137,17 @@ function LoadingSkeleton() {
|
|||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="h-5 w-32 animate-pulse rounded bg-grayScale-100" />
|
||||
<div className="grid gap-6 lg:grid-cols-[340px_1fr]">
|
||||
<div className="grid gap-6 lg:grid-cols-2">
|
||||
<div className="space-y-6">
|
||||
<div className="h-80 animate-pulse rounded-2xl bg-grayScale-100" />
|
||||
<div className="h-64 animate-pulse rounded-2xl bg-grayScale-100" />
|
||||
<div className="h-48 animate-pulse rounded-2xl bg-grayScale-100" />
|
||||
</div>
|
||||
<div className="space-y-6">
|
||||
<div className="h-56 animate-pulse rounded-2xl bg-grayScale-100" />
|
||||
<div className="h-72 animate-pulse rounded-2xl bg-grayScale-100" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="h-64 animate-pulse rounded-2xl bg-grayScale-100" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -219,27 +220,30 @@ export function UserDetailPage() {
|
|||
void loadLearningActivity();
|
||||
}, [id]);
|
||||
|
||||
const refreshSubscriptions = async () => {
|
||||
const userId = Number(id);
|
||||
if (!Number.isFinite(userId) || userId <= 0) return;
|
||||
|
||||
setSubscriptionsLoading(true);
|
||||
setSubscriptionsError(null);
|
||||
try {
|
||||
const res = await getUserSubscriptions(userId);
|
||||
setSubscriptions(res.data.data);
|
||||
} catch (err) {
|
||||
console.error("Failed to load subscriptions", err);
|
||||
setSubscriptions(null);
|
||||
setSubscriptionsError(getApiErrorMessage(err, "Failed to load subscriptions."));
|
||||
} finally {
|
||||
setSubscriptionsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!id) return;
|
||||
const userId = Number(id);
|
||||
if (Number.isNaN(userId)) return;
|
||||
|
||||
const loadSubscriptions = async () => {
|
||||
setSubscriptionsLoading(true);
|
||||
setSubscriptionsError(null);
|
||||
try {
|
||||
const res = await getUserSubscriptions(userId);
|
||||
setSubscriptions(res.data.data);
|
||||
} catch (err) {
|
||||
console.error("Failed to load subscriptions", err);
|
||||
setSubscriptions(null);
|
||||
setSubscriptionsError(getApiErrorMessage(err, "Failed to load subscriptions."));
|
||||
} finally {
|
||||
setSubscriptionsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
void loadSubscriptions();
|
||||
void refreshSubscriptions();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [id]);
|
||||
|
||||
useEffect(() => {
|
||||
|
|
@ -360,8 +364,8 @@ export function UserDetailPage() {
|
|||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-6 lg:grid-cols-[340px_1fr]">
|
||||
<div className="space-y-6">
|
||||
<div className="grid gap-6 lg:grid-cols-2 lg:items-start">
|
||||
<div className="min-w-0 space-y-6">
|
||||
<Card className="overflow-hidden shadow-soft">
|
||||
<CardContent className="space-y-5 p-5">
|
||||
<div className="flex items-center gap-4">
|
||||
|
|
@ -407,7 +411,7 @@ export function UserDetailPage() {
|
|||
|
||||
<Separator />
|
||||
|
||||
<div className="grid gap-3 text-sm">
|
||||
<div className="grid gap-3 text-sm sm:grid-cols-2">
|
||||
<InfoRow label="Joined" value={formatDate(user.created_at)} />
|
||||
<InfoRow label="Last login" value={formatDateTime(user.last_login, "Never")} />
|
||||
<InfoRow label="Gender" value={displayValue(user.gender)} />
|
||||
|
|
@ -440,12 +444,6 @@ export function UserDetailPage() {
|
|||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<UserSubscriptionsSection
|
||||
subscriptions={subscriptions}
|
||||
loading={subscriptionsLoading}
|
||||
error={subscriptionsError}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="min-w-0 space-y-6">
|
||||
|
|
@ -459,7 +457,7 @@ export function UserDetailPage() {
|
|||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-5">
|
||||
<div className="grid grid-cols-1 gap-x-6 gap-y-4 sm:grid-cols-2 lg:grid-cols-3">
|
||||
<div className="grid grid-cols-1 gap-x-6 gap-y-4 sm:grid-cols-2">
|
||||
<InfoItem label="Education level" value={displayValue(user.education_level)} />
|
||||
<InfoItem label="Age group" value={formatAgeGroup(user.age_group)} />
|
||||
<InfoItem label="Favorite topic" value={displayValue(user.favoutite_topic)} />
|
||||
|
|
@ -552,6 +550,16 @@ export function UserDetailPage() {
|
|||
</div>
|
||||
</div>
|
||||
|
||||
<UserSubscriptionsSection
|
||||
userId={Number(id)}
|
||||
userRole={user.role}
|
||||
userName={[user.first_name, user.last_name].filter(Boolean).join(" ") || user.email}
|
||||
subscriptions={subscriptions}
|
||||
loading={subscriptionsLoading}
|
||||
error={subscriptionsError}
|
||||
onRefresh={() => void refreshSubscriptions()}
|
||||
/>
|
||||
|
||||
{confirmDialog && (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm">
|
||||
<div className="mx-4 w-full max-w-sm rounded-xl bg-white shadow-2xl">
|
||||
|
|
|
|||
|
|
@ -0,0 +1,73 @@
|
|||
import { useEffect, useState } from "react"
|
||||
import { toast } from "sonner"
|
||||
import { adminCancelSubscription } from "../../../api/admin-subscriptions.api"
|
||||
import { notifyApiError } from "../../../lib/apiErrors"
|
||||
import { formatPlanCategory } from "../../../lib/subscriptionPlans"
|
||||
import { TypeToConfirmDialog } from "../../../lib/typeToConfirm"
|
||||
import type { UserSubscriptionRecord } from "../../../types/userAdmin.types"
|
||||
|
||||
const CONFIRM_WORD = "CANCEL"
|
||||
|
||||
type CancelSubscriptionDialogProps = {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
subscription: UserSubscriptionRecord | null
|
||||
onCancelled: () => void
|
||||
}
|
||||
|
||||
export function CancelSubscriptionDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
subscription,
|
||||
onCancelled,
|
||||
}: CancelSubscriptionDialogProps) {
|
||||
const [cancelling, setCancelling] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) setCancelling(false)
|
||||
}, [open, subscription?.id])
|
||||
|
||||
const handleConfirmCancel = async () => {
|
||||
if (!subscription) return
|
||||
setCancelling(true)
|
||||
try {
|
||||
const res = await adminCancelSubscription(subscription.id)
|
||||
toast.success(res.message || "Subscription cancelled")
|
||||
onCancelled()
|
||||
onOpenChange(false)
|
||||
} catch (err) {
|
||||
notifyApiError(err, "Failed to cancel subscription")
|
||||
} finally {
|
||||
setCancelling(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<TypeToConfirmDialog
|
||||
open={open && subscription != null}
|
||||
onOpenChange={(next) => {
|
||||
if (cancelling) return
|
||||
if (!next) onOpenChange(false)
|
||||
}}
|
||||
title="Are you sure?"
|
||||
description={
|
||||
subscription ? (
|
||||
<>
|
||||
Cancel subscription <strong>#{subscription.id}</strong> (
|
||||
{subscription.plan_name}) for this learner? They will lose access for{" "}
|
||||
<strong>{formatPlanCategory(subscription.plan_category)}</strong> immediately. Paid
|
||||
payment history is kept.
|
||||
</>
|
||||
) : (
|
||||
"Cancel this subscription? Access ends immediately. Paid payment history is kept."
|
||||
)
|
||||
}
|
||||
confirmWord={CONFIRM_WORD}
|
||||
confirmLabel="Confirm cancel"
|
||||
cancelLabel="Keep subscription"
|
||||
confirming={cancelling}
|
||||
variant="destructive"
|
||||
onConfirm={handleConfirmCancel}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,99 @@
|
|||
import { useEffect, useState } from "react"
|
||||
import { toast } from "sonner"
|
||||
import { adminApplySubscription } from "../../../api/admin-subscriptions.api"
|
||||
import { notifyApiError } from "../../../lib/apiErrors"
|
||||
import { formatPlanCategory } from "../../../lib/subscriptionPlans"
|
||||
import { TypeToConfirmDialog } from "../../../lib/typeToConfirm"
|
||||
import type { UserSubscriptionRecord } from "../../../types/userAdmin.types"
|
||||
|
||||
const CONFIRM_WORD = "EXTEND"
|
||||
|
||||
type ExtendSubscriptionDialogProps = {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
userId: number
|
||||
subscription: UserSubscriptionRecord | null
|
||||
onExtended: () => void
|
||||
}
|
||||
|
||||
function formatDateTime(value?: string | null): string {
|
||||
if (!value?.trim()) return "—"
|
||||
const parsed = new Date(value)
|
||||
if (Number.isNaN(parsed.getTime())) return "—"
|
||||
return parsed.toLocaleString(undefined, {
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
year: "numeric",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
})
|
||||
}
|
||||
|
||||
export function ExtendSubscriptionDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
userId,
|
||||
subscription,
|
||||
onExtended,
|
||||
}: ExtendSubscriptionDialogProps) {
|
||||
const [saving, setSaving] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) setSaving(false)
|
||||
}, [open, subscription?.id])
|
||||
|
||||
const handleConfirmExtend = async () => {
|
||||
if (!subscription) return
|
||||
|
||||
setSaving(true)
|
||||
try {
|
||||
const res = await adminApplySubscription(userId, {
|
||||
plan_id: subscription.plan_id,
|
||||
})
|
||||
const expiresLabel = res.data?.expires_at
|
||||
? formatDateTime(res.data.expires_at)
|
||||
: null
|
||||
toast.success(
|
||||
expiresLabel
|
||||
? `Subscription extended to ${expiresLabel}`
|
||||
: res.message || "Subscription extended",
|
||||
)
|
||||
onExtended()
|
||||
onOpenChange(false)
|
||||
} catch (err) {
|
||||
notifyApiError(err, "Failed to extend subscription")
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<TypeToConfirmDialog
|
||||
open={open && subscription != null}
|
||||
onOpenChange={(next) => {
|
||||
if (saving) return
|
||||
if (!next) onOpenChange(false)
|
||||
}}
|
||||
title="Are you sure?"
|
||||
description={
|
||||
subscription ? (
|
||||
<>
|
||||
Extend <strong>{subscription.plan_name}</strong> (#
|
||||
{subscription.id}) by one plan period? Current expiry:{" "}
|
||||
<strong>{formatDateTime(subscription.expires_at)}</strong>
|
||||
{subscription.plan_category
|
||||
? ` · ${formatPlanCategory(subscription.plan_category)}`
|
||||
: ""}
|
||||
.
|
||||
</>
|
||||
) : (
|
||||
"Extend this subscription by one plan period?"
|
||||
)
|
||||
}
|
||||
confirmWord={CONFIRM_WORD}
|
||||
confirmLabel="Extend subscription"
|
||||
confirming={saving}
|
||||
onConfirm={handleConfirmExtend}
|
||||
/>
|
||||
)
|
||||
}
|
||||
336
src/pages/user-management/components/GrantSubscriptionDialog.tsx
Normal file
336
src/pages/user-management/components/GrantSubscriptionDialog.tsx
Normal file
|
|
@ -0,0 +1,336 @@
|
|||
import { useEffect, useMemo, useState } from "react"
|
||||
import { ChevronDown, Gift, Search } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
import { adminApplySubscription } from "../../../api/admin-subscriptions.api"
|
||||
import { getSubscriptionPlans } from "../../../api/subscription-plans.api"
|
||||
import { Button } from "../../../components/ui/button"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "../../../components/ui/dialog"
|
||||
import { Input } from "../../../components/ui/input"
|
||||
import { SpinnerIcon } from "../../../components/ui/spinner-icon"
|
||||
import { getApiErrorMessage, notifyApiError } from "../../../lib/apiErrors"
|
||||
import {
|
||||
formatPlanCategory,
|
||||
formatPlanDuration,
|
||||
formatPlanPrice,
|
||||
} from "../../../lib/subscriptionPlans"
|
||||
import { TypeToConfirmDialog } from "../../../lib/typeToConfirm"
|
||||
import { cn } from "../../../lib/utils"
|
||||
import type { SubscriptionPlan } from "../../../types/subscription.types"
|
||||
|
||||
const CONFIRM_WORD = "GRANT"
|
||||
|
||||
type GrantSubscriptionDialogProps = {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
userId: number
|
||||
userName?: string
|
||||
activeByCategory: Record<string, boolean>
|
||||
onGranted: () => void
|
||||
}
|
||||
|
||||
function planLabel(plan: SubscriptionPlan): string {
|
||||
return `${plan.name} · ${formatPlanCategory(plan.category)} · ${formatPlanDuration(plan)} · ${formatPlanPrice(plan)}`
|
||||
}
|
||||
|
||||
export function GrantSubscriptionDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
userId,
|
||||
userName,
|
||||
activeByCategory,
|
||||
onGranted,
|
||||
}: GrantSubscriptionDialogProps) {
|
||||
const [plans, setPlans] = useState<SubscriptionPlan[]>([])
|
||||
const [plansLoading, setPlansLoading] = useState(false)
|
||||
const [planId, setPlanId] = useState("")
|
||||
const [planSearch, setPlanSearch] = useState("")
|
||||
const [planMenuOpen, setPlanMenuOpen] = useState(false)
|
||||
const [confirmOpen, setConfirmOpen] = useState(false)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [formError, setFormError] = useState<string | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
setPlanId("")
|
||||
setPlanSearch("")
|
||||
setPlanMenuOpen(false)
|
||||
setConfirmOpen(false)
|
||||
setFormError(null)
|
||||
setSaving(false)
|
||||
|
||||
const loadPlans = async () => {
|
||||
setPlansLoading(true)
|
||||
try {
|
||||
const res = await getSubscriptionPlans()
|
||||
setPlans(res.data.filter((plan) => plan.is_active))
|
||||
} catch (err) {
|
||||
setPlans([])
|
||||
notifyApiError(err, "Failed to load subscription plans")
|
||||
} finally {
|
||||
setPlansLoading(false)
|
||||
}
|
||||
}
|
||||
void loadPlans()
|
||||
}, [open])
|
||||
|
||||
const selectedPlan = useMemo(
|
||||
() => plans.find((p) => String(p.id) === planId) ?? null,
|
||||
[plans, planId],
|
||||
)
|
||||
|
||||
const categoryBlocked =
|
||||
selectedPlan != null && activeByCategory[selectedPlan.category] === true
|
||||
|
||||
const filteredPlans = useMemo(() => {
|
||||
const q = planSearch.trim().toLowerCase()
|
||||
if (!q) return plans
|
||||
return plans.filter((plan) => {
|
||||
const haystack = [
|
||||
plan.name,
|
||||
plan.category,
|
||||
formatPlanCategory(plan.category),
|
||||
formatPlanDuration(plan),
|
||||
formatPlanPrice(plan),
|
||||
plan.description ?? "",
|
||||
]
|
||||
.join(" ")
|
||||
.toLowerCase()
|
||||
return haystack.includes(q)
|
||||
})
|
||||
}, [plans, planSearch])
|
||||
|
||||
const handleContinue = (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
setFormError(null)
|
||||
|
||||
const id = Number(planId)
|
||||
if (!Number.isFinite(id) || id < 1) {
|
||||
setFormError("Select a subscription plan.")
|
||||
return
|
||||
}
|
||||
if (categoryBlocked) {
|
||||
setFormError(
|
||||
"This learner already has an active subscription in that category. Extend the existing plan or cancel it first.",
|
||||
)
|
||||
return
|
||||
}
|
||||
setPlanMenuOpen(false)
|
||||
setConfirmOpen(true)
|
||||
}
|
||||
|
||||
const handleConfirmGrant = async () => {
|
||||
const id = Number(planId)
|
||||
if (!Number.isFinite(id) || id < 1 || categoryBlocked) return
|
||||
|
||||
setSaving(true)
|
||||
try {
|
||||
const res = await adminApplySubscription(userId, { plan_id: id })
|
||||
toast.success(res.message || "Subscription granted")
|
||||
setConfirmOpen(false)
|
||||
onGranted()
|
||||
onOpenChange(false)
|
||||
} catch (err) {
|
||||
const detail = getApiErrorMessage(err, "Failed to grant subscription")
|
||||
setFormError(detail)
|
||||
setConfirmOpen(false)
|
||||
notifyApiError(err, "Failed to grant subscription")
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Dialog
|
||||
open={open && !confirmOpen}
|
||||
onOpenChange={(next) => {
|
||||
if (saving) return
|
||||
if (!next) {
|
||||
setConfirmOpen(false)
|
||||
onOpenChange(false)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<DialogContent className="h-auto max-h-[90vh] w-full max-w-lg overflow-y-auto rounded-[12px] border border-grayScale-100 p-0 sm:max-w-xl">
|
||||
<form onSubmit={handleContinue}>
|
||||
<DialogHeader className="border-b border-grayScale-100 px-4 py-4 sm:px-6">
|
||||
<DialogTitle className="flex items-center gap-2 text-lg font-bold text-grayScale-900">
|
||||
<Gift className="h-5 w-5 text-brand-600" aria-hidden />
|
||||
Mark as paid
|
||||
</DialogTitle>
|
||||
<DialogDescription className="text-sm text-grayScale-500">
|
||||
Grant plan access
|
||||
{userName ? ` to ${userName}` : ""}. A payment is recorded at the
|
||||
plan price.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4 px-6 py-5">
|
||||
<div className="space-y-1.5">
|
||||
<label className="text-[11px] font-bold uppercase tracking-wider text-grayScale-400">
|
||||
Plan <span className="text-destructive">*</span>
|
||||
</label>
|
||||
{plansLoading ? (
|
||||
<div className="flex items-center gap-2 text-sm text-grayScale-500">
|
||||
<SpinnerIcon className="h-4 w-4" />
|
||||
Loading plans…
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
<button
|
||||
type="button"
|
||||
className="flex h-11 w-full items-center justify-between rounded-[6px] border border-input bg-grayScale-50 px-3 text-left text-sm text-grayScale-700 shadow-sm transition hover:bg-grayScale-100 focus:outline-none focus-visible:border-brand-400 focus-visible:ring-2 focus-visible:ring-brand-200"
|
||||
onClick={() => {
|
||||
setPlanMenuOpen((prev) => !prev)
|
||||
if (planMenuOpen) setPlanSearch("")
|
||||
}}
|
||||
aria-haspopup="listbox"
|
||||
aria-expanded={planMenuOpen}
|
||||
>
|
||||
<span className={cn("truncate", !selectedPlan && "text-grayScale-400")}>
|
||||
{selectedPlan ? planLabel(selectedPlan) : "Select a plan…"}
|
||||
</span>
|
||||
<ChevronDown
|
||||
className={cn(
|
||||
"h-4 w-4 shrink-0 text-grayScale-400 transition-transform",
|
||||
planMenuOpen && "rotate-180",
|
||||
)}
|
||||
/>
|
||||
</button>
|
||||
|
||||
{planMenuOpen ? (
|
||||
<div className="rounded-[8px] border border-grayScale-200 bg-white p-2 shadow-sm">
|
||||
<div className="relative mb-2">
|
||||
<Search className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-grayScale-300" />
|
||||
<Input
|
||||
value={planSearch}
|
||||
onChange={(e) => setPlanSearch(e.target.value)}
|
||||
placeholder="Search plans…"
|
||||
className="h-9 rounded-lg border-grayScale-200 pl-8 text-sm"
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
className="max-h-[min(16rem,40vh)] space-y-1 overflow-y-auto"
|
||||
role="listbox"
|
||||
>
|
||||
{filteredPlans.map((plan) => {
|
||||
const blocked = activeByCategory[plan.category] === true
|
||||
const selected = String(plan.id) === planId
|
||||
return (
|
||||
<button
|
||||
key={plan.id}
|
||||
type="button"
|
||||
role="option"
|
||||
aria-selected={selected}
|
||||
disabled={blocked}
|
||||
className={cn(
|
||||
"w-full rounded-md px-2 py-2 text-left text-sm transition",
|
||||
blocked && "cursor-not-allowed opacity-50",
|
||||
selected
|
||||
? "bg-brand-100/50 text-brand-700"
|
||||
: "text-grayScale-600 hover:bg-grayScale-100",
|
||||
)}
|
||||
onClick={() => {
|
||||
if (blocked) return
|
||||
setPlanId(String(plan.id))
|
||||
setPlanMenuOpen(false)
|
||||
setPlanSearch("")
|
||||
setFormError(null)
|
||||
}}
|
||||
>
|
||||
<span className="block font-medium">{plan.name}</span>
|
||||
<span className="block text-xs text-grayScale-400">
|
||||
{formatPlanCategory(plan.category)} · {formatPlanDuration(plan)} ·{" "}
|
||||
{formatPlanPrice(plan)}
|
||||
{blocked ? " — category active" : ""}
|
||||
</span>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
{filteredPlans.length === 0 ? (
|
||||
<p className="px-2 py-1.5 text-sm text-grayScale-400">
|
||||
No plans found
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
)}
|
||||
{selectedPlan && categoryBlocked ? (
|
||||
<p className="text-xs text-amber-700">
|
||||
An active {formatPlanCategory(selectedPlan.category)} subscription already
|
||||
exists. Extend or cancel it instead.
|
||||
</p>
|
||||
) : selectedPlan ? (
|
||||
<p className="text-xs text-grayScale-500">
|
||||
Payment recorded: {formatPlanPrice(selectedPlan)}.
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{formError ? <p className="text-sm text-destructive">{formError}</p> : null}
|
||||
</div>
|
||||
|
||||
<DialogFooter className="gap-2 border-t border-grayScale-100 px-6 py-4 sm:justify-end">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="rounded-[6px]"
|
||||
disabled={saving}
|
||||
onClick={() => onOpenChange(false)}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={saving || plansLoading || !planId || categoryBlocked}
|
||||
className="rounded-[6px] bg-brand-500 font-semibold text-white hover:bg-brand-600"
|
||||
>
|
||||
Continue
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<TypeToConfirmDialog
|
||||
open={confirmOpen}
|
||||
onOpenChange={setConfirmOpen}
|
||||
title="Are you sure?"
|
||||
description={
|
||||
selectedPlan ? (
|
||||
<>
|
||||
Grant <strong>{selectedPlan.name}</strong> (
|
||||
{formatPlanCategory(selectedPlan.category)})
|
||||
{userName ? (
|
||||
<>
|
||||
{" "}
|
||||
to <strong>{userName}</strong>
|
||||
</>
|
||||
) : (
|
||||
" to this learner"
|
||||
)}
|
||||
? A payment of <strong>{formatPlanPrice(selectedPlan)}</strong> will be
|
||||
recorded.
|
||||
</>
|
||||
) : (
|
||||
"Grant this subscription?"
|
||||
)
|
||||
}
|
||||
confirmWord={CONFIRM_WORD}
|
||||
confirmLabel="Mark as paid"
|
||||
confirming={saving}
|
||||
onConfirm={handleConfirmGrant}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
|
@ -1,9 +1,8 @@
|
|||
import { useState } from "react";
|
||||
import { ChevronDown, ChevronRight, CreditCard, RefreshCw } from "lucide-react";
|
||||
import { Badge } from "../../../components/ui/badge";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "../../../components/ui/card";
|
||||
import { Separator } from "../../../components/ui/separator";
|
||||
import { SpinnerIcon } from "../../../components/ui/spinner-icon";
|
||||
import { useMemo, useState } from "react"
|
||||
import { ChevronDown, ChevronRight, RefreshCw } from "lucide-react"
|
||||
import { Button } from "../../../components/ui/button"
|
||||
import { Card, CardContent } from "../../../components/ui/card"
|
||||
import { SpinnerIcon } from "../../../components/ui/spinner-icon"
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
|
|
@ -11,272 +10,615 @@ import {
|
|||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "../../../components/ui/table";
|
||||
import { cn } from "../../../lib/utils";
|
||||
import { formatPlanCategory } from "../../../lib/subscriptionPlans";
|
||||
import { displayValue, NOT_ASSIGNED_LABEL } from "../../../lib/displayValue";
|
||||
import type { UserSubscriptionsData } from "../../../types/userAdmin.types";
|
||||
} from "../../../components/ui/table"
|
||||
import { useTeamPermissions } from "../../../hooks/useTeamPermissions"
|
||||
import { displayValue, NOT_ASSIGNED_LABEL } from "../../../lib/displayValue"
|
||||
import {
|
||||
formatAdminPaymentMethod,
|
||||
hasSubscriptionAdminPermission,
|
||||
isLearnerRole,
|
||||
SUBSCRIPTION_ADMIN_PERMISSIONS,
|
||||
} from "../../../lib/subscriptionAdminPermissions"
|
||||
import { formatPlanCategory } from "../../../lib/subscriptionPlans"
|
||||
import { cn } from "../../../lib/utils"
|
||||
import type { UserSubscriptionRecord, UserSubscriptionsData } from "../../../types/userAdmin.types"
|
||||
import { CancelSubscriptionDialog } from "./CancelSubscriptionDialog"
|
||||
import { ExtendSubscriptionDialog } from "./ExtendSubscriptionDialog"
|
||||
import { GrantSubscriptionDialog } from "./GrantSubscriptionDialog"
|
||||
|
||||
function formatStatusLabel(status: string): string {
|
||||
const value = status.trim();
|
||||
if (!value) return NOT_ASSIGNED_LABEL;
|
||||
return value
|
||||
.split("_")
|
||||
.map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase())
|
||||
.join(" ");
|
||||
function formatPlanTitle(subscription: UserSubscriptionRecord): string {
|
||||
const name = subscription.plan_name?.trim()
|
||||
if (name) return name
|
||||
if (subscription.duration_value && subscription.duration_unit) {
|
||||
const unit = subscription.duration_unit.toLowerCase().replace(/s$/, "")
|
||||
const plural = subscription.duration_value === 1 ? unit : `${unit}s`
|
||||
return `${subscription.duration_value}-${plural.charAt(0).toUpperCase()}${plural.slice(1)}`
|
||||
}
|
||||
return NOT_ASSIGNED_LABEL
|
||||
}
|
||||
|
||||
function formatCategoryLabel(value: string): string {
|
||||
return formatPlanCategory(value);
|
||||
function formatExpiryDate(value?: string | null): string {
|
||||
if (!value?.trim()) return NOT_ASSIGNED_LABEL
|
||||
const parsed = new Date(value)
|
||||
if (Number.isNaN(parsed.getTime())) return NOT_ASSIGNED_LABEL
|
||||
return parsed.toLocaleDateString(undefined, {
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
year: "numeric",
|
||||
})
|
||||
}
|
||||
|
||||
function formatDateTime(value?: string | null): string {
|
||||
if (!value?.trim()) return NOT_ASSIGNED_LABEL;
|
||||
const parsed = new Date(value);
|
||||
if (Number.isNaN(parsed.getTime())) return NOT_ASSIGNED_LABEL;
|
||||
if (!value?.trim()) return NOT_ASSIGNED_LABEL
|
||||
const parsed = new Date(value)
|
||||
if (Number.isNaN(parsed.getTime())) return NOT_ASSIGNED_LABEL
|
||||
return parsed.toLocaleString(undefined, {
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
year: "numeric",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
function getSubscriptionStatusClasses(status: string): string {
|
||||
const normalized = status.trim().toUpperCase();
|
||||
if (normalized === "ACTIVE" || normalized === "SUCCESS") {
|
||||
return "bg-mint-500/15 text-mint-500 border border-mint-500/25";
|
||||
}
|
||||
if (normalized === "PENDING") {
|
||||
return "bg-gold-100 text-gold-600 border border-gold-300/40";
|
||||
}
|
||||
if (normalized === "FAILED" || normalized === "EXPIRED") {
|
||||
return "bg-destructive/15 text-destructive border border-destructive/25";
|
||||
}
|
||||
return "bg-grayScale-100 text-grayScale-600 border border-grayScale-200";
|
||||
function getDaysLeft(expiresAt?: string | null): number | null {
|
||||
if (!expiresAt?.trim()) return null
|
||||
const expires = new Date(expiresAt)
|
||||
if (Number.isNaN(expires.getTime())) return null
|
||||
const ms = expires.getTime() - Date.now()
|
||||
return Math.ceil(ms / 86_400_000)
|
||||
}
|
||||
|
||||
function formatDuration(value: number, unit: string): string {
|
||||
if (!value) return NOT_ASSIGNED_LABEL;
|
||||
const label = unit.trim().toLowerCase();
|
||||
const plural = value === 1 ? label.replace(/s$/, "") : label.endsWith("s") ? label : `${label}s`;
|
||||
return `${value} ${plural}`;
|
||||
function formatDaysLeftLabel(daysLeft: number): string {
|
||||
if (daysLeft <= 0) return "Expired"
|
||||
if (daysLeft === 1) return "1 day left"
|
||||
return `${daysLeft} days left`
|
||||
}
|
||||
|
||||
function formatMoney(amount: number, currency: string): string {
|
||||
if (!Number.isFinite(amount)) return NOT_ASSIGNED_LABEL;
|
||||
const code = currency.trim() || "ETB";
|
||||
return `${amount.toLocaleString()} ${code}`;
|
||||
if (!Number.isFinite(amount)) return NOT_ASSIGNED_LABEL
|
||||
const code = currency.trim() || "ETB"
|
||||
return `${amount.toLocaleString()} ${code}`
|
||||
}
|
||||
|
||||
function formatStatusLabel(status: string): string {
|
||||
const value = status.trim()
|
||||
if (!value) return NOT_ASSIGNED_LABEL
|
||||
return value
|
||||
.split("_")
|
||||
.map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase())
|
||||
.join(" ")
|
||||
}
|
||||
|
||||
function ActiveStatusBadge({
|
||||
label,
|
||||
tone,
|
||||
}: {
|
||||
label: string
|
||||
tone: "active" | "pending" | "inactive"
|
||||
}) {
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-xs font-semibold",
|
||||
tone === "active" && "bg-emerald-50 text-emerald-700",
|
||||
tone === "pending" && "bg-amber-50 text-amber-700",
|
||||
tone === "inactive" && "bg-grayScale-100 text-grayScale-600",
|
||||
)}
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
"h-1.5 w-1.5 rounded-full",
|
||||
tone === "active" && "bg-emerald-500",
|
||||
tone === "pending" && "bg-amber-500",
|
||||
tone === "inactive" && "bg-grayScale-400",
|
||||
)}
|
||||
/>
|
||||
{label}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
function SubscriptionManageCard({
|
||||
subscription,
|
||||
canExtend,
|
||||
canGrant,
|
||||
canCancel,
|
||||
hasActiveSubscription,
|
||||
onExtend,
|
||||
onGrant,
|
||||
onCancel,
|
||||
}: {
|
||||
subscription: UserSubscriptionRecord
|
||||
canExtend: boolean
|
||||
canGrant: boolean
|
||||
canCancel: boolean
|
||||
hasActiveSubscription: boolean
|
||||
onExtend: () => void
|
||||
onGrant: () => void
|
||||
onCancel: () => void
|
||||
}) {
|
||||
const daysLeft = getDaysLeft(subscription.expires_at)
|
||||
const statusUpper = subscription.status.toUpperCase()
|
||||
const isActive = subscription.is_currently_active || statusUpper === "ACTIVE"
|
||||
const statusTone = isActive ? "active" : statusUpper === "PENDING" ? "pending" : "inactive"
|
||||
const extendEnabled = canExtend && hasActiveSubscription && isActive
|
||||
const cancelEnabled = canCancel && hasActiveSubscription && isActive && statusUpper !== "CANCELLED"
|
||||
const markAsPaidEnabled = canGrant && !hasActiveSubscription
|
||||
|
||||
return (
|
||||
<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">
|
||||
<h3 className="text-base font-bold text-grayScale-900">Subscription</h3>
|
||||
<ActiveStatusBadge label={formatStatusLabel(subscription.status)} tone={statusTone} />
|
||||
</div>
|
||||
|
||||
<div className="mt-4 border-t border-grayScale-100 pt-4">
|
||||
<div className="grid gap-5 sm:grid-cols-2">
|
||||
<div>
|
||||
<p className="text-xs font-medium text-grayScale-400">Current Plan</p>
|
||||
<p className="mt-1 text-lg font-bold tracking-tight text-grayScale-900">
|
||||
{formatPlanTitle(subscription)}
|
||||
</p>
|
||||
<p className="mt-0.5 text-xs text-grayScale-500">
|
||||
{formatPlanCategory(subscription.plan_category)}
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-xs font-medium text-grayScale-400">Expires On</p>
|
||||
<div className="mt-1 flex flex-wrap items-center gap-2">
|
||||
<p className="text-lg font-bold tracking-tight text-grayScale-900">
|
||||
{formatExpiryDate(subscription.expires_at)}
|
||||
</p>
|
||||
{daysLeft != null ? (
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex rounded-full px-2 py-0.5 text-[11px] font-semibold",
|
||||
daysLeft <= 0
|
||||
? "bg-destructive/10 text-destructive"
|
||||
: daysLeft <= 14
|
||||
? "bg-orange-50 text-orange-600"
|
||||
: "bg-emerald-50 text-emerald-700",
|
||||
)}
|
||||
>
|
||||
{formatDaysLeftLabel(daysLeft)}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-6 space-y-2.5">
|
||||
{canExtend ? (
|
||||
<Button
|
||||
type="button"
|
||||
className="h-11 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}
|
||||
title={
|
||||
!extendEnabled
|
||||
? "Extend is only available when this learner has an active subscription."
|
||||
: undefined
|
||||
}
|
||||
onClick={onExtend}
|
||||
>
|
||||
<RefreshCw className="mr-2 h-4 w-4" />
|
||||
Extend Subscription
|
||||
</Button>
|
||||
) : null}
|
||||
|
||||
{(canGrant || canCancel) && (
|
||||
<div
|
||||
className={cn(
|
||||
"grid gap-2.5",
|
||||
canGrant && canCancel ? "grid-cols-2" : "grid-cols-1",
|
||||
)}
|
||||
>
|
||||
{canGrant ? (
|
||||
<Button
|
||||
type="button"
|
||||
className="h-11 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}
|
||||
title={
|
||||
!markAsPaidEnabled
|
||||
? "Mark as paid is unavailable while this learner already has an active subscription."
|
||||
: undefined
|
||||
}
|
||||
onClick={onGrant}
|
||||
>
|
||||
Mark as Paid
|
||||
</Button>
|
||||
) : null}
|
||||
{canCancel ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="h-11 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 learner has an active subscription."
|
||||
: undefined
|
||||
}
|
||||
onClick={onCancel}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function EmptySubscriptionCard({
|
||||
displayStatus,
|
||||
canGrant,
|
||||
canExtend,
|
||||
canCancel,
|
||||
onGrant,
|
||||
}: {
|
||||
displayStatus: string
|
||||
canGrant: boolean
|
||||
canExtend: boolean
|
||||
canCancel: boolean
|
||||
onGrant: () => void
|
||||
}) {
|
||||
const upper = displayStatus.toUpperCase()
|
||||
const tone =
|
||||
upper === "ACTIVE" ? "active" : upper === "PENDING" ? "pending" : "inactive"
|
||||
|
||||
return (
|
||||
<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">
|
||||
<h3 className="text-base font-bold text-grayScale-900">Subscription</h3>
|
||||
<ActiveStatusBadge
|
||||
label={formatStatusLabel(displayStatus || "Unsubscribed")}
|
||||
tone={tone}
|
||||
/>
|
||||
</div>
|
||||
<div className="mt-4 border-t border-grayScale-100 pt-4">
|
||||
<p className="text-sm text-grayScale-500">No active subscription for this learner.</p>
|
||||
</div>
|
||||
<div className="mt-6 space-y-2.5">
|
||||
{canExtend ? (
|
||||
<Button
|
||||
type="button"
|
||||
className="h-11 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
|
||||
title="Extend is only available when this learner has an active subscription."
|
||||
>
|
||||
<RefreshCw className="mr-2 h-4 w-4" />
|
||||
Extend Subscription
|
||||
</Button>
|
||||
) : null}
|
||||
{(canGrant || canCancel) && (
|
||||
<div
|
||||
className={cn(
|
||||
"grid gap-2.5",
|
||||
canGrant && canCancel ? "grid-cols-2" : "grid-cols-1",
|
||||
)}
|
||||
>
|
||||
{canGrant ? (
|
||||
<Button
|
||||
type="button"
|
||||
className="h-11 rounded-xl bg-brand-500 text-sm font-semibold text-white hover:bg-brand-600"
|
||||
onClick={onGrant}
|
||||
>
|
||||
Mark as Paid
|
||||
</Button>
|
||||
) : null}
|
||||
{canCancel ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="h-11 rounded-xl border-grayScale-200 bg-white text-sm font-semibold text-grayScale-700 disabled:pointer-events-auto disabled:cursor-not-allowed disabled:opacity-50"
|
||||
disabled
|
||||
title="Cancel is only available when this learner has an active subscription."
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function UserSubscriptionsSection({
|
||||
userId,
|
||||
userRole,
|
||||
userName,
|
||||
subscriptions,
|
||||
loading,
|
||||
error,
|
||||
onRefresh,
|
||||
}: {
|
||||
subscriptions: UserSubscriptionsData | null;
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
userId: number
|
||||
userRole?: string
|
||||
userName?: string
|
||||
subscriptions: UserSubscriptionsData | null
|
||||
loading: boolean
|
||||
error: string | null
|
||||
onRefresh: () => void
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const recentPayments = subscriptions?.payments.slice(0, 8) ?? [];
|
||||
const { permissions } = useTeamPermissions()
|
||||
const [detailsOpen, setDetailsOpen] = useState(false)
|
||||
const [grantOpen, setGrantOpen] = useState(false)
|
||||
const [extendTarget, setExtendTarget] = useState<UserSubscriptionRecord | null>(null)
|
||||
const [cancelTarget, setCancelTarget] = useState<UserSubscriptionRecord | null>(null)
|
||||
|
||||
const canApply = hasSubscriptionAdminPermission(
|
||||
SUBSCRIPTION_ADMIN_PERMISSIONS.apply,
|
||||
permissions,
|
||||
)
|
||||
const canExtend = canApply
|
||||
const canCancel = hasSubscriptionAdminPermission(
|
||||
SUBSCRIPTION_ADMIN_PERMISSIONS.cancel,
|
||||
permissions,
|
||||
)
|
||||
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 recentPayments = subscriptions?.payments.slice(0, 12) ?? []
|
||||
const history = useMemo(() => {
|
||||
if (!subscriptions) return []
|
||||
const activeIds = new Set(subscriptions.active_subscriptions.map((s) => s.id))
|
||||
return subscriptions.subscriptions.filter((s) => !activeIds.has(s.id))
|
||||
}, [subscriptions])
|
||||
|
||||
return (
|
||||
<Card className="shadow-soft">
|
||||
<CardHeader className="pb-3">
|
||||
<button
|
||||
type="button"
|
||||
className="flex w-full items-start justify-between gap-3 text-left"
|
||||
onClick={() => setOpen((prev) => !prev)}
|
||||
aria-expanded={open}
|
||||
>
|
||||
<div className="flex items-start gap-2">
|
||||
<div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-brand-100/50">
|
||||
<CreditCard className="h-4 w-4 text-brand-600" />
|
||||
</div>
|
||||
<div>
|
||||
<CardTitle className="text-base">Subscriptions</CardTitle>
|
||||
<p className="mt-0.5 text-xs text-grayScale-500">
|
||||
Active plans, billing history, and payment records for this user.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-2">
|
||||
{!open && subscriptions ? (
|
||||
<Badge className={cn(getSubscriptionStatusClasses(subscriptions.display_status))}>
|
||||
{formatStatusLabel(subscriptions.display_status)}
|
||||
</Badge>
|
||||
) : null}
|
||||
{open ? (
|
||||
<ChevronDown className="mt-1 h-4 w-4 text-grayScale-400" />
|
||||
) : (
|
||||
<ChevronRight className="mt-1 h-4 w-4 text-grayScale-400" />
|
||||
)}
|
||||
</div>
|
||||
</button>
|
||||
</CardHeader>
|
||||
{open ? (
|
||||
<CardContent className="space-y-4">
|
||||
<>
|
||||
<div className="w-full max-w-md space-y-4">
|
||||
{loading ? (
|
||||
<div className="flex items-center gap-2 text-sm text-grayScale-400">
|
||||
<SpinnerIcon className="h-4 w-4" />
|
||||
Loading subscriptions...
|
||||
</div>
|
||||
<Card className="rounded-2xl border border-grayScale-200 shadow-sm">
|
||||
<CardContent className="flex items-center gap-2 p-6 text-sm text-grayScale-400">
|
||||
<SpinnerIcon className="h-4 w-4" />
|
||||
Loading subscription…
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : null}
|
||||
|
||||
{error ? <p className="text-sm text-destructive">{error}</p> : null}
|
||||
{error ? (
|
||||
<Card className="rounded-2xl border border-destructive/20 shadow-sm">
|
||||
<CardContent className="p-6 text-sm text-destructive">{error}</CardContent>
|
||||
</Card>
|
||||
) : null}
|
||||
|
||||
{!loading && !error && subscriptions ? (
|
||||
<>
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<span className="text-sm text-grayScale-500">Overall status</span>
|
||||
<Badge className={cn(getSubscriptionStatusClasses(subscriptions.display_status))}>
|
||||
{formatStatusLabel(subscriptions.display_status)}
|
||||
</Badge>
|
||||
</div>
|
||||
{activePlans.length > 0 ? (
|
||||
<div className="space-y-4">
|
||||
{activePlans.map((subscription) => (
|
||||
<SubscriptionManageCard
|
||||
key={subscription.id}
|
||||
subscription={subscription}
|
||||
canExtend={canExtend}
|
||||
canGrant={showGrant}
|
||||
canCancel={canCancel}
|
||||
hasActiveSubscription={hasActiveSubscription}
|
||||
onExtend={() => setExtendTarget(subscription)}
|
||||
onGrant={() => setGrantOpen(true)}
|
||||
onCancel={() => setCancelTarget(subscription)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<EmptySubscriptionCard
|
||||
displayStatus={subscriptions.display_status}
|
||||
canGrant={showGrant}
|
||||
canExtend={canExtend}
|
||||
canCancel={canCancel}
|
||||
onGrant={() => setGrantOpen(true)}
|
||||
/>
|
||||
)}
|
||||
|
||||
<div className="flex items-center justify-between gap-3 text-sm">
|
||||
<span className="text-grayScale-500">Active subscription</span>
|
||||
<span className="font-medium text-grayScale-700">
|
||||
{subscriptions.has_active_subscription ? "Yes" : "No"}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{Object.keys(subscriptions.active_by_category).length > 0 ? (
|
||||
<>
|
||||
<Separator />
|
||||
<div>
|
||||
<p className="mb-2 text-[11px] font-medium uppercase tracking-wider text-grayScale-400">
|
||||
Access by category
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{Object.entries(subscriptions.active_by_category).map(([category, active]) => (
|
||||
<Badge
|
||||
key={category}
|
||||
variant={active ? "default" : "outline"}
|
||||
className={cn(!active && "text-grayScale-500")}
|
||||
>
|
||||
{formatCategoryLabel(category)}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
) : null}
|
||||
|
||||
<Separator />
|
||||
|
||||
<div>
|
||||
<p className="mb-2 text-[11px] font-medium uppercase tracking-wider text-grayScale-400">
|
||||
Active plans
|
||||
</p>
|
||||
{subscriptions.active_subscriptions.length === 0 ? (
|
||||
<p className="text-sm text-grayScale-400">No active subscriptions.</p>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{subscriptions.active_subscriptions.map((subscription) => (
|
||||
<div
|
||||
key={subscription.id}
|
||||
className="rounded-xl border border-grayScale-100 bg-grayScale-50/60 p-3"
|
||||
>
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div>
|
||||
<p className="text-sm font-semibold text-grayScale-800">{subscription.plan_name}</p>
|
||||
<p className="text-xs text-grayScale-500">
|
||||
{formatCategoryLabel(subscription.plan_category)}
|
||||
</p>
|
||||
{(history.length > 0 || recentPayments.length > 0) && (
|
||||
<Card className="rounded-2xl border border-grayScale-200 shadow-sm">
|
||||
<button
|
||||
type="button"
|
||||
className="flex w-full items-center justify-between gap-3 px-5 py-4 text-left"
|
||||
onClick={() => setDetailsOpen((v) => !v)}
|
||||
aria-expanded={detailsOpen}
|
||||
>
|
||||
<span className="text-sm font-semibold text-grayScale-800">
|
||||
History & payments
|
||||
</span>
|
||||
{detailsOpen ? (
|
||||
<ChevronDown className="h-4 w-4 text-grayScale-400" />
|
||||
) : (
|
||||
<ChevronRight className="h-4 w-4 text-grayScale-400" />
|
||||
)}
|
||||
</button>
|
||||
{detailsOpen ? (
|
||||
<CardContent className="space-y-5 border-t border-grayScale-100 px-5 pb-5 pt-4">
|
||||
{Object.keys(subscriptions.active_by_category).length > 0 ? (
|
||||
<div>
|
||||
<p className="mb-2 text-[11px] font-medium uppercase tracking-wider text-grayScale-400">
|
||||
Access by category
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{Object.entries(subscriptions.active_by_category).map(
|
||||
([category, active]) => (
|
||||
<span
|
||||
key={category}
|
||||
className={cn(
|
||||
"inline-flex rounded-full px-2.5 py-1 text-xs font-semibold",
|
||||
active
|
||||
? "bg-emerald-50 text-emerald-700"
|
||||
: "bg-grayScale-100 text-grayScale-500",
|
||||
)}
|
||||
>
|
||||
{formatPlanCategory(category)} {active ? "✓" : "✗"}
|
||||
</span>
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
<Badge className={cn(getSubscriptionStatusClasses(subscription.status))}>
|
||||
{formatStatusLabel(subscription.status)}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="mt-3 grid gap-2 text-xs text-grayScale-600 sm:grid-cols-2">
|
||||
<p>
|
||||
<span className="text-grayScale-400">Price: </span>
|
||||
{formatMoney(subscription.price, subscription.currency)}
|
||||
</p>
|
||||
<p>
|
||||
<span className="text-grayScale-400">Duration: </span>
|
||||
{formatDuration(subscription.duration_value, subscription.duration_unit)}
|
||||
</p>
|
||||
<p>
|
||||
<span className="text-grayScale-400">Starts: </span>
|
||||
{formatDateTime(subscription.starts_at)}
|
||||
</p>
|
||||
<p>
|
||||
<span className="text-grayScale-400">Expires: </span>
|
||||
{formatDateTime(subscription.expires_at)}
|
||||
</p>
|
||||
<p>
|
||||
<span className="text-grayScale-400">Payment: </span>
|
||||
{displayValue(subscription.payment_method)}
|
||||
</p>
|
||||
<p className="inline-flex items-center gap-1">
|
||||
<RefreshCw className="h-3 w-3 text-grayScale-400" />
|
||||
Auto-renew: {subscription.auto_renew ? "On" : "Off"}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{recentPayments.length > 0 ? (
|
||||
<>
|
||||
<Separator />
|
||||
<div>
|
||||
<p className="mb-2 text-[11px] font-medium uppercase tracking-wider text-grayScale-400">
|
||||
Recent payments
|
||||
</p>
|
||||
<div className="overflow-x-auto rounded-xl border">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Plan</TableHead>
|
||||
<TableHead>Amount</TableHead>
|
||||
<TableHead>Status</TableHead>
|
||||
<TableHead>Method</TableHead>
|
||||
<TableHead>Date</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{recentPayments.map((payment) => (
|
||||
<TableRow key={payment.id}>
|
||||
<TableCell className="text-sm text-grayScale-700">
|
||||
{displayValue(payment.plan_name)}
|
||||
</TableCell>
|
||||
<TableCell className="text-sm text-grayScale-700">
|
||||
{formatMoney(payment.amount, payment.currency)}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Badge className={cn(getSubscriptionStatusClasses(payment.status))}>
|
||||
{formatStatusLabel(payment.status)}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell className="text-xs text-grayScale-500">
|
||||
{displayValue(payment.payment_method)}
|
||||
</TableCell>
|
||||
<TableCell className="text-xs text-grayScale-500">
|
||||
{formatDateTime(payment.paid_at || payment.created_at)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
{history.length > 0 ? (
|
||||
<div className="space-y-2">
|
||||
<p className="text-[11px] font-medium uppercase tracking-wider text-grayScale-400">
|
||||
Past subscriptions
|
||||
</p>
|
||||
{history.map((subscription) => (
|
||||
<div
|
||||
key={subscription.id}
|
||||
className="flex flex-wrap items-center justify-between gap-2 rounded-xl border border-grayScale-100 px-3 py-2.5"
|
||||
>
|
||||
<div>
|
||||
<p className="text-sm font-medium text-grayScale-800">
|
||||
#{subscription.id} · {formatPlanTitle(subscription)}
|
||||
</p>
|
||||
<p className="text-xs text-grayScale-500">
|
||||
{formatPlanCategory(subscription.plan_category)} ·{" "}
|
||||
{formatExpiryDate(subscription.expires_at)}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<ActiveStatusBadge
|
||||
label={formatStatusLabel(subscription.status)}
|
||||
tone={
|
||||
subscription.status.toUpperCase() === "PENDING"
|
||||
? "pending"
|
||||
: "inactive"
|
||||
}
|
||||
/>
|
||||
{canExtend ? (
|
||||
<Button
|
||||
type="button"
|
||||
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}
|
||||
title={
|
||||
!hasActiveSubscription || !subscription.is_currently_active
|
||||
? "Extend is only available for an active subscription."
|
||||
: undefined
|
||||
}
|
||||
onClick={() => setExtendTarget(subscription)}
|
||||
>
|
||||
Extend
|
||||
</Button>
|
||||
) : null}
|
||||
{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={
|
||||
!hasActiveSubscription ||
|
||||
!subscription.is_currently_active ||
|
||||
subscription.status.toUpperCase() === "CANCELLED"
|
||||
}
|
||||
title={
|
||||
!hasActiveSubscription || !subscription.is_currently_active
|
||||
? "Cancel is only available for an active subscription."
|
||||
: undefined
|
||||
}
|
||||
onClick={() => setCancelTarget(subscription)}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{recentPayments.length > 0 ? (
|
||||
<div>
|
||||
<p className="mb-2 text-[11px] font-medium uppercase tracking-wider text-grayScale-400">
|
||||
Recent payments
|
||||
</p>
|
||||
<div className="overflow-x-auto rounded-xl border border-grayScale-100">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Plan</TableHead>
|
||||
<TableHead>Amount</TableHead>
|
||||
<TableHead>Status</TableHead>
|
||||
<TableHead>Method</TableHead>
|
||||
<TableHead>Date</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{recentPayments.map((payment) => (
|
||||
<TableRow key={payment.id}>
|
||||
<TableCell className="text-sm text-grayScale-700">
|
||||
{displayValue(payment.plan_name)}
|
||||
</TableCell>
|
||||
<TableCell className="text-sm text-grayScale-700">
|
||||
{formatMoney(payment.amount, payment.currency)}
|
||||
</TableCell>
|
||||
<TableCell className="text-sm text-grayScale-700">
|
||||
{formatStatusLabel(payment.status)}
|
||||
</TableCell>
|
||||
<TableCell className="text-xs text-grayScale-500">
|
||||
{formatAdminPaymentMethod(payment.payment_method)}
|
||||
</TableCell>
|
||||
<TableCell className="text-xs text-grayScale-500">
|
||||
{formatDateTime(payment.paid_at || payment.created_at)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</CardContent>
|
||||
) : null}
|
||||
</Card>
|
||||
)}
|
||||
</>
|
||||
) : null}
|
||||
|
||||
{!loading && !error && !subscriptions ? (
|
||||
<p className="text-sm text-grayScale-400">No subscription data available.</p>
|
||||
<Card className="rounded-2xl border border-grayScale-200 shadow-sm">
|
||||
<CardContent className="p-6 text-sm text-grayScale-400">
|
||||
No subscription data available.
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : null}
|
||||
</CardContent>
|
||||
) : null}
|
||||
</Card>
|
||||
);
|
||||
</div>
|
||||
|
||||
<GrantSubscriptionDialog
|
||||
open={grantOpen}
|
||||
onOpenChange={setGrantOpen}
|
||||
userId={userId}
|
||||
userName={userName}
|
||||
activeByCategory={subscriptions?.active_by_category ?? {}}
|
||||
onGranted={onRefresh}
|
||||
/>
|
||||
|
||||
<ExtendSubscriptionDialog
|
||||
open={extendTarget != null}
|
||||
onOpenChange={(next) => {
|
||||
if (!next) setExtendTarget(null)
|
||||
}}
|
||||
userId={userId}
|
||||
subscription={extendTarget}
|
||||
onExtended={onRefresh}
|
||||
/>
|
||||
|
||||
<CancelSubscriptionDialog
|
||||
open={cancelTarget != null}
|
||||
onOpenChange={(next) => {
|
||||
if (!next) setCancelTarget(null)
|
||||
}}
|
||||
subscription={cancelTarget}
|
||||
onCancelled={onRefresh}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
|
|
|||
35
src/types/adminSubscription.types.ts
Normal file
35
src/types/adminSubscription.types.ts
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
export type AdminSubscriptionStatus = "PENDING" | "ACTIVE" | "EXPIRED" | "CANCELLED" | string
|
||||
|
||||
export interface AdminSubscriptionRes {
|
||||
id: number
|
||||
user_id: number
|
||||
plan_id: number
|
||||
plan_name?: string
|
||||
starts_at: string
|
||||
expires_at: string
|
||||
status: AdminSubscriptionStatus
|
||||
payment_reference?: string
|
||||
payment_method?: string
|
||||
auto_renew: boolean
|
||||
duration_value?: number
|
||||
duration_unit?: string
|
||||
price?: number
|
||||
currency?: string
|
||||
created_at: string
|
||||
}
|
||||
|
||||
/** Body for unified grant-or-extend. */
|
||||
export interface AdminApplySubscriptionBody {
|
||||
plan_id: number
|
||||
}
|
||||
|
||||
/** @deprecated Prefer AdminApplySubscriptionBody */
|
||||
export type AdminGrantSubscriptionBody = AdminApplySubscriptionBody
|
||||
|
||||
export interface AdminSubscriptionMutationResponse {
|
||||
message?: string
|
||||
data: AdminSubscriptionRes
|
||||
success?: boolean
|
||||
status_code?: number
|
||||
metadata?: unknown
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user