Security: - Replace all binding: tags with validate: + c.Validate() in admin handlers - Add rate limiting to auth endpoints (login, register, password reset) - Add security headers (HSTS, XSS protection, nosniff, frame options) - Wire Google Pub/Sub token verification into webhook handler - Replace ParseUnverified with proper OIDC/JWKS key verification - Verify inner Apple JWS signatures in webhook handler - Add io.LimitReader (1MB) to all webhook body reads - Add ownership verification to file deletion - Move hardcoded admin credentials to env vars - Add uniqueIndex to User.Email - Hide ConfirmationCode from JSON serialization - Mask confirmation codes in admin responses - Use http.DetectContentType for upload validation - Fix path traversal in storage service - Replace os.Getenv with Viper in stripe service - Sanitize Redis URLs before logging - Separate DEBUG_FIXED_CODES from DEBUG flag - Reject weak SECRET_KEY in production - Add host check on /_next/* proxy routes - Use explicit localhost CORS origins in debug mode - Replace err.Error() with generic messages in all admin error responses Critical fixes: - Rewrite FCM to HTTP v1 API with OAuth 2.0 service account auth - Fix user_customuser -> auth_user table names in raw SQL - Fix dashboard verified query to use UserProfile model - Add escapeLikeWildcards() to prevent SQL wildcard injection Bug fixes: - Add bounds checks for days/expiring_soon query params (1-3650) - Add receipt_data/transaction_id empty-check to RestoreSubscription - Change Active bool -> *bool in device handler - Check all unchecked GORM/FindByIDWithProfile errors - Add validation for notification hour fields (0-23) - Add max=10000 validation on task description updates Transactions & data integrity: - Wrap registration flow in transaction - Wrap QuickComplete in transaction - Move image creation inside completion transaction - Wrap SetSpecialties in transaction - Wrap GetOrCreateToken in transaction - Wrap completion+image deletion in transaction Performance: - Batch completion summaries (2 queries vs 2N) - Reuse single http.Client in IAP validation - Cache dashboard counts (30s TTL) - Batch COUNT queries in admin user list - Add Limit(500) to document queries - Add reminder_stage+due_date filters to reminder queries - Parse AllowedTypes once at init - In-memory user cache in auth middleware (30s TTL) - Timezone change detection cache - Optimize P95 with per-endpoint sorted buffers - Replace crypto/md5 with hash/fnv for ETags Code quality: - Add sync.Once to all monitoring Stop()/Close() methods - Replace 8 fmt.Printf with zerolog in auth service - Log previously discarded errors - Standardize delete response shapes - Route hardcoded English through i18n - Remove FileURL from DocumentResponse (keep MediaURL only) - Thread user timezone through kanban board responses - Initialize empty slices to prevent null JSON - Extract shared field map for task Update/UpdateTx - Delete unused SoftDeleteModel, min(), formatCron, legacy handlers Worker & jobs: - Wire Asynq email infrastructure into worker - Register HandleReminderLogCleanup with daily 3AM cron - Use per-user timezone in HandleSmartReminder - Replace direct DB queries with repository calls - Delete legacy reminder handlers (~200 lines) - Delete unused task type constants Dependencies: - Replace archived jung-kurt/gofpdf with go-pdf/fpdf - Replace unmaintained gomail.v2 with wneessen/go-mail - Add TODO for Echo jwt v3 transitive dep removal Test infrastructure: - Fix MakeRequest/SeedLookupData error handling - Replace os.Exit(0) with t.Skip() in scope/consistency tests - Add 11 new FCM v1 tests Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
227 lines
6.7 KiB
Go
227 lines
6.7 KiB
Go
package repositories
|
|
|
|
import (
|
|
"time"
|
|
|
|
"gorm.io/gorm"
|
|
|
|
"github.com/treytartt/honeydue-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
|
|
}
|
|
|
|
// ReminderKey uniquely identifies a reminder that may have been sent.
|
|
type ReminderKey struct {
|
|
TaskID uint
|
|
UserID uint
|
|
DueDate time.Time
|
|
Stage models.ReminderStage
|
|
}
|
|
|
|
// HasSentReminderBatch checks which reminders from the given list have already been sent.
|
|
// Returns a set of indices into the input slice that have already been sent.
|
|
// This replaces N individual HasSentReminder calls with a single query.
|
|
func (r *ReminderRepository) HasSentReminderBatch(keys []ReminderKey) (map[int]bool, error) {
|
|
result := make(map[int]bool)
|
|
if len(keys) == 0 {
|
|
return result, nil
|
|
}
|
|
|
|
// Build a lookup from (task_id, user_id, due_date, stage) -> index
|
|
type normalizedKey struct {
|
|
TaskID uint
|
|
UserID uint
|
|
DueDate string
|
|
Stage models.ReminderStage
|
|
}
|
|
keyToIdx := make(map[normalizedKey][]int, len(keys))
|
|
|
|
// Collect unique task IDs and user IDs for the WHERE clause
|
|
taskIDSet := make(map[uint]bool)
|
|
userIDSet := make(map[uint]bool)
|
|
for i, k := range keys {
|
|
taskIDSet[k.TaskID] = true
|
|
userIDSet[k.UserID] = true
|
|
dueDateOnly := time.Date(k.DueDate.Year(), k.DueDate.Month(), k.DueDate.Day(), 0, 0, 0, 0, time.UTC)
|
|
nk := normalizedKey{
|
|
TaskID: k.TaskID,
|
|
UserID: k.UserID,
|
|
DueDate: dueDateOnly.Format("2006-01-02"),
|
|
Stage: k.Stage,
|
|
}
|
|
keyToIdx[nk] = append(keyToIdx[nk], i)
|
|
}
|
|
|
|
taskIDs := make([]uint, 0, len(taskIDSet))
|
|
for id := range taskIDSet {
|
|
taskIDs = append(taskIDs, id)
|
|
}
|
|
userIDs := make([]uint, 0, len(userIDSet))
|
|
for id := range userIDSet {
|
|
userIDs = append(userIDs, id)
|
|
}
|
|
|
|
// Collect unique stages and due dates for tighter SQL filtering
|
|
stageSet := make(map[models.ReminderStage]bool)
|
|
dueDateSet := make(map[string]bool)
|
|
var minDueDate, maxDueDate time.Time
|
|
for _, k := range keys {
|
|
stageSet[k.Stage] = true
|
|
dueDateOnly := time.Date(k.DueDate.Year(), k.DueDate.Month(), k.DueDate.Day(), 0, 0, 0, 0, time.UTC)
|
|
dueDateSet[dueDateOnly.Format("2006-01-02")] = true
|
|
if minDueDate.IsZero() || dueDateOnly.Before(minDueDate) {
|
|
minDueDate = dueDateOnly
|
|
}
|
|
if maxDueDate.IsZero() || dueDateOnly.After(maxDueDate) {
|
|
maxDueDate = dueDateOnly
|
|
}
|
|
}
|
|
stages := make([]models.ReminderStage, 0, len(stageSet))
|
|
for s := range stageSet {
|
|
stages = append(stages, s)
|
|
}
|
|
|
|
// Query matching reminder logs with tighter filters to reduce result set.
|
|
// Filter on reminder_stage and due_date range in addition to task_id/user_id.
|
|
var logs []models.TaskReminderLog
|
|
err := r.db.Where(
|
|
"task_id IN ? AND user_id IN ? AND reminder_stage IN ? AND due_date >= ? AND due_date <= ?",
|
|
taskIDs, userIDs, stages, minDueDate, maxDueDate,
|
|
).Find(&logs).Error
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// Match returned logs against our key set
|
|
for _, l := range logs {
|
|
dueDateStr := l.DueDate.Format("2006-01-02")
|
|
nk := normalizedKey{
|
|
TaskID: l.TaskID,
|
|
UserID: l.UserID,
|
|
DueDate: dueDateStr,
|
|
Stage: l.ReminderStage,
|
|
}
|
|
if indices, ok := keyToIdx[nk]; ok {
|
|
for _, idx := range indices {
|
|
result[idx] = true
|
|
}
|
|
}
|
|
}
|
|
|
|
return result, 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
|
|
}
|