Enhance finance tracking with record creation and improved data handling
Updates the FinancesPage component to allow creating financial records via API. Replit-Commit-Author: Agent Replit-Commit-Session-Id: d7e7c4e8-20cb-41c4-9d0e-79f48938fede Replit-Commit-Screenshot-Url: https://storage.googleapis.com/screenshot-production-us-central1/9777c70b-fc38-4831-8d6b-78dfffe041b0/0880b8cd-75f3-424e-a72e-7bb3a1a4d190.jpg
This commit is contained in:
+160
-207
@@ -1,94 +1,100 @@
|
|||||||
import { useState } from "react";
|
import { useState } from 'react';
|
||||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from '@/components/ui/button';
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from '@/components/ui/input';
|
||||||
import { Label } from "@/components/ui/label";
|
import { Label } from '@/components/ui/label';
|
||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
import { Textarea } from '@/components/ui/textarea';
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||||
import { PageHeader } from "@/components/ui/page-header";
|
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
|
||||||
import { useToast } from "@/hooks/use-toast";
|
import { Badge } from '@/components/ui/badge';
|
||||||
import Sidebar from "@/components/layout/Sidebar";
|
import { PageHeader } from '@/components/ui/page-header';
|
||||||
import { Plus, DollarSign, TrendingUp, TrendingDown } from "lucide-react";
|
import { useToast } from '@/hooks/use-toast';
|
||||||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
|
import { apiRequest } from '@/lib/queryClient';
|
||||||
import { apiRequest } from "@/lib/queryClient";
|
import Sidebar from '@/components/layout/Sidebar';
|
||||||
|
import { Plus, TrendingUp, TrendingDown, DollarSign } from 'lucide-react';
|
||||||
|
|
||||||
export default function FinancesPage() {
|
export default function FinancesPage() {
|
||||||
const { toast } = useToast();
|
const { toast } = useToast();
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
const [open, setOpen] = useState(false);
|
const [open, setOpen] = useState(false);
|
||||||
const [newRecord, setNewRecord] = useState({
|
const [newRecord, setNewRecord] = useState({
|
||||||
type: "expense",
|
type: 'expense' as 'income' | 'expense',
|
||||||
amount: "",
|
amount: '',
|
||||||
description: "",
|
category: '',
|
||||||
category: "",
|
description: ''
|
||||||
});
|
});
|
||||||
|
|
||||||
const { data: recordsResponse, isLoading: recordsLoading } = useQuery({
|
// Fetch financial records
|
||||||
queryKey: ["/api/financial/records"],
|
const { data: records, isLoading } = useQuery({
|
||||||
|
queryKey: ['/api/financial-records'],
|
||||||
|
queryFn: async () => {
|
||||||
|
const response = await fetch('/api/financial-records');
|
||||||
|
if (!response.ok) throw new Error('Failed to fetch records');
|
||||||
|
return response.json();
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
const { data: summaryResponse, isLoading: summaryLoading } = useQuery({
|
// Fetch financial summary
|
||||||
queryKey: ["/api/financial/summary"],
|
const { data: summary } = useQuery({
|
||||||
|
queryKey: ['/api/financial-records/summary'],
|
||||||
|
queryFn: async () => {
|
||||||
|
const response = await fetch('/api/financial-records/summary');
|
||||||
|
if (!response.ok) throw new Error('Failed to fetch summary');
|
||||||
|
return response.json();
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
const records = (recordsResponse as any)?.records || [];
|
// Create record mutation
|
||||||
const summary = (summaryResponse as any)?.summary || { income: 0, expenses: 0, net: 0 };
|
const createMutation = useMutation({
|
||||||
|
mutationFn: async (recordData: typeof newRecord) => {
|
||||||
const createRecordMutation = useMutation({
|
const response = await fetch('/api/financial-records', {
|
||||||
mutationFn: async (record: typeof newRecord) => {
|
method: 'POST',
|
||||||
const response = await fetch("/api/financial/records", {
|
headers: { 'Content-Type': 'application/json' },
|
||||||
method: "POST",
|
|
||||||
headers: {
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
},
|
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
...record,
|
...recordData,
|
||||||
amount: parseFloat(record.amount),
|
amount: parseFloat(recordData.amount)
|
||||||
}),
|
})
|
||||||
credentials: "include",
|
|
||||||
});
|
});
|
||||||
if (!response.ok) throw new Error("Failed to create record");
|
if (!response.ok) throw new Error('Failed to create record');
|
||||||
return response.json();
|
return response.json();
|
||||||
},
|
},
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: ["/api/financial/records"] });
|
queryClient.invalidateQueries({ queryKey: ['/api/financial-records'] });
|
||||||
queryClient.invalidateQueries({ queryKey: ["/api/financial/summary"] });
|
queryClient.invalidateQueries({ queryKey: ['/api/financial-records/summary'] });
|
||||||
setOpen(false);
|
setOpen(false);
|
||||||
setNewRecord({ type: "expense", amount: "", description: "", category: "" });
|
setNewRecord({ type: 'expense', amount: '', category: '', description: '' });
|
||||||
toast({
|
toast({ title: "Record created successfully!" });
|
||||||
title: "Record created",
|
|
||||||
description: "Your financial record has been successfully created.",
|
|
||||||
});
|
|
||||||
},
|
},
|
||||||
onError: () => {
|
onError: () => {
|
||||||
toast({
|
toast({ title: "Failed to create record", variant: "destructive" });
|
||||||
title: "Error",
|
}
|
||||||
description: "Failed to create record. Please try again.",
|
|
||||||
variant: "destructive",
|
|
||||||
});
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const handleCreateRecord = (e: React.FormEvent) => {
|
const handleSubmit = (e: React.FormEvent) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
if (!newRecord.amount || isNaN(parseFloat(newRecord.amount))) {
|
if (!newRecord.amount || !newRecord.category) {
|
||||||
toast({
|
toast({ title: "Please fill in all required fields", variant: "destructive" });
|
||||||
title: "Invalid amount",
|
|
||||||
description: "Please enter a valid amount.",
|
|
||||||
variant: "destructive",
|
|
||||||
});
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
createRecordMutation.mutate(newRecord);
|
createMutation.mutate(newRecord);
|
||||||
};
|
};
|
||||||
|
|
||||||
const categories = {
|
// Income categories
|
||||||
income: ["Salary", "Freelance", "Investment", "Business", "Other"],
|
const incomeCategories = [
|
||||||
expense: ["Food", "Transportation", "Housing", "Entertainment", "Healthcare", "Shopping", "Other"],
|
'Salary', 'Freelancing', 'Investment', 'Business', 'Gift', 'Other'
|
||||||
};
|
];
|
||||||
|
|
||||||
if (recordsLoading || summaryLoading) {
|
// Expense categories
|
||||||
|
const expenseCategories = [
|
||||||
|
'Food', 'Transportation', 'Housing', 'Utilities', 'Healthcare',
|
||||||
|
'Entertainment', 'Shopping', 'Education', 'Travel', 'Other'
|
||||||
|
];
|
||||||
|
|
||||||
|
const categories = newRecord.type === 'income' ? incomeCategories : expenseCategories;
|
||||||
|
|
||||||
|
// Loading state
|
||||||
|
if (isLoading) {
|
||||||
return (
|
return (
|
||||||
<div className="flex h-screen bg-gray-50 dark:bg-gray-900">
|
<div className="flex h-screen bg-gray-50 dark:bg-gray-900">
|
||||||
<Sidebar className="w-64 border-r" />
|
<Sidebar className="w-64 border-r" />
|
||||||
@@ -97,7 +103,7 @@ export default function FinancesPage() {
|
|||||||
<div className="h-8 bg-gray-200 dark:bg-gray-700 rounded w-1/4"></div>
|
<div className="h-8 bg-gray-200 dark:bg-gray-700 rounded w-1/4"></div>
|
||||||
<div className="h-4 bg-gray-200 dark:bg-gray-700 rounded w-1/2"></div>
|
<div className="h-4 bg-gray-200 dark:bg-gray-700 rounded w-1/2"></div>
|
||||||
<div className="grid grid-cols-3 gap-4">
|
<div className="grid grid-cols-3 gap-4">
|
||||||
{[1, 2, 3].map((i) => (
|
{[...Array(3)].map((_, i) => (
|
||||||
<div key={i} className="h-24 bg-gray-200 dark:bg-gray-700 rounded"></div>
|
<div key={i} className="h-24 bg-gray-200 dark:bg-gray-700 rounded"></div>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
@@ -131,58 +137,9 @@ export default function FinancesPage() {
|
|||||||
</DialogDescription>
|
</DialogDescription>
|
||||||
</DialogHeader>
|
</DialogHeader>
|
||||||
<form onSubmit={handleSubmit} className="space-y-4">
|
<form onSubmit={handleSubmit} className="space-y-4">
|
||||||
<div className="space-y-2">
|
|
||||||
<Label htmlFor="amount">Amount</Label>
|
|
||||||
<Input
|
|
||||||
id="amount"
|
|
||||||
type="number"
|
|
||||||
step="0.01"
|
|
||||||
value={formData.amount}
|
|
||||||
onChange={(e) => setFormData({ ...formData, amount: e.target.value })}
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="type">Type</Label>
|
<Label htmlFor="type">Type</Label>
|
||||||
<Select value={formData.type} onValueChange={(value) => setFormData({ ...formData, type: value })}>
|
<Select value={newRecord.type} onValueChange={(value: any) => setNewRecord({ ...newRecord, type: value, category: '' })}>
|
||||||
<SelectTrigger>
|
|
||||||
<SelectValue />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
<SelectItem value="income">Income</SelectItem>
|
|
||||||
<SelectItem value="expense">Expense</SelectItem>
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label htmlFor="category">Category</Label>
|
|
||||||
<Input
|
|
||||||
id="category"
|
|
||||||
value={formData.category}
|
|
||||||
onChange={(e) => setFormData({ ...formData, category: e.target.value })}
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label htmlFor="description">Description</Label>
|
|
||||||
<Textarea
|
|
||||||
id="description"
|
|
||||||
value={formData.description}
|
|
||||||
onChange={(e) => setFormData({ ...formData, description: e.target.value })}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<Button type="submit" disabled={createMutation.isPending}>
|
|
||||||
{createMutation.isPending ? "Adding..." : "Add Record"}
|
|
||||||
</Button>
|
|
||||||
</form>
|
|
||||||
</DialogContent>
|
|
||||||
</Dialog>
|
|
||||||
</PageHeader>
|
|
||||||
|
|
||||||
<div className="space-y-6">
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label htmlFor="type">Type</Label>
|
|
||||||
<Select value={newRecord.type} onValueChange={(value) => setNewRecord({ ...newRecord, type: value, category: "" })}>
|
|
||||||
<SelectTrigger>
|
<SelectTrigger>
|
||||||
<SelectValue />
|
<SelectValue />
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
@@ -211,8 +168,8 @@ export default function FinancesPage() {
|
|||||||
<SelectValue placeholder="Select category" />
|
<SelectValue placeholder="Select category" />
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
{categories[newRecord.type as keyof typeof categories].map((category) => (
|
{categories.map((category) => (
|
||||||
<SelectItem key={category} value={category}>
|
<SelectItem key={category} value={category.toLowerCase()}>
|
||||||
{category}
|
{category}
|
||||||
</SelectItem>
|
</SelectItem>
|
||||||
))}
|
))}
|
||||||
@@ -221,112 +178,108 @@ export default function FinancesPage() {
|
|||||||
</div>
|
</div>
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="description">Description</Label>
|
<Label htmlFor="description">Description</Label>
|
||||||
<Input
|
<Textarea
|
||||||
id="description"
|
id="description"
|
||||||
placeholder="Brief description"
|
placeholder="Optional description..."
|
||||||
value={newRecord.description}
|
value={newRecord.description}
|
||||||
onChange={(e) => setNewRecord({ ...newRecord, description: e.target.value })}
|
onChange={(e) => setNewRecord({ ...newRecord, description: e.target.value })}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<Button type="submit" disabled={createRecordMutation.isPending}>
|
<Button type="submit" disabled={createMutation.isPending}>
|
||||||
{createRecordMutation.isPending ? "Adding..." : "Add Record"}
|
{createMutation.isPending ? "Adding..." : "Add Record"}
|
||||||
</Button>
|
</Button>
|
||||||
</form>
|
</form>
|
||||||
</DialogContent>
|
</DialogContent>
|
||||||
</Dialog>
|
</Dialog>
|
||||||
</div>
|
</PageHeader>
|
||||||
|
|
||||||
{/* Summary Cards */}
|
<div className="space-y-6">
|
||||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-6">
|
{/* Financial Summary Cards */}
|
||||||
<Card>
|
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
|
||||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
<Card>
|
||||||
<CardTitle className="text-sm font-medium">Total Income</CardTitle>
|
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||||
<TrendingUp className="h-4 w-4 text-green-600" />
|
<CardTitle className="text-sm font-medium">Total Income</CardTitle>
|
||||||
</CardHeader>
|
<TrendingUp className="h-4 w-4 text-green-600" />
|
||||||
<CardContent>
|
</CardHeader>
|
||||||
<div className="text-2xl font-bold text-green-600">
|
<CardContent>
|
||||||
${summary.income.toFixed(2)}
|
<div className="text-2xl font-bold text-green-600">
|
||||||
</div>
|
${summary?.income?.toFixed(2) || '0.00'}
|
||||||
</CardContent>
|
</div>
|
||||||
</Card>
|
</CardContent>
|
||||||
|
</Card>
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||||
<CardTitle className="text-sm font-medium">Total Expenses</CardTitle>
|
<CardTitle className="text-sm font-medium">Total Expenses</CardTitle>
|
||||||
<TrendingDown className="h-4 w-4 text-red-600" />
|
<TrendingDown className="h-4 w-4 text-red-600" />
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
<div className="text-2xl font-bold text-red-600">
|
<div className="text-2xl font-bold text-red-600">
|
||||||
${summary.expenses.toFixed(2)}
|
${summary?.expenses?.toFixed(2) || '0.00'}
|
||||||
</div>
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
<Card>
|
||||||
<Card>
|
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
<CardTitle className="text-sm font-medium">Net Balance</CardTitle>
|
||||||
<CardTitle className="text-sm font-medium">Net Balance</CardTitle>
|
<DollarSign className="h-4 w-4 text-blue-600" />
|
||||||
<DollarSign className="h-4 w-4 text-blue-600" />
|
</CardHeader>
|
||||||
</CardHeader>
|
<CardContent>
|
||||||
<CardContent>
|
<div className={`text-2xl font-bold ${(summary?.net || 0) >= 0 ? 'text-green-600' : 'text-red-600'}`}>
|
||||||
<div className={`text-2xl font-bold ${summary.net >= 0 ? 'text-green-600' : 'text-red-600'}`}>
|
${summary?.net?.toFixed(2) || '0.00'}
|
||||||
${summary.net.toFixed(2)}
|
</div>
|
||||||
</div>
|
</CardContent>
|
||||||
</CardContent>
|
</Card>
|
||||||
</Card>
|
</div>
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Records List */}
|
{/* Recent Transactions */}
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle>Recent Transactions</CardTitle>
|
<CardTitle>Recent Transactions</CardTitle>
|
||||||
<CardDescription>
|
<CardDescription>
|
||||||
Your latest financial transactions
|
Your latest financial records
|
||||||
</CardDescription>
|
</CardDescription>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
{records.length === 0 ? (
|
{!records || records.length === 0 ? (
|
||||||
<div className="text-center py-6">
|
<div className="text-center py-8">
|
||||||
<DollarSign className="w-12 h-12 mx-auto text-gray-400 mb-4" />
|
<p className="text-muted-foreground mb-4">
|
||||||
<h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-2">
|
No financial records yet. Start by adding your first transaction.
|
||||||
No records yet
|
</p>
|
||||||
</h3>
|
<Button onClick={() => setOpen(true)}>
|
||||||
<p className="text-gray-600 dark:text-gray-300 mb-4">
|
<Plus className="w-4 h-4 mr-2" />
|
||||||
Start tracking your finances by adding your first record.
|
Add Record
|
||||||
</p>
|
</Button>
|
||||||
<Button onClick={() => setOpen(true)}>
|
</div>
|
||||||
<Plus className="w-4 h-4 mr-2" />
|
) : (
|
||||||
Add Record
|
<div className="space-y-4">
|
||||||
</Button>
|
{records.map((record: any) => (
|
||||||
</div>
|
<div key={record.id} className="flex items-center justify-between p-4 border rounded-lg">
|
||||||
) : (
|
<div className="flex items-center gap-4">
|
||||||
<div className="space-y-4">
|
<div className={`p-2 rounded-full ${record.type === 'income' ? 'bg-green-100 text-green-600' : 'bg-red-100 text-red-600'}`}>
|
||||||
{records.map((record: any) => (
|
{record.type === 'income' ? <TrendingUp className="w-4 h-4" /> : <TrendingDown className="w-4 h-4" />}
|
||||||
<div key={record.id} className="flex items-center justify-between p-4 border rounded-lg">
|
</div>
|
||||||
<div className="flex items-center gap-4">
|
<div>
|
||||||
<div className={`p-2 rounded-full ${record.type === 'income' ? 'bg-green-100 text-green-600' : 'bg-red-100 text-red-600'}`}>
|
<div className="font-medium">{record.description || record.category}</div>
|
||||||
{record.type === 'income' ? <TrendingUp className="w-4 h-4" /> : <TrendingDown className="w-4 h-4" />}
|
<div className="text-sm text-gray-600 dark:text-gray-300">
|
||||||
</div>
|
{record.category} • {new Date(record.createdAt).toLocaleDateString()}
|
||||||
<div>
|
</div>
|
||||||
<div className="font-medium">{record.description || record.category}</div>
|
|
||||||
<div className="text-sm text-gray-600 dark:text-gray-300">
|
|
||||||
{record.category} • {new Date(record.createdAt).toLocaleDateString()}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
<div className="text-right">
|
||||||
<div className="text-right">
|
<div className={`font-semibold ${record.type === 'income' ? 'text-green-600' : 'text-red-600'}`}>
|
||||||
<div className={`font-semibold ${record.type === 'income' ? 'text-green-600' : 'text-red-600'}`}>
|
{record.type === 'income' ? '+' : '-'}${record.amount.toFixed(2)}
|
||||||
{record.type === 'income' ? '+' : '-'}${record.amount.toFixed(2)}
|
</div>
|
||||||
|
<Badge variant={record.type === 'income' ? 'default' : 'secondary'}>
|
||||||
|
{record.type}
|
||||||
|
</Badge>
|
||||||
</div>
|
</div>
|
||||||
<Badge variant={record.type === 'income' ? 'default' : 'secondary'}>
|
|
||||||
{record.type}
|
|
||||||
</Badge>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
))}
|
||||||
))}
|
</div>
|
||||||
</div>
|
)}
|
||||||
)}
|
</CardContent>
|
||||||
</CardContent>
|
</Card>
|
||||||
</Card>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
Reference in New Issue
Block a user