Enhance smoking tracking API with new features and improvements

- Added a new API endpoint `GET /api/v1/smoke/home` to consolidate core modules for the home dashboard, reducing the need for multiple requests.
- Updated the `smoke` routes to include the new home endpoint and improved user profile management with the addition of a `quit_date` field.
- Enhanced the algorithm for calculating daily targets and next smoke suggestions, ensuring accurate future time handling and user-specific recommendations.
- Improved API documentation to reflect new endpoints, response formats, and detailed field descriptions for better clarity and usability.
- Refactored user authentication handling in various handlers to streamline the process and ensure consistent error responses.
This commit is contained in:
nepiedg
2026-01-29 17:16:35 +00:00
parent 3154365ab2
commit 9200600b1c
21 changed files with 703 additions and 178 deletions
@@ -44,12 +44,12 @@ func NewSmokeAINextSmokeService(db *gorm.DB, cfg config.AIConfig) *SmokeAINextSm
}
type aiNextSmokeInput struct {
AsOf string `json:"as_of"`
PlanDate string `json:"plan_date"`
MinNotBeforeAt string `json:"min_not_before_at"`
AsOf string `json:"as_of"`
PlanDate string `json:"plan_date"`
MinNotBeforeAt string `json:"min_not_before_at"`
DefaultSuggestion NextSmokeSuggestion `json:"default_suggestion"`
Profile *adviceUserProfile `json:"profile,omitempty"`
Recent3Days []recentDaySnapshot `json:"recent_3_days"`
Profile *adviceUserProfile `json:"profile,omitempty"`
Recent3Days []recentDaySnapshot `json:"recent_3_days"`
}
type aiNextSmokeOutput struct {
@@ -75,14 +75,14 @@ type recentDayNode struct {
}
type AINextSmokeSuggestion struct {
PlanDate string `json:"plan_date"`
NotBeforeAt string `json:"not_before_at"`
SuggestedAt string `json:"suggested_at"`
TimeNodes []string `json:"time_nodes"`
Advice string `json:"advice"`
PromptVersion string `json:"prompt_version"`
Model string `json:"model,omitempty"`
Provider string `json:"provider,omitempty"`
PlanDate string `json:"plan_date"`
NotBeforeAt string `json:"not_before_at"`
SuggestedAt string `json:"suggested_at"`
TimeNodes []string `json:"time_nodes"`
Advice string `json:"advice"`
PromptVersion string `json:"prompt_version"`
Model string `json:"model,omitempty"`
Provider string `json:"provider,omitempty"`
}
func (s *SmokeAINextSmokeService) GetOrGenerate(ctx context.Context, user *usermodel.User, asOf time.Time, planDate time.Time, promptVersion string, defaultSuggestion NextSmokeSuggestion) (AINextSmokeSuggestion, error) {
@@ -122,12 +122,12 @@ func (s *SmokeAINextSmokeService) GetOrGenerate(ctx context.Context, user *userm
minNotBefore := s.computeMinNotBefore(asOf, planDate, defaultSuggestion, profile)
input := aiNextSmokeInput{
AsOf: asOf.In(time.Local).Format(time.RFC3339),
PlanDate: planDate.Format("2006-01-02"),
MinNotBeforeAt: minNotBefore.In(time.Local).Format(time.RFC3339),
DefaultSuggestion: defaultSuggestion,
Profile: profile,
Recent3Days: recent,
AsOf: asOf.In(time.Local).Format(time.RFC3339),
PlanDate: planDate.Format("2006-01-02"),
MinNotBeforeAt: minNotBefore.In(time.Local).Format(time.RFC3339),
DefaultSuggestion: defaultSuggestion,
Profile: profile,
Recent3Days: recent,
}
inputJSON, _ := json.Marshal(input)
@@ -402,7 +402,7 @@ func (s *SmokeAINextSmokeService) loadRecent3Days(ctx context.Context, uid int,
}
snap := ensure(day)
isResisted := l.Level == 0 && l.Num == 0
isResisted := l.Num == 0
if isResisted {
snap.ResistedCount++
} else if l.Num > 0 {
+34 -6
View File
@@ -95,6 +95,7 @@ type ListSmokeLogsRequest struct {
PageSize int
Start *time.Time
End *time.Time
Type string
}
type ListSmokeLogsResult struct {
@@ -124,6 +125,7 @@ type SmokeHomeSummary struct {
ResistedCount int
ReducedFromYesterday int
ExceededYesterday bool
SecondsSinceLast int
}
// DashboardWeeklyStat 表示某一天的抽烟支数以及是否为今天。
@@ -155,6 +157,14 @@ func (s *SmokeLogService) List(ctx context.Context, uid int, req ListSmokeLogsRe
if req.End != nil {
tx = tx.Where("smoke_time <= ?", req.End.Format("2006-01-02"))
}
switch req.Type {
case "", "all":
// no-op
case "smoke":
tx = tx.Where("num > 0")
case "resisted":
tx = tx.Where("num = 0")
}
var total int64
if err := tx.Count(&total).Error; err != nil {
@@ -164,7 +174,7 @@ func (s *SmokeLogService) List(ctx context.Context, uid int, req ListSmokeLogsRe
var items []smokemodel.SmokeLog
offset := (page - 1) * pageSize
if err := tx.
Order("smoke_time DESC").
Order("COALESCE(smoke_at, FROM_UNIXTIME(createtime), smoke_time) DESC").
Order("id DESC").
Limit(pageSize).
Offset(offset).
@@ -221,7 +231,7 @@ func (s *SmokeLogService) Dashboard(ctx context.Context, uid int, req SmokeDashb
var last smokemodel.SmokeLog
if err := s.db.WithContext(ctx).
Where("uid = ? AND (deletetime IS NULL OR deletetime = 0)", uid).
Where("NOT (level = 0 AND num = 0)").
Where("num > 0").
Order("COALESCE(smoke_at, FROM_UNIXTIME(createtime), smoke_time) DESC").
Order("id DESC").
Limit(1).
@@ -259,6 +269,7 @@ func (s *SmokeLogService) Dashboard(ctx context.Context, uid int, req SmokeDashb
// HomeSummary 返回首页所需的汇总数据(不包含时间范围的周统计)。
func (s *SmokeLogService) HomeSummary(ctx context.Context, uid int, asOf time.Time) (SmokeHomeSummary, error) {
localAsOf := asOf.In(time.Local)
today := dateOnly(asOf)
todayKey := today.Format("2006-01-02")
yesterdayKey := today.AddDate(0, 0, -1).Format("2006-01-02")
@@ -276,7 +287,7 @@ func (s *SmokeLogService) HomeSummary(ctx context.Context, uid int, asOf time.Ti
if err := s.db.WithContext(ctx).
Model(&smokemodel.SmokeLog{}).
Where("uid = ? AND (deletetime IS NULL OR deletetime = 0)", uid).
Where("level = 0 AND num = 0 AND smoke_time = ?", todayKey).
Where("num = 0 AND smoke_time = ?", todayKey).
Count(&resistedCount).Error; err != nil {
return SmokeHomeSummary{}, fmt.Errorf("count resisted logs: %w", err)
}
@@ -290,14 +301,22 @@ func (s *SmokeLogService) HomeSummary(ctx context.Context, uid int, asOf time.Ti
return SmokeHomeSummary{}, fmt.Errorf("count yesterday smoke logs: %w", err)
}
reduced := int(yesterdayCount - todayCount)
exceeded := reduced < 0
diffFromYesterday := int(yesterdayCount - todayCount)
reduced := 0
exceeded := false
if diffFromYesterday > 0 {
reduced = diffFromYesterday
} else if diffFromYesterday < 0 {
reduced = -diffFromYesterday
exceeded = true
}
var lastSmokeAt *time.Time
secondsSinceLast := -1
var last smokemodel.SmokeLog
if err := s.db.WithContext(ctx).
Where("uid = ? AND (deletetime IS NULL OR deletetime = 0)", uid).
Where("NOT (level = 0 AND num = 0)").
Where("num > 0").
Order("COALESCE(smoke_at, FROM_UNIXTIME(createtime), smoke_time) DESC").
Order("id DESC").
Limit(1).
@@ -306,7 +325,15 @@ func (s *SmokeLogService) HomeSummary(ctx context.Context, uid int, asOf time.Ti
return SmokeHomeSummary{}, fmt.Errorf("load last smoke log: %w", err)
}
} else if t, ok := lastEventTime(last); ok {
if t.After(localAsOf) {
t = localAsOf
}
lastSmokeAt = &t
diff := int(localAsOf.Sub(t).Seconds())
if diff < 0 {
diff = 0
}
secondsSinceLast = diff
}
return SmokeHomeSummary{
@@ -315,6 +342,7 @@ func (s *SmokeLogService) HomeSummary(ctx context.Context, uid int, asOf time.Ti
ResistedCount: int(resistedCount),
ReducedFromYesterday: reduced,
ExceededYesterday: exceeded,
SecondsSinceLast: secondsSinceLast,
}, nil
}
+34 -16
View File
@@ -20,21 +20,22 @@ func NewSmokeNextService(db *gorm.DB) *SmokeNextService {
}
type NextSmokeSuggestion struct {
LastSmokeAt *time.Time `json:"last_smoke_at,omitempty"`
NextSmokeAt *time.Time `json:"next_smoke_at,omitempty"`
BaseIntervalMinutes int `json:"base_interval_minutes"`
IntervalMinutes int `json:"interval_minutes"`
Stage int `json:"stage"`
Resisted7d int `json:"resisted_7d"`
SleepAdjusted bool `json:"sleep_adjusted"`
Algorithm string `json:"algorithm"`
AsOf string `json:"as_of"`
LastSmokeAt *time.Time `json:"last_smoke_at,omitempty"`
NextSmokeAt *time.Time `json:"next_smoke_at,omitempty"`
BaseIntervalMinutes int `json:"base_interval_minutes"`
IntervalMinutes int `json:"interval_minutes"`
Stage int `json:"stage"`
Resisted7d int `json:"resisted_7d"`
SleepAdjusted bool `json:"sleep_adjusted"`
Algorithm string `json:"algorithm"`
AsOf string `json:"as_of"`
}
// GetDefaultSuggestion 返回“未使用 AI 时”的默认下次抽烟时间建议(阶梯式延时算法)。
func (s *SmokeNextService) GetDefaultSuggestion(ctx context.Context, uid int, asOf time.Time, planDate time.Time, profileView SmokeProfileView) (NextSmokeSuggestion, error) {
now := asOf.In(time.Local)
planDay := dateOnly(planDate)
today := dateOnly(now)
base := profileView.BaselineIntervalMinute
if base <= 0 {
@@ -46,8 +47,11 @@ func (s *SmokeNextService) GetDefaultSuggestion(ctx context.Context, uid int, as
return NextSmokeSuggestion{}, err
}
if !ok {
nowCopy := now
lastSmokeAt = &nowCopy
lastCopy := now
lastSmokeAt = &lastCopy
} else if lastSmokeAt.After(now) {
clamped := now
lastSmokeAt = &clamped
}
resisted, err := s.countResistedLastDays(ctx, uid, 7)
@@ -68,7 +72,22 @@ func (s *SmokeNextService) GetDefaultSuggestion(ctx context.Context, uid int, as
interval = 240
}
next := lastSmokeAt.Add(time.Duration(interval) * time.Minute)
intervalDuration := time.Duration(interval) * time.Minute
next := lastSmokeAt.Add(intervalDuration)
if !planDay.After(today) && next.Before(now) {
if intervalDuration <= 0 {
next = now
} else {
elapsed := now.Sub(*lastSmokeAt)
missed := int(elapsed / intervalDuration)
if missed < 0 {
missed = 0
}
next = lastSmokeAt.Add(time.Duration(missed+1) * intervalDuration)
}
}
sleepAdjusted := false
var wakeUp, sleep string
@@ -78,7 +97,6 @@ func (s *SmokeNextService) GetDefaultSuggestion(ctx context.Context, uid int, as
}
// 如果是“生成某一天的计划”(例如明天),默认不早于该日的起床时间(若未配置则使用 07:00)。
today := dateOnly(now)
if planDay.After(today) {
minNotBefore := time.Date(planDay.Year(), planDay.Month(), planDay.Day(), 7, 0, 0, 0, time.Local)
if wakeUp != "" {
@@ -105,7 +123,7 @@ func (s *SmokeNextService) GetDefaultSuggestion(ctx context.Context, uid int, as
out := NextSmokeSuggestion{
BaseIntervalMinutes: base,
IntervalMinutes: interval,
Stage: stage,
Stage: stage,
Resisted7d: resisted,
SleepAdjusted: sleepAdjusted,
Algorithm: "staircase_delay_v1",
@@ -123,7 +141,7 @@ func (s *SmokeNextService) loadLastActualSmokeAt(ctx context.Context, uid int) (
var last smokemodel.SmokeLog
err := s.db.WithContext(ctx).
Where("uid = ? AND (deletetime IS NULL OR deletetime = 0)", uid).
Where("NOT (level = 0 AND num = 0)").
Where("num > 0").
Order("COALESCE(smoke_at, FROM_UNIXTIME(createtime), smoke_time) DESC").
Order("id DESC").
Limit(1).
@@ -152,7 +170,7 @@ func (s *SmokeNextService) countResistedLastDays(ctx context.Context, uid int, d
if err := s.db.WithContext(ctx).
Model(&smokemodel.SmokeLog{}).
Where("uid = ? AND (deletetime IS NULL OR deletetime = 0)", uid).
Where("level = 0 AND num = 0").
Where("num = 0").
Where("smoke_time BETWEEN ? AND ?", start.Format("2006-01-02"), end.Format("2006-01-02")).
Count(&count).Error; err != nil {
return 0, fmt.Errorf("count resisted logs: %w", err)
@@ -25,7 +25,7 @@ func NewSmokeProfileService(db *gorm.DB) *SmokeProfileService {
}
type SmokeProfileView struct {
Exists bool `json:"exists"`
Exists bool `json:"exists"`
Profile *smokemodel.SmokeUserProfile `json:"profile,omitempty"`
IsCompleted bool `json:"is_completed"`
@@ -89,6 +89,9 @@ type UpsertSmokeProfileRequest struct {
WakeUpTime *string
SleepTime *string
QuitDateProvided bool
QuitDate *time.Time
}
func (s *SmokeProfileService) Upsert(ctx context.Context, uid int, req UpsertSmokeProfileRequest) (SmokeProfileView, error) {
@@ -146,6 +149,9 @@ func (s *SmokeProfileService) Upsert(ctx context.Context, uid int, req UpsertSmo
if err := applyTimeStr(&profile.SleepTime, req.SleepTime); err != nil {
return SmokeProfileView{}, err
}
if req.QuitDateProvided {
profile.QuitDate = req.QuitDate
}
now := time.Now()
if profile.OnboardingCompletedAt == nil && isSmokeProfileCompleted(profile) {
@@ -195,7 +201,7 @@ func awakeMinutesWithFallback(wakeUp, sleep string) (int, error) {
if sleepMin > wakeMin {
return sleepMin - wakeMin, nil
}
return (24 * 60 - wakeMin) + sleepMin, nil
return (24*60 - wakeMin) + sleepMin, nil
}
func baselineIntervalMinutes(awakeMinutes int, baselineCigsPerDay int) int {
+63 -6
View File
@@ -83,6 +83,7 @@ func (s *SmokeLogService) Stats(ctx context.Context, uid int, req SmokeStatsRequ
if err != nil {
return SmokeStatsResult{}, err
}
trend = limitTrend(trend, 7)
dayCount := daysBetweenInclusive(start, end)
dailyAvg := 0
@@ -109,7 +110,7 @@ func (s *SmokeLogService) Stats(ctx context.Context, uid int, req SmokeStatsRequ
return SmokeStatsResult{}, err
}
money := s.computeMoney(profile, int(total), dayCount)
money := s.computeMoney(ctx, uid, profile, int(total), start, end)
health, err := s.computeHealth(ctx, uid, req.AsOf)
if err != nil {
return SmokeStatsResult{}, err
@@ -130,6 +131,24 @@ func (s *SmokeLogService) Stats(ctx context.Context, uid int, req SmokeStatsRequ
}, nil
}
func limitTrend(items []SmokeStatsTrend, max int) []SmokeStatsTrend {
if max <= 0 || len(items) <= max {
return items
}
lastIndex := len(items) - 1
out := make([]SmokeStatsTrend, 0, max)
seen := make(map[int]struct{}, max)
for i := 0; i < max; i++ {
pos := int(math.Round(float64(i) * float64(lastIndex) / float64(max-1)))
if _, ok := seen[pos]; ok {
continue
}
seen[pos] = struct{}{}
out = append(out, items[pos])
}
return out
}
func (s *SmokeLogService) loadDailyTrend(ctx context.Context, uid int, start, end time.Time) ([]SmokeStatsTrend, int64, error) {
type dailyCount struct {
SmokeTime time.Time `gorm:"column:smoke_time"`
@@ -225,7 +244,7 @@ func (s *SmokeLogService) countResisted(ctx context.Context, uid int, start, end
if err := s.db.WithContext(ctx).
Model(&smokemodel.SmokeLog{}).
Where("uid = ? AND (deletetime IS NULL OR deletetime = 0)", uid).
Where("level = 0 AND num = 0").
Where("num = 0").
Where("smoke_time BETWEEN ? AND ?", start.Format("2006-01-02"), end.Format("2006-01-02")).
Count(&count).Error; err != nil {
return 0, fmt.Errorf("count resisted: %w", err)
@@ -267,12 +286,31 @@ func (s *SmokeLogService) computeStreakDays(ctx context.Context, uid int, asOf t
return streak, nil
}
func (s *SmokeLogService) computeMoney(profile *smokemodel.SmokeUserProfile, actualTotal int, dayCount int) SmokeStatsMoney {
if profile == nil || profile.BaselineCigsPerDay <= 0 || profile.PackPriceCent <= 0 || dayCount <= 0 {
func (s *SmokeLogService) computeMoney(ctx context.Context, uid int, profile *smokemodel.SmokeUserProfile, actualTotal int, start, end time.Time) SmokeStatsMoney {
if profile == nil || profile.BaselineCigsPerDay <= 0 || profile.PackPriceCent <= 0 {
return SmokeStatsMoney{Available: false}
}
expectedTotal := profile.BaselineCigsPerDay * dayCount
activeDays, err := s.countLogDays(ctx, uid, start, end)
if err != nil {
return SmokeStatsMoney{Available: false}
}
if activeDays <= 0 {
return SmokeStatsMoney{
Available: true,
PackPriceCent: profile.PackPriceCent,
CigsPerPack: defaultCigsPerPack,
ExpectedTotal: 0,
ActualTotal: actualTotal,
SavedCent: 0,
}
}
expectedTotal := profile.BaselineCigsPerDay * activeDays
savedCigs := expectedTotal - actualTotal
if savedCigs < 0 {
savedCigs = 0
}
savedPacks := float64(savedCigs) / float64(defaultCigsPerPack)
savedCent := int(math.Round(savedPacks * float64(profile.PackPriceCent)))
return SmokeStatsMoney{
@@ -285,6 +323,25 @@ func (s *SmokeLogService) computeMoney(profile *smokemodel.SmokeUserProfile, act
}
}
func (s *SmokeLogService) countLogDays(ctx context.Context, uid int, start, end time.Time) (int, error) {
start = dateOnly(start)
end = dateOnly(end)
type row struct {
SmokeTime time.Time `gorm:"column:smoke_time"`
}
var rows []row
if err := s.db.WithContext(ctx).
Model(&smokemodel.SmokeLog{}).
Distinct("smoke_time").
Where("uid = ? AND (deletetime IS NULL OR deletetime = 0)", uid).
Where("smoke_time BETWEEN ? AND ?", start.Format("2006-01-02"), end.Format("2006-01-02")).
Find(&rows).Error; err != nil {
return 0, fmt.Errorf("count log days: %w", err)
}
return len(rows), nil
}
func (s *SmokeLogService) computeHealth(ctx context.Context, uid int, asOf time.Time) (SmokeStatsHealth, error) {
lastSmokeAt, err := s.loadLastActualSmokeAt(ctx, uid)
if err != nil {
@@ -311,7 +368,7 @@ func (s *SmokeLogService) loadLastActualSmokeAt(ctx context.Context, uid int) (*
var last smokemodel.SmokeLog
if err := s.db.WithContext(ctx).
Where("uid = ? AND (deletetime IS NULL OR deletetime = 0)", uid).
Where("NOT (level = 0 AND num = 0)").
Where("num > 0").
Order("COALESCE(smoke_at, FROM_UNIXTIME(createtime), smoke_time) DESC").
Order("id DESC").
Limit(1).