aboutsummaryrefslogtreecommitdiffstats
path: root/backend/internal/api/v1/loans/loans.go
blob: 1366b3b7212477932a9ce1cd2bade2e833b712ec (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
package loans

import (
	"net/http"
	"strconv"
	"time"

	"finance/backend/internal/database"
	"finance/backend/internal/models"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

// GetLoans returns all loans for the authenticated user
func GetLoans() gin.HandlerFunc {
	return func(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)
		var loans []models.Loan

		// Fetch all loans for the user
		if err := database.DB.Where("user_id = ?", userObj.ID).Find(&loans).Error; err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to fetch loans"})
			return
		}

		c.JSON(http.StatusOK, gin.H{"loans": loans})
	}
}

// GetLoanByID returns a specific loan by ID
func GetLoanByID() gin.HandlerFunc {
	return func(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
		}

		var loan models.Loan

		// Fetch the loan and ensure it belongs to the authenticated user
		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
		}

		c.JSON(http.StatusOK, gin.H{"loan": loan})
	}
}

// CreateLoan creates a new loan
func CreateLoan() gin.HandlerFunc {
	return func(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)

		// Define a struct to bind the request JSON
		var input struct {
			Name           string  `json:"name" binding:"required"`
			OriginalAmount int64   `json:"originalAmount" binding:"required"`
			CurrentBalance int64   `json:"currentBalance" binding:"required"`
			InterestRate   float64 `json:"interestRate"`
			StartDate      string  `json:"startDate" binding:"required"`
			EndDate        string  `json:"endDate" binding:"required"`
			AccountID      *uint   `json:"accountId"`
		}

		// Bind JSON to struct
		if err := c.ShouldBindJSON(&input); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}

		// Parse dates
		startDate, err := time.Parse("2006-01-02", input.StartDate)
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid start date format"})
			return
		}

		endDate, err := time.Parse("2006-01-02", input.EndDate)
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid end date format"})
			return
		}

		// Create loan object
		loan := models.Loan{
			UserID:         userObj.ID,
			Name:           input.Name,
			OriginalAmount: input.OriginalAmount,
			CurrentBalance: input.CurrentBalance,
			InterestRate:   input.InterestRate,
			StartDate:      startDate,
			EndDate:        endDate,
			AccountID:      input.AccountID,
		}

		// Save to database
		if err := database.DB.Create(&loan).Error; err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create loan"})
			return
		}

		c.JSON(http.StatusCreated, gin.H{"loan": loan})
	}
}

// UpdateLoan updates an existing loan
func UpdateLoan() gin.HandlerFunc {
	return func(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 {
			Name           string  `json:"name"`
			CurrentBalance int64   `json:"currentBalance"`
			InterestRate   float64 `json:"interestRate"`
			EndDate        string  `json:"endDate"`
			AccountID      *uint   `json:"accountId"`
		}

		// Bind JSON to struct
		if err := c.ShouldBindJSON(&input); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}

		// Update fields if provided
		if input.Name != "" {
			loan.Name = input.Name
		}
		if input.CurrentBalance != 0 {
			loan.CurrentBalance = input.CurrentBalance
		}
		if input.InterestRate != 0 {
			loan.InterestRate = input.InterestRate
		}
		if input.EndDate != "" {
			endDate, err := time.Parse("2006-01-02", input.EndDate)
			if err != nil {
				c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid end date format"})
				return
			}
			loan.EndDate = endDate
		}
		if input.AccountID != nil {
			loan.AccountID = input.AccountID
		}

		// Save updates to database
		if err := database.DB.Save(&loan).Error; err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to update loan"})
			return
		}

		c.JSON(http.StatusOK, gin.H{"loan": loan})
	}
}

// DeleteLoan deletes a loan
func DeleteLoan() gin.HandlerFunc {
	return func(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
		}

		// Delete the loan
		if err := database.DB.Delete(&loan).Error; err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to delete loan"})
			return
		}

		c.JSON(http.StatusOK, gin.H{"message": "Loan deleted successfully"})
	}
}