Restyle dashboard and subscription analytics to match the revenue mockup.

Add shared revenue/plans/renewal visuals and polish dashboard cards, charts, and section layout.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Yared Yemane 2026-07-30 01:58:46 -07:00
parent f5e0a668a1
commit ffab87858e
5 changed files with 783 additions and 254 deletions

View File

@ -0,0 +1,422 @@
import type { ReactNode } from "react"
import { Lightbulb } from "lucide-react"
import {
Area,
AreaChart,
CartesianGrid,
Cell,
Pie,
PieChart,
ResponsiveContainer,
Tooltip,
XAxis,
YAxis,
} from "recharts"
import { cn } from "../../lib/utils"
import { formatPercentRate } from "../../lib/analytics"
import { Card, CardContent, CardHeader, CardTitle } from "../ui/card"
import { SensitiveChart, SensitiveRevealToggle, SensitiveValue } from "../ui/sensitive-value"
export const SUBSCRIPTION_CHART_COLORS = [
"#8E248D",
"#FFD23F",
"#1DE9B6",
"#60A5FA",
"#C26FC0",
"#F97316",
"#14B8A6",
"#A78BFA",
]
const BRAND = "#8E248D"
const chartTooltipStyle = {
borderRadius: 10,
border: "1px solid #E8E8E8",
boxShadow: "0 8px 24px rgba(0,0,0,0.08)",
fontSize: 12,
}
export const analyticsSoftCardClass =
"rounded-xl border border-grayScale-200/70 bg-white shadow-[0_8px_24px_rgba(15,23,42,0.04)]"
type PieSlice = { name: string; value: number; color: string }
function PiePercentLabel(props: {
cx?: number
cy?: number
midAngle?: number
innerRadius?: number
outerRadius?: number
percent?: number
}) {
const { cx = 0, cy = 0, midAngle = 0, innerRadius = 0, outerRadius = 0, percent = 0 } = props
if (percent < 0.04) return null
const RADIAN = Math.PI / 180
const radius = innerRadius + (outerRadius - innerRadius) * 0.52
const x = cx + radius * Math.cos(-midAngle * RADIAN)
const y = cy + radius * Math.sin(-midAngle * RADIAN)
const pct = Math.round(percent * 100)
return (
<g>
<circle cx={x} cy={y} r={12} fill="#fff" stroke="#F0F0F0" strokeWidth={1} />
<text
x={x}
y={y}
fill="#4B5563"
textAnchor="middle"
dominantBaseline="central"
fontSize={9}
fontWeight={700}
>
{pct}%
</text>
</g>
)
}
export function MonthlyRevenueTrendPanel({
title = "Monthly Revenue Trend",
subtitle = "Revenue growth over the current fiscal year",
ytdLabel,
ytdValue,
trailing,
children,
className,
}: {
title?: string
subtitle?: string
ytdLabel?: string
ytdValue: ReactNode
trailing?: ReactNode
children: ReactNode
className?: string
}) {
return (
<Card className={cn(analyticsSoftCardClass, className)}>
<CardHeader className="flex flex-row flex-wrap items-start justify-between gap-3 space-y-0 pb-2 pt-5">
<div className="min-w-0 space-y-1">
<div className="flex items-center gap-1.5">
<CardTitle className="text-base font-bold text-grayScale-900">{title}</CardTitle>
<SensitiveRevealToggle />
</div>
<p className="text-xs text-grayScale-400">{subtitle}</p>
</div>
<div className="flex items-start gap-3">
{trailing}
<div className="text-right">
<div className="text-xl font-bold tracking-tight text-grayScale-900 sm:text-2xl">
{ytdValue}
</div>
{ytdLabel ? (
<div className="text-[11px] font-medium uppercase tracking-wide text-grayScale-400">
{ytdLabel}
</div>
) : null}
</div>
</div>
</CardHeader>
<CardContent className="px-5 pb-5 pt-1">{children}</CardContent>
</Card>
)
}
export function MonthlyRevenueAreaChart({
data,
gradientId = "monthlyRevenueFill",
dataKey = "revenue",
xKey = "month",
height = 240,
yTickFormatter,
}: {
data: Record<string, string | number>[]
gradientId?: string
dataKey?: string
xKey?: string
height?: number
yTickFormatter?: (value: number) => string
}) {
const peakIndex = data.reduce((best, row, idx) => {
const v = Number(row[dataKey] ?? 0)
const bestV = Number(data[best]?.[dataKey] ?? 0)
return v > bestV ? idx : best
}, 0)
return (
<SensitiveChart>
<ResponsiveContainer width="100%" height={height}>
<AreaChart data={data} margin={{ left: 4, right: 8, top: 12, bottom: 0 }}>
<defs>
<linearGradient id={gradientId} x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stopColor={BRAND} stopOpacity={0.32} />
<stop offset="100%" stopColor={BRAND} stopOpacity={0.02} />
</linearGradient>
</defs>
<CartesianGrid vertical={false} stroke="#EEEEEE" strokeDasharray="4 4" />
<XAxis
dataKey={xKey}
tickLine={false}
axisLine={false}
fontSize={11}
tick={{ fill: "#9E9E9E" }}
/>
<YAxis
tickLine={false}
axisLine={false}
fontSize={11}
width={44}
tick={{ fill: "#9E9E9E" }}
tickFormatter={yTickFormatter}
/>
<Tooltip
formatter={(value) => [`ETB ${Number(value).toLocaleString()}`, "Revenue"]}
contentStyle={chartTooltipStyle}
/>
<Area
type="monotone"
dataKey={dataKey}
stroke={BRAND}
strokeWidth={2.75}
fill={`url(#${gradientId})`}
dot={(props) => {
const { cx, cy, index } = props
if (cx == null || cy == null) return null
const highlight = index === peakIndex
return (
<circle
key={`dot-${index}`}
cx={cx}
cy={cy}
r={highlight ? 5.5 : 3.5}
fill={BRAND}
stroke="#fff"
strokeWidth={highlight ? 2 : 1}
/>
)
}}
activeDot={{ r: 6, strokeWidth: 2, stroke: "#fff" }}
/>
</AreaChart>
</ResponsiveContainer>
</SensitiveChart>
)
}
export function DonutBreakdownCard({
title,
data,
countSuffix = "Users",
emptyMessage = "No data available",
className,
}: {
title: string
data: PieSlice[]
countSuffix?: string
emptyMessage?: string
className?: string
}) {
const total = data.reduce((sum, row) => sum + row.value, 0)
return (
<Card className={cn(analyticsSoftCardClass, className)}>
<CardHeader className="pb-2 pt-5">
<CardTitle className="text-base font-bold text-grayScale-900">{title}</CardTitle>
</CardHeader>
<CardContent className="px-5 pb-5 pt-0">
{data.length > 0 && total > 0 ? (
<div className="grid items-center gap-5 md:grid-cols-[minmax(0,1fr)_minmax(0,1.1fr)]">
<div className="relative mx-auto h-[200px] w-full max-w-[220px]">
<ResponsiveContainer width="100%" height="100%">
<PieChart>
<Pie
data={data}
dataKey="value"
nameKey="name"
innerRadius={58}
outerRadius={82}
paddingAngle={3}
strokeWidth={0}
label={PiePercentLabel}
labelLine={false}
>
{data.map((entry) => (
<Cell key={entry.name} fill={entry.color} />
))}
</Pie>
<Tooltip
formatter={(value, name) => [
`${Number(value).toLocaleString()} ${countSuffix.toLowerCase()}`,
String(name),
]}
contentStyle={chartTooltipStyle}
/>
</PieChart>
</ResponsiveContainer>
</div>
<div className="space-y-3">
{data.map((s) => (
<div key={s.name} className="flex items-start gap-3">
<span
className="mt-0.5 h-10 w-1.5 shrink-0 rounded-full"
style={{ backgroundColor: s.color }}
/>
<div className="min-w-0">
<div className="truncate text-sm font-semibold text-grayScale-800">{s.name}</div>
<div className="text-xs text-grayScale-400">
{s.value.toLocaleString()} {countSuffix}
</div>
</div>
</div>
))}
</div>
</div>
) : (
<div className="py-12 text-center text-xs text-grayScale-400">{emptyMessage}</div>
)}
</CardContent>
</Card>
)
}
export function ActivePlansBreakdownCard({
title = "Active Plans Breakdown",
data,
className,
}: {
title?: string
data: PieSlice[]
className?: string
}) {
return (
<DonutBreakdownCard
title={title}
data={data}
countSuffix="Users"
emptyMessage="No plan data available"
className={className}
/>
)
}
export function RenewalRateCard({
renewalRate,
autoRenewCount,
cancelledCount,
activeNow,
tip = "Enable automated email reminders for manual renewal users to improve retention by estimated 3–5%.",
className,
}: {
renewalRate: number
autoRenewCount: number
cancelledCount: number
activeNow: number
tip?: string
className?: string
}) {
const ratePct = Math.max(0, Math.min(100, renewalRate * 100))
const circumference = 2 * Math.PI * 48
const dash = (ratePct / 100) * circumference
const autoRenewPct =
activeNow > 0 ? Math.min(100, (autoRenewCount / activeNow) * 100) : 0
const cancelledDenom = activeNow + cancelledCount
const cancelledPct =
cancelledDenom > 0 ? Math.min(100, (cancelledCount / cancelledDenom) * 100) : 0
return (
<Card className={cn(analyticsSoftCardClass, className)}>
<CardHeader className="pb-2 pt-5">
<CardTitle className="text-base font-bold text-grayScale-900">Renewal Rate</CardTitle>
</CardHeader>
<CardContent className="px-5 pb-5 pt-0">
<div className="flex flex-col gap-5 sm:flex-row sm:items-center">
<div className="relative mx-auto flex h-40 w-40 shrink-0 items-center justify-center">
<svg viewBox="0 0 120 120" className="h-full w-full -rotate-90">
<circle cx="60" cy="60" r="48" fill="none" stroke="#F0F0F0" strokeWidth="10" />
<circle
cx="60"
cy="60"
r="48"
fill="none"
stroke={BRAND}
strokeWidth="10"
strokeLinecap="round"
strokeDasharray={`${dash.toFixed(1)} ${circumference.toFixed(1)}`}
/>
</svg>
<div className="absolute inset-0 flex flex-col items-center justify-center text-center">
<span className="text-2xl font-bold tracking-tight text-grayScale-900">
{formatPercentRate(renewalRate, 0)}
</span>
<span className="text-[11px] font-medium text-grayScale-400">Retention</span>
</div>
</div>
<div className="min-w-0 flex-1 space-y-4">
<div>
<div className="mb-1.5 flex items-center justify-between gap-2 text-xs">
<span className="font-semibold text-grayScale-800">Auto-Renew</span>
<span className="text-grayScale-400">
{autoRenewCount.toLocaleString()} Users
</span>
</div>
<div className="h-2.5 overflow-hidden rounded-full bg-grayScale-100">
<div
className="h-full rounded-full transition-all"
style={{ width: `${autoRenewPct}%`, backgroundColor: BRAND }}
/>
</div>
</div>
<div>
<div className="mb-1.5 flex items-center justify-between gap-2 text-xs">
<span className="font-semibold text-grayScale-800">Canceled</span>
<span className="text-grayScale-400">
{cancelledCount.toLocaleString()} Users
</span>
</div>
<div className="h-2.5 overflow-hidden rounded-full bg-grayScale-100">
<div
className="h-full rounded-full bg-sky-300 transition-all"
style={{ width: `${Math.max(cancelledPct, cancelledCount > 0 ? 8 : 0)}%` }}
/>
</div>
</div>
</div>
</div>
<div className="mt-5 flex gap-2.5 rounded-xl bg-brand-100/50 px-3.5 py-3 text-xs leading-relaxed text-brand-600">
<Lightbulb className="mt-0.5 h-4 w-4 shrink-0 text-brand-500" />
<p>
<span className="font-semibold">Tip: </span>
{tip}
</p>
</div>
</CardContent>
</Card>
)
}
export function labelCountsToPieSlices(
rows: { label: string; count: number }[],
colors: string[] = SUBSCRIPTION_CHART_COLORS,
): PieSlice[] {
return rows
.filter((row) => row.count > 0)
.map((row, i) => ({
name: row.label,
value: row.count,
color: colors[i % colors.length],
}))
}
export function SensitiveYtdValue({ amount }: { amount: number }) {
return (
<SensitiveValue showToggle={false}>
{amount >= 1_000_000
? `ETB ${(amount / 1_000_000).toFixed(1)}M`
: amount >= 1_000
? `ETB ${(amount / 1_000).toFixed(1)}K`
: `ETB ${amount.toLocaleString()}`}
</SensitiveValue>
)
}

