Implement expense tracking foundation for v1

This commit is contained in:
2026-03-23 12:32:36 -04:00
parent 5d7e25c015
commit 905af75cd8
39 changed files with 9923 additions and 9 deletions

2
.env.example Normal file
View File

@@ -0,0 +1,2 @@
DATABASE_URL="file:./prisma/dev.db"
OPENAI_API_KEY=""

18
eslint.config.mjs Normal file
View File

@@ -0,0 +1,18 @@
import { defineConfig, globalIgnores } from "eslint/config";
import nextVitals from "eslint-config-next/core-web-vitals";
import nextTs from "eslint-config-next/typescript";
const eslintConfig = defineConfig([
...nextVitals,
...nextTs,
// Override default ignores of eslint-config-next.
globalIgnores([
// Default ignores of eslint-config-next:
".next/**",
"out/**",
"build/**",
"next-env.d.ts",
]),
]);
export default eslintConfig;

6
next-env.d.ts vendored Normal file
View File

@@ -0,0 +1,6 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
import "./.next/types/routes.d.ts";
// NOTE: This file should not be edited
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.

7
next.config.ts Normal file
View File

@@ -0,0 +1,7 @@
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
/* config options here */
};
export default nextConfig;

View File

@@ -1,21 +1,21 @@
## 1. Project setup ## 1. Project setup
- [ ] 1.1 Scaffold the `Next.js` app with TypeScript, linting, and baseline project configuration. - [x] 1.1 Scaffold the `Next.js` app with TypeScript, linting, and baseline project configuration.
- [ ] 1.2 Add runtime dependencies for Prisma, SQLite, validation, charts, and `OpenAI` integration. - [x] 1.2 Add runtime dependencies for Prisma, SQLite, validation, charts, and `OpenAI` integration.
- [ ] 1.3 Add development dependencies and scripts for testing, Prisma generation, and local development. - [x] 1.3 Add development dependencies and scripts for testing, Prisma generation, and local development.
- [ ] 1.4 Add base environment and ignore-file setup for local database and API key configuration. - [x] 1.4 Add base environment and ignore-file setup for local database and API key configuration.
## 2. Persistence and shared services ## 2. Persistence and shared services
- [ ] 2.1 Define Prisma models for `Expense`, `Paycheck`, and `MonthlyInsight` and create the initial SQLite migration. - [x] 2.1 Define Prisma models for `Expense`, `Paycheck`, and `MonthlyInsight` and create the initial SQLite migration.
- [ ] 2.2 Implement shared validation schemas for expenses, paychecks, and month query parameters. - [x] 2.2 Implement shared validation schemas for expenses, paychecks, and month query parameters.
- [ ] 2.3 Implement shared money and local-date utilities for month boundary calculations. - [x] 2.3 Implement shared money and local-date utilities for month boundary calculations.
## 3. Expense and paycheck workflows ## 3. Expense and paycheck workflows
- [ ] 3.1 Implement expense API routes for create, list, and delete operations. - [x] 3.1 Implement expense API routes for create, list, and delete operations.
- [ ] 3.2 Implement paycheck API routes for create, list, and delete operations. - [ ] 3.2 Implement paycheck API routes for create, list, and delete operations.
- [ ] 3.3 Build the `Add Expense` view with form submission, validation feedback, and expense listing. - [x] 3.3 Build the `Add Expense` view with form submission, validation feedback, and expense listing.
- [ ] 3.4 Build the `Income/Paychecks` view with form submission, validation feedback, and paycheck listing. - [ ] 3.4 Build the `Income/Paychecks` view with form submission, validation feedback, and paycheck listing.
## 4. Dashboard and insights ## 4. Dashboard and insights

8831
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

36
package.json Normal file
View File

@@ -0,0 +1,36 @@
{
"name": "monthly-expense-tracker",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "eslint",
"test": "vitest run",
"test:watch": "vitest",
"prisma:generate": "prisma generate",
"prisma:migrate": "prisma migrate dev"
},
"dependencies": {
"@prisma/client": "^6.6.0",
"next": "16.2.1",
"openai": "^5.10.2",
"react": "19.2.4",
"react-dom": "19.2.4",
"recharts": "^2.15.4",
"zod": "^3.24.2"
},
"devDependencies": {
"@tailwindcss/postcss": "^4",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"eslint": "^9",
"eslint-config-next": "16.2.1",
"prisma": "^6.6.0",
"tailwindcss": "^4",
"typescript": "^5",
"vitest": "^3.1.1"
}
}

7
postcss.config.mjs Normal file
View File

@@ -0,0 +1,7 @@
const config = {
plugins: {
"@tailwindcss/postcss": {},
},
};
export default config;

View File

