1. Dashboard & Analytics
Your Project Management App has pages for managing tasks and projects, but no home screen that tells you what’s actually going on. In this tutorial you’ll build a stats dashboard powered by DaaS aggregate queries — counting, grouping, and summarising data at the API level without loading every record into memory.
By the end you’ll have:
- A
/dashboardpage with live stat cards (total tasks, completed, overdue, done this month) - A “Tasks by Status” breakdown using
groupBy - A bar chart of the breakdown
- The dashboard wired directly to the data service’s aggregate queries
Prerequisites
- Completed Tutorial 8: Event Hooks & Extensions — or at minimum Tutorial 5, so
taskshas theworkflow_statefield (Todo, In Progress, In Review, Done). - At least 10 tasks in your database across different states and due dates to see meaningful stats.
The aggregate API — The /api/items/:collection endpoint accepts an aggregate parameter that computes count, sum, avg, min, max and a groupBy parameter that buckets results. Computation happens in the database, not in your app code. Your app’s own /api/items/[collection] route, installed by the CLI’s bootstrap, forwards these parameters to the data service with the signed-in user’s token. See the DaaS items documentation for the full filter syntax.
Scaffold the Dashboard Page
Ask your AI assistant to create the dashboard:
/create-feature dashboard page with task statsOr create app/[lang]/(authenticated)/dashboard/page.tsx yourself. Pages sit under app/[lang]/, so /dashboard opens /en/dashboard. The page fetches its stats with three aggregate queries and renders them as cards.
Fetch Task Counts by State
Use the groupBy aggregate to get task counts split by workflow_state in a single query:
GET /api/items/tasks
?aggregate[count]=*
&groupBy[]=workflow_stateResponse:
{
"data": [
{ "workflow_state": "Todo", "count": 8 },
{ "workflow_state": "In Progress", "count": 3 },
{ "workflow_state": "In Review", "count": 2 },
{ "workflow_state": "Done", "count": 14 }
]
}The page reads each query through a small helper that unwraps data:
async function aggregate<T>(query: string): Promise<T[]> {
const res = await fetch(`/api/items/tasks?${query}`, { cache: "no-store" });
if (!res.ok) throw new Error(`Request failed (${res.status})`);
const body = (await res.json()) as { data: T[] };
return body.data;
}Fetch the Overdue Task Count
Combine a filter with an aggregate to count only tasks that are overdue and not yet done:
GET /api/items/tasks
?aggregate[count]=*
&filter[due_date][_lt]=$NOW
&filter[workflow_state][_neq]=DoneThe answer is one row, { "data": [{ "count": 5 }] }.
Fetch Tasks Completed This Month
GET /api/items/tasks
?aggregate[count]=*
&filter[workflow_state][_eq]=Done
&filter[date_updated][_gte]=<first day of the month>Build the Stats Cards
Put the three queries together in the page. StatCard is a small component of the page itself:
"use client";
import { useEffect, useState } from "react";
import { SimpleGrid, Paper, Text, Title } from "@mantine/core";
interface StateCount {
workflow_state: string;
count: number;
}
async function aggregate<T>(query: string): Promise<T[]> {
const res = await fetch(`/api/items/tasks?${query}`, { cache: "no-store" });
if (!res.ok) throw new Error(`Request failed (${res.status})`);
const body = (await res.json()) as { data: T[] };
return body.data;
}
export default function DashboardPage() {
const [byState, setByState] = useState<StateCount[]>([]);
const [overdue, setOverdue] = useState(0);
const [doneThisMonth, setDoneThisMonth] = useState(0);
useEffect(() => {
const startOfMonth = new Date();
startOfMonth.setDate(1);
startOfMonth.setHours(0, 0, 0, 0);
aggregate<StateCount>("aggregate[count]=*&groupBy[]=workflow_state").then(setByState);
aggregate<{ count: number }>(
"aggregate[count]=*&filter[due_date][_lt]=$NOW&filter[workflow_state][_neq]=Done",
).then((rows) => setOverdue(rows[0]?.count ?? 0));
aggregate<{ count: number }>(
`aggregate[count]=*&filter[workflow_state][_eq]=Done&filter[date_updated][_gte]=${startOfMonth.toISOString()}`,
).then((rows) => setDoneThisMonth(rows[0]?.count ?? 0));
}, []);
const totalTasks = byState.reduce((sum, s) => sum + s.count, 0);
const doneTasks = byState.find((s) => s.workflow_state === "Done")?.count ?? 0;
return (
<div>
<Title order={2} mb="lg">Dashboard</Title>
<SimpleGrid cols={{ base: 2, md: 4 }} mb="xl">
<StatCard label="Total Tasks" value={totalTasks} />
<StatCard label="Completed" value={doneTasks} color="green" />
<StatCard label="Overdue" value={overdue} color="red" />
<StatCard label="Done This Month" value={doneThisMonth} color="blue" />
</SimpleGrid>
</div>
);
}
function StatCard({ label, value, color }: { label: string; value: number; color?: string }) {
return (
<Paper p="md" withBorder>
<Text size="sm" c="dimmed">{label}</Text>
<Text size="xl" fw={700} c={color}>{value}</Text>
</Paper>
);
}Add a Tasks by State Bar Chart
Install Mantine Charts, which a Buildpad app does not include by default:
pnpm add @mantine/charts@8 rechartsImport its styles once, in app/[lang]/layout.tsx next to the other Mantine styles: import "@mantine/charts/styles.css";. Then add the chart below the stat cards:
import { BarChart } from "@mantine/charts";
// Inside your component, below the stat cards:
const chartData = byState.map((s) => ({ state: s.workflow_state, count: s.count }));
return (
// ...stat cards above...
<Paper p="md" withBorder>
<Title order={4} mb="md">Tasks by State</Title>
<BarChart
h={240}
data={chartData}
dataKey="state"
series={[{ name: "count", color: "blue" }]}
/>
</Paper>
);Add the Dashboard to Navigation
Add an entry to NAV_ITEMS in components/layout/navigation.ts, above the buildpad:nav-insert line. Write the href without the language prefix:
import { IconHome, IconLayoutDashboard } from "@tabler/icons-react";
export const NAV_ITEMS: NavItem[] = [
{ label: "Home", labelKey: "app.nav.home", href: "/", icon: IconHome },
{ label: "Dashboard", href: "/dashboard", icon: IconLayoutDashboard },
// buildpad:nav-insert — installed route modules add entries above this line. Do not remove.
];Performance Notes
- Aggregate queries return one row (or one row per group) however many tasks exist — use them for any stat that would otherwise require fetching and counting records in JavaScript.
- The
groupByparameter can group by more than one field:&groupBy[]=workflow_state&groupBy[]=prioritygives you counts per state and priority. - Aggregates respect the signed-in user’s permissions: a user who can read only some tasks gets counts of those tasks only.
What’s Next
Your app now has a data-driven dashboard. When you’re ready to share it with real users, see 2. Deploying to Production.