feat: initial finance SPA — phases 1 & 2

Next.js 16 personal finance dashboard connected to postgres-personal.

Phase 1 (Foundation):
- API routes: GET /api/transactions (paginated, filterable, sortable),
  GET /api/statements, GET /api/merchants
- Transactions data table with date/category/bank/search filters, pagination, sort
- Statements card grid with period, due date, amount, transaction count
- Sidebar layout with nav for all planned sections

Phase 2 (Normalisation):
- PATCH /api/transactions/[id] — upsert transaction_overrides
- POST /api/transactions/bulk — bulk categorize/normalize
- Inline click-to-edit category (22 options) and merchant name
- Blue dot override indicator, bulk action bar
- Effective values via COALESCE(override, llm_value) pattern

Stack: Next.js 16 (App Router, standalone), Prisma 7.x + @prisma/adapter-pg,
TanStack Query, Tailwind CSS. Auth via Traefik chain-oauth@file.
This commit is contained in:
2026-03-07 23:31:40 +11:00
parent 28207b42b5
commit 35a5be97b0
31 changed files with 2243 additions and 99 deletions
+16
View File
@@ -0,0 +1,16 @@
import { NextRequest, NextResponse } from "next/server";
import { getMerchantSuggestions, getBankNames } from "@/lib/queries";
export async function GET(req: NextRequest) {
const search = req.nextUrl.searchParams.get("search");
const type = req.nextUrl.searchParams.get("type");
if (type === "banks") {
const banks = await getBankNames();
return NextResponse.json(banks.map((b) => b.bank_name));
}
if (!search) return NextResponse.json([]);
const merchants = await getMerchantSuggestions(search);
return NextResponse.json(merchants.map((m) => m.merchant));
}
+12
View File
@@ -0,0 +1,12 @@
import { NextRequest, NextResponse } from "next/server";
import { getStatementById } from "@/lib/queries";
export async function GET(
_req: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const { id } = await params;
const stmt = await getStatementById(Number(id));
if (!stmt) return NextResponse.json({ error: "Not found" }, { status: 404 });
return NextResponse.json(stmt);
}
+7
View File
@@ -0,0 +1,7 @@
import { NextResponse } from "next/server";
import { getStatements } from "@/lib/queries";
export async function GET() {
const statements = await getStatements();
return NextResponse.json(statements);
}
+46
View File
@@ -0,0 +1,46 @@
import { NextRequest, NextResponse } from "next/server";
import { getTransactionById } from "@/lib/queries";
import { prisma } from "@/lib/db";
export async function GET(
_req: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const { id } = await params;
const txn = await getTransactionById(Number(id));
if (!txn) return NextResponse.json({ error: "Not found" }, { status: 404 });
return NextResponse.json(txn);
}
export async function PATCH(
req: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const { id } = await params;
const transactionId = Number(id);
const body = await req.json();
const { category, merchant_normalized, notes } = body as {
category?: string;
merchant_normalized?: string;
notes?: string;
};
const data: Record<string, unknown> = { updated_at: new Date() };
if (category !== undefined) data.category_override = category;
if (merchant_normalized !== undefined) data.merchant_normalized = merchant_normalized;
if (notes !== undefined) data.notes = notes;
const override = await prisma.transaction_overrides.upsert({
where: { transaction_id: transactionId },
update: data,
create: {
transaction_id: transactionId,
category_override: category || null,
merchant_normalized: merchant_normalized || null,
notes: notes || null,
},
});
return NextResponse.json(override);
}
+42
View File
@@ -0,0 +1,42 @@
import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/db";
export async function POST(req: NextRequest) {
const body = await req.json();
const { action, ids, category, merchant_normalized } = body as {
action: string;
ids: number[];
category?: string;
merchant_normalized?: string;
};
if (!ids || !Array.isArray(ids) || ids.length === 0) {
return NextResponse.json({ error: "ids required" }, { status: 400 });
}
if (action === "categorize" && category) {
const ops = ids.map((id) =>
prisma.transaction_overrides.upsert({
where: { transaction_id: id },
update: { category_override: category, updated_at: new Date() },
create: { transaction_id: id, category_override: category },
})
);
await prisma.$transaction(ops);
return NextResponse.json({ updated: ids.length });
}
if (action === "normalize" && merchant_normalized) {
const ops = ids.map((id) =>
prisma.transaction_overrides.upsert({
where: { transaction_id: id },
update: { merchant_normalized, updated_at: new Date() },
create: { transaction_id: id, merchant_normalized },
})
);
await prisma.$transaction(ops);
return NextResponse.json({ updated: ids.length });
}
return NextResponse.json({ error: "Invalid action" }, { status: 400 });
}
+21
View File
@@ -0,0 +1,21 @@
import { NextRequest, NextResponse } from "next/server";
import { getTransactions } from "@/lib/queries";
export async function GET(req: NextRequest) {
const sp = req.nextUrl.searchParams;
const result = await getTransactions({
from: sp.get("from") || undefined,
to: sp.get("to") || undefined,
category: sp.get("category") || undefined,
bank_name: sp.get("bank_name") || undefined,
search: sp.get("search") || undefined,
statement_id: sp.get("statement_id") || undefined,
sort_by: sp.get("sort_by") || undefined,
sort_dir: sp.get("sort_dir") || undefined,
limit: sp.get("limit") ? Number(sp.get("limit")) : undefined,
offset: sp.get("offset") ? Number(sp.get("offset")) : undefined,
});
return NextResponse.json(result);
}
+8
View File
@@ -0,0 +1,8 @@
export default function BudgetPage() {
return (
<div>
<h2 className="text-xl font-semibold mb-4">Budget</h2>
<p className="text-zinc-500">Coming soon - monthly budgets and analytics.</p>
</div>
);
}
-20
View File
@@ -1,26 +1,6 @@
@import "tailwindcss";
:root {
--background: #ffffff;
--foreground: #171717;
}
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--font-sans: var(--font-geist-sans);
--font-mono: var(--font-geist-mono);
}
@media (prefers-color-scheme: dark) {
:root {
--background: #0a0a0a;
--foreground: #ededed;
}
}
body {
background: var(--background);
color: var(--foreground);
font-family: Arial, Helvetica, sans-serif;
}
+12 -5
View File
@@ -1,6 +1,8 @@
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
import { Providers } from "@/components/providers";
import { Sidebar } from "@/components/sidebar";
const geistSans = Geist({
variable: "--font-geist-sans",
@@ -13,8 +15,8 @@ const geistMono = Geist_Mono({
});
export const metadata: Metadata = {
title: "Create Next App",
description: "Generated by create next app",
title: "Finance",
description: "Personal Finance Dashboard",
};
export default function RootLayout({
@@ -23,11 +25,16 @@ export default function RootLayout({
children: React.ReactNode;
}>) {
return (
<html lang="en">
<html lang="en" className="dark">
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
className={`${geistSans.variable} ${geistMono.variable} antialiased bg-zinc-950 text-zinc-100`}
>
{children}
<Providers>
<div className="flex min-h-screen">
<Sidebar />
<main className="flex-1 p-6 overflow-auto">{children}</main>
</div>
</Providers>
</body>
</html>
);
+2 -62
View File
@@ -1,65 +1,5 @@
import Image from "next/image";
import { redirect } from "next/navigation";
export default function Home() {
return (
<div className="flex min-h-screen items-center justify-center bg-zinc-50 font-sans dark:bg-black">
<main className="flex min-h-screen w-full max-w-3xl flex-col items-center justify-between py-32 px-16 bg-white dark:bg-black sm:items-start">
<Image
className="dark:invert"
src="/next.svg"
alt="Next.js logo"
width={100}
height={20}
priority
/>
<div className="flex flex-col items-center gap-6 text-center sm:items-start sm:text-left">
<h1 className="max-w-xs text-3xl font-semibold leading-10 tracking-tight text-black dark:text-zinc-50">
To get started, edit the page.tsx file.
</h1>
<p className="max-w-md text-lg leading-8 text-zinc-600 dark:text-zinc-400">
Looking for a starting point or more instructions? Head over to{" "}
<a
href="https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
className="font-medium text-zinc-950 dark:text-zinc-50"
>
Templates
</a>{" "}
or the{" "}
<a
href="https://nextjs.org/learn?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
className="font-medium text-zinc-950 dark:text-zinc-50"
>
Learning
</a>{" "}
center.
</p>
</div>
<div className="flex flex-col gap-4 text-base font-medium sm:flex-row">
<a
className="flex h-12 w-full items-center justify-center gap-2 rounded-full bg-foreground px-5 text-background transition-colors hover:bg-[#383838] dark:hover:bg-[#ccc] md:w-[158px]"
href="https://vercel.com/new?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
className="dark:invert"
src="/vercel.svg"
alt="Vercel logomark"
width={16}
height={16}
/>
Deploy Now
</a>
<a
className="flex h-12 w-full items-center justify-center rounded-full border border-solid border-black/[.08] px-5 transition-colors hover:border-transparent hover:bg-black/[.04] dark:border-white/[.145] dark:hover:bg-[#1a1a1a] md:w-[158px]"
href="https://nextjs.org/docs?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
Documentation
</a>
</div>
</main>
</div>
);
redirect("/transactions");
}
+8
View File
@@ -0,0 +1,8 @@
export default function RulesPage() {
return (
<div>
<h2 className="text-xl font-semibold mb-4">Rules</h2>
<p className="text-zinc-500">Coming soon - auto-classify transactions with rules.</p>
</div>
);
}
+8
View File
@@ -0,0 +1,8 @@
export default function SharedPage() {
return (
<div>
<h2 className="text-xl font-semibold mb-4">Shared Expenses</h2>
<p className="text-zinc-500">Coming soon - track shared expenses and splits.</p>
</div>
);
}
+77
View File
@@ -0,0 +1,77 @@
"use client";
import Link from "next/link";
import { useStatements } from "@/lib/hooks";
function formatDate(d: string | null) {
if (!d) return "-";
return new Date(d).toLocaleDateString("en-AU", {
day: "2-digit",
month: "short",
year: "numeric",
});
}
function formatCurrency(amount: number | null, currency = "AUD") {
if (amount === null || amount === undefined) return "-";
return new Intl.NumberFormat("en-AU", {
style: "currency",
currency,
}).format(amount);
}
export default function StatementsPage() {
const { data: statements, isLoading } = useStatements();
return (
<div>
<h2 className="text-xl font-semibold mb-4">Statements</h2>
{isLoading ? (
<p className="text-zinc-500">Loading...</p>
) : !statements?.length ? (
<p className="text-zinc-500">No statements found</p>
) : (
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
{statements.map((s) => (
<div
key={s.id}
className="border border-zinc-800 rounded-lg p-4 bg-zinc-900/50 hover:border-zinc-700 transition-colors"
>
<div className="flex items-center justify-between mb-2">
<h3 className="font-medium">{s.bank_name}</h3>
<span className="text-xs text-zinc-500">{s.currency}</span>
</div>
{s.card_name && (
<p className="text-sm text-zinc-400 mb-2">{s.card_name}</p>
)}
<div className="text-sm text-zinc-400 space-y-1">
<p>Account: {s.account_number}</p>
<p>
Period: {formatDate(s.billing_start_date)} - {formatDate(s.billing_end_date)}
</p>
<p>Due: {formatDate(s.payment_due_date)}</p>
</div>
<div className="mt-3 pt-3 border-t border-zinc-800 flex items-center justify-between">
<div>
<p className="text-lg font-semibold text-red-400">
{formatCurrency(s.total_amount_due, s.currency)}
</p>
<p className="text-xs text-zinc-500">
{s.transaction_count} transactions
</p>
</div>
<Link
href={`/transactions?statement_id=${s.id}`}
className="px-3 py-1.5 bg-zinc-800 hover:bg-zinc-700 rounded text-sm transition-colors"
>
View
</Link>
</div>
</div>
))}
</div>
)}
</div>
);
}
+8
View File
@@ -0,0 +1,8 @@
export default function TagsPage() {
return (
<div>
<h2 className="text-xl font-semibold mb-4">Tags</h2>
<p className="text-zinc-500">Coming soon - tag transactions for trips, projects, and more.</p>
</div>
);
}
+358
View File
@@ -0,0 +1,358 @@
"use client";
import { useState, useCallback } from "react";
import { useTransactions, useBanks, useUpdateTransaction, useBulkAction } from "@/lib/hooks";
import { CATEGORIES, formatCategory } from "@/lib/categories";
function formatDate(d: string) {
return new Date(d).toLocaleDateString("en-AU", {
day: "2-digit",
month: "short",
year: "numeric",
});
}
function formatAmount(amount: number, type: string) {
const formatted = new Intl.NumberFormat("en-AU", {
style: "currency",
currency: "AUD",
}).format(amount);
return type === "debit" ? formatted : `+${formatted}`;
}
function TypeBadge({ type }: { type: string }) {
const colors: Record<string, string> = {
debit: "bg-red-900/30 text-red-400",
credit: "bg-green-900/30 text-green-400",
payment: "bg-blue-900/30 text-blue-400",
refund: "bg-emerald-900/30 text-emerald-400",
fee: "bg-yellow-900/30 text-yellow-400",
interest: "bg-orange-900/30 text-orange-400",
};
return (
<span className={`px-2 py-0.5 rounded text-xs font-medium ${colors[type] || "bg-zinc-800 text-zinc-400"}`}>
{type}
</span>
);
}
function InlineEdit({
value,
onSave,
type = "text",
options,
}: {
value: string;
onSave: (val: string) => void;
type?: "text" | "select";
options?: { value: string; label: string }[];
}) {
const [editing, setEditing] = useState(false);
const [draft, setDraft] = useState(value);
if (!editing) {
return (
<button
onClick={() => { setDraft(value); setEditing(true); }}
className="text-left hover:bg-zinc-800 px-1 -mx-1 rounded cursor-pointer transition-colors w-full truncate"
title="Click to edit"
>
{value || <span className="text-zinc-600 italic">unset</span>}
</button>
);
}
const commit = () => {
if (draft !== value) onSave(draft);
setEditing(false);
};
if (type === "select" && options) {
return (
<select
autoFocus
value={draft}
onChange={(e) => { setDraft(e.target.value); }}
onBlur={commit}
className="bg-zinc-800 border border-zinc-600 rounded px-1 py-0.5 text-sm w-full"
>
{options.map((o) => (
<option key={o.value} value={o.value}>{o.label}</option>
))}
</select>
);
}
return (
<input
autoFocus
value={draft}
onChange={(e) => setDraft(e.target.value)}
onBlur={commit}
onKeyDown={(e) => { if (e.key === "Enter") commit(); if (e.key === "Escape") setEditing(false); }}
className="bg-zinc-800 border border-zinc-600 rounded px-1 py-0.5 text-sm w-full"
/>
);
}
export default function TransactionsPage() {
const [filters, setFilters] = useState({
from: "",
to: "",
category: "",
bank_name: "",
search: "",
sort_by: "transaction_date",
sort_dir: "desc",
limit: 50,
offset: 0,
});
const [selected, setSelected] = useState<Set<number>>(new Set());
const [bulkCategory, setBulkCategory] = useState("");
const { data, isLoading } = useTransactions(filters);
const { data: banks } = useBanks();
const updateTxn = useUpdateTransaction();
const bulkAction = useBulkAction();
const toggleSelect = useCallback((id: number) => {
setSelected((prev) => {
const next = new Set(prev);
if (next.has(id)) next.delete(id);
else next.add(id);
return next;
});
}, []);
const toggleAll = useCallback(() => {
if (!data?.data) return;
setSelected((prev) => {
if (prev.size === data.data.length) return new Set();
return new Set(data.data.map((t) => t.id));
});
}, [data]);
const setPage = (newOffset: number) => {
setFilters((f) => ({ ...f, offset: newOffset }));
setSelected(new Set());
};
const toggleSort = (col: string) => {
setFilters((f) => ({
...f,
sort_by: col,
sort_dir: f.sort_by === col && f.sort_dir === "desc" ? "asc" : "desc",
offset: 0,
}));
};
const categoryOptions = CATEGORIES.map((c) => ({ value: c, label: formatCategory(c) }));
const totalPages = data ? Math.ceil(data.total / filters.limit) : 0;
const currentPage = Math.floor(filters.offset / filters.limit) + 1;
return (
<div>
<h2 className="text-xl font-semibold mb-4">Transactions</h2>
{/* Filter bar */}
<div className="flex flex-wrap gap-3 mb-4">
<input
type="text"
placeholder="Search..."
value={filters.search}
onChange={(e) => setFilters((f) => ({ ...f, search: e.target.value, offset: 0 }))}
className="bg-zinc-900 border border-zinc-700 rounded px-3 py-1.5 text-sm w-48"
/>
<input
type="date"
value={filters.from}
onChange={(e) => setFilters((f) => ({ ...f, from: e.target.value, offset: 0 }))}
className="bg-zinc-900 border border-zinc-700 rounded px-3 py-1.5 text-sm"
/>
<input
type="date"
value={filters.to}
onChange={(e) => setFilters((f) => ({ ...f, to: e.target.value, offset: 0 }))}
className="bg-zinc-900 border border-zinc-700 rounded px-3 py-1.5 text-sm"
/>
<select
value={filters.category}
onChange={(e) => setFilters((f) => ({ ...f, category: e.target.value, offset: 0 }))}
className="bg-zinc-900 border border-zinc-700 rounded px-3 py-1.5 text-sm"
>
<option value="">All Categories</option>
{CATEGORIES.map((c) => (
<option key={c} value={c}>{formatCategory(c)}</option>
))}
</select>
<select
value={filters.bank_name}
onChange={(e) => setFilters((f) => ({ ...f, bank_name: e.target.value, offset: 0 }))}
className="bg-zinc-900 border border-zinc-700 rounded px-3 py-1.5 text-sm"
>
<option value="">All Banks</option>
{banks?.map((b) => (
<option key={b} value={b}>{b}</option>
))}
</select>
</div>
{/* Bulk action bar */}
{selected.size > 0 && (
<div className="flex items-center gap-3 mb-3 p-2 bg-zinc-900 border border-zinc-700 rounded">
<span className="text-sm text-zinc-400">{selected.size} selected</span>
<select
value={bulkCategory}
onChange={(e) => setBulkCategory(e.target.value)}
className="bg-zinc-800 border border-zinc-600 rounded px-2 py-1 text-sm"
>
<option value="">Set category...</option>
{CATEGORIES.map((c) => (
<option key={c} value={c}>{formatCategory(c)}</option>
))}
</select>
<button
disabled={!bulkCategory || bulkAction.isPending}
onClick={() => {
bulkAction.mutate(
{ action: "categorize", ids: Array.from(selected), category: bulkCategory },
{ onSuccess: () => { setSelected(new Set()); setBulkCategory(""); } }
);
}}
className="px-3 py-1 bg-blue-600 hover:bg-blue-700 disabled:opacity-50 rounded text-sm"
>
Apply
</button>
<button
onClick={() => setSelected(new Set())}
className="px-3 py-1 text-zinc-400 hover:text-white text-sm"
>
Clear
</button>
</div>
)}
{/* Table */}
<div className="overflow-x-auto border border-zinc-800 rounded-lg">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-zinc-800 bg-zinc-900/50">
<th className="p-2 w-8">
<input
type="checkbox"
checked={data?.data.length ? selected.size === data.data.length : false}
onChange={toggleAll}
className="accent-blue-600"
/>
</th>
<th
className="p-2 text-left cursor-pointer hover:text-white"
onClick={() => toggleSort("transaction_date")}
>
Date {filters.sort_by === "transaction_date" && (filters.sort_dir === "desc" ? "\u2193" : "\u2191")}
</th>
<th className="p-2 text-left">Description</th>
<th className="p-2 text-left">Merchant</th>
<th
className="p-2 text-right cursor-pointer hover:text-white"
onClick={() => toggleSort("amount")}
>
Amount {filters.sort_by === "amount" && (filters.sort_dir === "desc" ? "\u2193" : "\u2191")}
</th>
<th className="p-2 text-left">Type</th>
<th className="p-2 text-left">Category</th>
<th className="p-2 text-left">Bank</th>
</tr>
</thead>
<tbody>
{isLoading ? (
<tr><td colSpan={8} className="p-8 text-center text-zinc-500">Loading...</td></tr>
) : !data?.data.length ? (
<tr><td colSpan={8} className="p-8 text-center text-zinc-500">No transactions found</td></tr>
) : (
data.data.map((t) => (
<tr
key={t.id}
className={`border-b border-zinc-800/50 hover:bg-zinc-900/30 ${
selected.has(t.id) ? "bg-zinc-800/40" : ""
}`}
>
<td className="p-2">
<input
type="checkbox"
checked={selected.has(t.id)}
onChange={() => toggleSelect(t.id)}
className="accent-blue-600"
/>
</td>
<td className="p-2 whitespace-nowrap">{formatDate(t.transaction_date)}</td>
<td className="p-2 max-w-xs truncate" title={t.description}>{t.description}</td>
<td className="p-2 max-w-[150px]">
<div className="relative">
<InlineEdit
value={t.effective_merchant || ""}
onSave={(val) => updateTxn.mutate({ id: t.id, merchant_normalized: val })}
/>
{t.merchant_override && (
<span className="absolute -left-2 top-1/2 -translate-y-1/2 w-1.5 h-1.5 bg-blue-500 rounded-full" title="Manually overridden" />
)}
</div>
</td>
<td className={`p-2 text-right whitespace-nowrap font-mono ${
t.transaction_type === "debit" ? "text-red-400" : "text-green-400"
}`}>
{formatAmount(t.amount, t.transaction_type)}
</td>
<td className="p-2"><TypeBadge type={t.transaction_type} /></td>
<td className="p-2 max-w-[140px]">
<div className="relative">
<InlineEdit
value={t.effective_category}
onSave={(val) => updateTxn.mutate({ id: t.id, category: val })}
type="select"
options={categoryOptions}
/>
{t.category_override && (
<span className="absolute -left-2 top-1/2 -translate-y-1/2 w-1.5 h-1.5 bg-blue-500 rounded-full" title="Manually overridden" />
)}
</div>
</td>
<td className="p-2 text-zinc-400 whitespace-nowrap">{t.bank_name}</td>
</tr>
))
)}
</tbody>
</table>
</div>
{/* Pagination */}
{data && data.total > filters.limit && (
<div className="flex items-center justify-between mt-4">
<span className="text-sm text-zinc-500">
Showing {filters.offset + 1}-{Math.min(filters.offset + filters.limit, data.total)} of {data.total}
</span>
<div className="flex gap-2">
<button
disabled={currentPage <= 1}
onClick={() => setPage(filters.offset - filters.limit)}
className="px-3 py-1 bg-zinc-800 hover:bg-zinc-700 disabled:opacity-50 rounded text-sm"
>
Previous
</button>
<span className="px-3 py-1 text-sm text-zinc-400">
Page {currentPage} of {totalPages}
</span>
<button
disabled={currentPage >= totalPages}
onClick={() => setPage(filters.offset + filters.limit)}
className="px-3 py-1 bg-zinc-800 hover:bg-zinc-700 disabled:opacity-50 rounded text-sm"
>
Next
</button>
</div>
</div>
)}
</div>
);
}