diff --git a/apps/api/package.json b/apps/api/package.json index 3c62cbed7962a5b87722afc2bb4130b3b4fde7c5..06e9720fc7087d4ef37bdd1970e6335e2a94a945 100644 --- a/apps/api/package.json +++ b/apps/api/package.json @@ -21,14 +21,18 @@ "@llm-router/shared": "workspace:*", "@neondatabase/serverless": "^1.1.0", "@types/express": "^5.0.6", + "bcrypt": "^6.0.0", "dotenv": "^17.4.2", "drizzle-orm": "^0.45.2", "express": "^5.2.1", + "jsonwebtoken": "^9.0.3", "ollama": "^0.6.3", "tesseract.js": "^5.1.0", "zod": "^4.4.3" }, "devDependencies": { + "@types/bcrypt": "^6.0.0", + "@types/jsonwebtoken": "^9.0.10", "@types/node": "^25.6.0", "drizzle-kit": "^0.31.10", "tsx": "^4.21.0", diff --git a/apps/api/src/auth/auth.routes.ts b/apps/api/src/auth/auth.routes.ts new file mode 100644 index 0000000000000000000000000000000000000000..42e3705c05b68d279996484434918809c535cf8d --- /dev/null +++ b/apps/api/src/auth/auth.routes.ts @@ -0,0 +1,39 @@ +import { Router, type IRouter } from 'express' +import bcrypt from 'bcrypt' +import jwt from 'jsonwebtoken' + +const router: IRouter = Router() + +router.post('/auth/login', async (req, res) => { + const { email, password } = req.body as { email?: string; password?: string } + + if (!email || !password) { + res.status(400).json({ error: 'email and password required' }) + return + } + + const expectedEmail = process.env['ADMIN_EMAIL'] + const passwordHash = process.env['ADMIN_PASSWORD_HASH'] + const jwtSecret = process.env['JWT_SECRET'] + + if (!expectedEmail || !passwordHash || !jwtSecret) { + res.status(500).json({ error: 'Server auth not configured' }) + return + } + + if (email !== expectedEmail) { + res.status(401).json({ error: 'Invalid credentials' }) + return + } + + const valid = await bcrypt.compare(password, passwordHash) + if (!valid) { + res.status(401).json({ error: 'Invalid credentials' }) + return + } + + const token = jwt.sign({ sub: 'admin' }, jwtSecret, { expiresIn: '7d' }) + res.json({ token }) +}) + +export { router as authRouter } diff --git a/apps/api/src/middleware/authMiddleware.ts b/apps/api/src/middleware/authMiddleware.ts index 2eba25cc5fa0000a6d8a7a95632d40fcf47482d8..16b0b23eb4da897f22b1044cae34111329da90d8 100644 --- a/apps/api/src/middleware/authMiddleware.ts +++ b/apps/api/src/middleware/authMiddleware.ts @@ -1,13 +1,26 @@ -import { Request, Response, NextFunction, RequestHandler } from 'express' +import type { Request, Response, NextFunction } from 'express' +import jwt from 'jsonwebtoken' export const authMiddleware = (req: Request, res: Response, next: NextFunction) => { if (req.path === '/health') return next() - const key = req.headers['x-internal-key'] as string - const bearerKey = (req.headers['authorization'] as string)?.replace('Bearer', '').trim() - const expected = process.env.INTERNAL_SECRET - if (expected && key !== expected && bearerKey !== expected) { - return res.status(401).json({ error: 'Unauthorized' }) + const key = req.headers['x-internal-key'] as string | undefined + const bearerToken = (req.headers['authorization'] as string | undefined) + ?.replace(/^Bearer\s+/i, '') + .trim() + const expectedKey = process.env['INTERNAL_SECRET'] + const jwtSecret = process.env['JWT_SECRET'] + + if (expectedKey && (key === expectedKey || bearerToken === expectedKey)) return next() + + if (jwtSecret && bearerToken) { + try { + jwt.verify(bearerToken, jwtSecret) + return next() + } catch { + // invalid JWT — fall through to 401 + } } - next() -} \ No newline at end of file + + res.status(401).json({ error: 'Unauthorized' }) +} diff --git a/apps/api/src/proxy.ts b/apps/api/src/proxy.ts index 820ac88f30cdaf444b219f1b8360f8a205c81018..14b4661f2ba602cd556f7390259844268b99ebd6 100644 --- a/apps/api/src/proxy.ts +++ b/apps/api/src/proxy.ts @@ -1,6 +1,7 @@ import 'dotenv/config' import express from 'express' import { authMiddleware } from './middleware/authMiddleware' +import { authRouter } from './auth/auth.routes' import { chatRouter } from './chat/chat.routes' import { expenseRouter } from './expense/expense.routes' import { healthRouter } from './health/health.routes' @@ -15,13 +16,14 @@ app.use(express.raw({ limit: '50mb', type: ['image/*', 'application/octet-stream app.use((req, res, next) => { res.setHeader('Access-Control-Allow-Origin', '*') - res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS') + res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS') res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, x-internal-key') if (req.method === 'OPTIONS') { res.sendStatus(204); return } next() }) -app.use(authMiddleware) +app.use(authRouter) // /auth/login is public +app.use(authMiddleware) // all other routes require auth app.use(healthRouter) app.use('/v1', chatRouter) diff --git a/apps/expense-dashboard/components.json b/apps/expense-dashboard/components.json new file mode 100644 index 0000000000000000000000000000000000000000..3b7e53db506fda3a5696e65599742920803dbb9c --- /dev/null +++ b/apps/expense-dashboard/components.json @@ -0,0 +1,23 @@ +{ + "$schema": "https://ui.shadcn.com/schema.json", + "style": "default", + "rsc": false, + "tsx": true, + "tailwind": { + "config": "tailwind.config.ts", + "css": "src/index.css", + "baseColor": "slate", + "cssVariables": true + }, + "aliases": { + "components": "@/components", + "utils": "@/lib/utils" + }, + "resolvedPaths": { + "tailwindConfig": "/Users/sumyatmon/Documents/Projects/exercise/llm_router/apps/expense-dashboard/tailwind.config.ts", + "tailwindCss": "/Users/sumyatmon/Documents/Projects/exercise/llm_router/apps/expense-dashboard/src/index.css", + "utils": "/Users/sumyatmon/Documents/Projects/exercise/llm_router/apps/expense-dashboard/src/lib/utils", + "components": "/Users/sumyatmon/Documents/Projects/exercise/llm_router/apps/expense-dashboard/src/components", + "ui": "/Users/sumyatmon/Documents/Projects/exercise/llm_router/apps/expense-dashboard/src/components/ui" + } +} diff --git a/apps/expense-dashboard/index.html b/apps/expense-dashboard/index.html new file mode 100644 index 0000000000000000000000000000000000000000..cd332cdd5c99c1406b6fed32d32eef036f8a58c6 --- /dev/null +++ b/apps/expense-dashboard/index.html @@ -0,0 +1,12 @@ + + + + + + Expense Dashboard + + +
+ + + diff --git a/apps/expense-dashboard/package.json b/apps/expense-dashboard/package.json new file mode 100644 index 0000000000000000000000000000000000000000..cb950a7cef7b3661d2adc7a8e3894d4c5cf2ffaa --- /dev/null +++ b/apps/expense-dashboard/package.json @@ -0,0 +1,40 @@ +{ + "name": "@llm-router/expense-dashboard", + "version": "0.1.0", + "private": true, + "type": "module", + "scripts": { + "dev": "vite", + "build": "tsc -b && vite build", + "preview": "vite preview" + }, + "dependencies": { + "@llm-router/shared": "workspace:*", + "@radix-ui/react-dialog": "^1.1.18", + "@radix-ui/react-label": "^2.1.11", + "@radix-ui/react-progress": "^1.1.11", + "@radix-ui/react-select": "^2.3.2", + "@radix-ui/react-separator": "^1.1.11", + "@radix-ui/react-slot": "^1.3.0", + "@radix-ui/react-tabs": "^1.1.16", + "class-variance-authority": "^0.7.1", + "clsx": "^2.1.1", + "lucide-react": "^0.462.0", + "react": "^18.3.1", + "react-dom": "^18.3.1", + "react-router-dom": "^6.28.0", + "recharts": "^2.13.0", + "tailwind-merge": "^2.5.4" + }, + "devDependencies": { + "@types/node": "^22.0.0", + "@types/react": "^18.3.12", + "@types/react-dom": "^18.3.1", + "@vitejs/plugin-react": "^4.3.3", + "autoprefixer": "^10.4.20", + "postcss": "^8.4.47", + "tailwindcss": "^3.4.14", + "typescript": "^5.6.3", + "vite": "^5.4.10" + } +} diff --git a/apps/expense-dashboard/postcss.config.js b/apps/expense-dashboard/postcss.config.js new file mode 100644 index 0000000000000000000000000000000000000000..be56e0e63a60151c9e1870053f93a2b274fe0bca --- /dev/null +++ b/apps/expense-dashboard/postcss.config.js @@ -0,0 +1,3 @@ +export default { + plugins: { tailwindcss: {}, autoprefixer: {} }, +} diff --git a/apps/expense-dashboard/src/App.tsx b/apps/expense-dashboard/src/App.tsx new file mode 100644 index 0000000000000000000000000000000000000000..95071468ccfa7d8758d023e479b762ec8b2a0ba7 --- /dev/null +++ b/apps/expense-dashboard/src/App.tsx @@ -0,0 +1,5 @@ +import AppRouter from './router' + +export default function App() { + return +} diff --git a/apps/expense-dashboard/src/api/analytics.ts b/apps/expense-dashboard/src/api/analytics.ts new file mode 100644 index 0000000000000000000000000000000000000000..384cd40d2989ced7178cc95d658ecc6f32b451d6 --- /dev/null +++ b/apps/expense-dashboard/src/api/analytics.ts @@ -0,0 +1,14 @@ +import { apiFetch } from './client' +import type { Summary, Trends } from '@llm-router/shared' + +export async function getSummary(): Promise { + const res = await apiFetch('/v1/expense/summary') + if (!res.ok) throw new Error('Failed to load summary') + return res.json() as Promise +} + +export async function getTrends(months = 6): Promise { + const res = await apiFetch(`/v1/expense/trends?months=${months}`) + if (!res.ok) throw new Error('Failed to load trends') + return res.json() as Promise +} diff --git a/apps/expense-dashboard/src/api/auth.ts b/apps/expense-dashboard/src/api/auth.ts new file mode 100644 index 0000000000000000000000000000000000000000..1821645c4cce38874ae197ddc7216e950218daac --- /dev/null +++ b/apps/expense-dashboard/src/api/auth.ts @@ -0,0 +1,13 @@ +import { apiFetch } from './client' + +export async function login(email: string, password: string): Promise<{ token: string }> { + const res = await apiFetch('/auth/login', { + method: 'POST', + body: JSON.stringify({ email, password }), + }) + if (!res.ok) { + const err = await res.json() as { error?: string } + throw new Error(err.error ?? 'Login failed') + } + return res.json() as Promise<{ token: string }> +} diff --git a/apps/expense-dashboard/src/api/budgets.ts b/apps/expense-dashboard/src/api/budgets.ts new file mode 100644 index 0000000000000000000000000000000000000000..d5e31098469542d0df93b71558f40a1666cc28fc --- /dev/null +++ b/apps/expense-dashboard/src/api/budgets.ts @@ -0,0 +1,37 @@ +import { apiFetch } from './client' +import type { Budget, CreateBudget, UpdateBudget } from '@llm-router/shared' + +export async function listBudgets(): Promise { + const res = await apiFetch('/v1/expense/budgets') + if (!res.ok) throw new Error('Failed to load budgets') + return res.json() as Promise +} + +export async function createBudget(data: CreateBudget): Promise { + const res = await apiFetch('/v1/expense/budgets', { + method: 'POST', + body: JSON.stringify(data), + }) + if (!res.ok) { + const err = await res.json() as { error?: string } + throw new Error(err.error ?? 'Failed to create budget') + } + return res.json() as Promise +} + +export async function updateBudget(id: string, data: UpdateBudget): Promise { + const res = await apiFetch(`/v1/expense/budgets/${id}`, { + method: 'PUT', + body: JSON.stringify(data), + }) + if (!res.ok) { + const err = await res.json() as { error?: string } + throw new Error(err.error ?? 'Failed to update budget') + } + return res.json() as Promise +} + +export async function deleteBudget(id: string): Promise { + const res = await apiFetch(`/v1/expense/budgets/${id}`, { method: 'DELETE' }) + if (!res.ok) throw new Error('Failed to delete budget') +} diff --git a/apps/expense-dashboard/src/api/categories.ts b/apps/expense-dashboard/src/api/categories.ts new file mode 100644 index 0000000000000000000000000000000000000000..5ad850079d6d7be857d647a57beb89fc7f77abfe --- /dev/null +++ b/apps/expense-dashboard/src/api/categories.ts @@ -0,0 +1,40 @@ +import { apiFetch } from './client' +import type { Category, CreateCategory, UpdateCategory } from '@llm-router/shared' + +export async function listCategories(): Promise { + const res = await apiFetch('/v1/expense/categories') + if (!res.ok) throw new Error('Failed to load categories') + return res.json() as Promise +} + +export async function createCategory(data: CreateCategory): Promise { + const res = await apiFetch('/v1/expense/categories', { + method: 'POST', + body: JSON.stringify(data), + }) + if (!res.ok) { + const err = await res.json() as { error?: string } + throw new Error(err.error ?? 'Failed to create category') + } + return res.json() as Promise +} + +export async function updateCategory(id: string, data: UpdateCategory): Promise { + const res = await apiFetch(`/v1/expense/categories/${id}`, { + method: 'PUT', + body: JSON.stringify(data), + }) + if (!res.ok) { + const err = await res.json() as { error?: string } + throw new Error(err.error ?? 'Failed to update category') + } + return res.json() as Promise +} + +export async function deleteCategory(id: string): Promise { + const res = await apiFetch(`/v1/expense/categories/${id}`, { method: 'DELETE' }) + if (!res.ok) { + const err = await res.json() as { error?: string } + throw new Error(err.error ?? 'Failed to delete category') + } +} diff --git a/apps/expense-dashboard/src/api/client.ts b/apps/expense-dashboard/src/api/client.ts new file mode 100644 index 0000000000000000000000000000000000000000..ee32e0376ed3e7875ca0e01bc90ae890eaf1a335 --- /dev/null +++ b/apps/expense-dashboard/src/api/client.ts @@ -0,0 +1,20 @@ +import { getToken, clearToken } from '@/lib/auth' + +export async function apiFetch(path: string, options: RequestInit = {}): Promise { + const token = getToken() + const res = await fetch(path, { + ...options, + headers: { + 'Content-Type': 'application/json', + ...(token ? { Authorization: `Bearer ${token}` } : {}), + ...(options.headers as Record | undefined ?? {}), + }, + }) + + if (res.status === 401) { + clearToken() + window.location.href = '/login' + } + + return res +} diff --git a/apps/expense-dashboard/src/api/expenses.ts b/apps/expense-dashboard/src/api/expenses.ts new file mode 100644 index 0000000000000000000000000000000000000000..8e2dcff7e537b6518984c13b737a92b89c6ac959 --- /dev/null +++ b/apps/expense-dashboard/src/api/expenses.ts @@ -0,0 +1,76 @@ +import { apiFetch } from './client' +import { monthRange } from '@/lib/dates' +import type { Expense, CreateExpense, UpdateExpense } from '@llm-router/shared' + +export interface ParsedExpenseResult { + amount: number + currency: string + date: string | null + merchant: string | null + category: string + confidence: number + raw_description: string +} + +export interface ParseReceiptResponse { + success: boolean + expense: ParsedExpenseResult + ocrUsed: boolean +} + +export async function parseReceipt(data: { text?: string; image?: string }): Promise { + const res = await apiFetch('/v1/expense/parse', { + method: 'POST', + body: JSON.stringify(data), + }) + if (!res.ok) { + const err = await res.json() as { error?: string } + throw new Error(err.error ?? 'Failed to parse receipt') + } + return res.json() as Promise +} + +export async function createExpense(data: CreateExpense): Promise { + const res = await apiFetch('/v1/expense/manual', { + method: 'POST', + body: JSON.stringify(data), + }) + if (!res.ok) { + const err = await res.json() as { error?: string } + throw new Error(err.error ?? 'Failed to create expense') + } + return res.json() as Promise +} + +export interface ListExpensesResult { + data: Expense[] + total: number + page: number + limit: number +} + +export async function listExpenses(month: string): Promise { + const { from, to } = monthRange(month) + const params = new URLSearchParams({ from, to, limit: '200' }) + const res = await apiFetch(`/v1/expense?${params.toString()}`) + if (!res.ok) throw new Error('Failed to load expenses') + const result = await res.json() as ListExpensesResult + return result.data +} + +export async function updateExpense(id: string, data: UpdateExpense): Promise { + const res = await apiFetch(`/v1/expense/${id}`, { + method: 'PUT', + body: JSON.stringify(data), + }) + if (!res.ok) { + const err = await res.json() as { error?: string } + throw new Error(err.error ?? 'Failed to update expense') + } + return res.json() as Promise +} + +export async function deleteExpense(id: string): Promise { + const res = await apiFetch(`/v1/expense/${id}`, { method: 'DELETE' }) + if (!res.ok) throw new Error('Failed to delete expense') +} diff --git a/apps/expense-dashboard/src/components/analytics/BudgetCard.tsx b/apps/expense-dashboard/src/components/analytics/BudgetCard.tsx new file mode 100644 index 0000000000000000000000000000000000000000..4e0129d9e10917d5521d30a2f9e20cb070f6e252 --- /dev/null +++ b/apps/expense-dashboard/src/components/analytics/BudgetCard.tsx @@ -0,0 +1,38 @@ +import { Card, CardContent } from '@/components/ui/card' +import { Progress } from '@/components/ui/progress' +import { cn } from '@/lib/utils' +import type { SummaryItem } from '@llm-router/shared' + +interface Props { item: SummaryItem } + +export default function BudgetCard({ item }: Props) { + const hasBudget = item.budget !== null && item.budget > 0 + const pct = hasBudget ? Math.min((item.spent / (item.budget ?? 1)) * 100, 100) : 0 + const statusColor = pct >= 100 ? 'text-destructive' : pct >= 80 ? 'text-yellow-600' : 'text-green-600' + + return ( + + +
+
+ + {item.category_name} +
+ + ฿{item.spent.toLocaleString()} + {hasBudget && / ฿{(item.budget ?? 0).toLocaleString()}} + +
+ {hasBudget && ( + = 100 ? '[&>div]:bg-destructive' : pct >= 80 ? '[&>div]:bg-yellow-500' : '')} + /> + )} + {!hasBudget && ( +

No budget set

+ )} +
+
+ ) +} diff --git a/apps/expense-dashboard/src/components/analytics/DailyBarChart.tsx b/apps/expense-dashboard/src/components/analytics/DailyBarChart.tsx new file mode 100644 index 0000000000000000000000000000000000000000..738495a38415f02878a1281f98682a1d51a5de15 --- /dev/null +++ b/apps/expense-dashboard/src/components/analytics/DailyBarChart.tsx @@ -0,0 +1,32 @@ +import { BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer, CartesianGrid } from 'recharts' +import type { Expense } from '@llm-router/shared' + +interface Props { expenses: Expense[] } + +export default function DailyBarChart({ expenses }: Props) { + const grouped = expenses.reduce>((acc, e) => { + const day = e.date.slice(8, 10) // DD from YYYY-MM-DD + acc[day] = (acc[day] ?? 0) + Number(e.amount) + return acc + }, {}) + + const data = Object.entries(grouped) + .sort(([a], [b]) => a.localeCompare(b)) + .map(([day, total]) => ({ day, total })) + + if (data.length === 0) { + return
No data
+ } + + return ( + + + + + + `฿${v.toLocaleString()}`} /> + + + + ) +} diff --git a/apps/expense-dashboard/src/components/analytics/SpendDonut.tsx b/apps/expense-dashboard/src/components/analytics/SpendDonut.tsx new file mode 100644 index 0000000000000000000000000000000000000000..4c01f7fa43979c1598daf76f2a3d738f7990ac55 --- /dev/null +++ b/apps/expense-dashboard/src/components/analytics/SpendDonut.tsx @@ -0,0 +1,38 @@ +import { PieChart, Pie, Cell, Tooltip, Legend, ResponsiveContainer } from 'recharts' +import type { SummaryItem } from '@llm-router/shared' + +interface Props { categories: SummaryItem[] } + +export default function SpendDonut({ categories }: Props) { + const data = categories.filter(c => c.spent > 0).map(c => ({ + name: c.category_name, + value: c.spent, + color: c.color, + })) + + if (data.length === 0) { + return
No spend data
+ } + + return ( + + + + {data.map((entry, i) => ( + + ))} + + `฿${v.toLocaleString()}`} /> + + + + ) +} diff --git a/apps/expense-dashboard/src/components/expenses/AddExpenseDrawer.tsx b/apps/expense-dashboard/src/components/expenses/AddExpenseDrawer.tsx new file mode 100644 index 0000000000000000000000000000000000000000..698feee7f261db88cdddc43a572d137bf5826d02 --- /dev/null +++ b/apps/expense-dashboard/src/components/expenses/AddExpenseDrawer.tsx @@ -0,0 +1,253 @@ +import { useState, useRef } from 'react' +import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog' +import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs' +import { Button } from '@/components/ui/button' +import { Input } from '@/components/ui/input' +import { Label } from '@/components/ui/label' +import CategoryPicker from './CategoryPicker' +import ReceiptPreview from './ReceiptPreview' +import { parseReceipt } from '@/api/expenses' +import type { Category, CreateExpense } from '@llm-router/shared' +import type { ParsedExpenseResult } from '@/api/expenses' + +interface Props { + open: boolean + onOpenChange: (open: boolean) => void + categories: Category[] + onSave: (data: CreateExpense) => Promise +} + +function ManualTab({ categories, onSave, onClose }: { + categories: Category[] + onSave: (data: CreateExpense) => Promise + onClose: () => void +}) { + const today = new Date().toISOString().slice(0, 10) + const [amount, setAmount] = useState('') + const [currency, setCurrency] = useState('THB') + const [merchant, setMerchant] = useState('') + const [date, setDate] = useState(today) + const [categoryId, setCategoryId] = useState('') + const [description, setDescription] = useState('') + const [saving, setSaving] = useState(false) + const [error, setError] = useState(null) + + async function handleSave() { + const amt = Number(amount) + if (!amount || isNaN(amt) || amt <= 0) { setError('Enter a valid amount'); return } + if (!categoryId) { setError('Select a category'); return } + if (!date) { setError('Enter a date'); return } + setSaving(true) + setError(null) + try { + await onSave({ + amount: amt, + currency, + category_id: categoryId, + date, + ...(merchant.trim() ? { merchant: merchant.trim() } : {}), + ...(description.trim() ? { description: description.trim() } : {}), + }) + onClose() + } catch (err) { + setError(err instanceof Error ? err.message : 'Save failed') + } finally { + setSaving(false) + } + } + + return ( +
+
+
+ + setAmount(e.target.value)} placeholder="350" autoFocus /> +
+
+ + setCurrency(e.target.value)} placeholder="THB" /> +
+
+
+ + setMerchant(e.target.value)} placeholder="Grab Food" /> +
+
+ + setDate(e.target.value)} /> +
+
+ + +
+
+ + setDescription(e.target.value)} placeholder="Business lunch" /> +
+ {error &&

{error}

} +
+ + +
+
+ ) +} + +function UploadTab({ categories, onSave, onClose }: { + categories: Category[] + onSave: (data: CreateExpense) => Promise + onClose: () => void +}) { + const fileRef = useRef(null) + const [description, setDescription] = useState('') + const [imageFile, setImageFile] = useState(null) + const [imagePreview, setImagePreview] = useState(null) + const [parsing, setParsing] = useState(false) + const [parsed, setParsed] = useState<{ result: ParsedExpenseResult; ocrUsed: boolean } | null>(null) + const [saving, setSaving] = useState(false) + const [error, setError] = useState(null) + + function handleFileChange(e: React.ChangeEvent) { + const file = e.target.files?.[0] + if (!file) return + setImageFile(file) + const reader = new FileReader() + reader.onload = ev => setImagePreview(ev.target?.result as string) + reader.readAsDataURL(file) + } + + async function handleParse() { + if (!imageFile && !description.trim()) { + setError('Provide a receipt image, description, or both') + return + } + setParsing(true) + setError(null) + try { + let imageBase64: string | undefined + if (imageFile && imagePreview) { + // strip "data:image/...;base64," prefix + imageBase64 = imagePreview.split(',')[1] ?? imagePreview + } + const res = await parseReceipt({ + ...(description.trim() ? { text: description.trim() } : {}), + ...(imageBase64 ? { image: imageBase64 } : {}), + }) + setParsed({ result: res.expense, ocrUsed: res.ocrUsed }) + } catch (err) { + setError(err instanceof Error ? err.message : 'Parse failed') + } finally { + setParsing(false) + } + } + + async function handleConfirm(categoryId: string) { + if (!parsed) return + const today = new Date().toISOString().slice(0, 10) + setSaving(true) + try { + await onSave({ + amount: parsed.result.amount, + currency: parsed.result.currency || 'THB', + category_id: categoryId, + date: parsed.result.date ?? today, + ...(parsed.result.merchant ? { merchant: parsed.result.merchant } : {}), + ...(description.trim() ? { description: description.trim() } : {}), + }) + onClose() + } catch (err) { + setError(err instanceof Error ? err.message : 'Save failed') + setSaving(false) + } + } + + if (parsed) { + return ( + setParsed(null)} + saving={saving} + /> + ) + } + + return ( +
+
+ +
fileRef.current?.click()} + > + {imagePreview ? ( + receipt + ) : ( +

Click to upload or drag & drop
JPEG / PNG

+ )} +
+ +
+
+ + setDescription(e.target.value)} + placeholder="e.g. Grab food 350 baht, business lunch" + /> +
+ {error &&

{error}

} +
+ + +
+
+ ) +} + +export default function AddExpenseDrawer({ open, onOpenChange, categories, onSave }: Props) { + const [tabKey, setTabKey] = useState(0) + + function handleOpenChange(newOpen: boolean) { + if (!newOpen) setTabKey(k => k + 1) + onOpenChange(newOpen) + } + + return ( + + + + Add Expense + + + + Upload Receipt + Manual Entry + + + onOpenChange(false)} + /> + + + onOpenChange(false)} + /> + + + + + ) +} diff --git a/apps/expense-dashboard/src/components/expenses/CategoryPicker.tsx b/apps/expense-dashboard/src/components/expenses/CategoryPicker.tsx new file mode 100644 index 0000000000000000000000000000000000000000..9b33e42cba6534970239cdd11b6c001ed937bb9d --- /dev/null +++ b/apps/expense-dashboard/src/components/expenses/CategoryPicker.tsx @@ -0,0 +1,29 @@ +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select' +import type { Category } from '@llm-router/shared' + +interface Props { + categories: Category[] + value: string + onChange: (id: string) => void + placeholder?: string +} + +export default function CategoryPicker({ categories, value, onChange, placeholder = 'Select category…' }: Props) { + return ( + + ) +} diff --git a/apps/expense-dashboard/src/components/expenses/ExpenseList.tsx b/apps/expense-dashboard/src/components/expenses/ExpenseList.tsx new file mode 100644 index 0000000000000000000000000000000000000000..2dfc4df4155342af2cd8592f58af2a1719fc086b --- /dev/null +++ b/apps/expense-dashboard/src/components/expenses/ExpenseList.tsx @@ -0,0 +1,55 @@ +import ExpenseRow from './ExpenseRow' +import type { Expense, Category } from '@llm-router/shared' + +interface Props { + expenses: Expense[] + categories: Category[] + onUpdate: (id: string, data: Partial<{ amount: number; merchant: string; date: string; category_id: string; description: string }>) => Promise + onDelete: (id: string) => Promise +} + +export default function ExpenseList({ expenses, categories, onUpdate, onDelete }: Props) { + if (expenses.length === 0) { + return

