ClaraSu commited on
Commit
d917c4e
·
verified ·
1 Parent(s): 917bcbe

Upload folder using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. apps/api/package.json +4 -0
  2. apps/api/src/auth/auth.routes.ts +39 -0
  3. apps/api/src/middleware/authMiddleware.ts +21 -8
  4. apps/api/src/proxy.ts +4 -2
  5. apps/expense-dashboard/components.json +23 -0
  6. apps/expense-dashboard/index.html +12 -0
  7. apps/expense-dashboard/package.json +40 -0
  8. apps/expense-dashboard/postcss.config.js +3 -0
  9. apps/expense-dashboard/src/App.tsx +5 -0
  10. apps/expense-dashboard/src/api/analytics.ts +14 -0
  11. apps/expense-dashboard/src/api/auth.ts +13 -0
  12. apps/expense-dashboard/src/api/budgets.ts +37 -0
  13. apps/expense-dashboard/src/api/categories.ts +40 -0
  14. apps/expense-dashboard/src/api/client.ts +20 -0
  15. apps/expense-dashboard/src/api/expenses.ts +76 -0
  16. apps/expense-dashboard/src/components/analytics/BudgetCard.tsx +38 -0
  17. apps/expense-dashboard/src/components/analytics/DailyBarChart.tsx +32 -0
  18. apps/expense-dashboard/src/components/analytics/SpendDonut.tsx +38 -0
  19. apps/expense-dashboard/src/components/expenses/AddExpenseDrawer.tsx +253 -0
  20. apps/expense-dashboard/src/components/expenses/CategoryPicker.tsx +29 -0
  21. apps/expense-dashboard/src/components/expenses/ExpenseList.tsx +55 -0
  22. apps/expense-dashboard/src/components/expenses/ExpenseRow.tsx +151 -0
  23. apps/expense-dashboard/src/components/expenses/ReceiptPreview.tsx +78 -0
  24. apps/expense-dashboard/src/components/layout/AppShell.tsx +12 -0
  25. apps/expense-dashboard/src/components/layout/Sidebar.tsx +63 -0
  26. apps/expense-dashboard/src/components/ui/badge.tsx +36 -0
  27. apps/expense-dashboard/src/components/ui/button.tsx +56 -0
  28. apps/expense-dashboard/src/components/ui/card.tsx +79 -0
  29. apps/expense-dashboard/src/components/ui/dialog.tsx +120 -0
  30. apps/expense-dashboard/src/components/ui/input.tsx +22 -0
  31. apps/expense-dashboard/src/components/ui/label.tsx +24 -0
  32. apps/expense-dashboard/src/components/ui/progress.tsx +28 -0
  33. apps/expense-dashboard/src/components/ui/select.tsx +160 -0
  34. apps/expense-dashboard/src/components/ui/separator.tsx +29 -0
  35. apps/expense-dashboard/src/components/ui/table.tsx +117 -0
  36. apps/expense-dashboard/src/components/ui/tabs.tsx +53 -0
  37. apps/expense-dashboard/src/hooks/useAnalytics.ts +28 -0
  38. apps/expense-dashboard/src/hooks/useBudgets.ts +42 -0
  39. apps/expense-dashboard/src/hooks/useCategories.ts +42 -0
  40. apps/expense-dashboard/src/hooks/useExpenses.ts +44 -0
  41. apps/expense-dashboard/src/index.css +31 -0
  42. apps/expense-dashboard/src/lib/auth.ts +17 -0
  43. apps/expense-dashboard/src/lib/dates.ts +31 -0
  44. apps/expense-dashboard/src/lib/utils.ts +6 -0
  45. apps/expense-dashboard/src/main.tsx +10 -0
  46. apps/expense-dashboard/src/pages/BudgetsPage.tsx +159 -0
  47. apps/expense-dashboard/src/pages/CategoriesPage.tsx +157 -0
  48. apps/expense-dashboard/src/pages/DashboardPage.tsx +101 -0
  49. apps/expense-dashboard/src/pages/ExpensesPage.tsx +82 -0
  50. apps/expense-dashboard/src/pages/LoginPage.tsx +70 -0
apps/api/package.json CHANGED
@@ -21,14 +21,18 @@
21
  "@llm-router/shared": "workspace:*",
22
  "@neondatabase/serverless": "^1.1.0",
23
  "@types/express": "^5.0.6",
 
24
  "dotenv": "^17.4.2",
25
  "drizzle-orm": "^0.45.2",
26
  "express": "^5.2.1",
 
27
  "ollama": "^0.6.3",
28
  "tesseract.js": "^5.1.0",
29
  "zod": "^4.4.3"
30
  },
31
  "devDependencies": {
 
 
32
  "@types/node": "^25.6.0",
33
  "drizzle-kit": "^0.31.10",
34
  "tsx": "^4.21.0",
 
21
  "@llm-router/shared": "workspace:*",
22
  "@neondatabase/serverless": "^1.1.0",
23
  "@types/express": "^5.0.6",
24
+ "bcrypt": "^6.0.0",
25
  "dotenv": "^17.4.2",
26
  "drizzle-orm": "^0.45.2",
27
  "express": "^5.2.1",
28
+ "jsonwebtoken": "^9.0.3",
29
  "ollama": "^0.6.3",
30
  "tesseract.js": "^5.1.0",
31
  "zod": "^4.4.3"
32
  },
33
  "devDependencies": {
34
+ "@types/bcrypt": "^6.0.0",
35
+ "@types/jsonwebtoken": "^9.0.10",
36
  "@types/node": "^25.6.0",
37
  "drizzle-kit": "^0.31.10",
38
  "tsx": "^4.21.0",
apps/api/src/auth/auth.routes.ts ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Router, type IRouter } from 'express'
2
+ import bcrypt from 'bcrypt'
3
+ import jwt from 'jsonwebtoken'
4
+
5
+ const router: IRouter = Router()
6
+
7
+ router.post('/auth/login', async (req, res) => {
8
+ const { email, password } = req.body as { email?: string; password?: string }
9
+
10
+ if (!email || !password) {
11
+ res.status(400).json({ error: 'email and password required' })
12
+ return
13
+ }
14
+
15
+ const expectedEmail = process.env['ADMIN_EMAIL']
16
+ const passwordHash = process.env['ADMIN_PASSWORD_HASH']
17
+ const jwtSecret = process.env['JWT_SECRET']
18
+
19
+ if (!expectedEmail || !passwordHash || !jwtSecret) {
20
+ res.status(500).json({ error: 'Server auth not configured' })
21
+ return
22
+ }
23
+
24
+ if (email !== expectedEmail) {
25
+ res.status(401).json({ error: 'Invalid credentials' })
26
+ return
27
+ }
28
+
29
+ const valid = await bcrypt.compare(password, passwordHash)
30
+ if (!valid) {
31
+ res.status(401).json({ error: 'Invalid credentials' })
32
+ return
33
+ }
34
+
35
+ const token = jwt.sign({ sub: 'admin' }, jwtSecret, { expiresIn: '7d' })
36
+ res.json({ token })
37
+ })
38
+
39
+ export { router as authRouter }
apps/api/src/middleware/authMiddleware.ts CHANGED
@@ -1,13 +1,26 @@
1
- import { Request, Response, NextFunction, RequestHandler } from 'express'
 
2
 
3
  export const authMiddleware = (req: Request, res: Response, next: NextFunction) => {
4
  if (req.path === '/health') return next()
5
 
6
- const key = req.headers['x-internal-key'] as string
7
- const bearerKey = (req.headers['authorization'] as string)?.replace('Bearer', '').trim()
8
- const expected = process.env.INTERNAL_SECRET
9
- if (expected && key !== expected && bearerKey !== expected) {
10
- return res.status(401).json({ error: 'Unauthorized' })
 
 
 
 
 
 
 
 
 
 
 
11
  }
12
- next()
13
- }
 
 
1
+ import type { Request, Response, NextFunction } from 'express'
2
+ import jwt from 'jsonwebtoken'
3
 
4
  export const authMiddleware = (req: Request, res: Response, next: NextFunction) => {
5
  if (req.path === '/health') return next()
6
 
7
+ const key = req.headers['x-internal-key'] as string | undefined
8
+ const bearerToken = (req.headers['authorization'] as string | undefined)
9
+ ?.replace(/^Bearer\s+/i, '')
10
+ .trim()
11
+ const expectedKey = process.env['INTERNAL_SECRET']
12
+ const jwtSecret = process.env['JWT_SECRET']
13
+
14
+ if (expectedKey && (key === expectedKey || bearerToken === expectedKey)) return next()
15
+
16
+ if (jwtSecret && bearerToken) {
17
+ try {
18
+ jwt.verify(bearerToken, jwtSecret)
19
+ return next()
20
+ } catch {
21
+ // invalid JWT — fall through to 401
22
+ }
23
  }
24
+
25
+ res.status(401).json({ error: 'Unauthorized' })
26
+ }
apps/api/src/proxy.ts CHANGED
@@ -1,6 +1,7 @@
1
  import 'dotenv/config'
2
  import express from 'express'
3
  import { authMiddleware } from './middleware/authMiddleware'
 
4
  import { chatRouter } from './chat/chat.routes'
5
  import { expenseRouter } from './expense/expense.routes'
6
  import { healthRouter } from './health/health.routes'
