Files
Novault-backend/internal/repository/notification_repository.go

75 lines
2.1 KiB
Go

package repository
import (
"accounting-app/internal/models"
"time"
"gorm.io/gorm"
)
type NotificationRepository struct {
db *gorm.DB
}
func NewNotificationRepository(db *gorm.DB) *NotificationRepository {
return &NotificationRepository{db: db}
}
// Create creates a new notification
func (r *NotificationRepository) Create(notification *models.Notification) error {
return r.db.Create(notification).Error
}
// FindAll retrieves notifications for a user with pagination and filtering
func (r *NotificationRepository) FindAll(userID uint, page, pageSize int, isRead *bool) ([]models.Notification, int64, error) {
var notifications []models.Notification
var total int64
query := r.db.Model(&models.Notification{}).Where("user_id = ?", userID)
if isRead != nil {
query = query.Where("is_read = ?", *isRead)
}
if err := query.Count(&total).Error; err != nil {
return nil, 0, err
}
offset := (page - 1) * pageSize
err := query.Order("created_at desc").
Offset(offset).
Limit(pageSize).
Find(&notifications).Error
return notifications, total, err
}
// CountUnread counts unread notifications for a user
func (r *NotificationRepository) CountUnread(userID uint) (int64, error) {
var count int64
err := r.db.Model(&models.Notification{}).
Where("user_id = ? AND is_read = ?", userID, false).
Count(&count).Error
return count, err
}
// MarkAsRead marks a single notification as read
func (r *NotificationRepository) MarkAsRead(id uint, userID uint) error {
return r.db.Model(&models.Notification{}).
Where("id = ? AND user_id = ?", id, userID).
Updates(map[string]interface{}{
"is_read": true,
"read_at": time.Now(),
}).Error
}
// MarkAllAsRead marks all notifications as read for a user
func (r *NotificationRepository) MarkAllAsRead(userID uint) error {
return r.db.Model(&models.Notification{}).
Where("user_id = ? AND is_read = ?", userID, false).
Updates(map[string]interface{}{
"is_read": true,
"read_at": time.Now(),
}).Error
}