Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| ed50d2427e | |||
| c20720f120 | |||
| a07d033e93 | |||
| 67fc508384 | |||
| 92fe617f73 | |||
| 94c5c30d09 | |||
| 2b059ec334 | |||
| 77cfb709d8 | |||
| aae68ba20e | |||
| 8883cdcb86 |
@@ -4,6 +4,7 @@ data/
|
||||
*.db-shm
|
||||
*.db-wal
|
||||
apocapoc-api
|
||||
/api
|
||||
dist/
|
||||
bin/
|
||||
.internal-notes/
|
||||
|
||||
@@ -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)
|
||||
@@ -139,7 +139,9 @@ API runs on `http://localhost:8080`
|
||||
|
||||
## API Documentation
|
||||
|
||||
Access the interactive Swagger UI at `http://localhost:8080/api/v1/docs`
|
||||
**Live:** [apocapoc.app/api/v1/docs](https://apocapoc.app/api/v1/docs)
|
||||
|
||||
**Local:** `http://localhost:8080/api/v1/docs`
|
||||
|
||||
Includes endpoint reference, schemas, authentication examples, and live testing.
|
||||
|
||||
|
||||
+31
-5
@@ -1,15 +1,20 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"apocapoc-api/internal/application/commands"
|
||||
"apocapoc-api/internal/application/queries"
|
||||
"apocapoc-api/internal/domain/services"
|
||||
"apocapoc-api/internal/i18n"
|
||||
"apocapoc-api/internal/infrastructure/auth"
|
||||
"apocapoc-api/internal/infrastructure/backup"
|
||||
@@ -90,7 +95,7 @@ func main() {
|
||||
jwtService := auth.NewJWTService(cfg.JWTSecret, jwtExpiryHours)
|
||||
passwordHasher := crypto.NewBcryptHasher()
|
||||
|
||||
var emailService *email.SMTPService
|
||||
var emailService services.EmailService = &services.NoOpEmailService{}
|
||||
if cfg.SMTPHost != "" {
|
||||
smtpPort, err := strconv.Atoi(cfg.SMTPPort)
|
||||
if err != nil {
|
||||
@@ -155,11 +160,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
@@ -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
@@ -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
@@ -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
|
||||
|
||||
@@ -13,9 +13,9 @@ import (
|
||||
)
|
||||
|
||||
type mockHabitRepoForBatch struct {
|
||||
habits map[string]*entities.Habit
|
||||
createFunc func(ctx context.Context, habit *entities.Habit) error
|
||||
updateFunc func(ctx context.Context, habit *entities.Habit) error
|
||||
habits map[string]*entities.Habit
|
||||
createFunc func(ctx context.Context, habit *entities.Habit) error
|
||||
updateFunc func(ctx context.Context, habit *entities.Habit) error
|
||||
softDeleteFunc func(ctx context.Context, id string) error
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ package commands
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"apocapoc-api/internal/domain/entities"
|
||||
"apocapoc-api/internal/domain/repositories"
|
||||
@@ -32,19 +33,19 @@ func NewCreateHabitHandler(habitRepo repositories.HabitRepository) *CreateHabitH
|
||||
|
||||
func (h *CreateHabitHandler) Handle(ctx context.Context, cmd CreateHabitCommand) (string, error) {
|
||||
if !cmd.Type.IsValid() {
|
||||
return "", errors.ErrInvalidInput
|
||||
return "", fmt.Errorf("%w: type: type_invalid", errors.ErrInvalidInput)
|
||||
}
|
||||
|
||||
if !cmd.Frequency.IsValid() {
|
||||
return "", errors.ErrInvalidInput
|
||||
return "", fmt.Errorf("%w: frequency: frequency_invalid", errors.ErrInvalidInput)
|
||||
}
|
||||
|
||||
if cmd.Frequency == value_objects.FrequencyWeekly && len(cmd.SpecificDays) == 0 {
|
||||
return "", errors.ErrInvalidInput
|
||||
return "", fmt.Errorf("%w: specific_days: specific_days_required", errors.ErrInvalidInput)
|
||||
}
|
||||
|
||||
if cmd.Frequency == value_objects.FrequencyMonthly && len(cmd.SpecificDates) == 0 {
|
||||
return "", errors.ErrInvalidInput
|
||||
return "", fmt.Errorf("%w: specific_dates: specific_dates_required", errors.ErrInvalidInput)
|
||||
}
|
||||
|
||||
habit := entities.NewHabit(cmd.UserID, cmd.Name, cmd.Type, cmd.Frequency, cmd.CarryOver, cmd.IsNegative)
|
||||
|
||||
@@ -4,6 +4,8 @@ import (
|
||||
"apocapoc-api/internal/domain/repositories"
|
||||
"apocapoc-api/internal/shared/pagination"
|
||||
"context"
|
||||
stderrors "errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -110,8 +112,31 @@ func TestCreateHabitHandler_InvalidType(t *testing.T) {
|
||||
|
||||
_, err := handler.Handle(context.Background(), cmd)
|
||||
|
||||
if err != errors.ErrInvalidInput {
|
||||
t.Errorf("Expected ErrInvalidInput, got %v", err)
|
||||
if !stderrors.Is(err, errors.ErrInvalidInput) {
|
||||
t.Fatalf("Expected ErrInvalidInput wrapper, got %v", err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "type: type_invalid") {
|
||||
t.Errorf("Expected 'type: type_invalid' in error, got %q", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateHabitHandler_EmptyType(t *testing.T) {
|
||||
mock := &mockHabitRepo{}
|
||||
handler := NewCreateHabitHandler(mock)
|
||||
|
||||
cmd := CreateHabitCommand{
|
||||
UserID: "user-123",
|
||||
Name: "Exercise",
|
||||
Frequency: "DAILY",
|
||||
}
|
||||
|
||||
_, err := handler.Handle(context.Background(), cmd)
|
||||
|
||||
if !stderrors.Is(err, errors.ErrInvalidInput) {
|
||||
t.Fatalf("Expected ErrInvalidInput wrapper, got %v", err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "type: type_invalid") {
|
||||
t.Errorf("Expected 'type: type_invalid' in error, got %q", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -128,8 +153,11 @@ func TestCreateHabitHandler_InvalidFrequency(t *testing.T) {
|
||||
|
||||
_, err := handler.Handle(context.Background(), cmd)
|
||||
|
||||
if err != errors.ErrInvalidInput {
|
||||
t.Errorf("Expected ErrInvalidInput, got %v", err)
|
||||
if !stderrors.Is(err, errors.ErrInvalidInput) {
|
||||
t.Fatalf("Expected ErrInvalidInput wrapper, got %v", err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "frequency: frequency_invalid") {
|
||||
t.Errorf("Expected 'frequency: frequency_invalid' in error, got %q", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -147,8 +175,11 @@ func TestCreateHabitHandler_WeeklyWithoutSpecificDays(t *testing.T) {
|
||||
|
||||
_, err := handler.Handle(context.Background(), cmd)
|
||||
|
||||
if err != errors.ErrInvalidInput {
|
||||
t.Errorf("Expected ErrInvalidInput, got %v", err)
|
||||
if !stderrors.Is(err, errors.ErrInvalidInput) {
|
||||
t.Fatalf("Expected ErrInvalidInput wrapper, got %v", err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "specific_days: specific_days_required") {
|
||||
t.Errorf("Expected 'specific_days: specific_days_required' in error, got %q", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -166,8 +197,11 @@ func TestCreateHabitHandler_MonthlyWithoutSpecificDates(t *testing.T) {
|
||||
|
||||
_, err := handler.Handle(context.Background(), cmd)
|
||||
|
||||
if err != errors.ErrInvalidInput {
|
||||
t.Errorf("Expected ErrInvalidInput, got %v", err)
|
||||
if !stderrors.Is(err, errors.ErrInvalidInput) {
|
||||
t.Fatalf("Expected ErrInvalidInput wrapper, got %v", err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "specific_dates: specific_dates_required") {
|
||||
t.Errorf("Expected 'specific_dates: specific_dates_required' in error, got %q", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -73,7 +73,7 @@ func (h *RegisterUserHandler) Handle(ctx context.Context, cmd RegisterUserComman
|
||||
user := entities.NewUser(cmd.Email, hashedPassword)
|
||||
|
||||
emailVerificationRequired := false
|
||||
if h.emailService != nil {
|
||||
if h.emailService.IsEnabled() {
|
||||
token, err := h.generateVerificationToken()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to generate verification token: %w", err)
|
||||
|
||||
@@ -2,6 +2,7 @@ package commands
|
||||
|
||||
import (
|
||||
"apocapoc-api/internal/domain/repositories"
|
||||
"apocapoc-api/internal/domain/services"
|
||||
"apocapoc-api/internal/shared/pagination"
|
||||
"context"
|
||||
"errors"
|
||||
@@ -71,7 +72,7 @@ func TestRegisterUserHandler_Success(t *testing.T) {
|
||||
},
|
||||
}
|
||||
hasher := &mockPasswordHasher{}
|
||||
handler := NewRegisterUserHandler(repo, hasher, nil, "", "open", false)
|
||||
handler := NewRegisterUserHandler(repo, hasher, &services.NoOpEmailService{}, "", "open", false)
|
||||
|
||||
cmd := RegisterUserCommand{
|
||||
Email: "test@example.com",
|
||||
@@ -88,7 +89,7 @@ func TestRegisterUserHandler_Success(t *testing.T) {
|
||||
}
|
||||
|
||||
if result.EmailVerificationRequired {
|
||||
t.Error("expected email verification to not be required when emailService is nil")
|
||||
t.Error("expected email verification to not be required when email is disabled")
|
||||
}
|
||||
|
||||
if createdUser == nil {
|
||||
@@ -103,7 +104,7 @@ func TestRegisterUserHandler_Success(t *testing.T) {
|
||||
func TestRegisterUserHandler_InvalidEmail(t *testing.T) {
|
||||
repo := &mockUserRepo{}
|
||||
hasher := &mockPasswordHasher{}
|
||||
handler := NewRegisterUserHandler(repo, hasher, nil, "", "open", false)
|
||||
handler := NewRegisterUserHandler(repo, hasher, &services.NoOpEmailService{}, "", "open", false)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
@@ -135,7 +136,7 @@ func TestRegisterUserHandler_InvalidEmail(t *testing.T) {
|
||||
func TestRegisterUserHandler_InvalidPassword(t *testing.T) {
|
||||
repo := &mockUserRepo{}
|
||||
hasher := &mockPasswordHasher{}
|
||||
handler := NewRegisterUserHandler(repo, hasher, nil, "", "open", false)
|
||||
handler := NewRegisterUserHandler(repo, hasher, &services.NoOpEmailService{}, "", "open", false)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
@@ -174,7 +175,7 @@ func TestRegisterUserHandler_EmailAlreadyExists(t *testing.T) {
|
||||
},
|
||||
}
|
||||
hasher := &mockPasswordHasher{}
|
||||
handler := NewRegisterUserHandler(repo, hasher, nil, "", "open", false)
|
||||
handler := NewRegisterUserHandler(repo, hasher, &services.NoOpEmailService{}, "", "open", false)
|
||||
|
||||
cmd := RegisterUserCommand{
|
||||
Email: "test@example.com",
|
||||
@@ -195,7 +196,7 @@ func TestRegisterUserHandler_PasswordHashingError(t *testing.T) {
|
||||
return "", expectedErr
|
||||
},
|
||||
}
|
||||
handler := NewRegisterUserHandler(repo, hasher, nil, "", "open", false)
|
||||
handler := NewRegisterUserHandler(repo, hasher, &services.NoOpEmailService{}, "", "open", false)
|
||||
|
||||
cmd := RegisterUserCommand{
|
||||
Email: "test@example.com",
|
||||
@@ -216,7 +217,7 @@ func TestRegisterUserHandler_RepositoryError(t *testing.T) {
|
||||
},
|
||||
}
|
||||
hasher := &mockPasswordHasher{}
|
||||
handler := NewRegisterUserHandler(repo, hasher, nil, "", "open", false)
|
||||
handler := NewRegisterUserHandler(repo, hasher, &services.NoOpEmailService{}, "", "open", false)
|
||||
|
||||
cmd := RegisterUserCommand{
|
||||
Email: "test@example.com",
|
||||
@@ -232,7 +233,7 @@ func TestRegisterUserHandler_RepositoryError(t *testing.T) {
|
||||
func TestRegisterUserHandler_EdgeCases(t *testing.T) {
|
||||
repo := &mockUserRepo{}
|
||||
hasher := &mockPasswordHasher{}
|
||||
handler := NewRegisterUserHandler(repo, hasher, nil, "", "open", false)
|
||||
handler := NewRegisterUserHandler(repo, hasher, &services.NoOpEmailService{}, "", "open", false)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
@@ -285,7 +286,7 @@ func TestRegisterUserHandler_EdgeCases(t *testing.T) {
|
||||
func TestRegisterUserHandler_ClosedRegistration(t *testing.T) {
|
||||
repo := &mockUserRepo{}
|
||||
hasher := &mockPasswordHasher{}
|
||||
handler := NewRegisterUserHandler(repo, hasher, nil, "", "closed", false)
|
||||
handler := NewRegisterUserHandler(repo, hasher, &services.NoOpEmailService{}, "", "closed", false)
|
||||
|
||||
cmd := RegisterUserCommand{
|
||||
Email: "test@example.com",
|
||||
|
||||
@@ -89,6 +89,10 @@ func (m *mockRequestResetEmailService) HealthCheck() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *mockRequestResetEmailService) IsEnabled() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func TestRequestPasswordResetHandler_Success(t *testing.T) {
|
||||
user := entities.NewUser("test@example.com", "hash")
|
||||
user.ID = "user-123"
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -69,6 +69,10 @@ func (m *mockEmailService) HealthCheck() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *mockEmailService) IsEnabled() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func TestVerifyEmailHandler_Success(t *testing.T) {
|
||||
token := "valid-token"
|
||||
expiry := time.Now().Add(24 * time.Hour)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -10,4 +10,11 @@ type EmailMessage struct {
|
||||
type EmailService interface {
|
||||
Send(message EmailMessage) error
|
||||
HealthCheck() error
|
||||
IsEnabled() bool
|
||||
}
|
||||
|
||||
type NoOpEmailService struct{}
|
||||
|
||||
func (n *NoOpEmailService) Send(_ EmailMessage) error { return nil }
|
||||
func (n *NoOpEmailService) HealthCheck() error { return nil }
|
||||
func (n *NoOpEmailService) IsEnabled() bool { return false }
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
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 {
|
||||
createdUTC := habit.CreatedAt.UTC()
|
||||
start := time.Date(createdUTC.Year(), createdUTC.Month(), createdUTC.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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -107,6 +107,10 @@ func (s *SMTPService) GetConfig() SMTPConfig {
|
||||
return s.config
|
||||
}
|
||||
|
||||
func (s *SMTPService) IsEnabled() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *SMTPService) HealthCheck() error {
|
||||
dialer := mail.NewDialer(s.config.Host, s.config.Port, s.config.Username, s.config.Password)
|
||||
dialer.TLSConfig = &tls.Config{
|
||||
|
||||
@@ -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 {
|
||||
@@ -124,12 +125,12 @@ type SyncHabitDTO struct {
|
||||
}
|
||||
|
||||
type SyncHabitEntryDTO struct {
|
||||
ID string `json:"id"`
|
||||
HabitID string `json:"habit_id"`
|
||||
ScheduledDate time.Time `json:"scheduled_date"`
|
||||
CompletedAt time.Time `json:"completed_at"`
|
||||
Value *float64 `json:"value,omitempty"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
ID string `json:"id"`
|
||||
HabitID string `json:"habit_id"`
|
||||
ScheduledDate time.Time `json:"scheduled_date"`
|
||||
CompletedAt time.Time `json:"completed_at"`
|
||||
Value *float64 `json:"value,omitempty"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type HabitChangesDTO struct {
|
||||
|
||||
@@ -2,6 +2,7 @@ package http
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
stderrors "errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -97,8 +98,8 @@ func (h *HabitHandlers) CreateHabit(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
habitID, err := h.createHandler.Handle(r.Context(), cmd)
|
||||
if err != nil {
|
||||
if err == errors.ErrInvalidInput {
|
||||
respondError(w, http.StatusBadRequest, err.Error())
|
||||
if stderrors.Is(err, errors.ErrInvalidInput) {
|
||||
respondValidationErrorI18n(w, r, h.translator, err)
|
||||
return
|
||||
}
|
||||
respondErrorI18n(w, r, h.translator, http.StatusInternalServerError, "failed_create_habit")
|
||||
@@ -313,10 +314,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)
|
||||
@@ -122,6 +123,47 @@ func TestHabitCRUDFlow(t *testing.T) {
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Create habit with missing type returns field-level error", func(t *testing.T) {
|
||||
token := registerAndLogin(t, *ts.Router, "validationuser@example.com", "Password123!")
|
||||
|
||||
reqBody := map[string]any{"name": "No Type"}
|
||||
rr := makeRequest(t, *ts.Router, "POST", "/api/v1/habits", reqBody, token)
|
||||
|
||||
if rr.Code != http.StatusBadRequest {
|
||||
t.Fatalf("Expected 400, got %d. Body: %s", rr.Code, rr.Body.String())
|
||||
}
|
||||
|
||||
var resp ValidationErrorResponse
|
||||
decodeResponse(t, rr, &resp)
|
||||
if resp.Field != "type" {
|
||||
t.Errorf("Expected field 'type', got %q. Body: %s", resp.Field, rr.Body.String())
|
||||
}
|
||||
if resp.Error == "" {
|
||||
t.Errorf("Expected non-empty translated error message. Body: %s", rr.Body.String())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Create weekly habit without specific_days returns field-level error", func(t *testing.T) {
|
||||
token := registerAndLogin(t, *ts.Router, "weeklyuser@example.com", "Password123!")
|
||||
|
||||
reqBody := CreateHabitRequest{
|
||||
Name: "Cut nails",
|
||||
Type: "BOOLEAN",
|
||||
Frequency: "WEEKLY",
|
||||
}
|
||||
rr := makeRequest(t, *ts.Router, "POST", "/api/v1/habits", reqBody, token)
|
||||
|
||||
if rr.Code != http.StatusBadRequest {
|
||||
t.Fatalf("Expected 400, got %d. Body: %s", rr.Code, rr.Body.String())
|
||||
}
|
||||
|
||||
var resp ValidationErrorResponse
|
||||
decodeResponse(t, rr, &resp)
|
||||
if resp.Field != "specific_days" {
|
||||
t.Errorf("Expected field 'specific_days', got %q. Body: %s", resp.Field, rr.Body.String())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Access other user's habit", func(t *testing.T) {
|
||||
otherToken := registerAndLogin(t, *ts.Router, "otheruser@example.com", "Password123!")
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
|
||||
"apocapoc-api/internal/application/commands"
|
||||
"apocapoc-api/internal/application/queries"
|
||||
"apocapoc-api/internal/domain/services"
|
||||
"apocapoc-api/internal/i18n"
|
||||
"apocapoc-api/internal/infrastructure/auth"
|
||||
"apocapoc-api/internal/infrastructure/crypto"
|
||||
@@ -43,14 +44,15 @@ func setupTestServer(t *testing.T) *TestServer {
|
||||
refreshTokenRepo := sqlite.NewRefreshTokenRepository(db)
|
||||
passwordResetTokenRepo := sqlite.NewPasswordResetTokenRepository(db)
|
||||
|
||||
registerHandler := commands.NewRegisterUserHandler(userRepo, passwordHasher, nil, "", "open", false)
|
||||
noOpEmail := &services.NoOpEmailService{}
|
||||
registerHandler := commands.NewRegisterUserHandler(userRepo, passwordHasher, noOpEmail, "", "open", false)
|
||||
loginHandler := queries.NewLoginUserHandler(userRepo, passwordHasher)
|
||||
refreshTokenHandler := queries.NewRefreshTokenHandler(refreshTokenRepo, userRepo)
|
||||
revokeTokenHandler := commands.NewRevokeTokenHandler(refreshTokenRepo)
|
||||
revokeAllTokensHandler := commands.NewRevokeAllTokensHandler(refreshTokenRepo)
|
||||
verifyEmailHandler := commands.NewVerifyEmailHandler(userRepo, nil, false)
|
||||
resendVerificationEmailHandler := commands.NewResendVerificationEmailHandler(userRepo, nil, "")
|
||||
requestPasswordResetHandler := commands.NewRequestPasswordResetHandler(userRepo, passwordResetTokenRepo, nil, "")
|
||||
verifyEmailHandler := commands.NewVerifyEmailHandler(userRepo, noOpEmail, false)
|
||||
resendVerificationEmailHandler := commands.NewResendVerificationEmailHandler(userRepo, noOpEmail, "")
|
||||
requestPasswordResetHandler := commands.NewRequestPasswordResetHandler(userRepo, passwordResetTokenRepo, noOpEmail, "")
|
||||
resetPasswordHandler := commands.NewResetPasswordHandler(userRepo, passwordResetTokenRepo, passwordHasher)
|
||||
createHandler := commands.NewCreateHabitHandler(habitRepo)
|
||||
getTodaysHandler := queries.NewGetTodaysHabitsHandler(habitRepo, entryRepo)
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -13,9 +13,9 @@ import (
|
||||
)
|
||||
|
||||
type SyncHandlers struct {
|
||||
getSyncChangesHandler *queries.GetSyncChangesHandler
|
||||
applySyncBatchHandler *commands.ApplySyncBatchHandler
|
||||
translator *i18n.Translator
|
||||
getSyncChangesHandler *queries.GetSyncChangesHandler
|
||||
applySyncBatchHandler *commands.ApplySyncBatchHandler
|
||||
translator *i18n.Translator
|
||||
}
|
||||
|
||||
func NewSyncHandlers(
|
||||
|
||||
Reference in New Issue
Block a user