aboutsummaryrefslogblamecommitdiffstats
path: root/internal/circle/handler.go
blob: c15d322f6672335c48babb227c82a8310377d833 (plain) (tree)
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442

























































































































































































































































































































































































































































                                                                                                                           
package circle

import (
	"log"

	"strconv"
	"time"

	auth "donetick.com/core/internal/authorization"
	"donetick.com/core/internal/chore"
	chRepo "donetick.com/core/internal/chore/repo"
	cModel "donetick.com/core/internal/circle/model"
	cRepo "donetick.com/core/internal/circle/repo"
	uModel "donetick.com/core/internal/user/model"
	uRepo "donetick.com/core/internal/user/repo"
	"donetick.com/core/logging"
	jwt "github.com/appleboy/gin-jwt/v2"
	"github.com/gin-gonic/gin"
)

type Handler struct {
	circleRepo *cRepo.CircleRepository
	userRepo   *uRepo.UserRepository
	choreRepo  *chRepo.ChoreRepository
}

func NewHandler(cr *cRepo.CircleRepository, ur *uRepo.UserRepository, c *chRepo.ChoreRepository) *Handler {
	return &Handler{
		circleRepo: cr,
		userRepo:   ur,
		choreRepo:  c,
	}
}

func (h *Handler) GetCircleMembers(c *gin.Context) {
	// Get the circle ID from the JWT
	log := logging.FromContext(c)
	currentUser, ok := auth.CurrentUser(c)
	if !ok {
		log.Error("Error getting current user")
		c.JSON(500, gin.H{
			"error": "Error getting current user",
		})
		return
	}

	// Get all the members of the circle
	members, err := h.circleRepo.GetCircleUsers(c, currentUser.CircleID)
	if err != nil {
		log.Error("Error getting circle members:", err)
		c.JSON(500, gin.H{
			"error": "Error getting circle members",
		})
		return
	}

	c.JSON(200, gin.H{
		"res": members,
	})
}

func (h *Handler) JoinCircle(c *gin.Context) {
	// Get the circle ID from the JWT
	log := logging.FromContext(c)
	log.Debug("handlder.go: JoinCircle")
	currentUser, ok := auth.CurrentUser(c)

	if !ok {
		c.JSON(500, gin.H{
			"error": "Error getting current user",
		})
		return
	}

	requestedCircleID := c.Query("invite_code")
	if requestedCircleID == "" {
		c.JSON(400, gin.H{
			"error": "Invalid request",
		})
		return
	}

	circle, err := h.circleRepo.GetCircleByInviteCode(c, requestedCircleID)

	if circle.ID == currentUser.CircleID {
		c.JSON(409, gin.H{
			"error": "You are already a member of this circle",
		})
		return
	}

	// Add the user to the circle
	err = h.circleRepo.AddUserToCircle(c, &cModel.UserCircle{
		CircleID: circle.ID,
		UserID:   currentUser.ID,
		Role:     "member",
		IsActive: false,
	})

	if err != nil {
		log.Error("Error adding user to circle:", err)
		c.JSON(500, gin.H{
			"error": "Error adding user to circle",
		})
		return
	}

	c.JSON(200, gin.H{
		"res": "User Requested to join circle successfully",
	})
}

func (h *Handler) LeaveCircle(c *gin.Context) {
	log := logging.FromContext(c)
	log.Debug("handler.go: LeaveCircle")
	currentUser, ok := auth.CurrentUser(c)
	if !ok {
		c.JSON(500, gin.H{
			"error": "Error getting current user",
		})
		return
	}
	rawCircleID := c.Query("circle_id")
	circleID, err := strconv.Atoi(rawCircleID)
	if err != nil {
		c.JSON(400, gin.H{
			"error": "Invalid request",
		})
		return
	}

	orginalCircleID, err := h.circleRepo.GetUserOriginalCircle(c, currentUser.ID)
	if err != nil {
		log.Error("Error getting user original circle:", err)
		c.JSON(500, gin.H{
			"error": "Error getting user original circle",
		})
		return
	}

	// START : HANDLE USER LEAVING CIRCLE
	// bulk update chores:
	if err := handleUserLeavingCircle(h, c, currentUser, orginalCircleID); err != nil {
		log.Error("Error handling user leaving circle:", err)
		c.JSON(500, gin.H{
			"error": "Error handling user leaving circle",
		})
		return
	}

	// END: HANDLE USER LEAVING CIRCLE

	err = h.circleRepo.LeaveCircleByUserID(c, circleID, currentUser.ID)
	if err != nil {
		log.Error("Error leaving circle:", err)
		c.JSON(500, gin.H{
			"error": "Error leaving circle",
		})
		return
	}

	if err := h.userRepo.UpdateUserCircle(c, currentUser.ID, orginalCircleID); err != nil {
		log.Error("Error updating user circle:", err)
		c.JSON(500, gin.H{
			"error": "Error updating user circle",
		})
		return
	}
	c.JSON(200, gin.H{
		"res": "User left circle successfully",
	})
}

