aboutsummaryrefslogtreecommitdiffstats
path: root/frontend/src/app
diff options
context:
space:
mode:
authorLibravatarLibravatar Biswa Kalyan Bhuyan <biswa@surgot.in> 2025-04-27 23:02:42 +0530
committerLibravatarLibravatar Biswa Kalyan Bhuyan <biswa@surgot.in> 2025-04-27 23:02:42 +0530
commit538d933baef56d7ee76f78617b553d63713efa24 (patch)
tree3fcbc4208849dfa0e5dc8fe5761e103a3591c283 /frontend/src/app
parent3941d80ff120238b973451325b834ebd8377281e (diff)
downloadfinance-master.tar.gz
finance-master.tar.bz2
finance-master.zip
finance: feat: added the goal page with some improvements of uiHEADmaster
Diffstat (limited to 'frontend/src/app')
-rw-r--r--frontend/src/app/(main)/goals/[id]/page.tsx290
-rw-r--r--frontend/src/app/(main)/goals/components/goal-form.tsx349
-rw-r--r--frontend/src/app/(main)/goals/components/goals-list.tsx297
-rw-r--r--frontend/src/app/(main)/goals/edit/[id]/page.tsx16
-rw-r--r--frontend/src/app/(main)/goals/layout.tsx14
-rw-r--r--frontend/src/app/(main)/goals/new/page.tsx16
-rw-r--r--frontend/src/app/(main)/goals/page.tsx44
-rw-r--r--frontend/src/app/(main)/layout.tsx8
-rw-r--r--frontend/src/app/layout.tsx2
9 files changed, 1032 insertions, 4 deletions
diff --git a/frontend/src/app/(main)/goals/[id]/page.tsx b/frontend/src/app/(main)/goals/[id]/page.tsx
new file mode 100644
index 0000000..3428ca4
--- /dev/null
+++ b/frontend/src/app/(main)/goals/[id]/page.tsx
@@ -0,0 +1,290 @@
+"use client";
+
+import { useState, useEffect, useCallback } from "react";
+import { useRouter } from "next/navigation";
+import Link from "next/link";
+import { Button } from "@/components/ui/button";
+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
+import { Progress } from "@/components/ui/progress";
+import { Badge } from "@/components/ui/badge";
+import { Edit, ArrowLeft, Loader2, RefreshCw } from "lucide-react";
+import { useToast } from "@/components/ui/use-toast";
+import { formatCurrency } from "@/lib/utils";
+import { api } from "@/lib/api";
+import { GoalProgress } from "../components/goals-list";
+
+export default function GoalDetailPage({ params }: { params: { id: string } }) {
+ const id = params.id;
+ const goalId = parseInt(id);
+
+ const [goal, setGoal] = useState<GoalWithProgress | null>(null);
+ const [loading, setLoading] = useState(true);
+ const [refreshing, setRefreshing] = useState(false);
+ const router = useRouter();
+ const { toast } = useToast();
+
+ const fetchGoalDetails = useCallback(async () => {
+ try {
+ console.log(`Fetching goal details for ID: ${goalId}`);
+ setLoading(true);
+
+ // Add cache-busting parameter
+ const response = await api.get<GoalProgress>(`/goals/${goalId}/progress?cache=${new Date().getTime()}`);
+ console.log("Goal details received:", response.data);
+
+ // Validate and normalize data
+ const data = response.data;
+ if (data && data.goal) {
+ const sanitizedData = {
+ ...data,
+ goal: {
+ ...data.goal,
+ targetAmount: Number(data.goal.targetAmount) || 0,
+ currentAmount: Number(data.goal.currentAmount) || 0,
+ createdAt: data.goal.createdAt || new Date().toISOString(),
+ },
+ percentComplete: Number(data.percentComplete) || 0,
+ amountRemaining: Number(data.amountRemaining) || 0,
+ daysRemaining: Number(data.daysRemaining) || 0,
+ requiredPerDay: Number(data.requiredPerDay) || 0,
+ requiredPerMonth: Number(data.requiredPerMonth) || 0,
+ };
+ console.log("Processed goal data:", sanitizedData);
+ setGoal(sanitizedData);
+ } else {
+ console.error("Invalid goal data format:", data);
+ throw new Error("Invalid goal data received");
+ }
+ } catch (error) {
+ console.error("Error fetching goal details:", error);
+ toast({
+ title: "Error",
+ description: "Failed to fetch goal details. Please try again.",
+ variant: "destructive",
+ });
+ router.push("/goals");
+ } finally {
+ setLoading(false);
+ }
+ }, [goalId, toast, router]);
+
+ // Fetch goal details when component mounts
+ useEffect(() => {
+ if (!id) {
+ toast({
+ title: "Error",
+ description: "Goal ID is missing. Please try again.",
+ variant: "destructive",
+ });
+ router.push("/goals");
+ return;
+ }
+
+ fetchGoalDetails();
+ }, [id, fetchGoalDetails, router, toast]);
+
+ const recalculateProgress = async () => {
+ if (isNaN(goalId)) {
+ toast({
+ title: "Error",
+ description: "Invalid goal ID",
+ variant: "destructive",
+ });
+ return;
+ }
+
+ try {
+ setRefreshing(true);
+ await api.post(`/goals/${goalId}/recalculate`);
+ toast({
+ title: "Progress recalculated",
+ description: "Your goal progress has been recalculated based on transactions.",
+ });
+ fetchGoalDetails();
+ } catch (error) {
+ toast({
+ title: "Error",
+ description: "Failed to recalculate goal progress. Please try again.",
+ variant: "destructive",
+ });
+ console.error("Error recalculating goal progress:", error);
+ } finally {
+ setRefreshing(false);
+ }
+ };
+
+ if (loading) {
+ return (
+ <div className="container mx-auto py-8 flex justify-center items-center">
+ <Loader2 className="h-8 w-8 animate-spin" />
+ </div>
+ );
+ }
+
+ if (!goal) {
+ return (
+ <div className="container mx-auto py-8 text-center">
+ <p className="mb-4">Goal not found or access denied.</p>
+ <Link href="/goals">
+ <Button>Back to Goals</Button>
+ </Link>
+ </div>
+ );
+ }
+
+ const { goal: goalData, percentComplete, amountRemaining, daysRemaining, requiredPerDay, requiredPerMonth, onTrack } = goal;
+ const isCompleted = goalData.status === "Achieved";
+
+ return (
+ <div className="container mx-auto py-8">
+ <div className="mb-6">
+ <Link href="/goals">
+ <Button variant="ghost" size="sm">
+ <ArrowLeft className="mr-2 h-4 w-4" />
+ Back to Goals
+ </Button>
+ </Link>
+ </div>
+
+ <div className="flex flex-col md:flex-row justify-between items-start md:items-center mb-6">
+ <div>
+ <h1 className="text-2xl font-bold tracking-tight">{goalData.name}</h1>
+ <p className="text-muted-foreground">
+ {isCompleted
+ ? "Goal has been achieved 🎉"
+ : onTrack
+ ? "Progress is on track"
+ : "Progress is behind schedule"}
+ </p>
+ </div>
+ <div className="flex space-x-3 mt-4 md:mt-0">
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={recalculateProgress}
+ disabled={refreshing}
+ >
+ {refreshing ? (
+ <Loader2 className="mr-2 h-4 w-4 animate-spin" />
+ ) : (
+ <RefreshCw className="mr-2 h-4 w-4" />
+ )}
+ Recalculate
+ </Button>
+ <Link href={`/goals/edit/${goalData.id}`}>
+ <Button variant="outline" size="sm">
+ <Edit className="mr-2 h-4 w-4" />
+ Edit
+ </Button>
+ </Link>
+ </div>
+ </div>
+
+ <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
+ <Card className="lg:col-span-2">
+ <CardHeader>
+ <div className="flex justify-between items-center">
+ <CardTitle>Goal Progress</CardTitle>
+ <Badge variant={isCompleted ? "default" : onTrack ? "outline" : "destructive"}>
+ {isCompleted ? "Achieved" : onTrack ? "On Track" : "Behind"}
+ </Badge>
+ </div>
+ </CardHeader>
+ <CardContent>
+ <div className="mb-6">
+ <div className="flex justify-between mb-2">
+ <span>Completion</span>
+ <span>{Math.round(percentComplete)}%</span>
+ </div>
+ <Progress value={percentComplete} className="h-3" />
+ </div>
+
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
+ <div className="space-y-4">
+ <div>
+ <h3 className="text-sm font-medium text-muted-foreground mb-1">Target Amount</h3>
+ <p className="text-2xl font-semibold">{formatCurrency(goalData.targetAmount)}</p>
+ </div>
+ <div>
+ <h3 className="text-sm font-medium text-muted-foreground mb-1">Current Amount</h3>
+ <p className="text-2xl font-semibold">{formatCurrency(goalData.currentAmount)}</p>
+ </div>
+ <div>
+ <h3 className="text-sm font-medium text-muted-foreground mb-1">Remaining</h3>
+ <p className="text-2xl font-semibold">{formatCurrency(amountRemaining)}</p>
+ </div>
+ </div>
+
+ <div className="space-y-4">
+ {goalData.targetDate && (
+ <div>
+ <h3 className="text-sm font-medium text-muted-foreground mb-1">Target Date</h3>
+ <p className="text-xl font-semibold">{new Date(goalData.targetDate).toLocaleDateString()}</p>
+ </div>
+ )}
+ {daysRemaining > 0 && (
+ <>
+ <div>
+ <h3 className="text-sm font-medium text-muted-foreground mb-1">Days Remaining</h3>
+ <p className="text-xl font-semibold">{daysRemaining} days</p>
+ </div>
+ <div>
+ <h3 className="text-sm font-medium text-muted-foreground mb-1">Required Per Day</h3>
+ <p className="text-xl font-semibold">{formatCurrency(requiredPerDay)}</p>
+ </div>
+ <div>
+ <h3 className="text-sm font-medium text-muted-foreground mb-1">Required Per Month</h3>
+ <p className="text-xl font-semibold">{formatCurrency(requiredPerMonth)}</p>
+ </div>
+ </>
+ )}
+ </div>
+ </div>
+ </CardContent>
+ </Card>
+
+ <Card>
+ <CardHeader>
+ <CardTitle>Goal Details</CardTitle>
+ </CardHeader>
+ <CardContent>
+ <div className="space-y-4">
+ <div>
+ <h3 className="text-sm font-medium text-muted-foreground mb-1">Goal Name</h3>
+ <p className="font-medium">{goalData.name}</p>
+ </div>
+ <div>
+ <h3 className="text-sm font-medium text-muted-foreground mb-1">Purpose</h3>
+ <p>{goalData.name}</p>
+ </div>
+ <div>
+ <h3 className="text-sm font-medium text-muted-foreground mb-1">Status</h3>
+ <p>{goalData.status}</p>
+ </div>
+ <div>
+ <h3 className="text-sm font-medium text-muted-foreground mb-1">Created</h3>
+ <p>{new Date(goalData.createdAt).toLocaleDateString()}</p>
+ </div>
+ {isCompleted ? (
+ <div className="pt-4">
+ <div className="p-4 bg-green-50 dark:bg-green-950 text-green-700 dark:text-green-300 rounded-md">
+ <p className="font-semibold">🎉 Goal achieved!</p>
+ <p className="text-sm mt-1">
+ Congratulations on achieving your financial goal.
+ </p>
+ </div>
+ </div>
+ ) : (
+ <div className="pt-4">
+ <Link href={`/transactions?goalId=${goalData.id}`}>
+ <Button variant="secondary" className="w-full">View Related Transactions</Button>
+ </Link>
+ </div>
+ )}
+ </div>
+ </CardContent>
+ </Card>
+ </div>
+ </div>
+ );
+} \ No newline at end of file
diff --git a/frontend/src/app/(main)/goals/components/goal-form.tsx b/frontend/src/app/(main)/goals/components/goal-form.tsx
new file mode 100644
index 0000000..6b1cbac
--- /dev/null
+++ b/frontend/src/app/(main)/goals/components/goal-form.tsx
@@ -0,0 +1,349 @@
+"use client";
+
+import { useState, useEffect, useCallback } from "react";
+import { useRouter } from "next/navigation";
+import { useForm } from "react-hook-form";
+import { zodResolver } from "@hookform/resolvers/zod";
+import * as z from "zod";
+import { CalendarIcon } from "lucide-react";
+import { format } from "date-fns";
+
+import { Button } from "@/components/ui/button";
+import {
+ Form,
+ FormControl,
+ FormDescription,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import { Card, CardContent } from "@/components/ui/card";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover";
+import { Calendar } from "@/components/ui/calendar";
+import { useToast } from "@/components/ui/use-toast";
+import { api } from "@/lib/api";
+
+// Validation schema
+const formSchema = z.object({
+ name: z
+ .string()
+ .min(3, { message: "Name must be at least 3 characters" })
+ .max(100, { message: "Name must be less than 100 characters" }),
+ targetAmount: z
+ .number()
+ .min(1, { message: "Target amount must be greater than 0" }),
+ currentAmount: z
+ .number()
+ .min(0, { message: "Current amount cannot be negative" })
+ .optional(),
+ targetDate: z.date().optional(),
+ status: z.enum(["Active", "Paused", "Achieved", "Cancelled"]),
+});
+
+type FormValues = z.infer<typeof formSchema>;
+
+interface GoalFormProps {
+ goalId?: number;
+ isEditing?: boolean;
+ onSuccess?: () => void;
+}
+
+export function GoalForm({
+ goalId,
+ isEditing = false,
+ onSuccess
+}: GoalFormProps) {
+ const [loading, setLoading] = useState(false);
+ const [initialLoading, setInitialLoading] = useState(false);
+ const router = useRouter();
+ const { toast } = useToast();
+
+ // Set up form with validation
+ const form = useForm<FormValues>({
+ resolver: zodResolver(formSchema),
+ defaultValues: {
+ name: "",
+ targetAmount: 0,
+ currentAmount: 0,
+ status: "Active",
+ },
+ });
+
+ const fetchGoalData = useCallback(async () => {
+ setInitialLoading(true);
+ try {
+ const response = await api.get(`/goals/${goalId}`);
+ const goalData = response.data;
+
+ // Set form values
+ form.reset({
+ name: goalData.name,
+ targetAmount: goalData.targetAmount,
+ currentAmount: goalData.currentAmount,
+ status: goalData.status as "Active" | "Paused" | "Achieved" | "Cancelled",
+ ...(goalData.targetDate && { targetDate: new Date(goalData.targetDate) }),
+ });
+ } catch (error) {
+ toast({
+ title: "Error",
+ description: "Failed to fetch goal data. Please try again.",
+ variant: "destructive",
+ });
+ console.error("Error fetching goal:", error);
+ router.push("/goals");
+ } finally {
+ setInitialLoading(false);
+ }
+ }, [goalId, form, toast, router]);
+
+ // Fetch goal data if editing
+ useEffect(() => {
+ if (isEditing && goalId) {
+ fetchGoalData();
+ }
+ }, [isEditing, goalId, fetchGoalData]);
+
+ const onSubmit = async (values: FormValues) => {
+ try {
+ setLoading(true);
+
+ // Format data for API
+ const formattedData = {
+ ...values,
+ targetDate: values.targetDate ? format(values.targetDate, "yyyy-MM-dd") : undefined,
+ };
+
+ console.log("Submitting goal:", formattedData);
+
+ if (isEditing) {
+ // Update existing goal
+ await api.put(`/goals/${goalId}`, formattedData);
+ toast({
+ title: "Goal updated",
+ description: "Your goal has been updated successfully.",
+ });
+ } else {
+ // Create new goal
+ const response = await api.post("/goals", formattedData);
+ console.log("Goal created response:", response.data);
+ toast({
+ title: "Goal created",
+ description: "Your new goal has been created successfully.",
+ });
+ }
+
+ // Call onSuccess callback if provided
+ if (onSuccess) {
+ onSuccess();
+ } else {
+ // Force a full page reload directly to the goals page
+ window.location.href = "/goals";
+ }
+
+ } catch (error) {
+ toast({
+ title: "Error",
+ description: `Failed to ${isEditing ? "update" : "create"} goal. Please try again.`,
+ variant: "destructive",
+ });
+ console.error(`Error ${isEditing ? "updating" : "creating"} goal:`, error);
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ if (initialLoading) {
+ return <div className="text-center py-8">Loading goal data...</div>;
+ }
+
+ return (
+ <Card>
+ <CardContent className="pt-6">
+ <Form {...form}>
+ <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
+ <FormField
+ control={form.control}
+ name="name"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Goal Name</FormLabel>
+ <FormControl>
+ <Input placeholder="e.g., Down Payment for House" {...field} />
+ </FormControl>
+ <FormDescription>
+ A descriptive name for your financial goal
+ </FormDescription>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
+ <FormField
+ control={form.control}
+ name="targetAmount"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Target Amount</FormLabel>
+ <FormControl>
+ <Input
+ type="number"
+ placeholder="10000"
+ {...field}
+ onChange={(e) => field.onChange(Number(e.target.value))}
+ />
+ </FormControl>
+ <FormDescription>
+ The total amount you want to save
+ </FormDescription>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="currentAmount"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Current Amount</FormLabel>
+ <FormControl>
+ <Input
+ type="number"
+ placeholder="0"
+ {...field}
+ value={field.value || ""}
+ onChange={(e) => field.onChange(Number(e.target.value) || 0)}
+ />
+ </FormControl>
+ <FormDescription>
+ How much you&apos;ve already saved towards this goal
+ </FormDescription>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ </div>
+
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
+ <FormField
+ control={form.control}
+ name="targetDate"
+ render={({ field }) => (
+ <FormItem className="flex flex-col">
+ <FormLabel>Target Date (Optional)</FormLabel>
+ <Popover>
+ <PopoverTrigger asChild>
+ <FormControl>
+ <Button
+ variant={"outline"}
+ className={`w-full pl-3 text-left font-normal ${
+ !field.value ? "text-muted-foreground" : ""
+ }`}
+ >
+ {field.value ? (
+ format(field.value, "PPP")
+ ) : (
+ <span>Pick a date</span>
+ )}
+ <CalendarIcon className="ml-auto h-4 w-4 opacity-50" />
+ </Button>
+ </FormControl>
+ </PopoverTrigger>
+ <PopoverContent className="w-auto p-0" align="start">
+ <Calendar
+ mode="single"
+ selected={field.value || undefined}
+ onSelect={field.onChange}
+ disabled={(date) => date < new Date()}
+ initialFocus
+ />
+ </PopoverContent>
+ </Popover>
+ <FormDescription>
+ When you aim to achieve this goal
+ </FormDescription>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="status"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Status</FormLabel>
+ <Select
+ onValueChange={field.onChange}
+ defaultValue={field.value}
+ value={field.value}
+ >
+ <FormControl>
+ <SelectTrigger>
+ <SelectValue placeholder="Select a status" />
+ </SelectTrigger>
+ </FormControl>
+ <SelectContent>
+ <SelectItem value="Active">Active</SelectItem>
+ <SelectItem value="Paused">Paused</SelectItem>
+ <SelectItem value="Achieved">Achieved</SelectItem>
+ <SelectItem value="Cancelled">Cancelled</SelectItem>
+ </SelectContent>
+ </Select>
+ <FormDescription>
+ The current status of your goal
+ </FormDescription>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ </div>
+
+ <div className="mb-6">
+ <h3 className="text-sm font-medium text-muted-foreground mb-2">
+ Don&apos;t see the amount you need?
+ </h3>
+ <p className="text-sm">
+ Use the calculator to determine your target amount.
+ </p>
+ </div>
+
+ <div className="flex justify-end space-x-4">
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => router.push("/goals")}
+ disabled={loading}
+ >
+ Cancel
+ </Button>
+ <Button type="submit" disabled={loading}>
+ {loading
+ ? isEditing
+ ? "Updating..."
+ : "Creating..."
+ : isEditing
+ ? "Update Goal"
+ : "Create Goal"}
+ </Button>
+ </div>
+ </form>
+ </Form>
+ </CardContent>
+ </Card>
+ );
+} \ No newline at end of file
diff --git a/frontend/src/app/(main)/goals/components/goals-list.tsx b/frontend/src/app/(main)/goals/components/goals-list.tsx
new file mode 100644
index 0000000..65f998a
--- /dev/null
+++ b/frontend/src/app/(main)/goals/components/goals-list.tsx
@@ -0,0 +1,297 @@
+"use client";
+
+import { useState, useEffect, useCallback } from "react";
+import { Button } from "@/components/ui/button";
+import { Card, CardContent, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
+import { Progress } from "@/components/ui/progress";
+import { Badge } from "@/components/ui/badge";
+import { Edit, Trash2, BarChart, AlertCircle } from "lucide-react";
+import Link from "next/link";
+import { useToast } from "@/components/ui/use-toast";
+import { formatCurrency } from "@/lib/utils";
+import { api } from "@/lib/api";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+
+// Type definitions
+export interface Goal {
+ id: number;
+ name: string;
+ targetAmount: number;
+ currentAmount: number;
+ status: string;
+ targetDate: string;
+}
+
+export interface GoalProgress {
+ goal: Goal;
+ percentComplete: number;
+ amountRemaining: number;
+ daysRemaining: number;
+ requiredPerDay: number;
+ requiredPerMonth: number;
+ onTrack: boolean;
+}
+
+// Backend API response type
+interface ApiGoal {
+ ID: number;
+ Name: string;
+ TargetAmount: number;
+ CurrentAmount: number;
+ Status: string;
+ TargetDate: string;
+ // Other fields might exist but we don't need them
+}
+
+interface ApiGoalProgress {
+ goal: ApiGoal;
+ percentComplete: number;
+ amountRemaining: number;
+ daysRemaining: number;
+ requiredPerDay: number;
+ requiredPerMonth: number;
+ onTrack: boolean;
+}
+
+export function GoalsList() {
+ const [goals, setGoals] = useState<GoalProgress[]>([]);
+ const [loading, setLoading] = useState(true);
+ const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
+ const [goalToDelete, setGoalToDelete] = useState<{id: number, name: string} | null>(null);
+ const { toast } = useToast();
+
+ const fetchGoals = useCallback(async () => {
+ try {
+ setLoading(true);
+
+ // Add timestamp parameter to prevent caching
+ const response = await api.get(`/goals/progress/all?cache=${new Date().getTime()}`);
+
+ if (!response.data || !Array.isArray(response.data)) {
+ setGoals([]);
+ return;
+ }
+
+ // Validate and sanitize the data before setting state
+ const validatedGoals = response.data.map((goalProgress: ApiGoalProgress) => {
+ // Map API field names (uppercase) to our component field names (lowercase)
+ const mappedGoal = {
+ id: goalProgress.goal.ID,
+ name: goalProgress.goal.Name,
+ targetAmount: Number(goalProgress.goal.TargetAmount) || 0,
+ currentAmount: Number(goalProgress.goal.CurrentAmount) || 0,
+ status: goalProgress.goal.Status,
+ targetDate: goalProgress.goal.TargetDate
+ };
+
+ return {
+ goal: mappedGoal,
+ percentComplete: Number(goalProgress.percentComplete) || 0,
+ amountRemaining: Number(goalProgress.amountRemaining) || 0,
+ daysRemaining: Number(goalProgress.daysRemaining) || 0,
+ requiredPerDay: Number(goalProgress.requiredPerDay) || 0,
+ requiredPerMonth: Number(goalProgress.requiredPerMonth) || 0,
+ onTrack: Boolean(goalProgress.onTrack)
+ };
+ });
+
+ setGoals(validatedGoals);
+ } catch (error) {
+ console.error("Error fetching goals:", error);
+ toast({
+ title: "Error",
+ description: "Failed to fetch goals. Please try again later.",
+ variant: "destructive",
+ });
+ } finally {
+ setLoading(false);
+ }
+ }, [toast]);
+
+ // Fetch goals when component mounts or if URL contains a refresh parameter
+ useEffect(() => {
+ fetchGoals();
+
+ // Add event listener to refresh when the window gains focus (user comes back to the tab)
+ window.addEventListener("focus", fetchGoals);
+
+ return () => {
+ window.removeEventListener("focus", fetchGoals);
+ };
+ }, [fetchGoals]);
+
+ const confirmDelete = (id: number, name: string) => {
+ setGoalToDelete({ id, name });
+ setDeleteDialogOpen(true);
+ };
+
+ const handleDeleteConfirm = async () => {
+ if (!goalToDelete) return;
+
+ try {
+ const goalId = Number(goalToDelete.id);
+ await api.delete(`/goals/${goalId}`);
+ toast({
+ title: "Goal deleted",
+ description: "The goal has been successfully deleted.",
+ });
+ fetchGoals();
+ } catch (error) {
+ console.error("Error deleting goal:", error);
+ toast({
+ title: "Error",
+ description: "Failed to delete the goal. Please try again.",
+ variant: "destructive",
+ });
+ } finally {
+ setDeleteDialogOpen(false);
+ setGoalToDelete(null);
+ }
+ };
+
+ const handleDeleteCancel = () => {
+ setDeleteDialogOpen(false);
+ setGoalToDelete(null);
+ };
+
+ if (loading) {
+ return <div className="text-center py-8">Loading goals...</div>;
+ }
+
+ if (!goals || goals.length === 0) {
+ return (
+ <div className="text-center py-8">
+ <p className="text-muted-foreground mb-4">You haven&apos;t created any goals yet.</p>
+ <Link href="/goals/new">
+ <Button>Create your first goal</Button>
+ </Link>
+ </div>
+ );
+ }
+
+ return (
+ <>
+ <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 md:gap-6">
+ {goals.map((goalProgress, index) => {
+ const { goal, percentComplete, amountRemaining, daysRemaining, onTrack } = goalProgress;
+ const isCompleted = goal.status === "Achieved";
+
+ return (
+ <Card key={`goal-${goal.id}-${index}`} className="flex flex-col h-full">
+ <CardHeader className="pb-2">
+ <div className="flex flex-wrap justify-between items-start gap-2">
+ <CardTitle className="text-base sm:text-lg break-words mr-2">{goal.name}</CardTitle>
+ <Badge variant={isCompleted ? "default" : onTrack ? "outline" : "destructive"} className="whitespace-nowrap">
+ {isCompleted ? "Achieved" : onTrack ? "On Track" : "Behind"}
+ </Badge>
+ </div>
+ <p className="text-xs sm:text-sm text-muted-foreground mt-1 break-words">
+ Saving for: {goal.name}
+ </p>
+ </CardHeader>
+ <CardContent className="flex-1 py-2">
+ <div className="mb-3">
+ <div className="flex justify-between mb-1 text-sm">
+ <span>Progress</span>
+ <span>{Math.round(percentComplete)}%</span>
+ </div>
+ <Progress value={percentComplete} className="h-2" />
+ </div>
+
+ <div className="space-y-1 text-xs sm:text-sm">
+ <div key={`target-${goal.id}`} className="flex justify-between">
+ <span className="text-muted-foreground">Target</span>
+ <span className="font-medium">{formatCurrency(goal.targetAmount)}</span>
+ </div>
+ <div key={`current-${goal.id}`} className="flex justify-between">
+ <span className="text-muted-foreground">Current</span>
+ <span className="font-medium">{formatCurrency(goal.currentAmount)}</span>
+ </div>
+ <div key={`remaining-${goal.id}`} className="flex justify-between">
+ <span className="text-muted-foreground">Remaining</span>
+ <span className="font-medium">{formatCurrency(amountRemaining)}</span>
+ </div>
+ {daysRemaining > 0 && (
+ <div key={`days-left-${goal.id}`} className="flex justify-between">
+ <span className="text-muted-foreground">Days Left</span>
+ <span className="font-medium">{daysRemaining}</span>
+ </div>
+ )}
+ {goal.targetDate && (
+ <div key={`target-date-${goal.id}`} className="flex justify-between">
+ <span className="text-muted-foreground">Target Date</span>
+ <span className="font-medium">{new Date(goal.targetDate).toLocaleDateString()}</span>
+ </div>
+ )}
+ </div>
+ </CardContent>
+ <CardFooter className="pt-2 flex flex-wrap gap-2">
+ <div className="flex flex-col sm:flex-row gap-2 w-full">
+ <Link key={`details-link-${goal.id}`} href={`/goals/${goal.id}`} className="flex-1 min-w-[80px]">
+ <Button variant="outline" size="sm" className="w-full text-xs">
+ <BarChart className="mr-1 h-3 w-3" />
+ Details
+ </Button>
+ </Link>
+ <Link key={`edit-link-${goal.id}`} href={`/goals/edit/${goal.id}`} className="flex-1 min-w-[80px]">
+ <Button variant="outline" size="sm" className="w-full text-xs">
+ <Edit className="mr-1 h-3 w-3" />
+ Edit
+ </Button>
+ </Link>
+ <Button
+ key={`delete-button-${goal.id}`}
+ variant="outline"
+ size="sm"
+ className="flex-1 min-w-[80px] text-xs"
+ onClick={() => confirmDelete(goal.id, goal.name)}
+ >
+ <Trash2 className="mr-1 h-3 w-3" />
+ Delete
+ </Button>
+ </div>
+ </CardFooter>
+ </Card>
+ );
+ })}
+ </div>
+
+ <Dialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
+ <DialogContent className="sm:max-w-[425px] p-4 sm:p-6 gap-4">
+ <DialogHeader className="space-y-3">
+ <DialogTitle className="flex items-center gap-2 text-lg">
+ <AlertCircle className="h-5 w-5 text-destructive" />
+ Confirm Deletion
+ </DialogTitle>
+ <DialogDescription className="text-sm">
+ Are you sure you want to delete the goal &ldquo;{goalToDelete?.name}&rdquo;? This action cannot be undone.
+ </DialogDescription>
+ </DialogHeader>
+ <DialogFooter className="mt-4 flex-col sm:flex-row gap-2">
+ <Button
+ variant="outline"
+ onClick={handleDeleteCancel}
+ className="w-full sm:w-auto"
+ >
+ Cancel
+ </Button>
+ <Button
+ variant="destructive"
+ onClick={handleDeleteConfirm}
+ className="w-full sm:w-auto"
+ >
+ Delete Goal
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ </>
+ );
+} \ No newline at end of file
diff --git a/frontend/src/app/(main)/goals/edit/[id]/page.tsx b/frontend/src/app/(main)/goals/edit/[id]/page.tsx
new file mode 100644
index 0000000..ed51f92
--- /dev/null
+++ b/frontend/src/app/(main)/goals/edit/[id]/page.tsx
@@ -0,0 +1,16 @@
+import { Metadata } from "next";
+import { GoalForm } from "../../components/goal-form";
+
+export const metadata: Metadata = {
+ title: "Edit Goal | Finance",
+ description: "Edit your financial goal",
+};
+
+export default function EditGoalPage({ params }: { params: { id: string } }) {
+ return (
+ <div className="container mx-auto py-8">
+ <h1 className="text-2xl font-bold tracking-tight mb-6">Edit Goal</h1>
+ <GoalForm goalId={parseInt(params.id)} />
+ </div>
+ );
+} \ No newline at end of file
diff --git a/frontend/src/app/(main)/goals/layout.tsx b/frontend/src/app/(main)/goals/layout.tsx
new file mode 100644
index 0000000..25ea209
--- /dev/null
+++ b/frontend/src/app/(main)/goals/layout.tsx
@@ -0,0 +1,14 @@
+import { Metadata } from "next";
+
+export const metadata: Metadata = {
+ title: "Goals | Finance",
+ description: "Manage your financial goals",
+};
+
+export default function GoalsLayout({
+ children,
+}: {
+ children: React.ReactNode;
+}) {
+ return <>{children}</>;
+} \ No newline at end of file
diff --git a/frontend/src/app/(main)/goals/new/page.tsx b/frontend/src/app/(main)/goals/new/page.tsx
new file mode 100644
index 0000000..7640659
--- /dev/null
+++ b/frontend/src/app/(main)/goals/new/page.tsx
@@ -0,0 +1,16 @@
+import { Metadata } from "next";
+import { GoalForm } from "../components/goal-form";
+
+export const metadata: Metadata = {
+ title: "New Goal | Finance",
+ description: "Create a new financial goal",
+};
+
+export default function NewGoalPage() {
+ return (
+ <div className="container mx-auto py-8">
+ <h1 className="text-2xl font-bold tracking-tight mb-6">Create New Goal</h1>
+ <GoalForm />
+ </div>
+ );
+} \ No newline at end of file
diff --git a/frontend/src/app/(main)/goals/page.tsx b/frontend/src/app/(main)/goals/page.tsx
new file mode 100644
index 0000000..b703cff
--- /dev/null
+++ b/frontend/src/app/(main)/goals/page.tsx
@@ -0,0 +1,44 @@
+"use client";
+
+import { Button } from "@/components/ui/button";
+import { PlusCircle, RefreshCw } from "lucide-react";
+import Link from "next/link";
+import { GoalsList } from "./components/goals-list";
+import { useState } from "react";
+
+export default function GoalsPage() {
+ const [refreshing, setRefreshing] = useState(false);
+
+ const handleRefresh = () => {
+ setRefreshing(true);
+ // Force reload the page
+ window.location.href = `/goals?refresh=${new Date().getTime()}`;
+ };
+
+ return (
+ <div className="container mx-auto px-4 py-6 md:py-8">
+ <div className="flex flex-col sm:flex-row sm:justify-between sm:items-center mb-6 gap-4">
+ <div>
+ <h1 className="text-xl sm:text-2xl font-bold tracking-tight">Financial Goals</h1>
+ <p className="text-sm text-muted-foreground">
+ Track your progress towards your financial goals
+ </p>
+ </div>
+ <div className="flex gap-2 sm:gap-3">
+ <Button variant="outline" onClick={handleRefresh} disabled={refreshing} size="sm" className="text-xs sm:text-sm">
+ <RefreshCw className="mr-1 h-3 w-3 sm:h-4 sm:w-4" />
+ Refresh
+ </Button>
+ <Link href="/goals/new">
+ <Button size="sm" className="text-xs sm:text-sm">
+ <PlusCircle className="mr-1 h-3 w-3 sm:h-4 sm:w-4" />
+ New Goal
+ </Button>
+ </Link>
+ </div>
+ </div>
+
+ <GoalsList />
+ </div>
+ );
+} \ No newline at end of file
diff --git a/frontend/src/app/(main)/layout.tsx b/frontend/src/app/(main)/layout.tsx
index 11e557b..28197e3 100644
--- a/frontend/src/app/(main)/layout.tsx
+++ b/frontend/src/app/(main)/layout.tsx
@@ -200,7 +200,7 @@ export default function MainLayout({
`}
title="Dashboard"
>
- <LayoutDashboardIcon size={18} className={`transition-transform duration-300 ${pathname === '/dashboard' ? 'scale-110' : ''}`} />
+ <LayoutDashboardIcon size={18} className={`transition-transform duration-300 ${pathname === '/dashboard' ? 'scale-110' : ''} ml-1`} />
<span className={`ml-2 transition-all duration-300 overflow-hidden whitespace-nowrap ${isSidebarCollapsed ? 'w-0 opacity-0' : 'w-auto opacity-100'}`}>
Dashboard
</span>
@@ -217,7 +217,7 @@ export default function MainLayout({
`}
title="Loans"
>
- <CoinsIcon size={18} className={`transition-transform duration-300 ${pathname === '/loans' ? 'scale-110' : ''}`} />
+ <CoinsIcon size={18} className={`transition-transform duration-300 ${pathname === '/loans' ? 'scale-110' : ''} ml-1`} />
<span className={`ml-2 transition-all duration-300 overflow-hidden whitespace-nowrap ${isSidebarCollapsed ? 'w-0 opacity-0' : 'w-auto opacity-100'}`}>
Loans
</span>
@@ -234,7 +234,7 @@ export default function MainLayout({
`}
title="Goals"
>
- <TargetIcon size={18} className={`transition-transform duration-300 ${pathname === '/goals' ? 'scale-110' : ''}`} />
+ <TargetIcon size={18} className={`transition-transform duration-300 ${pathname === '/goals' ? 'scale-110' : ''} ml-1`} />
<span className={`ml-2 transition-all duration-300 overflow-hidden whitespace-nowrap ${isSidebarCollapsed ? 'w-0 opacity-0' : 'w-auto opacity-100'}`}>
Goals
</span>
@@ -251,7 +251,7 @@ export default function MainLayout({
`}
title="Settings"
>
- <SettingsIcon size={18} className={`transition-transform duration-300 ${pathname === '/settings' ? 'scale-110' : ''}`} />
+ <SettingsIcon size={18} className={`transition-transform duration-300 ${pathname === '/settings' ? 'scale-110' : ''} ml-1`} />
<span className={`ml-2 transition-all duration-300 overflow-hidden whitespace-nowrap ${isSidebarCollapsed ? 'w-0 opacity-0' : 'w-auto opacity-100'}`}>
Settings
</span>
diff --git a/frontend/src/app/layout.tsx b/frontend/src/app/layout.tsx
index d1442c8..5d5da25 100644
--- a/frontend/src/app/layout.tsx
+++ b/frontend/src/app/layout.tsx
@@ -4,6 +4,7 @@ import "./globals.css";
import { Providers } from "./providers";
import { ThemeProvider } from "@/components/shared/ThemeProvider";
import { NotificationProvider } from "@/components/shared/NotificationContext";
+import { Toaster } from "@/components/ui/toaster";
const geistSans = Geist({
variable: "--font-geist-sans",
@@ -32,6 +33,7 @@ export default function RootLayout({
<Providers>
<NotificationProvider>
{children}
+ <Toaster />
</NotificationProvider>
</Providers>
</ThemeProvider>