forked from Samyukta-b/mutual-funds-manager
-
Notifications
You must be signed in to change notification settings - Fork 8
/
main.go
303 lines (242 loc) · 7.35 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
package main
import (
"context"
"log"
"strconv"
"time"
"github.com/gin-gonic/gin"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type CAGR struct {
OneYear float64 `json:"1_year" bson:"1_year"`
ThreeYear float64 `json:"3_year" bson:"3_year"`
FiveYear float64 `json:"5_year" bson:"5_year"`
}
type Fund struct {
FundID int `json:"fund_id" bson:"fund_id"`
Name string `json:"name" bson:"name"`
Category string `json:"category" bson:"category"`
CAGR []CAGR `json:"cagr" bson:"cagr"`
Rating int `json:"rating" bson:"rating"`
}
type User struct {
UserID string `json:"user_id" bson:"user_id"`
Username string `json:"username" bson:"username"`
Email string `json:"email" bson:"email"`
Password string `json:"-" bson:"password"`
FirstName string `json:"first_name" bson:"first_name"`
LastName string `json:"last_name" bson:"last_name"`
DateOfBirth time.Time `json:"date_of_birth" bson:"date_of_birth"`
PhoneNumber string `json:"phone_number" bson:"phone_number"`
LastLoginAt time.Time `json:"last_login_at" bson:"last_login_at"`
MutualFunds []Fund `json:"mutual_funds" bson:"mutual_funds"`
}
var collection *mongo.Collection
var userCollection *mongo.Collection
var counterCollection *mongo.Collection
func main() {
router := gin.Default()
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
client, err := mongo.Connect(context.TODO(), clientOptions)
if err != nil {
log.Fatal(err)
}
err = client.Ping(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
collection = client.Database("mutual_funds").Collection("funds")
userCollection = client.Database("mutual_funds").Collection("users")
counterCollection = client.Database("mutual_funds").Collection("counters")
router.GET("/getAllFunds", getAllFunds)
router.POST("/addFund", addFund)
router.GET("/user/:userID", getUser)
router.POST("/addUser", addUser)
router.DELETE("/deleteUser/:userID", deleteUser)
router.DELETE("/fund/:fundID", deleteFund)
router.PUT("/fund/:fundID", updateFund)
router.PUT("/user/:userID", updateUser)
router.Run()
}
func addFund(c *gin.Context) {
var fund Fund
if err := c.ShouldBindJSON(&fund); err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}
// Get the next FundID
fundID, err := getNextFundID()
if err != nil {
c.JSON(500, gin.H{"error": "Failed to generate FundID"})
return
}
fund.FundID = fundID
_, err = collection.InsertOne(context.TODO(), fund)
if err != nil {
c.JSON(500, gin.H{"error": err.Error()})
return
}
c.JSON(200, gin.H{"result": "success", "fund_id": fundID})
}
func getAllFunds(c *gin.Context) {
cursor, err := collection.Find(context.TODO(), bson.M{})
if err != nil {
c.JSON(500, gin.H{"error": err.Error()})
return
}
defer cursor.Close(context.TODO())
var funds []Fund
for cursor.Next(context.TODO()) {
var fund Fund
if err := cursor.Decode(&fund); err != nil {
c.JSON(500, gin.H{"error": err.Error()})
return
}
funds = append(funds, fund)
}
c.JSON(200, funds)
}
func getUser(c *gin.Context) {
userID := c.Param("userID")
var user User
err := userCollection.FindOne(context.TODO(), bson.M{"user_id": userID}).Decode(&user)
if err != nil {
if err == mongo.ErrNoDocuments {
c.JSON(404, gin.H{"error": "User not found"})
} else {
c.JSON(500, gin.H{"error": err.Error()})
}
return
}
c.JSON(200, user)
}
func addUser(c *gin.Context) {
var user User
if err := c.ShouldBindJSON(&user); err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}
// Generate a unique user ID (you may want to use a more robust method in production)
user.UserID = generateUniqueUserID()
// Set the last login time to the current time
user.LastLoginAt = time.Now()
_, err := userCollection.InsertOne(context.TODO(), user)
if err != nil {
c.JSON(500, gin.H{"error": err.Error()})
return
}
c.JSON(201, gin.H{"result": "success", "user_id": user.UserID})
}
func deleteUser(c *gin.Context) {
userID := c.Param("userID")
result, err := userCollection.DeleteOne(context.TODO(), bson.M{"user_id": userID})
if err != nil {
c.JSON(500, gin.H{"error": err.Error()})
return
}
if result.DeletedCount == 0 {
c.JSON(404, gin.H{"error": "User not found"})
return
}
c.JSON(200, gin.H{"result": "success", "message": "User deleted successfully"})
}
func generateUniqueUserID() string {
return time.Now().Format("20060102150405")
}
func getNextFundID() (int, error) {
filter := bson.M{"_id": "fundid"}
update := bson.M{"$inc": bson.M{"sequence_value": 1}}
options := options.FindOneAndUpdate().SetUpsert(true).SetReturnDocument(options.After)
var result struct {
SequenceValue int `bson:"sequence_value"`
}
err := counterCollection.FindOneAndUpdate(context.TODO(), filter, update, options).Decode(&result)
if err != nil {
return 0, err
}
return result.SequenceValue, nil
}
func deleteFund(c *gin.Context) {
fundID := c.Param("fundID")
// Convert fundID from string to int
id, err := strconv.Atoi(fundID)
if err != nil {
c.JSON(400, gin.H{"error": "Invalid fund ID"})
return
}
result, err := collection.DeleteOne(context.TODO(), bson.M{"fund_id": id})
if err != nil {
c.JSON(500, gin.H{"error": err.Error()})
return
}
if result.DeletedCount == 0 {
c.JSON(404, gin.H{"error": "Fund not found"})
return
}
c.JSON(200, gin.H{"result": "success", "message": "Fund deleted successfully"})
}
func updateFund(c *gin.Context) {
fundID := c.Param("fundID")
// Convert fundID from string to int
id, err := strconv.Atoi(fundID)
if err != nil {
c.JSON(400, gin.H{"error": "Invalid fund ID"})
return
}
var updatedFund Fund
if err := c.ShouldBindJSON(&updatedFund); err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}
// Ensure the fund ID in the URL matches the one in the request body
if id != updatedFund.FundID {
c.JSON(400, gin.H{"error": "Fund ID in URL does not match the one in request body"})
return
}
filter := bson.M{"fund_id": id}
update := bson.M{"$set": updatedFund}
result, err := collection.UpdateOne(context.TODO(), filter, update)
if err != nil {
c.JSON(500, gin.H{"error": err.Error()})
return
}
if result.MatchedCount == 0 {
c.JSON(404, gin.H{"error": "Fund not found"})
return
}
c.JSON(200, gin.H{"result": "success", "message": "Fund updated successfully"})
}
func updateUser(c *gin.Context) {
userID := c.Param("userID")
var updatedUser User
if err := c.ShouldBindJSON(&updatedUser); err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}
// Ensure the user ID in the URL matches the one in the request body
if userID != updatedUser.UserID {
c.JSON(400, gin.H{"error": "User ID in URL does not match the one in request body"})
return
}
filter := bson.M{"user_id": userID}
update := bson.M{"$set": bson.M{
"username": updatedUser.Username,
"email": updatedUser.Email,
"first_name": updatedUser.FirstName,
"last_name": updatedUser.LastName,
"date_of_birth": updatedUser.DateOfBirth,
"phone_number": updatedUser.PhoneNumber,
}}
result, err := userCollection.UpdateOne(context.TODO(), filter, update)
if err != nil {
c.JSON(500, gin.H{"error": err.Error()})
return
}
if result.MatchedCount == 0 {
c.JSON(404, gin.H{"error": "User not found"})
return
}
c.JSON(200, gin.H{"result": "success", "message": "User updated successfully"})
}