@@ -15,13 +16,14 @@ app.use(express.raw({ limit: '50mb', type: ['image/*', 'application/octet-stream
15
 
16
  app.use((req, res, next) => {
17
  res.setHeader('Access-Control-Allow-Origin', '*')
18
- res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
19
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, x-internal-key')
20
  if (req.method === 'OPTIONS') { res.sendStatus(204); return }
21
  next()
22
  })
23
 
24
- app.use(authMiddleware)
 
25
 
26
  app.use(healthRouter)
27
  app.use('/v1', chatRouter)
 
1
  import 'dotenv/config'
2
  import express from 'express'
3
  import { authMiddleware } from './middleware/authMiddleware'
4
+ import { authRouter } from './auth/auth.routes'
5
  import { chatRouter } from './chat/chat.routes'
6
  import { expenseRouter } from './expense/expense.routes'
7
  import { healthRouter } from './health/health.routes'
 
16
 
17
  app.use((req, res, next) => {
18
  res.setHeader('Access-Control-Allow-Origin', '*')
19
+ res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS')
20
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, x-internal-key')
21
  if (req.method === 'OPTIONS') { res.sendStatus(204); return }
22
  next()
23
  })
24
 
25
+ app.use(authRouter) // /auth/login is public
26
+ app.use(authMiddleware) // all other routes require auth
27
 
28
  app.use(healthRouter)
29
  app.use('/v1', chatRouter)
apps/expense-dashboard/components.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "$schema": "https://ui.shadcn.com/schema.json",
3
+ "style": "default",
4
+ "rsc": false,
5
+ "tsx": true,
6
+ "tailwind": {
7
+ "config": "tailwind.config.ts",
8
+ "css": "src/index.css",
9
+ "baseColor": "slate",
10
+ "cssVariables": true
11
+ },
12
+ "aliases": {
13
+ "components": "@/components",
14
+ "utils": "@/lib/utils"
15
+ },
16
+ "resolvedPaths": {
17
+ "tailwindConfig": "/Users/sumyatmon/Documents/Projects/exercise/llm_router/apps/expense-dashboard/tailwind.config.ts",
18
+ "tailwindCss": "/Users/sumyatmon/Documents/Projects/exercise/llm_router/apps/expense-dashboard/src/index.css",
19
+ "utils": "/Users/sumyatmon/Documents/Projects/exercise/llm_router/apps/expense-dashboard/src/lib/utils",
20
+ "components": "/Users/sumyatmon/Documents/Projects/exercise/llm_router/apps/expense-dashboard/src/components",
21
+ "ui": "/Users/sumyatmon/Documents/Projects/exercise/llm_router/apps/expense-dashboard/src/components/ui"
22
+ }
23
+ }
apps/expense-dashboard/index.html ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <title>Expense Dashboard</title>
7
+ </head>
8
+ <body>
9
+ <div id="root"></div>
10
+ <script type="module" src="/src/main.tsx"></script>
11
+ </body>
12
+ </html>
apps/expense-dashboard/package.json ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "@llm-router/expense-dashboard",
3
+ "version": "0.1.0",
4
+ "private": true,
5
+ "type": "module",
6
+ "scripts": {
7
+ "dev": "vite",
8
+ "build": "tsc -b && vite build",
9
+ "preview": "vite preview"
10
+ },
11
+ "dependencies": {
12
+ "@llm-router/shared": "workspace:*",
13
+ "@radix-ui/react-dialog": "^1.1.18",
14
+ "@radix-ui/react-label": "^2.1.11",
15
+ "@radix-ui/react-progress": "^1.1.11",
16
+ "@radix-ui/react-select": "^2.3.2",
17
+ "@radix-ui/react-separator": "^1.1.11",
18
+ "@radix-ui/react-slot": "^1.3.0",
19
+ "@radix-ui/react-tabs": "^1.1.16",
20
+ "class-variance-authority": "^0.7.1",
21
+ "clsx": "^2.1.1",
22
+ "lucide-react": "^0.462.0",
23
+ "react": "^18.3.1",
24
+ "react-dom": "^18.3.1",
25
+ "react-router-dom": "^6.28.0",
26
+ "recharts": "^2.13.0",
27
+ "tailwind-merge": "^2.5.4"
28
+ },
29
+ "devDependencies": {
30
+ "@types/node": "^22.0.0",
31
+ "@types/react": "^18.3.12",
32
+ "@types/react-dom": "^18.3.1",
33
+ "@vitejs/plugin-react": "^4.3.3",
34
+ "autoprefixer": "^10.4.20",
35
+ "postcss": "^8.4.47",
36
+ "tailwindcss": "^3.4.14",
37
+ "typescript": "^5.6.3",
38
+ "vite": "^5.4.10"
39
+ }
40
+ }
apps/expense-dashboard/postcss.config.js ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ export default {
2
+ plugins: { tailwindcss: {}, autoprefixer: {} },
3
+ }
apps/expense-dashboard/src/App.tsx ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ import AppRouter from './router'
2
+
3
+ export default function App() {
4
+ return <AppRouter />
5
+ }
apps/expense-dashboard/src/api/analytics.ts ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { apiFetch } from './client'
2
+ import type { Summary, Trends } from '@llm-router/shared'
3
+
4
+ export async function getSummary(): Promise<Summary> {
5
+ const res = await apiFetch('/v1/expense/summary')
6
+ if (!res.ok) throw new Error('Failed to load summary')
7
+ return res.json() as Promise<Summary>
8
+ }
9
+
10
+ export async function getTrends(months = 6): Promise<Trends> {
11
+ const res = await apiFetch(`/v1/expense/trends?months=${months}`)
12
+ if (!res.ok) throw new Error('Failed to load trends')
13
+ return res.json() as Promise<Trends>
14
+ }
apps/expense-dashboard/src/api/auth.ts ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { apiFetch } from './client'
2
+
3
+ export async function login(email: string, password: string): Promise<{ token: string }> {
4
+ const res = await apiFetch('/auth/login', {
5
+ method: 'POST',
6
+ body: JSON.stringify({ email, password }),
7
+ })
8
+ if (!res.ok) {
9
+ const err = await res.json() as { error?: string }
10
+ throw new Error(err.error ?? 'Login failed')
11
+ }
12
+ return res.json() as Promise<{ token: string }>
13
+ }
apps/expense-dashboard/src/api/budgets.ts ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { apiFetch } from './client'
2
+ import type { Budget, CreateBudget, UpdateBudget } from '@llm-router/shared'
3
+
4
+ export async function listBudgets(): Promise<Budget[]> {
5
+ const res = await apiFetch('/v1/expense/budgets')
6
+ if (!res.ok) throw new Error('Failed to load budgets')
7
+ return res.json() as Promise<Budget[]>
8
+ }
9
+
10
+ export async function createBudget(data: CreateBudget): Promise<Budget> {
11
+ const res = await apiFetch('/v1/expense/budgets', {
12
+ method: 'POST',
13
+ body: JSON.stringify(data),
14
+ })
15
+ if (!res.ok) {
16
+ const err = await res.json() as { error?: string }
17
+ throw new Error(err.error ?? 'Failed to create budget')
18
+ }
19
+ return res.json() as Promise<Budget>
20
+ }
21
+
22
+ export async function updateBudget(id: string, data: UpdateBudget): Promise<Budget> {
23
+ const res = await apiFetch(`/v1/expense/budgets/${id}`, {
24
+ method: 'PUT',
25
+ body: JSON.stringify(data),
26
+ })
27
+ if (!res.ok) {
28
+ const err = await res.json() as { error?: string }
29
+ throw new Error(err.error ?? 'Failed to update budget')
30
+ }
31
+ return res.json() as Promise<Budget>
32
+ }
33
+
34
+ export async function deleteBudget(id: string): Promise<void> {
35
+ const res = await apiFetch(`/v1/expense/budgets/${id}`, { method: 'DELETE' })
36
+ if (!res.ok) throw new Error('Failed to delete budget')
37
+ }
apps/expense-dashboard/src/api/categories.ts ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { apiFetch } from './client'
2
+ import type { Category, CreateCategory, UpdateCategory } from '@llm-router/shared'
3
+
4
+ export async function listCategories(): Promise<Category[]> {
5
+ const res = await apiFetch('/v1/expense/categories')
6
+ if (!res.ok) throw new Error('Failed to load categories')
7
+ return res.json() as Promise<Category[]>
8
+ }
9
+
10
+ export async function createCategory(data: CreateCategory): Promise<Category> {
11
+ const res = await apiFetch('/v1/expense/categories', {
12
+ method: 'POST',
13
+ body: JSON.stringify(data),
14
+ })
15
+ if (!res.ok) {
16
+ const err = await res.json() as { error?: string }
17
+ throw new Error(err.error ?? 'Failed to create category')
18
+ }
19
+ return res.json() as Promise<Category>
20
+ }
21
+
22
+ export async function updateCategory(id: string, data: UpdateCategory): Promise<Category> {
23
+ const res = await apiFetch(`/v1/expense/categories/${id}`, {
24
+ method: 'PUT',
25
+ body: JSON.stringify(data),
26
+ })
27
+ if (!res.ok) {
28
+ const err = await res.json() as { error?: string }
29
+ throw new Error(err.error ?? 'Failed to update category')
30
+ }
31
+ return res.json() as Promise<Category>
32
+ }
33
+
34
+ export async function deleteCategory(id: string): Promise<void> {
35
+ const res = await apiFetch(`/v1/expense/categories/${id}`, { method: 'DELETE' })
36
+ if (!res.ok) {
37
+ const err = await res.json() as { error?: string }
38
+ throw new Error(err.error ?? 'Failed to delete category')
39
+ }
40
+ }
apps/expense-dashboard/src/api/client.ts ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { getToken, clearToken } from '@/lib/auth'
2
+
3
+ export async function apiFetch(path: string, options: RequestInit = {}): Promise<Response> {
4
+ const token = getToken()
5
+ const res = await fetch(path, {
6
+ ...options,
7
+ headers: {
8
+ 'Content-Type': 'application/json',
9
+ ...(token ? { Authorization: `Bearer ${token}` } : {}),
10
+ ...(options.headers as Record<string, string> | undefined ?? {}),
11
+ },
12
+ })
13
+
14
+ if (res.status === 401) {
15
+ clearToken()
16
+ window.location.href = '/login'
17
+ }
18
+
19
+ return res
20
+ }
apps/expense-dashboard/src/api/expenses.ts ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { apiFetch } from './client'
2
+ import { monthRange } from '@/lib/dates'
3
+ import type { Expense, CreateExpense, UpdateExpense } from '@llm-router/shared'
4
+
5
+ export interface ParsedExpenseResult {
6
+ amount: number
7
+ currency: string
8
+ date: string | null
9
+ merchant: string | null
10
+ category: string
11
+ confidence: number
12
+ raw_description: string
13
+ }
14
+
15
+ export interface ParseReceiptResponse {
16
+ success: boolean
17
+ expense: ParsedExpenseResult
18
+ ocrUsed: boolean
19
+ }
20
+
21
+ export async function parseReceipt(data: { text?: string; image?: string }): Promise<ParseReceiptResponse> {
22
+ const res = await apiFetch('/v1/expense/parse', {
23
+ method: 'POST',
24
+ body: JSON.stringify(data),
25
+ })
26
+ if (!res.ok) {
27
+ const err = await res.json() as { error?: string }
28
+ throw new Error(err.error ?? 'Failed to parse receipt')
29
+ }
30
+ return res.json() as Promise<ParseReceiptResponse>
31
+ }
32
+
33
+ export async function createExpense(data: CreateExpense): Promise<Expense> {
34
+ const res = await apiFetch('/v1/expense/manual', {
35
+ method: 'POST',
36
+ body: JSON.stringify(data),
37
+ })
38
+ if (!res.ok) {
39
+ const err = await res.json() as { error?: string }
40
+ throw new Error(err.error ?? 'Failed to create expense')
41
+ }
42
+ return res.json() as Promise<Expense>
43
+ }
44
+
45
+ export interface ListExpensesResult {
46
+ data: Expense[]
47
+ total: number
48
+ page: number
49
+ limit: number
50
+ }
51
+
52
+ export async function listExpenses(month: string): Promise<Expense[]> {
53
+ const { from, to } = monthRange(month)
54
+ const params = new URLSearchParams({ from, to, limit: '200' })
55
+ const res = await apiFetch(`/v1/expense?${params.toString()}`)
56
+ if (!res.ok) throw new Error('Failed to load expenses')
57
+ const result = await res.json() as ListExpensesResult
58
+ return result.data
59
+ }
60
+
61
+ export async function updateExpense(id: string, data: UpdateExpense): Promise<Expense> {
62
+ const res = await apiFetch(`/v1/expense/${id}`, {
63
+ method: 'PUT',
64
+ body: JSON.stringify(data),
65
+ })
66
+ if (!res.ok) {
67
+ const err = await res.json() as { error?: string }
68
+ throw new Error(err.error ?? 'Failed to update expense')
69
+ }
70
+ return res.json() as Promise<Expense>
71
+ }
72
+
73
+ export async function deleteExpense(id: string): Promise<void> {
74
+ const res = await apiFetch(`/v1/expense/${id}`, { method: 'DELETE' })
75
+ if (!res.ok) throw new Error('Failed to delete expense')
76
+ }
apps/expense-dashboard/src/components/analytics/BudgetCard.tsx ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Card, CardContent } from '@/components/ui/card'
2
+ import { Progress } from '@/components/ui/progress'
3
+ import { cn } from '@/lib/utils'
4
+ import type { SummaryItem } from '@llm-router/shared'
5
+
6
+ interface Props { item: SummaryItem }
7
+
8
+ export default function BudgetCard({ item }: Props) {
9
+ const hasBudget = item.budget !== null && item.budget > 0
10
+ const pct = hasBudget ? Math.min((item.spent / (item.budget ?? 1)) * 100, 100) : 0
11
+ const statusColor = pct >= 100 ? 'text-destructive' : pct >= 80 ? 'text-yellow-600' : 'text-green-600'
12
+
13
+ return (
14
+ <Card>
15
+ <CardContent className="pt-4 space-y-2">
16
+ <div className="flex items-center justify-between">
17
+ <div className="flex items-center gap-2">
18
+ <span className="w-2.5 h-2.5 rounded-full" style={{ backgroundColor: item.color }} />
19
+ <span className="text-sm font-medium">{item.category_name}</span>
20
+ </div>
21
+ <span className={cn('text-sm font-semibold tabular-nums', statusColor)}>
22
+ ฿{item.spent.toLocaleString()}
23
+ {hasBudget && <span className="text-muted-foreground font-normal"> / ฿{(item.budget ?? 0).toLocaleString()}</span>}
24
+ </span>
25
+ </div>
26
+ {hasBudget && (
27
+ <Progress
28
+ value={pct}
29
+ className={cn('h-1.5', pct >= 100 ? '[&>div]:bg-destructive' : pct >= 80 ? '[&>div]:bg-yellow-500' : '')}
30
+ />
31
+ )}
32
+ {!hasBudget && (
33
+ <p className="text-xs text-muted-foreground">No budget set</p>
34
+ )}
35
+ </CardContent>
36
+ </Card>
37
+ )
38
+ }
apps/expense-dashboard/src/components/analytics/DailyBarChart.tsx ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer, CartesianGrid } from 'recharts'
2
+ import type { Expense } from '@llm-router/shared'
3
+
4
+ interface Props { expenses: Expense[] }
5
+
6
+ export default function DailyBarChart({ expenses }: Props) {
7
+ const grouped = expenses.reduce<Record<string, number>>((acc, e) => {
8
+ const day = e.date.slice(8, 10) // DD from YYYY-MM-DD
9
+ acc[day] = (acc[day] ?? 0) + Number(e.amount)
10
+ return acc
11
+ }, {})
12
+
13
+ const data = Object.entries(grouped)
14
+ .sort(([a], [b]) => a.localeCompare(b))
15
+ .map(([day, total]) => ({ day, total }))
16
+
17
+ if (data.length === 0) {
18
+ return <div className="flex items-center justify-center h-48 text-muted-foreground text-sm">No data</div>
19
+ }
20
+
21
+ return (
22
+ <ResponsiveContainer width="100%" height={200}>
23
+ <BarChart data={data} margin={{ top: 4, right: 8, left: -8, bottom: 0 }}>
24
+ <CartesianGrid strokeDasharray="3 3" vertical={false} />
25
+ <XAxis dataKey="day" tick={{ fontSize: 11 }} />
26
+ <YAxis tick={{ fontSize: 11 }} />
27
+ <Tooltip formatter={(v: number) => `฿${v.toLocaleString()}`} />
28
+ <Bar dataKey="total" fill="hsl(var(--primary))" radius={[3, 3, 0, 0]} />
29
+ </BarChart>
30
+ </ResponsiveContainer>
31
+ )
32
+ }
apps/expense-dashboard/src/components/analytics/SpendDonut.tsx ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { PieChart, Pie, Cell, Tooltip, Legend, ResponsiveContainer } from 'recharts'
2
+ import type { SummaryItem } from '@llm-router/shared'
3
+
4
+ interface Props { categories: SummaryItem[] }
5
+
6
+ export default function SpendDonut({ categories }: Props) {
7
+ const data = categories.filter(c => c.spent > 0).map(c => ({
8
+ name: c.category_name,
9
+ value: c.spent,
10
+ color: c.color,
11
+ }))
12
+
13
+ if (data.length === 0) {
14
+ return <div className="flex items-center justify-center h-48 text-muted-foreground text-sm">No spend data</div>
15
+ }
16
+
17
+ return (
18
+ <ResponsiveContainer width="100%" height={240}>
19
+ <PieChart>
20
+ <Pie
21
+ data={data}
22
+ cx="50%"
23
+ cy="50%"
24
+ innerRadius={60}
25
+ outerRadius={90}
26
+ paddingAngle={2}
27
+ dataKey="value"
28
+ >
29
+ {data.map((entry, i) => (
30
+ <Cell key={i} fill={entry.color} />
31
+ ))}
32
+ </Pie>
33
+ <Tooltip formatter={(v: number) => `฿${v.toLocaleString()}`} />
34
+ <Legend />
35
+ </PieChart>
36
+ </ResponsiveContainer>
37
+ )
38
+ }
apps/expense-dashboard/src/components/expenses/AddExpenseDrawer.tsx ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useState, useRef } from 'react'
2
+ import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
3
+ import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
4
+ import { Button } from '@/components/ui/button'
5
+ import { Input } from '@/components/ui/input'
6
+ import { Label } from '@/components/ui/label'
7
+ import CategoryPicker from './CategoryPicker'
8
+ import ReceiptPreview from './ReceiptPreview'
9
+ import { parseReceipt } from '@/api/expenses'
10
+ import type { Category, CreateExpense } from '@llm-router/shared'
11
+ import type { ParsedExpenseResult } from '@/api/expenses'
12
+
13
+ interface Props {
14
+ open: boolean
15
+ onOpenChange: (open: boolean) => void
16
+ categories: Category[]
17
+ onSave: (data: CreateExpense) => Promise<void>
18
+ }
19
+
20
+ function ManualTab({ categories, onSave, onClose }: {
21
+ categories: Category[]
22
+ onSave: (data: CreateExpense) => Promise<void>
23
+ onClose: () => void
24
+ }) {
25
+ const today = new Date().toISOString().slice(0, 10)
26
+ const [amount, setAmount] = useState('')
27
+ const [currency, setCurrency] = useState('THB')
28
+ const [merchant, setMerchant] = useState('')
29
+ const [date, setDate] = useState(today)
30
+ const [categoryId, setCategoryId] = useState('')
31
+ const [description, setDescription] = useState('')
32
+ const [saving, setSaving] = useState(false)
33
+ const [error, setError] = useState<string | null>(null)
34
+
35
+ async function handleSave() {
36
+ const amt = Number(amount)
37
+ if (!amount || isNaN(amt) || amt <= 0) { setError('Enter a valid amount'); return }
38
+ if (!categoryId) { setError('Select a category'); return }
39
+ if (!date) { setError('Enter a date'); return }
40
+ setSaving(true)
41
+ setError(null)
42
+ try {
43
+ await onSave({
44
+ amount: amt,
45
+ currency,
46
+ category_id: categoryId,
47
+ date,
48
+ ...(merchant.trim() ? { merchant: merchant.trim() } : {}),
49
+ ...(description.trim() ? { description: description.trim() } : {}),
50
+ })
51
+ onClose()
52
+ } catch (err) {
53
+ setError(err instanceof Error ? err.message : 'Save failed')
54
+ } finally {
55
+ setSaving(false)
56
+ }
57
+ }
58
+
59
+ return (
60
+ <div className="space-y-3 pt-2">
61
+ <div className="grid grid-cols-2 gap-3">
62
+ <div className="space-y-1">
63
+ <Label>Amount</Label>
64
+ <Input type="number" min="0" value={amount} onChange={e => setAmount(e.target.value)} placeholder="350" autoFocus />
65
+ </div>
66
+ <div className="space-y-1">
67
+ <Label>Currency</Label>
68
+ <Input value={currency} onChange={e => setCurrency(e.target.value)} placeholder="THB" />
69
+ </div>
70
+ </div>
71
+ <div className="space-y-1">
72
+ <Label>Merchant</Label>
73
+ <Input value={merchant} onChange={e => setMerchant(e.target.value)} placeholder="Grab Food" />
74
+ </div>
75
+ <div className="space-y-1">
76
+ <Label>Date</Label>
77
+ <Input type="date" value={date} onChange={e => setDate(e.target.value)} />
78
+ </div>
79
+ <div className="space-y-1">
80
+ <Label>Category</Label>
81
+ <CategoryPicker categories={categories} value={categoryId} onChange={setCategoryId} />
82
+ </div>
83
+ <div className="space-y-1">
84
+ <Label>Description (optional)</Label>
85
+ <Input value={description} onChange={e => setDescription(e.target.value)} placeholder="Business lunch" />
86
+ </div>
87
+ {error && <p className="text-sm text-destructive">{error}</p>}
88
+ <div className="flex justify-end gap-2 pt-2">
89
+ <Button variant="outline" onClick={onClose}>Cancel</Button>
90
+ <Button onClick={() => void handleSave()} disabled={saving}>
91
+ {saving ? 'Saving…' : 'Save'}
92
+ </Button>
93
+ </div>
94
+ </div>
95
+ )
96
+ }
97
+
98
+ function UploadTab({ categories, onSave, onClose }: {
99
+ categories: Category[]
100
+ onSave: (data: CreateExpense) => Promise<void>
101
+ onClose: () => void
102
+ }) {
103
+ const fileRef = useRef<HTMLInputElement>(null)
104
+ const [description, setDescription] = useState('')
105
+ const [imageFile, setImageFile] = useState<File | null>(null)
106
+ const [imagePreview, setImagePreview] = useState<string | null>(null)
107
+ const [parsing, setParsing] = useState(false)
108
+ const [parsed, setParsed] = useState<{ result: ParsedExpenseResult; ocrUsed: boolean } | null>(null)
109
+ const [saving, setSaving] = useState(false)
110
+ const [error, setError] = useState<string | null>(null)
111
+
112
+ function handleFileChange(e: React.ChangeEvent<HTMLInputElement>) {
113
+ const file = e.target.files?.[0]
114
+ if (!file) return
115
+ setImageFile(file)
116
+ const reader = new FileReader()
117
+ reader.onload = ev => setImagePreview(ev.target?.result as string)
118
+ reader.readAsDataURL(file)
119
+ }
120
+
121
+ async function handleParse() {
122
+ if (!imageFile && !description.trim()) {
123
+ setError('Provide a receipt image, description, or both')
124
+ return
125
+ }
126
+ setParsing(true)
127
+ setError(null)
128
+ try {
129
+ let imageBase64: string | undefined
130
+ if (imageFile && imagePreview) {
131
+ // strip "data:image/...;base64," prefix
132
+ imageBase64 = imagePreview.split(',')[1] ?? imagePreview
133
+ }
134
+ const res = await parseReceipt({
135
+ ...(description.trim() ? { text: description.trim() } : {}),
136
+ ...(imageBase64 ? { image: imageBase64 } : {}),
137
+ })
138
+ setParsed({ result: res.expense, ocrUsed: res.ocrUsed })
139
+ } catch (err) {
140
+ setError(err instanceof Error ? err.message : 'Parse failed')
141
+ } finally {
142
+ setParsing(false)
143
+ }
144
+ }
145
+
146
+ async function handleConfirm(categoryId: string) {
147
+ if (!parsed) return
148
+ const today = new Date().toISOString().slice(0, 10)
149
+ setSaving(true)
150
+ try {
151
+ await onSave({
152
+ amount: parsed.result.amount,
153
+ currency: parsed.result.currency || 'THB',
154
+ category_id: categoryId,
155
+ date: parsed.result.date ?? today,
156
+ ...(parsed.result.merchant ? { merchant: parsed.result.merchant } : {}),
157
+ ...(description.trim() ? { description: description.trim() } : {}),
158
+ })
159
+ onClose()
160
+ } catch (err) {
161
+ setError(err instanceof Error ? err.message : 'Save failed')
162
+ setSaving(false)
163
+ }
164
+ }
165
+
166
+ if (parsed) {
167
+ return (
168
+ <ReceiptPreview
169
+ parsed={parsed.result}
170
+ categories={categories}
171
+ ocrUsed={parsed.ocrUsed}
172
+ onConfirm={handleConfirm}
173
+ onCancel={() => setParsed(null)}
174
+ saving={saving}
175
+ />
176
+ )
177
+ }
178
+
179
+ return (
180
+ <div className="space-y-4 pt-2">
181
+ <div className="space-y-1">
182
+ <Label>Receipt image (optional)</Label>
183
+ <div
184
+ className="border-2 border-dashed rounded-lg p-4 text-center cursor-pointer hover:bg-muted/50 transition-colors"
185
+ onClick={() => fileRef.current?.click()}
186
+ >
187
+ {imagePreview ? (
188
+ <img src={imagePreview} alt="receipt" className="max-h-40 mx-auto rounded object-contain" />
189
+ ) : (
190
+ <p className="text-sm text-muted-foreground">Click to upload or drag & drop<br />JPEG / PNG</p>
191
+ )}
192
+ </div>
193
+ <input ref={fileRef} type="file" accept="image/*" className="hidden" onChange={handleFileChange} />
194
+ </div>
195
+ <div className="space-y-1">
196
+ <Label>Description / note (optional)</Label>
197
+ <Input
198
+ value={description}
199
+ onChange={e => setDescription(e.target.value)}
200
+ placeholder="e.g. Grab food 350 baht, business lunch"
201
+ />
202
+ </div>
203
+ {error && <p className="text-sm text-destructive">{error}</p>}
204
+ <div className="flex justify-end gap-2">
205
+ <Button variant="outline" onClick={onClose}>Cancel</Button>
206
+ <Button onClick={() => void handleParse()} disabled={parsing}>
207
+ {parsing ? 'Parsing…' : 'Parse receipt'}
208
+ </Button>
209
+ </div>
210
+ </div>
211
+ )
212
+ }
213
+
214
+ export default function AddExpenseDrawer({ open, onOpenChange, categories, onSave }: Props) {
215
+ const [tabKey, setTabKey] = useState(0)
216
+
217
+ function handleOpenChange(newOpen: boolean) {
218
+ if (!newOpen) setTabKey(k => k + 1)
219
+ onOpenChange(newOpen)
220
+ }
221
+
222
+ return (
223
+ <Dialog open={open} onOpenChange={handleOpenChange}>
224
+ <DialogContent className="sm:max-w-md">
225
+ <DialogHeader>
226
+ <DialogTitle>Add Expense</DialogTitle>
227
+ </DialogHeader>
228
+ <Tabs defaultValue="upload">
229
+ <TabsList className="w-full">
230
+ <TabsTrigger value="upload" className="flex-1">Upload Receipt</TabsTrigger>
231
+ <TabsTrigger value="manual" className="flex-1">Manual Entry</TabsTrigger>
232
+ </TabsList>
233
+ <TabsContent value="upload">
234
+ <UploadTab
235
+ key={tabKey}
236
+ categories={categories}
237
+ onSave={onSave}
238
+ onClose={() => onOpenChange(false)}
239
+ />
240
+ </TabsContent>
241
+ <TabsContent value="manual">
242
+ <ManualTab
243
+ key={tabKey}
244
+ categories={categories}
245
+ onSave={onSave}
246
+ onClose={() => onOpenChange(false)}
247
+ />
248
+ </TabsContent>
249
+ </Tabs>
250
+ </DialogContent>
251
+ </Dialog>
252
+ )
253
+ }
apps/expense-dashboard/src/components/expenses/CategoryPicker.tsx ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
2
+ import type { Category } from '@llm-router/shared'
3
+
4
+ interface Props {
5
+ categories: Category[]
6
+ value: string
7
+ onChange: (id: string) => void
8
+ placeholder?: string
9
+ }
10
+
11
+ export default function CategoryPicker({ categories, value, onChange, placeholder = 'Select category…' }: Props) {
12
+ return (
13
+ <Select value={value} onValueChange={onChange}>
14
+ <SelectTrigger>
15
+ <SelectValue placeholder={placeholder} />
16
+ </SelectTrigger>
17
+ <SelectContent>
18
+ {categories.map(c => (
19
+ <SelectItem key={c.id} value={c.id}>
20
+ <span className="flex items-center gap-2">
21
+ <span className="w-2.5 h-2.5 rounded-full inline-block" style={{ backgroundColor: c.color }} />
22
+ {c.icon} {c.name}
23
+ </span>
24
+ </SelectItem>
25
+ ))}
26
+ </SelectContent>
27
+ </Select>
28
+ )
29
+ }
apps/expense-dashboard/src/components/expenses/ExpenseList.tsx ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import ExpenseRow from './ExpenseRow'
2
+ import type { Expense, Category } from '@llm-router/shared'
3
+
4
+ interface Props {
5
+ expenses: Expense[]
6
+ categories: Category[]
7
+ onUpdate: (id: string, data: Partial<{ amount: number; merchant: string; date: string; category_id: string; description: string }>) => Promise<void>
8
+ onDelete: (id: string) => Promise<void>
9
+ }
10
+
11
+ export default function ExpenseList({ expenses, categories, onUpdate, onDelete }: Props) {
12
+ if (expenses.length === 0) {
13
+ return <p className="text-center text-muted-foreground py-12">No expenses this month.</p>
14
+ }
15
+
16
+ // Group by date descending
17
+ const grouped = expenses.reduce<Record<string, Expense[]>>((acc, e) => {
18
+ const key = e.date
19
+ if (!acc[key]) acc[key] = []
20
+ acc[key]!.push(e)
21
+ return acc
22
+ }, {})
23
+
24
+ const sortedDates = Object.keys(grouped).sort((a, b) => b.localeCompare(a))
25
+
26
+ return (
27
+ <div className="space-y-4">
28
+ {sortedDates.map(date => {
29
+ const dayExpenses = grouped[date]!
30
+ const dayTotal = dayExpenses.reduce((sum, e) => sum + Number(e.amount), 0)
31
+ return (
32
+ <div key={date}>
33
+ <div className="flex items-center justify-between mb-1">
34
+ <p className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">
35
+ {new Date(date + 'T00:00:00').toLocaleDateString('default', { weekday: 'short', month: 'short', day: 'numeric' })}
36
+ </p>
37
+ <p className="text-xs text-muted-foreground">฿{dayTotal.toLocaleString()}</p>
38
+ </div>
39
+ <div className="divide-y rounded-lg border bg-card overflow-hidden">
40
+ {dayExpenses.map(e => (
41
+ <ExpenseRow
42
+ key={e.id}
43
+ expense={e}
44
+ categories={categories}
45
+ onUpdate={onUpdate}
46
+ onDelete={onDelete}
47
+ />
48
+ ))}
49
+ </div>
50
+ </div>
51
+ )
52
+ })}
53
+ </div>
54
+ )
55
+ }
apps/expense-dashboard/src/components/expenses/ExpenseRow.tsx ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useState } from 'react'
2
+ import { Button } from '@/components/ui/button'
3
+ import { Input } from '@/components/ui/input'
4
+ import { Label } from '@/components/ui/label'
5
+ import { Badge } from '@/components/ui/badge'
6
+ import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog'
7
+ import { Pencil, Trash2 } from 'lucide-react'
8
+ import CategoryPicker from './CategoryPicker'
9
+ import type { Expense, Category } from '@llm-router/shared'
10
+
11
+ interface Props {
12
+ expense: Expense
13
+ categories: Category[]
14
+ onUpdate: (id: string, data: Partial<{ amount: number; merchant: string; date: string; category_id: string; description: string }>) => Promise<void>
15
+ onDelete: (id: string) => Promise<void>
16
+ }
17
+
18
+ export default function ExpenseRow({ expense, categories, onUpdate, onDelete }: Props) {
19
+ const [open, setOpen] = useState(false)
20
+ const [form, setForm] = useState({
21
+ amount: String(expense.amount),
22
+ merchant: expense.merchant ?? '',
23
+ date: expense.date,
24
+ category_id: expense.category_id,
25
+ description: expense.description ?? '',
26
+ })
27
+ const [saving, setSaving] = useState(false)
28
+
29
+ function handleOpenChange(open: boolean) {
30
+ if (open) {
31
+ setForm({
32
+ amount: String(expense.amount),
33
+ merchant: expense.merchant ?? '',
34
+ date: expense.date,
35
+ category_id: expense.category_id,
36
+ description: expense.description ?? '',
37
+ })
38
+ }
39
+ setOpen(open)
40
+ }
41
+
42
+ const cat = categories.find(c => c.id === expense.category_id)
43
+
44
+ async function handleSave() {
45
+ setSaving(true)
46
+ try {
47
+ await onUpdate(expense.id, {
48
+ amount: Number(form.amount),
49
+ merchant: form.merchant || undefined,
50
+ date: form.date,
51
+ category_id: form.category_id,
52
+ description: form.description || undefined,
53
+ })
54
+ setOpen(false)
55
+ } finally {
56
+ setSaving(false)
57
+ }
58
+ }
59
+
60
+ return (
61
+ <>
62
+ <div className="flex items-center justify-between py-2 px-1 hover:bg-muted/50 rounded group">
63
+ <div className="flex items-center gap-3 min-w-0">
64
+ <div>
65
+ <p className="font-medium text-sm truncate">{expense.merchant ?? '—'}</p>
66
+ {expense.description && (
67
+ <p className="text-xs text-muted-foreground truncate">{expense.description}</p>
68
+ )}
69
+ </div>
70
+ {cat && (
71
+ <Badge variant="outline" style={{ borderColor: cat.color, color: cat.color }}>
72
+ {cat.icon} {cat.name}
73
+ </Badge>
74
+ )}
75
+ </div>
76
+ <div className="flex items-center gap-3 shrink-0">
77
+ <span className="font-semibold tabular-nums">
78
+ {expense.currency} {Number(expense.amount).toLocaleString()}
79
+ </span>
80
+ <div className="opacity-0 group-hover:opacity-100 flex gap-1">
81
+ <Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => setOpen(true)}>
82
+ <Pencil size={12} />
83
+ </Button>
84
+ <Button
85
+ variant="ghost"
86
+ size="icon"
87
+ className="h-7 w-7"
88
+ onClick={() => void onDelete(expense.id)}
89
+ >
90
+ <Trash2 size={12} className="text-destructive" />
91
+ </Button>
92
+ </div>
93
+ </div>
94
+ </div>
95
+
96
+ <Dialog open={open} onOpenChange={handleOpenChange}>
97
+ <DialogContent>
98
+ <DialogHeader>
99
+ <DialogTitle>Edit Expense</DialogTitle>
100
+ </DialogHeader>
101
+ <div className="space-y-3 py-2">
102
+ <div className="space-y-1">
103
+ <Label>Amount</Label>
104
+ <Input
105
+ type="number"
106
+ value={form.amount}
107
+ onChange={e => setForm(f => ({ ...f, amount: e.target.value }))}
108
+ />
109
+ </div>
110
+ <div className="space-y-1">
111
+ <Label>Merchant</Label>
112
+ <Input
113
+ value={form.merchant}
114
+ onChange={e => setForm(f => ({ ...f, merchant: e.target.value }))}
115
+ />
116
+ </div>
117
+ <div className="space-y-1">
118
+ <Label>Date</Label>
119
+ <Input
120
+ type="date"
121
+ value={form.date}
122
+ onChange={e => setForm(f => ({ ...f, date: e.target.value }))}
123
+ />
124
+ </div>
125
+ <div className="space-y-1">
126
+ <Label>Category</Label>
127
+ <CategoryPicker
128
+ categories={categories}
129
+ value={form.category_id}
130
+ onChange={id => setForm(f => ({ ...f, category_id: id }))}
131
+ />
132
+ </div>
133
+ <div className="space-y-1">
134
+ <Label>Description</Label>
135
+ <Input
136
+ value={form.description}
137
+ onChange={e => setForm(f => ({ ...f, description: e.target.value }))}
138
+ />
139
+ </div>
140
+ </div>
141
+ <DialogFooter>
142
+ <Button variant="outline" onClick={() => setOpen(false)}>Cancel</Button>
143
+ <Button onClick={() => void handleSave()} disabled={saving}>
144
+ {saving ? 'Saving…' : 'Save'}
145
+ </Button>
146
+ </DialogFooter>
147
+ </DialogContent>
148
+ </Dialog>
149
+ </>
150
+ )
151
+ }
apps/expense-dashboard/src/components/expenses/ReceiptPreview.tsx ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useState } from 'react'
2
+ import { Card, CardContent } from '@/components/ui/card'
3
+ import { Button } from '@/components/ui/button'
4
+ import { Label } from '@/components/ui/label'
5
+ import { Badge } from '@/components/ui/badge'
6
+ import CategoryPicker from './CategoryPicker'
7
+ import type { Category } from '@llm-router/shared'
8
+ import type { ParsedExpenseResult } from '@/api/expenses'
9
+
10
+ interface Props {
11
+ parsed: ParsedExpenseResult
12
+ categories: Category[]
13
+ ocrUsed: boolean
14
+ onConfirm: (categoryId: string) => void
15
+ onCancel: () => void
16
+ saving: boolean
17
+ }
18
+
19
+ export default function ReceiptPreview({ parsed, categories, ocrUsed, onConfirm, onCancel, saving }: Props) {
20
+ const matched = categories.find(c => c.name.toLowerCase() === parsed.category.toLowerCase())
21
+ const [categoryId, setCategoryId] = useState(matched?.id ?? '')
22
+
23
+ return (
24
+ <div className="space-y-4 pt-2">
25
+ <Card>
26
+ <CardContent className="pt-4 space-y-2 text-sm">
27
+ <div className="flex justify-between">
28
+ <span className="text-muted-foreground">Amount</span>
29
+ <strong className="text-lg">{parsed.currency} {parsed.amount.toLocaleString()}</strong>
30
+ </div>
31
+ {parsed.merchant && (
32
+ <div className="flex justify-between">
33
+ <span className="text-muted-foreground">Merchant</span>
34
+ <span>{parsed.merchant}</span>
35
+ </div>
36
+ )}
37
+ <div className="flex justify-between">
38
+ <span className="text-muted-foreground">Date</span>
39
+ <span>{parsed.date ?? 'Today'}</span>
40
+ </div>
41
+ <div className="flex justify-between items-center">
42
+ <span className="text-muted-foreground">Detected category</span>
43
+ <Badge variant="outline">{parsed.category}</Badge>
44
+ </div>
45
+ <div className="flex justify-between">
46
+ <span className="text-muted-foreground">Confidence</span>
47
+ <span>{Math.round((parsed.confidence ?? 0) * 100)}%</span>
48
+ </div>
49
+ {ocrUsed && (
50
+ <p className="text-xs text-muted-foreground pt-1">📷 Text extracted via OCR</p>
51
+ )}
52
+ </CardContent>
53
+ </Card>
54
+
55
+ <div className="space-y-1">
56
+ <Label>
57
+ {matched ? 'Category (auto-detected — change if wrong)' : 'Category (no match found — required)'}
58
+ </Label>
59
+ <CategoryPicker
60
+ categories={categories}
61
+ value={categoryId}
62
+ onChange={setCategoryId}
63
+ placeholder={matched ? matched.name : 'Select category…'}
64
+ />
65
+ </div>
66
+
67
+ <div className="flex justify-end gap-2">
68
+ <Button variant="outline" onClick={onCancel}>Back</Button>
69
+ <Button
70
+ onClick={() => onConfirm(categoryId)}
71
+ disabled={!categoryId || saving}
72
+ >
73
+ {saving ? 'Saving…' : 'Save expense'}
74
+ </Button>
75
+ </div>
76
+ </div>
77
+ )
78
+ }
apps/expense-dashboard/src/components/layout/AppShell.tsx ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Sidebar from './Sidebar'
2
+
3
+ export default function AppShell({ children }: { children: React.ReactNode }) {
4
+ return (
5
+ <div className="flex min-h-screen">
6
+ <Sidebar />
7
+ <main className="flex-1 overflow-y-auto bg-muted/30">
8
+ {children}
9
+ </main>
10
+ </div>
11
+ )
12
+ }
apps/expense-dashboard/src/components/layout/Sidebar.tsx ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { NavLink, useNavigate } from 'react-router-dom'
2
+ import { LayoutDashboard, Receipt, Tag, Wallet, LogOut } from 'lucide-react'
3
+ import { clearToken } from '@/lib/auth'
4
+ import { cn } from '@/lib/utils'
5
+ import { Button } from '@/components/ui/button'
6
+ import { Separator } from '@/components/ui/separator'
7
+
8
+ const NAV_ITEMS = [
9
+ { to: '/', icon: LayoutDashboard, label: 'Dashboard', end: true },
10
+ { to: '/expenses', icon: Receipt, label: 'Expenses', end: false },
11
+ { to: '/categories', icon: Tag, label: 'Categories', end: false },
12
+ { to: '/budgets', icon: Wallet, label: 'Budgets', end: false },
13
+ ]
14
+
15
+ export default function Sidebar() {
16
+ const navigate = useNavigate()
17
+
18
+ function handleLogout() {
19
+ clearToken()
20
+ navigate('/login')
21
+ }
22
+
23
+ return (
24
+ <aside className="w-56 min-h-screen bg-card border-r flex flex-col shrink-0">
25
+ <div className="px-4 py-5">
26
+ <h1 className="text-base font-semibold text-primary">💰 Expenses</h1>
27
+ </div>
28
+ <Separator />
29
+ <nav className="flex-1 px-2 py-3 space-y-1">
30
+ {NAV_ITEMS.map(({ to, icon: Icon, label, end }) => (
31
+ <NavLink
32
+ key={to}
33
+ to={to}
34
+ end={end}
35
+ className={({ isActive }) =>
36
+ cn(
37
+ 'flex items-center gap-3 px-3 py-2 rounded-md text-sm font-medium transition-colors',
38
+ isActive
39
+ ? 'bg-primary text-primary-foreground'
40
+ : 'text-muted-foreground hover:bg-accent hover:text-accent-foreground'
41
+ )
42
+ }
43
+ >
44
+ <Icon size={16} />
45
+ {label}
46
+ </NavLink>
47
+ ))}
48
+ </nav>
49
+ <div className="px-2 py-3">
50
+ <Separator className="mb-3" />
51
+ <Button
52
+ variant="ghost"
53
+ size="sm"
54
+ className="w-full justify-start gap-3 text-muted-foreground"
55
+ onClick={handleLogout}
56
+ >
57
+ <LogOut size={16} />
58
+ Sign out
59
+ </Button>
60
+ </div>
61
+ </aside>
62
+ )
63
+ }
apps/expense-dashboard/src/components/ui/badge.tsx ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import * as React from "react"
2
+ import { cva, type VariantProps } from "class-variance-authority"
3
+
4
+ import { cn } from "@/lib/utils"
5
+
6
+ const badgeVariants = cva(
7
+ "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",
8
+ {
9
+ variants: {
10
+ variant: {
11
+ default:
12
+ "border-transparent bg-primary text-primary-foreground hover:bg-primary/80",
13
+ secondary:
14
+ "border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
15
+ destructive:
16
+ "border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",
17
+ outline: "text-foreground",
18
+ },
19
+ },
20
+ defaultVariants: {
21
+ variant: "default",
22
+ },
23
+ }
24
+ )
25
+
26
+ export interface BadgeProps
27
+ extends React.HTMLAttributes<HTMLDivElement>,
28
+ VariantProps<typeof badgeVariants> {}
29
+
30
+ function Badge({ className, variant, ...props }: BadgeProps) {
31
+ return (
32
+ <div className={cn(badgeVariants({ variant }), className)} {...props} />
33
+ )
34
+ }
35
+
36
+ export { Badge, badgeVariants }
apps/expense-dashboard/src/components/ui/button.tsx ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import * as React from "react"
2
+ import { Slot } from "@radix-ui/react-slot"
3
+ import { cva, type VariantProps } from "class-variance-authority"
4
+
5
+ import { cn } from "@/lib/utils"
6
+
7
+ const buttonVariants = cva(
8
+ "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",
9
+ {
10
+ variants: {
11
+ variant: {
12
+ default: "bg-primary text-primary-foreground hover:bg-primary/90",
13
+ destructive:
14
+ "bg-destructive text-destructive-foreground hover:bg-destructive/90",
15
+ outline:
16
+ "border border-input bg-background hover:bg-accent hover:text-accent-foreground",
17
+ secondary:
18
+ "bg-secondary text-secondary-foreground hover:bg-secondary/80",
19
+ ghost: "hover:bg-accent hover:text-accent-foreground",
20
+ link: "text-primary underline-offset-4 hover:underline",
21
+ },
22
+ size: {
23
+ default: "h-10 px-4 py-2",
24
+ sm: "h-9 rounded-md px-3",
25
+ lg: "h-11 rounded-md px-8",
26
+ icon: "h-10 w-10",
27
+ },
28
+ },
29
+ defaultVariants: {
30
+ variant: "default",
31
+ size: "default",
32
+ },
33
+ }
34
+ )
35
+
36
+ export interface ButtonProps
37
+ extends React.ButtonHTMLAttributes<HTMLButtonElement>,
38
+ VariantProps<typeof buttonVariants> {
39
+ asChild?: boolean
40
+ }
41
+
42
+ const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
43
+ ({ className, variant, size, asChild = false, ...props }, ref) => {
44
+ const Comp = asChild ? Slot : "button"
45
+ return (
46
+ <Comp
47
+ className={cn(buttonVariants({ variant, size, className }))}
48
+ ref={ref}
49
+ {...props}
50
+ />
51
+ )
52
+ }
53
+ )
54
+ Button.displayName = "Button"
55
+
56
+ export { Button, buttonVariants }
apps/expense-dashboard/src/components/ui/card.tsx ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import * as React from "react"
2
+
3
+ import { cn } from "@/lib/utils"
4
+
5
+ const Card = React.forwardRef<
6
+ HTMLDivElement,
7
+ React.HTMLAttributes<HTMLDivElement>
8
+ >(({ className, ...props }, ref) => (
9
+ <div
10
+ ref={ref}
11
+ className={cn(
12
+ "rounded-lg border bg-card text-card-foreground shadow-sm",
13
+ className
14
+ )}
15
+ {...props}
16
+ />
17
+ ))
18
+ Card.displayName = "Card"
19
+
20
+ const CardHeader = React.forwardRef<
21
+ HTMLDivElement,
22
+ React.HTMLAttributes<HTMLDivElement>
23
+ >(({ className, ...props }, ref) => (
24
+ <div
25
+ ref={ref}
26
+ className={cn("flex flex-col space-y-1.5 p-6", className)}
27
+ {...props}
28
+ />
29
+ ))
30
+ CardHeader.displayName = "CardHeader"
31
+
32
+ const CardTitle = React.forwardRef<
33
+ HTMLDivElement,
34
+ React.HTMLAttributes<HTMLDivElement>
35
+ >(({ className, ...props }, ref) => (
36
+ <div
37
+ ref={ref}
38
+ className={cn(
39
+ "text-2xl font-semibold leading-none tracking-tight",
40
+ className
41
+ )}
42
+ {...props}
43
+ />
44
+ ))
45
+ CardTitle.displayName = "CardTitle"
46
+
47
+ const CardDescription = React.forwardRef<
48
+ HTMLDivElement,
49
+ React.HTMLAttributes<HTMLDivElement>
50
+ >(({ className, ...props }, ref) => (
51
+ <div
52
+ ref={ref}
53
+ className={cn("text-sm text-muted-foreground", className)}
54
+ {...props}
55
+ />
56
+ ))
57
+ CardDescription.displayName = "CardDescription"
58
+
59
+ const CardContent = React.forwardRef<
60
+ HTMLDivElement,
61
+ React.HTMLAttributes<HTMLDivElement>
62
+ >(({ className, ...props }, ref) => (
63
+ <div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
64
+ ))
65
+ CardContent.displayName = "CardContent"
66
+
67
+ const CardFooter = React.forwardRef<
68
+ HTMLDivElement,
69
+ React.HTMLAttributes<HTMLDivElement>
70
+ >(({ className, ...props }, ref) => (
71
+ <div
72
+ ref={ref}
73
+ className={cn("flex items-center p-6 pt-0", className)}
74
+ {...props}
75
+ />
76
+ ))
77
+ CardFooter.displayName = "CardFooter"
78
+
79
+ export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent }
apps/expense-dashboard/src/components/ui/dialog.tsx ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import * as React from "react"
2
+ import * as DialogPrimitive from "@radix-ui/react-dialog"
3
+ import { X } from "lucide-react"
4
+
5
+ import { cn } from "@/lib/utils"
6
+
7
+ const Dialog = DialogPrimitive.Root
8
+
9
+ const DialogTrigger = DialogPrimitive.Trigger
10
+
11
+ const DialogPortal = DialogPrimitive.Portal
12
+
13
+ const DialogClose = DialogPrimitive.Close
14
+
15
+ const DialogOverlay = React.forwardRef<
16
+ React.ElementRef<typeof DialogPrimitive.Overlay>,
17
+ React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
18
+ >(({ className, ...props }, ref) => (
19
+ <DialogPrimitive.Overlay
20
+ ref={ref}
21
+ className={cn(
22
+ "fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
23
+ className
24
+ )}
25
+ {...props}
26
+ />
27
+ ))
28
+ DialogOverlay.displayName = DialogPrimitive.Overlay.displayName
29
+
30
+ const DialogContent = React.forwardRef<
31
+ React.ElementRef<typeof DialogPrimitive.Content>,
32
+ React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
33
+ >(({ className, children, ...props }, ref) => (
34
+ <DialogPortal>
35
+ <DialogOverlay />
36
+ <DialogPrimitive.Content
37
+ ref={ref}
38
+ className={cn(
39
+ "fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
40
+ className
41
+ )}
42
+ {...props}
43
+ >
44
+ {children}
45
+ <DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
46
+ <X className="h-4 w-4" />
47
+ <span className="sr-only">Close</span>
48
+ </DialogPrimitive.Close>
49
+ </DialogPrimitive.Content>
50
+ </DialogPortal>
51
+ ))
52
+ DialogContent.displayName = DialogPrimitive.Content.displayName
53
+
54
+ const DialogHeader = ({
55
+ className,
56
+ ...props
57
+ }: React.HTMLAttributes<HTMLDivElement>) => (
58
+ <div
59
+ className={cn(
60
+ "flex flex-col space-y-1.5 text-center sm:text-left",
61
+ className
62
+ )}
63
+ {...props}
64
+ />
65
+ )
66
+ DialogHeader.displayName = "DialogHeader"
67
+
68
+ const DialogFooter = ({
69
+ className,
70
+ ...props
71
+ }: React.HTMLAttributes<HTMLDivElement>) => (
72
+ <div
73
+ className={cn(
74
+ "flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
75
+ className
76
+ )}
77
+ {...props}
78
+ />
79
+ )
80
+ DialogFooter.displayName = "DialogFooter"
81
+
82
+ const DialogTitle = React.forwardRef<
83
+ React.ElementRef<typeof DialogPrimitive.Title>,
84
+ React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
85
+ >(({ className, ...props }, ref) => (
86
+ <DialogPrimitive.Title
87
+ ref={ref}
88
+ className={cn(
89
+ "text-lg font-semibold leading-none tracking-tight",
90
+ className
91
+ )}
92
+ {...props}
93
+ />
94
+ ))
95
+ DialogTitle.displayName = DialogPrimitive.Title.displayName
96
+
97
+ const DialogDescription = React.forwardRef<
98
+ React.ElementRef<typeof DialogPrimitive.Description>,
99
+ React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
100
+ >(({ className, ...props }, ref) => (
101
+ <DialogPrimitive.Description
102
+ ref={ref}
103
+ className={cn("text-sm text-muted-foreground", className)}
104
+ {...props}
105
+ />
106
+ ))
107
+ DialogDescription.displayName = DialogPrimitive.Description.displayName
108
+
109
+ export {
110
+ Dialog,
111
+ DialogPortal,
112
+ DialogOverlay,
113
+ DialogClose,
114
+ DialogTrigger,
115
+ DialogContent,
116
+ DialogHeader,
117
+ DialogFooter,
118
+ DialogTitle,
119
+ DialogDescription,
120
+ }
apps/expense-dashboard/src/components/ui/input.tsx ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import * as React from "react"
2
+
3
+ import { cn } from "@/lib/utils"
4
+
5
+ const Input = React.forwardRef<HTMLInputElement, React.ComponentProps<"input">>(
6
+ ({ className, type, ...props }, ref) => {
7
+ return (
8
+ <input
9
+ type={type}
10
+ className={cn(
11
+ "flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
12
+ className
13
+ )}
14
+ ref={ref}
15
+ {...props}
16
+ />
17
+ )
18
+ }
19
+ )
20
+ Input.displayName = "Input"
21
+
22
+ export { Input }
apps/expense-dashboard/src/components/ui/label.tsx ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import * as React from "react"
2
+ import * as LabelPrimitive from "@radix-ui/react-label"
3
+ import { cva, type VariantProps } from "class-variance-authority"
4
+
5
+ import { cn } from "@/lib/utils"
6
+
7
+ const labelVariants = cva(
8
+ "text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
9
+ )
10
+
11
+ const Label = React.forwardRef<
12
+ React.ElementRef<typeof LabelPrimitive.Root>,
13
+ React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> &
14
+ VariantProps<typeof labelVariants>
15
+ >(({ className, ...props }, ref) => (
16
+ <LabelPrimitive.Root
17
+ ref={ref}
18
+ className={cn(labelVariants(), className)}
19
+ {...props}
20
+ />
21
+ ))
22
+ Label.displayName = LabelPrimitive.Root.displayName
23
+
24
+ export { Label }
apps/expense-dashboard/src/components/ui/progress.tsx ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "use client"
2
+
3
+ import * as React from "react"
4
+ import * as ProgressPrimitive from "@radix-ui/react-progress"
5
+
6
+ import { cn } from "@/lib/utils"
7
+
8
+ const Progress = React.forwardRef<
9
+ React.ElementRef<typeof ProgressPrimitive.Root>,
10
+ React.ComponentPropsWithoutRef<typeof ProgressPrimitive.Root>
11
+ >(({ className, value, ...props }, ref) => (
12
+ <ProgressPrimitive.Root
13
+ ref={ref}
14
+ className={cn(
15
+ "relative h-4 w-full overflow-hidden rounded-full bg-secondary",
16
+ className
17
+ )}
18
+ {...props}
19
+ >
20
+ <ProgressPrimitive.Indicator
21
+ className="h-full w-full flex-1 bg-primary transition-all"
22
+ style={{ transform: `translateX(-${100 - (value || 0)}%)` }}
23
+ />
24
+ </ProgressPrimitive.Root>
25
+ ))
26
+ Progress.displayName = ProgressPrimitive.Root.displayName
27
+
28
+ export { Progress }
apps/expense-dashboard/src/components/ui/select.tsx ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "use client"
2
+
3
+ import * as React from "react"
4
+ import * as SelectPrimitive from "@radix-ui/react-select"
5
+ import { Check, ChevronDown, ChevronUp } from "lucide-react"
6
+
7
+ import { cn } from "@/lib/utils"
8
+
9
+ const Select = SelectPrimitive.Root
10
+
11
+ const SelectGroup = SelectPrimitive.Group
12
+
13
+ const SelectValue = SelectPrimitive.Value
14
+
15
+ const SelectTrigger = React.forwardRef<
16
+ React.ElementRef<typeof SelectPrimitive.Trigger>,
17
+ React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>
18
+ >(({ className, children, ...props }, ref) => (
19
+ <SelectPrimitive.Trigger
20
+ ref={ref}
21
+ className={cn(
22
+ "flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background data-[placeholder]:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",
23
+ className
24
+ )}
25
+ {...props}
26
+ >
27
+ {children}
28
+ <SelectPrimitive.Icon asChild>
29
+ <ChevronDown className="h-4 w-4 opacity-50" />
30
+ </SelectPrimitive.Icon>
31
+ </SelectPrimitive.Trigger>
32
+ ))
33
+ SelectTrigger.displayName = SelectPrimitive.Trigger.displayName
34
+
35
+ const SelectScrollUpButton = React.forwardRef<
36
+ React.ElementRef<typeof SelectPrimitive.ScrollUpButton>,
37
+ React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollUpButton>
38
+ >(({ className, ...props }, ref) => (
39
+ <SelectPrimitive.ScrollUpButton
40
+ ref={ref}
41
+ className={cn(
42
+ "flex cursor-default items-center justify-center py-1",
43
+ className
44
+ )}
45
+ {...props}
46
+ >
47
+ <ChevronUp className="h-4 w-4" />
48
+ </SelectPrimitive.ScrollUpButton>
49
+ ))
50
+ SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName
51
+
52
+ const SelectScrollDownButton = React.forwardRef<
53
+ React.ElementRef<typeof SelectPrimitive.ScrollDownButton>,
54
+ React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollDownButton>
55
+ >(({ className, ...props }, ref) => (
56
+ <SelectPrimitive.ScrollDownButton
57
+ ref={ref}
58
+ className={cn(
59
+ "flex cursor-default items-center justify-center py-1",
60
+ className
61
+ )}
62
+ {...props}
63
+ >
64
+ <ChevronDown className="h-4 w-4" />
65
+ </SelectPrimitive.ScrollDownButton>
66
+ ))
67
+ SelectScrollDownButton.displayName =
68
+ SelectPrimitive.ScrollDownButton.displayName
69
+
70
+ const SelectContent = React.forwardRef<
71
+ React.ElementRef<typeof SelectPrimitive.Content>,
72
+ React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content>
73
+ >(({ className, children, position = "popper", ...props }, ref) => (
74
+ <SelectPrimitive.Portal>
75
+ <SelectPrimitive.Content
76
+ ref={ref}
77
+ className={cn(
78
+ "relative z-50 max-h-[--radix-select-content-available-height] min-w-[8rem] overflow-y-auto overflow-x-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 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 origin-[--radix-select-content-transform-origin]",
79
+ position === "popper" &&
80
+ "data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
81
+ className
82
+ )}
83
+ position={position}
84
+ {...props}
85
+ >
86
+ <SelectScrollUpButton />
87
+ <SelectPrimitive.Viewport
88
+ className={cn(
89
+ "p-1",
90
+ position === "popper" &&
91
+ "h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"
92
+ )}
93
+ >
94
+ {children}
95
+ </SelectPrimitive.Viewport>
96
+ <SelectScrollDownButton />
97
+ </SelectPrimitive.Content>
98
+ </SelectPrimitive.Portal>
99
+ ))
100
+ SelectContent.displayName = SelectPrimitive.Content.displayName
101
+
102
+ const SelectLabel = React.forwardRef<
103
+ React.ElementRef<typeof SelectPrimitive.Label>,
104
+ React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label>
105
+ >(({ className, ...props }, ref) => (
106
+ <SelectPrimitive.Label
107
+ ref={ref}
108
+ className={cn("py-1.5 pl-8 pr-2 text-sm font-semibold", className)}
109
+ {...props}
110
+ />
111
+ ))
112
+ SelectLabel.displayName = SelectPrimitive.Label.displayName
113
+
114
+ const SelectItem = React.forwardRef<
115
+ React.ElementRef<typeof SelectPrimitive.Item>,
116
+ React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>
117
+ >(({ className, children, ...props }, ref) => (
118
+ <SelectPrimitive.Item
119
+ ref={ref}
120
+ className={cn(
121
+ "relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
122
+ className
123
+ )}
124
+ {...props}
125
+ >
126
+ <span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
127
+ <SelectPrimitive.ItemIndicator>
128
+ <Check className="h-4 w-4" />
129
+ </SelectPrimitive.ItemIndicator>
130
+ </span>
131
+
132
+ <SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
133
+ </SelectPrimitive.Item>
134
+ ))
135
+ SelectItem.displayName = SelectPrimitive.Item.displayName
136
+
137
+ const SelectSeparator = React.forwardRef<
138
+ React.ElementRef<typeof SelectPrimitive.Separator>,
139
+ React.ComponentPropsWithoutRef<typeof SelectPrimitive.Separator>
140
+ >(({ className, ...props }, ref) => (
141
+ <SelectPrimitive.Separator
142
+ ref={ref}
143
+ className={cn("-mx-1 my-1 h-px bg-muted", className)}
144
+ {...props}
145
+ />
146
+ ))
147
+ SelectSeparator.displayName = SelectPrimitive.Separator.displayName
148
+
149
+ export {
150
+ Select,
151
+ SelectGroup,
152
+ SelectValue,
153
+ SelectTrigger,
154
+ SelectContent,
155
+ SelectLabel,
156
+ SelectItem,
157
+ SelectSeparator,
158
+ SelectScrollUpButton,
159
+ SelectScrollDownButton,
160
+ }
apps/expense-dashboard/src/components/ui/separator.tsx ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import * as React from "react"
2
+ import * as SeparatorPrimitive from "@radix-ui/react-separator"
3
+
4
+ import { cn } from "@/lib/utils"
5
+
6
+ const Separator = React.forwardRef<
7
+ React.ElementRef<typeof SeparatorPrimitive.Root>,
8
+ React.ComponentPropsWithoutRef<typeof SeparatorPrimitive.Root>
9
+ >(
10
+ (
11
+ { className, orientation = "horizontal", decorative = true, ...props },
12
+ ref
13
+ ) => (
14
+ <SeparatorPrimitive.Root
15
+ ref={ref}
16
+ decorative={decorative}
17
+ orientation={orientation}
18
+ className={cn(
19
+ "shrink-0 bg-border",
20
+ orientation === "horizontal" ? "h-[1px] w-full" : "h-full w-[1px]",
21
+ className
22
+ )}
23
+ {...props}
24
+ />
25
+ )
26
+ )
27
+ Separator.displayName = SeparatorPrimitive.Root.displayName
28
+
29
+ export { Separator }
apps/expense-dashboard/src/components/ui/table.tsx ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import * as React from "react"
2
+
3
+ import { cn } from "@/lib/utils"
4
+
5
+ const Table = React.forwardRef<
6
+ HTMLTableElement,
7
+ React.HTMLAttributes<HTMLTableElement>
8
+ >(({ className, ...props }, ref) => (
9
+ <div className="relative w-full overflow-auto">
10
+ <table
11
+ ref={ref}
12
+ className={cn("w-full caption-bottom text-sm", className)}
13
+ {...props}
14
+ />
15
+ </div>
16
+ ))
17
+ Table.displayName = "Table"
18
+
19
+ const TableHeader = React.forwardRef<
20
+ HTMLTableSectionElement,
21
+ React.HTMLAttributes<HTMLTableSectionElement>
22
+ >(({ className, ...props }, ref) => (
23
+ <thead ref={ref} className={cn("[&_tr]:border-b", className)} {...props} />
24
+ ))
25
+ TableHeader.displayName = "TableHeader"
26
+
27
+ const TableBody = React.forwardRef<
28
+ HTMLTableSectionElement,
29
+ React.HTMLAttributes<HTMLTableSectionElement>
30
+ >(({ className, ...props }, ref) => (
31
+ <tbody
32
+ ref={ref}
33
+ className={cn("[&_tr:last-child]:border-0", className)}
34
+ {...props}
35
+ />
36
+ ))
37
+ TableBody.displayName = "TableBody"
38
+
39
+ const TableFooter = React.forwardRef<
40
+ HTMLTableSectionElement,
41
+ React.HTMLAttributes<HTMLTableSectionElement>
42
+ >(({ className, ...props }, ref) => (
43
+ <tfoot
44
+ ref={ref}
45
+ className={cn(
46
+ "border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",
47
+ className
48
+ )}
49
+ {...props}
50
+ />
51
+ ))
52
+ TableFooter.displayName = "TableFooter"
53
+
54
+ const TableRow = React.forwardRef<
55
+ HTMLTableRowElement,
56
+ React.HTMLAttributes<HTMLTableRowElement>
57
+ >(({ className, ...props }, ref) => (
58
+ <tr
59
+ ref={ref}
60
+ className={cn(
61
+ "border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",
62
+ className
63
+ )}
64
+ {...props}
65
+ />
66
+ ))
67
+ TableRow.displayName = "TableRow"
68
+
69
+ const TableHead = React.forwardRef<
70
+ HTMLTableCellElement,
71
+ React.ThHTMLAttributes<HTMLTableCellElement>
72
+ >(({ className, ...props }, ref) => (
73
+ <th
74
+ ref={ref}
75
+ className={cn(
76
+ "h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",
77
+ className
78
+ )}
79
+ {...props}
80
+ />
81
+ ))
82
+ TableHead.displayName = "TableHead"
83
+
84
+ const TableCell = React.forwardRef<
85
+ HTMLTableCellElement,
86
+ React.TdHTMLAttributes<HTMLTableCellElement>
87
+ >(({ className, ...props }, ref) => (
88
+ <td
89
+ ref={ref}
90
+ className={cn("p-4 align-middle [&:has([role=checkbox])]:pr-0", className)}
91
+ {...props}
92
+ />
93
+ ))
94
+ TableCell.displayName = "TableCell"
95
+
96
+ const TableCaption = React.forwardRef<
97
+ HTMLTableCaptionElement,
98
+ React.HTMLAttributes<HTMLTableCaptionElement>
99
+ >(({ className, ...props }, ref) => (
100
+ <caption
101
+ ref={ref}
102
+ className={cn("mt-4 text-sm text-muted-foreground", className)}
103
+ {...props}
104
+ />
105
+ ))
106
+ TableCaption.displayName = "TableCaption"
107
+
108
+ export {
109
+ Table,
110
+ TableHeader,
111
+ TableBody,
112
+ TableFooter,
113
+ TableHead,
114
+ TableRow,
115
+ TableCell,
116
+ TableCaption,
117
+ }
apps/expense-dashboard/src/components/ui/tabs.tsx ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import * as React from "react"
2
+ import * as TabsPrimitive from "@radix-ui/react-tabs"
3
+
4
+ import { cn } from "@/lib/utils"
5
+
6
+ const Tabs = TabsPrimitive.Root
7
+
8
+ const TabsList = React.forwardRef<
9
+ React.ElementRef<typeof TabsPrimitive.List>,
10
+ React.ComponentPropsWithoutRef<typeof TabsPrimitive.List>
11
+ >(({ className, ...props }, ref) => (
12
+ <TabsPrimitive.List
13
+ ref={ref}
14
+ className={cn(
15
+ "inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",
16
+ className
17
+ )}
18
+ {...props}
19
+ />
20
+ ))
21
+ TabsList.displayName = TabsPrimitive.List.displayName
22
+
23
+ const TabsTrigger = React.forwardRef<
24
+ React.ElementRef<typeof TabsPrimitive.Trigger>,
25
+ React.ComponentPropsWithoutRef<typeof TabsPrimitive.Trigger>
26
+ >(({ className, ...props }, ref) => (
27
+ <TabsPrimitive.Trigger
28
+ ref={ref}
29
+ className={cn(
30
+ "inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm",
31
+ className
32
+ )}
33
+ {...props}
34
+ />
35
+ ))
36
+ TabsTrigger.displayName = TabsPrimitive.Trigger.displayName
37
+
38
+ const TabsContent = React.forwardRef<
39
+ React.ElementRef<typeof TabsPrimitive.Content>,
40
+ React.ComponentPropsWithoutRef<typeof TabsPrimitive.Content>
41
+ >(({ className, ...props }, ref) => (
42
+ <TabsPrimitive.Content
43
+ ref={ref}
44
+ className={cn(
45
+ "mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
46
+ className
47
+ )}
48
+ {...props}
49
+ />
50
+ ))
51
+ TabsContent.displayName = TabsPrimitive.Content.displayName
52
+
53
+ export { Tabs, TabsList, TabsTrigger, TabsContent }
apps/expense-dashboard/src/hooks/useAnalytics.ts ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useState, useEffect, useCallback } from 'react'
2
+ import { getSummary, getTrends } from '@/api/analytics'
3
+ import type { Summary, Trends } from '@llm-router/shared'
4
+
5
+ export function useAnalytics() {
6
+ const [summary, setSummary] = useState<Summary | null>(null)
7
+ const [trends, setTrends] = useState<Trends | null>(null)
8
+ const [loading, setLoading] = useState(true)
9
+ const [error, setError] = useState<string | null>(null)
10
+
11
+ const refresh = useCallback(async () => {
12
+ setLoading(true)
13
+ setError(null)
14
+ try {
15
+ const [s, t] = await Promise.all([getSummary(), getTrends(6)])
16
+ setSummary(s)
17
+ setTrends(t)
18
+ } catch (err) {
19
+ setError(err instanceof Error ? err.message : 'Failed to load analytics')
20
+ } finally {
21
+ setLoading(false)
22
+ }
23
+ }, [])
24
+
25
+ useEffect(() => { void refresh() }, [refresh])
26
+
27
+ return { summary, trends, loading, error, refresh }
28
+ }
apps/expense-dashboard/src/hooks/useBudgets.ts ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useState, useEffect, useCallback } from 'react'
2
+ import { listBudgets, createBudget, updateBudget, deleteBudget } from '@/api/budgets'
3
+ import type { Budget, CreateBudget, UpdateBudget } from '@llm-router/shared'
4
+
5
+ export function useBudgets() {
6
+ const [budgets, setBudgets] = useState<Budget[]>([])
7
+ const [loading, setLoading] = useState(true)
8
+ const [error, setError] = useState<string | null>(null)
9
+
10
+ const refresh = useCallback(async () => {
11
+ setLoading(true)
12
+ setError(null)
13
+ try {
14
+ setBudgets(await listBudgets())
15
+ } catch (err) {
16
+ setError(err instanceof Error ? err.message : 'Failed to load budgets')
17
+ } finally {
18
+ setLoading(false)
19
+ }
20
+ }, [])
21
+
22
+ useEffect(() => { void refresh() }, [refresh])
23
+
24
+ const create = useCallback(async (data: CreateBudget) => {
25
+ const created = await createBudget(data)
26
+ setBudgets(prev => [...prev, created])
27
+ return created
28
+ }, [])
29
+
30
+ const update = useCallback(async (id: string, data: UpdateBudget) => {
31
+ const updated = await updateBudget(id, data)
32
+ setBudgets(prev => prev.map(b => b.id === id ? updated : b))
33
+ return updated
34
+ }, [])
35
+
36
+ const remove = useCallback(async (id: string) => {
37
+ await deleteBudget(id)
38
+ setBudgets(prev => prev.filter(b => b.id !== id))
39
+ }, [])
40
+
41
+ return { budgets, loading, error, refresh, create, update, remove }
42
+ }
apps/expense-dashboard/src/hooks/useCategories.ts ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useState, useEffect, useCallback } from 'react'
2
+ import { listCategories, createCategory, updateCategory, deleteCategory } from '@/api/categories'
3
+ import type { Category, CreateCategory, UpdateCategory } from '@llm-router/shared'
4
+
5
+ export function useCategories() {
6
+ const [categories, setCategories] = useState<Category[]>([])
7
+ const [loading, setLoading] = useState(true)
8
+ const [error, setError] = useState<string | null>(null)
9
+
10
+ const refresh = useCallback(async () => {
11
+ setLoading(true)
12
+ setError(null)
13
+ try {
14
+ setCategories(await listCategories())
15
+ } catch (err) {
16
+ setError(err instanceof Error ? err.message : 'Failed to load categories')
17
+ } finally {
18
+ setLoading(false)
19
+ }
20
+ }, [])
21
+
22
+ useEffect(() => { void refresh() }, [refresh])
23
+
24
+ const create = useCallback(async (data: CreateCategory) => {
25
+ const created = await createCategory(data)
26
+ setCategories(prev => [...prev, created])
27
+ return created
28
+ }, [])
29
+
30
+ const update = useCallback(async (id: string, data: UpdateCategory) => {
31
+ const updated = await updateCategory(id, data)
32
+ setCategories(prev => prev.map(c => c.id === id ? updated : c))
33
+ return updated
34
+ }, [])
35
+
36
+ const remove = useCallback(async (id: string) => {
37
+ await deleteCategory(id)
38
+ setCategories(prev => prev.filter(c => c.id !== id))
39
+ }, [])
40
+
41
+ return { categories, loading, error, refresh, create, update, remove }
42
+ }
apps/expense-dashboard/src/hooks/useExpenses.ts ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useState, useEffect, useCallback } from 'react'
2
+ import { listExpenses, createExpense, updateExpense, deleteExpense } from '@/api/expenses'
3
+ import { getCurrentMonth } from '@/lib/dates'
4
+ import type { Expense, CreateExpense, UpdateExpense } from '@llm-router/shared'
5
+
6
+ export function useExpenses(month?: string) {
7
+ const [selectedMonth, setSelectedMonth] = useState(month ?? getCurrentMonth())
8
+ const [expenses, setExpenses] = useState<Expense[]>([])
9
+ const [loading, setLoading] = useState(true)
10
+ const [error, setError] = useState<string | null>(null)
11
+
12
+ const refresh = useCallback(async () => {
13
+ setLoading(true)
14
+ setError(null)
15
+ try {
16
+ setExpenses(await listExpenses(selectedMonth))
17
+ } catch (err) {
18
+ setError(err instanceof Error ? err.message : 'Failed to load expenses')
19
+ } finally {
20
+ setLoading(false)
21
+ }
22
+ }, [selectedMonth])
23
+
24
+ useEffect(() => { void refresh() }, [refresh])
25
+
26
+ const create = useCallback(async (data: CreateExpense) => {
27
+ const created = await createExpense(data)
28
+ await refresh()
29
+ return created
30
+ }, [refresh])
31
+
32
+ const update = useCallback(async (id: string, data: UpdateExpense) => {
33
+ const updated = await updateExpense(id, data)
34
+ setExpenses(prev => prev.map(e => e.id === id ? updated : e))
35
+ return updated
36
+ }, [])
37
+
38
+ const remove = useCallback(async (id: string) => {
39
+ await deleteExpense(id)
40
+ setExpenses(prev => prev.filter(e => e.id !== id))
41
+ }, [])
42
+
43
+ return { expenses, loading, error, selectedMonth, setSelectedMonth, refresh, create, update, remove }
44
+ }
apps/expense-dashboard/src/index.css ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @tailwind base;
2
+ @tailwind components;
3
+ @tailwind utilities;
4
+
5
+ @layer base {
6
+ :root {
7
+ --background: 0 0% 100%;
8
+ --foreground: 222.2 84% 4.9%;
9
+ --card: 0 0% 100%;
10
+ --card-foreground: 222.2 84% 4.9%;
11
+ --primary: 222.2 47.4% 11.2%;
12
+ --primary-foreground: 210 40% 98%;
13
+ --secondary: 210 40% 96.1%;
14
+ --secondary-foreground: 222.2 47.4% 11.2%;
15
+ --muted: 210 40% 96.1%;
16
+ --muted-foreground: 215.4 16.3% 46.9%;
17
+ --accent: 210 40% 96.1%;
18
+ --accent-foreground: 222.2 47.4% 11.2%;
19
+ --destructive: 0 84.2% 60.2%;
20
+ --destructive-foreground: 210 40% 98%;
21
+ --border: 214.3 31.8% 91.4%;
22
+ --input: 214.3 31.8% 91.4%;
23
+ --ring: 222.2 84% 4.9%;
24
+ --radius: 0.5rem;
25
+ }
26
+ }
27
+
28
+ @layer base {
29
+ * { @apply border-border; }
30
+ body { @apply bg-background text-foreground; }
31
+ }
apps/expense-dashboard/src/lib/auth.ts ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const TOKEN_KEY = 'expense_token'
2
+
3
+ export function getToken(): string | null {
4
+ return localStorage.getItem(TOKEN_KEY)
5
+ }
6
+
7
+ export function setToken(token: string): void {
8
+ localStorage.setItem(TOKEN_KEY, token)
9
+ }
10
+
11
+ export function clearToken(): void {
12
+ localStorage.removeItem(TOKEN_KEY)
13
+ }
14
+
15
+ export function isAuthenticated(): boolean {
16
+ return getToken() !== null
17
+ }
apps/expense-dashboard/src/lib/dates.ts ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export function getCurrentMonth(): string {
2
+ const now = new Date()
3
+ return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`
4
+ }
5
+
6
+ export function monthRange(month: string): { from: string; to: string } {
7
+ const parts = month.split('-')
8
+ const year = Number(parts[0])
9
+ const mon = Number(parts[1])
10
+ const from = `${year}-${String(mon).padStart(2, '0')}-01`
11
+ const lastDay = new Date(year, mon, 0).getDate()
12
+ const to = `${year}-${String(mon).padStart(2, '0')}-${String(lastDay).padStart(2, '0')}`
13
+ return { from, to }
14
+ }
15
+
16
+ export function formatMonth(month: string): string {
17
+ const parts = month.split('-')
18
+ const year = Number(parts[0])
19
+ const mon = Number(parts[1])
20
+ return new Date(year, mon - 1, 1).toLocaleString('default', { month: 'long', year: 'numeric' })
21
+ }
22
+
23
+ export function getLast12Months(): string[] {
24
+ const months: string[] = []
25
+ const now = new Date()
26
+ for (let i = 0; i < 12; i++) {
27
+ const d = new Date(now.getFullYear(), now.getMonth() - i, 1)
28
+ months.push(`${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`)
29
+ }
30
+ return months
31
+ }
apps/expense-dashboard/src/lib/utils.ts ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ import { clsx, type ClassValue } from 'clsx'
2
+ import { twMerge } from 'tailwind-merge'
3
+
4
+ export function cn(...inputs: ClassValue[]) {
5
+ return twMerge(clsx(inputs))
6
+ }
apps/expense-dashboard/src/main.tsx ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ import React from 'react'
2
+ import ReactDOM from 'react-dom/client'
3
+ import App from './App'
4
+ import './index.css'
5
+
6
+ ReactDOM.createRoot(document.getElementById('root')!).render(
7
+ <React.StrictMode>
8
+ <App />
9
+ </React.StrictMode>
10
+ )
apps/expense-dashboard/src/pages/BudgetsPage.tsx ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useState } from 'react'
2
+ import { useBudgets } from '@/hooks/useBudgets'
3
+ import { useCategories } from '@/hooks/useCategories'
4
+ import { Button } from '@/components/ui/button'
5
+ import { Input } from '@/components/ui/input'
6
+ import { Label } from '@/components/ui/label'
7
+ import { Card, CardContent } from '@/components/ui/card'
8
+ import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog'
9
+ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
10
+ import { Pencil, Trash2, Plus } from 'lucide-react'
11
+ import type { Budget } from '@llm-router/shared'
12
+
13
+ export default function BudgetsPage() {
14
+ const { budgets, loading, error, create, update, remove } = useBudgets()
15
+ const { categories } = useCategories()
16
+ const [open, setOpen] = useState(false)
17
+ const [editing, setEditing] = useState<Budget | null>(null)
18
+ const [categoryId, setCategoryId] = useState('')
19
+ const [amount, setAmount] = useState('')
20
+ const [saving, setSaving] = useState(false)
21
+ const [formError, setFormError] = useState<string | null>(null)
22
+
23
+ function openCreate() {
24
+ setEditing(null)
25
+ setCategoryId('')
26
+ setAmount('')
27
+ setFormError(null)
28
+ setOpen(true)
29
+ }
30
+
31
+ function openEdit(b: Budget) {
32
+ setEditing(b)
33
+ setCategoryId(b.category_id)
34
+ setAmount(String(b.amount))
35
+ setFormError(null)
36
+ setOpen(true)
37
+ }
38
+
39
+ async function handleSave() {
40
+ const amt = Number(amount)
41
+ if (!categoryId) { setFormError('Select a category'); return }
42
+ if (!amount || isNaN(amt) || amt <= 0) { setFormError('Enter a valid amount'); return }
43
+ setSaving(true)
44
+ setFormError(null)
45
+ try {
46
+ if (editing) {
47
+ await update(editing.id, { amount: amt })
48
+ } else {
49
+ await create({ category_id: categoryId, amount: amt, period: 'monthly' })
50
+ }
51
+ setOpen(false)
52
+ } catch (err) {
53
+ setFormError(err instanceof Error ? err.message : 'Save failed')
54
+ } finally {
55
+ setSaving(false)
56
+ }
57
+ }
58
+
59
+ async function handleDelete(id: string) {
60
+ if (!confirm('Delete this budget?')) return
61
+ try {
62
+ await remove(id)
63
+ } catch (err) {
64
+ alert(err instanceof Error ? err.message : 'Delete failed')
65
+ }
66
+ }
67
+
68
+ const categoryMap = Object.fromEntries(categories.map(c => [c.id, c]))
69
+ const usedCategoryIds = new Set(budgets.map(b => b.category_id))
70
+
71
+ return (
72
+ <div className="p-6 max-w-2xl">
73
+ <div className="flex items-center justify-between mb-6">
74
+ <h1 className="text-2xl font-bold">Monthly Budgets</h1>
75
+ <Button onClick={openCreate} size="sm">
76
+ <Plus size={16} className="mr-1" /> Add budget
77
+ </Button>
78
+ </div>
79
+
80
+ {loading && <p className="text-muted-foreground">Loading…</p>}
81
+ {error && <p className="text-destructive">{error}</p>}
82
+
83
+ <div className="space-y-2">
84
+ {budgets.map(b => {
85
+ const cat = categoryMap[b.category_id]
86
+ return (
87
+ <Card key={b.id}>
88
+ <CardContent className="py-3 flex items-center justify-between">
89
+ <div className="flex items-center gap-3">
90
+ {cat && (
91
+ <span className="w-3 h-3 rounded-full" style={{ backgroundColor: cat.color }} />
92
+ )}
93
+ <span className="font-medium">{cat?.icon} {cat?.name ?? b.category_id}</span>
94
+ <span className="text-muted-foreground text-sm">— ฿{Number(b.amount).toLocaleString()} / month</span>
95
+ </div>
96
+ <div className="flex gap-2">
97
+ <Button variant="ghost" size="icon" onClick={() => openEdit(b)}>
98
+ <Pencil size={14} />
99
+ </Button>
100
+ <Button variant="ghost" size="icon" onClick={() => void handleDelete(b.id)}>
101
+ <Trash2 size={14} className="text-destructive" />
102
+ </Button>
103
+ </div>
104
+ </CardContent>
105
+ </Card>
106
+ )
107
+ })}
108
+ </div>
109
+
110
+ <Dialog open={open} onOpenChange={setOpen}>
111
+ <DialogContent>
112
+ <DialogHeader>
113
+ <DialogTitle>{editing ? 'Edit Budget' : 'New Monthly Budget'}</DialogTitle>
114
+ </DialogHeader>
115
+ <div className="space-y-4 py-2">
116
+ <div className="space-y-1">
117
+ <Label>Category</Label>
118
+ <Select
119
+ value={categoryId}
120
+ onValueChange={setCategoryId}
121
+ disabled={!!editing}
122
+ >
123
+ <SelectTrigger>
124
+ <SelectValue placeholder="Select category…" />
125
+ </SelectTrigger>
126
+ <SelectContent>
127
+ {categories
128
+ .filter(c => editing ? true : !usedCategoryIds.has(c.id))
129
+ .map(c => (
130
+ <SelectItem key={c.id} value={c.id}>
131
+ {c.icon} {c.name}
132
+ </SelectItem>
133
+ ))}
134
+ </SelectContent>
135
+ </Select>
136
+ </div>
137
+ <div className="space-y-1">
138
+ <Label>Monthly limit (฿)</Label>
139
+ <Input
140
+ type="number"
141
+ min="1"
142
+ value={amount}
143
+ onChange={e => setAmount(e.target.value)}
144
+ placeholder="5000"
145
+ />
146
+ </div>
147
+ {formError && <p className="text-sm text-destructive">{formError}</p>}
148
+ </div>
149
+ <DialogFooter>
150
+ <Button variant="outline" onClick={() => setOpen(false)}>Cancel</Button>
151
+ <Button onClick={() => void handleSave()} disabled={saving}>
152
+ {saving ? 'Saving…' : 'Save'}
153
+ </Button>
154
+ </DialogFooter>
155
+ </DialogContent>
156
+ </Dialog>
157
+ </div>
158
+ )
159
+ }
apps/expense-dashboard/src/pages/CategoriesPage.tsx ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useState } from 'react'
2
+ import { useCategories } from '@/hooks/useCategories'
3
+ import { Button } from '@/components/ui/button'
4
+ import { Input } from '@/components/ui/input'
5
+ import { Label } from '@/components/ui/label'
6
+ import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
7
+ import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog'
8
+ import { Pencil, Trash2, Plus } from 'lucide-react'
9
+ import type { Category } from '@llm-router/shared'
10
+
11
+ interface FormState { name: string; color: string; icon: string }
12
+ const EMPTY: FormState = { name: '', color: '#6B7280', icon: '' }
13
+
14
+ export default function CategoriesPage() {
15
+ const { categories, loading, error, create, update, remove } = useCategories()
16
+ const [open, setOpen] = useState(false)
17
+ const [editing, setEditing] = useState<Category | null>(null)
18
+ const [form, setForm] = useState<FormState>(EMPTY)
19
+ const [saving, setSaving] = useState(false)
20
+ const [formError, setFormError] = useState<string | null>(null)
21
+
22
+ function openCreate() {
23
+ setEditing(null)
24
+ setForm(EMPTY)
25
+ setFormError(null)
26
+ setOpen(true)
27
+ }
28
+
29
+ function openEdit(cat: Category) {
30
+ setEditing(cat)
31
+ setForm({ name: cat.name, color: cat.color, icon: cat.icon ?? '' })
32
+ setFormError(null)
33
+ setOpen(true)
34
+ }
35
+
36
+ async function handleSave() {
37
+ if (!form.name.trim()) { setFormError('Name is required'); return }
38
+ if (!/^#[0-9A-Fa-f]{6}$/.test(form.color)) { setFormError('Color must be hex e.g. #FF5500'); return }
39
+ setSaving(true)
40
+ setFormError(null)
41
+ try {
42
+ const payload = {
43
+ name: form.name.trim(),
44
+ color: form.color,
45
+ ...(form.icon.trim() ? { icon: form.icon.trim() } : {}),
46
+ }
47
+ if (editing) {
48
+ await update(editing.id, payload)
49
+ } else {
50
+ await create(payload)
51
+ }
52
+ setOpen(false)
53
+ } catch (err) {
54
+ setFormError(err instanceof Error ? err.message : 'Save failed')
55
+ } finally {
56
+ setSaving(false)
57
+ }
58
+ }
59
+
60
+ async function handleDelete(id: string) {
61
+ if (!confirm('Delete this category? This will fail if expenses are assigned to it.')) return
62
+ try {
63
+ await remove(id)
64
+ } catch (err) {
65
+ alert(err instanceof Error ? err.message : 'Delete failed')
66
+ }
67
+ }
68
+
69
+ return (
70
+ <div className="p-6 max-w-2xl">
71
+ <div className="flex items-center justify-between mb-6">
72
+ <h1 className="text-2xl font-bold">Categories</h1>
73
+ <Button onClick={openCreate} size="sm">
74
+ <Plus size={16} className="mr-1" /> Add category
75
+ </Button>
76
+ </div>
77
+
78
+ {loading && <p className="text-muted-foreground">Loading…</p>}
79
+ {error && <p className="text-destructive">{error}</p>}
80
+
81
+ <div className="space-y-2">
82
+ {categories.map(cat => (
83
+ <Card key={cat.id}>
84
+ <CardContent className="py-3 flex items-center justify-between">
85
+ <div className="flex items-center gap-3">
86
+ <span
87
+ className="w-4 h-4 rounded-full shrink-0"
88
+ style={{ backgroundColor: cat.color }}
89
+ />
90
+ <span className="font-medium">{cat.icon} {cat.name}</span>
91
+ </div>
92
+ <div className="flex gap-2">
93
+ <Button variant="ghost" size="icon" onClick={() => openEdit(cat)}>
94
+ <Pencil size={14} />
95
+ </Button>
96
+ <Button variant="ghost" size="icon" onClick={() => void handleDelete(cat.id)}>
97
+ <Trash2 size={14} className="text-destructive" />
98
+ </Button>
99
+ </div>
100
+ </CardContent>
101
+ </Card>
102
+ ))}
103
+ </div>
104
+
105
+ <Dialog open={open} onOpenChange={setOpen}>
106
+ <DialogContent>
107
+ <DialogHeader>
108
+ <DialogTitle>{editing ? 'Edit Category' : 'New Category'}</DialogTitle>
109
+ </DialogHeader>
110
+ <div className="space-y-4 py-2">
111
+ <div className="space-y-1">
112
+ <Label>Name</Label>
113
+ <Input
114
+ value={form.name}
115
+ onChange={e => setForm(f => ({ ...f, name: e.target.value }))}
116
+ placeholder="e.g. Food"
117
+ autoFocus
118
+ />
119
+ </div>
120
+ <div className="space-y-1">
121
+ <Label>Color (hex)</Label>
122
+ <div className="flex gap-2 items-center">
123
+ <input
124
+ type="color"
125
+ value={form.color}
126
+ onChange={e => setForm(f => ({ ...f, color: e.target.value }))}
127
+ className="w-10 h-10 rounded border cursor-pointer"
128
+ />
129
+ <Input
130
+ value={form.color}
131
+ onChange={e => setForm(f => ({ ...f, color: e.target.value }))}
132
+ placeholder="#6B7280"
133
+ className="font-mono"
134
+ />
135
+ </div>
136
+ </div>
137
+ <div className="space-y-1">
138
+ <Label>Icon (emoji, optional)</Label>
139
+ <Input
140
+ value={form.icon}
141
+ onChange={e => setForm(f => ({ ...f, icon: e.target.value }))}
142
+ placeholder="🍔"
143
+ />
144
+ </div>
145
+ {formError && <p className="text-sm text-destructive">{formError}</p>}
146
+ </div>
147
+ <DialogFooter>
148
+ <Button variant="outline" onClick={() => setOpen(false)}>Cancel</Button>
149
+ <Button onClick={() => void handleSave()} disabled={saving}>
150
+ {saving ? 'Saving…' : 'Save'}
151
+ </Button>
152
+ </DialogFooter>
153
+ </DialogContent>
154
+ </Dialog>
155
+ </div>
156
+ )
157
+ }
apps/expense-dashboard/src/pages/DashboardPage.tsx ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useAnalytics } from '@/hooks/useAnalytics'
2
+ import { useExpenses } from '@/hooks/useExpenses'
3
+ import SpendDonut from '@/components/analytics/SpendDonut'
4
+ import DailyBarChart from '@/components/analytics/DailyBarChart'
5
+ import BudgetCard from '@/components/analytics/BudgetCard'
6
+ import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
7
+ import { getCurrentMonth, formatMonth } from '@/lib/dates'
8
+
9
+ export default function DashboardPage() {
10
+ const { summary, trends, loading, error } = useAnalytics()
11
+ const { expenses } = useExpenses(getCurrentMonth())
12
+
13
+ const currentMonth = formatMonth(getCurrentMonth())
14
+
15
+ return (
16
+ <div className="p-6 max-w-5xl space-y-6">
17
+ <h1 className="text-2xl font-bold">Dashboard — {currentMonth}</h1>
18
+
19
+ {loading && <p className="text-muted-foreground">Loading…</p>}
20
+ {error && <p className="text-destructive">{error}</p>}
21
+
22
+ {summary && (
23
+ <>
24
+ {/* Total spend summary */}
25
+ <Card>
26
+ <CardContent className="pt-6">
27
+ <p className="text-sm text-muted-foreground">Total spent this month</p>
28
+ <p className="text-4xl font-bold tabular-nums mt-1">
29
+ ฿{summary.total_spent.toLocaleString()}
30
+ </p>
31
+ {summary.currency_warning && (
32
+ <p className="text-xs text-yellow-600 mt-1">⚠ Multiple currencies detected — totals are approximate</p>
33
+ )}
34
+ </CardContent>
35
+ </Card>
36
+
37
+ {/* Charts row */}
38
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
39
+ <Card>
40
+ <CardHeader className="pb-2">
41
+ <CardTitle className="text-base">Spend by category</CardTitle>
42
+ </CardHeader>
43
+ <CardContent>
44
+ <SpendDonut categories={summary.categories} />
45
+ </CardContent>
46
+ </Card>
47
+
48
+ <Card>
49
+ <CardHeader className="pb-2">
50
+ <CardTitle className="text-base">Daily spend</CardTitle>
51
+ </CardHeader>
52
+ <CardContent>
53
+ <DailyBarChart expenses={expenses} />
54
+ </CardContent>
55
+ </Card>
56
+ </div>
57
+
58
+ {/* Budget cards */}
59
+ {summary.categories.length > 0 && (
60
+ <div>
61
+ <h2 className="text-base font-semibold mb-3">Budget tracking</h2>
62
+ <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">
63
+ {summary.categories.map(item => (
64
+ <BudgetCard key={item.category_id} item={item} />
65
+ ))}
66
+ </div>
67
+ </div>
68
+ )}
69
+
70
+ {/* Trends */}
71
+ {trends && trends.months.length > 0 && (
72
+ <Card>
73
+ <CardHeader className="pb-2">
74
+ <CardTitle className="text-base">6-month trend</CardTitle>
75
+ </CardHeader>
76
+ <CardContent>
77
+ <div className="flex items-end gap-2 h-24">
78
+ {[...trends.months].reverse().map(m => {
79
+ const maxTotal = Math.max(...trends.months.map(x => x.total), 1)
80
+ const heightPct = (m.total / maxTotal) * 100
81
+ return (
82
+ <div key={m.period} className="flex-1 flex flex-col items-center gap-1">
83
+ <div
84
+ className="w-full bg-primary/70 rounded-t"
85
+ style={{ height: `${Math.max(heightPct, 4)}%` }}
86
+ />
87
+ <span className="text-xs text-muted-foreground">
88
+ {m.period.slice(5)}
89
+ </span>
90
+ </div>
91
+ )
92
+ })}
93
+ </div>
94
+ </CardContent>
95
+ </Card>
96
+ )}
97
+ </>
98
+ )}
99
+ </div>
100
+ )
101
+ }
apps/expense-dashboard/src/pages/ExpensesPage.tsx ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useState } from 'react'
2
+ import { useExpenses } from '@/hooks/useExpenses'
3
+ import { useCategories } from '@/hooks/useCategories'
4
+ import ExpenseList from '@/components/expenses/ExpenseList'
5
+ import AddExpenseDrawer from '@/components/expenses/AddExpenseDrawer'
6
+ import { Button } from '@/components/ui/button'
7
+ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
8
+ import { Plus } from 'lucide-react'
9
+ import { formatMonth, getLast12Months } from '@/lib/dates'
10
+ import type { CreateExpense } from '@llm-router/shared'
11
+
12
+ export default function ExpensesPage() {
13
+ const { expenses, loading, error, selectedMonth, setSelectedMonth, create, update, remove } = useExpenses()
14
+ const { categories } = useCategories()
15
+ const [drawerOpen, setDrawerOpen] = useState(false)
16
+ const months = getLast12Months()
17
+
18
+ const totalSpent = expenses.reduce((sum, e) => sum + Number(e.amount), 0)
19
+
20
+ async function handleSave(data: CreateExpense) {
21
+ await create(data)
22
+ }
23
+
24
+ async function handleUpdate(id: string, data: Parameters<typeof update>[1]) {
25
+ await update(id, data)
26
+ }
27
+
28
+ async function handleDelete(id: string) {
29
+ if (!confirm('Delete this expense?')) return
30
+ try {
31
+ await remove(id)
32
+ } catch (err) {
33
+ alert(err instanceof Error ? err.message : 'Delete failed')
34
+ }
35
+ }
36
+
37
+ return (
38
+ <div className="p-6 max-w-3xl">
39
+ <div className="flex items-center justify-between mb-6">
40
+ <div className="flex items-center gap-4">
41
+ <h1 className="text-2xl font-bold">Expenses</h1>
42
+ <Select value={selectedMonth} onValueChange={setSelectedMonth}>
43
+ <SelectTrigger className="w-40">
44
+ <SelectValue />
45
+ </SelectTrigger>
46
+ <SelectContent>
47
+ {months.map(m => (
48
+ <SelectItem key={m} value={m}>{formatMonth(m)}</SelectItem>
49
+ ))}
50
+ </SelectContent>
51
+ </Select>
52
+ </div>
53
+ <div className="flex items-center gap-4">
54
+ <span className="text-muted-foreground text-sm">
55
+ Total: <strong className="text-foreground">฿{totalSpent.toLocaleString()}</strong>
56
+ </span>
57
+ <Button size="sm" onClick={() => setDrawerOpen(true)}>
58
+ <Plus size={16} className="mr-1" /> Add
59
+ </Button>
60
+ </div>
61
+ </div>
62
+
63
+ {loading && <p className="text-muted-foreground">Loading…</p>}
64
+ {error && <p className="text-destructive">{error}</p>}
65
+ {!loading && (
66
+ <ExpenseList
67
+ expenses={expenses}
68
+ categories={categories}
69
+ onUpdate={handleUpdate}
70
+ onDelete={handleDelete}
71
+ />
72
+ )}
73
+
74
+ <AddExpenseDrawer
75
+ open={drawerOpen}
76
+ onOpenChange={setDrawerOpen}
77
+ categories={categories}
78
+ onSave={handleSave}
79
+ />
80
+ </div>
81
+ )
82
+ }
apps/expense-dashboard/src/pages/LoginPage.tsx ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useState, type FormEvent } from 'react'
2
+ import { useNavigate } from 'react-router-dom'
3
+ import { setToken } from '@/lib/auth'
4
+ import { login } from '@/api/auth'
5
+ import { Button } from '@/components/ui/button'
6
+ import { Input } from '@/components/ui/input'
7
+ import { Label } from '@/components/ui/label'
8
+ import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
9
+
10
+ export default function LoginPage() {
11
+ const navigate = useNavigate()
12
+ const [email, setEmail] = useState('')
13
+ const [password, setPassword] = useState('')
14
+ const [loading, setLoading] = useState(false)
15
+ const [error, setError] = useState<string | null>(null)
16
+
17
+ async function handleSubmit(e: FormEvent) {
18
+ e.preventDefault()
19
+ setLoading(true)
20
+ setError(null)
21
+ try {
22
+ const { token } = await login(email, password)
23
+ setToken(token)
24
+ navigate('/')
25
+ } catch (err) {
26
+ setError(err instanceof Error ? err.message : 'Login failed')
27
+ } finally {
28
+ setLoading(false)
29
+ }
30
+ }
31
+
32
+ return (
33
+ <div className="min-h-screen flex items-center justify-center bg-muted">
34
+ <Card className="w-full max-w-sm">
35
+ <CardHeader>
36
+ <CardTitle className="text-2xl text-center">Expense Dashboard</CardTitle>
37
+ </CardHeader>
38
+ <CardContent>
39
+ <form onSubmit={handleSubmit} className="space-y-4">
40
+ <div className="space-y-1">
41
+ <Label htmlFor="email">Email</Label>
42
+ <Input
43
+ id="email"
44
+ type="email"
45
+ value={email}
46
+ onChange={e => setEmail(e.target.value)}
47
+ required
48
+ autoFocus
49
+ />
50
+ </div>
51
+ <div className="space-y-1">
52
+ <Label htmlFor="password">Password</Label>
53
+ <Input
54
+ id="password"
55
+ type="password"
56
+ value={password}
57
+ onChange={e => setPassword(e.target.value)}
58
+ required
59
+ />
60
+ </div>
61
+ {error && <p className="text-sm text-destructive">{error}</p>}
62
+ <Button type="submit" className="w-full" disabled={loading}>
63
+ {loading ? 'Signing in…' : 'Sign in'}
64
+ </Button>
65
+ </form>
66
+ </CardContent>
67
+ </Card>
68
+ </div>
69
+ )
70
+ }