Merge branch 'production' of https://gitea.yaltopia.com/Yimaru/Yimaru-Admin into el-ui
This commit is contained in:
commit
99f14a1789
74
src/api/admin-subscriptions.api.ts
Normal file
74
src/api/admin-subscriptions.api.ts
Normal file
|
|
@ -0,0 +1,74 @@
|
||||||
|
import http from "./http"
|
||||||
|
import type {
|
||||||
|
AdminApplySubscriptionBody,
|
||||||
|
AdminSubscriptionMutationResponse,
|
||||||
|
AdminSubscriptionRes,
|
||||||
|
} from "../types/adminSubscription.types"
|
||||||
|
|
||||||
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||||
|
return value !== null && typeof value === "object" && !Array.isArray(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeSubscriptionRes(raw: unknown): AdminSubscriptionRes | null {
|
||||||
|
if (!isRecord(raw)) return null
|
||||||
|
const id = Number(raw.id)
|
||||||
|
const userId = Number(raw.user_id)
|
||||||
|
const planId = Number(raw.plan_id)
|
||||||
|
if (!Number.isFinite(id) || !Number.isFinite(userId) || !Number.isFinite(planId)) return null
|
||||||
|
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
user_id: userId,
|
||||||
|
plan_id: planId,
|
||||||
|
plan_name: raw.plan_name != null ? String(raw.plan_name) : undefined,
|
||||||
|
starts_at: String(raw.starts_at ?? ""),
|
||||||
|
expires_at: String(raw.expires_at ?? ""),
|
||||||
|
status: String(raw.status ?? ""),
|
||||||
|
payment_reference:
|
||||||
|
raw.payment_reference != null ? String(raw.payment_reference) : undefined,
|
||||||
|
payment_method: raw.payment_method != null ? String(raw.payment_method) : undefined,
|
||||||
|
auto_renew: Boolean(raw.auto_renew),
|
||||||
|
duration_value:
|
||||||
|
raw.duration_value != null && Number.isFinite(Number(raw.duration_value))
|
||||||
|
? Number(raw.duration_value)
|
||||||
|
: undefined,
|
||||||
|
duration_unit: raw.duration_unit != null ? String(raw.duration_unit) : undefined,
|
||||||
|
price:
|
||||||
|
raw.price != null && Number.isFinite(Number(raw.price)) ? Number(raw.price) : undefined,
|
||||||
|
currency: raw.currency != null ? String(raw.currency) : undefined,
|
||||||
|
created_at: String(raw.created_at ?? ""),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function mutationResult(res: { data: unknown; status?: number }) {
|
||||||
|
const body = isRecord(res.data) ? res.data : null
|
||||||
|
const plan = normalizeSubscriptionRes(body?.data ?? body)
|
||||||
|
return {
|
||||||
|
...res,
|
||||||
|
data: plan,
|
||||||
|
message: body ? String(body.message ?? "") : undefined,
|
||||||
|
httpStatus: res.status,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* POST /admin/users/:user_id/subscriptions/extend
|
||||||
|
* Unified grant-or-extend: no active sub in plan category → grant (201);
|
||||||
|
* active in category → extend one period of selected plan (200).
|
||||||
|
*/
|
||||||
|
export const adminApplySubscription = (userId: number, body: AdminApplySubscriptionBody) =>
|
||||||
|
http
|
||||||
|
.post<AdminSubscriptionMutationResponse>(
|
||||||
|
`/admin/users/${userId}/subscriptions/extend`,
|
||||||
|
body,
|
||||||
|
)
|
||||||
|
.then(mutationResult)
|
||||||
|
|
||||||
|
/** @deprecated Use adminApplySubscription */
|
||||||
|
export const adminGrantSubscription = adminApplySubscription
|
||||||
|
|
||||||
|
/** POST /admin/subscriptions/:id/cancel — admin cancel (not learner self-cancel). */
|
||||||
|
export const adminCancelSubscription = (subscriptionId: number) =>
|
||||||
|
http
|
||||||
|
.post<AdminSubscriptionMutationResponse>(`/admin/subscriptions/${subscriptionId}/cancel`)
|
||||||
|
.then(mutationResult)
|
||||||
|
|
@ -67,7 +67,10 @@ const isAuthEndpointRequest = (url?: string) => {
|
||||||
url.includes("/team/google-login") ||
|
url.includes("/team/google-login") ||
|
||||||
url.includes("/team/refresh") ||
|
url.includes("/team/refresh") ||
|
||||||
url.includes("/team/invitations/verify") ||
|
url.includes("/team/invitations/verify") ||
|
||||||
url.includes("/team/invitations/accept")
|
url.includes("/team/invitations/accept") ||
|
||||||
|
url.includes("/team/sendResetCode") ||
|
||||||
|
url.includes("/team/verifyResetCode") ||
|
||||||
|
url.includes("/team/resetPassword")
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -50,14 +50,18 @@ export function parseSubscriptionPlanMutation(body: unknown): SubscriptionPlan |
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface GetSubscriptionPlansOptions {
|
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
|
active_only?: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
export const getSubscriptionPlans = (options?: GetSubscriptionPlansOptions) =>
|
export const getSubscriptionPlans = (options?: GetSubscriptionPlansOptions) => {
|
||||||
http
|
const activeOnly = options?.active_only ?? true
|
||||||
|
return http
|
||||||
.get<SubscriptionPlansListResponse | SubscriptionPlan[]>("/subscription-plans", {
|
.get<SubscriptionPlansListResponse | SubscriptionPlan[]>("/subscription-plans", {
|
||||||
params: { active_only: options?.active_only ?? false },
|
params: activeOnly ? undefined : { active_only: false },
|
||||||
})
|
})
|
||||||
.then((res) => {
|
.then((res) => {
|
||||||
const plans = parseSubscriptionPlansList(res.data)
|
const plans = parseSubscriptionPlansList(res.data)
|
||||||
|
|
@ -66,6 +70,7 @@ export const getSubscriptionPlans = (options?: GetSubscriptionPlansOptions) =>
|
||||||
data: plans,
|
data: plans,
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
}
|
||||||
|
|
||||||
function mutationResult(res: { data: unknown }) {
|
function mutationResult(res: { data: unknown }) {
|
||||||
const plan = parseSubscriptionPlanMutation(res.data)
|
const plan = parseSubscriptionPlanMutation(res.data)
|
||||||
|
|
|
||||||
|
|
@ -18,6 +18,11 @@ import type {
|
||||||
UpdateTeamMeRequest,
|
UpdateTeamMeRequest,
|
||||||
TeamMember,
|
TeamMember,
|
||||||
TeamMemberDetail,
|
TeamMemberDetail,
|
||||||
|
TeamResetPasswordRequest,
|
||||||
|
TeamPasswordResetResponse,
|
||||||
|
TeamSendPasswordResetRequest,
|
||||||
|
TeamVerifyPasswordResetData,
|
||||||
|
TeamVerifyPasswordResetResponse,
|
||||||
} from "../types/team.types"
|
} from "../types/team.types"
|
||||||
|
|
||||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||||
|
|
@ -153,6 +158,35 @@ export const updateTeamMember = (id: number, data: UpdateTeamMemberRequest) =>
|
||||||
export const changeTeamMemberPassword = (id: number, data: ChangeTeamMemberPasswordRequest) =>
|
export const changeTeamMemberPassword = (id: number, data: ChangeTeamMemberPasswordRequest) =>
|
||||||
http.post<ChangeTeamMemberPasswordResponse>(`/team/members/${id}/change-password`, data)
|
http.post<ChangeTeamMemberPasswordResponse>(`/team/members/${id}/change-password`, data)
|
||||||
|
|
||||||
|
/** POST /team/sendResetCode — public; emails a password-reset link. */
|
||||||
|
export const sendTeamPasswordReset = (data: TeamSendPasswordResetRequest) =>
|
||||||
|
http.post<TeamPasswordResetResponse>("/team/sendResetCode", data, {
|
||||||
|
skipErrorToast: true,
|
||||||
|
})
|
||||||
|
|
||||||
|
/** GET /team/verifyResetCode — public; validates email+otp without consuming. */
|
||||||
|
export const verifyTeamPasswordReset = (email: string, otp: string) =>
|
||||||
|
http.get<TeamVerifyPasswordResetResponse>("/team/verifyResetCode", {
|
||||||
|
params: { email, otp },
|
||||||
|
skipErrorToast: true,
|
||||||
|
})
|
||||||
|
|
||||||
|
export function parseVerifyPasswordReset(
|
||||||
|
response: Awaited<ReturnType<typeof verifyTeamPasswordReset>>,
|
||||||
|
): 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<TeamPasswordResetResponse>("/team/resetPassword", data, {
|
||||||
|
skipErrorToast: true,
|
||||||
|
})
|
||||||
|
|
||||||
/** POST /team/members/invite — send invitation email (permission: team.members.invite). */
|
/** POST /team/members/invite — send invitation email (permission: team.members.invite). */
|
||||||
export const inviteTeamMember = (data: InviteTeamMemberRequest) =>
|
export const inviteTeamMember = (data: InviteTeamMemberRequest) =>
|
||||||
http.post<InviteTeamMemberResponse>("/team/members/invite", data, {
|
http.post<InviteTeamMemberResponse>("/team/members/invite", data, {
|
||||||
|
|
|
||||||
|
|
@ -66,6 +66,7 @@ import { AddTeamMemberPage } from "../pages/team/AddTeamMemberPage";
|
||||||
import { TeamMemberDetailPage } from "../pages/team/TeamMemberDetailPage";
|
import { TeamMemberDetailPage } from "../pages/team/TeamMemberDetailPage";
|
||||||
import { LoginPage } from "../pages/auth/LoginPage";
|
import { LoginPage } from "../pages/auth/LoginPage";
|
||||||
import { ForgotPasswordPage } from "../pages/auth/ForgotPasswordPage";
|
import { ForgotPasswordPage } from "../pages/auth/ForgotPasswordPage";
|
||||||
|
import { ResetPasswordPage } from "../pages/auth/ResetPasswordPage";
|
||||||
import { VerificationPage } from "../pages/auth/VerificationPage";
|
import { VerificationPage } from "../pages/auth/VerificationPage";
|
||||||
import { AcceptInvitePage } from "../pages/auth/AcceptInvitePage";
|
import { AcceptInvitePage } from "../pages/auth/AcceptInvitePage";
|
||||||
import { AboutPage } from "../pages/AboutPage";
|
import { AboutPage } from "../pages/AboutPage";
|
||||||
|
|
@ -82,6 +83,7 @@ export function AppRoutes() {
|
||||||
<Routes>
|
<Routes>
|
||||||
<Route path="/login" element={<LoginPage />} />
|
<Route path="/login" element={<LoginPage />} />
|
||||||
<Route path="/forgot-password" element={<ForgotPasswordPage />} />
|
<Route path="/forgot-password" element={<ForgotPasswordPage />} />
|
||||||
|
<Route path="/reset-password" element={<ResetPasswordPage />} />
|
||||||
<Route path="/verification" element={<VerificationPage />} />
|
<Route path="/verification" element={<VerificationPage />} />
|
||||||
<Route path="/accept-invite" element={<AcceptInvitePage />} />
|
<Route path="/accept-invite" element={<AcceptInvitePage />} />
|
||||||
<Route path="/about" element={<AboutPage />} />
|
<Route path="/about" element={<AboutPage />} />
|
||||||
|
|
|
||||||
|
|
@ -4,6 +4,7 @@ import { getDashboard } from "../../api/analytics.api"
|
||||||
import { getYearOptions } from "../analytics/AnalyticsTimeRangeFilter"
|
import { getYearOptions } from "../analytics/AnalyticsTimeRangeFilter"
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "../ui/card"
|
import { Card, CardContent, CardHeader, CardTitle } from "../ui/card"
|
||||||
import { Select } from "../ui/select"
|
import { Select } from "../ui/select"
|
||||||
|
import { SensitiveChart, SensitiveRevealToggle, SensitiveValue } from "../ui/sensitive-value"
|
||||||
import { aggregateRevenueByMonth, formatRevenueAxisTick } from "../../lib/analytics"
|
import { aggregateRevenueByMonth, formatRevenueAxisTick } from "../../lib/analytics"
|
||||||
import type { DateRevenue } from "../../types/analytics.types"
|
import type { DateRevenue } from "../../types/analytics.types"
|
||||||
import spinnerSrc from "../../assets/Circular-indeterminate progress indicator.svg"
|
import spinnerSrc from "../../assets/Circular-indeterminate progress indicator.svg"
|
||||||
|
|
@ -63,9 +64,12 @@ export function RevenueTrendCard() {
|
||||||
<CardHeader className="pb-2">
|
<CardHeader className="pb-2">
|
||||||
<div className="flex items-start justify-between gap-3">
|
<div className="flex items-start justify-between gap-3">
|
||||||
<div>
|
<div>
|
||||||
|
<div className="flex items-center gap-1">
|
||||||
<CardTitle>Revenue Trend</CardTitle>
|
<CardTitle>Revenue Trend</CardTitle>
|
||||||
|
<SensitiveRevealToggle />
|
||||||
|
</div>
|
||||||
<div className="mt-2 text-2xl font-semibold tracking-tight">
|
<div className="mt-2 text-2xl font-semibold tracking-tight">
|
||||||
ETB {totalRevenue.toLocaleString()}
|
<SensitiveValue showToggle={false}>ETB {totalRevenue.toLocaleString()}</SensitiveValue>
|
||||||
</div>
|
</div>
|
||||||
<div className="text-xs font-medium text-grayScale-500">Monthly · {year} (ETB)</div>
|
<div className="text-xs font-medium text-grayScale-500">Monthly · {year} (ETB)</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
@ -89,6 +93,7 @@ export function RevenueTrendCard() {
|
||||||
<img src={spinnerSrc} alt="" className="h-8 w-8 animate-spin" />
|
<img src={spinnerSrc} alt="" className="h-8 w-8 animate-spin" />
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
|
<SensitiveChart>
|
||||||
<ResponsiveContainer width="100%" height="100%">
|
<ResponsiveContainer width="100%" height="100%">
|
||||||
<ComposedChart data={chartData} margin={{ left: 4, right: 8, top: 8, bottom: 0 }} barGap={-28}>
|
<ComposedChart data={chartData} margin={{ left: 4, right: 8, top: 8, bottom: 0 }} barGap={-28}>
|
||||||
<CartesianGrid vertical={false} stroke="#E0E0E0" strokeDasharray="4 4" />
|
<CartesianGrid vertical={false} stroke="#E0E0E0" strokeDasharray="4 4" />
|
||||||
|
|
@ -123,6 +128,7 @@ export function RevenueTrendCard() {
|
||||||
</Bar>
|
</Bar>
|
||||||
</ComposedChart>
|
</ComposedChart>
|
||||||
</ResponsiveContainer>
|
</ResponsiveContainer>
|
||||||
|
</SensitiveChart>
|
||||||
)}
|
)}
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,5 @@
|
||||||
import type { LucideIcon } from "lucide-react"
|
import type { LucideIcon } from "lucide-react"
|
||||||
|
import type { ReactNode } from "react"
|
||||||
import { cn } from "../../lib/utils"
|
import { cn } from "../../lib/utils"
|
||||||
import { Card, CardContent } from "../ui/card"
|
import { Card, CardContent } from "../ui/card"
|
||||||
|
|
||||||
|
|
@ -11,7 +12,7 @@ export function StatCard({
|
||||||
}: {
|
}: {
|
||||||
icon: LucideIcon
|
icon: LucideIcon
|
||||||
label: string
|
label: string
|
||||||
value: string
|
value: ReactNode
|
||||||
deltaLabel: string
|
deltaLabel: string
|
||||||
deltaPositive: boolean
|
deltaPositive: boolean
|
||||||
}) {
|
}) {
|
||||||
|
|
|
||||||
|
|
@ -53,7 +53,7 @@ const DialogHeader = ({
|
||||||
}: React.HTMLAttributes<HTMLDivElement>) => (
|
}: React.HTMLAttributes<HTMLDivElement>) => (
|
||||||
<div
|
<div
|
||||||
className={cn(
|
className={cn(
|
||||||
"flex flex-col space-y-1.5 text-center sm:text-left",
|
"flex flex-col space-y-1.5 pr-10 text-center sm:text-left",
|
||||||
className,
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
|
|
|
||||||
126
src/components/ui/sensitive-value.tsx
Normal file
126
src/components/ui/sensitive-value.tsx
Normal file
|
|
@ -0,0 +1,126 @@
|
||||||
|
import {
|
||||||
|
createContext,
|
||||||
|
useCallback,
|
||||||
|
useContext,
|
||||||
|
useState,
|
||||||
|
type ReactNode,
|
||||||
|
} from "react"
|
||||||
|
import { Eye, EyeOff } from "lucide-react"
|
||||||
|
import { cn } from "../../lib/utils"
|
||||||
|
|
||||||
|
type SensitiveRevealContextValue = {
|
||||||
|
revealed: boolean
|
||||||
|
toggle: () => void
|
||||||
|
}
|
||||||
|
|
||||||
|
const SensitiveRevealContext = createContext<SensitiveRevealContextValue | null>(null)
|
||||||
|
|
||||||
|
export function SensitiveRevealProvider({ children }: { children: ReactNode }) {
|
||||||
|
const [revealed, setRevealed] = useState(false)
|
||||||
|
const toggle = useCallback(() => setRevealed((v) => !v), [])
|
||||||
|
|
||||||
|
return (
|
||||||
|
<SensitiveRevealContext.Provider value={{ revealed, toggle }}>
|
||||||
|
{children}
|
||||||
|
</SensitiveRevealContext.Provider>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useSensitiveReveal() {
|
||||||
|
const ctx = useContext(SensitiveRevealContext)
|
||||||
|
const [localRevealed, setLocalRevealed] = useState(false)
|
||||||
|
const toggleLocal = useCallback(() => setLocalRevealed((v) => !v), [])
|
||||||
|
|
||||||
|
if (ctx) return ctx
|
||||||
|
|
||||||
|
return {
|
||||||
|
revealed: localRevealed,
|
||||||
|
toggle: toggleLocal,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SensitiveRevealToggle({
|
||||||
|
className,
|
||||||
|
label = "revenue",
|
||||||
|
}: {
|
||||||
|
className?: string
|
||||||
|
label?: string
|
||||||
|
}) {
|
||||||
|
const { revealed, toggle } = useSensitiveReveal()
|
||||||
|
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={toggle}
|
||||||
|
className={cn(
|
||||||
|
"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-lg text-grayScale-500 transition-colors hover:bg-grayScale-100 hover:text-grayScale-800",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
aria-label={revealed ? `Hide ${label}` : `Show ${label}`}
|
||||||
|
title={revealed ? `Hide ${label}` : `Show ${label}`}
|
||||||
|
>
|
||||||
|
{revealed ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
|
||||||
|
</button>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SensitiveValue({
|
||||||
|
children,
|
||||||
|
className,
|
||||||
|
showToggle = true,
|
||||||
|
}: {
|
||||||
|
children: ReactNode
|
||||||
|
className?: string
|
||||||
|
showToggle?: boolean
|
||||||
|
}) {
|
||||||
|
const { revealed } = useSensitiveReveal()
|
||||||
|
|
||||||
|
return (
|
||||||
|
<span className={cn("inline-flex items-center gap-1.5", className)}>
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
"transition-[filter] duration-200",
|
||||||
|
!revealed && "select-none blur-[6px]",
|
||||||
|
)}
|
||||||
|
aria-hidden={!revealed}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</span>
|
||||||
|
{showToggle ? <SensitiveRevealToggle /> : null}
|
||||||
|
</span>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SensitiveChart({
|
||||||
|
children,
|
||||||
|
className,
|
||||||
|
}: {
|
||||||
|
children: ReactNode
|
||||||
|
className?: string
|
||||||
|
}) {
|
||||||
|
const { revealed, toggle } = useSensitiveReveal()
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={cn("relative h-full w-full", className)}>
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"h-full w-full transition-[filter] duration-200",
|
||||||
|
!revealed && "pointer-events-none select-none blur-md",
|
||||||
|
)}
|
||||||
|
aria-hidden={!revealed}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
{!revealed ? (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={toggle}
|
||||||
|
className="absolute inset-0 z-10 flex flex-col items-center justify-center gap-2 rounded-lg bg-white/40 text-sm font-medium text-grayScale-600 backdrop-blur-[1px] transition-colors hover:bg-white/55 hover:text-grayScale-800"
|
||||||
|
>
|
||||||
|
<Eye className="h-5 w-5" />
|
||||||
|
Show revenue
|
||||||
|
</button>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
@ -50,6 +50,9 @@ const ACTION_LABELS: Record<string, string> = {
|
||||||
PAYMENT_VERIFIED: "Payment verified",
|
PAYMENT_VERIFIED: "Payment verified",
|
||||||
PAYMENT_CANCELLED: "Payment cancelled",
|
PAYMENT_CANCELLED: "Payment cancelled",
|
||||||
PAYMENT_WEBHOOK_RECEIVED: "Payment webhook received",
|
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_BULK_SENT: "Bulk notification sent",
|
||||||
NOTIFICATION_CREATED: "Notification created",
|
NOTIFICATION_CREATED: "Notification created",
|
||||||
NOTIFICATION_UPDATED: "Notification updated",
|
NOTIFICATION_UPDATED: "Notification updated",
|
||||||
|
|
@ -80,6 +83,7 @@ const ACTION_CATEGORY: Record<string, ActionBadgeTone> = {
|
||||||
PAYMENT_CANCELLED: "billing",
|
PAYMENT_CANCELLED: "billing",
|
||||||
PAYMENT_WEBHOOK_RECEIVED: "billing",
|
PAYMENT_WEBHOOK_RECEIVED: "billing",
|
||||||
SUBSCRIPTION_CREATED: "billing",
|
SUBSCRIPTION_CREATED: "billing",
|
||||||
|
SUBSCRIPTION_EXTENDED: "billing",
|
||||||
SUBSCRIPTION_CANCELLED: "billing",
|
SUBSCRIPTION_CANCELLED: "billing",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -166,6 +170,7 @@ export const ACTION_FILTER_GROUPS: { label: string; actions: string[] }[] = [
|
||||||
"SUBSCRIPTION_PLAN_CREATED",
|
"SUBSCRIPTION_PLAN_CREATED",
|
||||||
"SUBSCRIPTION_PLAN_UPDATED",
|
"SUBSCRIPTION_PLAN_UPDATED",
|
||||||
"SUBSCRIPTION_CREATED",
|
"SUBSCRIPTION_CREATED",
|
||||||
|
"SUBSCRIPTION_EXTENDED",
|
||||||
"SUBSCRIPTION_CANCELLED",
|
"SUBSCRIPTION_CANCELLED",
|
||||||
"PAYMENT_INITIATED",
|
"PAYMENT_INITIATED",
|
||||||
"PAYMENT_VERIFIED",
|
"PAYMENT_VERIFIED",
|
||||||
|
|
|
||||||
|
|
@ -5,6 +5,21 @@ import type {
|
||||||
LabelCount,
|
LabelCount,
|
||||||
} from "../types/analytics.types"
|
} from "../types/analytics.types"
|
||||||
|
|
||||||
|
/** Canonical subscription row statuses shown in analytics breakdowns. */
|
||||||
|
export const SUBSCRIPTION_STATUS_BREAKDOWN = [
|
||||||
|
"ACTIVE",
|
||||||
|
"PENDING",
|
||||||
|
"EXPIRED",
|
||||||
|
"CANCELLED",
|
||||||
|
] as const
|
||||||
|
|
||||||
|
const SUBSCRIPTION_STATUS_COLORS: Record<string, string> = {
|
||||||
|
ACTIVE: "#9E2891",
|
||||||
|
PENDING: "#FFD23F",
|
||||||
|
EXPIRED: "#F97316",
|
||||||
|
CANCELLED: "#EF4444",
|
||||||
|
}
|
||||||
|
|
||||||
const INACTIVE_SUBSCRIPTION_STATUSES = new Set([
|
const INACTIVE_SUBSCRIPTION_STATUSES = new Set([
|
||||||
"INACTIVE",
|
"INACTIVE",
|
||||||
"CANCELLED",
|
"CANCELLED",
|
||||||
|
|
@ -20,6 +35,51 @@ export interface SubscriptionMetrics {
|
||||||
inactive: number
|
inactive: number
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface SubscriptionStatusPieSlice {
|
||||||
|
name: string
|
||||||
|
value: number
|
||||||
|
color: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ensures every canonical subscription status appears in the pie/legend,
|
||||||
|
* including statuses with a count of 0.
|
||||||
|
*/
|
||||||
|
export function buildSubscriptionStatusPie(
|
||||||
|
byStatus: LabelCount[] | null | undefined,
|
||||||
|
fallbackColors: string[] = ["#9E2891", "#FFD23F", "#1DE9B6", "#C26FC0"],
|
||||||
|
): SubscriptionStatusPieSlice[] {
|
||||||
|
const counts = new Map<string, number>()
|
||||||
|
for (const row of byStatus ?? []) {
|
||||||
|
const key = row.label.trim().toUpperCase()
|
||||||
|
if (!key) continue
|
||||||
|
counts.set(key, (counts.get(key) ?? 0) + row.count)
|
||||||
|
}
|
||||||
|
|
||||||
|
const known = new Set<string>(SUBSCRIPTION_STATUS_BREAKDOWN)
|
||||||
|
const slices: SubscriptionStatusPieSlice[] = SUBSCRIPTION_STATUS_BREAKDOWN.map(
|
||||||
|
(status, index) => ({
|
||||||
|
name: status,
|
||||||
|
value: counts.get(status) ?? 0,
|
||||||
|
color:
|
||||||
|
SUBSCRIPTION_STATUS_COLORS[status] ??
|
||||||
|
fallbackColors[index % fallbackColors.length],
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
// Preserve any unexpected statuses from the API after the canonical set.
|
||||||
|
for (const [status, value] of counts) {
|
||||||
|
if (known.has(status)) continue
|
||||||
|
slices.push({
|
||||||
|
name: status,
|
||||||
|
value,
|
||||||
|
color: fallbackColors[slices.length % fallbackColors.length],
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return slices
|
||||||
|
}
|
||||||
|
|
||||||
/** Derives inactive count from by_status when present, else total − active. */
|
/** Derives inactive count from by_status when present, else total − active. */
|
||||||
export function getSubscriptionMetrics(
|
export function getSubscriptionMetrics(
|
||||||
subscriptions: DashboardSubscriptions,
|
subscriptions: DashboardSubscriptions,
|
||||||
|
|
|
||||||
44
src/lib/subscriptionAdminPermissions.ts
Normal file
44
src/lib/subscriptionAdminPermissions.ts
Normal file
|
|
@ -0,0 +1,44 @@
|
||||||
|
import { getNormalizedSessionTeamRole } from "./teamRole"
|
||||||
|
|
||||||
|
export const SUBSCRIPTION_ADMIN_PERMISSIONS = {
|
||||||
|
/** Unified grant-or-extend (admin_grant removed from API seeds). */
|
||||||
|
apply: "subscriptions.admin_extend",
|
||||||
|
extend: "subscriptions.admin_extend",
|
||||||
|
cancel: "subscriptions.admin_cancel",
|
||||||
|
getByUser: "subscriptions.get_by_user",
|
||||||
|
} as const
|
||||||
|
|
||||||
|
const ALL_ADMIN_SUBSCRIPTION_PERMISSIONS = [
|
||||||
|
SUBSCRIPTION_ADMIN_PERMISSIONS.apply,
|
||||||
|
SUBSCRIPTION_ADMIN_PERMISSIONS.cancel,
|
||||||
|
SUBSCRIPTION_ADMIN_PERMISSIONS.getByUser,
|
||||||
|
] as const
|
||||||
|
|
||||||
|
/** Default access by team role (matches API RBAC seeds for ADMIN). */
|
||||||
|
const ROLE_PERMISSIONS: Record<string, readonly string[]> = {
|
||||||
|
SUPER_ADMIN: ALL_ADMIN_SUBSCRIPTION_PERMISSIONS,
|
||||||
|
ADMIN: ALL_ADMIN_SUBSCRIPTION_PERMISSIONS,
|
||||||
|
}
|
||||||
|
|
||||||
|
export function hasSubscriptionAdminPermission(
|
||||||
|
permission: string,
|
||||||
|
permissions: string[],
|
||||||
|
): boolean {
|
||||||
|
if (permissions.includes(permission)) return true
|
||||||
|
const rolePerms = ROLE_PERMISSIONS[getNormalizedSessionTeamRole()]
|
||||||
|
return rolePerms?.includes(permission) ?? false
|
||||||
|
}
|
||||||
|
|
||||||
|
const LEARNER_ROLES = new Set(["STUDENT", "OPEN_LEARNER"])
|
||||||
|
|
||||||
|
export function isLearnerRole(role: string | null | undefined): boolean {
|
||||||
|
return LEARNER_ROLES.has(String(role ?? "").trim().toUpperCase())
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatAdminPaymentMethod(method: string | null | undefined): string {
|
||||||
|
const value = String(method ?? "").trim().toUpperCase()
|
||||||
|
if (value === "ADMIN_GRANT") return "Admin grant"
|
||||||
|
if (value === "ADMIN_EXTEND") return "Admin extend"
|
||||||
|
if (!value) return "—"
|
||||||
|
return method!.trim()
|
||||||
|
}
|
||||||
78
src/lib/teamPasswordReset.ts
Normal file
78
src/lib/teamPasswordReset.ts
Normal file
|
|
@ -0,0 +1,78 @@
|
||||||
|
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 {
|
||||||
|
if (axios.isAxiosError(error)) {
|
||||||
|
const data = error.response?.data
|
||||||
|
if (data && typeof data === "object") {
|
||||||
|
const record = data as Record<string, unknown>
|
||||||
|
if (typeof record.error === "string" && record.error.trim()) {
|
||||||
|
return record.error.trim()
|
||||||
|
}
|
||||||
|
if (typeof record.message === "string" && record.message.trim()) {
|
||||||
|
return record.message.trim()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return fallback
|
||||||
|
}
|
||||||
|
|
||||||
|
export function mapTeamPasswordResetError(error: unknown): string {
|
||||||
|
const detail = getTeamAuthErrorMessage(error, "")
|
||||||
|
const lower = detail.toLowerCase()
|
||||||
|
|
||||||
|
if (lower.includes("not active")) {
|
||||||
|
return "This account is inactive. Contact an administrator."
|
||||||
|
}
|
||||||
|
if (lower.includes("accept your invitation")) {
|
||||||
|
return "Finish accepting your invitation before resetting your password."
|
||||||
|
}
|
||||||
|
if (lower.includes("not found")) {
|
||||||
|
return "No team account found for that email."
|
||||||
|
}
|
||||||
|
if (lower.includes("expired")) {
|
||||||
|
return "This reset link has expired (valid for 5 minutes). Request a new one."
|
||||||
|
}
|
||||||
|
if (lower.includes("already been used")) {
|
||||||
|
return "This reset link was already used. Request a new one."
|
||||||
|
}
|
||||||
|
if (lower.includes("invalid or missing reset code") || lower.includes("invalid")) {
|
||||||
|
return "Invalid reset code. Request a new link from Forgot password."
|
||||||
|
}
|
||||||
|
if (lower.includes("team_password_reset_base_url")) {
|
||||||
|
return "Password reset is not configured. Contact an administrator."
|
||||||
|
}
|
||||||
|
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."
|
||||||
|
}
|
||||||
|
}
|
||||||
146
src/lib/typeToConfirm.tsx
Normal file
146
src/lib/typeToConfirm.tsx
Normal file
|
|
@ -0,0 +1,146 @@
|
||||||
|
import { useEffect, useState, type ReactNode } from "react"
|
||||||
|
import { Button } from "../components/ui/button"
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from "../components/ui/dialog"
|
||||||
|
import { Input } from "../components/ui/input"
|
||||||
|
import { SpinnerIcon } from "../components/ui/spinner-icon"
|
||||||
|
import { cn } from "./utils"
|
||||||
|
|
||||||
|
type TypeToConfirmFieldProps = {
|
||||||
|
labelWord: string
|
||||||
|
value: string
|
||||||
|
onChange: (value: string) => void
|
||||||
|
disabled?: boolean
|
||||||
|
className?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Requires the admin to type an exact confirmation word (case-insensitive). */
|
||||||
|
export function TypeToConfirmField({
|
||||||
|
labelWord,
|
||||||
|
value,
|
||||||
|
onChange,
|
||||||
|
disabled,
|
||||||
|
className,
|
||||||
|
}: TypeToConfirmFieldProps) {
|
||||||
|
const expected = labelWord.trim().toUpperCase()
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={cn("space-y-1.5", className)}>
|
||||||
|
<label className="block text-sm text-grayScale-600">
|
||||||
|
Type <span className="font-bold text-grayScale-900">{expected}</span> to confirm
|
||||||
|
</label>
|
||||||
|
<Input
|
||||||
|
value={value}
|
||||||
|
onChange={(e) => onChange(e.target.value)}
|
||||||
|
disabled={disabled}
|
||||||
|
placeholder={expected}
|
||||||
|
autoComplete="off"
|
||||||
|
spellCheck={false}
|
||||||
|
onCopy={(e) => e.preventDefault()}
|
||||||
|
onCut={(e) => e.preventDefault()}
|
||||||
|
onPaste={(e) => e.preventDefault()}
|
||||||
|
onDrop={(e) => e.preventDefault()}
|
||||||
|
className="rounded-[6px] font-mono uppercase tracking-wide"
|
||||||
|
aria-label={`Type ${expected} to confirm`}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function matchesConfirmWord(value: string, expectedWord: string): boolean {
|
||||||
|
return value.trim().toUpperCase() === expectedWord.trim().toUpperCase()
|
||||||
|
}
|
||||||
|
|
||||||
|
type TypeToConfirmDialogProps = {
|
||||||
|
open: boolean
|
||||||
|
onOpenChange: (open: boolean) => void
|
||||||
|
title: string
|
||||||
|
description?: ReactNode
|
||||||
|
confirmWord: string
|
||||||
|
confirmLabel?: string
|
||||||
|
cancelLabel?: string
|
||||||
|
confirming?: boolean
|
||||||
|
variant?: "default" | "destructive"
|
||||||
|
onConfirm: () => void | Promise<void>
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Separate “Are you sure?” modal that requires typing a confirmation word. */
|
||||||
|
export function TypeToConfirmDialog({
|
||||||
|
open,
|
||||||
|
onOpenChange,
|
||||||
|
title,
|
||||||
|
description,
|
||||||
|
confirmWord,
|
||||||
|
confirmLabel = "Confirm",
|
||||||
|
cancelLabel = "Cancel",
|
||||||
|
confirming = false,
|
||||||
|
variant = "default",
|
||||||
|
onConfirm,
|
||||||
|
}: TypeToConfirmDialogProps) {
|
||||||
|
const [confirmText, setConfirmText] = useState("")
|
||||||
|
const confirmMatched = matchesConfirmWord(confirmText, confirmWord)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) return
|
||||||
|
setConfirmText("")
|
||||||
|
}, [open, confirmWord])
|
||||||
|
|
||||||
|
const handleConfirm = async () => {
|
||||||
|
if (!confirmMatched || confirming) return
|
||||||
|
await onConfirm()
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={(next) => !confirming && onOpenChange(next)}>
|
||||||
|
<DialogContent className="max-w-md rounded-[12px] border border-grayScale-100 sm:max-w-md">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle className="text-lg font-bold text-grayScale-900">{title}</DialogTitle>
|
||||||
|
{description ? (
|
||||||
|
<DialogDescription className="text-left text-grayScale-600">
|
||||||
|
{description}
|
||||||
|
</DialogDescription>
|
||||||
|
) : null}
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
<TypeToConfirmField
|
||||||
|
labelWord={confirmWord}
|
||||||
|
value={confirmText}
|
||||||
|
onChange={setConfirmText}
|
||||||
|
disabled={confirming}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<DialogFooter className="gap-2 sm:gap-2">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
className="rounded-[6px]"
|
||||||
|
disabled={confirming}
|
||||||
|
onClick={() => onOpenChange(false)}
|
||||||
|
>
|
||||||
|
{cancelLabel}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant={variant === "destructive" ? "destructive" : "default"}
|
||||||
|
className={cn(
|
||||||
|
"rounded-[6px]",
|
||||||
|
variant === "default" &&
|
||||||
|
"bg-brand-500 font-semibold text-white hover:bg-brand-600",
|
||||||
|
)}
|
||||||
|
disabled={confirming || !confirmMatched}
|
||||||
|
onClick={() => void handleConfirm()}
|
||||||
|
>
|
||||||
|
{confirming ? <SpinnerIcon className="h-4 w-4" /> : null}
|
||||||
|
{confirming ? "Working…" : confirmLabel}
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
@ -33,6 +33,7 @@ import { StatCard } from "../components/dashboard/StatCard"
|
||||||
import alertSrc from "../assets/Alert.svg"
|
import alertSrc from "../assets/Alert.svg"
|
||||||
import { Badge } from "../components/ui/badge"
|
import { Badge } from "../components/ui/badge"
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "../components/ui/card"
|
import { Card, CardContent, CardHeader, CardTitle } from "../components/ui/card"
|
||||||
|
import { SensitiveRevealProvider, SensitiveValue } from "../components/ui/sensitive-value"
|
||||||
import { cn } from "../lib/utils"
|
import { cn } from "../lib/utils"
|
||||||
import { getTeamMemberById } from "../api/team.api"
|
import { getTeamMemberById } from "../api/team.api"
|
||||||
import { getDashboard } from "../api/analytics.api"
|
import { getDashboard } from "../api/analytics.api"
|
||||||
|
|
@ -46,6 +47,7 @@ import {
|
||||||
getSeriesPeriodLabel,
|
getSeriesPeriodLabel,
|
||||||
getSubscriptionMetrics,
|
getSubscriptionMetrics,
|
||||||
getVideoLessonsSummary,
|
getVideoLessonsSummary,
|
||||||
|
buildSubscriptionStatusPie,
|
||||||
} from "../lib/analytics"
|
} from "../lib/analytics"
|
||||||
import type { DashboardData, DashboardFilters } from "../types/analytics.types"
|
import type { DashboardData, DashboardFilters } from "../types/analytics.types"
|
||||||
import { formatAverageStars } from "../lib/ratingsDisplay"
|
import { formatAverageStars } from "../lib/ratingsDisplay"
|
||||||
|
|
@ -155,13 +157,10 @@ export function DashboardPage() {
|
||||||
count: d.count,
|
count: d.count,
|
||||||
})) ?? []
|
})) ?? []
|
||||||
|
|
||||||
const subscriptionStatusData =
|
const subscriptionStatusData = buildSubscriptionStatusPie(
|
||||||
dashboard?.subscriptions.by_status.map((s, i) => ({
|
dashboard?.subscriptions.by_status,
|
||||||
name: s.label,
|
PIE_COLORS,
|
||||||
value: s.count,
|
)
|
||||||
color: PIE_COLORS[i % PIE_COLORS.length],
|
|
||||||
})) ?? []
|
|
||||||
|
|
||||||
const issueStatusData =
|
const issueStatusData =
|
||||||
dashboard?.issues.by_status.map((s, i) => ({
|
dashboard?.issues.by_status.map((s, i) => ({
|
||||||
name: s.label,
|
name: s.label,
|
||||||
|
|
@ -175,6 +174,7 @@ export function DashboardPage() {
|
||||||
: null
|
: null
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
<SensitiveRevealProvider>
|
||||||
<div className="mx-auto w-full min-w-0 max-w-6xl">
|
<div className="mx-auto w-full min-w-0 max-w-6xl">
|
||||||
<div className="mb-2 flex flex-wrap items-center justify-between gap-3">
|
<div className="mb-2 flex flex-wrap items-center justify-between gap-3">
|
||||||
<div className="text-sm font-semibold text-grayScale-500">Dashboard</div>
|
<div className="text-sm font-semibold text-grayScale-500">Dashboard</div>
|
||||||
|
|
@ -252,7 +252,11 @@ export function DashboardPage() {
|
||||||
<StatCard
|
<StatCard
|
||||||
icon={DollarSign}
|
icon={DollarSign}
|
||||||
label="Total Revenue (ETB)"
|
label="Total Revenue (ETB)"
|
||||||
value={dashboard.payments.total_revenue.toLocaleString()}
|
value={
|
||||||
|
<SensitiveValue>
|
||||||
|
{dashboard.payments.total_revenue.toLocaleString()}
|
||||||
|
</SensitiveValue>
|
||||||
|
}
|
||||||
deltaLabel={`${dashboard.payments.total_payments} payments`}
|
deltaLabel={`${dashboard.payments.total_payments} payments`}
|
||||||
deltaPositive={dashboard.payments.total_revenue > 0}
|
deltaPositive={dashboard.payments.total_revenue > 0}
|
||||||
/>
|
/>
|
||||||
|
|
@ -596,5 +600,6 @@ export function DashboardPage() {
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
</SensitiveRevealProvider>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
import { useEffect, useState } from "react"
|
import { useEffect, useState, type ElementType, type ReactNode } from "react"
|
||||||
import spinnerSrc from "../../assets/Circular-indeterminate progress indicator.svg"
|
import spinnerSrc from "../../assets/Circular-indeterminate progress indicator.svg"
|
||||||
import {
|
import {
|
||||||
Area,
|
Area,
|
||||||
|
|
@ -38,6 +38,12 @@ import {
|
||||||
CheckCircle2,
|
CheckCircle2,
|
||||||
} from "lucide-react"
|
} from "lucide-react"
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card"
|
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 { Badge } from "../../components/ui/badge"
|
||||||
import { Button } from "../../components/ui/button"
|
import { Button } from "../../components/ui/button"
|
||||||
import { cn } from "../../lib/utils"
|
import { cn } from "../../lib/utils"
|
||||||
|
|
@ -50,6 +56,7 @@ import {
|
||||||
getSubscriptionMetrics,
|
getSubscriptionMetrics,
|
||||||
getVideoLessonsSummary,
|
getVideoLessonsSummary,
|
||||||
formatPercentRate,
|
formatPercentRate,
|
||||||
|
buildSubscriptionStatusPie,
|
||||||
} from "../../lib/analytics"
|
} from "../../lib/analytics"
|
||||||
import type { DashboardData, DashboardFilters, LabelCount } from "../../types/analytics.types"
|
import type { DashboardData, DashboardFilters, LabelCount } from "../../types/analytics.types"
|
||||||
|
|
||||||
|
|
@ -74,10 +81,10 @@ function KpiCard({
|
||||||
trend,
|
trend,
|
||||||
className,
|
className,
|
||||||
}: {
|
}: {
|
||||||
icon: React.ElementType
|
icon: ElementType
|
||||||
label: string
|
label: string
|
||||||
value: string
|
value: ReactNode
|
||||||
sub?: string
|
sub?: ReactNode
|
||||||
trend?: "up" | "down" | "neutral"
|
trend?: "up" | "down" | "neutral"
|
||||||
className?: string
|
className?: string
|
||||||
}) {
|
}) {
|
||||||
|
|
@ -388,12 +395,10 @@ export function AnalyticsPage() {
|
||||||
color: PIE_COLORS[i % PIE_COLORS.length],
|
color: PIE_COLORS[i % PIE_COLORS.length],
|
||||||
}))
|
}))
|
||||||
|
|
||||||
const subscriptionStatusPie = subscriptions.by_status.map((s, i) => ({
|
const subscriptionStatusPie = buildSubscriptionStatusPie(
|
||||||
name: s.label,
|
subscriptions.by_status,
|
||||||
value: s.count,
|
PIE_COLORS,
|
||||||
color: PIE_COLORS[i % PIE_COLORS.length],
|
)
|
||||||
}))
|
|
||||||
|
|
||||||
const notifByTypePie = notifications.by_type.slice(0, 8).map((s, i) => ({
|
const notifByTypePie = notifications.by_type.slice(0, 8).map((s, i) => ({
|
||||||
name: s.label,
|
name: s.label,
|
||||||
value: s.count,
|
value: s.count,
|
||||||
|
|
@ -424,6 +429,7 @@ export function AnalyticsPage() {
|
||||||
})
|
})
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
<SensitiveRevealProvider>
|
||||||
<div className="mx-auto w-full max-w-[1280px] px-2 pb-6 sm:px-4">
|
<div className="mx-auto w-full max-w-[1280px] px-2 pb-6 sm:px-4">
|
||||||
{/* Header */}
|
{/* Header */}
|
||||||
<div className="mb-7 flex flex-wrap items-end justify-between gap-4">
|
<div className="mb-7 flex flex-wrap items-end justify-between gap-4">
|
||||||
|
|
@ -515,8 +521,19 @@ export function AnalyticsPage() {
|
||||||
<KpiCard
|
<KpiCard
|
||||||
icon={DollarSign}
|
icon={DollarSign}
|
||||||
label="Total Revenue"
|
label="Total Revenue"
|
||||||
value={`ETB ${formatNumber(payments.total_revenue)}`}
|
value={
|
||||||
sub={`${payments.successful_payments}/${payments.total_payments} successful · Avg ETB ${payments.avg_transaction_value.toLocaleString()}`}
|
<SensitiveValue>
|
||||||
|
{`ETB ${formatNumber(payments.total_revenue)}`}
|
||||||
|
</SensitiveValue>
|
||||||
|
}
|
||||||
|
sub={
|
||||||
|
<>
|
||||||
|
{payments.successful_payments}/{payments.total_payments} successful · Avg{" "}
|
||||||
|
<SensitiveValue showToggle={false}>
|
||||||
|
ETB {payments.avg_transaction_value.toLocaleString()}
|
||||||
|
</SensitiveValue>
|
||||||
|
</>
|
||||||
|
}
|
||||||
trend={payments.total_revenue > 0 ? "up" : "neutral"}
|
trend={payments.total_revenue > 0 ? "up" : "neutral"}
|
||||||
/>
|
/>
|
||||||
<KpiCard
|
<KpiCard
|
||||||
|
|
@ -781,9 +798,14 @@ export function AnalyticsPage() {
|
||||||
<CardHeader className="pb-2">
|
<CardHeader className="pb-2">
|
||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
<div>
|
<div>
|
||||||
|
<div className="flex items-center gap-1">
|
||||||
<CardTitle>Revenue</CardTitle>
|
<CardTitle>Revenue</CardTitle>
|
||||||
|
<SensitiveRevealToggle />
|
||||||
|
</div>
|
||||||
<div className="mt-1 text-2xl font-semibold tracking-tight">
|
<div className="mt-1 text-2xl font-semibold tracking-tight">
|
||||||
|
<SensitiveValue showToggle={false}>
|
||||||
ETB {payments.total_revenue.toLocaleString()}
|
ETB {payments.total_revenue.toLocaleString()}
|
||||||
|
</SensitiveValue>
|
||||||
</div>
|
</div>
|
||||||
<div className="text-xs text-grayScale-400">Daily revenue over last 30 days</div>
|
<div className="text-xs text-grayScale-400">Daily revenue over last 30 days</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
@ -791,6 +813,7 @@ export function AnalyticsPage() {
|
||||||
</div>
|
</div>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent className="h-[240px] p-6 pt-2">
|
<CardContent className="h-[240px] p-6 pt-2">
|
||||||
|
<SensitiveChart>
|
||||||
<ResponsiveContainer width="100%" height="100%">
|
<ResponsiveContainer width="100%" height="100%">
|
||||||
<BarChart data={revenueData} margin={{ left: 8, right: 8, top: 8 }}>
|
<BarChart data={revenueData} margin={{ left: 8, right: 8, top: 8 }}>
|
||||||
<CartesianGrid vertical={false} stroke="#E0E0E0" strokeDasharray="4 4" />
|
<CartesianGrid vertical={false} stroke="#E0E0E0" strokeDasharray="4 4" />
|
||||||
|
|
@ -808,6 +831,7 @@ export function AnalyticsPage() {
|
||||||
<Bar dataKey="revenue" radius={[6, 6, 0, 0]} fill="#9E2891" />
|
<Bar dataKey="revenue" radius={[6, 6, 0, 0]} fill="#9E2891" />
|
||||||
</BarChart>
|
</BarChart>
|
||||||
</ResponsiveContainer>
|
</ResponsiveContainer>
|
||||||
|
</SensitiveChart>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
|
|
@ -1059,5 +1083,6 @@ export function AnalyticsPage() {
|
||||||
</Section>
|
</Section>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
</SensitiveRevealProvider>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,28 +1,48 @@
|
||||||
import { useState } from "react"
|
import { useState } from "react"
|
||||||
import { Link } from "react-router-dom"
|
import { Link } from "react-router-dom"
|
||||||
import { ArrowLeft } from "lucide-react"
|
import { ArrowLeft } from "lucide-react"
|
||||||
|
import { toast } from "sonner"
|
||||||
import successSrc from "../../assets/success.svg"
|
import successSrc from "../../assets/success.svg"
|
||||||
|
import { sendTeamPasswordReset } from "../../api/team.api"
|
||||||
import { BrandLogo } from "../../components/brand/BrandLogo"
|
import { BrandLogo } from "../../components/brand/BrandLogo"
|
||||||
import { Button } from "../../components/ui/button"
|
import { Button } from "../../components/ui/button"
|
||||||
import { Input } from "../../components/ui/input"
|
import { Input } from "../../components/ui/input"
|
||||||
|
import { SpinnerIcon } from "../../components/ui/spinner-icon"
|
||||||
|
import { mapTeamPasswordResetError } from "../../lib/teamPasswordReset"
|
||||||
|
|
||||||
export function ForgotPasswordPage() {
|
export function ForgotPasswordPage() {
|
||||||
const [email, setEmail] = useState("")
|
const [email, setEmail] = useState("")
|
||||||
const [submitted, setSubmitted] = useState(false)
|
const [submitted, setSubmitted] = useState(false)
|
||||||
|
const [submitting, setSubmitting] = useState(false)
|
||||||
|
const [error, setError] = useState<string | null>(null)
|
||||||
|
|
||||||
const handleSubmit = (e: React.FormEvent) => {
|
const handleSubmit = async (e: React.FormEvent) => {
|
||||||
e.preventDefault()
|
e.preventDefault()
|
||||||
// Handle forgot password logic here
|
setError(null)
|
||||||
console.log("Forgot password:", { email })
|
|
||||||
|
const trimmed = email.trim()
|
||||||
|
if (!trimmed) {
|
||||||
|
setError("Email is required.")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
setSubmitting(true)
|
||||||
|
try {
|
||||||
|
await sendTeamPasswordReset({ email: trimmed })
|
||||||
setSubmitted(true)
|
setSubmitted(true)
|
||||||
|
toast.success("Reset link sent", {
|
||||||
|
description: "Check your email. The link expires in 5 minutes.",
|
||||||
|
})
|
||||||
|
} catch (err) {
|
||||||
|
setError(mapTeamPasswordResetError(err))
|
||||||
|
} finally {
|
||||||
|
setSubmitting(false)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="relative flex h-dvh overflow-y-auto">
|
<div className="relative flex h-dvh overflow-y-auto">
|
||||||
{/* Decorative left panel */}
|
<div className="relative hidden items-center justify-center bg-gradient-to-br from-brand-600 via-brand-500 to-brand-400 lg:flex lg:w-1/2 xl:w-[55%]">
|
||||||
<div className="hidden lg:flex lg:w-1/2 xl:w-[55%] items-center justify-center bg-gradient-to-br from-brand-600 via-brand-500 to-brand-400 relative">
|
|
||||||
{/* Abstract decorative shapes */}
|
|
||||||
<div className="absolute inset-0 overflow-hidden">
|
<div className="absolute inset-0 overflow-hidden">
|
||||||
<div className="absolute -left-20 -top-20 h-96 w-96 rounded-full bg-white/5" />
|
<div className="absolute -left-20 -top-20 h-96 w-96 rounded-full bg-white/5" />
|
||||||
<div className="absolute -bottom-32 -right-16 h-[500px] w-[500px] rounded-full bg-white/5" />
|
<div className="absolute -bottom-32 -right-16 h-[500px] w-[500px] rounded-full bg-white/5" />
|
||||||
|
|
@ -31,7 +51,6 @@ export function ForgotPasswordPage() {
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="relative z-10 max-w-md px-12 text-center">
|
<div className="relative z-10 max-w-md px-12 text-center">
|
||||||
{/* Brand logo */}
|
|
||||||
<BrandLogo variant="light" className="mx-auto mb-8 h-16" />
|
<BrandLogo variant="light" className="mx-auto mb-8 h-16" />
|
||||||
<p className="text-base leading-relaxed text-white/70">
|
<p className="text-base leading-relaxed text-white/70">
|
||||||
Manage your academy, track student progress, and streamline
|
Manage your academy, track student progress, and streamline
|
||||||
|
|
@ -40,15 +59,12 @@ export function ForgotPasswordPage() {
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Right panel – form */}
|
|
||||||
<div className="flex w-full flex-col items-center justify-center bg-white px-6 py-12 lg:w-1/2 xl:w-[45%]">
|
<div className="flex w-full flex-col items-center justify-center bg-white px-6 py-12 lg:w-1/2 xl:w-[45%]">
|
||||||
<div className="w-full max-w-[420px]">
|
<div className="w-full max-w-[420px]">
|
||||||
{/* Mobile-only logo */}
|
|
||||||
<div className="mb-10 flex justify-center lg:hidden">
|
<div className="mb-10 flex justify-center lg:hidden">
|
||||||
<BrandLogo />
|
<BrandLogo />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Back link */}
|
|
||||||
<Link
|
<Link
|
||||||
to="/login"
|
to="/login"
|
||||||
className="mb-8 inline-flex items-center gap-1.5 text-sm font-medium text-grayScale-400 transition-colors hover:text-grayScale-600"
|
className="mb-8 inline-flex items-center gap-1.5 text-sm font-medium text-grayScale-400 transition-colors hover:text-grayScale-600"
|
||||||
|
|
@ -58,30 +74,30 @@ export function ForgotPasswordPage() {
|
||||||
</Link>
|
</Link>
|
||||||
|
|
||||||
{submitted ? (
|
{submitted ? (
|
||||||
/* Success state */
|
|
||||||
<div className="text-center">
|
<div className="text-center">
|
||||||
<img src={successSrc} alt="" className="mx-auto mb-6 h-20 w-20" />
|
<img src={successSrc} alt="" className="mx-auto mb-6 h-20 w-20" />
|
||||||
<h1 className="mb-2 text-2xl font-bold tracking-tight text-grayScale-600">
|
<h1 className="mb-2 text-2xl font-bold tracking-tight text-grayScale-600">
|
||||||
Check your email
|
Check your email
|
||||||
</h1>
|
</h1>
|
||||||
<p className="mb-8 text-sm leading-relaxed text-grayScale-400">
|
<p className="mb-8 text-sm leading-relaxed text-grayScale-400">
|
||||||
We've sent a password reset link to{" "}
|
We've sent a password reset link to{" "}
|
||||||
<span className="font-medium text-grayScale-600">{email}</span>.
|
<span className="font-medium text-grayScale-600">{email.trim()}</span>.
|
||||||
Please check your inbox and follow the instructions.
|
The link expires in 5 minutes — open it promptly to set a new password.
|
||||||
</p>
|
</p>
|
||||||
<Button
|
<Button
|
||||||
type="button"
|
type="button"
|
||||||
variant="outline"
|
variant="outline"
|
||||||
className="h-11 rounded-xl px-6 text-sm font-semibold"
|
className="h-11 rounded-xl px-6 text-sm font-semibold"
|
||||||
onClick={() => setSubmitted(false)}
|
onClick={() => {
|
||||||
|
setSubmitted(false)
|
||||||
|
setError(null)
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
Try a different email
|
Try a different email
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
/* Form state */
|
|
||||||
<>
|
<>
|
||||||
{/* Header */}
|
|
||||||
<div className="mb-10">
|
<div className="mb-10">
|
||||||
<p className="mb-1.5 text-sm font-medium uppercase tracking-widest text-brand-400">
|
<p className="mb-1.5 text-sm font-medium uppercase tracking-widest text-brand-400">
|
||||||
Account Recovery
|
Account Recovery
|
||||||
|
|
@ -90,7 +106,7 @@ export function ForgotPasswordPage() {
|
||||||
Forgot password?
|
Forgot password?
|
||||||
</h1>
|
</h1>
|
||||||
<p className="text-sm leading-relaxed text-grayScale-400">
|
<p className="text-sm leading-relaxed text-grayScale-400">
|
||||||
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.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|
@ -107,23 +123,41 @@ export function ForgotPasswordPage() {
|
||||||
type="email"
|
type="email"
|
||||||
placeholder="you@example.com"
|
placeholder="you@example.com"
|
||||||
value={email}
|
value={email}
|
||||||
onChange={(e) => setEmail(e.target.value)}
|
onChange={(e) => {
|
||||||
|
setEmail(e.target.value)
|
||||||
|
if (error) setError(null)
|
||||||
|
}}
|
||||||
required
|
required
|
||||||
|
autoComplete="email"
|
||||||
|
disabled={submitting}
|
||||||
className="h-11 rounded-xl"
|
className="h-11 rounded-xl"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{error ? (
|
||||||
|
<p className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700">
|
||||||
|
{error}
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
|
|
||||||
<Button
|
<Button
|
||||||
type="submit"
|
type="submit"
|
||||||
|
disabled={submitting}
|
||||||
className="mt-2 h-11 w-full rounded-xl text-sm font-semibold tracking-wide"
|
className="mt-2 h-11 w-full rounded-xl text-sm font-semibold tracking-wide"
|
||||||
>
|
>
|
||||||
Send reset link
|
{submitting ? (
|
||||||
|
<span className="inline-flex items-center gap-2">
|
||||||
|
<SpinnerIcon className="h-4 w-4" />
|
||||||
|
Sending…
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
"Send reset link"
|
||||||
|
)}
|
||||||
</Button>
|
</Button>
|
||||||
</form>
|
</form>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Footer */}
|
|
||||||
<p className="mt-10 text-center text-xs text-grayScale-400">
|
<p className="mt-10 text-center text-xs text-grayScale-400">
|
||||||
© {new Date().getFullYear()} Yimaru Academy · All rights reserved
|
© {new Date().getFullYear()} Yimaru Academy · All rights reserved
|
||||||
</p>
|
</p>
|
||||||
|
|
|
||||||
|
|
@ -78,6 +78,14 @@ export function LoginPage() {
|
||||||
setSearchParams({}, { replace: true });
|
setSearchParams({}, { replace: true });
|
||||||
}, [searchParams, setSearchParams]);
|
}, [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(() => {
|
useEffect(() => {
|
||||||
if (searchParams.get("account_inactive") !== "1") return;
|
if (searchParams.get("account_inactive") !== "1") return;
|
||||||
toast.error("Account inactive", {
|
toast.error("Account inactive", {
|
||||||
|
|
|
||||||
334
src/pages/auth/ResetPasswordPage.tsx
Normal file
334
src/pages/auth/ResetPasswordPage.tsx
Normal file
|
|
@ -0,0 +1,334 @@
|
||||||
|
import { useCallback, useEffect, useMemo, useState } from "react"
|
||||||
|
import { Link, useNavigate, useSearchParams } from "react-router-dom"
|
||||||
|
import { AlertCircle, ArrowLeft, Eye, EyeOff } from "lucide-react"
|
||||||
|
import { toast } from "sonner"
|
||||||
|
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 {
|
||||||
|
getInvalidResetLinkDescription,
|
||||||
|
getInvalidResetLinkTitle,
|
||||||
|
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 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)
|
||||||
|
const [password, setPassword] = useState("")
|
||||||
|
const [confirmPassword, setConfirmPassword] = useState("")
|
||||||
|
const [showPassword, setShowPassword] = useState(false)
|
||||||
|
const [submitting, setSubmitting] = useState(false)
|
||||||
|
const [error, setError] = useState<string | null>(null)
|
||||||
|
|
||||||
|
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])
|
||||||
|
|
||||||
|
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 (
|
||||||
|
<div className="relative flex h-dvh overflow-y-auto">
|
||||||
|
<div className="relative hidden items-center justify-center bg-gradient-to-br from-brand-600 via-brand-500 to-brand-400 lg:flex lg:w-1/2 xl:w-[55%]">
|
||||||
|
<div className="absolute inset-0 overflow-hidden">
|
||||||
|
<div className="absolute -left-20 -top-20 h-96 w-96 rounded-full bg-white/5" />
|
||||||
|
<div className="absolute -bottom-32 -right-16 h-[500px] w-[500px] rounded-full bg-white/5" />
|
||||||
|
<div className="absolute left-1/3 top-1/4 h-64 w-64 rounded-full bg-white/5" />
|
||||||
|
</div>
|
||||||
|
<div className="relative z-10 max-w-md px-12 text-center">
|
||||||
|
<BrandLogo variant="light" className="mx-auto mb-8 h-16" />
|
||||||
|
<p className="text-base leading-relaxed text-white/70">
|
||||||
|
Choose a strong password to secure your admin account.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex w-full flex-col items-center justify-center bg-white px-6 py-12 lg:w-1/2 xl:w-[45%]">
|
||||||
|
<div className="w-full max-w-[420px]">
|
||||||
|
<div className="mb-10 flex justify-center lg:hidden">
|
||||||
|
<BrandLogo />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Link
|
||||||
|
to="/login"
|
||||||
|
className="mb-8 inline-flex items-center gap-1.5 text-sm font-medium text-grayScale-400 transition-colors hover:text-grayScale-600"
|
||||||
|
>
|
||||||
|
<ArrowLeft size={16} />
|
||||||
|
Back to sign in
|
||||||
|
</Link>
|
||||||
|
|
||||||
|
<div className="mb-8">
|
||||||
|
<p className="mb-1.5 text-sm font-medium uppercase tracking-widest text-brand-400">
|
||||||
|
Account Recovery
|
||||||
|
</p>
|
||||||
|
<h1 className="mb-2 text-3xl font-bold tracking-tight text-grayScale-600">
|
||||||
|
{verifyState === "invalid" ? invalidTitle : "Reset password"}
|
||||||
|
</h1>
|
||||||
|
<p className="text-sm leading-relaxed text-grayScale-400">
|
||||||
|
{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."}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{verifyState === "loading" ? (
|
||||||
|
<div className="flex flex-col items-center gap-3 py-16">
|
||||||
|
<SpinnerIcon className="h-8 w-8" />
|
||||||
|
<p className="text-sm text-grayScale-400">Verifying reset link…</p>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{verifyState === "invalid" ? (
|
||||||
|
<div className="space-y-4 rounded-xl border border-red-200 bg-red-50 px-4 py-4">
|
||||||
|
<div className="flex gap-3">
|
||||||
|
<AlertCircle className="mt-0.5 h-5 w-5 shrink-0 text-red-600" />
|
||||||
|
<div className="space-y-2 text-sm text-red-800">
|
||||||
|
<p className="font-semibold">{invalidTitle}</p>
|
||||||
|
<p>{invalidDescription}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<Link
|
||||||
|
to="/forgot-password"
|
||||||
|
className="inline-block text-sm font-semibold text-red-800 underline"
|
||||||
|
>
|
||||||
|
Request a new reset link
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{verifyState === "ready" ? (
|
||||||
|
<>
|
||||||
|
{!hasLinkParams ? (
|
||||||
|
<div className="mb-5 rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-800">
|
||||||
|
Missing reset link details. You can enter them manually, or{" "}
|
||||||
|
<Link to="/forgot-password" className="font-semibold underline">
|
||||||
|
request a new link
|
||||||
|
</Link>
|
||||||
|
.
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
<form onSubmit={handleSubmit} className="space-y-4">
|
||||||
|
<div>
|
||||||
|
<label
|
||||||
|
htmlFor="reset-email"
|
||||||
|
className="mb-1.5 block text-sm font-medium text-grayScale-600"
|
||||||
|
>
|
||||||
|
Email address
|
||||||
|
</label>
|
||||||
|
<Input
|
||||||
|
id="reset-email"
|
||||||
|
type="email"
|
||||||
|
value={email}
|
||||||
|
onChange={(e) => setEmail(e.target.value)}
|
||||||
|
readOnly={emailLocked}
|
||||||
|
required
|
||||||
|
autoComplete="email"
|
||||||
|
disabled={submitting}
|
||||||
|
className="h-11 rounded-xl"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label
|
||||||
|
htmlFor="reset-otp"
|
||||||
|
className="mb-1.5 block text-sm font-medium text-grayScale-600"
|
||||||
|
>
|
||||||
|
Reset code
|
||||||
|
</label>
|
||||||
|
<Input
|
||||||
|
id="reset-otp"
|
||||||
|
type={otpLocked ? "password" : "text"}
|
||||||
|
value={otp}
|
||||||
|
onChange={(e) => setOtp(e.target.value)}
|
||||||
|
readOnly={otpLocked}
|
||||||
|
required
|
||||||
|
autoComplete="one-time-code"
|
||||||
|
disabled={submitting}
|
||||||
|
className="h-11 rounded-xl"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label
|
||||||
|
htmlFor="reset-password"
|
||||||
|
className="mb-1.5 block text-sm font-medium text-grayScale-600"
|
||||||
|
>
|
||||||
|
New password
|
||||||
|
</label>
|
||||||
|
<div className="relative">
|
||||||
|
<Input
|
||||||
|
id="reset-password"
|
||||||
|
type={showPassword ? "text" : "password"}
|
||||||
|
value={password}
|
||||||
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
|
required
|
||||||
|
minLength={8}
|
||||||
|
autoComplete="new-password"
|
||||||
|
disabled={submitting}
|
||||||
|
className="h-11 rounded-xl pr-11"
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="absolute right-3 top-1/2 -translate-y-1/2 text-grayScale-400 hover:text-grayScale-600"
|
||||||
|
onClick={() => setShowPassword((v) => !v)}
|
||||||
|
aria-label={showPassword ? "Hide password" : "Show password"}
|
||||||
|
>
|
||||||
|
{showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<p className="mt-1 text-xs text-grayScale-400">At least 8 characters</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label
|
||||||
|
htmlFor="reset-confirm"
|
||||||
|
className="mb-1.5 block text-sm font-medium text-grayScale-600"
|
||||||
|
>
|
||||||
|
Confirm password
|
||||||
|
</label>
|
||||||
|
<Input
|
||||||
|
id="reset-confirm"
|
||||||
|
type={showPassword ? "text" : "password"}
|
||||||
|
value={confirmPassword}
|
||||||
|
onChange={(e) => setConfirmPassword(e.target.value)}
|
||||||
|
required
|
||||||
|
minLength={8}
|
||||||
|
autoComplete="new-password"
|
||||||
|
disabled={submitting}
|
||||||
|
className="h-11 rounded-xl"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{error ? (
|
||||||
|
<div className="space-y-2 rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700">
|
||||||
|
<p>{error}</p>
|
||||||
|
{(error.toLowerCase().includes("expired") ||
|
||||||
|
error.toLowerCase().includes("already used") ||
|
||||||
|
error.toLowerCase().includes("invalid reset")) && (
|
||||||
|
<Link
|
||||||
|
to="/forgot-password"
|
||||||
|
className="inline-block font-semibold text-red-800 underline"
|
||||||
|
>
|
||||||
|
Request a new reset link
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
<Button
|
||||||
|
type="submit"
|
||||||
|
disabled={submitting || !canSubmit}
|
||||||
|
className="mt-2 h-11 w-full rounded-xl text-sm font-semibold tracking-wide"
|
||||||
|
>
|
||||||
|
{submitting ? (
|
||||||
|
<span className="inline-flex items-center gap-2">
|
||||||
|
<SpinnerIcon className="h-4 w-4" />
|
||||||
|
Saving…
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
"Reset password"
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
</form>
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
<p className="mt-10 text-center text-xs text-grayScale-400">
|
||||||
|
© {new Date().getFullYear()} Yimaru Academy · All rights reserved
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
@ -64,10 +64,7 @@ import { DEFAULT_TABLE_PAGE_SIZE, TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tabl
|
||||||
|
|
||||||
const STATUS_FILTERS: { value: PaymentStatus; label: string }[] = [
|
const STATUS_FILTERS: { value: PaymentStatus; label: string }[] = [
|
||||||
{ value: "PENDING", label: "Pending" },
|
{ value: "PENDING", label: "Pending" },
|
||||||
{ value: "PROCESSING", label: "Processing" },
|
|
||||||
{ value: "SUCCESS", label: "Success" },
|
{ value: "SUCCESS", label: "Success" },
|
||||||
{ value: "FAILED", label: "Failed" },
|
|
||||||
{ value: "CANCELLED", label: "Cancelled" },
|
|
||||||
{ value: "EXPIRED", label: "Expired" },
|
{ value: "EXPIRED", label: "Expired" },
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -137,10 +137,10 @@ function LoadingSkeleton() {
|
||||||
return (
|
return (
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
<div className="h-5 w-32 animate-pulse rounded bg-grayScale-100" />
|
<div className="h-5 w-32 animate-pulse rounded bg-grayScale-100" />
|
||||||
<div className="grid gap-6 lg:grid-cols-[340px_1fr]">
|
<div className="grid gap-6 lg:grid-cols-2">
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
<div className="h-80 animate-pulse rounded-2xl bg-grayScale-100" />
|
<div className="h-80 animate-pulse rounded-2xl bg-grayScale-100" />
|
||||||
<div className="h-64 animate-pulse rounded-2xl bg-grayScale-100" />
|
<div className="h-48 animate-pulse rounded-2xl bg-grayScale-100" />
|
||||||
</div>
|
</div>
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
<div className="h-56 animate-pulse rounded-2xl bg-grayScale-100" />
|
<div className="h-56 animate-pulse rounded-2xl bg-grayScale-100" />
|
||||||
|
|
@ -219,12 +219,10 @@ export function UserDetailPage() {
|
||||||
void loadLearningActivity();
|
void loadLearningActivity();
|
||||||
}, [id]);
|
}, [id]);
|
||||||
|
|
||||||
useEffect(() => {
|
const refreshSubscriptions = async () => {
|
||||||
if (!id) return;
|
|
||||||
const userId = Number(id);
|
const userId = Number(id);
|
||||||
if (Number.isNaN(userId)) return;
|
if (!Number.isFinite(userId) || userId <= 0) return;
|
||||||
|
|
||||||
const loadSubscriptions = async () => {
|
|
||||||
setSubscriptionsLoading(true);
|
setSubscriptionsLoading(true);
|
||||||
setSubscriptionsError(null);
|
setSubscriptionsError(null);
|
||||||
try {
|
try {
|
||||||
|
|
@ -239,7 +237,12 @@ export function UserDetailPage() {
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
void loadSubscriptions();
|
useEffect(() => {
|
||||||
|
if (!id) return;
|
||||||
|
const userId = Number(id);
|
||||||
|
if (Number.isNaN(userId)) return;
|
||||||
|
void refreshSubscriptions();
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
}, [id]);
|
}, [id]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
|
@ -360,8 +363,8 @@ export function UserDetailPage() {
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="grid gap-6 lg:grid-cols-[340px_1fr]">
|
<div className="grid gap-6 lg:grid-cols-2 lg:items-start">
|
||||||
<div className="space-y-6">
|
<div className="min-w-0 space-y-6">
|
||||||
<Card className="overflow-hidden shadow-soft">
|
<Card className="overflow-hidden shadow-soft">
|
||||||
<CardContent className="space-y-5 p-5">
|
<CardContent className="space-y-5 p-5">
|
||||||
<div className="flex items-center gap-4">
|
<div className="flex items-center gap-4">
|
||||||
|
|
@ -407,7 +410,7 @@ export function UserDetailPage() {
|
||||||
|
|
||||||
<Separator />
|
<Separator />
|
||||||
|
|
||||||
<div className="grid gap-3 text-sm">
|
<div className="grid gap-3 text-sm sm:grid-cols-2">
|
||||||
<InfoRow label="Joined" value={formatDate(user.created_at)} />
|
<InfoRow label="Joined" value={formatDate(user.created_at)} />
|
||||||
<InfoRow label="Last login" value={formatDateTime(user.last_login, "Never")} />
|
<InfoRow label="Last login" value={formatDateTime(user.last_login, "Never")} />
|
||||||
<InfoRow label="Gender" value={displayValue(user.gender)} />
|
<InfoRow label="Gender" value={displayValue(user.gender)} />
|
||||||
|
|
@ -442,9 +445,13 @@ export function UserDetailPage() {
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
<UserSubscriptionsSection
|
<UserSubscriptionsSection
|
||||||
|
userId={Number(id)}
|
||||||
|
userRole={user.role}
|
||||||
|
userName={[user.first_name, user.last_name].filter(Boolean).join(" ") || user.email}
|
||||||
subscriptions={subscriptions}
|
subscriptions={subscriptions}
|
||||||
loading={subscriptionsLoading}
|
loading={subscriptionsLoading}
|
||||||
error={subscriptionsError}
|
error={subscriptionsError}
|
||||||
|
onRefresh={() => void refreshSubscriptions()}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|
@ -459,7 +466,7 @@ export function UserDetailPage() {
|
||||||
</div>
|
</div>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent className="space-y-5">
|
<CardContent className="space-y-5">
|
||||||
<div className="grid grid-cols-1 gap-x-6 gap-y-4 sm:grid-cols-2 lg:grid-cols-3">
|
<div className="grid grid-cols-1 gap-x-6 gap-y-4 sm:grid-cols-2">
|
||||||
<InfoItem label="Education level" value={displayValue(user.education_level)} />
|
<InfoItem label="Education level" value={displayValue(user.education_level)} />
|
||||||
<InfoItem label="Age group" value={formatAgeGroup(user.age_group)} />
|
<InfoItem label="Age group" value={formatAgeGroup(user.age_group)} />
|
||||||
<InfoItem label="Favorite topic" value={displayValue(user.favoutite_topic)} />
|
<InfoItem label="Favorite topic" value={displayValue(user.favoutite_topic)} />
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,73 @@
|
||||||
|
import { useEffect, useState } from "react"
|
||||||
|
import { toast } from "sonner"
|
||||||
|
import { adminCancelSubscription } from "../../../api/admin-subscriptions.api"
|
||||||
|
import { notifyApiError } from "../../../lib/apiErrors"
|
||||||
|
import { formatPlanCategory } from "../../../lib/subscriptionPlans"
|
||||||
|
import { TypeToConfirmDialog } from "../../../lib/typeToConfirm"
|
||||||
|
import type { UserSubscriptionRecord } from "../../../types/userAdmin.types"
|
||||||
|
|
||||||
|
const CONFIRM_WORD = "CANCEL"
|
||||||
|
|
||||||
|
type CancelSubscriptionDialogProps = {
|
||||||
|
open: boolean
|
||||||
|
onOpenChange: (open: boolean) => void
|
||||||
|
subscription: UserSubscriptionRecord | null
|
||||||
|
onCancelled: () => void
|
||||||
|
}
|
||||||
|
|
||||||
|
export function CancelSubscriptionDialog({
|
||||||
|
open,
|
||||||
|
onOpenChange,
|
||||||
|
subscription,
|
||||||
|
onCancelled,
|
||||||
|
}: CancelSubscriptionDialogProps) {
|
||||||
|
const [cancelling, setCancelling] = useState(false)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) setCancelling(false)
|
||||||
|
}, [open, subscription?.id])
|
||||||
|
|
||||||
|
const handleConfirmCancel = async () => {
|
||||||
|
if (!subscription) return
|
||||||
|
setCancelling(true)
|
||||||
|
try {
|
||||||
|
const res = await adminCancelSubscription(subscription.id)
|
||||||
|
toast.success(res.message || "Subscription cancelled")
|
||||||
|
onCancelled()
|
||||||
|
onOpenChange(false)
|
||||||
|
} catch (err) {
|
||||||
|
notifyApiError(err, "Failed to cancel subscription")
|
||||||
|
} finally {
|
||||||
|
setCancelling(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<TypeToConfirmDialog
|
||||||
|
open={open && subscription != null}
|
||||||
|
onOpenChange={(next) => {
|
||||||
|
if (cancelling) return
|
||||||
|
if (!next) onOpenChange(false)
|
||||||
|
}}
|
||||||
|
title="Are you sure?"
|
||||||
|
description={
|
||||||
|
subscription ? (
|
||||||
|
<>
|
||||||
|
Cancel subscription <strong>#{subscription.id}</strong> (
|
||||||
|
{subscription.plan_name}) for this learner? They will lose access for{" "}
|
||||||
|
<strong>{formatPlanCategory(subscription.plan_category)}</strong> immediately. Paid
|
||||||
|
payment history is kept.
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
"Cancel this subscription? Access ends immediately. Paid payment history is kept."
|
||||||
|
)
|
||||||
|
}
|
||||||
|
confirmWord={CONFIRM_WORD}
|
||||||
|
confirmLabel="Confirm cancel"
|
||||||
|
cancelLabel="Keep subscription"
|
||||||
|
confirming={cancelling}
|
||||||
|
variant="destructive"
|
||||||
|
onConfirm={handleConfirmCancel}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,99 @@
|
||||||
|
import { useEffect, useState } from "react"
|
||||||
|
import { toast } from "sonner"
|
||||||
|
import { adminApplySubscription } from "../../../api/admin-subscriptions.api"
|
||||||
|
import { notifyApiError } from "../../../lib/apiErrors"
|
||||||
|
import { formatPlanCategory } from "../../../lib/subscriptionPlans"
|
||||||
|
import { TypeToConfirmDialog } from "../../../lib/typeToConfirm"
|
||||||
|
import type { UserSubscriptionRecord } from "../../../types/userAdmin.types"
|
||||||
|
|
||||||
|
const CONFIRM_WORD = "EXTEND"
|
||||||
|
|
||||||
|
type ExtendSubscriptionDialogProps = {
|
||||||
|
open: boolean
|
||||||
|
onOpenChange: (open: boolean) => void
|
||||||
|
userId: number
|
||||||
|
subscription: UserSubscriptionRecord | null
|
||||||
|
onExtended: () => void
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatDateTime(value?: string | null): string {
|
||||||
|
if (!value?.trim()) return "—"
|
||||||
|
const parsed = new Date(value)
|
||||||
|
if (Number.isNaN(parsed.getTime())) return "—"
|
||||||
|
return parsed.toLocaleString(undefined, {
|
||||||
|
month: "short",
|
||||||
|
day: "numeric",
|
||||||
|
year: "numeric",
|
||||||
|
hour: "2-digit",
|
||||||
|
minute: "2-digit",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ExtendSubscriptionDialog({
|
||||||
|
open,
|
||||||
|
onOpenChange,
|
||||||
|
userId,
|
||||||
|
subscription,
|
||||||
|
onExtended,
|
||||||
|
}: ExtendSubscriptionDialogProps) {
|
||||||
|
const [saving, setSaving] = useState(false)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) setSaving(false)
|
||||||
|
}, [open, subscription?.id])
|
||||||
|
|
||||||
|
const handleConfirmExtend = async () => {
|
||||||
|
if (!subscription) return
|
||||||
|
|
||||||
|
setSaving(true)
|
||||||
|
try {
|
||||||
|
const res = await adminApplySubscription(userId, {
|
||||||
|
plan_id: subscription.plan_id,
|
||||||
|
})
|
||||||
|
const expiresLabel = res.data?.expires_at
|
||||||
|
? formatDateTime(res.data.expires_at)
|
||||||
|
: null
|
||||||
|
toast.success(
|
||||||
|
expiresLabel
|
||||||
|
? `Subscription extended to ${expiresLabel}`
|
||||||
|
: res.message || "Subscription extended",
|
||||||
|
)
|
||||||
|
onExtended()
|
||||||
|
onOpenChange(false)
|
||||||
|
} catch (err) {
|
||||||
|
notifyApiError(err, "Failed to extend subscription")
|
||||||
|
} finally {
|
||||||
|
setSaving(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<TypeToConfirmDialog
|
||||||
|
open={open && subscription != null}
|
||||||
|
onOpenChange={(next) => {
|
||||||
|
if (saving) return
|
||||||
|
if (!next) onOpenChange(false)
|
||||||
|
}}
|
||||||
|
title="Are you sure?"
|
||||||
|
description={
|
||||||
|
subscription ? (
|
||||||
|
<>
|
||||||
|
Extend <strong>{subscription.plan_name}</strong> (#
|
||||||
|
{subscription.id}) by one plan period? Current expiry:{" "}
|
||||||
|
<strong>{formatDateTime(subscription.expires_at)}</strong>
|
||||||
|
{subscription.plan_category
|
||||||
|
? ` · ${formatPlanCategory(subscription.plan_category)}`
|
||||||
|
: ""}
|
||||||
|
.
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
"Extend this subscription by one plan period?"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
confirmWord={CONFIRM_WORD}
|
||||||
|
confirmLabel="Extend subscription"
|
||||||
|
confirming={saving}
|
||||||
|
onConfirm={handleConfirmExtend}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
336
src/pages/user-management/components/GrantSubscriptionDialog.tsx
Normal file
336
src/pages/user-management/components/GrantSubscriptionDialog.tsx
Normal file
|
|
@ -0,0 +1,336 @@
|
||||||
|
import { useEffect, useMemo, useState } from "react"
|
||||||
|
import { ChevronDown, Gift, Search } from "lucide-react"
|
||||||
|
import { toast } from "sonner"
|
||||||
|
import { adminApplySubscription } from "../../../api/admin-subscriptions.api"
|
||||||
|
import { getSubscriptionPlans } from "../../../api/subscription-plans.api"
|
||||||
|
import { Button } from "../../../components/ui/button"
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from "../../../components/ui/dialog"
|
||||||
|
import { Input } from "../../../components/ui/input"
|
||||||
|
import { SpinnerIcon } from "../../../components/ui/spinner-icon"
|
||||||
|
import { getApiErrorMessage, notifyApiError } from "../../../lib/apiErrors"
|
||||||
|
import {
|
||||||
|
formatPlanCategory,
|
||||||
|
formatPlanDuration,
|
||||||
|
formatPlanPrice,
|
||||||
|
} from "../../../lib/subscriptionPlans"
|
||||||
|
import { TypeToConfirmDialog } from "../../../lib/typeToConfirm"
|
||||||
|
import { cn } from "../../../lib/utils"
|
||||||
|
import type { SubscriptionPlan } from "../../../types/subscription.types"
|
||||||
|
|
||||||
|
const CONFIRM_WORD = "GRANT"
|
||||||
|
|
||||||
|
type GrantSubscriptionDialogProps = {
|
||||||
|
open: boolean
|
||||||
|
onOpenChange: (open: boolean) => void
|
||||||
|
userId: number
|
||||||
|
userName?: string
|
||||||
|
activeByCategory: Record<string, boolean>
|
||||||
|
onGranted: () => void
|
||||||
|
}
|
||||||
|
|
||||||
|
function planLabel(plan: SubscriptionPlan): string {
|
||||||
|
return `${plan.name} · ${formatPlanCategory(plan.category)} · ${formatPlanDuration(plan)} · ${formatPlanPrice(plan)}`
|
||||||
|
}
|
||||||
|
|
||||||
|
export function GrantSubscriptionDialog({
|
||||||
|
open,
|
||||||
|
onOpenChange,
|
||||||
|
userId,
|
||||||
|
userName,
|
||||||
|
activeByCategory,
|
||||||
|
onGranted,
|
||||||
|
}: GrantSubscriptionDialogProps) {
|
||||||
|
const [plans, setPlans] = useState<SubscriptionPlan[]>([])
|
||||||
|
const [plansLoading, setPlansLoading] = useState(false)
|
||||||
|
const [planId, setPlanId] = useState("")
|
||||||
|
const [planSearch, setPlanSearch] = useState("")
|
||||||
|
const [planMenuOpen, setPlanMenuOpen] = useState(false)
|
||||||
|
const [confirmOpen, setConfirmOpen] = useState(false)
|
||||||
|
const [saving, setSaving] = useState(false)
|
||||||
|
const [formError, setFormError] = useState<string | null>(null)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) return
|
||||||
|
setPlanId("")
|
||||||
|
setPlanSearch("")
|
||||||
|
setPlanMenuOpen(false)
|
||||||
|
setConfirmOpen(false)
|
||||||
|
setFormError(null)
|
||||||
|
setSaving(false)
|
||||||
|
|
||||||
|
const loadPlans = async () => {
|
||||||
|
setPlansLoading(true)
|
||||||
|
try {
|
||||||
|
const res = await getSubscriptionPlans()
|
||||||
|
setPlans(res.data.filter((plan) => plan.is_active))
|
||||||
|
} catch (err) {
|
||||||
|
setPlans([])
|
||||||
|
notifyApiError(err, "Failed to load subscription plans")
|
||||||
|
} finally {
|
||||||
|
setPlansLoading(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
void loadPlans()
|
||||||
|
}, [open])
|
||||||
|
|
||||||
|
const selectedPlan = useMemo(
|
||||||
|
() => plans.find((p) => String(p.id) === planId) ?? null,
|
||||||
|
[plans, planId],
|
||||||
|
)
|
||||||
|
|
||||||
|
const categoryBlocked =
|
||||||
|
selectedPlan != null && activeByCategory[selectedPlan.category] === true
|
||||||
|
|
||||||
|
const filteredPlans = useMemo(() => {
|
||||||
|
const q = planSearch.trim().toLowerCase()
|
||||||
|
if (!q) return plans
|
||||||
|
return plans.filter((plan) => {
|
||||||
|
const haystack = [
|
||||||
|
plan.name,
|
||||||
|
plan.category,
|
||||||
|
formatPlanCategory(plan.category),
|
||||||
|
formatPlanDuration(plan),
|
||||||
|
formatPlanPrice(plan),
|
||||||
|
plan.description ?? "",
|
||||||
|
]
|
||||||
|
.join(" ")
|
||||||
|
.toLowerCase()
|
||||||
|
return haystack.includes(q)
|
||||||
|
})
|
||||||
|
}, [plans, planSearch])
|
||||||
|
|
||||||
|
const handleContinue = (e: React.FormEvent) => {
|
||||||
|
e.preventDefault()
|
||||||
|
setFormError(null)
|
||||||
|
|
||||||
|
const id = Number(planId)
|
||||||
|
if (!Number.isFinite(id) || id < 1) {
|
||||||
|
setFormError("Select a subscription plan.")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (categoryBlocked) {
|
||||||
|
setFormError(
|
||||||
|
"This learner already has an active subscription in that category. Extend the existing plan or cancel it first.",
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
setPlanMenuOpen(false)
|
||||||
|
setConfirmOpen(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleConfirmGrant = async () => {
|
||||||
|
const id = Number(planId)
|
||||||
|
if (!Number.isFinite(id) || id < 1 || categoryBlocked) return
|
||||||
|
|
||||||
|
setSaving(true)
|
||||||
|
try {
|
||||||
|
const res = await adminApplySubscription(userId, { plan_id: id })
|
||||||
|
toast.success(res.message || "Subscription granted")
|
||||||
|
setConfirmOpen(false)
|
||||||
|
onGranted()
|
||||||
|
onOpenChange(false)
|
||||||
|
} catch (err) {
|
||||||
|
const detail = getApiErrorMessage(err, "Failed to grant subscription")
|
||||||
|
setFormError(detail)
|
||||||
|
setConfirmOpen(false)
|
||||||
|
notifyApiError(err, "Failed to grant subscription")
|
||||||
|
} finally {
|
||||||
|
setSaving(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Dialog
|
||||||
|
open={open && !confirmOpen}
|
||||||
|
onOpenChange={(next) => {
|
||||||
|
if (saving) return
|
||||||
|
if (!next) {
|
||||||
|
setConfirmOpen(false)
|
||||||
|
onOpenChange(false)
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<DialogContent className="h-auto max-h-[90vh] w-full max-w-lg overflow-y-auto rounded-[12px] border border-grayScale-100 p-0 sm:max-w-xl">
|
||||||
|
<form onSubmit={handleContinue}>
|
||||||
|
<DialogHeader className="border-b border-grayScale-100 px-4 py-4 sm:px-6">
|
||||||
|
<DialogTitle className="flex items-center gap-2 text-lg font-bold text-grayScale-900">
|
||||||
|
<Gift className="h-5 w-5 text-brand-600" aria-hidden />
|
||||||
|
Mark as paid
|
||||||
|
</DialogTitle>
|
||||||
|
<DialogDescription className="text-sm text-grayScale-500">
|
||||||
|
Grant plan access
|
||||||
|
{userName ? ` to ${userName}` : ""}. A payment is recorded at the
|
||||||
|
plan price.
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
<div className="space-y-4 px-6 py-5">
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<label className="text-[11px] font-bold uppercase tracking-wider text-grayScale-400">
|
||||||
|
Plan <span className="text-destructive">*</span>
|
||||||
|
</label>
|
||||||
|
{plansLoading ? (
|
||||||
|
<div className="flex items-center gap-2 text-sm text-grayScale-500">
|
||||||
|
<SpinnerIcon className="h-4 w-4" />
|
||||||
|
Loading plans…
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-2">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="flex h-11 w-full items-center justify-between rounded-[6px] border border-input bg-grayScale-50 px-3 text-left text-sm text-grayScale-700 shadow-sm transition hover:bg-grayScale-100 focus:outline-none focus-visible:border-brand-400 focus-visible:ring-2 focus-visible:ring-brand-200"
|
||||||
|
onClick={() => {
|
||||||
|
setPlanMenuOpen((prev) => !prev)
|
||||||
|
if (planMenuOpen) setPlanSearch("")
|
||||||
|
}}
|
||||||
|
aria-haspopup="listbox"
|
||||||
|
aria-expanded={planMenuOpen}
|
||||||
|
>
|
||||||
|
<span className={cn("truncate", !selectedPlan && "text-grayScale-400")}>
|
||||||
|
{selectedPlan ? planLabel(selectedPlan) : "Select a plan…"}
|
||||||
|
</span>
|
||||||
|
<ChevronDown
|
||||||
|
className={cn(
|
||||||
|
"h-4 w-4 shrink-0 text-grayScale-400 transition-transform",
|
||||||
|
planMenuOpen && "rotate-180",
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{planMenuOpen ? (
|
||||||
|
<div className="rounded-[8px] border border-grayScale-200 bg-white p-2 shadow-sm">
|
||||||
|
<div className="relative mb-2">
|
||||||
|
<Search className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-grayScale-300" />
|
||||||
|
<Input
|
||||||
|
value={planSearch}
|
||||||
|
onChange={(e) => setPlanSearch(e.target.value)}
|
||||||
|
placeholder="Search plans…"
|
||||||
|
className="h-9 rounded-lg border-grayScale-200 pl-8 text-sm"
|
||||||
|
autoFocus
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
className="max-h-[min(16rem,40vh)] space-y-1 overflow-y-auto"
|
||||||
|
role="listbox"
|
||||||
|
>
|
||||||
|
{filteredPlans.map((plan) => {
|
||||||
|
const blocked = activeByCategory[plan.category] === true
|
||||||
|
const selected = String(plan.id) === planId
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={plan.id}
|
||||||
|
type="button"
|
||||||
|
role="option"
|
||||||
|
aria-selected={selected}
|
||||||
|
disabled={blocked}
|
||||||
|
className={cn(
|
||||||
|
"w-full rounded-md px-2 py-2 text-left text-sm transition",
|
||||||
|
blocked && "cursor-not-allowed opacity-50",
|
||||||
|
selected
|
||||||
|
? "bg-brand-100/50 text-brand-700"
|
||||||
|
: "text-grayScale-600 hover:bg-grayScale-100",
|
||||||
|
)}
|
||||||
|
onClick={() => {
|
||||||
|
if (blocked) return
|
||||||
|
setPlanId(String(plan.id))
|
||||||
|
setPlanMenuOpen(false)
|
||||||
|
setPlanSearch("")
|
||||||
|
setFormError(null)
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<span className="block font-medium">{plan.name}</span>
|
||||||
|
<span className="block text-xs text-grayScale-400">
|
||||||
|
{formatPlanCategory(plan.category)} · {formatPlanDuration(plan)} ·{" "}
|
||||||
|
{formatPlanPrice(plan)}
|
||||||
|
{blocked ? " — category active" : ""}
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
{filteredPlans.length === 0 ? (
|
||||||
|
<p className="px-2 py-1.5 text-sm text-grayScale-400">
|
||||||
|
No plans found
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{selectedPlan && categoryBlocked ? (
|
||||||
|
<p className="text-xs text-amber-700">
|
||||||
|
An active {formatPlanCategory(selectedPlan.category)} subscription already
|
||||||
|
exists. Extend or cancel it instead.
|
||||||
|
</p>
|
||||||
|
) : selectedPlan ? (
|
||||||
|
<p className="text-xs text-grayScale-500">
|
||||||
|
Payment recorded: {formatPlanPrice(selectedPlan)}.
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{formError ? <p className="text-sm text-destructive">{formError}</p> : null}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<DialogFooter className="gap-2 border-t border-grayScale-100 px-6 py-4 sm:justify-end">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
className="rounded-[6px]"
|
||||||
|
disabled={saving}
|
||||||
|
onClick={() => onOpenChange(false)}
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="submit"
|
||||||
|
disabled={saving || plansLoading || !planId || categoryBlocked}
|
||||||
|
className="rounded-[6px] bg-brand-500 font-semibold text-white hover:bg-brand-600"
|
||||||
|
>
|
||||||
|
Continue
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</form>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
|
||||||
|
<TypeToConfirmDialog
|
||||||
|
open={confirmOpen}
|
||||||
|
onOpenChange={setConfirmOpen}
|
||||||
|
title="Are you sure?"
|
||||||
|
description={
|
||||||
|
selectedPlan ? (
|
||||||
|
<>
|
||||||
|
Grant <strong>{selectedPlan.name}</strong> (
|
||||||
|
{formatPlanCategory(selectedPlan.category)})
|
||||||
|
{userName ? (
|
||||||
|
<>
|
||||||
|
{" "}
|
||||||
|
to <strong>{userName}</strong>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
" to this learner"
|
||||||
|
)}
|
||||||
|
? A payment of <strong>{formatPlanPrice(selectedPlan)}</strong> will be
|
||||||
|
recorded.
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
"Grant this subscription?"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
confirmWord={CONFIRM_WORD}
|
||||||
|
confirmLabel="Mark as paid"
|
||||||
|
confirming={saving}
|
||||||
|
onConfirm={handleConfirmGrant}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
@ -1,9 +1,8 @@
|
||||||
import { useState } from "react";
|
import { useMemo, useState } from "react"
|
||||||
import { ChevronDown, ChevronRight, CreditCard, RefreshCw } from "lucide-react";
|
import { ChevronDown, ChevronRight, RefreshCw } from "lucide-react"
|
||||||
import { Badge } from "../../../components/ui/badge";
|
import { Button } from "../../../components/ui/button"
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "../../../components/ui/card";
|
import { Card, CardContent } from "../../../components/ui/card"
|
||||||
import { Separator } from "../../../components/ui/separator";
|
import { SpinnerIcon } from "../../../components/ui/spinner-icon"
|
||||||
import { SpinnerIcon } from "../../../components/ui/spinner-icon";
|
|
||||||
import {
|
import {
|
||||||
Table,
|
Table,
|
||||||
TableBody,
|
TableBody,
|
||||||
|
|
@ -11,226 +10,527 @@ import {
|
||||||
TableHead,
|
TableHead,
|
||||||
TableHeader,
|
TableHeader,
|
||||||
TableRow,
|
TableRow,
|
||||||
} from "../../../components/ui/table";
|
} from "../../../components/ui/table"
|
||||||
import { cn } from "../../../lib/utils";
|
import { useTeamPermissions } from "../../../hooks/useTeamPermissions"
|
||||||
import { formatPlanCategory } from "../../../lib/subscriptionPlans";
|
import { displayValue, NOT_ASSIGNED_LABEL } from "../../../lib/displayValue"
|
||||||
import { displayValue, NOT_ASSIGNED_LABEL } from "../../../lib/displayValue";
|
import {
|
||||||
import type { UserSubscriptionsData } from "../../../types/userAdmin.types";
|
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 {
|
function formatPlanTitle(subscription: UserSubscriptionRecord): string {
|
||||||
const value = status.trim();
|
const name = subscription.plan_name?.trim()
|
||||||
if (!value) return NOT_ASSIGNED_LABEL;
|
if (name) return name
|
||||||
return value
|
if (subscription.duration_value && subscription.duration_unit) {
|
||||||
.split("_")
|
const unit = subscription.duration_unit.toLowerCase().replace(/s$/, "")
|
||||||
.map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase())
|
const plural = subscription.duration_value === 1 ? unit : `${unit}s`
|
||||||
.join(" ");
|
return `${subscription.duration_value}-${plural.charAt(0).toUpperCase()}${plural.slice(1)}`
|
||||||
|
}
|
||||||
|
return NOT_ASSIGNED_LABEL
|
||||||
}
|
}
|
||||||
|
|
||||||
function formatCategoryLabel(value: string): string {
|
function formatExpiryDate(value?: string | null): string {
|
||||||
return formatPlanCategory(value);
|
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 {
|
function formatDateTime(value?: string | null): string {
|
||||||
if (!value?.trim()) return NOT_ASSIGNED_LABEL;
|
if (!value?.trim()) return NOT_ASSIGNED_LABEL
|
||||||
const parsed = new Date(value);
|
const parsed = new Date(value)
|
||||||
if (Number.isNaN(parsed.getTime())) return NOT_ASSIGNED_LABEL;
|
if (Number.isNaN(parsed.getTime())) return NOT_ASSIGNED_LABEL
|
||||||
return parsed.toLocaleString(undefined, {
|
return parsed.toLocaleString(undefined, {
|
||||||
month: "short",
|
month: "short",
|
||||||
day: "numeric",
|
day: "numeric",
|
||||||
year: "numeric",
|
year: "numeric",
|
||||||
hour: "2-digit",
|
hour: "2-digit",
|
||||||
minute: "2-digit",
|
minute: "2-digit",
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
function getSubscriptionStatusClasses(status: string): string {
|
function getDaysLeft(expiresAt?: string | null): number | null {
|
||||||
const normalized = status.trim().toUpperCase();
|
if (!expiresAt?.trim()) return null
|
||||||
if (normalized === "ACTIVE" || normalized === "SUCCESS") {
|
const expires = new Date(expiresAt)
|
||||||
return "bg-mint-500/15 text-mint-500 border border-mint-500/25";
|
if (Number.isNaN(expires.getTime())) return null
|
||||||
}
|
const ms = expires.getTime() - Date.now()
|
||||||
if (normalized === "PENDING") {
|
return Math.ceil(ms / 86_400_000)
|
||||||
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 formatDuration(value: number, unit: string): string {
|
function formatDaysLeftLabel(daysLeft: number): string {
|
||||||
if (!value) return NOT_ASSIGNED_LABEL;
|
if (daysLeft <= 0) return "Expired"
|
||||||
const label = unit.trim().toLowerCase();
|
if (daysLeft === 1) return "1 day left"
|
||||||
const plural = value === 1 ? label.replace(/s$/, "") : label.endsWith("s") ? label : `${label}s`;
|
return `${daysLeft} days left`
|
||||||
return `${value} ${plural}`;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function formatMoney(amount: number, currency: string): string {
|
function formatMoney(amount: number, currency: string): string {
|
||||||
if (!Number.isFinite(amount)) return NOT_ASSIGNED_LABEL;
|
if (!Number.isFinite(amount)) return NOT_ASSIGNED_LABEL
|
||||||
const code = currency.trim() || "ETB";
|
const code = currency.trim() || "ETB"
|
||||||
return `${amount.toLocaleString()} ${code}`;
|
return `${amount.toLocaleString()} ${code}`
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatStatusLabel(status: string): string {
|
||||||
|
const value = status.trim()
|
||||||
|
if (!value) return NOT_ASSIGNED_LABEL
|
||||||
|
return value
|
||||||
|
.split("_")
|
||||||
|
.map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase())
|
||||||
|
.join(" ")
|
||||||
|
}
|
||||||
|
|
||||||
|
function ActiveStatusBadge({
|
||||||
|
label,
|
||||||
|
tone,
|
||||||
|
}: {
|
||||||
|
label: string
|
||||||
|
tone: "active" | "pending" | "inactive"
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
"inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-xs font-semibold",
|
||||||
|
tone === "active" && "bg-emerald-50 text-emerald-700",
|
||||||
|
tone === "pending" && "bg-amber-50 text-amber-700",
|
||||||
|
tone === "inactive" && "bg-grayScale-100 text-grayScale-600",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
"h-1.5 w-1.5 rounded-full",
|
||||||
|
tone === "active" && "bg-emerald-500",
|
||||||
|
tone === "pending" && "bg-amber-500",
|
||||||
|
tone === "inactive" && "bg-grayScale-400",
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
{label}
|
||||||
|
</span>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function SubscriptionManageCard({
|
||||||
|
subscription,
|
||||||
|
canExtend,
|
||||||
|
canGrant,
|
||||||
|
canCancel,
|
||||||
|
hasActiveSubscription,
|
||||||
|
onExtend,
|
||||||
|
onGrant,
|
||||||
|
onCancel,
|
||||||
|
}: {
|
||||||
|
subscription: UserSubscriptionRecord
|
||||||
|
canExtend: boolean
|
||||||
|
canGrant: boolean
|
||||||
|
canCancel: boolean
|
||||||
|
hasActiveSubscription: boolean
|
||||||
|
onExtend: () => void
|
||||||
|
onGrant: () => void
|
||||||
|
onCancel: () => void
|
||||||
|
}) {
|
||||||
|
const daysLeft = getDaysLeft(subscription.expires_at)
|
||||||
|
const statusUpper = subscription.status.toUpperCase()
|
||||||
|
const isActive = subscription.is_currently_active || statusUpper === "ACTIVE"
|
||||||
|
const statusTone = isActive ? "active" : statusUpper === "PENDING" ? "pending" : "inactive"
|
||||||
|
const extendEnabled = canExtend && hasActiveSubscription && isActive
|
||||||
|
const cancelEnabled = canCancel && hasActiveSubscription && isActive && statusUpper !== "CANCELLED"
|
||||||
|
const markAsPaidEnabled = canGrant && !hasActiveSubscription
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="rounded-2xl border border-grayScale-200 bg-white p-5 shadow-sm sm:p-6">
|
||||||
|
<div className="flex items-start justify-between gap-3">
|
||||||
|
<h3 className="text-base font-bold text-grayScale-900">Subscription</h3>
|
||||||
|
<ActiveStatusBadge label={formatStatusLabel(subscription.status)} tone={statusTone} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-4 border-t border-grayScale-100 pt-4">
|
||||||
|
<div className="grid gap-5 sm:grid-cols-2">
|
||||||
|
<div>
|
||||||
|
<p className="text-xs font-medium text-grayScale-400">Current Plan</p>
|
||||||
|
<p className="mt-1 text-lg font-bold tracking-tight text-grayScale-900">
|
||||||
|
{formatPlanTitle(subscription)}
|
||||||
|
</p>
|
||||||
|
<p className="mt-0.5 text-xs text-grayScale-500">
|
||||||
|
{formatPlanCategory(subscription.plan_category)}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p className="text-xs font-medium text-grayScale-400">Expires On</p>
|
||||||
|
<div className="mt-1 flex flex-wrap items-center gap-2">
|
||||||
|
<p className="text-lg font-bold tracking-tight text-grayScale-900">
|
||||||
|
{formatExpiryDate(subscription.expires_at)}
|
||||||
|
</p>
|
||||||
|
{daysLeft != null ? (
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
"inline-flex rounded-full px-2 py-0.5 text-[11px] font-semibold",
|
||||||
|
daysLeft <= 0
|
||||||
|
? "bg-destructive/10 text-destructive"
|
||||||
|
: daysLeft <= 14
|
||||||
|
? "bg-orange-50 text-orange-600"
|
||||||
|
: "bg-emerald-50 text-emerald-700",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{formatDaysLeftLabel(daysLeft)}
|
||||||
|
</span>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-6 flex flex-col gap-2">
|
||||||
|
{canExtend ? (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
className="h-10 w-full rounded-xl bg-brand-500 text-sm font-semibold text-white hover:bg-brand-600 disabled:pointer-events-auto disabled:cursor-not-allowed disabled:opacity-50"
|
||||||
|
disabled={!extendEnabled}
|
||||||
|
title={
|
||||||
|
!extendEnabled
|
||||||
|
? "Extend is only available when this learner has an active subscription."
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
|
onClick={onExtend}
|
||||||
|
>
|
||||||
|
<RefreshCw className="mr-2 h-4 w-4" />
|
||||||
|
Extend Subscription
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{(canGrant || canCancel) && (
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
{canGrant ? (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
className="h-10 min-w-0 flex-1 rounded-xl bg-grayScale-100 text-sm font-semibold text-grayScale-700 hover:bg-grayScale-200 disabled:pointer-events-auto disabled:cursor-not-allowed disabled:opacity-50"
|
||||||
|
disabled={!markAsPaidEnabled}
|
||||||
|
title={
|
||||||
|
!markAsPaidEnabled
|
||||||
|
? "Mark as paid is unavailable while this learner already has an active subscription."
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
|
onClick={onGrant}
|
||||||
|
>
|
||||||
|
Mark as Paid
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
{canCancel ? (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
className="h-10 min-w-0 flex-1 rounded-xl border-grayScale-200 bg-white text-sm font-semibold text-grayScale-700 hover:bg-grayScale-50 disabled:pointer-events-auto disabled:cursor-not-allowed disabled:opacity-50"
|
||||||
|
disabled={!cancelEnabled}
|
||||||
|
title={
|
||||||
|
!cancelEnabled
|
||||||
|
? "Cancel is only available when this learner has an active subscription."
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
|
onClick={onCancel}
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function EmptySubscriptionCard({
|
||||||
|
displayStatus,
|
||||||
|
canGrant,
|
||||||
|
canExtend,
|
||||||
|
canCancel,
|
||||||
|
onGrant,
|
||||||
|
}: {
|
||||||
|
displayStatus: string
|
||||||
|
canGrant: boolean
|
||||||
|
canExtend: boolean
|
||||||
|
canCancel: boolean
|
||||||
|
onGrant: () => void
|
||||||
|
}) {
|
||||||
|
const upper = displayStatus.toUpperCase()
|
||||||
|
const tone =
|
||||||
|
upper === "ACTIVE" ? "active" : upper === "PENDING" ? "pending" : "inactive"
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="rounded-2xl border border-grayScale-200 bg-white p-5 shadow-sm sm:p-6">
|
||||||
|
<div className="flex items-start justify-between gap-3">
|
||||||
|
<h3 className="text-base font-bold text-grayScale-900">Subscription</h3>
|
||||||
|
<ActiveStatusBadge
|
||||||
|
label={formatStatusLabel(displayStatus || "Unsubscribed")}
|
||||||
|
tone={tone}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="mt-4 border-t border-grayScale-100 pt-4">
|
||||||
|
<p className="text-sm text-grayScale-500">No active subscription for this learner.</p>
|
||||||
|
</div>
|
||||||
|
<div className="mt-6 flex flex-col gap-2">
|
||||||
|
{canExtend ? (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
className="h-10 w-full rounded-xl bg-brand-500 text-sm font-semibold text-white hover:bg-brand-600 disabled:pointer-events-auto disabled:cursor-not-allowed disabled:opacity-50"
|
||||||
|
disabled
|
||||||
|
title="Extend is only available when this learner has an active subscription."
|
||||||
|
>
|
||||||
|
<RefreshCw className="mr-2 h-4 w-4" />
|
||||||
|
Extend Subscription
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
{(canGrant || canCancel) && (
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
{canGrant ? (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
className="h-10 min-w-0 flex-1 rounded-xl bg-brand-500 text-sm font-semibold text-white hover:bg-brand-600"
|
||||||
|
onClick={onGrant}
|
||||||
|
>
|
||||||
|
Mark as Paid
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
{canCancel ? (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
className="h-10 min-w-0 flex-1 rounded-xl border-grayScale-200 bg-white text-sm font-semibold text-grayScale-700 disabled:pointer-events-auto disabled:cursor-not-allowed disabled:opacity-50"
|
||||||
|
disabled
|
||||||
|
title="Cancel is only available when this learner has an active subscription."
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
export function UserSubscriptionsSection({
|
export function UserSubscriptionsSection({
|
||||||
|
userId,
|
||||||
|
userRole,
|
||||||
|
userName,
|
||||||
subscriptions,
|
subscriptions,
|
||||||
loading,
|
loading,
|
||||||
error,
|
error,
|
||||||
|
onRefresh,
|
||||||
}: {
|
}: {
|
||||||
subscriptions: UserSubscriptionsData | null;
|
userId: number
|
||||||
loading: boolean;
|
userRole?: string
|
||||||
error: string | null;
|
userName?: string
|
||||||
|
subscriptions: UserSubscriptionsData | null
|
||||||
|
loading: boolean
|
||||||
|
error: string | null
|
||||||
|
onRefresh: () => void
|
||||||
}) {
|
}) {
|
||||||
const [open, setOpen] = useState(false);
|
const { permissions } = useTeamPermissions()
|
||||||
const recentPayments = subscriptions?.payments.slice(0, 8) ?? [];
|
const [detailsOpen, setDetailsOpen] = useState(false)
|
||||||
|
const [grantOpen, setGrantOpen] = useState(false)
|
||||||
|
const [extendTarget, setExtendTarget] = useState<UserSubscriptionRecord | null>(null)
|
||||||
|
const [cancelTarget, setCancelTarget] = useState<UserSubscriptionRecord | null>(null)
|
||||||
|
|
||||||
|
const canApply = hasSubscriptionAdminPermission(
|
||||||
|
SUBSCRIPTION_ADMIN_PERMISSIONS.apply,
|
||||||
|
permissions,
|
||||||
|
)
|
||||||
|
const canExtend = canApply
|
||||||
|
const canCancel = hasSubscriptionAdminPermission(
|
||||||
|
SUBSCRIPTION_ADMIN_PERMISSIONS.cancel,
|
||||||
|
permissions,
|
||||||
|
)
|
||||||
|
const learner = isLearnerRole(userRole)
|
||||||
|
const showGrant = canApply && learner
|
||||||
|
const hasActiveSubscription =
|
||||||
|
Boolean(subscriptions?.has_active_subscription) ||
|
||||||
|
(subscriptions?.active_subscriptions.length ?? 0) > 0
|
||||||
|
|
||||||
|
const activePlans = subscriptions?.active_subscriptions ?? []
|
||||||
|
const recentPayments = subscriptions?.payments.slice(0, 12) ?? []
|
||||||
|
const history = useMemo(() => {
|
||||||
|
if (!subscriptions) return []
|
||||||
|
const activeIds = new Set(subscriptions.active_subscriptions.map((s) => s.id))
|
||||||
|
return subscriptions.subscriptions.filter((s) => !activeIds.has(s.id))
|
||||||
|
}, [subscriptions])
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Card className="shadow-soft">
|
<>
|
||||||
<CardHeader className="pb-3">
|
<div className="w-full space-y-4">
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
className="flex w-full items-start justify-between gap-3 text-left"
|
|
||||||
onClick={() => setOpen((prev) => !prev)}
|
|
||||||
aria-expanded={open}
|
|
||||||
>
|
|
||||||
<div className="flex items-start gap-2">
|
|
||||||
<div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-brand-100/50">
|
|
||||||
<CreditCard className="h-4 w-4 text-brand-600" />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<CardTitle className="text-base">Subscriptions</CardTitle>
|
|
||||||
<p className="mt-0.5 text-xs text-grayScale-500">
|
|
||||||
Active plans, billing history, and payment records for this user.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="flex shrink-0 items-center gap-2">
|
|
||||||
{!open && subscriptions ? (
|
|
||||||
<Badge className={cn(getSubscriptionStatusClasses(subscriptions.display_status))}>
|
|
||||||
{formatStatusLabel(subscriptions.display_status)}
|
|
||||||
</Badge>
|
|
||||||
) : null}
|
|
||||||
{open ? (
|
|
||||||
<ChevronDown className="mt-1 h-4 w-4 text-grayScale-400" />
|
|
||||||
) : (
|
|
||||||
<ChevronRight className="mt-1 h-4 w-4 text-grayScale-400" />
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</button>
|
|
||||||
</CardHeader>
|
|
||||||
{open ? (
|
|
||||||
<CardContent className="space-y-4">
|
|
||||||
{loading ? (
|
{loading ? (
|
||||||
<div className="flex items-center gap-2 text-sm text-grayScale-400">
|
<Card className="rounded-2xl border border-grayScale-200 shadow-sm">
|
||||||
|
<CardContent className="flex items-center gap-2 p-6 text-sm text-grayScale-400">
|
||||||
<SpinnerIcon className="h-4 w-4" />
|
<SpinnerIcon className="h-4 w-4" />
|
||||||
Loading subscriptions...
|
Loading subscription…
|
||||||
</div>
|
</CardContent>
|
||||||
|
</Card>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
{error ? <p className="text-sm text-destructive">{error}</p> : null}
|
{error ? (
|
||||||
|
<Card className="rounded-2xl border border-destructive/20 shadow-sm">
|
||||||
|
<CardContent className="p-6 text-sm text-destructive">{error}</CardContent>
|
||||||
|
</Card>
|
||||||
|
) : null}
|
||||||
|
|
||||||
{!loading && !error && subscriptions ? (
|
{!loading && !error && subscriptions ? (
|
||||||
<>
|
<>
|
||||||
<div className="flex items-center justify-between gap-3">
|
{activePlans.length > 0 ? (
|
||||||
<span className="text-sm text-grayScale-500">Overall status</span>
|
<div className="space-y-4">
|
||||||
<Badge className={cn(getSubscriptionStatusClasses(subscriptions.display_status))}>
|
{activePlans.map((subscription) => (
|
||||||
{formatStatusLabel(subscriptions.display_status)}
|
<SubscriptionManageCard
|
||||||
</Badge>
|
key={subscription.id}
|
||||||
|
subscription={subscription}
|
||||||
|
canExtend={canExtend}
|
||||||
|
canGrant={showGrant}
|
||||||
|
canCancel={canCancel}
|
||||||
|
hasActiveSubscription={hasActiveSubscription}
|
||||||
|
onExtend={() => setExtendTarget(subscription)}
|
||||||
|
onGrant={() => setGrantOpen(true)}
|
||||||
|
onCancel={() => setCancelTarget(subscription)}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
) : (
|
||||||
|
<EmptySubscriptionCard
|
||||||
|
displayStatus={subscriptions.display_status}
|
||||||
|
canGrant={showGrant}
|
||||||
|
canExtend={canExtend}
|
||||||
|
canCancel={canCancel}
|
||||||
|
onGrant={() => setGrantOpen(true)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
<div className="flex items-center justify-between gap-3 text-sm">
|
{(history.length > 0 || recentPayments.length > 0) && (
|
||||||
<span className="text-grayScale-500">Active subscription</span>
|
<Card className="rounded-2xl border border-grayScale-200 shadow-sm">
|
||||||
<span className="font-medium text-grayScale-700">
|
<button
|
||||||
{subscriptions.has_active_subscription ? "Yes" : "No"}
|
type="button"
|
||||||
|
className="flex w-full items-center justify-between gap-3 px-5 py-4 text-left"
|
||||||
|
onClick={() => setDetailsOpen((v) => !v)}
|
||||||
|
aria-expanded={detailsOpen}
|
||||||
|
>
|
||||||
|
<span className="text-sm font-semibold text-grayScale-800">
|
||||||
|
History & payments
|
||||||
</span>
|
</span>
|
||||||
</div>
|
{detailsOpen ? (
|
||||||
|
<ChevronDown className="h-4 w-4 text-grayScale-400" />
|
||||||
|
) : (
|
||||||
|
<ChevronRight className="h-4 w-4 text-grayScale-400" />
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
{detailsOpen ? (
|
||||||
|
<CardContent className="space-y-5 border-t border-grayScale-100 px-5 pb-5 pt-4">
|
||||||
{Object.keys(subscriptions.active_by_category).length > 0 ? (
|
{Object.keys(subscriptions.active_by_category).length > 0 ? (
|
||||||
<>
|
|
||||||
<Separator />
|
|
||||||
<div>
|
<div>
|
||||||
<p className="mb-2 text-[11px] font-medium uppercase tracking-wider text-grayScale-400">
|
<p className="mb-2 text-[11px] font-medium uppercase tracking-wider text-grayScale-400">
|
||||||
Access by category
|
Access by category
|
||||||
</p>
|
</p>
|
||||||
<div className="flex flex-wrap gap-2">
|
<div className="flex flex-wrap gap-2">
|
||||||
{Object.entries(subscriptions.active_by_category).map(([category, active]) => (
|
{Object.entries(subscriptions.active_by_category).map(
|
||||||
<Badge
|
([category, active]) => (
|
||||||
|
<span
|
||||||
key={category}
|
key={category}
|
||||||
variant={active ? "default" : "outline"}
|
className={cn(
|
||||||
className={cn(!active && "text-grayScale-500")}
|
"inline-flex rounded-full px-2.5 py-1 text-xs font-semibold",
|
||||||
|
active
|
||||||
|
? "bg-emerald-50 text-emerald-700"
|
||||||
|
: "bg-grayScale-100 text-grayScale-500",
|
||||||
|
)}
|
||||||
>
|
>
|
||||||
{formatCategoryLabel(category)}
|
{formatPlanCategory(category)} {active ? "✓" : "✗"}
|
||||||
</Badge>
|
</span>
|
||||||
))}
|
),
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</>
|
|
||||||
) : null}
|
|
||||||
|
|
||||||
<Separator />
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<p className="mb-2 text-[11px] font-medium uppercase tracking-wider text-grayScale-400">
|
|
||||||
Active plans
|
|
||||||
</p>
|
|
||||||
{subscriptions.active_subscriptions.length === 0 ? (
|
|
||||||
<p className="text-sm text-grayScale-400">No active subscriptions.</p>
|
|
||||||
) : (
|
|
||||||
<div className="space-y-3">
|
|
||||||
{subscriptions.active_subscriptions.map((subscription) => (
|
|
||||||
<div
|
|
||||||
key={subscription.id}
|
|
||||||
className="rounded-xl border border-grayScale-100 bg-grayScale-50/60 p-3"
|
|
||||||
>
|
|
||||||
<div className="flex items-start justify-between gap-3">
|
|
||||||
<div>
|
|
||||||
<p className="text-sm font-semibold text-grayScale-800">{subscription.plan_name}</p>
|
|
||||||
<p className="text-xs text-grayScale-500">
|
|
||||||
{formatCategoryLabel(subscription.plan_category)}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<Badge className={cn(getSubscriptionStatusClasses(subscription.status))}>
|
|
||||||
{formatStatusLabel(subscription.status)}
|
|
||||||
</Badge>
|
|
||||||
</div>
|
|
||||||
<div className="mt-3 grid gap-2 text-xs text-grayScale-600 sm:grid-cols-2">
|
|
||||||
<p>
|
|
||||||
<span className="text-grayScale-400">Price: </span>
|
|
||||||
{formatMoney(subscription.price, subscription.currency)}
|
|
||||||
</p>
|
|
||||||
<p>
|
|
||||||
<span className="text-grayScale-400">Duration: </span>
|
|
||||||
{formatDuration(subscription.duration_value, subscription.duration_unit)}
|
|
||||||
</p>
|
|
||||||
<p>
|
|
||||||
<span className="text-grayScale-400">Starts: </span>
|
|
||||||
{formatDateTime(subscription.starts_at)}
|
|
||||||
</p>
|
|
||||||
<p>
|
|
||||||
<span className="text-grayScale-400">Expires: </span>
|
|
||||||
{formatDateTime(subscription.expires_at)}
|
|
||||||
</p>
|
|
||||||
<p>
|
|
||||||
<span className="text-grayScale-400">Payment: </span>
|
|
||||||
{displayValue(subscription.payment_method)}
|
|
||||||
</p>
|
|
||||||
<p className="inline-flex items-center gap-1">
|
|
||||||
<RefreshCw className="h-3 w-3 text-grayScale-400" />
|
|
||||||
Auto-renew: {subscription.auto_renew ? "On" : "Off"}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{history.length > 0 ? (
|
||||||
|
<div className="space-y-2">
|
||||||
|
<p className="text-[11px] font-medium uppercase tracking-wider text-grayScale-400">
|
||||||
|
Past subscriptions
|
||||||
|
</p>
|
||||||
|
{history.map((subscription) => (
|
||||||
|
<div
|
||||||
|
key={subscription.id}
|
||||||
|
className="flex flex-wrap items-center justify-between gap-2 rounded-xl border border-grayScale-100 px-3 py-2.5"
|
||||||
|
>
|
||||||
|
<div>
|
||||||
|
<p className="text-sm font-medium text-grayScale-800">
|
||||||
|
#{subscription.id} · {formatPlanTitle(subscription)}
|
||||||
|
</p>
|
||||||
|
<p className="text-xs text-grayScale-500">
|
||||||
|
{formatPlanCategory(subscription.plan_category)} ·{" "}
|
||||||
|
{formatExpiryDate(subscription.expires_at)}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
|
<ActiveStatusBadge
|
||||||
|
label={formatStatusLabel(subscription.status)}
|
||||||
|
tone={
|
||||||
|
subscription.status.toUpperCase() === "PENDING"
|
||||||
|
? "pending"
|
||||||
|
: "inactive"
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
{canExtend ? (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
className="h-8 rounded-lg text-xs disabled:pointer-events-auto disabled:cursor-not-allowed disabled:opacity-50"
|
||||||
|
disabled={!hasActiveSubscription || !subscription.is_currently_active}
|
||||||
|
title={
|
||||||
|
!hasActiveSubscription || !subscription.is_currently_active
|
||||||
|
? "Extend is only available for an active subscription."
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
|
onClick={() => setExtendTarget(subscription)}
|
||||||
|
>
|
||||||
|
Extend
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
{canCancel ? (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
className="h-8 rounded-lg text-xs text-destructive disabled:pointer-events-auto disabled:cursor-not-allowed disabled:opacity-50"
|
||||||
|
disabled={
|
||||||
|
!hasActiveSubscription ||
|
||||||
|
!subscription.is_currently_active ||
|
||||||
|
subscription.status.toUpperCase() === "CANCELLED"
|
||||||
|
}
|
||||||
|
title={
|
||||||
|
!hasActiveSubscription || !subscription.is_currently_active
|
||||||
|
? "Cancel is only available for an active subscription."
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
|
onClick={() => setCancelTarget(subscription)}
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
{recentPayments.length > 0 ? (
|
{recentPayments.length > 0 ? (
|
||||||
<>
|
|
||||||
<Separator />
|
|
||||||
<div>
|
<div>
|
||||||
<p className="mb-2 text-[11px] font-medium uppercase tracking-wider text-grayScale-400">
|
<p className="mb-2 text-[11px] font-medium uppercase tracking-wider text-grayScale-400">
|
||||||
Recent payments
|
Recent payments
|
||||||
</p>
|
</p>
|
||||||
<div className="overflow-x-auto rounded-xl border">
|
<div className="overflow-x-auto rounded-xl border border-grayScale-100">
|
||||||
<Table>
|
<Table>
|
||||||
<TableHeader>
|
<TableHeader>
|
||||||
<TableRow>
|
<TableRow>
|
||||||
|
|
@ -250,13 +550,11 @@ export function UserSubscriptionsSection({
|
||||||
<TableCell className="text-sm text-grayScale-700">
|
<TableCell className="text-sm text-grayScale-700">
|
||||||
{formatMoney(payment.amount, payment.currency)}
|
{formatMoney(payment.amount, payment.currency)}
|
||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell>
|
<TableCell className="text-sm text-grayScale-700">
|
||||||
<Badge className={cn(getSubscriptionStatusClasses(payment.status))}>
|
|
||||||
{formatStatusLabel(payment.status)}
|
{formatStatusLabel(payment.status)}
|
||||||
</Badge>
|
|
||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell className="text-xs text-grayScale-500">
|
<TableCell className="text-xs text-grayScale-500">
|
||||||
{displayValue(payment.payment_method)}
|
{formatAdminPaymentMethod(payment.payment_method)}
|
||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell className="text-xs text-grayScale-500">
|
<TableCell className="text-xs text-grayScale-500">
|
||||||
{formatDateTime(payment.paid_at || payment.created_at)}
|
{formatDateTime(payment.paid_at || payment.created_at)}
|
||||||
|
|
@ -267,16 +565,50 @@ export function UserSubscriptionsSection({
|
||||||
</Table>
|
</Table>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</>
|
|
||||||
) : null}
|
|
||||||
</>
|
|
||||||
) : null}
|
|
||||||
|
|
||||||
{!loading && !error && !subscriptions ? (
|
|
||||||
<p className="text-sm text-grayScale-400">No subscription data available.</p>
|
|
||||||
) : null}
|
) : null}
|
||||||
</CardContent>
|
</CardContent>
|
||||||
) : null}
|
) : null}
|
||||||
</Card>
|
</Card>
|
||||||
);
|
)}
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{!loading && !error && !subscriptions ? (
|
||||||
|
<Card className="rounded-2xl border border-grayScale-200 shadow-sm">
|
||||||
|
<CardContent className="p-6 text-sm text-grayScale-400">
|
||||||
|
No subscription data available.
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<GrantSubscriptionDialog
|
||||||
|
open={grantOpen}
|
||||||
|
onOpenChange={setGrantOpen}
|
||||||
|
userId={userId}
|
||||||
|
userName={userName}
|
||||||
|
activeByCategory={subscriptions?.active_by_category ?? {}}
|
||||||
|
onGranted={onRefresh}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<ExtendSubscriptionDialog
|
||||||
|
open={extendTarget != null}
|
||||||
|
onOpenChange={(next) => {
|
||||||
|
if (!next) setExtendTarget(null)
|
||||||
|
}}
|
||||||
|
userId={userId}
|
||||||
|
subscription={extendTarget}
|
||||||
|
onExtended={onRefresh}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<CancelSubscriptionDialog
|
||||||
|
open={cancelTarget != null}
|
||||||
|
onOpenChange={(next) => {
|
||||||
|
if (!next) setCancelTarget(null)
|
||||||
|
}}
|
||||||
|
subscription={cancelTarget}
|
||||||
|
onCancelled={onRefresh}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
35
src/types/adminSubscription.types.ts
Normal file
35
src/types/adminSubscription.types.ts
Normal file
|
|
@ -0,0 +1,35 @@
|
||||||
|
export type AdminSubscriptionStatus = "PENDING" | "ACTIVE" | "EXPIRED" | "CANCELLED" | string
|
||||||
|
|
||||||
|
export interface AdminSubscriptionRes {
|
||||||
|
id: number
|
||||||
|
user_id: number
|
||||||
|
plan_id: number
|
||||||
|
plan_name?: string
|
||||||
|
starts_at: string
|
||||||
|
expires_at: string
|
||||||
|
status: AdminSubscriptionStatus
|
||||||
|
payment_reference?: string
|
||||||
|
payment_method?: string
|
||||||
|
auto_renew: boolean
|
||||||
|
duration_value?: number
|
||||||
|
duration_unit?: string
|
||||||
|
price?: number
|
||||||
|
currency?: string
|
||||||
|
created_at: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Body for unified grant-or-extend. */
|
||||||
|
export interface AdminApplySubscriptionBody {
|
||||||
|
plan_id: number
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @deprecated Prefer AdminApplySubscriptionBody */
|
||||||
|
export type AdminGrantSubscriptionBody = AdminApplySubscriptionBody
|
||||||
|
|
||||||
|
export interface AdminSubscriptionMutationResponse {
|
||||||
|
message?: string
|
||||||
|
data: AdminSubscriptionRes
|
||||||
|
success?: boolean
|
||||||
|
status_code?: number
|
||||||
|
metadata?: unknown
|
||||||
|
}
|
||||||
|
|
@ -139,3 +139,39 @@ export interface ChangeTeamMemberPasswordResponse {
|
||||||
status_code?: number
|
status_code?: number
|
||||||
metadata?: unknown
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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
|
||||||
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue
Block a user