Complete CRUD operations for habits

Implement all missing endpoints for full habit management:
- GET /api/v1/habits - List all user habits
- GET /api/v1/habits/{id} - Get specific habit
- PUT /api/v1/habits/{id} - Update habit
- DELETE /api/v1/habits/{id} - Archive habit (soft delete)
- GET /api/v1/habits/{id}/entries - Get habit entry history
- DELETE /api/v1/habits/{id}/entries/{date} - Unmark habit (soft delete entry)

All endpoints include:
- TDD approach with comprehensive test coverage
- JWT authentication and ownership validation
- Proper error handling (404, 403, 400, 500)
- Clean architecture with separated commands/queries
This commit is contained in:
2025-11-26 14:50:11 +01:00
parent e87b7df979
commit 74cd2ec84d
16 changed files with 1474 additions and 7 deletions
@@ -0,0 +1,42 @@
package commands
import (
"context"
"apocapoc-api/internal/domain/repositories"
"apocapoc-api/internal/shared/errors"
)
type ArchiveHabitCommand struct {
HabitID string
UserID string
}
type ArchiveHabitHandler struct {
habitRepo repositories.HabitRepository
}
func NewArchiveHabitHandler(habitRepo repositories.HabitRepository) *ArchiveHabitHandler {
return &ArchiveHabitHandler{
habitRepo: habitRepo,
}
}
func (h *ArchiveHabitHandler) Handle(ctx context.Context, cmd ArchiveHabitCommand) error {
// Find existing habit
habit, err := h.habitRepo.FindByID(ctx, cmd.HabitID)
if err != nil {
return err
}
// Check ownership
if habit.UserID != cmd.UserID {
return errors.ErrUnauthorized
}
// Archive the habit (idempotent operation)
habit.Archive()
// Save changes
return h.habitRepo.Update(ctx, habit)
}
@@ -0,0 +1,105 @@
package commands
import (
"context"
"testing"
"apocapoc-api/internal/domain/entities"
"apocapoc-api/internal/domain/value_objects"
"apocapoc-api/internal/shared/errors"
)
func TestArchiveHabitHandler_ArchivesSuccessfully(t *testing.T) {
habit := entities.NewHabit("user-123", "Exercise", value_objects.HabitTypeBoolean, value_objects.FrequencyDaily, false)
habit.ID = "habit-1"
habitRepo := &mockHabitRepoForUpdate{
habitToReturn: habit,
}
handler := NewArchiveHabitHandler(habitRepo)
cmd := ArchiveHabitCommand{
HabitID: "habit-1",
UserID: "user-123",
}
err := handler.Handle(context.Background(), cmd)
if err != nil {
t.Fatalf("Expected no error, got %v", err)
}
if habitRepo.updatedHabit.ArchivedAt == nil {
t.Error("Expected habit to be archived")
}
if habitRepo.updatedHabit.IsActive() {
t.Error("Expected habit to not be active")
}
}
func TestArchiveHabitHandler_ReturnsErrorWhenHabitNotFound(t *testing.T) {
habitRepo := &mockHabitRepoForUpdate{
errorOnFind: errors.ErrNotFound,
}
handler := NewArchiveHabitHandler(habitRepo)
cmd := ArchiveHabitCommand{
HabitID: "non-existent",
UserID: "user-123",
}
err := handler.Handle(context.Background(), cmd)
if err != errors.ErrNotFound {
t.Errorf("Expected ErrNotFound, got %v", err)
}
}
func TestArchiveHabitHandler_ReturnsErrorWhenUserDoesNotOwnHabit(t *testing.T) {
habit := entities.NewHabit("user-123", "Exercise", value_objects.HabitTypeBoolean, value_objects.FrequencyDaily, false)
habit.ID = "habit-1"
habitRepo := &mockHabitRepoForUpdate{
habitToReturn: habit,
}
handler := NewArchiveHabitHandler(habitRepo)
cmd := ArchiveHabitCommand{
HabitID: "habit-1",
UserID: "user-456", // Different user
}
err := handler.Handle(context.Background(), cmd)
if err != errors.ErrUnauthorized {
t.Errorf("Expected ErrUnauthorized, got %v", err)
}
}
func TestArchiveHabitHandler_CanArchiveAlreadyArchivedHabit(t *testing.T) {
habit := entities.NewHabit("user-123", "Exercise", value_objects.HabitTypeBoolean, value_objects.FrequencyDaily, false)
habit.ID = "habit-1"
habit.Archive()
habitRepo := &mockHabitRepoForUpdate{
habitToReturn: habit,
}
handler := NewArchiveHabitHandler(habitRepo)
cmd := ArchiveHabitCommand{
HabitID: "habit-1",
UserID: "user-123",
}
err := handler.Handle(context.Background(), cmd)
// Should be idempotent - no error
if err != nil {
t.Fatalf("Expected no error for already archived habit, got %v", err)
}
}
@@ -0,0 +1,78 @@
package commands
import (
"context"
"time"
"apocapoc-api/internal/domain/entities"
"apocapoc-api/internal/domain/repositories"
"apocapoc-api/internal/shared/errors"
)
type UnmarkHabitCommand struct {
HabitID string
UserID string
ScheduledDate time.Time
}
type UnmarkHabitHandler struct {
habitRepo repositories.HabitRepository
entryRepo repositories.HabitEntryRepository
}
func NewUnmarkHabitHandler(
habitRepo repositories.HabitRepository,
entryRepo repositories.HabitEntryRepository,
) *UnmarkHabitHandler {
return &UnmarkHabitHandler{
habitRepo: habitRepo,
entryRepo: entryRepo,
}
}
func (h *UnmarkHabitHandler) Handle(ctx context.Context, cmd UnmarkHabitCommand) error {
// Verify habit exists and user owns it
habit, err := h.habitRepo.FindByID(ctx, cmd.HabitID)
if err != nil {
return err
}
if habit.UserID != cmd.UserID {
return errors.ErrUnauthorized
}
// Find the entry for the scheduled date
// We search within the same day
startOfDay := time.Date(
cmd.ScheduledDate.Year(),
cmd.ScheduledDate.Month(),
cmd.ScheduledDate.Day(),
0, 0, 0, 0,
cmd.ScheduledDate.Location(),
)
endOfDay := startOfDay.Add(24 * time.Hour)
entries, err := h.entryRepo.FindByHabitIDAndDateRange(ctx, cmd.HabitID, startOfDay, endOfDay)
if err != nil {
return err
}
// Find the active entry for this date
var targetEntry *entities.HabitEntry
for _, entry := range entries {
if entry.ScheduledDate.Equal(cmd.ScheduledDate) && entry.DeletedAt == nil {
targetEntry = entry
break
}
}
if targetEntry == nil {
return errors.ErrNotFound
}
// Soft delete the entry
now := time.Now()
targetEntry.DeletedAt = &now
return h.entryRepo.Update(ctx, targetEntry)
}
@@ -0,0 +1,178 @@
package commands
import (
"context"
"testing"
"time"
"apocapoc-api/internal/domain/entities"
"apocapoc-api/internal/domain/value_objects"
"apocapoc-api/internal/shared/errors"
)
type mockEntryRepoForUnmark struct {
mockEntryRepo
entries []*entities.HabitEntry
updatedEntry *entities.HabitEntry
errorOnUpdate error
}
func (m *mockEntryRepoForUnmark) FindByHabitIDAndDateRange(ctx context.Context, habitID string, from, to time.Time) ([]*entities.HabitEntry, error) {
return m.entries, nil
}
func (m *mockEntryRepoForUnmark) Update(ctx context.Context, entry *entities.HabitEntry) error {
if m.errorOnUpdate != nil {
return m.errorOnUpdate
}
m.updatedEntry = entry
return nil
}
func TestUnmarkHabitHandler_UnmarksSuccessfully(t *testing.T) {
habit := entities.NewHabit("user-123", "Exercise", value_objects.HabitTypeBoolean, value_objects.FrequencyDaily, false)
habit.ID = "habit-1"
scheduledDate := time.Date(2025, 1, 15, 0, 0, 0, 0, time.UTC)
entry := entities.NewHabitEntry("habit-1", scheduledDate, nil)
entry.ID = "entry-1"
habitRepo := &mockHabitRepoForUpdate{
habitToReturn: habit,
}
entryRepo := &mockEntryRepoForUnmark{
entries: []*entities.HabitEntry{entry},
}
handler := NewUnmarkHabitHandler(habitRepo, entryRepo)
cmd := UnmarkHabitCommand{
HabitID: "habit-1",
UserID: "user-123",
ScheduledDate: scheduledDate,
}
err := handler.Handle(context.Background(), cmd)
if err != nil {
t.Fatalf("Expected no error, got %v", err)
}
if entryRepo.updatedEntry == nil {
t.Fatal("Expected entry to be updated")
}
if entryRepo.updatedEntry.DeletedAt == nil {
t.Error("Expected entry to be soft deleted")
}
}
func TestUnmarkHabitHandler_ReturnsErrorWhenHabitNotFound(t *testing.T) {
habitRepo := &mockHabitRepoForUpdate{
errorOnFind: errors.ErrNotFound,
}
entryRepo := &mockEntryRepoForUnmark{}
handler := NewUnmarkHabitHandler(habitRepo, entryRepo)
cmd := UnmarkHabitCommand{
HabitID: "non-existent",
UserID: "user-123",
ScheduledDate: time.Now(),
}
err := handler.Handle(context.Background(), cmd)
if err != errors.ErrNotFound {
t.Errorf("Expected ErrNotFound, got %v", err)
}
}
func TestUnmarkHabitHandler_ReturnsErrorWhenUserDoesNotOwnHabit(t *testing.T) {
habit := entities.NewHabit("user-123", "Exercise", value_objects.HabitTypeBoolean, value_objects.FrequencyDaily, false)
habit.ID = "habit-1"
habitRepo := &mockHabitRepoForUpdate{
habitToReturn: habit,
}
entryRepo := &mockEntryRepoForUnmark{}
handler := NewUnmarkHabitHandler(habitRepo, entryRepo)
cmd := UnmarkHabitCommand{
HabitID: "habit-1",
UserID: "user-456", // Different user
ScheduledDate: time.Now(),
}
err := handler.Handle(context.Background(), cmd)
if err != errors.ErrUnauthorized {
t.Errorf("Expected ErrUnauthorized, got %v", err)
}
}
func TestUnmarkHabitHandler_ReturnsErrorWhenEntryNotFound(t *testing.T) {
habit := entities.NewHabit("user-123", "Exercise", value_objects.HabitTypeBoolean, value_objects.FrequencyDaily, false)
habit.ID = "habit-1"
habitRepo := &mockHabitRepoForUpdate{
habitToReturn: habit,
}
// No entries
entryRepo := &mockEntryRepoForUnmark{
entries: []*entities.HabitEntry{},
}
handler := NewUnmarkHabitHandler(habitRepo, entryRepo)
cmd := UnmarkHabitCommand{
HabitID: "habit-1",
UserID: "user-123",
ScheduledDate: time.Date(2025, 1, 15, 0, 0, 0, 0, time.UTC),
}
err := handler.Handle(context.Background(), cmd)
if err != errors.ErrNotFound {
t.Errorf("Expected ErrNotFound for missing entry, got %v", err)
}
}
func TestUnmarkHabitHandler_IgnoresAlreadyDeletedEntry(t *testing.T) {
habit := entities.NewHabit("user-123", "Exercise", value_objects.HabitTypeBoolean, value_objects.FrequencyDaily, false)
habit.ID = "habit-1"
scheduledDate := time.Date(2025, 1, 15, 0, 0, 0, 0, time.UTC)
entry := entities.NewHabitEntry("habit-1", scheduledDate, nil)
entry.ID = "entry-1"
now := time.Now()
entry.DeletedAt = &now // Already deleted
habitRepo := &mockHabitRepoForUpdate{
habitToReturn: habit,
}
entryRepo := &mockEntryRepoForUnmark{
entries: []*entities.HabitEntry{entry},
}
handler := NewUnmarkHabitHandler(habitRepo, entryRepo)
cmd := UnmarkHabitCommand{
HabitID: "habit-1",
UserID: "user-123",
ScheduledDate: scheduledDate,
}
err := handler.Handle(context.Background(), cmd)
// Should return not found since the active entry doesn't exist
if err != errors.ErrNotFound {
t.Errorf("Expected ErrNotFound for already deleted entry, got %v", err)
}
}
@@ -0,0 +1,64 @@
package commands
import (
"context"
"strings"
"apocapoc-api/internal/domain/repositories"
"apocapoc-api/internal/shared/errors"
)
type UpdateHabitCommand struct {
HabitID string
UserID string
Name string
Description string
CarryOver bool
TargetValue *float64
SpecificDays []int
SpecificDates []int
}
type UpdateHabitHandler struct {
habitRepo repositories.HabitRepository
}
func NewUpdateHabitHandler(habitRepo repositories.HabitRepository) *UpdateHabitHandler {
return &UpdateHabitHandler{
habitRepo: habitRepo,
}
}
func (h *UpdateHabitHandler) Handle(ctx context.Context, cmd UpdateHabitCommand) error {
// Validate input
if strings.TrimSpace(cmd.Name) == "" {
return errors.ErrInvalidInput
}
// Find existing habit
habit, err := h.habitRepo.FindByID(ctx, cmd.HabitID)
if err != nil {
return err
}
// Check ownership
if habit.UserID != cmd.UserID {
return errors.ErrUnauthorized
}
// Cannot update archived habits
if !habit.IsActive() {
return errors.ErrInvalidInput
}
// Update fields
habit.Name = cmd.Name
habit.Description = cmd.Description
habit.CarryOver = cmd.CarryOver
habit.TargetValue = cmd.TargetValue
habit.SpecificDays = cmd.SpecificDays
habit.SpecificDates = cmd.SpecificDates
// Save changes
return h.habitRepo.Update(ctx, habit)
}
@@ -0,0 +1,171 @@
package commands
import (
"context"
"testing"
"apocapoc-api/internal/domain/entities"
"apocapoc-api/internal/domain/value_objects"
"apocapoc-api/internal/shared/errors"
)
type mockHabitRepoForUpdate struct {
mockHabitRepo
habitToReturn *entities.Habit
errorOnFind error
errorOnUpdate error
updatedHabit *entities.Habit
}
func (m *mockHabitRepoForUpdate) FindByID(ctx context.Context, id string) (*entities.Habit, error) {
if m.errorOnFind != nil {
return nil, m.errorOnFind
}
return m.habitToReturn, nil
}
func (m *mockHabitRepoForUpdate) Update(ctx context.Context, habit *entities.Habit) error {
if m.errorOnUpdate != nil {
return m.errorOnUpdate
}
m.updatedHabit = habit
return nil
}
func TestUpdateHabitHandler_UpdatesSuccessfully(t *testing.T) {
habit := entities.NewHabit("user-123", "Exercise", value_objects.HabitTypeBoolean, value_objects.FrequencyDaily, false)
habit.ID = "habit-1"
habitRepo := &mockHabitRepoForUpdate{
habitToReturn: habit,
}
handler := NewUpdateHabitHandler(habitRepo)
newTargetValue := 5.0
cmd := UpdateHabitCommand{
HabitID: "habit-1",
UserID: "user-123",
Name: "Morning Exercise",
Description: "Updated description",
CarryOver: true,
TargetValue: &newTargetValue,
SpecificDays: []int{1, 3, 5},
}
err := handler.Handle(context.Background(), cmd)
if err != nil {
t.Fatalf("Expected no error, got %v", err)
}
if habitRepo.updatedHabit.Name != "Morning Exercise" {
t.Errorf("Expected name to be updated to 'Morning Exercise', got %s", habitRepo.updatedHabit.Name)
}
if habitRepo.updatedHabit.Description != "Updated description" {
t.Errorf("Expected description to be updated, got %s", habitRepo.updatedHabit.Description)
}
if !habitRepo.updatedHabit.CarryOver {
t.Error("Expected CarryOver to be true")
}
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) {
habitRepo := &mockHabitRepoForUpdate{
errorOnFind: errors.ErrNotFound,
}
handler := NewUpdateHabitHandler(habitRepo)
cmd := UpdateHabitCommand{
HabitID: "non-existent",
UserID: "user-123",
Name: "Exercise",
}
err := handler.Handle(context.Background(), cmd)
if err != errors.ErrNotFound {
t.Errorf("Expected ErrNotFound, got %v", err)
}
}
func TestUpdateHabitHandler_ReturnsErrorWhenUserDoesNotOwnHabit(t *testing.T) {
habit := entities.NewHabit("user-123", "Exercise", value_objects.HabitTypeBoolean, value_objects.FrequencyDaily, false)
habit.ID = "habit-1"
habitRepo := &mockHabitRepoForUpdate{
habitToReturn: habit,
}
handler := NewUpdateHabitHandler(habitRepo)
cmd := UpdateHabitCommand{
HabitID: "habit-1",
UserID: "user-456", // Different user
Name: "Exercise",
}
err := handler.Handle(context.Background(), cmd)
if err != errors.ErrUnauthorized {
t.Errorf("Expected ErrUnauthorized, got %v", err)
}
}
func TestUpdateHabitHandler_CannotUpdateArchivedHabit(t *testing.T) {
habit := entities.NewHabit("user-123", "Exercise", value_objects.HabitTypeBoolean, value_objects.FrequencyDaily, false)
habit.ID = "habit-1"
habit.Archive()
habitRepo := &mockHabitRepoForUpdate{
habitToReturn: habit,
}
handler := NewUpdateHabitHandler(habitRepo)
cmd := UpdateHabitCommand{
HabitID: "habit-1",
UserID: "user-123",
Name: "Updated Exercise",
}
err := handler.Handle(context.Background(), cmd)
if err != errors.ErrInvalidInput {
t.Errorf("Expected ErrInvalidInput for archived habit, got %v", err)
}
}
func TestUpdateHabitHandler_ValidatesInput(t *testing.T) {
habit := entities.NewHabit("user-123", "Exercise", value_objects.HabitTypeBoolean, value_objects.FrequencyDaily, false)
habit.ID = "habit-1"
habitRepo := &mockHabitRepoForUpdate{
habitToReturn: habit,
}
handler := NewUpdateHabitHandler(habitRepo)
cmd := UpdateHabitCommand{
HabitID: "habit-1",
UserID: "user-123",
Name: "", // Empty name
}
err := handler.Handle(context.Background(), cmd)
if err != errors.ErrInvalidInput {
t.Errorf("Expected ErrInvalidInput for empty name, got %v", err)
}
}