82 lines
2.5 KiB
Go
82 lines
2.5 KiB
Go
// internal/controllers/notification_controller.go
|
|
package controllers
|
|
|
|
import (
|
|
"lost-and-found/internal/models"
|
|
"lost-and-found/internal/services"
|
|
"lost-and-found/internal/utils"
|
|
"net/http"
|
|
"strconv"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type NotificationController struct {
|
|
notificationService *services.NotificationService
|
|
}
|
|
|
|
func NewNotificationController(db *gorm.DB) *NotificationController {
|
|
return &NotificationController{
|
|
notificationService: services.NewNotificationService(db),
|
|
}
|
|
}
|
|
|
|
// GetUserNotifications gets notifications for current user
|
|
// GET /api/notifications
|
|
func (c *NotificationController) GetUserNotifications(ctx *gin.Context) {
|
|
userObj, _ := ctx.Get("user")
|
|
user := userObj.(*models.User)
|
|
|
|
page, _ := strconv.Atoi(ctx.DefaultQuery("page", "1"))
|
|
limit, _ := strconv.Atoi(ctx.DefaultQuery("limit", "10"))
|
|
onlyUnread := ctx.Query("unread") == "true"
|
|
|
|
notifications, total, err := c.notificationService.GetUserNotifications(user.ID, page, limit, onlyUnread)
|
|
if err != nil {
|
|
utils.ErrorResponse(ctx, http.StatusInternalServerError, "Failed to get notifications", err.Error())
|
|
return
|
|
}
|
|
|
|
count, _ := c.notificationService.CountUnread(user.ID)
|
|
|
|
utils.SuccessResponse(ctx, http.StatusOK, "Notifications retrieved", gin.H{
|
|
"notifications": notifications,
|
|
"total": total,
|
|
"unread_count": count,
|
|
})
|
|
}
|
|
|
|
// MarkAsRead marks a notification as read
|
|
// PATCH /api/notifications/:id/read
|
|
func (c *NotificationController) MarkAsRead(ctx *gin.Context) {
|
|
userObj, _ := ctx.Get("user")
|
|
user := userObj.(*models.User)
|
|
|
|
id, err := strconv.ParseUint(ctx.Param("id"), 10, 32)
|
|
if err != nil {
|
|
utils.ErrorResponse(ctx, http.StatusBadRequest, "Invalid ID", err.Error())
|
|
return
|
|
}
|
|
|
|
if err := c.notificationService.MarkAsRead(user.ID, uint(id)); err != nil {
|
|
utils.ErrorResponse(ctx, http.StatusBadRequest, "Failed to mark as read", err.Error())
|
|
return
|
|
}
|
|
|
|
utils.SuccessResponse(ctx, http.StatusOK, "Notification marked as read", nil)
|
|
}
|
|
|
|
// MarkAllAsRead marks all notifications as read
|
|
// PATCH /api/notifications/read-all
|
|
func (c *NotificationController) MarkAllAsRead(ctx *gin.Context) {
|
|
userObj, _ := ctx.Get("user")
|
|
user := userObj.(*models.User)
|
|
|
|
if err := c.notificationService.MarkAllAsRead(user.ID); err != nil {
|
|
utils.ErrorResponse(ctx, http.StatusInternalServerError, "Failed to mark all as read", err.Error())
|
|
return
|
|
}
|
|
|
|
utils.SuccessResponse(ctx, http.StatusOK, "All notifications marked as read", nil)
|
|
} |