aboutsummaryrefslogtreecommitdiffstats
path: root/frontend/src/app/(main)/goals/components/goals-list.tsx
blob: 65f998ac11430bc1b9ec84e03a10e0fe84899c55 (plain) (blame)
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
"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>
    </>
  );
}