Files
apocapoc-api/internal/application/queries/get_todays_habits.go
T
david 9f673bfca3 Refactor habit entries: remove soft delete and add smart pagination
Remove soft delete from HabitEntry:
- Eliminate DeletedAt field from entity and database
- Change UnmarkHabit from soft delete to hard delete
- Simplify all queries removing deleted_at checks
- Update migration to remove deleted_at column

Add date filtering and smart pagination to GetHabitEntries:
- Support optional from/to date parameters
- Implement intelligent pagination rules:
  * No date range: pagination required
  * Date range > 1 year: pagination required
  * Date range ≤ 1 year: pagination optional
- Pagination defaults (page=1, limit=50) only when required
- Return metadata with total count, page, and limit

Technical improvements:
- Cleaner codebase without soft delete complexity
- Better performance (no filtering in queries)
- More intuitive API with flexible pagination
- Comprehensive test coverage for validation rules
2025-11-26 16:33:40 +01:00

93 lines
1.8 KiB
Go

package queries
import (
"context"
"time"
"apocapoc-api/internal/domain/repositories"
"apocapoc-api/internal/shared/utils"
)
type TodaysHabitDTO struct {
ID string
Name string
Type string
TargetValue *float64
ScheduledDate time.Time
IsCarriedOver bool
}
type GetTodaysHabitsQuery struct {
UserID string
Timezone string
Date time.Time
}
type GetTodaysHabitsHandler struct {
habitRepo repositories.HabitRepository
entryRepo repositories.HabitEntryRepository
}
func NewGetTodaysHabitsHandler(
habitRepo repositories.HabitRepository,
entryRepo repositories.HabitEntryRepository,
) *GetTodaysHabitsHandler {
return &GetTodaysHabitsHandler{
habitRepo: habitRepo,
entryRepo: entryRepo,
}
}
func (h *GetTodaysHabitsHandler) Handle(
ctx context.Context,
query GetTodaysHabitsQuery,
) ([]TodaysHabitDTO, error) {
habits, err := h.habitRepo.FindActiveByUserID(ctx, query.UserID)
if err != nil {
return nil, err
}
var result []TodaysHabitDTO
for _, habit := range habits {
shouldAppear := utils.ShouldAppearToday(
string(habit.Frequency),
habit.SpecificDays,
habit.SpecificDates,
query.Date,
)
if !shouldAppear && !habit.CarryOver {
continue
}
entries, _ := h.entryRepo.FindByHabitIDAndDateRange(
ctx,
habit.ID,
query.Date.AddDate(0, 0, -30),
query.Date,
)
isCompleted := false
for _, entry := range entries {
if entry.ScheduledDate.Equal(query.Date) {
isCompleted = true
break
}
}
if !isCompleted {
result = append(result, TodaysHabitDTO{
ID: habit.ID,
Name: habit.Name,
Type: string(habit.Type),
TargetValue: habit.TargetValue,
ScheduledDate: query.Date,
IsCarriedOver: !shouldAppear && habit.CarryOver,
})
}
}
return result, nil
}