No expenses this month.

+ } + + // Group by date descending + const grouped = expenses.reduce>((acc, e) => { + const key = e.date + if (!acc[key]) acc[key] = [] + acc[key]!.push(e) + return acc + }, {}) + + const sortedDates = Object.keys(grouped).sort((a, b) => b.localeCompare(a)) + + return ( +
+ {sortedDates.map(date => { + const dayExpenses = grouped[date]! + const dayTotal = dayExpenses.reduce((sum, e) => sum + Number(e.amount), 0) + return ( +
+
+

+ {new Date(date + 'T00:00:00').toLocaleDateString('default', { weekday: 'short', month: 'short', day: 'numeric' })} +

+

฿{dayTotal.toLocaleString()}

+
+
+ {dayExpenses.map(e => ( + + ))} +
+
+ ) + })} +
+ ) +} diff --git a/apps/expense-dashboard/src/components/expenses/ExpenseRow.tsx b/apps/expense-dashboard/src/components/expenses/ExpenseRow.tsx new file mode 100644 index 0000000000000000000000000000000000000000..fd5fd2ff721f801223aad08b63402c700d77647c --- /dev/null +++ b/apps/expense-dashboard/src/components/expenses/ExpenseRow.tsx @@ -0,0 +1,151 @@ +import { useState } from 'react' +import { Button } from '@/components/ui/button' +import { Input } from '@/components/ui/input' +import { Label } from '@/components/ui/label' +import { Badge } from '@/components/ui/badge' +import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog' +import { Pencil, Trash2 } from 'lucide-react' +import CategoryPicker from './CategoryPicker' +import type { Expense, Category } from '@llm-router/shared' + +interface Props { + expense: Expense + categories: Category[] + onUpdate: (id: string, data: Partial<{ amount: number; merchant: string; date: string; category_id: string; description: string }>) => Promise + onDelete: (id: string) => Promise +} + +export default function ExpenseRow({ expense, categories, onUpdate, onDelete }: Props) { + const [open, setOpen] = useState(false) + const [form, setForm] = useState({ + amount: String(expense.amount), + merchant: expense.merchant ?? '', + date: expense.date, + category_id: expense.category_id, + description: expense.description ?? '', + }) + const [saving, setSaving] = useState(false) + + function handleOpenChange(open: boolean) { + if (open) { + setForm({ + amount: String(expense.amount), + merchant: expense.merchant ?? '', + date: expense.date, + category_id: expense.category_id, + description: expense.description ?? '', + }) + } + setOpen(open) + } + + const cat = categories.find(c => c.id === expense.category_id) + + async function handleSave() { + setSaving(true) + try { + await onUpdate(expense.id, { + amount: Number(form.amount), + merchant: form.merchant || undefined, + date: form.date, + category_id: form.category_id, + description: form.description || undefined, + }) + setOpen(false) + } finally { + setSaving(false) + } + } + + return ( + <> +
+
+
+

