first build commit
This commit is contained in:
26
.dockerignore
Normal file
26
.dockerignore
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
# Dependencies (rebuilt inside Docker)
|
||||||
|
node_modules
|
||||||
|
npm-debug.log*
|
||||||
|
|
||||||
|
# Next.js build output (rebuilt inside Docker)
|
||||||
|
.next
|
||||||
|
out
|
||||||
|
|
||||||
|
# Environment files (injected at runtime via Docker Compose)
|
||||||
|
.env
|
||||||
|
.env.local
|
||||||
|
.env.*.local
|
||||||
|
|
||||||
|
# Version control
|
||||||
|
.git
|
||||||
|
.gitignore
|
||||||
|
.gitattributes
|
||||||
|
|
||||||
|
# Editor / OS
|
||||||
|
.DS_Store
|
||||||
|
*.log
|
||||||
|
.vscode
|
||||||
|
.idea
|
||||||
|
|
||||||
|
# TypeScript build cache
|
||||||
|
tsconfig.tsbuildinfo
|
||||||
15
.env.example
Normal file
15
.env.example
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
# Database
|
||||||
|
DATABASE_URL="postgresql://financeapp:password@localhost:5432/financeapp"
|
||||||
|
|
||||||
|
# NextAuth
|
||||||
|
NEXTAUTH_SECRET="<generate with: openssl rand -base64 32>"
|
||||||
|
NEXTAUTH_URL="http://localhost:3000"
|
||||||
|
|
||||||
|
# Seed user (used by prisma/seed.ts only)
|
||||||
|
SEED_EMAIL="your@email.com"
|
||||||
|
SEED_PASSWORD="your-secure-password"
|
||||||
|
|
||||||
|
# Postgres (used by docker-compose.yml)
|
||||||
|
POSTGRES_USER="financeapp"
|
||||||
|
POSTGRES_PASSWORD="password"
|
||||||
|
POSTGRES_DB="financeapp"
|
||||||
5
.gitignore
vendored
5
.gitignore
vendored
@@ -30,8 +30,9 @@ yarn-debug.log*
|
|||||||
yarn-error.log*
|
yarn-error.log*
|
||||||
.pnpm-debug.log*
|
.pnpm-debug.log*
|
||||||
|
|
||||||
# env files (can opt-in for committing if needed)
|
# env files
|
||||||
.env*
|
.env*
|
||||||
|
!.env.example
|
||||||
|
|
||||||
# vercel
|
# vercel
|
||||||
.vercel
|
.vercel
|
||||||
@@ -39,3 +40,5 @@ yarn-error.log*
|
|||||||
# typescript
|
# typescript
|
||||||
*.tsbuildinfo
|
*.tsbuildinfo
|
||||||
next-env.d.ts
|
next-env.d.ts
|
||||||
|
|
||||||
|
/src/generated/prisma
|
||||||
|
|||||||
357
CLAUDE.md
357
CLAUDE.md
@@ -1 +1,356 @@
|
|||||||
@AGENTS.md
|
# Finance App — Claude Context
|
||||||
|
|
||||||
|
Personal finance web app for tracking bank transactions, monitoring net worth, and visualizing spending. Single-user, self-hosted via Docker Compose.
|
||||||
|
|
||||||
|
## Tech Stack
|
||||||
|
|
||||||
|
| Layer | Choice |
|
||||||
|
|---|---|
|
||||||
|
| Framework | Next.js 16+ App Router + TypeScript |
|
||||||
|
| Database | PostgreSQL + Prisma ORM |
|
||||||
|
| Auth | NextAuth.js v5 (Credentials provider, bcrypt, JWT sessions) |
|
||||||
|
| UI | Tailwind CSS + shadcn/ui |
|
||||||
|
| Charts | Recharts |
|
||||||
|
| CSV Parsing | Papa Parse (server-side only — never client-side) |
|
||||||
|
| Validation | Zod on every API route before any DB access |
|
||||||
|
| Deployment | Docker Compose (postgres:16-alpine + Next.js app) |
|
||||||
|
|
||||||
|
## Build Status
|
||||||
|
|
||||||
|
**Phases 1–6 complete.**
|
||||||
|
|
||||||
|
## Implementation Phases
|
||||||
|
|
||||||
|
| # | Phase | Status |
|
||||||
|
|---|---|---|
|
||||||
|
| 1 | Scaffold: create-next-app, shadcn, Prisma schema, Docker, .env | Done |
|
||||||
|
| 2 | Auth: NextAuth, middleware, login page, seed script | Done |
|
||||||
|
| 3 | Accounts CRUD: API routes + AccountList UI | Done |
|
||||||
|
| 4 | CSV Upload: bank profiles, parser, normalizer, upload API + UI | Done |
|
||||||
|
| 5 | Transaction browsing: paginated API, filters, edit dialog | Done |
|
||||||
|
| 6 | Budgets: CRUD API, UI, assign transactions to budgets | Done |
|
||||||
|
| 7 | Dashboard: aggregate API, NetWorthCard, CashFlowCard, BudgetSummary | Not started |
|
||||||
|
| 8 | Graphs: Recharts components, BalanceSnapshot read path | Not started |
|
||||||
|
| 9 | Security hardening: HTTP headers, rate limiting, Origin check | Not started |
|
||||||
|
| 10 | Docker polish: multi-stage Dockerfile, health checks, README | Not started |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Prisma 7 Notes
|
||||||
|
|
||||||
|
- Generator provider is `prisma-client` (not `prisma-client-js`)
|
||||||
|
- Client output: `src/generated/prisma/` — import as `@/generated/prisma/client`
|
||||||
|
- **Requires Driver Adapter** — no URL in constructor. Use `@prisma/adapter-pg` with `pg`:
|
||||||
|
```ts
|
||||||
|
import { Pool } from 'pg'
|
||||||
|
import { PrismaPg } from '@prisma/adapter-pg'
|
||||||
|
const pool = new Pool({ connectionString: process.env.DATABASE_URL })
|
||||||
|
const adapter = new PrismaPg(pool)
|
||||||
|
new PrismaClient({ adapter })
|
||||||
|
```
|
||||||
|
- Datasource URL configured in `prisma.config.ts` (for CLI) and via `Pool` at runtime
|
||||||
|
- Singleton: `src/lib/prisma.ts`
|
||||||
|
- Seed: `npx prisma db seed` (runs `tsx prisma/seed.ts`)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Database Schema
|
||||||
|
|
||||||
|
Store all money as **integer cents** (never floats). `100.10` → `10010`.
|
||||||
|
|
||||||
|
```prisma
|
||||||
|
// prisma/schema.prisma
|
||||||
|
|
||||||
|
generator client {
|
||||||
|
provider = "prisma-client"
|
||||||
|
output = "../src/generated/prisma"
|
||||||
|
}
|
||||||
|
|
||||||
|
datasource db {
|
||||||
|
provider = "postgresql"
|
||||||
|
}
|
||||||
|
|
||||||
|
model User {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
email String @unique
|
||||||
|
passwordHash String // bcrypt hash, cost factor 12
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
|
accounts Account[]
|
||||||
|
budgets Budget[]
|
||||||
|
}
|
||||||
|
|
||||||
|
enum AccountType {
|
||||||
|
BANK // Checking, savings, investment — counts toward net worth
|
||||||
|
CREDIT_CARD // Tracking only — never counted in net worth or cash flow
|
||||||
|
}
|
||||||
|
|
||||||
|
model Account {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
userId String
|
||||||
|
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||||
|
name String
|
||||||
|
institution String?
|
||||||
|
type AccountType
|
||||||
|
currency String @default("USD")
|
||||||
|
currentBalanceCents Int @default(0)
|
||||||
|
isActive Boolean @default(true)
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
|
transactions Transaction[]
|
||||||
|
uploads CsvUpload[]
|
||||||
|
@@index([userId])
|
||||||
|
}
|
||||||
|
|
||||||
|
enum TransactionType {
|
||||||
|
DEBIT // Money out (spending, withdrawals, purchases)
|
||||||
|
CREDIT // Money in (deposits, payments received, refunds)
|
||||||
|
}
|
||||||
|
|
||||||
|
model Transaction {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
accountId String
|
||||||
|
account Account @relation(fields: [accountId], references: [id], onDelete: Cascade)
|
||||||
|
uploadId String?
|
||||||
|
upload CsvUpload? @relation(fields: [uploadId], references: [id])
|
||||||
|
budgetId String?
|
||||||
|
budget Budget? @relation(fields: [budgetId], references: [id], onDelete: SetNull)
|
||||||
|
date DateTime
|
||||||
|
description String
|
||||||
|
amountCents Int // Always positive; direction from `type` field
|
||||||
|
type TransactionType
|
||||||
|
category String?
|
||||||
|
notes String?
|
||||||
|
dedupeHash String // SHA-256(accountId|date|description|amountCents) — prevents re-upload duplicates
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
|
@@unique([dedupeHash])
|
||||||
|
@@index([accountId, date])
|
||||||
|
@@index([date])
|
||||||
|
@@index([budgetId])
|
||||||
|
}
|
||||||
|
|
||||||
|
// User-defined spending groups, primarily for CC transactions
|
||||||
|
model Budget {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
userId String
|
||||||
|
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||||
|
name String // e.g. "Groceries", "Entertainment"
|
||||||
|
limitCents Int? // Optional monthly cap
|
||||||
|
color String? // Hex color for UI, e.g. "#6366f1"
|
||||||
|
isActive Boolean @default(true)
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
|
transactions Transaction[]
|
||||||
|
@@index([userId])
|
||||||
|
}
|
||||||
|
|
||||||
|
model CsvUpload {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
accountId String
|
||||||
|
account Account @relation(fields: [accountId], references: [id])
|
||||||
|
fileName String
|
||||||
|
rowCount Int
|
||||||
|
importedCount Int
|
||||||
|
skippedCount Int
|
||||||
|
status String // PENDING | SUCCESS | PARTIAL | FAILED
|
||||||
|
errorMessage String?
|
||||||
|
uploadedAt DateTime @default(now())
|
||||||
|
transactions Transaction[]
|
||||||
|
@@index([accountId])
|
||||||
|
}
|
||||||
|
|
||||||
|
// Monthly balance snapshots for net worth trend graphs.
|
||||||
|
// No FK to Account intentionally — snapshots survive account deletion.
|
||||||
|
model BalanceSnapshot {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
accountId String
|
||||||
|
year Int
|
||||||
|
month Int // 1–12
|
||||||
|
balanceCents Int
|
||||||
|
computedAt DateTime @default(now())
|
||||||
|
@@unique([accountId, year, month])
|
||||||
|
@@index([year, month])
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Key schema decisions
|
||||||
|
- `currentBalanceCents` is always **recomputed by summing all transactions** after each upload — never incremented by delta — to handle out-of-order historical imports
|
||||||
|
- `dedupeHash` unique constraint lets `createMany({ skipDuplicates: true })` silently handle re-uploads
|
||||||
|
- `budgetId` uses `onDelete: SetNull` — deleting a budget unlinks its transactions, never deletes them
|
||||||
|
- `BalanceSnapshot` has no FK so historical net worth graphs survive account deletion
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## CSV Bank Profiles
|
||||||
|
|
||||||
|
All 4 user banks with exact column mappings. Implement in `src/lib/csv/bank-profiles.ts`.
|
||||||
|
|
||||||
|
### Discover High Yield Savings → `BANK`
|
||||||
|
- **Strategy**: B (split debit/credit columns)
|
||||||
|
- `date` ← `Transaction Date`
|
||||||
|
- `description` ← `Transaction Description`
|
||||||
|
- `debitAmount` ← `Debit`
|
||||||
|
- `creditAmount` ← `Credit`
|
||||||
|
- `balance` ← `Balance` (reference only)
|
||||||
|
- Ignore: `Transaction Type`
|
||||||
|
|
||||||
|
### Discover Credit Card → `CREDIT_CARD`
|
||||||
|
- **Strategy**: A (single signed column)
|
||||||
|
- `date` ← `Trans. Date`
|
||||||
|
- `description` ← `Description`
|
||||||
|
- `amount` ← `Amount` — **positive = DEBIT (charge), negative = CREDIT (payment/refund)**
|
||||||
|
- Ignore: `Post Date`, `Category`
|
||||||
|
|
||||||
|
### Huntington Checking → `BANK`
|
||||||
|
- **Strategy**: A (single signed column)
|
||||||
|
- `date` ← `Date`
|
||||||
|
- `description` ← `Description`
|
||||||
|
- `amount` ← `Amount` — **negative = DEBIT, positive = CREDIT**
|
||||||
|
- Ignore: `Category`, `Split`, `Tags`
|
||||||
|
|
||||||
|
### Fidelity → `BANK` (investment — cash activity only)
|
||||||
|
- **Strategy**: A (single signed column)
|
||||||
|
- `date` ← `Run Date`
|
||||||
|
- `description` ← `Description`
|
||||||
|
- `amount` ← `Amount($)` — **negative = DEBIT (purchase), positive = CREDIT (dividend/sale)**
|
||||||
|
- `balance` ← `Cash Balance ($)` (reference only)
|
||||||
|
- Ignore: `Action`, `Symbol`, `Type`, `Price($)`, `Quantity`, `Commission ($)`, `Fees ($)`, `Accrued Interest ($)`, `Settlement Date`
|
||||||
|
- **Known limitation**: tracks cash activity only, not total portfolio value (securities not included)
|
||||||
|
|
||||||
|
### Amount parsing strategies
|
||||||
|
```typescript
|
||||||
|
// Strategy A — single signed column
|
||||||
|
// Sign convention varies per bank; each profile has invertAmountSign: boolean
|
||||||
|
function parseStrategyA(raw: string, invert: boolean): { amountCents: number; type: TransactionType }
|
||||||
|
|
||||||
|
// Strategy B — separate debit/credit columns (Discover Savings)
|
||||||
|
// The non-empty/non-zero column determines type and amount
|
||||||
|
function parseStrategyB(debitRaw: string, creditRaw: string): { amountCents: number; type: TransactionType }
|
||||||
|
|
||||||
|
// All amounts via:
|
||||||
|
function parseCents(raw: string): number {
|
||||||
|
return Math.round(parseFloat(raw.replace(/[$,\s]/g, '')) * 100)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Upload flow
|
||||||
|
1. Server parses header row → attempts profile auto-detection by matching column names
|
||||||
|
2. **Match found**: auto-proceeds; client shows "Detected: [Bank Name]"
|
||||||
|
3. **No match**: returns `{ requiresMapping: true, headers, sampleRows }` → client renders `ColumnMapper` for manual column assignment
|
||||||
|
4. After mapping resolved: normalize all rows → compute `dedupeHash` → `createMany({ skipDuplicates: true })` → recompute `currentBalanceCents` (full sum) → write/update `BalanceSnapshot` for each affected month
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Key Features
|
||||||
|
|
||||||
|
### Account types
|
||||||
|
- **BANK** (Discover Savings, Huntington Checking, Fidelity): counted in net worth and cash flow
|
||||||
|
- **CREDIT_CARD** (Discover CC): tracked only — never in net worth or cash flow calculations
|
||||||
|
|
||||||
|
### Budgets (for CC transactions primarily)
|
||||||
|
- User creates named budgets with optional monthly spending caps and a hex color
|
||||||
|
- Any transaction can be assigned to a budget via `budgetId`
|
||||||
|
- `BudgetCard` shows: name, current-month DEBIT total, limit, progress bar (green <75% / yellow 75-100% / red >100%)
|
||||||
|
- Dashboard has a `BudgetSummary` section with all active budgets
|
||||||
|
- Deleting a budget sets `budgetId = null` on all its transactions (transactions not deleted)
|
||||||
|
|
||||||
|
### Net worth calculation
|
||||||
|
```sql
|
||||||
|
-- Always filter type = 'BANK'; credit card accounts never appear here
|
||||||
|
SELECT SUM(currentBalanceCents) FROM Account WHERE userId = ? AND type = 'BANK' AND isActive = true
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Security Requirements
|
||||||
|
|
||||||
|
- **All API routes**: validate with Zod before any DB access; scope every Prisma query by `userId`
|
||||||
|
- **Auth**: bcrypt cost 12; JWT sessions 1-hour expiry; `middleware.ts` protects all `/(app)` routes and `/api/*` except `/api/auth`
|
||||||
|
- **CSV upload**: max 10 MB; check MIME type + file extension server-side; never write file to disk; parse in memory then discard
|
||||||
|
- **Raw SQL** (aggregation queries only): use `Prisma.sql` tagged templates — never string concatenation
|
||||||
|
- **HTTP security headers** in `next.config.ts`: `Content-Security-Policy`, `X-Frame-Options: DENY`, `X-Content-Type-Options: nosniff`, `Referrer-Policy: strict-origin-when-cross-origin`
|
||||||
|
- **Docker**: Next.js runs as non-root user (`USER node`); PostgreSQL binds to `127.0.0.1` only
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## .env Variables Required
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Database
|
||||||
|
DATABASE_URL="postgresql://financeapp:password@localhost:5432/financeapp"
|
||||||
|
|
||||||
|
# NextAuth
|
||||||
|
NEXTAUTH_SECRET="<generate with: openssl rand -base64 32>"
|
||||||
|
NEXTAUTH_URL="http://localhost:3000"
|
||||||
|
|
||||||
|
# Seed user (used by prisma/seed.ts only)
|
||||||
|
SEED_EMAIL="your@email.com"
|
||||||
|
SEED_PASSWORD="your-secure-password"
|
||||||
|
|
||||||
|
# Postgres (used by docker-compose.yml)
|
||||||
|
POSTGRES_USER="financeapp"
|
||||||
|
POSTGRES_PASSWORD="password"
|
||||||
|
POSTGRES_DB="financeapp"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Project File Structure (target)
|
||||||
|
|
||||||
|
```
|
||||||
|
finance-app/
|
||||||
|
├── .env # Never committed
|
||||||
|
├── .env.example
|
||||||
|
├── .gitignore
|
||||||
|
├── docker-compose.yml
|
||||||
|
├── Dockerfile
|
||||||
|
├── next.config.ts
|
||||||
|
├── tailwind.config.ts
|
||||||
|
├── components.json # shadcn/ui config
|
||||||
|
├── prisma/
|
||||||
|
│ ├── schema.prisma
|
||||||
|
│ ├── seed.ts
|
||||||
|
│ └── migrations/
|
||||||
|
└── src/
|
||||||
|
├── middleware.ts
|
||||||
|
├── app/
|
||||||
|
│ ├── (auth)/login/page.tsx
|
||||||
|
│ ├── (app)/
|
||||||
|
│ │ ├── layout.tsx
|
||||||
|
│ │ ├── dashboard/page.tsx
|
||||||
|
│ │ ├── accounts/page.tsx
|
||||||
|
│ │ ├── accounts/[id]/page.tsx
|
||||||
|
│ │ ├── transactions/page.tsx
|
||||||
|
│ │ ├── upload/page.tsx
|
||||||
|
│ │ ├── budgets/page.tsx
|
||||||
|
│ │ └── graphs/page.tsx
|
||||||
|
│ └── api/
|
||||||
|
│ ├── auth/[...nextauth]/route.ts
|
||||||
|
│ ├── accounts/route.ts + [id]/route.ts
|
||||||
|
│ ├── transactions/route.ts + [id]/route.ts
|
||||||
|
│ ├── upload/route.ts
|
||||||
|
│ ├── budgets/route.ts + [id]/route.ts
|
||||||
|
│ └── dashboard/route.ts
|
||||||
|
├── components/
|
||||||
|
│ ├── ui/ # shadcn/ui generated
|
||||||
|
│ ├── layout/ # Sidebar, TopNav, PageHeader
|
||||||
|
│ ├── accounts/ # AccountList, AccountCard, CreateAccountDialog, AccountBadge
|
||||||
|
│ ├── transactions/ # TransactionTable, TransactionFilters, EditTransactionDialog
|
||||||
|
│ ├── upload/ # UploadDropzone, UploadForm, ColumnMapper, UploadPreview
|
||||||
|
│ ├── budgets/ # BudgetList, BudgetCard, CreateBudgetDialog, BudgetProgress
|
||||||
|
│ ├── dashboard/ # NetWorthCard, CashFlowCard, MonthlyBalanceCard, BudgetSummary
|
||||||
|
│ └── graphs/ # MonthlySpendingChart, NetWorthTrendChart, CategoryBreakdownChart, CashFlowChart, BudgetChart
|
||||||
|
└── lib/
|
||||||
|
├── auth.ts # NextAuth config (imported by route + middleware)
|
||||||
|
├── prisma.ts # Singleton PrismaClient
|
||||||
|
├── csv/
|
||||||
|
│ ├── bank-profiles.ts # All 4 bank profiles
|
||||||
|
│ ├── parser.ts # Profile detection + Papa Parse wrapper
|
||||||
|
│ └── normalizer.ts # Row → Transaction, cents parsing, dedupeHash
|
||||||
|
├── validations/ # account.ts, transaction.ts, upload.ts, budget.ts (Zod schemas)
|
||||||
|
└── utils/
|
||||||
|
├── currency.ts # cents → display string formatter
|
||||||
|
├── dates.ts # month boundary helpers
|
||||||
|
└── cn.ts # shadcn class merge utility
|
||||||
|
```
|
||||||
|
|||||||
38
Dockerfile
Normal file
38
Dockerfile
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
FROM node:22-alpine AS base
|
||||||
|
|
||||||
|
# ── deps: install production + dev dependencies ───────────────────────────────
|
||||||
|
FROM base AS deps
|
||||||
|
WORKDIR /app
|
||||||
|
COPY package*.json ./
|
||||||
|
RUN npm ci
|
||||||
|
|
||||||
|
# ── builder: generate Prisma client + build Next.js ──────────────────────────
|
||||||
|
FROM base AS builder
|
||||||
|
WORKDIR /app
|
||||||
|
COPY --from=deps /app/node_modules ./node_modules
|
||||||
|
COPY . .
|
||||||
|
RUN npx prisma generate
|
||||||
|
RUN npm run build
|
||||||
|
|
||||||
|
# ── runner: minimal production image ─────────────────────────────────────────
|
||||||
|
FROM base AS runner
|
||||||
|
WORKDIR /app
|
||||||
|
ENV NODE_ENV=production
|
||||||
|
|
||||||
|
RUN addgroup --system --gid 1001 nodejs && \
|
||||||
|
adduser --system --uid 1001 nextjs && \
|
||||||
|
apk add --no-cache curl
|
||||||
|
|
||||||
|
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"
|
||||||
|
|
||||||
|
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
|
||||||
|
CMD curl -f http://localhost:3000/api/health || exit 1
|
||||||
|
|
||||||
|
CMD ["node", "server.js"]
|
||||||
128
README.md
128
README.md
@@ -1,36 +1,120 @@
|
|||||||
This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).
|
# Finance App
|
||||||
|
|
||||||
## Getting Started
|
Personal finance web app for tracking bank transactions, monitoring net worth, and visualizing spending. Self-hosted via Docker Compose — no cloud services required.
|
||||||
|
|
||||||
First, run the development server:
|
## Features
|
||||||
|
|
||||||
```bash
|
- Import transactions from CSV exports (Discover Savings, Discover Credit Card, Huntington Checking, Fidelity)
|
||||||
npm run dev
|
- Net worth tracking across bank accounts
|
||||||
# or
|
- Browse, filter, and annotate transactions
|
||||||
yarn dev
|
- Assign transactions to budgets with optional monthly caps
|
||||||
# or
|
- Dashboard: net worth snapshot, cash flow, recent transactions, budget summary
|
||||||
pnpm dev
|
- Charts: net worth trend, monthly cash flow, spending by category, budget performance
|
||||||
# or
|
|
||||||
bun dev
|
## Quick start
|
||||||
|
|
||||||
|
**Prerequisites:** Docker and Docker Compose
|
||||||
|
|
||||||
|
```sh
|
||||||
|
# 1. Copy the example env file
|
||||||
|
cp .env.example .env
|
||||||
```
|
```
|
||||||
|
|
||||||
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
|
Edit `.env`:
|
||||||
|
- Set `NEXTAUTH_SECRET` to the output of `openssl rand -base64 32`
|
||||||
|
- Set `SEED_EMAIL` and `SEED_PASSWORD` to your desired login credentials
|
||||||
|
- Change `POSTGRES_PASSWORD` to a strong password
|
||||||
|
|
||||||
You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
|
```sh
|
||||||
|
# 2. Build and start the stack
|
||||||
|
docker compose up --build -d
|
||||||
|
|
||||||
This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.
|
# 3. First-run only: apply the schema and create your user
|
||||||
|
docker compose exec app npx prisma db push
|
||||||
|
docker compose exec app npx prisma db seed
|
||||||
|
|
||||||
## Learn More
|
# 4. Open the app
|
||||||
|
open http://localhost:3000
|
||||||
|
```
|
||||||
|
|
||||||
To learn more about Next.js, take a look at the following resources:
|
Sign in with the `SEED_EMAIL` / `SEED_PASSWORD` you set.
|
||||||
|
|
||||||
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
|
## Environment variables
|
||||||
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
|
|
||||||
|
|
||||||
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!
|
| Variable | Description |
|
||||||
|
|---|---|
|
||||||
|
| `NEXTAUTH_SECRET` | Secret for JWT signing — run `openssl rand -base64 32` |
|
||||||
|
| `NEXTAUTH_URL` | Public URL of the app (default: `http://localhost:3000`) |
|
||||||
|
| `SEED_EMAIL` | Login email created by the seed script |
|
||||||
|
| `SEED_PASSWORD` | Login password created by the seed script |
|
||||||
|
| `POSTGRES_USER` | PostgreSQL username |
|
||||||
|
| `POSTGRES_PASSWORD` | PostgreSQL password |
|
||||||
|
| `POSTGRES_DB` | PostgreSQL database name |
|
||||||
|
| `DATABASE_URL` | Full connection string — set automatically by Compose |
|
||||||
|
|
||||||
## Deploy on Vercel
|
## Useful commands
|
||||||
|
|
||||||
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
|
```sh
|
||||||
|
# View logs
|
||||||
|
docker compose logs -f app
|
||||||
|
|
||||||
Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.
|
# Stop the stack
|
||||||
|
docker compose down
|
||||||
|
|
||||||
|
# Stop and wipe the database volume
|
||||||
|
docker compose down -v
|
||||||
|
|
||||||
|
# Re-seed after a wipe
|
||||||
|
docker compose exec app npx prisma db push
|
||||||
|
docker compose exec app npx prisma db seed
|
||||||
|
|
||||||
|
# Check health
|
||||||
|
curl http://localhost:3000/api/health
|
||||||
|
```
|
||||||
|
|
||||||
|
## CSV import
|
||||||
|
|
||||||
|
Upload CSV files at `/upload`. The bank profile is auto-detected from the header row. Supported profiles:
|
||||||
|
|
||||||
|
| Bank | Account type |
|
||||||
|
|---|---|
|
||||||
|
| Discover High Yield Savings | BANK |
|
||||||
|
| Discover Credit Card | CREDIT_CARD |
|
||||||
|
| Huntington Checking | BANK |
|
||||||
|
| Fidelity (cash activity only) | BANK |
|
||||||
|
|
||||||
|
If auto-detection fails, a column mapper is shown for manual field assignment.
|
||||||
|
|
||||||
|
**BANK** accounts count toward net worth and cash flow. **CREDIT_CARD** accounts are tracked only.
|
||||||
|
|
||||||
|
## Development
|
||||||
|
|
||||||
|
```sh
|
||||||
|
# Start the database
|
||||||
|
docker compose up db -d
|
||||||
|
|
||||||
|
# Install dependencies
|
||||||
|
npm install
|
||||||
|
|
||||||
|
# Apply schema
|
||||||
|
npx prisma db push
|
||||||
|
|
||||||
|
# Seed a user
|
||||||
|
npx prisma db seed
|
||||||
|
|
||||||
|
# Start the dev server
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
The app is at http://localhost:3000.
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
| Layer | Choice |
|
||||||
|
|---|---|
|
||||||
|
| Framework | Next.js 16 App Router + TypeScript |
|
||||||
|
| Database | PostgreSQL 16 + Prisma ORM |
|
||||||
|
| Auth | NextAuth.js v5 (JWT sessions, bcrypt) |
|
||||||
|
| UI | Tailwind CSS + shadcn/ui |
|
||||||
|
| Charts | Recharts |
|
||||||
|
| Deployment | Docker Compose |
|
||||||
|
|||||||
37
docker-compose.yml
Normal file
37
docker-compose.yml
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
services:
|
||||||
|
db:
|
||||||
|
image: postgres:16-alpine
|
||||||
|
environment:
|
||||||
|
POSTGRES_USER: ${POSTGRES_USER}
|
||||||
|
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
|
||||||
|
POSTGRES_DB: ${POSTGRES_DB}
|
||||||
|
volumes:
|
||||||
|
- postgres_data:/var/lib/postgresql/data
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:5432:5432"
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER} -d ${POSTGRES_DB}"]
|
||||||
|
interval: 5s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 5
|
||||||
|
|
||||||
|
app:
|
||||||
|
build: .
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:3000:3000"
|
||||||
|
environment:
|
||||||
|
DATABASE_URL: postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}
|
||||||
|
NEXTAUTH_SECRET: ${NEXTAUTH_SECRET}
|
||||||
|
NEXTAUTH_URL: ${NEXTAUTH_URL:-http://localhost:3000}
|
||||||
|
depends_on:
|
||||||
|
db:
|
||||||
|
condition: service_healthy
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "curl", "-f", "http://localhost:3000/api/health"]
|
||||||
|
interval: 30s
|
||||||
|
timeout: 10s
|
||||||
|
retries: 3
|
||||||
|
start_period: 60s
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
postgres_data:
|
||||||
@@ -1,7 +1,32 @@
|
|||||||
import type { NextConfig } from "next";
|
import type { NextConfig } from 'next'
|
||||||
|
|
||||||
|
const securityHeaders = [
|
||||||
|
{ key: 'X-Frame-Options', value: 'DENY' },
|
||||||
|
{ key: 'X-Content-Type-Options', value: 'nosniff' },
|
||||||
|
{ key: 'Referrer-Policy', value: 'strict-origin-when-cross-origin' },
|
||||||
|
{ key: 'Permissions-Policy', value: 'camera=(), microphone=(), geolocation=()' },
|
||||||
|
{
|
||||||
|
key: 'Content-Security-Policy',
|
||||||
|
value: [
|
||||||
|
"default-src 'self'",
|
||||||
|
"script-src 'self' 'unsafe-inline' 'unsafe-eval'",
|
||||||
|
"style-src 'self' 'unsafe-inline'",
|
||||||
|
"img-src 'self' data: blob:",
|
||||||
|
"font-src 'self'",
|
||||||
|
"connect-src 'self'",
|
||||||
|
"object-src 'none'",
|
||||||
|
"base-uri 'self'",
|
||||||
|
"form-action 'self'",
|
||||||
|
"frame-ancestors 'none'",
|
||||||
|
].join('; '),
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
const nextConfig: NextConfig = {
|
const nextConfig: NextConfig = {
|
||||||
/* config options here */
|
output: 'standalone',
|
||||||
};
|
async headers() {
|
||||||
|
return [{ source: '/(.*)', headers: securityHeaders }]
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
export default nextConfig;
|
export default nextConfig
|
||||||
|
|||||||
715
package-lock.json
generated
715
package-lock.json
generated
@@ -1,14 +1,15 @@
|
|||||||
{
|
{
|
||||||
"name": "finance-app-scaffold",
|
"name": "finance-app",
|
||||||
"version": "0.1.0",
|
"version": "0.1.0",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "finance-app-scaffold",
|
"name": "finance-app",
|
||||||
"version": "0.1.0",
|
"version": "0.1.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@base-ui/react": "^1.4.0",
|
"@base-ui/react": "^1.4.0",
|
||||||
|
"@prisma/adapter-pg": "^7.7.0",
|
||||||
"@prisma/client": "^7.7.0",
|
"@prisma/client": "^7.7.0",
|
||||||
"bcryptjs": "^3.0.3",
|
"bcryptjs": "^3.0.3",
|
||||||
"class-variance-authority": "^0.7.1",
|
"class-variance-authority": "^0.7.1",
|
||||||
@@ -17,6 +18,7 @@
|
|||||||
"next": "16.2.4",
|
"next": "16.2.4",
|
||||||
"next-auth": "^5.0.0-beta.31",
|
"next-auth": "^5.0.0-beta.31",
|
||||||
"papaparse": "^5.5.3",
|
"papaparse": "^5.5.3",
|
||||||
|
"pg": "^8.20.0",
|
||||||
"react": "19.2.4",
|
"react": "19.2.4",
|
||||||
"react-dom": "19.2.4",
|
"react-dom": "19.2.4",
|
||||||
"recharts": "^3.8.1",
|
"recharts": "^3.8.1",
|
||||||
@@ -30,12 +32,14 @@
|
|||||||
"@types/bcryptjs": "^2.4.6",
|
"@types/bcryptjs": "^2.4.6",
|
||||||
"@types/node": "^20",
|
"@types/node": "^20",
|
||||||
"@types/papaparse": "^5.5.2",
|
"@types/papaparse": "^5.5.2",
|
||||||
|
"@types/pg": "^8.20.0",
|
||||||
"@types/react": "^19",
|
"@types/react": "^19",
|
||||||
"@types/react-dom": "^19",
|
"@types/react-dom": "^19",
|
||||||
"eslint": "^9",
|
"eslint": "^9",
|
||||||
"eslint-config-next": "16.2.4",
|
"eslint-config-next": "16.2.4",
|
||||||
"prisma": "^7.7.0",
|
"prisma": "^7.7.0",
|
||||||
"tailwindcss": "^4",
|
"tailwindcss": "^4",
|
||||||
|
"tsx": "^4.21.0",
|
||||||
"typescript": "^5"
|
"typescript": "^5"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -829,6 +833,448 @@
|
|||||||
"tslib": "^2.4.0"
|
"tslib": "^2.4.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@esbuild/aix-ppc64": {
|
||||||
|
"version": "0.27.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.7.tgz",
|
||||||
|
"integrity": "sha512-EKX3Qwmhz1eMdEJokhALr0YiD0lhQNwDqkPYyPhiSwKrh7/4KRjQc04sZ8db+5DVVnZ1LmbNDI1uAMPEUBnQPg==",
|
||||||
|
"cpu": [
|
||||||
|
"ppc64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"aix"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/android-arm": {
|
||||||
|
"version": "0.27.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.7.tgz",
|
||||||
|
"integrity": "sha512-jbPXvB4Yj2yBV7HUfE2KHe4GJX51QplCN1pGbYjvsyCZbQmies29EoJbkEc+vYuU5o45AfQn37vZlyXy4YJ8RQ==",
|
||||||
|
"cpu": [
|
||||||
|
"arm"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"android"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/android-arm64": {
|
||||||
|
"version": "0.27.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.7.tgz",
|
||||||
|
"integrity": "sha512-62dPZHpIXzvChfvfLJow3q5dDtiNMkwiRzPylSCfriLvZeq0a1bWChrGx/BbUbPwOrsWKMn8idSllklzBy+dgQ==",
|
||||||
|
"cpu": [
|
||||||
|
"arm64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"android"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/android-x64": {
|
||||||
|
"version": "0.27.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.7.tgz",
|
||||||
|
"integrity": "sha512-x5VpMODneVDb70PYV2VQOmIUUiBtY3D3mPBG8NxVk5CogneYhkR7MmM3yR/uMdITLrC1ml/NV1rj4bMJuy9MCg==",
|
||||||
|
"cpu": [
|
||||||
|
"x64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"android"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/darwin-arm64": {
|
||||||
|
"version": "0.27.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.7.tgz",
|
||||||
|
"integrity": "sha512-5lckdqeuBPlKUwvoCXIgI2D9/ABmPq3Rdp7IfL70393YgaASt7tbju3Ac+ePVi3KDH6N2RqePfHnXkaDtY9fkw==",
|
||||||
|
"cpu": [
|
||||||
|
"arm64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"darwin"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/darwin-x64": {
|
||||||
|
"version": "0.27.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.7.tgz",
|
||||||
|
"integrity": "sha512-rYnXrKcXuT7Z+WL5K980jVFdvVKhCHhUwid+dDYQpH+qu+TefcomiMAJpIiC2EM3Rjtq0sO3StMV/+3w3MyyqQ==",
|
||||||
|
"cpu": [
|
||||||
|
"x64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"darwin"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/freebsd-arm64": {
|
||||||
|
"version": "0.27.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.7.tgz",
|
||||||
|
"integrity": "sha512-B48PqeCsEgOtzME2GbNM2roU29AMTuOIN91dsMO30t+Ydis3z/3Ngoj5hhnsOSSwNzS+6JppqWsuhTp6E82l2w==",
|
||||||
|
"cpu": [
|
||||||
|
"arm64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"freebsd"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/freebsd-x64": {
|
||||||
|
"version": "0.27.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.7.tgz",
|
||||||
|
"integrity": "sha512-jOBDK5XEjA4m5IJK3bpAQF9/Lelu/Z9ZcdhTRLf4cajlB+8VEhFFRjWgfy3M1O4rO2GQ/b2dLwCUGpiF/eATNQ==",
|
||||||
|
"cpu": [
|
||||||
|
"x64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"freebsd"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/linux-arm": {
|
||||||
|
"version": "0.27.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.7.tgz",
|
||||||
|
"integrity": "sha512-RkT/YXYBTSULo3+af8Ib0ykH8u2MBh57o7q/DAs3lTJlyVQkgQvlrPTnjIzzRPQyavxtPtfg0EopvDyIt0j1rA==",
|
||||||
|
"cpu": [
|
||||||
|
"arm"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/linux-arm64": {
|
||||||
|
"version": "0.27.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.7.tgz",
|
||||||
|
"integrity": "sha512-RZPHBoxXuNnPQO9rvjh5jdkRmVizktkT7TCDkDmQ0W2SwHInKCAV95GRuvdSvA7w4VMwfCjUiPwDi0ZO6Nfe9A==",
|
||||||
|
"cpu": [
|
||||||
|
"arm64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/linux-ia32": {
|
||||||
|
"version": "0.27.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.7.tgz",
|
||||||
|
"integrity": "sha512-GA48aKNkyQDbd3KtkplYWT102C5sn/EZTY4XROkxONgruHPU72l+gW+FfF8tf2cFjeHaRbWpOYa/uRBz/Xq1Pg==",
|
||||||
|
"cpu": [
|
||||||
|
"ia32"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/linux-loong64": {
|
||||||
|
"version": "0.27.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.7.tgz",
|
||||||
|
"integrity": "sha512-a4POruNM2oWsD4WKvBSEKGIiWQF8fZOAsycHOt6JBpZ+JN2n2JH9WAv56SOyu9X5IqAjqSIPTaJkqN8F7XOQ5Q==",
|
||||||
|
"cpu": [
|
||||||
|
"loong64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/linux-mips64el": {
|
||||||
|
"version": "0.27.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.7.tgz",
|
||||||
|
"integrity": "sha512-KabT5I6StirGfIz0FMgl1I+R1H73Gp0ofL9A3nG3i/cYFJzKHhouBV5VWK1CSgKvVaG4q1RNpCTR2LuTVB3fIw==",
|
||||||
|
"cpu": [
|
||||||
|
"mips64el"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/linux-ppc64": {
|
||||||
|
"version": "0.27.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.7.tgz",
|
||||||
|
"integrity": "sha512-gRsL4x6wsGHGRqhtI+ifpN/vpOFTQtnbsupUF5R5YTAg+y/lKelYR1hXbnBdzDjGbMYjVJLJTd2OFmMewAgwlQ==",
|
||||||
|
"cpu": [
|
||||||
|
"ppc64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/linux-riscv64": {
|
||||||
|
"version": "0.27.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.7.tgz",
|
||||||
|
"integrity": "sha512-hL25LbxO1QOngGzu2U5xeXtxXcW+/GvMN3ejANqXkxZ/opySAZMrc+9LY/WyjAan41unrR3YrmtTsUpwT66InQ==",
|
||||||
|
"cpu": [
|
||||||
|
"riscv64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/linux-s390x": {
|
||||||
|
"version": "0.27.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.7.tgz",
|
||||||
|
"integrity": "sha512-2k8go8Ycu1Kb46vEelhu1vqEP+UeRVj2zY1pSuPdgvbd5ykAw82Lrro28vXUrRmzEsUV0NzCf54yARIK8r0fdw==",
|
||||||
|
"cpu": [
|
||||||
|
"s390x"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/linux-x64": {
|
||||||
|
"version": "0.27.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.7.tgz",
|
||||||
|
"integrity": "sha512-hzznmADPt+OmsYzw1EE33ccA+HPdIqiCRq7cQeL1Jlq2gb1+OyWBkMCrYGBJ+sxVzve2ZJEVeePbLM2iEIZSxA==",
|
||||||
|
"cpu": [
|
||||||
|
"x64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/netbsd-arm64": {
|
||||||
|
"version": "0.27.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.7.tgz",
|
||||||
|
"integrity": "sha512-b6pqtrQdigZBwZxAn1UpazEisvwaIDvdbMbmrly7cDTMFnw/+3lVxxCTGOrkPVnsYIosJJXAsILG9XcQS+Yu6w==",
|
||||||
|
"cpu": [
|
||||||
|
"arm64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"netbsd"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/netbsd-x64": {
|
||||||
|
"version": "0.27.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.7.tgz",
|
||||||
|
"integrity": "sha512-OfatkLojr6U+WN5EDYuoQhtM+1xco+/6FSzJJnuWiUw5eVcicbyK3dq5EeV/QHT1uy6GoDhGbFpprUiHUYggrw==",
|
||||||
|
"cpu": [
|
||||||
|
"x64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"netbsd"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/openbsd-arm64": {
|
||||||
|
"version": "0.27.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.7.tgz",
|
||||||
|
"integrity": "sha512-AFuojMQTxAz75Fo8idVcqoQWEHIXFRbOc1TrVcFSgCZtQfSdc1RXgB3tjOn/krRHENUB4j00bfGjyl2mJrU37A==",
|
||||||
|
"cpu": [
|
||||||
|
"arm64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"openbsd"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/openbsd-x64": {
|
||||||
|
"version": "0.27.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.7.tgz",
|
||||||
|
"integrity": "sha512-+A1NJmfM8WNDv5CLVQYJ5PshuRm/4cI6WMZRg1by1GwPIQPCTs1GLEUHwiiQGT5zDdyLiRM/l1G0Pv54gvtKIg==",
|
||||||
|
"cpu": [
|
||||||
|
"x64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"openbsd"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/openharmony-arm64": {
|
||||||
|
"version": "0.27.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.7.tgz",
|
||||||
|
"integrity": "sha512-+KrvYb/C8zA9CU/g0sR6w2RBw7IGc5J2BPnc3dYc5VJxHCSF1yNMxTV5LQ7GuKteQXZtspjFbiuW5/dOj7H4Yw==",
|
||||||
|
"cpu": [
|
||||||
|
"arm64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"openharmony"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/sunos-x64": {
|
||||||
|
"version": "0.27.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.7.tgz",
|
||||||
|
"integrity": "sha512-ikktIhFBzQNt/QDyOL580ti9+5mL/YZeUPKU2ivGtGjdTYoqz6jObj6nOMfhASpS4GU4Q/Clh1QtxWAvcYKamA==",
|
||||||
|
"cpu": [
|
||||||
|
"x64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"sunos"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/win32-arm64": {
|
||||||
|
"version": "0.27.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.7.tgz",
|
||||||
|
"integrity": "sha512-7yRhbHvPqSpRUV7Q20VuDwbjW5kIMwTHpptuUzV+AA46kiPze5Z7qgt6CLCK3pWFrHeNfDd1VKgyP4O+ng17CA==",
|
||||||
|
"cpu": [
|
||||||
|
"arm64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"win32"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/win32-ia32": {
|
||||||
|
"version": "0.27.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.7.tgz",
|
||||||
|
"integrity": "sha512-SmwKXe6VHIyZYbBLJrhOoCJRB/Z1tckzmgTLfFYOfpMAx63BJEaL9ExI8x7v0oAO3Zh6D/Oi1gVxEYr5oUCFhw==",
|
||||||
|
"cpu": [
|
||||||
|
"ia32"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"win32"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/win32-x64": {
|
||||||
|
"version": "0.27.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.7.tgz",
|
||||||
|
"integrity": "sha512-56hiAJPhwQ1R4i+21FVF7V8kSD5zZTdHcVuRFMW0hn753vVfQN8xlx4uOPT4xoGH0Z/oVATuR82AiqSTDIpaHg==",
|
||||||
|
"cpu": [
|
||||||
|
"x64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"win32"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@eslint-community/eslint-utils": {
|
"node_modules/@eslint-community/eslint-utils": {
|
||||||
"version": "4.9.1",
|
"version": "4.9.1",
|
||||||
"resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.9.1.tgz",
|
"resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.9.1.tgz",
|
||||||
@@ -2046,6 +2492,18 @@
|
|||||||
"url": "https://github.com/sponsors/panva"
|
"url": "https://github.com/sponsors/panva"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@prisma/adapter-pg": {
|
||||||
|
"version": "7.7.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@prisma/adapter-pg/-/adapter-pg-7.7.0.tgz",
|
||||||
|
"integrity": "sha512-q33Ta8sKbgzEpAy0lx45tAq//yMv0qcb+8nj+TCA3P4wiAY+OBFEFk/NDkZncAfHaNJeGo5WJpJdpbL+ijYx8g==",
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"dependencies": {
|
||||||
|
"@prisma/driver-adapter-utils": "7.7.0",
|
||||||
|
"@types/pg": "^8.16.0",
|
||||||
|
"pg": "^8.16.3",
|
||||||
|
"postgres-array": "3.0.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@prisma/client": {
|
"node_modules/@prisma/client": {
|
||||||
"version": "7.7.0",
|
"version": "7.7.0",
|
||||||
"resolved": "https://registry.npmjs.org/@prisma/client/-/client-7.7.0.tgz",
|
"resolved": "https://registry.npmjs.org/@prisma/client/-/client-7.7.0.tgz",
|
||||||
@@ -2093,7 +2551,6 @@
|
|||||||
"version": "7.7.0",
|
"version": "7.7.0",
|
||||||
"resolved": "https://registry.npmjs.org/@prisma/debug/-/debug-7.7.0.tgz",
|
"resolved": "https://registry.npmjs.org/@prisma/debug/-/debug-7.7.0.tgz",
|
||||||
"integrity": "sha512-12J62XdqCmpiwJHhHdQxZeY3ckVCWIFmcJP8hg5dPTceeiQ0wiojXGFYTluKqFQfu46fRLgb/rLALZMAx3+dTA==",
|
"integrity": "sha512-12J62XdqCmpiwJHhHdQxZeY3ckVCWIFmcJP8hg5dPTceeiQ0wiojXGFYTluKqFQfu46fRLgb/rLALZMAx3+dTA==",
|
||||||
"devOptional": true,
|
|
||||||
"license": "Apache-2.0"
|
"license": "Apache-2.0"
|
||||||
},
|
},
|
||||||
"node_modules/@prisma/dev": {
|
"node_modules/@prisma/dev": {
|
||||||
@@ -2122,6 +2579,15 @@
|
|||||||
"zeptomatch": "2.1.0"
|
"zeptomatch": "2.1.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@prisma/driver-adapter-utils": {
|
||||||
|
"version": "7.7.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@prisma/driver-adapter-utils/-/driver-adapter-utils-7.7.0.tgz",
|
||||||
|
"integrity": "sha512-gZXREeu6mOk7zXfGFJgh86p7Vhj0sXNKp+4Cg1tWYo7V2dfncP2qxS2BiTmbIIha8xPqItkl0WSw38RuSq1HoQ==",
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"dependencies": {
|
||||||
|
"@prisma/debug": "7.7.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@prisma/engines": {
|
"node_modules/@prisma/engines": {
|
||||||
"version": "7.7.0",
|
"version": "7.7.0",
|
||||||
"resolved": "https://registry.npmjs.org/@prisma/engines/-/engines-7.7.0.tgz",
|
"resolved": "https://registry.npmjs.org/@prisma/engines/-/engines-7.7.0.tgz",
|
||||||
@@ -2956,6 +3422,17 @@
|
|||||||
"@types/node": "*"
|
"@types/node": "*"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@types/pg": {
|
||||||
|
"version": "8.20.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@types/pg/-/pg-8.20.0.tgz",
|
||||||
|
"integrity": "sha512-bEPFOaMAHTEP1EzpvHTbmwR8UsFyHSKsRisLIHVMXnpNefSbGA1bD6CVy+qKjGSqmZqNqBDV2azOBo8TgkcVow==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@types/node": "*",
|
||||||
|
"pg-protocol": "*",
|
||||||
|
"pg-types": "^2.2.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@types/react": {
|
"node_modules/@types/react": {
|
||||||
"version": "19.2.14",
|
"version": "19.2.14",
|
||||||
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.14.tgz",
|
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.14.tgz",
|
||||||
@@ -5272,6 +5749,48 @@
|
|||||||
"benchmarks"
|
"benchmarks"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
|
"node_modules/esbuild": {
|
||||||
|
"version": "0.27.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.7.tgz",
|
||||||
|
"integrity": "sha512-IxpibTjyVnmrIQo5aqNpCgoACA/dTKLTlhMHihVHhdkxKyPO1uBBthumT0rdHmcsk9uMonIWS0m4FljWzILh3w==",
|
||||||
|
"dev": true,
|
||||||
|
"hasInstallScript": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"bin": {
|
||||||
|
"esbuild": "bin/esbuild"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
},
|
||||||
|
"optionalDependencies": {
|
||||||
|
"@esbuild/aix-ppc64": "0.27.7",
|
||||||
|
"@esbuild/android-arm": "0.27.7",
|
||||||
|
"@esbuild/android-arm64": "0.27.7",
|
||||||
|
"@esbuild/android-x64": "0.27.7",
|
||||||
|
"@esbuild/darwin-arm64": "0.27.7",
|
||||||
|
"@esbuild/darwin-x64": "0.27.7",
|
||||||
|
"@esbuild/freebsd-arm64": "0.27.7",
|
||||||
|
"@esbuild/freebsd-x64": "0.27.7",
|
||||||
|
"@esbuild/linux-arm": "0.27.7",
|
||||||
|
"@esbuild/linux-arm64": "0.27.7",
|
||||||
|
"@esbuild/linux-ia32": "0.27.7",
|
||||||
|
"@esbuild/linux-loong64": "0.27.7",
|
||||||
|
"@esbuild/linux-mips64el": "0.27.7",
|
||||||
|
"@esbuild/linux-ppc64": "0.27.7",
|
||||||
|
"@esbuild/linux-riscv64": "0.27.7",
|
||||||
|
"@esbuild/linux-s390x": "0.27.7",
|
||||||
|
"@esbuild/linux-x64": "0.27.7",
|
||||||
|
"@esbuild/netbsd-arm64": "0.27.7",
|
||||||
|
"@esbuild/netbsd-x64": "0.27.7",
|
||||||
|
"@esbuild/openbsd-arm64": "0.27.7",
|
||||||
|
"@esbuild/openbsd-x64": "0.27.7",
|
||||||
|
"@esbuild/openharmony-arm64": "0.27.7",
|
||||||
|
"@esbuild/sunos-x64": "0.27.7",
|
||||||
|
"@esbuild/win32-arm64": "0.27.7",
|
||||||
|
"@esbuild/win32-ia32": "0.27.7",
|
||||||
|
"@esbuild/win32-x64": "0.27.7"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/escalade": {
|
"node_modules/escalade": {
|
||||||
"version": "3.2.0",
|
"version": "3.2.0",
|
||||||
"resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",
|
"resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",
|
||||||
@@ -6170,6 +6689,21 @@
|
|||||||
"node": ">=14.14"
|
"node": ">=14.14"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/fsevents": {
|
||||||
|
"version": "2.3.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
|
||||||
|
"integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
|
||||||
|
"dev": true,
|
||||||
|
"hasInstallScript": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"darwin"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/function-bind": {
|
"node_modules/function-bind": {
|
||||||
"version": "1.1.2",
|
"version": "1.1.2",
|
||||||
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
|
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
|
||||||
@@ -8868,6 +9402,104 @@
|
|||||||
"devOptional": true,
|
"devOptional": true,
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/pg": {
|
||||||
|
"version": "8.20.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/pg/-/pg-8.20.0.tgz",
|
||||||
|
"integrity": "sha512-ldhMxz2r8fl/6QkXnBD3CR9/xg694oT6DZQ2s6c/RI28OjtSOpxnPrUCGOBJ46RCUxcWdx3p6kw/xnDHjKvaRA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"pg-connection-string": "^2.12.0",
|
||||||
|
"pg-pool": "^3.13.0",
|
||||||
|
"pg-protocol": "^1.13.0",
|
||||||
|
"pg-types": "2.2.0",
|
||||||
|
"pgpass": "1.0.5"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 16.0.0"
|
||||||
|
},
|
||||||
|
"optionalDependencies": {
|
||||||
|
"pg-cloudflare": "^1.3.0"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"pg-native": ">=3.0.1"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"pg-native": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/pg-cloudflare": {
|
||||||
|
"version": "1.3.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/pg-cloudflare/-/pg-cloudflare-1.3.0.tgz",
|
||||||
|
"integrity": "sha512-6lswVVSztmHiRtD6I8hw4qP/nDm1EJbKMRhf3HCYaqud7frGysPv7FYJ5noZQdhQtN2xJnimfMtvQq21pdbzyQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"node_modules/pg-connection-string": {
|
||||||
|
"version": "2.12.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/pg-connection-string/-/pg-connection-string-2.12.0.tgz",
|
||||||
|
"integrity": "sha512-U7qg+bpswf3Cs5xLzRqbXbQl85ng0mfSV/J0nnA31MCLgvEaAo7CIhmeyrmJpOr7o+zm0rXK+hNnT5l9RHkCkQ==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/pg-int8": {
|
||||||
|
"version": "1.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/pg-int8/-/pg-int8-1.0.1.tgz",
|
||||||
|
"integrity": "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==",
|
||||||
|
"license": "ISC",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=4.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/pg-pool": {
|
||||||
|
"version": "3.13.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/pg-pool/-/pg-pool-3.13.0.tgz",
|
||||||
|
"integrity": "sha512-gB+R+Xud1gLFuRD/QgOIgGOBE2KCQPaPwkzBBGC9oG69pHTkhQeIuejVIk3/cnDyX39av2AxomQiyPT13WKHQA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"peerDependencies": {
|
||||||
|
"pg": ">=8.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/pg-protocol": {
|
||||||
|
"version": "1.13.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.13.0.tgz",
|
||||||
|
"integrity": "sha512-zzdvXfS6v89r6v7OcFCHfHlyG/wvry1ALxZo4LqgUoy7W9xhBDMaqOuMiF3qEV45VqsN6rdlcehHrfDtlCPc8w==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/pg-types": {
|
||||||
|
"version": "2.2.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/pg-types/-/pg-types-2.2.0.tgz",
|
||||||
|
"integrity": "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"pg-int8": "1.0.1",
|
||||||
|
"postgres-array": "~2.0.0",
|
||||||
|
"postgres-bytea": "~1.0.0",
|
||||||
|
"postgres-date": "~1.0.4",
|
||||||
|
"postgres-interval": "^1.1.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/pg-types/node_modules/postgres-array": {
|
||||||
|
"version": "2.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz",
|
||||||
|
"integrity": "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/pgpass": {
|
||||||
|
"version": "1.0.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/pgpass/-/pgpass-1.0.5.tgz",
|
||||||
|
"integrity": "sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"split2": "^4.1.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/picocolors": {
|
"node_modules/picocolors": {
|
||||||
"version": "1.1.1",
|
"version": "1.1.1",
|
||||||
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
|
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
|
||||||
@@ -8972,6 +9604,45 @@
|
|||||||
"url": "https://github.com/sponsors/porsager"
|
"url": "https://github.com/sponsors/porsager"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/postgres-array": {
|
||||||
|
"version": "3.0.4",
|
||||||
|
"resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-3.0.4.tgz",
|
||||||
|
"integrity": "sha512-nAUSGfSDGOaOAEGwqsRY27GPOea7CNipJPOA7lPbdEpx5Kg3qzdP0AaWC5MlhTWV9s4hFX39nomVZ+C4tnGOJQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=12"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/postgres-bytea": {
|
||||||
|
"version": "1.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/postgres-bytea/-/postgres-bytea-1.0.1.tgz",
|
||||||
|
"integrity": "sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=0.10.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/postgres-date": {
|
||||||
|
"version": "1.0.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/postgres-date/-/postgres-date-1.0.7.tgz",
|
||||||
|
"integrity": "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=0.10.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/postgres-interval": {
|
||||||
|
"version": "1.2.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/postgres-interval/-/postgres-interval-1.2.0.tgz",
|
||||||
|
"integrity": "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"xtend": "^4.0.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=0.10.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/powershell-utils": {
|
"node_modules/powershell-utils": {
|
||||||
"version": "0.1.0",
|
"version": "0.1.0",
|
||||||
"resolved": "https://registry.npmjs.org/powershell-utils/-/powershell-utils-0.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/powershell-utils/-/powershell-utils-0.1.0.tgz",
|
||||||
@@ -10045,6 +10716,15 @@
|
|||||||
"node": ">=0.10.0"
|
"node": ">=0.10.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/split2": {
|
||||||
|
"version": "4.2.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz",
|
||||||
|
"integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==",
|
||||||
|
"license": "ISC",
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 10.x"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/sqlstring": {
|
"node_modules/sqlstring": {
|
||||||
"version": "2.3.3",
|
"version": "2.3.3",
|
||||||
"resolved": "https://registry.npmjs.org/sqlstring/-/sqlstring-2.3.3.tgz",
|
"resolved": "https://registry.npmjs.org/sqlstring/-/sqlstring-2.3.3.tgz",
|
||||||
@@ -10574,6 +11254,26 @@
|
|||||||
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
|
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
|
||||||
"license": "0BSD"
|
"license": "0BSD"
|
||||||
},
|
},
|
||||||
|
"node_modules/tsx": {
|
||||||
|
"version": "4.21.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/tsx/-/tsx-4.21.0.tgz",
|
||||||
|
"integrity": "sha512-5C1sg4USs1lfG0GFb2RLXsdpXqBSEhAaA/0kPL01wxzpMqLILNxIxIOKiILz+cdg/pLnOUxFYOR5yhHU666wbw==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"esbuild": "~0.27.0",
|
||||||
|
"get-tsconfig": "^4.7.5"
|
||||||
|
},
|
||||||
|
"bin": {
|
||||||
|
"tsx": "dist/cli.mjs"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18.0.0"
|
||||||
|
},
|
||||||
|
"optionalDependencies": {
|
||||||
|
"fsevents": "~2.3.3"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/tw-animate-css": {
|
"node_modules/tw-animate-css": {
|
||||||
"version": "1.4.0",
|
"version": "1.4.0",
|
||||||
"resolved": "https://registry.npmjs.org/tw-animate-css/-/tw-animate-css-1.4.0.tgz",
|
"resolved": "https://registry.npmjs.org/tw-animate-css/-/tw-animate-css-1.4.0.tgz",
|
||||||
@@ -11153,6 +11853,15 @@
|
|||||||
"url": "https://github.com/sponsors/sindresorhus"
|
"url": "https://github.com/sponsors/sindresorhus"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/xtend": {
|
||||||
|
"version": "4.0.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",
|
||||||
|
"integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=0.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/y18n": {
|
"node_modules/y18n": {
|
||||||
"version": "5.0.8",
|
"version": "5.0.8",
|
||||||
"resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",
|
"resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
{
|
{
|
||||||
"name": "finance-app-scaffold",
|
"name": "finance-app",
|
||||||
"version": "0.1.0",
|
"version": "0.1.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"scripts": {
|
"scripts": {
|
||||||
@@ -10,6 +10,7 @@
|
|||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@base-ui/react": "^1.4.0",
|
"@base-ui/react": "^1.4.0",
|
||||||
|
"@prisma/adapter-pg": "^7.7.0",
|
||||||
"@prisma/client": "^7.7.0",
|
"@prisma/client": "^7.7.0",
|
||||||
"bcryptjs": "^3.0.3",
|
"bcryptjs": "^3.0.3",
|
||||||
"class-variance-authority": "^0.7.1",
|
"class-variance-authority": "^0.7.1",
|
||||||
@@ -18,6 +19,7 @@
|
|||||||
"next": "16.2.4",
|
"next": "16.2.4",
|
||||||
"next-auth": "^5.0.0-beta.31",
|
"next-auth": "^5.0.0-beta.31",
|
||||||
"papaparse": "^5.5.3",
|
"papaparse": "^5.5.3",
|
||||||
|
"pg": "^8.20.0",
|
||||||
"react": "19.2.4",
|
"react": "19.2.4",
|
||||||
"react-dom": "19.2.4",
|
"react-dom": "19.2.4",
|
||||||
"recharts": "^3.8.1",
|
"recharts": "^3.8.1",
|
||||||
@@ -26,17 +28,22 @@
|
|||||||
"tw-animate-css": "^1.4.0",
|
"tw-animate-css": "^1.4.0",
|
||||||
"zod": "^4.3.6"
|
"zod": "^4.3.6"
|
||||||
},
|
},
|
||||||
|
"prisma": {
|
||||||
|
"seed": "tsx prisma/seed.ts"
|
||||||
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@tailwindcss/postcss": "^4",
|
"@tailwindcss/postcss": "^4",
|
||||||
"@types/bcryptjs": "^2.4.6",
|
"@types/bcryptjs": "^2.4.6",
|
||||||
"@types/node": "^20",
|
"@types/node": "^20",
|
||||||
"@types/papaparse": "^5.5.2",
|
"@types/papaparse": "^5.5.2",
|
||||||
|
"@types/pg": "^8.20.0",
|
||||||
"@types/react": "^19",
|
"@types/react": "^19",
|
||||||
"@types/react-dom": "^19",
|
"@types/react-dom": "^19",
|
||||||
"eslint": "^9",
|
"eslint": "^9",
|
||||||
"eslint-config-next": "16.2.4",
|
"eslint-config-next": "16.2.4",
|
||||||
"prisma": "^7.7.0",
|
"prisma": "^7.7.0",
|
||||||
"tailwindcss": "^4",
|
"tailwindcss": "^4",
|
||||||
|
"tsx": "^4.21.0",
|
||||||
"typescript": "^5"
|
"typescript": "^5"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
14
prisma.config.ts
Normal file
14
prisma.config.ts
Normal file
@@ -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"],
|
||||||
|
},
|
||||||
|
});
|
||||||
113
prisma/schema.prisma
Normal file
113
prisma/schema.prisma
Normal file
@@ -0,0 +1,113 @@
|
|||||||
|
generator client {
|
||||||
|
provider = "prisma-client"
|
||||||
|
output = "../src/generated/prisma"
|
||||||
|
}
|
||||||
|
|
||||||
|
datasource db {
|
||||||
|
provider = "postgresql"
|
||||||
|
}
|
||||||
|
|
||||||
|
model User {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
email String @unique
|
||||||
|
passwordHash String
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
|
accounts Account[]
|
||||||
|
budgets Budget[]
|
||||||
|
}
|
||||||
|
|
||||||
|
enum AccountType {
|
||||||
|
BANK
|
||||||
|
CREDIT_CARD
|
||||||
|
}
|
||||||
|
|
||||||
|
model Account {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
userId String
|
||||||
|
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||||
|
name String
|
||||||
|
institution String?
|
||||||
|
type AccountType
|
||||||
|
currency String @default("USD")
|
||||||
|
currentBalanceCents Int @default(0)
|
||||||
|
isActive Boolean @default(true)
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
|
transactions Transaction[]
|
||||||
|
uploads CsvUpload[]
|
||||||
|
|
||||||
|
@@index([userId])
|
||||||
|
}
|
||||||
|
|
||||||
|
enum TransactionType {
|
||||||
|
DEBIT
|
||||||
|
CREDIT
|
||||||
|
}
|
||||||
|
|
||||||
|
model Transaction {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
accountId String
|
||||||
|
account Account @relation(fields: [accountId], references: [id], onDelete: Cascade)
|
||||||
|
uploadId String?
|
||||||
|
upload CsvUpload? @relation(fields: [uploadId], references: [id])
|
||||||
|
budgetId String?
|
||||||
|
budget Budget? @relation(fields: [budgetId], references: [id], onDelete: SetNull)
|
||||||
|
date DateTime
|
||||||
|
description String
|
||||||
|
amountCents Int
|
||||||
|
type TransactionType
|
||||||
|
category String?
|
||||||
|
notes String?
|
||||||
|
dedupeHash String
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
|
|
||||||
|
@@unique([dedupeHash])
|
||||||
|
@@index([accountId, date])
|
||||||
|
@@index([date])
|
||||||
|
@@index([budgetId])
|
||||||
|
}
|
||||||
|
|
||||||
|
model Budget {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
userId String
|
||||||
|
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||||
|
name String
|
||||||
|
limitCents Int?
|
||||||
|
color String?
|
||||||
|
isActive Boolean @default(true)
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
|
transactions Transaction[]
|
||||||
|
|
||||||
|
@@index([userId])
|
||||||
|
}
|
||||||
|
|
||||||
|
model CsvUpload {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
accountId String
|
||||||
|
account Account @relation(fields: [accountId], references: [id])
|
||||||
|
fileName String
|
||||||
|
rowCount Int
|
||||||
|
importedCount Int
|
||||||
|
skippedCount Int
|
||||||
|
status String
|
||||||
|
errorMessage String?
|
||||||
|
uploadedAt DateTime @default(now())
|
||||||
|
transactions Transaction[]
|
||||||
|
|
||||||
|
@@index([accountId])
|
||||||
|
}
|
||||||
|
|
||||||
|
model BalanceSnapshot {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
accountId String
|
||||||
|
year Int
|
||||||
|
month Int
|
||||||
|
balanceCents Int
|
||||||
|
computedAt DateTime @default(now())
|
||||||
|
|
||||||
|
@@unique([accountId, year, month])
|
||||||
|
@@index([year, month])
|
||||||
|
}
|
||||||
31
prisma/seed.ts
Normal file
31
prisma/seed.ts
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
import { Pool } from 'pg'
|
||||||
|
import { PrismaPg } from '@prisma/adapter-pg'
|
||||||
|
import { PrismaClient } from '../src/generated/prisma/client'
|
||||||
|
import bcrypt from 'bcryptjs'
|
||||||
|
|
||||||
|
const pool = new Pool({ connectionString: process.env.DATABASE_URL })
|
||||||
|
const adapter = new PrismaPg(pool)
|
||||||
|
const prisma = new PrismaClient({ adapter })
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
const email = process.env.SEED_EMAIL
|
||||||
|
const password = process.env.SEED_PASSWORD
|
||||||
|
|
||||||
|
if (!email || !password) {
|
||||||
|
throw new Error('SEED_EMAIL and SEED_PASSWORD must be set in .env')
|
||||||
|
}
|
||||||
|
|
||||||
|
const passwordHash = await bcrypt.hash(password, 12)
|
||||||
|
|
||||||
|
const user = await prisma.user.upsert({
|
||||||
|
where: { email },
|
||||||
|
update: { passwordHash },
|
||||||
|
create: { email, passwordHash },
|
||||||
|
})
|
||||||
|
|
||||||
|
console.log(`Seeded user: ${user.email}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
main()
|
||||||
|
.catch(console.error)
|
||||||
|
.finally(() => prisma.$disconnect())
|
||||||
88
src/app/(app)/accounts/[id]/page.tsx
Normal file
88
src/app/(app)/accounts/[id]/page.tsx
Normal file
@@ -0,0 +1,88 @@
|
|||||||
|
import { notFound } from 'next/navigation'
|
||||||
|
import { auth } from '@/lib/auth'
|
||||||
|
import { prisma } from '@/lib/prisma'
|
||||||
|
import { AccountBadge } from '@/components/accounts/AccountBadge'
|
||||||
|
import { formatCents } from '@/lib/utils/currency'
|
||||||
|
import { TransactionTable } from '@/components/transactions/TransactionTable'
|
||||||
|
|
||||||
|
const PAGE_LIMIT = 50
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
params: Promise<{ id: string }>
|
||||||
|
searchParams: Promise<Record<string, string | string[] | undefined>>
|
||||||
|
}
|
||||||
|
|
||||||
|
export default async function AccountDetailPage({ params, searchParams }: Props) {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) return null
|
||||||
|
|
||||||
|
const { id } = await params
|
||||||
|
const sp = await searchParams
|
||||||
|
const page = Math.max(1, Number(sp.page) || 1)
|
||||||
|
|
||||||
|
const [account, budgets] = await Promise.all([
|
||||||
|
prisma.account.findFirst({ where: { id, userId: session.user.id } }),
|
||||||
|
prisma.budget.findMany({
|
||||||
|
where: { userId: session.user.id, isActive: true },
|
||||||
|
select: { id: true, name: true, color: true },
|
||||||
|
orderBy: { name: 'asc' },
|
||||||
|
}),
|
||||||
|
])
|
||||||
|
|
||||||
|
if (!account) notFound()
|
||||||
|
|
||||||
|
const where = { accountId: id }
|
||||||
|
const [transactions, total] = await Promise.all([
|
||||||
|
prisma.transaction.findMany({
|
||||||
|
where,
|
||||||
|
include: {
|
||||||
|
account: { select: { name: true, type: true } },
|
||||||
|
budget: { select: { id: true, name: true, color: true } },
|
||||||
|
},
|
||||||
|
orderBy: { date: 'desc' },
|
||||||
|
skip: (page - 1) * PAGE_LIMIT,
|
||||||
|
take: PAGE_LIMIT,
|
||||||
|
}),
|
||||||
|
prisma.transaction.count({ where }),
|
||||||
|
])
|
||||||
|
|
||||||
|
const rows = transactions.map((tx) => ({
|
||||||
|
...tx,
|
||||||
|
date: tx.date.toISOString(),
|
||||||
|
createdAt: undefined,
|
||||||
|
updatedAt: undefined,
|
||||||
|
}))
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="p-6 space-y-6">
|
||||||
|
<div className="flex items-start justify-between">
|
||||||
|
<div className="space-y-1">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<h1 className="text-2xl font-bold">{account.name}</h1>
|
||||||
|
<AccountBadge type={account.type} />
|
||||||
|
</div>
|
||||||
|
{account.institution && (
|
||||||
|
<p className="text-muted-foreground">{account.institution}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="text-right">
|
||||||
|
<p className="text-3xl font-bold tabular-nums">
|
||||||
|
{formatCents(account.currentBalanceCents)}
|
||||||
|
</p>
|
||||||
|
<p className="text-xs text-muted-foreground mt-1">
|
||||||
|
{account.isActive ? 'Active' : 'Inactive'}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<TransactionTable
|
||||||
|
transactions={rows}
|
||||||
|
total={total}
|
||||||
|
page={page}
|
||||||
|
limit={PAGE_LIMIT}
|
||||||
|
showAccount={false}
|
||||||
|
budgets={budgets}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
19
src/app/(app)/accounts/page.tsx
Normal file
19
src/app/(app)/accounts/page.tsx
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
import { auth } from '@/lib/auth'
|
||||||
|
import { prisma } from '@/lib/prisma'
|
||||||
|
import { AccountList } from '@/components/accounts/AccountList'
|
||||||
|
|
||||||
|
export default async function AccountsPage() {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) return null
|
||||||
|
|
||||||
|
const accounts = await prisma.account.findMany({
|
||||||
|
where: { userId: session.user.id },
|
||||||
|
orderBy: { createdAt: 'asc' },
|
||||||
|
})
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="p-6">
|
||||||
|
<AccountList accounts={accounts} />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
47
src/app/(app)/budgets/page.tsx
Normal file
47
src/app/(app)/budgets/page.tsx
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
import { auth } from '@/lib/auth'
|
||||||
|
import { prisma } from '@/lib/prisma'
|
||||||
|
import { BudgetList } from '@/components/budgets/BudgetList'
|
||||||
|
|
||||||
|
export default async function BudgetsPage() {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) return null
|
||||||
|
|
||||||
|
const now = new Date()
|
||||||
|
const monthStart = new Date(now.getFullYear(), now.getMonth(), 1)
|
||||||
|
const monthEnd = new Date(now.getFullYear(), now.getMonth() + 1, 0, 23, 59, 59, 999)
|
||||||
|
|
||||||
|
const [budgets, spendRows] = await Promise.all([
|
||||||
|
prisma.budget.findMany({
|
||||||
|
where: { userId: session.user.id },
|
||||||
|
orderBy: { createdAt: 'asc' },
|
||||||
|
}),
|
||||||
|
prisma.$queryRaw<{ budgetId: string; total: bigint }[]>`
|
||||||
|
SELECT t."budgetId", COALESCE(SUM(t."amountCents"), 0)::bigint AS total
|
||||||
|
FROM "Transaction" t
|
||||||
|
JOIN "Account" a ON t."accountId" = a.id
|
||||||
|
WHERE a."userId" = ${session.user.id}
|
||||||
|
AND t."budgetId" IS NOT NULL
|
||||||
|
AND t.type = 'DEBIT'
|
||||||
|
AND t.date >= ${monthStart}
|
||||||
|
AND t.date <= ${monthEnd}
|
||||||
|
GROUP BY t."budgetId"
|
||||||
|
`,
|
||||||
|
])
|
||||||
|
|
||||||
|
const spendMap = new Map(spendRows.map((r) => [r.budgetId, Number(r.total)]))
|
||||||
|
|
||||||
|
const budgetsWithSpend = budgets.map((b) => ({
|
||||||
|
id: b.id,
|
||||||
|
name: b.name,
|
||||||
|
limitCents: b.limitCents,
|
||||||
|
color: b.color,
|
||||||
|
isActive: b.isActive,
|
||||||
|
spendCents: spendMap.get(b.id) ?? 0,
|
||||||
|
}))
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="p-6">
|
||||||
|
<BudgetList budgets={budgetsWithSpend} />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
104
src/app/(app)/dashboard/page.tsx
Normal file
104
src/app/(app)/dashboard/page.tsx
Normal file
@@ -0,0 +1,104 @@
|
|||||||
|
import { auth } from '@/lib/auth'
|
||||||
|
import { prisma } from '@/lib/prisma'
|
||||||
|
import { monthBounds, monthLabel } from '@/lib/utils/dates'
|
||||||
|
import { NetWorthCard } from '@/components/dashboard/NetWorthCard'
|
||||||
|
import { CashFlowCard } from '@/components/dashboard/CashFlowCard'
|
||||||
|
import { RecentTransactions } from '@/components/dashboard/RecentTransactions'
|
||||||
|
import { BudgetSummary } from '@/components/dashboard/BudgetSummary'
|
||||||
|
|
||||||
|
export default async function DashboardPage() {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) return null
|
||||||
|
|
||||||
|
const userId = session.user.id
|
||||||
|
const { start, end } = monthBounds()
|
||||||
|
|
||||||
|
const [accounts, cashFlowRows, budgets, spendRows, recentTx] = await Promise.all([
|
||||||
|
prisma.account.findMany({
|
||||||
|
where: { userId, isActive: true },
|
||||||
|
select: { id: true, name: true, type: true, currentBalanceCents: true },
|
||||||
|
orderBy: { name: 'asc' },
|
||||||
|
}),
|
||||||
|
prisma.$queryRaw<{ type: string; total: bigint }[]>`
|
||||||
|
SELECT t.type, COALESCE(SUM(t."amountCents"), 0)::bigint AS total
|
||||||
|
FROM "Transaction" t
|
||||||
|
JOIN "Account" a ON t."accountId" = a.id
|
||||||
|
WHERE a."userId" = ${userId}
|
||||||
|
AND a.type = 'BANK'
|
||||||
|
AND t.date >= ${start}
|
||||||
|
AND t.date <= ${end}
|
||||||
|
GROUP BY t.type
|
||||||
|
`,
|
||||||
|
prisma.budget.findMany({
|
||||||
|
where: { userId, isActive: true },
|
||||||
|
orderBy: { name: 'asc' },
|
||||||
|
}),
|
||||||
|
prisma.$queryRaw<{ budgetId: string; total: bigint }[]>`
|
||||||
|
SELECT t."budgetId", COALESCE(SUM(t."amountCents"), 0)::bigint AS total
|
||||||
|
FROM "Transaction" t
|
||||||
|
JOIN "Account" a ON t."accountId" = a.id
|
||||||
|
WHERE a."userId" = ${userId}
|
||||||
|
AND t."budgetId" IS NOT NULL
|
||||||
|
AND t.type = 'DEBIT'
|
||||||
|
AND t.date >= ${start}
|
||||||
|
AND t.date <= ${end}
|
||||||
|
GROUP BY t."budgetId"
|
||||||
|
`,
|
||||||
|
prisma.transaction.findMany({
|
||||||
|
where: { account: { userId } },
|
||||||
|
include: { account: { select: { name: true } } },
|
||||||
|
orderBy: { date: 'desc' },
|
||||||
|
take: 5,
|
||||||
|
}),
|
||||||
|
])
|
||||||
|
|
||||||
|
const bankAccounts = accounts.filter((a) => a.type === 'BANK')
|
||||||
|
const netWorthCents = bankAccounts.reduce((s, a) => s + a.currentBalanceCents, 0)
|
||||||
|
|
||||||
|
const cfMap = Object.fromEntries(cashFlowRows.map((r) => [r.type, Number(r.total)]))
|
||||||
|
const creditsCents = cfMap['CREDIT'] ?? 0
|
||||||
|
const debitsCents = cfMap['DEBIT'] ?? 0
|
||||||
|
|
||||||
|
const spendMap = new Map(spendRows.map((r) => [r.budgetId, Number(r.total)]))
|
||||||
|
|
||||||
|
const recentTransactions = recentTx.map((t) => ({
|
||||||
|
id: t.id,
|
||||||
|
date: t.date.toISOString(),
|
||||||
|
description: t.description,
|
||||||
|
amountCents: t.amountCents,
|
||||||
|
type: t.type,
|
||||||
|
accountName: t.account.name,
|
||||||
|
}))
|
||||||
|
|
||||||
|
const budgetsWithSpend = budgets.map((b) => ({
|
||||||
|
id: b.id,
|
||||||
|
name: b.name,
|
||||||
|
limitCents: b.limitCents,
|
||||||
|
color: b.color,
|
||||||
|
spendCents: spendMap.get(b.id) ?? 0,
|
||||||
|
}))
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="p-6 space-y-6">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-2xl font-bold">Dashboard</h1>
|
||||||
|
<p className="text-sm text-muted-foreground">{monthLabel()}</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid gap-4 sm:grid-cols-2">
|
||||||
|
<NetWorthCard netWorthCents={netWorthCents} bankAccounts={bankAccounts} />
|
||||||
|
<CashFlowCard
|
||||||
|
monthLabel={monthLabel()}
|
||||||
|
creditsCents={creditsCents}
|
||||||
|
debitsCents={debitsCents}
|
||||||
|
netCents={creditsCents - debitsCents}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid gap-4 lg:grid-cols-2">
|
||||||
|
<RecentTransactions transactions={recentTransactions} />
|
||||||
|
<BudgetSummary budgets={budgetsWithSpend} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
186
src/app/(app)/graphs/page.tsx
Normal file
186
src/app/(app)/graphs/page.tsx
Normal file
@@ -0,0 +1,186 @@
|
|||||||
|
import { auth } from '@/lib/auth'
|
||||||
|
import { prisma } from '@/lib/prisma'
|
||||||
|
import { monthBounds, monthLabel, formatYearMonth, lastNMonthsStart } from '@/lib/utils/dates'
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||||
|
import { NetWorthTrendChart } from '@/components/graphs/NetWorthTrendChart'
|
||||||
|
import { CashFlowChart } from '@/components/graphs/CashFlowChart'
|
||||||
|
import { MonthlySpendingChart } from '@/components/graphs/MonthlySpendingChart'
|
||||||
|
import { CategoryBreakdownChart } from '@/components/graphs/CategoryBreakdownChart'
|
||||||
|
import { BudgetChart } from '@/components/graphs/BudgetChart'
|
||||||
|
|
||||||
|
export default async function GraphsPage() {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) return null
|
||||||
|
|
||||||
|
const userId = session.user.id
|
||||||
|
const { start: monthStart, end: monthEnd } = monthBounds()
|
||||||
|
const sixMonthsAgo = lastNMonthsStart(6)
|
||||||
|
|
||||||
|
const [netWorthRows, cashFlowRows, spendingRows, categoryRows, budgetSpendRows, budgets] =
|
||||||
|
await Promise.all([
|
||||||
|
// Net worth trend from BalanceSnapshot (all time, BANK only)
|
||||||
|
prisma.$queryRaw<{ year: number; month: number; total: bigint }[]>`
|
||||||
|
SELECT bs.year, bs.month, COALESCE(SUM(bs."balanceCents"), 0)::bigint AS total
|
||||||
|
FROM "BalanceSnapshot" bs
|
||||||
|
JOIN "Account" a ON bs."accountId" = a.id
|
||||||
|
WHERE a."userId" = ${userId} AND a.type = 'BANK'
|
||||||
|
GROUP BY bs.year, bs.month
|
||||||
|
ORDER BY bs.year, bs.month
|
||||||
|
`,
|
||||||
|
// Monthly cash flow (last 6 months, BANK only)
|
||||||
|
prisma.$queryRaw<{ year: number; month: number; type: string; total: bigint }[]>`
|
||||||
|
SELECT
|
||||||
|
EXTRACT(YEAR FROM t.date)::int AS year,
|
||||||
|
EXTRACT(MONTH FROM t.date)::int AS month,
|
||||||
|
t.type,
|
||||||
|
COALESCE(SUM(t."amountCents"), 0)::bigint AS total
|
||||||
|
FROM "Transaction" t
|
||||||
|
JOIN "Account" a ON t."accountId" = a.id
|
||||||
|
WHERE a."userId" = ${userId}
|
||||||
|
AND a.type = 'BANK'
|
||||||
|
AND t.date >= ${sixMonthsAgo}
|
||||||
|
GROUP BY year, month, t.type
|
||||||
|
ORDER BY year, month
|
||||||
|
`,
|
||||||
|
// Monthly total spending across ALL accounts (last 6 months, DEBIT only)
|
||||||
|
prisma.$queryRaw<{ year: number; month: number; total: bigint }[]>`
|
||||||
|
SELECT
|
||||||
|
EXTRACT(YEAR FROM t.date)::int AS year,
|
||||||
|
EXTRACT(MONTH FROM t.date)::int AS month,
|
||||||
|
COALESCE(SUM(t."amountCents"), 0)::bigint AS total
|
||||||
|
FROM "Transaction" t
|
||||||
|
JOIN "Account" a ON t."accountId" = a.id
|
||||||
|
WHERE a."userId" = ${userId}
|
||||||
|
AND t.type = 'DEBIT'
|
||||||
|
AND t.date >= ${sixMonthsAgo}
|
||||||
|
GROUP BY year, month
|
||||||
|
ORDER BY year, month
|
||||||
|
`,
|
||||||
|
// Category breakdown (current month, all accounts, DEBIT)
|
||||||
|
prisma.$queryRaw<{ category: string; total: bigint }[]>`
|
||||||
|
SELECT
|
||||||
|
COALESCE(t.category, 'Uncategorized') AS category,
|
||||||
|
COALESCE(SUM(t."amountCents"), 0)::bigint AS total
|
||||||
|
FROM "Transaction" t
|
||||||
|
JOIN "Account" a ON t."accountId" = a.id
|
||||||
|
WHERE a."userId" = ${userId}
|
||||||
|
AND t.type = 'DEBIT'
|
||||||
|
AND t.date >= ${monthStart}
|
||||||
|
AND t.date <= ${monthEnd}
|
||||||
|
GROUP BY category
|
||||||
|
ORDER BY total DESC
|
||||||
|
`,
|
||||||
|
// Budget spend (current month)
|
||||||
|
prisma.$queryRaw<{ budgetId: string; total: bigint }[]>`
|
||||||
|
SELECT t."budgetId", COALESCE(SUM(t."amountCents"), 0)::bigint AS total
|
||||||
|
FROM "Transaction" t
|
||||||
|
JOIN "Account" a ON t."accountId" = a.id
|
||||||
|
WHERE a."userId" = ${userId}
|
||||||
|
AND t."budgetId" IS NOT NULL
|
||||||
|
AND t.type = 'DEBIT'
|
||||||
|
AND t.date >= ${monthStart}
|
||||||
|
AND t.date <= ${monthEnd}
|
||||||
|
GROUP BY t."budgetId"
|
||||||
|
`,
|
||||||
|
prisma.budget.findMany({
|
||||||
|
where: { userId, isActive: true },
|
||||||
|
orderBy: { name: 'asc' },
|
||||||
|
}),
|
||||||
|
])
|
||||||
|
|
||||||
|
// Net worth trend: take last 24 data points
|
||||||
|
const netWorthData = netWorthRows.slice(-24).map((r) => ({
|
||||||
|
label: formatYearMonth(r.year, r.month),
|
||||||
|
totalCents: Number(r.total),
|
||||||
|
}))
|
||||||
|
|
||||||
|
// Cash flow: build month-keyed map then fill in credits/debits
|
||||||
|
const cfMap = new Map<string, { label: string; creditsCents: number; debitsCents: number }>()
|
||||||
|
for (const r of cashFlowRows) {
|
||||||
|
const key = `${r.year}-${r.month}`
|
||||||
|
if (!cfMap.has(key)) {
|
||||||
|
cfMap.set(key, { label: formatYearMonth(r.year, r.month), creditsCents: 0, debitsCents: 0 })
|
||||||
|
}
|
||||||
|
const entry = cfMap.get(key)!
|
||||||
|
if (r.type === 'CREDIT') entry.creditsCents = Number(r.total)
|
||||||
|
else entry.debitsCents = Number(r.total)
|
||||||
|
}
|
||||||
|
const cashFlowData = Array.from(cfMap.values())
|
||||||
|
|
||||||
|
// Monthly spending (all accounts)
|
||||||
|
const monthlySpendData = spendingRows.map((r) => ({
|
||||||
|
label: formatYearMonth(r.year, r.month),
|
||||||
|
totalCents: Number(r.total),
|
||||||
|
}))
|
||||||
|
|
||||||
|
// Category breakdown
|
||||||
|
const categoryData = categoryRows.map((r) => ({
|
||||||
|
category: r.category,
|
||||||
|
totalCents: Number(r.total),
|
||||||
|
}))
|
||||||
|
|
||||||
|
// Budget chart
|
||||||
|
const spendMap = new Map(budgetSpendRows.map((r) => [r.budgetId, Number(r.total)]))
|
||||||
|
const budgetData = budgets.map((b) => ({
|
||||||
|
name: b.name,
|
||||||
|
spendCents: spendMap.get(b.id) ?? 0,
|
||||||
|
limitCents: b.limitCents ?? 0,
|
||||||
|
color: b.color,
|
||||||
|
}))
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="p-6 space-y-6">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-2xl font-bold">Graphs</h1>
|
||||||
|
<p className="text-sm text-muted-foreground">{monthLabel()}</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid gap-6 lg:grid-cols-2">
|
||||||
|
<Card className="lg:col-span-2">
|
||||||
|
<CardHeader className="pb-2">
|
||||||
|
<CardTitle className="text-base">Net Worth Trend</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<NetWorthTrendChart data={netWorthData} />
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<Card>
|
||||||
|
<CardHeader className="pb-2">
|
||||||
|
<CardTitle className="text-base">Cash Flow · Last 6 Months (Bank)</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<CashFlowChart data={cashFlowData} />
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<Card>
|
||||||
|
<CardHeader className="pb-2">
|
||||||
|
<CardTitle className="text-base">Monthly Spending · Last 6 Months (All Accounts)</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<MonthlySpendingChart data={monthlySpendData} />
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<Card>
|
||||||
|
<CardHeader className="pb-2">
|
||||||
|
<CardTitle className="text-base">Spending by Category · {monthLabel()}</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<CategoryBreakdownChart data={categoryData} />
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<Card>
|
||||||
|
<CardHeader className="pb-2">
|
||||||
|
<CardTitle className="text-base">Budget Performance · {monthLabel()}</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<BudgetChart data={budgetData} />
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
12
src/app/(app)/layout.tsx
Normal file
12
src/app/(app)/layout.tsx
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
import { Sidebar } from '@/components/layout/Sidebar'
|
||||||
|
|
||||||
|
export default function AppLayout({ children }: { children: React.ReactNode }) {
|
||||||
|
return (
|
||||||
|
<div className="flex min-h-screen bg-background">
|
||||||
|
<Sidebar />
|
||||||
|
<main className="flex-1 overflow-auto">
|
||||||
|
{children}
|
||||||
|
</main>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
84
src/app/(app)/transactions/page.tsx
Normal file
84
src/app/(app)/transactions/page.tsx
Normal file
@@ -0,0 +1,84 @@
|
|||||||
|
import { auth } from '@/lib/auth'
|
||||||
|
import { prisma } from '@/lib/prisma'
|
||||||
|
import { Prisma } from '@/generated/prisma/client'
|
||||||
|
import { TransactionFilters } from '@/components/transactions/TransactionFilters'
|
||||||
|
import { TransactionTable } from '@/components/transactions/TransactionTable'
|
||||||
|
|
||||||
|
const PAGE_LIMIT = 50
|
||||||
|
|
||||||
|
type SearchParams = Promise<Record<string, string | string[] | undefined>>
|
||||||
|
|
||||||
|
export default async function TransactionsPage({ searchParams }: { searchParams: SearchParams }) {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) return null
|
||||||
|
|
||||||
|
const sp = await searchParams
|
||||||
|
const get = (key: string) => (Array.isArray(sp[key]) ? sp[key][0] : sp[key]) ?? ''
|
||||||
|
|
||||||
|
const page = Math.max(1, Number(get('page')) || 1)
|
||||||
|
const accountId = get('accountId')
|
||||||
|
const dateFrom = get('dateFrom')
|
||||||
|
const dateTo = get('dateTo')
|
||||||
|
const type = get('type') as 'DEBIT' | 'CREDIT' | ''
|
||||||
|
const search = get('search')
|
||||||
|
|
||||||
|
const where: Prisma.TransactionWhereInput = {
|
||||||
|
account: { userId: session.user.id },
|
||||||
|
...(accountId && { accountId }),
|
||||||
|
...(type && { type }),
|
||||||
|
...(search && { description: { contains: search, mode: 'insensitive' } }),
|
||||||
|
...((dateFrom || dateTo) && {
|
||||||
|
date: {
|
||||||
|
...(dateFrom && { gte: new Date(dateFrom) }),
|
||||||
|
...(dateTo && { lte: new Date(dateTo + 'T23:59:59.999Z') }),
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
|
||||||
|
const [transactions, total, accounts, budgets] = await Promise.all([
|
||||||
|
prisma.transaction.findMany({
|
||||||
|
where,
|
||||||
|
include: {
|
||||||
|
account: { select: { name: true, type: true } },
|
||||||
|
budget: { select: { id: true, name: true, color: true } },
|
||||||
|
},
|
||||||
|
orderBy: { date: 'desc' },
|
||||||
|
skip: (page - 1) * PAGE_LIMIT,
|
||||||
|
take: PAGE_LIMIT,
|
||||||
|
}),
|
||||||
|
prisma.transaction.count({ where }),
|
||||||
|
prisma.account.findMany({
|
||||||
|
where: { userId: session.user.id },
|
||||||
|
select: { id: true, name: true },
|
||||||
|
orderBy: { name: 'asc' },
|
||||||
|
}),
|
||||||
|
prisma.budget.findMany({
|
||||||
|
where: { userId: session.user.id, isActive: true },
|
||||||
|
select: { id: true, name: true, color: true },
|
||||||
|
orderBy: { name: 'asc' },
|
||||||
|
}),
|
||||||
|
])
|
||||||
|
|
||||||
|
// Serialize dates for client components
|
||||||
|
const rows = transactions.map((tx) => ({
|
||||||
|
...tx,
|
||||||
|
date: tx.date.toISOString(),
|
||||||
|
createdAt: undefined,
|
||||||
|
updatedAt: undefined,
|
||||||
|
}))
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="p-6">
|
||||||
|
<h1 className="text-2xl font-bold mb-4">Transactions</h1>
|
||||||
|
<TransactionFilters accounts={accounts} />
|
||||||
|
<TransactionTable
|
||||||
|
transactions={rows}
|
||||||
|
total={total}
|
||||||
|
page={page}
|
||||||
|
limit={PAGE_LIMIT}
|
||||||
|
showAccount
|
||||||
|
budgets={budgets}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
24
src/app/(app)/upload/page.tsx
Normal file
24
src/app/(app)/upload/page.tsx
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
import { auth } from '@/lib/auth'
|
||||||
|
import { prisma } from '@/lib/prisma'
|
||||||
|
import { UploadForm } from '@/components/upload/UploadForm'
|
||||||
|
|
||||||
|
export default async function UploadPage() {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) return null
|
||||||
|
|
||||||
|
const accounts = await prisma.account.findMany({
|
||||||
|
where: { userId: session.user.id, isActive: true },
|
||||||
|
orderBy: { name: 'asc' },
|
||||||
|
select: { id: true, name: true },
|
||||||
|
})
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="p-6 max-w-2xl">
|
||||||
|
<h1 className="text-2xl font-bold mb-1">Upload Transactions</h1>
|
||||||
|
<p className="text-sm text-muted-foreground mb-6">
|
||||||
|
Import a bank CSV. Duplicates are silently skipped.
|
||||||
|
</p>
|
||||||
|
<UploadForm accounts={accounts} />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
75
src/app/(auth)/login/page.tsx
Normal file
75
src/app/(auth)/login/page.tsx
Normal file
@@ -0,0 +1,75 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { useState } from 'react'
|
||||||
|
import { signIn } from 'next-auth/react'
|
||||||
|
import { useRouter } from 'next/navigation'
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||||
|
import { Input } from '@/components/ui/input'
|
||||||
|
import { Label } from '@/components/ui/label'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
|
||||||
|
export default function LoginPage() {
|
||||||
|
const router = useRouter()
|
||||||
|
const [error, setError] = useState('')
|
||||||
|
const [loading, setLoading] = useState(false)
|
||||||
|
|
||||||
|
async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
|
||||||
|
e.preventDefault()
|
||||||
|
setError('')
|
||||||
|
setLoading(true)
|
||||||
|
|
||||||
|
const form = new FormData(e.currentTarget)
|
||||||
|
const result = await signIn('credentials', {
|
||||||
|
email: form.get('email') as string,
|
||||||
|
password: form.get('password') as string,
|
||||||
|
redirect: false,
|
||||||
|
})
|
||||||
|
|
||||||
|
if (result?.error) {
|
||||||
|
setError('Invalid email or password')
|
||||||
|
setLoading(false)
|
||||||
|
} else {
|
||||||
|
router.push('/dashboard')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen flex items-center justify-center bg-background p-4">
|
||||||
|
<Card className="w-full max-w-sm">
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle className="text-2xl">Sign in</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<form onSubmit={handleSubmit} className="space-y-4">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="email">Email</Label>
|
||||||
|
<Input
|
||||||
|
id="email"
|
||||||
|
name="email"
|
||||||
|
type="email"
|
||||||
|
autoComplete="email"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="password">Password</Label>
|
||||||
|
<Input
|
||||||
|
id="password"
|
||||||
|
name="password"
|
||||||
|
type="password"
|
||||||
|
autoComplete="current-password"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{error && (
|
||||||
|
<p className="text-sm text-destructive">{error}</p>
|
||||||
|
)}
|
||||||
|
<Button type="submit" className="w-full" disabled={loading}>
|
||||||
|
{loading ? 'Signing in…' : 'Sign in'}
|
||||||
|
</Button>
|
||||||
|
</form>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
63
src/app/api/accounts/[id]/route.ts
Normal file
63
src/app/api/accounts/[id]/route.ts
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
import { NextResponse } from 'next/server'
|
||||||
|
import { auth } from '@/lib/auth'
|
||||||
|
import { prisma } from '@/lib/prisma'
|
||||||
|
import { updateAccountSchema } from '@/lib/validations/account'
|
||||||
|
|
||||||
|
type Params = { params: Promise<{ id: string }> }
|
||||||
|
|
||||||
|
export async function GET(_req: Request, { params }: Params) {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||||
|
}
|
||||||
|
|
||||||
|
const { id } = await params
|
||||||
|
const account = await prisma.account.findFirst({
|
||||||
|
where: { id, userId: session.user.id },
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!account) return NextResponse.json({ error: 'Not found' }, { status: 404 })
|
||||||
|
return NextResponse.json(account)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function PATCH(req: Request, { params }: Params) {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||||
|
}
|
||||||
|
|
||||||
|
const { id } = await params
|
||||||
|
const body = await req.json()
|
||||||
|
const parsed = updateAccountSchema.safeParse(body)
|
||||||
|
if (!parsed.success) {
|
||||||
|
return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 })
|
||||||
|
}
|
||||||
|
|
||||||
|
const existing = await prisma.account.findFirst({
|
||||||
|
where: { id, userId: session.user.id },
|
||||||
|
})
|
||||||
|
if (!existing) return NextResponse.json({ error: 'Not found' }, { status: 404 })
|
||||||
|
|
||||||
|
const account = await prisma.account.update({
|
||||||
|
where: { id },
|
||||||
|
data: parsed.data,
|
||||||
|
})
|
||||||
|
|
||||||
|
return NextResponse.json(account)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function DELETE(_req: Request, { params }: Params) {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||||
|
}
|
||||||
|
|
||||||
|
const { id } = await params
|
||||||
|
const existing = await prisma.account.findFirst({
|
||||||
|
where: { id, userId: session.user.id },
|
||||||
|
})
|
||||||
|
if (!existing) return NextResponse.json({ error: 'Not found' }, { status: 404 })
|
||||||
|
|
||||||
|
await prisma.account.delete({ where: { id } })
|
||||||
|
return new NextResponse(null, { status: 204 })
|
||||||
|
}
|
||||||
37
src/app/api/accounts/route.ts
Normal file
37
src/app/api/accounts/route.ts
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
import { NextResponse } from 'next/server'
|
||||||
|
import { auth } from '@/lib/auth'
|
||||||
|
import { prisma } from '@/lib/prisma'
|
||||||
|
import { createAccountSchema } from '@/lib/validations/account'
|
||||||
|
|
||||||
|
export async function GET() {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||||
|
}
|
||||||
|
|
||||||
|
const accounts = await prisma.account.findMany({
|
||||||
|
where: { userId: session.user.id },
|
||||||
|
orderBy: { createdAt: 'asc' },
|
||||||
|
})
|
||||||
|
|
||||||
|
return NextResponse.json(accounts)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function POST(req: Request) {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||||
|
}
|
||||||
|
|
||||||
|
const body = await req.json()
|
||||||
|
const parsed = createAccountSchema.safeParse(body)
|
||||||
|
if (!parsed.success) {
|
||||||
|
return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 })
|
||||||
|
}
|
||||||
|
|
||||||
|
const account = await prisma.account.create({
|
||||||
|
data: { ...parsed.data, userId: session.user.id },
|
||||||
|
})
|
||||||
|
|
||||||
|
return NextResponse.json(account, { status: 201 })
|
||||||
|
}
|
||||||
3
src/app/api/auth/[...nextauth]/route.ts
Normal file
3
src/app/api/auth/[...nextauth]/route.ts
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
import { handlers } from '@/lib/auth'
|
||||||
|
|
||||||
|
export const { GET, POST } = handlers
|
||||||
45
src/app/api/budgets/[id]/route.ts
Normal file
45
src/app/api/budgets/[id]/route.ts
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
import { NextResponse } from 'next/server'
|
||||||
|
import { auth } from '@/lib/auth'
|
||||||
|
import { prisma } from '@/lib/prisma'
|
||||||
|
import { updateBudgetSchema } from '@/lib/validations/budget'
|
||||||
|
|
||||||
|
type Params = { params: Promise<{ id: string }> }
|
||||||
|
|
||||||
|
export async function PATCH(req: Request, { params }: Params) {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||||
|
}
|
||||||
|
|
||||||
|
const { id } = await params
|
||||||
|
const body = await req.json()
|
||||||
|
const parsed = updateBudgetSchema.safeParse(body)
|
||||||
|
if (!parsed.success) {
|
||||||
|
return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 })
|
||||||
|
}
|
||||||
|
|
||||||
|
const existing = await prisma.budget.findFirst({
|
||||||
|
where: { id, userId: session.user.id },
|
||||||
|
})
|
||||||
|
if (!existing) return NextResponse.json({ error: 'Not found' }, { status: 404 })
|
||||||
|
|
||||||
|
const budget = await prisma.budget.update({ where: { id }, data: parsed.data })
|
||||||
|
return NextResponse.json(budget)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function DELETE(_req: Request, { params }: Params) {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||||
|
}
|
||||||
|
|
||||||
|
const { id } = await params
|
||||||
|
const existing = await prisma.budget.findFirst({
|
||||||
|
where: { id, userId: session.user.id },
|
||||||
|
})
|
||||||
|
if (!existing) return NextResponse.json({ error: 'Not found' }, { status: 404 })
|
||||||
|
|
||||||
|
// onDelete: SetNull in schema nulls out Transaction.budgetId automatically
|
||||||
|
await prisma.budget.delete({ where: { id } })
|
||||||
|
return new NextResponse(null, { status: 204 })
|
||||||
|
}
|
||||||
37
src/app/api/budgets/route.ts
Normal file
37
src/app/api/budgets/route.ts
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
import { NextResponse } from 'next/server'
|
||||||
|
import { auth } from '@/lib/auth'
|
||||||
|
import { prisma } from '@/lib/prisma'
|
||||||
|
import { createBudgetSchema } from '@/lib/validations/budget'
|
||||||
|
|
||||||
|
export async function GET() {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||||
|
}
|
||||||
|
|
||||||
|
const budgets = await prisma.budget.findMany({
|
||||||
|
where: { userId: session.user.id },
|
||||||
|
orderBy: { createdAt: 'asc' },
|
||||||
|
})
|
||||||
|
|
||||||
|
return NextResponse.json(budgets)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function POST(req: Request) {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||||
|
}
|
||||||
|
|
||||||
|
const body = await req.json()
|
||||||
|
const parsed = createBudgetSchema.safeParse(body)
|
||||||
|
if (!parsed.success) {
|
||||||
|
return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 })
|
||||||
|
}
|
||||||
|
|
||||||
|
const budget = await prisma.budget.create({
|
||||||
|
data: { ...parsed.data, userId: session.user.id },
|
||||||
|
})
|
||||||
|
|
||||||
|
return NextResponse.json(budget, { status: 201 })
|
||||||
|
}
|
||||||
78
src/app/api/dashboard/route.ts
Normal file
78
src/app/api/dashboard/route.ts
Normal file
@@ -0,0 +1,78 @@
|
|||||||
|
import { NextResponse } from 'next/server'
|
||||||
|
import { auth } from '@/lib/auth'
|
||||||
|
import { prisma } from '@/lib/prisma'
|
||||||
|
import { monthBounds, monthLabel } from '@/lib/utils/dates'
|
||||||
|
|
||||||
|
export async function GET() {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||||
|
}
|
||||||
|
|
||||||
|
const userId = session.user.id
|
||||||
|
const { start, end } = monthBounds()
|
||||||
|
|
||||||
|
const [accounts, cashFlowRows, budgets, spendRows, recentTx] = await Promise.all([
|
||||||
|
prisma.account.findMany({
|
||||||
|
where: { userId, isActive: true },
|
||||||
|
select: { id: true, name: true, type: true, currentBalanceCents: true },
|
||||||
|
orderBy: { name: 'asc' },
|
||||||
|
}),
|
||||||
|
prisma.$queryRaw<{ type: string; total: bigint }[]>`
|
||||||
|
SELECT t.type, COALESCE(SUM(t."amountCents"), 0)::bigint AS total
|
||||||
|
FROM "Transaction" t
|
||||||
|
JOIN "Account" a ON t."accountId" = a.id
|
||||||
|
WHERE a."userId" = ${userId}
|
||||||
|
AND a.type = 'BANK'
|
||||||
|
AND t.date >= ${start}
|
||||||
|
AND t.date <= ${end}
|
||||||
|
GROUP BY t.type
|
||||||
|
`,
|
||||||
|
prisma.budget.findMany({
|
||||||
|
where: { userId, isActive: true },
|
||||||
|
orderBy: { name: 'asc' },
|
||||||
|
}),
|
||||||
|
prisma.$queryRaw<{ budgetId: string; total: bigint }[]>`
|
||||||
|
SELECT t."budgetId", COALESCE(SUM(t."amountCents"), 0)::bigint AS total
|
||||||
|
FROM "Transaction" t
|
||||||
|
JOIN "Account" a ON t."accountId" = a.id
|
||||||
|
WHERE a."userId" = ${userId}
|
||||||
|
AND t."budgetId" IS NOT NULL
|
||||||
|
AND t.type = 'DEBIT'
|
||||||
|
AND t.date >= ${start}
|
||||||
|
AND t.date <= ${end}
|
||||||
|
GROUP BY t."budgetId"
|
||||||
|
`,
|
||||||
|
prisma.transaction.findMany({
|
||||||
|
where: { account: { userId } },
|
||||||
|
include: { account: { select: { name: true } } },
|
||||||
|
orderBy: { date: 'desc' },
|
||||||
|
take: 5,
|
||||||
|
}),
|
||||||
|
])
|
||||||
|
|
||||||
|
const bankAccounts = accounts.filter((a) => a.type === 'BANK')
|
||||||
|
const netWorthCents = bankAccounts.reduce((s, a) => s + a.currentBalanceCents, 0)
|
||||||
|
|
||||||
|
const cfMap = Object.fromEntries(cashFlowRows.map((r) => [r.type, Number(r.total)]))
|
||||||
|
const creditsCents = cfMap['CREDIT'] ?? 0
|
||||||
|
const debitsCents = cfMap['DEBIT'] ?? 0
|
||||||
|
|
||||||
|
const spendMap = new Map(spendRows.map((r) => [r.budgetId, Number(r.total)]))
|
||||||
|
|
||||||
|
return NextResponse.json({
|
||||||
|
monthLabel: monthLabel(),
|
||||||
|
netWorthCents,
|
||||||
|
bankAccounts,
|
||||||
|
cashFlow: { creditsCents, debitsCents, netCents: creditsCents - debitsCents },
|
||||||
|
budgets: budgets.map((b) => ({ ...b, spendCents: spendMap.get(b.id) ?? 0 })),
|
||||||
|
recentTransactions: recentTx.map((t) => ({
|
||||||
|
id: t.id,
|
||||||
|
date: t.date.toISOString(),
|
||||||
|
description: t.description,
|
||||||
|
amountCents: t.amountCents,
|
||||||
|
type: t.type,
|
||||||
|
accountName: t.account.name,
|
||||||
|
})),
|
||||||
|
})
|
||||||
|
}
|
||||||
11
src/app/api/health/route.ts
Normal file
11
src/app/api/health/route.ts
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
import { NextResponse } from 'next/server'
|
||||||
|
import { prisma } from '@/lib/prisma'
|
||||||
|
|
||||||
|
export async function GET() {
|
||||||
|
try {
|
||||||
|
await prisma.$queryRaw`SELECT 1`
|
||||||
|
return NextResponse.json({ status: 'ok' })
|
||||||
|
} catch {
|
||||||
|
return NextResponse.json({ status: 'error', detail: 'database unreachable' }, { status: 503 })
|
||||||
|
}
|
||||||
|
}
|
||||||
41
src/app/api/transactions/[id]/route.ts
Normal file
41
src/app/api/transactions/[id]/route.ts
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
import { NextResponse } from 'next/server'
|
||||||
|
import { auth } from '@/lib/auth'
|
||||||
|
import { prisma } from '@/lib/prisma'
|
||||||
|
import { updateTransactionSchema } from '@/lib/validations/transaction'
|
||||||
|
|
||||||
|
type Params = { params: Promise<{ id: string }> }
|
||||||
|
|
||||||
|
export async function PATCH(req: Request, { params }: Params) {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||||
|
}
|
||||||
|
|
||||||
|
const { id } = await params
|
||||||
|
const body = await req.json()
|
||||||
|
const parsed = updateTransactionSchema.safeParse(body)
|
||||||
|
if (!parsed.success) {
|
||||||
|
return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 })
|
||||||
|
}
|
||||||
|
|
||||||
|
// Scope check via the account's userId
|
||||||
|
const existing = await prisma.transaction.findFirst({
|
||||||
|
where: { id, account: { userId: session.user.id } },
|
||||||
|
})
|
||||||
|
if (!existing) return NextResponse.json({ error: 'Not found' }, { status: 404 })
|
||||||
|
|
||||||
|
// Validate budgetId belongs to this user if provided
|
||||||
|
if (parsed.data.budgetId) {
|
||||||
|
const budget = await prisma.budget.findFirst({
|
||||||
|
where: { id: parsed.data.budgetId, userId: session.user.id },
|
||||||
|
})
|
||||||
|
if (!budget) return NextResponse.json({ error: 'Budget not found' }, { status: 404 })
|
||||||
|
}
|
||||||
|
|
||||||
|
const transaction = await prisma.transaction.update({
|
||||||
|
where: { id },
|
||||||
|
data: parsed.data,
|
||||||
|
})
|
||||||
|
|
||||||
|
return NextResponse.json(transaction)
|
||||||
|
}
|
||||||
50
src/app/api/transactions/route.ts
Normal file
50
src/app/api/transactions/route.ts
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
import { NextResponse } from 'next/server'
|
||||||
|
import { auth } from '@/lib/auth'
|
||||||
|
import { prisma } from '@/lib/prisma'
|
||||||
|
import { transactionQuerySchema } from '@/lib/validations/transaction'
|
||||||
|
import { Prisma } from '@/generated/prisma/client'
|
||||||
|
|
||||||
|
export async function GET(req: Request) {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||||
|
}
|
||||||
|
|
||||||
|
const { searchParams } = new URL(req.url)
|
||||||
|
const parsed = transactionQuerySchema.safeParse(Object.fromEntries(searchParams))
|
||||||
|
if (!parsed.success) {
|
||||||
|
return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 })
|
||||||
|
}
|
||||||
|
|
||||||
|
const { accountId, dateFrom, dateTo, type, search, budgetId, page, limit } = parsed.data
|
||||||
|
|
||||||
|
const where: Prisma.TransactionWhereInput = {
|
||||||
|
account: { userId: session.user.id },
|
||||||
|
...(accountId && { accountId }),
|
||||||
|
...(type && { type }),
|
||||||
|
...(budgetId !== undefined && { budgetId: budgetId || null }),
|
||||||
|
...(search && { description: { contains: search, mode: 'insensitive' } }),
|
||||||
|
...((dateFrom || dateTo) && {
|
||||||
|
date: {
|
||||||
|
...(dateFrom && { gte: new Date(dateFrom) }),
|
||||||
|
...(dateTo && { lte: new Date(dateTo + 'T23:59:59.999Z') }),
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
|
||||||
|
const [transactions, total] = await prisma.$transaction([
|
||||||
|
prisma.transaction.findMany({
|
||||||
|
where,
|
||||||
|
include: {
|
||||||
|
account: { select: { name: true, type: true } },
|
||||||
|
budget: { select: { id: true, name: true, color: true } },
|
||||||
|
},
|
||||||
|
orderBy: { date: 'desc' },
|
||||||
|
skip: (page - 1) * limit,
|
||||||
|
take: limit,
|
||||||
|
}),
|
||||||
|
prisma.transaction.count({ where }),
|
||||||
|
])
|
||||||
|
|
||||||
|
return NextResponse.json({ transactions, total, page, limit, totalPages: Math.ceil(total / limit) })
|
||||||
|
}
|
||||||
172
src/app/api/upload/route.ts
Normal file
172
src/app/api/upload/route.ts
Normal file
@@ -0,0 +1,172 @@
|
|||||||
|
import { NextResponse } from 'next/server'
|
||||||
|
import Papa from 'papaparse'
|
||||||
|
import { auth } from '@/lib/auth'
|
||||||
|
import { prisma } from '@/lib/prisma'
|
||||||
|
import { detectProfile } from '@/lib/csv/bank-profiles'
|
||||||
|
import { normalizeRows } from '@/lib/csv/normalizer'
|
||||||
|
import { columnMappingSchema } from '@/lib/validations/upload'
|
||||||
|
import type { NormalizerConfig } from '@/lib/csv/bank-profiles'
|
||||||
|
|
||||||
|
const MAX_FILE_SIZE = 10 * 1024 * 1024 // 10 MB
|
||||||
|
|
||||||
|
export async function POST(req: Request) {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||||
|
}
|
||||||
|
|
||||||
|
const formData = await req.formData()
|
||||||
|
const file = formData.get('file') as File | null
|
||||||
|
const accountId = formData.get('accountId') as string | null
|
||||||
|
const columnMappingRaw = formData.get('columnMapping') as string | null
|
||||||
|
|
||||||
|
if (!file || !accountId) {
|
||||||
|
return NextResponse.json({ error: 'file and accountId are required' }, { status: 400 })
|
||||||
|
}
|
||||||
|
if (file.size > MAX_FILE_SIZE) {
|
||||||
|
return NextResponse.json({ error: 'File too large (max 10 MB)' }, { status: 400 })
|
||||||
|
}
|
||||||
|
if (!file.name.toLowerCase().endsWith('.csv')) {
|
||||||
|
return NextResponse.json({ error: 'File must be a .csv file' }, { status: 400 })
|
||||||
|
}
|
||||||
|
const validMimes = ['text/csv', 'text/plain', 'application/vnd.ms-excel', 'application/csv', '']
|
||||||
|
if (file.type && !validMimes.includes(file.type)) {
|
||||||
|
return NextResponse.json({ error: 'Invalid file type' }, { status: 400 })
|
||||||
|
}
|
||||||
|
|
||||||
|
const account = await prisma.account.findFirst({
|
||||||
|
where: { id: accountId, userId: session.user.id },
|
||||||
|
})
|
||||||
|
if (!account) {
|
||||||
|
return NextResponse.json({ error: 'Account not found' }, { status: 404 })
|
||||||
|
}
|
||||||
|
|
||||||
|
const content = await file.text()
|
||||||
|
|
||||||
|
// Parse all rows once — used for both detection and normalization
|
||||||
|
const parsed = Papa.parse<Record<string, string>>(content, {
|
||||||
|
header: true,
|
||||||
|
skipEmptyLines: true,
|
||||||
|
transformHeader: (h) => h.trim(),
|
||||||
|
})
|
||||||
|
const headers = (parsed.meta.fields ?? []).map((h) => h.trim())
|
||||||
|
const allRows = parsed.data
|
||||||
|
|
||||||
|
// Detect profile or use provided manual mapping
|
||||||
|
const detected = detectProfile(headers)
|
||||||
|
|
||||||
|
if (!detected && !columnMappingRaw) {
|
||||||
|
return NextResponse.json({
|
||||||
|
requiresMapping: true,
|
||||||
|
headers,
|
||||||
|
sampleRows: allRows.slice(0, 5),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
let config: NormalizerConfig
|
||||||
|
if (detected && !columnMappingRaw) {
|
||||||
|
config = detected
|
||||||
|
} else {
|
||||||
|
const result = columnMappingSchema.safeParse(JSON.parse(columnMappingRaw!))
|
||||||
|
if (!result.success) {
|
||||||
|
return NextResponse.json({ error: result.error.flatten() }, { status: 400 })
|
||||||
|
}
|
||||||
|
config = result.data
|
||||||
|
}
|
||||||
|
|
||||||
|
const normalized = normalizeRows(allRows, accountId, config)
|
||||||
|
|
||||||
|
const upload = await prisma.csvUpload.create({
|
||||||
|
data: {
|
||||||
|
accountId,
|
||||||
|
fileName: file.name,
|
||||||
|
rowCount: allRows.length,
|
||||||
|
importedCount: 0,
|
||||||
|
skippedCount: 0,
|
||||||
|
status: 'PENDING',
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { count: importedCount } = await prisma.transaction.createMany({
|
||||||
|
data: normalized.map((r) => ({
|
||||||
|
accountId,
|
||||||
|
uploadId: upload.id,
|
||||||
|
date: r.date,
|
||||||
|
description: r.description,
|
||||||
|
amountCents: r.amountCents,
|
||||||
|
type: r.type,
|
||||||
|
dedupeHash: r.dedupeHash,
|
||||||
|
})),
|
||||||
|
skipDuplicates: true,
|
||||||
|
})
|
||||||
|
const skippedCount = normalized.length - importedCount
|
||||||
|
|
||||||
|
// Recompute current balance
|
||||||
|
const [balRow] = await prisma.$queryRaw<[{ balance: bigint }]>`
|
||||||
|
SELECT COALESCE(SUM(
|
||||||
|
CASE WHEN type = 'CREDIT' THEN "amountCents" ELSE -"amountCents" END
|
||||||
|
), 0)::bigint AS balance
|
||||||
|
FROM "Transaction"
|
||||||
|
WHERE "accountId" = ${accountId}
|
||||||
|
`
|
||||||
|
await prisma.account.update({
|
||||||
|
where: { id: accountId },
|
||||||
|
data: { currentBalanceCents: Number(balRow.balance) },
|
||||||
|
})
|
||||||
|
|
||||||
|
// Upsert balance snapshots for each affected month
|
||||||
|
const months = [
|
||||||
|
...new Map(
|
||||||
|
normalized.map((r) => {
|
||||||
|
const y = r.date.getFullYear()
|
||||||
|
const m = r.date.getMonth() + 1
|
||||||
|
return [`${y}-${m}`, { year: y, month: m }]
|
||||||
|
}),
|
||||||
|
).values(),
|
||||||
|
]
|
||||||
|
for (const { year, month } of months) {
|
||||||
|
const endOfMonth = new Date(year, month, 0, 23, 59, 59, 999)
|
||||||
|
const [snap] = await prisma.$queryRaw<[{ balance: bigint }]>`
|
||||||
|
SELECT COALESCE(SUM(
|
||||||
|
CASE WHEN type = 'CREDIT' THEN "amountCents" ELSE -"amountCents" END
|
||||||
|
), 0)::bigint AS balance
|
||||||
|
FROM "Transaction"
|
||||||
|
WHERE "accountId" = ${accountId}
|
||||||
|
AND date <= ${endOfMonth}
|
||||||
|
`
|
||||||
|
await prisma.balanceSnapshot.upsert({
|
||||||
|
where: { accountId_year_month: { accountId, year, month } },
|
||||||
|
update: { balanceCents: Number(snap.balance), computedAt: new Date() },
|
||||||
|
create: { accountId, year, month, balanceCents: Number(snap.balance) },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const status =
|
||||||
|
importedCount === 0 ? 'FAILED'
|
||||||
|
: skippedCount > 0 ? 'PARTIAL'
|
||||||
|
: 'SUCCESS'
|
||||||
|
|
||||||
|
await prisma.csvUpload.update({
|
||||||
|
where: { id: upload.id },
|
||||||
|
data: { importedCount, skippedCount, status },
|
||||||
|
})
|
||||||
|
|
||||||
|
return NextResponse.json({
|
||||||
|
success: true,
|
||||||
|
detected: detected?.name,
|
||||||
|
importedCount,
|
||||||
|
skippedCount,
|
||||||
|
fileName: file.name,
|
||||||
|
})
|
||||||
|
} catch (err) {
|
||||||
|
await prisma.csvUpload.update({
|
||||||
|
where: { id: upload.id },
|
||||||
|
data: {
|
||||||
|
status: 'FAILED',
|
||||||
|
errorMessage: err instanceof Error ? err.message : 'Unknown error',
|
||||||
|
},
|
||||||
|
})
|
||||||
|
return NextResponse.json({ error: 'Import failed' }, { status: 500 })
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -13,8 +13,8 @@ const geistMono = Geist_Mono({
|
|||||||
});
|
});
|
||||||
|
|
||||||
export const metadata: Metadata = {
|
export const metadata: Metadata = {
|
||||||
title: "Create Next App",
|
title: "Finance",
|
||||||
description: "Generated by create next app",
|
description: "Personal finance tracker",
|
||||||
};
|
};
|
||||||
|
|
||||||
export default function RootLayout({
|
export default function RootLayout({
|
||||||
|
|||||||
@@ -1,65 +1,5 @@
|
|||||||
import Image from "next/image";
|
import { redirect } from 'next/navigation'
|
||||||
|
|
||||||
export default function Home() {
|
export default function RootPage() {
|
||||||
return (
|
redirect('/dashboard')
|
||||||
<div className="flex flex-col flex-1 items-center justify-center bg-zinc-50 font-sans dark:bg-black">
|
|
||||||
<main className="flex flex-1 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>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|||||||
10
src/components/accounts/AccountBadge.tsx
Normal file
10
src/components/accounts/AccountBadge.tsx
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
import { Badge } from '@/components/ui/badge'
|
||||||
|
import { AccountType } from '@/generated/prisma/client'
|
||||||
|
|
||||||
|
export function AccountBadge({ type }: { type: AccountType }) {
|
||||||
|
return type === 'BANK' ? (
|
||||||
|
<Badge variant="secondary">Bank</Badge>
|
||||||
|
) : (
|
||||||
|
<Badge variant="outline">Credit Card</Badge>
|
||||||
|
)
|
||||||
|
}
|
||||||
97
src/components/accounts/AccountCard.tsx
Normal file
97
src/components/accounts/AccountCard.tsx
Normal file
@@ -0,0 +1,97 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { useState } from 'react'
|
||||||
|
import { useRouter } from 'next/navigation'
|
||||||
|
import Link from 'next/link'
|
||||||
|
import { Account } from '@/generated/prisma/client'
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||||
|
import {
|
||||||
|
DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator,
|
||||||
|
DropdownMenuTrigger,
|
||||||
|
} from '@/components/ui/dropdown-menu'
|
||||||
|
import { MoreHorizontal, Pencil, Trash2, EyeOff, Eye } from 'lucide-react'
|
||||||
|
import { AccountBadge } from './AccountBadge'
|
||||||
|
import { CreateAccountDialog } from './CreateAccountDialog'
|
||||||
|
import { formatCents } from '@/lib/utils/currency'
|
||||||
|
|
||||||
|
export function AccountCard({ account }: { account: Account }) {
|
||||||
|
const router = useRouter()
|
||||||
|
const [editOpen, setEditOpen] = useState(false)
|
||||||
|
|
||||||
|
async function handleToggleActive() {
|
||||||
|
await fetch(`/api/accounts/${account.id}`, {
|
||||||
|
method: 'PATCH',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ isActive: !account.isActive }),
|
||||||
|
})
|
||||||
|
router.refresh()
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleDelete() {
|
||||||
|
if (!confirm(`Delete "${account.name}"? This cannot be undone.`)) return
|
||||||
|
await fetch(`/api/accounts/${account.id}`, { method: 'DELETE' })
|
||||||
|
router.refresh()
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Card className={account.isActive ? '' : 'opacity-60'}>
|
||||||
|
<CardHeader className="flex flex-row items-start justify-between space-y-0 pb-2">
|
||||||
|
<div className="space-y-1 min-w-0">
|
||||||
|
<CardTitle className="text-base truncate">
|
||||||
|
<Link href={`/accounts/${account.id}`} className="hover:underline">
|
||||||
|
{account.name}
|
||||||
|
</Link>
|
||||||
|
</CardTitle>
|
||||||
|
{account.institution && (
|
||||||
|
<p className="text-xs text-muted-foreground truncate">{account.institution}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-1 shrink-0 ml-2">
|
||||||
|
<AccountBadge type={account.type} />
|
||||||
|
<DropdownMenu>
|
||||||
|
<DropdownMenuTrigger className="inline-flex h-7 w-7 items-center justify-center rounded-md hover:bg-accent transition-colors">
|
||||||
|
<MoreHorizontal className="h-4 w-4" />
|
||||||
|
<span className="sr-only">Account actions</span>
|
||||||
|
</DropdownMenuTrigger>
|
||||||
|
<DropdownMenuContent align="end">
|
||||||
|
<DropdownMenuItem onClick={() => setEditOpen(true)}>
|
||||||
|
<Pencil className="h-4 w-4 mr-2" />
|
||||||
|
Edit
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem onClick={handleToggleActive}>
|
||||||
|
{account.isActive
|
||||||
|
? <><EyeOff className="h-4 w-4 mr-2" />Deactivate</>
|
||||||
|
: <><Eye className="h-4 w-4 mr-2" />Activate</>
|
||||||
|
}
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuSeparator />
|
||||||
|
<DropdownMenuItem
|
||||||
|
onClick={handleDelete}
|
||||||
|
className="text-destructive focus:text-destructive"
|
||||||
|
>
|
||||||
|
<Trash2 className="h-4 w-4 mr-2" />
|
||||||
|
Delete
|
||||||
|
</DropdownMenuItem>
|
||||||
|
</DropdownMenuContent>
|
||||||
|
</DropdownMenu>
|
||||||
|
</div>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<p className="text-2xl font-bold tabular-nums">
|
||||||
|
{formatCents(account.currentBalanceCents)}
|
||||||
|
</p>
|
||||||
|
{!account.isActive && (
|
||||||
|
<p className="text-xs text-muted-foreground mt-1">Inactive</p>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<CreateAccountDialog
|
||||||
|
open={editOpen}
|
||||||
|
onOpenChange={setEditOpen}
|
||||||
|
account={account}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
47
src/components/accounts/AccountList.tsx
Normal file
47
src/components/accounts/AccountList.tsx
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { useState } from 'react'
|
||||||
|
import { Account } from '@/generated/prisma/client'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Plus } from 'lucide-react'
|
||||||
|
import { AccountCard } from './AccountCard'
|
||||||
|
import { CreateAccountDialog } from './CreateAccountDialog'
|
||||||
|
|
||||||
|
export function AccountList({ accounts }: { accounts: Account[] }) {
|
||||||
|
const [dialogOpen, setDialogOpen] = useState(false)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-2xl font-bold">Accounts</h1>
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
{accounts.length} account{accounts.length !== 1 ? 's' : ''}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Button onClick={() => setDialogOpen(true)}>
|
||||||
|
<Plus className="h-4 w-4 mr-2" />
|
||||||
|
Add account
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{accounts.length === 0 ? (
|
||||||
|
<div className="rounded-lg border border-dashed p-12 text-center">
|
||||||
|
<p className="text-muted-foreground">No accounts yet.</p>
|
||||||
|
<Button variant="outline" className="mt-4" onClick={() => setDialogOpen(true)}>
|
||||||
|
<Plus className="h-4 w-4 mr-2" />
|
||||||
|
Add your first account
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
|
||||||
|
{accounts.map((account) => (
|
||||||
|
<AccountCard key={account.id} account={account} />
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<CreateAccountDialog open={dialogOpen} onOpenChange={setDialogOpen} />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
112
src/components/accounts/CreateAccountDialog.tsx
Normal file
112
src/components/accounts/CreateAccountDialog.tsx
Normal file
@@ -0,0 +1,112 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { useState } from 'react'
|
||||||
|
import { useRouter } from 'next/navigation'
|
||||||
|
import { Account } from '@/generated/prisma/client'
|
||||||
|
import {
|
||||||
|
Dialog, DialogContent, DialogHeader, DialogTitle,
|
||||||
|
} from '@/components/ui/dialog'
|
||||||
|
import { Input } from '@/components/ui/input'
|
||||||
|
import { Label } from '@/components/ui/label'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import {
|
||||||
|
Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
|
||||||
|
} from '@/components/ui/select'
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
open: boolean
|
||||||
|
onOpenChange: (open: boolean) => void
|
||||||
|
account?: Account
|
||||||
|
}
|
||||||
|
|
||||||
|
export function CreateAccountDialog({ open, onOpenChange, account }: Props) {
|
||||||
|
const router = useRouter()
|
||||||
|
const isEdit = !!account
|
||||||
|
const [loading, setLoading] = useState(false)
|
||||||
|
const [error, setError] = useState('')
|
||||||
|
|
||||||
|
async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
|
||||||
|
e.preventDefault()
|
||||||
|
setError('')
|
||||||
|
setLoading(true)
|
||||||
|
|
||||||
|
const form = new FormData(e.currentTarget)
|
||||||
|
const body = {
|
||||||
|
name: form.get('name') as string,
|
||||||
|
institution: (form.get('institution') as string) || undefined,
|
||||||
|
type: form.get('type') as string,
|
||||||
|
currency: 'USD',
|
||||||
|
}
|
||||||
|
|
||||||
|
const res = await fetch(
|
||||||
|
isEdit ? `/api/accounts/${account.id}` : '/api/accounts',
|
||||||
|
{
|
||||||
|
method: isEdit ? 'PATCH' : 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
if (!res.ok) {
|
||||||
|
setError('Something went wrong. Please try again.')
|
||||||
|
setLoading(false)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
router.refresh()
|
||||||
|
onOpenChange(false)
|
||||||
|
setLoading(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||||
|
<DialogContent className="sm:max-w-md">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>{isEdit ? 'Edit account' : 'Add account'}</DialogTitle>
|
||||||
|
</DialogHeader>
|
||||||
|
<form onSubmit={handleSubmit} className="space-y-4 pt-2">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="name">Name</Label>
|
||||||
|
<Input
|
||||||
|
id="name"
|
||||||
|
name="name"
|
||||||
|
defaultValue={account?.name}
|
||||||
|
placeholder="e.g. Checking Account"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="institution">Institution <span className="text-muted-foreground">(optional)</span></Label>
|
||||||
|
<Input
|
||||||
|
id="institution"
|
||||||
|
name="institution"
|
||||||
|
defaultValue={account?.institution ?? ''}
|
||||||
|
placeholder="e.g. Chase"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="type">Type</Label>
|
||||||
|
<Select name="type" defaultValue={account?.type ?? 'BANK'} required>
|
||||||
|
<SelectTrigger id="type">
|
||||||
|
<SelectValue placeholder="Select type" />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="BANK">Bank</SelectItem>
|
||||||
|
<SelectItem value="CREDIT_CARD">Credit Card</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
{error && <p className="text-sm text-destructive">{error}</p>}
|
||||||
|
<div className="flex justify-end gap-2 pt-2">
|
||||||
|
<Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
<Button type="submit" disabled={loading}>
|
||||||
|
{loading ? 'Saving…' : isEdit ? 'Save changes' : 'Add account'}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
)
|
||||||
|
}
|
||||||
107
src/components/budgets/BudgetCard.tsx
Normal file
107
src/components/budgets/BudgetCard.tsx
Normal file
@@ -0,0 +1,107 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { useState } from 'react'
|
||||||
|
import { useRouter } from 'next/navigation'
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||||
|
import {
|
||||||
|
DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator,
|
||||||
|
DropdownMenuTrigger,
|
||||||
|
} from '@/components/ui/dropdown-menu'
|
||||||
|
import { MoreHorizontal, Pencil, Trash2, EyeOff, Eye } from 'lucide-react'
|
||||||
|
import { BudgetProgress } from './BudgetProgress'
|
||||||
|
import { CreateBudgetDialog } from './CreateBudgetDialog'
|
||||||
|
import { formatCents } from '@/lib/utils/currency'
|
||||||
|
|
||||||
|
export interface BudgetWithSpend {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
limitCents: number | null
|
||||||
|
color: string | null
|
||||||
|
isActive: boolean
|
||||||
|
spendCents: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export function BudgetCard({ budget }: { budget: BudgetWithSpend }) {
|
||||||
|
const router = useRouter()
|
||||||
|
const [editOpen, setEditOpen] = useState(false)
|
||||||
|
|
||||||
|
async function handleToggle() {
|
||||||
|
await fetch(`/api/budgets/${budget.id}`, {
|
||||||
|
method: 'PATCH',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ isActive: !budget.isActive }),
|
||||||
|
})
|
||||||
|
router.refresh()
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleDelete() {
|
||||||
|
if (!confirm(`Delete "${budget.name}"? All linked transactions will be unassigned.`)) return
|
||||||
|
await fetch(`/api/budgets/${budget.id}`, { method: 'DELETE' })
|
||||||
|
router.refresh()
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Card className={budget.isActive ? '' : 'opacity-60'}>
|
||||||
|
<CardHeader className="flex flex-row items-start justify-between space-y-0 pb-2">
|
||||||
|
<div className="flex items-center gap-2 min-w-0">
|
||||||
|
{budget.color && (
|
||||||
|
<span
|
||||||
|
className="h-3 w-3 rounded-full shrink-0"
|
||||||
|
style={{ backgroundColor: budget.color }}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
<CardTitle className="text-base truncate">{budget.name}</CardTitle>
|
||||||
|
</div>
|
||||||
|
<DropdownMenu>
|
||||||
|
<DropdownMenuTrigger className="inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-md hover:bg-accent transition-colors ml-1">
|
||||||
|
<MoreHorizontal className="h-4 w-4" />
|
||||||
|
<span className="sr-only">Budget actions</span>
|
||||||
|
</DropdownMenuTrigger>
|
||||||
|
<DropdownMenuContent align="end">
|
||||||
|
<DropdownMenuItem onClick={() => setEditOpen(true)}>
|
||||||
|
<Pencil className="h-4 w-4 mr-2" />Edit
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem onClick={handleToggle}>
|
||||||
|
{budget.isActive
|
||||||
|
? <><EyeOff className="h-4 w-4 mr-2" />Deactivate</>
|
||||||
|
: <><Eye className="h-4 w-4 mr-2" />Activate</>}
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuSeparator />
|
||||||
|
<DropdownMenuItem onClick={handleDelete} className="text-destructive focus:text-destructive">
|
||||||
|
<Trash2 className="h-4 w-4 mr-2" />Delete
|
||||||
|
</DropdownMenuItem>
|
||||||
|
</DropdownMenuContent>
|
||||||
|
</DropdownMenu>
|
||||||
|
</CardHeader>
|
||||||
|
|
||||||
|
<CardContent className="space-y-3">
|
||||||
|
<div className="flex items-baseline justify-between">
|
||||||
|
<span className="text-2xl font-bold tabular-nums">
|
||||||
|
{formatCents(budget.spendCents)}
|
||||||
|
</span>
|
||||||
|
{budget.limitCents ? (
|
||||||
|
<span className="text-sm text-muted-foreground">
|
||||||
|
of {formatCents(budget.limitCents)}
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
<span className="text-xs text-muted-foreground">no limit</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{budget.limitCents ? (
|
||||||
|
<BudgetProgress spendCents={budget.spendCents} limitCents={budget.limitCents} />
|
||||||
|
) : (
|
||||||
|
<p className="text-xs text-muted-foreground">This month</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{!budget.isActive && (
|
||||||
|
<p className="text-xs text-muted-foreground">Inactive</p>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<CreateBudgetDialog open={editOpen} onOpenChange={setEditOpen} budget={budget} />
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
59
src/components/budgets/BudgetList.tsx
Normal file
59
src/components/budgets/BudgetList.tsx
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { useState } from 'react'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Plus } from 'lucide-react'
|
||||||
|
import { BudgetCard, type BudgetWithSpend } from './BudgetCard'
|
||||||
|
import { CreateBudgetDialog } from './CreateBudgetDialog'
|
||||||
|
|
||||||
|
export function BudgetList({ budgets }: { budgets: BudgetWithSpend[] }) {
|
||||||
|
const [dialogOpen, setDialogOpen] = useState(false)
|
||||||
|
const active = budgets.filter((b) => b.isActive)
|
||||||
|
const inactive = budgets.filter((b) => !b.isActive)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-2xl font-bold">Budgets</h1>
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
{active.length} active budget{active.length !== 1 ? 's' : ''}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Button onClick={() => setDialogOpen(true)}>
|
||||||
|
<Plus className="h-4 w-4 mr-2" />
|
||||||
|
New budget
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{budgets.length === 0 ? (
|
||||||
|
<div className="rounded-lg border border-dashed p-12 text-center">
|
||||||
|
<p className="text-muted-foreground">No budgets yet.</p>
|
||||||
|
<Button variant="outline" className="mt-4" onClick={() => setDialogOpen(true)}>
|
||||||
|
<Plus className="h-4 w-4 mr-2" />
|
||||||
|
Create your first budget
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
|
||||||
|
{active.map((b) => <BudgetCard key={b.id} budget={b} />)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{inactive.length > 0 && (
|
||||||
|
<div>
|
||||||
|
<p className="text-xs font-medium text-muted-foreground uppercase tracking-wide mb-3">
|
||||||
|
Inactive
|
||||||
|
</p>
|
||||||
|
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
|
||||||
|
{inactive.map((b) => <BudgetCard key={b.id} budget={b} />)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<CreateBudgetDialog open={dialogOpen} onOpenChange={setDialogOpen} />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
28
src/components/budgets/BudgetProgress.tsx
Normal file
28
src/components/budgets/BudgetProgress.tsx
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
spendCents: number
|
||||||
|
limitCents: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export function BudgetProgress({ spendCents, limitCents }: Props) {
|
||||||
|
const pct = limitCents > 0 ? (spendCents / limitCents) * 100 : 0
|
||||||
|
const barPct = Math.min(pct, 100)
|
||||||
|
|
||||||
|
const barColor =
|
||||||
|
pct >= 100 ? 'bg-red-500'
|
||||||
|
: pct >= 75 ? 'bg-yellow-500'
|
||||||
|
: 'bg-green-500'
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-1">
|
||||||
|
<div className="h-2 w-full rounded-full bg-muted overflow-hidden">
|
||||||
|
<div
|
||||||
|
className={cn('h-full rounded-full transition-all duration-300', barColor)}
|
||||||
|
style={{ width: `${barPct}%` }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-muted-foreground text-right">{Math.round(pct)}%</p>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
142
src/components/budgets/CreateBudgetDialog.tsx
Normal file
142
src/components/budgets/CreateBudgetDialog.tsx
Normal file
@@ -0,0 +1,142 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { useState } from 'react'
|
||||||
|
import { useRouter } from 'next/navigation'
|
||||||
|
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||||
|
import { Input } from '@/components/ui/input'
|
||||||
|
import { Label } from '@/components/ui/label'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
|
||||||
|
const PALETTE = [
|
||||||
|
'#6366f1', '#8b5cf6', '#ec4899', '#ef4444',
|
||||||
|
'#f97316', '#eab308', '#22c55e', '#14b8a6',
|
||||||
|
'#3b82f6', '#06b6d4', '#64748b', '#78716c',
|
||||||
|
]
|
||||||
|
|
||||||
|
interface BudgetData {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
limitCents: number | null
|
||||||
|
color: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
open: boolean
|
||||||
|
onOpenChange: (open: boolean) => void
|
||||||
|
budget?: BudgetData
|
||||||
|
}
|
||||||
|
|
||||||
|
export function CreateBudgetDialog({ open, onOpenChange, budget }: Props) {
|
||||||
|
const router = useRouter()
|
||||||
|
const isEdit = !!budget
|
||||||
|
const [color, setColor] = useState(budget?.color ?? PALETTE[0])
|
||||||
|
const [loading, setLoading] = useState(false)
|
||||||
|
const [error, setError] = useState('')
|
||||||
|
|
||||||
|
async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
|
||||||
|
e.preventDefault()
|
||||||
|
setError('')
|
||||||
|
setLoading(true)
|
||||||
|
|
||||||
|
const form = new FormData(e.currentTarget)
|
||||||
|
const name = (form.get('name') as string).trim()
|
||||||
|
const limitRaw = (form.get('limit') as string).trim()
|
||||||
|
const limitCents = limitRaw ? Math.round(parseFloat(limitRaw) * 100) : null
|
||||||
|
|
||||||
|
if (limitRaw && (isNaN(limitCents!) || limitCents! <= 0)) {
|
||||||
|
setError('Limit must be a positive number.')
|
||||||
|
setLoading(false)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const res = await fetch(
|
||||||
|
isEdit ? `/api/budgets/${budget.id}` : '/api/budgets',
|
||||||
|
{
|
||||||
|
method: isEdit ? 'PATCH' : 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ name, limitCents, color }),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
if (!res.ok) {
|
||||||
|
setError('Something went wrong. Please try again.')
|
||||||
|
setLoading(false)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
router.refresh()
|
||||||
|
onOpenChange(false)
|
||||||
|
setLoading(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||||
|
<DialogContent className="sm:max-w-md">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>{isEdit ? 'Edit budget' : 'New budget'}</DialogTitle>
|
||||||
|
</DialogHeader>
|
||||||
|
<form onSubmit={handleSubmit} className="space-y-4 pt-2">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="name">Name</Label>
|
||||||
|
<Input
|
||||||
|
id="name"
|
||||||
|
name="name"
|
||||||
|
defaultValue={budget?.name}
|
||||||
|
placeholder="e.g. Groceries"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="limit">
|
||||||
|
Monthly limit <span className="text-muted-foreground">(optional)</span>
|
||||||
|
</Label>
|
||||||
|
<div className="relative">
|
||||||
|
<span className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground text-sm">$</span>
|
||||||
|
<Input
|
||||||
|
id="limit"
|
||||||
|
name="limit"
|
||||||
|
type="number"
|
||||||
|
min="0.01"
|
||||||
|
step="0.01"
|
||||||
|
className="pl-7"
|
||||||
|
defaultValue={budget?.limitCents ? (budget.limitCents / 100).toFixed(2) : ''}
|
||||||
|
placeholder="0.00"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>Color</Label>
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
{PALETTE.map((c) => (
|
||||||
|
<button
|
||||||
|
key={c}
|
||||||
|
type="button"
|
||||||
|
onClick={() => setColor(c)}
|
||||||
|
className={cn(
|
||||||
|
'h-7 w-7 rounded-full border-2 transition-transform hover:scale-110',
|
||||||
|
color === c ? 'border-foreground scale-110' : 'border-transparent',
|
||||||
|
)}
|
||||||
|
style={{ backgroundColor: c }}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{error && <p className="text-sm text-destructive">{error}</p>}
|
||||||
|
|
||||||
|
<div className="flex justify-end gap-2 pt-2">
|
||||||
|
<Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
<Button type="submit" disabled={loading}>
|
||||||
|
{loading ? 'Saving…' : isEdit ? 'Save changes' : 'Create budget'}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
)
|
||||||
|
}
|
||||||
61
src/components/dashboard/BudgetSummary.tsx
Normal file
61
src/components/dashboard/BudgetSummary.tsx
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
import Link from 'next/link'
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||||
|
import { BudgetProgress } from '@/components/budgets/BudgetProgress'
|
||||||
|
import { formatCents } from '@/lib/utils/currency'
|
||||||
|
import { ArrowRight } from 'lucide-react'
|
||||||
|
|
||||||
|
interface BudgetItem {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
limitCents: number | null
|
||||||
|
color: string | null
|
||||||
|
spendCents: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export function BudgetSummary({ budgets }: { budgets: BudgetItem[] }) {
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<CardHeader className="pb-2 flex flex-row items-center justify-between space-y-0">
|
||||||
|
<CardTitle className="text-sm font-medium text-muted-foreground">Budgets</CardTitle>
|
||||||
|
<Link
|
||||||
|
href="/budgets"
|
||||||
|
className="flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors"
|
||||||
|
>
|
||||||
|
Manage <ArrowRight className="h-3 w-3" />
|
||||||
|
</Link>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
{budgets.length === 0 ? (
|
||||||
|
<p className="text-sm text-muted-foreground py-4 text-center">No active budgets.</p>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-4">
|
||||||
|
{budgets.map((b) => (
|
||||||
|
<div key={b.id} className="space-y-1">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div className="flex items-center gap-2 min-w-0">
|
||||||
|
{b.color && (
|
||||||
|
<span
|
||||||
|
className="h-2.5 w-2.5 rounded-full shrink-0"
|
||||||
|
style={{ backgroundColor: b.color }}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
<span className="text-sm font-medium truncate">{b.name}</span>
|
||||||
|
</div>
|
||||||
|
<span className="text-sm tabular-nums text-muted-foreground shrink-0 ml-2">
|
||||||
|
{formatCents(b.spendCents)}
|
||||||
|
{b.limitCents ? ` / ${formatCents(b.limitCents)}` : ''}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
{b.limitCents ? (
|
||||||
|
<BudgetProgress spendCents={b.spendCents} limitCents={b.limitCents} />
|
||||||
|
) : (
|
||||||
|
<div className="h-1.5 rounded-full bg-muted" />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
)
|
||||||
|
}
|
||||||
49
src/components/dashboard/CashFlowCard.tsx
Normal file
49
src/components/dashboard/CashFlowCard.tsx
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||||
|
import { formatCents } from '@/lib/utils/currency'
|
||||||
|
import { ArrowDownLeft, ArrowUpRight, TrendingUp } from 'lucide-react'
|
||||||
|
|
||||||
|
interface CashFlowCardProps {
|
||||||
|
monthLabel: string
|
||||||
|
creditsCents: number
|
||||||
|
debitsCents: number
|
||||||
|
netCents: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export function CashFlowCard({ monthLabel, creditsCents, debitsCents, netCents }: CashFlowCardProps) {
|
||||||
|
const isPositive = netCents >= 0
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<CardHeader className="pb-2">
|
||||||
|
<CardTitle className="text-sm font-medium text-muted-foreground">
|
||||||
|
Cash Flow · {monthLabel}
|
||||||
|
</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="space-y-3">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<TrendingUp className={`h-5 w-5 shrink-0 ${isPositive ? 'text-green-500' : 'text-red-500'}`} />
|
||||||
|
<span className={`text-3xl font-bold tabular-nums ${isPositive ? 'text-green-600' : 'text-red-600'}`}>
|
||||||
|
{isPositive ? '+' : ''}{formatCents(netCents)}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-1">
|
||||||
|
<div className="flex items-center justify-between text-sm">
|
||||||
|
<span className="flex items-center gap-1.5 text-muted-foreground">
|
||||||
|
<ArrowDownLeft className="h-3.5 w-3.5 text-green-500" />
|
||||||
|
Income
|
||||||
|
</span>
|
||||||
|
<span className="tabular-nums font-medium text-green-600">{formatCents(creditsCents)}</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center justify-between text-sm">
|
||||||
|
<span className="flex items-center gap-1.5 text-muted-foreground">
|
||||||
|
<ArrowUpRight className="h-3.5 w-3.5 text-red-500" />
|
||||||
|
Spending
|
||||||
|
</span>
|
||||||
|
<span className="tabular-nums font-medium text-red-600">{formatCents(debitsCents)}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
)
|
||||||
|
}
|
||||||
41
src/components/dashboard/NetWorthCard.tsx
Normal file
41
src/components/dashboard/NetWorthCard.tsx
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||||
|
import { formatCents } from '@/lib/utils/currency'
|
||||||
|
|
||||||
|
interface BankAccount {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
currentBalanceCents: number
|
||||||
|
}
|
||||||
|
|
||||||
|
interface NetWorthCardProps {
|
||||||
|
netWorthCents: number
|
||||||
|
bankAccounts: BankAccount[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export function NetWorthCard({ netWorthCents, bankAccounts }: NetWorthCardProps) {
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<CardHeader className="pb-2">
|
||||||
|
<CardTitle className="text-sm font-medium text-muted-foreground">Net Worth</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="space-y-3">
|
||||||
|
<p className="text-3xl font-bold tabular-nums">{formatCents(netWorthCents)}</p>
|
||||||
|
{bankAccounts.length > 0 && (
|
||||||
|
<div className="space-y-1">
|
||||||
|
{bankAccounts.map((a) => (
|
||||||
|
<div key={a.id} className="flex items-center justify-between text-sm">
|
||||||
|
<span className="text-muted-foreground truncate">{a.name}</span>
|
||||||
|
<span className="tabular-nums font-medium ml-4 shrink-0">
|
||||||
|
{formatCents(a.currentBalanceCents)}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{bankAccounts.length === 0 && (
|
||||||
|
<p className="text-sm text-muted-foreground">No bank accounts yet.</p>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
)
|
||||||
|
}
|
||||||
58
src/components/dashboard/RecentTransactions.tsx
Normal file
58
src/components/dashboard/RecentTransactions.tsx
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
import Link from 'next/link'
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||||
|
import { formatCents } from '@/lib/utils/currency'
|
||||||
|
import { ArrowRight } from 'lucide-react'
|
||||||
|
|
||||||
|
interface RecentTx {
|
||||||
|
id: string
|
||||||
|
date: string
|
||||||
|
description: string
|
||||||
|
amountCents: number
|
||||||
|
type: string
|
||||||
|
accountName: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export function RecentTransactions({ transactions }: { transactions: RecentTx[] }) {
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<CardHeader className="pb-2 flex flex-row items-center justify-between space-y-0">
|
||||||
|
<CardTitle className="text-sm font-medium text-muted-foreground">Recent Transactions</CardTitle>
|
||||||
|
<Link
|
||||||
|
href="/transactions"
|
||||||
|
className="flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors"
|
||||||
|
>
|
||||||
|
View all <ArrowRight className="h-3 w-3" />
|
||||||
|
</Link>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
{transactions.length === 0 ? (
|
||||||
|
<p className="text-sm text-muted-foreground py-4 text-center">No transactions yet.</p>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-3">
|
||||||
|
{transactions.map((tx) => {
|
||||||
|
const date = new Date(tx.date)
|
||||||
|
const label = date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })
|
||||||
|
return (
|
||||||
|
<div key={tx.id} className="flex items-start justify-between gap-2">
|
||||||
|
<div className="min-w-0">
|
||||||
|
<p className="text-sm font-medium truncate">{tx.description}</p>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
{label} · {tx.accountName}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<span
|
||||||
|
className={`text-sm font-medium tabular-nums shrink-0 ${
|
||||||
|
tx.type === 'CREDIT' ? 'text-green-600' : 'text-foreground'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{tx.type === 'CREDIT' ? '+' : '-'}{formatCents(tx.amountCents)}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
)
|
||||||
|
}
|
||||||
79
src/components/graphs/BudgetChart.tsx
Normal file
79
src/components/graphs/BudgetChart.tsx
Normal file
@@ -0,0 +1,79 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import {
|
||||||
|
BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer, Cell,
|
||||||
|
} from 'recharts'
|
||||||
|
import { formatCents, formatCentsAbbrev } from '@/lib/utils/currency'
|
||||||
|
|
||||||
|
interface BudgetBar {
|
||||||
|
name: string
|
||||||
|
spendCents: number
|
||||||
|
limitCents: number
|
||||||
|
color: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
function ChartTooltip({ active, payload, label }: {
|
||||||
|
active?: boolean
|
||||||
|
payload?: Array<{ name: string; value: number }>
|
||||||
|
label?: string
|
||||||
|
}) {
|
||||||
|
if (!active || !payload?.length) return null
|
||||||
|
return (
|
||||||
|
<div className="rounded-md border bg-card p-3 shadow-md text-sm">
|
||||||
|
<p className="font-medium mb-1">{label}</p>
|
||||||
|
{payload.map((p) => (
|
||||||
|
<p key={p.name} className="text-muted-foreground">
|
||||||
|
{p.name}: {formatCents(p.value)}
|
||||||
|
</p>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function BudgetChart({ data }: { data: BudgetBar[] }) {
|
||||||
|
if (data.length === 0) {
|
||||||
|
return (
|
||||||
|
<div className="flex h-[300px] items-center justify-center text-sm text-muted-foreground">
|
||||||
|
No active budgets.
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const chartHeight = Math.max(200, data.length * 60 + 60)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ResponsiveContainer width="100%" height={chartHeight}>
|
||||||
|
<BarChart
|
||||||
|
layout="vertical"
|
||||||
|
data={data}
|
||||||
|
margin={{ top: 4, right: 24, left: 8, bottom: 0 }}
|
||||||
|
barGap={4}
|
||||||
|
>
|
||||||
|
<CartesianGrid strokeDasharray="3 3" className="stroke-muted" horizontal={false} />
|
||||||
|
<XAxis
|
||||||
|
type="number"
|
||||||
|
tickFormatter={formatCentsAbbrev}
|
||||||
|
tick={{ fontSize: 12 }}
|
||||||
|
tickLine={false}
|
||||||
|
axisLine={false}
|
||||||
|
/>
|
||||||
|
<YAxis
|
||||||
|
type="category"
|
||||||
|
dataKey="name"
|
||||||
|
tick={{ fontSize: 12 }}
|
||||||
|
tickLine={false}
|
||||||
|
axisLine={false}
|
||||||
|
width={90}
|
||||||
|
/>
|
||||||
|
<Tooltip content={<ChartTooltip />} />
|
||||||
|
<Legend wrapperStyle={{ fontSize: 12 }} />
|
||||||
|
<Bar dataKey="spendCents" name="Spent" radius={[0, 4, 4, 0]} maxBarSize={20}>
|
||||||
|
{data.map((d, i) => (
|
||||||
|
<Cell key={i} fill={d.color ?? '#6366f1'} />
|
||||||
|
))}
|
||||||
|
</Bar>
|
||||||
|
<Bar dataKey="limitCents" name="Limit" fill="#e2e8f0" radius={[0, 4, 4, 0]} maxBarSize={20} />
|
||||||
|
</BarChart>
|
||||||
|
</ResponsiveContainer>
|
||||||
|
)
|
||||||
|
}
|
||||||
60
src/components/graphs/CashFlowChart.tsx
Normal file
60
src/components/graphs/CashFlowChart.tsx
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import {
|
||||||
|
BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer,
|
||||||
|
} from 'recharts'
|
||||||
|
import { formatCents, formatCentsAbbrev } from '@/lib/utils/currency'
|
||||||
|
|
||||||
|
interface DataPoint {
|
||||||
|
label: string
|
||||||
|
creditsCents: number
|
||||||
|
debitsCents: number
|
||||||
|
}
|
||||||
|
|
||||||
|
function ChartTooltip({ active, payload, label }: {
|
||||||
|
active?: boolean
|
||||||
|
payload?: Array<{ name: string; value: number; color: string }>
|
||||||
|
label?: string
|
||||||
|
}) {
|
||||||
|
if (!active || !payload?.length) return null
|
||||||
|
return (
|
||||||
|
<div className="rounded-md border bg-card p-3 shadow-md text-sm">
|
||||||
|
<p className="font-medium mb-1">{label}</p>
|
||||||
|
{payload.map((p) => (
|
||||||
|
<p key={p.name} style={{ color: p.color }}>
|
||||||
|
{p.name}: {formatCents(p.value)}
|
||||||
|
</p>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function CashFlowChart({ data }: { data: DataPoint[] }) {
|
||||||
|
if (data.length === 0) {
|
||||||
|
return (
|
||||||
|
<div className="flex h-[300px] items-center justify-center text-sm text-muted-foreground">
|
||||||
|
No bank transaction data yet.
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ResponsiveContainer width="100%" height={300}>
|
||||||
|
<BarChart data={data} margin={{ top: 4, right: 16, left: 16, bottom: 0 }} barGap={4}>
|
||||||
|
<CartesianGrid strokeDasharray="3 3" className="stroke-muted" vertical={false} />
|
||||||
|
<XAxis dataKey="label" tick={{ fontSize: 12 }} tickLine={false} axisLine={false} />
|
||||||
|
<YAxis
|
||||||
|
tickFormatter={formatCentsAbbrev}
|
||||||
|
tick={{ fontSize: 12 }}
|
||||||
|
tickLine={false}
|
||||||
|
axisLine={false}
|
||||||
|
width={64}
|
||||||
|
/>
|
||||||
|
<Tooltip content={<ChartTooltip />} />
|
||||||
|
<Legend wrapperStyle={{ fontSize: 12 }} />
|
||||||
|
<Bar dataKey="creditsCents" name="Income" fill="#22c55e" radius={[4, 4, 0, 0]} maxBarSize={40} />
|
||||||
|
<Bar dataKey="debitsCents" name="Spending" fill="#ef4444" radius={[4, 4, 0, 0]} maxBarSize={40} />
|
||||||
|
</BarChart>
|
||||||
|
</ResponsiveContainer>
|
||||||
|
)
|
||||||
|
}
|
||||||
68
src/components/graphs/CategoryBreakdownChart.tsx
Normal file
68
src/components/graphs/CategoryBreakdownChart.tsx
Normal file
@@ -0,0 +1,68 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import {
|
||||||
|
PieChart, Pie, Cell, Tooltip, Legend, ResponsiveContainer,
|
||||||
|
} from 'recharts'
|
||||||
|
import { formatCents } from '@/lib/utils/currency'
|
||||||
|
|
||||||
|
interface DataPoint {
|
||||||
|
category: string
|
||||||
|
totalCents: number
|
||||||
|
}
|
||||||
|
|
||||||
|
const COLORS = [
|
||||||
|
'#6366f1', '#22c55e', '#f59e0b', '#ef4444', '#8b5cf6',
|
||||||
|
'#14b8a6', '#f97316', '#ec4899', '#0ea5e9', '#84cc16',
|
||||||
|
]
|
||||||
|
|
||||||
|
function ChartTooltip({ active, payload }: {
|
||||||
|
active?: boolean
|
||||||
|
payload?: Array<{ name: string; value: number; payload: DataPoint }>
|
||||||
|
}) {
|
||||||
|
if (!active || !payload?.length) return null
|
||||||
|
const item = payload[0]
|
||||||
|
return (
|
||||||
|
<div className="rounded-md border bg-card p-3 shadow-md text-sm">
|
||||||
|
<p className="font-medium">{item.payload.category}</p>
|
||||||
|
<p className="text-muted-foreground">{formatCents(item.value)}</p>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function CategoryBreakdownChart({ data }: { data: DataPoint[] }) {
|
||||||
|
if (data.length === 0) {
|
||||||
|
return (
|
||||||
|
<div className="flex h-[320px] items-center justify-center text-sm text-muted-foreground">
|
||||||
|
No spending this month.
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ResponsiveContainer width="100%" height={320}>
|
||||||
|
<PieChart>
|
||||||
|
<Pie
|
||||||
|
data={data}
|
||||||
|
dataKey="totalCents"
|
||||||
|
nameKey="category"
|
||||||
|
cx="50%"
|
||||||
|
cy="45%"
|
||||||
|
innerRadius={70}
|
||||||
|
outerRadius={110}
|
||||||
|
paddingAngle={2}
|
||||||
|
>
|
||||||
|
{data.map((_, i) => (
|
||||||
|
<Cell key={i} fill={COLORS[i % COLORS.length]} />
|
||||||
|
))}
|
||||||
|
</Pie>
|
||||||
|
<Tooltip content={<ChartTooltip />} />
|
||||||
|
<Legend
|
||||||
|
iconType="circle"
|
||||||
|
iconSize={8}
|
||||||
|
wrapperStyle={{ fontSize: 12 }}
|
||||||
|
formatter={(value) => <span className="text-foreground">{value}</span>}
|
||||||
|
/>
|
||||||
|
</PieChart>
|
||||||
|
</ResponsiveContainer>
|
||||||
|
)
|
||||||
|
}
|
||||||
53
src/components/graphs/MonthlySpendingChart.tsx
Normal file
53
src/components/graphs/MonthlySpendingChart.tsx
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import {
|
||||||
|
BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer,
|
||||||
|
} from 'recharts'
|
||||||
|
import { formatCents, formatCentsAbbrev } from '@/lib/utils/currency'
|
||||||
|
|
||||||
|
interface DataPoint {
|
||||||
|
label: string
|
||||||
|
totalCents: number
|
||||||
|
}
|
||||||
|
|
||||||
|
function ChartTooltip({ active, payload, label }: {
|
||||||
|
active?: boolean
|
||||||
|
payload?: Array<{ value: number }>
|
||||||
|
label?: string
|
||||||
|
}) {
|
||||||
|
if (!active || !payload?.length) return null
|
||||||
|
return (
|
||||||
|
<div className="rounded-md border bg-card p-3 shadow-md text-sm">
|
||||||
|
<p className="font-medium mb-1">{label}</p>
|
||||||
|
<p className="text-foreground">Total: {formatCents(payload[0].value)}</p>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function MonthlySpendingChart({ data }: { data: DataPoint[] }) {
|
||||||
|
if (data.length === 0) {
|
||||||
|
return (
|
||||||
|
<div className="flex h-[300px] items-center justify-center text-sm text-muted-foreground">
|
||||||
|
No spending data yet.
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ResponsiveContainer width="100%" height={300}>
|
||||||
|
<BarChart data={data} margin={{ top: 4, right: 16, left: 16, bottom: 0 }}>
|
||||||
|
<CartesianGrid strokeDasharray="3 3" className="stroke-muted" vertical={false} />
|
||||||
|
<XAxis dataKey="label" tick={{ fontSize: 12 }} tickLine={false} axisLine={false} />
|
||||||
|
<YAxis
|
||||||
|
tickFormatter={formatCentsAbbrev}
|
||||||
|
tick={{ fontSize: 12 }}
|
||||||
|
tickLine={false}
|
||||||
|
axisLine={false}
|
||||||
|
width={64}
|
||||||
|
/>
|
||||||
|
<Tooltip content={<ChartTooltip />} />
|
||||||
|
<Bar dataKey="totalCents" name="Spending" fill="#8b5cf6" radius={[4, 4, 0, 0]} maxBarSize={48} />
|
||||||
|
</BarChart>
|
||||||
|
</ResponsiveContainer>
|
||||||
|
)
|
||||||
|
}
|
||||||
68
src/components/graphs/NetWorthTrendChart.tsx
Normal file
68
src/components/graphs/NetWorthTrendChart.tsx
Normal file
@@ -0,0 +1,68 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import {
|
||||||
|
AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer,
|
||||||
|
} from 'recharts'
|
||||||
|
import { formatCents, formatCentsAbbrev } from '@/lib/utils/currency'
|
||||||
|
|
||||||
|
interface DataPoint {
|
||||||
|
label: string
|
||||||
|
totalCents: number
|
||||||
|
}
|
||||||
|
|
||||||
|
function ChartTooltip({ active, payload, label }: {
|
||||||
|
active?: boolean
|
||||||
|
payload?: Array<{ value: number }>
|
||||||
|
label?: string
|
||||||
|
}) {
|
||||||
|
if (!active || !payload?.length) return null
|
||||||
|
return (
|
||||||
|
<div className="rounded-md border bg-card p-3 shadow-md text-sm">
|
||||||
|
<p className="font-medium mb-1">{label}</p>
|
||||||
|
<p className="text-primary">{formatCents(payload[0].value)}</p>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function NetWorthTrendChart({ data }: { data: DataPoint[] }) {
|
||||||
|
if (data.length === 0) {
|
||||||
|
return (
|
||||||
|
<div className="flex h-[300px] items-center justify-center text-sm text-muted-foreground">
|
||||||
|
No snapshot data yet — upload transactions to populate this chart.
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ResponsiveContainer width="100%" height={300}>
|
||||||
|
<AreaChart data={data} margin={{ top: 4, right: 16, left: 16, bottom: 0 }}>
|
||||||
|
<defs>
|
||||||
|
<linearGradient id="netWorthGradient" x1="0" y1="0" x2="0" y2="1">
|
||||||
|
<stop offset="5%" stopColor="#6366f1" stopOpacity={0.3} />
|
||||||
|
<stop offset="95%" stopColor="#6366f1" stopOpacity={0} />
|
||||||
|
</linearGradient>
|
||||||
|
</defs>
|
||||||
|
<CartesianGrid strokeDasharray="3 3" className="stroke-muted" />
|
||||||
|
<XAxis dataKey="label" tick={{ fontSize: 12 }} tickLine={false} axisLine={false} />
|
||||||
|
<YAxis
|
||||||
|
tickFormatter={formatCentsAbbrev}
|
||||||
|
tick={{ fontSize: 12 }}
|
||||||
|
tickLine={false}
|
||||||
|
axisLine={false}
|
||||||
|
width={64}
|
||||||
|
/>
|
||||||
|
<Tooltip content={<ChartTooltip />} />
|
||||||
|
<Area
|
||||||
|
type="monotone"
|
||||||
|
dataKey="totalCents"
|
||||||
|
name="Net Worth"
|
||||||
|
stroke="#6366f1"
|
||||||
|
strokeWidth={2}
|
||||||
|
fill="url(#netWorthGradient)"
|
||||||
|
dot={false}
|
||||||
|
activeDot={{ r: 4 }}
|
||||||
|
/>
|
||||||
|
</AreaChart>
|
||||||
|
</ResponsiveContainer>
|
||||||
|
)
|
||||||
|
}
|
||||||
60
src/components/layout/Sidebar.tsx
Normal file
60
src/components/layout/Sidebar.tsx
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import Link from 'next/link'
|
||||||
|
import { usePathname } from 'next/navigation'
|
||||||
|
import { signOut } from 'next-auth/react'
|
||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
import {
|
||||||
|
LayoutDashboard, CreditCard, ArrowLeftRight,
|
||||||
|
Upload, PiggyBank, TrendingUp, LogOut,
|
||||||
|
} from 'lucide-react'
|
||||||
|
import { Separator } from '@/components/ui/separator'
|
||||||
|
|
||||||
|
const navItems = [
|
||||||
|
{ href: '/dashboard', label: 'Dashboard', icon: LayoutDashboard },
|
||||||
|
{ href: '/accounts', label: 'Accounts', icon: CreditCard },
|
||||||
|
{ href: '/transactions', label: 'Transactions', icon: ArrowLeftRight },
|
||||||
|
{ href: '/upload', label: 'Upload', icon: Upload },
|
||||||
|
{ href: '/budgets', label: 'Budgets', icon: PiggyBank },
|
||||||
|
{ href: '/graphs', label: 'Graphs', icon: TrendingUp },
|
||||||
|
]
|
||||||
|
|
||||||
|
export function Sidebar() {
|
||||||
|
const pathname = usePathname()
|
||||||
|
|
||||||
|
return (
|
||||||
|
<aside className="flex w-56 shrink-0 flex-col border-r bg-card">
|
||||||
|
<div className="flex h-14 items-center px-4">
|
||||||
|
<span className="font-semibold text-lg">Finance</span>
|
||||||
|
</div>
|
||||||
|
<Separator />
|
||||||
|
<nav className="flex-1 space-y-1 p-2">
|
||||||
|
{navItems.map(({ href, label, icon: Icon }) => (
|
||||||
|
<Link
|
||||||
|
key={href}
|
||||||
|
href={href}
|
||||||
|
className={cn(
|
||||||
|
'flex items-center gap-3 rounded-md px-3 py-2 text-sm font-medium transition-colors',
|
||||||
|
pathname.startsWith(href)
|
||||||
|
? 'bg-primary text-primary-foreground'
|
||||||
|
: 'text-muted-foreground hover:bg-accent hover:text-accent-foreground',
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<Icon className="h-4 w-4 shrink-0" />
|
||||||
|
{label}
|
||||||
|
</Link>
|
||||||
|
))}
|
||||||
|
</nav>
|
||||||
|
<Separator />
|
||||||
|
<div className="p-2">
|
||||||
|
<button
|
||||||
|
onClick={() => signOut({ callbackUrl: '/login' })}
|
||||||
|
className="flex w-full items-center gap-3 rounded-md px-3 py-2 text-sm font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-accent-foreground"
|
||||||
|
>
|
||||||
|
<LogOut className="h-4 w-4 shrink-0" />
|
||||||
|
Sign out
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</aside>
|
||||||
|
)
|
||||||
|
}
|
||||||
150
src/components/transactions/EditTransactionDialog.tsx
Normal file
150
src/components/transactions/EditTransactionDialog.tsx
Normal file
@@ -0,0 +1,150 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { useEffect, useState } from 'react'
|
||||||
|
import { useRouter } from 'next/navigation'
|
||||||
|
import {
|
||||||
|
Dialog, DialogContent, DialogHeader, DialogTitle,
|
||||||
|
} from '@/components/ui/dialog'
|
||||||
|
import { Label } from '@/components/ui/label'
|
||||||
|
import { Input } from '@/components/ui/input'
|
||||||
|
import { Textarea } from '@/components/ui/textarea'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import {
|
||||||
|
Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
|
||||||
|
} from '@/components/ui/select'
|
||||||
|
import { formatCents } from '@/lib/utils/currency'
|
||||||
|
import type { TransactionRow } from './TransactionTable'
|
||||||
|
|
||||||
|
interface BudgetOption { id: string; name: string; color: string | null }
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
transaction: TransactionRow | null
|
||||||
|
onOpenChange: (open: boolean) => void
|
||||||
|
budgets: BudgetOption[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export function EditTransactionDialog({ transaction, onOpenChange, budgets }: Props) {
|
||||||
|
const router = useRouter()
|
||||||
|
const [category, setCategory] = useState('')
|
||||||
|
const [notes, setNotes] = useState('')
|
||||||
|
const [budgetId, setBudgetId] = useState('')
|
||||||
|
const [loading, setLoading] = useState(false)
|
||||||
|
const [error, setError] = useState('')
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (transaction) {
|
||||||
|
setCategory(transaction.category ?? '')
|
||||||
|
setNotes(transaction.notes ?? '')
|
||||||
|
setBudgetId(transaction.budgetId ?? '')
|
||||||
|
setError('')
|
||||||
|
}
|
||||||
|
}, [transaction])
|
||||||
|
|
||||||
|
async function handleSubmit(e: React.FormEvent) {
|
||||||
|
e.preventDefault()
|
||||||
|
if (!transaction) return
|
||||||
|
setLoading(true)
|
||||||
|
setError('')
|
||||||
|
|
||||||
|
const res = await fetch(`/api/transactions/${transaction.id}`, {
|
||||||
|
method: 'PATCH',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({
|
||||||
|
category: category.trim() || null,
|
||||||
|
notes: notes.trim() || null,
|
||||||
|
budgetId: budgetId || null,
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!res.ok) {
|
||||||
|
setError('Failed to save. Please try again.')
|
||||||
|
setLoading(false)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
router.refresh()
|
||||||
|
onOpenChange(false)
|
||||||
|
setLoading(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!transaction) return null
|
||||||
|
const date = new Date(transaction.date).toLocaleDateString('en-US', {
|
||||||
|
month: 'short', day: 'numeric', year: 'numeric',
|
||||||
|
})
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={!!transaction} onOpenChange={onOpenChange}>
|
||||||
|
<DialogContent className="sm:max-w-md">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle className="text-base font-semibold leading-tight">
|
||||||
|
{transaction.description}
|
||||||
|
</DialogTitle>
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
{date} · <span className={transaction.type === 'CREDIT' ? 'text-green-600' : ''}>
|
||||||
|
{transaction.type === 'CREDIT' ? '+' : '-'}{formatCents(transaction.amountCents)}
|
||||||
|
</span>
|
||||||
|
</p>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
<form onSubmit={handleSubmit} className="space-y-4 pt-2">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="category">Category</Label>
|
||||||
|
<Input
|
||||||
|
id="category"
|
||||||
|
value={category}
|
||||||
|
onChange={(e) => setCategory(e.target.value)}
|
||||||
|
placeholder="e.g. Groceries"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="budget">Budget</Label>
|
||||||
|
<Select value={budgetId} onValueChange={(v) => setBudgetId(v ?? '')}>
|
||||||
|
<SelectTrigger id="budget">
|
||||||
|
<SelectValue placeholder="No budget" />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="">No budget</SelectItem>
|
||||||
|
{budgets.map((b) => (
|
||||||
|
<SelectItem key={b.id} value={b.id}>
|
||||||
|
<span className="flex items-center gap-2">
|
||||||
|
{b.color && (
|
||||||
|
<span
|
||||||
|
className="inline-block h-2.5 w-2.5 rounded-full shrink-0"
|
||||||
|
style={{ backgroundColor: b.color }}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{b.name}
|
||||||
|
</span>
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="notes">Notes</Label>
|
||||||
|
<Textarea
|
||||||
|
id="notes"
|
||||||
|
value={notes}
|
||||||
|
onChange={(e) => setNotes(e.target.value)}
|
||||||
|
placeholder="Optional notes…"
|
||||||
|
rows={3}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{error && <p className="text-sm text-destructive">{error}</p>}
|
||||||
|
|
||||||
|
<div className="flex justify-end gap-2 pt-2">
|
||||||
|
<Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
<Button type="submit" disabled={loading}>
|
||||||
|
{loading ? 'Saving…' : 'Save'}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
)
|
||||||
|
}
|
||||||
118
src/components/transactions/TransactionFilters.tsx
Normal file
118
src/components/transactions/TransactionFilters.tsx
Normal file
@@ -0,0 +1,118 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { useCallback, useEffect, useState } from 'react'
|
||||||
|
import { useRouter, useSearchParams, usePathname } from 'next/navigation'
|
||||||
|
import { Input } from '@/components/ui/input'
|
||||||
|
import { Label } from '@/components/ui/label'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import {
|
||||||
|
Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
|
||||||
|
} from '@/components/ui/select'
|
||||||
|
import { X } from 'lucide-react'
|
||||||
|
|
||||||
|
interface AccountOption { id: string; name: string }
|
||||||
|
|
||||||
|
export function TransactionFilters({ accounts }: { accounts: AccountOption[] }) {
|
||||||
|
const router = useRouter()
|
||||||
|
const pathname = usePathname()
|
||||||
|
const searchParams = useSearchParams()
|
||||||
|
|
||||||
|
const sp = (key: string) => searchParams.get(key) ?? ''
|
||||||
|
|
||||||
|
const [search, setSearch] = useState(sp('search'))
|
||||||
|
|
||||||
|
const push = useCallback(
|
||||||
|
(updates: Record<string, string>) => {
|
||||||
|
const params = new URLSearchParams(searchParams.toString())
|
||||||
|
for (const [k, v] of Object.entries(updates)) {
|
||||||
|
if (v) params.set(k, v); else params.delete(k)
|
||||||
|
}
|
||||||
|
params.delete('page')
|
||||||
|
router.replace(`${pathname}?${params.toString()}`)
|
||||||
|
},
|
||||||
|
[searchParams, pathname, router],
|
||||||
|
)
|
||||||
|
|
||||||
|
// Debounce search → URL
|
||||||
|
useEffect(() => {
|
||||||
|
const t = setTimeout(() => push({ search }), 400)
|
||||||
|
return () => clearTimeout(t)
|
||||||
|
}, [search, push])
|
||||||
|
|
||||||
|
function reset() {
|
||||||
|
setSearch('')
|
||||||
|
router.replace(pathname)
|
||||||
|
}
|
||||||
|
|
||||||
|
const hasFilters = !!(sp('accountId') || sp('dateFrom') || sp('dateTo') || sp('type') || sp('search'))
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex flex-wrap items-end gap-3 pb-4">
|
||||||
|
<div className="space-y-1">
|
||||||
|
<Label className="text-xs">Account</Label>
|
||||||
|
<Select value={sp('accountId')} onValueChange={(v) => push({ accountId: v ?? '' })}>
|
||||||
|
<SelectTrigger className="h-8 w-44 text-sm">
|
||||||
|
<SelectValue placeholder="All accounts" />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="">All accounts</SelectItem>
|
||||||
|
{accounts.map((a) => (
|
||||||
|
<SelectItem key={a.id} value={a.id}>{a.name}</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-1">
|
||||||
|
<Label className="text-xs">From</Label>
|
||||||
|
<Input
|
||||||
|
type="date"
|
||||||
|
className="h-8 w-36 text-sm"
|
||||||
|
value={sp('dateFrom')}
|
||||||
|
onChange={(e) => push({ dateFrom: e.target.value })}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-1">
|
||||||
|
<Label className="text-xs">To</Label>
|
||||||
|
<Input
|
||||||
|
type="date"
|
||||||
|
className="h-8 w-36 text-sm"
|
||||||
|
value={sp('dateTo')}
|
||||||
|
onChange={(e) => push({ dateTo: e.target.value })}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-1">
|
||||||
|
<Label className="text-xs">Type</Label>
|
||||||
|
<Select value={sp('type')} onValueChange={(v) => push({ type: v ?? '' })}>
|
||||||
|
<SelectTrigger className="h-8 w-32 text-sm">
|
||||||
|
<SelectValue placeholder="All types" />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="">All types</SelectItem>
|
||||||
|
<SelectItem value="DEBIT">Debit</SelectItem>
|
||||||
|
<SelectItem value="CREDIT">Credit</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex-1 min-w-40 space-y-1">
|
||||||
|
<Label className="text-xs">Search</Label>
|
||||||
|
<Input
|
||||||
|
className="h-8 text-sm"
|
||||||
|
placeholder="Search descriptions…"
|
||||||
|
value={search}
|
||||||
|
onChange={(e) => setSearch(e.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{hasFilters && (
|
||||||
|
<Button variant="ghost" size="sm" className="h-8" onClick={reset}>
|
||||||
|
<X className="h-3.5 w-3.5 mr-1" />
|
||||||
|
Reset
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
185
src/components/transactions/TransactionTable.tsx
Normal file
185
src/components/transactions/TransactionTable.tsx
Normal file
@@ -0,0 +1,185 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { useState } from 'react'
|
||||||
|
import Link from 'next/link'
|
||||||
|
import { usePathname, useSearchParams } from 'next/navigation'
|
||||||
|
import {
|
||||||
|
Table, TableBody, TableCell, TableHead, TableHeader, TableRow,
|
||||||
|
} from '@/components/ui/table'
|
||||||
|
import { Pencil, ChevronLeft, ChevronRight } from 'lucide-react'
|
||||||
|
import { formatCents } from '@/lib/utils/currency'
|
||||||
|
import { EditTransactionDialog } from './EditTransactionDialog'
|
||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
|
||||||
|
export type TransactionRow = {
|
||||||
|
id: string
|
||||||
|
date: string
|
||||||
|
description: string
|
||||||
|
amountCents: number
|
||||||
|
type: string
|
||||||
|
category: string | null
|
||||||
|
notes: string | null
|
||||||
|
accountId: string
|
||||||
|
budgetId: string | null
|
||||||
|
account: { name: string; type: string }
|
||||||
|
budget: { id: string; name: string; color: string | null } | null
|
||||||
|
}
|
||||||
|
|
||||||
|
type BudgetOption = { id: string; name: string; color: string | null }
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
transactions: TransactionRow[]
|
||||||
|
total: number
|
||||||
|
page: number
|
||||||
|
limit: number
|
||||||
|
showAccount?: boolean
|
||||||
|
budgets: BudgetOption[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export function TransactionTable({
|
||||||
|
transactions,
|
||||||
|
total,
|
||||||
|
page,
|
||||||
|
limit,
|
||||||
|
showAccount = true,
|
||||||
|
budgets,
|
||||||
|
}: Props) {
|
||||||
|
const pathname = usePathname()
|
||||||
|
const searchParams = useSearchParams()
|
||||||
|
const [editing, setEditing] = useState<TransactionRow | null>(null)
|
||||||
|
const totalPages = Math.ceil(total / limit)
|
||||||
|
|
||||||
|
function pageHref(p: number) {
|
||||||
|
const params = new URLSearchParams(searchParams.toString())
|
||||||
|
params.set('page', String(p))
|
||||||
|
return `${pathname}?${params.toString()}`
|
||||||
|
}
|
||||||
|
|
||||||
|
if (transactions.length === 0) {
|
||||||
|
return (
|
||||||
|
<div className="rounded-lg border border-dashed p-12 text-center text-muted-foreground">
|
||||||
|
No transactions found.
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<div className="rounded-md border overflow-hidden">
|
||||||
|
<Table>
|
||||||
|
<TableHeader>
|
||||||
|
<TableRow>
|
||||||
|
<TableHead className="w-28">Date</TableHead>
|
||||||
|
<TableHead>Description</TableHead>
|
||||||
|
{showAccount && <TableHead className="w-36">Account</TableHead>}
|
||||||
|
<TableHead className="w-32 text-right">Amount</TableHead>
|
||||||
|
<TableHead className="w-32">Category</TableHead>
|
||||||
|
<TableHead className="w-32">Budget</TableHead>
|
||||||
|
<TableHead className="w-10" />
|
||||||
|
</TableRow>
|
||||||
|
</TableHeader>
|
||||||
|
<TableBody>
|
||||||
|
{transactions.map((tx) => {
|
||||||
|
const isCredit = tx.type === 'CREDIT'
|
||||||
|
const dateStr = new Date(tx.date).toLocaleDateString('en-US', {
|
||||||
|
month: 'short', day: 'numeric', year: 'numeric',
|
||||||
|
})
|
||||||
|
return (
|
||||||
|
<TableRow key={tx.id}>
|
||||||
|
<TableCell className="text-sm text-muted-foreground whitespace-nowrap">
|
||||||
|
{dateStr}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="max-w-xs">
|
||||||
|
<div className="truncate text-sm">{tx.description}</div>
|
||||||
|
{tx.notes && (
|
||||||
|
<div className="truncate text-xs text-muted-foreground">{tx.notes}</div>
|
||||||
|
)}
|
||||||
|
</TableCell>
|
||||||
|
{showAccount && (
|
||||||
|
<TableCell className="text-sm text-muted-foreground">
|
||||||
|
{tx.account.name}
|
||||||
|
</TableCell>
|
||||||
|
)}
|
||||||
|
<TableCell className="text-right tabular-nums font-medium">
|
||||||
|
<span className={cn('text-sm', isCredit ? 'text-green-600' : '')}>
|
||||||
|
{isCredit ? '+' : '-'}{formatCents(tx.amountCents)}
|
||||||
|
</span>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="text-sm text-muted-foreground">
|
||||||
|
{tx.category ?? '—'}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
{tx.budget ? (
|
||||||
|
<span className="flex items-center gap-1.5 text-sm">
|
||||||
|
{tx.budget.color && (
|
||||||
|
<span
|
||||||
|
className="inline-block h-2 w-2 rounded-full shrink-0"
|
||||||
|
style={{ backgroundColor: tx.budget.color }}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{tx.budget.name}
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
<span className="text-sm text-muted-foreground">—</span>
|
||||||
|
)}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<button
|
||||||
|
onClick={() => setEditing(tx)}
|
||||||
|
className="inline-flex h-7 w-7 items-center justify-center rounded-md hover:bg-accent transition-colors"
|
||||||
|
>
|
||||||
|
<Pencil className="h-3.5 w-3.5 text-muted-foreground" />
|
||||||
|
<span className="sr-only">Edit</span>
|
||||||
|
</button>
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Pagination */}
|
||||||
|
<div className="flex items-center justify-between py-3">
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
{total.toLocaleString()} transaction{total !== 1 ? 's' : ''}
|
||||||
|
{totalPages > 1 && ` · page ${page} of ${totalPages}`}
|
||||||
|
</p>
|
||||||
|
{totalPages > 1 && (
|
||||||
|
<div className="flex items-center gap-1">
|
||||||
|
{page > 1 ? (
|
||||||
|
<Link
|
||||||
|
href={pageHref(page - 1)}
|
||||||
|
className="inline-flex items-center gap-1 rounded-md border px-3 py-1.5 text-sm font-medium hover:bg-accent transition-colors"
|
||||||
|
>
|
||||||
|
<ChevronLeft className="h-4 w-4" />Prev
|
||||||
|
</Link>
|
||||||
|
) : (
|
||||||
|
<span className="inline-flex items-center gap-1 rounded-md border px-3 py-1.5 text-sm font-medium opacity-50 cursor-not-allowed">
|
||||||
|
<ChevronLeft className="h-4 w-4" />Prev
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{page < totalPages ? (
|
||||||
|
<Link
|
||||||
|
href={pageHref(page + 1)}
|
||||||
|
className="inline-flex items-center gap-1 rounded-md border px-3 py-1.5 text-sm font-medium hover:bg-accent transition-colors"
|
||||||
|
>
|
||||||
|
Next<ChevronRight className="h-4 w-4" />
|
||||||
|
</Link>
|
||||||
|
) : (
|
||||||
|
<span className="inline-flex items-center gap-1 rounded-md border px-3 py-1.5 text-sm font-medium opacity-50 cursor-not-allowed">
|
||||||
|
Next<ChevronRight className="h-4 w-4" />
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<EditTransactionDialog
|
||||||
|
transaction={editing}
|
||||||
|
onOpenChange={(open) => { if (!open) setEditing(null) }}
|
||||||
|
budgets={budgets}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
76
src/components/ui/alert.tsx
Normal file
76
src/components/ui/alert.tsx
Normal file
@@ -0,0 +1,76 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
import { cva, type VariantProps } from "class-variance-authority"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
const alertVariants = cva(
|
||||||
|
"group/alert relative grid w-full gap-0.5 rounded-lg border px-2.5 py-2 text-left text-sm has-data-[slot=alert-action]:relative has-data-[slot=alert-action]:pr-18 has-[>svg]:grid-cols-[auto_1fr] has-[>svg]:gap-x-2 *:[svg]:row-span-2 *:[svg]:translate-y-0.5 *:[svg]:text-current *:[svg:not([class*='size-'])]:size-4",
|
||||||
|
{
|
||||||
|
variants: {
|
||||||
|
variant: {
|
||||||
|
default: "bg-card text-card-foreground",
|
||||||
|
destructive:
|
||||||
|
"bg-card text-destructive *:data-[slot=alert-description]:text-destructive/90 *:[svg]:text-current",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
defaultVariants: {
|
||||||
|
variant: "default",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
function Alert({
|
||||||
|
className,
|
||||||
|
variant,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"div"> & VariantProps<typeof alertVariants>) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="alert"
|
||||||
|
role="alert"
|
||||||
|
className={cn(alertVariants({ variant }), className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function AlertTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="alert-title"
|
||||||
|
className={cn(
|
||||||
|
"font-medium group-has-[>svg]/alert:col-start-2 [&_a]:underline [&_a]:underline-offset-3 [&_a]:hover:text-foreground",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function AlertDescription({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="alert-description"
|
||||||
|
className={cn(
|
||||||
|
"text-sm text-balance text-muted-foreground md:text-pretty [&_a]:underline [&_a]:underline-offset-3 [&_a]:hover:text-foreground [&_p:not(:last-child)]:mb-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function AlertAction({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="alert-action"
|
||||||
|
className={cn("absolute top-2 right-2", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Alert, AlertTitle, AlertDescription, AlertAction }
|
||||||
52
src/components/ui/badge.tsx
Normal file
52
src/components/ui/badge.tsx
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
import { mergeProps } from "@base-ui/react/merge-props"
|
||||||
|
import { useRender } from "@base-ui/react/use-render"
|
||||||
|
import { cva, type VariantProps } from "class-variance-authority"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
const badgeVariants = cva(
|
||||||
|
"group/badge inline-flex h-5 w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-4xl border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-all focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3!",
|
||||||
|
{
|
||||||
|
variants: {
|
||||||
|
variant: {
|
||||||
|
default: "bg-primary text-primary-foreground [a]:hover:bg-primary/80",
|
||||||
|
secondary:
|
||||||
|
"bg-secondary text-secondary-foreground [a]:hover:bg-secondary/80",
|
||||||
|
destructive:
|
||||||
|
"bg-destructive/10 text-destructive focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:focus-visible:ring-destructive/40 [a]:hover:bg-destructive/20",
|
||||||
|
outline:
|
||||||
|
"border-border text-foreground [a]:hover:bg-muted [a]:hover:text-muted-foreground",
|
||||||
|
ghost:
|
||||||
|
"hover:bg-muted hover:text-muted-foreground dark:hover:bg-muted/50",
|
||||||
|
link: "text-primary underline-offset-4 hover:underline",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
defaultVariants: {
|
||||||
|
variant: "default",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
function Badge({
|
||||||
|
className,
|
||||||
|
variant = "default",
|
||||||
|
render,
|
||||||
|
...props
|
||||||
|
}: useRender.ComponentProps<"span"> & VariantProps<typeof badgeVariants>) {
|
||||||
|
return useRender({
|
||||||
|
defaultTagName: "span",
|
||||||
|
props: mergeProps<"span">(
|
||||||
|
{
|
||||||
|
className: cn(badgeVariants({ variant }), className),
|
||||||
|
},
|
||||||
|
props
|
||||||
|
),
|
||||||
|
render,
|
||||||
|
state: {
|
||||||
|
slot: "badge",
|
||||||
|
variant,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Badge, badgeVariants }
|
||||||
103
src/components/ui/card.tsx
Normal file
103
src/components/ui/card.tsx
Normal file
@@ -0,0 +1,103 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
function Card({
|
||||||
|
className,
|
||||||
|
size = "default",
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"div"> & { size?: "default" | "sm" }) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="card"
|
||||||
|
data-size={size}
|
||||||
|
className={cn(
|
||||||
|
"group/card flex flex-col gap-4 overflow-hidden rounded-xl bg-card py-4 text-sm text-card-foreground ring-1 ring-foreground/10 has-data-[slot=card-footer]:pb-0 has-[>img:first-child]:pt-0 data-[size=sm]:gap-3 data-[size=sm]:py-3 data-[size=sm]:has-data-[slot=card-footer]:pb-0 *:[img:first-child]:rounded-t-xl *:[img:last-child]:rounded-b-xl",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="card-header"
|
||||||
|
className={cn(
|
||||||
|
"group/card-header @container/card-header grid auto-rows-min items-start gap-1 rounded-t-xl px-4 group-data-[size=sm]/card:px-3 has-data-[slot=card-action]:grid-cols-[1fr_auto] has-data-[slot=card-description]:grid-rows-[auto_auto] [.border-b]:pb-4 group-data-[size=sm]/card:[.border-b]:pb-3",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="card-title"
|
||||||
|
className={cn(
|
||||||
|
"font-heading text-base leading-snug font-medium group-data-[size=sm]/card:text-sm",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="card-description"
|
||||||
|
className={cn("text-sm text-muted-foreground", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="card-action"
|
||||||
|
className={cn(
|
||||||
|
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="card-content"
|
||||||
|
className={cn("px-4 group-data-[size=sm]/card:px-3", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="card-footer"
|
||||||
|
className={cn(
|
||||||
|
"flex items-center rounded-b-xl border-t bg-muted/50 p-4 group-data-[size=sm]/card:p-3",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
Card,
|
||||||
|
CardHeader,
|
||||||
|
CardFooter,
|
||||||
|
CardTitle,
|
||||||
|
CardAction,
|
||||||
|
CardDescription,
|
||||||
|
CardContent,
|
||||||
|
}
|
||||||
160
src/components/ui/dialog.tsx
Normal file
160
src/components/ui/dialog.tsx
Normal file
@@ -0,0 +1,160 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import * as React from "react"
|
||||||
|
import { Dialog as DialogPrimitive } from "@base-ui/react/dialog"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
import { Button } from "@/components/ui/button"
|
||||||
|
import { XIcon } from "lucide-react"
|
||||||
|
|
||||||
|
function Dialog({ ...props }: DialogPrimitive.Root.Props) {
|
||||||
|
return <DialogPrimitive.Root data-slot="dialog" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function DialogTrigger({ ...props }: DialogPrimitive.Trigger.Props) {
|
||||||
|
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function DialogPortal({ ...props }: DialogPrimitive.Portal.Props) {
|
||||||
|
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function DialogClose({ ...props }: DialogPrimitive.Close.Props) {
|
||||||
|
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function DialogOverlay({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: DialogPrimitive.Backdrop.Props) {
|
||||||
|
return (
|
||||||
|
<DialogPrimitive.Backdrop
|
||||||
|
data-slot="dialog-overlay"
|
||||||
|
className={cn(
|
||||||
|
"fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DialogContent({
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
showCloseButton = true,
|
||||||
|
...props
|
||||||
|
}: DialogPrimitive.Popup.Props & {
|
||||||
|
showCloseButton?: boolean
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<DialogPortal>
|
||||||
|
<DialogOverlay />
|
||||||
|
<DialogPrimitive.Popup
|
||||||
|
data-slot="dialog-content"
|
||||||
|
className={cn(
|
||||||
|
"fixed top-1/2 left-1/2 z-50 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl bg-popover p-4 text-sm text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
{showCloseButton && (
|
||||||
|
<DialogPrimitive.Close
|
||||||
|
data-slot="dialog-close"
|
||||||
|
render={
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
className="absolute top-2 right-2"
|
||||||
|
size="icon-sm"
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<XIcon
|
||||||
|
/>
|
||||||
|
<span className="sr-only">Close</span>
|
||||||
|
</DialogPrimitive.Close>
|
||||||
|
)}
|
||||||
|
</DialogPrimitive.Popup>
|
||||||
|
</DialogPortal>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="dialog-header"
|
||||||
|
className={cn("flex flex-col gap-2", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DialogFooter({
|
||||||
|
className,
|
||||||
|
showCloseButton = false,
|
||||||
|
children,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"div"> & {
|
||||||
|
showCloseButton?: boolean
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="dialog-footer"
|
||||||
|
className={cn(
|
||||||
|
"-mx-4 -mb-4 flex flex-col-reverse gap-2 rounded-b-xl border-t bg-muted/50 p-4 sm:flex-row sm:justify-end",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
{showCloseButton && (
|
||||||
|
<DialogPrimitive.Close render={<Button variant="outline" />}>
|
||||||
|
Close
|
||||||
|
</DialogPrimitive.Close>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DialogTitle({ className, ...props }: DialogPrimitive.Title.Props) {
|
||||||
|
return (
|
||||||
|
<DialogPrimitive.Title
|
||||||
|
data-slot="dialog-title"
|
||||||
|
className={cn(
|
||||||
|
"font-heading text-base leading-none font-medium",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DialogDescription({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: DialogPrimitive.Description.Props) {
|
||||||
|
return (
|
||||||
|
<DialogPrimitive.Description
|
||||||
|
data-slot="dialog-description"
|
||||||
|
className={cn(
|
||||||
|
"text-sm text-muted-foreground *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
Dialog,
|
||||||
|
DialogClose,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogOverlay,
|
||||||
|
DialogPortal,
|
||||||
|
DialogTitle,
|
||||||
|
DialogTrigger,
|
||||||
|
}
|
||||||
268
src/components/ui/dropdown-menu.tsx
Normal file
268
src/components/ui/dropdown-menu.tsx
Normal file
@@ -0,0 +1,268 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import * as React from "react"
|
||||||
|
import { Menu as MenuPrimitive } from "@base-ui/react/menu"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
import { ChevronRightIcon, CheckIcon } from "lucide-react"
|
||||||
|
|
||||||
|
function DropdownMenu({ ...props }: MenuPrimitive.Root.Props) {
|
||||||
|
return <MenuPrimitive.Root data-slot="dropdown-menu" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuPortal({ ...props }: MenuPrimitive.Portal.Props) {
|
||||||
|
return <MenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuTrigger({ ...props }: MenuPrimitive.Trigger.Props) {
|
||||||
|
return <MenuPrimitive.Trigger data-slot="dropdown-menu-trigger" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuContent({
|
||||||
|
align = "start",
|
||||||
|
alignOffset = 0,
|
||||||
|
side = "bottom",
|
||||||
|
sideOffset = 4,
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: MenuPrimitive.Popup.Props &
|
||||||
|
Pick<
|
||||||
|
MenuPrimitive.Positioner.Props,
|
||||||
|
"align" | "alignOffset" | "side" | "sideOffset"
|
||||||
|
>) {
|
||||||
|
return (
|
||||||
|
<MenuPrimitive.Portal>
|
||||||
|
<MenuPrimitive.Positioner
|
||||||
|
className="isolate z-50 outline-none"
|
||||||
|
align={align}
|
||||||
|
alignOffset={alignOffset}
|
||||||
|
side={side}
|
||||||
|
sideOffset={sideOffset}
|
||||||
|
>
|
||||||
|
<MenuPrimitive.Popup
|
||||||
|
data-slot="dropdown-menu-content"
|
||||||
|
className={cn("z-50 max-h-(--available-height) w-(--anchor-width) min-w-32 origin-(--transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover p-1 text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 outline-none data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:overflow-hidden data-closed:fade-out-0 data-closed:zoom-out-95", className )}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
</MenuPrimitive.Positioner>
|
||||||
|
</MenuPrimitive.Portal>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuGroup({ ...props }: MenuPrimitive.Group.Props) {
|
||||||
|
return <MenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuLabel({
|
||||||
|
className,
|
||||||
|
inset,
|
||||||
|
...props
|
||||||
|
}: MenuPrimitive.GroupLabel.Props & {
|
||||||
|
inset?: boolean
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<MenuPrimitive.GroupLabel
|
||||||
|
data-slot="dropdown-menu-label"
|
||||||
|
data-inset={inset}
|
||||||
|
className={cn(
|
||||||
|
"px-1.5 py-1 text-xs font-medium text-muted-foreground data-inset:pl-7",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuItem({
|
||||||
|
className,
|
||||||
|
inset,
|
||||||
|
variant = "default",
|
||||||
|
...props
|
||||||
|
}: MenuPrimitive.Item.Props & {
|
||||||
|
inset?: boolean
|
||||||
|
variant?: "default" | "destructive"
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<MenuPrimitive.Item
|
||||||
|
data-slot="dropdown-menu-item"
|
||||||
|
data-inset={inset}
|
||||||
|
data-variant={variant}
|
||||||
|
className={cn(
|
||||||
|
"group/dropdown-menu-item relative flex cursor-default items-center gap-1.5 rounded-md px-1.5 py-1 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-inset:pl-7 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 data-[variant=destructive]:*:[svg]:text-destructive",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuSub({ ...props }: MenuPrimitive.SubmenuRoot.Props) {
|
||||||
|
return <MenuPrimitive.SubmenuRoot data-slot="dropdown-menu-sub" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuSubTrigger({
|
||||||
|
className,
|
||||||
|
inset,
|
||||||
|
children,
|
||||||
|
...props
|
||||||
|
}: MenuPrimitive.SubmenuTrigger.Props & {
|
||||||
|
inset?: boolean
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<MenuPrimitive.SubmenuTrigger
|
||||||
|
data-slot="dropdown-menu-sub-trigger"
|
||||||
|
data-inset={inset}
|
||||||
|
className={cn(
|
||||||
|
"flex cursor-default items-center gap-1.5 rounded-md px-1.5 py-1 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-inset:pl-7 data-popup-open:bg-accent data-popup-open:text-accent-foreground data-open:bg-accent data-open:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
<ChevronRightIcon className="ml-auto" />
|
||||||
|
</MenuPrimitive.SubmenuTrigger>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuSubContent({
|
||||||
|
align = "start",
|
||||||
|
alignOffset = -3,
|
||||||
|
side = "right",
|
||||||
|
sideOffset = 0,
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DropdownMenuContent>) {
|
||||||
|
return (
|
||||||
|
<DropdownMenuContent
|
||||||
|
data-slot="dropdown-menu-sub-content"
|
||||||
|
className={cn("w-auto min-w-[96px] rounded-lg bg-popover p-1 text-popover-foreground shadow-lg ring-1 ring-foreground/10 duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95", className )}
|
||||||
|
align={align}
|
||||||
|
alignOffset={alignOffset}
|
||||||
|
side={side}
|
||||||
|
sideOffset={sideOffset}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuCheckboxItem({
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
checked,
|
||||||
|
inset,
|
||||||
|
...props
|
||||||
|
}: MenuPrimitive.CheckboxItem.Props & {
|
||||||
|
inset?: boolean
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<MenuPrimitive.CheckboxItem
|
||||||
|
data-slot="dropdown-menu-checkbox-item"
|
||||||
|
data-inset={inset}
|
||||||
|
className={cn(
|
||||||
|
"relative flex cursor-default items-center gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground focus:**:text-accent-foreground data-inset:pl-7 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
checked={checked}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<span
|
||||||
|
className="pointer-events-none absolute right-2 flex items-center justify-center"
|
||||||
|
data-slot="dropdown-menu-checkbox-item-indicator"
|
||||||
|
>
|
||||||
|
<MenuPrimitive.CheckboxItemIndicator>
|
||||||
|
<CheckIcon
|
||||||
|
/>
|
||||||
|
</MenuPrimitive.CheckboxItemIndicator>
|
||||||
|
</span>
|
||||||
|
{children}
|
||||||
|
</MenuPrimitive.CheckboxItem>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuRadioGroup({ ...props }: MenuPrimitive.RadioGroup.Props) {
|
||||||
|
return (
|
||||||
|
<MenuPrimitive.RadioGroup
|
||||||
|
data-slot="dropdown-menu-radio-group"
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuRadioItem({
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
inset,
|
||||||
|
...props
|
||||||
|
}: MenuPrimitive.RadioItem.Props & {
|
||||||
|
inset?: boolean
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<MenuPrimitive.RadioItem
|
||||||
|
data-slot="dropdown-menu-radio-item"
|
||||||
|
data-inset={inset}
|
||||||
|
className={cn(
|
||||||
|
"relative flex cursor-default items-center gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground focus:**:text-accent-foreground data-inset:pl-7 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<span
|
||||||
|
className="pointer-events-none absolute right-2 flex items-center justify-center"
|
||||||
|
data-slot="dropdown-menu-radio-item-indicator"
|
||||||
|
>
|
||||||
|
<MenuPrimitive.RadioItemIndicator>
|
||||||
|
<CheckIcon
|
||||||
|
/>
|
||||||
|
</MenuPrimitive.RadioItemIndicator>
|
||||||
|
</span>
|
||||||
|
{children}
|
||||||
|
</MenuPrimitive.RadioItem>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuSeparator({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: MenuPrimitive.Separator.Props) {
|
||||||
|
return (
|
||||||
|
<MenuPrimitive.Separator
|
||||||
|
data-slot="dropdown-menu-separator"
|
||||||
|
className={cn("-mx-1 my-1 h-px bg-border", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuShortcut({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"span">) {
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
data-slot="dropdown-menu-shortcut"
|
||||||
|
className={cn(
|
||||||
|
"ml-auto text-xs tracking-widest text-muted-foreground group-focus/dropdown-menu-item:text-accent-foreground",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
DropdownMenu,
|
||||||
|
DropdownMenuPortal,
|
||||||
|
DropdownMenuTrigger,
|
||||||
|
DropdownMenuContent,
|
||||||
|
DropdownMenuGroup,
|
||||||
|
DropdownMenuLabel,
|
||||||
|
DropdownMenuItem,
|
||||||
|
DropdownMenuCheckboxItem,
|
||||||
|
DropdownMenuRadioGroup,
|
||||||
|
DropdownMenuRadioItem,
|
||||||
|
DropdownMenuSeparator,
|
||||||
|
DropdownMenuShortcut,
|
||||||
|
DropdownMenuSub,
|
||||||
|
DropdownMenuSubTrigger,
|
||||||
|
DropdownMenuSubContent,
|
||||||
|
}
|
||||||
20
src/components/ui/input.tsx
Normal file
20
src/components/ui/input.tsx
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
import { Input as InputPrimitive } from "@base-ui/react/input"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
|
||||||
|
return (
|
||||||
|
<InputPrimitive
|
||||||
|
type={type}
|
||||||
|
data-slot="input"
|
||||||
|
className={cn(
|
||||||
|
"h-8 w-full min-w-0 rounded-lg border border-input bg-transparent px-2.5 py-1 text-base transition-colors outline-none file:inline-flex file:h-6 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Input }
|
||||||
20
src/components/ui/label.tsx
Normal file
20
src/components/ui/label.tsx
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import * as React from "react"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
function Label({ className, ...props }: React.ComponentProps<"label">) {
|
||||||
|
return (
|
||||||
|
<label
|
||||||
|
data-slot="label"
|
||||||
|
className={cn(
|
||||||
|
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Label }
|
||||||
201
src/components/ui/select.tsx
Normal file
201
src/components/ui/select.tsx
Normal file
@@ -0,0 +1,201 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import * as React from "react"
|
||||||
|
import { Select as SelectPrimitive } from "@base-ui/react/select"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
import { ChevronDownIcon, CheckIcon, ChevronUpIcon } from "lucide-react"
|
||||||
|
|
||||||
|
const Select = SelectPrimitive.Root
|
||||||
|
|
||||||
|
function SelectGroup({ className, ...props }: SelectPrimitive.Group.Props) {
|
||||||
|
return (
|
||||||
|
<SelectPrimitive.Group
|
||||||
|
data-slot="select-group"
|
||||||
|
className={cn("scroll-my-1 p-1", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function SelectValue({ className, ...props }: SelectPrimitive.Value.Props) {
|
||||||
|
return (
|
||||||
|
<SelectPrimitive.Value
|
||||||
|
data-slot="select-value"
|
||||||
|
className={cn("flex flex-1 text-left", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function SelectTrigger({
|
||||||
|
className,
|
||||||
|
size = "default",
|
||||||
|
children,
|
||||||
|
...props
|
||||||
|
}: SelectPrimitive.Trigger.Props & {
|
||||||
|
size?: "sm" | "default"
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<SelectPrimitive.Trigger
|
||||||
|
data-slot="select-trigger"
|
||||||
|
data-size={size}
|
||||||
|
className={cn(
|
||||||
|
"flex w-fit items-center justify-between gap-1.5 rounded-lg border border-input bg-transparent py-2 pr-2 pl-2.5 text-sm whitespace-nowrap transition-colors outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-placeholder:text-muted-foreground data-[size=default]:h-8 data-[size=sm]:h-7 data-[size=sm]:rounded-[min(var(--radius-md),10px)] *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-1.5 dark:bg-input/30 dark:hover:bg-input/50 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
<SelectPrimitive.Icon
|
||||||
|
render={
|
||||||
|
<ChevronDownIcon className="pointer-events-none size-4 text-muted-foreground" />
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</SelectPrimitive.Trigger>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function SelectContent({
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
side = "bottom",
|
||||||
|
sideOffset = 4,
|
||||||
|
align = "center",
|
||||||
|
alignOffset = 0,
|
||||||
|
alignItemWithTrigger = true,
|
||||||
|
...props
|
||||||
|
}: SelectPrimitive.Popup.Props &
|
||||||
|
Pick<
|
||||||
|
SelectPrimitive.Positioner.Props,
|
||||||
|
"align" | "alignOffset" | "side" | "sideOffset" | "alignItemWithTrigger"
|
||||||
|
>) {
|
||||||
|
return (
|
||||||
|
<SelectPrimitive.Portal>
|
||||||
|
<SelectPrimitive.Positioner
|
||||||
|
side={side}
|
||||||
|
sideOffset={sideOffset}
|
||||||
|
align={align}
|
||||||
|
alignOffset={alignOffset}
|
||||||
|
alignItemWithTrigger={alignItemWithTrigger}
|
||||||
|
className="isolate z-50"
|
||||||
|
>
|
||||||
|
<SelectPrimitive.Popup
|
||||||
|
data-slot="select-content"
|
||||||
|
data-align-trigger={alignItemWithTrigger}
|
||||||
|
className={cn("relative isolate z-50 max-h-(--available-height) w-(--anchor-width) min-w-36 origin-(--transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[align-trigger=true]:animate-none data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95", className )}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<SelectScrollUpButton />
|
||||||
|
<SelectPrimitive.List>{children}</SelectPrimitive.List>
|
||||||
|
<SelectScrollDownButton />
|
||||||
|
</SelectPrimitive.Popup>
|
||||||
|
</SelectPrimitive.Positioner>
|
||||||
|
</SelectPrimitive.Portal>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function SelectLabel({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: SelectPrimitive.GroupLabel.Props) {
|
||||||
|
return (
|
||||||
|
<SelectPrimitive.GroupLabel
|
||||||
|
data-slot="select-label"
|
||||||
|
className={cn("px-1.5 py-1 text-xs text-muted-foreground", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function SelectItem({
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
...props
|
||||||
|
}: SelectPrimitive.Item.Props) {
|
||||||
|
return (
|
||||||
|
<SelectPrimitive.Item
|
||||||
|
data-slot="select-item"
|
||||||
|
className={cn(
|
||||||
|
"relative flex w-full cursor-default items-center gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<SelectPrimitive.ItemText className="flex flex-1 shrink-0 gap-2 whitespace-nowrap">
|
||||||
|
{children}
|
||||||
|
</SelectPrimitive.ItemText>
|
||||||
|
<SelectPrimitive.ItemIndicator
|
||||||
|
render={
|
||||||
|
<span className="pointer-events-none absolute right-2 flex size-4 items-center justify-center" />
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<CheckIcon className="pointer-events-none" />
|
||||||
|
</SelectPrimitive.ItemIndicator>
|
||||||
|
</SelectPrimitive.Item>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function SelectSeparator({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: SelectPrimitive.Separator.Props) {
|
||||||
|
return (
|
||||||
|
<SelectPrimitive.Separator
|
||||||
|
data-slot="select-separator"
|
||||||
|
className={cn("pointer-events-none -mx-1 my-1 h-px bg-border", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function SelectScrollUpButton({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof SelectPrimitive.ScrollUpArrow>) {
|
||||||
|
return (
|
||||||
|
<SelectPrimitive.ScrollUpArrow
|
||||||
|
data-slot="select-scroll-up-button"
|
||||||
|
className={cn(
|
||||||
|
"top-0 z-10 flex w-full cursor-default items-center justify-center bg-popover py-1 [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<ChevronUpIcon
|
||||||
|
/>
|
||||||
|
</SelectPrimitive.ScrollUpArrow>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function SelectScrollDownButton({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof SelectPrimitive.ScrollDownArrow>) {
|
||||||
|
return (
|
||||||
|
<SelectPrimitive.ScrollDownArrow
|
||||||
|
data-slot="select-scroll-down-button"
|
||||||
|
className={cn(
|
||||||
|
"bottom-0 z-10 flex w-full cursor-default items-center justify-center bg-popover py-1 [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<ChevronDownIcon
|
||||||
|
/>
|
||||||
|
</SelectPrimitive.ScrollDownArrow>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
Select,
|
||||||
|
SelectContent,
|
||||||
|
SelectGroup,
|
||||||
|
SelectItem,
|
||||||
|
SelectLabel,
|
||||||
|
SelectScrollDownButton,
|
||||||
|
SelectScrollUpButton,
|
||||||
|
SelectSeparator,
|
||||||
|
SelectTrigger,
|
||||||
|
SelectValue,
|
||||||
|
}
|
||||||
25
src/components/ui/separator.tsx
Normal file
25
src/components/ui/separator.tsx
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import { Separator as SeparatorPrimitive } from "@base-ui/react/separator"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
function Separator({
|
||||||
|
className,
|
||||||
|
orientation = "horizontal",
|
||||||
|
...props
|
||||||
|
}: SeparatorPrimitive.Props) {
|
||||||
|
return (
|
||||||
|
<SeparatorPrimitive
|
||||||
|
data-slot="separator"
|
||||||
|
orientation={orientation}
|
||||||
|
className={cn(
|
||||||
|
"shrink-0 bg-border data-horizontal:h-px data-horizontal:w-full data-vertical:w-px data-vertical:self-stretch",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Separator }
|
||||||
116
src/components/ui/table.tsx
Normal file
116
src/components/ui/table.tsx
Normal file
@@ -0,0 +1,116 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import * as React from "react"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
function Table({ className, ...props }: React.ComponentProps<"table">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="table-container"
|
||||||
|
className="relative w-full overflow-x-auto"
|
||||||
|
>
|
||||||
|
<table
|
||||||
|
data-slot="table"
|
||||||
|
className={cn("w-full caption-bottom text-sm", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function TableHeader({ className, ...props }: React.ComponentProps<"thead">) {
|
||||||
|
return (
|
||||||
|
<thead
|
||||||
|
data-slot="table-header"
|
||||||
|
className={cn("[&_tr]:border-b", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function TableBody({ className, ...props }: React.ComponentProps<"tbody">) {
|
||||||
|
return (
|
||||||
|
<tbody
|
||||||
|
data-slot="table-body"
|
||||||
|
className={cn("[&_tr:last-child]:border-0", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) {
|
||||||
|
return (
|
||||||
|
<tfoot
|
||||||
|
data-slot="table-footer"
|
||||||
|
className={cn(
|
||||||
|
"border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function TableRow({ className, ...props }: React.ComponentProps<"tr">) {
|
||||||
|
return (
|
||||||
|
<tr
|
||||||
|
data-slot="table-row"
|
||||||
|
className={cn(
|
||||||
|
"border-b transition-colors hover:bg-muted/50 has-aria-expanded:bg-muted/50 data-[state=selected]:bg-muted",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function TableHead({ className, ...props }: React.ComponentProps<"th">) {
|
||||||
|
return (
|
||||||
|
<th
|
||||||
|
data-slot="table-head"
|
||||||
|
className={cn(
|
||||||
|
"h-10 px-2 text-left align-middle font-medium whitespace-nowrap text-foreground [&:has([role=checkbox])]:pr-0",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function TableCell({ className, ...props }: React.ComponentProps<"td">) {
|
||||||
|
return (
|
||||||
|
<td
|
||||||
|
data-slot="table-cell"
|
||||||
|
className={cn(
|
||||||
|
"p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function TableCaption({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"caption">) {
|
||||||
|
return (
|
||||||
|
<caption
|
||||||
|
data-slot="table-caption"
|
||||||
|
className={cn("mt-4 text-sm text-muted-foreground", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
Table,
|
||||||
|
TableHeader,
|
||||||
|
TableBody,
|
||||||
|
TableFooter,
|
||||||
|
TableHead,
|
||||||
|
TableRow,
|
||||||
|
TableCell,
|
||||||
|
TableCaption,
|
||||||
|
}
|
||||||
18
src/components/ui/textarea.tsx
Normal file
18
src/components/ui/textarea.tsx
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
|
||||||
|
return (
|
||||||
|
<textarea
|
||||||
|
data-slot="textarea"
|
||||||
|
className={cn(
|
||||||
|
"flex field-sizing-content min-h-16 w-full rounded-lg border border-input bg-transparent px-2.5 py-2 text-base transition-colors outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Textarea }
|
||||||
146
src/components/upload/ColumnMapper.tsx
Normal file
146
src/components/upload/ColumnMapper.tsx
Normal file
@@ -0,0 +1,146 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { useState } from 'react'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Label } from '@/components/ui/label'
|
||||||
|
import {
|
||||||
|
Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
|
||||||
|
} from '@/components/ui/select'
|
||||||
|
import {
|
||||||
|
Table, TableBody, TableCell, TableHead, TableHeader, TableRow,
|
||||||
|
} from '@/components/ui/table'
|
||||||
|
import type { ColumnMapping } from '@/lib/validations/upload'
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
headers: string[]
|
||||||
|
sampleRows: Record<string, string>[]
|
||||||
|
onSubmit: (mapping: ColumnMapping) => void
|
||||||
|
loading: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ColumnMapper({ headers, sampleRows, onSubmit, loading }: Props) {
|
||||||
|
const [strategy, setStrategy] = useState<'A' | 'B'>('A')
|
||||||
|
const [dateCol, setDateCol] = useState('')
|
||||||
|
const [descCol, setDescCol] = useState('')
|
||||||
|
const [amountCol, setAmountCol] = useState('')
|
||||||
|
const [invertSign, setInvertSign] = useState(false)
|
||||||
|
const [debitCol, setDebitCol] = useState('')
|
||||||
|
const [creditCol, setCreditCol] = useState('')
|
||||||
|
|
||||||
|
function handleSubmit(e: React.FormEvent) {
|
||||||
|
e.preventDefault()
|
||||||
|
const mapping: ColumnMapping =
|
||||||
|
strategy === 'A'
|
||||||
|
? { strategy, dateColumn: dateCol, descriptionColumn: descCol, amountColumn: amountCol, invertAmountSign: invertSign }
|
||||||
|
: { strategy, dateColumn: dateCol, descriptionColumn: descCol, debitColumn: debitCol, creditColumn: creditCol }
|
||||||
|
onSubmit(mapping)
|
||||||
|
}
|
||||||
|
|
||||||
|
const canSubmit = dateCol && descCol && (strategy === 'A' ? amountCol : debitCol && creditCol)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div>
|
||||||
|
<h2 className="font-semibold">Map columns</h2>
|
||||||
|
<p className="text-sm text-muted-foreground mt-1">
|
||||||
|
We couldn't auto-detect the bank format. Map your CSV columns to the required fields.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Sample rows preview */}
|
||||||
|
{sampleRows.length > 0 && (
|
||||||
|
<div className="rounded-md border overflow-x-auto">
|
||||||
|
<Table>
|
||||||
|
<TableHeader>
|
||||||
|
<TableRow>
|
||||||
|
{headers.map((h) => <TableHead key={h}>{h}</TableHead>)}
|
||||||
|
</TableRow>
|
||||||
|
</TableHeader>
|
||||||
|
<TableBody>
|
||||||
|
{sampleRows.map((row, i) => (
|
||||||
|
<TableRow key={i}>
|
||||||
|
{headers.map((h) => <TableCell key={h} className="text-xs">{row[h] ?? ''}</TableCell>)}
|
||||||
|
</TableRow>
|
||||||
|
))}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<form onSubmit={handleSubmit} className="space-y-4">
|
||||||
|
<div className="grid gap-4 sm:grid-cols-2">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>Date column</Label>
|
||||||
|
<Select value={dateCol} onValueChange={(v) => setDateCol(v ?? '')} required>
|
||||||
|
<SelectTrigger><SelectValue placeholder="Select…" /></SelectTrigger>
|
||||||
|
<SelectContent>{headers.map((h) => <SelectItem key={h} value={h}>{h}</SelectItem>)}</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>Description column</Label>
|
||||||
|
<Select value={descCol} onValueChange={(v) => setDescCol(v ?? '')} required>
|
||||||
|
<SelectTrigger><SelectValue placeholder="Select…" /></SelectTrigger>
|
||||||
|
<SelectContent>{headers.map((h) => <SelectItem key={h} value={h}>{h}</SelectItem>)}</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>Amount format</Label>
|
||||||
|
<Select value={strategy} onValueChange={(v) => setStrategy(v as 'A' | 'B')}>
|
||||||
|
<SelectTrigger><SelectValue /></SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="A">Single amount column</SelectItem>
|
||||||
|
<SelectItem value="B">Separate debit and credit columns</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{strategy === 'A' && (
|
||||||
|
<div className="grid gap-4 sm:grid-cols-2">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>Amount column</Label>
|
||||||
|
<Select value={amountCol} onValueChange={(v) => setAmountCol(v ?? '')} required>
|
||||||
|
<SelectTrigger><SelectValue placeholder="Select…" /></SelectTrigger>
|
||||||
|
<SelectContent>{headers.map((h) => <SelectItem key={h} value={h}>{h}</SelectItem>)}</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>Sign convention</Label>
|
||||||
|
<Select value={invertSign ? 'invert' : 'normal'} onValueChange={(v) => setInvertSign(v === 'invert')}>
|
||||||
|
<SelectTrigger><SelectValue /></SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="normal">Positive = spending (debit)</SelectItem>
|
||||||
|
<SelectItem value="invert">Negative = spending (debit)</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{strategy === 'B' && (
|
||||||
|
<div className="grid gap-4 sm:grid-cols-2">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>Debit column</Label>
|
||||||
|
<Select value={debitCol} onValueChange={(v) => setDebitCol(v ?? '')} required>
|
||||||
|
<SelectTrigger><SelectValue placeholder="Select…" /></SelectTrigger>
|
||||||
|
<SelectContent>{headers.map((h) => <SelectItem key={h} value={h}>{h}</SelectItem>)}</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>Credit column</Label>
|
||||||
|
<Select value={creditCol} onValueChange={(v) => setCreditCol(v ?? '')} required>
|
||||||
|
<SelectTrigger><SelectValue placeholder="Select…" /></SelectTrigger>
|
||||||
|
<SelectContent>{headers.map((h) => <SelectItem key={h} value={h}>{h}</SelectItem>)}</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Button type="submit" disabled={!canSubmit || loading}>
|
||||||
|
{loading ? 'Importing…' : 'Import'}
|
||||||
|
</Button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
57
src/components/upload/UploadDropzone.tsx
Normal file
57
src/components/upload/UploadDropzone.tsx
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { useRef, useState } from 'react'
|
||||||
|
import { Upload } from 'lucide-react'
|
||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
onFile: (file: File) => void
|
||||||
|
disabled?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export function UploadDropzone({ onFile, disabled }: Props) {
|
||||||
|
const inputRef = useRef<HTMLInputElement>(null)
|
||||||
|
const [dragging, setDragging] = useState(false)
|
||||||
|
|
||||||
|
function handleDrop(e: React.DragEvent) {
|
||||||
|
e.preventDefault()
|
||||||
|
setDragging(false)
|
||||||
|
if (disabled) return
|
||||||
|
const file = e.dataTransfer.files[0]
|
||||||
|
if (file) onFile(file)
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleChange(e: React.ChangeEvent<HTMLInputElement>) {
|
||||||
|
const file = e.target.files?.[0]
|
||||||
|
if (file) onFile(file)
|
||||||
|
e.target.value = ''
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
onClick={() => !disabled && inputRef.current?.click()}
|
||||||
|
onDragOver={(e) => { e.preventDefault(); if (!disabled) setDragging(true) }}
|
||||||
|
onDragLeave={() => setDragging(false)}
|
||||||
|
onDrop={handleDrop}
|
||||||
|
className={cn(
|
||||||
|
'flex cursor-pointer flex-col items-center justify-center gap-3 rounded-lg border-2 border-dashed p-12 transition-colors',
|
||||||
|
dragging ? 'border-primary bg-primary/5' : 'border-muted-foreground/25 hover:border-muted-foreground/50',
|
||||||
|
disabled && 'pointer-events-none opacity-50',
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<Upload className="h-8 w-8 text-muted-foreground" />
|
||||||
|
<div className="text-center">
|
||||||
|
<p className="text-sm font-medium">Drop a CSV file here or click to browse</p>
|
||||||
|
<p className="text-xs text-muted-foreground mt-1">Max 10 MB · .csv files only</p>
|
||||||
|
</div>
|
||||||
|
<input
|
||||||
|
ref={inputRef}
|
||||||
|
type="file"
|
||||||
|
accept=".csv"
|
||||||
|
className="hidden"
|
||||||
|
onChange={handleChange}
|
||||||
|
disabled={disabled}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
137
src/components/upload/UploadForm.tsx
Normal file
137
src/components/upload/UploadForm.tsx
Normal file
@@ -0,0 +1,137 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { useState } from 'react'
|
||||||
|
import { Label } from '@/components/ui/label'
|
||||||
|
import {
|
||||||
|
Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
|
||||||
|
} from '@/components/ui/select'
|
||||||
|
import { Alert, AlertDescription } from '@/components/ui/alert'
|
||||||
|
import { AlertCircle } from 'lucide-react'
|
||||||
|
import { UploadDropzone } from './UploadDropzone'
|
||||||
|
import { ColumnMapper } from './ColumnMapper'
|
||||||
|
import { UploadPreview } from './UploadPreview'
|
||||||
|
import type { ColumnMapping } from '@/lib/validations/upload'
|
||||||
|
|
||||||
|
interface AccountOption {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
accounts: AccountOption[]
|
||||||
|
}
|
||||||
|
|
||||||
|
type Stage =
|
||||||
|
| { status: 'idle' }
|
||||||
|
| { status: 'uploading' }
|
||||||
|
| { status: 'mapping'; headers: string[]; sampleRows: Record<string, string>[]; file: File }
|
||||||
|
| { status: 'result'; fileName: string; detected?: string; importedCount: number; skippedCount: number }
|
||||||
|
| { status: 'error'; message: string }
|
||||||
|
|
||||||
|
export function UploadForm({ accounts }: Props) {
|
||||||
|
const [accountId, setAccountId] = useState(accounts[0]?.id ?? '')
|
||||||
|
const [stage, setStage] = useState<Stage>({ status: 'idle' })
|
||||||
|
|
||||||
|
async function submit(file: File, columnMapping?: ColumnMapping) {
|
||||||
|
if (!accountId) return
|
||||||
|
setStage({ status: 'uploading' })
|
||||||
|
|
||||||
|
const formData = new FormData()
|
||||||
|
formData.append('file', file)
|
||||||
|
formData.append('accountId', accountId)
|
||||||
|
if (columnMapping) formData.append('columnMapping', JSON.stringify(columnMapping))
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/upload', { method: 'POST', body: formData })
|
||||||
|
const data = await res.json()
|
||||||
|
|
||||||
|
if (!res.ok) {
|
||||||
|
setStage({ status: 'error', message: data.error ?? 'Upload failed' })
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if (data.requiresMapping) {
|
||||||
|
setStage({ status: 'mapping', headers: data.headers, sampleRows: data.sampleRows, file })
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
setStage({
|
||||||
|
status: 'result',
|
||||||
|
fileName: data.fileName,
|
||||||
|
detected: data.detected,
|
||||||
|
importedCount: data.importedCount,
|
||||||
|
skippedCount: data.skippedCount,
|
||||||
|
})
|
||||||
|
} catch {
|
||||||
|
setStage({ status: 'error', message: 'Network error. Please try again.' })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleFile(file: File) {
|
||||||
|
submit(file)
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleMapping(mapping: ColumnMapping) {
|
||||||
|
if (stage.status === 'mapping') {
|
||||||
|
submit(stage.file, mapping)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (stage.status === 'result') {
|
||||||
|
return (
|
||||||
|
<UploadPreview
|
||||||
|
{...stage}
|
||||||
|
onReset={() => setStage({ status: 'idle' })}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="account">Account</Label>
|
||||||
|
{accounts.length === 0 ? (
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
No active accounts found. Create one in Accounts first.
|
||||||
|
</p>
|
||||||
|
) : (
|
||||||
|
<Select value={accountId} onValueChange={(v) => setAccountId(v ?? '')}>
|
||||||
|
<SelectTrigger id="account" className="w-72">
|
||||||
|
<SelectValue placeholder="Select account" />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
{accounts.map((a) => (
|
||||||
|
<SelectItem key={a.id} value={a.id}>{a.name}</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{stage.status === 'error' && (
|
||||||
|
<Alert variant="destructive">
|
||||||
|
<AlertCircle className="h-4 w-4" />
|
||||||
|
<AlertDescription>{stage.message}</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{stage.status === 'mapping' ? (
|
||||||
|
<ColumnMapper
|
||||||
|
headers={stage.headers}
|
||||||
|
sampleRows={stage.sampleRows}
|
||||||
|
onSubmit={handleMapping}
|
||||||
|
loading={false}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<UploadDropzone
|
||||||
|
onFile={handleFile}
|
||||||
|
disabled={!accountId || stage.status === 'uploading'}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{stage.status === 'uploading' && (
|
||||||
|
<p className="text-sm text-muted-foreground text-center">Importing…</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
30
src/components/upload/UploadPreview.tsx
Normal file
30
src/components/upload/UploadPreview.tsx
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
import { CheckCircle } from 'lucide-react'
|
||||||
|
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
fileName: string
|
||||||
|
detected?: string
|
||||||
|
importedCount: number
|
||||||
|
skippedCount: number
|
||||||
|
onReset: () => void
|
||||||
|
}
|
||||||
|
|
||||||
|
export function UploadPreview({ fileName, detected, importedCount, skippedCount, onReset }: Props) {
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<Alert>
|
||||||
|
<CheckCircle className="h-4 w-4" />
|
||||||
|
<AlertTitle>Import complete — {fileName}</AlertTitle>
|
||||||
|
<AlertDescription className="mt-1 space-y-1">
|
||||||
|
{detected && <p>Detected: <span className="font-medium">{detected}</span></p>}
|
||||||
|
<p>{importedCount} transaction{importedCount !== 1 ? 's' : ''} imported</p>
|
||||||
|
{skippedCount > 0 && (
|
||||||
|
<p className="text-muted-foreground">{skippedCount} duplicate{skippedCount !== 1 ? 's' : ''} skipped</p>
|
||||||
|
)}
|
||||||
|
</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
<Button variant="outline" onClick={onReset}>Upload another file</Button>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
54
src/lib/auth.ts
Normal file
54
src/lib/auth.ts
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
import NextAuth from 'next-auth'
|
||||||
|
import Credentials from 'next-auth/providers/credentials'
|
||||||
|
import bcrypt from 'bcryptjs'
|
||||||
|
import { z } from 'zod'
|
||||||
|
import { prisma } from '@/lib/prisma'
|
||||||
|
|
||||||
|
const loginSchema = z.object({
|
||||||
|
email: z.string().email(),
|
||||||
|
password: z.string().min(1),
|
||||||
|
})
|
||||||
|
|
||||||
|
export const { handlers, signIn, signOut, auth } = NextAuth({
|
||||||
|
providers: [
|
||||||
|
Credentials({
|
||||||
|
credentials: {
|
||||||
|
email: { label: 'Email', type: 'email' },
|
||||||
|
password: { label: 'Password', type: 'password' },
|
||||||
|
},
|
||||||
|
async authorize(credentials) {
|
||||||
|
const parsed = loginSchema.safeParse(credentials)
|
||||||
|
if (!parsed.success) return null
|
||||||
|
|
||||||
|
const { email, password } = parsed.data
|
||||||
|
|
||||||
|
const user = await prisma.user.findUnique({ where: { email } })
|
||||||
|
if (!user) return null
|
||||||
|
|
||||||
|
const valid = await bcrypt.compare(password, user.passwordHash)
|
||||||
|
if (!valid) return null
|
||||||
|
|
||||||
|
return { id: user.id, email: user.email }
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
session: {
|
||||||
|
strategy: 'jwt',
|
||||||
|
maxAge: 60 * 60, // 1 hour
|
||||||
|
},
|
||||||
|
secret: process.env.NEXTAUTH_SECRET,
|
||||||
|
trustHost: true,
|
||||||
|
pages: {
|
||||||
|
signIn: '/login',
|
||||||
|
},
|
||||||
|
callbacks: {
|
||||||
|
jwt({ token, user }) {
|
||||||
|
if (user) token.id = user.id
|
||||||
|
return token
|
||||||
|
},
|
||||||
|
session({ session, token }) {
|
||||||
|
if (token.id) session.user.id = token.id as string
|
||||||
|
return session
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
77
src/lib/csv/bank-profiles.ts
Normal file
77
src/lib/csv/bank-profiles.ts
Normal file
@@ -0,0 +1,77 @@
|
|||||||
|
export type ParseStrategy = 'A' | 'B'
|
||||||
|
|
||||||
|
export interface NormalizerConfig {
|
||||||
|
strategy: ParseStrategy
|
||||||
|
dateColumn: string
|
||||||
|
descriptionColumn: string
|
||||||
|
// Strategy A
|
||||||
|
amountColumn?: string
|
||||||
|
invertAmountSign?: boolean
|
||||||
|
// Strategy B
|
||||||
|
debitColumn?: string
|
||||||
|
creditColumn?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BankProfile extends NormalizerConfig {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
accountType: 'BANK' | 'CREDIT_CARD'
|
||||||
|
detectColumns: string[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export const bankProfiles: BankProfile[] = [
|
||||||
|
{
|
||||||
|
id: 'discover-savings',
|
||||||
|
name: 'Discover High Yield Savings',
|
||||||
|
accountType: 'BANK',
|
||||||
|
strategy: 'B',
|
||||||
|
dateColumn: 'Transaction Date',
|
||||||
|
descriptionColumn: 'Transaction Description',
|
||||||
|
debitColumn: 'Debit',
|
||||||
|
creditColumn: 'Credit',
|
||||||
|
detectColumns: ['Transaction Date', 'Transaction Description', 'Debit', 'Credit', 'Balance'],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'discover-cc',
|
||||||
|
name: 'Discover Credit Card',
|
||||||
|
accountType: 'CREDIT_CARD',
|
||||||
|
strategy: 'A',
|
||||||
|
dateColumn: 'Trans. Date',
|
||||||
|
descriptionColumn: 'Description',
|
||||||
|
amountColumn: 'Amount',
|
||||||
|
invertAmountSign: false, // positive = DEBIT (charge), negative = CREDIT (payment)
|
||||||
|
detectColumns: ['Trans. Date', 'Post Date', 'Description', 'Amount', 'Category'],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'huntington-checking',
|
||||||
|
name: 'Huntington Checking',
|
||||||
|
accountType: 'BANK',
|
||||||
|
strategy: 'A',
|
||||||
|
dateColumn: 'Date',
|
||||||
|
descriptionColumn: 'Description',
|
||||||
|
amountColumn: 'Amount',
|
||||||
|
invertAmountSign: true, // negative = DEBIT, positive = CREDIT
|
||||||
|
detectColumns: ['Date', 'Description', 'Amount', 'Split', 'Tags'],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'fidelity',
|
||||||
|
name: 'Fidelity',
|
||||||
|
accountType: 'BANK',
|
||||||
|
strategy: 'A',
|
||||||
|
dateColumn: 'Run Date',
|
||||||
|
descriptionColumn: 'Description',
|
||||||
|
amountColumn: 'Amount($)',
|
||||||
|
invertAmountSign: true, // negative = DEBIT (purchase), positive = CREDIT
|
||||||
|
detectColumns: ['Run Date', 'Description', 'Amount($)'],
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
export function detectProfile(headers: string[]): BankProfile | null {
|
||||||
|
const headerSet = new Set(headers.map((h) => h.trim()))
|
||||||
|
for (const profile of bankProfiles) {
|
||||||
|
if (profile.detectColumns.every((col) => headerSet.has(col))) {
|
||||||
|
return profile
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
108
src/lib/csv/normalizer.ts
Normal file
108
src/lib/csv/normalizer.ts
Normal file
@@ -0,0 +1,108 @@
|
|||||||
|
import { createHash } from 'crypto'
|
||||||
|
import type { NormalizerConfig } from './bank-profiles'
|
||||||
|
|
||||||
|
export interface NormalizedRow {
|
||||||
|
date: Date
|
||||||
|
description: string
|
||||||
|
amountCents: number
|
||||||
|
type: 'DEBIT' | 'CREDIT'
|
||||||
|
dedupeHash: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parseCents(raw: string): number {
|
||||||
|
const cleaned = raw.replace(/[$,\s]/g, '')
|
||||||
|
if (!cleaned || cleaned === '-') return 0
|
||||||
|
return Math.round(parseFloat(cleaned) * 100)
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseDate(raw: string): Date {
|
||||||
|
const trimmed = raw.trim()
|
||||||
|
// MM/DD/YYYY
|
||||||
|
if (/^\d{1,2}\/\d{1,2}\/\d{4}$/.test(trimmed)) {
|
||||||
|
const [m, d, y] = trimmed.split('/')
|
||||||
|
return new Date(parseInt(y), parseInt(m) - 1, parseInt(d))
|
||||||
|
}
|
||||||
|
const date = new Date(trimmed)
|
||||||
|
if (!isNaN(date.getTime())) return date
|
||||||
|
throw new Error(`Cannot parse date: ${raw}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
function strategyA(
|
||||||
|
raw: string,
|
||||||
|
invertAmountSign: boolean,
|
||||||
|
): { amountCents: number; type: 'DEBIT' | 'CREDIT' } {
|
||||||
|
const cents = parseCents(raw)
|
||||||
|
const isPositive = cents >= 0
|
||||||
|
// invertAmountSign=false: positive=DEBIT (e.g. Discover CC)
|
||||||
|
// invertAmountSign=true: positive=CREDIT, negative=DEBIT (e.g. Huntington, Fidelity)
|
||||||
|
const type = invertAmountSign
|
||||||
|
? isPositive ? 'CREDIT' : 'DEBIT'
|
||||||
|
: isPositive ? 'DEBIT' : 'CREDIT'
|
||||||
|
return { amountCents: Math.abs(cents), type }
|
||||||
|
}
|
||||||
|
|
||||||
|
function strategyB(
|
||||||
|
debitRaw: string,
|
||||||
|
creditRaw: string,
|
||||||
|
): { amountCents: number; type: 'DEBIT' | 'CREDIT' } {
|
||||||
|
const debit = parseCents(debitRaw)
|
||||||
|
if (debit > 0) return { amountCents: debit, type: 'DEBIT' }
|
||||||
|
return { amountCents: Math.abs(parseCents(creditRaw)), type: 'CREDIT' }
|
||||||
|
}
|
||||||
|
|
||||||
|
function dedupeHash(
|
||||||
|
accountId: string,
|
||||||
|
date: Date,
|
||||||
|
description: string,
|
||||||
|
amountCents: number,
|
||||||
|
): string {
|
||||||
|
const dateStr = date.toISOString().split('T')[0]
|
||||||
|
return createHash('sha256')
|
||||||
|
.update(`${accountId}|${dateStr}|${description}|${amountCents}`)
|
||||||
|
.digest('hex')
|
||||||
|
}
|
||||||
|
|
||||||
|
export function normalizeRows(
|
||||||
|
rows: Record<string, string>[],
|
||||||
|
accountId: string,
|
||||||
|
config: NormalizerConfig,
|
||||||
|
): NormalizedRow[] {
|
||||||
|
const out: NormalizedRow[] = []
|
||||||
|
|
||||||
|
for (const row of rows) {
|
||||||
|
try {
|
||||||
|
const date = parseDate(row[config.dateColumn] ?? '')
|
||||||
|
const description = (row[config.descriptionColumn] ?? '').trim()
|
||||||
|
if (!description) continue
|
||||||
|
|
||||||
|
let amountCents: number
|
||||||
|
let type: 'DEBIT' | 'CREDIT'
|
||||||
|
|
||||||
|
if (config.strategy === 'A' && config.amountColumn) {
|
||||||
|
const r = strategyA(row[config.amountColumn] ?? '0', config.invertAmountSign ?? false)
|
||||||
|
amountCents = r.amountCents
|
||||||
|
type = r.type
|
||||||
|
} else if (config.strategy === 'B' && config.debitColumn && config.creditColumn) {
|
||||||
|
const r = strategyB(row[config.debitColumn] ?? '', row[config.creditColumn] ?? '')
|
||||||
|
amountCents = r.amountCents
|
||||||
|
type = r.type
|
||||||
|
} else {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if (amountCents === 0) continue
|
||||||
|
|
||||||
|
out.push({
|
||||||
|
date,
|
||||||
|
description,
|
||||||
|
amountCents,
|
||||||
|
type,
|
||||||
|
dedupeHash: dedupeHash(accountId, date, description, amountCents),
|
||||||
|
})
|
||||||
|
} catch {
|
||||||
|
// skip unparseable rows
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return out
|
||||||
|
}
|
||||||
26
src/lib/csv/parser.ts
Normal file
26
src/lib/csv/parser.ts
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
import Papa from 'papaparse'
|
||||||
|
import { detectProfile, BankProfile } from './bank-profiles'
|
||||||
|
|
||||||
|
export type ParsedRow = Record<string, string>
|
||||||
|
|
||||||
|
export type ParseResult =
|
||||||
|
| { detected: BankProfile; headers: string[]; rows: ParsedRow[] }
|
||||||
|
| { requiresMapping: true; headers: string[]; sampleRows: ParsedRow[] }
|
||||||
|
|
||||||
|
export function parseCsvContent(content: string): ParseResult {
|
||||||
|
const result = Papa.parse<ParsedRow>(content, {
|
||||||
|
header: true,
|
||||||
|
skipEmptyLines: true,
|
||||||
|
transformHeader: (h) => h.trim(),
|
||||||
|
})
|
||||||
|
|
||||||
|
const headers = (result.meta.fields ?? []).map((h) => h.trim())
|
||||||
|
const rows = result.data
|
||||||
|
|
||||||
|
const detected = detectProfile(headers)
|
||||||
|
if (detected) {
|
||||||
|
return { detected, headers, rows }
|
||||||
|
}
|
||||||
|
|
||||||
|
return { requiresMapping: true, headers, sampleRows: rows.slice(0, 5) }
|
||||||
|
}
|
||||||
15
src/lib/prisma.ts
Normal file
15
src/lib/prisma.ts
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
import { Pool } from 'pg'
|
||||||
|
import { PrismaPg } from '@prisma/adapter-pg'
|
||||||
|
import { PrismaClient } from '@/generated/prisma/client'
|
||||||
|
|
||||||
|
const globalForPrisma = globalThis as unknown as { prisma: PrismaClient }
|
||||||
|
|
||||||
|
function createPrismaClient() {
|
||||||
|
const pool = new Pool({ connectionString: process.env.DATABASE_URL })
|
||||||
|
const adapter = new PrismaPg(pool)
|
||||||
|
return new PrismaClient({ adapter })
|
||||||
|
}
|
||||||
|
|
||||||
|
export const prisma = globalForPrisma.prisma ?? createPrismaClient()
|
||||||
|
|
||||||
|
if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma
|
||||||
14
src/lib/utils/currency.ts
Normal file
14
src/lib/utils/currency.ts
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
export function formatCents(cents: number, currency = 'USD'): string {
|
||||||
|
return new Intl.NumberFormat('en-US', {
|
||||||
|
style: 'currency',
|
||||||
|
currency,
|
||||||
|
}).format(cents / 100)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatCentsAbbrev(cents: number): string {
|
||||||
|
const dollars = Math.abs(cents / 100)
|
||||||
|
const sign = cents < 0 ? '-' : ''
|
||||||
|
if (dollars >= 1_000_000) return `${sign}$${(dollars / 1_000_000).toFixed(1)}M`
|
||||||
|
if (dollars >= 1_000) return `${sign}$${(dollars / 1_000).toFixed(0)}K`
|
||||||
|
return `${sign}$${dollars.toFixed(0)}`
|
||||||
|
}
|
||||||
19
src/lib/utils/dates.ts
Normal file
19
src/lib/utils/dates.ts
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
export function monthBounds(date = new Date()): { start: Date; end: Date } {
|
||||||
|
return {
|
||||||
|
start: new Date(date.getFullYear(), date.getMonth(), 1),
|
||||||
|
end: new Date(date.getFullYear(), date.getMonth() + 1, 0, 23, 59, 59, 999),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function monthLabel(date = new Date()): string {
|
||||||
|
return date.toLocaleDateString('en-US', { month: 'long', year: 'numeric' })
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatYearMonth(year: number, month: number): string {
|
||||||
|
return new Date(year, month - 1, 1).toLocaleDateString('en-US', { month: 'short', year: '2-digit' })
|
||||||
|
}
|
||||||
|
|
||||||
|
export function lastNMonthsStart(n: number): Date {
|
||||||
|
const now = new Date()
|
||||||
|
return new Date(now.getFullYear(), now.getMonth() - (n - 1), 1)
|
||||||
|
}
|
||||||
17
src/lib/validations/account.ts
Normal file
17
src/lib/validations/account.ts
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
import { z } from 'zod'
|
||||||
|
|
||||||
|
export const createAccountSchema = z.object({
|
||||||
|
name: z.string().min(1, 'Name is required').max(100),
|
||||||
|
institution: z.string().max(100).optional(),
|
||||||
|
type: z.enum(['BANK', 'CREDIT_CARD']),
|
||||||
|
currency: z.string().length(3).default('USD'),
|
||||||
|
})
|
||||||
|
|
||||||
|
export const updateAccountSchema = z.object({
|
||||||
|
name: z.string().min(1).max(100).optional(),
|
||||||
|
institution: z.string().max(100).nullable().optional(),
|
||||||
|
isActive: z.boolean().optional(),
|
||||||
|
})
|
||||||
|
|
||||||
|
export type CreateAccountInput = z.infer<typeof createAccountSchema>
|
||||||
|
export type UpdateAccountInput = z.infer<typeof updateAccountSchema>
|
||||||
17
src/lib/validations/budget.ts
Normal file
17
src/lib/validations/budget.ts
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
import { z } from 'zod'
|
||||||
|
|
||||||
|
export const createBudgetSchema = z.object({
|
||||||
|
name: z.string().min(1, 'Name is required').max(100),
|
||||||
|
limitCents: z.number().int().positive().nullable().optional(),
|
||||||
|
color: z.string().regex(/^#[0-9a-fA-F]{6}$/).nullable().optional(),
|
||||||
|
})
|
||||||
|
|
||||||
|
export const updateBudgetSchema = z.object({
|
||||||
|
name: z.string().min(1).max(100).optional(),
|
||||||
|
limitCents: z.number().int().positive().nullable().optional(),
|
||||||
|
color: z.string().regex(/^#[0-9a-fA-F]{6}$/).nullable().optional(),
|
||||||
|
isActive: z.boolean().optional(),
|
||||||
|
})
|
||||||
|
|
||||||
|
export type CreateBudgetInput = z.infer<typeof createBudgetSchema>
|
||||||
|
export type UpdateBudgetInput = z.infer<typeof updateBudgetSchema>
|
||||||
21
src/lib/validations/transaction.ts
Normal file
21
src/lib/validations/transaction.ts
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
import { z } from 'zod'
|
||||||
|
|
||||||
|
export const transactionQuerySchema = z.object({
|
||||||
|
accountId: z.string().optional(),
|
||||||
|
dateFrom: z.string().optional(),
|
||||||
|
dateTo: z.string().optional(),
|
||||||
|
type: z.enum(['DEBIT', 'CREDIT']).optional(),
|
||||||
|
search: z.string().optional(),
|
||||||
|
budgetId: z.string().optional(),
|
||||||
|
page: z.coerce.number().min(1).default(1),
|
||||||
|
limit: z.coerce.number().min(1).max(100).default(50),
|
||||||
|
})
|
||||||
|
|
||||||
|
export const updateTransactionSchema = z.object({
|
||||||
|
notes: z.string().nullable().optional(),
|
||||||
|
category: z.string().max(100).nullable().optional(),
|
||||||
|
budgetId: z.string().nullable().optional(),
|
||||||
|
})
|
||||||
|
|
||||||
|
export type TransactionQuery = z.infer<typeof transactionQuerySchema>
|
||||||
|
export type UpdateTransactionInput = z.infer<typeof updateTransactionSchema>
|
||||||
13
src/lib/validations/upload.ts
Normal file
13
src/lib/validations/upload.ts
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
import { z } from 'zod'
|
||||||
|
|
||||||
|
export const columnMappingSchema = z.object({
|
||||||
|
strategy: z.enum(['A', 'B']),
|
||||||
|
dateColumn: z.string().min(1),
|
||||||
|
descriptionColumn: z.string().min(1),
|
||||||
|
amountColumn: z.string().optional(),
|
||||||
|
invertAmountSign: z.boolean().optional(),
|
||||||
|
debitColumn: z.string().optional(),
|
||||||
|
creditColumn: z.string().optional(),
|
||||||
|
})
|
||||||
|
|
||||||
|
export type ColumnMapping = z.infer<typeof columnMappingSchema>
|
||||||
85
src/middleware.ts
Normal file
85
src/middleware.ts
Normal file
@@ -0,0 +1,85 @@
|
|||||||
|
import { auth } from '@/lib/auth'
|
||||||
|
import { NextResponse, type NextRequest } from 'next/server'
|
||||||
|
|
||||||
|
// Process-local store — adequate for a self-hosted single-instance deployment.
|
||||||
|
const rateLimitStore = new Map<string, { count: number; resetAt: number }>()
|
||||||
|
const RATE_LIMIT = 10
|
||||||
|
const RATE_WINDOW_MS = 15 * 60 * 1000
|
||||||
|
|
||||||
|
function clientIp(req: NextRequest): string {
|
||||||
|
return (
|
||||||
|
req.headers.get('x-forwarded-for')?.split(',')[0].trim() ??
|
||||||
|
req.headers.get('x-real-ip') ??
|
||||||
|
'unknown'
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function isRateLimited(ip: string): boolean {
|
||||||
|
const now = Date.now()
|
||||||
|
const rec = rateLimitStore.get(ip)
|
||||||
|
if (!rec || now > rec.resetAt) {
|
||||||
|
rateLimitStore.set(ip, { count: 1, resetAt: now + RATE_WINDOW_MS })
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if (rec.count >= RATE_LIMIT) return true
|
||||||
|
rec.count++
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
function hasValidOrigin(req: NextRequest): boolean {
|
||||||
|
const origin = req.headers.get('origin')
|
||||||
|
if (!origin) return true // non-browser (curl, server-to-server)
|
||||||
|
const expected = process.env.NEXTAUTH_URL
|
||||||
|
? new URL(process.env.NEXTAUTH_URL).origin
|
||||||
|
: req.nextUrl.origin
|
||||||
|
return origin === expected
|
||||||
|
}
|
||||||
|
|
||||||
|
export default auth((req) => {
|
||||||
|
const { pathname } = req.nextUrl
|
||||||
|
const method = req.method
|
||||||
|
|
||||||
|
// Rate-limit login POST before anything else
|
||||||
|
if (pathname === '/api/auth/callback/credentials' && method === 'POST') {
|
||||||
|
if (isRateLimited(clientIp(req))) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: 'Too many login attempts. Try again in 15 minutes.' },
|
||||||
|
{ status: 429 },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Let NextAuth handle its own routes
|
||||||
|
if (pathname.startsWith('/api/auth')) return NextResponse.next()
|
||||||
|
|
||||||
|
// Origin check on all state-mutating API calls
|
||||||
|
if (
|
||||||
|
pathname.startsWith('/api/') &&
|
||||||
|
['POST', 'PUT', 'PATCH', 'DELETE'].includes(method)
|
||||||
|
) {
|
||||||
|
if (!hasValidOrigin(req)) {
|
||||||
|
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Auth gate
|
||||||
|
const isLoggedIn = !!req.auth
|
||||||
|
if (!isLoggedIn) {
|
||||||
|
if (pathname.startsWith('/api/')) {
|
||||||
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||||
|
}
|
||||||
|
const loginUrl = new URL('/login', req.nextUrl.origin)
|
||||||
|
loginUrl.searchParams.set('callbackUrl', pathname)
|
||||||
|
return NextResponse.redirect(loginUrl)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (pathname === '/login') {
|
||||||
|
return NextResponse.redirect(new URL('/dashboard', req.nextUrl.origin))
|
||||||
|
}
|
||||||
|
|
||||||
|
return NextResponse.next()
|
||||||
|
})
|
||||||
|
|
||||||
|
export const config = {
|
||||||
|
matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user