func handleUserLeavingCircle(h *Handler, c *gin.Context, leavingUser *uModel.User, orginalCircleID int) error {
	userAssignedCircleChores, err := h.choreRepo.GetChores(c, leavingUser.CircleID, leavingUser.ID)
	if err != nil {
		return err
	}
	for _, ch := range userAssignedCircleChores {

		if ch.CreatedBy == leavingUser.ID && ch.AssignedTo != leavingUser.ID {
			ch.AssignedTo = leavingUser.ID
			ch.UpdatedAt = time.Now()
			ch.UpdatedBy = leavingUser.ID
			ch.CircleID = orginalCircleID
		} else if ch.CreatedBy != leavingUser.ID && ch.AssignedTo == leavingUser.ID {
			chore.RemoveAssigneeAndReassign(ch, leavingUser.ID)
		}

	}

	h.choreRepo.UpdateChores(c, userAssignedCircleChores)
	h.choreRepo.RemoveChoreAssigneeByCircleID(c, leavingUser.ID, leavingUser.CircleID)
	return nil
}

func (h *Handler) DeleteCircleMember(c *gin.Context) {
	log := logging.FromContext(c)
	log.Debug("handler.go: DeleteCircleMember")
	currentUser, ok := auth.CurrentUser(c)
	if !ok {
		c.JSON(500, gin.H{
			"error": "Error getting current user",
		})
		return
	}
	rawCircleID := c.Param("id")
	circleID, err := strconv.Atoi(rawCircleID)
	if err != nil {
		c.JSON(400, gin.H{
			"error": "Invalid request",
		})
		return
	}
	rawMemeberIDToDeleted := c.Query("member_id")
	memberIDToDeleted, err := strconv.Atoi(rawMemeberIDToDeleted)
	if err != nil {
		c.JSON(400, gin.H{
			"error": "Invalid request",
		})
		return
	}
	admins, err := h.circleRepo.GetCircleAdmins(c, circleID)
	if err != nil {
		log.Error("Error getting circle admins:", err)
		c.JSON(500, gin.H{
			"error": "Error getting circle admins",
		})
		return
	}
	isAdmin := false
	for _, admin := range admins {
		if admin.UserID == currentUser.ID {
			isAdmin = true
			break
		}
	}
	if !isAdmin {
		c.JSON(403, gin.H{
			"error": "You are not an admin of this circle",
		})
		return
	}
	orginalCircleID, err := h.circleRepo.GetUserOriginalCircle(c, memberIDToDeleted)
	if handleUserLeavingCircle(h, c, &uModel.User{ID: memberIDToDeleted, CircleID: circleID}, orginalCircleID) != nil {
		log.Error("Error handling user leaving circle:", err)
		c.JSON(500, gin.H{
			"error": "Error handling user leaving circle",
		})
		return
	}

	err = h.circleRepo.DeleteMemberByID(c, circleID, memberIDToDeleted)
	if err != nil {
		log.Error("Error deleting circle member:", err)
		c.JSON(500, gin.H{
			"error": "Error deleting circle member",
		})
		return
	}
	c.JSON(200, gin.H{
		"res": "User deleted from circle successfully",
	})
}

func (h *Handler) GetUserCircles(c *gin.Context) {
	log := logging.FromContext(c)
	currentUser, ok := auth.CurrentUser(c)
	if !ok {
		c.JSON(500, gin.H{
			"error": "Error getting current user",
		})
		return
	}

	circles, err := h.circleRepo.GetUserCircles(c, currentUser.ID)
	if err != nil {
		log.Error("Error getting user circles:", err)
		c.JSON(500, gin.H{
			"error": "Error getting user circles",
		})
		return
	}

	c.JSON(200, gin.H{
		"res": circles,
	})
}