@@ -0,0 +1,28 @@
-- CreateTable
CREATE TABLE "Expense" (
"id" TEXT NOT NULL PRIMARY KEY,
"date" TEXT NOT NULL,
"title" TEXT NOT NULL,
"amountCents" INTEGER NOT NULL,
"category" TEXT NOT NULL,
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
);
-- CreateTable
CREATE TABLE "Paycheck" (
"id" TEXT NOT NULL PRIMARY KEY,
"payDate" TEXT NOT NULL,
"amountCents" INTEGER NOT NULL,
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
);
-- CreateTable
CREATE TABLE "MonthlyInsight" (
"id" TEXT NOT NULL PRIMARY KEY,
"month" TEXT NOT NULL,
"year" INTEGER NOT NULL,
"generatedAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
"summary" TEXT NOT NULL,
"recommendations" TEXT NOT NULL,
"inputSnapshot" TEXT NOT NULL
);

View File

@@ -0,0 +1,3 @@
# Please do not edit this file manually
# It should be added in your version-control system (e.g., Git)
provider = "sqlite"

BIN
prisma/prisma/dev.db Normal file

Binary file not shown.

45
prisma/schema.prisma Normal file
View File

@@ -0,0 +1,45 @@
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "sqlite"
url = env("DATABASE_URL")
}
enum Category {
RENT
FOOD
TRANSPORT
BILLS
SHOPPING
HEALTH
ENTERTAINMENT
MISC
}
model Expense {
id String @id @default(cuid())
date String
title String
amountCents Int
category Category
createdAt DateTime @default(now())
}
model Paycheck {
id String @id @default(cuid())
payDate String
amountCents Int
createdAt DateTime @default(now())
}
model MonthlyInsight {
id String @id @default(cuid())
month String
year Int
generatedAt DateTime @default(now())
summary String
recommendations String
inputSnapshot String
}

1
public/file.svg Normal file
View File

@@ -0,0 +1 @@
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>

After

Width:  |  Height:  |  Size: 391 B

1
public/globe.svg Normal file
View File

@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>

After

Width:  |  Height:  |  Size: 1.0 KiB

1
public/next.svg Normal file
View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

1
public/vercel.svg Normal file
View File

@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>

After

Width:  |  Height:  |  Size: 128 B

1
public/window.svg Normal file
View File

@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>

After

Width:  |  Height:  |  Size: 385 B

View File

@@ -0,0 +1,22 @@
import { ExpenseWorkspace } from "@/components/expense-workspace";
import { CATEGORY_OPTIONS } from "@/lib/categories";
export const metadata = {
title: "Add Expense | Monthy Tracker",
};
export default function AddExpensePage() {
return (
<div className="space-y-8">
<header className="max-w-2xl space-y-3">
<p className="text-sm font-semibold uppercase tracking-[0.28em] text-amber-700">Add Expense</p>
<h1 className="text-4xl font-semibold text-stone-950">Capture spending while it still feels fresh.</h1>
<p className="text-lg leading-8 text-stone-600">
This first slice focuses on fast local entry. Each saved expense appears immediately in your running history.
</p>
</header>
<ExpenseWorkspace categoryOptions={CATEGORY_OPTIONS.map((option) => ({ ...option }))} />
</div>
);
}

View File

@@ -0,0 +1,26 @@
import { Prisma } from "@prisma/client";
import { NextResponse } from "next/server";
import { removeExpense } from "@/lib/expenses";
type RouteContext = {
params: Promise<{ id: string }>;
};
export async function DELETE(_: Request, context: RouteContext) {
const { id } = await context.params;
try {
await removeExpense(id);
return new NextResponse(null, { status: 204 });
} catch (error) {
if (
error instanceof Prisma.PrismaClientKnownRequestError &&
error.code === "P2025"
) {
return NextResponse.json({ error: "Expense not found." }, { status: 404 });
}
throw error;
}
}

30
src/app/expenses/route.ts Normal file
View File

@@ -0,0 +1,30 @@
import { NextResponse } from "next/server";
import { createExpense, listExpenses } from "@/lib/expenses";
import { expenseInputSchema } from "@/lib/validation";
export async function GET() {
const expenses = await listExpenses();
return NextResponse.json({ expenses });
}
export async function POST(request: Request) {
const payload = await request.json();
const parsed = expenseInputSchema.safeParse(payload);
if (!parsed.success) {
return NextResponse.json(
{ error: parsed.error.issues[0]?.message ?? "Invalid expense payload." },
{ status: 400 },
);
}
const expense = await createExpense({
title: parsed.data.title,
amountCents: parsed.data.amount,
date: parsed.data.date,
category: parsed.data.category,
});
return NextResponse.json({ expense }, { status: 201 });
}

