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
This commit is contained in:
@@ -69,6 +69,13 @@ type HabitEntryResponse struct {
|
||||
Value *float64 `json:"value,omitempty"`
|
||||
}
|
||||
|
||||
type HabitEntriesResponse struct {
|
||||
Entries []HabitEntryResponse `json:"entries"`
|
||||
Total int `json:"total"`
|
||||
Page int `json:"page"`
|
||||
Limit int `json:"limit"`
|
||||
}
|
||||
|
||||
type ErrorResponse struct {
|
||||
Error string `json:"error"`
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package http
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"apocapoc-api/internal/application/commands"
|
||||
@@ -250,7 +251,64 @@ func (h *HabitHandlers) GetHabitEntries(w http.ResponseWriter, r *http.Request)
|
||||
UserID: userID,
|
||||
}
|
||||
|
||||
entries, err := h.getHabitEntriesHandler.Handle(r.Context(), query)
|
||||
if fromStr := r.URL.Query().Get("from"); fromStr != "" {
|
||||
from, err := time.Parse("2006-01-02", fromStr)
|
||||
if err != nil {
|
||||
respondError(w, http.StatusBadRequest, "Invalid 'from' date format (use YYYY-MM-DD)")
|
||||
return
|
||||
}
|
||||
query.From = &from
|
||||
}
|
||||
|
||||
if toStr := r.URL.Query().Get("to"); toStr != "" {
|
||||
to, err := time.Parse("2006-01-02", toStr)
|
||||
if err != nil {
|
||||
respondError(w, http.StatusBadRequest, "Invalid 'to' date format (use YYYY-MM-DD)")
|
||||
return
|
||||
}
|
||||
query.To = &to
|
||||
}
|
||||
|
||||
var dateRangeDays int
|
||||
if query.From != nil && query.To != nil {
|
||||
dateRangeDays = int(query.To.Sub(*query.From).Hours() / 24)
|
||||
}
|
||||
|
||||
requiresPagination := false
|
||||
if query.From == nil || query.To == nil {
|
||||
requiresPagination = true
|
||||
} else if dateRangeDays > 365 {
|
||||
requiresPagination = true
|
||||
}
|
||||
|
||||
if pageStr := r.URL.Query().Get("page"); pageStr != "" {
|
||||
page, err := strconv.Atoi(pageStr)
|
||||
if err != nil || page < 1 {
|
||||
respondError(w, http.StatusBadRequest, "Invalid 'page' parameter")
|
||||
return
|
||||
}
|
||||
query.Page = page
|
||||
} else if requiresPagination {
|
||||
query.Page = 1
|
||||
}
|
||||
|
||||
if limitStr := r.URL.Query().Get("limit"); limitStr != "" {
|
||||
limit, err := strconv.Atoi(limitStr)
|
||||
if err != nil || limit < 1 || limit > 100 {
|
||||
respondError(w, http.StatusBadRequest, "Invalid 'limit' parameter (must be 1-100)")
|
||||
return
|
||||
}
|
||||
query.Limit = limit
|
||||
} else if requiresPagination {
|
||||
query.Limit = 50
|
||||
}
|
||||
|
||||
if requiresPagination && query.Limit == 0 {
|
||||
respondError(w, http.StatusBadRequest, "Pagination required: provide 'limit' parameter or use date range \u2264 1 year")
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.getHabitEntriesHandler.Handle(r.Context(), query)
|
||||
if err != nil {
|
||||
if err == errors.ErrNotFound {
|
||||
respondError(w, http.StatusNotFound, "Habit not found")
|
||||
@@ -264,9 +322,9 @@ func (h *HabitHandlers) GetHabitEntries(w http.ResponseWriter, r *http.Request)
|
||||
return
|
||||
}
|
||||
|
||||
response := make([]HabitEntryResponse, len(entries))
|
||||
for i, entry := range entries {
|
||||
response[i] = HabitEntryResponse{
|
||||
entries := make([]HabitEntryResponse, len(result.Entries))
|
||||
for i, entry := range result.Entries {
|
||||
entries[i] = HabitEntryResponse{
|
||||
ID: entry.ID,
|
||||
HabitID: entry.HabitID,
|
||||
ScheduledDate: entry.ScheduledDate,
|
||||
@@ -275,6 +333,13 @@ func (h *HabitHandlers) GetHabitEntries(w http.ResponseWriter, r *http.Request)
|
||||
}
|
||||
}
|
||||
|
||||
response := HabitEntriesResponse{
|
||||
Entries: entries,
|
||||
Total: result.Total,
|
||||
Page: result.Page,
|
||||
Limit: result.Limit,
|
||||
}
|
||||
|
||||
respondJSON(w, http.StatusOK, response)
|
||||
}
|
||||
|
||||
|
||||
@@ -52,7 +52,7 @@ func (r *HabitEntryRepository) FindByHabitIDAndDateRange(
|
||||
from, to time.Time,
|
||||
) ([]*entities.HabitEntry, error) {
|
||||
query := `
|
||||
SELECT id, habit_id, scheduled_date, completed_at, value, deleted_at
|
||||
SELECT id, habit_id, scheduled_date, completed_at, value
|
||||
FROM habit_entries
|
||||
WHERE habit_id = ?
|
||||
AND scheduled_date >= ?
|
||||
@@ -76,11 +76,11 @@ func (r *HabitEntryRepository) FindByHabitIDAndDateRange(
|
||||
func (r *HabitEntryRepository) Update(ctx context.Context, entry *entities.HabitEntry) error {
|
||||
query := `
|
||||
UPDATE habit_entries
|
||||
SET deleted_at = ?
|
||||
SET value = ?, completed_at = ?
|
||||
WHERE id = ?
|
||||
`
|
||||
|
||||
result, err := r.db.ExecContext(ctx, query, entry.DeletedAt, entry.ID)
|
||||
result, err := r.db.ExecContext(ctx, query, entry.Value, entry.CompletedAt, entry.ID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to update entry: %w", err)
|
||||
}
|
||||
@@ -100,7 +100,6 @@ func (r *HabitEntryRepository) scanEntries(rows *sql.Rows) ([]*entities.HabitEnt
|
||||
var (
|
||||
entry entities.HabitEntry
|
||||
scheduledDate string
|
||||
deletedAt sql.NullTime
|
||||
)
|
||||
|
||||
err := rows.Scan(
|
||||
@@ -109,7 +108,6 @@ func (r *HabitEntryRepository) scanEntries(rows *sql.Rows) ([]*entities.HabitEnt
|
||||
&scheduledDate,
|
||||
&entry.CompletedAt,
|
||||
&entry.Value,
|
||||
&deletedAt,
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
@@ -125,10 +123,6 @@ func (r *HabitEntryRepository) scanEntries(rows *sql.Rows) ([]*entities.HabitEnt
|
||||
}
|
||||
entry.ScheduledDate = parsedDate
|
||||
|
||||
if deletedAt.Valid {
|
||||
entry.DeletedAt = &deletedAt.Time
|
||||
}
|
||||
|
||||
entries = append(entries, &entry)
|
||||
}
|
||||
|
||||
@@ -137,7 +131,7 @@ func (r *HabitEntryRepository) scanEntries(rows *sql.Rows) ([]*entities.HabitEnt
|
||||
|
||||
func (r *HabitEntryRepository) FindByID(ctx context.Context, id string) (*entities.HabitEntry, error) {
|
||||
query := `
|
||||
SELECT id, habit_id, scheduled_date, completed_at, value, deleted_at
|
||||
SELECT id, habit_id, scheduled_date, completed_at, value
|
||||
FROM habit_entries
|
||||
WHERE id = ?
|
||||
`
|
||||
@@ -145,7 +139,6 @@ func (r *HabitEntryRepository) FindByID(ctx context.Context, id string) (*entiti
|
||||
var (
|
||||
entry entities.HabitEntry
|
||||
scheduledDate string
|
||||
deletedAt sql.NullTime
|
||||
)
|
||||
|
||||
err := r.db.QueryRowContext(ctx, query, id).Scan(
|
||||
@@ -154,7 +147,6 @@ func (r *HabitEntryRepository) FindByID(ctx context.Context, id string) (*entiti
|
||||
&scheduledDate,
|
||||
&entry.CompletedAt,
|
||||
&entry.Value,
|
||||
&deletedAt,
|
||||
)
|
||||
|
||||
if err == sql.ErrNoRows {
|
||||
@@ -173,16 +165,12 @@ func (r *HabitEntryRepository) FindByID(ctx context.Context, id string) (*entiti
|
||||
}
|
||||
entry.ScheduledDate = parsedDate
|
||||
|
||||
if deletedAt.Valid {
|
||||
entry.DeletedAt = &deletedAt.Time
|
||||
}
|
||||
|
||||
return &entry, nil
|
||||
}
|
||||
|
||||
func (r *HabitEntryRepository) FindByHabitID(ctx context.Context, habitID string) ([]*entities.HabitEntry, error) {
|
||||
query := `
|
||||
SELECT id, habit_id, scheduled_date, completed_at, value, deleted_at
|
||||
SELECT id, habit_id, scheduled_date, completed_at, value
|
||||
FROM habit_entries
|
||||
WHERE habit_id = ?
|
||||
ORDER BY scheduled_date DESC
|
||||
@@ -199,11 +187,10 @@ func (r *HabitEntryRepository) FindByHabitID(ctx context.Context, habitID string
|
||||
|
||||
func (r *HabitEntryRepository) FindPendingByHabitID(ctx context.Context, habitID string, beforeDate time.Time) ([]*entities.HabitEntry, error) {
|
||||
query := `
|
||||
SELECT id, habit_id, scheduled_date, completed_at, value, deleted_at
|
||||
SELECT id, habit_id, scheduled_date, completed_at, value
|
||||
FROM habit_entries
|
||||
WHERE habit_id = ?
|
||||
AND scheduled_date < ?
|
||||
AND deleted_at IS NULL
|
||||
ORDER BY scheduled_date DESC
|
||||
`
|
||||
|
||||
|
||||
@@ -56,7 +56,6 @@ CREATE TABLE IF NOT EXISTS habit_entries (
|
||||
scheduled_date DATE NOT NULL,
|
||||
completed_at DATETIME NOT NULL,
|
||||
value REAL,
|
||||
deleted_at DATETIME,
|
||||
FOREIGN KEY (habit_id) REFERENCES habits(id) ON DELETE CASCADE,
|
||||
UNIQUE(habit_id, scheduled_date)
|
||||
);
|
||||
@@ -67,5 +66,4 @@ CREATE INDEX IF NOT EXISTS idx_habits_user ON habits(user_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_habits_active ON habits(user_id, archived_at);
|
||||
CREATE INDEX IF NOT EXISTS idx_entries_habit ON habit_entries(habit_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_entries_scheduled ON habit_entries(scheduled_date);
|
||||
CREATE INDEX IF NOT EXISTS idx_entries_deleted ON habit_entries(deleted_at);
|
||||
`
|
||||
|
||||
Reference in New Issue
Block a user