From 042df899e1697d95248b4851142df09d51e876c7 Mon Sep 17 00:00:00 2001 From: Yared Yemane Date: Fri, 10 Jul 2026 04:59:00 -0700 Subject: [PATCH 1/5] 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 --- src/api/admin-subscriptions.api.ts | 74 ++ src/api/subscription-plans.api.ts | 13 +- src/components/dashboard/RevenueTrendCard.tsx | 78 +- src/components/dashboard/StatCard.tsx | 3 +- src/components/ui/dialog.tsx | 6 +- src/components/ui/sensitive-value.tsx | 126 +++ src/lib/activityLogDisplay.ts | 5 + src/lib/subscriptionAdminPermissions.ts | 44 + src/lib/typeToConfirm.tsx | 146 ++++ src/pages/DashboardPage.tsx | 9 +- src/pages/analytics/AnalyticsPage.tsx | 76 +- src/pages/user-management/UserDetailPage.tsx | 66 +- .../components/CancelSubscriptionDialog.tsx | 73 ++ .../components/ExtendSubscriptionDialog.tsx | 99 +++ .../components/GrantSubscriptionDialog.tsx | 336 ++++++++ .../components/UserSubscriptionsSection.tsx | 800 +++++++++++++----- src/types/adminSubscription.types.ts | 35 + 17 files changed, 1661 insertions(+), 328 deletions(-) create mode 100644 src/api/admin-subscriptions.api.ts create mode 100644 src/components/ui/sensitive-value.tsx create mode 100644 src/lib/subscriptionAdminPermissions.ts create mode 100644 src/lib/typeToConfirm.tsx create mode 100644 src/pages/user-management/components/CancelSubscriptionDialog.tsx create mode 100644 src/pages/user-management/components/ExtendSubscriptionDialog.tsx create mode 100644 src/pages/user-management/components/GrantSubscriptionDialog.tsx create mode 100644 src/types/adminSubscription.types.ts 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 +} From f6ad0d3cb5ec17c75cae94cdaa294bd01e6602a2 Mon Sep 17 00:00:00 2001 From: Yared Yemane Date: Fri, 10 Jul 2026 05:06:43 -0700 Subject: [PATCH 2/5] Move subscriptions into the user detail sidebar column. Tighten subscription action button layout so the card fits the narrower column. Co-authored-by: Cursor --- src/pages/user-management/UserDetailPage.tsx | 21 ++++++------ .../components/UserSubscriptionsSection.tsx | 32 +++++++------------ 2 files changed, 21 insertions(+), 32 deletions(-) diff --git a/src/pages/user-management/UserDetailPage.tsx b/src/pages/user-management/UserDetailPage.tsx index fbf36a7..444a350 100644 --- a/src/pages/user-management/UserDetailPage.tsx +++ b/src/pages/user-management/UserDetailPage.tsx @@ -147,7 +147,6 @@ function LoadingSkeleton() {
-
); } @@ -444,6 +443,16 @@ export function UserDetailPage() { />
+ + void refreshSubscriptions()} + />
@@ -550,16 +559,6 @@ export function UserDetailPage() {
- void refreshSubscriptions()} - /> - {confirmDialog && (
diff --git a/src/pages/user-management/components/UserSubscriptionsSection.tsx b/src/pages/user-management/components/UserSubscriptionsSection.tsx index b6ce2fb..14b1a51 100644 --- a/src/pages/user-management/components/UserSubscriptionsSection.tsx +++ b/src/pages/user-management/components/UserSubscriptionsSection.tsx @@ -189,11 +189,11 @@ function SubscriptionManageCard({
-
+
{canExtend ? (
-
+
{canExtend ? ( ) : null} {(canGrant || canCancel) && ( -
+
{canGrant ? (
) : ( - /* Form state */ <> - {/* Header */}

Account Recovery @@ -90,7 +106,7 @@ export function ForgotPasswordPage() { Forgot password?

- No worries — enter your email and we'll send you a reset link. + Enter your team email and we'll send you a reset link.

@@ -107,23 +123,41 @@ export function ForgotPasswordPage() { type="email" placeholder="you@example.com" value={email} - onChange={(e) => setEmail(e.target.value)} + onChange={(e) => { + setEmail(e.target.value) + if (error) setError(null) + }} required + autoComplete="email" + disabled={submitting} className="h-11 rounded-xl" />
+ {error ? ( +

+ {error} +

+ ) : null} + )} - {/* Footer */}

© {new Date().getFullYear()} Yimaru Academy · All rights reserved

diff --git a/src/pages/auth/LoginPage.tsx b/src/pages/auth/LoginPage.tsx index 5e9fc34..dc02fc6 100644 --- a/src/pages/auth/LoginPage.tsx +++ b/src/pages/auth/LoginPage.tsx @@ -78,6 +78,14 @@ export function LoginPage() { setSearchParams({}, { replace: true }); }, [searchParams, setSearchParams]); + useEffect(() => { + if (searchParams.get("reset") !== "1") return; + toast.success("Password reset", { + description: "Sign in with your new password.", + }); + setSearchParams({}, { replace: true }); + }, [searchParams, setSearchParams]); + useEffect(() => { if (searchParams.get("account_inactive") !== "1") return; toast.error("Account inactive", { diff --git a/src/pages/auth/ResetPasswordPage.tsx b/src/pages/auth/ResetPasswordPage.tsx new file mode 100644 index 0000000..9d3fbd8 --- /dev/null +++ b/src/pages/auth/ResetPasswordPage.tsx @@ -0,0 +1,255 @@ +import { useMemo, useState } from "react" +import { Link, useNavigate, useSearchParams } from "react-router-dom" +import { ArrowLeft, Eye, EyeOff } from "lucide-react" +import { toast } from "sonner" +import { resetTeamPassword } from "../../api/team.api" +import { BrandLogo } from "../../components/brand/BrandLogo" +import { Button } from "../../components/ui/button" +import { Input } from "../../components/ui/input" +import { SpinnerIcon } from "../../components/ui/spinner-icon" +import { mapTeamPasswordResetError } from "../../lib/teamPasswordReset" + +export function ResetPasswordPage() { + const navigate = useNavigate() + const [searchParams] = useSearchParams() + + const emailFromQuery = searchParams.get("email")?.trim() ?? "" + const otpFromQuery = searchParams.get("otp")?.trim() ?? "" + + const [email, setEmail] = useState(emailFromQuery) + const [otp, setOtp] = useState(otpFromQuery) + const [password, setPassword] = useState("") + const [confirmPassword, setConfirmPassword] = useState("") + const [showPassword, setShowPassword] = useState(false) + const [submitting, setSubmitting] = useState(false) + const [error, setError] = useState(null) + + const hasLinkParams = Boolean(emailFromQuery && otpFromQuery) + const emailLocked = Boolean(emailFromQuery) + const otpLocked = Boolean(otpFromQuery) + + const canSubmit = useMemo(() => { + return email.trim().length > 0 && otp.trim().length > 0 && password.length >= 8 + }, [email, otp, password]) + + const handleSubmit = async (e: React.FormEvent) => { + e.preventDefault() + setError(null) + + if (!email.trim() || !otp.trim()) { + setError("Email and reset code are required. Open the link from your email or request a new one.") + return + } + if (password.length < 8) { + setError("Password must be at least 8 characters.") + return + } + if (password !== confirmPassword) { + setError("Passwords do not match.") + return + } + + setSubmitting(true) + try { + await resetTeamPassword({ + email: email.trim(), + otp: otp.trim(), + password, + }) + toast.success("Password reset successfully", { + description: "Sign in with your new password.", + }) + navigate("/login?reset=1", { replace: true }) + } catch (err) { + setError(mapTeamPasswordResetError(err)) + } finally { + setSubmitting(false) + } + } + + return ( +
+
+
+
+
+
+
+
+ +

+ Choose a strong password to secure your admin account. +

+
+
+ +
+
+
+ +
+ + + + Back to sign in + + +
+

+ Account Recovery +

+

+ Reset password +

+

+ {hasLinkParams + ? "Set a new password for your team account. This link expires in 5 minutes." + : "Enter the email and code from your reset email, then choose a new password."} +

+
+ + {!hasLinkParams ? ( +
+ Missing reset link details. You can enter them manually, or{" "} + + request a new link + + . +
+ ) : null} + +
+
+ + setEmail(e.target.value)} + readOnly={emailLocked} + required + autoComplete="email" + disabled={submitting} + className="h-11 rounded-xl" + /> +
+ +
+ + setOtp(e.target.value)} + readOnly={otpLocked} + required + autoComplete="one-time-code" + disabled={submitting} + className="h-11 rounded-xl" + /> +
+ +
+ +
+ setPassword(e.target.value)} + required + minLength={8} + autoComplete="new-password" + disabled={submitting} + className="h-11 rounded-xl pr-11" + /> + +
+

At least 8 characters

+
+ +
+ + setConfirmPassword(e.target.value)} + required + minLength={8} + autoComplete="new-password" + disabled={submitting} + className="h-11 rounded-xl" + /> +
+ + {error ? ( +
+

{error}

+ {(error.toLowerCase().includes("expired") || + error.toLowerCase().includes("already used") || + error.toLowerCase().includes("invalid reset")) && ( + + Request a new reset link + + )} +
+ ) : null} + + +
+ +

+ © {new Date().getFullYear()} Yimaru Academy · All rights reserved +

+
+
+
+ ) +} diff --git a/src/types/team.types.ts b/src/types/team.types.ts index 70150fb..ef6dbf0 100644 --- a/src/types/team.types.ts +++ b/src/types/team.types.ts @@ -139,3 +139,21 @@ export interface ChangeTeamMemberPasswordResponse { status_code?: number metadata?: unknown } + +/** POST /team/sendResetCode — public forgot-password */ +export interface TeamSendPasswordResetRequest { + email: string +} + +/** POST /team/resetPassword — public complete reset from email link */ +export interface TeamResetPasswordRequest { + email: string + otp: string + password: string +} + +export interface TeamPasswordResetResponse { + message?: string + success?: boolean + data?: unknown +} From a880f06b143188e0548021a53d32f1ce43803c9e Mon Sep 17 00:00:00 2001 From: Yared Yemane Date: Fri, 10 Jul 2026 06:38:50 -0700 Subject: [PATCH 5/5] Verify team reset links before showing the password form. Call GET /team/verifyResetCode on load and surface used, expired, or invalid link states with a path to request a new link. Co-authored-by: Cursor --- src/api/http.ts | 1 + src/api/team.api.ts | 19 ++ src/lib/teamPasswordReset.ts | 31 +++ src/pages/auth/ResetPasswordPage.tsx | 345 ++++++++++++++++----------- src/types/team.types.ts | 18 ++ 5 files changed, 281 insertions(+), 133 deletions(-) diff --git a/src/api/http.ts b/src/api/http.ts index b9f7ee6..cb07deb 100644 --- a/src/api/http.ts +++ b/src/api/http.ts @@ -69,6 +69,7 @@ const isAuthEndpointRequest = (url?: string) => { url.includes("/team/invitations/verify") || url.includes("/team/invitations/accept") || url.includes("/team/sendResetCode") || + url.includes("/team/verifyResetCode") || url.includes("/team/resetPassword") ); }; diff --git a/src/api/team.api.ts b/src/api/team.api.ts index 9afe06a..f6a218c 100644 --- a/src/api/team.api.ts +++ b/src/api/team.api.ts @@ -21,6 +21,8 @@ import type { TeamResetPasswordRequest, TeamPasswordResetResponse, TeamSendPasswordResetRequest, + TeamVerifyPasswordResetData, + TeamVerifyPasswordResetResponse, } from "../types/team.types" function isRecord(value: unknown): value is Record { @@ -162,6 +164,23 @@ export const sendTeamPasswordReset = (data: TeamSendPasswordResetRequest) => skipErrorToast: true, }) +/** GET /team/verifyResetCode — public; validates email+otp without consuming. */ +export const verifyTeamPasswordReset = (email: string, otp: string) => + http.get("/team/verifyResetCode", { + params: { email, otp }, + skipErrorToast: true, + }) + +export function parseVerifyPasswordReset( + response: Awaited>, +): TeamVerifyPasswordResetData | null { + const body = response.data + if (body?.data && typeof body.data === "object" && "valid" in body.data) { + return body.data + } + return null +} + /** POST /team/resetPassword — public; completes reset with email + OTP from the link. */ export const resetTeamPassword = (data: TeamResetPasswordRequest) => http.post("/team/resetPassword", data, { diff --git a/src/lib/teamPasswordReset.ts b/src/lib/teamPasswordReset.ts index 742ae36..d6ae1c0 100644 --- a/src/lib/teamPasswordReset.ts +++ b/src/lib/teamPasswordReset.ts @@ -1,4 +1,5 @@ import axios from "axios" +import type { TeamVerifyPasswordResetData } from "../types/team.types" /** Prefer API `error` detail over generic `message` for auth recovery flows. */ export function getTeamAuthErrorMessage(error: unknown, fallback: string): string { @@ -45,3 +46,33 @@ export function mapTeamPasswordResetError(error: unknown): string { if (detail) return detail return "Something went wrong. Please try again." } + +export function getInvalidResetLinkTitle( + data: TeamVerifyPasswordResetData | null, +): string { + switch (data?.reason) { + case "used": + return "This reset link was already used" + case "expired": + return "This reset link has expired" + case "missing": + return "Reset link is incomplete" + default: + return "This reset link is invalid" + } +} + +export function getInvalidResetLinkDescription( + data: TeamVerifyPasswordResetData | null, +): string { + switch (data?.reason) { + case "used": + return "Each reset link can only be used once. Request a new link to set a new password." + case "expired": + return "Reset links are valid for 5 minutes. Request a new one to continue." + case "missing": + return "Open the full link from your email, or request a new reset link." + default: + return "The link may be expired, invalid, or already used. Request a new one from Forgot password." + } +} diff --git a/src/pages/auth/ResetPasswordPage.tsx b/src/pages/auth/ResetPasswordPage.tsx index 9d3fbd8..1ea0bac 100644 --- a/src/pages/auth/ResetPasswordPage.tsx +++ b/src/pages/auth/ResetPasswordPage.tsx @@ -1,13 +1,21 @@ -import { useMemo, useState } from "react" +import { useCallback, useEffect, useMemo, useState } from "react" import { Link, useNavigate, useSearchParams } from "react-router-dom" -import { ArrowLeft, Eye, EyeOff } from "lucide-react" +import { AlertCircle, ArrowLeft, Eye, EyeOff } from "lucide-react" import { toast } from "sonner" -import { resetTeamPassword } from "../../api/team.api" +import { + parseVerifyPasswordReset, + resetTeamPassword, + verifyTeamPasswordReset, +} from "../../api/team.api" import { BrandLogo } from "../../components/brand/BrandLogo" import { Button } from "../../components/ui/button" import { Input } from "../../components/ui/input" import { SpinnerIcon } from "../../components/ui/spinner-icon" -import { mapTeamPasswordResetError } from "../../lib/teamPasswordReset" +import { + getInvalidResetLinkDescription, + getInvalidResetLinkTitle, + mapTeamPasswordResetError, +} from "../../lib/teamPasswordReset" export function ResetPasswordPage() { const navigate = useNavigate() @@ -15,6 +23,13 @@ export function ResetPasswordPage() { const emailFromQuery = searchParams.get("email")?.trim() ?? "" const otpFromQuery = searchParams.get("otp")?.trim() ?? "" + const hasLinkParams = Boolean(emailFromQuery && otpFromQuery) + + const [verifyState, setVerifyState] = useState<"loading" | "invalid" | "ready">( + hasLinkParams ? "loading" : "ready", + ) + const [invalidTitle, setInvalidTitle] = useState("") + const [invalidDescription, setInvalidDescription] = useState("") const [email, setEmail] = useState(emailFromQuery) const [otp, setOtp] = useState(otpFromQuery) @@ -24,10 +39,41 @@ export function ResetPasswordPage() { const [submitting, setSubmitting] = useState(false) const [error, setError] = useState(null) - const hasLinkParams = Boolean(emailFromQuery && otpFromQuery) const emailLocked = Boolean(emailFromQuery) const otpLocked = Boolean(otpFromQuery) + const loadVerification = useCallback(async () => { + if (!hasLinkParams) { + setVerifyState("ready") + return + } + + setVerifyState("loading") + try { + const res = await verifyTeamPasswordReset(emailFromQuery, otpFromQuery) + const data = parseVerifyPasswordReset(res) + + if (!data || data.valid !== true) { + setInvalidTitle(getInvalidResetLinkTitle(data)) + setInvalidDescription(getInvalidResetLinkDescription(data)) + setVerifyState("invalid") + return + } + + setVerifyState("ready") + } catch { + setInvalidTitle("This reset link is invalid") + setInvalidDescription( + "The link may be expired, invalid, or already used. Request a new one from Forgot password.", + ) + setVerifyState("invalid") + } + }, [emailFromQuery, hasLinkParams, otpFromQuery]) + + useEffect(() => { + void loadVerification() + }, [loadVerification]) + const canSubmit = useMemo(() => { return email.trim().length > 0 && otp.trim().length > 0 && password.length >= 8 }, [email, otp, password]) @@ -102,148 +148,181 @@ export function ResetPasswordPage() { Account Recovery

- Reset password + {verifyState === "invalid" ? invalidTitle : "Reset password"}

- {hasLinkParams - ? "Set a new password for your team account. This link expires in 5 minutes." - : "Enter the email and code from your reset email, then choose a new password."} + {verifyState === "loading" + ? "Checking your reset link…" + : verifyState === "invalid" + ? invalidDescription + : hasLinkParams + ? "Set a new password for your team account. This link expires in 5 minutes." + : "Enter the email and code from your reset email, then choose a new password."}

- {!hasLinkParams ? ( -
- Missing reset link details. You can enter them manually, or{" "} - - request a new link - - . + {verifyState === "loading" ? ( +
+ +

Verifying reset link…

) : null} -
-
- - setEmail(e.target.value)} - readOnly={emailLocked} - required - autoComplete="email" - disabled={submitting} - className="h-11 rounded-xl" - /> -
- -
- - setOtp(e.target.value)} - readOnly={otpLocked} - required - autoComplete="one-time-code" - disabled={submitting} - className="h-11 rounded-xl" - /> -
- -
- -
- setPassword(e.target.value)} - required - minLength={8} - autoComplete="new-password" - disabled={submitting} - className="h-11 rounded-xl pr-11" - /> - + {verifyState === "invalid" ? ( +
+
+ +
+

{invalidTitle}

+

{invalidDescription}

+
-

At least 8 characters

-
- -
- - setConfirmPassword(e.target.value)} - required - minLength={8} - autoComplete="new-password" - disabled={submitting} - className="h-11 rounded-xl" - /> + Request a new reset link +
+ ) : null} - {error ? ( -
-

{error}

- {(error.toLowerCase().includes("expired") || - error.toLowerCase().includes("already used") || - error.toLowerCase().includes("invalid reset")) && ( - - Request a new reset link + {verifyState === "ready" ? ( + <> + {!hasLinkParams ? ( +
+ Missing reset link details. You can enter them manually, or{" "} + + request a new link - )} -
- ) : null} + . +
+ ) : null} - - +
+
+ + setEmail(e.target.value)} + readOnly={emailLocked} + required + autoComplete="email" + disabled={submitting} + className="h-11 rounded-xl" + /> +
+ +
+ + setOtp(e.target.value)} + readOnly={otpLocked} + required + autoComplete="one-time-code" + disabled={submitting} + className="h-11 rounded-xl" + /> +
+ +
+ +
+ setPassword(e.target.value)} + required + minLength={8} + autoComplete="new-password" + disabled={submitting} + className="h-11 rounded-xl pr-11" + /> + +
+

At least 8 characters

+
+ +
+ + setConfirmPassword(e.target.value)} + required + minLength={8} + autoComplete="new-password" + disabled={submitting} + className="h-11 rounded-xl" + /> +
+ + {error ? ( +
+

{error}

+ {(error.toLowerCase().includes("expired") || + error.toLowerCase().includes("already used") || + error.toLowerCase().includes("invalid reset")) && ( + + Request a new reset link + + )} +
+ ) : null} + + +
+ + ) : null}

© {new Date().getFullYear()} Yimaru Academy · All rights reserved diff --git a/src/types/team.types.ts b/src/types/team.types.ts index ef6dbf0..d9113a6 100644 --- a/src/types/team.types.ts +++ b/src/types/team.types.ts @@ -157,3 +157,21 @@ export interface TeamPasswordResetResponse { success?: boolean data?: unknown } + +/** GET /team/verifyResetCode — public; checks link without consuming OTP */ +export type TeamVerifyPasswordResetReason = + | "missing" + | "invalid" + | "used" + | "expired" + +export interface TeamVerifyPasswordResetData { + valid: boolean + reason?: TeamVerifyPasswordResetReason | string +} + +export interface TeamVerifyPasswordResetResponse { + message?: string + success?: boolean + data?: TeamVerifyPasswordResetData +}