View File

@ -1,17 +1,16 @@
import { useEffect, useMemo, useState } from "react"
import { Bar, CartesianGrid, Cell, ComposedChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts"
import { getDashboard } from "../../api/analytics.api"
import { getYearOptions } from "../analytics/AnalyticsTimeRangeFilter"
import { Card, CardContent, CardHeader, CardTitle } from "../ui/card"
import {
MonthlyRevenueAreaChart,
MonthlyRevenueTrendPanel,
SensitiveYtdValue,
} from "../analytics/SubscriptionRevenueVisuals"
import { Select } from "../ui/select"
import { SensitiveChart, SensitiveRevealToggle, SensitiveValue } from "../ui/sensitive-value"
import { aggregateRevenueByMonth, formatRevenueAxisTick } from "../../lib/analytics"
import type { DateRevenue } from "../../types/analytics.types"
import spinnerSrc from "../../assets/Circular-indeterminate progress indicator.svg"
const TRACK_COLOR = "#E8E8E8"
const BAR_COLOR = "#9E2891"
export function RevenueTrendCard() {
const currentYear = new Date().getFullYear()
const [year, setYear] = useState(currentYear)
@ -47,90 +46,42 @@ export function RevenueTrendCard() {
}
}, [year])
const chartData = useMemo(() => {
const monthly = aggregateRevenueByMonth(dailyRevenue, year)
const peak = Math.max(...monthly.map((point) => point.revenue), 1)
const trackMax = peak * 1.15
return monthly.map((point) => ({
month: point.month,
revenue: point.revenue,
track: trackMax,
}))
}, [dailyRevenue, year])
const chartData = useMemo(
() => aggregateRevenueByMonth(dailyRevenue, year),
[dailyRevenue, year],
)
return (
<Card className="shadow-none">
<CardHeader className="pb-2">
<div className="flex items-start justify-between gap-3">
<div>
<div className="flex items-center gap-1">
<CardTitle>Revenue Trend</CardTitle>
<SensitiveRevealToggle />
</div>
<div className="mt-2 text-2xl font-semibold tracking-tight">
<SensitiveValue showToggle={false}>ETB {totalRevenue.toLocaleString()}</SensitiveValue>
</div>
<div className="text-xs font-medium text-grayScale-500">Monthly · {year} (ETB)</div>
</div>
<Select
value={String(year)}
onChange={(e) => setYear(Number(e.target.value))}
className="h-9 w-[96px] shrink-0 rounded-lg py-1 text-sm font-medium"
aria-label="Revenue trend year"
>
{years.map((optionYear) => (
<option key={optionYear} value={optionYear}>
{optionYear}
</option>
))}
</Select>
<MonthlyRevenueTrendPanel
subtitle={`Revenue growth over ${year}`}
ytdValue={<SensitiveYtdValue amount={totalRevenue} />}
ytdLabel="YTD"
trailing={
<Select
value={String(year)}
onChange={(e) => setYear(Number(e.target.value))}
className="h-8 w-[92px] shrink-0 rounded-lg border-grayScale-200 py-1 text-xs font-medium"
aria-label="Revenue trend year"
>
{years.map((optionYear) => (
<option key={optionYear} value={optionYear}>
{optionYear}
</option>
))}
</Select>
}
>
{loading ? (
<div className="flex h-[240px] items-center justify-center">
<img src={spinnerSrc} alt="" className="h-8 w-8 animate-spin" />
</div>
</CardHeader>
<CardContent className="h-[240px] p-6 pt-2">
{loading ? (
<div className="flex h-full items-center justify-center">
<img src={spinnerSrc} alt="" className="h-8 w-8 animate-spin" />
</div>
) : (
<SensitiveChart>
<ResponsiveContainer width="100%" height="100%">
<ComposedChart data={chartData} margin={{ left: 4, right: 8, top: 8, bottom: 0 }} barGap={-28}>
<CartesianGrid vertical={false} stroke="#E0E0E0" strokeDasharray="4 4" />
<XAxis dataKey="month" tickLine={false} axisLine={false} fontSize={12} />
<YAxis
tickLine={false}
axisLine={false}
fontSize={12}
width={44}
tickFormatter={formatRevenueAxisTick}
/>
<Tooltip
formatter={(value, name) => {
if (name !== "revenue") return null
return [`ETB ${Number(value).toLocaleString()}`, "Revenue"]
}}
contentStyle={{
borderRadius: 12,
border: "1px solid #E0E0E0",
boxShadow: "0 10px 30px rgba(0,0,0,0.08)",
}}
/>
<Bar dataKey="track" barSize={28} radius={[8, 8, 0, 0]} isAnimationActive={false}>
{chartData.map((entry) => (
<Cell key={`track-${entry.month}`} fill={TRACK_COLOR} />
))}
</Bar>
<Bar dataKey="revenue" barSize={28} radius={[8, 8, 0, 0]}>
{chartData.map((entry) => (
<Cell key={`revenue-${entry.month}`} fill={BAR_COLOR} />
))}
</Bar>
</ComposedChart>
</ResponsiveContainer>
</SensitiveChart>
)}
</CardContent>
</Card>
) : (
<MonthlyRevenueAreaChart
data={chartData}
gradientId="dashboardMonthlyRevenueFill"
yTickFormatter={formatRevenueAxisTick}
/>
)}
</MonthlyRevenueTrendPanel>
)
}

