diff --git a/cmd/api/main.go b/cmd/api/main.go index 963cda4..44d118a 100644 --- a/cmd/api/main.go +++ b/cmd/api/main.go @@ -52,6 +52,7 @@ func main() { &smokemodel.SmokeUserProfile{}, &smokemodel.SmokeAIAdvice{}, &smokemodel.SmokeAIAdviceUnlock{}, + &smokemodel.SmokeAINextSmoke{}, ); err != nil { log.Fatalf("auto migrate failed: %v", err) } @@ -73,7 +74,9 @@ func main() { smokeLogService := smokeservice.NewSmokeLogService(database.DB) smokeAIAdviceService := smokeservice.NewSmokeAIAdviceService(database.DB, config.AppConfig.AI) smokeProfileService := smokeservice.NewSmokeProfileService(database.DB) - smokeHandler := smokehandler.NewSmokeHandler(smokeLogService, smokeAIAdviceService, smokeProfileService) + smokeNextService := smokeservice.NewSmokeNextService(database.DB) + smokeAINextService := smokeservice.NewSmokeAINextSmokeService(database.DB, config.AppConfig.AI) + smokeHandler := smokehandler.NewSmokeHandler(smokeLogService, smokeAIAdviceService, smokeProfileService, smokeNextService, smokeAINextService) redeemCodeService := membershipservice.NewRedeemCodeService(database.DB, config.AppConfig.Admin.Token) redeemCodeHandler := membershiphandler.NewRedeemCodeHandler(redeemCodeService) diff --git a/docs/smoke/API.md b/docs/smoke/API.md index ad709a1..f3b25a9 100644 --- a/docs/smoke/API.md +++ b/docs/smoke/API.md @@ -22,7 +22,8 @@ 说明: - `smoke_time` 可选;不传则默认“当天”。 - `smoke_at` 可选;真实抽烟时间(格式 `YYYY-MM-DD HH:MM:SS`)。用于“按时间节点分析/AI 建议”;不传则可用 `createtime` 近似。 -- `level/num` 可选;不传或传 `<=0` 时会按 `1` 处理。 +- `level/num` 可选;不传时后端会按 `1` 处理。 +- 如果要记录“想抽但忍住了”,请传 `level=0` 且 `num=0`(会在 `fa_smoke_log` 中展示为一条记录,但不会影响看板的支数累加)。 curl 示例: @@ -120,7 +121,7 @@ curl -X GET 'http://127.0.0.1:8080/api/v1/smoke/logs/5202' \ 字段说明: - `today_count`:当天吸烟总支数(累加 `num`) -- `minutes_since_last`:距最后一次抽烟的分钟数,通过最近一条 `smoke_at/smoke_time/createtime` 计算;若历史为空则字段不存在 +- `minutes_since_last`:距最后一次“实际抽烟”(忽略 `level=0 && num=0` 的忍住记录)的分钟数,通过最近一条 `smoke_at/smoke_time/createtime` 计算;若历史为空则字段不存在 - `weekly`:起止日期内每日汇总,`count` 为当日总支数,`is_today` 标记当前日期(即便不在 `start/end` 范围内也会标记为 `false`) ## 5) 最近记录列表(轻量版) @@ -237,6 +238,8 @@ curl -X GET 'http://127.0.0.1:8080/api/v1/smoke/logs/5202' \ 说明: - 该接口用于记录“已完成观看广告”,落库到 `fa_smoke_ai_advice_unlocks`(`uid + unlock_date` 唯一)。 - `ad_watched_at` 可由后端取当前时间;如需审计/对账可保留前端上报并做校验。 +- 解锁是“按天”的:观看一次广告解锁一天内的 AI 生成功能(可用于「每日 AI 建议」以及「AI 下次抽烟时间节点」)。 +- 如果你要生成“明天”的 AI 时间节点,请把 `date` 传为明天日期(例如 `2026-01-06`)。 ## 10) 获取用户基础信息(首次进入:判断是否需要补全) @@ -321,3 +324,93 @@ curl -X GET 'http://127.0.0.1:8080/api/v1/smoke/logs/5202' \ ``` 成功响应:同 `GET /api/v1/smoke/profile`(返回最新 `profile` + `is_completed` + `baseline_interval_minutes`)。 + +## 12) 想抽但忍住了(写入一条 level=0,num=0 的记录) + +`POST /api/v1/smoke/logs/resisted` + +请求体(示例): +```json +{ + "smoke_time": "2026-01-05", + "smoke_at": "2026-01-05 10:20:00", + "remark": "压力大,想抽但忍住了" +} +``` + +说明: +- 该接口会在 `fa_smoke_log` 中新增一条记录:`level=0` 且 `num=0`,用于更直观记录“想抽/忍住”的过程。 +- 这类记录不会影响 `today_count/weekly.count` 的支数统计(因为 `num=0`)。 + +## 13) 获取“下次抽烟记录时间”(默认 + AI 自动切换) + +`GET /api/v1/smoke/next_smoke_time` + +说明: +- 用于首页展示“建议的下次记录时间”。 +- 如果指定日期存在 AI 给出的时间节点(`time_nodes` 不为空),则优先使用 AI 的建议;否则使用默认策略。 +- 可选参数: + - `date`:计划日期(默认今天),支持 `YYYY-MM-DD` 或 `today/tomorrow`。 + - `mode`(默认 `auto`) + - `auto`:只在已存在 AI 时间节点时使用 AI(不主动生成) + - `ai`:生成该 `date` 的 AI 时间节点(需要先看广告解锁;生成一次缓存一天) + - `default`:永远返回默认策略 + +默认策略(不使用 AI): +- 基础间隔:优先使用 `GET /api/v1/smoke/profile` 返回的 `baseline_interval_minutes`;若不存在则默认 `60` 分钟。 +- 阶梯式延时:最近 7 天内每累计 `5` 条“忍住记录(level=0,num=0)”,在基础间隔上 `+5` 分钟(最多 `+60` 分钟)。 +- 若用户已补全作息时间,会自动规避睡眠区间:若计算出的时间落在睡眠区间,顺延到下一次起床时间。 + +AI 生成说明: +- 当 `mode=ai` 时,会把最近 3 天的抽烟数据(含“忍住记录”)作为输入提供给 AI,用于更贴合近期模式生成时间节点。 +- 未解锁时会返回 `403`:提示需要观看广告解锁。 + +成功响应(示例:回落到默认): +```json +{ + "code": 200, + "message": "success", + "data": { + "source": "default", + "not_before_at": "2026-01-05T10:18:00+08:00", + "suggested_at": "2026-01-05T10:18:00+08:00", + "default": { + "last_smoke_at": "2026-01-05T09:30:00+08:00", + "next_smoke_at": "2026-01-05T10:18:00+08:00", + "base_interval_minutes": 48, + "interval_minutes": 48, + "stage": 0, + "resisted_7d": 3, + "sleep_adjusted": false, + "algorithm": "staircase_delay_v1", + "as_of": "2026-01-05T10:00:00+08:00" + } + } +} +``` + +当存在 AI 建议且包含 `time_nodes` 时,响应会是(示例): +```json +{ + "code": 200, + "message": "success", + "data": { + "source": "ai", + "not_before_at": "2026-01-05T10:18:00+08:00", + "suggested_at": "2026-01-05T10:28:00+08:00", + "time_nodes": ["10:30", "11:10", "14:00", "16:30"], + "advice": "先把这次冲动延后到10:28,期间做一次5分钟快走+喝水,压力场景用深呼吸替代。", + "default": { "algorithm": "staircase_delay_v1" }, + "ai": { + "plan_date": "2026-01-05", + "not_before_at": "2026-01-05T10:18:00+08:00", + "suggested_at": "2026-01-05T10:28:00+08:00", + "time_nodes": ["10:30", "11:10", "14:00", "16:30"], + "advice": "先把这次冲动延后到10:28,期间做一次5分钟快走+喝水,压力场景用深呼吸替代。", + "prompt_version": "v1", + "model": "gpt-4.1-mini", + "provider": "openai-compatible" + } + } +} +``` diff --git a/docs/smoke/README.md b/docs/smoke/README.md index 14bef5e..8489d71 100644 --- a/docs/smoke/README.md +++ b/docs/smoke/README.md @@ -41,6 +41,7 @@ 涉及表(DDL 见:`docs/sql/smoke.sql`): - `fa_smoke_ai_advice`:按 `uid + advice_date + prompt_version` 缓存建议结果,避免重复调用 AI。 - `fa_smoke_ai_advice_unlocks`:非会员用户的“每日解锁”记录(按 `uid + unlock_date` 唯一)。 +- `fa_smoke_ai_next_smoke`:保存“AI 下次抽烟时间节点”(每个时间点一条记录),AI 元信息复用 `fa_smoke_ai_advice`(`type=next_smoke_time`)。 建议的权限判断顺序: 1) 若用户是会员:直接允许生成/获取建议。 diff --git a/docs/sql/smoke.sql b/docs/sql/smoke.sql index 143a5e0..015818a 100644 --- a/docs/sql/smoke.sql +++ b/docs/sql/smoke.sql @@ -24,6 +24,7 @@ CREATE TABLE `fa_smoke_log` ( CREATE TABLE IF NOT EXISTS `fa_smoke_ai_advice` ( `id` bigint unsigned NOT NULL AUTO_INCREMENT, `uid` int(11) NOT NULL COMMENT '用户ID', + `type` varchar(30) NOT NULL DEFAULT 'daily_advice' COMMENT '用途类型(daily_advice/next_smoke_time/...)', `advice_date` date NOT NULL COMMENT '建议针对的日期(通常=昨天)', `prompt_version` varchar(30) NOT NULL DEFAULT 'v1' COMMENT '提示词版本', `provider` varchar(30) DEFAULT NULL COMMENT 'AI 提供方(可选)', @@ -37,7 +38,7 @@ CREATE TABLE IF NOT EXISTS `fa_smoke_ai_advice` ( `updatetime` int(11) DEFAULT NULL COMMENT '修改时间', `deletetime` int(11) DEFAULT NULL COMMENT '删除时间', PRIMARY KEY (`id`), - UNIQUE KEY `uniq_smoke_ai_advice` (`uid`,`advice_date`,`prompt_version`), + UNIQUE KEY `uniq_smoke_ai_advice` (`uid`,`type`,`advice_date`,`prompt_version`), KEY `idx_smoke_ai_advice_uid_date` (`uid`,`advice_date`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='每日AI戒烟建议'; @@ -77,3 +78,23 @@ CREATE TABLE IF NOT EXISTS `fa_smoke_user_profile` ( UNIQUE KEY `uniq_smoke_profile_uid` (`uid`), KEY `idx_smoke_profile_deleted_at` (`deleted_at`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='戒烟-用户基础信息'; + +-- AI 下次抽烟时间建议(结构化缓存:当天) +-- 说明: +-- - not_before_at:AI 给出的“不早于”时间;suggested_at:AI 建议的下次抽烟时间(>= not_before_at) +-- - time_nodes:建议时间节点(JSON 数组,例如 ["10:30","11:10","14:00"]) +CREATE TABLE IF NOT EXISTS `fa_smoke_ai_next_smoke` ( + `id` bigint unsigned NOT NULL AUTO_INCREMENT, + `uid` int(11) NOT NULL COMMENT '用户ID', + `plan_date` date NOT NULL COMMENT '计划日期(当天)', + `ai_advice_id` bigint unsigned NOT NULL COMMENT '关联AI建议ID(fa_smoke_ai_advice.id)', + `node_type` varchar(20) NOT NULL COMMENT '节点类型(not_before/suggested/node)', + `node_at` datetime NOT NULL COMMENT '时间点', + `createtime` int(11) DEFAULT NULL COMMENT '创建时间', + `updatetime` int(11) DEFAULT NULL COMMENT '修改时间', + `deletetime` int(11) DEFAULT NULL COMMENT '删除时间', + PRIMARY KEY (`id`), + UNIQUE KEY `uniq_smoke_ai_next_node` (`ai_advice_id`,`node_type`,`node_at`), + KEY `idx_smoke_ai_next_uid_date` (`uid`,`plan_date`), + KEY `idx_smoke_ai_next_advice` (`ai_advice_id`,`node_type`,`node_at`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='AI下次抽烟时间节点'; diff --git a/internal/routes/smoke_routes.go b/internal/routes/smoke_routes.go index 94d23e4..a5444f3 100644 --- a/internal/routes/smoke_routes.go +++ b/internal/routes/smoke_routes.go @@ -14,8 +14,12 @@ func registerSmokeRoutes(protected *gin.RouterGroup, smokeHandler *smokehandler. smoke.GET("/profile", smokeHandler.GetProfile) smoke.PUT("/profile", smokeHandler.UpsertProfile) + // 不使用 AI 时的默认“下次抽烟时间”建议(阶梯式延时) + smoke.GET("/next_smoke_time", smokeHandler.GetNextSmokeTime) + smoke.GET("/dashboard", smokeHandler.Dashboard) smoke.POST("/logs", smokeHandler.Create) + smoke.POST("/logs/resisted", smokeHandler.Resist) smoke.GET("/logs", smokeHandler.List) smoke.GET("/logs/latest", smokeHandler.LatestLogs) smoke.GET("/logs/:id", smokeHandler.Get) @@ -25,5 +29,8 @@ func registerSmokeRoutes(protected *gin.RouterGroup, smokeHandler *smokehandler. // AI 戒烟建议(会员优先;非会员需看广告解锁) smoke.GET("/ai/advice", smokeHandler.GetAIAdvice) smoke.POST("/ai/advice_unlocks", smokeHandler.UnlockAIAdvice) + + // AI 下次抽烟时间建议(结构化时间节点) + smoke.GET("/ai/next_smoke_time", smokeHandler.GetAINextSmokeTime) } } diff --git a/internal/smoke/handler/smoke_ai_next_smoke_handler.go b/internal/smoke/handler/smoke_ai_next_smoke_handler.go new file mode 100644 index 0000000..48fa3e8 --- /dev/null +++ b/internal/smoke/handler/smoke_ai_next_smoke_handler.go @@ -0,0 +1,12 @@ +package handler + +import ( + "github.com/gin-gonic/gin" +) + +func (h *SmokeHandler) GetAINextSmokeTime(c *gin.Context) { + q := c.Request.URL.Query() + q.Set("mode", "ai") + c.Request.URL.RawQuery = q.Encode() + h.GetNextSmokeTime(c) +} diff --git a/internal/smoke/handler/smoke_handler.go b/internal/smoke/handler/smoke_handler.go index 0fea49c..7bcffcd 100644 --- a/internal/smoke/handler/smoke_handler.go +++ b/internal/smoke/handler/smoke_handler.go @@ -2,6 +2,7 @@ package handler import ( "errors" + "io" "net/http" "strconv" "time" @@ -17,13 +18,23 @@ type SmokeHandler struct { smokeLogService *smokeservice.SmokeLogService smokeAIAdviceService *smokeservice.SmokeAIAdviceService smokeProfileService *smokeservice.SmokeProfileService + smokeNextService *smokeservice.SmokeNextService + smokeAINextService *smokeservice.SmokeAINextSmokeService } -func NewSmokeHandler(smokeLogService *smokeservice.SmokeLogService, smokeAIAdviceService *smokeservice.SmokeAIAdviceService, smokeProfileService *smokeservice.SmokeProfileService) *SmokeHandler { +func NewSmokeHandler( + smokeLogService *smokeservice.SmokeLogService, + smokeAIAdviceService *smokeservice.SmokeAIAdviceService, + smokeProfileService *smokeservice.SmokeProfileService, + smokeNextService *smokeservice.SmokeNextService, + smokeAINextService *smokeservice.SmokeAINextSmokeService, +) *SmokeHandler { return &SmokeHandler{ smokeLogService: smokeLogService, smokeAIAdviceService: smokeAIAdviceService, smokeProfileService: smokeProfileService, + smokeNextService: smokeNextService, + smokeAINextService: smokeAINextService, } } @@ -37,8 +48,8 @@ type createSmokeLogRequest struct { // 真实抽烟时间(精确到时分秒,可补录) SmokeAt string `json:"smoke_at"` Remark string `json:"remark"` - Level int64 `json:"level"` - Num int `json:"num"` + Level *int64 `json:"level"` + Num *int `json:"num"` } func (h *SmokeHandler) Create(c *gin.Context) { @@ -54,6 +65,83 @@ func (h *SmokeHandler) Create(c *gin.Context) { return } + level := int64(1) + if req.Level != nil { + if *req.Level < 0 { + c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "level 不能为负数")) + return + } + level = *req.Level + } + num := 1 + if req.Num != nil { + if *req.Num < 0 { + c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "num 不能为负数")) + return + } + num = *req.Num + } + + if level < 0 || num < 0 { + c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "level/num 不能为负数")) + return + } + + var smokeTime *time.Time + if req.SmokeTime != "" { + parsed, err := time.ParseInLocation(dateLayout, req.SmokeTime, time.Local) + if err != nil { + c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "smoke_time 格式错误,应为 YYYY-MM-DD")) + return + } + smokeTime = &parsed + } + + var smokeAt *time.Time + if req.SmokeAt != "" { + parsed, err := time.ParseInLocation(dateTimeLayout, req.SmokeAt, time.Local) + if err != nil { + c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "smoke_at 格式错误,应为 YYYY-MM-DD HH:MM:SS")) + return + } + smokeAt = &parsed + } + + record, err := h.smokeLogService.Create(c.Request.Context(), int(user.ID), smokeservice.CreateSmokeLogRequest{ + SmokeTime: smokeTime, + SmokeAt: smokeAt, + Remark: req.Remark, + Level: level, + Num: num, + }) + if err != nil { + c.JSON(http.StatusInternalServerError, model.Error(http.StatusInternalServerError, "创建记录失败,请稍后重试")) + return + } + + c.JSON(http.StatusOK, model.Success(record)) +} + +type resistedSmokeLogRequest struct { + SmokeTime string `json:"smoke_time"` + SmokeAt string `json:"smoke_at"` + Remark string `json:"remark"` +} + +// Resist 表示“想抽但忍住了”:在 fa_smoke_log 中写入 level=0,num=0。 +func (h *SmokeHandler) Resist(c *gin.Context) { + user, ok := middleware.CurrentUser(c) + if !ok { + c.JSON(http.StatusUnauthorized, model.Error(http.StatusUnauthorized, "未登录或登录已过期")) + return + } + + var req resistedSmokeLogRequest + if err := c.ShouldBindJSON(&req); err != nil && !errors.Is(err, io.EOF) { + c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "请求参数错误")) + return + } + var smokeTime *time.Time if req.SmokeTime != "" { parsed, err := time.ParseInLocation(dateLayout, req.SmokeTime, time.Local) @@ -78,8 +166,8 @@ func (h *SmokeHandler) Create(c *gin.Context) { SmokeTime: smokeTime, SmokeAt: smokeAt, Remark: req.Remark, - Level: req.Level, - Num: req.Num, + Level: 0, + Num: 0, }) if err != nil { c.JSON(http.StatusInternalServerError, model.Error(http.StatusInternalServerError, "创建记录失败,请稍后重试")) @@ -271,6 +359,15 @@ func (h *SmokeHandler) Update(c *gin.Context) { return } + if req.Level != nil && *req.Level < 0 { + c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "level 不能为负数")) + return + } + if req.Num != nil && *req.Num < 0 { + c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "num 不能为负数")) + return + } + smokeTimeProvided := req.SmokeTime != nil var smokeTime *time.Time if req.SmokeTime != nil { diff --git a/internal/smoke/handler/smoke_next_handler.go b/internal/smoke/handler/smoke_next_handler.go new file mode 100644 index 0000000..3846481 --- /dev/null +++ b/internal/smoke/handler/smoke_next_handler.go @@ -0,0 +1,140 @@ +package handler + +import ( + "errors" + "net/http" + "strings" + "time" + + "github.com/gin-gonic/gin" + + "wx_service/internal/middleware" + "wx_service/internal/model" + smokeservice "wx_service/internal/smoke/service" +) + +type nextSmokeTimeUnifiedResponse struct { + Source string `json:"source"` + NotBeforeAt string `json:"not_before_at"` + SuggestedAt string `json:"suggested_at"` + TimeNodes []string `json:"time_nodes,omitempty"` + Advice string `json:"advice,omitempty"` + Default smokeservice.NextSmokeSuggestion `json:"default"` + AI *smokeservice.AINextSmokeSuggestion `json:"ai,omitempty"` +} + +func (h *SmokeHandler) GetNextSmokeTime(c *gin.Context) { + user, ok := middleware.CurrentUser(c) + if !ok { + c.JSON(http.StatusUnauthorized, model.Error(http.StatusUnauthorized, "未登录或登录已过期")) + return + } + + asOf := time.Now().In(time.Local) + planDate := dateOnlyLocal(asOf) + if v := strings.TrimSpace(c.Query("date")); v != "" { + switch strings.ToLower(v) { + case "today": + planDate = dateOnlyLocal(asOf) + case "tomorrow": + planDate = dateOnlyLocal(asOf).AddDate(0, 0, 1) + default: + parsed, err := time.ParseInLocation(dateLayout, v, time.Local) + if err != nil { + c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "date 格式错误,应为 YYYY-MM-DD 或 today/tomorrow")) + return + } + planDate = parsed + } + } + if planDate.Before(dateOnlyLocal(asOf)) { + c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "date 不能早于今天")) + return + } + + view, err := h.smokeProfileService.GetView(c.Request.Context(), int(user.ID)) + if err != nil { + if errors.Is(err, smokeservice.ErrSmokeProfileInvalidTime) { + c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "作息时间格式错误,应为 HH:MM")) + return + } + c.JSON(http.StatusInternalServerError, model.Error(http.StatusInternalServerError, "获取基础信息失败,请稍后重试")) + return + } + + defaultSuggestion, err := h.smokeNextService.GetDefaultSuggestion(c.Request.Context(), int(user.ID), asOf, planDate, view) + if err != nil { + c.JSON(http.StatusInternalServerError, model.Error(http.StatusInternalServerError, "计算失败,请稍后重试")) + return + } + + mode := strings.ToLower(strings.TrimSpace(c.DefaultQuery("mode", "auto"))) + + formatPtr := func(t *time.Time) string { + if t == nil { + return "" + } + return t.In(time.Local).Format(time.RFC3339) + } + + resp := nextSmokeTimeUnifiedResponse{ + Source: "default", + NotBeforeAt: formatPtr(defaultSuggestion.NextSmokeAt), + SuggestedAt: formatPtr(defaultSuggestion.NextSmokeAt), + Default: defaultSuggestion, + } + + // mode=default: 永远返回默认建议 + if mode == "default" { + c.JSON(http.StatusOK, model.Success(resp)) + return + } + + // mode=auto: 仅在“已存在 AI 时间节点”时使用 AI(不主动生成) + // mode=ai: 尝试生成/刷新 AI,再优先使用 AI;失败则回落到默认 + var ai smokeservice.AINextSmokeSuggestion + var hasAI bool + + if mode == "ai" { + v, err := h.smokeAINextService.GetOrGenerate(c.Request.Context(), user, asOf, planDate, "v1", defaultSuggestion) + if err != nil { + switch { + case errors.Is(err, smokeservice.ErrAINextLocked): + c.JSON(http.StatusForbidden, model.Error(http.StatusForbidden, "需要观看广告解锁后才可生成")) + return + case errors.Is(err, smokeservice.ErrAINextServiceDisabled): + c.JSON(http.StatusServiceUnavailable, model.Error(http.StatusServiceUnavailable, "AI 服务暂不可用,请联系管理员")) + return + default: + c.JSON(http.StatusInternalServerError, model.Error(http.StatusInternalServerError, "生成 AI 建议失败,请稍后重试")) + return + } + } + ai = v + hasAI = len(ai.TimeNodes) > 0 + } else { + v, ok, err := h.smokeAINextService.GetCached(c.Request.Context(), user, planDate, "v1") + if err != nil { + c.JSON(http.StatusInternalServerError, model.Error(http.StatusInternalServerError, "获取 AI 建议失败,请稍后重试")) + return + } + ai = v + hasAI = ok && len(ai.TimeNodes) > 0 + } + + if hasAI { + resp.Source = "ai" + resp.NotBeforeAt = ai.NotBeforeAt + resp.SuggestedAt = ai.SuggestedAt + resp.TimeNodes = ai.TimeNodes + resp.Advice = ai.Advice + resp.AI = &ai + } + + c.JSON(http.StatusOK, model.Success(resp)) +} + +func dateOnlyLocal(t time.Time) time.Time { + local := t.In(time.Local) + return time.Date(local.Year(), local.Month(), local.Day(), 0, 0, 0, 0, time.Local) +} diff --git a/internal/smoke/model/smoke_ai.go b/internal/smoke/model/smoke_ai.go index ab7c5bb..55b1e33 100644 --- a/internal/smoke/model/smoke_ai.go +++ b/internal/smoke/model/smoke_ai.go @@ -9,8 +9,11 @@ type SmokeAIAdvice struct { ID uint `gorm:"primaryKey;autoIncrement;comment:记录ID" json:"id"` UID int `gorm:"column:uid;index:idx_smoke_ai_advice_uid_date,priority:1;uniqueIndex:uniq_smoke_ai_advice,priority:1" json:"-"` - AdviceDate time.Time `gorm:"column:advice_date;type:date;index:idx_smoke_ai_advice_uid_date,priority:2;uniqueIndex:uniq_smoke_ai_advice,priority:2;comment:建议日期" json:"advice_date"` - PromptVersion string `gorm:"column:prompt_version;size:30;default:v1;uniqueIndex:uniq_smoke_ai_advice,priority:3;comment:提示词版本" json:"prompt_version"` + // Type 用于区分 AI 使用场景(例如:daily_advice / next_smoke_time)。 + Type string `gorm:"column:type;size:30;default:daily_advice;index:idx_smoke_ai_advice_uid_date,priority:2;uniqueIndex:uniq_smoke_ai_advice,priority:2;comment:用途类型" json:"type"` + + AdviceDate time.Time `gorm:"column:advice_date;type:date;index:idx_smoke_ai_advice_uid_date,priority:3;uniqueIndex:uniq_smoke_ai_advice,priority:3;comment:建议日期" json:"advice_date"` + PromptVersion string `gorm:"column:prompt_version;size:30;default:v1;uniqueIndex:uniq_smoke_ai_advice,priority:4;comment:提示词版本" json:"prompt_version"` Provider string `gorm:"column:provider;size:30;comment:AI提供方" json:"provider,omitempty"` Model string `gorm:"column:model;size:60;comment:模型名" json:"model,omitempty"` diff --git a/internal/smoke/model/smoke_ai_next_smoke.go b/internal/smoke/model/smoke_ai_next_smoke.go new file mode 100644 index 0000000..187be22 --- /dev/null +++ b/internal/smoke/model/smoke_ai_next_smoke.go @@ -0,0 +1,32 @@ +package model + +import "time" + +// SmokeAINextSmoke 对应表 fa_smoke_ai_next_smoke(AI 生成的“下次抽烟时间节点”)。 +// +// 说明: +// - 该表只保存“时间节点”本身(每个时间点一条记录),AI 元信息复用 fa_smoke_ai_advice(通过 AIAdviceID 关联)。 +// - 沿用旧系统字段(createtime/updatetime/deletetime 为秒级时间戳),不使用 gorm.Model。 +type SmokeAINextSmoke struct { + ID uint `gorm:"primaryKey;autoIncrement;comment:记录ID" json:"id"` + UID int `gorm:"column:uid;index:idx_smoke_ai_next_uid_date,priority:1;comment:用户ID" json:"-"` + + PlanDate time.Time `gorm:"column:plan_date;type:date;index:idx_smoke_ai_next_uid_date,priority:2;comment:计划日期(当天)" json:"plan_date"` + AIAdviceID uint `gorm:"column:ai_advice_id;index:idx_smoke_ai_next_advice,priority:1;comment:关联AI建议ID(fa_smoke_ai_advice.id)" json:"ai_advice_id"` + + // NodeType: not_before / suggested / node + NodeType string `gorm:"column:node_type;size:20;index:idx_smoke_ai_next_advice,priority:2;uniqueIndex:uniq_smoke_ai_next_node,priority:2;comment:节点类型" json:"node_type"` + NodeAt time.Time `gorm:"column:node_at;type:datetime;uniqueIndex:uniq_smoke_ai_next_node,priority:3;comment:时间点" json:"node_at"` + + CreateTime *int64 `gorm:"column:createtime;comment:创建时间(秒)" json:"createtime,omitempty"` + UpdateTime *int64 `gorm:"column:updatetime;comment:更新时间(秒)" json:"updatetime,omitempty"` + DeleteTime *int64 `gorm:"column:deletetime;comment:删除时间(秒)" json:"deletetime,omitempty"` +} + +func (SmokeAINextSmoke) TableName() string { + return "fa_smoke_ai_next_smoke" +} + +func (SmokeAINextSmoke) TableComment() string { + return "AI下次抽烟时间节点" +} diff --git a/internal/smoke/service/smoke_ai_advice_service.go b/internal/smoke/service/smoke_ai_advice_service.go index eec65c4..a772e76 100644 --- a/internal/smoke/service/smoke_ai_advice_service.go +++ b/internal/smoke/service/smoke_ai_advice_service.go @@ -30,6 +30,11 @@ const ( defaultTemperature = 0.7 ) +const ( + SmokeAIAdviceTypeDaily = "daily_advice" + SmokeAIAdviceTypeNextSmoke = "next_smoke_time" +) + type SmokeAIAdviceService struct { db *gorm.DB cfg config.AIConfig @@ -82,7 +87,7 @@ func (s *SmokeAIAdviceService) GetOrGenerate(ctx context.Context, user *usermode promptVersion = DefaultAdvicePromptVersion } - cached, err := s.getCached(ctx, int(user.ID), adviceDate, promptVersion) + cached, err := s.getCached(ctx, int(user.ID), SmokeAIAdviceTypeDaily, adviceDate, promptVersion) if err != nil { return nil, err } @@ -114,6 +119,7 @@ func (s *SmokeAIAdviceService) GetOrGenerate(ctx context.Context, user *usermode record := smokemodel.SmokeAIAdvice{ UID: int(user.ID), + Type: SmokeAIAdviceTypeDaily, AdviceDate: dateOnly(adviceDate), PromptVersion: promptVersion, Provider: "openai-compatible", @@ -166,11 +172,11 @@ func (s *SmokeAIAdviceService) Unlock(ctx context.Context, user *usermodel.User, return nil } -func (s *SmokeAIAdviceService) getCached(ctx context.Context, uid int, adviceDate time.Time, promptVersion string) (*smokemodel.SmokeAIAdvice, error) { +func (s *SmokeAIAdviceService) getCached(ctx context.Context, uid int, adviceType string, adviceDate time.Time, promptVersion string) (*smokemodel.SmokeAIAdvice, error) { var record smokemodel.SmokeAIAdvice err := s.db.WithContext(ctx). - Where("uid = ? AND advice_date = ? AND prompt_version = ? AND (deletetime IS NULL OR deletetime = 0)", - uid, dateOnly(adviceDate).Format("2006-01-02"), promptVersion). + Where("uid = ? AND type = ? AND advice_date = ? AND prompt_version = ? AND (deletetime IS NULL OR deletetime = 0)", + uid, adviceType, dateOnly(adviceDate).Format("2006-01-02"), promptVersion). First(&record).Error if err == nil { return &record, nil @@ -231,7 +237,7 @@ func (s *SmokeAIAdviceService) buildSnapshot(ctx context.Context, uid int, advic return adviceSnapshot{}, nil, ErrNoSmokeLogs } - profile := s.loadAdviceProfile(ctx, uid) + profile := loadAdviceUserProfile(ctx, s.db, uid) type timedLog struct { log smokemodel.SmokeLog @@ -299,9 +305,9 @@ func (s *SmokeAIAdviceService) buildSnapshot(ctx context.Context, uid int, advic return snap, b, nil } -func (s *SmokeAIAdviceService) loadAdviceProfile(ctx context.Context, uid int) *adviceUserProfile { +func loadAdviceUserProfile(ctx context.Context, db *gorm.DB, uid int) *adviceUserProfile { var profile smokemodel.SmokeUserProfile - err := s.db.WithContext(ctx). + err := db.WithContext(ctx). Where("uid = ? AND deleted_at IS NULL", uid). First(&profile).Error if err != nil { diff --git a/internal/smoke/service/smoke_ai_next_smoke_service.go b/internal/smoke/service/smoke_ai_next_smoke_service.go new file mode 100644 index 0000000..706d4b0 --- /dev/null +++ b/internal/smoke/service/smoke_ai_next_smoke_service.go @@ -0,0 +1,666 @@ +package service + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "strings" + "time" + + "gorm.io/gorm" + + "wx_service/config" + usermodel "wx_service/internal/model" + smokemodel "wx_service/internal/smoke/model" +) + +var ( + ErrAINextServiceDisabled = errors.New("ai service is not configured") + ErrAINextLocked = errors.New("ai next smoke is locked, ad unlock required") +) + +type SmokeAINextSmokeService struct { + db *gorm.DB + cfg config.AIConfig + client *http.Client +} + +func NewSmokeAINextSmokeService(db *gorm.DB, cfg config.AIConfig) *SmokeAINextSmokeService { + timeout := cfg.RequestTimeout + if timeout <= 0 { + timeout = 15 * time.Second + } + return &SmokeAINextSmokeService{ + db: db, + cfg: cfg, + client: &http.Client{ + Timeout: timeout, + }, + } +} + +type aiNextSmokeInput struct { + 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"` +} + +type aiNextSmokeOutput struct { + NotBeforeAt string `json:"not_before_at"` + SuggestedAt string `json:"suggested_at"` + TimeNodes []string `json:"time_nodes"` + Advice string `json:"advice"` +} + +type recentDaySnapshot struct { + Date string `json:"date"` + TotalNum int `json:"total_num"` + ResistedCount int `json:"resisted_count"` + Nodes []recentDayNode `json:"nodes"` +} + +type recentDayNode struct { + Time string `json:"time"` + Num int `json:"num"` + Level int64 `json:"level"` + IsResisted bool `json:"is_resisted"` + Remark string `json:"remark,omitempty"` +} + +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"` +} + +func (s *SmokeAINextSmokeService) GetOrGenerate(ctx context.Context, user *usermodel.User, asOf time.Time, planDate time.Time, promptVersion string, defaultSuggestion NextSmokeSuggestion) (AINextSmokeSuggestion, error) { + if promptVersion == "" { + promptVersion = "v1" + } + + planDate = dateOnly(planDate) + cachedAdvice, err := s.getCachedAdvice(ctx, int(user.ID), planDate, promptVersion) + if err != nil { + return AINextSmokeSuggestion{}, err + } + if cachedAdvice != nil { + return s.buildFromCache(ctx, cachedAdvice) + } + + if s.cfg.APIKey == "" || s.cfg.Model == "" || s.cfg.BaseURL == "" { + return AINextSmokeSuggestion{}, ErrAINextServiceDisabled + } + + allowed, err := s.isAllowed(ctx, user, planDate) + if err != nil { + return AINextSmokeSuggestion{}, err + } + if !allowed { + return AINextSmokeSuggestion{}, ErrAINextLocked + } + + // 尝试复用 profile(用于 sleep window / 动机动力);如果读取失败则忽略。 + profile := loadAdviceUserProfile(ctx, s.db, int(user.ID)) + + recent, err := s.loadRecent3Days(ctx, int(user.ID), planDate) + if err != nil { + return AINextSmokeSuggestion{}, err + } + + 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, + } + inputJSON, _ := json.Marshal(input) + + output, outputJSON, modelName, tokensIn, tokensOut, err := s.callAI(ctx, input) + if err != nil { + return AINextSmokeSuggestion{}, err + } + + notBeforeAt, err := parseFlexibleTime(output.NotBeforeAt, planDate) + if err != nil { + return AINextSmokeSuggestion{}, fmt.Errorf("parse not_before_at: %w", err) + } + suggestedAt, err := parseFlexibleTime(output.SuggestedAt, planDate) + if err != nil { + return AINextSmokeSuggestion{}, fmt.Errorf("parse suggested_at: %w", err) + } + + // 强制:AI 的“不早于”不可以早于 minNotBefore(避免比默认更激进,且支持明天计划)。 + if notBeforeAt.Before(minNotBefore) { + notBeforeAt = minNotBefore + } + if suggestedAt.Before(notBeforeAt) { + suggestedAt = notBeforeAt + } + + // 避免睡眠时间:若 profile 有作息,则把 not_before/suggested 落在睡眠区间的情况顺延到起床。 + if profile != nil && strings.TrimSpace(profile.WakeUpTime) != "" && strings.TrimSpace(profile.SleepTime) != "" { + if adjusted, ok, _ := adjustToWakeIfInSleep(notBeforeAt, profile.WakeUpTime, profile.SleepTime); ok { + notBeforeAt = adjusted + } + if adjusted, ok, _ := adjustToWakeIfInSleep(suggestedAt, profile.WakeUpTime, profile.SleepTime); ok { + suggestedAt = adjusted + } + if suggestedAt.Before(notBeforeAt) { + suggestedAt = notBeforeAt + } + } + + nowUnix := time.Now().Unix() + createTime := nowUnix + updateTime := nowUnix + + // 1) 写入 AI 元信息与建议(复用 fa_smoke_ai_advice + type 区分) + adviceRecord := smokemodel.SmokeAIAdvice{ + UID: int(user.ID), + Type: SmokeAIAdviceTypeNextSmoke, + AdviceDate: planDate, + PromptVersion: promptVersion, + Provider: "openai-compatible", + Model: modelName, + InputSnapshot: inputJSON, + Advice: strings.TrimSpace(output.Advice), + TokensIn: tokensIn, + TokensOut: tokensOut, + CreateTime: &createTime, + UpdateTime: &updateTime, + } + + if err := s.db.WithContext(ctx).Create(&adviceRecord).Error; err != nil { + return AINextSmokeSuggestion{}, fmt.Errorf("save ai next smoke advice: %w", err) + } + + // 2) 写入时间节点(每个时间点一条) + nodes, err := s.normalizeNodes(output.TimeNodes, asOf, planDate, notBeforeAt, profile) + if err != nil { + return AINextSmokeSuggestion{}, err + } + + if err := s.saveNodes(ctx, int(user.ID), planDate, adviceRecord.ID, notBeforeAt, suggestedAt, nodes); err != nil { + return AINextSmokeSuggestion{}, err + } + + _ = outputJSON + return AINextSmokeSuggestion{ + PlanDate: planDate.Format("2006-01-02"), + NotBeforeAt: notBeforeAt.In(time.Local).Format(time.RFC3339), + SuggestedAt: suggestedAt.In(time.Local).Format(time.RFC3339), + TimeNodes: nodes, + Advice: adviceRecord.Advice, + PromptVersion: adviceRecord.PromptVersion, + Model: adviceRecord.Model, + Provider: adviceRecord.Provider, + }, nil +} + +func (s *SmokeAINextSmokeService) GetCached(ctx context.Context, user *usermodel.User, planDate time.Time, promptVersion string) (AINextSmokeSuggestion, bool, error) { + if promptVersion == "" { + promptVersion = "v1" + } + + planDate = dateOnly(planDate) + cachedAdvice, err := s.getCachedAdvice(ctx, int(user.ID), planDate, promptVersion) + if err != nil { + return AINextSmokeSuggestion{}, false, err + } + if cachedAdvice == nil { + return AINextSmokeSuggestion{}, false, nil + } + + suggestion, err := s.buildFromCache(ctx, cachedAdvice) + if err != nil { + return AINextSmokeSuggestion{}, false, err + } + return suggestion, true, nil +} + +func (s *SmokeAINextSmokeService) getCachedAdvice(ctx context.Context, uid int, planDate time.Time, promptVersion string) (*smokemodel.SmokeAIAdvice, error) { + var record smokemodel.SmokeAIAdvice + err := s.db.WithContext(ctx). + Where("uid = ? AND type = ? AND advice_date = ? AND prompt_version = ? AND (deletetime IS NULL OR deletetime = 0)", + uid, SmokeAIAdviceTypeNextSmoke, dateOnly(planDate).Format("2006-01-02"), promptVersion). + First(&record).Error + if err == nil { + return &record, nil + } + if errors.Is(err, gorm.ErrRecordNotFound) { + return nil, nil + } + return nil, fmt.Errorf("load cached ai next smoke advice: %w", err) +} + +func (s *SmokeAINextSmokeService) buildFromCache(ctx context.Context, advice *smokemodel.SmokeAIAdvice) (AINextSmokeSuggestion, error) { + nodes, notBeforeAt, suggestedAt, err := s.loadNodes(ctx, advice.ID) + if err != nil { + return AINextSmokeSuggestion{}, err + } + return AINextSmokeSuggestion{ + PlanDate: dateOnly(advice.AdviceDate).Format("2006-01-02"), + NotBeforeAt: notBeforeAt.In(time.Local).Format(time.RFC3339), + SuggestedAt: suggestedAt.In(time.Local).Format(time.RFC3339), + TimeNodes: nodes, + Advice: advice.Advice, + PromptVersion: advice.PromptVersion, + Model: advice.Model, + Provider: advice.Provider, + }, nil +} + +func (s *SmokeAINextSmokeService) loadNodes(ctx context.Context, aiAdviceID uint) ([]string, time.Time, time.Time, error) { + var rows []smokemodel.SmokeAINextSmoke + if err := s.db.WithContext(ctx). + Where("ai_advice_id = ? AND (deletetime IS NULL OR deletetime = 0)", aiAdviceID). + Order("node_at ASC"). + Find(&rows).Error; err != nil { + return nil, time.Time{}, time.Time{}, fmt.Errorf("load ai next nodes: %w", err) + } + + var notBeforeAt, suggestedAt time.Time + var nodes []string + for _, r := range rows { + switch r.NodeType { + case "not_before": + notBeforeAt = r.NodeAt.In(time.Local) + case "suggested": + suggestedAt = r.NodeAt.In(time.Local) + case "node": + nodes = append(nodes, r.NodeAt.In(time.Local).Format("15:04")) + } + } + if notBeforeAt.IsZero() { + notBeforeAt = time.Now().In(time.Local) + } + if suggestedAt.IsZero() { + suggestedAt = notBeforeAt + } + return nodes, notBeforeAt, suggestedAt, nil +} + +func (s *SmokeAINextSmokeService) normalizeNodes(raw []string, asOf time.Time, planDate time.Time, notBeforeAt time.Time, profile *adviceUserProfile) ([]string, error) { + now := asOf.In(time.Local) + seen := map[string]bool{} + out := make([]string, 0, 6) + + for _, v := range raw { + if len(out) >= 6 { + break + } + t, err := parseFlexibleTime(v, planDate) + if err != nil { + continue + } + t = t.In(time.Local) + if dateOnly(t) != dateOnly(planDate) { + continue + } + // 计划日期=今天:不能早于当前时间;计划日期=明天:这里通常不会早于 now。 + if t.Before(now) && dateOnly(planDate).Equal(dateOnly(now)) { + continue + } + if t.Before(notBeforeAt) { + continue + } + if profile != nil && strings.TrimSpace(profile.WakeUpTime) != "" && strings.TrimSpace(profile.SleepTime) != "" { + if adjusted, ok, _ := adjustToWakeIfInSleep(t, profile.WakeUpTime, profile.SleepTime); ok { + t = adjusted + } + if t.Before(notBeforeAt) { + continue + } + if dateOnly(t) != dateOnly(planDate) { + continue + } + } + label := t.Format("15:04") + if seen[label] { + continue + } + seen[label] = true + out = append(out, label) + } + + return out, nil +} + +func (s *SmokeAINextSmokeService) computeMinNotBefore(asOf time.Time, planDate time.Time, defaultSuggestion NextSmokeSuggestion, profile *adviceUserProfile) time.Time { + asOf = asOf.In(time.Local) + planDate = dateOnly(planDate) + today := dateOnly(asOf) + + if planDate.After(today) { + min := time.Date(planDate.Year(), planDate.Month(), planDate.Day(), 7, 0, 0, 0, time.Local) + if profile != nil && strings.TrimSpace(profile.WakeUpTime) != "" { + if m, err := parseHHMMToMinutes(profile.WakeUpTime); err == nil { + min = time.Date(planDate.Year(), planDate.Month(), planDate.Day(), m/60, m%60, 0, 0, time.Local) + } + } + return min + } + + if defaultSuggestion.NextSmokeAt != nil && !defaultSuggestion.NextSmokeAt.IsZero() { + return defaultSuggestion.NextSmokeAt.In(time.Local) + } + return asOf.Add(5 * time.Minute) +} + +func (s *SmokeAINextSmokeService) loadRecent3Days(ctx context.Context, uid int, planDate time.Time) ([]recentDaySnapshot, error) { + planDate = dateOnly(planDate) + today := dateOnly(time.Now().In(time.Local)) + + end := planDate + if end.After(today) { + end = today + } + start := end.AddDate(0, 0, -2) + + var logs []smokemodel.SmokeLog + if err := s.db.WithContext(ctx). + 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")). + Order("smoke_time ASC"). + Order("COALESCE(smoke_at, FROM_UNIXTIME(createtime)) ASC"). + Order("id ASC"). + Find(&logs).Error; err != nil { + return nil, fmt.Errorf("load recent logs: %w", err) + } + + byDay := map[string]*recentDaySnapshot{} + ensure := func(day time.Time) *recentDaySnapshot { + key := dateOnly(day).Format("2006-01-02") + if existing, ok := byDay[key]; ok { + return existing + } + snap := &recentDaySnapshot{Date: key, Nodes: []recentDayNode{}} + byDay[key] = snap + return snap + } + + for _, l := range logs { + day := start + if l.SmokeTime != nil { + day = dateOnly(*l.SmokeTime) + } + snap := ensure(day) + + isResisted := l.Level == 0 && l.Num == 0 + if isResisted { + snap.ResistedCount++ + } else if l.Num > 0 { + snap.TotalNum += l.Num + } + + if len(snap.Nodes) >= 50 { + continue + } + + eventAt, ok := lastEventTime(l) + timeLabel := "" + if ok { + timeLabel = eventAt.In(time.Local).Format("15:04") + } + + remark := strings.TrimSpace(l.Remark) + if len(remark) > 80 { + remark = remark[:80] + } + + snap.Nodes = append(snap.Nodes, recentDayNode{ + Time: timeLabel, + Num: l.Num, + Level: l.Level, + IsResisted: isResisted, + Remark: remark, + }) + } + + out := make([]recentDaySnapshot, 0, 3) + for d := start; !d.After(end); d = d.AddDate(0, 0, 1) { + key := d.Format("2006-01-02") + if snap, ok := byDay[key]; ok { + out = append(out, *snap) + } else { + out = append(out, recentDaySnapshot{Date: key, Nodes: []recentDayNode{}}) + } + } + return out, nil +} + +func (s *SmokeAINextSmokeService) isAllowed(ctx context.Context, user *usermodel.User, planDate time.Time) (bool, error) { + isVIP, err := s.isVIP(ctx, user) + if err != nil { + return false, err + } + if isVIP { + return true, nil + } + return s.isUnlocked(ctx, int(user.ID), planDate) +} + +func (s *SmokeAINextSmokeService) isVIP(ctx context.Context, user *usermodel.User) (bool, error) { + now := time.Now() + var count int64 + if err := s.db.WithContext(ctx). + Model(&usermodel.UserMembership{}). + Where("mini_program_id = ? AND user_id = ? AND status = ? AND ends_at > ?", + user.MiniProgramID, user.ID, "active", now). + Count(&count).Error; err != nil { + return false, fmt.Errorf("check vip: %w", err) + } + return count > 0, nil +} + +func (s *SmokeAINextSmokeService) isUnlocked(ctx context.Context, uid int, planDate time.Time) (bool, error) { + startOfDay := dateOnly(planDate) + var unlock smokemodel.SmokeAIAdviceUnlock + err := s.db.WithContext(ctx). + Where("uid = ? AND unlock_date = ? AND (deletetime IS NULL OR deletetime = 0)", uid, startOfDay.Format("2006-01-02")). + First(&unlock).Error + if err == nil { + return true, nil + } + if errors.Is(err, gorm.ErrRecordNotFound) { + return false, nil + } + return false, fmt.Errorf("check unlock: %w", err) +} + +func (s *SmokeAINextSmokeService) saveNodes(ctx context.Context, uid int, planDate time.Time, aiAdviceID uint, notBeforeAt time.Time, suggestedAt time.Time, nodes []string) error { + nowUnix := time.Now().Unix() + createTime := nowUnix + updateTime := nowUnix + + rows := []smokemodel.SmokeAINextSmoke{ + { + UID: uid, + PlanDate: planDate, + AIAdviceID: aiAdviceID, + NodeType: "not_before", + NodeAt: notBeforeAt, + CreateTime: &createTime, + UpdateTime: &updateTime, + }, + { + UID: uid, + PlanDate: planDate, + AIAdviceID: aiAdviceID, + NodeType: "suggested", + NodeAt: suggestedAt, + CreateTime: &createTime, + UpdateTime: &updateTime, + }, + } + + ref := planDate.In(time.Local) + for _, label := range nodes { + t, err := parseFlexibleTime(label, ref) + if err != nil { + continue + } + rows = append(rows, smokemodel.SmokeAINextSmoke{ + UID: uid, + PlanDate: planDate, + AIAdviceID: aiAdviceID, + NodeType: "node", + NodeAt: t.In(time.Local), + CreateTime: &createTime, + UpdateTime: &updateTime, + }) + } + + if err := s.db.WithContext(ctx).Create(&rows).Error; err != nil { + return fmt.Errorf("save ai next smoke nodes: %w", err) + } + return nil +} + +func (s *SmokeAINextSmokeService) callAI(ctx context.Context, input aiNextSmokeInput) (aiNextSmokeOutput, []byte, string, *int, *int, error) { + systemPrompt := strings.TrimSpace(` +你是一名专业的戒烟教练与行为改变顾问。你将收到一段 JSON,包含: +- 现在时间(as_of) +- 计划日期(plan_date):你输出的时间必须属于该日期 +- 最小不早于时间(min_not_before_at):你输出的 not_before_at 必须 >= 该值 +- 最近3天数据(recent_3_days):用于判断近期模式(含忍住记录) +- 后端默认策略(default_suggestion):仅供参考 +- 可选的用户 profile:包含作息时间、动机/动力 + +你必须只输出一段严格的 JSON(不要 Markdown、不要解释文字),格式: +{ + "not_before_at": "RFC3339 时间字符串(含时区)", + "suggested_at": "RFC3339 时间字符串(含时区)", + "time_nodes": ["HH:MM", "HH:MM", ...], + "advice": "一句话建议(<=200字)" +} + +约束: +1) not_before_at 必须 >= min_not_before_at; +2) suggested_at 必须 >= not_before_at; +3) 如果 profile 提供了 wake_up_time/sleep_time,建议时间与 time_nodes 不要落在睡眠区间;如不可避免,顺延到起床后; +4) time_nodes 只需要给出 plan_date 的 3~6 个“关键节点”(字符串 HH:MM),并且都不早于 not_before_at。 +`) + + userPrompt := fmt.Sprintf("输入(JSON):\n%s", mustJSON(input)) + + reqBody := chatCompletionRequest{ + Model: s.cfg.Model, + Messages: []chatMessage{ + {Role: "system", Content: systemPrompt}, + {Role: "user", Content: userPrompt}, + }, + Temperature: defaultTemperature, + } + + payload, err := json.Marshal(reqBody) + if err != nil { + return aiNextSmokeOutput{}, nil, "", nil, nil, fmt.Errorf("marshal ai request: %w", err) + } + + endpoint := strings.TrimRight(s.cfg.BaseURL, "/") + "/chat/completions" + httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(payload)) + if err != nil { + return aiNextSmokeOutput{}, nil, "", nil, nil, fmt.Errorf("build ai request: %w", err) + } + httpReq.Header.Set("Content-Type", "application/json") + httpReq.Header.Set("Authorization", "Bearer "+s.cfg.APIKey) + + resp, err := s.client.Do(httpReq) + if err != nil { + return aiNextSmokeOutput{}, nil, "", nil, nil, fmt.Errorf("call ai: %w", err) + } + defer resp.Body.Close() + + body, err := io.ReadAll(resp.Body) + if err != nil { + return aiNextSmokeOutput{}, nil, "", nil, nil, fmt.Errorf("read ai response: %w", err) + } + if resp.StatusCode != http.StatusOK { + return aiNextSmokeOutput{}, nil, "", nil, nil, fmt.Errorf("ai http %d: %s", resp.StatusCode, truncateString(string(body), 512)) + } + + var parsed chatCompletionResponse + if err := json.Unmarshal(body, &parsed); err != nil { + return aiNextSmokeOutput{}, nil, "", nil, nil, fmt.Errorf("parse ai response: %w", err) + } + if len(parsed.Choices) == 0 { + return aiNextSmokeOutput{}, nil, "", nil, nil, errors.New("ai response has no choices") + } + + content := strings.TrimSpace(parsed.Choices[0].Message.Content) + if content == "" { + return aiNextSmokeOutput{}, nil, "", nil, nil, errors.New("ai response content is empty") + } + + jsonPart := extractJSONObject(content) + if jsonPart == "" { + return aiNextSmokeOutput{}, nil, "", nil, nil, fmt.Errorf("ai response is not json: %s", truncateString(content, 256)) + } + + var out aiNextSmokeOutput + if err := json.Unmarshal([]byte(jsonPart), &out); err != nil { + return aiNextSmokeOutput{}, nil, "", nil, nil, fmt.Errorf("unmarshal ai json: %w", err) + } + + modelName := parsed.Model + if modelName == "" { + modelName = s.cfg.Model + } + + var tokensIn, tokensOut *int + if parsed.Usage != nil { + tokensIn = &parsed.Usage.PromptTokens + tokensOut = &parsed.Usage.CompletionTokens + } + + return out, []byte(jsonPart), modelName, tokensIn, tokensOut, nil +} + +func extractJSONObject(s string) string { + start := strings.Index(s, "{") + end := strings.LastIndex(s, "}") + if start < 0 || end < 0 || end <= start { + return "" + } + return s[start : end+1] +} + +func parseFlexibleTime(value string, ref time.Time) (time.Time, error) { + value = strings.TrimSpace(value) + if value == "" { + return time.Time{}, errors.New("empty time") + } + if t, err := time.Parse(time.RFC3339, value); err == nil { + return t.In(time.Local), nil + } + if t, err := time.ParseInLocation("2006-01-02 15:04:05", value, time.Local); err == nil { + return t.In(time.Local), nil + } + // 仅提供 HH:MM:使用 ref 的日期 + if len(value) == 5 && value[2] == ':' { + min, err := parseHHMMToMinutes(value) + if err != nil { + return time.Time{}, err + } + r := ref.In(time.Local) + return time.Date(r.Year(), r.Month(), r.Day(), min/60, min%60, 0, 0, time.Local), nil + } + return time.Time{}, fmt.Errorf("unsupported time format: %s", value) +} diff --git a/internal/smoke/service/smoke_log_service.go b/internal/smoke/service/smoke_log_service.go index f7e1223..5000065 100644 --- a/internal/smoke/service/smoke_log_service.go +++ b/internal/smoke/service/smoke_log_service.go @@ -37,11 +37,11 @@ func (s *SmokeLogService) Create(ctx context.Context, uid int, req CreateSmokeLo updateTime := now level := req.Level - if level <= 0 { + if level < 0 { level = 1 } num := req.Num - if num <= 0 { + if num < 0 { num = 1 } @@ -212,7 +212,8 @@ 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). - Order("COALESCE(smoke_at, smoke_time, FROM_UNIXTIME(createtime)) DESC"). + Where("NOT (level = 0 AND num = 0)"). + Order("COALESCE(smoke_at, FROM_UNIXTIME(createtime), smoke_time) DESC"). Order("id DESC"). Limit(1). Take(&last).Error; err != nil { @@ -260,7 +261,7 @@ func (s *SmokeLogService) ListLatest(ctx context.Context, uid int, limit int) ([ Model(&smokemodel.SmokeLog{}). Select("id, uid, smoke_time, smoke_at, remark, level, num, createtime, updatetime, deletetime"). Where("uid = ? AND (deletetime IS NULL OR deletetime = 0)", uid). - Order("COALESCE(smoke_at, smoke_time, FROM_UNIXTIME(createtime)) DESC"). + Order("COALESCE(smoke_at, FROM_UNIXTIME(createtime), smoke_time) DESC"). Order("id DESC"). Limit(limit). Find(&items).Error; err != nil { @@ -274,13 +275,13 @@ func lastEventTime(log smokemodel.SmokeLog) (time.Time, bool) { if log.SmokeAt != nil { return log.SmokeAt.In(time.Local), true } + if log.CreateTime != nil { + return time.Unix(*log.CreateTime, 0).In(time.Local), true + } if log.SmokeTime != nil { day := dateOnly(*log.SmokeTime) return day, true } - if log.CreateTime != nil { - return time.Unix(*log.CreateTime, 0).In(time.Local), true - } return time.Time{}, false } @@ -321,14 +322,14 @@ func (s *SmokeLogService) Update(ctx context.Context, uid int, id int, req Updat updates["remark"] = *req.Remark } if req.Level != nil { - if *req.Level <= 0 { + if *req.Level < 0 { updates["level"] = int64(1) } else { updates["level"] = *req.Level } } if req.Num != nil { - if *req.Num <= 0 { + if *req.Num < 0 { updates["num"] = 1 } else { updates["num"] = *req.Num diff --git a/internal/smoke/service/smoke_next_service.go b/internal/smoke/service/smoke_next_service.go new file mode 100644 index 0000000..cd78377 --- /dev/null +++ b/internal/smoke/service/smoke_next_service.go @@ -0,0 +1,202 @@ +package service + +import ( + "context" + "errors" + "fmt" + "time" + + "gorm.io/gorm" + + smokemodel "wx_service/internal/smoke/model" +) + +type SmokeNextService struct { + db *gorm.DB +} + +func NewSmokeNextService(db *gorm.DB) *SmokeNextService { + return &SmokeNextService{db: db} +} + +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"` +} + +// 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) + + base := profileView.BaselineIntervalMinute + if base <= 0 { + base = 60 + } + + lastSmokeAt, ok, err := s.loadLastActualSmokeAt(ctx, uid) + if err != nil { + return NextSmokeSuggestion{}, err + } + if !ok { + nowCopy := now + lastSmokeAt = &nowCopy + } + + resisted, err := s.countResistedLastDays(ctx, uid, 7) + if err != nil { + return NextSmokeSuggestion{}, err + } + + stage := resisted / 5 + if stage > 12 { + stage = 12 + } + + interval := base + stage*5 + if interval < 5 { + interval = 5 + } + if interval > 240 { + interval = 240 + } + + next := lastSmokeAt.Add(time.Duration(interval) * time.Minute) + sleepAdjusted := false + + var wakeUp, sleep string + if profileView.Profile != nil { + wakeUp = profileView.Profile.WakeUpTime + sleep = profileView.Profile.SleepTime + } + + // 如果是“生成某一天的计划”(例如明天),默认不早于该日的起床时间(若未配置则使用 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 != "" { + if m, err := parseHHMMToMinutes(wakeUp); err == nil { + minNotBefore = time.Date(planDay.Year(), planDay.Month(), planDay.Day(), m/60, m%60, 0, 0, time.Local) + } + } + if next.Before(minNotBefore) { + next = minNotBefore + } + } + + if wakeUp != "" && sleep != "" { + adjusted, ok, err := adjustToWakeIfInSleep(next, wakeUp, sleep) + if err != nil && !errors.Is(err, ErrSmokeProfileInvalidTime) { + return NextSmokeSuggestion{}, err + } + if ok { + next = adjusted + sleepAdjusted = true + } + } + + out := NextSmokeSuggestion{ + BaseIntervalMinutes: base, + IntervalMinutes: interval, + Stage: stage, + Resisted7d: resisted, + SleepAdjusted: sleepAdjusted, + Algorithm: "staircase_delay_v1", + AsOf: now.Format(time.RFC3339), + } + out.LastSmokeAt = lastSmokeAt + if !next.IsZero() { + t := next + out.NextSmokeAt = &t + } + return out, nil +} + +func (s *SmokeNextService) loadLastActualSmokeAt(ctx context.Context, uid int) (*time.Time, bool, error) { + 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)"). + Order("COALESCE(smoke_at, FROM_UNIXTIME(createtime), smoke_time) DESC"). + Order("id DESC"). + Limit(1). + Take(&last).Error + if err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + return nil, false, nil + } + return nil, false, fmt.Errorf("load last smoke log: %w", err) + } + t, ok := lastEventTime(last) + if !ok { + return nil, false, nil + } + return &t, true, nil +} + +func (s *SmokeNextService) countResistedLastDays(ctx context.Context, uid int, days int) (int, error) { + if days <= 0 { + days = 7 + } + end := dateOnly(time.Now().In(time.Local)) + start := end.AddDate(0, 0, -(days - 1)) + + var count int64 + 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("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) + } + return int(count), nil +} + +func adjustToWakeIfInSleep(t time.Time, wakeUpHHMM, sleepHHMM string) (time.Time, bool, error) { + wakeMin, err := parseHHMMToMinutes(wakeUpHHMM) + if err != nil { + return time.Time{}, false, ErrSmokeProfileInvalidTime + } + sleepMin, err := parseHHMMToMinutes(sleepHHMM) + if err != nil { + return time.Time{}, false, ErrSmokeProfileInvalidTime + } + if wakeMin == sleepMin { + return t, false, nil + } + + minutes := t.Hour()*60 + t.Minute() + inSleep := isInSleepWindow(minutes, wakeMin, sleepMin) + if !inSleep { + return t, false, nil + } + + wakeToday := time.Date(t.Year(), t.Month(), t.Day(), wakeMin/60, wakeMin%60, 0, 0, t.Location()) + if !wakeToday.After(t) { + wakeToday = wakeToday.Add(24 * time.Hour) + } + return wakeToday, true, nil +} + +func isInSleepWindow(minuteOfDay int, wakeMin int, sleepMin int) bool { + if minuteOfDay < 0 { + minuteOfDay = 0 + } + if minuteOfDay >= 24*60 { + minuteOfDay = 24*60 - 1 + } + // wake < sleep: awake=[wake,sleep), sleep=else + if wakeMin < sleepMin { + return minuteOfDay < wakeMin || minuteOfDay >= sleepMin + } + // wake > sleep: awake 跨午夜,sleep=[sleep,wake) + return minuteOfDay >= sleepMin && minuteOfDay < wakeMin +} diff --git a/internal/smoke/service/smoke_next_service_test.go b/internal/smoke/service/smoke_next_service_test.go new file mode 100644 index 0000000..7f0938e --- /dev/null +++ b/internal/smoke/service/smoke_next_service_test.go @@ -0,0 +1,83 @@ +package service + +import ( + "testing" + "time" +) + +func TestIsInSleepWindow(t *testing.T) { + t.Parallel() + + // wake=07:30, sleep=23:30 => sleep: [23:30, 07:30) + wake := 7*60 + 30 + sleep := 23*60 + 30 + + if !isInSleepWindow(0, wake, sleep) { + t.Fatalf("expected 00:00 to be in sleep window") + } + if isInSleepWindow(8*60, wake, sleep) { + t.Fatalf("expected 08:00 to be awake") + } + if !isInSleepWindow(23*60+45, wake, sleep) { + t.Fatalf("expected 23:45 to be in sleep window") + } + + // wake=18:00, sleep=02:00 => sleep: [02:00, 18:00) + wake = 18 * 60 + sleep = 2 * 60 + if isInSleepWindow(1*60, wake, sleep) { + t.Fatalf("expected 01:00 to be awake (awake window crosses midnight)") + } + if !isInSleepWindow(10*60, wake, sleep) { + t.Fatalf("expected 10:00 to be in sleep window") + } +} + +func TestAdjustToWakeIfInSleep(t *testing.T) { + t.Parallel() + + loc := time.Local + // wake=07:30, sleep=23:30 + wake := "07:30" + sleep := "23:30" + + // 02:00 should adjust to same-day 07:30 + in := time.Date(2026, 1, 2, 2, 0, 0, 0, loc) + out, adjusted, err := adjustToWakeIfInSleep(in, wake, sleep) + if err != nil { + t.Fatalf("adjustToWakeIfInSleep: %v", err) + } + if !adjusted { + t.Fatalf("expected adjustment") + } + if out.Hour() != 7 || out.Minute() != 30 { + t.Fatalf("expected 07:30, got %02d:%02d", out.Hour(), out.Minute()) + } + + // 10:00 should not adjust + in = time.Date(2026, 1, 2, 10, 0, 0, 0, loc) + out, adjusted, err = adjustToWakeIfInSleep(in, wake, sleep) + if err != nil { + t.Fatalf("adjustToWakeIfInSleep: %v", err) + } + if adjusted { + t.Fatalf("expected no adjustment") + } + if !out.Equal(in) { + t.Fatalf("expected unchanged time") + } + + // 23:45 should adjust to next-day 07:30 + in = time.Date(2026, 1, 2, 23, 45, 0, 0, loc) + out, adjusted, err = adjustToWakeIfInSleep(in, wake, sleep) + if err != nil { + t.Fatalf("adjustToWakeIfInSleep: %v", err) + } + if !adjusted { + t.Fatalf("expected adjustment") + } + if out.Day() != 3 || out.Hour() != 7 || out.Minute() != 30 { + t.Fatalf("expected next day 07:30, got %s", out.Format(time.RFC3339)) + } +} +