mirror of
https://github.com/dat515-2025/Group-8.git
synced 2026-03-22 15:12:08 +01:00
Compare commits
1 Commits
89d032dd69
...
20-create-
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
405be381fc |
@@ -1,27 +1,39 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import './App.css';
|
||||
import LoginRegisterPage from './pages/LoginRegisterPage';
|
||||
import Dashboard from './pages/Dashboard';
|
||||
import { logout } from './api';
|
||||
import { useState } from 'react'
|
||||
import reactLogo from './assets/react.svg'
|
||||
import viteLogo from '/vite.svg'
|
||||
import './App.css'
|
||||
import { BACKEND_URL } from './config'
|
||||
|
||||
function App() {
|
||||
const [hasToken, setHasToken] = useState<boolean>(!!localStorage.getItem('token'));
|
||||
|
||||
useEffect(() => {
|
||||
const onStorage = (e: StorageEvent) => {
|
||||
if (e.key === 'token') setHasToken(!!e.newValue);
|
||||
};
|
||||
window.addEventListener('storage', onStorage);
|
||||
return () => window.removeEventListener('storage', onStorage);
|
||||
}, []);
|
||||
|
||||
if (!hasToken) {
|
||||
return <LoginRegisterPage onLoggedIn={() => setHasToken(true)} />;
|
||||
}
|
||||
const [count, setCount] = useState(0)
|
||||
|
||||
return (
|
||||
<Dashboard onLogout={() => { logout(); setHasToken(false); }} />
|
||||
);
|
||||
<>
|
||||
<div>
|
||||
<a href="https://vite.dev" target="_blank">
|
||||
<img src={viteLogo} className="logo" alt="Vite logo" />
|
||||
</a>
|
||||
<a href="https://react.dev" target="_blank">
|
||||
<img src={reactLogo} className="logo react" alt="React logo" />
|
||||
</a>
|
||||
</div>
|
||||
<h1>Vite + React</h1>
|
||||
<div className="card">
|
||||
<button onClick={() => setCount((count) => count + 1)}>
|
||||
count is {count}
|
||||
</button>
|
||||
<p>
|
||||
Edit <code>src/App.tsx</code> and save to test HMR
|
||||
</p>
|
||||
<p style={{ fontSize: 12, color: '#888' }}>
|
||||
Backend URL: <code>{BACKEND_URL || '(not configured)'}</code>
|
||||
</p>
|
||||
</div>
|
||||
<p className="read-the-docs">
|
||||
Click on the Vite and React logos to learn more
|
||||
</p>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default App;
|
||||
export default App
|
||||
|
||||
@@ -1,100 +0,0 @@
|
||||
import { BACKEND_URL } from './config';
|
||||
|
||||
export type LoginResponse = {
|
||||
access_token: string;
|
||||
token_type: string;
|
||||
};
|
||||
|
||||
export type Category = {
|
||||
id: number;
|
||||
name: string;
|
||||
description?: string | null;
|
||||
};
|
||||
|
||||
export type Transaction = {
|
||||
id: number;
|
||||
amount: number;
|
||||
description?: string | null;
|
||||
category_ids: number[];
|
||||
};
|
||||
|
||||
function getBaseUrl() {
|
||||
const base = BACKEND_URL?.replace(/\/$/, '') || '';
|
||||
return base || '';
|
||||
}
|
||||
|
||||
function authHeaders() {
|
||||
const token = localStorage.getItem('token');
|
||||
return token ? { Authorization: `Bearer ${token}` } : {};
|
||||
}
|
||||
|
||||
export async function login(email: string, password: string): Promise<void> {
|
||||
const body = new URLSearchParams();
|
||||
body.set('username', email);
|
||||
body.set('password', password);
|
||||
|
||||
const res = await fetch(`${getBaseUrl()}/auth/jwt/login`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
},
|
||||
body: body.toString(),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const text = await res.text();
|
||||
throw new Error(text || 'Login failed');
|
||||
}
|
||||
const data: LoginResponse = await res.json();
|
||||
localStorage.setItem('token', data.access_token);
|
||||
}
|
||||
|
||||
export async function register(email: string, password: string, first_name?: string, last_name?: string): Promise<void> {
|
||||
const res = await fetch(`${getBaseUrl()}/auth/register`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ email, password, first_name, last_name }),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const text = await res.text();
|
||||
throw new Error(text || 'Registration failed');
|
||||
}
|
||||
}
|
||||
|
||||
export async function getCategories(): Promise<Category[]> {
|
||||
const res = await fetch(`${getBaseUrl()}/categories/`, {
|
||||
headers: { 'Content-Type': 'application/json', ...authHeaders() },
|
||||
});
|
||||
if (!res.ok) throw new Error('Failed to load categories');
|
||||
return res.json();
|
||||
}
|
||||
|
||||
export type CreateTransactionInput = {
|
||||
amount: number;
|
||||
description?: string;
|
||||
category_ids?: number[];
|
||||
};
|
||||
|
||||
export async function createTransaction(input: CreateTransactionInput): Promise<Transaction> {
|
||||
const res = await fetch(`${getBaseUrl()}/transactions/create`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', ...authHeaders() },
|
||||
body: JSON.stringify(input),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const text = await res.text();
|
||||
throw new Error(text || 'Failed to create transaction');
|
||||
}
|
||||
return res.json();
|
||||
}
|
||||
|
||||
export async function getTransactions(): Promise<Transaction[]> {
|
||||
const res = await fetch(`${getBaseUrl()}/transactions/`, {
|
||||
headers: { 'Content-Type': 'application/json', ...authHeaders() },
|
||||
});
|
||||
if (!res.ok) throw new Error('Failed to load transactions');
|
||||
return res.json();
|
||||
}
|
||||
|
||||
export function logout() {
|
||||
localStorage.removeItem('token');
|
||||
}
|
||||
@@ -1,155 +0,0 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { type Category, type Transaction, createTransaction, getCategories, getTransactions } from '../api';
|
||||
|
||||
function formatAmount(n: number) {
|
||||
return new Intl.NumberFormat(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(n);
|
||||
}
|
||||
|
||||
export default function Dashboard({ onLogout }: { onLogout: () => void }) {
|
||||
const [transactions, setTransactions] = useState<Transaction[]>([]);
|
||||
const [categories, setCategories] = useState<Category[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// New transaction form state
|
||||
const [amount, setAmount] = useState<string>('');
|
||||
const [description, setDescription] = useState('');
|
||||
const [selectedCategoryId, setSelectedCategoryId] = useState<number | ''>('');
|
||||
|
||||
// Filters
|
||||
const [minAmount, setMinAmount] = useState<string>('');
|
||||
const [maxAmount, setMaxAmount] = useState<string>('');
|
||||
const [filterCategoryId, setFilterCategoryId] = useState<number | ''>('');
|
||||
const [searchText, setSearchText] = useState('');
|
||||
|
||||
async function loadAll() {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const [txs, cats] = await Promise.all([getTransactions(), getCategories()]);
|
||||
setTransactions(txs);
|
||||
setCategories(cats);
|
||||
} catch (err: any) {
|
||||
setError(err?.message || 'Failed to load data');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
loadAll();
|
||||
}, []);
|
||||
|
||||
const last10 = useMemo(() => {
|
||||
const sorted = [...transactions].sort((a, b) => b.id - a.id);
|
||||
return sorted.slice(0, 10);
|
||||
}, [transactions]);
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
let arr = last10;
|
||||
const min = minAmount !== '' ? Number(minAmount) : undefined;
|
||||
const max = maxAmount !== '' ? Number(maxAmount) : undefined;
|
||||
if (min !== undefined) arr = arr.filter(t => t.amount >= min);
|
||||
if (max !== undefined) arr = arr.filter(t => t.amount <= max);
|
||||
if (filterCategoryId !== '') arr = arr.filter(t => t.category_ids.includes(filterCategoryId as number));
|
||||
if (searchText.trim()) arr = arr.filter(t => (t.description || '').toLowerCase().includes(searchText.toLowerCase()));
|
||||
return arr;
|
||||
}, [last10, minAmount, maxAmount, filterCategoryId, searchText]);
|
||||
|
||||
function categoryNameById(id: number) {
|
||||
return categories.find(c => c.id === id)?.name || `#${id}`;
|
||||
}
|
||||
|
||||
async function handleCreate(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!amount) return;
|
||||
const payload = {
|
||||
amount: Number(amount),
|
||||
description: description || undefined,
|
||||
category_ids: selectedCategoryId !== '' ? [Number(selectedCategoryId)] : undefined,
|
||||
};
|
||||
try {
|
||||
const created = await createTransaction(payload);
|
||||
setTransactions(prev => [created, ...prev]);
|
||||
// reset form
|
||||
setAmount('');
|
||||
setDescription('');
|
||||
setSelectedCategoryId('');
|
||||
} catch (err: any) {
|
||||
alert(err?.message || 'Failed to create transaction');
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{ maxWidth: 900, margin: '2rem auto', padding: 16 }}>
|
||||
<header style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}>
|
||||
<h2 style={{ margin: 0 }}>Dashboard</h2>
|
||||
<button onClick={onLogout}>Logout</button>
|
||||
</header>
|
||||
|
||||
<section style={{ border: '1px solid #eee', padding: 12, borderRadius: 8, marginBottom: 16 }}>
|
||||
<h3 style={{ marginTop: 0 }}>Add Transaction</h3>
|
||||
<form onSubmit={handleCreate} style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
|
||||
<input type="number" step="0.01" placeholder="Amount" value={amount} onChange={(e) => setAmount(e.target.value)} required />
|
||||
<input type="text" placeholder="Description (optional)" value={description} onChange={(e) => setDescription(e.target.value)} />
|
||||
<select value={selectedCategoryId} onChange={(e) => setSelectedCategoryId(e.target.value ? Number(e.target.value) : '')}>
|
||||
<option value="">No category</option>
|
||||
{categories.map(c => (
|
||||
<option key={c.id} value={c.id}>{c.name}</option>
|
||||
))}
|
||||
</select>
|
||||
<button type="submit">Add</button>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section style={{ border: '1px solid #eee', padding: 12, borderRadius: 8, marginBottom: 16 }}>
|
||||
<h3 style={{ marginTop: 0 }}>Filters</h3>
|
||||
<div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
|
||||
<input type="number" step="0.01" placeholder="Min amount" value={minAmount} onChange={(e) => setMinAmount(e.target.value)} />
|
||||
<input type="number" step="0.01" placeholder="Max amount" value={maxAmount} onChange={(e) => setMaxAmount(e.target.value)} />
|
||||
<select value={filterCategoryId} onChange={(e) => setFilterCategoryId(e.target.value ? Number(e.target.value) : '')}>
|
||||
<option value="">All categories</option>
|
||||
{categories.map(c => (
|
||||
<option key={c.id} value={c.id}>{c.name}</option>
|
||||
))}
|
||||
</select>
|
||||
<input type="text" placeholder="Search in description" value={searchText} onChange={(e) => setSearchText(e.target.value)} />
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section style={{ border: '1px solid #eee', padding: 12, borderRadius: 8 }}>
|
||||
<h3 style={{ marginTop: 0 }}>Latest Transactions (last 10)</h3>
|
||||
{loading ? (
|
||||
<div>Loading…</div>
|
||||
) : error ? (
|
||||
<div style={{ color: 'crimson' }}>{error}</div>
|
||||
) : filtered.length === 0 ? (
|
||||
<div>No transactions</div>
|
||||
) : (
|
||||
<table style={{ width: '100%', borderCollapse: 'collapse' }}>
|
||||
<thead>
|
||||
<tr>
|
||||
<th style={{ textAlign: 'left', borderBottom: '1px solid #ddd' }}>ID</th>
|
||||
<th style={{ textAlign: 'right', borderBottom: '1px solid #ddd' }}>Amount</th>
|
||||
<th style={{ textAlign: 'left', borderBottom: '1px solid #ddd' }}>Description</th>
|
||||
<th style={{ textAlign: 'left', borderBottom: '1px solid #ddd' }}>Categories</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{filtered.map(t => (
|
||||
<tr key={t.id}>
|
||||
<td style={{ padding: '6px 4px' }}>{t.id}</td>
|
||||
<td style={{ padding: '6px 4px', textAlign: 'right' }}>{formatAmount(t.amount)}</td>
|
||||
<td style={{ padding: '6px 4px' }}>{t.description || ''}</td>
|
||||
<td style={{ padding: '6px 4px' }}>
|
||||
{t.category_ids.map(id => categoryNameById(id)).join(', ')}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,71 +0,0 @@
|
||||
import { useState } from 'react';
|
||||
import { login, register } from '../api';
|
||||
|
||||
export default function LoginRegisterPage({ onLoggedIn }: { onLoggedIn: () => void }) {
|
||||
const [mode, setMode] = useState<'login' | 'register'>('login');
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [firstName, setFirstName] = useState('');
|
||||
const [lastName, setLastName] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
if (mode === 'login') {
|
||||
await login(email, password);
|
||||
onLoggedIn();
|
||||
} else {
|
||||
await register(email, password, firstName || undefined, lastName || undefined);
|
||||
// After register, prompt login automatically
|
||||
await login(email, password);
|
||||
onLoggedIn();
|
||||
}
|
||||
} catch (err: any) {
|
||||
setError(err?.message || 'Operation failed');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{ maxWidth: 420, margin: '4rem auto', padding: 24, border: '1px solid #ddd', borderRadius: 8 }}>
|
||||
<h2 style={{ marginTop: 0 }}>{mode === 'login' ? 'Login' : 'Register'}</h2>
|
||||
<div style={{ marginBottom: 16 }}>
|
||||
<button onClick={() => setMode('login')} disabled={mode === 'login'}>Login</button>
|
||||
<button onClick={() => setMode('register')} disabled={mode === 'register'} style={{ marginLeft: 8 }}>Register</button>
|
||||
</div>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div style={{ marginBottom: 12 }}>
|
||||
<label>Email<br />
|
||||
<input type="email" required value={email} onChange={(e) => setEmail(e.target.value)} style={{ width: '100%' }} />
|
||||
</label>
|
||||
</div>
|
||||
<div style={{ marginBottom: 12 }}>
|
||||
<label>Password<br />
|
||||
<input type="password" required value={password} onChange={(e) => setPassword(e.target.value)} style={{ width: '100%' }} />
|
||||
</label>
|
||||
</div>
|
||||
{mode === 'register' && (
|
||||
<>
|
||||
<div style={{ marginBottom: 12 }}>
|
||||
<label>First name (optional)<br />
|
||||
<input type="text" value={firstName} onChange={(e) => setFirstName(e.target.value)} style={{ width: '100%' }} />
|
||||
</label>
|
||||
</div>
|
||||
<div style={{ marginBottom: 12 }}>
|
||||
<label>Last name (optional)<br />
|
||||
<input type="text" value={lastName} onChange={(e) => setLastName(e.target.value)} style={{ width: '100%' }} />
|
||||
</label>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{error && <div style={{ color: 'crimson', marginBottom: 12 }}>{error}</div>}
|
||||
<button type="submit" disabled={loading}>{loading ? 'Please wait…' : (mode === 'login' ? 'Login' : 'Register')}</button>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user