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:
@@ -0,0 +1,4 @@
|
||||
node_modules
|
||||
.next
|
||||
.git
|
||||
*.md
|
||||
@@ -39,3 +39,5 @@ yarn-error.log*
|
||||
# typescript
|
||||
*.tsbuildinfo
|
||||
next-env.d.ts
|
||||
|
||||
/src/generated/prisma
|
||||
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
FROM node:20-alpine AS base
|
||||
|
||||
FROM base AS deps
|
||||
WORKDIR /app
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci
|
||||
|
||||
FROM base AS builder
|
||||
WORKDIR /app
|
||||
COPY --from=deps /app/node_modules ./node_modules
|
||||
COPY . .
|
||||
RUN npx prisma generate
|
||||
RUN npm run build
|
||||
|
||||
FROM base AS runner
|
||||
WORKDIR /app
|
||||
ENV NODE_ENV=production
|
||||
RUN addgroup --system --gid 1001 nodejs
|
||||
RUN adduser --system --uid 1001 nextjs
|
||||
|
||||
COPY --from=builder /app/public ./public
|
||||
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
|
||||
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
|
||||
|
||||
USER nextjs
|
||||
EXPOSE 3000
|
||||
ENV PORT=3000
|
||||
ENV HOSTNAME="0.0.0.0"
|
||||
CMD ["node", "server.js"]
|
||||
+2
-1
@@ -1,7 +1,8 @@
|
||||
import type { NextConfig } from "next";
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
/* config options here */
|
||||
output: "standalone",
|
||||
serverExternalPackages: ["@prisma/adapter-pg", "pg"],
|
||||
};
|
||||
|
||||
export default nextConfig;
|
||||
|
||||
Generated
+1063
-11
File diff suppressed because it is too large
Load Diff
@@ -9,13 +9,19 @@
|
||||
"lint": "eslint"
|
||||
},
|
||||
"dependencies": {
|
||||
"@prisma/adapter-pg": "^7.4.2",
|
||||
"@prisma/client": "^7.4.2",
|
||||
"@tanstack/react-query": "^5.90.21",
|
||||
"next": "16.1.6",
|
||||
"pg": "^8.20.0",
|
||||
"prisma": "^7.4.2",
|
||||
"react": "19.2.3",
|
||||
"react-dom": "19.2.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/postcss": "^4",
|
||||
"@types/node": "^20",
|
||||
"@types/pg": "^8.18.0",
|
||||
"@types/react": "^19",
|
||||
"@types/react-dom": "^19",
|
||||
"eslint": "^9",
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
// This file was generated by Prisma, and assumes you have installed the following:
|
||||
// npm install --save-dev prisma dotenv
|
||||
import "dotenv/config";
|
||||
import { defineConfig } from "prisma/config";
|
||||
|
||||
export default defineConfig({
|
||||
schema: "prisma/schema.prisma",
|
||||
migrations: {
|
||||
path: "prisma/migrations",
|
||||
},
|
||||
datasource: {
|
||||
url: process.env["DATABASE_URL"],
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
-- Add merchant_normalized column to existing transactions table
|
||||
ALTER TABLE transactions ADD COLUMN IF NOT EXISTS merchant_normalized TEXT;
|
||||
|
||||
-- Create transaction_overrides table
|
||||
CREATE TABLE IF NOT EXISTS transaction_overrides (
|
||||
id SERIAL PRIMARY KEY,
|
||||
transaction_id INTEGER NOT NULL UNIQUE REFERENCES transactions(id) ON DELETE CASCADE,
|
||||
merchant_normalized TEXT,
|
||||
category_override TEXT,
|
||||
notes TEXT,
|
||||
updated_at TIMESTAMPTZ DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_overrides_txn_id ON transaction_overrides(transaction_id);
|
||||
@@ -0,0 +1,3 @@
|
||||
# Please do not edit this file manually
|
||||
# It should be added in your version-control system (i.e. Git)
|
||||
provider = "postgresql"
|
||||
@@ -0,0 +1,17 @@
|
||||
generator client {
|
||||
provider = "prisma-client"
|
||||
output = "../src/generated/prisma"
|
||||
}
|
||||
|
||||
datasource db {
|
||||
provider = "postgresql"
|
||||
}
|
||||
|
||||
model transaction_overrides {
|
||||
id Int @id @default(autoincrement())
|
||||
transaction_id Int @unique
|
||||
merchant_normalized String?
|
||||
category_override String?
|
||||
notes String?
|
||||
updated_at DateTime @default(now()) @updatedAt
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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
@@ -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
@@ -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");
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
"use client";
|
||||
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { useState } from "react";
|
||||
|
||||
export function Providers({ children }: { children: React.ReactNode }) {
|
||||
const [queryClient] = useState(
|
||||
() =>
|
||||
new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { staleTime: 30_000, refetchOnWindowFocus: false },
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
|
||||
const NAV_ITEMS = [
|
||||
{ href: "/transactions", label: "Transactions", icon: "receipt" },
|
||||
{ href: "/statements", label: "Statements", icon: "file-text" },
|
||||
{ href: "/shared", label: "Shared", icon: "users" },
|
||||
{ href: "/budget", label: "Budget", icon: "bar-chart" },
|
||||
{ href: "/tags", label: "Tags", icon: "tag" },
|
||||
{ href: "/rules", label: "Rules", icon: "settings" },
|
||||
];
|
||||
|
||||
const ICONS: Record<string, React.ReactNode> = {
|
||||
receipt: (
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
|
||||
</svg>
|
||||
),
|
||||
"file-text": (
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
|
||||
</svg>
|
||||
),
|
||||
users: (
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197M13 7a4 4 0 11-8 0 4 4 0 018 0z" />
|
||||
</svg>
|
||||
),
|
||||
"bar-chart": (
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
|
||||
</svg>
|
||||
),
|
||||
tag: (
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z" />
|
||||
</svg>
|
||||
),
|
||||
settings: (
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.066 2.573c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.573 1.066c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.066-2.573c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
|
||||
</svg>
|
||||
),
|
||||
};
|
||||
|
||||
export function Sidebar() {
|
||||
const pathname = usePathname();
|
||||
|
||||
return (
|
||||
<aside className="w-56 bg-zinc-900 border-r border-zinc-800 flex flex-col min-h-screen">
|
||||
<div className="p-4 border-b border-zinc-800">
|
||||
<h1 className="text-lg font-semibold text-white">Finance</h1>
|
||||
</div>
|
||||
<nav className="flex-1 p-2">
|
||||
{NAV_ITEMS.map((item) => {
|
||||
const active = pathname.startsWith(item.href);
|
||||
return (
|
||||
<Link
|
||||
key={item.href}
|
||||
href={item.href}
|
||||
className={`flex items-center gap-3 px-3 py-2 rounded-md text-sm mb-0.5 transition-colors ${
|
||||
active
|
||||
? "bg-zinc-800 text-white"
|
||||
: "text-zinc-400 hover:text-white hover:bg-zinc-800/50"
|
||||
}`}
|
||||
>
|
||||
{ICONS[item.icon]}
|
||||
{item.label}
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
export const CATEGORIES = [
|
||||
"groceries",
|
||||
"dining",
|
||||
"transport",
|
||||
"fuel",
|
||||
"shopping",
|
||||
"utilities",
|
||||
"entertainment",
|
||||
"travel",
|
||||
"health",
|
||||
"insurance",
|
||||
"subscriptions",
|
||||
"cash_advance",
|
||||
"government",
|
||||
"education",
|
||||
"rent",
|
||||
"transfers",
|
||||
"income",
|
||||
"personal_care",
|
||||
"pets",
|
||||
"gifts",
|
||||
"charity",
|
||||
"other",
|
||||
] as const;
|
||||
|
||||
export type Category = (typeof CATEGORIES)[number];
|
||||
|
||||
export function formatCategory(cat: string): string {
|
||||
return cat
|
||||
.split("_")
|
||||
.map((w) => w.charAt(0).toUpperCase() + w.slice(1))
|
||||
.join(" ");
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { PrismaClient } from "@/generated/prisma/client";
|
||||
import { PrismaPg } from "@prisma/adapter-pg";
|
||||
|
||||
const globalForPrisma = globalThis as unknown as { prisma: PrismaClient };
|
||||
|
||||
function createPrisma() {
|
||||
const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL! });
|
||||
return new PrismaClient({ adapter });
|
||||
}
|
||||
|
||||
export const prisma = globalForPrisma.prisma || createPrisma();
|
||||
|
||||
if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma;
|
||||
|
||||
export async function queryRaw<T>(sql: string, params: unknown[] = []): Promise<T[]> {
|
||||
return prisma.$queryRawUnsafe<T[]>(sql, ...params);
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
"use client";
|
||||
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import type { TransactionRow, StatementRow } from "./queries";
|
||||
|
||||
interface TransactionsResponse {
|
||||
data: TransactionRow[];
|
||||
total: number;
|
||||
limit: number;
|
||||
offset: number;
|
||||
}
|
||||
|
||||
interface TransactionFilters {
|
||||
from?: string;
|
||||
to?: string;
|
||||
category?: string;
|
||||
bank_name?: string;
|
||||
search?: string;
|
||||
statement_id?: string;
|
||||
sort_by?: string;
|
||||
sort_dir?: string;
|
||||
limit?: number;
|
||||
offset?: number;
|
||||
}
|
||||
|
||||
function buildParams(filters: TransactionFilters): string {
|
||||
const params = new URLSearchParams();
|
||||
Object.entries(filters).forEach(([key, val]) => {
|
||||
if (val !== undefined && val !== "") params.set(key, String(val));
|
||||
});
|
||||
return params.toString();
|
||||
}
|
||||
|
||||
export function useTransactions(filters: TransactionFilters) {
|
||||
return useQuery<TransactionsResponse>({
|
||||
queryKey: ["transactions", filters],
|
||||
queryFn: async () => {
|
||||
const res = await fetch(`/api/transactions?${buildParams(filters)}`);
|
||||
return res.json();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useTransaction(id: number) {
|
||||
return useQuery<TransactionRow>({
|
||||
queryKey: ["transaction", id],
|
||||
queryFn: async () => {
|
||||
const res = await fetch(`/api/transactions/${id}`);
|
||||
return res.json();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useStatements() {
|
||||
return useQuery<StatementRow[]>({
|
||||
queryKey: ["statements"],
|
||||
queryFn: async () => {
|
||||
const res = await fetch("/api/statements");
|
||||
return res.json();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useStatement(id: number) {
|
||||
return useQuery<StatementRow>({
|
||||
queryKey: ["statement", id],
|
||||
queryFn: async () => {
|
||||
const res = await fetch(`/api/statements/${id}`);
|
||||
return res.json();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useBanks() {
|
||||
return useQuery<string[]>({
|
||||
queryKey: ["banks"],
|
||||
queryFn: async () => {
|
||||
const res = await fetch("/api/merchants?type=banks");
|
||||
return res.json();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useUpdateTransaction() {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: async ({
|
||||
id,
|
||||
...data
|
||||
}: {
|
||||
id: number;
|
||||
category?: string;
|
||||
merchant_normalized?: string;
|
||||
notes?: string;
|
||||
}) => {
|
||||
const res = await fetch(`/api/transactions/${id}`, {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
return res.json();
|
||||
},
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: ["transactions"] });
|
||||
qc.invalidateQueries({ queryKey: ["transaction"] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useBulkAction() {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: async (body: {
|
||||
action: string;
|
||||
ids: number[];
|
||||
category?: string;
|
||||
merchant_normalized?: string;
|
||||
}) => {
|
||||
const res = await fetch("/api/transactions/bulk", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
return res.json();
|
||||
},
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: ["transactions"] });
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
import { queryRaw } from "./db";
|
||||
|
||||
export interface TransactionRow {
|
||||
id: number;
|
||||
statement_id: number;
|
||||
transaction_date: string;
|
||||
description: string;
|
||||
amount: number;
|
||||
transaction_type: string;
|
||||
merchant_name: string | null;
|
||||
merchant_normalized: string | null;
|
||||
location: string | null;
|
||||
foreign_currency_amount: number | null;
|
||||
foreign_currency_code: string | null;
|
||||
category: string;
|
||||
row_index: number;
|
||||
created_at: string;
|
||||
// override fields
|
||||
category_override: string | null;
|
||||
merchant_override: string | null;
|
||||
notes: string | null;
|
||||
effective_category: string;
|
||||
effective_merchant: string;
|
||||
// statement context
|
||||
bank_name: string;
|
||||
}
|
||||
|
||||
export interface StatementRow {
|
||||
id: number;
|
||||
bank_name: string;
|
||||
card_name: string | null;
|
||||
account_number: string;
|
||||
account_type: string | null;
|
||||
billing_start_date: string | null;
|
||||
billing_end_date: string | null;
|
||||
total_amount_due: number;
|
||||
minimum_amount_due: number | null;
|
||||
payment_due_date: string;
|
||||
opening_balance: number | null;
|
||||
closing_balance: number | null;
|
||||
total_credits: number | null;
|
||||
total_debits: number | null;
|
||||
interest_charged: number | null;
|
||||
fees_charged: number | null;
|
||||
credit_limit: number | null;
|
||||
currency: string;
|
||||
tier_used: string | null;
|
||||
created_at: string;
|
||||
transaction_count: number;
|
||||
}
|
||||
|
||||
interface TransactionFilters {
|
||||
from?: string;
|
||||
to?: string;
|
||||
category?: string;
|
||||
bank_name?: string;
|
||||
search?: string;
|
||||
statement_id?: string;
|
||||
sort_by?: string;
|
||||
sort_dir?: string;
|
||||
limit?: number;
|
||||
offset?: number;
|
||||
}
|
||||
|
||||
export async function getTransactions(filters: TransactionFilters) {
|
||||
const conditions: string[] = [];
|
||||
const params: unknown[] = [];
|
||||
let paramIdx = 1;
|
||||
|
||||
if (filters.from) {
|
||||
conditions.push(`t.transaction_date >= $${paramIdx++}`);
|
||||
params.push(filters.from);
|
||||
}
|
||||
if (filters.to) {
|
||||
conditions.push(`t.transaction_date <= $${paramIdx++}`);
|
||||
params.push(filters.to);
|
||||
}
|
||||
if (filters.category) {
|
||||
conditions.push(`COALESCE(o.category_override, t.category) = $${paramIdx++}`);
|
||||
params.push(filters.category);
|
||||
}
|
||||
if (filters.bank_name) {
|
||||
conditions.push(`s.bank_name = $${paramIdx++}`);
|
||||
params.push(filters.bank_name);
|
||||
}
|
||||
if (filters.search) {
|
||||
conditions.push(`(t.description ILIKE $${paramIdx} OR t.merchant_name ILIKE $${paramIdx})`);
|
||||
params.push(`%${filters.search}%`);
|
||||
paramIdx++;
|
||||
}
|
||||
if (filters.statement_id) {
|
||||
conditions.push(`t.statement_id = $${paramIdx++}`);
|
||||
params.push(Number(filters.statement_id));
|
||||
}
|
||||
|
||||
const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
|
||||
|
||||
const sortCol = filters.sort_by === "amount" ? "t.amount" : "t.transaction_date";
|
||||
const sortDir = filters.sort_dir === "asc" ? "ASC" : "DESC";
|
||||
const limit = filters.limit || 50;
|
||||
const offset = filters.offset || 0;
|
||||
|
||||
// Count query
|
||||
const countSql = `
|
||||
SELECT COUNT(*)::int as total
|
||||
FROM transactions t
|
||||
LEFT JOIN transaction_overrides o ON o.transaction_id = t.id
|
||||
JOIN statements s ON s.id = t.statement_id
|
||||
${where}
|
||||
`;
|
||||
const countResult = await queryRaw<{ total: number }>(countSql, params);
|
||||
const total = countResult[0]?.total || 0;
|
||||
|
||||
// Data query
|
||||
const dataSql = `
|
||||
SELECT t.*,
|
||||
o.category_override, o.merchant_normalized as merchant_override, o.notes,
|
||||
COALESCE(o.category_override, t.category) as effective_category,
|
||||
COALESCE(o.merchant_normalized, t.merchant_normalized, t.merchant_name) as effective_merchant,
|
||||
s.bank_name
|
||||
FROM transactions t
|
||||
LEFT JOIN transaction_overrides o ON o.transaction_id = t.id
|
||||
JOIN statements s ON s.id = t.statement_id
|
||||
${where}
|
||||
ORDER BY ${sortCol} ${sortDir}, t.row_index ASC
|
||||
LIMIT $${paramIdx++} OFFSET $${paramIdx++}
|
||||
`;
|
||||
params.push(limit, offset);
|
||||
|
||||
const data = await queryRaw<TransactionRow>(dataSql, params);
|
||||
|
||||
return { data, total, limit, offset };
|
||||
}
|
||||
|
||||
export async function getTransactionById(id: number) {
|
||||
const sql = `
|
||||
SELECT t.*,
|
||||
o.category_override, o.merchant_normalized as merchant_override, o.notes,
|
||||
COALESCE(o.category_override, t.category) as effective_category,
|
||||
COALESCE(o.merchant_normalized, t.merchant_normalized, t.merchant_name) as effective_merchant,
|
||||
s.bank_name
|
||||
FROM transactions t
|
||||
LEFT JOIN transaction_overrides o ON o.transaction_id = t.id
|
||||
JOIN statements s ON s.id = t.statement_id
|
||||
WHERE t.id = $1
|
||||
`;
|
||||
const rows = await queryRaw<TransactionRow>(sql, [id]);
|
||||
return rows[0] || null;
|
||||
}
|
||||
|
||||
export async function getStatements() {
|
||||
const sql = `
|
||||
SELECT s.*,
|
||||
(SELECT COUNT(*)::int FROM transactions t WHERE t.statement_id = s.id) as transaction_count
|
||||
FROM statements s
|
||||
ORDER BY s.billing_end_date DESC NULLS LAST, s.created_at DESC
|
||||
`;
|
||||
return queryRaw<StatementRow>(sql);
|
||||
}
|
||||
|
||||
export async function getStatementById(id: number) {
|
||||
const sql = `
|
||||
SELECT s.*,
|
||||
(SELECT COUNT(*)::int FROM transactions t WHERE t.statement_id = s.id) as transaction_count
|
||||
FROM statements s
|
||||
WHERE s.id = $1
|
||||
`;
|
||||
const rows = await queryRaw<StatementRow>(sql, [id]);
|
||||
return rows[0] || null;
|
||||
}
|
||||
|
||||
export async function getMerchantSuggestions(search: string) {
|
||||
const sql = `
|
||||
SELECT DISTINCT COALESCE(o.merchant_normalized, t.merchant_normalized, t.merchant_name) as merchant
|
||||
FROM transactions t
|
||||
LEFT JOIN transaction_overrides o ON o.transaction_id = t.id
|
||||
WHERE COALESCE(o.merchant_normalized, t.merchant_normalized, t.merchant_name) ILIKE $1
|
||||
ORDER BY merchant
|
||||
LIMIT 20
|
||||
`;
|
||||
return queryRaw<{ merchant: string }>(sql, [`%${search}%`]);
|
||||
}
|
||||
|
||||
export async function getBankNames() {
|
||||
const sql = `SELECT DISTINCT bank_name FROM statements ORDER BY bank_name`;
|
||||
return queryRaw<{ bank_name: string }>(sql);
|
||||
}
|
||||
Reference in New Issue
Block a user