Add smart notification reminder system with frequency-aware scheduling
Replaces one-size-fits-all "2 days before" reminders with intelligent
scheduling based on task frequency. Infrequent tasks (annual) get 30-day
advance notice while frequent tasks (weekly) only get day-of reminders.
Key features:
- Frequency-aware pre-reminders: annual (30d, 14d, 7d), quarterly (7d, 3d),
monthly (3d), bi-weekly (1d), daily/weekly/once (day-of only)
- Overdue tapering: daily for 3 days, then every 3 days, stops after 14 days
- Reminder log table prevents duplicate notifications per due date/stage
- Admin endpoint displays notification schedules for all frequencies
- Comprehensive test suite (100 random tasks, 61 days each, 10 test functions)
New files:
- internal/notifications/reminder_config.go - Editable schedule configuration
- internal/notifications/reminder_schedule.go - Schedule lookup logic
- internal/notifications/reminder_schedule_test.go - Dynamic test suite
- internal/models/reminder_log.go - TaskReminderLog model
- internal/repositories/reminder_repo.go - Reminder log repository
- migrations/010_add_task_reminder_log.{up,down}.sql
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
125
internal/repositories/reminder_repo.go
Normal file
125
internal/repositories/reminder_repo.go
Normal file
@@ -0,0 +1,125 @@
|
||||
package repositories
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/treytartt/casera-api/internal/models"
|
||||
)
|
||||
|
||||
// ReminderRepository handles database operations for task reminder logs
|
||||
type ReminderRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewReminderRepository creates a new reminder repository
|
||||
func NewReminderRepository(db *gorm.DB) *ReminderRepository {
|
||||
return &ReminderRepository{db: db}
|
||||
}
|
||||
|
||||
// HasSentReminder checks if a reminder has already been sent for the given
|
||||
// task, user, due date, and reminder stage.
|
||||
func (r *ReminderRepository) HasSentReminder(taskID, userID uint, dueDate time.Time, stage models.ReminderStage) (bool, error) {
|
||||
// Normalize to date only
|
||||
dueDateOnly := time.Date(dueDate.Year(), dueDate.Month(), dueDate.Day(), 0, 0, 0, 0, time.UTC)
|
||||
|
||||
var count int64
|
||||
err := r.db.Model(&models.TaskReminderLog{}).
|
||||
Where("task_id = ? AND user_id = ? AND due_date = ? AND reminder_stage = ?",
|
||||
taskID, userID, dueDateOnly, stage).
|
||||
Count(&count).Error
|
||||
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
return count > 0, nil
|
||||
}
|
||||
|
||||
// LogReminder records that a reminder was sent.
|
||||
// Returns the created log entry or an error if the reminder was already sent
|
||||
// (unique constraint violation).
|
||||
func (r *ReminderRepository) LogReminder(taskID, userID uint, dueDate time.Time, stage models.ReminderStage, notificationID *uint) (*models.TaskReminderLog, error) {
|
||||
// Normalize to date only
|
||||
dueDateOnly := time.Date(dueDate.Year(), dueDate.Month(), dueDate.Day(), 0, 0, 0, 0, time.UTC)
|
||||
|
||||
log := &models.TaskReminderLog{
|
||||
TaskID: taskID,
|
||||
UserID: userID,
|
||||
DueDate: dueDateOnly,
|
||||
ReminderStage: stage,
|
||||
SentAt: time.Now().UTC(),
|
||||
NotificationID: notificationID,
|
||||
}
|
||||
|
||||
err := r.db.Create(log).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return log, nil
|
||||
}
|
||||
|
||||
// GetSentRemindersForTask returns all reminder logs for a specific task and user.
|
||||
func (r *ReminderRepository) GetSentRemindersForTask(taskID, userID uint) ([]models.TaskReminderLog, error) {
|
||||
var logs []models.TaskReminderLog
|
||||
err := r.db.Where("task_id = ? AND user_id = ?", taskID, userID).
|
||||
Order("sent_at DESC").
|
||||
Find(&logs).Error
|
||||
return logs, err
|
||||
}
|
||||
|
||||
// GetSentRemindersForDueDate returns all reminder logs for a specific task,
|
||||
// user, and due date.
|
||||
func (r *ReminderRepository) GetSentRemindersForDueDate(taskID, userID uint, dueDate time.Time) ([]models.TaskReminderLog, error) {
|
||||
dueDateOnly := time.Date(dueDate.Year(), dueDate.Month(), dueDate.Day(), 0, 0, 0, 0, time.UTC)
|
||||
|
||||
var logs []models.TaskReminderLog
|
||||
err := r.db.Where("task_id = ? AND user_id = ? AND due_date = ?",
|
||||
taskID, userID, dueDateOnly).
|
||||
Order("sent_at DESC").
|
||||
Find(&logs).Error
|
||||
return logs, err
|
||||
}
|
||||
|
||||
// CleanupOldLogs removes reminder logs older than the specified number of days.
|
||||
// This helps keep the table from growing indefinitely.
|
||||
func (r *ReminderRepository) CleanupOldLogs(daysOld int) (int64, error) {
|
||||
cutoff := time.Now().UTC().AddDate(0, 0, -daysOld)
|
||||
|
||||
result := r.db.Where("sent_at < ?", cutoff).
|
||||
Delete(&models.TaskReminderLog{})
|
||||
|
||||
return result.RowsAffected, result.Error
|
||||
}
|
||||
|
||||
// GetRecentReminderStats returns statistics about recent reminders sent.
|
||||
// Useful for admin/monitoring purposes.
|
||||
func (r *ReminderRepository) GetRecentReminderStats(sinceHours int) (map[string]int64, error) {
|
||||
since := time.Now().UTC().Add(-time.Duration(sinceHours) * time.Hour)
|
||||
|
||||
stats := make(map[string]int64)
|
||||
|
||||
// Count by stage
|
||||
rows, err := r.db.Model(&models.TaskReminderLog{}).
|
||||
Select("reminder_stage, COUNT(*) as count").
|
||||
Where("sent_at >= ?", since).
|
||||
Group("reminder_stage").
|
||||
Rows()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
for rows.Next() {
|
||||
var stage string
|
||||
var count int64
|
||||
if err := rows.Scan(&stage, &count); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
stats[stage] = count
|
||||
}
|
||||
|
||||
return stats, nil
|
||||
}
|
||||
@@ -50,6 +50,7 @@ type TaskFilterOptions struct {
|
||||
PreloadAssignedTo bool
|
||||
PreloadResidence bool
|
||||
PreloadCompletions bool // Minimal: just id, task_id, completed_at
|
||||
PreloadFrequency bool // For smart notifications
|
||||
}
|
||||
|
||||
// applyFilterOptions applies the filter options to a query.
|
||||
@@ -88,6 +89,9 @@ func (r *TaskRepository) applyFilterOptions(query *gorm.DB, opts TaskFilterOptio
|
||||
return db.Select("id", "task_id", "completed_at")
|
||||
})
|
||||
}
|
||||
if opts.PreloadFrequency {
|
||||
query = query.Preload("Frequency")
|
||||
}
|
||||
|
||||
return query
|
||||
}
|
||||
@@ -209,6 +213,32 @@ func (r *TaskRepository) GetCancelledTasks(opts TaskFilterOptions) ([]models.Tas
|
||||
return tasks, err
|
||||
}
|
||||
|
||||
// GetActiveTasksForUsers returns all active, non-completed tasks for the specified users.
|
||||
// This is used by the smart notification system to evaluate all tasks for potential reminders.
|
||||
// It includes tasks that are overdue, due soon, or upcoming - the caller determines
|
||||
// which reminders to send based on the task's frequency and due date.
|
||||
func (r *TaskRepository) GetActiveTasksForUsers(now time.Time, opts TaskFilterOptions) ([]models.Task, error) {
|
||||
var tasks []models.Task
|
||||
|
||||
// Get all active, non-completed tasks
|
||||
query := r.db.Model(&models.Task{}).
|
||||
Scopes(task.ScopeActive, task.ScopeNotCompleted)
|
||||
|
||||
// Include in-progress tasks if specified
|
||||
if !opts.IncludeInProgress {
|
||||
query = query.Scopes(task.ScopeNotInProgress)
|
||||
}
|
||||
|
||||
// Apply filters and preloads
|
||||
query = r.applyFilterOptions(query, opts)
|
||||
|
||||
// Order by due date for consistent processing
|
||||
query = query.Order("COALESCE(next_due_date, due_date) ASC NULLS LAST")
|
||||
|
||||
err := query.Find(&tasks).Error
|
||||
return tasks, err
|
||||
}
|
||||
|
||||
// === Task CRUD ===
|
||||
|
||||
// FindByID finds a task by ID with preloaded relations
|
||||
|
||||
Reference in New Issue
Block a user