3 Commits

Author SHA1 Message Date
david 94c5c30d09 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
2026-03-08 00:14:25 +01:00
david 2b059ec334 refactor: extract streak calculation to domain service
Move streak logic from application query to a dedicated domain service,
making it reusable and properly tested for all habit configurations.

- Support streaks for all habit types (boolean, counter, value) combined
  with positive/negative and optional target values
- Handle weekly habits with specific days (streak counts scheduled days)
- Today completed counts toward streak; not yet completed doesn't break it
- Calculate current and longest streak in a single forward pass
- Remove completion_rate from stats (not a useful metric for habits)
- Add comprehensive unit tests covering all 10 type combinations
2026-03-07 22:49:31 +01:00
david 77cfb709d8 feat: add graceful shutdown on SIGINT/SIGTERM 2026-03-07 14:33:30 +01:00
15 changed files with 604 additions and 144 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
- Flexible scheduling: Daily, Weekly, Monthly
- Statistics: Streaks, completion rates, progress tracking
- Statistics: Streaks and completions tracking
- JWT authentication, rate limiting, optional email verification
- Registration modes: Open or closed
- SQLite database (single file)
+29 -4
View File
@@ -1,11 +1,15 @@
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"strconv"
"strings"
"syscall"
"time"
"apocapoc-api/internal/application/commands"
@@ -155,11 +159,32 @@ func main() {
router := httpInfra.NewRouter(cfg.AppURL, habitHandlers, authHandlers, statsHandlers, healthHandlers, userHandlers, exportHandlers, syncHandlers, jwtService, translator)
addr := fmt.Sprintf("0.0.0.0:%s", cfg.Port)
logger.Info().Str("address", addr).Msg("Server starting")
if err := http.ListenAndServe(addr, router); err != nil {
logger.Fatal().Err(err).Msg("Server failed")
server := &http.Server{
Addr: addr,
Handler: router,
}
shutdown := make(chan os.Signal, 1)
signal.Notify(shutdown, syscall.SIGINT, syscall.SIGTERM)
go func() {
logger.Info().Str("address", addr).Msg("Server starting")
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
logger.Fatal().Err(err).Msg("Server failed")
}
}()
<-shutdown
logger.Info().Msg("Shutting down gracefully...")
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if err := server.Shutdown(ctx); err != nil {
logger.Fatal().Err(err).Msg("Server forced to shutdown")
}
logger.Info().Msg("Server stopped")
}
func parseJWTExpiry(expiry string) (int, error) {
+4 -4
View File
@@ -1172,7 +1172,7 @@ const docTemplate = `{
"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": [
"application/json"
],
@@ -1800,6 +1800,9 @@ const docTemplate = `{
"description": {
"type": "string"
},
"frequency": {
"$ref": "#/definitions/value_objects.Frequency"
},
"name": {
"type": "string"
},
@@ -1978,9 +1981,6 @@ const docTemplate = `{
"queries.HabitStatsDTO": {
"type": "object",
"properties": {
"completion_rate": {
"type": "number"
},
"completions_this_month": {
"type": "integer"
},
+4 -4
View File
@@ -1164,7 +1164,7 @@
"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": [
"application/json"
],
@@ -1792,6 +1792,9 @@
"description": {
"type": "string"
},
"frequency": {
"$ref": "#/definitions/value_objects.Frequency"
},
"name": {
"type": "string"
},
@@ -1970,9 +1973,6 @@
"queries.HabitStatsDTO": {
"type": "object",
"properties": {
"completion_rate": {
"type": "number"
},
"completions_this_month": {
"type": "integer"
},
+3 -4
View File
@@ -268,6 +268,8 @@ definitions:
type: boolean
description:
type: string
frequency:
$ref: '#/definitions/value_objects.Frequency'
name:
type: string
specific_dates:
@@ -384,8 +386,6 @@ definitions:
type: object
queries.HabitStatsDTO:
properties:
completion_rate:
type: number
completions_this_month:
type: integer
completions_this_week:
@@ -1191,8 +1191,7 @@ paths:
- system
/stats/habits/{id}:
get:
description: Get statistics for a specific habit including streaks and completion
rates
description: Get statistics for a specific habit including streaks and completions
parameters:
- description: Habit ID
in: path
+19 -4
View File
@@ -5,6 +5,7 @@ import (
"strings"
"apocapoc-api/internal/domain/repositories"
"apocapoc-api/internal/domain/value_objects"
"apocapoc-api/internal/shared/errors"
)
@@ -13,10 +14,11 @@ type UpdateHabitCommand struct {
UserID string
Name string
Description string
CarryOver bool
TargetValue *float64
Frequency value_objects.Frequency
SpecificDays []int
SpecificDates []int
CarryOver bool
TargetValue *float64
}
type UpdateHabitHandler struct {
@@ -34,6 +36,18 @@ func (h *UpdateHabitHandler) Handle(ctx context.Context, cmd UpdateHabitCommand)
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)
if err != nil {
return err
@@ -49,10 +63,11 @@ func (h *UpdateHabitHandler) Handle(ctx context.Context, cmd UpdateHabitCommand)
habit.Name = cmd.Name
habit.Description = cmd.Description
habit.CarryOver = cmd.CarryOver
habit.TargetValue = cmd.TargetValue
habit.Frequency = cmd.Frequency
habit.SpecificDays = cmd.SpecificDays
habit.SpecificDates = cmd.SpecificDates
habit.CarryOver = cmd.CarryOver
habit.TargetValue = cmd.TargetValue
return h.habitRepo.Update(ctx, habit)
}
@@ -48,9 +48,10 @@ func TestUpdateHabitHandler_UpdatesSuccessfully(t *testing.T) {
UserID: "user-123",
Name: "Morning Exercise",
Description: "Updated description",
Frequency: value_objects.FrequencyWeekly,
SpecificDays: []int{1, 3, 5},
CarryOver: true,
TargetValue: &newTargetValue,
SpecificDays: []int{1, 3, 5},
}
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)
}
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 {
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 {
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) {
@@ -88,9 +93,10 @@ func TestUpdateHabitHandler_ReturnsErrorWhenHabitNotFound(t *testing.T) {
handler := NewUpdateHabitHandler(habitRepo)
cmd := UpdateHabitCommand{
HabitID: "non-existent",
UserID: "user-123",
Name: "Exercise",
HabitID: "non-existent",
UserID: "user-123",
Name: "Exercise",
Frequency: value_objects.FrequencyDaily,
}
err := handler.Handle(context.Background(), cmd)
@@ -111,9 +117,10 @@ func TestUpdateHabitHandler_ReturnsErrorWhenUserDoesNotOwnHabit(t *testing.T) {
handler := NewUpdateHabitHandler(habitRepo)
cmd := UpdateHabitCommand{
HabitID: "habit-1",
UserID: "user-456", // Different user
Name: "Exercise",
HabitID: "habit-1",
UserID: "user-456", // Different user
Name: "Exercise",
Frequency: value_objects.FrequencyDaily,
}
err := handler.Handle(context.Background(), cmd)
@@ -135,9 +142,10 @@ func TestUpdateHabitHandler_CannotUpdateArchivedHabit(t *testing.T) {
handler := NewUpdateHabitHandler(habitRepo)
cmd := UpdateHabitCommand{
HabitID: "habit-1",
UserID: "user-123",
Name: "Updated Exercise",
HabitID: "habit-1",
UserID: "user-123",
Name: "Updated Exercise",
Frequency: value_objects.FrequencyDaily,
}
err := handler.Handle(context.Background(), cmd)
@@ -158,9 +166,10 @@ func TestUpdateHabitHandler_ValidatesInput(t *testing.T) {
handler := NewUpdateHabitHandler(habitRepo)
cmd := UpdateHabitCommand{
HabitID: "habit-1",
UserID: "user-123",
Name: "", // Empty name
HabitID: "habit-1",
UserID: "user-123",
Name: "", // Empty name
Frequency: value_objects.FrequencyDaily,
}
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)
}
}
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)
}
}
+13 -94
View File
@@ -6,18 +6,18 @@ import (
"apocapoc-api/internal/domain/entities"
"apocapoc-api/internal/domain/repositories"
"apocapoc-api/internal/domain/services"
"apocapoc-api/internal/shared/errors"
)
type HabitStatsDTO struct {
HabitID string `json:"habit_id"`
HabitName string `json:"habit_name"`
TotalCompletions int `json:"total_completions"`
CurrentStreak int `json:"current_streak"`
LongestStreak int `json:"longest_streak"`
CompletionRate float64 `json:"completion_rate"`
CompletionsThisWeek int `json:"completions_this_week"`
CompletionsThisMonth int `json:"completions_this_month"`
HabitID string `json:"habit_id"`
HabitName string `json:"habit_name"`
TotalCompletions int `json:"total_completions"`
CurrentStreak int `json:"current_streak"`
LongestStreak int `json:"longest_streak"`
CompletionsThisWeek int `json:"completions_this_week"`
CompletionsThisMonth int `json:"completions_this_month"`
}
type GetHabitStatsQuery struct {
@@ -60,102 +60,21 @@ func (h *GetHabitStatsHandler) Handle(ctx context.Context, query GetHabitStatsQu
HabitName: habit.Name,
}
if len(entries) == 0 {
if len(entries) == 0 && !habit.IsNegative {
return stats, nil
}
stats.TotalCompletions = len(entries)
stats.CurrentStreak = calculateCurrentStreak(entries)
stats.LongestStreak = calculateLongestStreak(entries)
stats.CompletionRate = calculateCompletionRate(entries, habit.CreatedAt)
stats.CompletionsThisWeek = countCompletionsInPeriod(entries, 7)
stats.CompletionsThisMonth = countCompletionsInPeriod(entries, 30)
streaks := services.CalculateStreaks(entries, habit, time.Now().UTC())
stats.CurrentStreak = streaks.Current
stats.LongestStreak = streaks.Longest
return stats, nil
}
func calculateCurrentStreak(entries []*entities.HabitEntry) int {
if len(entries) == 0 {
return 0
}
dateMap := make(map[string]bool)
for _, entry := range entries {
dateStr := entry.ScheduledDate.Format("2006-01-02")
dateMap[dateStr] = true
}
streak := 0
currentDate := time.Now().UTC()
for {
dateStr := currentDate.Format("2006-01-02")
if !dateMap[dateStr] {
break
}
streak++
currentDate = currentDate.AddDate(0, 0, -1)
}
return streak
}
func calculateLongestStreak(entries []*entities.HabitEntry) int {
if len(entries) == 0 {
return 0
}
dateMap := make(map[string]bool)
var dates []time.Time
for _, entry := range entries {
date := time.Date(entry.ScheduledDate.Year(), entry.ScheduledDate.Month(), entry.ScheduledDate.Day(), 0, 0, 0, 0, time.UTC)
dateStr := date.Format("2006-01-02")
if !dateMap[dateStr] {
dateMap[dateStr] = true
dates = append(dates, date)
}
}
if len(dates) == 0 {
return 0
}
longestStreak := 1
currentStreak := 1
for i := 1; i < len(dates); i++ {
diff := dates[i].Sub(dates[i-1]).Hours() / 24
if diff == 1 {
currentStreak++
if currentStreak > longestStreak {
longestStreak = currentStreak
}
} else {
currentStreak = 1
}
}
return longestStreak
}
func calculateCompletionRate(entries []*entities.HabitEntry, createdAt time.Time) float64 {
if len(entries) == 0 {
return 0
}
daysSinceCreation := int(time.Since(createdAt).Hours() / 24)
if daysSinceCreation == 0 {
daysSinceCreation = 1
}
rate := float64(len(entries)) / float64(daysSinceCreation) * 100
if rate > 100 {
rate = 100
}
return rate
}
func countCompletionsInPeriod(entries []*entities.HabitEntry, days int) int {
cutoff := time.Now().UTC().AddDate(0, 0, -days)
count := 0
+98
View File
@@ -0,0 +1,98 @@
package services
import (
"time"
"apocapoc-api/internal/domain/entities"
"apocapoc-api/internal/shared/utils"
)
type StreakResult struct {
Current int
Longest int
}
func CalculateStreaks(entries []*entities.HabitEntry, habit *entities.Habit, now time.Time) StreakResult {
entryMap := buildEntryMap(entries)
scheduled := allScheduledDates(habit, now)
if len(scheduled) == 0 {
return StreakResult{}
}
today := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.UTC)
longest := 0
current := 0
for _, d := range scheduled {
if IsDaySuccessful(d.Format("2006-01-02"), entryMap, habit) {
current++
if current > longest {
longest = current
}
} else if d.Equal(today) && !habit.IsNegative {
continue
} else {
current = 0
}
}
return StreakResult{Current: current, Longest: longest}
}
func buildEntryMap(entries []*entities.HabitEntry) map[string]*entities.HabitEntry {
m := make(map[string]*entities.HabitEntry)
for _, e := range entries {
m[e.ScheduledDate.Format("2006-01-02")] = e
}
return m
}
func allScheduledDates(habit *entities.Habit, now time.Time) []time.Time {
start := time.Date(habit.CreatedAt.Year(), habit.CreatedAt.Month(), habit.CreatedAt.Day(), 0, 0, 0, 0, time.UTC)
today := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.UTC)
freq := string(habit.Frequency)
var dates []time.Time
for d := start; !d.After(today); d = d.AddDate(0, 0, 1) {
if utils.ShouldAppearToday(freq, habit.SpecificDays, habit.SpecificDates, d) {
dates = append(dates, d)
}
}
return dates
}
func IsDaySuccessful(dateStr string, entryMap map[string]*entities.HabitEntry, habit *entities.Habit) bool {
entry, hasEntry := entryMap[dateStr]
habitType := string(habit.Type)
if !habit.IsNegative {
if !hasEntry {
return false
}
if habit.TargetValue != nil && entry.Value != nil {
return *entry.Value >= *habit.TargetValue
}
return true
}
if habitType == "VALUE" && habit.TargetValue != nil {
if !hasEntry {
return false
}
if entry.Value != nil {
return *entry.Value <= *habit.TargetValue
}
return false
}
if !hasEntry {
return true
}
if habit.TargetValue != nil && entry.Value != nil {
return *entry.Value <= *habit.TargetValue
}
return false
}
+337
View File
@@ -0,0 +1,337 @@
package services
import (
"testing"
"time"
"apocapoc-api/internal/domain/entities"
"apocapoc-api/internal/domain/value_objects"
)
func makeEntry(d time.Time, value *float64) *entities.HabitEntry {
return &entities.HabitEntry{ScheduledDate: d, Value: value}
}
func floatPtr(v float64) *float64 { return &v }
func dt(year, month, day int) time.Time {
return time.Date(year, time.Month(month), day, 0, 0, 0, 0, time.UTC)
}
func habit(t value_objects.HabitType, negative bool, target *float64) *entities.Habit {
return &entities.Habit{
Type: t,
Frequency: value_objects.FrequencyDaily,
IsNegative: negative,
TargetValue: target,
CreatedAt: dt(2026, 1, 1),
}
}
// --- IsDaySuccessful ---
func TestIsDaySuccessful_BooleanPositive(t *testing.T) {
h := habit(value_objects.HabitTypeBoolean, false, nil)
em := map[string]*entities.HabitEntry{"2026-03-01": makeEntry(dt(2026, 3, 1), nil)}
if !IsDaySuccessful("2026-03-01", em, h) {
t.Error("entry should be success")
}
if IsDaySuccessful("2026-03-01", map[string]*entities.HabitEntry{}, h) {
t.Error("no entry should be failure")
}
}
func TestIsDaySuccessful_BooleanNegative(t *testing.T) {
h := habit(value_objects.HabitTypeBoolean, true, nil)
em := map[string]*entities.HabitEntry{"2026-03-01": makeEntry(dt(2026, 3, 1), nil)}
if !IsDaySuccessful("2026-03-01", map[string]*entities.HabitEntry{}, h) {
t.Error("no entry should be success (resisted)")
}
if IsDaySuccessful("2026-03-01", em, h) {
t.Error("entry should be failure")
}
}
func TestIsDaySuccessful_CounterPositiveNoTarget(t *testing.T) {
h := habit(value_objects.HabitTypeCounter, false, nil)
if !IsDaySuccessful("2026-03-01", map[string]*entities.HabitEntry{"2026-03-01": makeEntry(dt(2026, 3, 1), floatPtr(5))}, h) {
t.Error("entry should be success")
}
if IsDaySuccessful("2026-03-01", map[string]*entities.HabitEntry{}, h) {
t.Error("no entry should be failure")
}
}
func TestIsDaySuccessful_CounterPositiveWithTarget(t *testing.T) {
h := habit(value_objects.HabitTypeCounter, false, floatPtr(8))
cases := []struct {
name string
value *float64
has bool
success bool
}{
{"value >= target", floatPtr(10), true, true},
{"value == target", floatPtr(8), true, true},
{"value < target", floatPtr(3), true, false},
{"no entry", nil, false, false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
em := map[string]*entities.HabitEntry{}
if tc.has {
em["2026-03-01"] = makeEntry(dt(2026, 3, 1), tc.value)
}
if IsDaySuccessful("2026-03-01", em, h) != tc.success {
t.Errorf("Expected %v", tc.success)
}
})
}
}
func TestIsDaySuccessful_CounterNegativeNoTarget(t *testing.T) {
h := habit(value_objects.HabitTypeCounter, true, nil)
if !IsDaySuccessful("2026-03-01", map[string]*entities.HabitEntry{}, h) {
t.Error("no entry should be success")
}
if IsDaySuccessful("2026-03-01", map[string]*entities.HabitEntry{"2026-03-01": makeEntry(dt(2026, 3, 1), floatPtr(3))}, h) {
t.Error("entry should be failure")
}
}
func TestIsDaySuccessful_CounterNegativeWithTarget(t *testing.T) {
h := habit(value_objects.HabitTypeCounter, true, floatPtr(2))
cases := []struct {
name string
value *float64
has bool
success bool
}{
{"no entry", nil, false, true},
{"within limit", floatPtr(1), true, true},
{"at limit", floatPtr(2), true, true},
{"over limit", floatPtr(5), true, false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
em := map[string]*entities.HabitEntry{}
if tc.has {
em["2026-03-01"] = makeEntry(dt(2026, 3, 1), tc.value)
}
if IsDaySuccessful("2026-03-01", em, h) != tc.success {
t.Errorf("Expected %v", tc.success)
}
})
}
}
func TestIsDaySuccessful_ValuePositiveNoTarget(t *testing.T) {
h := habit(value_objects.HabitTypeValue, false, nil)
if !IsDaySuccessful("2026-03-01", map[string]*entities.HabitEntry{"2026-03-01": makeEntry(dt(2026, 3, 1), floatPtr(72))}, h) {
t.Error("entry should be success")
}
if IsDaySuccessful("2026-03-01", map[string]*entities.HabitEntry{}, h) {
t.Error("no entry should be failure")
}
}
func TestIsDaySuccessful_ValuePositiveWithTarget(t *testing.T) {
h := habit(value_objects.HabitTypeValue, false, floatPtr(7))
if !IsDaySuccessful("2026-03-01", map[string]*entities.HabitEntry{"2026-03-01": makeEntry(dt(2026, 3, 1), floatPtr(8))}, h) {
t.Error("value >= target should be success")
}
if IsDaySuccessful("2026-03-01", map[string]*entities.HabitEntry{"2026-03-01": makeEntry(dt(2026, 3, 1), floatPtr(5))}, h) {
t.Error("value < target should be failure")
}
}
func TestIsDaySuccessful_ValueNegativeNoTarget(t *testing.T) {
h := habit(value_objects.HabitTypeValue, true, nil)
if !IsDaySuccessful("2026-03-01", map[string]*entities.HabitEntry{}, h) {
t.Error("no entry should be success")
}
if IsDaySuccessful("2026-03-01", map[string]*entities.HabitEntry{"2026-03-01": makeEntry(dt(2026, 3, 1), floatPtr(3))}, h) {
t.Error("entry should be failure")
}
}
func TestIsDaySuccessful_ValueNegativeWithTarget(t *testing.T) {
h := habit(value_objects.HabitTypeValue, true, floatPtr(70))
cases := []struct {
name string
value *float64
has bool
success bool
}{
{"below target", floatPtr(68), true, true},
{"above target", floatPtr(75), true, false},
{"no entry (didnt track)", nil, false, false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
em := map[string]*entities.HabitEntry{}
if tc.has {
em["2026-03-01"] = makeEntry(dt(2026, 3, 1), tc.value)
}
if IsDaySuccessful("2026-03-01", em, h) != tc.success {
t.Errorf("Expected %v", tc.success)
}
})
}
}
// --- CalculateStreaks ---
func TestStreaks_DailyBooleanPositive(t *testing.T) {
h := habit(value_objects.HabitTypeBoolean, false, nil)
t.Run("3 consecutive days", func(t *testing.T) {
entries := []*entities.HabitEntry{
makeEntry(dt(2026, 3, 1), nil),
makeEntry(dt(2026, 3, 2), nil),
makeEntry(dt(2026, 3, 3), nil),
}
r := CalculateStreaks(entries, h, dt(2026, 3, 3))
if r.Current != 3 || r.Longest != 3 {
t.Errorf("Expected current=3 longest=3, got current=%d longest=%d", r.Current, r.Longest)
}
})
t.Run("gap finds longest and current separately", func(t *testing.T) {
entries := []*entities.HabitEntry{
makeEntry(dt(2026, 3, 1), nil),
makeEntry(dt(2026, 3, 2), nil),
makeEntry(dt(2026, 3, 3), nil),
// gap Mar 4
makeEntry(dt(2026, 3, 5), nil),
}
r := CalculateStreaks(entries, h, dt(2026, 3, 5))
if r.Current != 1 || r.Longest != 3 {
t.Errorf("Expected current=1 longest=3, got current=%d longest=%d", r.Current, r.Longest)
}
})
t.Run("today not completed doesnt break streak", func(t *testing.T) {
entries := []*entities.HabitEntry{
makeEntry(dt(2026, 3, 1), nil),
makeEntry(dt(2026, 3, 2), nil),
}
r := CalculateStreaks(entries, h, dt(2026, 3, 3))
if r.Current != 2 || r.Longest != 2 {
t.Errorf("Expected current=2 longest=2, got current=%d longest=%d", r.Current, r.Longest)
}
})
t.Run("missed yesterday breaks streak", func(t *testing.T) {
entries := []*entities.HabitEntry{
makeEntry(dt(2026, 3, 1), nil),
makeEntry(dt(2026, 3, 2), nil),
}
r := CalculateStreaks(entries, h, dt(2026, 3, 4))
if r.Current != 0 || r.Longest != 2 {
t.Errorf("Expected current=0 longest=2, got current=%d longest=%d", r.Current, r.Longest)
}
})
}
func TestStreaks_DailyBooleanNegative(t *testing.T) {
h := habit(value_objects.HabitTypeBoolean, true, nil)
h.CreatedAt = dt(2026, 3, 1)
t.Run("3 days no entries is 3 streak", func(t *testing.T) {
r := CalculateStreaks(nil, h, dt(2026, 3, 3))
if r.Current != 3 || r.Longest != 3 {
t.Errorf("Expected current=3 longest=3, got current=%d longest=%d", r.Current, r.Longest)
}
})
t.Run("entry breaks streak", func(t *testing.T) {
entries := []*entities.HabitEntry{makeEntry(dt(2026, 3, 2), nil)}
r := CalculateStreaks(entries, h, dt(2026, 3, 3))
if r.Current != 1 || r.Longest != 1 {
t.Errorf("Expected current=1 longest=1, got current=%d longest=%d", r.Current, r.Longest)
}
})
}
func TestStreaks_WeeklyBooleanPositive(t *testing.T) {
h := &entities.Habit{
Type: value_objects.HabitTypeBoolean,
Frequency: value_objects.FrequencyWeekly,
SpecificDays: []int{1, 3, 5},
CreatedAt: dt(2026, 3, 1),
}
t.Run("3 consecutive scheduled days", func(t *testing.T) {
entries := []*entities.HabitEntry{
makeEntry(dt(2026, 3, 2), nil),
makeEntry(dt(2026, 3, 4), nil),
makeEntry(dt(2026, 3, 6), nil),
}
r := CalculateStreaks(entries, h, dt(2026, 3, 6))
if r.Current != 3 || r.Longest != 3 {
t.Errorf("Expected current=3 longest=3, got current=%d longest=%d", r.Current, r.Longest)
}
})
t.Run("missed Wednesday breaks streak", func(t *testing.T) {
entries := []*entities.HabitEntry{
makeEntry(dt(2026, 3, 2), nil),
makeEntry(dt(2026, 3, 6), nil),
}
r := CalculateStreaks(entries, h, dt(2026, 3, 6))
if r.Current != 1 || r.Longest != 1 {
t.Errorf("Expected current=1 longest=1, got current=%d longest=%d", r.Current, r.Longest)
}
})
}
func TestStreaks_CounterWithTarget(t *testing.T) {
h := habit(value_objects.HabitTypeCounter, false, floatPtr(8))
t.Run("all meet target", func(t *testing.T) {
entries := []*entities.HabitEntry{
makeEntry(dt(2026, 3, 1), floatPtr(8)),
makeEntry(dt(2026, 3, 2), floatPtr(10)),
makeEntry(dt(2026, 3, 3), floatPtr(9)),
}
r := CalculateStreaks(entries, h, dt(2026, 3, 3))
if r.Current != 3 {
t.Errorf("Expected current=3, got %d", r.Current)
}
})
}
func TestStreaks_WeeklyCounterNegativeWithTarget(t *testing.T) {
h := &entities.Habit{
Type: value_objects.HabitTypeCounter,
Frequency: value_objects.FrequencyWeekly,
SpecificDays: []int{1, 5},
IsNegative: true,
TargetValue: floatPtr(2),
CreatedAt: dt(2026, 3, 1),
}
t.Run("within limit and no entry both count as success", func(t *testing.T) {
entries := []*entities.HabitEntry{
makeEntry(dt(2026, 3, 2), floatPtr(1)),
makeEntry(dt(2026, 3, 9), floatPtr(5)),
}
r := CalculateStreaks(entries, h, dt(2026, 3, 13))
if r.Current != 1 || r.Longest != 2 {
t.Errorf("Expected current=1 longest=2, got current=%d longest=%d", r.Current, r.Longest)
}
})
}
+7 -6
View File
@@ -20,12 +20,13 @@ type CreateHabitRequest struct {
}
type UpdateHabitRequest struct {
Name string `json:"name"`
Description string `json:"description"`
SpecificDays []int `json:"specific_days,omitempty"`
SpecificDates []int `json:"specific_dates,omitempty"`
CarryOver bool `json:"carry_over"`
TargetValue *float64 `json:"target_value,omitempty"`
Name string `json:"name"`
Description string `json:"description"`
Frequency value_objects.Frequency `json:"frequency"`
SpecificDays []int `json:"specific_days,omitempty"`
SpecificDates []int `json:"specific_dates,omitempty"`
CarryOver bool `json:"carry_over"`
TargetValue *float64 `json:"target_value,omitempty"`
}
type HabitResponse struct {
@@ -313,10 +313,11 @@ func (h *HabitHandlers) UpdateHabit(w http.ResponseWriter, r *http.Request) {
UserID: userID,
Name: req.Name,
Description: req.Description,
CarryOver: req.CarryOver,
TargetValue: req.TargetValue,
Frequency: req.Frequency,
SpecificDays: req.SpecificDays,
SpecificDates: req.SpecificDates,
CarryOver: req.CarryOver,
TargetValue: req.TargetValue,
}
if err := h.updateHandler.Handle(r.Context(), cmd); err != nil {
@@ -89,6 +89,7 @@ func TestHabitCRUDFlow(t *testing.T) {
reqBody := UpdateHabitRequest{
Name: "Morning Exercise",
Description: "Updated description",
Frequency: "DAILY",
}
rr := makeRequest(t, *ts.Router, "PUT", "/api/v1/habits/"+habitID, reqBody, token)
@@ -27,7 +27,7 @@ func NewStatsHandlers(
// GetHabitStats godoc
// @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
// @Produce json
// @Security BearerAuth
@@ -47,7 +47,7 @@ func TestHabitStatsFlow(t *testing.T) {
today := time.Now().UTC().Format("2006-01-02")
t.Run("Stats after marking habit once", func(t *testing.T) {
t.Run("Stats after marking habit today", func(t *testing.T) {
markReq := MarkHabitRequest{
ScheduledDate: today,
}
@@ -69,7 +69,7 @@ func TestHabitStatsFlow(t *testing.T) {
t.Errorf("Expected 1 total completion, got %d", stats.TotalCompletions)
}
if stats.CurrentStreak != 1 {
t.Errorf("Expected current streak of 1, got %d", stats.CurrentStreak)
t.Errorf("Expected current streak of 1 (today completed counts), got %d", stats.CurrentStreak)
}
if stats.LongestStreak != 1 {
t.Errorf("Expected longest streak of 1, got %d", stats.LongestStreak)
@@ -120,7 +120,8 @@ func TestHabitUpdateAffectsStats(t *testing.T) {
t.Run("Stats remain after updating habit name", func(t *testing.T) {
updateReq := UpdateHabitRequest{
Name: "Morning Running",
Name: "Morning Running",
Frequency: "DAILY",
}
rr := makeRequest(t, *ts.Router, "PUT", "/api/v1/habits/"+habitID, updateReq, token)
if rr.Code != http.StatusOK {