26 Commits

Author SHA1 Message Date
david 67fc508384 Fix import order 2026-03-27 00:04:15 +01:00
david 92fe617f73 Fix typed nil panic when SMTP is not configured 2026-03-27 00:00:02 +01:00
david 77cfb709d8 feat: add graceful shutdown on SIGINT/SIGTERM 2026-03-07 14:33:30 +01:00
david aa8f7af55d feat: implement offline sync endpoints with Last-Write-Wins strategy
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 ✓
2025-12-12 00:11:46 +01:00
david e9e7e9dbac Add automated backup system with SQLite VACUUM
- Implement backup package with SQLite VACUUM INTO for safe backups
- Add scheduler with configurable interval (default: 24h)
- Add retention policy with automatic cleanup (default: 7 days)
- Add optional gzip compression (~10x size reduction)
- Add comprehensive tests for backup creation and cleanup
- Integrate backup scheduler in main.go with graceful shutdown
- Add backup configuration variables (BACKUP_ENABLED, BACKUP_INTERVAL, BACKUP_RETENTION_DAYS, BACKUP_PATH, BACKUP_COMPRESS)
- Backups run automatically in background goroutine
- Coverage: backup package 52.7%
2025-12-05 00:17:37 +01:00
david 29f0f9b468 Add structured logging with zerolog
- Implement zerolog logger package with configurable levels
- Add contextual logging middleware (request_id, user_id, method, path, status, duration)
- Support both JSON (production) and human-readable (development) formats
- Add LOG_LEVEL and ENVIRONMENT configuration variables
- Replace standard log calls with structured logger throughout application
- Integrate logger in HTTP router and auth middleware
2025-12-04 23:22:05 +01:00
david 788b6cf430 Add data export functionality with gzip compression
- 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)
2025-12-03 22:32:22 +01:00
david 568ba3b016 Add email logging and SMTP health check
- 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
2025-12-03 20:41:40 +01:00
david 5d92820591 Remove timezone from User model and pass as request parameter
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
2025-11-29 16:18:04 +01:00
david a2aa8b2a76 Add i18n support with English and Spanish translations
- 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
2025-11-29 12:27:26 +01:00
david 90d5628a42 Fix today's habits timezone calculation and include entry data
- 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
2025-11-29 02:09:30 +01:00
david f37c1ac19b Improve email verification flow and error handling
- 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
2025-11-28 11:32:51 +01:00
david 00f6b51228 Add optional email verification and registration control
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)
2025-11-28 08:21:51 +01:00
david 0e909182c2 Add contact email to documentation
- Add Support section to README with contact email and issues link
- Add contact email to Swagger API documentation
- Regenerate Swagger docs
2025-11-28 01:26:33 +01:00
david ac521c38a8 Improve Docker image tagging strategy and remove Swagger version
- Replace 'stable' tag with semver-based tags (1.2.3, 1.2, 1)
- Use 'edge' tag for main branch instead of 'latest'
- Reserve 'latest' tag only for tagged releases
- Remove version from Swagger docs (tracked via git tags instead)
- Document available image tags in README
2025-11-27 23:59:27 +01:00
david bbe0757ab6 Add refresh token authentication system
CI/CD Pipeline / Test (push) Has been cancelled
CI/CD Pipeline / Lint (push) Has been cancelled
CI/CD Pipeline / Build and Push Docker Image (push) Has been cancelled
Implement complete refresh token flow for improved security:
- Short-lived access tokens (configurable, default 1h)
- Long-lived refresh tokens (configurable, default 7d)
- Automatic token rotation on refresh
- Token revocation for proper logout

Domain layer:
- Add RefreshToken entity with validation and revocation
- Add RefreshTokenRepository interface

Application layer:
- Add RefreshTokenHandler for token refresh operations
- Add RevokeTokenHandler for single token revocation
- Add RevokeAllTokensHandler for user-wide revocation

Infrastructure layer:
- Implement SQLite RefreshTokenRepository
- Add refresh_tokens table migration with indexes
- Add parseDuration helper for flexible time configuration

HTTP layer:
- Add POST /api/v1/auth/refresh endpoint
- Add POST /api/v1/auth/logout endpoint
- Update login/register to return refresh tokens
- Improve Swagger documentation with clear descriptions

Configuration:
- Update .env.example with secure token expiry defaults
- Add support for minute/hour/day duration formats

Tests:
- Fix test suite to work with new signatures
- All existing tests passing
2025-11-27 09:57:54 +01:00
david 7768037724 Add robust input validation system and fix test suite
- Add comprehensive validation package with email (RFC 5322), password strength, and IANA timezone validation
- Implement strict password requirements: min 8 chars, uppercase, lowercase, digit, special character
- Integrate validation into RegisterUserHandler with complete test coverage (59 validation tests + 25 handler tests)
- Fix pre-existing test failures:
  - Remove tests for non-existent HabitEntry.DeletedAt and Delete() methods
  - Replace deprecated HabitTypeQuantity with HabitTypeValue
  - Add missing FindByHabitIDAndDateRange mock implementation
- Remove hardcoded localhost:8080 from Swagger config for self-hosted flexibility
2025-11-27 00:17:18 +01:00
david 4c8f3022f0 Refactor password hashing to follow DIP and improve CI/CD
CI/CD Pipeline / Test (push) Has been cancelled
CI/CD Pipeline / Lint (push) Has been cancelled
CI/CD Pipeline / Build and Push Docker Image (push) Has been cancelled
- 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.
2025-11-26 21:39:52 +01:00
david daa7154b12 Add enhanced health check endpoint
- 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
2025-11-26 20:40:03 +01:00
david a0141019b4 Add habit statistics feature
- 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
2025-11-26 18:45:27 +01:00
david 52ecc2fab5 Add OpenAPI/Swagger documentation
- 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
2025-11-26 18:38:26 +01:00
david 74cd2ec84d 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
2025-11-26 14:50:11 +01:00
david e87b7df979 Rename project to apocapoc-api
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).
2025-11-26 11:21:17 +01:00
david b2894fca70 Add JWT authentication
- 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
2025-11-26 01:05:08 +01:00
david 3e8883d878 Add habit HTTP endpoints
- 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
2025-11-26 00:41:05 +01:00
david 76893bd114 Add HTTP layer and server setup
- 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
2025-11-26 00:21:07 +01:00