feat(savings): Add savings module with categories, transactions, recurring plans
- Categories: regular, deposits, credits, recurring, multi-user, accounts - Transactions: deposits and withdrawals with user tracking - Recurring plans: monthly payment obligations per user - Stats: overdues calculation with allocation algorithm - Excludes is_account categories from total sums - Documentation: docs/SAVINGS.md
This commit is contained in:
@@ -2,18 +2,26 @@ package service
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/daniil/homelab-api/internal/model"
|
||||
"github.com/daniil/homelab-api/internal/repository"
|
||||
)
|
||||
|
||||
var ErrFutureDate = errors.New("cannot log habit for future date")
|
||||
var ErrAlreadyLogged = errors.New("habit already logged for this date")
|
||||
|
||||
type HabitService struct {
|
||||
habitRepo *repository.HabitRepository
|
||||
habitRepo *repository.HabitRepository
|
||||
freezeRepo *repository.HabitFreezeRepository
|
||||
}
|
||||
|
||||
func NewHabitService(habitRepo *repository.HabitRepository) *HabitService {
|
||||
return &HabitService{habitRepo: habitRepo}
|
||||
func NewHabitService(habitRepo *repository.HabitRepository, freezeRepo *repository.HabitFreezeRepository) *HabitService {
|
||||
return &HabitService{
|
||||
habitRepo: habitRepo,
|
||||
freezeRepo: freezeRepo,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *HabitService) Create(userID int64, req *model.CreateHabitRequest) (*model.Habit, error) {
|
||||
@@ -32,6 +40,17 @@ func (s *HabitService) Create(userID int64, req *model.CreateHabitRequest) (*mod
|
||||
habit.ReminderTime = sql.NullString{String: *req.ReminderTime, Valid: true}
|
||||
}
|
||||
|
||||
// Handle start_date - default to today if not provided
|
||||
if req.StartDate != nil && *req.StartDate != "" {
|
||||
parsed, err := time.Parse("2006-01-02", *req.StartDate)
|
||||
if err == nil {
|
||||
habit.StartDate = sql.NullTime{Time: parsed, Valid: true}
|
||||
}
|
||||
} else {
|
||||
// Default to today
|
||||
habit.StartDate = sql.NullTime{Time: time.Now().Truncate(24 * time.Hour), Valid: true}
|
||||
}
|
||||
|
||||
if err := s.habitRepo.Create(habit); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -89,6 +108,16 @@ func (s *HabitService) Update(id, userID int64, req *model.UpdateHabitRequest) (
|
||||
habit.ReminderTime = sql.NullString{String: *req.ReminderTime, Valid: true}
|
||||
}
|
||||
}
|
||||
if req.StartDate != nil {
|
||||
if *req.StartDate == "" {
|
||||
habit.StartDate = sql.NullTime{Valid: false}
|
||||
} else {
|
||||
parsed, err := time.Parse("2006-01-02", *req.StartDate)
|
||||
if err == nil {
|
||||
habit.StartDate = sql.NullTime{Time: parsed, Valid: true}
|
||||
}
|
||||
}
|
||||
}
|
||||
if req.IsArchived != nil {
|
||||
habit.IsArchived = *req.IsArchived
|
||||
}
|
||||
@@ -111,13 +140,29 @@ func (s *HabitService) Log(habitID, userID int64, req *model.LogHabitRequest) (*
|
||||
return nil, err
|
||||
}
|
||||
|
||||
date := time.Now().Truncate(24 * time.Hour)
|
||||
today := time.Now().Truncate(24 * time.Hour)
|
||||
date := today
|
||||
|
||||
if req.Date != "" {
|
||||
parsed, err := time.Parse("2006-01-02", req.Date)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
date = parsed
|
||||
date = parsed.Truncate(24 * time.Hour)
|
||||
}
|
||||
|
||||
// Validate: cannot log for future date
|
||||
if date.After(today) {
|
||||
return nil, ErrFutureDate
|
||||
}
|
||||
|
||||
// Check if already logged for this date
|
||||
alreadyLogged, err := s.habitRepo.IsHabitCompletedOnDate(habitID, userID, date)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if alreadyLogged {
|
||||
return nil, ErrAlreadyLogged
|
||||
}
|
||||
|
||||
log := &model.HabitLog{
|
||||
@@ -160,11 +205,20 @@ func (s *HabitService) DeleteLog(logID, userID int64) error {
|
||||
|
||||
func (s *HabitService) GetHabitStats(habitID, userID int64) (*model.HabitStats, error) {
|
||||
// Verify habit exists and belongs to user
|
||||
if _, err := s.habitRepo.GetByID(habitID, userID); err != nil {
|
||||
habit, err := s.habitRepo.GetByID(habitID, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return s.habitRepo.GetStats(habitID, userID)
|
||||
stats, err := s.habitRepo.GetStats(habitID, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Recalculate completion percentage with frozen days excluded
|
||||
stats.CompletionPct = s.calculateCompletionPctWithFreezes(habit, stats.TotalLogs)
|
||||
|
||||
return stats, nil
|
||||
}
|
||||
|
||||
func (s *HabitService) GetOverallStats(userID int64) (*model.OverallStats, error) {
|
||||
@@ -190,6 +244,75 @@ func (s *HabitService) GetOverallStats(userID int64) (*model.OverallStats, error
|
||||
}, nil
|
||||
}
|
||||
|
||||
// calculateCompletionPctWithFreezes calculates completion % excluding frozen days
|
||||
func (s *HabitService) calculateCompletionPctWithFreezes(habit *model.Habit, totalLogs int) float64 {
|
||||
if totalLogs == 0 {
|
||||
return 0
|
||||
}
|
||||
|
||||
// Use start_date if set, otherwise use created_at
|
||||
var startDate time.Time
|
||||
if habit.StartDate.Valid {
|
||||
startDate = habit.StartDate.Time.Truncate(24 * time.Hour)
|
||||
} else {
|
||||
startDate = habit.CreatedAt.Truncate(24 * time.Hour)
|
||||
}
|
||||
today := time.Now().Truncate(24 * time.Hour)
|
||||
|
||||
// Get frozen days count for this habit
|
||||
frozenDays, err := s.freezeRepo.CountFrozenDaysInRange(habit.ID, startDate, today)
|
||||
if err != nil {
|
||||
frozenDays = 0
|
||||
}
|
||||
|
||||
expectedCount := 0
|
||||
|
||||
// For interval habits, calculate expected differently
|
||||
if (habit.Frequency == "interval" || habit.Frequency == "custom") && habit.TargetCount > 0 {
|
||||
// Expected = (days since start - frozen days) / interval + 1
|
||||
totalDays := int(today.Sub(startDate).Hours()/24) + 1 - frozenDays
|
||||
if totalDays <= 0 {
|
||||
return 100
|
||||
}
|
||||
expectedCount = (totalDays / habit.TargetCount) + 1
|
||||
} else {
|
||||
for d := startDate; !d.After(today); d = d.AddDate(0, 0, 1) {
|
||||
// Check if this day is frozen
|
||||
frozen, _ := s.freezeRepo.IsHabitFrozenOnDate(habit.ID, d)
|
||||
if frozen {
|
||||
continue
|
||||
}
|
||||
|
||||
if habit.Frequency == "daily" {
|
||||
expectedCount++
|
||||
} else if habit.Frequency == "weekly" && len(habit.TargetDays) > 0 {
|
||||
weekday := int(d.Weekday())
|
||||
if weekday == 0 {
|
||||
weekday = 7
|
||||
}
|
||||
for _, td := range habit.TargetDays {
|
||||
if td == weekday {
|
||||
expectedCount++
|
||||
break
|
||||
}
|
||||
}
|
||||
} else {
|
||||
expectedCount++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if expectedCount == 0 {
|
||||
return 100
|
||||
}
|
||||
|
||||
pct := float64(totalLogs) / float64(expectedCount) * 100
|
||||
if pct > 100 {
|
||||
pct = 100
|
||||
}
|
||||
return pct
|
||||
}
|
||||
|
||||
func defaultString(val, def string) string {
|
||||
if val == "" {
|
||||
return def
|
||||
|
||||
Reference in New Issue
Block a user