diff --git a/src/api/admin-subscriptions.api.ts b/src/api/admin-subscriptions.api.ts new file mode 100644 index 0000000..a62730a --- /dev/null +++ b/src/api/admin-subscriptions.api.ts @@ -0,0 +1,74 @@ +import http from "./http" +import type { + AdminApplySubscriptionBody, + AdminSubscriptionMutationResponse, + AdminSubscriptionRes, +} from "../types/adminSubscription.types" + +function isRecord(value: unknown): value is Record { + 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( + `/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(`/admin/subscriptions/${subscriptionId}/cancel`) + .then(mutationResult) diff --git a/src/api/subscription-plans.api.ts b/src/api/subscription-plans.api.ts index a018c6b..f79dae5 100644 --- a/src/api/subscription-plans.api.ts +++ b/src/api/subscription-plans.api.ts @@ -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("/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) diff --git a/src/components/dashboard/RevenueTrendCard.tsx b/src/components/dashboard/RevenueTrendCard.tsx index beb9c03..35c4a1e 100644 --- a/src/components/dashboard/RevenueTrendCard.tsx +++ b/src/components/dashboard/RevenueTrendCard.tsx @@ -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() {
- Revenue Trend +
+ Revenue Trend + +
- ETB {totalRevenue.toLocaleString()} + ETB {totalRevenue.toLocaleString()}
Monthly · {year} (ETB)
@@ -89,40 +93,42 @@ export function RevenueTrendCard() {
) : ( - - - - - - { - 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)", - }} - /> - - {chartData.map((entry) => ( - - ))} - - - {chartData.map((entry) => ( - - ))} - - - + + + + + + + { + 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)", + }} + /> + + {chartData.map((entry) => ( + + ))} + + + {chartData.map((entry) => ( + + ))} + + + + )} diff --git a/src/components/dashboard/StatCard.tsx b/src/components/dashboard/StatCard.tsx index 62a6cbc..2b68f72 100644 --- a/src/components/dashboard/StatCard.tsx +++ b/src/components/dashboard/StatCard.tsx @@ -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 }) { diff --git a/src/components/ui/dialog.tsx b/src/components/ui/dialog.tsx index 7eb994d..72da8d4 100644 --- a/src/components/ui/dialog.tsx +++ b/src/components/ui/dialog.tsx @@ -38,8 +38,8 @@ const DialogContent = React.forwardRef< {...props} > {children} - - + + Close @@ -53,7 +53,7 @@ const DialogHeader = ({ }: React.HTMLAttributes) => (
void +} + +const SensitiveRevealContext = createContext(null) + +export function SensitiveRevealProvider({ children }: { children: ReactNode }) { + const [revealed, setRevealed] = useState(false) + const toggle = useCallback(() => setRevealed((v) => !v), []) + + return ( + + {children} + + ) +} + +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 ( + + ) +} + +export function SensitiveValue({ + children, + className, + showToggle = true, +}: { + children: ReactNode + className?: string + showToggle?: boolean +}) { + const { revealed } = useSensitiveReveal() + + return ( + + + {children} + + {showToggle ? : null} + + ) +} + +export function SensitiveChart({ + children, + className, +}: { + children: ReactNode + className?: string +}) { + const { revealed, toggle } = useSensitiveReveal() + + return ( +
+
+ {children} +
+ {!revealed ? ( + + ) : null} +
+ ) +} diff --git a/src/lib/activityLogDisplay.ts b/src/lib/activityLogDisplay.ts index 957183b..652ff74 100644 --- a/src/lib/activityLogDisplay.ts +++ b/src/lib/activityLogDisplay.ts @@ -50,6 +50,9 @@ const ACTION_LABELS: Record = { 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 = { 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", diff --git a/src/lib/subscriptionAdminPermissions.ts b/src/lib/subscriptionAdminPermissions.ts new file mode 100644 index 0000000..60e1930 --- /dev/null +++ b/src/lib/subscriptionAdminPermissions.ts @@ -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 = { + 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() +} diff --git a/src/lib/typeToConfirm.tsx b/src/lib/typeToConfirm.tsx new file mode 100644 index 0000000..342ea56 --- /dev/null +++ b/src/lib/typeToConfirm.tsx @@ -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 ( +
+ + 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`} + /> +
+ ) +} + +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 +} + +/** 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 ( + !confirming && onOpenChange(next)}> + + + {title} + {description ? ( + + {description} + + ) : null} + + + + + + + + + + + ) +} diff --git a/src/pages/DashboardPage.tsx b/src/pages/DashboardPage.tsx index 4d3a515..eb76571 100644 --- a/src/pages/DashboardPage.tsx +++ b/src/pages/DashboardPage.tsx @@ -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 ( +
Dashboard
@@ -252,7 +254,11 @@ export function DashboardPage() { + {dashboard.payments.total_revenue.toLocaleString()} + + } deltaLabel={`${dashboard.payments.total_payments} payments`} deltaPositive={dashboard.payments.total_revenue > 0} /> @@ -596,5 +602,6 @@ export function DashboardPage() { )}
+ ) } diff --git a/src/pages/analytics/AnalyticsPage.tsx b/src/pages/analytics/AnalyticsPage.tsx index b178494..215f895 100644 --- a/src/pages/analytics/AnalyticsPage.tsx +++ b/src/pages/analytics/AnalyticsPage.tsx @@ -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 ( +
{/* Header */}
@@ -521,8 +528,19 @@ export function AnalyticsPage() { + {`ETB ${formatNumber(payments.total_revenue)}`} + + } + sub={ + <> + {payments.successful_payments}/{payments.total_payments} successful · Avg{" "} + + ETB {payments.avg_transaction_value.toLocaleString()} + + + } trend={payments.total_revenue > 0 ? "up" : "neutral"} />
- Revenue +
+ Revenue + +
- ETB {payments.total_revenue.toLocaleString()} + + ETB {payments.total_revenue.toLocaleString()} +
Daily revenue over last 30 days
@@ -794,23 +817,25 @@ export function AnalyticsPage() {
- - - - - - [`ETB ${Number(v).toLocaleString()}`, "Revenue"]} - contentStyle={{ - borderRadius: 12, - border: "1px solid #E0E0E0", - boxShadow: "0 10px 30px rgba(0,0,0,0.08)", - fontSize: 12, - }} - /> - - - + + + + + + + [`ETB ${Number(v).toLocaleString()}`, "Revenue"]} + contentStyle={{ + borderRadius: 12, + border: "1px solid #E0E0E0", + boxShadow: "0 10px 30px rgba(0,0,0,0.08)", + fontSize: 12, + }} + /> + + + +
@@ -1062,5 +1087,6 @@ export function AnalyticsPage() {
+
) } diff --git a/src/pages/user-management/UserDetailPage.tsx b/src/pages/user-management/UserDetailPage.tsx index 556dee0..fbf36a7 100644 --- a/src/pages/user-management/UserDetailPage.tsx +++ b/src/pages/user-management/UserDetailPage.tsx @@ -137,16 +137,17 @@ function LoadingSkeleton() { return (
-
+
-
+
+
); } @@ -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() {
-
-
+
+
@@ -407,7 +411,7 @@ export function UserDetailPage() { -
+
@@ -440,12 +444,6 @@ export function UserDetailPage() { /> - -
@@ -459,7 +457,7 @@ export function UserDetailPage() {
-
+
@@ -552,6 +550,16 @@ export function UserDetailPage() {
+ void refreshSubscriptions()} + /> + {confirmDialog && (
diff --git a/src/pages/user-management/components/CancelSubscriptionDialog.tsx b/src/pages/user-management/components/CancelSubscriptionDialog.tsx new file mode 100644 index 0000000..1808237 --- /dev/null +++ b/src/pages/user-management/components/CancelSubscriptionDialog.tsx @@ -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 ( + { + if (cancelling) return + if (!next) onOpenChange(false) + }} + title="Are you sure?" + description={ + subscription ? ( + <> + Cancel subscription #{subscription.id} ( + {subscription.plan_name}) for this learner? They will lose access for{" "} + {formatPlanCategory(subscription.plan_category)} 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} + /> + ) +} diff --git a/src/pages/user-management/components/ExtendSubscriptionDialog.tsx b/src/pages/user-management/components/ExtendSubscriptionDialog.tsx new file mode 100644 index 0000000..94d0e7d --- /dev/null +++ b/src/pages/user-management/components/ExtendSubscriptionDialog.tsx @@ -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 ( + { + if (saving) return + if (!next) onOpenChange(false) + }} + title="Are you sure?" + description={ + subscription ? ( + <> + Extend {subscription.plan_name} (# + {subscription.id}) by one plan period? Current expiry:{" "} + {formatDateTime(subscription.expires_at)} + {subscription.plan_category + ? ` · ${formatPlanCategory(subscription.plan_category)}` + : ""} + . + + ) : ( + "Extend this subscription by one plan period?" + ) + } + confirmWord={CONFIRM_WORD} + confirmLabel="Extend subscription" + confirming={saving} + onConfirm={handleConfirmExtend} + /> + ) +} diff --git a/src/pages/user-management/components/GrantSubscriptionDialog.tsx b/src/pages/user-management/components/GrantSubscriptionDialog.tsx new file mode 100644 index 0000000..1042ed1 --- /dev/null +++ b/src/pages/user-management/components/GrantSubscriptionDialog.tsx @@ -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 + 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([]) + 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(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 ( + <> + { + if (saving) return + if (!next) { + setConfirmOpen(false) + onOpenChange(false) + } + }} + > + +
+ + + + Mark as paid + + + Grant plan access + {userName ? ` to ${userName}` : ""}. A payment is recorded at the + plan price. + + + +
+
+ + {plansLoading ? ( +
+ + Loading plans… +
+ ) : ( +
+ + + {planMenuOpen ? ( +
+
+ + setPlanSearch(e.target.value)} + placeholder="Search plans…" + className="h-9 rounded-lg border-grayScale-200 pl-8 text-sm" + autoFocus + /> +
+
+ {filteredPlans.map((plan) => { + const blocked = activeByCategory[plan.category] === true + const selected = String(plan.id) === planId + return ( + + ) + })} + {filteredPlans.length === 0 ? ( +

+ No plans found +

+ ) : null} +
+
+ ) : null} +
+ )} + {selectedPlan && categoryBlocked ? ( +

+ An active {formatPlanCategory(selectedPlan.category)} subscription already + exists. Extend or cancel it instead. +

+ ) : selectedPlan ? ( +

+ Payment recorded: {formatPlanPrice(selectedPlan)}. +

+ ) : null} +
+ + {formError ?

{formError}

: null} +
+ + + + + +
+
+
+ + + Grant {selectedPlan.name} ( + {formatPlanCategory(selectedPlan.category)}) + {userName ? ( + <> + {" "} + to {userName} + + ) : ( + " to this learner" + )} + ? A payment of {formatPlanPrice(selectedPlan)} will be + recorded. + + ) : ( + "Grant this subscription?" + ) + } + confirmWord={CONFIRM_WORD} + confirmLabel="Mark as paid" + confirming={saving} + onConfirm={handleConfirmGrant} + /> + + ) +} diff --git a/src/pages/user-management/components/UserSubscriptionsSection.tsx b/src/pages/user-management/components/UserSubscriptionsSection.tsx index 4fda5e0..b6ce2fb 100644 --- a/src/pages/user-management/components/UserSubscriptionsSection.tsx +++ b/src/pages/user-management/components/UserSubscriptionsSection.tsx @@ -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 ( + + + {label} + + ) +} + +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 ( +
+
+

Subscription

+ +
+ +
+
+
+

Current Plan

+

+ {formatPlanTitle(subscription)} +

+

+ {formatPlanCategory(subscription.plan_category)} +

+
+
+

Expires On

+
+

+ {formatExpiryDate(subscription.expires_at)} +

+ {daysLeft != null ? ( + + {formatDaysLeftLabel(daysLeft)} + + ) : null} +
+
+
+
+ +
+ {canExtend ? ( + + ) : null} + + {(canGrant || canCancel) && ( +
+ {canGrant ? ( + + ) : null} + {canCancel ? ( + + ) : null} +
+ )} +
+
+ ) +} + +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 ( +
+
+

Subscription

+ +
+
+

No active subscription for this learner.

+
+
+ {canExtend ? ( + + ) : null} + {(canGrant || canCancel) && ( +
+ {canGrant ? ( + + ) : null} + {canCancel ? ( + + ) : null} +
+ )} +
+
+ ) } 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(null) + const [cancelTarget, setCancelTarget] = useState(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 ( - - - - - {open ? ( - + <> +
{loading ? ( -
- - Loading subscriptions... -
+ + + + Loading subscription… + + ) : null} - {error ?

{error}

: null} + {error ? ( + + {error} + + ) : null} {!loading && !error && subscriptions ? ( <> -
- Overall status - - {formatStatusLabel(subscriptions.display_status)} - -
+ {activePlans.length > 0 ? ( +
+ {activePlans.map((subscription) => ( + setExtendTarget(subscription)} + onGrant={() => setGrantOpen(true)} + onCancel={() => setCancelTarget(subscription)} + /> + ))} +
+ ) : ( + setGrantOpen(true)} + /> + )} -
- Active subscription - - {subscriptions.has_active_subscription ? "Yes" : "No"} - -
- - {Object.keys(subscriptions.active_by_category).length > 0 ? ( - <> - -
-

- Access by category -

-
- {Object.entries(subscriptions.active_by_category).map(([category, active]) => ( - - {formatCategoryLabel(category)} - - ))} -
-
- - ) : null} - - - -
-

- Active plans -

- {subscriptions.active_subscriptions.length === 0 ? ( -

No active subscriptions.

- ) : ( -
- {subscriptions.active_subscriptions.map((subscription) => ( -
-
-
-

{subscription.plan_name}

-

- {formatCategoryLabel(subscription.plan_category)} -

+ {(history.length > 0 || recentPayments.length > 0) && ( + + + {detailsOpen ? ( + + {Object.keys(subscriptions.active_by_category).length > 0 ? ( +
+

+ Access by category +

+
+ {Object.entries(subscriptions.active_by_category).map( + ([category, active]) => ( + + {formatPlanCategory(category)} {active ? "✓" : "✗"} + + ), + )}
- - {formatStatusLabel(subscription.status)} -
-
-

- Price: - {formatMoney(subscription.price, subscription.currency)} -

-

- Duration: - {formatDuration(subscription.duration_value, subscription.duration_unit)} -

-

- Starts: - {formatDateTime(subscription.starts_at)} -

-

- Expires: - {formatDateTime(subscription.expires_at)} -

-

- Payment: - {displayValue(subscription.payment_method)} -

-

- - Auto-renew: {subscription.auto_renew ? "On" : "Off"} -

-
-
- ))} -
- )} -
+ ) : null} - {recentPayments.length > 0 ? ( - <> - -
-

- Recent payments -

-
- - - - Plan - Amount - Status - Method - Date - - - - {recentPayments.map((payment) => ( - - - {displayValue(payment.plan_name)} - - - {formatMoney(payment.amount, payment.currency)} - - - - {formatStatusLabel(payment.status)} - - - - {displayValue(payment.payment_method)} - - - {formatDateTime(payment.paid_at || payment.created_at)} - - + {history.length > 0 ? ( +
+

+ Past subscriptions +

+ {history.map((subscription) => ( +
+
+

+ #{subscription.id} · {formatPlanTitle(subscription)} +

+

+ {formatPlanCategory(subscription.plan_category)} ·{" "} + {formatExpiryDate(subscription.expires_at)} +

+
+
+ + {canExtend ? ( + + ) : null} + {canCancel ? ( + + ) : null} +
+
))} - -
-
-
- - ) : null} +
+ ) : null} + + {recentPayments.length > 0 ? ( +
+

+ Recent payments +

+
+ + + + Plan + Amount + Status + Method + Date + + + + {recentPayments.map((payment) => ( + + + {displayValue(payment.plan_name)} + + + {formatMoney(payment.amount, payment.currency)} + + + {formatStatusLabel(payment.status)} + + + {formatAdminPaymentMethod(payment.payment_method)} + + + {formatDateTime(payment.paid_at || payment.created_at)} + + + ))} + +
+
+
+ ) : null} + + ) : null} + + )} ) : null} {!loading && !error && !subscriptions ? ( -

No subscription data available.

+ + + No subscription data available. + + ) : null} - - ) : null} - - ); +
+ + + + { + if (!next) setExtendTarget(null) + }} + userId={userId} + subscription={extendTarget} + onExtended={onRefresh} + /> + + { + if (!next) setCancelTarget(null) + }} + subscription={cancelTarget} + onCancelled={onRefresh} + /> + + ) } diff --git a/src/types/adminSubscription.types.ts b/src/types/adminSubscription.types.ts new file mode 100644 index 0000000..3636c59 --- /dev/null +++ b/src/types/adminSubscription.types.ts @@ -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 +}