first build commit

This commit is contained in:
2026-04-19 00:44:43 -04:00
parent bc271b7ce1
commit 55debd082b
82 changed files with 6217 additions and 97 deletions

View 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>
)
}

View 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}
/>
</>
)
}

View 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>
)
}

View 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>
)
}

View 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} />
</>
)
}

View 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>
)
}

View 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>
)
}

View 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>
)
}

View 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>
)
}

View 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>
)
}

View 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>
)
}

View 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>
)
}

View 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>
)
}

View 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>
)
}

View 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>
)
}

View 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>
)
}

View 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>
)
}

View 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>
)
}

View 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>
)
}

View 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>
)
}

View 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}
/>
</>
)
}

View 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 }

View 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
View 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,
}

View 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,
}

View 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,
}

View 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 }

View 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 }

View 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,
}

View 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
View 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,
}

View 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 }

View 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&apos;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>
)
}

View 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>
)
}

View 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>
)
}

View 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>
)
}