BIN
src/app/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

41
src/app/globals.css Normal file
View File

@@ -0,0 +1,41 @@
@import "tailwindcss";
:root {
--background: #ffffff;
--foreground: #171717;
}
@theme inline {
--color-background: #fbfaf7;
--color-foreground: #1c1917;
--font-sans: var(--font-body);
--font-heading: var(--font-heading);
}
* {
box-sizing: border-box;
}
html {
scroll-behavior: smooth;
}
body {
background: var(--background);
color: var(--foreground);
font-family: var(--font-body), sans-serif;
}
h1,
h2,
h3,
h4 {
font-family: var(--font-heading), serif;
}
a,
button,
input,
select {
transition-duration: 180ms;
}

15
src/app/income/page.tsx Normal file
View File

@@ -0,0 +1,15 @@
export const metadata = {
title: "Income & Paychecks | Monthy Tracker",
};
export default function IncomePage() {
return (
<div className="rounded-[2rem] border border-stone-200 bg-white p-8 shadow-[0_24px_60px_rgba(120,90,50,0.08)]">
<p className="text-sm font-semibold uppercase tracking-[0.28em] text-stone-500">Coming next</p>
<h1 className="mt-3 text-4xl font-semibold text-stone-950">Paycheck tracking lands in the next implementation slice.</h1>
<p className="mt-4 max-w-2xl text-lg leading-8 text-stone-600">
The data model is already prepared for paychecks. This view will add create, list, and delete flows after expense tracking is validated.
</p>
</div>
);
}

47
src/app/layout.tsx Normal file
View File

@@ -0,0 +1,47 @@
import type { Metadata } from "next";
import { Fraunces, Manrope } from "next/font/google";
import { SiteNav } from "@/components/site-nav";
import "./globals.css";
const headingFont = Fraunces({
variable: "--font-heading",
subsets: ["latin"],
});
const bodyFont = Manrope({
variable: "--font-body",
subsets: ["latin"],
});
export const metadata: Metadata = {
title: "Monthy Tracker",
description: "Local-first monthly expense tracking with AI insights.",
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html
lang="en"
className={`${headingFont.variable} ${bodyFont.variable} h-full antialiased`}
>
<body className="min-h-full bg-[linear-gradient(180deg,#f8f3ea_0%,#f5efe4_28%,#fbfaf7_100%)] text-stone-950">
<div className="mx-auto flex min-h-full w-full max-w-7xl flex-col px-4 py-6 sm:px-6 lg:px-8">
<header className="mb-10 flex flex-col gap-4 rounded-[2rem] border border-white/70 bg-white/80 px-6 py-5 shadow-[0_20px_50px_rgba(120,90,50,0.08)] backdrop-blur sm:flex-row sm:items-center sm:justify-between">
<div>
<p className="text-xs font-semibold uppercase tracking-[0.28em] text-amber-700">Monthy Tracker</p>
<p className="mt-2 text-lg text-stone-600">Track the month as it unfolds, not after it slips away.</p>
</div>
<SiteNav />
</header>
<main className="flex-1 pb-10">{children}</main>
</div>
</body>
</html>
);
}

94
src/app/page.tsx Normal file
View File