{expense.merchant ?? '—'}

+ {expense.description && ( +

{expense.description}

+ )} +
+ {cat && ( + + {cat.icon} {cat.name} + + )} +
+
+ + {expense.currency} {Number(expense.amount).toLocaleString()} + +
+ + +
+
+
+ + + + + Edit Expense + +
+
+ + setForm(f => ({ ...f, amount: e.target.value }))} + /> +
+
+ + setForm(f => ({ ...f, merchant: e.target.value }))} + /> +
+
+ + setForm(f => ({ ...f, date: e.target.value }))} + /> +
+
+ + setForm(f => ({ ...f, category_id: id }))} + /> +
+
+ + setForm(f => ({ ...f, description: e.target.value }))} + /> +
+
+ + + + +
+
+ + ) +} diff --git a/apps/expense-dashboard/src/components/expenses/ReceiptPreview.tsx b/apps/expense-dashboard/src/components/expenses/ReceiptPreview.tsx new file mode 100644 index 0000000000000000000000000000000000000000..0088aa365cdc017f49093cb0ec57d349e4b7cb25 --- /dev/null +++ b/apps/expense-dashboard/src/components/expenses/ReceiptPreview.tsx @@ -0,0 +1,78 @@ +import { useState } from 'react' +import { Card, CardContent } from '@/components/ui/card' +import { Button } from '@/components/ui/button' +import { Label } from '@/components/ui/label' +import { Badge } from '@/components/ui/badge' +import CategoryPicker from './CategoryPicker' +import type { Category } from '@llm-router/shared' +import type { ParsedExpenseResult } from '@/api/expenses' + +interface Props { + parsed: ParsedExpenseResult + categories: Category[] + ocrUsed: boolean + onConfirm: (categoryId: string) => void + onCancel: () => void + saving: boolean +} + +export default function ReceiptPreview({ parsed, categories, ocrUsed, onConfirm, onCancel, saving }: Props) { + const matched = categories.find(c => c.name.toLowerCase() === parsed.category.toLowerCase()) + const [categoryId, setCategoryId] = useState(matched?.id ?? '') + + return ( +
+ + +
+ Amount + {parsed.currency} {parsed.amount.toLocaleString()} +
+ {parsed.merchant && ( +
+ Merchant + {parsed.merchant} +
+ )} +
+ Date + {parsed.date ?? 'Today'} +
+
+ Detected category + {parsed.category} +
+
+ Confidence + {Math.round((parsed.confidence ?? 0) * 100)}% +
+ {ocrUsed && ( +

📷 Text extracted via OCR

+ )} +
+
+ +
+ + +
+ +
+ + +
+
+ ) +} diff --git a/apps/expense-dashboard/src/components/layout/AppShell.tsx b/apps/expense-dashboard/src/components/layout/AppShell.tsx new file mode 100644 index 0000000000000000000000000000000000000000..ea9baf04561c4499fc8abf01acaf9558c93a73b7 --- /dev/null +++ b/apps/expense-dashboard/src/components/layout/AppShell.tsx @@ -0,0 +1,12 @@ +import Sidebar from './Sidebar' + +export default function AppShell({ children }: { children: React.ReactNode }) { + return ( +
+ +
+ {children} +
+
+ ) +} diff --git a/apps/expense-dashboard/src/components/layout/Sidebar.tsx b/apps/expense-dashboard/src/components/layout/Sidebar.tsx new file mode 100644 index 0000000000000000000000000000000000000000..3c57b4cf653937fab378943417c37653c7500359 --- /dev/null +++ b/apps/expense-dashboard/src/components/layout/Sidebar.tsx @@ -0,0 +1,63 @@ +import { NavLink, useNavigate } from 'react-router-dom' +import { LayoutDashboard, Receipt, Tag, Wallet, LogOut } from 'lucide-react' +import { clearToken } from '@/lib/auth' +import { cn } from '@/lib/utils' +import { Button } from '@/components/ui/button' +import { Separator } from '@/components/ui/separator' + +const NAV_ITEMS = [ + { to: '/', icon: LayoutDashboard, label: 'Dashboard', end: true }, + { to: '/expenses', icon: Receipt, label: 'Expenses', end: false }, + { to: '/categories', icon: Tag, label: 'Categories', end: false }, + { to: '/budgets', icon: Wallet, label: 'Budgets', end: false }, +] + +export default function Sidebar() { + const navigate = useNavigate() + + function handleLogout() { + clearToken() + navigate('/login') + } + + return ( + + ) +} diff --git a/apps/expense-dashboard/src/components/ui/badge.tsx b/apps/expense-dashboard/src/components/ui/badge.tsx new file mode 100644 index 0000000000000000000000000000000000000000..f000e3ef5176395b067dfc3f3e1256a80c450015 --- /dev/null +++ b/apps/expense-dashboard/src/components/ui/badge.tsx @@ -0,0 +1,36 @@ +import * as React from "react" +import { cva, type VariantProps } from "class-variance-authority" + +import { cn } from "@/lib/utils" + +const badgeVariants = cva( + "inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2", + { + variants: { + variant: { + default: + "border-transparent bg-primary text-primary-foreground hover:bg-primary/80", + secondary: + "border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80", + destructive: + "border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80", + outline: "text-foreground", + }, + }, + defaultVariants: { + variant: "default", + }, + } +) + +export interface BadgeProps + extends React.HTMLAttributes, + VariantProps {} + +function Badge({ className, variant, ...props }: BadgeProps) { + return ( +
+ ) +} + +export { Badge, badgeVariants } diff --git a/apps/expense-dashboard/src/components/ui/button.tsx b/apps/expense-dashboard/src/components/ui/button.tsx new file mode 100644 index 0000000000000000000000000000000000000000..36496a28727a3643b4212a14225d4f6cbd50bda5 --- /dev/null +++ b/apps/expense-dashboard/src/components/ui/button.tsx @@ -0,0 +1,56 @@ +import * as React from "react" +import { Slot } from "@radix-ui/react-slot" +import { cva, type VariantProps } from "class-variance-authority" + +import { cn } from "@/lib/utils" + +const buttonVariants = cva( + "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0", + { + variants: { + variant: { + default: "bg-primary text-primary-foreground hover:bg-primary/90", + destructive: + "bg-destructive text-destructive-foreground hover:bg-destructive/90", + outline: + "border border-input bg-background hover:bg-accent hover:text-accent-foreground", + secondary: + "bg-secondary text-secondary-foreground hover:bg-secondary/80", + ghost: "hover:bg-accent hover:text-accent-foreground", + link: "text-primary underline-offset-4 hover:underline", + }, + size: { + default: "h-10 px-4 py-2", + sm: "h-9 rounded-md px-3", + lg: "h-11 rounded-md px-8", + icon: "h-10 w-10", + }, + }, + defaultVariants: { + variant: "default", + size: "default", + }, + } +) + +export interface ButtonProps + extends React.ButtonHTMLAttributes, + VariantProps { + asChild?: boolean +} + +const Button = React.forwardRef( + ({ className, variant, size, asChild = false, ...props }, ref) => { + const Comp = asChild ? Slot : "button" + return ( + + ) + } +) +Button.displayName = "Button" + +export { Button, buttonVariants } diff --git a/apps/expense-dashboard/src/components/ui/card.tsx b/apps/expense-dashboard/src/components/ui/card.tsx new file mode 100644 index 0000000000000000000000000000000000000000..f62edea578d50058bef5e6bcc178b88d145564e9 --- /dev/null +++ b/apps/expense-dashboard/src/components/ui/card.tsx @@ -0,0 +1,79 @@ +import * as React from "react" + +import { cn } from "@/lib/utils" + +const Card = React.forwardRef< + HTMLDivElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( +
+)) +Card.displayName = "Card" + +const CardHeader = React.forwardRef< + HTMLDivElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( +
+)) +CardHeader.displayName = "CardHeader" + +const CardTitle = React.forwardRef< + HTMLDivElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( +
+)) +CardTitle.displayName = "CardTitle" + +const CardDescription = React.forwardRef< + HTMLDivElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( +
+)) +CardDescription.displayName = "CardDescription" + +const CardContent = React.forwardRef< + HTMLDivElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( +
+)) +CardContent.displayName = "CardContent" + +const CardFooter = React.forwardRef< + HTMLDivElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( +
+)) +CardFooter.displayName = "CardFooter" + +export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent } diff --git a/apps/expense-dashboard/src/components/ui/dialog.tsx b/apps/expense-dashboard/src/components/ui/dialog.tsx new file mode 100644 index 0000000000000000000000000000000000000000..c680b9d30913cd442fc0056af3e1e924b0bf1d20 --- /dev/null +++ b/apps/expense-dashboard/src/components/ui/dialog.tsx @@ -0,0 +1,120 @@ +import * as React from "react" +import * as DialogPrimitive from "@radix-ui/react-dialog" +import { X } from "lucide-react" + +import { cn } from "@/lib/utils" + +const Dialog = DialogPrimitive.Root + +const DialogTrigger = DialogPrimitive.Trigger + +const DialogPortal = DialogPrimitive.Portal + +const DialogClose = DialogPrimitive.Close + +const DialogOverlay = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)) +DialogOverlay.displayName = DialogPrimitive.Overlay.displayName + +const DialogContent = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, children, ...props }, ref) => ( + + + + {children} + + + Close + + + +)) +DialogContent.displayName = DialogPrimitive.Content.displayName + +const DialogHeader = ({ + className, + ...props +}: React.HTMLAttributes) => ( +
+) +DialogHeader.displayName = "DialogHeader" + +const DialogFooter = ({ + className, + ...props +}: React.HTMLAttributes) => ( +
+) +DialogFooter.displayName = "DialogFooter" + +const DialogTitle = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)) +DialogTitle.displayName = DialogPrimitive.Title.displayName + +const DialogDescription = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)) +DialogDescription.displayName = DialogPrimitive.Description.displayName + +export { + Dialog, + DialogPortal, + DialogOverlay, + DialogClose, + DialogTrigger, + DialogContent, + DialogHeader, + DialogFooter, + DialogTitle, + DialogDescription, +} diff --git a/apps/expense-dashboard/src/components/ui/input.tsx b/apps/expense-dashboard/src/components/ui/input.tsx new file mode 100644 index 0000000000000000000000000000000000000000..68551b9276b4164a8263aa58d385db30f81a4453 --- /dev/null +++ b/apps/expense-dashboard/src/components/ui/input.tsx @@ -0,0 +1,22 @@ +import * as React from "react" + +import { cn } from "@/lib/utils" + +const Input = React.forwardRef>( + ({ className, type, ...props }, ref) => { + return ( + + ) + } +) +Input.displayName = "Input" + +export { Input } diff --git a/apps/expense-dashboard/src/components/ui/label.tsx b/apps/expense-dashboard/src/components/ui/label.tsx new file mode 100644 index 0000000000000000000000000000000000000000..683faa793819982d64e21cb2939666fd6d4a7b13 --- /dev/null +++ b/apps/expense-dashboard/src/components/ui/label.tsx @@ -0,0 +1,24 @@ +import * as React from "react" +import * as LabelPrimitive from "@radix-ui/react-label" +import { cva, type VariantProps } from "class-variance-authority" + +import { cn } from "@/lib/utils" + +const labelVariants = cva( + "text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70" +) + +const Label = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef & + VariantProps +>(({ className, ...props }, ref) => ( + +)) +Label.displayName = LabelPrimitive.Root.displayName + +export { Label } diff --git a/apps/expense-dashboard/src/components/ui/progress.tsx b/apps/expense-dashboard/src/components/ui/progress.tsx new file mode 100644 index 0000000000000000000000000000000000000000..5c87ea4865610374cdc591d1619157b4d8909a87 --- /dev/null +++ b/apps/expense-dashboard/src/components/ui/progress.tsx @@ -0,0 +1,28 @@ +"use client" + +import * as React from "react" +import * as ProgressPrimitive from "@radix-ui/react-progress" + +import { cn } from "@/lib/utils" + +const Progress = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, value, ...props }, ref) => ( + + + +)) +Progress.displayName = ProgressPrimitive.Root.displayName + +export { Progress } diff --git a/apps/expense-dashboard/src/components/ui/select.tsx b/apps/expense-dashboard/src/components/ui/select.tsx new file mode 100644 index 0000000000000000000000000000000000000000..a45647c222f60248d3a206e50c9266fecda2bf1c --- /dev/null +++ b/apps/expense-dashboard/src/components/ui/select.tsx @@ -0,0 +1,160 @@ +"use client" + +import * as React from "react" +import * as SelectPrimitive from "@radix-ui/react-select" +import { Check, ChevronDown, ChevronUp } from "lucide-react" + +import { cn } from "@/lib/utils" + +const Select = SelectPrimitive.Root + +const SelectGroup = SelectPrimitive.Group + +const SelectValue = SelectPrimitive.Value + +const SelectTrigger = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, children, ...props }, ref) => ( + span]:line-clamp-1", + className + )} + {...props} + > + {children} + + + + +)) +SelectTrigger.displayName = SelectPrimitive.Trigger.displayName + +const SelectScrollUpButton = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + + + +)) +SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName + +const SelectScrollDownButton = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + + + +)) +SelectScrollDownButton.displayName = + SelectPrimitive.ScrollDownButton.displayName + +const SelectContent = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, children, position = "popper", ...props }, ref) => ( + + + + + {children} + + + + +)) +SelectContent.displayName = SelectPrimitive.Content.displayName + +const SelectLabel = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)) +SelectLabel.displayName = SelectPrimitive.Label.displayName + +const SelectItem = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, children, ...props }, ref) => ( + + + + + + + + {children} + +)) +SelectItem.displayName = SelectPrimitive.Item.displayName + +const SelectSeparator = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)) +SelectSeparator.displayName = SelectPrimitive.Separator.displayName + +export { + Select, + SelectGroup, + SelectValue, + SelectTrigger, + SelectContent, + SelectLabel, + SelectItem, + SelectSeparator, + SelectScrollUpButton, + SelectScrollDownButton, +} diff --git a/apps/expense-dashboard/src/components/ui/separator.tsx b/apps/expense-dashboard/src/components/ui/separator.tsx new file mode 100644 index 0000000000000000000000000000000000000000..6d7f12265ba0338704f013930ce4d52c56527dd1 --- /dev/null +++ b/apps/expense-dashboard/src/components/ui/separator.tsx @@ -0,0 +1,29 @@ +import * as React from "react" +import * as SeparatorPrimitive from "@radix-ui/react-separator" + +import { cn } from "@/lib/utils" + +const Separator = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>( + ( + { className, orientation = "horizontal", decorative = true, ...props }, + ref + ) => ( + + ) +) +Separator.displayName = SeparatorPrimitive.Root.displayName + +export { Separator } diff --git a/apps/expense-dashboard/src/components/ui/table.tsx b/apps/expense-dashboard/src/components/ui/table.tsx new file mode 100644 index 0000000000000000000000000000000000000000..7f3502f8b2820be1d6f0aa4c1ffaa351799c1ed3 --- /dev/null +++ b/apps/expense-dashboard/src/components/ui/table.tsx @@ -0,0 +1,117 @@ +import * as React from "react" + +import { cn } from "@/lib/utils" + +const Table = React.forwardRef< + HTMLTableElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( +
+ + +)) +Table.displayName = "Table" + +const TableHeader = React.forwardRef< + HTMLTableSectionElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( + +)) +TableHeader.displayName = "TableHeader" + +const TableBody = React.forwardRef< + HTMLTableSectionElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( + +)) +TableBody.displayName = "TableBody" + +const TableFooter = React.forwardRef< + HTMLTableSectionElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( + tr]:last:border-b-0", + className + )} + {...props} + /> +)) +TableFooter.displayName = "TableFooter" + +const TableRow = React.forwardRef< + HTMLTableRowElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( + +)) +TableRow.displayName = "TableRow" + +const TableHead = React.forwardRef< + HTMLTableCellElement, + React.ThHTMLAttributes +>(({ className, ...props }, ref) => ( +
+)) +TableHead.displayName = "TableHead" + +const TableCell = React.forwardRef< + HTMLTableCellElement, + React.TdHTMLAttributes +>(({ className, ...props }, ref) => ( + +)) +TableCell.displayName = "TableCell" + +const TableCaption = React.forwardRef< + HTMLTableCaptionElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( +
+)) +TableCaption.displayName = "TableCaption" + +export { + Table, + TableHeader, + TableBody, + TableFooter, + TableHead, + TableRow, + TableCell, + TableCaption, +} diff --git a/apps/expense-dashboard/src/components/ui/tabs.tsx b/apps/expense-dashboard/src/components/ui/tabs.tsx new file mode 100644 index 0000000000000000000000000000000000000000..f57fffdb5a07cd21b12f8c014513475a6980a469 --- /dev/null +++ b/apps/expense-dashboard/src/components/ui/tabs.tsx @@ -0,0 +1,53 @@ +import * as React from "react" +import * as TabsPrimitive from "@radix-ui/react-tabs" + +import { cn } from "@/lib/utils" + +const Tabs = TabsPrimitive.Root + +const TabsList = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)) +TabsList.displayName = TabsPrimitive.List.displayName + +const TabsTrigger = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)) +TabsTrigger.displayName = TabsPrimitive.Trigger.displayName + +const TabsContent = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)) +TabsContent.displayName = TabsPrimitive.Content.displayName + +export { Tabs, TabsList, TabsTrigger, TabsContent } diff --git a/apps/expense-dashboard/src/hooks/useAnalytics.ts b/apps/expense-dashboard/src/hooks/useAnalytics.ts new file mode 100644 index 0000000000000000000000000000000000000000..031280277f6d4ea620efa05809e4eb93b03896f6 --- /dev/null +++ b/apps/expense-dashboard/src/hooks/useAnalytics.ts @@ -0,0 +1,28 @@ +import { useState, useEffect, useCallback } from 'react' +import { getSummary, getTrends } from '@/api/analytics' +import type { Summary, Trends } from '@llm-router/shared' + +export function useAnalytics() { + const [summary, setSummary] = useState(null) + const [trends, setTrends] = useState(null) + const [loading, setLoading] = useState(true) + const [error, setError] = useState(null) + + const refresh = useCallback(async () => { + setLoading(true) + setError(null) + try { + const [s, t] = await Promise.all([getSummary(), getTrends(6)]) + setSummary(s) + setTrends(t) + } catch (err) { + setError(err instanceof Error ? err.message : 'Failed to load analytics') + } finally { + setLoading(false) + } + }, []) + + useEffect(() => { void refresh() }, [refresh]) + + return { summary, trends, loading, error, refresh } +} diff --git a/apps/expense-dashboard/src/hooks/useBudgets.ts b/apps/expense-dashboard/src/hooks/useBudgets.ts new file mode 100644 index 0000000000000000000000000000000000000000..196705110a66a0d3f7fd27c45ae7ed96295a5ff2 --- /dev/null +++ b/apps/expense-dashboard/src/hooks/useBudgets.ts @@ -0,0 +1,42 @@ +import { useState, useEffect, useCallback } from 'react' +import { listBudgets, createBudget, updateBudget, deleteBudget } from '@/api/budgets' +import type { Budget, CreateBudget, UpdateBudget } from '@llm-router/shared' + +export function useBudgets() { + const [budgets, setBudgets] = useState([]) + const [loading, setLoading] = useState(true) + const [error, setError] = useState(null) + + const refresh = useCallback(async () => { + setLoading(true) + setError(null) + try { + setBudgets(await listBudgets()) + } catch (err) { + setError(err instanceof Error ? err.message : 'Failed to load budgets') + } finally { + setLoading(false) + } + }, []) + + useEffect(() => { void refresh() }, [refresh]) + + const create = useCallback(async (data: CreateBudget) => { + const created = await createBudget(data) + setBudgets(prev => [...prev, created]) + return created + }, []) + + const update = useCallback(async (id: string, data: UpdateBudget) => { + const updated = await updateBudget(id, data) + setBudgets(prev => prev.map(b => b.id === id ? updated : b)) + return updated + }, []) + + const remove = useCallback(async (id: string) => { + await deleteBudget(id) + setBudgets(prev => prev.filter(b => b.id !== id)) + }, []) + + return { budgets, loading, error, refresh, create, update, remove } +} diff --git a/apps/expense-dashboard/src/hooks/useCategories.ts b/apps/expense-dashboard/src/hooks/useCategories.ts new file mode 100644 index 0000000000000000000000000000000000000000..35b16421999c75452080cad6acddbd1f80a7c42c --- /dev/null +++ b/apps/expense-dashboard/src/hooks/useCategories.ts @@ -0,0 +1,42 @@ +import { useState, useEffect, useCallback } from 'react' +import { listCategories, createCategory, updateCategory, deleteCategory } from '@/api/categories' +import type { Category, CreateCategory, UpdateCategory } from '@llm-router/shared' + +export function useCategories() { + const [categories, setCategories] = useState([]) + const [loading, setLoading] = useState(true) + const [error, setError] = useState(null) + + const refresh = useCallback(async () => { + setLoading(true) + setError(null) + try { + setCategories(await listCategories()) + } catch (err) { + setError(err instanceof Error ? err.message : 'Failed to load categories') + } finally { + setLoading(false) + } + }, []) + + useEffect(() => { void refresh() }, [refresh]) + + const create = useCallback(async (data: CreateCategory) => { + const created = await createCategory(data) + setCategories(prev => [...prev, created]) + return created + }, []) + + const update = useCallback(async (id: string, data: UpdateCategory) => { + const updated = await updateCategory(id, data) + setCategories(prev => prev.map(c => c.id === id ? updated : c)) + return updated + }, []) + + const remove = useCallback(async (id: string) => { + await deleteCategory(id) + setCategories(prev => prev.filter(c => c.id !== id)) + }, []) + + return { categories, loading, error, refresh, create, update, remove } +} diff --git a/apps/expense-dashboard/src/hooks/useExpenses.ts b/apps/expense-dashboard/src/hooks/useExpenses.ts new file mode 100644 index 0000000000000000000000000000000000000000..8d5dd50ae57ab43c1839ee7e9a8fe1a57299b5e7 --- /dev/null +++ b/apps/expense-dashboard/src/hooks/useExpenses.ts @@ -0,0 +1,44 @@ +import { useState, useEffect, useCallback } from 'react' +import { listExpenses, createExpense, updateExpense, deleteExpense } from '@/api/expenses' +import { getCurrentMonth } from '@/lib/dates' +import type { Expense, CreateExpense, UpdateExpense } from '@llm-router/shared' + +export function useExpenses(month?: string) { + const [selectedMonth, setSelectedMonth] = useState(month ?? getCurrentMonth()) + const [expenses, setExpenses] = useState([]) + const [loading, setLoading] = useState(true) + const [error, setError] = useState(null) + + const refresh = useCallback(async () => { + setLoading(true) + setError(null) + try { + setExpenses(await listExpenses(selectedMonth)) + } catch (err) { + setError(err instanceof Error ? err.message : 'Failed to load expenses') + } finally { + setLoading(false) + } + }, [selectedMonth]) + + useEffect(() => { void refresh() }, [refresh]) + + const create = useCallback(async (data: CreateExpense) => { + const created = await createExpense(data) + await refresh() + return created + }, [refresh]) + + const update = useCallback(async (id: string, data: UpdateExpense) => { + const updated = await updateExpense(id, data) + setExpenses(prev => prev.map(e => e.id === id ? updated : e)) + return updated + }, []) + + const remove = useCallback(async (id: string) => { + await deleteExpense(id) + setExpenses(prev => prev.filter(e => e.id !== id)) + }, []) + + return { expenses, loading, error, selectedMonth, setSelectedMonth, refresh, create, update, remove } +} diff --git a/apps/expense-dashboard/src/index.css b/apps/expense-dashboard/src/index.css new file mode 100644 index 0000000000000000000000000000000000000000..5378dfe8c65861d386443a1f7f416f0ed3dd2923 --- /dev/null +++ b/apps/expense-dashboard/src/index.css @@ -0,0 +1,31 @@ +@tailwind base; +@tailwind components; +@tailwind utilities; + +@layer base { + :root { + --background: 0 0% 100%; + --foreground: 222.2 84% 4.9%; + --card: 0 0% 100%; + --card-foreground: 222.2 84% 4.9%; + --primary: 222.2 47.4% 11.2%; + --primary-foreground: 210 40% 98%; + --secondary: 210 40% 96.1%; + --secondary-foreground: 222.2 47.4% 11.2%; + --muted: 210 40% 96.1%; + --muted-foreground: 215.4 16.3% 46.9%; + --accent: 210 40% 96.1%; + --accent-foreground: 222.2 47.4% 11.2%; + --destructive: 0 84.2% 60.2%; + --destructive-foreground: 210 40% 98%; + --border: 214.3 31.8% 91.4%; + --input: 214.3 31.8% 91.4%; + --ring: 222.2 84% 4.9%; + --radius: 0.5rem; + } +} + +@layer base { + * { @apply border-border; } + body { @apply bg-background text-foreground; } +} diff --git a/apps/expense-dashboard/src/lib/auth.ts b/apps/expense-dashboard/src/lib/auth.ts new file mode 100644 index 0000000000000000000000000000000000000000..84a5e6b36c4f16119b5bd91bb195efaa163f348f --- /dev/null +++ b/apps/expense-dashboard/src/lib/auth.ts @@ -0,0 +1,17 @@ +const TOKEN_KEY = 'expense_token' + +export function getToken(): string | null { + return localStorage.getItem(TOKEN_KEY) +} + +export function setToken(token: string): void { + localStorage.setItem(TOKEN_KEY, token) +} + +export function clearToken(): void { + localStorage.removeItem(TOKEN_KEY) +} + +export function isAuthenticated(): boolean { + return getToken() !== null +} diff --git a/apps/expense-dashboard/src/lib/dates.ts b/apps/expense-dashboard/src/lib/dates.ts new file mode 100644 index 0000000000000000000000000000000000000000..bc25ab32724dc87e0e356e7ca3096c821deb450a --- /dev/null +++ b/apps/expense-dashboard/src/lib/dates.ts @@ -0,0 +1,31 @@ +export function getCurrentMonth(): string { + const now = new Date() + return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}` +} + +export function monthRange(month: string): { from: string; to: string } { + const parts = month.split('-') + const year = Number(parts[0]) + const mon = Number(parts[1]) + const from = `${year}-${String(mon).padStart(2, '0')}-01` + const lastDay = new Date(year, mon, 0).getDate() + const to = `${year}-${String(mon).padStart(2, '0')}-${String(lastDay).padStart(2, '0')}` + return { from, to } +} + +export function formatMonth(month: string): string { + const parts = month.split('-') + const year = Number(parts[0]) + const mon = Number(parts[1]) + return new Date(year, mon - 1, 1).toLocaleString('default', { month: 'long', year: 'numeric' }) +} + +export function getLast12Months(): string[] { + const months: string[] = [] + const now = new Date() + for (let i = 0; i < 12; i++) { + const d = new Date(now.getFullYear(), now.getMonth() - i, 1) + months.push(`${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`) + } + return months +} diff --git a/apps/expense-dashboard/src/lib/utils.ts b/apps/expense-dashboard/src/lib/utils.ts new file mode 100644 index 0000000000000000000000000000000000000000..fed2fe91e4d2321f997c0209881db87fe0d07ba9 --- /dev/null +++ b/apps/expense-dashboard/src/lib/utils.ts @@ -0,0 +1,6 @@ +import { clsx, type ClassValue } from 'clsx' +import { twMerge } from 'tailwind-merge' + +export function cn(...inputs: ClassValue[]) { + return twMerge(clsx(inputs)) +} diff --git a/apps/expense-dashboard/src/main.tsx b/apps/expense-dashboard/src/main.tsx new file mode 100644 index 0000000000000000000000000000000000000000..4a1b15096e15b1e15988686be6341c14defc85ac --- /dev/null +++ b/apps/expense-dashboard/src/main.tsx @@ -0,0 +1,10 @@ +import React from 'react' +import ReactDOM from 'react-dom/client' +import App from './App' +import './index.css' + +ReactDOM.createRoot(document.getElementById('root')!).render( + + + +) diff --git a/apps/expense-dashboard/src/pages/BudgetsPage.tsx b/apps/expense-dashboard/src/pages/BudgetsPage.tsx new file mode 100644 index 0000000000000000000000000000000000000000..2c82325e6a2a3baadb064d97181c698b3d5a0d00 --- /dev/null +++ b/apps/expense-dashboard/src/pages/BudgetsPage.tsx @@ -0,0 +1,159 @@ +import { useState } from 'react' +import { useBudgets } from '@/hooks/useBudgets' +import { useCategories } from '@/hooks/useCategories' +import { Button } from '@/components/ui/button' +import { Input } from '@/components/ui/input' +import { Label } from '@/components/ui/label' +import { Card, CardContent } from '@/components/ui/card' +import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog' +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select' +import { Pencil, Trash2, Plus } from 'lucide-react' +import type { Budget } from '@llm-router/shared' + +export default function BudgetsPage() { + const { budgets, loading, error, create, update, remove } = useBudgets() + const { categories } = useCategories() + const [open, setOpen] = useState(false) + const [editing, setEditing] = useState(null) + const [categoryId, setCategoryId] = useState('') + const [amount, setAmount] = useState('') + const [saving, setSaving] = useState(false) + const [formError, setFormError] = useState(null) + + function openCreate() { + setEditing(null) + setCategoryId('') + setAmount('') + setFormError(null) + setOpen(true) + } + + function openEdit(b: Budget) { + setEditing(b) + setCategoryId(b.category_id) + setAmount(String(b.amount)) + setFormError(null) + setOpen(true) + } + + async function handleSave() { + const amt = Number(amount) + if (!categoryId) { setFormError('Select a category'); return } + if (!amount || isNaN(amt) || amt <= 0) { setFormError('Enter a valid amount'); return } + setSaving(true) + setFormError(null) + try { + if (editing) { + await update(editing.id, { amount: amt }) + } else { + await create({ category_id: categoryId, amount: amt, period: 'monthly' }) + } + setOpen(false) + } catch (err) { + setFormError(err instanceof Error ? err.message : 'Save failed') + } finally { + setSaving(false) + } + } + + async function handleDelete(id: string) { + if (!confirm('Delete this budget?')) return + try { + await remove(id) + } catch (err) { + alert(err instanceof Error ? err.message : 'Delete failed') + } + } + + const categoryMap = Object.fromEntries(categories.map(c => [c.id, c])) + const usedCategoryIds = new Set(budgets.map(b => b.category_id)) + + return ( +
+
+

Monthly Budgets

+ +
+ + {loading &&

Loading…

} + {error &&

{error}

} + +
+ {budgets.map(b => { + const cat = categoryMap[b.category_id] + return ( + + +
+ {cat && ( + + )} + {cat?.icon} {cat?.name ?? b.category_id} + — ฿{Number(b.amount).toLocaleString()} / month +
+
+ + +
+
+
+ ) + })} +
+ + + + + {editing ? 'Edit Budget' : 'New Monthly Budget'} + +
+
+ + +
+
+ + setAmount(e.target.value)} + placeholder="5000" + /> +
+ {formError &&

{formError}

} +
+ + + + +
+
+
+ ) +} diff --git a/apps/expense-dashboard/src/pages/CategoriesPage.tsx b/apps/expense-dashboard/src/pages/CategoriesPage.tsx new file mode 100644 index 0000000000000000000000000000000000000000..f5205f87cc67b14f46b600ca13639861f19f18e2 --- /dev/null +++ b/apps/expense-dashboard/src/pages/CategoriesPage.tsx @@ -0,0 +1,157 @@ +import { useState } from 'react' +import { useCategories } from '@/hooks/useCategories' +import { Button } from '@/components/ui/button' +import { Input } from '@/components/ui/input' +import { Label } from '@/components/ui/label' +import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card' +import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog' +import { Pencil, Trash2, Plus } from 'lucide-react' +import type { Category } from '@llm-router/shared' + +interface FormState { name: string; color: string; icon: string } +const EMPTY: FormState = { name: '', color: '#6B7280', icon: '' } + +export default function CategoriesPage() { + const { categories, loading, error, create, update, remove } = useCategories() + const [open, setOpen] = useState(false) + const [editing, setEditing] = useState(null) + const [form, setForm] = useState(EMPTY) + const [saving, setSaving] = useState(false) + const [formError, setFormError] = useState(null) + + function openCreate() { + setEditing(null) + setForm(EMPTY) + setFormError(null) + setOpen(true) + } + + function openEdit(cat: Category) { + setEditing(cat) + setForm({ name: cat.name, color: cat.color, icon: cat.icon ?? '' }) + setFormError(null) + setOpen(true) + } + + async function handleSave() { + if (!form.name.trim()) { setFormError('Name is required'); return } + if (!/^#[0-9A-Fa-f]{6}$/.test(form.color)) { setFormError('Color must be hex e.g. #FF5500'); return } + setSaving(true) + setFormError(null) + try { + const payload = { + name: form.name.trim(), + color: form.color, + ...(form.icon.trim() ? { icon: form.icon.trim() } : {}), + } + if (editing) { + await update(editing.id, payload) + } else { + await create(payload) + } + setOpen(false) + } catch (err) { + setFormError(err instanceof Error ? err.message : 'Save failed') + } finally { + setSaving(false) + } + } + + async function handleDelete(id: string) { + if (!confirm('Delete this category? This will fail if expenses are assigned to it.')) return + try { + await remove(id) + } catch (err) { + alert(err instanceof Error ? err.message : 'Delete failed') + } + } + + return ( +
+
+

Categories

+ +
+ + {loading &&

Loading…

} + {error &&

{error}

} + +
+ {categories.map(cat => ( + + +
+ + {cat.icon} {cat.name} +
+
+ + +
+
+
+ ))} +
+ + + + + {editing ? 'Edit Category' : 'New Category'} + +
+
+ + setForm(f => ({ ...f, name: e.target.value }))} + placeholder="e.g. Food" + autoFocus + /> +
+
+ +
+ setForm(f => ({ ...f, color: e.target.value }))} + className="w-10 h-10 rounded border cursor-pointer" + /> + setForm(f => ({ ...f, color: e.target.value }))} + placeholder="#6B7280" + className="font-mono" + /> +
+
+
+ + setForm(f => ({ ...f, icon: e.target.value }))} + placeholder="🍔" + /> +
+ {formError &&

{formError}

} +
+ + + + +
+
+
+ ) +} diff --git a/apps/expense-dashboard/src/pages/DashboardPage.tsx b/apps/expense-dashboard/src/pages/DashboardPage.tsx new file mode 100644 index 0000000000000000000000000000000000000000..346b7df16e85b255d47df20691b26f36f14e123c --- /dev/null +++ b/apps/expense-dashboard/src/pages/DashboardPage.tsx @@ -0,0 +1,101 @@ +import { useAnalytics } from '@/hooks/useAnalytics' +import { useExpenses } from '@/hooks/useExpenses' +import SpendDonut from '@/components/analytics/SpendDonut' +import DailyBarChart from '@/components/analytics/DailyBarChart' +import BudgetCard from '@/components/analytics/BudgetCard' +import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card' +import { getCurrentMonth, formatMonth } from '@/lib/dates' + +export default function DashboardPage() { + const { summary, trends, loading, error } = useAnalytics() + const { expenses } = useExpenses(getCurrentMonth()) + + const currentMonth = formatMonth(getCurrentMonth()) + + return ( +
+

Dashboard — {currentMonth}

+ + {loading &&

Loading…

} + {error &&

{error}

} + + {summary && ( + <> + {/* Total spend summary */} + + +

Total spent this month

+

+ ฿{summary.total_spent.toLocaleString()} +

+ {summary.currency_warning && ( +

⚠ Multiple currencies detected — totals are approximate

+ )} +
+
+ + {/* Charts row */} +
+ + + Spend by category + + + + + + + + + Daily spend + + + + + +
+ + {/* Budget cards */} + {summary.categories.length > 0 && ( +
+

Budget tracking

+
+ {summary.categories.map(item => ( + + ))} +
+
+ )} + + {/* Trends */} + {trends && trends.months.length > 0 && ( + + + 6-month trend + + +
+ {[...trends.months].reverse().map(m => { + const maxTotal = Math.max(...trends.months.map(x => x.total), 1) + const heightPct = (m.total / maxTotal) * 100 + return ( +
+
+ + {m.period.slice(5)} + +
+ ) + })} +
+ + + )} + + )} +
+ ) +} diff --git a/apps/expense-dashboard/src/pages/ExpensesPage.tsx b/apps/expense-dashboard/src/pages/ExpensesPage.tsx new file mode 100644 index 0000000000000000000000000000000000000000..e6ca58f5c355534f2b79ddc1613359ecddb736f5 --- /dev/null +++ b/apps/expense-dashboard/src/pages/ExpensesPage.tsx @@ -0,0 +1,82 @@ +import { useState } from 'react' +import { useExpenses } from '@/hooks/useExpenses' +import { useCategories } from '@/hooks/useCategories' +import ExpenseList from '@/components/expenses/ExpenseList' +import AddExpenseDrawer from '@/components/expenses/AddExpenseDrawer' +import { Button } from '@/components/ui/button' +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select' +import { Plus } from 'lucide-react' +import { formatMonth, getLast12Months } from '@/lib/dates' +import type { CreateExpense } from '@llm-router/shared' + +export default function ExpensesPage() { + const { expenses, loading, error, selectedMonth, setSelectedMonth, create, update, remove } = useExpenses() + const { categories } = useCategories() + const [drawerOpen, setDrawerOpen] = useState(false) + const months = getLast12Months() + + const totalSpent = expenses.reduce((sum, e) => sum + Number(e.amount), 0) + + async function handleSave(data: CreateExpense) { + await create(data) + } + + async function handleUpdate(id: string, data: Parameters[1]) { + await update(id, data) + } + + async function handleDelete(id: string) { + if (!confirm('Delete this expense?')) return + try { + await remove(id) + } catch (err) { + alert(err instanceof Error ? err.message : 'Delete failed') + } + } + + return ( +
+
+
+

Expenses

+ +
+
+ + Total: ฿{totalSpent.toLocaleString()} + + +
+
+ + {loading &&

Loading…

} + {error &&

{error}

} + {!loading && ( + + )} + + +
+ ) +} diff --git a/apps/expense-dashboard/src/pages/LoginPage.tsx b/apps/expense-dashboard/src/pages/LoginPage.tsx new file mode 100644 index 0000000000000000000000000000000000000000..722be2c127f2e53a96783fdf534d7709bcf27b5e --- /dev/null +++ b/apps/expense-dashboard/src/pages/LoginPage.tsx @@ -0,0 +1,70 @@ +import { useState, type FormEvent } from 'react' +import { useNavigate } from 'react-router-dom' +import { setToken } from '@/lib/auth' +import { login } from '@/api/auth' +import { Button } from '@/components/ui/button' +import { Input } from '@/components/ui/input' +import { Label } from '@/components/ui/label' +import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card' + +export default function LoginPage() { + const navigate = useNavigate() + const [email, setEmail] = useState('') + const [password, setPassword] = useState('') + const [loading, setLoading] = useState(false) + const [error, setError] = useState(null) + + async function handleSubmit(e: FormEvent) { + e.preventDefault() + setLoading(true) + setError(null) + try { + const { token } = await login(email, password) + setToken(token) + navigate('/') + } catch (err) { + setError(err instanceof Error ? err.message : 'Login failed') + } finally { + setLoading(false) + } + } + + return ( +
+ + + Expense Dashboard + + +
+
+ + setEmail(e.target.value)} + required + autoFocus + /> +
+
+ + setPassword(e.target.value)} + required + /> +
+ {error &&

{error}

} + +
+
+
+
+ ) +} diff --git a/apps/expense-dashboard/src/router.tsx b/apps/expense-dashboard/src/router.tsx new file mode 100644 index 0000000000000000000000000000000000000000..e730968c01e8ceabb474ef462c179c9c6d92167b --- /dev/null +++ b/apps/expense-dashboard/src/router.tsx @@ -0,0 +1,28 @@ +import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom' +import { isAuthenticated } from '@/lib/auth' +import AppShell from '@/components/layout/AppShell' +import LoginPage from '@/pages/LoginPage' +import DashboardPage from '@/pages/DashboardPage' +import ExpensesPage from '@/pages/ExpensesPage' +import CategoriesPage from '@/pages/CategoriesPage' +import BudgetsPage from '@/pages/BudgetsPage' + +function ProtectedRoute({ children }: { children: React.ReactNode }) { + if (!isAuthenticated()) return + return {children} +} + +export default function AppRouter() { + return ( + + + } /> + } /> + } /> + } /> + } /> + } /> + + + ) +} diff --git a/apps/expense-dashboard/tailwind.config.ts b/apps/expense-dashboard/tailwind.config.ts new file mode 100644 index 0000000000000000000000000000000000000000..a2cb22db3bc3d4e889461cc89cb34288f7d77d3c --- /dev/null +++ b/apps/expense-dashboard/tailwind.config.ts @@ -0,0 +1,31 @@ +import type { Config } from 'tailwindcss' + +const config: Config = { + darkMode: ['class'], + content: ['./index.html', './src/**/*.{ts,tsx}'], + theme: { + extend: { + colors: { + border: 'hsl(var(--border))', + input: 'hsl(var(--input))', + ring: 'hsl(var(--ring))', + background: 'hsl(var(--background))', + foreground: 'hsl(var(--foreground))', + primary: { DEFAULT: 'hsl(var(--primary))', foreground: 'hsl(var(--primary-foreground))' }, + secondary: { DEFAULT: 'hsl(var(--secondary))', foreground: 'hsl(var(--secondary-foreground))' }, + destructive: { DEFAULT: 'hsl(var(--destructive))', foreground: 'hsl(var(--destructive-foreground))' }, + muted: { DEFAULT: 'hsl(var(--muted))', foreground: 'hsl(var(--muted-foreground))' }, + accent: { DEFAULT: 'hsl(var(--accent))', foreground: 'hsl(var(--accent-foreground))' }, + card: { DEFAULT: 'hsl(var(--card))', foreground: 'hsl(var(--card-foreground))' }, + }, + borderRadius: { + lg: 'var(--radius)', + md: 'calc(var(--radius) - 2px)', + sm: 'calc(var(--radius) - 4px)', + }, + }, + }, + plugins: [], +} + +export default config diff --git a/apps/expense-dashboard/tsconfig.app.json b/apps/expense-dashboard/tsconfig.app.json new file mode 100644 index 0000000000000000000000000000000000000000..1d6297d3f72578e542d49e97de4c2b0c052522b9 --- /dev/null +++ b/apps/expense-dashboard/tsconfig.app.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "target": "ES2020", + "useDefineForClassFields": true, + "lib": ["ES2020", "DOM", "DOM.Iterable"], + "module": "ESNext", + "skipLibCheck": true, + "moduleResolution": "bundler", + "allowImportingTsExtensions": true, + "isolatedModules": true, + "moduleDetection": "force", + "noEmit": true, + "jsx": "react-jsx", + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noFallthroughCasesInSwitch": true, + "paths": { "@/*": ["./src/*"] } + }, + "include": ["src"] +} diff --git a/apps/expense-dashboard/tsconfig.json b/apps/expense-dashboard/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..1ffef600d959ec9e396d5a260bd3f5b927b2cef8 --- /dev/null +++ b/apps/expense-dashboard/tsconfig.json @@ -0,0 +1,7 @@ +{ + "files": [], + "references": [ + { "path": "./tsconfig.app.json" }, + { "path": "./tsconfig.node.json" } + ] +} diff --git a/apps/expense-dashboard/tsconfig.node.json b/apps/expense-dashboard/tsconfig.node.json new file mode 100644 index 0000000000000000000000000000000000000000..aaa8c3b5d22979d393ff558e093d39500e0c7a8e --- /dev/null +++ b/apps/expense-dashboard/tsconfig.node.json @@ -0,0 +1,14 @@ +{ + "compilerOptions": { + "target": "ES2022", + "lib": ["ES2023"], + "module": "ESNext", + "skipLibCheck": true, + "moduleResolution": "bundler", + "allowImportingTsExtensions": true, + "isolatedModules": true, + "moduleDetection": "force", + "noEmit": true + }, + "include": ["vite.config.ts"] +} diff --git a/apps/expense-dashboard/vite.config.ts b/apps/expense-dashboard/vite.config.ts new file mode 100644 index 0000000000000000000000000000000000000000..d7da7fd902f6b9d890296b0bff76f514ae85e87f --- /dev/null +++ b/apps/expense-dashboard/vite.config.ts @@ -0,0 +1,18 @@ +import { defineConfig } from 'vite' +import react from '@vitejs/plugin-react' +import path from 'path' + +export default defineConfig({ + plugins: [react()], + resolve: { + alias: { '@': path.resolve(__dirname, './src') }, + }, + server: { + port: 5173, + proxy: { + '/auth': 'http://localhost:7860', + '/v1': 'http://localhost:7860', + '/health': 'http://localhost:7860', + }, + }, +}) diff --git a/docs/superpowers/specs/2026-07-02-expense-dashboard-design.md b/docs/superpowers/specs/2026-07-02-expense-dashboard-design.md new file mode 100644 index 0000000000000000000000000000000000000000..019334a05362552c0e1f40a04c9b28f36e57517d --- /dev/null +++ b/docs/superpowers/specs/2026-07-02-expense-dashboard-design.md @@ -0,0 +1,217 @@ +# Expense Dashboard Design + +## Overview + +A single-user React web app for managing personal expenses. Lives at `apps/expense-dashboard` in the monorepo. Talks to the existing `apps/api` on port 7860. + +--- + +## Tech Stack + +| Concern | Choice | +|---|---| +| Build tool | Vite | +| Framework | React 18 + TypeScript | +| Styling | Tailwind CSS | +| Components | shadcn/ui | +| Charts | Recharts | +| Auth token | JWT stored in localStorage | +| HTTP | fetch (typed wrappers in `src/api/`) | + +--- + +## Authentication + +Single-user. Login with email + password. + +**Backend addition:** `POST /auth/login` endpoint in `apps/api` +- Accepts `{ email, password }` +- Verifies password against `ADMIN_PASSWORD` env var (bcrypt hash) +- Returns `{ token: }` signed with `JWT_SECRET` env var, 7-day expiry +- JWT payload: `{ sub: 'admin' }` + +**Frontend:** +- Unauthenticated users redirected to `/login` +- JWT stored in `localStorage` as `expense_token` +- All API requests send `Authorization: Bearer ` +- On 401 response → clear token, redirect to `/login` + +--- + +## File Structure + +``` +apps/expense-dashboard/ + src/ + api/ + client.ts ← base fetch wrapper (attaches Bearer token, handles 401) + auth.ts ← login() + expenses.ts ← parse(), create(), list(), update(), delete() + categories.ts ← list(), create(), update(), delete() + budgets.ts ← list(), create(), update(), delete() + analytics.ts ← summary(), trends() + components/ + layout/ + Sidebar.tsx + AppShell.tsx + expenses/ + ExpenseList.tsx + ExpenseRow.tsx + AddExpenseDrawer.tsx ← two tabs: Upload Receipt / Manual Entry + ReceiptPreview.tsx ← parsed result + category picker + CategoryPicker.tsx + analytics/ + SpendDonut.tsx + DailyBarChart.tsx + BudgetCard.tsx + ui/ ← shadcn generated components + pages/ + LoginPage.tsx + DashboardPage.tsx + ExpensesPage.tsx + CategoriesPage.tsx + BudgetsPage.tsx + hooks/ + useAuth.ts + useExpenses.ts + useCategories.ts + useBudgets.ts + useAnalytics.ts + lib/ + auth.ts ← getToken(), clearToken(), isAuthenticated() + dates.ts ← formatMonth(), monthRange() + router.tsx ← React Router v6, protected route wrapper + main.tsx + index.html + vite.config.ts + tailwind.config.ts + tsconfig.json + package.json +``` + +--- + +## Pages + +### Login (`/login`) +- Email + password form +- Calls `POST /auth/login`, stores JWT, redirects to `/` +- No sidebar — full-screen centered card + +### Dashboard (`/`) +- Month picker (default: current month) +- **Total spend vs budget** — large number + overall progress bar +- **Spend by category** — donut chart (Recharts PieChart) +- **Daily spend** — bar chart (Recharts BarChart), x-axis = days of month +- **Budget cards** — one card per category with a budget set: spent / limit, color-coded (green < 80%, amber 80–100%, red > 100%) + +### Expenses (`/expenses`) +- Month picker at top +- Expense list — grouped by date, sorted newest first +- Each row: date, merchant, category badge (color), amount +- Click row → inline edit (amount, merchant, date, category, description) +- Delete button on row +- Floating **+ Add** button → opens `AddExpenseDrawer` + +**AddExpenseDrawer — two tabs:** + +*Upload Receipt* +1. Image dropzone (accepts JPEG/PNG/base64) + optional description textarea +2. "Parse" button → calls `POST /v1/expense/parse` +3. `ReceiptPreview` shows: amount, merchant, date, detected category +4. Category picker: auto-selects if name matches existing category; required picker if no match +5. "Save" → calls `POST /v1/expense/manual` with confirmed data + +*Manual Entry* +- Amount, currency, merchant, date, description fields +- Category picker (required) +- "Save" → calls `POST /v1/expense/manual` + +### Categories (`/categories`) +- List of categories with color swatch and icon +- Add category: name, color (hex picker), emoji icon (optional) +- Edit inline +- Delete (disabled if category has expenses) + +### Budgets (`/budgets`) +- List of monthly budgets, one per category +- Add budget: pick category, set amount +- Edit amount inline +- Delete + +--- + +## Key Flows + +### Receipt Upload + Category Tagging + +``` +User drops image (+ optional description) + → POST /v1/expense/parse → { expense: { amount, merchant, date, category, confidence }, ocrUsed } + → ReceiptPreview rendered + → FE matches expense.category string against categories list (case-insensitive) + match found → category pre-selected, user can override + no match → CategoryPicker shown, required before save + → User confirms + → POST /v1/expense/manual → { id, ... } + → Expense list refreshed +``` + +### Month Navigation + +All pages with a month picker share a `selectedMonth` state (YYYY-MM string). The month picker is a `