Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
96 changes: 60 additions & 36 deletions src/app/api/categories/route.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,15 @@
import { NextResponse } from 'next/server';
import { getCurrentUser, handleApiError } from '@/lib/auth';
import { getDb } from '@/lib/db';
import { FinanceService } from '@/lib/finance-service';

export const runtime = 'nodejs';

export async function GET(req: Request) {
try {
const user = getCurrentUser(req);
const db = getDb();

const categories = db.prepare(`
SELECT * FROM categories
WHERE (user_id = ? OR id LIKE 'cat-%') AND archived = 0
ORDER BY sort_order ASC, name ASC
`).all(user.id) as any[];

// Structure into parent and subcategories
const parents = categories.filter(c => !c.parent_id);
const tree = parents.map(p => ({
...p,
subcategories: categories.filter(c => c.parent_id === p.id),
}));

return NextResponse.json({ categories, tree });
const service = new FinanceService();
const result = service.getCategories(user.id);
return NextResponse.json(result);
} catch (error: any) {
return handleApiError(error, 'Failed to fetch categories');
}
Expand All @@ -32,30 +19,67 @@ export async function POST(req: Request) {
try {
const user = getCurrentUser(req);
const body = await req.json();
const db = getDb();

if (!body.name || !body.type) {
return NextResponse.json({ error: 'Name and type are required' }, { status: 400 });
if (!body.name) {
return NextResponse.json({ error: 'Category name is required' }, { status: 400 });
}

const id = `cat_${Date.now()}_${Math.random().toString(36).substring(2, 6)}`;
db.prepare(`
INSERT INTO categories (id, user_id, parent_id, name, type, icon, color, sort_order)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
`).run(
id,
user.id,
body.parentId || null,
body.name,
body.type,
body.icon || 'tag',
body.color || '#6B7280',
body.sortOrder || 99
);

const category = db.prepare('SELECT * FROM categories WHERE id = ?').get(id);
const service = new FinanceService();
const category = service.createCategory(user.id, {
name: body.name,
type: body.type,
parentId: body.parentId,
isSubcategory: body.isSubcategory,
icon: body.icon,
color: body.color,
sortOrder: body.sortOrder,
});

return NextResponse.json({ category }, { status: 201 });
} catch (error: any) {
return handleApiError(error, 'Failed to create category');
}
}

export async function PUT(req: Request) {
try {
const user = getCurrentUser(req);
const body = await req.json();

if (!body.id) {
return NextResponse.json({ error: 'Category id is required' }, { status: 400 });
}

const service = new FinanceService();
const category = service.updateCategory(user.id, body.id, {
name: body.name,
parentId: body.parentId,
icon: body.icon,
color: body.color,
sortOrder: body.sortOrder,
});

return NextResponse.json({ category });
} catch (error: any) {
return handleApiError(error, 'Failed to update category');
}
}

export async function DELETE(req: Request) {
try {
const user = getCurrentUser(req);
const { searchParams } = new URL(req.url);
const id = searchParams.get('id');

if (!id) {
return NextResponse.json({ error: 'Category id is required' }, { status: 400 });
}

const service = new FinanceService();
service.deleteCategory(user.id, id);

return NextResponse.json({ success: true });
} catch (error: any) {
return handleApiError(error, 'Failed to delete category');
}
}
38 changes: 31 additions & 7 deletions src/app/budgets/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { Plus, PieChart, AlertTriangle, CheckCircle2, Trash2, X } from 'lucide-r
import { formatIndianNumberString, parseIndianNumber } from '@/lib/amount-evaluator';

export default function BudgetsPage() {
const { showToast, refreshKey, triggerRefresh, startAsyncOp, stopAsyncOp } = useApp();
const { showToast, refreshKey, triggerRefresh, startAsyncOp, stopAsyncOp, openCategoryModal } = useApp();
const [budgets, setBudgets] = useState<any[]>([]);
const [categories, setCategories] = useState<any[]>([]);
const [loading, setLoading] = useState(true);
Expand Down Expand Up @@ -94,9 +94,14 @@ export default function BudgetsPage() {
</p>
</div>

<button className="btn-primary" onClick={() => setIsOpen(true)}>
<Plus size={16} /> Create Budget
</button>
<div style={{ display: 'flex', gap: '0.5rem', alignItems: 'center' }}>
<button className="btn-secondary" onClick={() => openCategoryModal('expense')}>
<Plus size={15} /> Add Category
</button>
<button className="btn-primary" onClick={() => setIsOpen(true)}>
<Plus size={16} /> Create Budget
</button>
</div>
</div>

{/* Summary Cards */}
Expand Down Expand Up @@ -200,9 +205,28 @@ export default function BudgetsPage() {

<form onSubmit={handleCreate} style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}>
<div>
<label style={{ display: 'block', fontSize: '0.75rem', fontWeight: 600, color: 'var(--text-muted)', marginBottom: '0.35rem' }}>
CATEGORY
</label>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '0.35rem' }}>
<label style={{ display: 'block', fontSize: '0.75rem', fontWeight: 600, color: 'var(--text-muted)', margin: 0 }}>
CATEGORY
</label>
<button
type="button"
onClick={() => {
openCategoryModal('expense', undefined, '', false, newCat => {
fetch('/api/categories')
.then(r => r.json())
.then(d => {
const exp = (d.categories || []).filter((c: any) => c.type === 'expense');
setCategories(exp);
if (newCat?.id) setCategoryId(newCat.id);
});
});
}}
style={{ fontSize: '0.75rem', color: 'var(--brand-primary)', fontWeight: 600, background: 'none', border: 'none', cursor: 'pointer', padding: 0 }}
>
+ Add Category
</button>
</div>
<select
className="input-field"
value={categoryId}
Expand Down
2 changes: 2 additions & 0 deletions src/app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { TransactionModal } from '@/components/TransactionModal';
import { CommandPalette } from '@/components/CommandPalette';
import { ImportModal } from '@/components/ImportModal';
import { AccountModal } from '@/components/AccountModal';
import { GlobalCategoryModal } from '@/components/CategoryModal';
import { ToastContainer } from '@/components/ToastContainer';
import { Analytics } from '@vercel/analytics/next';
import { SpeedInsights } from '@vercel/speed-insights/next';
Expand Down Expand Up @@ -66,6 +67,7 @@ export default function RootLayout({
<CommandPalette />
<ImportModal />
<AccountModal />
<GlobalCategoryModal />
<ToastContainer />
</AppProvider>
<Analytics />
Expand Down
Loading
Loading