7 Commits

25 changed files with 1958 additions and 107 deletions
+8 -3
View File
@@ -8,13 +8,14 @@ import (
"github.com/gin-gonic/gin"
"wx_service/config"
"wx_service/internal/achievement"
adminmodule "wx_service/internal/admin"
authhandler "wx_service/internal/common/auth/handler"
authservice "wx_service/internal/common/auth/service"
uploadhandler "wx_service/internal/common/upload/handler"
uploadservice "wx_service/internal/common/upload/service"
rediscache "wx_service/internal/common/redis/cache"
redisservice "wx_service/internal/common/redis/service"
uploadhandler "wx_service/internal/common/upload/handler"
uploadservice "wx_service/internal/common/upload/service"
oahandler "wx_service/internal/common/wechat_official/handler"
oaservice "wx_service/internal/common/wechat_official/service"
"wx_service/internal/database"
@@ -30,7 +31,6 @@ import (
membershipservice "wx_service/internal/membership/service"
"wx_service/internal/model"
"wx_service/internal/observability"
"wx_service/internal/achievement"
quitcheckinhandler "wx_service/internal/quitcheckin/handler"
quitcheckinmodel "wx_service/internal/quitcheckin/model"
quitcheckinservice "wx_service/internal/quitcheckin/service"
@@ -88,6 +88,11 @@ func main() {
&quitcheckinmodel.Profile{},
&quitcheckinmodel.DailyStatus{},
&quitcheckinmodel.RelapseEvent{},
&quitcheckinmodel.HPChangeLog{},
&quitcheckinmodel.SupervisorInvite{},
&quitcheckinmodel.SupervisorBinding{},
&quitcheckinmodel.SupervisorReminderSetting{},
&quitcheckinmodel.SupervisorReminderLog{},
&quitcheckinmodel.RewardGoal{},
&quitcheckinmodel.DreamPreset{},
&achievement.Theme{},
+7 -1
View File
@@ -13,6 +13,7 @@
{
"smoke_time": "2025-12-31",
"smoke_at": "2025-12-31 08:30:00",
"reason_tags": ["stress", "social"],
"remark": "压力大",
"level": 2,
"num": 3
@@ -22,6 +23,7 @@
说明:
- `smoke_time` 可选;不传则默认“当天”。
- `smoke_at` 可选;真实抽烟时间(格式 `YYYY-MM-DD HH:MM:SS`)。用于“按时间节点分析/AI 建议”;不传则可用 `createtime` 近似。
- `reason_tags` 可选;结构化原因标签,传 JSON 数组,例如 `["stress","after_meal"]`
- `level/num` 可选;不传时后端会按 `1` 处理。
- `POST /api/v1/smoke/logs` 仅用于“抽烟记录”,`num` 必须 `>0`
- “想抽但忍住了”请使用 `POST /api/v1/smoke/logs/resisted`;系统以 `level=0 且 num=0` 作为“忍住”的判断条件。
@@ -32,7 +34,7 @@ curl 示例:
curl -X POST 'http://127.0.0.1:8080/api/v1/smoke/logs' \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer wx-session-key' \
-d '{"smoke_time":"2025-12-31","smoke_at":"2025-12-31 08:30:00","remark":"压力大","level":2,"num":3}'
-d '{"smoke_time":"2025-12-31","smoke_at":"2025-12-31 08:30:00","reason_tags":["stress","social"],"remark":"压力大","level":2,"num":3}'
```
成功响应示例(字段以实际为准):
@@ -46,6 +48,7 @@ curl -X POST 'http://127.0.0.1:8080/api/v1/smoke/logs' \
"smoke_time": "2025-12-31T00:00:00+08:00",
"smoke_at": "2025-12-31T08:30:00+08:00",
"remark": "压力大",
"reason_tags": ["stress", "social"],
"createtime": 1735600000,
"updatetime": 1735600000,
"deletetime": null,
@@ -149,6 +152,7 @@ curl -X GET 'http://127.0.0.1:8080/api/v1/smoke/logs/5202' \
"smoke_time": "2026-01-05T00:00:00+08:00",
"smoke_at": "2026-01-05T09:12:00+08:00",
"remark": "压力大",
"reason_tags": ["stress"],
"level": 3,
"num": 2,
"createtime": 1736049120
@@ -168,6 +172,7 @@ curl -X GET 'http://127.0.0.1:8080/api/v1/smoke/logs/5202' \
{
"smoke_time": "2026-01-01",
"smoke_at": "2026-01-01 21:10:00",
"reason_tags": ["social"],
"remark": "聚会",
"level": 3,
"num": 1
@@ -464,6 +469,7 @@ curl -X GET 'http://127.0.0.1:8080/api/v1/smoke/logs/5202' \
{
"smoke_time": "2026-01-05",
"smoke_at": "2026-01-05 10:20:00",
"reason_tags": ["deep_breath", "water"],
"remark": "压力大,想抽但忍住了",
"level": 0,
"num": 0
+32
View File
@@ -0,0 +1,32 @@
-- QuitCheckin (V2) schema notes
-- This file documents the minimal DDL related to the HP persistence model (Phase 3 / issue #39).
-- 1) Profile: add persistent HP field (nullable for migration compatibility)
ALTER TABLE `fa_quit_checkin_profile`
ADD COLUMN `hp_current` INT NULL COMMENT '肺部HP(0~100)' AFTER `reset_rule`;
-- 2) HP change log: each HP delta is recorded for daily aggregation and future analytics
CREATE TABLE IF NOT EXISTS `fa_quit_checkin_hp_change_log` (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键',
`created_at` DATETIME(3) NOT NULL COMMENT '创建时间',
`updated_at` DATETIME(3) NOT NULL COMMENT '更新时间',
`deleted_at` DATETIME(3) NULL COMMENT '删除时间',
`uid` INT NOT NULL COMMENT '用户ID',
`change_date` DATE NOT NULL COMMENT '所属自然日',
`change_at` DATETIME(3) NOT NULL COMMENT '变动时间',
`delta` INT NOT NULL COMMENT '变动值(可正可负)',
`hp_before` INT NOT NULL COMMENT '变动前HP',
`hp_after` INT NOT NULL COMMENT '变动后HP',
`reason` VARCHAR(64) NOT NULL COMMENT '变动原因(checkin|smoke|relapse|migrate_init...)',
`source_type` VARCHAR(32) NOT NULL DEFAULT '' COMMENT '来源类型',
`source_id` BIGINT UNSIGNED NULL COMMENT '来源ID',
PRIMARY KEY (`id`),
KEY `idx_quit_hp_uid_date` (`uid`, `change_date`),
KEY `idx_quit_hp_reason` (`reason`),
KEY `idx_quit_hp_deleted_at` (`deleted_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='V2-无烟打卡-HP变动日志';
+1
View File
@@ -7,6 +7,7 @@ CREATE TABLE IF NOT EXISTS `fa_smoke_log` (
`smoke_time` date DEFAULT NULL COMMENT '抽烟时间',
`smoke_at` datetime DEFAULT NULL COMMENT '真实抽烟时间(可补录,精确到时分秒;为空则可用 createtime 近似)',
`remark` text COMMENT '抽烟原因',
`reason_tags` json DEFAULT NULL COMMENT '结构化原因标签(JSON数组)',
`createtime` int(11) DEFAULT NULL COMMENT '创建时间',
`updatetime` int(11) DEFAULT NULL COMMENT '修改时间',
`deletetime` int(11) DEFAULT NULL COMMENT '删除时间',
+12 -10
View File
@@ -25,12 +25,13 @@ type smokeLogListQuery struct {
}
type smokeLogUpsertRequest struct {
UID *int `json:"uid"`
SmokeTime *string `json:"smoke_time"`
SmokeAt *string `json:"smoke_at"`
Remark *string `json:"remark"`
Level *int64 `json:"level"`
Num *int `json:"num"`
UID *int `json:"uid"`
SmokeTime *string `json:"smoke_time"`
SmokeAt *string `json:"smoke_at"`
Remark *string `json:"remark"`
ReasonTags *smokemodel.StringSlice `json:"reason_tags"`
Level *int64 `json:"level"`
Num *int `json:"num"`
}
func (h *Handler) ListSmokeLogs(c *gin.Context) {
@@ -167,10 +168,11 @@ func (h *Handler) DeleteSmokeLog(c *gin.Context) {
func buildSmokeLogInput(req smokeLogUpsertRequest) (adminservice.SmokeLogUpsertInput, error) {
input := adminservice.SmokeLogUpsertInput{
UID: req.UID,
Remark: req.Remark,
Level: req.Level,
Num: req.Num,
UID: req.UID,
Remark: req.Remark,
ReasonTags: req.ReasonTags,
Level: req.Level,
Num: req.Num,
}
if req.SmokeTime != nil {
parsed, err := parseDateOnlyRequired(*req.SmokeTime)
+25 -15
View File
@@ -24,15 +24,16 @@ type ListSmokeLogsQuery struct {
}
type SmokeLogItem struct {
ID int `json:"id"`
UID int `json:"uid"`
SmokeTime *time.Time `json:"smoke_time,omitempty"`
SmokeAt *time.Time `json:"smoke_at,omitempty"`
Remark string `json:"remark"`
Level int64 `json:"level"`
Num int `json:"num"`
CreateTime *int64 `json:"createtime,omitempty"`
UpdateTime *int64 `json:"updatetime,omitempty"`
ID int `json:"id"`
UID int `json:"uid"`
SmokeTime *time.Time `json:"smoke_time,omitempty"`
SmokeAt *time.Time `json:"smoke_at,omitempty"`
Remark string `json:"remark"`
ReasonTags smokemodel.StringSlice `json:"reason_tags,omitempty"`
Level int64 `json:"level"`
Num int `json:"num"`
CreateTime *int64 `json:"createtime,omitempty"`
UpdateTime *int64 `json:"updatetime,omitempty"`
}
type ListSmokeLogsResult struct {
@@ -45,12 +46,13 @@ type ListSmokeLogsResult struct {
// SmokeLogUpsertInput 用于新增与更新戒烟记录。
// 说明:更新时可只传部分字段(指针字段支持局部更新)。
type SmokeLogUpsertInput struct {
UID *int
SmokeTime **time.Time
SmokeAt **time.Time
Remark *string
Level *int64
Num *int
UID *int
SmokeTime **time.Time
SmokeAt **time.Time
Remark *string
ReasonTags *smokemodel.StringSlice
Level *int64
Num *int
}
func (s *Service) ListSmokeLogs(ctx context.Context, query ListSmokeLogsQuery) (*ListSmokeLogsResult, error) {
@@ -93,6 +95,7 @@ func (s *Service) ListSmokeLogs(ctx context.Context, query ListSmokeLogsQuery) (
SmokeTime: row.SmokeTime,
SmokeAt: row.SmokeAt,
Remark: row.Remark,
ReasonTags: row.ReasonTags,
Level: row.Level,
Num: row.Num,
CreateTime: row.CreateTime,
@@ -126,6 +129,7 @@ func (s *Service) GetSmokeLog(ctx context.Context, id int) (*SmokeLogItem, error
SmokeTime: row.SmokeTime,
SmokeAt: row.SmokeAt,
Remark: row.Remark,
ReasonTags: row.ReasonTags,
Level: row.Level,
Num: row.Num,
CreateTime: row.CreateTime,
@@ -164,6 +168,9 @@ func (s *Service) CreateSmokeLog(ctx context.Context, input SmokeLogUpsertInput)
if input.Remark != nil {
row.Remark = strings.TrimSpace(*input.Remark)
}
if input.ReasonTags != nil {
row.ReasonTags = *input.ReasonTags
}
if err := s.db.WithContext(ctx).Create(row).Error; err != nil {
return nil, err
@@ -189,6 +196,9 @@ func (s *Service) UpdateSmokeLog(ctx context.Context, id int, input SmokeLogUpse
if input.Remark != nil {
updates["remark"] = strings.TrimSpace(*input.Remark)
}
if input.ReasonTags != nil {
updates["reason_tags"] = *input.ReasonTags
}
if input.Level != nil {
if *input.Level <= 0 {
return nil, ErrInvalidInput
@@ -0,0 +1,73 @@
package handler
import (
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
"wx_service/internal/middleware"
"wx_service/internal/model"
service "wx_service/internal/quitcheckin/service"
)
// GetReminderSettings GET /api/v2/supervisor/reminders/settings
// owner 读取自己的提醒设置。
func (h *Handler) GetReminderSettings(c *gin.Context) {
user := middleware.MustCurrentUser(c)
res, err := h.service.GetReminderSettings(c.Request.Context(), int(user.ID))
if err != nil {
c.JSON(http.StatusInternalServerError, model.Error(http.StatusInternalServerError, "获取提醒设置失败,请稍后重试"))
return
}
c.JSON(http.StatusOK, model.Success(res))
}
type updateReminderSettingsRequest struct {
Enabled *bool `json:"enabled"`
NotifyTime *string `json:"notify_time"`
MaxPerDay *int `json:"max_per_day"`
}
// UpdateReminderSettings PUT /api/v2/supervisor/reminders/settings
func (h *Handler) UpdateReminderSettings(c *gin.Context) {
user := middleware.MustCurrentUser(c)
var req updateReminderSettingsRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "请求参数错误"))
return
}
// basic trim
if req.NotifyTime != nil {
v := strings.TrimSpace(*req.NotifyTime)
req.NotifyTime = &v
}
res, err := h.service.UpdateReminderSettings(c.Request.Context(), int(user.ID), service.UpdateReminderSettingsRequest{
Enabled: req.Enabled,
NotifyTime: req.NotifyTime,
MaxPerDay: req.MaxPerDay,
}, time.Now())
if err != nil {
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "保存提醒设置失败"))
return
}
c.JSON(http.StatusOK, model.Success(res))
}
// RunReminders POST /api/v2/supervisor/reminders/run
// supervisor 手动触发提醒(开发/测试用):只会给“当前用户作为监督人”的绑定关系写 reminder_log。
func (h *Handler) RunReminders(c *gin.Context) {
user := middleware.MustCurrentUser(c)
res, err := h.service.RunMissedCheckinRemindersForSupervisor(c.Request.Context(), int(user.ID), time.Now())
if err != nil {
c.JSON(http.StatusInternalServerError, model.Error(http.StatusInternalServerError, "触发提醒失败,请稍后重试"))
return
}
c.JSON(http.StatusOK, model.Success(res))
}
@@ -0,0 +1,121 @@
package handler
import (
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
"wx_service/internal/middleware"
"wx_service/internal/model"
)
type createSupervisorInviteRequest struct {
Days int `json:"days"`
}
// CreateSupervisorInvite POST /api/v2/supervisor/invites
func (h *Handler) CreateSupervisorInvite(c *gin.Context) {
user := middleware.MustCurrentUser(c)
var req createSupervisorInviteRequest
_ = c.ShouldBindJSON(&req)
res, err := h.service.CreateSupervisorInvite(c.Request.Context(), int(user.ID), time.Now(), req.Days)
if err != nil {
c.JSON(http.StatusInternalServerError, model.Error(http.StatusInternalServerError, "生成邀请失败,请稍后重试"))
return
}
c.JSON(http.StatusOK, model.Success(res))
}
type bindSupervisorInviteRequest struct {
Token string `json:"token"`
}
// BindSupervisorInvite POST /api/v2/supervisor/bind
func (h *Handler) BindSupervisorInvite(c *gin.Context) {
user := middleware.MustCurrentUser(c)
var req bindSupervisorInviteRequest
if err := c.ShouldBindJSON(&req); err != nil || strings.TrimSpace(req.Token) == "" {
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "请求参数错误"))
return
}
if err := h.service.BindSupervisorInvite(c.Request.Context(), int(user.ID), req.Token, time.Now()); err != nil {
msg := "绑定失败,请稍后重试"
switch err {
case nil:
// no-op
default:
// 针对业务错误给出更友好的提示
switch err.Error() {
case "邀请不存在":
msg = "邀请不存在"
case "邀请已过期":
msg = "邀请已过期"
case "邀请已被使用":
msg = "邀请已被使用"
case "不能绑定自己为监督人":
msg = "不能绑定自己"
case "监督关系已存在":
msg = "已绑定,无需重复操作"
case "监督人已达上限":
msg = "对方监督人已达上限(最多 3 人)"
}
}
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, msg))
return
}
c.JSON(http.StatusOK, model.Success(gin.H{"ok": true}))
}
// GetSupervisorOverview GET /api/v2/supervisor/overview
func (h *Handler) GetSupervisorOverview(c *gin.Context) {
user := middleware.MustCurrentUser(c)
res, err := h.service.GetSupervisorOverview(c.Request.Context(), int(user.ID), time.Now())
if err != nil {
c.JSON(http.StatusInternalServerError, model.Error(http.StatusInternalServerError, "获取监督概览失败,请稍后重试"))
return
}
c.JSON(http.StatusOK, model.Success(res))
}
// GetSupervisorStatus GET /api/v2/supervisor/status
func (h *Handler) GetSupervisorStatus(c *gin.Context) {
user := middleware.MustCurrentUser(c)
res, err := h.service.GetSupervisorStatus(c.Request.Context(), int(user.ID))
if err != nil {
c.JSON(http.StatusInternalServerError, model.Error(http.StatusInternalServerError, "获取监督信息失败,请稍后重试"))
return
}
c.JSON(http.StatusOK, model.Success(res))
}
type revokeSupervisorBindingRequest struct {
OwnerUID int `json:"owner_uid"`
SupervisorUID int `json:"supervisor_uid"`
}
// RevokeSupervisorBinding POST /api/v2/supervisor/revoke
func (h *Handler) RevokeSupervisorBinding(c *gin.Context) {
user := middleware.MustCurrentUser(c)
var req revokeSupervisorBindingRequest
if err := c.ShouldBindJSON(&req); err != nil || req.OwnerUID <= 0 || req.SupervisorUID <= 0 {
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "请求参数错误"))
return
}
if err := h.service.RevokeSupervisorBinding(c.Request.Context(), int(user.ID), req.OwnerUID, req.SupervisorUID, time.Now()); err != nil {
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "解除失败"))
return
}
c.JSON(http.StatusOK, model.Success(gin.H{"ok": true}))
}
@@ -0,0 +1,40 @@
package model
import (
"time"
"gorm.io/gorm"
)
// HPChangeLog 记录每次 HP 变动明细,用于:
// - 首页展示“今日 +x / -x”
// - 后续趋势图、剧情、监督机制的数据基础
type HPChangeLog struct {
ID uint `gorm:"primaryKey;comment:主键" json:"id"`
CreatedAt time.Time `gorm:"comment:创建时间" json:"created_at"`
UpdatedAt time.Time `gorm:"comment:更新时间" json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index;comment:删除时间" json:"-"`
UID int `gorm:"index;comment:用户ID" json:"-"`
// ChangeDate 用于按自然日聚合(例如:统计“今日变动”)。
ChangeDate time.Time `gorm:"column:change_date;type:date;index;comment:所属自然日" json:"change_date"`
ChangeAt time.Time `gorm:"column:change_at;comment:变动时间" json:"change_at"`
Delta int `gorm:"column:delta;comment:变动值(可正可负)" json:"delta"`
HPBefore int `gorm:"column:hp_before;comment:变动前HP" json:"hp_before"`
HPAfter int `gorm:"column:hp_after;comment:变动后HP" json:"hp_after"`
Reason string `gorm:"column:reason;size:64;index;comment:变动原因(checkin|smoke|relapse|migrate_init...)" json:"reason"`
// Source 可选:记录来源(例如 smoke_log / relapse_event 等),便于排查与溯源。
SourceType string `gorm:"column:source_type;size:32;comment:来源类型" json:"source_type,omitempty"`
SourceID *uint `gorm:"column:source_id;comment:来源ID" json:"source_id,omitempty"`
}
func (HPChangeLog) TableName() string {
return "fa_quit_checkin_hp_change_log"
}
func (HPChangeLog) TableComment() string {
return "V2-无烟打卡-HP变动日志"
}
+3
View File
@@ -21,6 +21,9 @@ type Profile struct {
Motivation string `gorm:"column:motivation;size:200;comment:戒烟初心" json:"motivation"`
NotifyTime string `gorm:"column:notify_time;size:5;comment:提醒时间(HH:MM)" json:"notify_time"`
ResetRule string `gorm:"column:reset_rule;size:64;comment:连续天数重置规则" json:"reset_rule"`
// HpCurrent 表示“肺部 HP”(0~100)。允许为 NULL:用于兼容老数据,首次访问时再做迁移初始化。
HpCurrent *int `gorm:"column:hp_current;comment:肺部HP(0~100)" json:"hp_current,omitempty"`
}
// TableName 返回用户资料表名。
@@ -0,0 +1,28 @@
package model
import (
"time"
"gorm.io/gorm"
)
// SupervisorBinding 表示监督关系(一对:owner -> supervisor)。
type SupervisorBinding struct {
ID uint `gorm:"primaryKey;comment:主键" json:"id"`
CreatedAt time.Time `gorm:"comment:创建时间" json:"created_at"`
UpdatedAt time.Time `gorm:"comment:更新时间" json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index;comment:删除时间" json:"-"`
OwnerUID int `gorm:"column:owner_uid;uniqueIndex:uniq_owner_supervisor;index;comment:被监督用户ID" json:"owner_uid"`
SupervisorUID int `gorm:"column:supervisor_uid;uniqueIndex:uniq_owner_supervisor;index;comment:监督人用户ID" json:"supervisor_uid"`
Status string `gorm:"column:status;size:16;index;comment:状态(active|revoked)" json:"status"`
}
func (SupervisorBinding) TableName() string {
return "fa_quit_checkin_supervisor_binding"
}
func (SupervisorBinding) TableComment() string {
return "V2-无烟打卡-监督关系"
}
@@ -0,0 +1,31 @@
package model
import (
"time"
"gorm.io/gorm"
)
// SupervisorInvite 表示一次“邀请监督人”的邀请记录。
// 邀请通过 token 进行一次性绑定:被接受后 used_at/used_by_uid 会被写入。
type SupervisorInvite struct {
ID uint `gorm:"primaryKey;comment:主键" json:"id"`
CreatedAt time.Time `gorm:"comment:创建时间" json:"created_at"`
UpdatedAt time.Time `gorm:"comment:更新时间" json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index;comment:删除时间" json:"-"`
OwnerUID int `gorm:"column:owner_uid;index;comment:被监督用户ID" json:"-"`
Token string `gorm:"column:token;size:64;uniqueIndex;comment:邀请token" json:"token"`
ExpireAt time.Time `gorm:"column:expire_at;comment:过期时间" json:"expire_at"`
UsedAt *time.Time `gorm:"column:used_at;comment:被使用时间" json:"used_at,omitempty"`
UsedByUID *int `gorm:"column:used_by_uid;comment:使用者(监督人)用户ID" json:"used_by_uid,omitempty"`
}
func (SupervisorInvite) TableName() string {
return "fa_quit_checkin_supervisor_invite"
}
func (SupervisorInvite) TableComment() string {
return "V2-无烟打卡-监督人邀请"
}
@@ -0,0 +1,37 @@
package model
import (
"time"
"gorm.io/gorm"
)
// SupervisorReminderLog 记录一次提醒尝试,用于:
// - 频控:按天限制每个 (owner, supervisor) 的提醒次数
// - 追踪:后续接入真实通道(订阅消息)时可落库 status/result
type SupervisorReminderLog struct {
ID uint `gorm:"primaryKey;comment:主键" json:"id"`
CreatedAt time.Time `gorm:"comment:创建时间" json:"created_at"`
UpdatedAt time.Time `gorm:"comment:更新时间" json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index;comment:删除时间" json:"-"`
OwnerUID int `gorm:"column:owner_uid;index:idx_owner_supervisor_date,priority:1;comment:被监督用户ID" json:"owner_uid"`
SupervisorUID int `gorm:"column:supervisor_uid;index:idx_owner_supervisor_date,priority:2;comment:监督人用户ID" json:"supervisor_uid"`
ReminderDate time.Time `gorm:"column:reminder_date;type:date;index:idx_owner_supervisor_date,priority:3;comment:所属自然日" json:"reminder_date"`
ReminderAt time.Time `gorm:"column:reminder_at;comment:提醒时间" json:"reminder_at"`
Type string `gorm:"column:type;size:32;index;comment:提醒类型(missed_checkin...)" json:"type"`
Status string `gorm:"column:status;size:16;index;comment:状态(stubbed|sent|failed)" json:"status"`
Channel string `gorm:"column:channel;size:32;comment:通道(stub|subscribe_msg...)" json:"channel"`
Message string `gorm:"column:message;type:text;comment:提醒内容(可选)" json:"message,omitempty"`
}
func (SupervisorReminderLog) TableName() string {
return "fa_quit_checkin_supervisor_reminder_log"
}
func (SupervisorReminderLog) TableComment() string {
return "V2-无烟打卡-监督提醒记录"
}
@@ -0,0 +1,31 @@
package model
import (
"time"
"gorm.io/gorm"
)
// SupervisorReminderSetting 表示“被监督用户(owner)”对提醒机制的配置。
// 注意:提醒本质是隐私相关能力,默认应为关闭,需 owner 显式开启。
type SupervisorReminderSetting struct {
ID uint `gorm:"primaryKey;comment:主键" json:"id"`
CreatedAt time.Time `gorm:"comment:创建时间" json:"created_at"`
UpdatedAt time.Time `gorm:"comment:更新时间" json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index;comment:删除时间" json:"-"`
OwnerUID int `gorm:"column:owner_uid;uniqueIndex;comment:被监督用户ID" json:"owner_uid"`
Enabled bool `gorm:"column:enabled;comment:是否启用提醒" json:"enabled"`
NotifyTime string `gorm:"column:notify_time;size:5;comment:提醒时间(HH:MM)" json:"notify_time"`
MaxPerDay int `gorm:"column:max_per_day;comment:每日最多提醒次数(每个监督人)" json:"max_per_day"`
ChannelHint string `gorm:"column:channel_hint;size:32;comment:提醒通道提示(stub|subscribe_msg...)" json:"channel_hint,omitempty"`
}
func (SupervisorReminderSetting) TableName() string {
return "fa_quit_checkin_supervisor_reminder_setting"
}
func (SupervisorReminderSetting) TableComment() string {
return "V2-无烟打卡-监督提醒设置"
}
@@ -0,0 +1,156 @@
package service
import (
"context"
"testing"
"time"
quitmodel "wx_service/internal/quitcheckin/model"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
func setupQuitHPTestDB(t *testing.T) *gorm.DB {
t.Helper()
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{
Logger: logger.Default.LogMode(logger.Silent),
})
if err != nil {
t.Fatalf("open sqlite: %v", err)
}
if err := db.AutoMigrate(
&quitmodel.Profile{},
&quitmodel.DailyStatus{},
&quitmodel.RelapseEvent{},
&quitmodel.HPChangeLog{},
&quitmodel.RewardGoal{},
&quitmodel.DreamPreset{},
); err != nil {
t.Fatalf("auto migrate: %v", err)
}
return db
}
func TestQuitCheckinHomeInitializesHP(t *testing.T) {
t.Parallel()
db := setupQuitHPTestDB(t)
svc := NewService(db)
ctx := context.Background()
uid := 2001
startDate := time.Date(2026, 4, 10, 0, 0, 0, 0, time.Local)
now := time.Date(2026, 4, 10, 9, 0, 0, 0, time.Local)
if _, err := svc.UpsertProfile(ctx, uid, UpsertProfileRequest{
QuitStartDate: &startDate,
PackPriceCent: intPtr(2500),
BaselineCigsPerDay: intPtr(12),
}, "测试用户", "", now); err != nil {
t.Fatalf("upsert profile: %v", err)
}
home, err := svc.Home(ctx, uid, now)
if err != nil {
t.Fatalf("home: %v", err)
}
if home.Summary.HPCurrent <= 0 {
t.Fatalf("hp_current=%d, want > 0", home.Summary.HPCurrent)
}
if home.Summary.HPChangeToday != 0 {
t.Fatalf("hp_change_today=%d, want 0", home.Summary.HPChangeToday)
}
}
func TestQuitCheckinCheckinIncreasesHPAndTracksTodayDelta(t *testing.T) {
t.Parallel()
db := setupQuitHPTestDB(t)
svc := NewService(db)
ctx := context.Background()
uid := 2002
startDate := time.Date(2026, 4, 10, 0, 0, 0, 0, time.Local)
day1 := time.Date(2026, 4, 10, 9, 0, 0, 0, time.Local)
if _, err := svc.UpsertProfile(ctx, uid, UpsertProfileRequest{
QuitStartDate: &startDate,
PackPriceCent: intPtr(2500),
BaselineCigsPerDay: intPtr(10),
}, "测试用户", "", day1); err != nil {
t.Fatalf("upsert profile: %v", err)
}
before, err := svc.Home(ctx, uid, day1)
if err != nil {
t.Fatalf("home before: %v", err)
}
_, err = svc.Checkin(ctx, uid, CheckinRequest{Date: day1, Note: "day1"}, day1)
if err != nil {
t.Fatalf("checkin: %v", err)
}
after, err := svc.Home(ctx, uid, day1)
if err != nil {
t.Fatalf("home after: %v", err)
}
if after.Summary.HPCurrent <= before.Summary.HPCurrent {
t.Fatalf("hp_current before=%d after=%d, want after > before", before.Summary.HPCurrent, after.Summary.HPCurrent)
}
if after.Summary.HPChangeToday <= 0 {
t.Fatalf("hp_change_today=%d, want > 0", after.Summary.HPChangeToday)
}
}
func TestQuitCheckinSmokeSlipDecreasesHPAndMarksRelapsed(t *testing.T) {
t.Parallel()
db := setupQuitHPTestDB(t)
svc := NewService(db)
ctx := context.Background()
uid := 2003
startDate := time.Date(2026, 4, 10, 0, 0, 0, 0, time.Local)
day1 := time.Date(2026, 4, 10, 9, 0, 0, 0, time.Local)
if _, err := svc.UpsertProfile(ctx, uid, UpsertProfileRequest{
QuitStartDate: &startDate,
PackPriceCent: intPtr(2500),
BaselineCigsPerDay: intPtr(8),
}, "测试用户", "", day1); err != nil {
t.Fatalf("upsert profile: %v", err)
}
before, err := svc.Home(ctx, uid, day1)
if err != nil {
t.Fatalf("home before: %v", err)
}
slipAt := time.Date(2026, 4, 10, 10, 15, 0, 0, time.Local)
if err := svc.RecordSmokeSlip(ctx, uid, slipAt, 1, "slip"); err != nil {
t.Fatalf("record slip: %v", err)
}
after, err := svc.Home(ctx, uid, day1)
if err != nil {
t.Fatalf("home after: %v", err)
}
if after.DailyStatus.Status != quitmodel.DailyStatusRelapsed {
t.Fatalf("daily status=%s, want=%s", after.DailyStatus.Status, quitmodel.DailyStatusRelapsed)
}
if after.Summary.HPCurrent >= before.Summary.HPCurrent {
t.Fatalf("hp_current before=%d after=%d, want after < before", before.Summary.HPCurrent, after.Summary.HPCurrent)
}
if after.Summary.HPChangeToday >= 0 {
t.Fatalf("hp_change_today=%d, want < 0", after.Summary.HPChangeToday)
}
if after.Summary.CurrentStreakDays != 0 {
t.Fatalf("current_streak_days=%d, want 0", after.Summary.CurrentStreakDays)
}
}
+253
View File
@@ -0,0 +1,253 @@
package service
import (
"context"
"errors"
"fmt"
"strings"
"time"
quitmodel "wx_service/internal/quitcheckin/model"
"gorm.io/gorm"
)
const (
reminderTypeMissedCheckin = "missed_checkin"
reminderStatusStubbed = "stubbed"
reminderChannelStub = "stub"
)
type ReminderSettingsResult struct {
Enabled bool `json:"enabled"`
NotifyTime string `json:"notify_time"`
MaxPerDay int `json:"max_per_day"`
}
type UpdateReminderSettingsRequest struct {
Enabled *bool
NotifyTime *string
MaxPerDay *int
}
type RunRemindersResult struct {
Created int `json:"created"`
Skipped int `json:"skipped"`
}
var (
ErrReminderSettingsInvalid = errors.New("提醒设置不合法")
)
func (s *Service) GetReminderSettings(ctx context.Context, ownerUID int) (ReminderSettingsResult, error) {
setting, err := s.loadOrInitReminderSetting(ctx, ownerUID, time.Now().In(time.Local))
if err != nil {
return ReminderSettingsResult{}, err
}
return ReminderSettingsResult{
Enabled: setting.Enabled,
NotifyTime: setting.NotifyTime,
MaxPerDay: setting.MaxPerDay,
}, nil
}
func (s *Service) UpdateReminderSettings(ctx context.Context, ownerUID int, req UpdateReminderSettingsRequest, now time.Time) (ReminderSettingsResult, error) {
setting, err := s.loadOrInitReminderSetting(ctx, ownerUID, now)
if err != nil {
return ReminderSettingsResult{}, err
}
updates := map[string]interface{}{}
if req.Enabled != nil {
updates["enabled"] = *req.Enabled
setting.Enabled = *req.Enabled
}
if req.NotifyTime != nil {
v := strings.TrimSpace(*req.NotifyTime)
if !ParseNotifyTime(v) {
return ReminderSettingsResult{}, ErrReminderSettingsInvalid
}
updates["notify_time"] = v
setting.NotifyTime = v
}
if req.MaxPerDay != nil {
v := *req.MaxPerDay
if v < 0 || v > 10 {
return ReminderSettingsResult{}, ErrReminderSettingsInvalid
}
if v == 0 {
// 0 表示关闭提醒(即使 enabled=true 也不会发送)
updates["max_per_day"] = 0
setting.MaxPerDay = 0
} else {
updates["max_per_day"] = v
setting.MaxPerDay = v
}
}
if len(updates) == 0 {
return ReminderSettingsResult{
Enabled: setting.Enabled,
NotifyTime: setting.NotifyTime,
MaxPerDay: setting.MaxPerDay,
}, nil
}
updates["updated_at"] = now
if err := s.db.WithContext(ctx).
Model(&quitmodel.SupervisorReminderSetting{}).
Where("owner_uid = ?", ownerUID).
Updates(updates).Error; err != nil {
return ReminderSettingsResult{}, err
}
return ReminderSettingsResult{
Enabled: setting.Enabled,
NotifyTime: setting.NotifyTime,
MaxPerDay: setting.MaxPerDay,
}, nil
}
// RunMissedCheckinRemindersForSupervisor 手动触发提醒(用于开发/测试):
// - 只会针对“当前监督人”绑定的 owner
// - 只会写入 reminder_logstubbed),不接真实通道
func (s *Service) RunMissedCheckinRemindersForSupervisor(ctx context.Context, supervisorUID int, now time.Time) (RunRemindersResult, error) {
today := normalizeDate(now)
var bindings []quitmodel.SupervisorBinding
if err := s.db.WithContext(ctx).
Where("supervisor_uid = ? AND status = ?", supervisorUID, "active").
Find(&bindings).Error; err != nil {
return RunRemindersResult{}, err
}
if len(bindings) == 0 {
return RunRemindersResult{Created: 0, Skipped: 0}, nil
}
created := 0
skipped := 0
for _, b := range bindings {
ownerUID := b.OwnerUID
// owner 必须有 profile 才视为 quit-checkin 用户;没有就跳过。
_, err := s.loadProfile(ctx, ownerUID)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
skipped++
continue
}
return RunRemindersResult{}, err
}
setting, err := s.loadOrInitReminderSetting(ctx, ownerUID, now)
if err != nil {
return RunRemindersResult{}, err
}
if !setting.Enabled || setting.MaxPerDay <= 0 {
skipped++
continue
}
// 触发时间门槛:now >= notify_time
if !isAfterNotifyTime(now, setting.NotifyTime) {
skipped++
continue
}
// 今日状态:已打卡或已复吸,则无需提醒
var status quitmodel.DailyStatus
err = s.db.WithContext(ctx).
Where("uid = ? AND date = ?", ownerUID, today).
First(&status).Error
if err == nil {
if status.Status == quitmodel.DailyStatusCheckedIn || status.Status == quitmodel.DailyStatusRelapsed {
skipped++
continue
}
} else if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
return RunRemindersResult{}, err
}
// 频控:每日最多 N 次(按 owner+supervisor+date 计数)
var count int64
if err := s.db.WithContext(ctx).
Model(&quitmodel.SupervisorReminderLog{}).
Where("owner_uid = ? AND supervisor_uid = ? AND reminder_date = ?", ownerUID, supervisorUID, today).
Count(&count).Error; err != nil {
return RunRemindersResult{}, err
}
if int(count) >= setting.MaxPerDay {
skipped++
continue
}
msg := fmt.Sprintf("提醒:%s 今天还没打卡", safeNickname(ownerUID))
logRow := quitmodel.SupervisorReminderLog{
OwnerUID: ownerUID,
SupervisorUID: supervisorUID,
ReminderDate: today,
ReminderAt: now,
Type: reminderTypeMissedCheckin,
Status: reminderStatusStubbed,
Channel: reminderChannelStub,
Message: msg,
}
if err := s.db.WithContext(ctx).Create(&logRow).Error; err != nil {
return RunRemindersResult{}, err
}
created++
}
return RunRemindersResult{Created: created, Skipped: skipped}, nil
}
func (s *Service) loadOrInitReminderSetting(ctx context.Context, ownerUID int, now time.Time) (*quitmodel.SupervisorReminderSetting, error) {
var row quitmodel.SupervisorReminderSetting
err := s.db.WithContext(ctx).Where("owner_uid = ?", ownerUID).First(&row).Error
if err == nil {
// sanity defaults
if row.NotifyTime == "" {
row.NotifyTime = "21:00"
}
if row.MaxPerDay < 0 {
row.MaxPerDay = 0
}
return &row, nil
}
if !errors.Is(err, gorm.ErrRecordNotFound) {
return nil, err
}
// 默认关闭,避免隐私风险
row = quitmodel.SupervisorReminderSetting{
OwnerUID: ownerUID,
Enabled: false,
NotifyTime: "21:00",
MaxPerDay: 1,
ChannelHint: "stub",
}
if err := s.db.WithContext(ctx).Create(&row).Error; err != nil {
return nil, err
}
return &row, nil
}
func isAfterNotifyTime(now time.Time, notifyTime string) bool {
notifyTime = strings.TrimSpace(notifyTime)
if notifyTime == "" {
notifyTime = "21:00"
}
t, err := time.ParseInLocation("15:04", notifyTime, time.Local)
if err != nil {
return true
}
target := time.Date(now.Year(), now.Month(), now.Day(), t.Hour(), t.Minute(), 0, 0, time.Local)
return !now.Before(target)
}
func safeNickname(uid int) string {
// 这里先不依赖 user.nickname,避免跨模块耦合和额外查询。
// motivation 字段也不适合作为昵称,仅作占位。
return fmt.Sprintf("用户%d", uid)
}
@@ -0,0 +1,153 @@
package service
import (
"context"
"testing"
"time"
quitmodel "wx_service/internal/quitcheckin/model"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
func setupReminderTestDB(t *testing.T) *gorm.DB {
t.Helper()
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{
Logger: logger.Default.LogMode(logger.Silent),
})
if err != nil {
t.Fatalf("open sqlite: %v", err)
}
if err := db.AutoMigrate(
&quitmodel.Profile{},
&quitmodel.DailyStatus{},
&quitmodel.RelapseEvent{},
&quitmodel.RewardGoal{},
&quitmodel.DreamPreset{},
&quitmodel.SupervisorBinding{},
&quitmodel.SupervisorInvite{},
&quitmodel.SupervisorReminderSetting{},
&quitmodel.SupervisorReminderLog{},
&quitmodel.HPChangeLog{},
); err != nil {
t.Fatalf("auto migrate: %v", err)
}
return db
}
func TestReminderRunCreatesLogAfterNotifyTime(t *testing.T) {
t.Parallel()
db := setupReminderTestDB(t)
svc := NewService(db)
ctx := context.Background()
ownerUID := 4001
supervisorUID := 4002
startDate := time.Date(2026, 4, 10, 0, 0, 0, 0, time.Local)
now := time.Date(2026, 4, 16, 21, 30, 0, 0, time.Local)
// seed quit profile
if err := db.Create(&quitmodel.Profile{
UID: ownerUID,
QuitStartDate: startDate,
PackPriceCent: 2500,
BaselineCigsPerDay: 10,
NotifyTime: "21:00",
ResetRule: "relapse_clears_streak",
}).Error; err != nil {
t.Fatalf("seed profile: %v", err)
}
// seed binding
if err := db.Create(&quitmodel.SupervisorBinding{
OwnerUID: ownerUID,
SupervisorUID: supervisorUID,
Status: "active",
}).Error; err != nil {
t.Fatalf("seed binding: %v", err)
}
// enable reminder
if err := db.Create(&quitmodel.SupervisorReminderSetting{
OwnerUID: ownerUID,
Enabled: true,
NotifyTime: "21:00",
MaxPerDay: 1,
ChannelHint: "stub",
}).Error; err != nil {
t.Fatalf("seed setting: %v", err)
}
res, err := svc.RunMissedCheckinRemindersForSupervisor(ctx, supervisorUID, now)
if err != nil {
t.Fatalf("run: %v", err)
}
if res.Created != 1 {
t.Fatalf("created=%d want=1", res.Created)
}
// run again should be rate-limited
res2, err := svc.RunMissedCheckinRemindersForSupervisor(ctx, supervisorUID, now.Add(10*time.Minute))
if err != nil {
t.Fatalf("run2: %v", err)
}
if res2.Created != 0 {
t.Fatalf("created2=%d want=0", res2.Created)
}
}
func TestReminderRunSkipsBeforeNotifyTime(t *testing.T) {
t.Parallel()
db := setupReminderTestDB(t)
svc := NewService(db)
ctx := context.Background()
ownerUID := 4011
supervisorUID := 4012
startDate := time.Date(2026, 4, 10, 0, 0, 0, 0, time.Local)
now := time.Date(2026, 4, 16, 20, 50, 0, 0, time.Local)
if err := db.Create(&quitmodel.Profile{
UID: ownerUID,
QuitStartDate: startDate,
PackPriceCent: 2500,
BaselineCigsPerDay: 10,
NotifyTime: "21:00",
ResetRule: "relapse_clears_streak",
}).Error; err != nil {
t.Fatalf("seed profile: %v", err)
}
if err := db.Create(&quitmodel.SupervisorBinding{
OwnerUID: ownerUID,
SupervisorUID: supervisorUID,
Status: "active",
}).Error; err != nil {
t.Fatalf("seed binding: %v", err)
}
if err := db.Create(&quitmodel.SupervisorReminderSetting{
OwnerUID: ownerUID,
Enabled: true,
NotifyTime: "21:00",
MaxPerDay: 1,
ChannelHint: "stub",
}).Error; err != nil {
t.Fatalf("seed setting: %v", err)
}
res, err := svc.RunMissedCheckinRemindersForSupervisor(ctx, supervisorUID, now)
if err != nil {
t.Fatalf("run: %v", err)
}
if res.Created != 0 {
t.Fatalf("created=%d want=0", res.Created)
}
}
+330 -39
View File
@@ -103,6 +103,8 @@ type SummaryResult struct {
AvoidedCigs int `json:"avoided_cigs"`
AvoidedCigsMode string `json:"avoided_cigs_mode"`
HealthRecoveryPercent int `json:"health_recovery_percent"`
HPCurrent int `json:"hp_current"`
HPChangeToday int `json:"hp_change_today"`
}
// RewardGoalResult 表示梦想目标展示数据。
@@ -283,7 +285,7 @@ func (s *Service) GetProfile(ctx context.Context, uid int, nickname, avatarURL s
return ProfileView{}, err
}
summary, lastCheckin, lastRelapse, _, err := s.computeSummary(ctx, uid, *profile, now)
summary, lastCheckin, lastRelapse, _, err := s.computeSummary(ctx, uid, profile, now)
if err != nil {
return ProfileView{}, err
}
@@ -371,7 +373,7 @@ func (s *Service) Home(ctx context.Context, uid int, now time.Time) (HomeResult,
return HomeResult{}, err
}
summary, _, _, unlockedCount, err := s.computeSummary(ctx, uid, *profile, now)
summary, _, _, unlockedCount, err := s.computeSummary(ctx, uid, profile, now)
if err != nil {
return HomeResult{}, err
}
@@ -404,38 +406,69 @@ func (s *Service) Checkin(ctx context.Context, uid int, req CheckinRequest, now
date := normalizeDate(req.Date)
var status quitmodel.DailyStatus
err = s.db.WithContext(ctx).Where("uid = ? AND date = ?", uid, date).First(&status).Error
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
shouldApplyHP := false
err = s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
err := tx.WithContext(ctx).Where("uid = ? AND date = ?", uid, date).First(&status).Error
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
return err
}
checkinAt := now
if errors.Is(err, gorm.ErrRecordNotFound) {
status = quitmodel.DailyStatus{
UID: uid,
Date: date,
Status: quitmodel.DailyStatusCheckedIn,
CheckInAt: &checkinAt,
Note: strings.TrimSpace(req.Note),
}
if e := tx.WithContext(ctx).Create(&status).Error; e != nil {
return e
}
shouldApplyHP = true
} else {
if status.Status == quitmodel.DailyStatusRelapsed {
return ErrAlreadyRelapsed
}
if status.Status != quitmodel.DailyStatusCheckedIn {
status.Status = quitmodel.DailyStatusCheckedIn
status.CheckInAt = &checkinAt
status.Note = strings.TrimSpace(req.Note)
if e := tx.WithContext(ctx).Save(&status).Error; e != nil {
return e
}
shouldApplyHP = true
}
}
if !shouldApplyHP {
return nil
}
hpBefore, err := s.ensureHPInitializedBasicTx(ctx, tx, profile, now)
if err != nil {
return err
}
// 打卡回血:前期更快,后期更慢
delta := 2
switch {
case hpBefore < 40:
delta = 4
case hpBefore < 70:
delta = 3
case hpBefore < 90:
delta = 2
default:
delta = 1
}
return s.applyHPDeltaTx(ctx, tx, profile, delta, "checkin", "daily_status", uintPtr(status.ID), now)
})
if err != nil {
return CheckinResult{}, err
}
checkinAt := now
if errors.Is(err, gorm.ErrRecordNotFound) {
status = quitmodel.DailyStatus{
UID: uid,
Date: date,
Status: quitmodel.DailyStatusCheckedIn,
CheckInAt: &checkinAt,
Note: strings.TrimSpace(req.Note),
}
if err := s.db.WithContext(ctx).Create(&status).Error; err != nil {
return CheckinResult{}, err
}
} else {
if status.Status == quitmodel.DailyStatusRelapsed {
return CheckinResult{}, ErrAlreadyRelapsed
}
if status.Status != quitmodel.DailyStatusCheckedIn {
status.Status = quitmodel.DailyStatusCheckedIn
status.CheckInAt = &checkinAt
status.Note = strings.TrimSpace(req.Note)
if err := s.db.WithContext(ctx).Save(&status).Error; err != nil {
return CheckinResult{}, err
}
}
}
summary, _, _, _, err := s.computeSummary(ctx, uid, *profile, now)
summary, _, _, _, err := s.computeSummary(ctx, uid, profile, now)
if err != nil {
return CheckinResult{}, err
}
@@ -472,6 +505,7 @@ func (s *Service) Relapse(ctx context.Context, uid int, req RelapseRequest, now
}
err = s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
wasRelapsed := false
if errors.Is(err, gorm.ErrRecordNotFound) {
status = quitmodel.DailyStatus{
UID: uid,
@@ -487,6 +521,7 @@ func (s *Service) Relapse(ctx context.Context, uid int, req RelapseRequest, now
return e
}
} else {
wasRelapsed = status.Status == quitmodel.DailyStatusRelapsed
status.Status = quitmodel.DailyStatusRelapsed
status.CheckInAt = nil
status.RelapsedAt = &relapsedAt
@@ -505,9 +540,27 @@ func (s *Service) Relapse(ctx context.Context, uid int, req RelapseRequest, now
RelapseNum: req.RelapseNum,
Reason: strings.TrimSpace(req.Reason),
Note: strings.TrimSpace(req.Note),
AffectStreak: true,
AffectStreak: !wasRelapsed,
}
return tx.Create(&event).Error
if e := tx.Create(&event).Error; e != nil {
return e
}
hpBefore, err := s.ensureHPInitializedBasicTx(ctx, tx, profile, relapsedAt)
if err != nil {
return err
}
_ = hpBefore
// 复吸:每支烟扣 M;当日首次复吸额外惩罚。
perCig := 4
delta := -perCig * maxInt(1, req.RelapseNum)
reason := "smoke"
if !wasRelapsed {
delta -= 10
reason = "relapse"
}
return s.applyHPDeltaTx(ctx, tx, profile, delta, reason, "relapse_event", uintPtr(event.ID), relapsedAt)
})
if err != nil {
return RelapseResult{}, err
@@ -518,7 +571,7 @@ func (s *Service) Relapse(ctx context.Context, uid int, req RelapseRequest, now
return RelapseResult{}, err
}
summary, _, _, _, err := s.computeSummary(ctx, uid, *profile, now)
summary, _, _, _, err := s.computeSummary(ctx, uid, profile, now)
if err != nil {
return RelapseResult{}, err
}
@@ -540,6 +593,88 @@ func (s *Service) Relapse(ctx context.Context, uid int, req RelapseRequest, now
}, nil
}
// RecordSmokeSlip 用于 quit 模式下的“抽烟记录”同步到 quitcheckin
// - 当天标记为 relapsed
// - 写入 relapse_event(同一天第二次 slip 不再 affect_streak
// - 扣减 HP(每支烟扣 M;首次 slip 额外惩罚)
func (s *Service) RecordSmokeSlip(ctx context.Context, uid int, slipAt time.Time, slipNum int, note string) error {
if slipNum <= 0 {
return nil
}
profile, err := s.loadProfile(ctx, uid)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil
}
return err
}
date := normalizeDate(slipAt)
var status quitmodel.DailyStatus
return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
err := tx.WithContext(ctx).Where("uid = ? AND date = ?", uid, date).First(&status).Error
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
return err
}
wasRelapsed := false
if errors.Is(err, gorm.ErrRecordNotFound) {
status = quitmodel.DailyStatus{
UID: uid,
Date: date,
Status: quitmodel.DailyStatusRelapsed,
RelapsedAt: &slipAt,
RelapseNum: slipNum,
Note: strings.TrimSpace(note),
CheckInAt: nil,
}
if e := tx.WithContext(ctx).Create(&status).Error; e != nil {
return e
}
} else {
wasRelapsed = status.Status == quitmodel.DailyStatusRelapsed
status.Status = quitmodel.DailyStatusRelapsed
status.CheckInAt = nil
status.RelapsedAt = &slipAt
// 多次 slip:累加当日 relapse_num,便于 avoided_cigs 统计更接近真实。
status.RelapseNum += slipNum
if strings.TrimSpace(note) != "" && strings.TrimSpace(status.Note) == "" {
status.Note = strings.TrimSpace(note)
}
if e := tx.WithContext(ctx).Save(&status).Error; e != nil {
return e
}
}
event := quitmodel.RelapseEvent{
UID: uid,
Date: date,
RelapseAt: slipAt,
RelapseNum: slipNum,
Reason: "smoke_log",
Note: strings.TrimSpace(note),
AffectStreak: !wasRelapsed,
}
if e := tx.WithContext(ctx).Create(&event).Error; e != nil {
return e
}
// 复吸:每支烟扣 M;当日首次复吸额外惩罚。
perCig := 4
delta := -perCig * maxInt(1, slipNum)
reason := "smoke"
if !wasRelapsed {
delta -= 10
reason = "relapse"
}
if _, err := s.ensureHPInitializedBasicTx(ctx, tx, profile, slipAt); err != nil {
return err
}
return s.applyHPDeltaTx(ctx, tx, profile, delta, reason, "smoke_log", nil, slipAt)
})
}
// StatsOverview 返回统计概览。
func (s *Service) StatsOverview(ctx context.Context, uid int, rangeName string, now time.Time) (StatsOverviewResult, error) {
profile, err := s.loadProfile(ctx, uid)
@@ -596,7 +731,7 @@ func (s *Service) StatsOverview(ctx context.Context, uid int, rangeName string,
trend = append(trend, TrendItemResult{Date: key, Status: item.Status, RelapseNum: item.RelapseNum})
}
summary, _, _, _, err := s.computeSummary(ctx, uid, *profile, now)
summary, _, _, _, err := s.computeSummary(ctx, uid, profile, now)
if err != nil {
return StatsOverviewResult{}, err
}
@@ -626,7 +761,7 @@ func (s *Service) ListBadges(ctx context.Context, uid int, now time.Time) (Badge
return BadgeListResult{}, err
}
summary, _, _, _, err := s.computeSummary(ctx, uid, *profile, now)
summary, _, _, _, err := s.computeSummary(ctx, uid, profile, now)
if err != nil {
return BadgeListResult{}, err
}
@@ -814,7 +949,7 @@ func (s *Service) PosterData(ctx context.Context, uid int, nickname string, temp
return PosterDataResult{}, err
}
summary, _, _, _, err := s.computeSummary(ctx, uid, *profile, now)
summary, _, _, _, err := s.computeSummary(ctx, uid, profile, now)
if err != nil {
return PosterDataResult{}, err
}
@@ -867,6 +1002,151 @@ func (s *Service) loadProfile(ctx context.Context, uid int) (*quitmodel.Profile,
return &profile, nil
}
func (s *Service) ensureHPInitialized(ctx context.Context, profile *quitmodel.Profile, currentStreak int, now time.Time) (int, error) {
if profile.HpCurrent != nil {
return clampHP(*profile.HpCurrent), nil
}
// 迁移/初始化:只依赖 quitcheckin profile 的 baseline + 当前 streak,避免跨模块耦合。
base := 50
if profile.BaselineCigsPerDay > 0 {
base = 60 - profile.BaselineCigsPerDay
}
base = clampInt(base, 20, 60)
initHP := clampHP(base + currentStreak*3)
profile.HpCurrent = &initHP
changeDate := normalizeDate(now)
row := quitmodel.HPChangeLog{
UID: profile.UID,
ChangeDate: changeDate,
ChangeAt: now,
Delta: 0,
HPBefore: initHP,
HPAfter: initHP,
Reason: "migrate_init",
SourceType: "profile",
}
if err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
// 条件更新,避免并发覆盖(nil -> initHP 只做一次)。
if e := tx.WithContext(ctx).Model(&quitmodel.Profile{}).
Where("id = ? AND uid = ? AND hp_current IS NULL", profile.ID, profile.UID).
Updates(map[string]interface{}{"hp_current": initHP}).Error; e != nil {
return e
}
return tx.WithContext(ctx).Create(&row).Error
}); err != nil {
return 0, err
}
return initHP, nil
}
func (s *Service) sumHPChangeByDate(ctx context.Context, uid int, date time.Time) (int, error) {
date = normalizeDate(date)
var sum int64
if err := s.db.WithContext(ctx).
Model(&quitmodel.HPChangeLog{}).
Where("uid = ? AND change_date = ?", uid, date).
Select("COALESCE(SUM(delta), 0)").
Scan(&sum).Error; err != nil {
return 0, err
}
return int(sum), nil
}
func (s *Service) ensureHPInitializedBasicTx(ctx context.Context, tx *gorm.DB, profile *quitmodel.Profile, now time.Time) (int, error) {
if profile.HpCurrent != nil {
return clampHP(*profile.HpCurrent), nil
}
// 基础初始化:不引入 streak(事件触发时先给个合理起点;更准确的迁移会在 computeSummary 中做)。
base := 50
if profile.BaselineCigsPerDay > 0 {
base = 60 - profile.BaselineCigsPerDay
}
base = clampInt(base, 20, 60)
initHP := clampHP(base)
profile.HpCurrent = &initHP
if e := tx.WithContext(ctx).Model(&quitmodel.Profile{}).
Where("id = ? AND uid = ? AND hp_current IS NULL", profile.ID, profile.UID).
Updates(map[string]interface{}{"hp_current": initHP}).Error; e != nil {
return 0, e
}
row := quitmodel.HPChangeLog{
UID: profile.UID,
ChangeDate: normalizeDate(now),
ChangeAt: now,
Delta: 0,
HPBefore: initHP,
HPAfter: initHP,
Reason: "migrate_init",
SourceType: "profile",
}
if e := tx.WithContext(ctx).Create(&row).Error; e != nil {
return 0, e
}
return initHP, nil
}
func (s *Service) applyHPDeltaTx(ctx context.Context, tx *gorm.DB, profile *quitmodel.Profile, delta int, reason string, sourceType string, sourceID *uint, changeAt time.Time) error {
before := 0
if profile.HpCurrent != nil {
before = clampHP(*profile.HpCurrent)
}
after := clampHP(before + delta)
if e := tx.WithContext(ctx).Model(&quitmodel.Profile{}).
Where("id = ? AND uid = ?", profile.ID, profile.UID).
Updates(map[string]interface{}{"hp_current": after}).Error; e != nil {
return e
}
profile.HpCurrent = &after
row := quitmodel.HPChangeLog{
UID: profile.UID,
ChangeDate: normalizeDate(changeAt),
ChangeAt: changeAt,
Delta: after - before,
HPBefore: before,
HPAfter: after,
Reason: strings.TrimSpace(reason),
SourceType: strings.TrimSpace(sourceType),
SourceID: sourceID,
}
return tx.WithContext(ctx).Create(&row).Error
}
func clampHP(v int) int {
return clampInt(v, 0, 100)
}
func clampInt(v, minV, maxV int) int {
if v < minV {
return minV
}
if v > maxV {
return maxV
}
return v
}
func maxInt(a, b int) int {
if a > b {
return a
}
return b
}
func uintPtr(v uint) *uint {
return &v
}
func (s *Service) getOrBuildDailyStatus(ctx context.Context, uid int, date, now time.Time) (quitmodel.DailyStatus, error) {
var status quitmodel.DailyStatus
err := s.db.WithContext(ctx).Where("uid = ? AND date = ?", uid, date).First(&status).Error
@@ -902,14 +1182,14 @@ func (s *Service) currentSavedMoney(ctx context.Context, uid int, now time.Time)
}
return 0, err
}
summary, _, _, _, err := s.computeSummary(ctx, uid, *profile, now)
summary, _, _, _, err := s.computeSummary(ctx, uid, profile, now)
if err != nil {
return 0, err
}
return summary.SavedMoneyCent, nil
}
func (s *Service) computeSummary(ctx context.Context, uid int, profile quitmodel.Profile, now time.Time) (SummaryResult, *string, *string, int, error) {
func (s *Service) computeSummary(ctx context.Context, uid int, profile *quitmodel.Profile, now time.Time) (SummaryResult, *string, *string, int, error) {
today := normalizeDate(now)
var statuses []quitmodel.DailyStatus
@@ -1007,6 +1287,15 @@ func (s *Service) computeSummary(ctx context.Context, uid int, profile quitmodel
}
}
hpCurrent, err := s.ensureHPInitialized(ctx, profile, currentStreak, now)
if err != nil {
return SummaryResult{}, nil, nil, 0, err
}
hpChangeToday, err := s.sumHPChangeByDate(ctx, uid, today)
if err != nil {
return SummaryResult{}, nil, nil, 0, err
}
return SummaryResult{
CurrentStreakDays: currentStreak,
MaxStreakDays: maxStreak,
@@ -1016,6 +1305,8 @@ func (s *Service) computeSummary(ctx context.Context, uid int, profile quitmodel
AvoidedCigs: avoidedCigs,
AvoidedCigsMode: "exact",
HealthRecoveryPercent: healthPercent,
HPCurrent: hpCurrent,
HPChangeToday: hpChangeToday,
}, lastCheckin, lastRelapse, unlockedCount, nil
}
+274
View File
@@ -0,0 +1,274 @@
package service
import (
"context"
"crypto/rand"
"encoding/base32"
"errors"
"fmt"
"strings"
"time"
usermodel "wx_service/internal/model"
quitmodel "wx_service/internal/quitcheckin/model"
"gorm.io/gorm"
)
type SupervisorInviteResult struct {
Token string `json:"token"`
ExpireAt string `json:"expire_at"`
}
type SupervisorOwnerSummary struct {
Owner userSummary `json:"owner"`
Home HomeResult `json:"home"`
}
type userSummary struct {
UserID int `json:"user_id"`
Nickname string `json:"nickname,omitempty"`
AvatarURL string `json:"avatar_url,omitempty"`
}
type SupervisorOverviewResult struct {
Items []SupervisorOwnerSummary `json:"items"`
}
type SupervisorStatusResult struct {
Items []userSummary `json:"items"`
}
var (
ErrInviteNotFound = errors.New("邀请不存在")
ErrInviteExpired = errors.New("邀请已过期")
ErrInviteUsed = errors.New("邀请已被使用")
ErrCannotBindSelf = errors.New("不能绑定自己为监督人")
ErrBindingExists = errors.New("监督关系已存在")
ErrBindingNotFound = errors.New("监督关系不存在")
ErrSupervisorLimitReached = errors.New("监督人已达上限")
)
const maxSupervisorsPerOwner = 3
func (s *Service) CreateSupervisorInvite(ctx context.Context, ownerUID int, now time.Time, days int) (SupervisorInviteResult, error) {
if days <= 0 {
days = 7
}
if days > 30 {
days = 30
}
token := newInviteToken()
expireAt := now.Add(time.Duration(days) * 24 * time.Hour)
row := quitmodel.SupervisorInvite{
OwnerUID: ownerUID,
Token: token,
ExpireAt: expireAt,
UsedAt: nil,
UsedByUID: nil,
}
if err := s.db.WithContext(ctx).Create(&row).Error; err != nil {
return SupervisorInviteResult{}, fmt.Errorf("create invite: %w", err)
}
return SupervisorInviteResult{
Token: token,
ExpireAt: expireAt.Format(time.RFC3339),
}, nil
}
func (s *Service) BindSupervisorInvite(ctx context.Context, supervisorUID int, token string, now time.Time) error {
token = strings.TrimSpace(token)
if token == "" {
return ErrInviteNotFound
}
return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
var invite quitmodel.SupervisorInvite
if err := tx.WithContext(ctx).Where("token = ?", token).First(&invite).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return ErrInviteNotFound
}
return err
}
if invite.UsedAt != nil || invite.UsedByUID != nil {
return ErrInviteUsed
}
if now.After(invite.ExpireAt) {
return ErrInviteExpired
}
if invite.OwnerUID == supervisorUID {
return ErrCannotBindSelf
}
// 检查是否已存在绑定
var existing quitmodel.SupervisorBinding
err := tx.WithContext(ctx).
Where("owner_uid = ? AND supervisor_uid = ? AND status = ?", invite.OwnerUID, supervisorUID, "active").
First(&existing).Error
if err == nil {
return ErrBindingExists
}
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
return err
}
// 多人监督:允许多个 supervisor,但限制最多 3 个 active supervisor。
var activeCount int64
if err := tx.WithContext(ctx).
Model(&quitmodel.SupervisorBinding{}).
Where("owner_uid = ? AND status = ?", invite.OwnerUID, "active").
Count(&activeCount).Error; err != nil {
return err
}
if activeCount >= maxSupervisorsPerOwner {
return ErrSupervisorLimitReached
}
binding := quitmodel.SupervisorBinding{
OwnerUID: invite.OwnerUID,
SupervisorUID: supervisorUID,
Status: "active",
}
if err := tx.WithContext(ctx).Create(&binding).Error; err != nil {
return err
}
usedAt := now
usedBy := supervisorUID
if err := tx.WithContext(ctx).Model(&quitmodel.SupervisorInvite{}).
Where("id = ? AND used_at IS NULL AND used_by_uid IS NULL", invite.ID).
Updates(map[string]interface{}{
"used_at": &usedAt,
"used_by_uid": &usedBy,
}).Error; err != nil {
return err
}
return nil
})
}
func (s *Service) GetSupervisorOverview(ctx context.Context, supervisorUID int, now time.Time) (SupervisorOverviewResult, error) {
var bindings []quitmodel.SupervisorBinding
if err := s.db.WithContext(ctx).
Where("supervisor_uid = ? AND status = ?", supervisorUID, "active").
Order("id DESC").
Find(&bindings).Error; err != nil {
return SupervisorOverviewResult{}, err
}
if len(bindings) == 0 {
return SupervisorOverviewResult{Items: []SupervisorOwnerSummary{}}, nil
}
ownerIDs := make([]int, 0, len(bindings))
for _, b := range bindings {
ownerIDs = append(ownerIDs, b.OwnerUID)
}
// 拉用户昵称/头像(非强依赖:缺失不影响)
userMap := make(map[int]userSummary, len(ownerIDs))
var users []usermodel.User
_ = s.db.WithContext(ctx).Where("id IN ?", ownerIDs).Find(&users).Error
for _, u := range users {
userMap[int(u.ID)] = userSummary{
UserID: int(u.ID),
Nickname: u.NickName,
AvatarURL: u.AvatarURL,
}
}
items := make([]SupervisorOwnerSummary, 0, len(bindings))
for _, b := range bindings {
owner := userMap[b.OwnerUID]
if owner.UserID == 0 {
owner = userSummary{UserID: b.OwnerUID}
}
// 只读概览:复用 Home(内部包含 summary + 今日状态)
home, err := s.Home(ctx, b.OwnerUID, now)
if err != nil {
// 对单个 owner 的失败做降级,不影响其他人的展示
continue
}
// 权限边界:监督视图只展示必要字段,避免泄露备注/梦想目标等更私密的信息。
home.DailyStatus.Note = nil
home.Goal = nil
items = append(items, SupervisorOwnerSummary{
Owner: owner,
Home: home,
})
}
return SupervisorOverviewResult{Items: items}, nil
}
func (s *Service) GetSupervisorStatus(ctx context.Context, ownerUID int) (SupervisorStatusResult, error) {
var bindings []quitmodel.SupervisorBinding
if err := s.db.WithContext(ctx).
Where("owner_uid = ? AND status = ?", ownerUID, "active").
Order("id DESC").
Find(&bindings).Error; err != nil {
return SupervisorStatusResult{}, err
}
if len(bindings) == 0 {
return SupervisorStatusResult{Items: []userSummary{}}, nil
}
supervisorIDs := make([]int, 0, len(bindings))
for _, b := range bindings {
supervisorIDs = append(supervisorIDs, b.SupervisorUID)
}
var users []usermodel.User
if err := s.db.WithContext(ctx).Where("id IN ?", supervisorIDs).Find(&users).Error; err != nil {
return SupervisorStatusResult{}, err
}
items := make([]userSummary, 0, len(users))
for _, u := range users {
items = append(items, userSummary{
UserID: int(u.ID),
Nickname: u.NickName,
AvatarURL: u.AvatarURL,
})
}
return SupervisorStatusResult{Items: items}, nil
}
// RevokeSupervisorBinding 解除监督关系(owner 或 supervisor 任一方均可解除)。
func (s *Service) RevokeSupervisorBinding(ctx context.Context, actorUID int, ownerUID int, supervisorUID int, now time.Time) error {
if ownerUID <= 0 || supervisorUID <= 0 {
return ErrBindingNotFound
}
if actorUID != ownerUID && actorUID != supervisorUID {
return ErrBindingNotFound
}
result := s.db.WithContext(ctx).
Model(&quitmodel.SupervisorBinding{}).
Where("owner_uid = ? AND supervisor_uid = ? AND status = ?", ownerUID, supervisorUID, "active").
Updates(map[string]interface{}{
"status": "revoked",
"updated_at": now,
})
if result.Error != nil {
return result.Error
}
if result.RowsAffected == 0 {
return ErrBindingNotFound
}
return nil
}
func newInviteToken() string {
// 80-bit random -> base32 -> ~16 chars, URL safe-ish, upper-case; unify to lower for nicer display.
buf := make([]byte, 10)
_, _ = rand.Read(buf)
enc := base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(buf)
return strings.ToLower(enc)
}
@@ -0,0 +1,204 @@
package service
import (
"context"
"errors"
"testing"
"time"
usermodel "wx_service/internal/model"
quitmodel "wx_service/internal/quitcheckin/model"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
func setupSupervisorTestDB(t *testing.T) *gorm.DB {
t.Helper()
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{
Logger: logger.Default.LogMode(logger.Silent),
})
if err != nil {
t.Fatalf("open sqlite: %v", err)
}
if err := db.AutoMigrate(
&usermodel.User{},
&quitmodel.Profile{},
&quitmodel.DailyStatus{},
&quitmodel.RelapseEvent{},
&quitmodel.HPChangeLog{},
&quitmodel.SupervisorInvite{},
&quitmodel.SupervisorBinding{},
&quitmodel.RewardGoal{},
&quitmodel.DreamPreset{},
); err != nil {
t.Fatalf("auto migrate: %v", err)
}
return db
}
func TestSupervisorInviteBindAndOverview(t *testing.T) {
t.Parallel()
db := setupSupervisorTestDB(t)
svc := NewService(db)
ctx := context.Background()
ownerUID := 3001
supervisorUID := 3002
now := time.Date(2026, 4, 16, 10, 0, 0, 0, time.Local)
if err := db.Create(&usermodel.User{ID: uint(ownerUID), NickName: "owner"}).Error; err != nil {
t.Fatalf("seed owner user: %v", err)
}
if err := db.Create(&usermodel.User{ID: uint(supervisorUID), NickName: "supervisor"}).Error; err != nil {
t.Fatalf("seed supervisor user: %v", err)
}
startDate := time.Date(2026, 4, 10, 0, 0, 0, 0, time.Local)
if _, err := svc.UpsertProfile(ctx, ownerUID, UpsertProfileRequest{
QuitStartDate: &startDate,
PackPriceCent: intPtr(2500),
BaselineCigsPerDay: intPtr(10),
}, "owner", "", now); err != nil {
t.Fatalf("upsert profile: %v", err)
}
invite, err := svc.CreateSupervisorInvite(ctx, ownerUID, now, 7)
if err != nil {
t.Fatalf("create invite: %v", err)
}
if invite.Token == "" {
t.Fatalf("invite token empty")
}
if err := svc.BindSupervisorInvite(ctx, supervisorUID, invite.Token, now); err != nil {
t.Fatalf("bind: %v", err)
}
overview, err := svc.GetSupervisorOverview(ctx, supervisorUID, now)
if err != nil {
t.Fatalf("overview: %v", err)
}
if len(overview.Items) != 1 {
t.Fatalf("overview items=%d, want=1", len(overview.Items))
}
if overview.Items[0].Owner.UserID != ownerUID {
t.Fatalf("owner uid=%d, want=%d", overview.Items[0].Owner.UserID, ownerUID)
}
if overview.Items[0].Home.Summary.HPCurrent <= 0 {
t.Fatalf("hp_current=%d, want > 0", overview.Items[0].Home.Summary.HPCurrent)
}
status, err := svc.GetSupervisorStatus(ctx, ownerUID)
if err != nil {
t.Fatalf("status: %v", err)
}
if len(status.Items) != 1 || status.Items[0].UserID != supervisorUID {
t.Fatalf("status=%v, want one supervisor uid=%d", status.Items, supervisorUID)
}
}
func TestSupervisorRevokeBindingBySupervisor(t *testing.T) {
t.Parallel()
db := setupSupervisorTestDB(t)
svc := NewService(db)
ctx := context.Background()
ownerUID := 3101
supervisorUID := 3102
now := time.Date(2026, 4, 16, 10, 0, 0, 0, time.Local)
if err := db.Create(&usermodel.User{ID: uint(ownerUID), NickName: "owner"}).Error; err != nil {
t.Fatalf("seed owner user: %v", err)
}
if err := db.Create(&usermodel.User{ID: uint(supervisorUID), NickName: "supervisor"}).Error; err != nil {
t.Fatalf("seed supervisor user: %v", err)
}
startDate := time.Date(2026, 4, 10, 0, 0, 0, 0, time.Local)
if _, err := svc.UpsertProfile(ctx, ownerUID, UpsertProfileRequest{
QuitStartDate: &startDate,
PackPriceCent: intPtr(2500),
BaselineCigsPerDay: intPtr(10),
}, "owner", "", now); err != nil {
t.Fatalf("upsert profile: %v", err)
}
invite, err := svc.CreateSupervisorInvite(ctx, ownerUID, now, 7)
if err != nil {
t.Fatalf("create invite: %v", err)
}
if err := svc.BindSupervisorInvite(ctx, supervisorUID, invite.Token, now); err != nil {
t.Fatalf("bind: %v", err)
}
if err := svc.RevokeSupervisorBinding(ctx, supervisorUID, ownerUID, supervisorUID, now); err != nil {
t.Fatalf("revoke by supervisor: %v", err)
}
overview, err := svc.GetSupervisorOverview(ctx, supervisorUID, now)
if err != nil {
t.Fatalf("overview: %v", err)
}
if len(overview.Items) != 0 {
t.Fatalf("overview items=%d, want=0 after revoke", len(overview.Items))
}
}
func TestSupervisorBindRespectsMaxSupervisors(t *testing.T) {
t.Parallel()
db := setupSupervisorTestDB(t)
svc := NewService(db)
ctx := context.Background()
ownerUID := 3201
now := time.Date(2026, 4, 16, 10, 0, 0, 0, time.Local)
if err := db.Create(&usermodel.User{ID: uint(ownerUID), NickName: "owner"}).Error; err != nil {
t.Fatalf("seed owner user: %v", err)
}
startDate := time.Date(2026, 4, 10, 0, 0, 0, 0, time.Local)
if _, err := svc.UpsertProfile(ctx, ownerUID, UpsertProfileRequest{
QuitStartDate: &startDate,
PackPriceCent: intPtr(2500),
BaselineCigsPerDay: intPtr(10),
}, "owner", "", now); err != nil {
t.Fatalf("upsert profile: %v", err)
}
for i := 0; i < 3; i++ {
supervisorUID := 3300 + i
if err := db.Create(&usermodel.User{ID: uint(supervisorUID), NickName: "s"}).Error; err != nil {
t.Fatalf("seed supervisor user: %v", err)
}
invite, err := svc.CreateSupervisorInvite(ctx, ownerUID, now, 7)
if err != nil {
t.Fatalf("create invite: %v", err)
}
if err := svc.BindSupervisorInvite(ctx, supervisorUID, invite.Token, now); err != nil {
t.Fatalf("bind #%d: %v", i+1, err)
}
}
supervisorUID := 3399
if err := db.Create(&usermodel.User{ID: uint(supervisorUID), NickName: "s4"}).Error; err != nil {
t.Fatalf("seed supervisor user: %v", err)
}
invite, err := svc.CreateSupervisorInvite(ctx, ownerUID, now, 7)
if err != nil {
t.Fatalf("create invite: %v", err)
}
if err := svc.BindSupervisorInvite(ctx, supervisorUID, invite.Token, now); err == nil {
t.Fatalf("bind #4 should fail")
} else if !errors.Is(err, ErrSupervisorLimitReached) {
t.Fatalf("bind #4 err=%v, want ErrSupervisorLimitReached", err)
}
}
+9
View File
@@ -17,6 +17,15 @@ func registerQuitCheckinRoutes(protected *gin.RouterGroup, handler *quitcheckinh
v2.POST("/checkin/check", handler.Checkin)
v2.POST("/checkin/relapse", handler.Relapse)
v2.POST("/supervisor/invites", handler.CreateSupervisorInvite)
v2.POST("/supervisor/bind", handler.BindSupervisorInvite)
v2.POST("/supervisor/revoke", handler.RevokeSupervisorBinding)
v2.GET("/supervisor/overview", handler.GetSupervisorOverview)
v2.GET("/supervisor/status", handler.GetSupervisorStatus)
v2.GET("/supervisor/reminders/settings", handler.GetReminderSettings)
v2.PUT("/supervisor/reminders/settings", handler.UpdateReminderSettings)
v2.POST("/supervisor/reminders/run", handler.RunReminders)
v2.GET("/stats/overview", handler.StatsOverview)
v2.GET("/badges", handler.ListBadges)
v2.GET("/relapses", handler.ListRelapses)
+46 -22
View File
@@ -3,6 +3,7 @@ package handler
import (
"errors"
"io"
"log"
"net/http"
"strconv"
"strings"
@@ -14,6 +15,7 @@ import (
"wx_service/internal/middleware"
"wx_service/internal/model"
quitcheckinservice "wx_service/internal/quitcheckin/service"
smokemodel "wx_service/internal/smoke/model"
smokeservice "wx_service/internal/smoke/service"
)
@@ -58,10 +60,11 @@ type createSmokeLogRequest struct {
// 只记录“日期”即可;如果不传,后端会按当天处理
SmokeTime string `json:"smoke_time"`
// 真实抽烟时间(精确到时分秒,可补录)
SmokeAt string `json:"smoke_at"`
Remark string `json:"remark"`
Level *int64 `json:"level"`
Num *int `json:"num"`
SmokeAt string `json:"smoke_at"`
Remark string `json:"remark"`
ReasonTags smokemodel.StringSlice `json:"reason_tags"`
Level *int64 `json:"level"`
Num *int `json:"num"`
}
func (h *SmokeHandler) Create(c *gin.Context) {
@@ -120,24 +123,42 @@ func (h *SmokeHandler) Create(c *gin.Context) {
}
record, err := h.smokeLogService.Create(c.Request.Context(), int(user.ID), smokeservice.CreateSmokeLogRequest{
SmokeTime: smokeTime,
SmokeAt: smokeAt,
Remark: req.Remark,
Level: level,
Num: num,
SmokeTime: smokeTime,
SmokeAt: smokeAt,
Remark: req.Remark,
ReasonTags: req.ReasonTags,
Level: level,
Num: num,
})
if err != nil {
c.JSON(http.StatusInternalServerError, model.Error(http.StatusInternalServerError, "创建记录失败,请稍后重试"))
return
}
// quit 模式下:把“抽烟记录”视作一次 slip/复吸,同步到 quitcheckin(扣 HP + 标记当日 relapsed)。
// 这一步失败不影响主流程(记录仍应成功写入 smoke_log)。
if record != nil && record.Num > 0 {
if profile, e := h.smokeProfileService.Get(c.Request.Context(), int(user.ID)); e == nil && profile != nil {
if strings.TrimSpace(strings.ToLower(profile.Mode)) == "quit" {
slipAt := time.Now().In(time.Local)
if record.SmokeAt != nil {
slipAt = record.SmokeAt.In(time.Local)
}
if e := h.quitCheckinService.RecordSmokeSlip(c.Request.Context(), int(user.ID), slipAt, record.Num, record.Remark); e != nil {
log.Printf("[smoke_create] sync quitcheckin slip degraded uid=%d err=%v", user.ID, e)
}
}
}
}
c.JSON(http.StatusOK, model.Success(record))
}
type resistedSmokeLogRequest struct {
SmokeTime string `json:"smoke_time"`
SmokeAt string `json:"smoke_at"`
Remark string `json:"remark"`
SmokeTime string `json:"smoke_time"`
SmokeAt string `json:"smoke_at"`
Remark string `json:"remark"`
ReasonTags smokemodel.StringSlice `json:"reason_tags"`
}
// Resist 表示“想抽但忍住了”:在 fa_smoke_log 中写入 level=0,num=0。
@@ -171,11 +192,12 @@ func (h *SmokeHandler) Resist(c *gin.Context) {
}
record, err := h.smokeLogService.Create(c.Request.Context(), int(user.ID), smokeservice.CreateSmokeLogRequest{
SmokeTime: smokeTime,
SmokeAt: smokeAt,
Remark: req.Remark,
Level: 0,
Num: 0,
SmokeTime: smokeTime,
SmokeAt: smokeAt,
Remark: req.Remark,
ReasonTags: req.ReasonTags,
Level: 0,
Num: 0,
})
if err != nil {
c.JSON(http.StatusInternalServerError, model.Error(http.StatusInternalServerError, "创建记录失败,请稍后重试"))
@@ -331,11 +353,12 @@ func (h *SmokeHandler) LatestLogs(c *gin.Context) {
}
type updateSmokeLogRequest struct {
SmokeTime *string `json:"smoke_time"`
SmokeAt *string `json:"smoke_at"`
Remark *string `json:"remark"`
Level *int64 `json:"level"`
Num *int `json:"num"`
SmokeTime *string `json:"smoke_time"`
SmokeAt *string `json:"smoke_at"`
Remark *string `json:"remark"`
ReasonTags *smokemodel.StringSlice `json:"reason_tags"`
Level *int64 `json:"level"`
Num *int `json:"num"`
}
func (h *SmokeHandler) Update(c *gin.Context) {
@@ -402,6 +425,7 @@ func (h *SmokeHandler) Update(c *gin.Context) {
SmokeAtProvided: smokeAtProvided,
SmokeAt: smokeAt,
Remark: req.Remark,
ReasonTags: req.ReasonTags,
Level: req.Level,
Num: req.Num,
})
+2 -1
View File
@@ -16,7 +16,8 @@ type SmokeLog struct {
// smoke_at:真实抽烟时间(可补录,精确到时分秒)
SmokeAt *time.Time `gorm:"column:smoke_at;type:datetime;comment:真实抽烟时间(精确到秒)" json:"smoke_at,omitempty"`
Remark string `gorm:"column:remark;type:text;comment:原因/备注" json:"remark,omitempty"`
Remark string `gorm:"column:remark;type:text;comment:原因/备注" json:"remark,omitempty"`
ReasonTags StringSlice `gorm:"column:reason_tags;type:json;comment:结构化原因标签(JSON数组)" json:"reason_tags,omitempty"`
// createtime/updatetime/deletetime:秒级 Unix 时间戳(与 gorm 默认字段不同)
CreateTime *int64 `gorm:"column:createtime;comment:创建时间(秒)" json:"createtime,omitempty"`
+24 -16
View File
@@ -21,16 +21,17 @@ type SmokeLogService struct {
// smokeLogCreateRow 用于写入 fa_smoke_log,避免 SmokeLog 的 default 标签覆盖 0 值。
type smokeLogCreateRow struct {
ID int `gorm:"column:id;primaryKey;autoIncrement"`
UID int `gorm:"column:uid"`
SmokeTime *time.Time `gorm:"column:smoke_time"`
SmokeAt *time.Time `gorm:"column:smoke_at"`
Remark string `gorm:"column:remark"`
CreateTime *int64 `gorm:"column:createtime"`
UpdateTime *int64 `gorm:"column:updatetime"`
DeleteTime *int64 `gorm:"column:deletetime"`
Level *int64 `gorm:"column:level"`
Num *int `gorm:"column:num"`
ID int `gorm:"column:id;primaryKey;autoIncrement"`
UID int `gorm:"column:uid"`
SmokeTime *time.Time `gorm:"column:smoke_time"`
SmokeAt *time.Time `gorm:"column:smoke_at"`
Remark string `gorm:"column:remark"`
ReasonTags smokemodel.StringSlice `gorm:"column:reason_tags"`
CreateTime *int64 `gorm:"column:createtime"`
UpdateTime *int64 `gorm:"column:updatetime"`
DeleteTime *int64 `gorm:"column:deletetime"`
Level *int64 `gorm:"column:level"`
Num *int `gorm:"column:num"`
}
func (smokeLogCreateRow) TableName() string {
@@ -42,11 +43,12 @@ func NewSmokeLogService(db *gorm.DB) *SmokeLogService {
}
type CreateSmokeLogRequest struct {
SmokeTime *time.Time
SmokeAt *time.Time
Remark string
Level int64
Num int
SmokeTime *time.Time
SmokeAt *time.Time
Remark string
ReasonTags smokemodel.StringSlice
Level int64
Num int
}
func (s *SmokeLogService) Create(ctx context.Context, uid int, req CreateSmokeLogRequest) (*smokemodel.SmokeLog, error) {
@@ -82,6 +84,7 @@ func (s *SmokeLogService) Create(ctx context.Context, uid int, req CreateSmokeLo
SmokeTime: smokeTime,
SmokeAt: smokeAt,
Remark: req.Remark,
ReasonTags: req.ReasonTags,
CreateTime: &createTime,
UpdateTime: &updateTime,
Level: &level,
@@ -98,6 +101,7 @@ func (s *SmokeLogService) Create(ctx context.Context, uid int, req CreateSmokeLo
SmokeTime: insert.SmokeTime,
SmokeAt: insert.SmokeAt,
Remark: insert.Remark,
ReasonTags: insert.ReasonTags,
CreateTime: insert.CreateTime,
UpdateTime: insert.UpdateTime,
DeleteTime: insert.DeleteTime,
@@ -393,7 +397,7 @@ func (s *SmokeLogService) ListLatest(ctx context.Context, uid int, limit int) ([
var items []smokemodel.SmokeLog
if err := s.db.WithContext(ctx).
Model(&smokemodel.SmokeLog{}).
Select("id, uid, smoke_time, smoke_at, remark, level, num, createtime, updatetime, deletetime").
Select("id, uid, smoke_time, smoke_at, remark, reason_tags, level, num, createtime, updatetime, deletetime").
Where("uid = ? AND (deletetime IS NULL OR deletetime = 0)", uid).
Order("COALESCE(smoke_at, FROM_UNIXTIME(createtime), smoke_time) DESC").
Order("id DESC").
@@ -431,6 +435,7 @@ type UpdateSmokeLogRequest struct {
SmokeAtProvided bool
SmokeAt *time.Time
Remark *string
ReasonTags *smokemodel.StringSlice
Level *int64
Num *int
}
@@ -455,6 +460,9 @@ func (s *SmokeLogService) Update(ctx context.Context, uid int, id int, req Updat
if req.Remark != nil {
updates["remark"] = *req.Remark
}
if req.ReasonTags != nil {
updates["reason_tags"] = *req.ReasonTags
}
if req.Level != nil {
if *req.Level < 0 {
updates["level"] = int64(1)
@@ -29,6 +29,7 @@ CREATE TABLE fa_smoke_log (
smoke_time DATE NULL,
smoke_at DATETIME NULL,
remark TEXT,
reason_tags TEXT,
createtime INTEGER,
updatetime INTEGER,
deletetime INTEGER,
@@ -68,3 +69,60 @@ func TestSmokeLogServiceCreateKeepsZeroForResisted(t *testing.T) {
}
}
func TestSmokeLogServiceCreatePersistsReasonTags(t *testing.T) {
t.Parallel()
db := setupSmokeLogServiceTestDB(t)
svc := NewSmokeLogService(db)
smokeAt := time.Date(2026, 3, 4, 8, 30, 0, 0, time.Local)
_, err := svc.Create(context.Background(), 1002, CreateSmokeLogRequest{
SmokeAt: &smokeAt,
Remark: "压力大;会后补了一根",
ReasonTags: smokemodel.StringSlice{"stress", "social"},
Level: 3,
Num: 1,
})
if err != nil {
t.Fatalf("create log with reason tags: %v", err)
}
var got smokemodel.SmokeLog
if err := db.Where("uid = ?", 1002).Order("id DESC").First(&got).Error; err != nil {
t.Fatalf("load created record: %v", err)
}
if len(got.ReasonTags) != 2 || got.ReasonTags[0] != "stress" || got.ReasonTags[1] != "social" {
t.Fatalf("created reason_tags=%v, want=[stress social]", got.ReasonTags)
}
}
func TestSmokeLogServiceUpdatePersistsReasonTags(t *testing.T) {
t.Parallel()
db := setupSmokeLogServiceTestDB(t)
svc := NewSmokeLogService(db)
smokeAt := time.Date(2026, 3, 4, 9, 0, 0, 0, time.Local)
record, err := svc.Create(context.Background(), 1003, CreateSmokeLogRequest{
SmokeAt: &smokeAt,
Remark: "old",
Level: 2,
Num: 1,
})
if err != nil {
t.Fatalf("create seed log: %v", err)
}
reasonTags := smokemodel.StringSlice{"after_meal", "other"}
updated, err := svc.Update(context.Background(), 1003, record.ID, UpdateSmokeLogRequest{
ReasonTags: &reasonTags,
})
if err != nil {
t.Fatalf("update reason_tags: %v", err)
}
if len(updated.ReasonTags) != 2 || updated.ReasonTags[0] != "after_meal" || updated.ReasonTags[1] != "other" {
t.Fatalf("updated reason_tags=%v, want=[after_meal other]", updated.ReasonTags)
}
}