aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--README.md8
-rw-r--r--backend/internal/api/handlers/goal_handler.go128
-rw-r--r--backend/internal/api/handlers/loan_handler.go312
-rw-r--r--backend/internal/api/v1/goals/goals.go26
-rw-r--r--backend/internal/api/v1/loans/loans.go25
-rw-r--r--backend/internal/core/goal_service.go196
-rw-r--r--backend/internal/core/goal_service_test.go129
-rw-r--r--backend/internal/database/database.go1
-rw-r--r--backend/internal/models/models.go18
-rw-r--r--backend/internal/router/router.go12
-rw-r--r--frontend/package-lock.json483
-rw-r--r--frontend/package.json7
-rw-r--r--frontend/src/app/(main)/goals/[id]/page.tsx293
-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.tsx18
-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
-rw-r--r--frontend/src/components/ui/badge.tsx36
-rw-r--r--frontend/src/components/ui/calendar.tsx64
-rw-r--r--frontend/src/components/ui/popover.tsx29
-rw-r--r--frontend/src/components/ui/progress.tsx26
-rw-r--r--frontend/src/components/ui/select.tsx158
-rw-r--r--frontend/src/components/ui/toast.tsx127
-rw-r--r--frontend/src/components/ui/toaster.tsx35
-rw-r--r--frontend/src/components/ui/use-toast.tsx191
-rw-r--r--frontend/src/lib/api.ts304
-rw-r--r--frontend/src/lib/utils.ts14
31 files changed, 3172 insertions, 198 deletions
diff --git a/README.md b/README.md
index b390b63..29d291a 100644
--- a/README.md
+++ b/README.md
@@ -111,15 +111,15 @@ An application designed to help manage personal finances, including income (like
* **Backend:**
* [x] Implement logic for loan calculations (remaining balance, interest if applicable)
- * [ ] Implement logic for goal progress tracking based on transactions/savings
- * [ ] Refine APIs for Loans and Goals based on frontend needs
+ * [x] Implement logic for goal progress tracking based on transactions/savings
+ * [x] Refine APIs for Loans and Goals based on frontend needs
* [ ] Add validation logic for all inputs
* [ ] Enhance tests for loan and goal logic
* **Frontend:**
* [x] Create components for displaying loan details and history
* [x] Create forms for adding/editing loans
- * [ ] Create components for displaying financial goals and progress
- * [ ] Create forms for adding/editing goals
+ * [x] Create components for displaying financial goals and progress
+ * [x] Create forms for adding/editing goals
* [x] Connect loan and goal components to backend APIs
**Phase 4: Notifications**
diff --git a/backend/internal/api/handlers/goal_handler.go b/backend/internal/api/handlers/goal_handler.go
index 09bea74..efbe7f9 100644
--- a/backend/internal/api/handlers/goal_handler.go
+++ b/backend/internal/api/handlers/goal_handler.go
@@ -6,6 +6,7 @@ import (
"strconv"
"time"
+ "finance/backend/internal/core"
"finance/backend/internal/database"
"finance/backend/internal/models"
@@ -35,13 +36,21 @@ type UpdateGoalProgressInput struct {
CurrentAmount int64 `json:"currentAmount" binding:"required"`
}
+// LinkTransactionInput defines the structure for linking a transaction to a goal
+type LinkTransactionInput struct {
+ TransactionID uint `json:"transactionId" binding:"required"`
+}
+
// GoalHandler handles all goal-related operations in the API
type GoalHandler struct {
+ goalService *core.GoalService
}
// NewGoalHandler creates and returns a new GoalHandler instance
func NewGoalHandler() *GoalHandler {
- return &GoalHandler{}
+ return &GoalHandler{
+ goalService: core.NewGoalService(),
+ }
}
// GetGoals retrieves all goals for the authenticated user
@@ -270,3 +279,120 @@ func (h *GoalHandler) DeleteGoal(c *gin.Context) {
log.Printf("Goal ID %d deleted successfully for user %d", goalID, userID)
c.JSON(http.StatusOK, gin.H{"message": "Goal deleted successfully"})
}
+
+// GetGoalProgressDetails retrieves a goal with detailed progress information
+func (h *GoalHandler) GetGoalProgressDetails(c *gin.Context) {
+ userID := c.MustGet("userID").(uint)
+ goalID, err := strconv.ParseUint(c.Param("id"), 10, 32)
+ if err != nil {
+ log.Printf("Error parsing goal ID: %v", err)
+ c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid goal ID"})
+ return
+ }
+
+ progress, err := h.goalService.GetGoalProgress(userID, uint(goalID))
+ if err != nil {
+ log.Printf("Error fetching goal progress for ID %d, user %d: %v", goalID, userID, err)
+ c.JSON(http.StatusNotFound, gin.H{"error": "Goal not found"})
+ return
+ }
+
+ c.JSON(http.StatusOK, progress)
+}
+
+// GetAllGoalsProgressDetails retrieves all goals with enhanced progress details
+func (h *GoalHandler) GetAllGoalsProgressDetails(c *gin.Context) {
+ userID := c.MustGet("userID").(uint)
+
+ // Filter by status if provided
+ status := c.Query("status")
+
+ progress, err := h.goalService.GetAllGoalsProgress(userID, status)
+ if err != nil {
+ log.Printf("Error fetching all goals progress for user %d: %v", userID, err)
+ c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to get goal progress"})
+ return
+ }
+
+ c.JSON(http.StatusOK, progress)
+}
+
+// LinkTransactionToGoal links a transaction to a specific goal
+func (h *GoalHandler) LinkTransactionToGoal(c *gin.Context) {
+ userID := c.MustGet("userID").(uint)
+ goalID, err := strconv.ParseUint(c.Param("id"), 10, 32)
+ if err != nil {
+ log.Printf("Error parsing goal ID: %v", err)
+ c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid goal ID"})
+ return
+ }
+
+ var input LinkTransactionInput
+ if err := c.ShouldBindJSON(&input); err != nil {
+ log.Printf("Error binding JSON for linking transaction: %v", err)
+ c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ return
+ }
+
+ // Verify the goal belongs to the user
+ var goal models.Goal
+ if err := database.DB.Where("id = ? AND user_id = ?", goalID, userID).First(&goal).Error; err != nil {
+ log.Printf("Error fetching goal ID %d for user %d: %v", goalID, userID, err)
+ c.JSON(http.StatusNotFound, gin.H{"error": "Goal not found"})
+ return
+ }
+
+ // Verify the transaction belongs to the user
+ var transaction models.Transaction
+ if err := database.DB.Where("id = ? AND user_id = ?", input.TransactionID, userID).First(&transaction).Error; err != nil {
+ log.Printf("Error fetching transaction ID %d for user %d: %v", input.TransactionID, userID, err)
+ c.JSON(http.StatusNotFound, gin.H{"error": "Transaction not found"})
+ return
+ }
+
+ // Link the transaction to the goal
+ if err := h.goalService.LinkTransactionToGoal(input.TransactionID, uint(goalID)); err != nil {
+ log.Printf("Error linking transaction %d to goal %d: %v", input.TransactionID, goalID, err)
+ c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to link transaction to goal"})
+ return
+ }
+
+ log.Printf("Transaction ID %d successfully linked to goal ID %d for user %d", input.TransactionID, goalID, userID)
+ c.JSON(http.StatusOK, gin.H{"message": "Transaction linked to goal successfully"})
+}
+
+// RecalculateGoalProgress recalculates a goal's progress based on linked transactions
+func (h *GoalHandler) RecalculateGoalProgress(c *gin.Context) {
+ userID := c.MustGet("userID").(uint)
+ goalID, err := strconv.ParseUint(c.Param("id"), 10, 32)
+ if err != nil {
+ log.Printf("Error parsing goal ID: %v", err)
+ c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid goal ID"})
+ return
+ }
+
+ // Verify the goal belongs to the user
+ var goal models.Goal
+ if err := database.DB.Where("id = ? AND user_id = ?", goalID, userID).First(&goal).Error; err != nil {
+ log.Printf("Error fetching goal ID %d for user %d: %v", goalID, userID, err)
+ c.JSON(http.StatusNotFound, gin.H{"error": "Goal not found"})
+ return
+ }
+
+ // Recalculate the goal progress
+ if err := h.goalService.UpdateGoalFromTransactions(uint(goalID)); err != nil {
+ log.Printf("Error recalculating goal progress for ID %d: %v", goalID, err)
+ c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to recalculate goal progress"})
+ return
+ }
+
+ // Fetch the updated goal to return in response
+ if err := database.DB.First(&goal, goalID).Error; err != nil {
+ log.Printf("Error fetching updated goal after recalculation: %v", err)
+ c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to fetch updated goal"})
+ return
+ }
+
+ log.Printf("Goal ID %d progress recalculated successfully for user %d", goalID, userID)
+ c.JSON(http.StatusOK, goal)
+}
diff --git a/backend/internal/api/handlers/loan_handler.go b/backend/internal/api/handlers/loan_handler.go
index 3edb559..a80c4b7 100644
--- a/backend/internal/api/handlers/loan_handler.go
+++ b/backend/internal/api/handlers/loan_handler.go
@@ -10,6 +10,7 @@ import (
"finance/backend/internal/models"
"github.com/gin-gonic/gin"
+ "gorm.io/gorm"
)
// LoanHandler handles loan-related operations
@@ -237,3 +238,314 @@ func (h *LoanHandler) DeleteLoan(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"message": "Loan deleted successfully"})
}
+
+// CreateLoanPayment creates a new payment for a loan
+func (h *LoanHandler) CreateLoanPayment(c *gin.Context) {
+ // Get user from context (set by auth middleware)
+ user, exists := c.Get("user")
+ if !exists {
+ c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
+ return
+ }
+ userObj := user.(models.User)
+
+ // Get loan ID from URL parameter
+ loanID, err := strconv.ParseUint(c.Param("id"), 10, 32)
+ if err != nil {
+ c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid loan ID format"})
+ return
+ }
+
+ // Check if the loan exists and belongs to the user
+ var loan models.Loan
+ if err := database.DB.Where("id = ? AND user_id = ?", loanID, userObj.ID).First(&loan).Error; err != nil {
+ if err == gorm.ErrRecordNotFound {
+ c.JSON(http.StatusNotFound, gin.H{"error": "Loan not found"})
+ } else {
+ c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to fetch loan"})
+ }
+ return
+ }
+
+ // Define a struct to bind the request JSON
+ var input struct {
+ Amount int64 `json:"amount" binding:"required"`
+ PaymentDate string `json:"paymentDate" binding:"required"`
+ Principal int64 `json:"principal"`
+ Interest int64 `json:"interest"`
+ TransactionID *uint `json:"transactionId"`
+ Notes string `json:"notes"`
+ }
+
+ // Bind JSON to struct
+ if err := c.ShouldBindJSON(&input); err != nil {
+ c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ return
+ }
+
+ // Parse date
+ paymentDate, err := time.Parse("2006-01-02", input.PaymentDate)
+ if err != nil {
+ c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid payment date format"})
+ return
+ }
+
+ // Create payment object
+ payment := models.LoanPayment{
+ UserID: userObj.ID,
+ LoanID: uint(loanID),
+ Amount: input.Amount,
+ PaymentDate: paymentDate,
+ Principal: input.Principal,
+ Interest: input.Interest,
+ TransactionID: input.TransactionID,
+ Notes: input.Notes,
+ }
+
+ // Save to database in a transaction
+ tx := database.DB.Begin()
+ if err := tx.Create(&payment).Error; err != nil {
+ tx.Rollback()
+ c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create payment"})
+ return
+ }
+
+ // Update loan balance
+ loan.CurrentBalance -= input.Principal
+ if err := tx.Save(&loan).Error; err != nil {
+ tx.Rollback()
+ c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to update loan balance"})
+ return
+ }
+
+ tx.Commit()
+ c.JSON(http.StatusCreated, gin.H{"payment": payment, "updatedLoanBalance": loan.CurrentBalance})
+}
+
+// GetLoanPayments returns all payments for a specific loan
+func (h *LoanHandler) GetLoanPayments(c *gin.Context) {
+ // Get user from context (set by auth middleware)
+ user, exists := c.Get("user")
+ if !exists {
+ c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
+ return
+ }
+ userObj := user.(models.User)
+
+ // Get loan ID from URL parameter
+ loanID, err := strconv.ParseUint(c.Param("id"), 10, 32)
+ if err != nil {
+ c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid loan ID format"})
+ return
+ }
+
+ // Check if the loan exists and belongs to the user
+ var loan models.Loan
+ if err := database.DB.Where("id = ? AND user_id = ?", loanID, userObj.ID).First(&loan).Error; err != nil {
+ if err == gorm.ErrRecordNotFound {
+ c.JSON(http.StatusNotFound, gin.H{"error": "Loan not found"})
+ } else {
+ c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to fetch loan"})
+ }
+ return
+ }
+
+ // Fetch all payments for the loan
+ var payments []models.LoanPayment
+ if err := database.DB.Where("loan_id = ?", loanID).Order("payment_date DESC").Find(&payments).Error; err != nil {
+ c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to fetch loan payments"})
+ return
+ }
+
+ c.JSON(http.StatusOK, gin.H{"payments": payments})
+}
+
+// DeleteLoanPayment deletes a payment for a loan
+func (h *LoanHandler) DeleteLoanPayment(c *gin.Context) {
+ // Get user from context (set by auth middleware)
+ user, exists := c.Get("user")
+ if !exists {
+ c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
+ return
+ }
+ userObj := user.(models.User)
+
+ // Get payment ID from URL parameter
+ paymentID, err := strconv.ParseUint(c.Param("paymentId"), 10, 32)
+ if err != nil {
+ c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid payment ID format"})
+ return
+ }
+
+ // Check if the payment exists and belongs to the user
+ var payment models.LoanPayment
+ if err := database.DB.Where("id = ? AND user_id = ?", paymentID, userObj.ID).First(&payment).Error; err != nil {
+ if err == gorm.ErrRecordNotFound {
+ c.JSON(http.StatusNotFound, gin.H{"error": "Payment not found"})
+ } else {
+ c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to fetch payment"})
+ }
+ return
+ }
+
+ // Get the loan to update its balance
+ var loan models.Loan
+ if err := database.DB.First(&loan, payment.LoanID).Error; err != nil {
+ c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to fetch related loan"})
+ return
+ }
+
+ // Update loan and delete payment in a transaction
+ tx := database.DB.Begin()
+
+ // Reverse the principal payment (add it back to the loan balance)
+ loan.CurrentBalance += payment.Principal
+ if err := tx.Save(&loan).Error; err != nil {
+ tx.Rollback()
+ c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to update loan balance"})
+ return
+ }
+
+ // Delete the payment
+ if err := tx.Delete(&payment).Error; err != nil {
+ tx.Rollback()
+ c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to delete payment"})
+ return
+ }
+
+ tx.Commit()
+ c.JSON(http.StatusOK, gin.H{"message": "Payment deleted successfully", "updatedLoanBalance": loan.CurrentBalance})
+}
+
+// GetLoanPaymentSchedule generates an estimated payment schedule for a loan
+func (h *LoanHandler) GetLoanPaymentSchedule(c *gin.Context) {
+ // Get user from context (set by auth middleware)
+ user, exists := c.Get("user")
+ if !exists {
+ c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
+ return
+ }
+ userObj := user.(models.User)
+
+ // Get loan ID from URL parameter
+ loanID, err := strconv.ParseUint(c.Param("id"), 10, 32)
+ if err != nil {
+ c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid loan ID format"})
+ return
+ }
+
+ // Check if the loan exists and belongs to the user
+ var loan models.Loan
+ if err := database.DB.Where("id = ? AND user_id = ?", loanID, userObj.ID).First(&loan).Error; err != nil {
+ if err == gorm.ErrRecordNotFound {
+ c.JSON(http.StatusNotFound, gin.H{"error": "Loan not found"})
+ } else {
+ c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to fetch loan"})
+ }
+ return
+ }
+
+ // Parse payment frequency parameter (defaults to monthly)
+ frequency := c.DefaultQuery("frequency", "monthly")
+ if frequency != "monthly" && frequency != "biweekly" && frequency != "weekly" {
+ c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid frequency. Allowed values: monthly, biweekly, weekly"})
+ return
+ }
+
+ // Calculate remaining months (approximately)
+ now := time.Now()
+ remainingMonths := int(loan.EndDate.Sub(now).Hours() / 24 / 30)
+ if remainingMonths <= 0 {
+ c.JSON(http.StatusBadRequest, gin.H{"error": "Loan end date is in the past"})
+ return
+ }
+
+ // Calculate number of payments based on frequency
+ paymentsCount := remainingMonths
+ var intervalDays int
+ if frequency == "weekly" {
+ paymentsCount = remainingMonths * 4 // ~4 weeks per month
+ intervalDays = 7
+ } else if frequency == "biweekly" {
+ paymentsCount = remainingMonths * 2 // ~2 bi-weeks per month
+ intervalDays = 14
+ } else {
+ // Monthly
+ intervalDays = 30
+ }
+
+ // Simple amortization calculation
+ rate := loan.InterestRate / 12 / 100 // Monthly interest rate
+ if frequency == "weekly" {
+ rate = loan.InterestRate / 52 / 100
+ } else if frequency == "biweekly" {
+ rate = loan.InterestRate / 26 / 100
+ }
+
+ // For zero interest loans
+ var paymentAmount int64
+ if loan.InterestRate <= 0 {
+ paymentAmount = loan.CurrentBalance / int64(paymentsCount)
+ } else {
+ // Formula: PMT = P * (r * (1+r)^n) / ((1+r)^n - 1)
+ // Where PMT = payment, P = principal, r = rate per period, n = number of periods
+
+ // Simplified calculation (not exact but good approximation)
+ totalWithInterest := float64(loan.CurrentBalance) * (1 + float64(paymentsCount)*rate)
+ paymentAmount = int64(totalWithInterest) / int64(paymentsCount)
+ }
+
+ // Generate payment schedule
+ var schedule []map[string]interface{}
+ balance := loan.CurrentBalance
+ currentDate := now
+
+ for i := 0; i < paymentsCount && balance > 0; i++ {
+ // Calculate interest for this period
+ interestPayment := int64(float64(balance) * rate)
+ principalPayment := paymentAmount - interestPayment
+
+ // Adjust last payment if needed
+ if principalPayment > balance {
+ principalPayment = balance
+ paymentAmount = principalPayment + interestPayment
+ }
+
+ // Update remaining balance
+ balance -= principalPayment
+
+ // Create payment entry
+ payment := map[string]interface{}{
+ "paymentNumber": i + 1,
+ "date": currentDate.Format("2006-01-02"),
+ "totalPayment": paymentAmount,
+ "principalPayment": principalPayment,
+ "interestPayment": interestPayment,
+ "remainingBalance": balance,
+ }
+ schedule = append(schedule, payment)
+
+ // Increment date based on interval
+ currentDate = currentDate.AddDate(0, 0, intervalDays)
+ }
+
+ c.JSON(http.StatusOK, gin.H{
+ "loanDetails": loan,
+ "schedule": schedule,
+ "summary": map[string]interface{}{
+ "totalPayments": len(schedule),
+ "frequency": frequency,
+ "estimatedPayoffDate": schedule[len(schedule)-1]["date"],
+ "totalInterestPaid": sumInterest(schedule),
+ },
+ })
+}
+
+// Helper function to sum up total interest in a payment schedule
+func sumInterest(schedule []map[string]interface{}) int64 {
+ var total int64
+ for _, payment := range schedule {
+ total += payment["interestPayment"].(int64)
+ }
+ return total
+}
diff --git a/backend/internal/api/v1/goals/goals.go b/backend/internal/api/v1/goals/goals.go
index 1d2cd6f..4f99468 100644
--- a/backend/internal/api/v1/goals/goals.go
+++ b/backend/internal/api/v1/goals/goals.go
@@ -1,7 +1,7 @@
package goals
import (
- "finance/backend/handlers"
+ "finance/backend/internal/api/handlers"
"github.com/gin-gonic/gin"
)
@@ -41,3 +41,27 @@ func UpdateGoalProgress() gin.HandlerFunc {
handler := handlers.NewGoalHandler()
return handler.UpdateGoalProgress
}
+
+// GetGoalProgressDetails returns goal with enhanced progress tracking details
+func GetGoalProgressDetails() gin.HandlerFunc {
+ handler := handlers.NewGoalHandler()
+ return handler.GetGoalProgressDetails
+}
+
+// GetAllGoalsProgressDetails returns all goals with enhanced progress tracking details
+func GetAllGoalsProgressDetails() gin.HandlerFunc {
+ handler := handlers.NewGoalHandler()
+ return handler.GetAllGoalsProgressDetails
+}
+
+// LinkTransactionToGoal links a transaction to a goal for progress tracking
+func LinkTransactionToGoal() gin.HandlerFunc {
+ handler := handlers.NewGoalHandler()
+ return handler.LinkTransactionToGoal
+}
+
+// RecalculateGoalProgress recalculates the progress of a goal based on its transactions
+func RecalculateGoalProgress() gin.HandlerFunc {
+ handler := handlers.NewGoalHandler()
+ return handler.RecalculateGoalProgress
+}
diff --git a/backend/internal/api/v1/loans/loans.go b/backend/internal/api/v1/loans/loans.go
index 1366b3b..49ab320 100644
--- a/backend/internal/api/v1/loans/loans.go
+++ b/backend/internal/api/v1/loans/loans.go
@@ -5,6 +5,7 @@ import (
"strconv"
"time"
+ "finance/backend/internal/api/handlers"
"finance/backend/internal/database"
"finance/backend/internal/models"
@@ -246,3 +247,27 @@ func DeleteLoan() gin.HandlerFunc {
c.JSON(http.StatusOK, gin.H{"message": "Loan deleted successfully"})
}
}
+
+// GetLoanPayments returns all payments for a specific loan
+func GetLoanPayments() gin.HandlerFunc {
+ handler := handlers.NewLoanHandler()
+ return handler.GetLoanPayments
+}
+
+// CreateLoanPayment creates a new payment for a loan
+func CreateLoanPayment() gin.HandlerFunc {
+ handler := handlers.NewLoanHandler()
+ return handler.CreateLoanPayment
+}
+
+// DeleteLoanPayment deletes a loan payment
+func DeleteLoanPayment() gin.HandlerFunc {
+ handler := handlers.NewLoanHandler()
+ return handler.DeleteLoanPayment
+}
+
+// GetLoanPaymentSchedule generates an estimated payment schedule for a loan
+func GetLoanPaymentSchedule() gin.HandlerFunc {
+ handler := handlers.NewLoanHandler()
+ return handler.GetLoanPaymentSchedule
+}
diff --git a/backend/internal/core/goal_service.go b/backend/internal/core/goal_service.go
new file mode 100644
index 0000000..60cffd5
--- /dev/null
+++ b/backend/internal/core/goal_service.go
@@ -0,0 +1,196 @@
+package core
+
+import (
+ "finance/backend/internal/database"
+ "finance/backend/internal/models"
+ "fmt"
+ "log"
+ "time"
+
+ "gorm.io/gorm"
+)
+
+// GoalService handles business logic for financial goals
+type GoalService struct {
+ db *gorm.DB
+}
+
+// NewGoalService creates and returns a new GoalService
+func NewGoalService() *GoalService {
+ return &GoalService{
+ db: database.DB,
+ }
+}
+
+// GoalProgress represents calculated progress data for a goal
+type GoalProgress struct {
+ Goal models.Goal `json:"goal"`
+ PercentComplete float64 `json:"percentComplete"`
+ AmountRemaining int64 `json:"amountRemaining"`
+ DaysRemaining int `json:"daysRemaining,omitempty"`
+ RequiredPerDay int64 `json:"requiredPerDay,omitempty"`
+ RequiredPerMonth int64 `json:"requiredPerMonth,omitempty"`
+ OnTrack bool `json:"onTrack"`
+}
+
+// GetGoalProgress retrieves a single goal with enhanced progress tracking data
+func (s *GoalService) GetGoalProgress(userID uint, goalID uint) (*GoalProgress, error) {
+ var goal models.Goal
+ if err := s.db.Where("id = ? AND user_id = ?", goalID, userID).First(&goal).Error; err != nil {
+ return nil, err
+ }
+
+ // Calculate progress
+ return s.calculateGoalProgress(&goal)
+}
+
+// GetAllGoalsProgress retrieves all goals for a user with enhanced progress data
+func (s *GoalService) GetAllGoalsProgress(userID uint, status string) ([]*GoalProgress, error) {
+ var goals []models.Goal
+
+ query := s.db.Where("user_id = ?", userID)
+ if status != "" {
+ query = query.Where("status = ?", status)
+ }
+
+ if err := query.Find(&goals).Error; err != nil {
+ return nil, err
+ }
+
+ progress := make([]*GoalProgress, 0, len(goals))
+ for i := range goals {
+ goalProgress, err := s.calculateGoalProgress(&goals[i])
+ if err != nil {
+ log.Printf("Error calculating progress for goal %d: %v", goals[i].ID, err)
+ continue
+ }
+ progress = append(progress, goalProgress)
+ }
+
+ return progress, nil
+}
+
+// calculateGoalProgress computes additional progress metrics for a goal
+func (s *GoalService) calculateGoalProgress(goal *models.Goal) (*GoalProgress, error) {
+ progress := &GoalProgress{
+ Goal: *goal,
+ AmountRemaining: goal.TargetAmount - goal.CurrentAmount,
+ }
+
+ // Calculate percentage complete (avoid division by zero)
+ if goal.TargetAmount > 0 {
+ progress.PercentComplete = float64(goal.CurrentAmount) / float64(goal.TargetAmount) * 100
+ }
+
+ // Calculate time-based metrics if a target date exists
+ if !goal.TargetDate.IsZero() {
+ now := time.Now()
+
+ // Only calculate days remaining if target date is in the future
+ if goal.TargetDate.After(now) {
+ daysRemaining := int(goal.TargetDate.Sub(now).Hours() / 24)
+ progress.DaysRemaining = daysRemaining
+
+ // Calculate required savings per day/month
+ if progress.AmountRemaining > 0 && daysRemaining > 0 {
+ progress.RequiredPerDay = progress.AmountRemaining / int64(daysRemaining)
+ progress.RequiredPerMonth = progress.AmountRemaining / int64((daysRemaining+30-1)/30) // Ceiling division to months
+ }
+
+ // Calculate if on track based on time elapsed vs progress made
+ totalDuration := goal.TargetDate.Sub(goal.CreatedAt)
+ elapsedDuration := now.Sub(goal.CreatedAt)
+
+ if totalDuration > 0 {
+ expectedProgress := float64(elapsedDuration) / float64(totalDuration)
+ actualProgress := float64(goal.CurrentAmount) / float64(goal.TargetAmount)
+
+ // Consider on track if actual progress is at least 90% of expected progress
+ progress.OnTrack = actualProgress >= (expectedProgress * 0.9)
+ }
+ } else {
+ // Target date passed
+ progress.DaysRemaining = 0
+ progress.OnTrack = goal.CurrentAmount >= goal.TargetAmount
+ }
+ } else {
+ // No target date, so consider on track if any progress is made
+ progress.OnTrack = goal.CurrentAmount > 0
+ }
+
+ return progress, nil
+}
+
+// UpdateGoalFromTransactions updates goal progress based on recent transactions
+// This can be run periodically or when triggered by transaction changes
+func (s *GoalService) UpdateGoalFromTransactions(goalID uint) error {
+ var goal models.Goal
+ if err := s.db.First(&goal, goalID).Error; err != nil {
+ return err
+ }
+
+ // Get all related savings transactions for this goal
+ // This assumes a category field in transactions that indicates
+ // they are related to this goal (format: "Goal:<goalID>")
+ var transactions []models.Transaction
+ if err := s.db.Where("user_id = ? AND category = ?",
+ goal.UserID, fmt.Sprintf("Goal:%d", goalID)).Find(&transactions).Error; err != nil {
+ return err
+ }
+
+ // Calculate sum of all savings transactions
+ var totalSaved int64
+ for _, tx := range transactions {
+ if tx.Type == "Income" || tx.Type == "Savings" {
+ totalSaved += tx.Amount
+ } else if tx.Type == "Expense" {
+ totalSaved -= tx.Amount
+ }
+ }
+
+ // Update goal progress
+ goal.CurrentAmount = totalSaved
+
+ // Check if goal has been achieved
+ if goal.CurrentAmount >= goal.TargetAmount {
+ goal.Status = "Achieved"
+ }
+
+ return s.db.Save(&goal).Error
+}
+
+// LinkTransactionToGoal tags a transaction as contributing to a specific goal
+func (s *GoalService) LinkTransactionToGoal(txID uint, goalID uint) error {
+ var transaction models.Transaction
+ if err := s.db.First(&transaction, txID).Error; err != nil {
+ return err
+ }
+
+ // Set the category to indicate this transaction is for the goal
+ transaction.Category = fmt.Sprintf("Goal:%d", goalID)
+
+ // Save the updated transaction
+ if err := s.db.Save(&transaction).Error; err != nil {
+ return err
+ }
+
+ // Update the goal progress based on this and other transactions
+ return s.UpdateGoalFromTransactions(goalID)
+}
+
+// RecalculateAllGoals updates the progress of all active goals
+// This could be run daily as a background task
+func (s *GoalService) RecalculateAllGoals() error {
+ var goals []models.Goal
+ if err := s.db.Where("status = ?", "Active").Find(&goals).Error; err != nil {
+ return err
+ }
+
+ for _, goal := range goals {
+ if err := s.UpdateGoalFromTransactions(goal.ID); err != nil {
+ log.Printf("Error updating goal %d: %v", goal.ID, err)
+ }
+ }
+
+ return nil
+}
diff --git a/backend/internal/core/goal_service_test.go b/backend/internal/core/goal_service_test.go
new file mode 100644
index 0000000..2a4446a
--- /dev/null
+++ b/backend/internal/core/goal_service_test.go
@@ -0,0 +1,129 @@
+package core
+
+import (
+ "finance/backend/internal/models"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/assert"
+ "gorm.io/gorm"
+)
+
+// Mock goal for testing
+func createTestGoal() *models.Goal {
+ return &models.Goal{
+ Model: gorm.Model{ID: 1, CreatedAt: time.Now().Add(-30 * 24 * time.Hour)}, // created 30 days ago
+ UserID: 1,
+ Name: "Test Goal",
+ TargetAmount: 10000,
+ CurrentAmount: 3000,
+ Status: "Active",
+ TargetDate: time.Now().Add(60 * 24 * time.Hour), // due in 60 days
+ }
+}
+
+// TestCalculateGoalProgress tests the goal progress calculation logic
+func TestCalculateGoalProgress(t *testing.T) {
+ // Create a test service
+ service := &GoalService{}
+
+ // Test with a goal that's on track
+ goal := createTestGoal()
+ progress, err := service.calculateGoalProgress(goal)
+
+ assert.NoError(t, err)
+ assert.NotNil(t, progress)
+
+ // Verify calculations
+ assert.Equal(t, int64(7000), progress.AmountRemaining)
+ assert.InDelta(t, 30.0, progress.PercentComplete, 0.1)
+
+ // Should have around 60 days remaining (might vary slightly based on test execution time)
+ assert.True(t, progress.DaysRemaining > 55 && progress.DaysRemaining <= 61)
+
+ // Test required amounts
+ assert.True(t, progress.RequiredPerDay > 0)
+ assert.True(t, progress.RequiredPerMonth > 0)
+
+ // Verify on track status - goal is at 30% completion, we're 1/3 through the time period
+ // so it should be on track
+ assert.True(t, progress.OnTrack)
+
+ // Test with a goal that's behind
+ goal.CurrentAmount = 1000 // only 10% complete after 1/3 of the time
+ progress, err = service.calculateGoalProgress(goal)
+
+ assert.NoError(t, err)
+ assert.NotNil(t, progress)
+ assert.False(t, progress.OnTrack)
+
+ // Test with a goal that has no target date
+ goal = createTestGoal()
+ goal.TargetDate = time.Time{} // zero time
+ progress, err = service.calculateGoalProgress(goal)
+
+ assert.NoError(t, err)
+ assert.NotNil(t, progress)
+ assert.True(t, progress.OnTrack) // should be on track if any progress made
+ assert.Equal(t, 0, progress.DaysRemaining)
+
+ // Test with a goal whose target date has passed
+ goal = createTestGoal()
+ goal.TargetDate = time.Now().Add(-10 * 24 * time.Hour) // 10 days ago
+ progress, err = service.calculateGoalProgress(goal)
+
+ assert.NoError(t, err)
+ assert.NotNil(t, progress)
+ assert.Equal(t, 0, progress.DaysRemaining)
+
+ // Not on track if target amount not reached
+ assert.False(t, progress.OnTrack)
+
+ // But should be on track if target amount reached despite date passed
+ goal.CurrentAmount = goal.TargetAmount
+ progress, err = service.calculateGoalProgress(goal)
+
+ assert.NoError(t, err)
+ assert.True(t, progress.OnTrack)
+}
+
+// TestUpdateGoalFromTransactions tests updating a goal based on transactions
+func TestUpdateGoalFromTransactions(t *testing.T) {
+ // This test would need a mock database to be fully implemented
+ // Here's a placeholder for when DB mocking is available
+
+ /*
+ // Setup a mock DB
+ db, mock := setupMockDB(t)
+ service := &GoalService{db: db}
+
+ // Setup expectations
+ goalID := uint(1)
+ userID := uint(1)
+
+ // Expect a query to fetch the goal
+ mock.ExpectQuery(`SELECT * FROM "goals" WHERE "id" = ?`).
+ WithArgs(goalID).
+ WillReturnRows(sqlmock.NewRows([]string{"id", "user_id", "name", "target_amount", "current_amount", "status"}).
+ AddRow(goalID, userID, "Test Goal", 10000, 0, "Active"))
+
+ // Expect a query to fetch transactions
+ mock.ExpectQuery(`SELECT * FROM "transactions" WHERE "user_id" = ? AND "category" = ?`).
+ WithArgs(userID, "Goal:1").
+ WillReturnRows(sqlmock.NewRows([]string{"id", "user_id", "amount", "type", "category"}).
+ AddRow(1, userID, 500, "Income", "Goal:1").
+ AddRow(2, userID, 300, "Income", "Goal:1").
+ AddRow(3, userID, 200, "Expense", "Goal:1"))
+
+ // Expect an update to the goal
+ mock.ExpectBegin()
+ mock.ExpectExec(`UPDATE "goals" SET`).
+ WithArgs(600, "Active", goalID). // 500 + 300 - 200 = 600
+ WillReturnResult(sqlmock.NewResult(1, 1))
+ mock.ExpectCommit()
+
+ // Run the test
+ err := service.UpdateGoalFromTransactions(goalID)
+ assert.NoError(t, err)
+ */
+}
diff --git a/backend/internal/database/database.go b/backend/internal/database/database.go
index 15228e2..ca81e01 100644
--- a/backend/internal/database/database.go
+++ b/backend/internal/database/database.go
@@ -50,6 +50,7 @@ func InitDatabase(cfg *config.Config) error {
&models.Transaction{},
&models.Loan{},
&models.Goal{},
+ &models.LoanPayment{},
)
if err != nil {
log.Printf("Failed to run migrations: %v\n", err)
diff --git a/backend/internal/models/models.go b/backend/internal/models/models.go
index c984012..3d409a6 100644
--- a/backend/internal/models/models.go
+++ b/backend/internal/models/models.go
@@ -94,4 +94,20 @@ type Goal struct {
// RelatedLoanID *uint
}
-// Add other models below (Goal)
+// LoanPayment tracks payments made towards a loan
+type LoanPayment struct {
+ gorm.Model
+ UserID uint `gorm:"not null;index"` // Foreign key to User
+ User User // Belongs To relationship
+ LoanID uint `gorm:"not null;index"` // Foreign key to Loan
+ Loan Loan // Belongs To relationship
+ Amount int64 `gorm:"not null"` // In smallest currency unit
+ PaymentDate time.Time `gorm:"not null;index"` // Date payment was made
+ TransactionID *uint `gorm:"index"` // Optional link to transaction
+ Transaction *Transaction // Belongs To relationship
+ Principal int64 // Portion of payment going to principal
+ Interest int64 // Portion of payment going to interest
+ Notes string // Any payment notes
+}
+
+// Add other models below
diff --git a/backend/internal/router/router.go b/backend/internal/router/router.go
index 3a4d413..42753b4 100644
--- a/backend/internal/router/router.go
+++ b/backend/internal/router/router.go
@@ -110,12 +110,24 @@ func SetupRouter(cfg *config.Config) *gin.Engine {
protected.DELETE("/goals/:id", goalHandler.DeleteGoal)
protected.PATCH("/goals/:id/progress", goalHandler.UpdateGoalProgress)
+ // New Goal Progress Tracking routes
+ protected.GET("/goals/:id/progress", goalHandler.GetGoalProgressDetails)
+ protected.GET("/goals/progress/all", goalHandler.GetAllGoalsProgressDetails)
+ protected.POST("/goals/:id/link-transaction", goalHandler.LinkTransactionToGoal)
+ protected.POST("/goals/:id/recalculate", goalHandler.RecalculateGoalProgress)
+
// Loan routes
protected.GET("/loans", loanHandler.GetLoans)
protected.GET("/loans/:id", loanHandler.GetLoanByID)
protected.POST("/loans", loanHandler.CreateLoan)
protected.PUT("/loans/:id", loanHandler.UpdateLoan)
protected.DELETE("/loans/:id", loanHandler.DeleteLoan)
+
+ // Loan payment routes
+ protected.GET("/loans/:id/payments", loanHandler.GetLoanPayments)
+ protected.POST("/loans/:id/payments", loanHandler.CreateLoanPayment)
+ protected.DELETE("/loans/:id/payments/:paymentId", loanHandler.DeleteLoanPayment)
+ protected.GET("/loans/:id/payment-schedule", loanHandler.GetLoanPaymentSchedule)
}
}
diff --git a/frontend/package-lock.json b/frontend/package-lock.json
index 5eaa75f..32406b1 100644
--- a/frontend/package-lock.json
+++ b/frontend/package-lock.json
@@ -11,14 +11,21 @@
"@hookform/resolvers": "^5.0.1",
"@radix-ui/react-dialog": "^1.1.11",
"@radix-ui/react-label": "^2.1.4",
+ "@radix-ui/react-popover": "^1.1.11",
+ "@radix-ui/react-progress": "^1.1.4",
+ "@radix-ui/react-select": "^2.2.2",
"@radix-ui/react-slot": "^1.2.0",
+ "@radix-ui/react-toast": "^1.2.11",
"@tanstack/react-query": "^5.74.4",
+ "axios": "^1.9.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
+ "date-fns": "^3.6.0",
"framer-motion": "^11.18.2",
"lucide-react": "^0.503.0",
"next": "15.3.1",
"react": "^19.0.0",
+ "react-day-picker": "^8.10.1",
"react-dom": "^19.0.0",
"react-hook-form": "^7.56.1",
"tailwind-merge": "^3.2.0",
@@ -208,6 +215,40 @@
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
}
},
+ "node_modules/@floating-ui/core": {
+ "version": "1.6.9",
+ "resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.6.9.tgz",
+ "integrity": "sha512-uMXCuQ3BItDUbAMhIXw7UPXRfAlOAvZzdK9BWpE60MCn+Svt3aLn9jsPTi/WNGlRUu2uI0v5S7JiIUsbsvh3fw==",
+ "dependencies": {
+ "@floating-ui/utils": "^0.2.9"
+ }
+ },
+ "node_modules/@floating-ui/dom": {
+ "version": "1.6.13",
+ "resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.6.13.tgz",
+ "integrity": "sha512-umqzocjDgNRGTuO7Q8CU32dkHkECqI8ZdMZ5Swb6QAM0t5rnlrN3lGo1hdpscRd3WS8T6DKYK4ephgIH9iRh3w==",
+ "dependencies": {
+ "@floating-ui/core": "^1.6.0",
+ "@floating-ui/utils": "^0.2.9"
+ }
+ },
+ "node_modules/@floating-ui/react-dom": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/@floating-ui/react-dom/-/react-dom-2.1.2.tgz",
+ "integrity": "sha512-06okr5cgPzMNBy+Ycse2A6udMi4bqwW/zgBF/rwjcNqWkyr82Mcg8b0vjX8OJpZFy/FKjJmw6wV7t44kK6kW7A==",
+ "dependencies": {
+ "@floating-ui/dom": "^1.0.0"
+ },
+ "peerDependencies": {
+ "react": ">=16.8.0",
+ "react-dom": ">=16.8.0"
+ }
+ },
+ "node_modules/@floating-ui/utils": {
+ "version": "0.2.9",
+ "resolved": "https://registry.npmjs.org/@floating-ui/utils/-/utils-0.2.9.tgz",
+ "integrity": "sha512-MDWhGtE+eHw5JW7lq4qhc5yRLS11ERl1c7Z6Xd0a58DozHES6EnNNwUWbMiG4J9Cgj053Bhk8zvlhFYKVhULwg=="
+ },
"node_modules/@hookform/resolvers": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/@hookform/resolvers/-/resolvers-5.0.1.tgz",
@@ -827,11 +868,63 @@
"node": ">=12.4.0"
}
},
+ "node_modules/@radix-ui/number": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/@radix-ui/number/-/number-1.1.1.tgz",
+ "integrity": "sha512-MkKCwxlXTgz6CFoJx3pCwn07GKp36+aZyu/u2Ln2VrA5DcdyCZkASEDBTd8x5whTQQL5CiYf4prXKLcgQdv29g=="
+ },
"node_modules/@radix-ui/primitive": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.1.2.tgz",
"integrity": "sha512-XnbHrrprsNqZKQhStrSwgRUQzoCI1glLzdw79xiZPoofhGICeZRSQ3dIxAKH1gb3OHfNf4d6f+vAv3kil2eggA=="
},
+ "node_modules/@radix-ui/react-arrow": {
+ "version": "1.1.4",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-arrow/-/react-arrow-1.1.4.tgz",
+ "integrity": "sha512-qz+fxrqgNxG0dYew5l7qR3c7wdgRu1XVUHGnGYX7rg5HM4p9SWaRmJwfgR3J0SgyUKayLmzQIun+N6rWRgiRKw==",
+ "dependencies": {
+ "@radix-ui/react-primitive": "2.1.0"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "@types/react-dom": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "@types/react-dom": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@radix-ui/react-collection": {
+ "version": "1.1.4",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-collection/-/react-collection-1.1.4.tgz",
+ "integrity": "sha512-cv4vSf7HttqXilDnAnvINd53OTl1/bjUYVZrkFnA7nwmY9Ob2POUy0WY0sfqBAe1s5FyKsyceQlqiEGPYNTadg==",
+ "dependencies": {
+ "@radix-ui/react-compose-refs": "1.1.2",
+ "@radix-ui/react-context": "1.1.2",
+ "@radix-ui/react-primitive": "2.1.0",
+ "@radix-ui/react-slot": "1.2.0"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "@types/react-dom": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "@types/react-dom": {
+ "optional": true
+ }
+ }
+ },
"node_modules/@radix-ui/react-compose-refs": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.2.tgz",
@@ -895,6 +988,20 @@
}
}
},
+ "node_modules/@radix-ui/react-direction": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-direction/-/react-direction-1.1.1.tgz",
+ "integrity": "sha512-1UEWRX6jnOA2y4H5WczZ44gOOjTEmlqv1uNW4GAJEO5+bauCBhv8snY65Iw5/VOS/ghKN9gr2KjnLKxrsvoMVw==",
+ "peerDependencies": {
+ "@types/react": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ }
+ }
+ },
"node_modules/@radix-ui/react-dismissable-layer": {
"version": "1.1.7",
"resolved": "https://registry.npmjs.org/@radix-ui/react-dismissable-layer/-/react-dismissable-layer-1.1.7.tgz",
@@ -998,6 +1105,73 @@
}
}
},
+ "node_modules/@radix-ui/react-popover": {
+ "version": "1.1.11",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-popover/-/react-popover-1.1.11.tgz",
+ "integrity": "sha512-yFMfZkVA5G3GJnBgb2PxrrcLKm1ZLWXrbYVgdyTl//0TYEIHS9LJbnyz7WWcZ0qCq7hIlJZpRtxeSeIG5T5oJw==",
+ "dependencies": {
+ "@radix-ui/primitive": "1.1.2",
+ "@radix-ui/react-compose-refs": "1.1.2",
+ "@radix-ui/react-context": "1.1.2",
+ "@radix-ui/react-dismissable-layer": "1.1.7",
+ "@radix-ui/react-focus-guards": "1.1.2",
+ "@radix-ui/react-focus-scope": "1.1.4",
+ "@radix-ui/react-id": "1.1.1",
+ "@radix-ui/react-popper": "1.2.4",
+ "@radix-ui/react-portal": "1.1.6",
+ "@radix-ui/react-presence": "1.1.4",
+ "@radix-ui/react-primitive": "2.1.0",
+ "@radix-ui/react-slot": "1.2.0",
+ "@radix-ui/react-use-controllable-state": "1.2.2",
+ "aria-hidden": "^1.2.4",
+ "react-remove-scroll": "^2.6.3"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "@types/react-dom": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "@types/react-dom": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@radix-ui/react-popper": {
+ "version": "1.2.4",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-popper/-/react-popper-1.2.4.tgz",
+ "integrity": "sha512-3p2Rgm/a1cK0r/UVkx5F/K9v/EplfjAeIFCGOPYPO4lZ0jtg4iSQXt/YGTSLWaf4x7NG6Z4+uKFcylcTZjeqDA==",
+ "dependencies": {
+ "@floating-ui/react-dom": "^2.0.0",
+ "@radix-ui/react-arrow": "1.1.4",
+ "@radix-ui/react-compose-refs": "1.1.2",
+ "@radix-ui/react-context": "1.1.2",
+ "@radix-ui/react-primitive": "2.1.0",
+ "@radix-ui/react-use-callback-ref": "1.1.1",
+ "@radix-ui/react-use-layout-effect": "1.1.1",
+ "@radix-ui/react-use-rect": "1.1.1",
+ "@radix-ui/react-use-size": "1.1.1",
+ "@radix-ui/rect": "1.1.1"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "@types/react-dom": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "@types/react-dom": {
+ "optional": true
+ }
+ }
+ },
"node_modules/@radix-ui/react-portal": {
"version": "1.1.6",
"resolved": "https://registry.npmjs.org/@radix-ui/react-portal/-/react-portal-1.1.6.tgz",
@@ -1066,6 +1240,71 @@
}
}
},
+ "node_modules/@radix-ui/react-progress": {
+ "version": "1.1.4",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-progress/-/react-progress-1.1.4.tgz",
+ "integrity": "sha512-8rl9w7lJdcVPor47Dhws9mUHRHLE+8JEgyJRdNWCpGPa6HIlr3eh+Yn9gyx1CnCLbw5naHsI2gaO9dBWO50vzw==",
+ "dependencies": {
+ "@radix-ui/react-context": "1.1.2",
+ "@radix-ui/react-primitive": "2.1.0"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "@types/react-dom": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "@types/react-dom": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@radix-ui/react-select": {
+ "version": "2.2.2",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-select/-/react-select-2.2.2.tgz",
+ "integrity": "sha512-HjkVHtBkuq+r3zUAZ/CvNWUGKPfuicGDbgtZgiQuFmNcV5F+Tgy24ep2nsAW2nFgvhGPJVqeBZa6KyVN0EyrBA==",
+ "dependencies": {
+ "@radix-ui/number": "1.1.1",
+ "@radix-ui/primitive": "1.1.2",
+ "@radix-ui/react-collection": "1.1.4",
+ "@radix-ui/react-compose-refs": "1.1.2",
+ "@radix-ui/react-context": "1.1.2",
+ "@radix-ui/react-direction": "1.1.1",
+ "@radix-ui/react-dismissable-layer": "1.1.7",
+ "@radix-ui/react-focus-guards": "1.1.2",
+ "@radix-ui/react-focus-scope": "1.1.4",
+ "@radix-ui/react-id": "1.1.1",
+ "@radix-ui/react-popper": "1.2.4",
+ "@radix-ui/react-portal": "1.1.6",
+ "@radix-ui/react-primitive": "2.1.0",
+ "@radix-ui/react-slot": "1.2.0",
+ "@radix-ui/react-use-callback-ref": "1.1.1",
+ "@radix-ui/react-use-controllable-state": "1.2.2",
+ "@radix-ui/react-use-layout-effect": "1.1.1",
+ "@radix-ui/react-use-previous": "1.1.1",
+ "@radix-ui/react-visually-hidden": "1.2.0",
+ "aria-hidden": "^1.2.4",
+ "react-remove-scroll": "^2.6.3"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "@types/react-dom": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "@types/react-dom": {
+ "optional": true
+ }
+ }
+ },
"node_modules/@radix-ui/react-slot": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.2.0.tgz",
@@ -1083,6 +1322,39 @@
}
}
},
+ "node_modules/@radix-ui/react-toast": {
+ "version": "1.2.11",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-toast/-/react-toast-1.2.11.tgz",
+ "integrity": "sha512-Ed2mlOmT+tktOsu2NZBK1bCSHh/uqULu1vWOkpQTVq53EoOuZUZw7FInQoDB3uil5wZc2oe0XN9a7uVZB7/6AQ==",
+ "dependencies": {
+ "@radix-ui/primitive": "1.1.2",
+ "@radix-ui/react-collection": "1.1.4",
+ "@radix-ui/react-compose-refs": "1.1.2",
+ "@radix-ui/react-context": "1.1.2",
+ "@radix-ui/react-dismissable-layer": "1.1.7",
+ "@radix-ui/react-portal": "1.1.6",
+ "@radix-ui/react-presence": "1.1.4",
+ "@radix-ui/react-primitive": "2.1.0",
+ "@radix-ui/react-use-callback-ref": "1.1.1",
+ "@radix-ui/react-use-controllable-state": "1.2.2",
+ "@radix-ui/react-use-layout-effect": "1.1.1",
+ "@radix-ui/react-visually-hidden": "1.2.0"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "@types/react-dom": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "@types/react-dom": {
+ "optional": true
+ }
+ }
+ },
"node_modules/@radix-ui/react-use-callback-ref": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/@radix-ui/react-use-callback-ref/-/react-use-callback-ref-1.1.1.tgz",
@@ -1163,6 +1435,81 @@
}
}
},
+ "node_modules/@radix-ui/react-use-previous": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-use-previous/-/react-use-previous-1.1.1.tgz",
+ "integrity": "sha512-2dHfToCj/pzca2Ck724OZ5L0EVrr3eHRNsG/b3xQJLA2hZpVCS99bLAX+hm1IHXDEnzU6by5z/5MIY794/a8NQ==",
+ "peerDependencies": {
+ "@types/react": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@radix-ui/react-use-rect": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-use-rect/-/react-use-rect-1.1.1.tgz",
+ "integrity": "sha512-QTYuDesS0VtuHNNvMh+CjlKJ4LJickCMUAqjlE3+j8w+RlRpwyX3apEQKGFzbZGdo7XNG1tXa+bQqIE7HIXT2w==",
+ "dependencies": {
+ "@radix-ui/rect": "1.1.1"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@radix-ui/react-use-size": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-use-size/-/react-use-size-1.1.1.tgz",
+ "integrity": "sha512-ewrXRDTAqAXlkl6t/fkXWNAhFX9I+CkKlw6zjEwk86RSPKwZr3xpBRso655aqYafwtnbpHLj6toFzmd6xdVptQ==",
+ "dependencies": {
+ "@radix-ui/react-use-layout-effect": "1.1.1"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@radix-ui/react-visually-hidden": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-visually-hidden/-/react-visually-hidden-1.2.0.tgz",
+ "integrity": "sha512-rQj0aAWOpCdCMRbI6pLQm8r7S2BM3YhTa0SzOYD55k+hJA8oo9J+H+9wLM9oMlZWOX/wJWPTzfDfmZkf7LvCfg==",
+ "dependencies": {
+ "@radix-ui/react-primitive": "2.1.0"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "@types/react-dom": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "@types/react-dom": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@radix-ui/rect": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/@radix-ui/rect/-/rect-1.1.1.tgz",
+ "integrity": "sha512-HPwpGIzkl28mWyZqG52jiqDJ12waP11Pa1lGoiyUkIEuMLBP0oeK/C89esbXrxsky5we7dfd8U58nm0SgAWpVw=="
+ },
"node_modules/@rtsao/scc": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@rtsao/scc/-/scc-1.1.0.tgz",
@@ -1511,7 +1858,7 @@
"version": "19.1.2",
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.1.2.tgz",
"integrity": "sha512-oxLPMytKchWGbnQM9O7D67uPa9paTNxO7jVoNMXgkkErULBPhPARCfkKL9ytcIJJRGjbsVwW4ugJzyFFvm/Tiw==",
- "devOptional": true,
+ "dev": true,
"dependencies": {
"csstype": "^3.0.2"
}
@@ -1520,7 +1867,7 @@
"version": "19.1.2",
"resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.1.2.tgz",
"integrity": "sha512-XGJkWF41Qq305SKWEILa1O8vzhb3aOo3ogBlSmiqNko/WmRb6QIaweuZCXjKygVDXpzXb5wyxKTSOsmkuqj+Qw==",
- "devOptional": true,
+ "dev": true,
"peerDependencies": {
"@types/react": "^19.0.0"
}
@@ -2216,6 +2563,11 @@
"node": ">= 0.4"
}
},
+ "node_modules/asynckit": {
+ "version": "0.4.0",
+ "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
+ "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q=="
+ },
"node_modules/available-typed-arrays": {
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/available-typed-arrays/-/available-typed-arrays-1.0.7.tgz",
@@ -2240,6 +2592,16 @@
"node": ">=4"
}
},
+ "node_modules/axios": {
+ "version": "1.9.0",
+ "resolved": "https://registry.npmjs.org/axios/-/axios-1.9.0.tgz",
+ "integrity": "sha512-re4CqKTJaURpzbLHtIi6XpDv20/CnpXOtjRY5/CU32L8gU8ek9UIivcfvSWvmKEngmVbrUtPpdDwWDWL7DNHvg==",
+ "dependencies": {
+ "follow-redirects": "^1.15.6",
+ "form-data": "^4.0.0",
+ "proxy-from-env": "^1.1.0"
+ }
+ },
"node_modules/axobject-query": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-4.1.0.tgz",
@@ -2310,7 +2672,6 @@
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
"integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",
- "dev": true,
"dependencies": {
"es-errors": "^1.3.0",
"function-bind": "^1.1.2"
@@ -2444,6 +2805,17 @@
"simple-swizzle": "^0.2.2"
}
},
+ "node_modules/combined-stream": {
+ "version": "1.0.8",
+ "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
+ "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",
+ "dependencies": {
+ "delayed-stream": "~1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
"node_modules/concat-map": {
"version": "0.0.1",
"resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
@@ -2468,7 +2840,7 @@
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.3.tgz",
"integrity": "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw==",
- "devOptional": true
+ "dev": true
},
"node_modules/damerau-levenshtein": {
"version": "1.0.8",
@@ -2527,6 +2899,15 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/date-fns": {
+ "version": "3.6.0",
+ "resolved": "https://registry.npmjs.org/date-fns/-/date-fns-3.6.0.tgz",
+ "integrity": "sha512-fRHTG8g/Gif+kSh50gaGEdToemgfj74aRX3swtiouboip5JDLAyDE9F11nHMIcvOaXeOC6D7SpNhi7uFyB7Uww==",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/kossnocorp"
+ }
+ },
"node_modules/debug": {
"version": "4.4.0",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.0.tgz",
@@ -2584,6 +2965,14 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/delayed-stream": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
+ "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==",
+ "engines": {
+ "node": ">=0.4.0"
+ }
+ },
"node_modules/detect-libc": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.0.4.tgz",
@@ -2614,7 +3003,6 @@
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
"integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",
- "dev": true,
"dependencies": {
"call-bind-apply-helpers": "^1.0.1",
"es-errors": "^1.3.0",
@@ -2712,7 +3100,6 @@
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
"integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
- "dev": true,
"engines": {
"node": ">= 0.4"
}
@@ -2721,7 +3108,6 @@
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",
"integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
- "dev": true,
"engines": {
"node": ">= 0.4"
}
@@ -2757,7 +3143,6 @@
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz",
"integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==",
- "dev": true,
"dependencies": {
"es-errors": "^1.3.0"
},
@@ -2769,7 +3154,6 @@
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz",
"integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==",
- "dev": true,
"dependencies": {
"es-errors": "^1.3.0",
"get-intrinsic": "^1.2.6",
@@ -3339,6 +3723,25 @@
"integrity": "sha512-GX+ysw4PBCz0PzosHDepZGANEuFCMLrnRTiEy9McGjmkCQYwRq4A/X786G/fjM/+OjsWSU1ZrY5qyARZmO/uwg==",
"dev": true
},
+ "node_modules/follow-redirects": {
+ "version": "1.15.9",
+ "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.9.tgz",
+ "integrity": "sha512-gew4GsXizNgdoRyqmyfMHyAmXsZDk6mHkSxZFCzW9gwlbtOW44CDtYavM+y+72qD/Vq2l550kMF52DT8fOLJqQ==",
+ "funding": [
+ {
+ "type": "individual",
+ "url": "https://github.com/sponsors/RubenVerborgh"
+ }
+ ],
+ "engines": {
+ "node": ">=4.0"
+ },
+ "peerDependenciesMeta": {
+ "debug": {
+ "optional": true
+ }
+ }
+ },
"node_modules/for-each": {
"version": "0.3.5",
"resolved": "https://registry.npmjs.org/for-each/-/for-each-0.3.5.tgz",
@@ -3354,6 +3757,20 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/form-data": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.2.tgz",
+ "integrity": "sha512-hGfm/slu0ZabnNt4oaRZ6uREyfCj6P4fT/n6A1rGV+Z0VdGXjfOhVUpkn6qVQONHGIFwmveGXyDs75+nr6FM8w==",
+ "dependencies": {
+ "asynckit": "^0.4.0",
+ "combined-stream": "^1.0.8",
+ "es-set-tostringtag": "^2.1.0",
+ "mime-types": "^2.1.12"
+ },
+ "engines": {
+ "node": ">= 6"
+ }
+ },
"node_modules/framer-motion": {
"version": "11.18.2",
"resolved": "https://registry.npmjs.org/framer-motion/-/framer-motion-11.18.2.tgz",
@@ -3384,7 +3801,6 @@
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
"integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
- "dev": true,
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
@@ -3422,7 +3838,6 @@
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
"integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",
- "dev": true,
"dependencies": {
"call-bind-apply-helpers": "^1.0.2",
"es-define-property": "^1.0.1",
@@ -3454,7 +3869,6 @@
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",
"integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",
- "dev": true,
"dependencies": {
"dunder-proto": "^1.0.1",
"es-object-atoms": "^1.0.0"
@@ -3536,7 +3950,6 @@
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
"integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
- "dev": true,
"engines": {
"node": ">= 0.4"
},
@@ -3608,7 +4021,6 @@
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",
"integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",
- "dev": true,
"engines": {
"node": ">= 0.4"
},
@@ -3620,7 +4032,6 @@
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz",
"integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==",
- "dev": true,
"dependencies": {
"has-symbols": "^1.0.3"
},
@@ -3635,7 +4046,6 @@
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz",
"integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==",
- "dev": true,
"dependencies": {
"function-bind": "^1.1.2"
},
@@ -4474,7 +4884,6 @@
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
"integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",
- "dev": true,
"engines": {
"node": ">= 0.4"
}
@@ -4501,6 +4910,25 @@
"node": ">=8.6"
}
},
+ "node_modules/mime-db": {
+ "version": "1.52.0",
+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
+ "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/mime-types": {
+ "version": "2.1.35",
+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
+ "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
+ "dependencies": {
+ "mime-db": "1.52.0"
+ },
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
"node_modules/minimatch": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz",
@@ -4948,6 +5376,11 @@
"react-is": "^16.13.1"
}
},
+ "node_modules/proxy-from-env": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz",
+ "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg=="
+ },
"node_modules/punycode": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
@@ -4985,6 +5418,19 @@
"node": ">=0.10.0"
}
},
+ "node_modules/react-day-picker": {
+ "version": "8.10.1",
+ "resolved": "https://registry.npmjs.org/react-day-picker/-/react-day-picker-8.10.1.tgz",
+ "integrity": "sha512-TMx7fNbhLk15eqcMt+7Z7S2KF7mfTId/XJDjKE8f+IUcFn0l08/kI4FiYTL/0yuOLmEcbR4Fwe3GJf/NiiMnPA==",
+ "funding": {
+ "type": "individual",
+ "url": "https://github.com/sponsors/gpbl"
+ },
+ "peerDependencies": {
+ "date-fns": "^2.28.0 || ^3.0.0",
+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0"
+ }
+ },
"node_modules/react-dom": {
"version": "19.1.0",
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.1.0.tgz",
@@ -5661,7 +6107,8 @@
"node_modules/tailwindcss": {
"version": "4.1.4",
"resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.1.4.tgz",
- "integrity": "sha512-1ZIUqtPITFbv/DxRmDr5/agPqJwF69d24m9qmM1939TJehgY539CtzeZRjbLt5G6fSy/7YqqYsfvoTEw9xUI2A=="
+ "integrity": "sha512-1ZIUqtPITFbv/DxRmDr5/agPqJwF69d24m9qmM1939TJehgY539CtzeZRjbLt5G6fSy/7YqqYsfvoTEw9xUI2A==",
+ "dev": true
},
"node_modules/tailwindcss-animate": {
"version": "1.0.7",
diff --git a/frontend/package.json b/frontend/package.json
index eb04e83..4623f98 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -12,14 +12,21 @@
"@hookform/resolvers": "^5.0.1",
"@radix-ui/react-dialog": "^1.1.11",
"@radix-ui/react-label": "^2.1.4",
+ "@radix-ui/react-popover": "^1.1.11",
+ "@radix-ui/react-progress": "^1.1.4",
+ "@radix-ui/react-select": "^2.2.2",
"@radix-ui/react-slot": "^1.2.0",
+ "@radix-ui/react-toast": "^1.2.11",
"@tanstack/react-query": "^5.74.4",
+ "axios": "^1.9.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
+ "date-fns": "^3.6.0",
"framer-motion": "^11.18.2",
"lucide-react": "^0.503.0",
"next": "15.3.1",
"react": "^19.0.0",
+ "react-day-picker": "^8.10.1",
"react-dom": "^19.0.0",
"react-hook-form": "^7.56.1",
"tailwind-merge": "^3.2.0",
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..cda33c1
--- /dev/null
+++ b/frontend/src/app/(main)/goals/[id]/page.tsx
@@ -0,0 +1,293 @@
+"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";
+import { use } from "react";
+
+export default function GoalDetailPage({ params }: { params: { id: string } }) {
+ // Unwrap params Promise using React.use()
+ const unwrappedParams = use(params);
+ const id = unwrappedParams.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..4c02bb2
--- /dev/null
+++ b/frontend/src/app/(main)/goals/edit/[id]/page.tsx
@@ -0,0 +1,18 @@
+import { Metadata } from "next";
+import { GoalForm } from "../../components/goal-form";
+import { use } from "react";
+
+export const metadata: Metadata = {
+ title: "Edit Goal | Finance",
+ description: "Edit your financial goal",
+};
+
+export default function EditGoalPage({ params }: { params: { id: string } }) {
+ const unwrappedParams = use(params);
+ return (
+ <div className="container mx-auto py-8">
+ <h1 className="text-2xl font-bold tracking-tight mb-6">Edit Goal</h1>
+ <GoalForm goalId={parseInt(unwrappedParams.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>
diff --git a/frontend/src/components/ui/badge.tsx b/frontend/src/components/ui/badge.tsx
new file mode 100644
index 0000000..fd86b2b
--- /dev/null
+++ b/frontend/src/components/ui/badge.tsx
@@ -0,0 +1,36 @@
+import * as React from "react"
+import { cva, type VariantProps } from "class-variance-authority"
+
+import { cn } from "@/lib/utils"
+
+const badgeVariants = cva(
+ "inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
+ {
+ variants: {
+ variant: {
+ default:
+ "border-transparent bg-primary text-primary-foreground hover:bg-primary/80",
+ secondary:
+ "border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
+ destructive:
+ "border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",
+ outline: "text-foreground",
+ },
+ },
+ defaultVariants: {
+ variant: "default",
+ },
+ }
+)
+
+export interface BadgeProps
+ extends React.HTMLAttributes<HTMLDivElement>,
+ VariantProps<typeof badgeVariants> {}
+
+function Badge({ className, variant, ...props }: BadgeProps) {
+ return (
+ <div className={cn(badgeVariants({ variant }), className)} {...props} />
+ )
+}
+
+export { Badge, badgeVariants } \ No newline at end of file
diff --git a/frontend/src/components/ui/calendar.tsx b/frontend/src/components/ui/calendar.tsx
new file mode 100644
index 0000000..144b6b6
--- /dev/null
+++ b/frontend/src/components/ui/calendar.tsx
@@ -0,0 +1,64 @@
+import * as React from "react"
+import { ChevronLeft, ChevronRight } from "lucide-react"
+import { DayPicker } from "react-day-picker"
+
+import { cn } from "@/lib/utils"
+import { buttonVariants } from "@/components/ui/button"
+
+export type CalendarProps = React.ComponentProps<typeof DayPicker>
+
+function Calendar({
+ className,
+ classNames,
+ showOutsideDays = true,
+ ...props
+}: CalendarProps) {
+ return (
+ <DayPicker
+ showOutsideDays={showOutsideDays}
+ className={cn("p-3", className)}
+ classNames={{
+ months: "flex flex-col sm:flex-row space-y-4 sm:space-x-4 sm:space-y-0",
+ month: "space-y-4",
+ caption: "flex justify-center pt-1 relative items-center",
+ caption_label: "text-sm font-medium",
+ nav: "space-x-1 flex items-center",
+ nav_button: cn(
+ buttonVariants({ variant: "outline" }),
+ "h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100"
+ ),
+ nav_button_previous: "absolute left-1",
+ nav_button_next: "absolute right-1",
+ table: "w-full border-collapse space-y-1",
+ head_row: "flex",
+ head_cell:
+ "text-muted-foreground rounded-md w-9 font-normal text-[0.8rem]",
+ row: "flex w-full mt-2",
+ cell: "h-9 w-9 text-center text-sm p-0 relative [&:has([aria-selected].day-range-end)]:rounded-r-md [&:has([aria-selected].day-outside)]:bg-accent/50 [&:has([aria-selected])]:bg-accent first:[&:has([aria-selected])]:rounded-l-md last:[&:has([aria-selected])]:rounded-r-md focus-within:relative focus-within:z-20",
+ day: cn(
+ buttonVariants({ variant: "ghost" }),
+ "h-9 w-9 p-0 font-normal aria-selected:opacity-100"
+ ),
+ day_range_end: "day-range-end",
+ day_selected:
+ "bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground focus:bg-primary focus:text-primary-foreground",
+ day_today: "bg-accent text-accent-foreground",
+ day_outside:
+ "day-outside text-muted-foreground opacity-50 aria-selected:bg-accent/50 aria-selected:text-muted-foreground aria-selected:opacity-30",
+ day_disabled: "text-muted-foreground opacity-50",
+ day_range_middle:
+ "aria-selected:bg-accent aria-selected:text-accent-foreground",
+ day_hidden: "invisible",
+ ...classNames,
+ }}
+ components={{
+ IconLeft: () => <ChevronLeft className="h-4 w-4" />,
+ IconRight: () => <ChevronRight className="h-4 w-4" />,
+ }}
+ {...props}
+ />
+ )
+}
+Calendar.displayName = "Calendar"
+
+export { Calendar } \ No newline at end of file
diff --git a/frontend/src/components/ui/popover.tsx b/frontend/src/components/ui/popover.tsx
new file mode 100644
index 0000000..8577b8a
--- /dev/null
+++ b/frontend/src/components/ui/popover.tsx
@@ -0,0 +1,29 @@
+import * as React from "react"
+import * as PopoverPrimitive from "@radix-ui/react-popover"
+
+import { cn } from "@/lib/utils"
+
+const Popover = PopoverPrimitive.Root
+
+const PopoverTrigger = PopoverPrimitive.Trigger
+
+const PopoverContent = React.forwardRef<
+ React.ElementRef<typeof PopoverPrimitive.Content>,
+ React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Content>
+>(({ className, align = "center", sideOffset = 4, ...props }, ref) => (
+ <PopoverPrimitive.Portal>
+ <PopoverPrimitive.Content
+ ref={ref}
+ align={align}
+ sideOffset={sideOffset}
+ className={cn(
+ "z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
+ className
+ )}
+ {...props}
+ />
+ </PopoverPrimitive.Portal>
+))
+PopoverContent.displayName = PopoverPrimitive.Content.displayName
+
+export { Popover, PopoverTrigger, PopoverContent } \ No newline at end of file
diff --git a/frontend/src/components/ui/progress.tsx b/frontend/src/components/ui/progress.tsx
new file mode 100644
index 0000000..bd761c6
--- /dev/null
+++ b/frontend/src/components/ui/progress.tsx
@@ -0,0 +1,26 @@
+import * as React from "react"
+import * as ProgressPrimitive from "@radix-ui/react-progress"
+
+import { cn } from "@/lib/utils"
+
+const Progress = React.forwardRef<
+ React.ElementRef<typeof ProgressPrimitive.Root>,
+ React.ComponentPropsWithoutRef<typeof ProgressPrimitive.Root>
+>(({ className, value, ...props }, ref) => (
+ <ProgressPrimitive.Root
+ ref={ref}
+ className={cn(
+ "relative h-4 w-full overflow-hidden rounded-full bg-secondary",
+ className
+ )}
+ {...props}
+ >
+ <ProgressPrimitive.Indicator
+ className="h-full w-full flex-1 bg-primary transition-all"
+ style={{ transform: `translateX(-${100 - (value || 0)}%)` }}
+ />
+ </ProgressPrimitive.Root>
+))
+Progress.displayName = ProgressPrimitive.Root.displayName
+
+export { Progress } \ No newline at end of file
diff --git a/frontend/src/components/ui/select.tsx b/frontend/src/components/ui/select.tsx
new file mode 100644
index 0000000..c6bde11
--- /dev/null
+++ b/frontend/src/components/ui/select.tsx
@@ -0,0 +1,158 @@
+import * as React from "react"
+import * as SelectPrimitive from "@radix-ui/react-select"
+import { Check, ChevronDown, ChevronUp } from "lucide-react"
+
+import { cn } from "@/lib/utils"
+
+const Select = SelectPrimitive.Root
+
+const SelectGroup = SelectPrimitive.Group
+
+const SelectValue = SelectPrimitive.Value
+
+const SelectTrigger = React.forwardRef<
+ React.ElementRef<typeof SelectPrimitive.Trigger>,
+ React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>
+>(({ className, children, ...props }, ref) => (
+ <SelectPrimitive.Trigger
+ ref={ref}
+ className={cn(
+ "flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",
+ className
+ )}
+ {...props}
+ >
+ {children}
+ <SelectPrimitive.Icon asChild>
+ <ChevronDown className="h-4 w-4 opacity-50" />
+ </SelectPrimitive.Icon>
+ </SelectPrimitive.Trigger>
+))
+SelectTrigger.displayName = SelectPrimitive.Trigger.displayName
+
+const SelectScrollUpButton = React.forwardRef<
+ React.ElementRef<typeof SelectPrimitive.ScrollUpButton>,
+ React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollUpButton>
+>(({ className, ...props }, ref) => (
+ <SelectPrimitive.ScrollUpButton
+ ref={ref}
+ className={cn(
+ "flex cursor-default items-center justify-center py-1",
+ className
+ )}
+ {...props}
+ >
+ <ChevronUp className="h-4 w-4" />
+ </SelectPrimitive.ScrollUpButton>
+))
+SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName
+
+const SelectScrollDownButton = React.forwardRef<
+ React.ElementRef<typeof SelectPrimitive.ScrollDownButton>,
+ React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollDownButton>
+>(({ className, ...props }, ref) => (
+ <SelectPrimitive.ScrollDownButton
+ ref={ref}
+ className={cn(
+ "flex cursor-default items-center justify-center py-1",
+ className
+ )}
+ {...props}
+ >
+ <ChevronDown className="h-4 w-4" />
+ </SelectPrimitive.ScrollDownButton>
+))
+SelectScrollDownButton.displayName =
+ SelectPrimitive.ScrollDownButton.displayName
+
+const SelectContent = React.forwardRef<
+ React.ElementRef<typeof SelectPrimitive.Content>,
+ React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content>
+>(({ className, children, position = "popper", ...props }, ref) => (
+ <SelectPrimitive.Portal>
+ <SelectPrimitive.Content
+ ref={ref}
+ className={cn(
+ "relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
+ position === "popper" &&
+ "data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
+ className
+ )}
+ position={position}
+ {...props}
+ >
+ <SelectScrollUpButton />
+ <SelectPrimitive.Viewport
+ className={cn(
+ "p-1",
+ position === "popper" &&
+ "h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"
+ )}
+ >
+ {children}
+ </SelectPrimitive.Viewport>
+ <SelectScrollDownButton />
+ </SelectPrimitive.Content>
+ </SelectPrimitive.Portal>
+))
+SelectContent.displayName = SelectPrimitive.Content.displayName
+
+const SelectLabel = React.forwardRef<
+ React.ElementRef<typeof SelectPrimitive.Label>,
+ React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label>
+>(({ className, ...props }, ref) => (
+ <SelectPrimitive.Label
+ ref={ref}
+ className={cn("py-1.5 pl-8 pr-2 text-sm font-semibold", className)}
+ {...props}
+ />
+))
+SelectLabel.displayName = SelectPrimitive.Label.displayName
+
+const SelectItem = React.forwardRef<
+ React.ElementRef<typeof SelectPrimitive.Item>,
+ React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>
+>(({ className, children, ...props }, ref) => (
+ <SelectPrimitive.Item
+ ref={ref}
+ className={cn(
+ "relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
+ className
+ )}
+ {...props}
+ >
+ <span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
+ <SelectPrimitive.ItemIndicator>
+ <Check className="h-4 w-4" />
+ </SelectPrimitive.ItemIndicator>
+ </span>
+
+ <SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
+ </SelectPrimitive.Item>
+))
+SelectItem.displayName = SelectPrimitive.Item.displayName
+
+const SelectSeparator = React.forwardRef<
+ React.ElementRef<typeof SelectPrimitive.Separator>,
+ React.ComponentPropsWithoutRef<typeof SelectPrimitive.Separator>
+>(({ className, ...props }, ref) => (
+ <SelectPrimitive.Separator
+ ref={ref}
+ className={cn("-mx-1 my-1 h-px bg-muted", className)}
+ {...props}
+ />
+))
+SelectSeparator.displayName = SelectPrimitive.Separator.displayName
+
+export {
+ Select,
+ SelectGroup,
+ SelectValue,
+ SelectTrigger,
+ SelectContent,
+ SelectLabel,
+ SelectItem,
+ SelectSeparator,
+ SelectScrollUpButton,
+ SelectScrollDownButton,
+} \ No newline at end of file
diff --git a/frontend/src/components/ui/toast.tsx b/frontend/src/components/ui/toast.tsx
new file mode 100644
index 0000000..800ff84
--- /dev/null
+++ b/frontend/src/components/ui/toast.tsx
@@ -0,0 +1,127 @@
+import * as React from "react"
+import * as ToastPrimitives from "@radix-ui/react-toast"
+import { cva, type VariantProps } from "class-variance-authority"
+import { X } from "lucide-react"
+
+import { cn } from "@/lib/utils"
+
+const ToastProvider = ToastPrimitives.Provider
+
+const ToastViewport = React.forwardRef<
+ React.ElementRef<typeof ToastPrimitives.Viewport>,
+ React.ComponentPropsWithoutRef<typeof ToastPrimitives.Viewport>
+>(({ className, ...props }, ref) => (
+ <ToastPrimitives.Viewport
+ ref={ref}
+ className={cn(
+ "fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",
+ className
+ )}
+ {...props}
+ />
+))
+ToastViewport.displayName = ToastPrimitives.Viewport.displayName
+
+const toastVariants = cva(
+ "group pointer-events-auto relative flex w-full items-center justify-between space-x-4 overflow-hidden rounded-md border p-6 pr-8 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",
+ {
+ variants: {
+ variant: {
+ default: "border bg-background text-foreground",
+ destructive:
+ "destructive group border-destructive bg-destructive text-destructive-foreground",
+ },
+ },
+ defaultVariants: {
+ variant: "default",
+ },
+ }
+)
+
+const Toast = React.forwardRef<
+ React.ElementRef<typeof ToastPrimitives.Root>,
+ React.ComponentPropsWithoutRef<typeof ToastPrimitives.Root> &
+ VariantProps<typeof toastVariants>
+>(({ className, variant, ...props }, ref) => {
+ return (
+ <ToastPrimitives.Root
+ ref={ref}
+ className={cn(toastVariants({ variant }), className)}
+ {...props}
+ />
+ )
+})
+Toast.displayName = ToastPrimitives.Root.displayName
+
+const ToastAction = React.forwardRef<
+ React.ElementRef<typeof ToastPrimitives.Action>,
+ React.ComponentPropsWithoutRef<typeof ToastPrimitives.Action>
+>(({ className, ...props }, ref) => (
+ <ToastPrimitives.Action
+ ref={ref}
+ className={cn(
+ "inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium ring-offset-background transition-colors hover:bg-secondary focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",
+ className
+ )}
+ {...props}
+ />
+))
+ToastAction.displayName = ToastPrimitives.Action.displayName
+
+const ToastClose = React.forwardRef<
+ React.ElementRef<typeof ToastPrimitives.Close>,
+ React.ComponentPropsWithoutRef<typeof ToastPrimitives.Close>
+>(({ className, ...props }, ref) => (
+ <ToastPrimitives.Close
+ ref={ref}
+ className={cn(
+ "absolute right-2 top-2 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-2 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",
+ className
+ )}
+ toast-close=""
+ {...props}
+ >
+ <X className="h-4 w-4" />
+ </ToastPrimitives.Close>
+))
+ToastClose.displayName = ToastPrimitives.Close.displayName
+
+const ToastTitle = React.forwardRef<
+ React.ElementRef<typeof ToastPrimitives.Title>,
+ React.ComponentPropsWithoutRef<typeof ToastPrimitives.Title>
+>(({ className, ...props }, ref) => (
+ <ToastPrimitives.Title
+ ref={ref}
+ className={cn("text-sm font-semibold", className)}
+ {...props}
+ />
+))
+ToastTitle.displayName = ToastPrimitives.Title.displayName
+
+const ToastDescription = React.forwardRef<
+ React.ElementRef<typeof ToastPrimitives.Description>,
+ React.ComponentPropsWithoutRef<typeof ToastPrimitives.Description>
+>(({ className, ...props }, ref) => (
+ <ToastPrimitives.Description
+ ref={ref}
+ className={cn("text-sm opacity-90", className)}
+ {...props}
+ />
+))
+ToastDescription.displayName = ToastPrimitives.Description.displayName
+
+type ToastProps = React.ComponentPropsWithoutRef<typeof Toast>
+
+type ToastActionElement = React.ReactElement<typeof ToastAction>
+
+export {
+ type ToastProps,
+ type ToastActionElement,
+ ToastProvider,
+ ToastViewport,
+ Toast,
+ ToastTitle,
+ ToastDescription,
+ ToastClose,
+ ToastAction,
+} \ No newline at end of file
diff --git a/frontend/src/components/ui/toaster.tsx b/frontend/src/components/ui/toaster.tsx
new file mode 100644
index 0000000..62bb68a
--- /dev/null
+++ b/frontend/src/components/ui/toaster.tsx
@@ -0,0 +1,35 @@
+"use client"
+
+import {
+ Toast,
+ ToastClose,
+ ToastDescription,
+ ToastProvider,
+ ToastTitle,
+ ToastViewport,
+} from "@/components/ui/toast"
+import { useToast } from "@/components/ui/use-toast"
+
+export function Toaster() {
+ const { toasts } = useToast()
+
+ return (
+ <ToastProvider>
+ {toasts.map(function ({ id, title, description, action, ...props }) {
+ return (
+ <Toast key={id} {...props}>
+ <div className="grid gap-1">
+ {title && <ToastTitle>{title}</ToastTitle>}
+ {description && (
+ <ToastDescription>{description}</ToastDescription>
+ )}
+ </div>
+ {action}
+ <ToastClose />
+ </Toast>
+ )
+ })}
+ <ToastViewport />
+ </ToastProvider>
+ )
+} \ No newline at end of file
diff --git a/frontend/src/components/ui/use-toast.tsx b/frontend/src/components/ui/use-toast.tsx
new file mode 100644
index 0000000..effb83e
--- /dev/null
+++ b/frontend/src/components/ui/use-toast.tsx
@@ -0,0 +1,191 @@
+// Inspired by react-hot-toast library
+import * as React from "react"
+
+import type {
+ ToastActionElement,
+ ToastProps,
+} from "@/components/ui/toast"
+
+const TOAST_LIMIT = 5
+const TOAST_REMOVE_DELAY = 1000000
+
+type ToasterToast = ToastProps & {
+ id: string
+ title?: React.ReactNode
+ description?: React.ReactNode
+ action?: ToastActionElement
+}
+
+// Define action types as enum or const object
+export const ActionType = {
+ ADD_TOAST: "ADD_TOAST",
+ UPDATE_TOAST: "UPDATE_TOAST",
+ DISMISS_TOAST: "DISMISS_TOAST",
+ REMOVE_TOAST: "REMOVE_TOAST",
+} as const
+
+let count = 0
+
+function genId() {
+ count = (count + 1) % Number.MAX_VALUE
+ return count.toString()
+}
+
+type Action =
+ | {
+ type: typeof ActionType["ADD_TOAST"]
+ toast: ToasterToast
+ }
+ | {
+ type: typeof ActionType["UPDATE_TOAST"]
+ toast: Partial<ToasterToast>
+ }
+ | {
+ type: typeof ActionType["DISMISS_TOAST"]
+ toastId?: ToasterToast["id"]
+ }
+ | {
+ type: typeof ActionType["REMOVE_TOAST"]
+ toastId?: ToasterToast["id"]
+ }
+
+interface State {
+ toasts: ToasterToast[]
+}
+
+const toastTimeouts = new Map<string, ReturnType<typeof setTimeout>>()
+
+const addToRemoveQueue = (toastId: string) => {
+ if (toastTimeouts.has(toastId)) {
+ return
+ }
+
+ const timeout = setTimeout(() => {
+ toastTimeouts.delete(toastId)
+ dispatch({
+ type: "REMOVE_TOAST",
+ toastId: toastId,
+ })
+ }, TOAST_REMOVE_DELAY)
+
+ toastTimeouts.set(toastId, timeout)
+}
+
+export const reducer = (state: State, action: Action): State => {
+ switch (action.type) {
+ case "ADD_TOAST":
+ return {
+ ...state,
+ toasts: [action.toast, ...state.toasts].slice(0, TOAST_LIMIT),
+ }
+
+ case "UPDATE_TOAST":
+ return {
+ ...state,
+ toasts: state.toasts.map((t) =>
+ t.id === action.toast.id ? { ...t, ...action.toast } : t
+ ),
+ }
+
+ case "DISMISS_TOAST": {
+ const { toastId } = action
+
+ // ! Side effects ! - This could be extracted into a dismissToast() action,
+ // but I'll keep it here for simplicity
+ if (toastId) {
+ addToRemoveQueue(toastId)
+ } else {
+ state.toasts.forEach((toast) => {
+ addToRemoveQueue(toast.id)
+ })
+ }
+
+ return {
+ ...state,
+ toasts: state.toasts.map((t) =>
+ t.id === toastId || toastId === undefined
+ ? {
+ ...t,
+ open: false,
+ }
+ : t
+ ),
+ }
+ }
+ case "REMOVE_TOAST":
+ if (action.toastId === undefined) {
+ return {
+ ...state,
+ toasts: [],
+ }
+ }
+ return {
+ ...state,
+ toasts: state.toasts.filter((t) => t.id !== action.toastId),
+ }
+ }
+}
+
+const listeners: Array<(state: State) => void> = []
+
+let memoryState: State = { toasts: [] }
+
+function dispatch(action: Action) {
+ memoryState = reducer(memoryState, action)
+ listeners.forEach((listener) => {
+ listener(memoryState)
+ })
+}
+
+type Toast = Omit<ToasterToast, "id">
+
+function toast({ ...props }: Toast) {
+ const id = genId()
+
+ const update = (props: ToasterToast) =>
+ dispatch({
+ type: "UPDATE_TOAST",
+ toast: { ...props, id },
+ })
+ const dismiss = () => dispatch({ type: "DISMISS_TOAST", toastId: id })
+
+ dispatch({
+ type: "ADD_TOAST",
+ toast: {
+ ...props,
+ id,
+ open: true,
+ onOpenChange: (open) => {
+ if (!open) dismiss()
+ },
+ },
+ })
+
+ return {
+ id: id,
+ dismiss,
+ update,
+ }
+}
+
+function useToast() {
+ const [state, setState] = React.useState<State>(memoryState)
+
+ React.useEffect(() => {
+ listeners.push(setState)
+ return () => {
+ const index = listeners.indexOf(setState)
+ if (index > -1) {
+ listeners.splice(index, 1)
+ }
+ }
+ }, [state])
+
+ return {
+ ...state,
+ toast,
+ dismiss: (toastId?: string) => dispatch({ type: "DISMISS_TOAST", toastId }),
+ }
+}
+
+export { useToast, toast } \ No newline at end of file
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 11cee62..67ea975 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -1,72 +1,52 @@
+import axios from 'axios';
+
// API base URL
const API_BASE_URL = 'http://localhost:8080/api/v1';
-// Helper function for fetching data with authorization
-async function fetchWithAuth(url: string, options: RequestInit = {}) {
- // Get token from local storage
- const token = localStorage.getItem('token');
-
- // Set up headers with authorization
- const headers = {
+// Create axios instance with defaults
+export const api = axios.create({
+ baseURL: API_BASE_URL,
+ headers: {
'Content-Type': 'application/json',
- ...(token ? { 'Authorization': `Bearer ${token}` } : {}),
- ...options.headers
- };
-
- // Perform fetch
- const response = await fetch(`${API_BASE_URL}${url}`, {
- ...options,
- headers
- });
-
- // Handle unauthorized responses
- if (response.status === 401) {
- localStorage.removeItem('token');
- window.location.href = '/login';
- throw new Error('Unauthorized');
- }
-
- // Parse response
- if (!response.ok) {
- const errorData = await response.json().catch(() => null);
- throw new Error(errorData?.error || `API Error: ${response.status}`);
+ },
+});
+
+// Add auth interceptor
+api.interceptors.request.use(
+ (config) => {
+ const token = localStorage.getItem('token');
+ if (token) {
+ config.headers.Authorization = `Bearer ${token}`;
+ }
+ return config;
+ },
+ (error) => Promise.reject(error)
+);
+
+// Handle auth errors
+api.interceptors.response.use(
+ (response) => response,
+ (error) => {
+ if (error.response && error.response.status === 401 && typeof window !== 'undefined') {
+ localStorage.removeItem('token');
+ window.location.href = '/login';
+ }
+ return Promise.reject(error);
}
-
- return response.json();
-}
+);
// Auth API
export const authApi = {
login: async (email: string, password: string) => {
- const response = await fetch(`${API_BASE_URL}/auth/login`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ email, password })
- });
-
- if (!response.ok) {
- const errorData = await response.json().catch(() => null);
- throw new Error(errorData?.error || 'Login failed');
- }
-
- const data = await response.json();
- localStorage.setItem('token', data.token);
- return data;
+ const response = await api.post('/auth/login', { email, password });
+ const { token } = response.data;
+ localStorage.setItem('token', token);
+ return response.data;
},
signup: async (name: string, email: string, password: string) => {
- const response = await fetch(`${API_BASE_URL}/auth/signup`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ name, email, password })
- });
-
- if (!response.ok) {
- const errorData = await response.json().catch(() => null);
- throw new Error(errorData?.error || 'Signup failed');
- }
-
- return response.json();
+ const response = await api.post('/auth/signup', { name, email, password });
+ return response.data;
},
logout: () => {
@@ -77,14 +57,14 @@ export const authApi = {
// Account API
export interface Account {
- ID: number;
- CreatedAt: string;
- UpdatedAt: string;
- DeletedAt: string | null;
- UserID: number;
- Name: string;
- Type: string;
- Balance: number;
+ id: number;
+ createdAt: string;
+ updatedAt: string;
+ deletedAt: string | null;
+ userID: number;
+ name: string;
+ type: string;
+ balance: number;
}
export interface AccountInput {
@@ -94,34 +74,26 @@ export interface AccountInput {
}
export const accountApi = {
- getAccounts: () => fetchWithAuth('/accounts'),
- getAccount: (id: number) => fetchWithAuth(`/accounts/${id}`),
- createAccount: (account: AccountInput) => fetchWithAuth('/accounts', {
- method: 'POST',
- body: JSON.stringify(account)
- }),
- updateAccount: (id: number, account: Partial<AccountInput>) => fetchWithAuth(`/accounts/${id}`, {
- method: 'PUT',
- body: JSON.stringify(account)
- }),
- deleteAccount: (id: number) => fetchWithAuth(`/accounts/${id}`, {
- method: 'DELETE'
- })
+ getAccounts: () => api.get('/accounts').then(res => res.data),
+ getAccount: (id: number) => api.get(`/accounts/${id}`).then(res => res.data),
+ createAccount: (account: AccountInput) => api.post('/accounts', account).then(res => res.data),
+ updateAccount: (id: number, account: Partial<AccountInput>) => api.put(`/accounts/${id}`, account).then(res => res.data),
+ deleteAccount: (id: number) => api.delete(`/accounts/${id}`).then(res => res.data)
};
// Transaction API
export interface Transaction {
- ID: number;
- CreatedAt: string;
- UpdatedAt: string;
- DeletedAt: string | null;
- UserID: number;
- AccountID: number | null;
- Description: string;
- Amount: number;
- Type: "Income" | "Expense";
- Date: string;
- Category: string;
+ id: number;
+ createdAt: string;
+ updatedAt: string;
+ deletedAt: string | null;
+ userID: number;
+ accountID: number | null;
+ description: string;
+ amount: number;
+ type: "Income" | "Expense";
+ date: string;
+ category: string;
}
export interface TransactionInput {
@@ -139,55 +111,54 @@ export interface TransactionFilters {
category?: string;
startDate?: string; // YYYY-MM-DD format
endDate?: string; // YYYY-MM-DD format
+ goalId?: number;
}
export const transactionApi = {
getTransactions: (filters?: TransactionFilters) => {
- let queryParams = '';
-
+ const params: Record<string, string | number | undefined> = {};
if (filters) {
- const params = new URLSearchParams();
- if (filters.type) params.append('type', filters.type);
- if (filters.accountId) params.append('account_id', filters.accountId.toString());
- if (filters.category) params.append('category', filters.category);
- if (filters.startDate) params.append('start_date', filters.startDate);
- if (filters.endDate) params.append('end_date', filters.endDate);
-
- queryParams = `?${params.toString()}`;
+ if (filters.type) params.type = filters.type;
+ if (filters.accountId) params.account_id = filters.accountId;
+ if (filters.category) params.category = filters.category;
+ if (filters.startDate) params.start_date = filters.startDate;
+ if (filters.endDate) params.end_date = filters.endDate;
+ if (filters.goalId) params.goal_id = filters.goalId;
}
-
- return fetchWithAuth(`/transactions${queryParams}`);
+ return api.get('/transactions', { params }).then(res => res.data);
},
- getTransaction: (id: number) => fetchWithAuth(`/transactions/${id}`),
+ getTransaction: (id: number) => api.get(`/transactions/${id}`).then(res => res.data),
- createTransaction: (transaction: TransactionInput) => fetchWithAuth('/transactions', {
- method: 'POST',
- body: JSON.stringify(transaction)
- }),
+ createTransaction: (transaction: TransactionInput) => api.post('/transactions', transaction).then(res => res.data),
- updateTransaction: (id: number, transaction: Partial<TransactionInput>) => fetchWithAuth(`/transactions/${id}`, {
- method: 'PUT',
- body: JSON.stringify(transaction)
- }),
+ updateTransaction: (id: number, transaction: Partial<TransactionInput>) => api.put(`/transactions/${id}`, transaction).then(res => res.data),
- deleteTransaction: (id: number) => fetchWithAuth(`/transactions/${id}`, {
- method: 'DELETE'
- })
+ deleteTransaction: (id: number) => api.delete(`/transactions/${id}`).then(res => res.data)
};
// Goal API
export interface Goal {
- ID: number;
- CreatedAt: string;
- UpdatedAt: string;
- DeletedAt: string | null;
- UserID: number;
- Name: string;
- TargetAmount: number;
- CurrentAmount: number;
- TargetDate: string | null;
- Status: "Active" | "Achieved" | "Cancelled";
+ id: number;
+ createdAt: string;
+ updatedAt: string;
+ deletedAt: string | null;
+ userID: number;
+ name: string;
+ targetAmount: number;
+ currentAmount: number;
+ targetDate: string | null;
+ status: "Active" | "Paused" | "Achieved" | "Cancelled";
+}
+
+export interface GoalProgress {
+ goal: Goal;
+ percentComplete: number;
+ amountRemaining: number;
+ daysRemaining: number;
+ requiredPerDay: number;
+ requiredPerMonth: number;
+ onTrack: boolean;
}
export interface GoalInput {
@@ -195,51 +166,54 @@ export interface GoalInput {
targetAmount: number;
currentAmount?: number;
targetDate?: string; // YYYY-MM-DD format
- status?: "Active" | "Achieved" | "Cancelled";
+ status?: "Active" | "Paused" | "Achieved" | "Cancelled";
}
export const goalApi = {
- getGoals: (status?: "Active" | "Achieved" | "Cancelled") => {
- const queryParams = status ? `?status=${status}` : '';
- return fetchWithAuth(`/goals${queryParams}`);
+ getGoals: (status?: "Active" | "Paused" | "Achieved" | "Cancelled") => {
+ const params = status ? { status } : {};
+ return api.get('/goals', { params }).then(res => res.data);
},
- getGoal: (id: number) => fetchWithAuth(`/goals/${id}`),
+ getGoal: (id: number) => api.get(`/goals/${id}`).then(res => res.data),
+
+ createGoal: (goal: GoalInput) => api.post('/goals', goal).then(res => res.data),
- createGoal: (goal: GoalInput) => fetchWithAuth('/goals', {
- method: 'POST',
- body: JSON.stringify(goal)
- }),
+ updateGoal: (id: number, goal: Partial<GoalInput>) => api.put(`/goals/${id}`, goal).then(res => res.data),
- updateGoal: (id: number, goal: Partial<GoalInput>) => fetchWithAuth(`/goals/${id}`, {
- method: 'PUT',
- body: JSON.stringify(goal)
- }),
+ updateGoalProgress: (id: number, currentAmount: number) =>
+ api.patch(`/goals/${id}/progress`, { currentAmount }).then(res => res.data),
- updateGoalProgress: (id: number, currentAmount: number) => fetchWithAuth(`/goals/${id}/progress`, {
- method: 'PATCH',
- body: JSON.stringify({ currentAmount })
- }),
+ deleteGoal: (id: number) => api.delete(`/goals/${id}`).then(res => res.data),
- deleteGoal: (id: number) => fetchWithAuth(`/goals/${id}`, {
- method: 'DELETE'
- })
+ // New goal progress tracking endpoints
+ getGoalProgress: (id: number) => api.get(`/goals/${id}/progress`).then(res => res.data),
+
+ getAllGoalsProgress: (status?: string) => {
+ const params = status ? { status } : {};
+ return api.get('/goals/progress/all', { params }).then(res => res.data);
+ },
+
+ linkTransactionToGoal: (goalId: number, transactionId: number) =>
+ api.post(`/goals/${goalId}/link-transaction`, { transactionId }).then(res => res.data),
+
+ recalculateGoalProgress: (id: number) => api.post(`/goals/${id}/recalculate`).then(res => res.data)
};
// Loan API
export interface Loan {
- ID: number;
- CreatedAt: string;
- UpdatedAt: string;
- DeletedAt: string | null;
- UserID: number;
- AccountID: number | null;
- Name: string;
- OriginalAmount: number;
- CurrentBalance: number;
- InterestRate: number;
- StartDate: string;
- EndDate: string;
+ id: number;
+ createdAt: string;
+ updatedAt: string;
+ deletedAt: string | null;
+ userID: number;
+ accountID: number | null;
+ name: string;
+ originalAmount: number;
+ currentBalance: number;
+ interestRate: number;
+ startDate: string;
+ endDate: string;
}
export interface LoanInput {
@@ -253,22 +227,14 @@ export interface LoanInput {
}
export const loanApi = {
- getLoans: () => fetchWithAuth('/loans'),
- getLoan: (id: number) => fetchWithAuth(`/loans/${id}`),
- createLoan: (loan: LoanInput) => fetchWithAuth('/loans', {
- method: 'POST',
- body: JSON.stringify(loan)
- }),
- updateLoan: (id: number, loan: Partial<LoanInput>) => fetchWithAuth(`/loans/${id}`, {
- method: 'PUT',
- body: JSON.stringify(loan)
- }),
- deleteLoan: (id: number) => fetchWithAuth(`/loans/${id}`, {
- method: 'DELETE'
- })
+ getLoans: () => api.get('/loans').then(res => res.data),
+ getLoan: (id: number) => api.get(`/loans/${id}`).then(res => res.data),
+ createLoan: (loan: LoanInput) => api.post('/loans', loan).then(res => res.data),
+ updateLoan: (id: number, loan: Partial<LoanInput>) => api.put(`/loans/${id}`, loan).then(res => res.data),
+ deleteLoan: (id: number) => api.delete(`/loans/${id}`).then(res => res.data)
};
// User API
export const userApi = {
- getProfile: () => fetchWithAuth('/users/me')
+ getProfile: () => api.get('/users/me').then(res => res.data)
}; \ No newline at end of file
diff --git a/frontend/src/lib/utils.ts b/frontend/src/lib/utils.ts
index bd0c391..25e4a61 100644
--- a/frontend/src/lib/utils.ts
+++ b/frontend/src/lib/utils.ts
@@ -4,3 +4,17 @@ import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
+
+export function formatCurrency(amount: number | null | undefined): string {
+ // Check if amount is null, undefined or NaN
+ if (amount === null || amount === undefined || isNaN(amount)) {
+ return '$0';
+ }
+
+ return new Intl.NumberFormat('en-US', {
+ style: 'currency',
+ currency: 'USD',
+ minimumFractionDigits: 0,
+ maximumFractionDigits: 0,
+ }).format(amount);
+}