@@ -0,0 +1,94 @@
import Link from "next/link";
import { unstable_noStore as noStore } from "next/cache";
import { getCategoryLabel } from "@/lib/categories";
import { getMonthLabel } from "@/lib/date";
import { getExpenseDashboardPreview } from "@/lib/expenses";
import { formatCurrencyFromCents } from "@/lib/money";
export const dynamic = "force-dynamic";
export default async function Home() {
noStore();
const preview = await getExpenseDashboardPreview();
return (
<div className="space-y-10">
<section className="grid gap-6 rounded-[2rem] border border-stone-200 bg-[radial-gradient(circle_at_top_left,_rgba(251,191,36,0.26),_transparent_32%),linear-gradient(135deg,#fffaf2,#f3efe7)] p-8 shadow-[0_28px_70px_rgba(120,90,50,0.10)] lg:grid-cols-[1.2fr_0.8fr]">
<div className="space-y-5">
<p className="text-sm font-semibold uppercase tracking-[0.28em] text-amber-700">Monthly Expense Tracker</p>
<h1 className="max-w-3xl text-5xl font-semibold leading-tight text-stone-950">
A calm local-first home for everyday spending.
</h1>
<p className="max-w-2xl text-lg leading-8 text-stone-600">
The dashboard is starting with the expense-tracking slice first: fast entry, visible history, and a live pulse on the current month.
</p>
<div className="flex flex-wrap gap-3">
<Link
href="/add-expense"
className="rounded-full bg-stone-950 px-5 py-3 text-sm font-semibold text-white transition hover:bg-stone-800"
>
Add an expense
</Link>
<Link
href="/income"
className="rounded-full border border-stone-300 bg-white px-5 py-3 text-sm font-semibold text-stone-800 transition hover:border-stone-900"
>
View paycheck plan
</Link>
</div>
</div>
<div className="rounded-[1.75rem] border border-white/80 bg-white/90 p-6">
<p className="text-sm font-semibold uppercase tracking-[0.24em] text-stone-500">This month</p>
<h2 className="mt-2 text-3xl font-semibold text-stone-950">{getMonthLabel(preview.month)}</h2>
<div className="mt-6 grid gap-4 sm:grid-cols-2">
<article className="rounded-3xl bg-stone-950 px-4 py-5 text-white">
<p className="text-xs uppercase tracking-[0.2em] text-stone-300">Total spent</p>
<p className="mt-3 text-3xl font-semibold">{formatCurrencyFromCents(preview.totalSpentCents)}</p>
</article>
<article className="rounded-3xl bg-amber-50 px-4 py-5 text-stone-950">
<p className="text-xs uppercase tracking-[0.2em] text-amber-700">Entries logged</p>
<p className="mt-3 text-3xl font-semibold">{preview.expenseCount}</p>
</article>
</div>
</div>
</section>
<section className="rounded-[2rem] border border-stone-200 bg-white p-8 shadow-[0_24px_60px_rgba(120,90,50,0.08)]">
<div className="flex items-center justify-between gap-4">
<div>
<p className="text-sm font-semibold uppercase tracking-[0.24em] text-stone-500">Recent expense pulse</p>
<h2 className="mt-2 text-3xl font-semibold text-stone-950">Latest entries</h2>
</div>
<Link href="/add-expense" className="text-sm font-semibold text-amber-800 transition hover:text-stone-950">
Manage expenses
</Link>
</div>
<div className="mt-6 grid gap-3">
{preview.recentExpenses.length === 0 ? (
<div className="rounded-3xl border border-dashed border-stone-300 px-4 py-10 text-center text-stone-600">
No expenses recorded yet. Start with one quick entry.
</div>
) : (
preview.recentExpenses.map((expense) => (
<article
key={expense.id}
className="flex flex-wrap items-center justify-between gap-3 rounded-3xl border border-stone-200 bg-[#fffcf7] px-4 py-4"
>
<div>
<p className="font-semibold text-stone-950">{expense.title}</p>
<p className="mt-1 text-sm text-stone-600">
{expense.date} · {getCategoryLabel(expense.category)}
</p>
</div>
<p className="font-semibold text-stone-950">{formatCurrencyFromCents(expense.amountCents)}</p>
</article>
))
)}
</div>
</section>
</div>
);
}

View File

