Previously all validation failures in CreateHabitHandler returned a
generic {"error":"invalid input"}, making it impossible to tell
whether type, frequency, specific_days or specific_dates was the
problem. Errors are now wrapped with field + i18n key and the HTTP
layer replies via respondValidationErrorI18n, matching the pattern
already used by auth endpoints.
Replace nil email service pattern with NoOpEmailService (Null Object)
to eliminate nil pointer panics across all handlers.
Add /docs route as a shortcut to Swagger UI.
Fix streak calculation returning 0 when server timezone differs from
UTC — CreatedAt was not converted to UTC before date extraction.
- 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
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
Add comprehensive offline synchronization support for habits and entries:
## Infrastructure (Phase 1)
- Add UpdatedAt and DeletedAt timestamps to Habit and HabitEntry entities
- Implement soft delete with Delete(), Touch(), and IsDeleted() methods
- Create SQL migration with optimized composite indexes for sync queries
- Add GetChangesSince() and SoftDelete() to both repositories
- Update all Find* methods to exclude soft-deleted records
- 13 comprehensive TDD tests for sync repository methods
## HTTP Endpoints (Phase 2)
- GET /api/v1/sync/changes: retrieve all changes since timestamp
- POST /api/v1/sync/batch: apply client changes with conflict resolution
- Implement Last-Write-Wins strategy using UpdatedAt timestamps
- Add authentication and rate limiting (100 req/min)
- Validate user ownership for all sync operations
- 9 tests for sync handlers (3 queries + 6 commands)
## Technical Details
- Composite indexes: (user_id, updated_at) for optimal query performance
- No pagination: atomic sync operations for data consistency
- Upsert behavior: create resources if not found on server
- DTOs with full entity state including timestamps
- Swagger documentation updated for new endpoints
All 220+ tests passing ✓
- Add RateLimitByEmail middleware (3 attempts/hour per email)
- Apply rate limiting to /api/v1/auth/forgot-password endpoint
- Expand SMTP tests with config validation, message types, and error detection
- Improve test coverage from 44.6% to 53.3%
- Add FindByUserID method to HabitEntryRepository (JOIN with habits)
- Implement ExportUserDataHandler to export all user data
- Add GET /api/v1/export endpoint with gzip compression
- Apply strict rate limiting (1 export per hour per user)
- Export includes all habits (active + archived) and entries
- Add i18n translations for export errors (en/es)
- Update all test mocks to implement new repository method
- Export format: JSON with gzip (~10x compression ratio)
- Add structured logging for email sending (success/failure)
- Add HealthCheck method to EmailService interface
- Extend /health endpoint to include SMTP status
- Update all email service mocks to implement HealthCheck
- SMTP status shows: ok, error, or disabled
Implemented comprehensive filtering capabilities for the habits list endpoint:
- Filter by type (BOOLEAN, COUNTER, VALUE)
- Filter by frequency (DAILY, WEEKLY, MONTHLY)
- Filter by archived status
- Text search in habit name and description
- All filters can be combined
- Filters work with pagination
Technical changes:
- Added FilterParams to GetUserHabitsQuery
- Created HabitFilter struct in repository interface
- Implemented dynamic SQL query building in SQLite repository
- Updated HTTP handler to parse filter query parameters
- Added comprehensive tests for repository and handler filtering
- Updated all test mocks with new filter methods
- Create pagination package with Params and Response structs
- Add FindActiveByUserIDWithPagination and CountActiveByUserID methods to HabitRepository interface
- Implement pagination in SQLite repository using LIMIT and OFFSET
- Update GetUserHabitsHandler to support optional pagination parameters
- Modify HTTP endpoint to parse 'page' and 'page_size' query params (default: page=1, page_size=50, max=100)
- Add GetUserHabitsResponse DTO with pagination metadata
- Maintain backward compatibility - endpoint works with and without pagination params
- Add comprehensive tests for pagination logic in repository, handler, and pagination package
- Update all mock repositories to implement new pagination methods
- Add comprehensive tests for RequestPasswordResetHandler covering success and error cases
- Fix timezone-related test failures after removal of User.Timezone field:
- Remove Timezone assertions from login_user_test.go
- Remove Timezone field from RegisterRequest in integration tests
- Update ValidateRegistration test cases (no longer validates timezone)
- Update migrations_test to check current user table schema
- Fix syntax errors in user_repository_test.go (duplicate closing braces on lines 114 and 210)
Timezone is now sent from the client on each request that needs it,
instead of storing it in the database. This simplifies the model and
allows timezone to be dynamic (useful for traveling users).
Changes:
- Remove timezone field from User entity
- Remove timezone from user registration
- GET /habits/today now requires ?timezone= query param
- Add migration to drop timezone column from database
- Update related tests
- Created i18n package with translator and middleware
- Added translation files for English (en.json) and Spanish (es.json)
- Updated all HTTP handlers to use i18n for error/success messages
- Added comprehensive test coverage for i18n (87%)
- Updated CI workflow to use Go 1.24
- All tests passing with 50.8% total coverage
- Calculate today based on user's timezone instead of always using UTC
- Include habit entry in response if it exists for the current day
- Update GetTodaysHabitsHandler to fetch and return entry information
- Add entry field to TodaysHabitDTO and TodaysHabitResponse
- Update tests to reflect new behavior of including completed habits
- Add test for habits with value entries
Separated ErrorResponse and ValidationErrorResponse types:
- ErrorResponse: general errors (401, 403, 404, 500) - no field attribute
- ValidationErrorResponse: form validation errors (400) - includes field attribute
Updated respondValidationError to return appropriate type based on error format.
Updated Swagger documentation to use ValidationErrorResponse only for validation endpoints.
This ensures the field attribute only appears in API responses for actual form field validation errors, not in general error responses.
- Send verification email before creating user to prevent orphaned accounts
- Detect SMTP authentication errors and fail fast without retries
- Add field-level validation errors for better frontend UX
- Configure docker-compose with explicit environment variables
- Document dollar sign escaping in .env.example (use $$)
- Implement welcome email on successful verification
- Clean up unnecessary comments
Implemented email service infrastructure with SMTP support and optional email verification for self-hosted deployments. Registration flow now supports open/closed modes and hardcoded Apocapoc branding.
Key features:
- Email service with SMTP and template rendering
- Optional email verification (auto-verified without SMTP config)
- Registration modes: open/closed for access control
- Hardcoded Apocapoc branding (AppName, AppURL, DefaultFrom)
- Separate registration and login flows (registration no longer returns tokens)
- Replace mattn/go-sqlite3 with modernc.org/sqlite (pure-Go, no CGO required)
- Update GoReleaser config to disable CGO for ARM64 builds
- Change driver name from 'sqlite3' to 'sqlite' in all sql.Open calls
- Enables successful cross-compilation for ARM64 without cross-compiler toolchain
- All tests passing with new driver
Update test passwords from 'password123' to 'Password123!' to meet security requirements (uppercase, lowercase, digit, special char).
Fix migrations test to match actual habit_entries schema (removed non-existent deleted_at column).
Add user-based rate limiting middleware (100 req/min) for authenticated endpoints using httprate library. Implement common password validation blocking 50+ weak passwords. Improve test coverage from 38.3% to 44.6% with comprehensive refresh token tests.
Security improvements:
- Rate limiting by user ID for /habits and /stats endpoints
- X-RateLimit-Limit header in responses
- Common password blacklist in password validation
- Refresh token test suite with 5 scenarios (valid, invalid, expired, revoked, empty)
COUNTER type:
- Only accepts integer values (rejects decimals)
- Auto-increment behavior: each mark adds to existing value
- Supports decrement via negative values (e.g., -2)
- Enforces minimum value of 0 (never negative)
- Default increment is 1 if no value provided
VALUE type:
- Accepts decimal values
- Replaces value (no auto-increment)
IsNegative field:
- New boolean field on Habit entity
- Persisted in database (is_negative column)
- Available in all DTOs and HTTP responses
- Marks habits as "negative" (e.g., candy consumption)
Examples:
- COUNTER: 5 + (-2) = 3, 2 + (-3) = 0, 0 + (-1) = 0
- VALUE: 5000 → 12000 = 12000 (replacement)
Replace generic string types with strongly-typed value objects throughout
the application layer. This change ensures compile-time type checking and
automatic validation during JSON deserialization.
Changes:
- Add JSON marshaling/unmarshaling to HabitType and Frequency value objects
- Update all DTOs to use typed fields instead of strings
- Update commands and queries to use proper types
- Remove unnecessary string conversions
- Add comprehensive JSON serialization tests
- Fix existing tests to work with typed fields
Benefits:
- Type safety: compiler catches invalid usage
- Automatic validation: invalid values rejected during JSON parsing
- Better code documentation and self-explanatory APIs
- Reduced runtime errors
- Create PasswordHasher interface in domain layer
- Implement BcryptHasher in infrastructure layer
- Update RegisterUserHandler and LoginUserHandler to use interface
- Remove bcrypt dependency from application layer
- Update main.go and integration tests with dependency injection
- Enhance CI/CD workflow with test and lint jobs
- Add code coverage check (minimum 50%)
- Add go vet and gofmt validation
- Configure build job to depend on test and lint passing
- Update GitHub Actions to latest versions (v4→v5)
This achieves 100% SOLID compliance (DIP) and ensures Clean Architecture
by removing external library dependencies from application/domain layers.
- Implement comprehensive health check with database ping
- Track and report server uptime
- Return proper HTTP status codes (503 if database is down)
- Add Swagger documentation for health endpoint
- Add httprate dependency for rate limiting
- Apply 10 requests per minute limit on auth endpoints
- Prevent brute force attacks on login/register
- Update README with security features
- Implement GetHabitStatsHandler with streak calculations
- Calculate current streak, longest streak, and completion rate
- Track completions this week and this month
- Add stats HTTP handler and route at /api/v1/stats/habits/{id}
- Add Swagger documentation for stats endpoint
- Add Swagger dependencies to go.mod
- Annotate all API endpoints with Swagger comments
- Add Swagger UI at /api/v1/docs endpoint
- Auto-generate Swagger docs in Dockerfile build
- Update README with API documentation link
- Create Dockerfile with multi-stage build for optimized image size
- Add GitHub Actions workflow for automatic image publishing to ghcr.io
- Add PORT and HOST fallback defaults in config (8080 and 0.0.0.0)
- Update README with Docker Compose installation instructions
Remove soft delete from HabitEntry:
- Eliminate DeletedAt field from entity and database
- Change UnmarkHabit from soft delete to hard delete
- Simplify all queries removing deleted_at checks
- Update migration to remove deleted_at column
Add date filtering and smart pagination to GetHabitEntries:
- Support optional from/to date parameters
- Implement intelligent pagination rules:
* No date range: pagination required
* Date range > 1 year: pagination required
* Date range ≤ 1 year: pagination optional
- Pagination defaults (page=1, limit=50) only when required
- Return metadata with total count, page, and limit
Technical improvements:
- Cleaner codebase without soft delete complexity
- Better performance (no filtering in queries)
- More intuitive API with flexible pagination
- Comprehensive test coverage for validation rules
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
Update module name and all imports from habit-tracker-api to apocapoc-api.
This reflects the project's new branding as part of the apocapoc ecosystem
(apocapoc-api, apocapoc-web, apocapoc-android).
- Create register and login use cases
- Implement JWT service for token generation and validation
- Add authentication middleware to protect habit endpoints
- Create auth HTTP handlers (register, login)
- Update habit handlers to extract userID from JWT token
- Register/login endpoints: POST /auth/register, POST /auth/login
- Habit endpoints now require Bearer token in Authorization header
- Tested: register -> create habit -> list habits works correctly
- Create DTOs for HTTP requests and responses
- Implement habit handlers (create, get today's, mark)
- Register routes in router: POST /habits, GET /habits/today, POST /habits/{id}/mark
- Add missing repository methods (FindByID, FindByHabitID, FindPendingByHabitID, Delete)
- Wire up dependencies in main.go
- Tested with curl: create, list, mark habits work correctly
- Add strict configuration management (no fallbacks)
- Create HTTP router with Chi and CORS middleware
- Implement health check endpoint
- Add main entry point with database initialization
- Server runs on configurable host and port
- Add SQLite and UUID dependencies (go-sqlite3, google/uuid)
- Create database connection with automatic migrations
- Implement UserRepository with full CRUD operations
- Implement HabitRepository with JSON serialization for arrays
- Implement HabitEntryRepository with date range queries
- Add comprehensive test coverage for all repositories
- Fix User entity to default timezone to UTC when empty
- All tests passing with TDD approach (Red-Green-Refactor)