func (h *Handler) GetPendingCircleMembers(c *gin.Context) {
	log := logging.FromContext(c)
	currentUser, ok := auth.CurrentUser(c)
	if !ok {
		c.JSON(500, gin.H{
			"error": "Error getting current user",
		})
		return
	}

	currentMemebers, err := h.circleRepo.GetCircleUsers(c, currentUser.CircleID)
	if err != nil {
		log.Error("Error getting circle members:", err)
		c.JSON(500, gin.H{
			"error": "Error getting circle members",
		})
		return
	}

	// confirm that the current user is an admin:
	isAdmin := false
	for _, member := range currentMemebers {
		if member.UserID == currentUser.ID && member.Role == "admin" {
			isAdmin = true
			break
		}
	}
	if !isAdmin {
		c.JSON(403, gin.H{
			"error": "You are not an admin of this circle",
		})
		return
	}

	members, err := h.circleRepo.GetPendingJoinRequests(c, currentUser.CircleID)
	if err != nil {
		log.Error("Error getting pending circle members:", err)
		c.JSON(500, gin.H{
			"error": "Error getting pending circle members",
		})
		return
	}

	c.JSON(200, gin.H{
		"res": members,
	})
}

func (h *Handler) AcceptJoinRequest(c *gin.Context) {
	log := logging.FromContext(c)
	currentUser, ok := auth.CurrentUser(c)
	if !ok {
		c.JSON(500, gin.H{
			"error": "Error getting current user",
		})
		return
	}

	rawRequestID := c.Query("requestId")
	requestID, err := strconv.Atoi(rawRequestID)
	if err != nil {
		c.JSON(400, gin.H{
			"error": "Invalid request",
		})
		return
	}

	currentMemebers, err := h.circleRepo.GetCircleUsers(c, currentUser.CircleID)
	if err != nil {
		log.Error("Error getting circle members:", err)
		c.JSON(500, gin.H{
			"error": "Error getting circle members",
		})
		return
	}

	// confirm that the current user is an admin:
	isAdmin := false
	for _, member := range currentMemebers {
		if member.UserID == currentUser.ID && member.Role == "admin" {
			isAdmin = true
			break
		}
	}
	if !isAdmin {
		c.JSON(403, gin.H{
			"error": "You are not an admin of this circle",
		})
		return
	}
	pendingRequests, err := h.circleRepo.GetPendingJoinRequests(c, currentUser.CircleID)
	if err != nil {
		log.Error("Error getting pending circle members:", err)
		c.JSON(500, gin.H{
			"error": "Error getting pending circle members",
		})
		return
	}
	isActiveRequest := false
	var requestedCircle *cModel.UserCircleDetail
	for _, request := range pendingRequests {
		if request.ID == requestID {
			requestedCircle = request
			isActiveRequest = true
			break
		}
	}
	if !isActiveRequest {
		c.JSON(400, gin.H{
			"error": "Invalid request",
		})
		return
	}

	err = h.circleRepo.AcceptJoinRequest(c, currentUser.CircleID, requestID)
	if err != nil {
		log.Error("Error accepting join request:", err)
		c.JSON(500, gin.H{
			"error": "Error accepting join request",
		})
		return
	}

	if err := h.userRepo.UpdateUserCircle(c, requestedCircle.UserID, currentUser.CircleID); err != nil {
		log.Error("Error updating user circle:", err)
		c.JSON(500, gin.H{
			"error": "Error updating user circle",
		})
		return
	}

	c.JSON(200, gin.H{
		"res": "Join request accepted successfully",
	})
}

func Routes(router *gin.Engine, h *Handler, auth *jwt.GinJWTMiddleware) {
	log.Println("Registering routes")

	circleRoutes := router.Group("circles")
	circleRoutes.Use(auth.MiddlewareFunc())
	{
		circleRoutes.GET("/members", h.GetCircleMembers)
		circleRoutes.GET("/members/requests", h.GetPendingCircleMembers)
		circleRoutes.PUT("/members/requests/accept", h.AcceptJoinRequest)
		circleRoutes.GET("/", h.GetUserCircles)
		circleRoutes.POST("/join", h.JoinCircle)
		circleRoutes.DELETE("/leave", h.LeaveCircle)
		circleRoutes.DELETE("/:id/members/delete", h.DeleteCircleMember)

	}

}