@@ -0,0 +1,209 @@
"use client";
import { useEffect, useMemo, useState, type FormEvent } from "react";
import { getCategoryLabel, type CategoryValue } from "@/lib/categories";
import { formatCurrencyFromCents } from "@/lib/money";
type ExpenseRecord = {
id: string;
title: string;
amountCents: number;
date: string;
category: CategoryValue;
};
type CategoryOption = {
value: string;
label: string;
};
type Props = {
categoryOptions: CategoryOption[];
};
export function ExpenseWorkspace({ categoryOptions }: Props) {
const [expenses, setExpenses] = useState<ExpenseRecord[]>([]);
const [formState, setFormState] = useState({
title: "",
amount: "",
date: new Date().toISOString().slice(0, 10),
category: categoryOptions[0]?.value ?? "",
});
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
async function loadExpenses() {
const response = await fetch("/expenses", { cache: "no-store" });
const payload = (await response.json()) as { expenses?: ExpenseRecord[] };
setExpenses(payload.expenses ?? []);
}
void loadExpenses();
}, []);
const totalSpent = useMemo(
() => expenses.reduce((sum, expense) => sum + expense.amountCents, 0),
[expenses],
);
async function handleSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
setBusy(true);
setError(null);
const response = await fetch("/expenses", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(formState),
});
setBusy(false);
if (!response.ok) {
const payload = (await response.json().catch(() => null)) as { error?: string } | null;
setError(payload?.error ?? "Could not save the expense.");
return;
}
const payload = (await response.json()) as { expense: ExpenseRecord };
setExpenses((current) => [payload.expense, ...current]);
setFormState((current) => ({ ...current, title: "", amount: "" }));
}
async function handleDelete(id: string) {
setBusy(true);
setError(null);
const response = await fetch(`/expenses/${id}`, { method: "DELETE" });
setBusy(false);
if (!response.ok) {
setError("Could not delete the expense.");
return;
}
setExpenses((current) => current.filter((expense) => expense.id !== id));
}
return (
<div className="grid gap-6 lg:grid-cols-[1.1fr_0.9fr]">
<section className="rounded-[2rem] border border-stone-200 bg-white p-6 shadow-[0_24px_60px_rgba(120,90,50,0.08)]">
<div className="mb-6 flex items-center justify-between gap-4">
<div>
<p className="text-sm font-semibold uppercase tracking-[0.24em] text-amber-700">Daily entry</p>
<h2 className="mt-2 text-3xl font-semibold text-stone-950">Log today&apos;s spend in seconds</h2>
</div>
<div className="rounded-2xl bg-amber-50 px-4 py-3 text-right">
<p className="text-xs uppercase tracking-[0.2em] text-amber-700">Current list total</p>
<p className="mt-1 text-2xl font-semibold text-stone-950">{formatCurrencyFromCents(totalSpent)}</p>
</div>
</div>
<form className="grid gap-4 md:grid-cols-2" onSubmit={handleSubmit}>
<label className="grid gap-2 text-sm font-medium text-stone-700 md:col-span-2">
Title
<input
required
value={formState.title}
onChange={(event) => setFormState((current) => ({ ...current, title: event.target.value }))}
className="rounded-2xl border border-stone-300 bg-stone-50 px-4 py-3 outline-none transition focus:border-stone-900"
placeholder="Groceries, rent, train pass..."
/>
</label>
<label className="grid gap-2 text-sm font-medium text-stone-700">
Amount
<input
required
inputMode="decimal"
value={formState.amount}
onChange={(event) => setFormState((current) => ({ ...current, amount: event.target.value }))}
className="rounded-2xl border border-stone-300 bg-stone-50 px-4 py-3 outline-none transition focus:border-stone-900"
placeholder="42.50"
/>
</label>
<label className="grid gap-2 text-sm font-medium text-stone-700">
Date
<input
required
type="date"
value={formState.date}
onChange={(event) => setFormState((current) => ({ ...current, date: event.target.value }))}
className="rounded-2xl border border-stone-300 bg-stone-50 px-4 py-3 outline-none transition focus:border-stone-900"
/>
</label>
<label className="grid gap-2 text-sm font-medium text-stone-700 md:col-span-2">
Category
<select
value={formState.category}
onChange={(event) => setFormState((current) => ({ ...current, category: event.target.value }))}
className="rounded-2xl border border-stone-300 bg-stone-50 px-4 py-3 outline-none transition focus:border-stone-900"
>
{categoryOptions.map((option) => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</select>
</label>
<div className="md:col-span-2 flex items-center justify-between gap-3">
<p className="text-sm text-rose-700">{error}</p>
<button
type="submit"
disabled={busy}
className="rounded-full bg-stone-950 px-5 py-3 text-sm font-semibold text-white transition hover:bg-stone-800 disabled:cursor-not-allowed disabled:bg-stone-400"
>
{busy ? "Saving..." : "Save expense"}
</button>
</div>
</form>
</section>
<section className="rounded-[2rem] border border-stone-200 bg-[#fffaf2] p-6 shadow-[0_24px_60px_rgba(120,90,50,0.08)]">
<div className="mb-5">
<p className="text-sm font-semibold uppercase tracking-[0.24em] text-stone-500">Recent entries</p>
<h2 className="mt-2 text-2xl font-semibold text-stone-950">Expense history</h2>
</div>
<div className="space-y-3">
{expenses.length === 0 ? (
<div className="rounded-3xl border border-dashed border-stone-300 px-4 py-6 text-sm text-stone-600">
No expenses yet. Add your first entry to start the month.
</div>
) : (
expenses.map((expense) => (
<article
key={expense.id}
className="flex items-center justify-between gap-4 rounded-3xl border border-stone-200 bg-white px-4 py-4"
>
<div>
<p className="font-semibold text-stone-950">{expense.title}</p>
<p className="mt-1 text-sm text-stone-600">
{expense.date} · {getCategoryLabel(expense.category)}
</p>
</div>
<div className="flex items-center gap-4">
<p className="font-semibold text-stone-950">{formatCurrencyFromCents(expense.amountCents)}</p>
<button
type="button"
onClick={() => handleDelete(expense.id)}
className="rounded-full border border-stone-300 px-3 py-2 text-xs font-semibold uppercase tracking-[0.2em] text-stone-600 transition hover:border-rose-400 hover:text-rose-600"
>
Delete
</button>
</div>
</article>
))
)}
</div>
</section>
</div>
);
}

View File

@@ -0,0 +1,121 @@
"use client";
import Link from "next/link";
import { useEffect, useMemo, useState } from "react";
import { getCategoryLabel, type CategoryValue } from "@/lib/categories";
import { getCurrentMonthKey, getMonthLabel, isDateInMonth } from "@/lib/date";
import { formatCurrencyFromCents } from "@/lib/money";
type ExpenseRecord = {
id: string;
title: string;
amountCents: number;
date: string;
category: CategoryValue;
};
export function HomeDashboard() {
const [expenses, setExpenses] = useState<ExpenseRecord[]>([]);
useEffect(() => {
async function loadExpenses() {
const response = await fetch("/expenses", { cache: "no-store" });
const payload = (await response.json()) as { expenses?: ExpenseRecord[] };
setExpenses(payload.expenses ?? []);
}
void loadExpenses();
}, []);
const month = getCurrentMonthKey();
const monthExpenses = useMemo(
() => expenses.filter((expense) => isDateInMonth(expense.date, month)),
[expenses, month],
);
const recentExpenses = useMemo(() => monthExpenses.slice(0, 6), [monthExpenses]);
const totalSpentCents = useMemo(
() => monthExpenses.reduce((sum, expense) => sum + expense.amountCents, 0),
[monthExpenses],
);
return (
<div className="space-y-10">
<section className="grid gap-6 rounded-[2rem] border border-stone-200 bg-[radial-gradient(circle_at_top_left,_rgba(251,191,36,0.26),_transparent_32%),linear-gradient(135deg,#fffaf2,#f3efe7)] p-8 shadow-[0_28px_70px_rgba(120,90,50,0.10)] lg:grid-cols-[1.2fr_0.8fr]">
<div className="space-y-5">
<p className="text-sm font-semibold uppercase tracking-[0.28em] text-amber-700">Monthly Expense Tracker</p>
<h1 className="max-w-3xl text-5xl font-semibold leading-tight text-stone-950">
A calm local-first home for everyday spending.
</h1>
<p className="max-w-2xl text-lg leading-8 text-stone-600">
The dashboard is starting with the expense-tracking slice first: fast entry, visible history, and a live pulse on the current month.
</p>
<div className="flex flex-wrap gap-3">
<Link
href="/add-expense"
className="rounded-full bg-stone-950 px-5 py-3 text-sm font-semibold text-white transition hover:bg-stone-800"
>
Add an expense
</Link>
<Link
href="/income"
className="rounded-full border border-stone-300 bg-white px-5 py-3 text-sm font-semibold text-stone-800 transition hover:border-stone-900"
>
View paycheck plan
</Link>
</div>
</div>
<div className="rounded-[1.75rem] border border-white/80 bg-white/90 p-6">
<p className="text-sm font-semibold uppercase tracking-[0.24em] text-stone-500">This month</p>
<h2 className="mt-2 text-3xl font-semibold text-stone-950">{getMonthLabel(month)}</h2>
<div className="mt-6 grid gap-4 sm:grid-cols-2">
<article className="rounded-3xl bg-stone-950 px-4 py-5 text-white">
<p className="text-xs uppercase tracking-[0.2em] text-stone-300">Total spent</p>
<p className="mt-3 text-3xl font-semibold">{formatCurrencyFromCents(totalSpentCents)}</p>
</article>
<article className="rounded-3xl bg-amber-50 px-4 py-5 text-stone-950">
<p className="text-xs uppercase tracking-[0.2em] text-amber-700">Entries logged</p>
<p className="mt-3 text-3xl font-semibold">{monthExpenses.length}</p>
</article>
</div>
</div>
</section>
<section className="rounded-[2rem] border border-stone-200 bg-white p-8 shadow-[0_24px_60px_rgba(120,90,50,0.08)]">
<div className="flex items-center justify-between gap-4">
<div>
<p className="text-sm font-semibold uppercase tracking-[0.24em] text-stone-500">Recent expense pulse</p>
<h2 className="mt-2 text-3xl font-semibold text-stone-950">Latest entries</h2>
</div>
<Link href="/add-expense" className="text-sm font-semibold text-amber-800 transition hover:text-stone-950">
Manage expenses
</Link>
</div>
<div className="mt-6 grid gap-3">
{recentExpenses.length === 0 ? (
<div className="rounded-3xl border border-dashed border-stone-300 px-4 py-10 text-center text-stone-600">
No expenses recorded yet. Start with one quick entry.
</div>
) : (
recentExpenses.map((expense) => (
<article
key={expense.id}
className="flex flex-wrap items-center justify-between gap-3 rounded-3xl border border-stone-200 bg-[#fffcf7] px-4 py-4"
>
<div>
<p className="font-semibold text-stone-950">{expense.title}</p>
<p className="mt-1 text-sm text-stone-600">
{expense.date} · {getCategoryLabel(expense.category)}
</p>
</div>
<p className="font-semibold text-stone-950">{formatCurrencyFromCents(expense.amountCents)}</p>
</article>
))
)}
</div>
</section>
</div>
);
}

View File

@@ -0,0 +1,23 @@
import Link from "next/link";
const links = [
{ href: "/", label: "Dashboard" },
{ href: "/add-expense", label: "Add Expense" },
{ href: "/income", label: "Income / Paychecks" },
];
export function SiteNav() {
return (
<nav className="flex flex-wrap gap-3 text-sm font-semibold text-stone-700">
{links.map((link) => (
<Link
key={link.href}
href={link.href}
className="rounded-full border border-stone-300/80 bg-white/80 px-4 py-2 transition hover:border-stone-900 hover:text-stone-950"
>
{link.label}
</Link>
))}
</nav>
);
}

18
src/lib/categories.ts Normal file
View File

@@ -0,0 +1,18 @@
export const CATEGORY_OPTIONS = [
{ value: "RENT", label: "Rent" },
{ value: "FOOD", label: "Food" },
{ value: "TRANSPORT", label: "Transport" },
{ value: "BILLS", label: "Bills" },
{ value: "SHOPPING", label: "Shopping" },
{ value: "HEALTH", label: "Health" },
{ value: "ENTERTAINMENT", label: "Entertainment" },
{ value: "MISC", label: "Misc" },
] as const;
export const CATEGORY_VALUES = CATEGORY_OPTIONS.map((option) => option.value);
export type CategoryValue = (typeof CATEGORY_VALUES)[number];
export function getCategoryLabel(value: CategoryValue) {
return CATEGORY_OPTIONS.find((option) => option.value === value)?.label ?? value;
}

17
src/lib/date.test.ts Normal file
View File

@@ -0,0 +1,17 @@
import { describe, expect, it } from "vitest";
import { getMonthKeyFromLocalDate, isDateInMonth, isValidLocalDate, isValidMonthKey } from "@/lib/date";
describe("date helpers", () => {
it("validates local calendar dates", () => {
expect(isValidLocalDate("2026-03-23")).toBe(true);
expect(isValidLocalDate("2026-02-31")).toBe(false);
});
it("derives and checks month keys", () => {
expect(getMonthKeyFromLocalDate("2026-03-23")).toBe("2026-03");
expect(isDateInMonth("2026-03-23", "2026-03")).toBe(true);
expect(isValidMonthKey("2026-03")).toBe(true);
expect(isValidMonthKey("2026-13")).toBe(false);
});
});

54
src/lib/date.ts Normal file
View File

@@ -0,0 +1,54 @@
const LOCAL_DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
function pad(value: number) {
return value.toString().padStart(2, "0");
}
export function getLocalToday() {
const now = new Date();
return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;
}
export function getCurrentMonthKey() {
return getMonthKeyFromLocalDate(getLocalToday());
}
export function isValidLocalDate(date: string) {
if (!LOCAL_DATE_PATTERN.test(date)) {
return false;
}
const [year, month, day] = date.split("-").map(Number);
const candidate = new Date(year, month - 1, day);
return (
candidate.getFullYear() === year &&
candidate.getMonth() === month - 1 &&
candidate.getDate() === day
);
}
export function isValidMonthKey(month: string) {
if (!/^\d{4}-\d{2}$/.test(month)) {
return false;
}
const [year, numericMonth] = month.split("-").map(Number);
return year > 2000 && numericMonth >= 1 && numericMonth <= 12;
}
export function getMonthKeyFromLocalDate(date: string) {
return date.slice(0, 7);
}
export function isDateInMonth(date: string, month: string) {
return date.startsWith(`${month}-`);
}
export function getMonthLabel(month: string) {
const [year, numericMonth] = month.split("-").map(Number);
return new Intl.DateTimeFormat("en-US", {
month: "long",
year: "numeric",
}).format(new Date(year, numericMonth - 1, 1));
}

15
src/lib/db.ts Normal file
View File

@@ -0,0 +1,15 @@
import { PrismaClient } from "@prisma/client";
const globalForPrisma = globalThis as typeof globalThis & {
prisma?: PrismaClient;
};
export const db =
globalForPrisma.prisma ??
new PrismaClient({
log: process.env.NODE_ENV === "development" ? ["error", "warn"] : ["error"],
});
if (process.env.NODE_ENV !== "production") {
globalForPrisma.prisma = db;
}

43
src/lib/expenses.ts Normal file
View File

@@ -0,0 +1,43 @@
import type { Category } from "@prisma/client";
import { db } from "@/lib/db";
import { getCurrentMonthKey, isDateInMonth } from "@/lib/date";
export async function listExpenses() {
return db.expense.findMany({
orderBy: [{ date: "desc" }, { createdAt: "desc" }],
});
}
export async function createExpense(input: {
title: string;
amountCents: number;
date: string;
category: Category;
}) {
return db.expense.create({
data: {
title: input.title.trim(),
amountCents: input.amountCents,
date: input.date,
category: input.category,
},
});
}
export async function removeExpense(id: string) {
return db.expense.delete({ where: { id } });
}
export async function getExpenseDashboardPreview(month = getCurrentMonthKey()) {
const expenses = await listExpenses();
const monthExpenses = expenses.filter((expense) => isDateInMonth(expense.date, month));
const totalSpentCents = monthExpenses.reduce((sum, expense) => sum + expense.amountCents, 0);
return {
month,
totalSpentCents,
expenseCount: monthExpenses.length,
recentExpenses: monthExpenses.slice(0, 6),
};
}

14
src/lib/money.test.ts Normal file
View File

@@ -0,0 +1,14 @@
import { describe, expect, it } from "vitest";
import { parseAmountToCents } from "@/lib/money";
describe("parseAmountToCents", () => {
it("parses decimal currency input", () => {
expect(parseAmountToCents("42.50")).toBe(4250);
});
it("rejects invalid amounts", () => {
expect(parseAmountToCents("12.345")).toBeNull();
expect(parseAmountToCents("0")).toBeNull();
});
});

22
src/lib/money.ts Normal file
View File

@@ -0,0 +1,22 @@
const AMOUNT_PATTERN = /^\d+(?:\.\d{1,2})?$/;
export function parseAmountToCents(value: string | number) {
const normalized = typeof value === "number" ? value.toString() : value.trim();
if (!AMOUNT_PATTERN.test(normalized)) {
return null;
}
const [whole, fraction = ""] = normalized.split(".");
const cents = Number.parseInt(whole, 10) * 100 + Number.parseInt(fraction.padEnd(2, "0"), 10);
return Number.isSafeInteger(cents) && cents > 0 ? cents : null;
}
export function formatCurrencyFromCents(value: number) {
return new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
maximumFractionDigits: 2,
}).format(value / 100);
}

