RezinaLMS-BackEnd/internal/web_server/handlers/notification_handler.go

2316 lines
84 KiB
Go

package handlers
import (
"Rezina-Backend/internal/domain"
"Rezina-Backend/internal/pkgs/helpers"
notificationservice "Rezina-Backend/internal/services/notification"
"Rezina-Backend/internal/web_server/ws"
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"strconv"
"strings"
"time"
"github.com/gofiber/fiber/v2"
"github.com/gorilla/websocket"
"github.com/jackc/pgx/v5/pgconn"
"github.com/resend/resend-go/v2"
"go.uber.org/zap"
)
func notificationRequestContext(c *fiber.Ctx) context.Context {
receiver := domain.ReceiverTypeUser
if c.Locals("api_audience") == "admin" {
receiver = domain.ReceiverTypeTeamMember
}
userID, _ := c.Locals("user_id").(int64)
return domain.WithNotificationScope(c.Context(), userID, receiver)
}
// ConnectSocket godoc
// @Summary Connect Socket
// @Tags ws
// @Param token query string true "Access token"
// @Router /api/v1/admin/ws/connect [get]
// @Router /api/v1/ws/connect [get]
// @Success 101 {string} string "WebSocket protocol upgrade; subsequent messages are notification events"
// @Failure 401 {string} string "Authentication failed"
func (h *Handler) ConnectSocket(c *fiber.Ctx) error {
userID, ok := c.Locals("userID").(int64)
if !ok || userID == 0 {
h.mongoLoggerSvc.Info("Invalid user ID in context",
zap.Int64("userID", userID),
zap.Int("status_code", fiber.StatusUnauthorized),
zap.Time("timestamp", time.Now()),
)
return fiber.NewError(fiber.StatusUnauthorized, "Invalid user identification")
}
receiverType := domain.ReceiverTypeUser
if c.Locals("api_audience") == "admin" {
receiverType = domain.ReceiverTypeTeamMember
}
// Convert fasthttp request to net/http request for gorilla upgrader
stdReq := &http.Request{
Method: http.MethodGet,
Header: make(http.Header),
}
c.Context().Request.Header.VisitAll(func(key, value []byte) {
stdReq.Header.Set(string(key), string(value))
})
stdReq.Host = string(c.Context().Host())
stdReq.RequestURI = string(c.Context().RequestURI())
// Hijack the underlying net.Conn from fasthttp
// The hijack callback runs after the handler returns, so we must not block.
c.Context().HijackSetNoResponse(true)
c.Context().Hijack(func(netConn net.Conn) {
// Create a hijackable response writer around the raw connection
hjRW := &hijackResponseWriter{
conn: netConn,
brw: bufio.NewReadWriter(bufio.NewReader(netConn), bufio.NewWriter(netConn)),
h: make(http.Header),
}
wsConn, err := ws.Upgrader.Upgrade(hjRW, stdReq, nil)
if err != nil {
h.mongoLoggerSvc.Error("WebSocket upgrade failed",
zap.Int64("userID", userID),
zap.Error(err),
zap.Time("timestamp", time.Now()),
)
netConn.Close()
return
}
client := &ws.Client{
ReceiverType: receiverType,
Conn: wsConn,
RecipientID: userID,
}
h.notificationSvc.Hub.Register <- client
defer func() {
h.notificationSvc.Hub.Unregister <- client
wsConn.Close()
}()
h.mongoLoggerSvc.Info("WebSocket connection established",
zap.Int64("userID", userID),
zap.Time("timestamp", time.Now()),
)
for {
_, _, err := wsConn.ReadMessage()
if err != nil {
if websocket.IsCloseError(err, websocket.CloseNormalClosure, websocket.CloseGoingAway) {
h.mongoLoggerSvc.Info("WebSocket closed normally",
zap.Int64("userID", userID),
zap.Time("timestamp", time.Now()),
)
} else {
h.mongoLoggerSvc.Info("Unexpected WebSocket closure",
zap.Int64("userID", userID),
zap.Error(err),
zap.Time("timestamp", time.Now()),
)
}
break
}
}
})
return nil
}
// hijackResponseWriter implements http.ResponseWriter and http.Hijacker
// so gorilla/websocket can upgrade over a raw net.Conn.
type hijackResponseWriter struct {
conn net.Conn
brw *bufio.ReadWriter
h http.Header
}
func (w *hijackResponseWriter) Header() http.Header { return w.h }
func (w *hijackResponseWriter) WriteHeader(statusCode int) {}
func (w *hijackResponseWriter) Write(b []byte) (int, error) { return w.conn.Write(b) }
func (w *hijackResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
return w.conn, w.brw, nil
}
// GetNotificationByID godoc
// @Summary Get in-app notification by ID
// @Description Returns a single in-app notification. Users may only fetch their own notifications unless they have list-all access.
// @Tags notifications
// @Produce json
// @Param id path int true "Notification ID"
// @Success 200 {object} domain.Response{data=domain.Notification}
// @Failure 400 {object} domain.ErrorResponse
// @Failure 403 {object} domain.ErrorResponse
// @Failure 404 {object} domain.ErrorResponse
// @Failure 500 {object} domain.ErrorResponse
// @Router /api/v1/admin/notifications/{id} [get]
// @Router /api/v1/notifications/{id} [get]
// @Security Bearer
// @Failure 401 {string} string "Missing, invalid, or expired Bearer token"
func (h *Handler) GetNotificationByID(c *fiber.Ctx) error {
idStr := c.Params("id")
id, err := strconv.ParseInt(idStr, 10, 64)
if err != nil || id <= 0 {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid notification ID",
Error: err.Error(),
})
}
userID, ok := c.Locals("user_id").(int64)
if !ok || userID == 0 {
return c.Status(fiber.StatusUnauthorized).JSON(domain.ErrorResponse{
Message: "Invalid user identification",
Error: "User ID not found in context",
})
}
role, _ := c.Locals("role").(domain.Role)
allowAll := h.rbacSvc.HasPermission(string(role), "notifications.list_all")
if c.Locals("api_audience") == "client" {
allowAll = false
}
notification, err := h.notificationSvc.GetNotificationByID(notificationRequestContext(c), id, userID, allowAll)
if err != nil {
switch {
case errors.Is(err, notificationservice.ErrNotificationNotFound):
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
Message: "Notification not found",
Error: err.Error(),
})
case errors.Is(err, notificationservice.ErrNotificationForbidden):
return c.Status(fiber.StatusForbidden).JSON(domain.ErrorResponse{
Message: "Notification access denied",
Error: err.Error(),
})
default:
h.mongoLoggerSvc.Error("[NotificationHandler.GetNotificationByID] Failed to get notification",
zap.Int64("notificationID", id),
zap.Int64("userID", userID),
zap.Error(err),
zap.Time("timestamp", time.Now()),
)
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to get notification",
Error: err.Error(),
})
}
}
return c.Status(fiber.StatusOK).JSON(domain.Response{
Message: "Notification retrieved successfully",
Success: true,
StatusCode: fiber.StatusOK,
Data: notification,
})
}
// MarkNotificationAsRead godoc
// @Summary Mark Notification As Read
// @Tags notifications
// @Router /api/v1/admin/notifications/{id}/read [patch]
// @Router /api/v1/notifications/{id}/read [patch]
// @Security Bearer
// @Param id path int64 true "Id"
// @Success 200 {object} domain.Response{data=domain.Notification}
// @Produce json
// @Failure 401 {string} string "Missing, invalid, or expired Bearer token"
// @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation"
// @Failure 400 {object} domain.ErrorResponse "Invalid request"
// @Failure 500 {object} domain.ErrorResponse "Internal server error"
func (h *Handler) MarkNotificationAsRead(c *fiber.Ctx) error {
idStr := c.Params("id")
id, err := strconv.ParseInt(idStr, 10, 64)
if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid notification ID",
Error: err.Error(),
})
}
notification, err := h.notificationSvc.MarkNotificationAsRead(notificationRequestContext(c), id)
if err != nil {
h.mongoLoggerSvc.Error("[NotificationHandler.MarkNotificationAsRead] Failed to mark notification as read",
zap.Int64("notificationID", id),
zap.Int("status_code", fiber.StatusInternalServerError),
zap.Error(err),
zap.Time("timestamp", time.Now()),
)
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to mark notification as read",
Error: err.Error(),
})
}
h.recordActivity(c, domain.ActionNotificationUpdated, domain.ResourceNotification, &id, fmt.Sprintf("Marked notification %d as read", id), nil)
return c.Status(fiber.StatusOK).JSON(domain.Response{
Message: "Notification marked as read",
Success: true,
StatusCode: fiber.StatusOK,
Data: notification,
})
}
// MarkAllNotificationsAsRead godoc
// @Summary Mark All Notifications As Read
// @Tags notifications
// @Router /api/v1/admin/notifications/mark-all-read [post]
// @Router /api/v1/notifications/mark-all-read [post]
// @Security Bearer
// @Success 200 {object} MessageResponse
// @Produce json
// @Failure 401 {string} string "Missing, invalid, or expired Bearer token"
// @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation"
// @Failure 500 {object} domain.ErrorResponse "Internal server error"
func (h *Handler) MarkAllNotificationsAsRead(c *fiber.Ctx) error {
userID, ok := c.Locals("user_id").(int64)
if !ok || userID == 0 {
return c.Status(fiber.StatusUnauthorized).JSON(domain.ErrorResponse{
Message: "Invalid user identification",
Error: "User ID not found in context",
})
}
if err := h.notificationSvc.MarkAllUserNotificationsAsRead(notificationRequestContext(c), userID); err != nil {
h.mongoLoggerSvc.Error("[NotificationHandler.MarkAllNotificationsAsRead] Failed to mark all notifications as read",
zap.Int64("userID", userID),
zap.Int("status_code", fiber.StatusInternalServerError),
zap.Error(err),
zap.Time("timestamp", time.Now()),
)
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to mark all notifications as read",
Error: err.Error(),
})
}
h.recordActivity(c, domain.ActionNotificationUpdated, domain.ResourceNotification, &userID, fmt.Sprintf("Marked all notifications as read for user %d", userID), nil)
return c.Status(fiber.StatusOK).JSON(domain.Response{
Message: "All notifications marked as read",
Success: true,
StatusCode: fiber.StatusOK,
})
}
// MarkNotificationAsUnread godoc
// @Summary Mark Notification As Unread
// @Tags notifications
// @Router /api/v1/admin/notifications/{id}/unread [patch]
// @Router /api/v1/notifications/{id}/unread [patch]
// @Security Bearer
// @Param id path int64 true "Id"
// @Success 200 {object} domain.Response{data=domain.Notification}
// @Produce json
// @Failure 401 {string} string "Missing, invalid, or expired Bearer token"
// @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation"
// @Failure 400 {object} domain.ErrorResponse "Invalid request"
// @Failure 500 {object} domain.ErrorResponse "Internal server error"
func (h *Handler) MarkNotificationAsUnread(c *fiber.Ctx) error {
idStr := c.Params("id")
id, err := strconv.ParseInt(idStr, 10, 64)
if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid notification ID",
Error: err.Error(),
})
}
notification, err := h.notificationSvc.MarkNotificationAsUnread(notificationRequestContext(c), id)
if err != nil {
h.mongoLoggerSvc.Error("[NotificationHandler.MarkNotificationAsUnread] Failed to mark notification as unread",
zap.Int64("notificationID", id),
zap.Int("status_code", fiber.StatusInternalServerError),
zap.Error(err),
zap.Time("timestamp", time.Now()),
)
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to mark notification as unread",
Error: err.Error(),
})
}
h.recordActivity(c, domain.ActionNotificationUpdated, domain.ResourceNotification, &id, fmt.Sprintf("Marked notification %d as unread", id), nil)
return c.Status(fiber.StatusOK).JSON(domain.Response{
Message: "Notification marked as unread",
Success: true,
StatusCode: fiber.StatusOK,
Data: notification,
})
}
// MarkAllNotificationsAsUnread godoc
// @Summary Mark All Notifications As Unread
// @Tags notifications
// @Router /api/v1/admin/notifications/mark-all-unread [post]
// @Router /api/v1/notifications/mark-all-unread [post]
// @Security Bearer
// @Success 200 {object} MessageResponse
// @Produce json
// @Failure 401 {string} string "Missing, invalid, or expired Bearer token"
// @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation"
// @Failure 500 {object} domain.ErrorResponse "Internal server error"
func (h *Handler) MarkAllNotificationsAsUnread(c *fiber.Ctx) error {
userID, ok := c.Locals("user_id").(int64)
if !ok || userID == 0 {
return c.Status(fiber.StatusUnauthorized).JSON(domain.ErrorResponse{
Message: "Invalid user identification",
Error: "User ID not found in context",
})
}
if err := h.notificationSvc.MarkAllUserNotificationsAsUnread(notificationRequestContext(c), userID); err != nil {
h.mongoLoggerSvc.Error("[NotificationHandler.MarkAllNotificationsAsUnread] Failed to mark all notifications as unread",
zap.Int64("userID", userID),
zap.Int("status_code", fiber.StatusInternalServerError),
zap.Error(err),
zap.Time("timestamp", time.Now()),
)
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to mark all notifications as unread",
Error: err.Error(),
})
}
h.recordActivity(c, domain.ActionNotificationUpdated, domain.ResourceNotification, &userID, fmt.Sprintf("Marked all notifications as unread for user %d", userID), nil)
return c.Status(fiber.StatusOK).JSON(domain.Response{
Message: "All notifications marked as unread",
Success: true,
StatusCode: fiber.StatusOK,
})
}
// DeleteUserNotifications godoc
// @Summary Delete User Notifications
// @Tags notifications
// @Router /api/v1/admin/notifications [delete]
// @Router /api/v1/notifications [delete]
// @Security Bearer
// @Success 200 {object} MessageResponse
// @Produce json
// @Failure 401 {string} string "Missing, invalid, or expired Bearer token"
// @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation"
// @Failure 500 {object} domain.ErrorResponse "Internal server error"
func (h *Handler) DeleteUserNotifications(c *fiber.Ctx) error {
userID, ok := c.Locals("user_id").(int64)
if !ok || userID == 0 {
return c.Status(fiber.StatusUnauthorized).JSON(domain.ErrorResponse{
Message: "Invalid user identification",
Error: "User ID not found in context",
})
}
if err := h.notificationSvc.DeleteUserNotifications(notificationRequestContext(c), userID); err != nil {
h.mongoLoggerSvc.Error("[NotificationHandler.DeleteUserNotifications] Failed to delete notifications",
zap.Int64("userID", userID),
zap.Int("status_code", fiber.StatusInternalServerError),
zap.Error(err),
zap.Time("timestamp", time.Now()),
)
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to delete notifications",
Error: err.Error(),
})
}
h.recordActivity(c, domain.ActionNotificationDeleted, domain.ResourceNotification, &userID, fmt.Sprintf("Deleted all notifications for user ID: %d", userID), nil)
return c.Status(fiber.StatusOK).JSON(domain.Response{
Message: "All notifications deleted successfully",
Success: true,
StatusCode: fiber.StatusOK,
})
}
// DeleteInAppNotification godoc
// @Summary Delete a single in-app notification
// @Description Deletes one in-app notification owned by the authenticated user.
// @Tags notifications
// @Produce json
// @Param id path int true "Notification ID"
// @Success 200 {object} MessageResponse
// @Failure 400 {object} domain.ErrorResponse
// @Failure 404 {object} domain.ErrorResponse
// @Failure 500 {object} domain.ErrorResponse
// @Router /api/v1/admin/notifications/{id} [delete]
// @Router /api/v1/notifications/{id} [delete]
// @Security Bearer
// @Failure 401 {string} string "Missing, invalid, or expired Bearer token"
// @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation"
func (h *Handler) DeleteInAppNotification(c *fiber.Ctx) error {
idStr := c.Params("id")
id, err := strconv.ParseInt(idStr, 10, 64)
if err != nil || id <= 0 {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid notification ID",
Error: err.Error(),
})
}
userID, ok := c.Locals("user_id").(int64)
if !ok || userID == 0 {
return c.Status(fiber.StatusUnauthorized).JSON(domain.ErrorResponse{
Message: "Invalid user identification",
Error: "User ID not found in context",
})
}
if err := h.notificationSvc.DeleteUserInAppNotification(notificationRequestContext(c), id, userID); err != nil {
switch {
case errors.Is(err, notificationservice.ErrNotificationNotFound):
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
Message: "In-app notification not found",
Error: err.Error(),
})
default:
h.mongoLoggerSvc.Error("[NotificationHandler.DeleteInAppNotification] Failed to delete in-app notification",
zap.Int64("notificationID", id),
zap.Int64("userID", userID),
zap.Error(err),
zap.Time("timestamp", time.Now()),
)
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to delete in-app notification",
Error: err.Error(),
})
}
}
h.recordActivity(c, domain.ActionNotificationDeleted, domain.ResourceNotification, &id, fmt.Sprintf("Deleted in-app notification ID: %d", id), nil)
return c.Status(fiber.StatusOK).JSON(domain.Response{
Message: "In-app notification deleted successfully",
Success: true,
StatusCode: fiber.StatusOK,
})
}
// DeleteInAppNotifications godoc
// @Summary Delete multiple in-app notifications
// @Description Deletes in-app notifications by ID for the authenticated user. Non-matching IDs are ignored.
// @Tags notifications
// @Accept json
// @Produce json
// @Param body body object true "Notification IDs" example({"ids":[1,2,3]})
// @Success 200 {object} domain.Response{data=DeleteInAppNotificationsData}
// @Failure 400 {object} domain.ErrorResponse
// @Failure 500 {object} domain.ErrorResponse
// @Router /api/v1/admin/notifications/delete-in-app [post]
// @Router /api/v1/notifications/delete-in-app [post]
// @Security Bearer
// @Failure 401 {string} string "Missing, invalid, or expired Bearer token"
// @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation"
func (h *Handler) DeleteInAppNotifications(c *fiber.Ctx) error {
type request struct {
IDs []int64 `json:"ids"`
}
userID, ok := c.Locals("user_id").(int64)
if !ok || userID == 0 {
return c.Status(fiber.StatusUnauthorized).JSON(domain.ErrorResponse{
Message: "Invalid user identification",
Error: "User ID not found in context",
})
}
var req request
if err := c.BodyParser(&req); err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid request body",
Error: err.Error(),
})
}
if len(req.IDs) == 0 {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "At least one notification ID is required",
Error: "ids must contain at least one item",
})
}
deletedCount, err := h.notificationSvc.DeleteUserInAppNotifications(notificationRequestContext(c), userID, req.IDs)
if err != nil {
h.mongoLoggerSvc.Error("[NotificationHandler.DeleteInAppNotifications] Failed to delete in-app notifications",
zap.Int64("userID", userID),
zap.Int("idCount", len(req.IDs)),
zap.Error(err),
zap.Time("timestamp", time.Now()),
)
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to delete in-app notifications",
Error: err.Error(),
})
}
deleteMeta, _ := json.Marshal(map[string]interface{}{
"deleted_count": deletedCount,
"requested_ids": len(req.IDs),
})
h.recordActivity(c, domain.ActionNotificationDeleted, domain.ResourceNotification, nil, fmt.Sprintf("Deleted %d in-app notifications", deletedCount), deleteMeta)
return c.Status(fiber.StatusOK).JSON(domain.Response{
Success: true,
StatusCode: fiber.StatusOK,
Data: fiber.Map{
"deleted_count": deletedCount,
"requested_ids": len(req.IDs),
},
})
}
// CreateAndSendNotification godoc
// @Summary Create And Send Notification
// @Tags notifications
// @Router /api/v1/admin/notifications/create [post]
// @Security Bearer
// @Accept json
// @Param body body handlers.CreateAndSendNotification.Request true "Notification recipient and delivery settings"
// @Success 201 {object} NotificationDispatchResponse
// @Produce json
// @Failure 401 {string} string "Missing, invalid, or expired Bearer token"
// @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation"
// @Failure 400 {string} string "Invalid request"
// @Failure 500 {string} string "Internal server error"
func (h *Handler) CreateAndSendNotification(c *fiber.Ctx) error {
type Request struct {
RecipientID int64 `json:"recipient_id" validate:"required_if=DeliveryScheme single"`
Type domain.NotificationType `json:"type" validate:"required"`
Level domain.NotificationLevel `json:"level" validate:"required"`
ErrorSeverity *domain.NotificationErrorSeverity `json:"error_severity"`
Reciever domain.NotificationRecieverSide `json:"reciever" validate:"required"`
DeliveryScheme domain.NotificationDeliveryScheme `json:"delivery_scheme" validate:"required"`
DeliveryChannel domain.DeliveryChannel `json:"delivery_channel" validate:"required"`
Payload domain.NotificationPayload `json:"payload" validate:"required"`
Priority int `json:"priority"`
Metadata json.RawMessage `json:"metadata,omitempty"`
}
var req Request
if err := c.BodyParser(&req); err != nil {
h.mongoLoggerSvc.Info("[NotificationSvc.CreateAndSendNotification] Failed to parse request body",
zap.Int("status_code", fiber.StatusBadRequest),
zap.Error(err),
zap.Time("timestamp", time.Now()),
)
return fiber.NewError(fiber.StatusBadRequest, "Invalid request body")
}
// userID, ok := c.Locals("userID").(int64)
// if !ok || userID == 0 {
// h.logger.Error("[NotificationSvc.CreateAndSendNotification] Invalid user ID in context")
// return fiber.NewError(fiber.StatusUnauthorized, "Invalid user identification")
// }
switch req.DeliveryScheme {
case domain.NotificationDeliverySchemeSingle:
// if req.Reciever == domain.NotificationRecieverSideCustomer {
// h.logger.Warn("[NotificationSvc.CreateAndSendNotification] Unauthorized attempt to send notification", "recipientID", req.RecipientID)
// return fiber.NewError(fiber.StatusForbidden, "Unauthorized to send notification to this recipient")
// }
errorSeverity := domain.NotificationErrorSeverityMedium
if req.ErrorSeverity != nil {
errorSeverity = *req.ErrorSeverity
}
notification := &domain.Notification{
ID: "",
RecipientID: req.RecipientID,
ReceiverType: domain.ReceiverTypeFromReciever(req.Reciever),
Type: req.Type,
Level: req.Level,
ErrorSeverity: errorSeverity,
Reciever: req.Reciever,
IsRead: false,
DeliveryStatus: domain.DeliveryStatusPending,
DeliveryChannel: req.DeliveryChannel,
Payload: req.Payload,
Priority: req.Priority,
Metadata: req.Metadata,
}
if err := h.notificationSvc.SendNotification(context.Background(), notification); err != nil {
h.mongoLoggerSvc.Error("[NotificationSvc.CreateAndSendNotification] Failed to send single notification",
zap.Int64("recipientID", req.RecipientID),
zap.Int("status_code", fiber.StatusInternalServerError),
zap.Error(err),
zap.Time("timestamp", time.Now()),
)
return fiber.NewError(fiber.StatusInternalServerError, "Failed to send notification:"+err.Error())
}
h.mongoLoggerSvc.Info("[NotificationSvc.CreateAndSendNotification] Single notification sent successfully",
zap.Int64("recipientID", req.RecipientID),
zap.String("type", string(req.Type)),
zap.Time("timestamp", time.Now()),
)
singleMeta, _ := json.Marshal(map[string]interface{}{
"notification_id": notification.ID,
"recipient_id": req.RecipientID,
"type": req.Type,
"channel": req.DeliveryChannel,
})
h.recordActivity(c, domain.ActionNotificationCreated, domain.ResourceNotification, nil, "Single notification sent", singleMeta)
return c.Status(fiber.StatusCreated).JSON(fiber.Map{"message": "Single notification sent successfully", "notification_id": notification.ID})
case domain.NotificationDeliverySchemeBulk:
recipients, _, err := h.userSvc.GetAllUsers(context.Background(), domain.UserFilter{
Role: string(req.Reciever),
})
if err != nil {
h.mongoLoggerSvc.Error("[NotificationSvc.CreateAndSendNotification] Failed to fetch recipients for bulk notification",
zap.Int64("RecipientID", req.RecipientID),
zap.String("Reciever", string(req.Reciever)),
zap.Int("status_code", fiber.StatusInternalServerError),
zap.Error(err),
zap.Time("timestamp", time.Now()),
)
return fiber.NewError(fiber.StatusInternalServerError, "Failed to fetch recipients:"+err.Error())
}
notificationIDs := make([]string, 0, len(recipients))
for _, user := range recipients {
errorSeverity := domain.NotificationErrorSeverityMedium
if req.ErrorSeverity != nil {
errorSeverity = *req.ErrorSeverity
}
notification := &domain.Notification{
ID: "",
RecipientID: user.ID,
ReceiverType: domain.ReceiverTypeFromReciever(req.Reciever),
Type: req.Type,
Level: req.Level,
ErrorSeverity: errorSeverity,
Reciever: req.Reciever,
IsRead: false,
DeliveryStatus: domain.DeliveryStatusPending,
DeliveryChannel: req.DeliveryChannel,
Payload: req.Payload,
Priority: req.Priority,
Metadata: req.Metadata,
}
if err := h.notificationSvc.SendNotification(context.Background(), notification); err != nil {
h.mongoLoggerSvc.Error("[NotificationSvc.CreateAndSendNotification] Failed to send bulk notification",
zap.Int64("UserID", user.ID),
zap.Error(err),
zap.Time("timestamp", time.Now()),
)
continue
}
notificationIDs = append(notificationIDs, notification.ID)
}
h.mongoLoggerSvc.Error("[NotificationSvc.CreateAndSendNotification] Bulk notification sent successfully",
zap.Int("recipient_count", len(recipients)),
zap.String("type", string(req.Type)),
zap.Int("status_code", fiber.StatusCreated),
zap.Error(err),
zap.Time("timestamp", time.Now()),
)
bulkMeta, _ := json.Marshal(map[string]interface{}{
"recipient_count": len(recipients),
"notification_ids": notificationIDs,
"type": req.Type,
"channel": req.DeliveryChannel,
})
h.recordActivity(c, domain.ActionNotificationBulkSent, domain.ResourceNotification, nil, fmt.Sprintf("Bulk notification sent to %d recipients", len(recipients)), bulkMeta)
return c.Status(fiber.StatusCreated).JSON(fiber.Map{
"message": "Bulk notification sent successfully",
"recipient_count": len(recipients),
"notification_ids": notificationIDs,
})
default:
h.mongoLoggerSvc.Info("[NotificationSvc.CreateAndSendNotification] Invalid delivery scheme",
zap.String("delivery_scheme", string(req.DeliveryScheme)),
zap.Int("status_code", fiber.StatusBadRequest),
zap.Time("timestamp", time.Now()),
)
return fiber.NewError(fiber.StatusBadRequest, "Invalid delivery scheme")
}
}
// GetUserNotification godoc
// @Summary Get User Notification
// @Tags notifications
// @Router /api/v1/admin/notifications [get]
// @Router /api/v1/notifications [get]
// @Security Bearer
// @Param limit query int false "Limit" default(10)
// @Param offset query int false "Offset" default(0) minimum(0)
// @Success 200 {object} GetUserNotificationResponse
// @Produce json
// @Failure 401 {string} string "Missing, invalid, or expired Bearer token"
// @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation"
// @Failure 400 {string} string "Invalid request"
// @Failure 500 {string} string "Internal server error"
func (h *Handler) GetUserNotification(c *fiber.Ctx) error {
limitStr := c.Query("limit", "10")
offsetStr := c.Query("offset", "0")
// Convert limit and offset to integers
limit, err := strconv.Atoi(limitStr)
if err != nil || limit <= 0 {
h.mongoLoggerSvc.Info("[NotificationSvc.GetUserNotification] Invalid limit value",
zap.String("limit", limitStr),
zap.Int("status_code", fiber.StatusBadRequest),
zap.Error(err),
zap.Time("timestamp", time.Now()),
)
return fiber.NewError(fiber.StatusBadRequest, "Invalid limit value")
}
offset, err := strconv.Atoi(offsetStr)
if err != nil || offset < 0 {
h.mongoLoggerSvc.Info("[NotificationSvc.GetUserNotification] Invalid offset value",
zap.String("offset", offsetStr),
zap.Int("status_code", fiber.StatusBadRequest),
zap.Error(err),
zap.Time("timestamp", time.Now()),
)
return fiber.NewError(fiber.StatusBadRequest, "Invalid offset value")
}
userID, ok := c.Locals("user_id").(int64)
if !ok || userID == 0 {
h.mongoLoggerSvc.Error("[NotificationSvc.GetUserNotification] Invalid user ID in context",
zap.Int64("userID", userID),
zap.Int("status_code", fiber.StatusInternalServerError),
zap.Error(err),
zap.Time("timestamp", time.Now()),
)
return fiber.NewError(fiber.StatusInternalServerError, "Invalid user identification")
}
notifications, total, err := h.notificationSvc.GetUserNotifications(notificationRequestContext(c), userID, limit, offset)
if err != nil {
h.mongoLoggerSvc.Error("[NotificationSvc.GetUserNotification] Failed to fetch notifications",
zap.Int64("userID", userID),
zap.Int("status_code", fiber.StatusInternalServerError),
zap.Error(err),
zap.Time("timestamp", time.Now()),
)
return fiber.NewError(fiber.StatusInternalServerError, "Failed to fetch notifications:"+err.Error())
}
return c.Status(fiber.StatusOK).JSON(fiber.Map{
"notifications": notifications,
"total_count": total,
"limit": limit,
"offset": offset,
})
}
// func (h *Handler) GetAllRecipientIDs(ctx context.Context, receiver domain.NotificationRecieverSide) ([]int64, error) {
// return h.notificationSvc.ListRecipientIDs(ctx, receiver)
// }
// CountUnreadNotifications godoc
// @Summary Count Unread Notifications
// @Tags notifications
// @Router /api/v1/admin/notifications/unread [get]
// @Router /api/v1/notifications/unread [get]
// @Security Bearer
// @Success 200 {object} CountUnreadNotificationsResponse
// @Produce json
// @Failure 401 {string} string "Missing, invalid, or expired Bearer token"
// @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation"
// @Failure 500 {string} string "Internal server error"
func (h *Handler) CountUnreadNotifications(c *fiber.Ctx) error {
userID, ok := c.Locals("user_id").(int64)
if !ok || userID == 0 {
h.mongoLoggerSvc.Error("NotificationSvc.GetNotifications] Invalid user ID in context",
zap.Int64("userID", userID),
zap.Int("status_code", fiber.StatusInternalServerError),
zap.Time("timestamp", time.Now()),
)
return fiber.NewError(fiber.StatusInternalServerError, "Invalid user identification")
}
total, err := h.notificationSvc.CountUnreadNotifications(notificationRequestContext(c), userID)
if err != nil {
h.mongoLoggerSvc.Error("[NotificationSvc.CountUnreadNotifications] Failed to fetch unread notification count",
zap.Int64("userID", userID),
zap.Int("status_code", fiber.StatusInternalServerError),
zap.Error(err),
zap.Time("timestamp", time.Now()),
)
return fiber.NewError(fiber.StatusInternalServerError, "Failed to fetch notifications:"+err.Error())
}
return c.Status(fiber.StatusOK).JSON(fiber.Map{
"unread": total,
})
}
// GetAllNotifications godoc
// @Summary Get All Notifications
// @Tags notifications
// @Router /api/v1/admin/notifications/all [get]
// @Security Bearer
// @Param limit query int false "Limit" default(10)
// @Param page query int false "Page" default(1)
// @Param channel query string false "Channel"
// @Param type query string false "Type"
// @Param user_id query int false "User id"
// @Param is_read query bool false "Is read"
// @Param after query string false "After"
// @Param before query string false "Before"
// @Success 200 {object} GetAllNotificationsResponse
// @Produce json
// @Failure 401 {string} string "Missing, invalid, or expired Bearer token"
// @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation"
// @Failure 400 {string} string "Invalid request"
// @Failure 500 {string} string "Internal server error"
func (h *Handler) GetAllNotifications(c *fiber.Ctx) error {
limitStr := c.Query("limit", "10")
pageStr := c.Query("page", "1")
limit, err := strconv.Atoi(limitStr)
if err != nil || limit <= 0 {
return fiber.NewError(fiber.StatusBadRequest, "Invalid limit value")
}
page, err := strconv.Atoi(pageStr)
if err != nil || page <= 0 {
return fiber.NewError(fiber.StatusBadRequest, "Invalid page value")
}
filter := domain.NotificationFilter{
Channel: c.Query("channel"),
Type: c.Query("type"),
Limit: limit,
Offset: (page - 1) * limit,
}
if uid := c.Query("user_id"); uid != "" {
id, err := strconv.ParseInt(uid, 10, 64)
if err != nil {
return fiber.NewError(fiber.StatusBadRequest, "Invalid user_id value")
}
filter.UserID = &id
}
if isRead := c.Query("is_read"); isRead != "" {
val := isRead == "true"
filter.IsRead = &val
}
if after := c.Query("after"); after != "" {
t, err := time.Parse(time.RFC3339, after)
if err != nil {
return fiber.NewError(fiber.StatusBadRequest, "Invalid after date, use RFC3339 format")
}
filter.After = &t
}
if before := c.Query("before"); before != "" {
t, err := time.Parse(time.RFC3339, before)
if err != nil {
return fiber.NewError(fiber.StatusBadRequest, "Invalid before date, use RFC3339 format")
}
filter.Before = &t
}
notifications, total, err := h.notificationSvc.GetFilteredNotifications(context.Background(), filter)
if err != nil {
h.mongoLoggerSvc.Error("[NotificationSvc.GetNotifications] Failed to fetch notifications",
zap.Int("status_code", fiber.StatusInternalServerError),
zap.Error(err),
zap.Time("timestamp", time.Now()),
)
return fiber.NewError(fiber.StatusInternalServerError, "Failed to fetch notifications")
}
return c.Status(fiber.StatusOK).JSON(fiber.Map{
"notifications": notifications,
"total_count": total,
"limit": limit,
"page": page,
})
}
type SendSingleAfroSMSReq struct {
Recipient string `json:"recipient" validate:"required" example:"+251912345678"`
Message string `json:"message" validate:"required" example:"Hello world"`
}
// SendSingleAfroSMS godoc
// @Summary Send single SMS via AfroMessage
// @Description Sends an SMS message to a single phone number using AfroMessage
// @Tags user
// @Accept json
// @Produce json
// @Param sendSMS body SendSingleAfroSMSReq true "Send SMS request"
// @Success 200 {object} domain.Response{data=SendSingleAfroSMSReq}
// @Failure 400 {object} domain.ErrorResponse
// @Failure 500 {object} domain.ErrorResponse
// @Router /api/v1/admin/sendSMS [post]
// @Security Bearer
// @Failure 401 {string} string "Missing, invalid, or expired Bearer token"
// @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation"
func (h *Handler) SendSingleAfroSMS(c *fiber.Ctx) error {
var req SendSingleAfroSMSReq
if err := c.BodyParser(&req); err != nil {
h.mongoLoggerSvc.Info("Failed to parse SendSingleAfroSMS request",
zap.Int("status_code", fiber.StatusBadRequest),
zap.Error(err),
zap.Time("timestamp", time.Now()),
)
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Failed to send SMS",
Error: "Invalid request body: " + err.Error(),
})
}
// Validate request
if valErrs, ok := h.validator.Validate(c, req); !ok {
var errMsg string
for field, msg := range valErrs {
errMsg += fmt.Sprintf("%s: %s; ", field, msg)
}
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Failed to send SMS",
Error: errMsg,
})
}
// Send SMS via service
if err := h.notificationSvc.SendAfroMessageSMSTemp(
c.Context(),
req.Recipient,
req.Message,
nil,
); err != nil {
h.mongoLoggerSvc.Error("Failed to send AfroMessage SMS",
zap.String("phone_number", req.Recipient),
zap.Int("status_code", fiber.StatusInternalServerError),
zap.Error(err),
zap.Time("timestamp", time.Now()),
)
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to send SMS",
Error: err.Error(),
})
}
h.recordActivity(c, domain.ActionSMSSent, domain.ResourceNotification, nil, "Sent SMS to "+req.Recipient, nil)
return c.Status(fiber.StatusOK).JSON(domain.Response{
Message: "SMS sent successfully",
Success: true,
StatusCode: fiber.StatusOK,
Data: req,
})
}
// RegisterDeviceToken godoc
// @Summary Register Device Token
// @Tags devices
// @Router /api/v1/admin/devices/register [post]
// @Router /api/v1/devices/register [post]
// @Security Bearer
// @Accept json
// @Param body body handlers.RegisterDeviceToken.Request true "Device token and platform"
// @Success 201 {object} MessageResponse
// @Produce json
// @Failure 401 {string} string "Missing, invalid, or expired Bearer token"
// @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation"
// @Failure 400 {object} domain.ErrorResponse "Invalid request"
// @Failure 500 {string} string "Internal server error"
func (h *Handler) RegisterDeviceToken(c *fiber.Ctx) error {
type Request struct {
DeviceToken string `json:"device_token" validate:"required"`
Platform string `json:"platform" validate:"required,oneof=android ios web"`
}
var req Request
if err := c.BodyParser(&req); err != nil {
h.mongoLoggerSvc.Info("[NotificationHandler.RegisterDeviceToken] Failed to parse request body",
zap.Int("status_code", fiber.StatusBadRequest),
zap.Error(err),
zap.Time("timestamp", time.Now()),
)
return fiber.NewError(fiber.StatusBadRequest, "Invalid request body")
}
if valErrs, ok := h.validator.Validate(c, req); !ok {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Validation failed",
Error: firstValidationError(valErrs),
})
}
userID, ok := c.Locals("user_id").(int64)
if !ok || userID == 0 {
h.mongoLoggerSvc.Error("[NotificationHandler.RegisterDeviceToken] Invalid user ID in context",
zap.Int("status_code", fiber.StatusUnauthorized),
zap.Time("timestamp", time.Now()),
)
return fiber.NewError(fiber.StatusUnauthorized, "Invalid user identification")
}
if err := h.userSvc.RegisterDevice(c.Context(), userID, req.DeviceToken, req.Platform); err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == "23503" && pgErr.ConstraintName == "devices_user_fk" {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid authenticated user",
Error: "authenticated user does not exist in users table",
})
}
h.mongoLoggerSvc.Error("[NotificationHandler.RegisterDeviceToken] Failed to register device token",
zap.Int64("userID", userID),
zap.String("platform", req.Platform),
zap.Int("status_code", fiber.StatusInternalServerError),
zap.Error(err),
zap.Time("timestamp", time.Now()),
)
return fiber.NewError(fiber.StatusInternalServerError, "Failed to register device token: "+err.Error())
}
h.mongoLoggerSvc.Info("[NotificationHandler.RegisterDeviceToken] Device token registered successfully",
zap.Int64("userID", userID),
zap.String("platform", req.Platform),
zap.Time("timestamp", time.Now()),
)
deviceMeta, _ := json.Marshal(map[string]interface{}{
"user_id": userID,
"platform": req.Platform,
})
h.recordActivity(c, domain.ActionDeviceRegistered, domain.ResourceDevice, &userID, fmt.Sprintf("Device registered for user ID: %d", userID), deviceMeta)
return c.Status(fiber.StatusCreated).JSON(domain.Response{
Message: "Device token registered successfully",
Success: true,
StatusCode: fiber.StatusCreated,
})
}
// SendTestPushNotification sends a test push notification to the authenticated user
// @Summary Send test push notification
// @Description Sends a test push notification to all registered devices of the current user
// @Tags notifications
// @Accept json
// @Produce json
// @Param body body object{title=string,message=string} true "Test notification content"
// @Success 200 {object} domain.Response{data=SendTestPushNotificationData}
// @Failure 400 {object} domain.ErrorResponse
// @Failure 401 {object} domain.ErrorResponse
// @Failure 500 {object} domain.ErrorResponse
// @Router /api/v1/admin/notifications/test-push [post]
// @Security Bearer
// @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation"
func (h *Handler) SendTestPushNotification(c *fiber.Ctx) error {
title := c.FormValue("title", "Test Push Notification")
message := c.FormValue("message", "This is a test push notification from Rezina")
h.mongoLoggerSvc.Info("notification test-push diagnostics",
zap.Bool("fcm_credentials_configured", strings.TrimSpace(h.Cfg.FCMServiceAccountKey) != ""),
zap.Int("fcm_service_account_json_len", len(strings.TrimSpace(h.Cfg.FCMServiceAccountKey))),
)
userID, ok := c.Locals("user_id").(int64)
if !ok || userID == 0 {
return c.Status(fiber.StatusUnauthorized).JSON(domain.ErrorResponse{
Message: "Invalid user identification",
Error: "User ID not found in context",
})
}
// Get user's device tokens first to provide feedback
tokens, err := h.userSvc.GetUserDeviceTokens(c.Context(), userID)
if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to get device tokens",
Error: err.Error(),
})
}
if len(tokens) == 0 {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "No registered devices found",
Error: "Please register a device token first using POST /devices/register",
})
}
// Handle optional image upload
var imageURL string
if _, err := c.FormFile("file"); err == nil {
savedPath, saveErr := h.processAndSaveThumbnail(c, "notification_images")
if saveErr != nil {
return saveErr
}
resolved := h.resolveFileURL(c, savedPath)
if strings.HasPrefix(resolved, "/") {
imageURL = c.BaseURL() + resolved
} else {
imageURL = resolved
}
}
// Create test notification
notification := &domain.Notification{
RecipientID: userID,
Type: "system_alert",
DeliveryChannel: domain.DeliveryChannelPush,
Image: imageURL,
Payload: domain.NotificationPayload{
Headline: title,
Message: message,
},
}
// Send push notification
err = h.notificationSvc.SendPushNotification(c.Context(), notification)
if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to send push notification",
Error: err.Error(),
})
}
// Record in DB for history
h.notificationSvc.RecordNotification(c.Context(), userID, domain.NOTIFICATION_TYPE_SYSTEM_ALERT, domain.DeliveryChannelPush, domain.NotificationLevelInfo, title, message)
h.mongoLoggerSvc.Info("[NotificationHandler.SendTestPushNotification] Test push sent",
zap.Int64("userID", userID),
zap.Int("deviceCount", len(tokens)),
zap.Time("timestamp", time.Now()),
)
h.recordActivity(c, domain.ActionNotificationCreated, domain.ResourceNotification, &userID, fmt.Sprintf("Test push notification sent to user %d", userID), nil)
return c.Status(fiber.StatusOK).JSON(domain.Response{
Message: "Test push notification sent successfully",
Success: true,
StatusCode: fiber.StatusOK,
Data: map[string]interface{}{
"devices_count": len(tokens),
"title": title,
"message": message,
"image": imageURL,
},
})
}
// SendBulkPushNotification sends a push notification to multiple users or all users of a given role.
// @Summary Send bulk push notification
// @Description Sends a push notification to specified user IDs or all users matching a role. Optionally schedule for later with scheduled_at (RFC3339).
// @Tags notifications
// @Accept json
// @Produce json
// @Param body body object{title=string,message=string,image=string,user_ids=[]int64,role=string,scheduled_at=string} true "Bulk push content"
// @Success 200 {object} domain.Response{data=SendBulkPushNotificationData}
// @Failure 400 {object} domain.ErrorResponse
// @Failure 500 {object} domain.ErrorResponse
// @Router /api/v1/admin/notifications/bulk-push [post]
// @Security Bearer
// @Failure 401 {string} string "Missing, invalid, or expired Bearer token"
// @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation"
// @Success 201 {object} domain.Response{data=domain.ScheduledNotification} "Scheduled notification created when scheduled_at is provided"
func (h *Handler) SendBulkPushNotification(c *fiber.Ctx) error {
title := c.FormValue("title")
message := c.FormValue("message")
role := c.FormValue("role")
userIDsRaw := c.FormValue("user_ids")
scheduledAtRaw := c.FormValue("scheduled_at")
if title == "" {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Title is required",
})
}
if message == "" {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Message is required",
})
}
// Parse user_ids from JSON array string e.g. "[1,2,3]"
var userIDs []int64
if userIDsRaw != "" {
if err := json.Unmarshal([]byte(userIDsRaw), &userIDs); err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid user_ids format",
Error: "user_ids must be a JSON array of integers, e.g. [1,2,3]",
})
}
}
if len(userIDs) == 0 && role == "" {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "No target users specified",
Error: "Provide either user_ids or role",
})
}
// Schedule for later if scheduled_at is provided
if scheduledAtRaw != "" {
scheduledAt, err := time.Parse(time.RFC3339, scheduledAtRaw)
if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid scheduled_at format, use RFC3339 (e.g. 2025-06-01T10:00:00Z)",
Error: err.Error(),
})
}
if scheduledAt.Before(time.Now()) {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "scheduled_at must be in the future",
})
}
creatorID, _ := c.Locals("user_id").(int64)
sn := &domain.ScheduledNotification{
Channel: domain.DeliveryChannelPush,
Title: title,
Message: message,
ScheduledAt: scheduledAt,
TargetUserIDs: userIDs,
TargetRole: role,
CreatedBy: creatorID,
}
created, err := h.notificationSvc.CreateScheduledNotification(c.Context(), sn)
if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to schedule push notification",
Error: err.Error(),
})
}
scheduledID := created.ID
scheduleMeta, _ := json.Marshal(map[string]interface{}{
"channel": "push",
"target_users": len(userIDs),
"target_role": role,
"scheduled_at": scheduledAtRaw,
})
h.recordActivity(c, domain.ActionNotificationBulkSent, domain.ResourceNotification, &scheduledID, fmt.Sprintf("Scheduled push notification ID: %d", scheduledID), scheduleMeta)
return c.Status(fiber.StatusCreated).JSON(domain.Response{
Message: "Push notification scheduled",
Success: true,
StatusCode: fiber.StatusCreated,
Data: created,
})
}
// Determine target user IDs by role if no specific IDs given
if len(userIDs) == 0 && role != "" {
users, _, err := h.userSvc.GetAllUsers(context.Background(), domain.UserFilter{Role: role})
if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to fetch users for role",
Error: err.Error(),
})
}
for _, u := range users {
userIDs = append(userIDs, u.ID)
}
}
if len(userIDs) == 0 {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "No target users found",
})
}
// Handle optional image upload
var imageURL string
if _, err := c.FormFile("file"); err == nil {
savedPath, saveErr := h.processAndSaveThumbnail(c, "notification_images")
if saveErr != nil {
return saveErr
}
resolved := h.resolveFileURL(c, savedPath)
if strings.HasPrefix(resolved, "/") {
imageURL = c.BaseURL() + resolved
} else {
imageURL = resolved
}
}
notification := &domain.Notification{
ID: helpers.GenerateID(),
Type: domain.NOTIFICATION_TYPE_SYSTEM_ALERT,
DeliveryChannel: domain.DeliveryChannelPush,
Image: imageURL,
Payload: domain.NotificationPayload{
Headline: title,
Message: message,
},
}
delivery, err := h.notificationSvc.SendBulkPushNotification(c.Context(), userIDs, notification)
if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to send bulk push notification",
Error: err.Error(),
})
}
// Record in DB for history
for _, uid := range userIDs {
h.notificationSvc.RecordNotification(c.Context(), uid, domain.NOTIFICATION_TYPE_SYSTEM_ALERT, domain.DeliveryChannelPush, domain.NotificationLevelInfo, title, message)
}
h.mongoLoggerSvc.Info("[NotificationHandler.SendBulkPushNotification] Bulk push sent",
zap.Int("targetUsers", len(userIDs)),
zap.Int("devicesTargeted", delivery.DevicesTargeted),
zap.Int("sent", delivery.Sent),
zap.Int("failed", delivery.Failed),
zap.String("fcmProjectID", delivery.FCMProjectID),
zap.Time("timestamp", time.Now()),
)
responseMessage := "Bulk push notification sent"
switch {
case delivery.DevicesTargeted == 0:
responseMessage = "No registered device tokens for target users"
case delivery.Sent == 0 && delivery.Failed > 0:
responseMessage = "Bulk push completed with delivery failures"
case delivery.Failed > 0:
responseMessage = "Bulk push partially delivered"
}
responseData := map[string]interface{}{
"target_users": len(userIDs),
"devices_targeted": delivery.DevicesTargeted,
"sent": delivery.Sent,
"failed": delivery.Failed,
"image": imageURL,
}
if delivery.FCMProjectID != "" {
responseData["fcm_project_id"] = delivery.FCMProjectID
}
if len(delivery.Failures) > 0 {
responseData["failures"] = delivery.Failures
}
bulkPushMeta, _ := json.Marshal(map[string]interface{}{
"channel": "push",
"target_users": len(userIDs),
"devices_targeted": delivery.DevicesTargeted,
"sent": delivery.Sent,
"failed": delivery.Failed,
})
h.recordActivity(c, domain.ActionNotificationBulkSent, domain.ResourceNotification, nil, fmt.Sprintf("Bulk push notification sent to %d users", len(userIDs)), bulkPushMeta)
return c.Status(fiber.StatusOK).JSON(domain.Response{
Message: responseMessage,
Success: true,
StatusCode: fiber.StatusOK,
Data: responseData,
})
}
// SendBulkSMS sends an SMS to multiple users by user IDs, role, or direct phone numbers.
// @Summary Send bulk SMS
// @Description Sends an SMS to specified user IDs, all users of a role, or direct phone numbers. Optionally schedule for later with scheduled_at (RFC3339).
// @Tags notifications
// @Accept json
// @Produce json
// @Param body body object{message=string,user_ids=[]int64,role=string,phone_numbers=[]string,scheduled_at=string} true "Bulk SMS content"
// @Success 200 {object} domain.Response{data=SendBulkSMSData}
// @Failure 400 {object} domain.ErrorResponse
// @Failure 500 {object} domain.ErrorResponse
// @Router /api/v1/admin/notifications/bulk-sms [post]
// @Security Bearer
// @Failure 401 {string} string "Missing, invalid, or expired Bearer token"
// @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation"
// @Success 201 {object} domain.Response{data=domain.ScheduledNotification} "Scheduled notification created when scheduled_at is provided"
func (h *Handler) SendBulkSMS(c *fiber.Ctx) error {
type Request struct {
Message string `json:"message" validate:"required"`
UserIDs []int64 `json:"user_ids"`
Role string `json:"role"`
PhoneNumbers []string `json:"phone_numbers"`
ScheduledAt string `json:"scheduled_at"`
}
var req Request
if err := c.BodyParser(&req); err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid request body",
Error: err.Error(),
})
}
if req.Message == "" {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Message is required",
})
}
if len(req.UserIDs) == 0 && req.Role == "" && len(req.PhoneNumbers) == 0 {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "No recipients specified",
Error: "Provide user_ids, role, or phone_numbers",
})
}
// Schedule for later if scheduled_at is provided
if req.ScheduledAt != "" {
scheduledAt, err := time.Parse(time.RFC3339, req.ScheduledAt)
if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid scheduled_at format, use RFC3339 (e.g. 2025-06-01T10:00:00Z)",
Error: err.Error(),
})
}
if scheduledAt.Before(time.Now()) {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "scheduled_at must be in the future",
})
}
creatorID, _ := c.Locals("user_id").(int64)
var targetRaw json.RawMessage
if len(req.PhoneNumbers) > 0 {
raw := domain.ScheduledNotificationTargetRaw{Phones: req.PhoneNumbers}
targetRaw, _ = json.Marshal(raw)
}
sn := &domain.ScheduledNotification{
Channel: domain.DeliveryChannelSMS,
Message: req.Message,
ScheduledAt: scheduledAt,
TargetUserIDs: req.UserIDs,
TargetRole: req.Role,
TargetRaw: targetRaw,
CreatedBy: creatorID,
}
created, err := h.notificationSvc.CreateScheduledNotification(c.Context(), sn)
if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to schedule SMS",
Error: err.Error(),
})
}
scheduledID := created.ID
scheduleMeta, _ := json.Marshal(map[string]interface{}{
"channel": "sms",
"target_users": len(req.UserIDs),
"target_role": req.Role,
"scheduled_at": req.ScheduledAt,
})
h.recordActivity(c, domain.ActionNotificationBulkSent, domain.ResourceNotification, &scheduledID, fmt.Sprintf("Scheduled SMS notification ID: %d", scheduledID), scheduleMeta)
return c.Status(fiber.StatusCreated).JSON(domain.Response{
Message: "SMS scheduled",
Success: true,
StatusCode: fiber.StatusCreated,
Data: created,
})
}
// Collect phone numbers from all sources
phoneNumbers := make(map[string]struct{})
// Add directly provided phone numbers
for _, p := range req.PhoneNumbers {
phoneNumbers[p] = struct{}{}
}
// Collect user IDs from role if needed
userIDs := req.UserIDs
if len(userIDs) == 0 && req.Role != "" {
users, _, err := h.userSvc.GetAllUsers(context.Background(), domain.UserFilter{Role: req.Role})
if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to fetch users for role",
Error: err.Error(),
})
}
for _, u := range users {
userIDs = append(userIDs, u.ID)
}
}
// Resolve user IDs to phone numbers
for _, uid := range userIDs {
user, err := h.userSvc.GetUserByID(context.Background(), uid)
if err != nil {
h.mongoLoggerSvc.Warn("[NotificationHandler.SendBulkSMS] Failed to get user",
zap.Int64("userID", uid),
zap.Error(err),
)
continue
}
if user.PhoneNumber != "" {
phoneNumbers[user.PhoneNumber] = struct{}{}
}
}
if len(phoneNumbers) == 0 {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "No recipients found",
Error: "Provide user_ids, role, or phone_numbers",
})
}
// Flatten to slice
recipients := make([]string, 0, len(phoneNumbers))
for p := range phoneNumbers {
recipients = append(recipients, p)
}
sent, failed := h.notificationSvc.SendBulkSMS(c.Context(), recipients, req.Message)
// Record in DB for history (only for known users)
for _, uid := range userIDs {
h.notificationSvc.RecordNotification(c.Context(), uid, domain.NOTIFICATION_TYPE_SYSTEM_ALERT, domain.DeliveryChannelSMS, domain.NotificationLevelInfo, "SMS Notification", req.Message)
}
h.mongoLoggerSvc.Info("[NotificationHandler.SendBulkSMS] Bulk SMS sent",
zap.Int("totalRecipients", len(recipients)),
zap.Int("sent", sent),
zap.Int("failed", failed),
zap.Time("timestamp", time.Now()),
)
bulkSMSMeta, _ := json.Marshal(map[string]interface{}{
"channel": "sms",
"total_recipients": len(recipients),
"sent": sent,
"failed": failed,
})
h.recordActivity(c, domain.ActionNotificationBulkSent, domain.ResourceNotification, nil, fmt.Sprintf("Bulk SMS sent to %d recipients", len(recipients)), bulkSMSMeta)
return c.Status(fiber.StatusOK).JSON(domain.Response{
Message: "Bulk SMS sent",
Success: true,
StatusCode: fiber.StatusOK,
Data: map[string]interface{}{
"total_recipients": len(recipients),
"sent": sent,
"failed": failed,
},
})
}
// SendBulkInAppNotification godoc
// @Summary Send bulk in-app notification
// @Description Creates in-app notifications for specified platform user IDs, users matching a platform role, team member IDs, or team members matching a team_role. Optionally schedule for later with scheduled_at (RFC3339).
// @Tags notifications
// @Accept json
// @Produce json
// @Param body body object{title=string,message=string,user_ids=[]int64,role=string,team_member_ids=[]int64,team_role=string,scheduled_at=string,type=string,level=string} true "Bulk in-app content"
// @Success 200 {object} domain.Response{data=SendBulkInAppNotificationData}
// @Failure 400 {object} domain.ErrorResponse
// @Failure 500 {object} domain.ErrorResponse
// @Router /api/v1/admin/notifications/bulk-in-app [post]
// @Security Bearer
// @Failure 401 {string} string "Missing, invalid, or expired Bearer token"
// @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation"
// @Success 201 {object} domain.Response{data=domain.ScheduledNotification} "Scheduled notification created when scheduled_at is provided"
func (h *Handler) SendBulkInAppNotification(c *fiber.Ctx) error {
type Request struct {
Title string `json:"title" validate:"required"`
Message string `json:"message" validate:"required"`
UserIDs []int64 `json:"user_ids"`
Role string `json:"role"`
TeamMemberIDs []int64 `json:"team_member_ids"`
TeamRole string `json:"team_role"`
ScheduledAt string `json:"scheduled_at"`
Type string `json:"type"`
Level string `json:"level"`
}
var req Request
if err := c.BodyParser(&req); err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid request body",
Error: err.Error(),
})
}
if strings.TrimSpace(req.Title) == "" || strings.TrimSpace(req.Message) == "" {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Title and message are required",
})
}
if len(req.UserIDs) == 0 && req.Role == "" && len(req.TeamMemberIDs) == 0 && req.TeamRole == "" {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "No recipients specified",
Error: "Provide user_ids, role, team_member_ids, or team_role",
})
}
notifType := domain.NOTIFICATION_TYPE_SYSTEM_ALERT
if t := strings.TrimSpace(req.Type); t != "" {
notifType = domain.NotificationType(t)
}
level := domain.NotificationLevelInfo
if l := strings.TrimSpace(req.Level); l != "" {
level = domain.NotificationLevel(l)
}
if req.ScheduledAt != "" {
scheduledAt, err := time.Parse(time.RFC3339, req.ScheduledAt)
if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid scheduled_at format, use RFC3339 (e.g. 2025-06-01T10:00:00Z)",
Error: err.Error(),
})
}
if scheduledAt.Before(time.Now()) {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "scheduled_at must be in the future",
})
}
creatorID, _ := c.Locals("user_id").(int64)
targetRaw, _ := json.Marshal(domain.ScheduledNotificationTargetRaw{
Type: string(notifType),
Level: string(level),
TeamMemberIDs: req.TeamMemberIDs,
TeamRole: req.TeamRole,
})
sn := &domain.ScheduledNotification{
Channel: domain.DeliveryChannelInApp,
Title: req.Title,
Message: req.Message,
ScheduledAt: scheduledAt,
TargetUserIDs: req.UserIDs,
TargetRole: req.Role,
TargetRaw: targetRaw,
CreatedBy: creatorID,
}
created, err := h.notificationSvc.CreateScheduledNotification(c.Context(), sn)
if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to schedule in-app notification",
Error: err.Error(),
})
}
scheduledID := created.ID
scheduleMeta, _ := json.Marshal(map[string]interface{}{
"channel": "in_app",
"target_users": len(req.UserIDs),
"target_role": req.Role,
"target_team_members": len(req.TeamMemberIDs),
"target_team_role": req.TeamRole,
"scheduled_at": req.ScheduledAt,
})
h.recordActivity(c, domain.ActionNotificationBulkSent, domain.ResourceNotification, &scheduledID, fmt.Sprintf("Scheduled in-app notification ID: %d", scheduledID), scheduleMeta)
return c.Status(fiber.StatusCreated).JSON(domain.Response{
Message: "In-app notification scheduled",
Success: true,
StatusCode: fiber.StatusCreated,
Data: created,
})
}
userIDs, err := h.notificationSvc.ResolveUserIDsForBulk(c.Context(), req.UserIDs, req.Role)
if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to fetch users for role",
Error: err.Error(),
})
}
teamMemberIDs, err := h.notificationSvc.ResolveTeamMemberIDsForBulk(c.Context(), req.TeamMemberIDs, req.TeamRole)
if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to fetch team members for team_role",
Error: err.Error(),
})
}
if len(userIDs) == 0 && len(teamMemberIDs) == 0 {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "No target recipients found",
})
}
userSent, userFailed := h.notificationSvc.SendBulkInAppNotification(c.Context(), userIDs, req.Title, req.Message, notifType, level)
teamSent, teamFailed := h.notificationSvc.SendBulkInAppToTeamMembers(c.Context(), teamMemberIDs, req.Title, req.Message, notifType, level)
sent := userSent + teamSent
failed := userFailed + teamFailed
totalRecipients := len(userIDs) + len(teamMemberIDs)
h.mongoLoggerSvc.Info("[NotificationHandler.SendBulkInAppNotification] Bulk in-app sent",
zap.Int("totalRecipients", totalRecipients),
zap.Int("sent", sent),
zap.Int("failed", failed),
zap.Time("timestamp", time.Now()),
)
bulkInAppMeta, _ := json.Marshal(map[string]interface{}{
"channel": "in_app",
"total_recipients": totalRecipients,
"user_recipients": len(userIDs),
"team_member_recipients": len(teamMemberIDs),
"sent": sent,
"failed": failed,
})
h.recordActivity(c, domain.ActionNotificationBulkSent, domain.ResourceNotification, nil, fmt.Sprintf("Bulk in-app notification sent to %d recipients", totalRecipients), bulkInAppMeta)
return c.Status(fiber.StatusOK).JSON(domain.Response{
Message: "Bulk in-app notification sent",
Success: true,
StatusCode: fiber.StatusOK,
Data: map[string]interface{}{
"total_recipients": totalRecipients,
"user_recipients": len(userIDs),
"team_member_recipients": len(teamMemberIDs),
"sent": sent,
"failed": failed,
},
})
}
// GetScheduledNotification retrieves a single scheduled notification by ID.
// @Summary Get scheduled notification
// @Description Returns a single scheduled notification by its ID
// @Tags notifications
// @Produce json
// @Param id path int true "Scheduled Notification ID"
// @Success 200 {object} domain.Response{data=domain.ScheduledNotification}
// @Failure 400 {object} domain.ErrorResponse
// @Failure 500 {object} domain.ErrorResponse
// @Router /api/v1/admin/notifications/scheduled/{id} [get]
// @Security Bearer
// @Failure 401 {string} string "Missing, invalid, or expired Bearer token"
// @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation"
func (h *Handler) GetScheduledNotification(c *fiber.Ctx) error {
id, err := strconv.ParseInt(c.Params("id"), 10, 64)
if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid ID",
Error: err.Error(),
})
}
sn, err := h.notificationSvc.GetScheduledNotification(c.Context(), id)
if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to get scheduled notification",
Error: err.Error(),
})
}
return c.Status(fiber.StatusOK).JSON(domain.Response{
Message: "Scheduled notification retrieved",
Success: true,
StatusCode: fiber.StatusOK,
Data: sn,
})
}
// ListScheduledNotifications lists scheduled notifications with optional filters.
// @Summary List scheduled notifications
// @Description Returns paginated scheduled notifications with optional status, channel, and date filters
// @Tags notifications
// @Produce json
// @Param status query string false "Filter by status"
// @Param channel query string false "Filter by channel"
// @Param after query string false "Filter after date (RFC3339)"
// @Param before query string false "Filter before date (RFC3339)"
// @Param limit query int false "Page size" default(20)
// @Param page query int false "Page number" default(1)
// @Success 200 {object} ListScheduledNotificationsResponse
// @Failure 400 {object} domain.ErrorResponse
// @Failure 500 {object} domain.ErrorResponse
// @Router /api/v1/admin/notifications/scheduled [get]
// @Security Bearer
// @Failure 401 {string} string "Missing, invalid, or expired Bearer token"
// @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation"
func (h *Handler) ListScheduledNotifications(c *fiber.Ctx) error {
limit, err := strconv.Atoi(c.Query("limit", "20"))
if err != nil || limit <= 0 {
limit = 20
}
page, err := strconv.Atoi(c.Query("page", "1"))
if err != nil || page <= 0 {
page = 1
}
filter := domain.ScheduledNotificationFilter{
Status: c.Query("status"),
Channel: c.Query("channel"),
Limit: limit,
Offset: (page - 1) * limit,
}
if after := c.Query("after"); after != "" {
t, err := time.Parse(time.RFC3339, after)
if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid after date, use RFC3339 format",
Error: err.Error(),
})
}
filter.After = &t
}
if before := c.Query("before"); before != "" {
t, err := time.Parse(time.RFC3339, before)
if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid before date, use RFC3339 format",
Error: err.Error(),
})
}
filter.Before = &t
}
notifications, total, err := h.notificationSvc.ListScheduledNotifications(c.Context(), filter)
if err != nil {
h.mongoLoggerSvc.Error("[NotificationHandler.ListScheduledNotifications] Failed",
zap.Error(err),
zap.Time("timestamp", time.Now()),
)
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to list scheduled notifications",
Error: err.Error(),
})
}
return c.Status(fiber.StatusOK).JSON(fiber.Map{
"scheduled_notifications": notifications,
"total_count": total,
"limit": limit,
"page": page,
})
}
// CancelScheduledNotification cancels a pending or processing scheduled notification.
// @Summary Cancel scheduled notification
// @Description Cancels a scheduled notification if it is still pending or processing
// @Tags notifications
// @Produce json
// @Param id path int true "Scheduled Notification ID"
// @Success 200 {object} domain.Response{data=domain.ScheduledNotification}
// @Failure 400 {object} domain.ErrorResponse
// @Failure 500 {object} domain.ErrorResponse
// @Router /api/v1/admin/notifications/scheduled/{id}/cancel [post]
// @Security Bearer
// @Failure 401 {string} string "Missing, invalid, or expired Bearer token"
// @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation"
func (h *Handler) CancelScheduledNotification(c *fiber.Ctx) error {
id, err := strconv.ParseInt(c.Params("id"), 10, 64)
if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid ID",
Error: err.Error(),
})
}
cancelled, err := h.notificationSvc.CancelScheduledNotification(c.Context(), id)
if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to cancel scheduled notification",
Error: err.Error(),
})
}
h.recordActivity(c, domain.ActionScheduledNotificationCancelled, domain.ResourceNotification, &id, fmt.Sprintf("Cancelled scheduled notification ID: %d", id), nil)
return c.Status(fiber.StatusOK).JSON(domain.Response{
Message: "Scheduled notification cancelled",
Success: true,
StatusCode: fiber.StatusOK,
Data: cancelled,
})
}
// parseEmailAttachment reads an optional "file" from the multipart form and returns a Resend attachment.
func (h *Handler) parseEmailAttachment(c *fiber.Ctx) []*resend.Attachment {
fileHeader, err := c.FormFile("file")
if err != nil {
return nil
}
fh, err := fileHeader.Open()
if err != nil {
return nil
}
defer fh.Close()
data, err := io.ReadAll(fh)
if err != nil {
return nil
}
return []*resend.Attachment{
{
Content: data,
Filename: fileHeader.Filename,
},
}
}
// SendSingleEmail sends an email to a single recipient with an optional image attachment.
// @Summary Send single email
// @Description Sends an email to a single email address with optional image attachment
// @Tags notifications
// @Accept multipart/form-data
// @Produce json
// @Success 200 {object} MessageResponse
// @Failure 400 {object} domain.ErrorResponse
// @Failure 500 {object} domain.ErrorResponse
// @Router /api/v1/admin/notifications/send-email [post]
// @Security Bearer
// @Failure 401 {string} string "Missing, invalid, or expired Bearer token"
// @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation"
// @Param email_template_slug formData string false "Saved template slug; otherwise subject and message or html are required"
// @Param template_variables formData string false "JSON object of template variables"
// @Param subject formData string false "Subject, required when no template is selected"
// @Param message formData string false "Plain-text body, required without a template unless html is supplied"
// @Param html formData string false "HTML body alternative to message"
// @Param file formData file false "Optional attachment"
// @Param recipient formData string true "Recipient email address"
func (h *Handler) SendSingleEmail(c *fiber.Ctx) error {
recipient := strings.TrimSpace(c.FormValue("recipient"))
if recipient == "" {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Recipient is required",
})
}
content, err := parseOutboundEmailFromForm(c)
if err != nil {
if fe, ok := err.(*fiber.Error); ok {
return c.Status(fe.Code).JSON(domain.ErrorResponse{Message: fe.Message})
}
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid email content",
Error: err.Error(),
})
}
attachments := h.parseEmailAttachment(c)
if err := h.notificationSvc.SendOutboundEmail(
c.Context(), recipient, content, attachments,
); err != nil {
h.mongoLoggerSvc.Error("[NotificationHandler.SendSingleEmail] Failed to send email",
zap.String("recipient", recipient),
zap.Error(err),
zap.Time("timestamp", time.Now()),
)
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to send email",
Error: err.Error(),
})
}
emailMeta, _ := json.Marshal(map[string]string{"recipient": recipient})
h.recordActivity(c, domain.ActionNotificationBulkSent, domain.ResourceNotification, nil, fmt.Sprintf("Email sent to %s", recipient), emailMeta)
return c.Status(fiber.StatusOK).JSON(domain.Response{
Message: "Email sent successfully",
Success: true,
StatusCode: fiber.StatusOK,
})
}
// SendBulkEmail sends an email to multiple users by user IDs, role, team member IDs, team role, or direct email addresses.
// @Summary Send bulk email
// @Description Sends an email to specified user IDs, users of a platform role, team member IDs, team members of a team_role, or direct email addresses with optional image attachment. Optionally schedule for later with scheduled_at (RFC3339).
// @Tags notifications
// @Accept multipart/form-data
// @Produce json
// @Success 200 {object} domain.Response{data=SendBulkEmailData}
// @Failure 400 {object} domain.ErrorResponse
// @Failure 500 {object} domain.ErrorResponse
// @Router /api/v1/admin/notifications/bulk-email [post]
// @Security Bearer
// @Failure 401 {string} string "Missing, invalid, or expired Bearer token"
// @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation"
// @Param email_template_slug formData string false "Saved template slug; otherwise subject and message or html are required"
// @Param template_variables formData string false "JSON object of template variables"
// @Param subject formData string false "Subject, required when no template is selected"
// @Param message formData string false "Plain-text body, required without a template unless html is supplied"
// @Param html formData string false "HTML body alternative to message"
// @Param file formData file false "Optional attachment"
// @Param emails formData string false "Comma-separated direct email addresses"
// @Param user_ids formData string false "Comma-separated customer IDs"
// @Param role formData string false "Customer role used to select recipients"
// @Param team_member_ids formData string false "Comma-separated team-member IDs"
// @Param team_role formData string false "Team role used to select recipients"
// @Param scheduled_at formData string false "Optional future delivery time in RFC3339 format"
// @Success 201 {object} domain.Response{data=domain.ScheduledNotification} "Scheduled notification created when scheduled_at is provided"
func (h *Handler) SendBulkEmail(c *fiber.Ctx) error {
role := c.FormValue("role")
userIDsRaw := c.FormValue("user_ids")
teamMemberIDsRaw := c.FormValue("team_member_ids")
teamRole := c.FormValue("team_role")
emailsRaw := c.FormValue("emails")
scheduledAtRaw := c.FormValue("scheduled_at")
content, err := parseOutboundEmailFromForm(c)
if err != nil {
if fe, ok := err.(*fiber.Error); ok {
return c.Status(fe.Code).JSON(domain.ErrorResponse{Message: fe.Message})
}
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid email content",
Error: err.Error(),
})
}
// Parse direct emails
var directEmails []string
if emailsRaw != "" {
if err := json.Unmarshal([]byte(emailsRaw), &directEmails); err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid emails format",
Error: "emails must be a JSON array of strings",
})
}
}
// Parse user_ids
var userIDs []int64
if userIDsRaw != "" {
if err := json.Unmarshal([]byte(userIDsRaw), &userIDs); err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid user_ids format",
Error: "user_ids must be a JSON array of integers",
})
}
}
var teamMemberIDs []int64
if teamMemberIDsRaw != "" {
if err := json.Unmarshal([]byte(teamMemberIDsRaw), &teamMemberIDs); err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid team_member_ids format",
Error: "team_member_ids must be a JSON array of integers",
})
}
}
if len(userIDs) == 0 && role == "" && len(teamMemberIDs) == 0 && teamRole == "" && len(directEmails) == 0 {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "No recipients specified",
Error: "Provide user_ids, role, team_member_ids, team_role, or emails",
})
}
// Schedule for later if scheduled_at is provided
if scheduledAtRaw != "" {
scheduledAt, err := time.Parse(time.RFC3339, scheduledAtRaw)
if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid scheduled_at format, use RFC3339 (e.g. 2025-06-01T10:00:00Z)",
Error: err.Error(),
})
}
if scheduledAt.Before(time.Now()) {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "scheduled_at must be in the future",
})
}
creatorID, _ := c.Locals("user_id").(int64)
targetRaw, _ := json.Marshal(domain.ScheduledNotificationTargetRaw{
Emails: directEmails,
TeamMemberIDs: teamMemberIDs,
TeamRole: teamRole,
})
sn := &domain.ScheduledNotification{
Channel: domain.DeliveryChannelEmail,
Title: content.Subject,
Message: content.Message,
HTML: content.HTML,
EmailTemplateSlug: content.TemplateSlug,
EmailTemplateVariables: outboundEmailTemplateVariablesJSON(content),
ScheduledAt: scheduledAt,
TargetUserIDs: userIDs,
TargetRole: role,
TargetRaw: targetRaw,
CreatedBy: creatorID,
}
created, err := h.notificationSvc.CreateScheduledNotification(c.Context(), sn)
if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to schedule email",
Error: err.Error(),
})
}
scheduledID := created.ID
scheduleMeta, _ := json.Marshal(map[string]interface{}{
"channel": "email",
"target_users": len(userIDs),
"target_role": role,
"target_team_members": len(teamMemberIDs),
"target_team_role": teamRole,
"scheduled_at": scheduledAtRaw,
})
h.recordActivity(c, domain.ActionNotificationBulkSent, domain.ResourceNotification, &scheduledID, fmt.Sprintf("Scheduled email notification ID: %d", scheduledID), scheduleMeta)
return c.Status(fiber.StatusCreated).JSON(domain.Response{
Message: "Email scheduled",
Success: true,
StatusCode: fiber.StatusCreated,
Data: created,
})
}
// Immediate send: collect emails from all sources
recipients, resolvedUserIDs, resolvedTeamMemberIDs, err := h.notificationSvc.ResolveBulkEmailAddresses(
c.Context(),
userIDs,
role,
teamMemberIDs,
teamRole,
directEmails,
)
if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to resolve email recipients",
Error: err.Error(),
})
}
if len(recipients) == 0 {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "No recipients found",
Error: "Provide user_ids, role, team_member_ids, team_role, or emails",
})
}
attachments := h.parseEmailAttachment(c)
sent, failed := h.notificationSvc.SendBulkEmail(c.Context(), recipients, content, attachments)
for _, uid := range resolvedUserIDs {
h.notificationSvc.RecordNotification(c.Context(), uid, domain.NOTIFICATION_TYPE_SYSTEM_ALERT, domain.DeliveryChannelEmail, domain.NotificationLevelInfo, content.Subject, content.Message)
}
for _, mid := range resolvedTeamMemberIDs {
h.notificationSvc.RecordTeamMemberNotification(c.Context(), mid, domain.NOTIFICATION_TYPE_SYSTEM_ALERT, domain.DeliveryChannelEmail, domain.NotificationLevelInfo, content.Subject, content.Message)
}
h.mongoLoggerSvc.Info("[NotificationHandler.SendBulkEmail] Bulk email sent",
zap.Int("totalRecipients", len(recipients)),
zap.Int("sent", sent),
zap.Int("failed", failed),
zap.Time("timestamp", time.Now()),
)
bulkEmailMeta, _ := json.Marshal(map[string]interface{}{
"channel": "email",
"total_recipients": len(recipients),
"user_recipients": len(resolvedUserIDs),
"team_member_recipients": len(resolvedTeamMemberIDs),
"sent": sent,
"failed": failed,
})
h.recordActivity(c, domain.ActionNotificationBulkSent, domain.ResourceNotification, nil, fmt.Sprintf("Bulk email sent to %d recipients", len(recipients)), bulkEmailMeta)
return c.Status(fiber.StatusOK).JSON(domain.Response{
Message: "Bulk email sent",
Success: true,
StatusCode: fiber.StatusOK,
Data: map[string]interface{}{
"total_recipients": len(recipients),
"user_recipients": len(resolvedUserIDs),
"team_member_recipients": len(resolvedTeamMemberIDs),
"sent": sent,
"failed": failed,
},
})
}
// UnregisterDeviceToken godoc
// @Summary Unregister Device Token
// @Tags devices
// @Router /api/v1/admin/devices/unregister [post]
// @Router /api/v1/devices/unregister [post]
// @Security Bearer
// @Accept json
// @Param body body handlers.UnregisterDeviceToken.Request true "Device token to unregister"
// @Success 200 {object} MessageResponse
// @Produce json
// @Failure 401 {string} string "Missing, invalid, or expired Bearer token"
// @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation"
// @Failure 400 {string} string "Invalid request"
// @Failure 500 {string} string "Internal server error"
func (h *Handler) UnregisterDeviceToken(c *fiber.Ctx) error {
type Request struct {
DeviceToken string `json:"device_token" validate:"required"`
}
var req Request
if err := c.BodyParser(&req); err != nil {
h.mongoLoggerSvc.Info("[NotificationHandler.UnregisterDeviceToken] Failed to parse request body",
zap.Int("status_code", fiber.StatusBadRequest),
zap.Error(err),
zap.Time("timestamp", time.Now()),
)
return fiber.NewError(fiber.StatusBadRequest, "Invalid request body")
}
userID, ok := c.Locals("user_id").(int64)
if !ok || userID == 0 {
h.mongoLoggerSvc.Error("[NotificationHandler.UnregisterDeviceToken] Invalid user ID in context",
zap.Int("status_code", fiber.StatusUnauthorized),
zap.Time("timestamp", time.Now()),
)
return fiber.NewError(fiber.StatusUnauthorized, "Invalid user identification")
}
if err := h.userSvc.DeactivateDevice(c.Context(), userID, req.DeviceToken); err != nil {
h.mongoLoggerSvc.Error("[NotificationHandler.UnregisterDeviceToken] Failed to unregister device token",
zap.Int64("userID", userID),
zap.Int("status_code", fiber.StatusInternalServerError),
zap.Error(err),
zap.Time("timestamp", time.Now()),
)
return fiber.NewError(fiber.StatusInternalServerError, "Failed to unregister device token: "+err.Error())
}
h.mongoLoggerSvc.Info("[NotificationHandler.UnregisterDeviceToken] Device token unregistered successfully",
zap.Int64("userID", userID),
zap.Time("timestamp", time.Now()),
)
h.recordActivity(c, domain.ActionDeviceUnregistered, domain.ResourceDevice, &userID, fmt.Sprintf("Device unregistered for user ID: %d", userID), nil)
return c.Status(fiber.StatusOK).JSON(domain.Response{
Message: "Device token unregistered successfully",
Success: true,
StatusCode: fiber.StatusOK,
})
}