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
8 changes: 5 additions & 3 deletions src/app/api/auth/otp/verify/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,14 @@ export async function POST(req: Request) {
user: result.user,
});

const isProd = process.env.NODE_ENV === 'production';
const host = req.headers.get('host') || '';
const isLocal = host.includes('localhost') || host.includes('127.0.0.1');
const isSecure = process.env.NODE_ENV === 'production' && !isLocal;

// Set secure HTTP-only session cookie for 30 days
response.cookies.set('apex_session_token', result.token, {
httpOnly: true,
secure: isProd,
secure: isSecure,
sameSite: 'lax',
path: '/',
maxAge: 30 * 24 * 60 * 60, // 30 days
Expand All @@ -48,7 +50,7 @@ export async function POST(req: Request) {
// Also set finance_user_id for profile routing
response.cookies.set('finance_user_id', result.user.id, {
httpOnly: true,
secure: isProd,
secure: isSecure,
sameSite: 'lax',
path: '/',
maxAge: 30 * 24 * 60 * 60,
Expand Down
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
37 changes: 30 additions & 7 deletions src/app/loans/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ export default function LoansPage() {
if (!res.ok) throw new Error(data.error || 'Failed to record payment');

const emiFormatted = Math.round(payModalLoan.emi_amount / 100).toLocaleString('en-IN');
showToast(`Installment of ₹${emiFormatted} recorded! Bank cash & liabilities updated.`);
showToast(`Repayment transfer of ₹${emiFormatted} recorded! Cash & debt updated.`);
setPayModalLoan(null);
triggerRefresh();
} catch (err: any) {
Expand Down Expand Up @@ -402,7 +402,8 @@ export default function LoansPage() {
className="btn-primary"
onClick={() => {
setPayModalLoan(loan);
if (loan.account_id) setPayAccountId(loan.account_id);
const defaultDebit = accounts.find(a => a.id !== loan.account_id && (a.type === 'bank' || a.type === 'savings' || a.type === 'current' || a.type === 'cash')) || accounts.find(a => a.id !== loan.account_id) || accounts[0];
if (defaultDebit) setPayAccountId(defaultDebit.id);
setPayDate(new Date().toISOString().substring(0, 10));
}}
style={{
Expand Down Expand Up @@ -501,6 +502,7 @@ export default function LoansPage() {
<th style={{ padding: '0.5rem 0.75rem', textAlign: 'right' }}>Principal</th>
<th style={{ padding: '0.5rem 0.75rem', textAlign: 'right' }}>Interest</th>
<th style={{ padding: '0.5rem 0.75rem', textAlign: 'right' }}>Remaining Balance</th>
<th style={{ padding: '0.5rem 0.75rem', textAlign: 'center' }}>Status</th>
</tr>
</thead>
<tbody>
Expand All @@ -517,8 +519,8 @@ export default function LoansPage() {
<td style={{ padding: '0.4rem 0.75rem', textAlign: 'right', color: 'var(--color-expense)' }}>
₹{Math.round(row.interestComponent / 100).toLocaleString('en-IN')}
</td>
<td style={{ padding: '0.4rem 0.75rem', textAlign: 'right' }}>
₹{Math.round(row.remainingPrincipal / 100).toLocaleString('en-IN')}
<td style={{ padding: '0.4rem 0.75rem', textAlign: 'right', fontWeight: 600 }}>
₹{Math.round((row.remainingBalance ?? row.remainingPrincipal) / 100).toLocaleString('en-IN')}
</td>
</tr>
))}
Expand Down Expand Up @@ -828,9 +830,30 @@ export default function LoansPage() {
</div>
</div>

{payModalLoan.account_name && (
<div
style={{
padding: '0.6rem 0.75rem',
borderRadius: 'var(--radius-md)',
backgroundColor: 'rgba(59, 130, 246, 0.08)',
border: '1px solid rgba(59, 130, 246, 0.2)',
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
fontSize: '0.78rem',
}}
>
<div style={{ display: 'flex', alignItems: 'center', gap: '0.4rem' }}>
<CreditCard size={15} style={{ color: 'var(--brand-primary)' }} />
<span>Target Account: <strong>{payModalLoan.account_name}</strong></span>
</div>
<span style={{ fontSize: '0.7rem', color: 'var(--brand-primary)', fontWeight: 600 }}>Repayment Transfer</span>
</div>
)}

<div>
<label style={{ display: 'block', fontSize: '0.75rem', fontWeight: 600, color: 'var(--text-muted)', marginBottom: '0.35rem' }}>
PAY FROM ACCOUNT (LIQUID CASH) *
PAY FROM ACCOUNT (LIQUID CASH / BANK) *
</label>
<select
className="input-field"
Expand All @@ -839,12 +862,12 @@ export default function LoansPage() {
>
{accounts.map(a => (
<option key={a.id} value={a.id}>
{a.name} (Balance: ₹{Math.round(a.current_balance / 100).toLocaleString('en-IN')})
{a.name} ({a.type}) - Balance: ₹{Math.round(a.current_balance / 100).toLocaleString('en-IN')}
</option>
))}
</select>
<p style={{ fontSize: '0.72rem', color: 'var(--text-muted)', marginTop: '0.25rem' }}>
This will record an expense transaction and automatically deduct ₹{Math.round(payModalLoan.emi_amount / 100).toLocaleString('en-IN')} from your liquid cash.
This will record a repayment transfer from your selected account to {payModalLoan.account_name || 'the linked debt account'}, reducing both your liquid cash and debt.
</p>
</div>

Expand Down
Loading
Loading