From ffab87858e84c1ed77a85bc928554306fd136e41 Mon Sep 17 00:00:00 2001 From: Yared Yemane Date: Thu, 30 Jul 2026 01:58:46 -0700 Subject: [PATCH] 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 --- .../analytics/SubscriptionRevenueVisuals.tsx | 422 ++++++++++++++++++ src/components/dashboard/RevenueTrendCard.tsx | 127 ++---- src/components/dashboard/StatCard.tsx | 44 +- src/pages/DashboardPage.tsx | 327 ++++++++------ src/pages/analytics/AnalyticsPage.tsx | 117 +++-- 5 files changed, 783 insertions(+), 254 deletions(-) create mode 100644 src/components/analytics/SubscriptionRevenueVisuals.tsx diff --git a/src/components/analytics/SubscriptionRevenueVisuals.tsx b/src/components/analytics/SubscriptionRevenueVisuals.tsx new file mode 100644 index 0000000..29fbf55 --- /dev/null +++ b/src/components/analytics/SubscriptionRevenueVisuals.tsx @@ -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 ( + + + + {pct}% + + + ) +} + +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 ( + + +
+
+ {title} + +
+

{subtitle}

+
+
+ {trailing} +
+
+ {ytdValue} +
+ {ytdLabel ? ( +
+ {ytdLabel} +
+ ) : null} +
+
+
+ {children} +
+ ) +} + +export function MonthlyRevenueAreaChart({ + data, + gradientId = "monthlyRevenueFill", + dataKey = "revenue", + xKey = "month", + height = 240, + yTickFormatter, +}: { + data: Record[] + 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 ( + + + + + + + + + + + + + [`ETB ${Number(value).toLocaleString()}`, "Revenue"]} + contentStyle={chartTooltipStyle} + /> + { + const { cx, cy, index } = props + if (cx == null || cy == null) return null + const highlight = index === peakIndex + return ( + + ) + }} + activeDot={{ r: 6, strokeWidth: 2, stroke: "#fff" }} + /> + + + + ) +} + +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 ( + + + {title} + + + {data.length > 0 && total > 0 ? ( +
+
+ + + + {data.map((entry) => ( + + ))} + + [ + `${Number(value).toLocaleString()} ${countSuffix.toLowerCase()}`, + String(name), + ]} + contentStyle={chartTooltipStyle} + /> + + +
+
+ {data.map((s) => ( +
+ +
+
{s.name}
+
+ {s.value.toLocaleString()} {countSuffix} +
+
+
+ ))} +
+
+ ) : ( +
{emptyMessage}
+ )} +
+
+ ) +} + +export function ActivePlansBreakdownCard({ + title = "Active Plans Breakdown", + data, + className, +}: { + title?: string + data: PieSlice[] + className?: string +}) { + return ( + + ) +} + +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 ( + + + Renewal Rate + + +
+
+ + + + +
+ + {formatPercentRate(renewalRate, 0)} + + Retention +
+
+ +
+
+
+ Auto-Renew + + {autoRenewCount.toLocaleString()} Users + +
+
+
+
+
+
+
+ Canceled + + {cancelledCount.toLocaleString()} Users + +
+
+
0 ? 8 : 0)}%` }} + /> +
+
+
+
+ +
+ +

+ Tip: + {tip} +

+
+ + + ) +} + +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 ( + + {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()}`} + + ) +} diff --git a/src/components/dashboard/RevenueTrendCard.tsx b/src/components/dashboard/RevenueTrendCard.tsx index 35c4a1e..e658681 100644 --- a/src/components/dashboard/RevenueTrendCard.tsx +++ b/src/components/dashboard/RevenueTrendCard.tsx @@ -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 ( - - -
-
-
- Revenue Trend - -
-
- ETB {totalRevenue.toLocaleString()} -
-
Monthly · {year} (ETB)
-
- + } + ytdLabel="YTD" + trailing={ + + } + > + {loading ? ( +
+
- - - {loading ? ( -
- -
- ) : ( - - - - - - - { - if (name !== "revenue") return null - return [`ETB ${Number(value).toLocaleString()}`, "Revenue"] - }} - contentStyle={{ - borderRadius: 12, - border: "1px solid #E0E0E0", - boxShadow: "0 10px 30px rgba(0,0,0,0.08)", - }} - /> - - {chartData.map((entry) => ( - - ))} - - - {chartData.map((entry) => ( - - ))} - - - - - )} -
- + ) : ( + + )} +
) } diff --git a/src/components/dashboard/StatCard.tsx b/src/components/dashboard/StatCard.tsx index 2b68f72..73ca200 100644 --- a/src/components/dashboard/StatCard.tsx +++ b/src/components/dashboard/StatCard.tsx @@ -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 ( - +
-
-
{value}
-
{label}
+
+
+ {label} +
+
+ {value} +
-
+
-
-
- {deltaLabel} - vs Last Month -
+
+ {resolvedTrend === "up" && } + {resolvedTrend === "down" && } + {deltaLabel}
) } - - diff --git a/src/pages/DashboardPage.tsx b/src/pages/DashboardPage.tsx index d44449b..b0ec911 100644 --- a/src/pages/DashboardPage.tsx +++ b/src/pages/DashboardPage.tsx @@ -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 ( +

{children}

+ ) +} 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 ( -
-
-
Dashboard
- -
-
- Welcome, {userFirstName || localStorage.getItem("user_first_name")} +
+
+
+
+ Dashboard +
+

+ Welcome back, {userFirstName || localStorage.getItem("user_first_name") || "there"} +

+

+ Snapshot for {getDashboardFilterLabel(filters)} + {dashboard ? ` · Updated ${generatedAt}` : ""} +

+
+
+ + Full analytics → + + +
{loading ? ( -
+
Loading dashboard…
) : !dashboard ? ( -
+
Failed to load dashboard data.
) : ( <> - {/* Stat tabs */} -
+