View File

@ -1,7 +1,9 @@
import type { LucideIcon } from "lucide-react"
import type { ReactNode } from "react"
import { TrendingDown, TrendingUp } from "lucide-react"
import { cn } from "../../lib/utils"
import { Card, CardContent } from "../ui/card"
import { analyticsSoftCardClass } from "../analytics/SubscriptionRevenueVisuals"
export function StatCard({
icon: Icon,
@ -9,35 +11,53 @@ export function StatCard({
value,
deltaLabel,
deltaPositive,
trend = "auto",
}: {
icon: LucideIcon
label: string
value: ReactNode
deltaLabel: string
deltaPositive: boolean
trend?: "up" | "down" | "neutral" | "auto"
}) {
const resolvedTrend =
trend === "auto" ? (deltaPositive ? "up" : "down") : trend
return (
<Card className="shadow-none">
<Card
className={cn(
analyticsSoftCardClass,
"transition-all duration-200 hover:-translate-y-0.5 hover:shadow-[0_12px_32px_rgba(15,23,42,0.08)]",
)}
>
<CardContent className="p-5">
<div className="flex items-start justify-between gap-3">
<div>
<div className="text-2xl font-semibold tracking-tight">{value}</div>
<div className="mt-1 text-xs font-medium text-grayScale-500">{label}</div>
<div className="min-w-0">
<div className="text-xs font-semibold uppercase tracking-wide text-grayScale-400">
{label}
</div>
<div className="mt-1.5 text-[1.75rem] font-semibold leading-none tracking-tight text-grayScale-900">
{value}
</div>
</div>
<div className="grid h-11 w-11 place-items-center rounded-xl bg-brand-100/60 text-brand-600">
<div className="grid h-11 w-11 shrink-0 place-items-center rounded-xl bg-brand-100/60 text-brand-600 ring-1 ring-brand-100/80">
<Icon className="h-5 w-5" />
</div>
</div>
<div className="border-t border-grayScale-200 mt-4 pt-3">
<div className="text-xs font-medium">
<span className={cn(deltaPositive ? "text-mint-500" : "text-destructive")}>{deltaLabel}</span>
<span className="text-grayScale-400"> vs Last Month</span>
</div>
<div
className={cn(
"mt-4 flex items-center gap-1 border-t border-grayScale-100 pt-3 text-xs font-medium",
resolvedTrend === "up" && "text-mint-500",
resolvedTrend === "down" && "text-destructive",
resolvedTrend === "neutral" && "text-grayScale-400",
)}
>
{resolvedTrend === "up" && <TrendingUp className="h-3 w-3 shrink-0" />}
{resolvedTrend === "down" && <TrendingDown className="h-3 w-3 shrink-0" />}
<span className="line-clamp-2">{deltaLabel}</span>
</div>
</CardContent>
</Card>
)
}

View File

@ -20,9 +20,6 @@ import {
Area,
AreaChart,
CartesianGrid,
Cell,
Pie,
PieChart,
ResponsiveContainer,
Tooltip,
XAxis,
@ -30,6 +27,14 @@ import {
} from "recharts"
import { RevenueTrendCard } from "../components/dashboard/RevenueTrendCard"
import { StatCard } from "../components/dashboard/StatCard"
import {
ActivePlansBreakdownCard,
RenewalRateCard,
DonutBreakdownCard,
analyticsSoftCardClass,
labelCountsToPieSlices,
SUBSCRIPTION_CHART_COLORS,
} from "../components/analytics/SubscriptionRevenueVisuals"
import alertSrc from "../assets/Alert.svg"
import { Badge } from "../components/ui/badge"
import { Card, CardContent, CardHeader, CardTitle } from "../components/ui/card"
@ -39,9 +44,9 @@ import { getTeamMemberById } from "../api/team.api"
import { getDashboard } from "../api/analytics.api"
import { getSubscriptionPlans } from "../api/subscription-plans.api"
import { getRatingSummary, listRatingsByTarget } from "../api/ratings.api"
import { useEffect, useState } from "react"
import { useEffect, useState, type ReactNode } from "react"
import { Link } from "react-router-dom"
import { AnalyticsTimeRangeFilter } from "../components/analytics/AnalyticsTimeRangeFilter"
import { AnalyticsTimeRangeFilter, getDashboardFilterLabel } from "../components/analytics/AnalyticsTimeRangeFilter"
import {
getPrimaryQuestionTypeSummary,
getSeriesPeriodLabel,
@ -55,7 +60,20 @@ import { formatPlanDuration } from "../lib/subscriptionPlans"
import type { SubscriptionPlan } from "../types/subscription.types"
import type { Rating, RatingSummary } from "../types/ratings.types"
const PIE_COLORS = ["#9E2891", "#FFD23F", "#1DE9B6", "#C26FC0", "#6366F1", "#F97316", "#14B8A6", "#EF4444"]
const PIE_COLORS = SUBSCRIPTION_CHART_COLORS
const CHART_BRAND = SUBSCRIPTION_CHART_COLORS[0]
const chartTooltipStyle = {
borderRadius: 10,
border: "1px solid #E8E8E8",
boxShadow: "0 8px 24px rgba(0,0,0,0.08)",
fontSize: 12,
}
function DashboardSectionTitle({ children }: { children: ReactNode }) {
return (
<h2 className="text-xs font-semibold uppercase tracking-wider text-grayScale-400">{children}</h2>
)
}
function formatDate(dateStr: string) {
const d = new Date(dateStr)
@ -173,31 +191,59 @@ export function DashboardPage() {
? getSubscriptionMetrics(dashboard.subscriptions)
: null
const generatedAt = dashboard
? new Date(dashboard.generated_at).toLocaleString("en-US", {
month: "short",
day: "numeric",
hour: "2-digit",
minute: "2-digit",
})
: ""
const registrationPeakIndex = registrationData.reduce((best, row, idx) => {
return row.count > (registrationData[best]?.count ?? 0) ? idx : best
}, 0)
return (
<SensitiveRevealProvider>
<div className="mx-auto w-full min-w-0 max-w-6xl">
<div className="mb-2 flex flex-wrap items-center justify-between gap-3">
<div className="text-sm font-semibold text-grayScale-500">Dashboard</div>
<AnalyticsTimeRangeFilter value={filters} onChange={setFilters} />
</div>
<div className="mb-5 text-2xl font-semibold tracking-tight">
Welcome, {userFirstName || localStorage.getItem("user_first_name")}
<div className="mx-auto w-full min-w-0 max-w-[1280px] px-2 pb-8 sm:px-4">
<div className="mb-7 flex flex-wrap items-end justify-between gap-4">
<div>
<div className="mb-1 text-xs font-semibold uppercase tracking-wide text-grayScale-400">
Dashboard
</div>
<h1 className="text-3xl font-semibold tracking-tight text-grayScale-900">
Welcome back, {userFirstName || localStorage.getItem("user_first_name") || "there"}
</h1>
<p className="mt-1.5 text-sm text-grayScale-500">
Snapshot for {getDashboardFilterLabel(filters)}
{dashboard ? ` · Updated ${generatedAt}` : ""}
</p>
</div>
<div className="flex flex-wrap items-center gap-3">
<Link
to="/analytics"
className="text-xs font-semibold text-brand-600 transition-colors hover:text-brand-500"
>
Full analytics →
</Link>
<AnalyticsTimeRangeFilter value={filters} onChange={setFilters} />
</div>
</div>
{loading ? (
<div className="flex flex-col items-center justify-center gap-3 py-20">
<div className="flex flex-col items-center justify-center gap-3 rounded-2xl border border-grayScale-100 bg-white py-24 shadow-sm">
<img src={spinnerSrc} alt="" className="h-10 w-10 animate-spin" />
<span className="text-sm font-medium text-grayScale-400">Loading dashboard…</span>
</div>
) : !dashboard ? (
<div className="flex flex-col items-center justify-center gap-3 py-20">
<div className="flex flex-col items-center justify-center gap-3 rounded-2xl border border-red-100 bg-red-50/40 py-24">
<img src={alertSrc} alt="" className="h-12 w-12" />
<span className="text-sm font-medium text-destructive">Failed to load dashboard data.</span>
</div>
) : (
<>
{/* Stat tabs */}
<div className="mb-3 border-b border-grayScale-200">
<div className="mb-6 rounded-2xl border border-grayScale-100 bg-white px-5 pt-4 shadow-sm">
<div className="-mb-px flex gap-6">
<button
type="button"
@ -234,7 +280,7 @@ export function DashboardPage() {
{/* Stat Cards */}
{activeStatTab === "primary" && (
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
<div className="mb-8 grid gap-4 md:grid-cols-2 lg:grid-cols-4">
<StatCard
icon={Users}
label="Total Users"
@ -272,7 +318,7 @@ export function DashboardPage() {
{/* Secondary Stats */}
{activeStatTab === "secondary" && subscriptionMetrics && (
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
<div className="mb-8 grid gap-4 md:grid-cols-2 lg:grid-cols-4">
<StatCard
icon={CreditCard}
label="Total Subscriptions"
@ -297,6 +343,7 @@ export function DashboardPage() {
: "Total minus active"
}
deltaPositive={subscriptionMetrics.inactive === 0}
trend="neutral"
/>
<StatCard
icon={Video}
@ -321,6 +368,7 @@ export function DashboardPage() {
value={dashboard.notifications.total_sent.toLocaleString()}
deltaLabel={`${dashboard.notifications.unread_count} unread`}
deltaPositive={dashboard.notifications.unread_count === 0}
trend={dashboard.notifications.unread_count > 0 ? "neutral" : "up"}
/>
<StatCard
icon={UsersRound}
@ -328,134 +376,157 @@ export function DashboardPage() {
value={dashboard.team.total_members.toLocaleString()}
deltaLabel={`${dashboard.team.by_role.length} roles`}
deltaPositive
trend="neutral"
/>
</div>
)}
{/* User Registrations Chart */}
<div className="mt-5 grid gap-4">
<Card className="shadow-none">
<CardHeader className="pb-2">
<div className="flex items-center justify-between gap-3">
<div className="space-y-8">
<section className="space-y-4">
<DashboardSectionTitle>Growth</DashboardSectionTitle>
<Card className={cn(analyticsSoftCardClass)}>
<CardHeader className="pb-2 pt-5">
<div className="flex items-start justify-between gap-3">
<div>
<CardTitle>User Registrations</CardTitle>
<div className="mt-1 text-2xl font-semibold tracking-tight">
<CardTitle className="text-base font-bold text-grayScale-900">
User Registrations
</CardTitle>
<p className="mt-1 text-xs text-grayScale-400">
New sign-ups over {seriesPeriodLabel.toLowerCase()}
</p>
<div className="mt-3 text-2xl font-bold tracking-tight text-grayScale-900">
{dashboard.users.total_users.toLocaleString()}
</div>
<div className="text-xs font-medium text-mint-500">
<div className="mt-1 text-xs font-medium text-mint-500">
+{dashboard.users.new_today} today · +{dashboard.users.new_week} this week
</div>
</div>
<div className="rounded-full bg-grayScale-100 px-3 py-1 text-xs font-semibold text-grayScale-500">
<Badge variant="secondary" className="shrink-0 font-semibold">
{seriesPeriodLabel}
</div>
</Badge>
</div>
</CardHeader>
<CardContent className="h-[280px] p-6 pt-2">
<CardContent className="h-[280px] px-5 pb-5 pt-2">
<ResponsiveContainer width="100%" height="100%">
<AreaChart data={registrationData} margin={{ left: 8, right: 8, top: 8, bottom: 0 }}>
<AreaChart data={registrationData} margin={{ left: 4, right: 8, top: 12, bottom: 0 }}>
<defs>
<linearGradient id="fillBrand" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stopColor="#9E2891" stopOpacity={0.25} />
<stop offset="100%" stopColor="#9E2891" stopOpacity={0.02} />
<linearGradient id="dashboardRegFill" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stopColor={CHART_BRAND} stopOpacity={0.32} />
<stop offset="100%" stopColor={CHART_BRAND} stopOpacity={0.02} />
</linearGradient>
</defs>
<CartesianGrid vertical={false} stroke="#E0E0E0" strokeDasharray="4 4" />
<XAxis dataKey="date" tickLine={false} axisLine={false} fontSize={12} />
<YAxis tickLine={false} axisLine={false} fontSize={12} width={32} allowDecimals={false} />
<Tooltip
contentStyle={{
borderRadius: 12,
border: "1px solid #E0E0E0",
boxShadow: "0 10px 30px rgba(0,0,0,0.08)",
}}
<CartesianGrid vertical={false} stroke="#EEEEEE" strokeDasharray="4 4" />
<XAxis
dataKey="date"
tickLine={false}
axisLine={false}
fontSize={11}
tick={{ fill: "#9E9E9E" }}
/>
<YAxis
tickLine={false}
axisLine={false}
fontSize={11}
width={36}
allowDecimals={false}
tick={{ fill: "#9E9E9E" }}
/>
<Tooltip contentStyle={chartTooltipStyle} />
<Area
type="monotone"
dataKey="count"
stroke="#9E2891"
strokeWidth={2}
fill="url(#fillBrand)"
stroke={CHART_BRAND}
strokeWidth={2.75}
fill="url(#dashboardRegFill)"
dot={(props) => {
const { cx, cy, index } = props
if (cx == null || cy == null) return null
const highlight = index === registrationPeakIndex
return (
<circle
key={`reg-dot-${index}`}
cx={cx}
cy={cy}
r={highlight ? 5.5 : 3.5}
fill={CHART_BRAND}
stroke="#fff"
strokeWidth={highlight ? 2 : 1}
/>
)
}}
activeDot={{ r: 6, strokeWidth: 2, stroke: "#fff" }}
/>
</AreaChart>
</ResponsiveContainer>
</CardContent>
</Card>
</section>
<div className="grid gap-4 lg:grid-cols-2">
{/* Subscription / Issue Status Pie */}
<Card className="shadow-none">
<CardHeader className="pb-2">
<CardTitle>
{subscriptionStatusData.length > 0 ? "Subscription Status" : "Issue Status"}
</CardTitle>
</CardHeader>
<CardContent className="grid gap-4 p-6 pt-2 md:grid-cols-2">
{(subscriptionStatusData.length > 0 ? subscriptionStatusData : issueStatusData).length > 0 ? (
<>
<div className="h-[180px]">
<ResponsiveContainer width="100%" height="100%">
<PieChart>
<Pie
data={subscriptionStatusData.length > 0 ? subscriptionStatusData : issueStatusData}
dataKey="value"
nameKey="name"
innerRadius={55}
outerRadius={80}
paddingAngle={2}
>
{(subscriptionStatusData.length > 0 ? subscriptionStatusData : issueStatusData).map(
(entry) => (
<Cell key={entry.name} fill={entry.color} />
),
)}
</Pie>
<Tooltip
contentStyle={{
borderRadius: 12,
border: "1px solid #E0E0E0",
boxShadow: "0 10px 30px rgba(0,0,0,0.08)",
}}
/>
</PieChart>
</ResponsiveContainer>
</div>
<div className="space-y-3">
{(subscriptionStatusData.length > 0 ? subscriptionStatusData : issueStatusData).map((s) => (
<div key={s.name} className="flex items-center justify-between gap-3 text-sm">
<div className="flex items-center gap-2">
<span
className="h-2.5 w-2.5 rounded-full"
style={{ backgroundColor: s.color }}
/>
<span className="text-grayScale-600">{s.name}</span>
</div>
<span className="font-semibold text-grayScale-600">{s.value.toLocaleString()}</span>
</div>
))}
</div>
</>
) : (
<div className="col-span-2 flex items-center justify-center py-10 text-sm text-grayScale-400">
No data available
</div>
)}
</CardContent>
</Card>
<section className="space-y-4">
<DashboardSectionTitle>Revenue &amp; subscriptions</DashboardSectionTitle>
<div className="grid gap-4">
<RevenueTrendCard />
</div>
{/* Subscription plans (from catalog API) */}
<Card className="shadow-none">
<CardHeader className="pb-2">
<div className="grid gap-4 lg:grid-cols-2">
<ActivePlansBreakdownCard
data={labelCountsToPieSlices(
(dashboard.subscriptions.active_by_plan?.length
? dashboard.subscriptions.active_by_plan
: dashboard.subscriptions.by_status
).map((row) => ({
label: row.label,
count: row.count,
})),
)}
/>
<RenewalRateCard
renewalRate={dashboard.subscriptions.renewal?.renewal_rate ?? 0}
autoRenewCount={dashboard.subscriptions.snapshot?.auto_renew_enabled ?? 0}
cancelledCount={dashboard.subscriptions.snapshot?.cancelled_now ?? 0}
activeNow={
dashboard.subscriptions.snapshot?.active_now ??
subscriptionMetrics?.active ??
0
}
/>
</div>
<div className="grid gap-4 lg:grid-cols-2">
{subscriptionStatusData.length > 0 ? (
<DonutBreakdownCard
title="Subscription Status"
data={subscriptionStatusData}
countSuffix="Subscriptions"
/>
) : null}
{issueStatusData.length > 0 ? (
<DonutBreakdownCard
title="Issue Status"
data={issueStatusData}
countSuffix="Issues"
/>
) : null}
</div>
</div>
</section>
<section className="space-y-4">
<DashboardSectionTitle>Catalog &amp; feedback</DashboardSectionTitle>
<Card className={cn(analyticsSoftCardClass)}>
<CardHeader className="pb-2 pt-5">
<div className="flex items-center gap-2">
<CreditCard className="h-5 w-5 text-brand-500" />
<CardTitle>Subscription plans</CardTitle>
<div className="grid h-9 w-9 place-items-center rounded-lg bg-brand-100/60 text-brand-600">
<CreditCard className="h-4 w-4" />
</div>
<div>
<CardTitle className="text-base font-bold text-grayScale-900">
Subscription plans
</CardTitle>
<p className="text-sm text-grayScale-500">Available billing plans for learners.</p>
</div>
</div>
<p className="text-sm text-grayScale-500">Available billing plans for learners.</p>
</CardHeader>
<CardContent className="p-6 pt-2">
<CardContent className="px-5 pb-5 pt-2">
{subscriptionPlansLoading ? (
<div className="flex items-center justify-center py-10">
<img src={spinnerSrc} alt="" className="h-8 w-8 animate-spin" />
@ -469,7 +540,7 @@ export function DashboardPage() {
{subscriptionPlans.map((plan) => (
<div
key={plan.id}
className="flex flex-col rounded-xl border border-grayScale-200 bg-grayScale-50/50 p-4"
className="flex flex-col rounded-xl border border-grayScale-200/80 bg-white p-4 shadow-sm transition-all duration-200 hover:-translate-y-0.5 hover:border-brand-200/60 hover:shadow-md"
>
<div className="flex items-start justify-between gap-2">
<h3 className="font-semibold text-grayScale-700">{plan.name}</h3>
@ -507,23 +578,26 @@ export function DashboardPage() {
</CardContent>
</Card>
{/* App Ratings */}
<Card className="shadow-none">
<CardHeader className="pb-2">
<Card className={cn(analyticsSoftCardClass)}>
<CardHeader className="pb-2 pt-5">
<div className="flex items-center justify-between gap-2">
<div className="flex items-center gap-2">
<MessageSquare className="h-5 w-5 text-brand-500" />
<CardTitle>Recent App Reviews</CardTitle>
<div className="grid h-9 w-9 place-items-center rounded-lg bg-brand-100/60 text-brand-600">
<MessageSquare className="h-4 w-4" />
</div>
<CardTitle className="text-base font-bold text-grayScale-900">
Recent App Reviews
</CardTitle>
</div>
<Link
to="/app-reviews"
className="text-xs font-medium text-brand-600 hover:underline"
className="rounded-lg px-2.5 py-1 text-xs font-semibold text-brand-600 transition-colors hover:bg-brand-100/40"
>
View all
</Link>
</div>
</CardHeader>
<CardContent className="p-6 pt-2">
<CardContent className="px-5 pb-5 pt-2">
{appRatingsLoading ? (
<div className="flex items-center justify-center py-10">
<img src={spinnerSrc} alt="" className="h-8 w-8 animate-spin" />
@ -534,7 +608,7 @@ export function DashboardPage() {
</div>
) : (
<>
<div className="mb-4 flex items-center gap-3 rounded-lg bg-grayScale-50 px-4 py-3">
<div className="mb-4 flex items-center gap-3 rounded-xl border border-grayScale-100 bg-gradient-to-r from-amber-50/80 to-white px-4 py-3">
<div className="flex items-center gap-1">
{Array.from({ length: 5 }).map((_, i) => (
<Star
@ -557,9 +631,9 @@ export function DashboardPage() {
</span>
</div>
<div className="space-y-4">
<div className="divide-y divide-grayScale-100">
{appRatings.map((rating) => (
<div key={rating.id} className="flex gap-3">
<div key={rating.id} className="flex gap-3 py-4 first:pt-0 last:pb-0">
<div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-brand-50 text-xs font-semibold text-brand-600">
U{rating.user_id}
</div>
@ -596,6 +670,7 @@ export function DashboardPage() {
)}
</CardContent>
</Card>
</section>
</div>
</>
)}

View File

@ -43,7 +43,6 @@ import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/ca
import {
SensitiveChart,
SensitiveRevealProvider,
SensitiveRevealToggle,
SensitiveValue,
} from "../../components/ui/sensitive-value"
import { Badge } from "../../components/ui/badge"
@ -51,6 +50,15 @@ import { Button } from "../../components/ui/button"
import { cn } from "../../lib/utils"
import { getDashboard } from "../../api/analytics.api"
import { AnalyticsTimeRangeFilter, getDashboardFilterLabel } from "../../components/analytics/AnalyticsTimeRangeFilter"
import {
ActivePlansBreakdownCard,
MonthlyRevenueAreaChart,
MonthlyRevenueTrendPanel,
RenewalRateCard,
SensitiveYtdValue,
analyticsSoftCardClass,
labelCountsToPieSlices,
} from "../../components/analytics/SubscriptionRevenueVisuals"
import {
getPrimaryQuestionTypeSummary,
getSeriesPeriodLabel,
@ -59,6 +67,8 @@ import {
getVideoLessonsSummary,
formatPercentRate,
buildSubscriptionStatusPie,
aggregateRevenueByMonth,
formatRevenueAxisTick,
} from "../../lib/analytics"
import type { DashboardData, DashboardFilters, LabelCount } from "../../types/analytics.types"
@ -498,6 +508,19 @@ export function AnalyticsPage() {
revenue: d.revenue,
}))
const dateFilter = dashboard.date_filter
const useMonthlyRevenueTrend =
dateFilter?.mode === "year" ||
dateFilter?.mode === "all_time" ||
(filters.mode === "year" || filters.mode === "all_time")
const monthlyTrendYear =
(dateFilter?.mode === "year" && dateFilter.year) ||
(filters.mode === "year" && filters.year) ||
new Date().getFullYear()
const monthlyRevenueTrendData = useMonthlyRevenueTrend
? aggregateRevenueByMonth(payments.revenue_last_30_days, monthlyTrendYear)
: revenueData
const issueStatusPie = issues.by_status.map((s, i) => ({
name: s.label,
value: s.count,
@ -930,8 +953,45 @@ export function AnalyticsPage() {
/>
</div>
)}
<div className="mb-4 space-y-4">
<MonthlyRevenueTrendPanel
subtitle={
useMonthlyRevenueTrend
? `Revenue growth over ${monthlyTrendYear}`
: `Revenue over ${seriesPeriodLabel.toLowerCase()}`
}
ytdValue={<SensitiveYtdValue amount={payments.total_revenue} />}
ytdLabel={useMonthlyRevenueTrend ? "YTD" : "Period"}
>
<MonthlyRevenueAreaChart
data={monthlyRevenueTrendData}
xKey={useMonthlyRevenueTrend ? "month" : "date"}
gradientId="analyticsMonthlyRevenueFill"
height={260}
yTickFormatter={formatRevenueAxisTick}
/>
</MonthlyRevenueTrendPanel>
<div className="grid gap-4 lg:grid-cols-2">
<ActivePlansBreakdownCard
data={labelCountsToPieSlices(
(subscriptions.active_by_plan?.length
? subscriptions.active_by_plan
: subscriptions.by_status
).map((row) => ({ label: row.label, count: row.count })),
)}
/>
<RenewalRateCard
renewalRate={renewal?.renewal_rate ?? 0}
autoRenewCount={snapshot?.auto_renew_enabled ?? 0}
cancelledCount={snapshot?.cancelled_now ?? 0}
activeNow={snapshot?.active_now ?? subscriptionMetrics.active}
/>
</div>
</div>
<div className="grid gap-4 lg:grid-cols-2">
<Card className="shadow-none">
<Card className={analyticsSoftCardClass}>
<CardHeader className="pb-2">
<div className="flex items-center justify-between">
<div>
@ -951,41 +1011,42 @@ export function AnalyticsPage() {
<AreaChart data={subscriptionData} margin={{ left: 8, right: 8, top: 8, bottom: 0 }}>
<defs>
<linearGradient id="gradSub" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stopColor="#6366F1" stopOpacity={0.2} />
<stop offset="100%" stopColor="#6366F1" stopOpacity={0.02} />
<stop offset="0%" stopColor="#8E248D" stopOpacity={0.22} />
<stop offset="100%" stopColor="#8E248D" stopOpacity={0.02} />
</linearGradient>
</defs>
<CartesianGrid vertical={false} stroke="#E0E0E0" strokeDasharray="4 4" />
<XAxis dataKey="date" tickLine={false} axisLine={false} fontSize={11} />
<YAxis tickLine={false} axisLine={false} fontSize={11} width={30} allowDecimals={false} />
<CartesianGrid vertical={false} stroke="#EEEEEE" strokeDasharray="4 4" />
<XAxis dataKey="date" tickLine={false} axisLine={false} fontSize={11} tick={{ fill: "#9E9E9E" }} />
<YAxis tickLine={false} axisLine={false} fontSize={11} width={30} allowDecimals={false} tick={{ fill: "#9E9E9E" }} />
<Tooltip
contentStyle={{
borderRadius: 12,
border: "1px solid #E0E0E0",
boxShadow: "0 10px 30px rgba(0,0,0,0.08)",
borderRadius: 10,
border: "1px solid #E8E8E8",
boxShadow: "0 8px 24px rgba(0,0,0,0.08)",
fontSize: 12,
}}
/>
<Area type="monotone" dataKey="count" stroke="#6366F1" strokeWidth={2} fill="url(#gradSub)" />
<Area
type="monotone"
dataKey="count"
stroke="#8E248D"
strokeWidth={2.5}
fill="url(#gradSub)"
dot={{ r: 3.5, fill: "#8E248D", strokeWidth: 0 }}
/>
</AreaChart>
</ResponsiveContainer>
</CardContent>
</Card>
<Card className="shadow-none">
<Card className={analyticsSoftCardClass}>
<CardHeader className="pb-2">
<div className="flex items-center justify-between">
<div>
<div className="flex items-center gap-1">
<CardTitle>Revenue</CardTitle>
<SensitiveRevealToggle />
<CardTitle>Daily Revenue Detail</CardTitle>
<div className="mt-1 text-xs text-grayScale-400">
Same period as filters · ETB
</div>
<div className="mt-1 text-2xl font-semibold tracking-tight">
<SensitiveValue showToggle={false}>
ETB {payments.total_revenue.toLocaleString()}
</SensitiveValue>
</div>
<div className="text-xs text-grayScale-400">Daily revenue over last 30 days</div>
</div>
<Badge variant="secondary">{seriesPeriodLabel}</Badge>
</div>
@ -994,19 +1055,19 @@ export function AnalyticsPage() {
<SensitiveChart>
<ResponsiveContainer width="100%" height="100%">
<BarChart data={revenueData} margin={{ left: 8, right: 8, top: 8 }}>
<CartesianGrid vertical={false} stroke="#E0E0E0" strokeDasharray="4 4" />
<XAxis dataKey="date" tickLine={false} axisLine={false} fontSize={11} />
<YAxis tickLine={false} axisLine={false} fontSize={11} width={42} />
<CartesianGrid vertical={false} stroke="#EEEEEE" strokeDasharray="4 4" />
<XAxis dataKey="date" tickLine={false} axisLine={false} fontSize={11} tick={{ fill: "#9E9E9E" }} />
<YAxis tickLine={false} axisLine={false} fontSize={11} width={42} tick={{ fill: "#9E9E9E" }} />
<Tooltip
formatter={(v) => [`ETB ${Number(v).toLocaleString()}`, "Revenue"]}
contentStyle={{
borderRadius: 12,
border: "1px solid #E0E0E0",
boxShadow: "0 10px 30px rgba(0,0,0,0.08)",
borderRadius: 10,
border: "1px solid #E8E8E8",
boxShadow: "0 8px 24px rgba(0,0,0,0.08)",
fontSize: 12,
}}
/>
<Bar dataKey="revenue" radius={[6, 6, 0, 0]} fill="#9E2891" />
<Bar dataKey="revenue" radius={[6, 6, 0, 0]} fill="#8E248D" />
</BarChart>
</ResponsiveContainer>
</SensitiveChart>