feat: allow editing frequency and target_value on habits

- Add frequency to UpdateHabitRequest (was immutable, now editable)
- Validate frequency + specific_days/dates coherence on update
- Keep type and is_negative immutable (they change entry semantics)
- Remove completion_rate references from swagger and README
This commit is contained in:
2026-03-08 00:02:37 +01:00
parent 2b059ec334
commit 63dd650755
11 changed files with 133 additions and 36 deletions
+1 -1
View File
@@ -20,7 +20,7 @@ REST API for habit tracking built with Go. Self-hosted alternative for developer
- Multiple habit types: Boolean, Counter, Value - Multiple habit types: Boolean, Counter, Value
- Flexible scheduling: Daily, Weekly, Monthly - Flexible scheduling: Daily, Weekly, Monthly
- Statistics: Streaks, completion rates, progress tracking - Statistics: Streaks and completions tracking
- JWT authentication, rate limiting, optional email verification - JWT authentication, rate limiting, optional email verification
- Registration modes: Open or closed - Registration modes: Open or closed
- SQLite database (single file) - SQLite database (single file)
+7 -1
View File
@@ -1172,7 +1172,7 @@ const docTemplate = `{
"BearerAuth": [] "BearerAuth": []
} }
], ],
"description": "Get statistics for a specific habit including streaks and completion rates", "description": "Get statistics for a specific habit including streaks and completions",
"produces": [ "produces": [
"application/json" "application/json"
], ],
@@ -1800,6 +1800,12 @@ const docTemplate = `{
"description": { "description": {
"type": "string" "type": "string"
}, },
"frequency": {
"$ref": "#/definitions/value_objects.Frequency"
},
"is_negative": {
"type": "boolean"
},
"name": { "name": {
"type": "string" "type": "string"
}, },
+7 -1
View File
@@ -1164,7 +1164,7 @@
"BearerAuth": [] "BearerAuth": []
} }
], ],
"description": "Get statistics for a specific habit including streaks and completion rates", "description": "Get statistics for a specific habit including streaks and completions",
"produces": [ "produces": [
"application/json" "application/json"
], ],
@@ -1792,6 +1792,12 @@
"description": { "description": {
"type": "string" "type": "string"
}, },
"frequency": {
"$ref": "#/definitions/value_objects.Frequency"
},
"is_negative": {
"type": "boolean"
},
"name": { "name": {
"type": "string" "type": "string"
}, },
+5 -2
View File
@@ -268,6 +268,10 @@ definitions:
type: boolean type: boolean
description: description:
type: string type: string
frequency:
$ref: '#/definitions/value_objects.Frequency'
is_negative:
type: boolean
name: name:
type: string type: string
specific_dates: specific_dates:
@@ -1189,8 +1193,7 @@ paths:
- system - system
/stats/habits/{id}: /stats/habits/{id}:
get: get:
description: Get statistics for a specific habit including streaks and completion description: Get statistics for a specific habit including streaks and completions
rates
parameters: parameters:
- description: Habit ID - description: Habit ID
in: path in: path
+19 -4
View File
@@ -5,6 +5,7 @@ import (
"strings" "strings"
"apocapoc-api/internal/domain/repositories" "apocapoc-api/internal/domain/repositories"
"apocapoc-api/internal/domain/value_objects"
"apocapoc-api/internal/shared/errors" "apocapoc-api/internal/shared/errors"
) )
@@ -13,10 +14,11 @@ type UpdateHabitCommand struct {
UserID string UserID string
Name string Name string
Description string Description string
CarryOver bool Frequency value_objects.Frequency
TargetValue *float64
SpecificDays []int SpecificDays []int
SpecificDates []int SpecificDates []int
CarryOver bool
TargetValue *float64
} }
type UpdateHabitHandler struct { type UpdateHabitHandler struct {
@@ -34,6 +36,18 @@ func (h *UpdateHabitHandler) Handle(ctx context.Context, cmd UpdateHabitCommand)
return errors.ErrInvalidInput return errors.ErrInvalidInput
} }
if !cmd.Frequency.IsValid() {
return errors.ErrInvalidInput
}
if cmd.Frequency == value_objects.FrequencyWeekly && len(cmd.SpecificDays) == 0 {
return errors.ErrInvalidInput
}
if cmd.Frequency == value_objects.FrequencyMonthly && len(cmd.SpecificDates) == 0 {
return errors.ErrInvalidInput
}
habit, err := h.habitRepo.FindByID(ctx, cmd.HabitID) habit, err := h.habitRepo.FindByID(ctx, cmd.HabitID)
if err != nil { if err != nil {
return err return err
@@ -49,10 +63,11 @@ func (h *UpdateHabitHandler) Handle(ctx context.Context, cmd UpdateHabitCommand)
habit.Name = cmd.Name habit.Name = cmd.Name
habit.Description = cmd.Description habit.Description = cmd.Description
habit.CarryOver = cmd.CarryOver habit.Frequency = cmd.Frequency
habit.TargetValue = cmd.TargetValue
habit.SpecificDays = cmd.SpecificDays habit.SpecificDays = cmd.SpecificDays
habit.SpecificDates = cmd.SpecificDates habit.SpecificDates = cmd.SpecificDates
habit.CarryOver = cmd.CarryOver
habit.TargetValue = cmd.TargetValue
return h.habitRepo.Update(ctx, habit) return h.habitRepo.Update(ctx, habit)
} }
@@ -48,9 +48,10 @@ func TestUpdateHabitHandler_UpdatesSuccessfully(t *testing.T) {
UserID: "user-123", UserID: "user-123",
Name: "Morning Exercise", Name: "Morning Exercise",
Description: "Updated description", Description: "Updated description",
Frequency: value_objects.FrequencyWeekly,
SpecificDays: []int{1, 3, 5},
CarryOver: true, CarryOver: true,
TargetValue: &newTargetValue, TargetValue: &newTargetValue,
SpecificDays: []int{1, 3, 5},
} }
err := handler.Handle(context.Background(), cmd) err := handler.Handle(context.Background(), cmd)
@@ -67,6 +68,14 @@ func TestUpdateHabitHandler_UpdatesSuccessfully(t *testing.T) {
t.Errorf("Expected description to be updated, got %s", habitRepo.updatedHabit.Description) t.Errorf("Expected description to be updated, got %s", habitRepo.updatedHabit.Description)
} }
if habitRepo.updatedHabit.Frequency != value_objects.FrequencyWeekly {
t.Errorf("Expected frequency WEEKLY, got %s", habitRepo.updatedHabit.Frequency)
}
if len(habitRepo.updatedHabit.SpecificDays) != 3 {
t.Errorf("Expected 3 specific days, got %d", len(habitRepo.updatedHabit.SpecificDays))
}
if !habitRepo.updatedHabit.CarryOver { if !habitRepo.updatedHabit.CarryOver {
t.Error("Expected CarryOver to be true") t.Error("Expected CarryOver to be true")
} }
@@ -74,10 +83,6 @@ func TestUpdateHabitHandler_UpdatesSuccessfully(t *testing.T) {
if habitRepo.updatedHabit.TargetValue == nil || *habitRepo.updatedHabit.TargetValue != 5.0 { if habitRepo.updatedHabit.TargetValue == nil || *habitRepo.updatedHabit.TargetValue != 5.0 {
t.Errorf("Expected target value 5.0, got %v", habitRepo.updatedHabit.TargetValue) t.Errorf("Expected target value 5.0, got %v", habitRepo.updatedHabit.TargetValue)
} }
if len(habitRepo.updatedHabit.SpecificDays) != 3 {
t.Errorf("Expected 3 specific days, got %d", len(habitRepo.updatedHabit.SpecificDays))
}
} }
func TestUpdateHabitHandler_ReturnsErrorWhenHabitNotFound(t *testing.T) { func TestUpdateHabitHandler_ReturnsErrorWhenHabitNotFound(t *testing.T) {
@@ -91,6 +96,7 @@ func TestUpdateHabitHandler_ReturnsErrorWhenHabitNotFound(t *testing.T) {
HabitID: "non-existent", HabitID: "non-existent",
UserID: "user-123", UserID: "user-123",
Name: "Exercise", Name: "Exercise",
Frequency: value_objects.FrequencyDaily,
} }
err := handler.Handle(context.Background(), cmd) err := handler.Handle(context.Background(), cmd)
@@ -114,6 +120,7 @@ func TestUpdateHabitHandler_ReturnsErrorWhenUserDoesNotOwnHabit(t *testing.T) {
HabitID: "habit-1", HabitID: "habit-1",
UserID: "user-456", // Different user UserID: "user-456", // Different user
Name: "Exercise", Name: "Exercise",
Frequency: value_objects.FrequencyDaily,
} }
err := handler.Handle(context.Background(), cmd) err := handler.Handle(context.Background(), cmd)
@@ -138,6 +145,7 @@ func TestUpdateHabitHandler_CannotUpdateArchivedHabit(t *testing.T) {
HabitID: "habit-1", HabitID: "habit-1",
UserID: "user-123", UserID: "user-123",
Name: "Updated Exercise", Name: "Updated Exercise",
Frequency: value_objects.FrequencyDaily,
} }
err := handler.Handle(context.Background(), cmd) err := handler.Handle(context.Background(), cmd)
@@ -161,6 +169,7 @@ func TestUpdateHabitHandler_ValidatesInput(t *testing.T) {
HabitID: "habit-1", HabitID: "habit-1",
UserID: "user-123", UserID: "user-123",
Name: "", // Empty name Name: "", // Empty name
Frequency: value_objects.FrequencyDaily,
} }
err := handler.Handle(context.Background(), cmd) err := handler.Handle(context.Background(), cmd)
@@ -169,3 +178,57 @@ func TestUpdateHabitHandler_ValidatesInput(t *testing.T) {
t.Errorf("Expected ErrInvalidInput for empty name, got %v", err) t.Errorf("Expected ErrInvalidInput for empty name, got %v", err)
} }
} }
func TestUpdateHabitHandler_InvalidFrequency(t *testing.T) {
habitRepo := &mockHabitRepoForUpdate{}
handler := NewUpdateHabitHandler(habitRepo)
cmd := UpdateHabitCommand{
HabitID: "habit-1",
UserID: "user-123",
Name: "Exercise",
Frequency: "INVALID",
}
err := handler.Handle(context.Background(), cmd)
if err != errors.ErrInvalidInput {
t.Errorf("Expected ErrInvalidInput for invalid frequency, got %v", err)
}
}
func TestUpdateHabitHandler_WeeklyRequiresSpecificDays(t *testing.T) {
habitRepo := &mockHabitRepoForUpdate{}
handler := NewUpdateHabitHandler(habitRepo)
cmd := UpdateHabitCommand{
HabitID: "habit-1",
UserID: "user-123",
Name: "Exercise",
Frequency: value_objects.FrequencyWeekly,
}
err := handler.Handle(context.Background(), cmd)
if err != errors.ErrInvalidInput {
t.Errorf("Expected ErrInvalidInput for weekly without specific days, got %v", err)
}
}
func TestUpdateHabitHandler_MonthlyRequiresSpecificDates(t *testing.T) {
habitRepo := &mockHabitRepoForUpdate{}
handler := NewUpdateHabitHandler(habitRepo)
cmd := UpdateHabitCommand{
HabitID: "habit-1",
UserID: "user-123",
Name: "Exercise",
Frequency: value_objects.FrequencyMonthly,
}
err := handler.Handle(context.Background(), cmd)
if err != errors.ErrInvalidInput {
t.Errorf("Expected ErrInvalidInput for monthly without specific dates, got %v", err)
}
}
+1
View File
@@ -22,6 +22,7 @@ type CreateHabitRequest struct {
type UpdateHabitRequest struct { type UpdateHabitRequest struct {
Name string `json:"name"` Name string `json:"name"`
Description string `json:"description"` Description string `json:"description"`
Frequency value_objects.Frequency `json:"frequency"`
SpecificDays []int `json:"specific_days,omitempty"` SpecificDays []int `json:"specific_days,omitempty"`
SpecificDates []int `json:"specific_dates,omitempty"` SpecificDates []int `json:"specific_dates,omitempty"`
CarryOver bool `json:"carry_over"` CarryOver bool `json:"carry_over"`
@@ -313,10 +313,11 @@ func (h *HabitHandlers) UpdateHabit(w http.ResponseWriter, r *http.Request) {
UserID: userID, UserID: userID,
Name: req.Name, Name: req.Name,
Description: req.Description, Description: req.Description,
CarryOver: req.CarryOver, Frequency: req.Frequency,
TargetValue: req.TargetValue,
SpecificDays: req.SpecificDays, SpecificDays: req.SpecificDays,
SpecificDates: req.SpecificDates, SpecificDates: req.SpecificDates,
CarryOver: req.CarryOver,
TargetValue: req.TargetValue,
} }
if err := h.updateHandler.Handle(r.Context(), cmd); err != nil { if err := h.updateHandler.Handle(r.Context(), cmd); err != nil {
@@ -89,6 +89,7 @@ func TestHabitCRUDFlow(t *testing.T) {
reqBody := UpdateHabitRequest{ reqBody := UpdateHabitRequest{
Name: "Morning Exercise", Name: "Morning Exercise",
Description: "Updated description", Description: "Updated description",
Frequency: "DAILY",
} }
rr := makeRequest(t, *ts.Router, "PUT", "/api/v1/habits/"+habitID, reqBody, token) rr := makeRequest(t, *ts.Router, "PUT", "/api/v1/habits/"+habitID, reqBody, token)
@@ -27,7 +27,7 @@ func NewStatsHandlers(
// GetHabitStats godoc // GetHabitStats godoc
// @Summary Get habit statistics // @Summary Get habit statistics
// @Description Get statistics for a specific habit including streaks and completion rates // @Description Get statistics for a specific habit including streaks and completions
// @Tags stats // @Tags stats
// @Produce json // @Produce json
// @Security BearerAuth // @Security BearerAuth
@@ -121,6 +121,7 @@ func TestHabitUpdateAffectsStats(t *testing.T) {
t.Run("Stats remain after updating habit name", func(t *testing.T) { t.Run("Stats remain after updating habit name", func(t *testing.T) {
updateReq := UpdateHabitRequest{ updateReq := UpdateHabitRequest{
Name: "Morning Running", Name: "Morning Running",
Frequency: "DAILY",
} }
rr := makeRequest(t, *ts.Router, "PUT", "/api/v1/habits/"+habitID, updateReq, token) rr := makeRequest(t, *ts.Router, "PUT", "/api/v1/habits/"+habitID, updateReq, token)
if rr.Code != http.StatusOK { if rr.Code != http.StatusOK {