1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
|
'use client';
import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Table, TableHeader, TableRow, TableHead, TableBody, TableCell } from '@/components/ui/table';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { loanApi, Loan, LoanInput } from '@/lib/api';
export default function LoansPage() {
const queryClient = useQueryClient();
const [isAddDialogOpen, setIsAddDialogOpen] = useState(false);
const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
const [loanToDelete, setLoanToDelete] = useState<number | null>(null);
const [selectedLoan, setSelectedLoan] = useState<Loan | null>(null);
// Form state
const [loanName, setLoanName] = useState('');
const [originalAmount, setOriginalAmount] = useState('');
const [currentBalance, setCurrentBalance] = useState('');
const [interestRate, setInterestRate] = useState('');
const [startDate, setStartDate] = useState('');
const [endDate, setEndDate] = useState('');
const [formError, setFormError] = useState('');
// Query loans
const { data, isLoading, error } = useQuery({
queryKey: ['loans'],
queryFn: async () => {
const response = await loanApi.getLoans();
console.log('API Response:', response); // Debug the response structure
// The response might be the array directly rather than nested under a 'loans' property
if (Array.isArray(response)) {
return response as Loan[];
}
// Or it might be nested under a 'loans' or 'data' property
return (response.loans || response.data || []) as Loan[];
}
});
// Create loan mutation
const createLoanMutation = useMutation({
mutationFn: (loanData: LoanInput) => loanApi.createLoan(loanData),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['loans'] });
resetForm();
setIsAddDialogOpen(false);
},
onError: (error: Error) => {
setFormError(error.message);
}
});
// Delete loan mutation
const deleteLoanMutation = useMutation({
mutationFn: (id: number) => loanApi.deleteLoan(id),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['loans'] });
setIsDeleteDialogOpen(false);
setLoanToDelete(null);
}
});
const resetForm = () => {
setLoanName('');
setOriginalAmount('');
setCurrentBalance('');
setInterestRate('');
setStartDate('');
setEndDate('');
setFormError('');
setSelectedLoan(null);
};
const handleCreateLoan = (e: React.FormEvent) => {
e.preventDefault();
setFormError('');
try {
// Validate inputs
if (!loanName || !originalAmount || !currentBalance || !startDate || !endDate) {
setFormError('Please fill in all required fields');
return;
}
const loanData: LoanInput = {
name: loanName,
originalAmount: Number(originalAmount) * 100, // Convert to cents
currentBalance: Number(currentBalance) * 100, // Convert to cents
interestRate: Number(interestRate) || 0,
startDate,
endDate,
};
createLoanMutation.mutate(loanData);
} catch (err: any) {
setFormError(err.message || 'Error creating loan');
}
};
const handleDeleteLoan = (id: number) => {
setLoanToDelete(id);
setIsDeleteDialogOpen(true);
};
const confirmDeleteLoan = () => {
if (loanToDelete !== null) {
deleteLoanMutation.mutate(loanToDelete);
}
};
// Format currency (convert cents to dollars)
const formatCurrency = (amount: number) => {
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
}).format(amount / 100);
};
// Format date
const formatDate = (dateString: string) => {
return new Date(dateString).toLocaleDateString();
};
if (isLoading) {
return <div>Loading loans...</div>;
}
if (error) {
return <div>Error loading loans: {error.toString()}</div>;
}
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<h1 className="text-3xl font-bold">Loans</h1>
<Dialog open={isAddDialogOpen} onOpenChange={setIsAddDialogOpen}>
<DialogTrigger asChild>
<Button onClick={resetForm}>Add New Loan</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>Add New Loan</DialogTitle>
</DialogHeader>
<form onSubmit={handleCreateLoan} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="name">Loan Name</Label>
<Input
id="name"
placeholder="e.g., Car Loan"
value={loanName}
onChange={(e) => setLoanName(e.target.value)}
required
/>
</div>
<div className="space-y-2">
<Label htmlFor="originalAmount">Original Amount ($)</Label>
<Input
id="originalAmount"
type="number"
step="0.01"
placeholder="10000.00"
value={originalAmount}
onChange={(e) => setOriginalAmount(e.target.value)}
required
/>
</div>
<div className="space-y-2">
<Label htmlFor="currentBalance">Current Balance ($)</Label>
<Input
id="currentBalance"
type="number"
step="0.01"
placeholder="9500.00"
value={currentBalance}
onChange={(e) => setCurrentBalance(e.target.value)}
required
/>
</div>
<div className="space-y-2">
<Label htmlFor="interestRate">Interest Rate (%)</Label>
<Input
id="interestRate"
type="number"
step="0.01"
placeholder="5.25"
value={interestRate}
onChange={(e) => setInterestRate(e.target.value)}
/>
</div>
<div className="space-y-2">
<Label htmlFor="startDate">Start Date</Label>
<Input
id="startDate"
type="date"
value={startDate}
onChange={(e) => setStartDate(e.target.value)}
required
/>
</div>
<div className="space-y-2">
<Label htmlFor="endDate">End Date</Label>
<Input
id="endDate"
type="date"
value={endDate}
onChange={(e) => setEndDate(e.target.value)}
required
/>
</div>
{formError && (
<div className="text-sm text-red-500">
{formError}
</div>
)}
<div className="flex justify-end space-x-2">
<Button type="button" variant="outline" onClick={() => setIsAddDialogOpen(false)}>
Cancel
</Button>
<Button type="submit" disabled={createLoanMutation.isPending}>
{createLoanMutation.isPending ? 'Saving...' : 'Save Loan'}
</Button>
</div>
</form>
</DialogContent>
</Dialog>
</div>
{/* Delete Confirmation Dialog */}
<Dialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>Confirm Deletion</DialogTitle>
</DialogHeader>
<div className="space-y-4 py-4">
<p>Are you sure you want to delete this loan? This action cannot be undone.</p>
</div>
<div className="flex justify-end space-x-2">
<Button variant="outline" onClick={() => setIsDeleteDialogOpen(false)}>
Cancel
</Button>
<Button
variant="destructive"
onClick={confirmDeleteLoan}
disabled={deleteLoanMutation.isPending}
>
{deleteLoanMutation.isPending ? 'Deleting...' : 'Delete Loan'}
</Button>
</div>
</DialogContent>
</Dialog>
{data && data.length > 0 ? (
<Card>
<CardHeader>
<CardTitle>Your Loans</CardTitle>
</CardHeader>
<CardContent>
<Table>
<TableHeader>
<TableRow>
<TableHead>Name</TableHead>
<TableHead>Original Amount</TableHead>
<TableHead>Current Balance</TableHead>
<TableHead>Interest Rate</TableHead>
<TableHead>Start Date</TableHead>
<TableHead>End Date</TableHead>
<TableHead>Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{data.map((loan) => (
<TableRow key={loan.ID}>
<TableCell className="font-medium">{loan.Name}</TableCell>
<TableCell>{formatCurrency(loan.OriginalAmount)}</TableCell>
<TableCell>{formatCurrency(loan.CurrentBalance)}</TableCell>
<TableCell>{loan.InterestRate}%</TableCell>
<TableCell>{formatDate(loan.StartDate)}</TableCell>
<TableCell>{formatDate(loan.EndDate)}</TableCell>
<TableCell>
<div className="flex items-center space-x-2">
<Button
variant="destructive"
size="sm"
onClick={() => handleDeleteLoan(loan.ID)}
disabled={deleteLoanMutation.isPending}
>
Delete
</Button>
</div>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</CardContent>
</Card>
) : (
<Card>
<CardContent className="flex flex-col items-center justify-center p-10">
<p className="text-muted-foreground mb-4">You don't have any loans yet.</p>
<Button onClick={() => setIsAddDialogOpen(true)}>Add Your First Loan</Button>
</CardContent>
</Card>
)}
</div>
);
}
|