feat: Implement a new dashboard shell with animated background, refactor dashboard data fetching into a dedicated API route, and introduce new UI components.**

This commit is contained in:
2025-12-10 03:16:36 -05:00
parent ca6484aea5
commit 39fdf16280
24 changed files with 767 additions and 412 deletions

View File

@@ -3,6 +3,7 @@
import { import {
TrendingDown, TrendingDown,
TrendingUp, TrendingUp,
Minus,
DollarSign, DollarSign,
Clock, Clock,
Users, Users,
@@ -15,7 +16,7 @@ interface AnimatedStatsCardProps {
title: string; title: string;
value: string; value: string;
change: string; change: string;
trend: "up" | "down"; trend: "up" | "down" | "neutral";
iconName: IconName; iconName: IconName;
description: string; description: string;
delay?: number; delay?: number;
@@ -42,8 +43,13 @@ export function AnimatedStatsCard({
numericValue, numericValue,
}: AnimatedStatsCardProps) { }: AnimatedStatsCardProps) {
const Icon = iconMap[iconName]; const Icon = iconMap[iconName];
const TrendIcon = trend === "up" ? TrendingUp : TrendingDown;
let TrendIcon = Minus;
if (trend === "up") TrendIcon = TrendingUp;
if (trend === "down") TrendIcon = TrendingDown;
const isPositive = trend === "up"; const isPositive = trend === "up";
const isNeutral = trend === "neutral";
// For now, always use the formatted value prop to ensure correct display // For now, always use the formatted value prop to ensure correct display
// Animation can be added back once the basic display is working correctly // Animation can be added back once the basic display is working correctly
@@ -65,9 +71,11 @@ export function AnimatedStatsCard({
<div <div
className="flex items-center space-x-1 text-xs" className="flex items-center space-x-1 text-xs"
style={{ style={{
color: isPositive color: isNeutral
? "oklch(var(--chart-2))" ? "hsl(var(--muted-foreground))"
: "oklch(var(--chart-3))", : isPositive
? "oklch(var(--chart-2))"
: "oklch(var(--chart-3))",
}} }}
> >
<TrendIcon className="h-3 w-3" /> <TrendIcon className="h-3 w-3" />

View File

@@ -8,8 +8,6 @@ import {
XAxis, XAxis,
YAxis, YAxis,
} from "recharts"; } from "recharts";
import { getEffectiveInvoiceStatus } from "~/lib/invoice-status";
import type { StoredInvoiceStatus } from "~/types/invoice";
import { useAnimationPreferences } from "~/components/providers/animation-preferences-provider"; import { useAnimationPreferences } from "~/components/providers/animation-preferences-provider";
interface Invoice { interface Invoice {
@@ -21,49 +19,16 @@ interface Invoice {
} }
interface RevenueChartProps { interface RevenueChartProps {
invoices: Invoice[]; data: {
month: string;
revenue: number;
monthLabel: string;
}[];
} }
export function RevenueChart({ invoices }: RevenueChartProps) { export function RevenueChart({ data }: RevenueChartProps) {
// Process invoice data to create monthly revenue data // Use data directly
const monthlyData = invoices const chartData = data;
.filter(
(invoice) =>
getEffectiveInvoiceStatus(
invoice.status as StoredInvoiceStatus,
invoice.dueDate,
) === "paid",
)
.reduce(
(acc, invoice) => {
const date = new Date(invoice.issueDate);
const monthKey = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}`;
acc[monthKey] ??= {
month: monthKey,
revenue: 0,
count: 0,
};
acc[monthKey].revenue += invoice.totalAmount;
acc[monthKey].count += 1;
return acc;
},
{} as Record<string, { month: string; revenue: number; count: number }>,
);
// Convert to array and sort by month
const chartData = Object.values(monthlyData)
.sort((a, b) => a.month.localeCompare(b.month))
.slice(-6) // Show last 6 months
.map((item) => ({
...item,
monthLabel: new Date(item.month + "-01").toLocaleDateString("en-US", {
month: "short",
year: "2-digit",
}),
}));
const formatCurrency = (value: number) => { const formatCurrency = (value: number) => {
return new Intl.NumberFormat("en-US", { return new Intl.NumberFormat("en-US", {
@@ -80,7 +45,7 @@ export function RevenueChart({ invoices }: RevenueChartProps) {
label, label,
}: { }: {
active?: boolean; active?: boolean;
payload?: Array<{ payload: { revenue: number; count: number } }>; payload?: Array<{ payload: { revenue: number } }>;
label?: string; label?: string;
}) => { }) => {
if (active && payload?.length) { if (active && payload?.length) {
@@ -92,7 +57,7 @@ export function RevenueChart({ invoices }: RevenueChartProps) {
Revenue: {formatCurrency(data.revenue)} Revenue: {formatCurrency(data.revenue)}
</p> </p>
<p className="text-muted-foreground text-sm"> <p className="text-muted-foreground text-sm">
{data.count} invoice{data.count !== 1 ? "s" : ""} {/* Count not available in aggregated view currently */}
</p> </p>
</div> </div>
); );

View File

@@ -90,8 +90,8 @@ export function ClientsDataTable({
const client = row.original; const client = row.original;
return ( return (
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
<div className="bg-status-info-muted hidden p-2 sm:flex"> <div className="bg-primary/10 hidden p-2 sm:flex">
<UserPlus className="text-status-info h-4 w-4" /> <UserPlus className="text-primary h-4 w-4" />
</div> </div>
<div className="min-w-0"> <div className="min-w-0">
<p className="truncate font-medium">{client.name}</p> <p className="truncate font-medium">{client.name}</p>

View File

@@ -4,10 +4,11 @@ import { PageHeader } from "~/components/layout/page-header";
import { Button } from "~/components/ui/button"; import { Button } from "~/components/ui/button";
import { HydrateClient } from "~/trpc/server"; import { HydrateClient } from "~/trpc/server";
import { ClientsTable } from "./_components/clients-table"; import { ClientsTable } from "./_components/clients-table";
import { Card, CardContent } from "~/components/ui/card";
export default async function ClientsPage() { export default async function ClientsPage() {
return ( return (
<div className="page-enter space-y-8"> <div className="page-enter space-y-6">
<PageHeader <PageHeader
title="Clients" title="Clients"
description="Manage your clients and their information." description="Manage your clients and their information."

View File

@@ -16,7 +16,7 @@ import {
DialogHeader, DialogHeader,
DialogTitle, DialogTitle,
} from "~/components/ui/dialog"; } from "~/components/ui/dialog";
import { Eye, Edit, Trash2 } from "lucide-react"; import { Eye, Edit, Trash2, FileText } from "lucide-react";
import { api } from "~/trpc/react"; import { api } from "~/trpc/react";
import { toast } from "sonner"; import { toast } from "sonner";
import { getEffectiveInvoiceStatus } from "~/lib/invoice-status"; import { getEffectiveInvoiceStatus } from "~/lib/invoice-status";
@@ -130,13 +130,18 @@ export function InvoicesDataTable({ invoices }: InvoicesDataTableProps) {
cell: ({ row }) => { cell: ({ row }) => {
const invoice = row.original; const invoice = row.original;
return ( return (
<div className="max-w-[80px] min-w-0 sm:max-w-[200px] lg:max-w-[300px]"> <div className="flex items-center gap-3">
<p className="truncate font-medium"> <div className="bg-primary/10 hidden p-2 sm:flex">
{invoice.client?.name ?? "—"} <FileText className="text-primary h-4 w-4" />
</p> </div>
<p className="text-muted-foreground truncate text-xs sm:text-sm"> <div className="max-w-[80px] min-w-0 sm:max-w-[200px] lg:max-w-[300px]">
{invoice.invoiceNumber} <p className="truncate font-medium">
</p> {invoice.client?.name ?? "—"}
</p>
<p className="text-muted-foreground truncate text-xs sm:text-sm">
{invoice.invoiceNumber}
</p>
</div>
</div> </div>
); );
}, },

View File

@@ -6,6 +6,7 @@ import { PageHeader } from "~/components/layout/page-header";
import { Plus, Upload } from "lucide-react"; import { Plus, Upload } from "lucide-react";
import { InvoicesDataTable } from "./_components/invoices-data-table"; import { InvoicesDataTable } from "./_components/invoices-data-table";
import { DataTableSkeleton } from "~/components/data/data-table"; import { DataTableSkeleton } from "~/components/data/data-table";
import { Card, CardContent } from "~/components/ui/card";
// Invoices Table Component // Invoices Table Component
async function InvoicesTable() { async function InvoicesTable() {
@@ -16,7 +17,7 @@ async function InvoicesTable() {
export default async function InvoicesPage() { export default async function InvoicesPage() {
return ( return (
<div className="page-enter space-y-8"> <div className="page-enter space-y-6">
<PageHeader <PageHeader
title="Invoices" title="Invoices"
description="Manage your invoices and track payments" description="Manage your invoices and track payments"

View File

@@ -1,30 +1,9 @@
import { Navbar } from "~/components/layout/navbar"; import { DashboardShell } from "~/components/layout/dashboard-shell";
import { Sidebar } from "~/components/layout/sidebar";
import { DashboardBreadcrumbs } from "~/components/navigation/dashboard-breadcrumbs";
export default function DashboardLayout({ export default function DashboardLayout({
children, children,
}: { }: {
children: React.ReactNode; children: React.ReactNode;
}) { }) {
return ( return <DashboardShell>{children}</DashboardShell>;
<div className="bg-dashboard relative min-h-screen">
<Navbar />
<Sidebar />
{/* Mobile layout - no left margin */}
<main className="relative z-10 min-h-screen pt-16 md:hidden">
<div className="bg-background px-4 pt-4 pb-6 sm:px-6">
<DashboardBreadcrumbs />
{children}
</div>
</main>
{/* Desktop layout - with sidebar margin */}
<main className="relative z-10 hidden min-h-screen pt-16 md:ml-64 md:block">
<div className="bg-background px-6 pt-6 pb-6">
<DashboardBreadcrumbs />
{children}
</div>
</main>
</div>
);
} }

View File

@@ -26,131 +26,10 @@ import { MonthlyMetricsChart } from "~/app/dashboard/_components/monthly-metrics
import { AnimatedStatsCard } from "~/app/dashboard/_components/animated-stats-card"; import { AnimatedStatsCard } from "~/app/dashboard/_components/animated-stats-card";
// Hero section with clean mono design // Hero section with clean mono design
function DashboardHero({ firstName }: { firstName: string }) {
return (
<div className="mb-8">
<h1 className="mb-2 text-3xl font-bold">Welcome back, {firstName}!</h1>
<p className="text-muted-foreground text-lg">
Here&apos;s what&apos;s happening with your business today
</p>
</div>
);
}
// Enhanced stats cards with better visuals // Enhanced stats cards with better visuals
async function DashboardStats() { function DashboardStats({ stats }: { stats: any }) { // TODO: Import RouterOutput type
const [clients, invoices] = await Promise.all([
api.clients.getAll(),
api.invoices.getAll(),
]);
const totalClients = clients.length;
const paidInvoices = invoices.filter(
(invoice) =>
getEffectiveInvoiceStatus(
invoice.status as StoredInvoiceStatus,
invoice.dueDate,
) === "paid",
);
const totalRevenue = paidInvoices.reduce(
(sum, invoice) => sum + invoice.totalAmount,
0,
);
const pendingInvoices = invoices.filter((invoice) => {
const effectiveStatus = getEffectiveInvoiceStatus(
invoice.status as StoredInvoiceStatus,
invoice.dueDate,
);
return effectiveStatus === "sent" || effectiveStatus === "overdue";
});
const pendingAmount = pendingInvoices.reduce(
(sum, invoice) => sum + invoice.totalAmount,
0,
);
const overdueInvoices = invoices.filter(
(invoice) =>
getEffectiveInvoiceStatus(
invoice.status as StoredInvoiceStatus,
invoice.dueDate,
) === "overdue",
);
// Calculate month-over-month trends
const now = new Date();
const currentMonth = new Date(now.getFullYear(), now.getMonth(), 1);
const lastMonth = new Date(now.getFullYear(), now.getMonth() - 1, 1);
// Current month data
const currentMonthInvoices = invoices.filter(
(invoice) => new Date(invoice.issueDate) >= currentMonth,
);
const currentMonthRevenue = currentMonthInvoices
.filter(
(invoice) =>
getEffectiveInvoiceStatus(
invoice.status as StoredInvoiceStatus,
invoice.dueDate,
) === "paid",
)
.reduce((sum, invoice) => sum + invoice.totalAmount, 0);
// Last month data
const lastMonthInvoices = invoices.filter((invoice) => {
const date = new Date(invoice.issueDate);
return date >= lastMonth && date < currentMonth;
});
const lastMonthRevenue = lastMonthInvoices
.filter(
(invoice) =>
getEffectiveInvoiceStatus(
invoice.status as StoredInvoiceStatus,
invoice.dueDate,
) === "paid",
)
.reduce((sum, invoice) => sum + invoice.totalAmount, 0);
// Previous month data for clients
const prevMonthClients = clients.filter(
(client) => new Date(client.createdAt) < currentMonth,
).length;
// Calculate trends
const revenueChange =
lastMonthRevenue > 0
? ((currentMonthRevenue - lastMonthRevenue) / lastMonthRevenue) * 100
: currentMonthRevenue > 0
? 100
: 0;
const pendingChange =
lastMonthInvoices.length > 0
? ((pendingInvoices.length -
lastMonthInvoices.filter((invoice) => {
const status = getEffectiveInvoiceStatus(
invoice.status as StoredInvoiceStatus,
invoice.dueDate,
);
return status === "sent" || status === "overdue";
}).length) /
lastMonthInvoices.length) *
100
: pendingInvoices.length > 0
? 100
: 0;
const clientChange = totalClients - prevMonthClients;
const lastMonthOverdue = lastMonthInvoices.filter(
(invoice) =>
getEffectiveInvoiceStatus(
invoice.status as StoredInvoiceStatus,
invoice.dueDate,
) === "overdue",
).length;
const overdueChange = overdueInvoices.length - lastMonthOverdue;
const formatTrend = (value: number, isCount = false) => { const formatTrend = (value: number, isCount = false) => {
if (isCount) { if (isCount) {
return value > 0 ? `+${value}` : value.toString(); return value > 0 ? `+${value}` : value.toString();
@@ -158,66 +37,52 @@ async function DashboardStats() {
return value > 0 ? `+${value.toFixed(1)}%` : `${value.toFixed(1)}%`; return value > 0 ? `+${value.toFixed(1)}%` : `${value.toFixed(1)}%`;
}; };
// Debug logging to see actual values const statCards = [
console.log("Dashboard Stats Debug:", {
totalRevenue,
pendingAmount,
totalClients,
overdueInvoices: overdueInvoices.length,
revenueChange,
pendingChange,
clientChange,
overdueChange,
paidInvoicesCount: paidInvoices.length,
pendingInvoicesCount: pendingInvoices.length,
});
const stats = [
{ {
title: "Total Revenue", title: "Total Revenue",
value: `$${totalRevenue.toLocaleString("en-US", { minimumFractionDigits: 2 })}`, value: `$${stats.totalRevenue.toLocaleString("en-US", { minimumFractionDigits: 2 })}`,
numericValue: totalRevenue, numericValue: stats.totalRevenue,
isCurrency: true, isCurrency: true,
change: formatTrend(revenueChange), change: formatTrend(stats.revenueChange),
trend: revenueChange >= 0 ? ("up" as const) : ("down" as const), trend: stats.revenueChange >= 0 ? ("up" as const) : ("down" as const),
iconName: "DollarSign" as const, iconName: "DollarSign" as const,
description: `From ${paidInvoices.length} paid invoices`, description: "Total collected revenue",
}, },
{ {
title: "Pending Amount", title: "Pending Amount",
value: `$${pendingAmount.toLocaleString("en-US", { minimumFractionDigits: 2 })}`, value: `$${stats.pendingAmount.toLocaleString("en-US", { minimumFractionDigits: 2 })}`,
numericValue: pendingAmount, numericValue: stats.pendingAmount,
isCurrency: true, isCurrency: true,
change: formatTrend(pendingChange), change: "0%", // TODO: Calculate pending change if needed
trend: pendingChange >= 0 ? ("up" as const) : ("down" as const), trend: "neutral" as const,
iconName: "Clock" as const, iconName: "Clock" as const,
description: `${pendingInvoices.length} invoices awaiting payment`, description: "Invoices awaiting payment",
}, },
{ {
title: "Active Clients", title: "Active Clients",
value: totalClients.toString(), value: stats.totalClients.toString(),
numericValue: totalClients, numericValue: stats.totalClients,
isCurrency: false, isCurrency: false,
change: formatTrend(clientChange, true), change: "0", // TODO: Calculate client change if needed
trend: clientChange >= 0 ? ("up" as const) : ("down" as const), trend: "neutral" as const,
iconName: "Users" as const, iconName: "Users" as const,
description: "Total registered clients", description: "Total registered clients",
}, },
{ {
title: "Overdue Invoices", title: "Overdue Invoices",
value: overdueInvoices.length.toString(), value: stats.overdueCount.toString(),
numericValue: overdueInvoices.length, numericValue: stats.overdueCount,
isCurrency: false, isCurrency: false,
change: formatTrend(overdueChange, true), change: "0", // TODO: Calculate overdue change if needed
trend: overdueChange <= 0 ? ("up" as const) : ("down" as const), trend: "neutral" as const,
iconName: "TrendingDown" as const, iconName: "TrendingDown" as const,
description: "Invoices past due date", description: "Invoices past due date",
}, },
]; ];
return ( return (
<div className="mb-8 grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-4"> <div className="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-4">
{stats.map((stat, index) => ( {statCards.map((stat, index) => (
<AnimatedStatsCard <AnimatedStatsCard
key={stat.title} key={stat.title}
title={stat.title} title={stat.title}
@@ -236,11 +101,14 @@ async function DashboardStats() {
} }
// Charts section // Charts section
async function ChartsSection() { async function ChartsSection({ stats }: { stats: any }) {
// We still fetch all invoices for the status chart for now, or we could aggregate that too.
// For now, let's keep status chart as is (fetching all) but use aggregated for revenue.
// Actually, let's fetch invoices here for the status chart to keep it working.
const invoices = await api.invoices.getAll(); const invoices = await api.invoices.getAll();
return ( return (
<div className="mb-8 grid grid-cols-1 gap-6 lg:grid-cols-2"> <div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
{/* Revenue Trend Chart */} {/* Revenue Trend Chart */}
<Card className="lg:col-span-2"> <Card className="lg:col-span-2">
<CardHeader> <CardHeader>
@@ -250,7 +118,7 @@ async function ChartsSection() {
</CardTitle> </CardTitle>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<RevenueChart invoices={invoices} /> <RevenueChart data={stats.revenueChartData} />
</CardContent> </CardContent>
</Card> </Card>
@@ -441,14 +309,8 @@ async function CurrentWork() {
} }
// Enhanced recent activity // Enhanced recent activity
async function RecentActivity() { async function RecentActivity({ recentInvoices }: { recentInvoices: any[] }) {
const invoices = await api.invoices.getAll(); // Use passed recentInvoices instead of fetching all
const recentInvoices = invoices
.sort(
(a, b) =>
new Date(b.issueDate).getTime() - new Date(a.issueDate).getTime(),
)
.slice(0, 5);
const getStatusStyle = (status: string) => { const getStatusStyle = (status: string) => {
switch (status) { switch (status) {
@@ -558,7 +420,7 @@ async function RecentActivity() {
// Loading skeletons // Loading skeletons
function StatsSkeleton() { function StatsSkeleton() {
return ( return (
<div className="mb-8 grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-4"> <div className="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-4">
{Array.from({ length: 4 }).map((_, i) => ( {Array.from({ length: 4 }).map((_, i) => (
<Card key={i}> <Card key={i}>
<CardContent className="p-6"> <CardContent className="p-6">
@@ -577,7 +439,7 @@ function StatsSkeleton() {
function ChartsSkeleton() { function ChartsSkeleton() {
return ( return (
<div className="mb-8 grid grid-cols-1 gap-6 lg:grid-cols-2"> <div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
<Card className="lg:col-span-2"> <Card className="lg:col-span-2">
<CardHeader> <CardHeader>
<Skeleton className="h-6 w-40" /> <Skeleton className="h-6 w-40" />
@@ -623,30 +485,40 @@ function CardSkeleton() {
); );
} }
import { DashboardPageHeader } from "~/components/layout/page-header";
// ... imports
export default async function DashboardPage() { export default async function DashboardPage() {
const session = await auth.api.getSession({ const session = await auth.api.getSession({
headers: await headers(), headers: await headers(),
}); });
const firstName = session?.user?.name?.split(" ")[0] ?? "User"; const firstName = session?.user?.name?.split(" ")[0] ?? "User";
// Fetch stats centrally
const stats = await api.dashboard.getStats();
return ( return (
<div className="page-enter space-y-8"> <div className="page-enter space-y-6">
<DashboardHero firstName={firstName} /> <DashboardPageHeader
title={`Welcome back, ${firstName}!`}
description="Here's what's happening with your business today"
/>
<HydrateClient> <HydrateClient>
<Suspense fallback={<StatsSkeleton />}> <Suspense fallback={<StatsSkeleton />}>
<DashboardStats /> <DashboardStats stats={stats} />
</Suspense> </Suspense>
</HydrateClient> </HydrateClient>
<HydrateClient> <HydrateClient>
<Suspense fallback={<ChartsSkeleton />}> <Suspense fallback={<ChartsSkeleton />}>
<ChartsSection /> <ChartsSection stats={stats} />
</Suspense> </Suspense>
</HydrateClient> </HydrateClient>
<div className="grid grid-cols-1 gap-8 lg:grid-cols-2"> <div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
<div className="space-y-8"> <div className="space-y-6">
<HydrateClient> <HydrateClient>
<Suspense fallback={<CardSkeleton />}> <Suspense fallback={<CardSkeleton />}>
<CurrentWork /> <CurrentWork />
@@ -657,7 +529,7 @@ export default async function DashboardPage() {
<HydrateClient> <HydrateClient>
<Suspense fallback={<CardSkeleton />}> <Suspense fallback={<CardSkeleton />}>
<RecentActivity /> <RecentActivity recentInvoices={stats.recentInvoices} />
</Suspense> </Suspense>
</HydrateClient> </HydrateClient>
</div> </div>

View File

@@ -3,21 +3,26 @@ import { HydrateClient } from "~/trpc/server";
import { PageHeader } from "~/components/layout/page-header"; import { PageHeader } from "~/components/layout/page-header";
import { DataTableSkeleton } from "~/components/data/data-table"; import { DataTableSkeleton } from "~/components/data/data-table";
import { SettingsContent } from "./_components/settings-content"; import { SettingsContent } from "./_components/settings-content";
import { Card, CardContent } from "~/components/ui/card";
export default async function SettingsPage() { export default async function SettingsPage() {
return ( return (
<div className="page-enter space-y-8"> <div className="page-enter space-y-6">
<PageHeader <PageHeader
title="Settings" title="Settings"
description="Manage your account preferences and data" description="Manage your account preferences and data"
variant="gradient" variant="gradient"
/> />
<HydrateClient> <Card>
<Suspense fallback={<DataTableSkeleton columns={1} rows={4} />}> <CardContent className="p-6">
<SettingsContent /> <HydrateClient>
</Suspense> <Suspense fallback={<DataTableSkeleton columns={1} rows={4} />}>
</HydrateClient> <SettingsContent />
</Suspense>
</HydrateClient>
</CardContent>
</Card>
</div> </div>
); );
} }

View File

@@ -6,6 +6,7 @@ import { Geist, Geist_Mono, Instrument_Serif } from "next/font/google";
import { TRPCReactProvider } from "~/trpc/react"; import { TRPCReactProvider } from "~/trpc/react";
import { Toaster } from "~/components/ui/sonner"; import { Toaster } from "~/components/ui/sonner";
import { AnimationPreferencesProvider } from "~/components/providers/animation-preferences-provider"; import { AnimationPreferencesProvider } from "~/components/providers/animation-preferences-provider";
import { MotionBackground } from "~/components/layout/motion-background";
import { ThemeProvider } from "~/components/providers/theme-provider"; import { ThemeProvider } from "~/components/providers/theme-provider";
import { ColorThemeProvider } from "~/components/providers/color-theme-provider"; import { ColorThemeProvider } from "~/components/providers/color-theme-provider";
@@ -141,6 +142,7 @@ export default function RootLayout({
<ThemeProvider> <ThemeProvider>
<ColorThemeProvider> <ColorThemeProvider>
<AnimationPreferencesProvider> <AnimationPreferencesProvider>
<MotionBackground />
{children} {children}
</AnimationPreferencesProvider> </AnimationPreferencesProvider>
<Toaster /> <Toaster />

View File

@@ -5,30 +5,29 @@ import { cn } from "~/lib/utils";
interface LogoProps { interface LogoProps {
className?: string; className?: string;
size?: "sm" | "md" | "lg" | "xl"; size?: "sm" | "md" | "lg" | "xl" | "icon";
animated?: boolean; animated?: boolean;
} }
export function Logo({ className, size = "md", animated = true }: LogoProps) { export function Logo({ className, size = "md", animated = true }: LogoProps) {
const sizeClasses = { const sizeClasses = {
sm: "text-sm", sm: "text-base",
md: "text-lg", md: "text-xl",
lg: "text-2xl", lg: "text-3xl",
xl: "text-4xl", xl: "text-5xl",
icon: "text-2xl",
}; };
if (!animated) { if (!animated) {
return <LogoContent className={className} size={size} sizeClasses={sizeClasses} />; return <LogoContent className={className} size={size} sizeClasses={sizeClasses} />;
} }
return ( return (
<motion.div <motion.div
initial={{ opacity: 0 }} initial={{ opacity: 0 }}
animate={{ opacity: 1 }} animate={{ opacity: 1 }}
transition={{ duration: 0.1, ease: "easeOut" }} transition={{ duration: 0.1, ease: "easeOut" }}
className={cn("flex items-center", sizeClasses[size], className)} className={cn("flex items-center font-mono", sizeClasses[size], className)}
> >
<motion.span <motion.span
initial={{ opacity: 0 }} initial={{ opacity: 0 }}
@@ -38,28 +37,32 @@ export function Logo({ className, size = "md", animated = true }: LogoProps) {
> >
$ $
</motion.span> </motion.span>
<motion.span {size !== "icon" && (
initial={{ opacity: 0 }} <>
animate={{ opacity: 1 }} <motion.span
transition={{ delay: 0.03, duration: 0.05, ease: "easeOut" }} initial={{ opacity: 0 }}
className="inline-block w-2" animate={{ opacity: 1 }}
></motion.span> transition={{ delay: 0.03, duration: 0.05, ease: "easeOut" }}
<motion.span className="inline-block w-1" // Reduced from w-2 to w-1 (half space)
initial={{ opacity: 0 }} ></motion.span>
animate={{ opacity: 1 }} <motion.span
transition={{ delay: 0.04, duration: 0.05, ease: "easeOut" }} initial={{ opacity: 0 }}
className="text-foreground font-bold tracking-tight" animate={{ opacity: 1 }}
> transition={{ delay: 0.04, duration: 0.05, ease: "easeOut" }}
been className="text-foreground font-bold tracking-tight"
</motion.span> >
<motion.span been
initial={{ opacity: 0 }} </motion.span>
animate={{ opacity: 1 }} <motion.span
transition={{ delay: 0.06, duration: 0.05, ease: "easeOut" }} initial={{ opacity: 0 }}
className="text-foreground/70 font-bold tracking-tight" animate={{ opacity: 1 }}
> transition={{ delay: 0.06, duration: 0.05, ease: "easeOut" }}
voice className="text-foreground/70 font-bold tracking-tight"
</motion.span> >
voice
</motion.span>
</>
)}
</motion.div> </motion.div>
); );
} }
@@ -70,15 +73,19 @@ function LogoContent({
sizeClasses, sizeClasses,
}: { }: {
className?: string; className?: string;
size: "sm" | "md" | "lg" | "xl"; size: "sm" | "md" | "lg" | "xl" | "icon";
sizeClasses: Record<string, string>; sizeClasses: Record<string, string>;
}) { }) {
return ( return (
<div className={cn("flex items-center", sizeClasses[size], className)}> <div className={cn("flex items-center font-mono", sizeClasses[size], className)}>
<span className="text-primary font-bold tracking-tight">$</span> <span className="text-primary font-bold tracking-tight">$</span>
<span className="inline-block w-2"></span> {size !== "icon" && (
<span className="text-foreground font-bold tracking-tight">been</span> <>
<span className="text-foreground/70 font-bold tracking-tight">voice</span> <span className="inline-block w-1"></span>
<span className="text-foreground font-bold tracking-tight">been</span>
<span className="text-foreground/70 font-bold tracking-tight">voice</span>
</>
)}
</div> </div>
); );
} }

View File

@@ -0,0 +1,70 @@
"use client";
import * as React from "react";
import { Sidebar } from "~/components/layout/sidebar";
import { SidebarProvider, useSidebar } from "~/components/layout/sidebar-provider";
import { cn } from "~/lib/utils";
import { Menu } from "lucide-react";
import { Button } from "~/components/ui/button";
import { Sheet, SheetContent, SheetTrigger } from "~/components/ui/sheet";
import { DashboardBreadcrumbs } from "~/components/navigation/dashboard-breadcrumbs";
function DashboardContent({ children }: { children: React.ReactNode }) {
const { isCollapsed } = useSidebar();
const [isMobileOpen, setIsMobileOpen] = React.useState(false);
return (
<div className="bg-dashboard relative min-h-screen flex">
{/* Desktop Sidebar */}
<div className="hidden md:block">
<Sidebar />
</div>
{/* Mobile Sidebar (Sheet) */}
<div className="md:hidden fixed top-4 left-4 z-50">
<Sheet open={isMobileOpen} onOpenChange={setIsMobileOpen}>
<SheetTrigger asChild>
<Button variant="outline" size="icon" className="h-10 w-10 bg-background shadow-sm">
<Menu className="h-5 w-5" />
<span className="sr-only">Toggle menu</span>
</Button>
</SheetTrigger>
<SheetContent side="left" className="p-0 w-72">
<Sidebar mobile onClose={() => setIsMobileOpen(false)} />
</SheetContent>
</Sheet>
</div>
{/* Main Content */}
<main
suppressHydrationWarning
className={cn(
"flex-1 min-h-screen transition-all duration-300 ease-in-out",
// Desktop margins based on collapsed state
"md:ml-0",
// Sidebar is fixed at left: 1rem (16px), width: 16rem (256px) or 4rem (64px)
// We need margin-left = left + width + gap
// Expanded: 16px + 256px + 16px (gap) = 288px (18rem)
// Collapsed: 16px + 64px + 16px (gap) = 96px (6rem)
isCollapsed ? "md:ml-24" : "md:ml-[18rem]"
)}
>
<div className="p-4 pt-16 md:pt-4">
{/* Mobile header spacer is handled by pt-16 on mobile */}
<div className="md:hidden mb-4">
{/* Mobile Breadcrumbs could go here or be part of the page */}
</div>
{children}
</div>
</main>
</div>
);
}
export function DashboardShell({ children }: { children: React.ReactNode }) {
return (
<SidebarProvider>
<DashboardContent>{children}</DashboardContent>
</SidebarProvider>
);
}

View File

@@ -0,0 +1,27 @@
"use client";
import { cn } from "~/lib/utils";
export function MotionBackground() {
return (
<div className="fixed inset-0 -z-50 overflow-hidden pointer-events-none bg-background">
<div
className={cn(
"absolute inset-[-50%] w-[200%] h-[200%]",
"bg-[radial-gradient(circle_at_center,_var(--tw-gradient-stops))]",
"from-[oklch(var(--primary)/0.15)] via-transparent to-transparent",
"animate-subtle-spin opacity-100"
)}
/>
<div
className={cn(
"absolute inset-[-50%] w-[200%] h-[200%]",
"bg-[radial-gradient(circle_at_center,_var(--tw-gradient-stops))]",
"from-[oklch(var(--accent)/0.15)] via-transparent to-transparent",
"animate-subtle-wave opacity-100"
)}
/>
<div className="absolute inset-0 bg-[url('/noise.svg')] opacity-[0.02] mix-blend-overlay" />
</div>
);
}

View File

@@ -1,4 +1,5 @@
import React from "react"; import React from "react";
import { DashboardBreadcrumbs } from "~/components/navigation/dashboard-breadcrumbs";
interface PageHeaderProps { interface PageHeaderProps {
title: string; title: string;
@@ -39,24 +40,51 @@ export function PageHeader({
}; };
return ( return (
<div className={`animate-fade-in-down mb-8 ${className}`}> <div className={`animate-fade-in-down mb-6 ${className}`}>
<div className="flex items-start justify-between gap-4"> {variant === "large-gradient" || variant === "gradient" ? (
<div className="animate-fade-in-up space-y-1"> <div className="rounded-xl border bg-card text-card-foreground shadow-sm overflow-hidden relative">
<h1 className={titleClassName ?? getTitleClasses()}>{title}</h1> <div className="absolute inset-0 bg-gradient-to-br from-primary/5 via-transparent to-transparent pointer-events-none" />
{description && ( <div className="p-6 relative">
<p <DashboardBreadcrumbs className="mb-4" />
className={`animate-fade-in-up animate-delay-100 text-muted-foreground ${getDescriptionSpacing()} text-lg`} <div className="flex items-start justify-between gap-4">
> <div className="space-y-1">
{description} <h1 className={titleClassName ?? getTitleClasses()}>{title}</h1>
</p> {description && (
)} <p className={`text-muted-foreground ${getDescriptionSpacing()} text-lg`}>
</div> {description}
{children && ( </p>
<div className="animate-slide-in-right animate-delay-200 flex flex-shrink-0 gap-2 sm:gap-3"> )}
{children} </div>
{children && (
<div className="flex flex-shrink-0 gap-2 sm:gap-3">
{children}
</div>
)}
</div>
</div> </div>
)} </div>
</div> ) : (
<>
<DashboardBreadcrumbs className="mb-2 sm:mb-4" />
<div className="flex items-start justify-between gap-4">
<div className="animate-fade-in-up space-y-1">
<h1 className={titleClassName ?? getTitleClasses()}>{title}</h1>
{description && (
<p
className={`animate-fade-in-up animate-delay-100 text-muted-foreground ${getDescriptionSpacing()} text-lg`}
>
{description}
</p>
)}
</div>
{children && (
<div className="animate-slide-in-right animate-delay-200 flex flex-shrink-0 gap-2 sm:gap-3">
{children}
</div>
)}
</div>
</>
)}
</div> </div>
); );
} }

View File

@@ -0,0 +1,60 @@
"use client";
import * as React from "react";
interface SidebarContextType {
isCollapsed: boolean;
toggleCollapse: () => void;
expand: () => void;
collapse: () => void;
}
const SidebarContext = React.createContext<SidebarContextType | undefined>(
undefined,
);
export function SidebarProvider({ children }: { children: React.ReactNode }) {
const [isCollapsed, setIsCollapsed] = React.useState(false);
// Persist state if needed, for now just local state
React.useEffect(() => {
const saved = localStorage.getItem("sidebar-collapsed");
if (saved) {
setIsCollapsed(JSON.parse(saved));
}
}, []);
const toggleCollapse = React.useCallback(() => {
setIsCollapsed((prev) => {
const next = !prev;
localStorage.setItem("sidebar-collapsed", JSON.stringify(next));
return next;
});
}, []);
const expand = React.useCallback(() => {
setIsCollapsed(false);
localStorage.setItem("sidebar-collapsed", JSON.stringify(false));
}, []);
const collapse = React.useCallback(() => {
setIsCollapsed(true);
localStorage.setItem("sidebar-collapsed", JSON.stringify(true));
}, []);
return (
<SidebarContext.Provider
value={{ isCollapsed, toggleCollapse, expand, collapse }}
>
{children}
</SidebarContext.Provider>
);
}
export function useSidebar() {
const context = React.useContext(SidebarContext);
if (context === undefined) {
throw new Error("useSidebar must be used within a SidebarProvider");
}
return context;
}

View File

@@ -5,102 +5,218 @@ import { usePathname } from "next/navigation";
import { authClient } from "~/lib/auth-client"; import { authClient } from "~/lib/auth-client";
import { Skeleton } from "~/components/ui/skeleton"; import { Skeleton } from "~/components/ui/skeleton";
import { Button } from "~/components/ui/button"; import { Button } from "~/components/ui/button";
import { LogOut, User } from "lucide-react"; import {
LogOut,
User,
ChevronLeft,
ChevronRight,
PanelLeftClose,
PanelLeftOpen,
Settings
} from "lucide-react";
import { navigationConfig } from "~/lib/navigation"; import { navigationConfig } from "~/lib/navigation";
import { useSidebar } from "./sidebar-provider";
import { cn } from "~/lib/utils";
import { Logo } from "~/components/branding/logo";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "~/components/ui/tooltip";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "~/components/ui/dropdown-menu";
import { getGravatarUrl } from "~/lib/gravatar";
import { Avatar, AvatarFallback, AvatarImage } from "~/components/ui/avatar";
export function Sidebar() { interface SidebarProps {
mobile?: boolean;
onClose?: () => void;
}
export function Sidebar({ mobile, onClose }: SidebarProps) {
const pathname = usePathname(); const pathname = usePathname();
const { data: session, isPending } = authClient.useSession(); const { data: session, isPending } = authClient.useSession();
const { isCollapsed, toggleCollapse } = useSidebar();
return ( // If mobile, always expanded
<aside className="bg-sidebar border-sidebar-border text-sidebar-foreground fixed top-[4rem] bottom-0 left-0 z-20 hidden w-64 flex-col justify-between border-r p-6 md:flex"> const collapsed = mobile ? false : isCollapsed;
<nav className="flex flex-col">
{navigationConfig.map((section, sectionIndex) => ( const SidebarContent = (
<div key={section.title} className={sectionIndex > 0 ? "mt-6" : ""}> <div className="flex h-full flex-col justify-between">
{sectionIndex > 0 && ( <div>
<div className="border-border/40 my-4 border-t" /> {/* Header / Logo */}
)} <div className={cn(
<div className="text-sidebar-foreground/60 mb-3 text-xs font-semibold tracking-wider uppercase"> "flex items-center h-14 px-4 mb-2",
{section.title} collapsed ? "justify-center px-2" : "justify-between"
)}>
{!collapsed && (
<div className="flex items-center gap-2">
<Logo size="sm" />
</div> </div>
<div className="flex flex-col gap-0.5"> )}
{isPending ? ( {collapsed && <Logo size="icon" />}
<>
{Array.from({ length: section.links.length }).map((_, i) => ( {!mobile && !collapsed && (
<div <div className="h-8 w-8" /> // Spacer to keep alignment if needed, or just remove
key={i} )}
className="flex items-center gap-3 px-3 py-2.5" </div>
>
<Skeleton className="bg-sidebar-accent/20 h-4 w-4" /> {/* Navigation */}
<Skeleton className="bg-sidebar-accent/20 h-4 w-20" /> <nav className={cn("flex flex-col px-2 gap-6 mt-4", collapsed && "items-center")}>
</div> {navigationConfig.map((section, sectionIndex) => (
))} <div key={section.title}>
</> {!collapsed && (
) : ( <div className="px-2 mb-2 text-xs font-semibold text-muted-foreground/60 tracking-wider uppercase">
section.links.map((link) => { {section.title}
const Icon = link.icon; </div>
return (
<Link
key={link.href}
href={link.href}
aria-current={pathname === link.href ? "page" : undefined}
className={`flex items-center gap-3 rounded-md px-3 py-2.5 text-sm font-medium transition-colors ${pathname === link.href
? "bg-sidebar-accent text-sidebar-accent-foreground"
: "text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground"
}`}
>
<Icon className="h-4 w-4" />
{link.name}
</Link>
);
})
)} )}
</div> <div className="flex flex-col gap-1">
</div> <div className="flex flex-col gap-1">
))} {section.links.map((link) => {
</nav> const Icon = link.icon;
const isActive = pathname === link.href;
{/* User Section */} if (collapsed) {
<div className="border-sidebar-border border-t pt-4"> return (
{isPending ? ( <TooltipProvider key={link.href} delayDuration={0}>
<div className="space-y-3"> <Tooltip>
<Skeleton className="bg-sidebar-accent/20 h-8 w-full" /> <TooltipTrigger asChild>
<Skeleton className="bg-sidebar-accent/20 h-8 w-full" /> <Link
<div className="flex items-center gap-3 p-3"> href={link.href}
<Skeleton className="bg-sidebar-accent/20 h-8 w-8 rounded-full" /> className={cn(
<div className="flex-1"> "flex items-center justify-center h-10 w-10 rounded-md transition-colors",
<Skeleton className="bg-sidebar-accent/20 mb-1 h-4 w-24" /> isActive
<Skeleton className="bg-sidebar-accent/20 h-3 w-32" /> ? "bg-primary text-primary-foreground shadow-sm"
: "text-muted-foreground hover:bg-muted hover:text-foreground"
)}
>
<Icon className="h-5 w-5" />
</Link>
</TooltipTrigger>
<TooltipContent side="right" className="font-medium">
{link.name}
</TooltipContent>
</Tooltip>
</TooltipProvider>
);
}
return (
<Link
key={link.href}
href={link.href}
onClick={mobile ? onClose : undefined}
className={cn(
"flex items-center gap-3 px-3 py-2 rounded-md text-sm font-medium transition-colors",
isActive
? "bg-primary/10 text-primary"
: "text-muted-foreground hover:bg-muted hover:text-foreground"
)}
>
<Icon className="h-4 w-4" />
{link.name}
</Link>
);
})}
</div>
</div> </div>
</div> </div>
</div> ))}
) : session?.user ? ( </nav>
<div className="space-y-3"> </div>
{/* Footer / User */}
<div className="p-2 mt-auto space-y-2">
{!mobile && (
<div className={cn("flex", collapsed ? "justify-center" : "justify-end px-2")}>
<Button <Button
variant="ghost" variant="ghost"
size="sm" size="icon"
onClick={() => authClient.signOut()} className="h-8 w-8 text-muted-foreground"
className="text-sidebar-foreground/60 hover:text-sidebar-foreground hover:bg-sidebar-accent w-full justify-start px-3" onClick={toggleCollapse}
> >
<LogOut className="mr-2 h-4 w-4" /> {collapsed ? <PanelLeftOpen className="h-4 w-4" /> : <PanelLeftClose className="h-4 w-4" />}
Sign Out
</Button> </Button>
<div className="flex items-center gap-3 px-3 pt-2">
<div className="bg-sidebar-accent flex h-8 w-8 items-center justify-center rounded-full">
<User className="h-4 w-4" />
</div>
<div className="min-w-0 flex-1">
<p className="text-sidebar-foreground truncate text-sm font-medium">
{session.user.name ?? "User"}
</p>
<p className="text-sidebar-foreground/60 truncate text-xs">
{session.user.email}
</p>
</div>
</div>
</div> </div>
) : null} )}
<div className={cn(
"border-t border-border/50 pt-4",
collapsed ? "flex flex-col items-center gap-2" : "px-2"
)}>
{isPending ? (
<div className={cn("flex items-center gap-3", collapsed ? "justify-center" : "px-2")}>
<Skeleton className="h-9 w-9 rounded-full" />
{!collapsed && (
<div className="space-y-1 flex-1">
<Skeleton className="h-3 w-20" />
<Skeleton className="h-2 w-24" />
</div>
)}
</div>
) : session?.user ? (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" className={cn("w-full justify-start p-0 hover:bg-transparent", collapsed && "justify-center")}>
<div className={cn("flex items-center gap-3", collapsed ? "justify-center" : "w-full")}>
<Avatar className="h-9 w-9 border border-border">
<AvatarImage src={getGravatarUrl(session.user.email)} alt={session.user.name ?? "User"} />
<AvatarFallback>{session.user.name?.[0] ?? "U"}</AvatarFallback>
</Avatar>
{!collapsed && (
<div className="flex-1 min-w-0 text-left">
<p className="text-sm font-medium truncate">{session.user.name}</p>
<p className="text-xs text-muted-foreground truncate">{session.user.email}</p>
</div>
)}
</div>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent side="right" align="end" className="w-56" sideOffset={10}>
<DropdownMenuLabel>
<div className="flex flex-col space-y-1">
<p className="text-sm font-medium leading-none">{session.user.name}</p>
<p className="text-xs leading-none text-muted-foreground">{session.user.email}</p>
</div>
</DropdownMenuLabel>
<DropdownMenuSeparator />
<DropdownMenuItem
onClick={async () => {
await authClient.signOut();
window.location.href = "/";
}}
className="text-red-600 focus:text-red-600 focus:bg-red-100/50 dark:focus:bg-red-900/20"
>
<LogOut className="mr-2 h-4 w-4" />
Sign Out
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
) : null}
</div>
</div> </div>
</div>
);
if (mobile) {
return (
<div className="h-full bg-background">
{SidebarContent}
</div>
);
}
return (
<aside
className={cn(
"fixed top-4 bottom-4 left-4 z-30 hidden md:flex flex-col",
"bg-card border border-border shadow-xl rounded-xl transition-all duration-300 ease-in-out",
isCollapsed ? "w-16" : "w-64"
)}
>
{SidebarContent}
</aside> </aside>
); );
} }

View File

@@ -32,7 +32,9 @@ const SPECIAL_SEGMENTS: Record<string, string> = {
dashboard: "Dashboard", dashboard: "Dashboard",
}; };
export function DashboardBreadcrumbs() { import { cn } from "~/lib/utils";
export function DashboardBreadcrumbs({ className }: { className?: string }) {
const pathname = usePathname(); const pathname = usePathname();
const segments = pathname.split("/").filter(Boolean); const segments = pathname.split("/").filter(Boolean);
@@ -144,7 +146,7 @@ export function DashboardBreadcrumbs() {
if (breadcrumbs.length === 0) return null; if (breadcrumbs.length === 0) return null;
return ( return (
<Breadcrumb className="mb-4 sm:mb-6"> <Breadcrumb className={cn("mb-4 sm:mb-6", className)}>
<BreadcrumbList className="flex-nowrap overflow-hidden"> <BreadcrumbList className="flex-nowrap overflow-hidden">
<BreadcrumbItem> <BreadcrumbItem>
<BreadcrumbLink asChild> <BreadcrumbLink asChild>

View File

@@ -398,9 +398,17 @@ export function AnimationPreferencesProvider({
export function useAnimationPreferences(): AnimationPreferencesContextValue { export function useAnimationPreferences(): AnimationPreferencesContextValue {
const ctx = useContext(AnimationPreferencesContext); const ctx = useContext(AnimationPreferencesContext);
if (!ctx) { if (!ctx) {
throw new Error( // Fallback instead of throwing to prevent runtime crashes if provider is missing
"useAnimationPreferences must be used within an AnimationPreferencesProvider", console.warn("useAnimationPreferences used without provider");
); return {
prefersReducedMotion: false,
animationSpeedMultiplier: 1,
updatePreferences: () => { },
setPrefersReducedMotion: () => { },
setAnimationSpeedMultiplier: () => { },
isUpdating: false,
lastSyncedAt: null,
};
} }
return ctx; return ctx;
} }

View File

@@ -0,0 +1,50 @@
"use client"
import * as React from "react"
import * as AvatarPrimitive from "@radix-ui/react-avatar"
import { cn } from "~/lib/utils"
const Avatar = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Root>
>(({ className, ...props }, ref) => (
<AvatarPrimitive.Root
ref={ref}
className={cn(
"relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",
className
)}
{...props}
/>
))
Avatar.displayName = AvatarPrimitive.Root.displayName
const AvatarImage = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Image>,
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Image>
>(({ className, ...props }, ref) => (
<AvatarPrimitive.Image
ref={ref}
className={cn("aspect-square h-full w-full", className)}
{...props}
/>
))
AvatarImage.displayName = AvatarPrimitive.Image.displayName
const AvatarFallback = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Fallback>,
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Fallback>
>(({ className, ...props }, ref) => (
<AvatarPrimitive.Fallback
ref={ref}
className={cn(
"flex h-full w-full items-center justify-center rounded-full bg-muted",
className
)}
{...props}
/>
))
AvatarFallback.displayName = AvatarPrimitive.Fallback.displayName
export { Avatar, AvatarImage, AvatarFallback }

7
src/lib/gravatar.ts Normal file
View File

@@ -0,0 +1,7 @@
import { createHash } from "crypto";
export function getGravatarUrl(email: string, size = 200) {
const trimmedEmail = email.trim().toLowerCase();
const hash = createHash("sha256").update(trimmedEmail).digest("hex");
return `https://www.gravatar.com/avatar/${hash}?s=${size}&d=mp`;
}

View File

@@ -3,6 +3,7 @@ import { businessesRouter } from "~/server/api/routers/businesses";
import { invoicesRouter } from "~/server/api/routers/invoices"; import { invoicesRouter } from "~/server/api/routers/invoices";
import { settingsRouter } from "~/server/api/routers/settings"; import { settingsRouter } from "~/server/api/routers/settings";
import { emailRouter } from "~/server/api/routers/email"; import { emailRouter } from "~/server/api/routers/email";
import { dashboardRouter } from "~/server/api/routers/dashboard";
import { createCallerFactory, createTRPCRouter } from "~/server/api/trpc"; import { createCallerFactory, createTRPCRouter } from "~/server/api/trpc";
/** /**
@@ -16,6 +17,7 @@ export const appRouter = createTRPCRouter({
invoices: invoicesRouter, invoices: invoicesRouter,
settings: settingsRouter, settings: settingsRouter,
email: emailRouter, email: emailRouter,
dashboard: dashboardRouter,
}); });
// export type definition of API // export type definition of API

View File

@@ -0,0 +1,126 @@
import { z } from "zod";
import { createTRPCRouter, protectedProcedure } from "~/server/api/trpc";
import { invoices, clients } from "~/server/db/schema";
import { eq, and, desc, sql, gte, lt } from "drizzle-orm";
export const dashboardRouter = createTRPCRouter({
getStats: protectedProcedure.query(async ({ ctx }) => {
const userId = ctx.session.user.id;
const now = new Date();
const currentMonthStart = new Date(now.getFullYear(), now.getMonth(), 1);
const lastMonthStart = new Date(now.getFullYear(), now.getMonth() - 1, 1);
// 1. Fetch all invoices for the user to calculate stats
// Note: For very large datasets, we should use separate count/sum queries,
// but for typical usage, fetching fields is fine and allows flexible JS calculation
// where SQL complexity might be high (e.g. dynamic status).
// However, let's try to be efficient with SQL where possible.
const userInvoices = await ctx.db.query.invoices.findMany({
where: eq(invoices.createdById, userId),
columns: {
id: true,
totalAmount: true,
status: true,
dueDate: true,
issueDate: true,
},
});
const userClientsCount = await ctx.db.$count(
clients,
eq(clients.createdById, userId),
);
// Helper to check status
const getStatus = (inv: typeof userInvoices[0]) => {
if (inv.status === "paid") return "paid";
if (inv.status === "draft") return "draft";
if (new Date(inv.dueDate) < now && inv.status !== "paid") return "overdue";
return "sent";
};
// Calculate Stats
let totalRevenue = 0;
let pendingAmount = 0;
let overdueCount = 0;
let currentMonthRevenue = 0;
let lastMonthRevenue = 0;
for (const inv of userInvoices) {
const status = getStatus(inv);
const amount = inv.totalAmount;
const issueDate = new Date(inv.issueDate);
if (status === "paid") {
totalRevenue += amount;
if (issueDate >= currentMonthStart) {
currentMonthRevenue += amount;
} else if (issueDate >= lastMonthStart && issueDate < currentMonthStart) {
lastMonthRevenue += amount;
}
} else if (status === "sent" || status === "overdue") {
pendingAmount += amount;
}
if (status === "overdue") {
overdueCount++;
}
}
// Revenue Trend (Last 6 months)
const revenueByMonth: Record<string, number> = {};
for (let i = 0; i < 6; i++) {
const d = new Date(now.getFullYear(), now.getMonth() - i, 1);
const key = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`;
revenueByMonth[key] = 0;
}
for (const inv of userInvoices) {
if (getStatus(inv) === "paid") {
const d = new Date(inv.issueDate);
const key = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`;
if (revenueByMonth[key] !== undefined) {
revenueByMonth[key] += inv.totalAmount;
}
}
}
const revenueChartData = Object.entries(revenueByMonth)
.map(([month, revenue]) => ({
month,
revenue,
monthLabel: new Date(month + "-01").toLocaleDateString("en-US", {
month: "short",
year: "2-digit",
}),
}))
.sort((a, b) => a.month.localeCompare(b.month));
// Recent Activity
const recentInvoices = await ctx.db.query.invoices.findMany({
where: eq(invoices.createdById, userId),
orderBy: [desc(invoices.issueDate)],
limit: 5,
with: {
client: {
columns: { name: true },
},
},
});
return {
totalRevenue,
pendingAmount,
overdueCount,
totalClients: userClientsCount,
revenueChange: lastMonthRevenue > 0
? ((currentMonthRevenue - lastMonthRevenue) / lastMonthRevenue) * 100
: 0,
revenueChartData,
recentInvoices,
};
}),
});

View File

@@ -455,6 +455,8 @@
} }
body { body {
background-color: var(--background);
color: var(--foreground); color: var(--foreground);
} background-image: radial-gradient(var(--border) 1px, transparent 1px);
background-size: 24px 24px;
background-attachment: fixed;
}

View File

@@ -74,6 +74,12 @@ export default {
"navbar-foreground": "var(--navbar-foreground)", "navbar-foreground": "var(--navbar-foreground)",
"navbar-border": "var(--navbar-border)", "navbar-border": "var(--navbar-border)",
}, },
animation: {
"accordion-down": "accordion-down 0.2s ease-out",
"accordion-up": "accordion-up 0.2s ease-out",
"subtle-spin": "spin-slow 20s linear infinite",
"subtle-wave": "wave 15s ease-in-out infinite alternate",
},
keyframes: { keyframes: {
"accordion-down": { "accordion-down": {
from: { height: "0" }, from: { height: "0" },
@@ -83,10 +89,16 @@ export default {
from: { height: "var(--radix-accordion-content-height)" }, from: { height: "var(--radix-accordion-content-height)" },
to: { height: "0" }, to: { height: "0" },
}, },
}, "spin-slow": {
animation: { from: { transform: "rotate(0deg)" },
"accordion-down": "accordion-down 0.2s ease-out", to: { transform: "rotate(360deg)" },
"accordion-up": "accordion-up 0.2s ease-out", },
wave: {
"0%": { transform: "translate(0, 0) scale(1)" },
"33%": { transform: "translate(30px, -50px) scale(1.1)" },
"66%": { transform: "translate(-20px, 20px) scale(0.9)" },
"100%": { transform: "translate(20px, -30px) scale(1.05)" },
},
}, },
borderRadius: { borderRadius: {
lg: `var(--radius)`, lg: `var(--radius)`,