View File

@@ -0,0 +1,27 @@
import { describe, expect, it } from "vitest";
import { expenseInputSchema } from "@/lib/validation";
describe("expenseInputSchema", () => {
it("accepts valid expense payloads", () => {
const parsed = expenseInputSchema.parse({
title: "Groceries",
amount: "64.32",
date: "2026-03-23",
category: "FOOD",
});
expect(parsed.amount).toBe(6432);
});
it("rejects invalid categories", () => {
const parsed = expenseInputSchema.safeParse({
title: "Groceries",
amount: "64.32",
date: "2026-03-23",
category: "OTHER",
});
expect(parsed.success).toBe(false);
});
});

39
src/lib/validation.ts Normal file
View File

@@ -0,0 +1,39 @@
import { Category } from "@prisma/client";
import { z } from "zod";
import { isValidLocalDate, isValidMonthKey } from "@/lib/date";
import { parseAmountToCents } from "@/lib/money";
const amountSchema = z
.union([z.string(), z.number()])
.transform((value, ctx) => {
const cents = parseAmountToCents(value);
if (!cents) {
ctx.addIssue({ code: z.ZodIssueCode.custom, message: "Enter a valid amount." });
return z.NEVER;
}
return cents;
});
const localDateSchema = z.string().refine(isValidLocalDate, "Enter a valid local date.");
export const expenseInputSchema = z.object({
title: z.string().trim().min(1, "Title is required.").max(80, "Keep titles under 80 characters."),
amount: amountSchema,
date: localDateSchema,
category: z.nativeEnum(Category, { message: "Choose a valid category." }),
});
export const paycheckInputSchema = z.object({
amount: amountSchema,
payDate: localDateSchema,
});
export const monthQuerySchema = z.object({
month: z.string().refine(isValidMonthKey, "Use a YYYY-MM month."),
});
export type ExpenseInput = z.infer<typeof expenseInputSchema>;
export type PaycheckInput = z.infer<typeof paycheckInputSchema>;

34
tsconfig.json Normal file
View File

@@ -0,0 +1,34 @@
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./src/*"]
}
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
".next/dev/types/**/*.ts",
"**/*.mts"
],
"exclude": ["node_modules"]
}

15
vitest.config.ts Normal file
View File

@@ -0,0 +1,15 @@
import { fileURLToPath } from "node:url";
import { defineConfig } from "vitest/config";
export default defineConfig({
resolve: {
alias: {
"@": fileURLToPath(new URL("./src", import.meta.url)),
},
},
test: {
environment: "node",
include: ["src/**/*.test.ts"],
},
});