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>
236 lines
10 KiB
Go
236 lines
10 KiB
Go
package models
|
|
|
|
import (
|
|
"time"
|
|
|
|
"github.com/shopspring/decimal"
|
|
)
|
|
|
|
// TaskCategory represents the task_taskcategory table
|
|
type TaskCategory struct {
|
|
BaseModel
|
|
Name string `gorm:"column:name;size:50;not null" json:"name"`
|
|
Description string `gorm:"column:description;type:text" json:"description"`
|
|
Icon string `gorm:"column:icon;size:50" json:"icon"`
|
|
Color string `gorm:"column:color;size:7" json:"color"` // Hex color
|
|
DisplayOrder int `gorm:"column:display_order;default:0" json:"display_order"`
|
|
}
|
|
|
|
// TableName returns the table name for GORM
|
|
func (TaskCategory) TableName() string {
|
|
return "task_taskcategory"
|
|
}
|
|
|
|
// TaskPriority represents the task_taskpriority table
|
|
type TaskPriority struct {
|
|
BaseModel
|
|
Name string `gorm:"column:name;size:20;not null" json:"name"`
|
|
Level int `gorm:"column:level;not null" json:"level"` // 1=low, 2=medium, 3=high, 4=urgent
|
|
Color string `gorm:"column:color;size:7" json:"color"`
|
|
DisplayOrder int `gorm:"column:display_order;default:0" json:"display_order"`
|
|
}
|
|
|
|
// TableName returns the table name for GORM
|
|
func (TaskPriority) TableName() string {
|
|
return "task_taskpriority"
|
|
}
|
|
|
|
// TaskFrequency represents the task_taskfrequency table
|
|
type TaskFrequency struct {
|
|
BaseModel
|
|
Name string `gorm:"column:name;size:20;not null" json:"name"`
|
|
Days *int `gorm:"column:days" json:"days"` // Number of days between occurrences (nil = one-time)
|
|
DisplayOrder int `gorm:"column:display_order;default:0" json:"display_order"`
|
|
}
|
|
|
|
// TableName returns the table name for GORM
|
|
func (TaskFrequency) TableName() string {
|
|
return "task_taskfrequency"
|
|
}
|
|
|
|
// Task represents the task_task table
|
|
type Task struct {
|
|
BaseModel
|
|
ResidenceID uint `gorm:"column:residence_id;index;not null" json:"residence_id"`
|
|
Residence Residence `gorm:"foreignKey:ResidenceID" json:"residence,omitempty"`
|
|
CreatedByID uint `gorm:"column:created_by_id;index;not null" json:"created_by_id"`
|
|
CreatedBy User `gorm:"foreignKey:CreatedByID" json:"created_by,omitempty"`
|
|
AssignedToID *uint `gorm:"column:assigned_to_id;index" json:"assigned_to_id"`
|
|
AssignedTo *User `gorm:"foreignKey:AssignedToID" json:"assigned_to,omitempty"`
|
|
|
|
Title string `gorm:"column:title;size:200;not null" json:"title"`
|
|
Description string `gorm:"column:description;type:text" json:"description"`
|
|
|
|
CategoryID *uint `gorm:"column:category_id;index" json:"category_id"`
|
|
Category *TaskCategory `gorm:"foreignKey:CategoryID" json:"category,omitempty"`
|
|
PriorityID *uint `gorm:"column:priority_id;index" json:"priority_id"`
|
|
Priority *TaskPriority `gorm:"foreignKey:PriorityID" json:"priority,omitempty"`
|
|
FrequencyID *uint `gorm:"column:frequency_id;index" json:"frequency_id"`
|
|
Frequency *TaskFrequency `gorm:"foreignKey:FrequencyID" json:"frequency,omitempty"`
|
|
CustomIntervalDays *int `gorm:"column:custom_interval_days" json:"custom_interval_days"` // For "Custom" frequency, user-specified days
|
|
|
|
// In Progress flag - replaces status lookup
|
|
InProgress bool `gorm:"column:in_progress;default:false;index" json:"in_progress"`
|
|
|
|
DueDate *time.Time `gorm:"column:due_date;type:date;index" json:"due_date"`
|
|
NextDueDate *time.Time `gorm:"column:next_due_date;type:date;index" json:"next_due_date"` // For recurring tasks, updated after each completion
|
|
EstimatedCost *decimal.Decimal `gorm:"column:estimated_cost;type:decimal(10,2)" json:"estimated_cost"`
|
|
ActualCost *decimal.Decimal `gorm:"column:actual_cost;type:decimal(10,2)" json:"actual_cost"`
|
|
|
|
// Contractor association
|
|
ContractorID *uint `gorm:"column:contractor_id;index" json:"contractor_id"`
|
|
// Contractor *Contractor `gorm:"foreignKey:ContractorID" json:"contractor,omitempty"`
|
|
|
|
// State flags
|
|
IsCancelled bool `gorm:"column:is_cancelled;default:false;index" json:"is_cancelled"`
|
|
IsArchived bool `gorm:"column:is_archived;default:false;index" json:"is_archived"`
|
|
|
|
// Optimistic locking version
|
|
Version int `gorm:"column:version;not null;default:1" json:"-"`
|
|
|
|
// Parent task for recurring tasks
|
|
ParentTaskID *uint `gorm:"column:parent_task_id;index" json:"parent_task_id"`
|
|
ParentTask *Task `gorm:"foreignKey:ParentTaskID" json:"parent_task,omitempty"`
|
|
|
|
// Completions
|
|
Completions []TaskCompletion `gorm:"foreignKey:TaskID" json:"completions,omitempty"`
|
|
|
|
// CompletionCount is a computed field populated via subquery for optimized queries.
|
|
// When populated (>= 0 and Completions slice is empty), predicates should use this
|
|
// instead of len(Completions) to avoid N+1 queries.
|
|
CompletionCount int `gorm:"-:all" json:"-"`
|
|
}
|
|
|
|
// TableName returns the table name for GORM
|
|
func (Task) TableName() string {
|
|
return "task_task"
|
|
}
|
|
|
|
// IsOverdue returns true if the task is past its due date and not completed.
|
|
//
|
|
// IMPORTANT: This method delegates to the predicates package which is the
|
|
// single source of truth for task logic. It uses EffectiveDate (NextDueDate ?? DueDate)
|
|
// rather than just DueDate, ensuring consistency with kanban categorization.
|
|
//
|
|
// Uses day-based comparison: a task due TODAY is NOT overdue, it only becomes
|
|
// overdue the NEXT day.
|
|
//
|
|
// Deprecated: Prefer using task.IsOverdue(t, time.Now().UTC()) directly for explicit time control.
|
|
func (t *Task) IsOverdue() bool {
|
|
return t.IsOverdueAt(time.Now().UTC())
|
|
}
|
|
|
|
// IsOverdueAt returns true if the task would be overdue at the given time.
|
|
// Uses day-based comparison: a task due on the same day as `now` is NOT overdue.
|
|
func (t *Task) IsOverdueAt(now time.Time) bool {
|
|
// Logic must match predicates.IsOverdue exactly:
|
|
// - Check active (not cancelled, not archived)
|
|
// - Check not completed (NextDueDate != nil || no completions)
|
|
// - Check effective date < start of today
|
|
if t.IsCancelled || t.IsArchived {
|
|
return false
|
|
}
|
|
// Completed check: NextDueDate == nil AND has completions
|
|
// Supports both preloaded Completions and computed CompletionCount
|
|
hasCompletions := len(t.Completions) > 0 || t.CompletionCount > 0
|
|
if t.NextDueDate == nil && hasCompletions {
|
|
return false
|
|
}
|
|
// Effective date: NextDueDate ?? DueDate
|
|
effectiveDate := t.NextDueDate
|
|
if effectiveDate == nil {
|
|
effectiveDate = t.DueDate
|
|
}
|
|
if effectiveDate == nil {
|
|
return false
|
|
}
|
|
// Day-based comparison: compare against start of today
|
|
startOfDay := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
|
|
return effectiveDate.Before(startOfDay)
|
|
}
|
|
|
|
// IsDueSoon returns true if the task is due within the specified days.
|
|
//
|
|
// IMPORTANT: This method uses EffectiveDate (NextDueDate ?? DueDate)
|
|
// rather than just DueDate, ensuring consistency with kanban categorization.
|
|
//
|
|
// Deprecated: Prefer using task.IsDueSoon(t, time.Now().UTC(), days) directly for explicit time control.
|
|
func (t *Task) IsDueSoon(days int) bool {
|
|
// Delegate to predicates package logic - single source of truth
|
|
// Logic must match predicates.IsDueSoon exactly
|
|
if t.IsCancelled || t.IsArchived {
|
|
return false
|
|
}
|
|
// Completed check: NextDueDate == nil AND has completions
|
|
// Supports both preloaded Completions and computed CompletionCount
|
|
hasCompletions := len(t.Completions) > 0 || t.CompletionCount > 0
|
|
if t.NextDueDate == nil && hasCompletions {
|
|
return false
|
|
}
|
|
// Effective date: NextDueDate ?? DueDate
|
|
effectiveDate := t.NextDueDate
|
|
if effectiveDate == nil {
|
|
effectiveDate = t.DueDate
|
|
}
|
|
if effectiveDate == nil {
|
|
return false
|
|
}
|
|
now := time.Now().UTC()
|
|
threshold := now.AddDate(0, 0, days)
|
|
// Due soon = not overdue AND before threshold
|
|
return !effectiveDate.Before(now) && effectiveDate.Before(threshold)
|
|
}
|
|
|
|
// TaskCompletion represents the task_taskcompletion table
|
|
type TaskCompletion struct {
|
|
BaseModel
|
|
TaskID uint `gorm:"column:task_id;index;not null" json:"task_id"`
|
|
Task Task `gorm:"foreignKey:TaskID" json:"-"`
|
|
CompletedByID uint `gorm:"column:completed_by_id;index;not null" json:"completed_by_id"`
|
|
CompletedBy User `gorm:"foreignKey:CompletedByID" json:"completed_by,omitempty"`
|
|
CompletedAt time.Time `gorm:"column:completed_at;not null" json:"completed_at"`
|
|
Notes string `gorm:"column:notes;type:text" json:"notes"`
|
|
ActualCost *decimal.Decimal `gorm:"column:actual_cost;type:decimal(10,2)" json:"actual_cost"`
|
|
Rating *int `gorm:"column:rating" json:"rating"` // 1-5 star rating
|
|
CompletedFromColumn string `gorm:"column:completed_from_column;type:varchar(50);default:'completed_tasks'" json:"completed_from_column"`
|
|
|
|
// Multiple images support
|
|
Images []TaskCompletionImage `gorm:"foreignKey:CompletionID" json:"images,omitempty"`
|
|
}
|
|
|
|
// TableName returns the table name for GORM
|
|
func (TaskCompletion) TableName() string {
|
|
return "task_taskcompletion"
|
|
}
|
|
|
|
// TaskCompletionImage represents the task_taskcompletionimage table
|
|
type TaskCompletionImage struct {
|
|
BaseModel
|
|
CompletionID uint `gorm:"column:completion_id;index;not null" json:"completion_id"`
|
|
ImageURL string `gorm:"column:image_url;size:500;not null" json:"image_url"`
|
|
Caption string `gorm:"column:caption;size:255" json:"caption"`
|
|
}
|
|
|
|
// TableName returns the table name for GORM
|
|
func (TaskCompletionImage) TableName() string {
|
|
return "task_taskcompletionimage"
|
|
}
|
|
|
|
// KanbanColumn represents a column in the kanban board
|
|
type KanbanColumn struct {
|
|
Name string `json:"name"`
|
|
DisplayName string `json:"display_name"`
|
|
ButtonTypes []string `json:"button_types"`
|
|
Icons map[string]string `json:"icons"`
|
|
Color string `json:"color"`
|
|
Tasks []Task `json:"tasks"`
|
|
Count int `json:"count"`
|
|
}
|
|
|
|
// KanbanBoard represents the full kanban board response
|
|
type KanbanBoard struct {
|
|
Columns []KanbanColumn `json:"columns"`
|
|
DaysThreshold int `json:"days_threshold"`
|
|
ResidenceID string `json:"residence_id"`
|
|
}
|