Compare commits
14 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f701feebe8 | |||
| 50352d67ca | |||
| 6cd6424561 | |||
| 55d84576f3 | |||
| 0eaf3a206a | |||
| a32ec911a1 | |||
| 6e0a06cfcf | |||
| 411ded8a0c | |||
| a6f0bfd4e8 | |||
| fd097729d7 | |||
| 1c0aeb152a | |||
| b4170b4863 | |||
| 1eab1b99c1 | |||
| aeaf6a04c2 |
+16
-16
@@ -46,25 +46,25 @@ ADMIN_API_TOKEN=replace-with-strong-random-token
|
||||
ADMIN_DEFAULT_USERNAME=admin
|
||||
ADMIN_DEFAULT_PASSWORD=admin123
|
||||
|
||||
# 七牛直传配置(Kodo)
|
||||
QINIU_ACCESS_KEY=replace-with-access-key
|
||||
QINIU_SECRET_KEY=replace-with-secret-key
|
||||
QINIU_BUCKET=replace-with-bucket
|
||||
# 上传地址:可保持默认(自动调度),也可以配置具体 Region 的 up 域名
|
||||
QINIU_UPLOAD_URL=https://upload.qiniup.com
|
||||
# CDN 域名(可选):用于拼接最终访问地址,例如 https://cdn.example.com
|
||||
QINIU_CDN_DOMAIN=
|
||||
# 阿里云 OSS 直传配置
|
||||
OSS_ACCESS_KEY=replace-with-access-key
|
||||
OSS_SECRET_KEY=replace-with-secret-key
|
||||
OSS_BUCKET=replace-with-bucket
|
||||
# 上传地址(可选):OSS 时自动根据 endpoint 计算,留空即可
|
||||
OSS_UPLOAD_URL=
|
||||
# CDN 域名:阿里云 OSS endpoint,例如 oss-cn-beijing.aliyuncs.com
|
||||
OSS_CDN_DOMAIN=
|
||||
# 上传 key 前缀(可选)
|
||||
QINIU_KEY_PREFIX=uploads/
|
||||
# token 有效期(秒)
|
||||
QINIU_TOKEN_EXPIRE_SECONDS=300
|
||||
# 上传回调地址(可选):配置后,七牛上传成功会回调该地址
|
||||
# 示例: https://api.example.com/api/v1/common/upload/qiniu/callback
|
||||
QINIU_CALLBACK_URL=
|
||||
OSS_KEY_PREFIX=uploads/
|
||||
# 凭证有效期(秒)
|
||||
OSS_TOKEN_EXPIRE_SECONDS=300
|
||||
# 上传回调地址(可选):上传成功后回调该地址
|
||||
# 示例: https://api.example.com/api/v1/common/upload/oss/callback
|
||||
OSS_CALLBACK_URL=
|
||||
# 回调内容模板(可选)
|
||||
QINIU_CALLBACK_BODY=key=$(key)&hash=$(etag)&fsize=$(fsize)&mimeType=$(mimeType)
|
||||
OSS_CALLBACK_BODY=key=$(key)&hash=$(etag)&fsize=$(fsize)&mimeType=$(mimeType)
|
||||
# 回调内容类型(可选)
|
||||
QINIU_CALLBACK_BODY_TYPE=application/x-www-form-urlencoded
|
||||
OSS_CALLBACK_BODY_TYPE=application/x-www-form-urlencoded
|
||||
|
||||
# 微信公众号(网页授权 OAuth2)
|
||||
WECHAT_OA_APP_ID=replace-with-oa-appid
|
||||
|
||||
@@ -36,3 +36,4 @@ go.work
|
||||
# Local build binary
|
||||
wx_service
|
||||
wx_service_api
|
||||
/api
|
||||
|
||||
+28
-6
@@ -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"
|
||||
qiniuhandler "wx_service/internal/common/qiniu/handler"
|
||||
qiniuservice "wx_service/internal/common/qiniu/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"
|
||||
@@ -82,10 +83,20 @@ func main() {
|
||||
&marketingmodel.MarketingCategory{},
|
||||
&marketingmodel.MarketingTemplate{},
|
||||
&marketingmodel.MarketingDownload{},
|
||||
&marketingmodel.UserLogo{},
|
||||
&marketingmodel.AdPlacement{},
|
||||
&quitcheckinmodel.Profile{},
|
||||
&quitcheckinmodel.DailyStatus{},
|
||||
&quitcheckinmodel.RelapseEvent{},
|
||||
&quitcheckinmodel.HPChangeLog{},
|
||||
&quitcheckinmodel.SupervisorInvite{},
|
||||
&quitcheckinmodel.SupervisorBinding{},
|
||||
&quitcheckinmodel.SupervisorReminderSetting{},
|
||||
&quitcheckinmodel.SupervisorReminderLog{},
|
||||
&quitcheckinmodel.RewardGoal{},
|
||||
&quitcheckinmodel.DreamPreset{},
|
||||
&achievement.Theme{},
|
||||
&achievement.Level{},
|
||||
); err != nil {
|
||||
log.Fatalf("auto migrate failed: %v", err)
|
||||
}
|
||||
@@ -115,16 +126,20 @@ func main() {
|
||||
smokeAINextService := smokeservice.NewSmokeAINextSmokeService(database.DB, config.AppConfig.AI)
|
||||
smokeShareService := smokeservice.NewSmokeShareService(database.DB)
|
||||
smokeQuitPlanService := smokeservice.NewSmokeQuitPlanService(database.DB, config.AppConfig.AI)
|
||||
smokeHandler := smokehandler.NewSmokeHandler(smokeLogService, smokeAIAdviceService, smokeProfileService, smokeNextService, smokeAINextService, smokeShareService)
|
||||
quitPlanHandler := smokehandler.NewQuitPlanHandler(smokeQuitPlanService)
|
||||
achievementService := achievement.NewService(database.DB)
|
||||
if err := achievementService.SeedDefaults(context.Background()); err != nil {
|
||||
log.Printf("seed achievement defaults: %v", err)
|
||||
}
|
||||
quitCheckinService := quitcheckinservice.NewService(database.DB)
|
||||
smokeHandler := smokehandler.NewSmokeHandler(smokeLogService, smokeAIAdviceService, smokeProfileService, smokeNextService, smokeAINextService, smokeShareService, achievementService, quitCheckinService)
|
||||
quitPlanHandler := smokehandler.NewQuitPlanHandler(smokeQuitPlanService)
|
||||
quitCheckinHandler := quitcheckinhandler.NewHandler(quitCheckinService)
|
||||
|
||||
redeemCodeService := membershipservice.NewRedeemCodeService(database.DB, config.AppConfig.Admin.Token)
|
||||
redeemCodeHandler := membershiphandler.NewRedeemCodeHandler(redeemCodeService)
|
||||
|
||||
qiniuService := qiniuservice.NewQiniuService(config.AppConfig.Qiniu)
|
||||
uploadHandler := qiniuhandler.NewUploadHandler(qiniuService)
|
||||
uploadSvc := uploadservice.NewUploadService(config.AppConfig.OSS)
|
||||
uploadHandler := uploadhandler.NewUploadHandler(uploadSvc)
|
||||
|
||||
oaService := oaservice.NewWeChatOAService(config.AppConfig.WeChatOA)
|
||||
oaOAuthHandler := oahandler.NewOAuthHandler(oaService)
|
||||
@@ -156,12 +171,17 @@ func main() {
|
||||
categoryRepo := marketingrepo.NewCategoryRepository(database.DB)
|
||||
templateRepo := marketingrepo.NewTemplateRepository(database.DB)
|
||||
downloadRepo := marketingrepo.NewDownloadRepository(database.DB)
|
||||
userLogoRepo := marketingrepo.NewUserLogoRepository(database.DB)
|
||||
categorySvc := marketingservice.NewCategoryService(categoryRepo)
|
||||
templateSvc := marketingservice.NewTemplateService(templateRepo)
|
||||
downloadSvc := marketingservice.NewDownloadService(downloadRepo, templateRepo)
|
||||
userLogoSvc := marketingservice.NewUserLogoService(userLogoRepo)
|
||||
marketingCategoryHandler := marketinghandler.NewCategoryHandler(categorySvc)
|
||||
marketingTemplateHandler := marketinghandler.NewTemplateHandler(templateSvc)
|
||||
marketingDownloadHandler := marketinghandler.NewDownloadHandler(downloadSvc)
|
||||
marketingUserLogoHandler := marketinghandler.NewUserLogoHandler(userLogoSvc)
|
||||
adPlacementRepo := marketingrepo.NewAdPlacementRepository(database.DB)
|
||||
marketingAdPlacementHandler := marketinghandler.NewAdPlacementHandler(adPlacementRepo)
|
||||
|
||||
adminService := adminmodule.NewService(
|
||||
database.DB,
|
||||
@@ -194,6 +214,8 @@ func main() {
|
||||
marketingCategoryHandler,
|
||||
marketingTemplateHandler,
|
||||
marketingDownloadHandler,
|
||||
marketingUserLogoHandler,
|
||||
marketingAdPlacementHandler,
|
||||
quitCheckinHandler,
|
||||
)
|
||||
|
||||
|
||||
+15
-15
@@ -17,7 +17,7 @@ type Config struct {
|
||||
ShortVideo ShortVideoConfig
|
||||
AI AIConfig
|
||||
Admin AdminConfig
|
||||
Qiniu QiniuConfig
|
||||
OSS OSSConfig
|
||||
WeChatOA WeChatOfficialConfig
|
||||
Redis RedisConfig
|
||||
}
|
||||
@@ -71,9 +71,9 @@ type AdminConfig struct {
|
||||
DefaultPassword string
|
||||
}
|
||||
|
||||
// QiniuConfig 用于七牛云(Kodo)直传相关配置。
|
||||
// 前端通常会向后端请求 upload token,然后直传文件到七牛。
|
||||
type QiniuConfig struct {
|
||||
// OSSConfig 用于阿里云 OSS 直传相关配置。
|
||||
// 前端通常会向后端请求上传凭证,然后直传文件到 OSS。
|
||||
type OSSConfig struct {
|
||||
AccessKey string
|
||||
SecretKey string
|
||||
Bucket string
|
||||
@@ -151,17 +151,17 @@ func LoadConfig() {
|
||||
DefaultUsername: getEnv("ADMIN_DEFAULT_USERNAME", "admin"),
|
||||
DefaultPassword: getEnv("ADMIN_DEFAULT_PASSWORD", "admin123"),
|
||||
},
|
||||
Qiniu: QiniuConfig{
|
||||
AccessKey: getEnv("QINIU_ACCESS_KEY", ""),
|
||||
SecretKey: getEnv("QINIU_SECRET_KEY", ""),
|
||||
Bucket: getEnv("QINIU_BUCKET", ""),
|
||||
UploadURL: getEnv("QINIU_UPLOAD_URL", "https://upload.qiniup.com"),
|
||||
CDNDomain: getEnv("QINIU_CDN_DOMAIN", ""),
|
||||
KeyPrefix: getEnv("QINIU_KEY_PREFIX", "uploads/"),
|
||||
TokenExpireSeconds: getEnvAsInt("QINIU_TOKEN_EXPIRE_SECONDS", 300),
|
||||
CallbackURL: getEnv("QINIU_CALLBACK_URL", ""),
|
||||
CallbackBody: getEnv("QINIU_CALLBACK_BODY", "key=$(key)&hash=$(etag)&fsize=$(fsize)&mimeType=$(mimeType)"),
|
||||
CallbackBodyType: getEnv("QINIU_CALLBACK_BODY_TYPE", "application/x-www-form-urlencoded"),
|
||||
OSS: OSSConfig{
|
||||
AccessKey: getEnv("OSS_ACCESS_KEY", ""),
|
||||
SecretKey: getEnv("OSS_SECRET_KEY", ""),
|
||||
Bucket: getEnv("OSS_BUCKET", ""),
|
||||
UploadURL: getEnv("OSS_UPLOAD_URL", ""),
|
||||
CDNDomain: getEnv("OSS_CDN_DOMAIN", ""),
|
||||
KeyPrefix: getEnv("OSS_KEY_PREFIX", "uploads/"),
|
||||
TokenExpireSeconds: getEnvAsInt("OSS_TOKEN_EXPIRE_SECONDS", 300),
|
||||
CallbackURL: getEnv("OSS_CALLBACK_URL", ""),
|
||||
CallbackBody: getEnv("OSS_CALLBACK_BODY", "key=$(key)&hash=$(etag)&fsize=$(fsize)&mimeType=$(mimeType)"),
|
||||
CallbackBodyType: getEnv("OSS_CALLBACK_BODY_TYPE", "application/x-www-form-urlencoded"),
|
||||
},
|
||||
WeChatOA: WeChatOfficialConfig{
|
||||
AppID: getEnv("WECHAT_OA_APP_ID", ""),
|
||||
|
||||
@@ -23,7 +23,7 @@
|
||||
|
||||
除登录接口外,其他接口都需要携带登录后返回的 `session_key`(见:`docs/common/auth.md`)。
|
||||
|
||||
## 上传(七牛直传)
|
||||
## 上传(阿里云 OSS 直传)
|
||||
|
||||
- `docs/common/upload_qiniu.md`
|
||||
|
||||
@@ -38,3 +38,7 @@
|
||||
## 自动化部署(非 Docker)
|
||||
|
||||
- `docs/common/deploy_ci.md`
|
||||
|
||||
## 后端开发规范
|
||||
|
||||
- `docs/common/backend_convention.md`(编码风格、模块分层、命名约定、接口规范、新增模块流程等)
|
||||
|
||||
@@ -0,0 +1,477 @@
|
||||
# 后端开发规范 (wx_service)
|
||||
|
||||
本文档定义 `wx_service` 后端项目的编码规范、架构约定和开发流程,适用于所有后端贡献者。
|
||||
|
||||
---
|
||||
|
||||
## 1. 技术栈与环境
|
||||
|
||||
| 分类 | 技术 | 最低版本 |
|
||||
|------|------|----------|
|
||||
| 语言 | Go | 1.23 |
|
||||
| Web 框架 | Gin | v1.11 |
|
||||
| ORM | GORM | v1.31 |
|
||||
| 数据库 | MySQL | 8.x |
|
||||
| 缓存 | Redis (go-redis v9) | 可选 |
|
||||
| 鉴权 | JWT (golang-jwt v5) | — |
|
||||
| 配置 | godotenv | — |
|
||||
|
||||
**开发工具要求**:
|
||||
- 使用 `gofmt` / `goimports` 格式化代码
|
||||
- 推荐 `golangci-lint` 进行静态检查
|
||||
- 提交前确保 `go vet ./...` 无警告
|
||||
|
||||
---
|
||||
|
||||
## 2. 项目结构
|
||||
|
||||
```
|
||||
wx_service/
|
||||
├── cmd/api/main.go # 程序入口(配置加载 → DB 初始化 → 依赖注入 → 路由注册 → 启动)
|
||||
├── config/ # 配置结构体与加载逻辑
|
||||
├── internal/ # 业务代码(不可被外部包导入)
|
||||
│ ├── admin/ # 管理后台模块
|
||||
│ ├── common/ # 公共能力
|
||||
│ │ ├── auth/ # 登录认证
|
||||
│ │ ├── upload/ # OSS 上传
|
||||
│ │ ├── redis/ # Redis 缓存
|
||||
│ │ └── wechat_official/ # 公众号 OAuth
|
||||
│ ├── database/ # 数据库连接与迁移
|
||||
│ ├── middleware/ # HTTP 中间件
|
||||
│ ├── model/ # 公共数据模型(User、MiniProgram、Response)
|
||||
│ ├── observability/ # 指标采集与日志
|
||||
│ ├── routes/ # 路由注册
|
||||
│ └── <module>/ # 业务模块(按域拆分)
|
||||
├── docs/ # 文档
|
||||
├── deploy/ # 部署配置
|
||||
├── scripts/ # 运维脚本
|
||||
├── .env.example # 环境变量模板
|
||||
├── Dockerfile # 容器镜像构建
|
||||
├── docker-compose.yml # 开发环境依赖
|
||||
└── docker-compose.prod.yml # 生产环境编排
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. 模块分层架构
|
||||
|
||||
每个业务模块位于 `internal/<module>/`,采用以下分层结构:
|
||||
|
||||
```
|
||||
internal/<module>/
|
||||
├── handler/ # HTTP 层
|
||||
├── service/ # 业务逻辑层
|
||||
├── model/ # 数据模型
|
||||
└── repository/ # 数据访问层(可选)
|
||||
```
|
||||
|
||||
### 3.1 各层职责
|
||||
|
||||
| 层 | 职责 | 禁止事项 |
|
||||
|----|------|----------|
|
||||
| **handler** | 解析请求参数、调用 service、组装 HTTP 响应 | 不包含业务逻辑、不直接操作数据库 |
|
||||
| **service** | 实现核心业务规则、编排多表操作、调用外部 API | 不感知 HTTP 层(不依赖 `gin.Context` 进行响应) |
|
||||
| **model** | 定义 GORM struct、表名、数据校验 | 不包含业务逻辑 |
|
||||
| **repository** | 封装数据库查询(可选,简单模块可由 service 直接操作 DB) | 不包含业务逻辑 |
|
||||
|
||||
### 3.2 依赖方向
|
||||
|
||||
```
|
||||
handler → service → repository → model
|
||||
→ model
|
||||
```
|
||||
|
||||
handler 依赖 service,service 依赖 repository(或直接使用 `*gorm.DB`),所有层共享 model。禁止反向依赖。
|
||||
|
||||
### 3.3 依赖注入
|
||||
|
||||
采用构造函数注入,在 `cmd/api/main.go` 中完成装配:
|
||||
|
||||
```go
|
||||
// service 接收 *gorm.DB 和配置
|
||||
svc := someservice.NewSomeService(database.DB, config.AppConfig.SomeConfig)
|
||||
|
||||
// handler 接收 service
|
||||
handler := somehandler.NewSomeHandler(svc)
|
||||
|
||||
// 路由注册接收 handler
|
||||
routes.Register(router, handler, ...)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. 命名规范
|
||||
|
||||
### 4.1 文件命名
|
||||
|
||||
- 使用 **snake_case**:`smoke_log_service.go`、`auth_handler.go`
|
||||
- 测试文件以 `_test.go` 结尾:`smoke_log_service_test.go`
|
||||
- 每个文件聚焦单一职责,避免大文件
|
||||
|
||||
### 4.2 包命名
|
||||
|
||||
- 全小写,不使用下划线:`handler`、`service`、`model`
|
||||
- 导入别名使用有意义的缩写:`smokeservice`、`rmhandler`
|
||||
|
||||
### 4.3 结构体与函数
|
||||
|
||||
- 导出类型使用 PascalCase:`SmokeHandler`、`SmokeLogService`
|
||||
- 构造函数统一使用 `New` 前缀:`NewSmokeHandler`
|
||||
- 请求结构体使用小写开头(非导出):`createSmokeLogRequest`
|
||||
- 常量使用 camelCase 或 PascalCase(视作用域定)
|
||||
|
||||
### 4.4 数据库相关
|
||||
|
||||
- 表名使用 **snake_case**:`fa_smoke_log`、`marketing_categories`
|
||||
- 模型通过 `TableName()` 方法显式指定表名
|
||||
- 字段标签使用 `gorm:"column:xxx"` 明确列名
|
||||
|
||||
---
|
||||
|
||||
## 5. HTTP 接口规范
|
||||
|
||||
### 5.1 响应格式
|
||||
|
||||
所有接口统一使用 `model.Response` 结构:
|
||||
|
||||
```go
|
||||
// 成功
|
||||
c.JSON(http.StatusOK, model.Success(data))
|
||||
|
||||
// 失败
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "参数错误描述"))
|
||||
```
|
||||
|
||||
响应 JSON 结构:
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"message": "success",
|
||||
"data": {}
|
||||
}
|
||||
```
|
||||
|
||||
### 5.2 HTTP 状态码使用
|
||||
|
||||
| 状态码 | 场景 |
|
||||
|--------|------|
|
||||
| 200 | 成功(包括空结果集) |
|
||||
| 400 | 请求参数校验失败 |
|
||||
| 401 | 未登录或 Token 过期 |
|
||||
| 403 | 无权限或业务限制(如额度用尽) |
|
||||
| 404 | 资源不存在 |
|
||||
| 500 | 服务端内部错误 |
|
||||
| 502 | 第三方服务调用失败 |
|
||||
| 503 | 关键配置缺失导致服务不可用 |
|
||||
|
||||
### 5.3 路由规范
|
||||
|
||||
- RESTful 风格:`GET` 获取、`POST` 创建、`PUT` 更新、`DELETE` 删除
|
||||
- 路由前缀:
|
||||
- `/api/v1` — 主版本 API
|
||||
- `/api/v2` — 新版本模块
|
||||
- `/api/expiry` — 保质期独立域
|
||||
- `/api/admin` — 管理后台
|
||||
- 路由注册集中在 `internal/routes/` 目录下
|
||||
- 每个模块创建独立的 `register<Module>Routes` 函数
|
||||
|
||||
### 5.4 认证
|
||||
|
||||
- 用户认证:`Bearer <session_key>`,通过 `AuthMiddleware` + `RequireUserMiddleware` 处理
|
||||
- 管理后台:`X-Admin-Token` 头或 JWT
|
||||
- 公开接口不挂载鉴权中间件
|
||||
- handler 中通过 `middleware.MustCurrentUser(c)` 获取当前用户
|
||||
|
||||
### 5.5 分页
|
||||
|
||||
列表接口统一使用以下参数和返回结构:
|
||||
|
||||
```
|
||||
// 请求参数
|
||||
?page=1&page_size=20
|
||||
|
||||
// 响应
|
||||
{
|
||||
"code": 200,
|
||||
"message": "success",
|
||||
"data": {
|
||||
"items": [...],
|
||||
"total": 100,
|
||||
"page": 1,
|
||||
"page_size": 20
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 6. 数据库规范
|
||||
|
||||
### 6.1 GORM 模型
|
||||
|
||||
```go
|
||||
type SomeModel struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
UserID uint `gorm:"index;not null" json:"user_id"`
|
||||
Name string `gorm:"size:100;not null" json:"name"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
|
||||
}
|
||||
|
||||
func (SomeModel) TableName() string {
|
||||
return "some_models"
|
||||
}
|
||||
```
|
||||
|
||||
### 6.2 迁移
|
||||
|
||||
- 开发阶段使用 `AutoMigrate`,在 `cmd/api/main.go` 中注册新模型
|
||||
- 生产环境建议手动迁移,SQL 参考放在 `docs/sql/` 目录
|
||||
|
||||
### 6.3 查询
|
||||
|
||||
- 优先使用 GORM 链式查询,避免裸 SQL
|
||||
- 复杂报表查询可使用 `db.Raw()`,但需添加注释说明
|
||||
- 列表查询必须加分页限制(`Limit` + `Offset`)
|
||||
- 敏感查询加 `context.Context` 传递超时控制
|
||||
|
||||
### 6.4 事务
|
||||
|
||||
涉及多表写入的操作使用事务:
|
||||
|
||||
```go
|
||||
err := db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
// 多步操作
|
||||
return nil
|
||||
})
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 7. 错误处理
|
||||
|
||||
### 7.1 Service 层
|
||||
|
||||
- 定义领域错误变量:`var ErrSmokeLogNotFound = errors.New("smoke log not found")`
|
||||
- Service 返回具体的错误类型,handler 据此决定 HTTP 状态码
|
||||
- 内部错误使用 `fmt.Errorf("xxx: %w", err)` 包装
|
||||
|
||||
### 7.2 Handler 层
|
||||
|
||||
- 用 `errors.Is()` 判断 service 返回的错误类型
|
||||
- 用户可见的错误信息使用中文
|
||||
- 内部错误记录日志后返回通用提示:"xxx失败,请稍后重试"
|
||||
|
||||
```go
|
||||
record, err := h.service.GetByID(ctx, userID, id)
|
||||
if err != nil {
|
||||
if errors.Is(err, service.ErrNotFound) {
|
||||
c.JSON(http.StatusNotFound, model.Error(http.StatusNotFound, "记录不存在"))
|
||||
return
|
||||
}
|
||||
log.Printf("GetByID failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, model.Error(http.StatusInternalServerError, "查询失败,请稍后重试"))
|
||||
return
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 8. 配置管理
|
||||
|
||||
### 8.1 环境变量
|
||||
|
||||
- 所有配置通过 `.env` 文件加载,使用 `godotenv`
|
||||
- 新增配置项必须同步更新 `.env.example`
|
||||
- 敏感信息(密钥、密码)不可提交到代码仓库
|
||||
|
||||
### 8.2 配置结构
|
||||
|
||||
配置统一定义在 `config/config.go` 的结构体中:
|
||||
|
||||
```go
|
||||
type Config struct {
|
||||
Server ServerConfig
|
||||
Database DatabaseConfig
|
||||
JWT JWTConfig
|
||||
// 按需扩展...
|
||||
}
|
||||
```
|
||||
|
||||
### 8.3 可选功能降级
|
||||
|
||||
部分功能(如 Redis、额外数据库)可选启用。启动时检测配置是否存在,缺失则打印日志并禁用相关接口,不阻塞服务启动:
|
||||
|
||||
```go
|
||||
if redisClient == nil {
|
||||
log.Println("redis disabled: ...")
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 9. 测试规范
|
||||
|
||||
### 9.1 文件与组织
|
||||
|
||||
- 测试文件与被测文件同目录:`smoke_log_service.go` → `smoke_log_service_test.go`
|
||||
- 使用 Go 标准测试框架 `testing`
|
||||
- 表驱动测试(table-driven tests)优先
|
||||
|
||||
### 9.2 命名
|
||||
|
||||
- 测试函数:`TestFunctionName_Scenario`
|
||||
- 子测试:`t.Run("scenario description", ...)`
|
||||
|
||||
### 9.3 运行
|
||||
|
||||
```bash
|
||||
# 运行全部测试
|
||||
go test ./...
|
||||
|
||||
# 运行指定模块测试
|
||||
go test ./internal/smoke/service/...
|
||||
|
||||
# 带覆盖率
|
||||
go test -cover ./...
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 10. 新增业务模块流程
|
||||
|
||||
以新增"xx功能"模块为例:
|
||||
|
||||
### 第一步:创建模块目录
|
||||
|
||||
```
|
||||
internal/xx/
|
||||
├── handler/
|
||||
│ └── xx_handler.go
|
||||
├── service/
|
||||
│ └── xx_service.go
|
||||
└── model/
|
||||
└── xx.go
|
||||
```
|
||||
|
||||
### 第二步:定义数据模型
|
||||
|
||||
```go
|
||||
// internal/xx/model/xx.go
|
||||
package model
|
||||
|
||||
type XX struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
UserID uint `gorm:"index;not null" json:"user_id"`
|
||||
// ...
|
||||
}
|
||||
|
||||
func (XX) TableName() string { return "xx_records" }
|
||||
```
|
||||
|
||||
### 第三步:实现 Service
|
||||
|
||||
```go
|
||||
// internal/xx/service/xx_service.go
|
||||
package service
|
||||
|
||||
type XXService struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewXXService(db *gorm.DB) *XXService {
|
||||
return &XXService{db: db}
|
||||
}
|
||||
```
|
||||
|
||||
### 第四步:实现 Handler
|
||||
|
||||
```go
|
||||
// internal/xx/handler/xx_handler.go
|
||||
package handler
|
||||
|
||||
type XXHandler struct {
|
||||
service *xxservice.XXService
|
||||
}
|
||||
|
||||
func NewXXHandler(svc *xxservice.XXService) *XXHandler {
|
||||
return &XXHandler{service: svc}
|
||||
}
|
||||
```
|
||||
|
||||
### 第五步:注册依赖和路由
|
||||
|
||||
1. 在 `cmd/api/main.go` 中:
|
||||
- 导入新模块
|
||||
- 初始化 service → handler
|
||||
- 将新模型加入 `AutoMigrate`
|
||||
2. 在 `internal/routes/` 中新建 `xx_routes.go`,实现 `registerXXRoutes`
|
||||
3. 在 `routes.go` 的 `Register` 函数中调用
|
||||
|
||||
### 第六步:编写文档
|
||||
|
||||
在 `docs/xx/` 下创建:
|
||||
- `README.md`:模块需求说明
|
||||
- `API.md`:接口文档(方法、路径、参数、返回值)
|
||||
|
||||
---
|
||||
|
||||
## 11. Git 与提交规范
|
||||
|
||||
### 11.1 分支策略
|
||||
|
||||
- `main` / `master`:生产分支,推送自动触发部署
|
||||
- 功能分支:`feature/<name>` 或 `fix/<name>`
|
||||
|
||||
### 11.2 提交信息格式
|
||||
|
||||
```
|
||||
<type>: <简要描述>
|
||||
|
||||
<可选的详细说明>
|
||||
```
|
||||
|
||||
类型约定:
|
||||
|
||||
| 类型 | 说明 |
|
||||
|------|------|
|
||||
| feat | 新功能 |
|
||||
| fix | 修复 Bug |
|
||||
| refactor | 重构(不影响功能) |
|
||||
| docs | 文档变更 |
|
||||
| test | 测试相关 |
|
||||
| chore | 构建/运维/依赖等杂项 |
|
||||
|
||||
示例:`feat: add quit plan CRUD endpoints`
|
||||
|
||||
### 11.3 提交检查清单
|
||||
|
||||
- [ ] `go vet ./...` 无警告
|
||||
- [ ] `gofmt` / `goimports` 已格式化
|
||||
- [ ] 相关测试通过
|
||||
- [ ] 新增接口已更新文档
|
||||
- [ ] `.env.example` 已同步更新(如有新配置项)
|
||||
|
||||
---
|
||||
|
||||
## 12. 部署
|
||||
|
||||
### Docker 方式
|
||||
|
||||
```bash
|
||||
docker compose -f docker-compose.prod.yml up -d
|
||||
```
|
||||
|
||||
### 非 Docker(GitHub Actions)
|
||||
|
||||
推送 `main` 分支自动触发 `.github/workflows/deploy-prod.yml`。
|
||||
|
||||
### 健康检查
|
||||
|
||||
- `GET /healthz` → `{"status": "ok"}`
|
||||
- Docker 健康检查间隔 30s
|
||||
- Nginx 反代配置在 `deploy/nginx/` 下
|
||||
|
||||
详细部署文档:`docs/common/deploy_ci.md`
|
||||
+34
-30
@@ -1,19 +1,19 @@
|
||||
# 七牛(Kodo)直传:获取上传凭证
|
||||
# 阿里云 OSS 直传:获取上传凭证
|
||||
|
||||
用途:小程序/前端把文件直接上传到七牛(CDN 源站),后端只负责签发上传 token,减少带宽与压力。
|
||||
用途:小程序/前端把文件直接上传到阿里云 OSS,后端只负责签发上传凭证,减少带宽与压力。
|
||||
|
||||
## 前置条件
|
||||
|
||||
- 已完成登录并拿到 `session_key`(见:`docs/common/auth.md`)
|
||||
- 已配置 `.env` 中的七牛参数(见:`.env.example`)
|
||||
- 已配置 `.env` 中的 OSS 参数(见:`.env.example`)
|
||||
- 若需要上传成功回调,请额外配置:
|
||||
- `QINIU_CALLBACK_URL`(例如:`https://api.example.com/api/v1/common/upload/qiniu/callback`)
|
||||
- `QINIU_CALLBACK_BODY`
|
||||
- `QINIU_CALLBACK_BODY_TYPE`
|
||||
- `OSS_CALLBACK_URL`(例如:`https://api.example.com/api/v1/common/upload/oss/callback`)
|
||||
- `OSS_CALLBACK_BODY`
|
||||
- `OSS_CALLBACK_BODY_TYPE`
|
||||
|
||||
## 接口
|
||||
|
||||
`POST /api/v1/common/upload/qiniu/token`
|
||||
`POST /api/v1/common/upload/oss/token`
|
||||
|
||||
Header:
|
||||
|
||||
@@ -33,66 +33,70 @@ Content-Type: application/json
|
||||
说明:
|
||||
- `filename` 仅用于提取文件后缀(例如 `.png`),以便后端生成带后缀的 `key`;不传也可以。
|
||||
|
||||
成功响应示例:
|
||||
成功响应示例(OSS PostObject 凭证):
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"message": "success",
|
||||
"data": {
|
||||
"token": "xxx",
|
||||
"key": "uploads/mp_1/user_123/20251231/ab12cd34ef....png",
|
||||
"upload_url": "https://upload.qiniup.com",
|
||||
"expire": 1767150000,
|
||||
"cdn_domain": "https://cdn.example.com"
|
||||
"key": "uploads/mp_1/user_123/20251231/ab12cd34....png",
|
||||
"upload_url": "https://bucket.oss-cn-beijing.aliyuncs.com",
|
||||
"cdn_domain": "https://bucket.oss-cn-beijing.aliyuncs.com",
|
||||
"oss_access_key_id": "LTAI5t...",
|
||||
"oss_policy": "base64...",
|
||||
"oss_signature": "sig..."
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
字段说明:
|
||||
- `token`:七牛上传凭证(uptoken)
|
||||
- `key`:后端生成的对象 key,上传时必须使用该 key
|
||||
- `upload_url`:上传入口(表单上传 URL)
|
||||
- `expire`:token 过期时间(Unix 秒)
|
||||
- `cdn_domain`:可选;如果配置了,可用 `cdn_domain + "/" + key` 拼出访问 URL
|
||||
- `upload_url`:OSS PostObject 上传地址
|
||||
- `cdn_domain`:CDN 访问域名,可用 `cdn_domain + "/" + key` 拼出访问 URL
|
||||
- `oss_access_key_id`:OSS AccessKeyId
|
||||
- `oss_policy`:Base64 编码的 Policy
|
||||
- `oss_signature`:HMAC-SHA1 签名
|
||||
|
||||
## 使用示例(curl 直传)
|
||||
|
||||
1) 先请求 token:
|
||||
1) 先请求凭证:
|
||||
|
||||
```bash
|
||||
curl -X POST 'http://127.0.0.1:8080/api/v1/common/upload/qiniu/token' \
|
||||
curl -X POST 'http://127.0.0.1:8080/api/v1/common/upload/oss/token' \
|
||||
-H 'Content-Type: application/json' \
|
||||
-H 'Authorization: Bearer wx-session-key' \
|
||||
-d '{"filename":"avatar.png"}'
|
||||
```
|
||||
|
||||
2) 再把文件直传七牛(multipart/form-data):
|
||||
2) 再把文件直传 OSS(multipart/form-data):
|
||||
|
||||
```bash
|
||||
curl -X POST 'https://upload.qiniup.com' \
|
||||
-F "token=上一步返回的 token" \
|
||||
-F "key=上一步返回的 key" \
|
||||
curl -X POST '<upload_url>' \
|
||||
-F "key=<上一步返回的 key>" \
|
||||
-F "policy=<oss_policy>" \
|
||||
-F "OSSAccessKeyId=<oss_access_key_id>" \
|
||||
-F "Signature=<oss_signature>" \
|
||||
-F "file=@./avatar.png"
|
||||
```
|
||||
|
||||
七牛成功时会返回 JSON(字段可能因配置不同略有差异),其中一般会包含 `key/hash`。
|
||||
OSS 成功时返回 HTTP 204(无 body)。
|
||||
|
||||
---
|
||||
|
||||
## 上传回调(服务端)
|
||||
|
||||
当配置了 `QINIU_CALLBACK_URL` 后,后端签发的 putPolicy 会包含 callback 参数。七牛上传成功后会回调:
|
||||
当配置了 `OSS_CALLBACK_URL` 后,上传成功后会回调:
|
||||
|
||||
`POST /api/v1/common/upload/qiniu/callback`
|
||||
`POST /api/v1/common/upload/oss/callback`
|
||||
|
||||
说明:
|
||||
- 该接口无需登录(由七牛服务端调用)。
|
||||
- 服务端会校验 `Authorization: QBox ...` 签名。
|
||||
- 该接口无需登录(由 OSS 服务端调用)。
|
||||
- 服务端会校验 `Authorization` 签名。
|
||||
- 验签失败返回 `401`,直接拒绝。
|
||||
- 当业务处理发生临时异常时可返回 `503`,利用七牛回调重试机制重试。
|
||||
- 当业务处理发生临时异常时可返回 `503`,利用回调重试机制重试。
|
||||
|
||||
默认回调体(可通过 `QINIU_CALLBACK_BODY` 调整):
|
||||
默认回调体(可通过 `OSS_CALLBACK_BODY` 调整):
|
||||
|
||||
```txt
|
||||
key=$(key)&hash=$(etag)&fsize=$(fsize)&mimeType=$(mimeType)
|
||||
|
||||
@@ -124,7 +124,7 @@ web/marketing/
|
||||
## 依赖的公共服务
|
||||
|
||||
- **鉴权**:复用 `middleware.AuthMiddleware` + `middleware.RequireUserMiddleware`
|
||||
- **七牛上传**:模板图片和用户 Logo 均通过七牛直传,复用 `common/qiniu` 模块
|
||||
- **OSS 上传**:模板图片和用户 Logo 均通过阿里云 OSS 直传,复用 `common/upload` 模块
|
||||
- **Admin Token**:通过 `X-Admin-Token` 请求头鉴权,Token 来自 `.env` 的 `ADMIN_API_TOKEN`
|
||||
|
||||
## Web 管理后台
|
||||
|
||||
+7
-1
@@ -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
|
||||
|
||||
@@ -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变动日志';
|
||||
|
||||
@@ -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 '删除时间',
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
module wx_service
|
||||
|
||||
go 1.23.0
|
||||
|
||||
toolchain go1.24.4
|
||||
go 1.25.0
|
||||
|
||||
require (
|
||||
github.com/DATA-DOG/go-sqlmock v1.5.2
|
||||
@@ -10,7 +8,8 @@ require (
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1
|
||||
github.com/joho/godotenv v1.5.1
|
||||
github.com/redis/go-redis/v9 v9.17.2
|
||||
golang.org/x/crypto v0.40.0
|
||||
golang.org/x/crypto v0.48.0
|
||||
golang.org/x/image v0.38.0
|
||||
gorm.io/driver/mysql v1.6.0
|
||||
gorm.io/driver/sqlite v1.6.0
|
||||
gorm.io/gorm v1.31.1
|
||||
@@ -47,11 +46,11 @@ require (
|
||||
github.com/ugorji/go/codec v1.3.0 // indirect
|
||||
go.uber.org/mock v0.5.0 // indirect
|
||||
golang.org/x/arch v0.20.0 // indirect
|
||||
golang.org/x/mod v0.25.0 // indirect
|
||||
golang.org/x/net v0.42.0 // indirect
|
||||
golang.org/x/sync v0.16.0 // indirect
|
||||
golang.org/x/sys v0.35.0 // indirect
|
||||
golang.org/x/text v0.27.0 // indirect
|
||||
golang.org/x/tools v0.34.0 // indirect
|
||||
golang.org/x/mod v0.33.0 // indirect
|
||||
golang.org/x/net v0.50.0 // indirect
|
||||
golang.org/x/sync v0.20.0 // indirect
|
||||
golang.org/x/sys v0.41.0 // indirect
|
||||
golang.org/x/text v0.35.0 // indirect
|
||||
golang.org/x/tools v0.42.0 // indirect
|
||||
google.golang.org/protobuf v1.36.9 // indirect
|
||||
)
|
||||
|
||||
@@ -92,21 +92,23 @@ go.uber.org/mock v0.5.0 h1:KAMbZvZPyBPWgD14IrIQ38QCyjwpvVVV6K/bHl1IwQU=
|
||||
go.uber.org/mock v0.5.0/go.mod h1:ge71pBPLYDk7QIi1LupWxdAykm7KIEFchiOqd6z7qMM=
|
||||
golang.org/x/arch v0.20.0 h1:dx1zTU0MAE98U+TQ8BLl7XsJbgze2WnNKF/8tGp/Q6c=
|
||||
golang.org/x/arch v0.20.0/go.mod h1:bdwinDaKcfZUGpH09BB7ZmOfhalA8lQdzl62l8gGWsk=
|
||||
golang.org/x/crypto v0.40.0 h1:r4x+VvoG5Fm+eJcxMaY8CQM7Lb0l1lsmjGBQ6s8BfKM=
|
||||
golang.org/x/crypto v0.40.0/go.mod h1:Qr1vMER5WyS2dfPHAlsOj01wgLbsyWtFn/aY+5+ZdxY=
|
||||
golang.org/x/mod v0.25.0 h1:n7a+ZbQKQA/Ysbyb0/6IbB1H/X41mKgbhfv7AfG/44w=
|
||||
golang.org/x/mod v0.25.0/go.mod h1:IXM97Txy2VM4PJ3gI61r1YEk/gAj6zAHN3AdZt6S9Ww=
|
||||
golang.org/x/net v0.42.0 h1:jzkYrhi3YQWD6MLBJcsklgQsoAcw89EcZbJw8Z614hs=
|
||||
golang.org/x/net v0.42.0/go.mod h1:FF1RA5d3u7nAYA4z2TkclSCKh68eSXtiFwcWQpPXdt8=
|
||||
golang.org/x/sync v0.16.0 h1:ycBJEhp9p4vXvUZNszeOq0kGTPghopOL8q0fq3vstxw=
|
||||
golang.org/x/sync v0.16.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
|
||||
golang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts=
|
||||
golang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos=
|
||||
golang.org/x/image v0.38.0 h1:5l+q+Y9JDC7mBOMjo4/aPhMDcxEptsX+Tt3GgRQRPuE=
|
||||
golang.org/x/image v0.38.0/go.mod h1:/3f6vaXC+6CEanU4KJxbcUZyEePbyKbaLoDOe4ehFYY=
|
||||
golang.org/x/mod v0.33.0 h1:tHFzIWbBifEmbwtGz65eaWyGiGZatSrT9prnU8DbVL8=
|
||||
golang.org/x/mod v0.33.0/go.mod h1:swjeQEj+6r7fODbD2cqrnje9PnziFuw4bmLbBZFrQ5w=
|
||||
golang.org/x/net v0.50.0 h1:ucWh9eiCGyDR3vtzso0WMQinm2Dnt8cFMuQa9K33J60=
|
||||
golang.org/x/net v0.50.0/go.mod h1:UgoSli3F/pBgdJBHCTc+tp3gmrU4XswgGRgtnwWTfyM=
|
||||
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
|
||||
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI=
|
||||
golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
|
||||
golang.org/x/text v0.27.0 h1:4fGWRpyh641NLlecmyl4LOe6yDdfaYNrGb2zdfo4JV4=
|
||||
golang.org/x/text v0.27.0/go.mod h1:1D28KMCvyooCX9hBiosv5Tz/+YLxj0j7XhWjpSUF7CU=
|
||||
golang.org/x/tools v0.34.0 h1:qIpSLOxeCYGg9TrcJokLBG4KFA6d795g0xkBkiESGlo=
|
||||
golang.org/x/tools v0.34.0/go.mod h1:pAP9OwEaY1CAW3HOmg3hLZC5Z0CCmzjAF2UQMSqNARg=
|
||||
golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=
|
||||
golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/text v0.35.0 h1:JOVx6vVDFokkpaq1AEptVzLTpDe9KGpj5tR4/X+ybL8=
|
||||
golang.org/x/text v0.35.0/go.mod h1:khi/HExzZJ2pGnjenulevKNX1W67CUy0AsXcNubPGCA=
|
||||
golang.org/x/tools v0.42.0 h1:uNgphsn75Tdz5Ji2q36v/nsFSfR/9BRFvqhGBaJGd5k=
|
||||
golang.org/x/tools v0.42.0/go.mod h1:Ma6lCIwGZvHK6XtgbswSoWroEkhugApmsXyrUmBhfr0=
|
||||
google.golang.org/protobuf v1.36.9 h1:w2gp2mA27hUeUzj9Ex9FBjsBm40zfaDtEWow293U7Iw=
|
||||
google.golang.org/protobuf v1.36.9/go.mod h1:fuxRtAxBytpl4zzqUh6/eyUujkJdNiuEkXntxiD/uRU=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
package achievement
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type Theme struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
|
||||
|
||||
Name string `gorm:"size:50;not null;comment:主题名称" json:"name"`
|
||||
Key string `gorm:"size:50;uniqueIndex;not null;comment:主题标识" json:"key"`
|
||||
Icon string `gorm:"size:255;comment:主题图标" json:"icon"`
|
||||
SortOrder int `gorm:"default:0;comment:排序" json:"sort_order"`
|
||||
IsActive bool `gorm:"default:true;comment:是否启用" json:"is_active"`
|
||||
|
||||
Levels []Level `gorm:"foreignKey:ThemeID" json:"levels,omitempty"`
|
||||
}
|
||||
|
||||
func (Theme) TableName() string {
|
||||
return "fa_achievement_theme"
|
||||
}
|
||||
|
||||
type Level struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
|
||||
|
||||
ThemeID uint `gorm:"index;not null;comment:主题ID" json:"theme_id"`
|
||||
Name string `gorm:"size:50;not null;comment:等级名称" json:"name"`
|
||||
Icon string `gorm:"size:255;comment:等级图标" json:"icon"`
|
||||
RequiredDays int `gorm:"not null;default:0;comment:所需打卡天数" json:"required_days"`
|
||||
SortOrder int `gorm:"default:0;comment:排序" json:"sort_order"`
|
||||
}
|
||||
|
||||
func (Level) TableName() string {
|
||||
return "fa_achievement_level"
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
package achievement
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
var ErrThemeNotFound = errors.New("achievement theme not found")
|
||||
|
||||
type Service struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewService(db *gorm.DB) *Service {
|
||||
return &Service{db: db}
|
||||
}
|
||||
|
||||
type UserAchievement struct {
|
||||
ThemeID uint `json:"theme_id"`
|
||||
ThemeName string `json:"theme_name"`
|
||||
ThemeKey string `json:"theme_key"`
|
||||
ThemeIcon string `json:"theme_icon"`
|
||||
Days int `json:"days"`
|
||||
Current *Level `json:"current"`
|
||||
Next *Level `json:"next,omitempty"`
|
||||
Progress float64 `json:"progress"`
|
||||
}
|
||||
|
||||
func (s *Service) ListActiveThemes(ctx context.Context) ([]Theme, error) {
|
||||
var themes []Theme
|
||||
err := s.db.WithContext(ctx).
|
||||
Where("is_active = ?", true).
|
||||
Preload("Levels", func(db *gorm.DB) *gorm.DB {
|
||||
return db.Order("required_days ASC, sort_order ASC")
|
||||
}).
|
||||
Order("sort_order ASC, id ASC").
|
||||
Find(&themes).Error
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list active themes: %w", err)
|
||||
}
|
||||
return themes, nil
|
||||
}
|
||||
|
||||
func (s *Service) GetUserAchievement(ctx context.Context, themeID uint, days int) (*UserAchievement, error) {
|
||||
var theme Theme
|
||||
err := s.db.WithContext(ctx).
|
||||
Preload("Levels", func(db *gorm.DB) *gorm.DB {
|
||||
return db.Order("required_days ASC, sort_order ASC")
|
||||
}).
|
||||
First(&theme, themeID).Error
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrThemeNotFound
|
||||
}
|
||||
return nil, fmt.Errorf("get theme: %w", err)
|
||||
}
|
||||
|
||||
if days < 0 {
|
||||
days = 0
|
||||
}
|
||||
|
||||
result := &UserAchievement{
|
||||
ThemeID: theme.ID,
|
||||
ThemeName: theme.Name,
|
||||
ThemeKey: theme.Key,
|
||||
ThemeIcon: theme.Icon,
|
||||
Days: days,
|
||||
}
|
||||
|
||||
for i, level := range theme.Levels {
|
||||
if days >= level.RequiredDays {
|
||||
lvl := level
|
||||
result.Current = &lvl
|
||||
if i+1 < len(theme.Levels) {
|
||||
next := theme.Levels[i+1]
|
||||
result.Next = &next
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if result.Current != nil && result.Next != nil {
|
||||
rangeTotal := result.Next.RequiredDays - result.Current.RequiredDays
|
||||
rangeDone := days - result.Current.RequiredDays
|
||||
if rangeTotal > 0 {
|
||||
result.Progress = float64(rangeDone) / float64(rangeTotal)
|
||||
}
|
||||
} else if result.Current != nil && result.Next == nil {
|
||||
result.Progress = 1.0
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (s *Service) SeedDefaults(ctx context.Context) error {
|
||||
var count int64
|
||||
if err := s.db.WithContext(ctx).Model(&Theme{}).Count(&count).Error; err != nil {
|
||||
return fmt.Errorf("count themes: %w", err)
|
||||
}
|
||||
if count > 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
themes := []struct {
|
||||
Name string
|
||||
Key string
|
||||
Icon string
|
||||
Levels []struct {
|
||||
Name string
|
||||
RequiredDays int
|
||||
}
|
||||
}{
|
||||
{
|
||||
Name: "修仙", Key: "xiuxian", Icon: "⚔️",
|
||||
Levels: []struct {
|
||||
Name string
|
||||
RequiredDays int
|
||||
}{
|
||||
{"炼体", 0}, {"练气", 3}, {"筑基", 7}, {"金丹", 30}, {"元婴", 90}, {"化神", 365},
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "军队", Key: "army", Icon: "🎖️",
|
||||
Levels: []struct {
|
||||
Name string
|
||||
RequiredDays int
|
||||
}{
|
||||
{"新兵", 0}, {"排长", 3}, {"连长", 7}, {"营长", 30}, {"师长", 90}, {"大将", 365},
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "魔法", Key: "magic", Icon: "🔮",
|
||||
Levels: []struct {
|
||||
Name string
|
||||
RequiredDays int
|
||||
}{
|
||||
{"学徒", 0}, {"术士", 3}, {"大术士", 7}, {"元素师", 30}, {"大魔导师", 90}, {"圣导师", 365},
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "武侠", Key: "wuxia", Icon: "🗡️",
|
||||
Levels: []struct {
|
||||
Name string
|
||||
RequiredDays int
|
||||
}{
|
||||
{"徒弟", 0}, {"掌门弟子", 3}, {"门派高手", 7}, {"大侠", 30}, {"剑仙", 90}, {"武圣", 365},
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "电竞", Key: "esports", Icon: "🏆",
|
||||
Levels: []struct {
|
||||
Name string
|
||||
RequiredDays int
|
||||
}{
|
||||
{"青铜", 0}, {"白银", 3}, {"黄金", 7}, {"铂金", 30}, {"钻石", 90}, {"王者", 365},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for i, t := range themes {
|
||||
theme := Theme{
|
||||
Name: t.Name,
|
||||
Key: t.Key,
|
||||
Icon: t.Icon,
|
||||
SortOrder: i,
|
||||
IsActive: true,
|
||||
}
|
||||
if err := s.db.WithContext(ctx).Create(&theme).Error; err != nil {
|
||||
return fmt.Errorf("seed theme %s: %w", t.Key, err)
|
||||
}
|
||||
for j, l := range t.Levels {
|
||||
level := Level{
|
||||
ThemeID: theme.ID,
|
||||
Name: l.Name,
|
||||
RequiredDays: l.RequiredDays,
|
||||
SortOrder: j,
|
||||
}
|
||||
if err := s.db.WithContext(ctx).Create(&level).Error; err != nil {
|
||||
return fmt.Errorf("seed level %s/%s: %w", t.Key, l.Name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"wx_service/internal/model"
|
||||
)
|
||||
|
||||
type achievementThemeRequest struct {
|
||||
Name string `json:"name"`
|
||||
Key string `json:"key"`
|
||||
Icon string `json:"icon"`
|
||||
SortOrder int `json:"sort_order"`
|
||||
IsActive *bool `json:"is_active"`
|
||||
}
|
||||
|
||||
type achievementLevelRequest struct {
|
||||
ThemeID uint `json:"theme_id"`
|
||||
Name string `json:"name"`
|
||||
Icon string `json:"icon"`
|
||||
RequiredDays int `json:"required_days"`
|
||||
SortOrder int `json:"sort_order"`
|
||||
}
|
||||
|
||||
func (h *Handler) ListAchievementThemes(c *gin.Context) {
|
||||
themes, err := h.svc.ListAchievementThemes(c.Request.Context())
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Error(http.StatusInternalServerError, "获取主题列表失败"))
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, model.Success(gin.H{"themes": themes}))
|
||||
}
|
||||
|
||||
func (h *Handler) GetAchievementTheme(c *gin.Context) {
|
||||
id, err := parseUintID(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "invalid id"))
|
||||
return
|
||||
}
|
||||
theme, err := h.svc.GetAchievementTheme(c.Request.Context(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, model.Error(http.StatusNotFound, "主题不存在"))
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, model.Success(theme))
|
||||
}
|
||||
|
||||
func (h *Handler) CreateAchievementTheme(c *gin.Context) {
|
||||
var req achievementThemeRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "请求参数错误"))
|
||||
return
|
||||
}
|
||||
if req.Name == "" || req.Key == "" {
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "name 和 key 必填"))
|
||||
return
|
||||
}
|
||||
theme, err := h.svc.CreateAchievementTheme(c.Request.Context(), req.Name, req.Key, req.Icon, req.SortOrder, req.IsActive)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Error(http.StatusInternalServerError, "创建主题失败"))
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, model.Success(theme))
|
||||
}
|
||||
|
||||
func (h *Handler) UpdateAchievementTheme(c *gin.Context) {
|
||||
id, err := parseUintID(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "invalid id"))
|
||||
return
|
||||
}
|
||||
var req achievementThemeRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "请求参数错误"))
|
||||
return
|
||||
}
|
||||
theme, err := h.svc.UpdateAchievementTheme(c.Request.Context(), id, req.Name, req.Key, req.Icon, req.SortOrder, req.IsActive)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Error(http.StatusInternalServerError, "更新主题失败"))
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, model.Success(theme))
|
||||
}
|
||||
|
||||
func (h *Handler) DeleteAchievementTheme(c *gin.Context) {
|
||||
id, err := parseUintID(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "invalid id"))
|
||||
return
|
||||
}
|
||||
if err := h.svc.DeleteAchievementTheme(c.Request.Context(), id); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Error(http.StatusInternalServerError, "删除主题失败"))
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, model.Success(gin.H{"deleted": true}))
|
||||
}
|
||||
|
||||
func (h *Handler) ListAchievementLevels(c *gin.Context) {
|
||||
themeID, err := parseUintID(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "invalid theme id"))
|
||||
return
|
||||
}
|
||||
levels, err := h.svc.ListAchievementLevels(c.Request.Context(), themeID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Error(http.StatusInternalServerError, "获取等级列表失败"))
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, model.Success(gin.H{"levels": levels}))
|
||||
}
|
||||
|
||||
func (h *Handler) CreateAchievementLevel(c *gin.Context) {
|
||||
var req achievementLevelRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "请求参数错误"))
|
||||
return
|
||||
}
|
||||
if req.Name == "" || req.ThemeID == 0 {
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "name 和 theme_id 必填"))
|
||||
return
|
||||
}
|
||||
level, err := h.svc.CreateAchievementLevel(c.Request.Context(), req.ThemeID, req.Name, req.Icon, req.RequiredDays, req.SortOrder)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Error(http.StatusInternalServerError, "创建等级失败"))
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, model.Success(level))
|
||||
}
|
||||
|
||||
func (h *Handler) UpdateAchievementLevel(c *gin.Context) {
|
||||
id, err := parseUintID(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "invalid id"))
|
||||
return
|
||||
}
|
||||
var req achievementLevelRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "请求参数错误"))
|
||||
return
|
||||
}
|
||||
level, err := h.svc.UpdateAchievementLevel(c.Request.Context(), id, req.Name, req.Icon, req.RequiredDays, req.SortOrder)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Error(http.StatusInternalServerError, "更新等级失败"))
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, model.Success(level))
|
||||
}
|
||||
|
||||
func (h *Handler) DeleteAchievementLevel(c *gin.Context) {
|
||||
id, err := parseUintID(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "invalid id"))
|
||||
return
|
||||
}
|
||||
if err := h.svc.DeleteAchievementLevel(c.Request.Context(), id); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Error(http.StatusInternalServerError, "删除等级失败"))
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, model.Success(gin.H{"deleted": true}))
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"wx_service/internal/model"
|
||||
)
|
||||
|
||||
type dreamPresetRequest struct {
|
||||
Title string `json:"title"`
|
||||
CoverImage string `json:"cover_image"`
|
||||
SortOrder int `json:"sort_order"`
|
||||
IsActive *bool `json:"is_active"`
|
||||
}
|
||||
|
||||
func (h *Handler) ListDreamPresets(c *gin.Context) {
|
||||
presets, err := h.svc.ListDreamPresets(c.Request.Context())
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Error(http.StatusInternalServerError, "获取预设目标失败"))
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, model.Success(gin.H{"items": presets}))
|
||||
}
|
||||
|
||||
func (h *Handler) CreateDreamPreset(c *gin.Context) {
|
||||
var req dreamPresetRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "参数错误"))
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(req.CoverImage) == "" {
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "图标不能为空"))
|
||||
return
|
||||
}
|
||||
preset, err := h.svc.CreateDreamPreset(c.Request.Context(), req.Title, req.CoverImage, req.SortOrder, req.IsActive)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Error(http.StatusInternalServerError, "创建失败"))
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, model.Success(preset))
|
||||
}
|
||||
|
||||
type dreamPresetUpdateRequest struct {
|
||||
Title *string `json:"title"`
|
||||
CoverImage *string `json:"cover_image"`
|
||||
SortOrder *int `json:"sort_order"`
|
||||
IsActive *bool `json:"is_active"`
|
||||
}
|
||||
|
||||
func (h *Handler) UpdateDreamPreset(c *gin.Context) {
|
||||
id, err := parseUintID(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "id 参数错误"))
|
||||
return
|
||||
}
|
||||
var req dreamPresetUpdateRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "参数错误"))
|
||||
return
|
||||
}
|
||||
preset, err := h.svc.UpdateDreamPreset(c.Request.Context(), id, req.Title, req.CoverImage, req.SortOrder, req.IsActive)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Error(http.StatusInternalServerError, "更新失败"))
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, model.Success(preset))
|
||||
}
|
||||
|
||||
func (h *Handler) DeleteDreamPreset(c *gin.Context) {
|
||||
id, err := parseUintID(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "id 参数错误"))
|
||||
return
|
||||
}
|
||||
if err := h.svc.DeleteDreamPreset(c.Request.Context(), id); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Error(http.StatusInternalServerError, "删除失败"))
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, model.Success(gin.H{"deleted": true}))
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
adminservice "wx_service/internal/admin/service"
|
||||
"wx_service/internal/model"
|
||||
)
|
||||
|
||||
type quitDailyListQuery struct {
|
||||
Page int `form:"page"`
|
||||
PageSize int `form:"page_size"`
|
||||
UID int `form:"uid"`
|
||||
DateFrom string `form:"date_from"`
|
||||
DateTo string `form:"date_to"`
|
||||
}
|
||||
|
||||
// ListQuitDailyStatuses GET /api/admin/quit-checkin/daily-statuses
|
||||
func (h *Handler) ListQuitDailyStatuses(c *gin.Context) {
|
||||
var query quitDailyListQuery
|
||||
if err := c.ShouldBindQuery(&query); err != nil {
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "invalid query"))
|
||||
return
|
||||
}
|
||||
if query.Page == 0 {
|
||||
query.Page = 1
|
||||
}
|
||||
if query.PageSize == 0 {
|
||||
query.PageSize = 20
|
||||
}
|
||||
|
||||
dateFrom, err := parseDateOnly(query.DateFrom)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "invalid date_from, expected YYYY-MM-DD"))
|
||||
return
|
||||
}
|
||||
dateTo, err := parseDateOnly(query.DateTo)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "invalid date_to, expected YYYY-MM-DD"))
|
||||
return
|
||||
}
|
||||
|
||||
data, err := h.svc.ListQuitDailyStatuses(c.Request.Context(), adminservice.ListQuitDailyStatusesQuery{
|
||||
Page: query.Page,
|
||||
PageSize: query.PageSize,
|
||||
UID: query.UID,
|
||||
DateFrom: dateFrom,
|
||||
DateTo: dateTo,
|
||||
})
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Error(http.StatusInternalServerError, "load quit daily statuses failed"))
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, model.Success(data))
|
||||
}
|
||||
|
||||
type quitRewardGoalsListQuery struct {
|
||||
Page int `form:"page"`
|
||||
PageSize int `form:"page_size"`
|
||||
UID int `form:"uid"`
|
||||
Status string `form:"status"`
|
||||
}
|
||||
|
||||
// ListQuitRewardGoals GET /api/admin/quit-checkin/reward-goals
|
||||
func (h *Handler) ListQuitRewardGoals(c *gin.Context) {
|
||||
var query quitRewardGoalsListQuery
|
||||
if err := c.ShouldBindQuery(&query); err != nil {
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "invalid query"))
|
||||
return
|
||||
}
|
||||
if query.Page == 0 {
|
||||
query.Page = 1
|
||||
}
|
||||
if query.PageSize == 0 {
|
||||
query.PageSize = 20
|
||||
}
|
||||
|
||||
data, err := h.svc.ListQuitRewardGoals(c.Request.Context(), adminservice.ListQuitRewardGoalsQuery{
|
||||
Page: query.Page,
|
||||
PageSize: query.PageSize,
|
||||
UID: query.UID,
|
||||
Status: strings.TrimSpace(query.Status),
|
||||
})
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Error(http.StatusInternalServerError, "load reward goals failed"))
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, model.Success(data))
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
"wx_service/internal/achievement"
|
||||
)
|
||||
|
||||
func (s *Service) ListAchievementThemes(ctx context.Context) ([]achievement.Theme, error) {
|
||||
var themes []achievement.Theme
|
||||
err := s.db.WithContext(ctx).
|
||||
Preload("Levels", func(db *gorm.DB) *gorm.DB {
|
||||
return db.Order("required_days ASC, sort_order ASC")
|
||||
}).
|
||||
Order("sort_order ASC, id ASC").
|
||||
Find(&themes).Error
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list themes: %w", err)
|
||||
}
|
||||
return themes, nil
|
||||
}
|
||||
|
||||
func (s *Service) GetAchievementTheme(ctx context.Context, id uint) (*achievement.Theme, error) {
|
||||
var theme achievement.Theme
|
||||
err := s.db.WithContext(ctx).
|
||||
Preload("Levels").
|
||||
First(&theme, id).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &theme, nil
|
||||
}
|
||||
|
||||
func (s *Service) CreateAchievementTheme(ctx context.Context, name, key, icon string, sortOrder int, isActive *bool) (*achievement.Theme, error) {
|
||||
active := true
|
||||
if isActive != nil {
|
||||
active = *isActive
|
||||
}
|
||||
theme := achievement.Theme{
|
||||
Name: name,
|
||||
Key: key,
|
||||
Icon: icon,
|
||||
SortOrder: sortOrder,
|
||||
IsActive: active,
|
||||
}
|
||||
if err := s.db.WithContext(ctx).Create(&theme).Error; err != nil {
|
||||
return nil, fmt.Errorf("create theme: %w", err)
|
||||
}
|
||||
return &theme, nil
|
||||
}
|
||||
|
||||
func (s *Service) UpdateAchievementTheme(ctx context.Context, id uint, name, key, icon string, sortOrder int, isActive *bool) (*achievement.Theme, error) {
|
||||
var theme achievement.Theme
|
||||
if err := s.db.WithContext(ctx).First(&theme, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if name != "" {
|
||||
theme.Name = name
|
||||
}
|
||||
if key != "" {
|
||||
theme.Key = key
|
||||
}
|
||||
if icon != "" {
|
||||
theme.Icon = icon
|
||||
}
|
||||
theme.SortOrder = sortOrder
|
||||
if isActive != nil {
|
||||
theme.IsActive = *isActive
|
||||
}
|
||||
if err := s.db.WithContext(ctx).Save(&theme).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &theme, nil
|
||||
}
|
||||
|
||||
func (s *Service) DeleteAchievementTheme(ctx context.Context, id uint) error {
|
||||
return s.db.WithContext(ctx).Delete(&achievement.Theme{}, id).Error
|
||||
}
|
||||
|
||||
func (s *Service) ListAchievementLevels(ctx context.Context, themeID uint) ([]achievement.Level, error) {
|
||||
var levels []achievement.Level
|
||||
err := s.db.WithContext(ctx).
|
||||
Where("theme_id = ?", themeID).
|
||||
Order("required_days ASC, sort_order ASC").
|
||||
Find(&levels).Error
|
||||
return levels, err
|
||||
}
|
||||
|
||||
func (s *Service) CreateAchievementLevel(ctx context.Context, themeID uint, name, icon string, requiredDays, sortOrder int) (*achievement.Level, error) {
|
||||
level := achievement.Level{
|
||||
ThemeID: themeID,
|
||||
Name: name,
|
||||
Icon: icon,
|
||||
RequiredDays: requiredDays,
|
||||
SortOrder: sortOrder,
|
||||
}
|
||||
if err := s.db.WithContext(ctx).Create(&level).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &level, nil
|
||||
}
|
||||
|
||||
func (s *Service) UpdateAchievementLevel(ctx context.Context, id uint, name, icon string, requiredDays, sortOrder int) (*achievement.Level, error) {
|
||||
var level achievement.Level
|
||||
if err := s.db.WithContext(ctx).First(&level, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if name != "" {
|
||||
level.Name = name
|
||||
}
|
||||
if icon != "" {
|
||||
level.Icon = icon
|
||||
}
|
||||
level.RequiredDays = requiredDays
|
||||
level.SortOrder = sortOrder
|
||||
if err := s.db.WithContext(ctx).Save(&level).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &level, nil
|
||||
}
|
||||
|
||||
func (s *Service) DeleteAchievementLevel(ctx context.Context, id uint) error {
|
||||
return s.db.WithContext(ctx).Delete(&achievement.Level{}, id).Error
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
quitmodel "wx_service/internal/quitcheckin/model"
|
||||
)
|
||||
|
||||
func (s *Service) ListDreamPresets(ctx context.Context) ([]quitmodel.DreamPreset, error) {
|
||||
var presets []quitmodel.DreamPreset
|
||||
err := s.db.WithContext(ctx).
|
||||
Order("sort_order ASC, id ASC").
|
||||
Find(&presets).Error
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list dream presets: %w", err)
|
||||
}
|
||||
return presets, nil
|
||||
}
|
||||
|
||||
func (s *Service) CreateDreamPreset(ctx context.Context, title, coverImage string, sortOrder int, isActive *bool) (*quitmodel.DreamPreset, error) {
|
||||
active := true
|
||||
if isActive != nil {
|
||||
active = *isActive
|
||||
}
|
||||
preset := quitmodel.DreamPreset{
|
||||
Title: title,
|
||||
CoverImage: coverImage,
|
||||
SortOrder: sortOrder,
|
||||
IsActive: active,
|
||||
}
|
||||
if err := s.db.WithContext(ctx).Create(&preset).Error; err != nil {
|
||||
return nil, fmt.Errorf("create dream preset: %w", err)
|
||||
}
|
||||
return &preset, nil
|
||||
}
|
||||
|
||||
func (s *Service) UpdateDreamPreset(ctx context.Context, id uint, title, coverImage *string, sortOrder *int, isActive *bool) (*quitmodel.DreamPreset, error) {
|
||||
var preset quitmodel.DreamPreset
|
||||
if err := s.db.WithContext(ctx).First(&preset, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if title != nil {
|
||||
preset.Title = *title
|
||||
}
|
||||
if coverImage != nil {
|
||||
preset.CoverImage = *coverImage
|
||||
}
|
||||
if sortOrder != nil {
|
||||
preset.SortOrder = *sortOrder
|
||||
}
|
||||
if isActive != nil {
|
||||
preset.IsActive = *isActive
|
||||
}
|
||||
if err := s.db.WithContext(ctx).Save(&preset).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &preset, nil
|
||||
}
|
||||
|
||||
func (s *Service) DeleteDreamPreset(ctx context.Context, id uint) error {
|
||||
return s.db.WithContext(ctx).Delete(&quitmodel.DreamPreset{}, id).Error
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
quitmodel "wx_service/internal/quitcheckin/model"
|
||||
)
|
||||
|
||||
// ListQuitDailyStatusesQuery 戒烟打卡每日状态列表查询。
|
||||
type ListQuitDailyStatusesQuery struct {
|
||||
Page int
|
||||
PageSize int
|
||||
UID int
|
||||
DateFrom *time.Time
|
||||
DateTo *time.Time
|
||||
}
|
||||
|
||||
// QuitDailyStatusItem 管理端展示用(含 uid)。
|
||||
type QuitDailyStatusItem struct {
|
||||
ID int `json:"id"`
|
||||
UID int `json:"uid"`
|
||||
Date string `json:"date"`
|
||||
Status string `json:"status"`
|
||||
CheckInAt *time.Time `json:"check_in_at,omitempty"`
|
||||
RelapsedAt *time.Time `json:"relapsed_at,omitempty"`
|
||||
RelapseNum int `json:"relapse_num"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
Note string `json:"note,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// ListQuitDailyStatusesResult 分页结果。
|
||||
type ListQuitDailyStatusesResult struct {
|
||||
List []QuitDailyStatusItem `json:"list"`
|
||||
Total int64 `json:"total"`
|
||||
Page int `json:"page"`
|
||||
PageSize int `json:"page_size"`
|
||||
}
|
||||
|
||||
// ListQuitDailyStatuses 分页查询 fa_quit_checkin_daily_status。
|
||||
func (s *Service) ListQuitDailyStatuses(ctx context.Context, q ListQuitDailyStatusesQuery) (*ListQuitDailyStatusesResult, error) {
|
||||
q.Page, q.PageSize = normalizePage(q.Page, q.PageSize)
|
||||
|
||||
dbQuery := s.db.WithContext(ctx).Model(&quitmodel.DailyStatus{})
|
||||
if q.UID > 0 {
|
||||
dbQuery = dbQuery.Where("uid = ?", q.UID)
|
||||
}
|
||||
if q.DateFrom != nil {
|
||||
dbQuery = dbQuery.Where("date >= ?", q.DateFrom.Format("2006-01-02"))
|
||||
}
|
||||
if q.DateTo != nil {
|
||||
dbQuery = dbQuery.Where("date <= ?", q.DateTo.Format("2006-01-02"))
|
||||
}
|
||||
|
||||
var total int64
|
||||
if err := dbQuery.Count(&total).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var rows []quitmodel.DailyStatus
|
||||
if total > 0 {
|
||||
if err := dbQuery.Order("date DESC, id DESC").
|
||||
Limit(q.PageSize).
|
||||
Offset((q.Page - 1) * q.PageSize).
|
||||
Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
list := make([]QuitDailyStatusItem, 0, len(rows))
|
||||
for _, r := range rows {
|
||||
dateStr := ""
|
||||
if !r.Date.IsZero() {
|
||||
dateStr = r.Date.Format("2006-01-02")
|
||||
}
|
||||
list = append(list, QuitDailyStatusItem{
|
||||
ID: int(r.ID),
|
||||
UID: r.UID,
|
||||
Date: dateStr,
|
||||
Status: r.Status,
|
||||
CheckInAt: r.CheckInAt,
|
||||
RelapsedAt: r.RelapsedAt,
|
||||
RelapseNum: r.RelapseNum,
|
||||
Reason: r.Reason,
|
||||
Note: r.Note,
|
||||
CreatedAt: r.CreatedAt,
|
||||
UpdatedAt: r.UpdatedAt,
|
||||
})
|
||||
}
|
||||
|
||||
return &ListQuitDailyStatusesResult{
|
||||
List: list,
|
||||
Total: total,
|
||||
Page: q.Page,
|
||||
PageSize: q.PageSize,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ListQuitRewardGoalsQuery 用户梦想目标列表查询。
|
||||
type ListQuitRewardGoalsQuery struct {
|
||||
Page int
|
||||
PageSize int
|
||||
UID int
|
||||
Status string
|
||||
}
|
||||
|
||||
// QuitRewardGoalItem 管理端展示用。
|
||||
type QuitRewardGoalItem struct {
|
||||
ID int `json:"id"`
|
||||
UID int `json:"uid"`
|
||||
Title string `json:"title"`
|
||||
TargetAmountCent int `json:"target_amount_cent"`
|
||||
CoverImage string `json:"cover_image,omitempty"`
|
||||
Status string `json:"status"`
|
||||
CompletedAt *time.Time `json:"completed_at,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// ListQuitRewardGoalsResult 分页结果。
|
||||
type ListQuitRewardGoalsResult struct {
|
||||
List []QuitRewardGoalItem `json:"list"`
|
||||
Total int64 `json:"total"`
|
||||
Page int `json:"page"`
|
||||
PageSize int `json:"page_size"`
|
||||
}
|
||||
|
||||
// ListQuitRewardGoals 分页查询 fa_quit_checkin_reward_goal。
|
||||
func (s *Service) ListQuitRewardGoals(ctx context.Context, q ListQuitRewardGoalsQuery) (*ListQuitRewardGoalsResult, error) {
|
||||
q.Page, q.PageSize = normalizePage(q.Page, q.PageSize)
|
||||
|
||||
dbQuery := s.db.WithContext(ctx).Model(&quitmodel.RewardGoal{})
|
||||
if q.UID > 0 {
|
||||
dbQuery = dbQuery.Where("uid = ?", q.UID)
|
||||
}
|
||||
if st := strings.TrimSpace(q.Status); st != "" && st != "all" {
|
||||
dbQuery = dbQuery.Where("status = ?", st)
|
||||
}
|
||||
|
||||
var total int64
|
||||
if err := dbQuery.Count(&total).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var rows []quitmodel.RewardGoal
|
||||
if total > 0 {
|
||||
if err := dbQuery.Order("id DESC").
|
||||
Limit(q.PageSize).
|
||||
Offset((q.Page - 1) * q.PageSize).
|
||||
Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
list := make([]QuitRewardGoalItem, 0, len(rows))
|
||||
for _, r := range rows {
|
||||
list = append(list, QuitRewardGoalItem{
|
||||
ID: int(r.ID),
|
||||
UID: r.UID,
|
||||
Title: r.Title,
|
||||
TargetAmountCent: r.TargetAmountCent,
|
||||
CoverImage: r.CoverImage,
|
||||
Status: r.Status,
|
||||
CompletedAt: r.CompletedAt,
|
||||
CreatedAt: r.CreatedAt,
|
||||
UpdatedAt: r.UpdatedAt,
|
||||
})
|
||||
}
|
||||
|
||||
return &ListQuitRewardGoalsResult{
|
||||
List: list,
|
||||
Total: total,
|
||||
Page: q.Page,
|
||||
PageSize: q.PageSize,
|
||||
}, nil
|
||||
}
|
||||
@@ -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
|
||||
@@ -247,6 +257,7 @@ type ListSmokeProfilesQuery struct {
|
||||
type SmokeProfileItem struct {
|
||||
ID uint `json:"id"`
|
||||
UID int `json:"uid"`
|
||||
Mode string `json:"mode,omitempty"`
|
||||
BaselineCigsPerDay int `json:"baseline_cigs_per_day"`
|
||||
SmokingYears float64 `json:"smoking_years"`
|
||||
PackPriceCent int `json:"pack_price_cent"`
|
||||
@@ -255,6 +266,7 @@ type SmokeProfileItem struct {
|
||||
WakeUpTime string `json:"wake_up_time"`
|
||||
SleepTime string `json:"sleep_time"`
|
||||
QuitDate *time.Time `json:"quit_date,omitempty"`
|
||||
AchievementThemeID *uint `json:"achievement_theme_id,omitempty"`
|
||||
OnboardingCompletedAt *time.Time `json:"onboarding_completed_at,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
@@ -368,6 +380,7 @@ func convertSmokeProfile(row smokemodel.SmokeUserProfile) SmokeProfileItem {
|
||||
return SmokeProfileItem{
|
||||
ID: row.ID,
|
||||
UID: row.UID,
|
||||
Mode: row.Mode,
|
||||
BaselineCigsPerDay: row.BaselineCigsPerDay,
|
||||
SmokingYears: row.SmokingYears,
|
||||
PackPriceCent: row.PackPriceCent,
|
||||
@@ -376,6 +389,7 @@ func convertSmokeProfile(row smokemodel.SmokeUserProfile) SmokeProfileItem {
|
||||
WakeUpTime: row.WakeUpTime,
|
||||
SleepTime: row.SleepTime,
|
||||
QuitDate: row.QuitDate,
|
||||
AchievementThemeID: row.AchievementThemeID,
|
||||
OnboardingCompletedAt: row.OnboardingCompletedAt,
|
||||
CreatedAt: row.CreatedAt,
|
||||
UpdatedAt: row.UpdatedAt,
|
||||
|
||||
@@ -2,11 +2,13 @@ package handler
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"wx_service/internal/common/auth/service"
|
||||
"wx_service/internal/middleware"
|
||||
"wx_service/internal/model"
|
||||
)
|
||||
|
||||
@@ -107,3 +109,100 @@ func (h *AuthHandler) LoginWithWeChat(c *gin.Context) {
|
||||
"mini_program": miniProgramPayload,
|
||||
}))
|
||||
}
|
||||
|
||||
type devLoginRequest struct {
|
||||
MiniProgramID uint `json:"mini_program_id"`
|
||||
}
|
||||
|
||||
// DevLogin 仅在非 release 模式下可用,用于 H5 开发调试。
|
||||
func (h *AuthHandler) DevLogin(c *gin.Context) {
|
||||
if gin.Mode() == gin.ReleaseMode {
|
||||
c.JSON(http.StatusNotFound, model.Error(http.StatusNotFound, "not found"))
|
||||
return
|
||||
}
|
||||
|
||||
var req devLoginRequest
|
||||
_ = c.ShouldBindJSON(&req)
|
||||
if req.MiniProgramID == 0 {
|
||||
req.MiniProgramID = 3
|
||||
}
|
||||
|
||||
result, err := h.authService.DevLogin(c.Request.Context(), req.MiniProgramID)
|
||||
if err != nil {
|
||||
log.Printf("[dev_login] error: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, model.Error(http.StatusInternalServerError, "dev login failed: "+err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, model.Success(gin.H{
|
||||
"user": gin.H{
|
||||
"id": result.User.ID,
|
||||
"mini_program_id": result.User.MiniProgramID,
|
||||
"open_id": result.User.OpenID,
|
||||
"nickname": result.User.NickName,
|
||||
"avatar_url": result.User.AvatarURL,
|
||||
},
|
||||
"session_key": result.SessionKey,
|
||||
"mini_program": gin.H{
|
||||
"id": result.MiniProgram.ID,
|
||||
"name": result.MiniProgram.Name,
|
||||
},
|
||||
}))
|
||||
}
|
||||
|
||||
type updateProfileRequest struct {
|
||||
Nickname string `json:"nickname"`
|
||||
AvatarURL string `json:"avatar_url"`
|
||||
}
|
||||
|
||||
type miniProgramCodeQuery struct {
|
||||
Path string `form:"path"`
|
||||
Width int `form:"width"`
|
||||
}
|
||||
|
||||
func (h *AuthHandler) UpdateProfile(c *gin.Context) {
|
||||
user := middleware.MustCurrentUser(c)
|
||||
|
||||
var req updateProfileRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "参数错误"))
|
||||
return
|
||||
}
|
||||
if req.Nickname == "" && req.AvatarURL == "" {
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "请提供昵称或头像"))
|
||||
return
|
||||
}
|
||||
|
||||
updated, err := h.authService.UpdateProfile(c.Request.Context(), user.ID, req.Nickname, req.AvatarURL)
|
||||
if err != nil {
|
||||
log.Printf("[update_profile] error: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, model.Error(http.StatusInternalServerError, "更新失败"))
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, model.Success(gin.H{
|
||||
"id": updated.ID,
|
||||
"nickname": updated.NickName,
|
||||
"avatar_url": updated.AvatarURL,
|
||||
}))
|
||||
}
|
||||
|
||||
func (h *AuthHandler) GetMiniProgramTestCode(c *gin.Context) {
|
||||
user := middleware.MustCurrentUser(c)
|
||||
|
||||
var query miniProgramCodeQuery
|
||||
if err := c.ShouldBindQuery(&query); err != nil {
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "参数错误"))
|
||||
return
|
||||
}
|
||||
|
||||
codeBytes, err := h.authService.GetMiniProgramTestCode(c.Request.Context(), user.ID, query.Path, query.Width)
|
||||
if err != nil {
|
||||
log.Printf("[get_mini_program_test_code] error: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, model.Error(http.StatusInternalServerError, "获取小程序码失败"))
|
||||
return
|
||||
}
|
||||
|
||||
c.Header("Cache-Control", "no-store")
|
||||
c.Data(http.StatusOK, "image/png", codeBytes)
|
||||
}
|
||||
|
||||
@@ -147,6 +147,76 @@ func (s *AuthService) LoginWithCode(ctx context.Context, req LoginRequest) (*Log
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// DevLogin 开发模式专用:创建或查找测试用户,无需微信授权。
|
||||
func (s *AuthService) DevLogin(ctx context.Context, miniProgramID uint) (*LoginResult, error) {
|
||||
if miniProgramID == 0 {
|
||||
return nil, ErrMiniProgramRequired
|
||||
}
|
||||
|
||||
miniProgram, err := s.miniProgramSvc.GetByID(ctx, miniProgramID)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrMiniProgramNotFound
|
||||
}
|
||||
return nil, fmt.Errorf("load mini program: %w", err)
|
||||
}
|
||||
|
||||
const devOpenID = "dev_test_user"
|
||||
sessionKey := fmt.Sprintf("dev_session_%d", miniProgramID)
|
||||
|
||||
tx := s.db.WithContext(ctx)
|
||||
var user model.User
|
||||
err = tx.Where("mini_program_id = ? AND open_id = ?", miniProgramID, devOpenID).First(&user).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
user = model.User{
|
||||
MiniProgramID: miniProgramID,
|
||||
OpenID: devOpenID,
|
||||
NickName: "开发测试用户",
|
||||
AvatarURL: defaultAvatarURL,
|
||||
SessionKey: sessionKey,
|
||||
}
|
||||
if err := tx.Create(&user).Error; err != nil {
|
||||
return nil, fmt.Errorf("create dev user: %w", err)
|
||||
}
|
||||
} else if err != nil {
|
||||
return nil, fmt.Errorf("query dev user: %w", err)
|
||||
} else {
|
||||
tx.Model(&user).Update("session_key", sessionKey)
|
||||
user.SessionKey = sessionKey
|
||||
}
|
||||
|
||||
return &LoginResult{
|
||||
User: &user,
|
||||
SessionKey: sessionKey,
|
||||
MiniProgram: miniProgram,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// UpdateProfile 更新用户昵称和头像。
|
||||
func (s *AuthService) UpdateProfile(ctx context.Context, userID uint, nickname, avatarURL string) (*model.User, error) {
|
||||
tx := s.db.WithContext(ctx)
|
||||
var user model.User
|
||||
if err := tx.First(&user, userID).Error; err != nil {
|
||||
return nil, fmt.Errorf("find user: %w", err)
|
||||
}
|
||||
|
||||
updates := map[string]interface{}{}
|
||||
if nickname != "" {
|
||||
updates["nick_name"] = nickname
|
||||
user.NickName = nickname
|
||||
}
|
||||
if avatarURL != "" {
|
||||
updates["avatar_url"] = avatarURL
|
||||
user.AvatarURL = avatarURL
|
||||
}
|
||||
if len(updates) > 0 {
|
||||
if err := tx.Model(&user).Updates(updates).Error; err != nil {
|
||||
return nil, fmt.Errorf("update profile: %w", err)
|
||||
}
|
||||
}
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
func (s *AuthService) getSmokeMode(ctx context.Context, uid int) (string, error) {
|
||||
var profile smokemodel.SmokeUserProfile
|
||||
err := s.db.WithContext(ctx).
|
||||
@@ -195,3 +265,32 @@ func normalizeAvatarURL(raw string) string {
|
||||
}
|
||||
return text
|
||||
}
|
||||
|
||||
func (s *AuthService) GetMiniProgramTestCode(ctx context.Context, userID uint, path string, width int) ([]byte, error) {
|
||||
var user model.User
|
||||
if err := s.db.WithContext(ctx).Select("id, mini_program_id").First(&user, userID).Error; err != nil {
|
||||
return nil, fmt.Errorf("find user: %w", err)
|
||||
}
|
||||
if user.MiniProgramID == 0 {
|
||||
return nil, fmt.Errorf("user mini program id missing")
|
||||
}
|
||||
|
||||
miniProgram, err := s.miniProgramSvc.GetByID(ctx, user.MiniProgramID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("load mini program: %w", err)
|
||||
}
|
||||
|
||||
if strings.TrimSpace(path) == "" {
|
||||
path = "pages/nsti/test?resume=0"
|
||||
}
|
||||
if width <= 0 {
|
||||
width = 280
|
||||
}
|
||||
|
||||
client := s.getWeChatClient(miniProgram)
|
||||
codeBytes, err := client.GetWXACode(ctx, path, width)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get mini program test code: %w", err)
|
||||
}
|
||||
return codeBytes, nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"wx_service/internal/model"
|
||||
)
|
||||
|
||||
func newAuthTestDB(t *testing.T) *gorm.DB {
|
||||
t.Helper()
|
||||
|
||||
db, err := gorm.Open(sqlite.Open("file::memory:?cache=shared"), &gorm.Config{})
|
||||
if err != nil {
|
||||
t.Fatalf("open sqlite: %v", err)
|
||||
}
|
||||
|
||||
if err := db.AutoMigrate(&model.User{}); err != nil {
|
||||
t.Fatalf("auto migrate: %v", err)
|
||||
}
|
||||
|
||||
return db
|
||||
}
|
||||
|
||||
func TestAuthServiceUpdateProfilePersistsUserFields(t *testing.T) {
|
||||
db := newAuthTestDB(t)
|
||||
svc := NewAuthService(db, nil)
|
||||
|
||||
user := model.User{
|
||||
MiniProgramID: 1,
|
||||
OpenID: "openid-1",
|
||||
NickName: "旧昵称",
|
||||
AvatarURL: "https://example.com/old.png",
|
||||
SessionKey: "session-1",
|
||||
}
|
||||
if err := db.Create(&user).Error; err != nil {
|
||||
t.Fatalf("seed user: %v", err)
|
||||
}
|
||||
|
||||
updated, err := svc.UpdateProfile(context.Background(), user.ID, "新昵称", "https://example.com/new.png")
|
||||
if err != nil {
|
||||
t.Fatalf("update profile: %v", err)
|
||||
}
|
||||
|
||||
if updated.NickName != "新昵称" {
|
||||
t.Fatalf("expected updated nickname, got %q", updated.NickName)
|
||||
}
|
||||
if updated.AvatarURL != "https://example.com/new.png" {
|
||||
t.Fatalf("expected updated avatar, got %q", updated.AvatarURL)
|
||||
}
|
||||
|
||||
var persisted model.User
|
||||
if err := db.First(&persisted, user.ID).Error; err != nil {
|
||||
t.Fatalf("reload user: %v", err)
|
||||
}
|
||||
|
||||
if persisted.NickName != "新昵称" {
|
||||
t.Fatalf("expected persisted nickname, got %q", persisted.NickName)
|
||||
}
|
||||
if persisted.AvatarURL != "https://example.com/new.png" {
|
||||
t.Fatalf("expected persisted avatar, got %q", persisted.AvatarURL)
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,19 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"time"
|
||||
)
|
||||
|
||||
const weChatCode2SessionURL = "https://api.weixin.qq.com/sns/jscode2session"
|
||||
const weChatAccessTokenURL = "https://api.weixin.qq.com/cgi-bin/token"
|
||||
const weChatGetWXACodeURL = "https://api.weixin.qq.com/wxa/getwxacode"
|
||||
|
||||
// WeChatClient 调用微信接口获取 session/openid。
|
||||
type WeChatClient struct {
|
||||
@@ -30,6 +34,13 @@ type weChatSessionResponse struct {
|
||||
ErrMsg string `json:"errmsg"`
|
||||
}
|
||||
|
||||
type weChatAccessTokenResponse struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
ExpiresIn int `json:"expires_in"`
|
||||
ErrCode int `json:"errcode"`
|
||||
ErrMsg string `json:"errmsg"`
|
||||
}
|
||||
|
||||
// WeChatError 表示微信接口级错误。
|
||||
type WeChatError struct {
|
||||
Code int
|
||||
@@ -87,3 +98,98 @@ func (c *WeChatClient) Code2Session(ctx context.Context, code string) (*WeChatSe
|
||||
|
||||
return &raw.WeChatSession, nil
|
||||
}
|
||||
|
||||
func (c *WeChatClient) GetAccessToken(ctx context.Context) (string, error) {
|
||||
query := url.Values{}
|
||||
query.Set("grant_type", "client_credential")
|
||||
query.Set("appid", c.appID)
|
||||
query.Set("secret", c.appSecret)
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("%s?%s", weChatAccessTokenURL, query.Encode()), nil)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("build access token request: %w", err)
|
||||
}
|
||||
|
||||
resp, err := c.client.Do(req)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("call wechat access token api: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", fmt.Errorf("wechat access token api unexpected status: %s", resp.Status)
|
||||
}
|
||||
|
||||
var raw weChatAccessTokenResponse
|
||||
if err := json.NewDecoder(resp.Body).Decode(&raw); err != nil {
|
||||
return "", fmt.Errorf("decode access token response: %w", err)
|
||||
}
|
||||
if raw.ErrCode != 0 {
|
||||
return "", &WeChatError{Code: raw.ErrCode, Msg: raw.ErrMsg}
|
||||
}
|
||||
if raw.AccessToken == "" {
|
||||
return "", fmt.Errorf("wechat access token missing")
|
||||
}
|
||||
return raw.AccessToken, nil
|
||||
}
|
||||
|
||||
type getWXACodeRequest struct {
|
||||
Path string `json:"path"`
|
||||
Width int `json:"width,omitempty"`
|
||||
AutoColor bool `json:"auto_color"`
|
||||
IsHyaline bool `json:"is_hyaline"`
|
||||
}
|
||||
|
||||
type weChatAPIErrorResponse struct {
|
||||
ErrCode int `json:"errcode"`
|
||||
ErrMsg string `json:"errmsg"`
|
||||
}
|
||||
|
||||
func (c *WeChatClient) GetWXACode(ctx context.Context, path string, width int) ([]byte, error) {
|
||||
accessToken, err := c.GetAccessToken(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
body, err := json.Marshal(getWXACodeRequest{
|
||||
Path: path,
|
||||
Width: width,
|
||||
AutoColor: false,
|
||||
IsHyaline: true,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("marshal getwxacode request: %w", err)
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(
|
||||
ctx,
|
||||
http.MethodPost,
|
||||
fmt.Sprintf("%s?access_token=%s", weChatGetWXACodeURL, url.QueryEscape(accessToken)),
|
||||
bytes.NewReader(body),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("build getwxacode request: %w", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := c.client.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("call wechat getwxacode api: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
payload, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read getwxacode response: %w", err)
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("wechat getwxacode api unexpected status: %s", resp.Status)
|
||||
}
|
||||
|
||||
var apiErr weChatAPIErrorResponse
|
||||
if err := json.Unmarshal(payload, &apiErr); err == nil && apiErr.ErrCode != 0 {
|
||||
return nil, &WeChatError{Code: apiErr.ErrCode, Msg: apiErr.ErrMsg}
|
||||
}
|
||||
|
||||
return payload, nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
package imageutil
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"image"
|
||||
"image/jpeg"
|
||||
"image/png"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/image/draw"
|
||||
)
|
||||
|
||||
type ResizeOptions struct {
|
||||
MaxWidth int
|
||||
Quality int // JPEG quality 1-100
|
||||
}
|
||||
|
||||
func DefaultResizeOptions() ResizeOptions {
|
||||
return ResizeOptions{MaxWidth: 800, Quality: 80}
|
||||
}
|
||||
|
||||
// GenerateThumbnail reads image data, resizes if wider than MaxWidth, and
|
||||
// re-encodes as JPEG. Returns the thumbnail bytes and whether the image
|
||||
// was actually resized (false if already small enough but still re-encoded).
|
||||
func GenerateThumbnail(data []byte, contentType string, opts ResizeOptions) ([]byte, error) {
|
||||
if opts.MaxWidth <= 0 {
|
||||
opts.MaxWidth = 800
|
||||
}
|
||||
if opts.Quality <= 0 || opts.Quality > 100 {
|
||||
opts.Quality = 80
|
||||
}
|
||||
|
||||
src, err := decodeImage(bytes.NewReader(data), contentType)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decode image: %w", err)
|
||||
}
|
||||
|
||||
bounds := src.Bounds()
|
||||
srcW := bounds.Dx()
|
||||
srcH := bounds.Dy()
|
||||
|
||||
dstW := srcW
|
||||
dstH := srcH
|
||||
if srcW > opts.MaxWidth {
|
||||
dstW = opts.MaxWidth
|
||||
dstH = srcH * opts.MaxWidth / srcW
|
||||
}
|
||||
|
||||
dst := image.NewRGBA(image.Rect(0, 0, dstW, dstH))
|
||||
draw.BiLinear.Scale(dst, dst.Bounds(), src, bounds, draw.Over, nil)
|
||||
|
||||
var buf bytes.Buffer
|
||||
if err := jpeg.Encode(&buf, dst, &jpeg.Options{Quality: opts.Quality}); err != nil {
|
||||
return nil, fmt.Errorf("encode jpeg: %w", err)
|
||||
}
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
|
||||
func decodeImage(r io.Reader, contentType string) (image.Image, error) {
|
||||
ct := strings.ToLower(contentType)
|
||||
switch {
|
||||
case strings.Contains(ct, "png"):
|
||||
return png.Decode(r)
|
||||
case strings.Contains(ct, "jpeg"), strings.Contains(ct, "jpg"):
|
||||
return jpeg.Decode(r)
|
||||
default:
|
||||
img, _, err := image.Decode(r)
|
||||
return img, err
|
||||
}
|
||||
}
|
||||
+25
-31
@@ -18,25 +18,24 @@ import (
|
||||
|
||||
"wx_service/config"
|
||||
oss "wx_service/internal/common/oss"
|
||||
qiniuservice "wx_service/internal/common/qiniu/service"
|
||||
uploadservice "wx_service/internal/common/upload/service"
|
||||
"wx_service/internal/middleware"
|
||||
"wx_service/internal/model"
|
||||
)
|
||||
|
||||
type UploadHandler struct {
|
||||
qiniuService *qiniuservice.QiniuService
|
||||
uploadService *uploadservice.UploadService
|
||||
}
|
||||
|
||||
func NewUploadHandler(qiniuService *qiniuservice.QiniuService) *UploadHandler {
|
||||
return &UploadHandler{qiniuService: qiniuService}
|
||||
func NewUploadHandler(uploadService *uploadservice.UploadService) *UploadHandler {
|
||||
return &UploadHandler{uploadService: uploadService}
|
||||
}
|
||||
|
||||
type qiniuTokenRequest struct {
|
||||
// filename 用于保留文件后缀(可选),例如:"a.png"、"video.mp4"
|
||||
type uploadTokenRequest struct {
|
||||
Filename string `json:"filename"`
|
||||
}
|
||||
|
||||
type qiniuCallbackPayload struct {
|
||||
type callbackPayload struct {
|
||||
Key string `json:"key"`
|
||||
Hash string `json:"hash"`
|
||||
Fsize int64 `json:"fsize"`
|
||||
@@ -56,15 +55,14 @@ type uploadTokenResponse struct {
|
||||
|
||||
var extPattern = regexp.MustCompile(`^\.[a-z0-9]{1,10}$`)
|
||||
|
||||
// QiniuToken 返回直传所需的 token/key/upload_url;CDN 为阿里云 OSS 时返回 OSS PostObject 凭证。
|
||||
// 建议放在鉴权后:用当前登录用户生成 key,避免前端写入任意路径。
|
||||
func (h *UploadHandler) QiniuToken(c *gin.Context) {
|
||||
// GetUploadToken 返回直传所需的凭证;CDN 为阿里云 OSS 时返回 OSS PostObject 凭证。
|
||||
func (h *UploadHandler) GetUploadToken(c *gin.Context) {
|
||||
user := middleware.MustCurrentUser(c)
|
||||
|
||||
var req qiniuTokenRequest
|
||||
var req uploadTokenRequest
|
||||
_ = c.ShouldBindJSON(&req)
|
||||
|
||||
cfg := config.AppConfig.Qiniu
|
||||
cfg := config.AppConfig.OSS
|
||||
cdnDomain := strings.TrimSpace(cfg.CDNDomain)
|
||||
|
||||
if oss.IsOSSDomain(cdnDomain) && cfg.AccessKey != "" && cfg.SecretKey != "" && cfg.Bucket != "" {
|
||||
@@ -99,10 +97,10 @@ func (h *UploadHandler) QiniuToken(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
token, err := h.qiniuService.CreateUploadToken(user.MiniProgramID, user.ID, req.Filename)
|
||||
token, err := h.uploadService.CreateUploadToken(user.MiniProgramID, user.ID, req.Filename)
|
||||
if err != nil {
|
||||
if errors.Is(err, qiniuservice.ErrQiniuNotConfigured) {
|
||||
c.JSON(http.StatusServiceUnavailable, model.Error(http.StatusServiceUnavailable, "未配置七牛上传服务,请联系管理员"))
|
||||
if errors.Is(err, uploadservice.ErrUploadNotConfigured) {
|
||||
c.JSON(http.StatusServiceUnavailable, model.Error(http.StatusServiceUnavailable, "未配置上传服务,请联系管理员"))
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusInternalServerError, model.Error(http.StatusInternalServerError, "获取上传凭证失败,请稍后重试"))
|
||||
@@ -111,28 +109,25 @@ func (h *UploadHandler) QiniuToken(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, model.Success(token))
|
||||
}
|
||||
|
||||
// QiniuCallback 处理七牛上传回调(无需登录),通过签名验签确保来源可信。
|
||||
// 说明:
|
||||
// - 验签失败返回 401(非可信请求,直接拒绝)
|
||||
// - 业务处理临时失败返回 503(触发七牛重试)
|
||||
func (h *UploadHandler) QiniuCallback(c *gin.Context) {
|
||||
// UploadCallback 处理上传回调(无需登录),通过签名验签确保来源可信。
|
||||
func (h *UploadHandler) UploadCallback(c *gin.Context) {
|
||||
rawBody, err := io.ReadAll(c.Request.Body)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "读取回调内容失败"))
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.qiniuService.VerifyCallbackSignature(c.Request, rawBody); err != nil {
|
||||
if err := h.uploadService.VerifyCallbackSignature(c.Request, rawBody); err != nil {
|
||||
switch {
|
||||
case errors.Is(err, qiniuservice.ErrQiniuNotConfigured):
|
||||
c.JSON(http.StatusServiceUnavailable, model.Error(http.StatusServiceUnavailable, "七牛服务未配置"))
|
||||
case errors.Is(err, uploadservice.ErrUploadNotConfigured):
|
||||
c.JSON(http.StatusServiceUnavailable, model.Error(http.StatusServiceUnavailable, "上传服务未配置"))
|
||||
default:
|
||||
c.JSON(http.StatusUnauthorized, model.Error(http.StatusUnauthorized, "回调验签失败"))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
payload, err := parseQiniuCallbackPayload(c.ContentType(), rawBody)
|
||||
payload, err := parseCallbackPayload(c.ContentType(), rawBody)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "回调内容格式错误"))
|
||||
return
|
||||
@@ -142,24 +137,23 @@ func (h *UploadHandler) QiniuCallback(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// 当前阶段先记录日志。后续如接入 DB/任务系统,处理失败可保持 503 以触发七牛重试。
|
||||
log.Printf("[qiniu_callback] key=%s hash=%s fsize=%d mimeType=%s", payload.Key, payload.Hash, payload.Fsize, payload.MimeType)
|
||||
log.Printf("[upload_callback] key=%s hash=%s fsize=%d mimeType=%s", payload.Key, payload.Hash, payload.Fsize, payload.MimeType)
|
||||
c.JSON(http.StatusOK, model.Success(gin.H{"ok": true}))
|
||||
}
|
||||
|
||||
func parseQiniuCallbackPayload(contentType string, raw []byte) (qiniuCallbackPayload, error) {
|
||||
var payload qiniuCallbackPayload
|
||||
func parseCallbackPayload(contentType string, raw []byte) (callbackPayload, error) {
|
||||
var payload callbackPayload
|
||||
trimmed := strings.TrimSpace(strings.ToLower(contentType))
|
||||
if strings.Contains(trimmed, "application/json") {
|
||||
if err := json.Unmarshal(raw, &payload); err != nil {
|
||||
return qiniuCallbackPayload{}, err
|
||||
return callbackPayload{}, err
|
||||
}
|
||||
return payload, nil
|
||||
}
|
||||
|
||||
values, err := url.ParseQuery(string(raw))
|
||||
if err != nil {
|
||||
return qiniuCallbackPayload{}, err
|
||||
return callbackPayload{}, err
|
||||
}
|
||||
payload.Key = strings.TrimSpace(values.Get("key"))
|
||||
payload.Hash = strings.TrimSpace(values.Get("hash"))
|
||||
@@ -167,7 +161,7 @@ func parseQiniuCallbackPayload(contentType string, raw []byte) (qiniuCallbackPay
|
||||
if rawFsize := strings.TrimSpace(values.Get("fsize")); rawFsize != "" {
|
||||
fsize, parseErr := strconv.ParseInt(rawFsize, 10, 64)
|
||||
if parseErr != nil {
|
||||
return qiniuCallbackPayload{}, parseErr
|
||||
return callbackPayload{}, parseErr
|
||||
}
|
||||
payload.Fsize = fsize
|
||||
}
|
||||
+22
-22
@@ -12,25 +12,25 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"wx_service/config"
|
||||
qiniuservice "wx_service/internal/common/qiniu/service"
|
||||
uploadservice "wx_service/internal/common/upload/service"
|
||||
)
|
||||
|
||||
func TestQiniuCallbackSuccess(t *testing.T) {
|
||||
func TestUploadCallbackSuccess(t *testing.T) {
|
||||
t.Parallel()
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
cfg := config.QiniuConfig{AccessKey: "ak-test", SecretKey: "sk-test"}
|
||||
h := NewUploadHandler(qiniuservice.NewQiniuService(cfg))
|
||||
cfg := config.OSSConfig{AccessKey: "ak-test", SecretKey: "sk-test"}
|
||||
h := NewUploadHandler(uploadservice.NewUploadService(cfg))
|
||||
|
||||
body := "key=uploads/test.png&hash=abc&fsize=12&mimeType=image%2Fpng"
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/common/upload/qiniu/callback", strings.NewReader(body))
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/common/upload/oss/callback", strings.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
req.Header.Set("Authorization", "QBox "+cfg.AccessKey+":"+signQiniu(req.URL.Path+"\n"+body, cfg.SecretKey))
|
||||
req.Header.Set("Authorization", "QBox "+cfg.AccessKey+":"+signCallback(req.URL.Path+"\n"+body, cfg.SecretKey))
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Request = req
|
||||
|
||||
h.QiniuCallback(c)
|
||||
h.UploadCallback(c)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status=%d, want=200, body=%s", w.Code, w.Body.String())
|
||||
@@ -40,63 +40,63 @@ func TestQiniuCallbackSuccess(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestQiniuCallbackInvalidSignature(t *testing.T) {
|
||||
func TestUploadCallbackInvalidSignature(t *testing.T) {
|
||||
t.Parallel()
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
cfg := config.QiniuConfig{AccessKey: "ak-test", SecretKey: "sk-test"}
|
||||
h := NewUploadHandler(qiniuservice.NewQiniuService(cfg))
|
||||
cfg := config.OSSConfig{AccessKey: "ak-test", SecretKey: "sk-test"}
|
||||
h := NewUploadHandler(uploadservice.NewUploadService(cfg))
|
||||
|
||||
body := "key=uploads/test.png&hash=abc"
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/common/upload/qiniu/callback", strings.NewReader(body))
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/common/upload/oss/callback", strings.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
req.Header.Set("Authorization", "QBox ak-test:bad-sign")
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Request = req
|
||||
|
||||
h.QiniuCallback(c)
|
||||
h.UploadCallback(c)
|
||||
|
||||
if w.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("status=%d, want=401, body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestQiniuCallbackMissingKey(t *testing.T) {
|
||||
func TestUploadCallbackMissingKey(t *testing.T) {
|
||||
t.Parallel()
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
cfg := config.QiniuConfig{AccessKey: "ak-test", SecretKey: "sk-test"}
|
||||
h := NewUploadHandler(qiniuservice.NewQiniuService(cfg))
|
||||
cfg := config.OSSConfig{AccessKey: "ak-test", SecretKey: "sk-test"}
|
||||
h := NewUploadHandler(uploadservice.NewUploadService(cfg))
|
||||
|
||||
body := "hash=abc&fsize=12"
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/common/upload/qiniu/callback", strings.NewReader(body))
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/common/upload/oss/callback", strings.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
req.Header.Set("Authorization", "QBox "+cfg.AccessKey+":"+signQiniu(req.URL.Path+"\n"+body, cfg.SecretKey))
|
||||
req.Header.Set("Authorization", "QBox "+cfg.AccessKey+":"+signCallback(req.URL.Path+"\n"+body, cfg.SecretKey))
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Request = req
|
||||
|
||||
h.QiniuCallback(c)
|
||||
h.UploadCallback(c)
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status=%d, want=400, body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseQiniuCallbackPayloadJSON(t *testing.T) {
|
||||
func TestParseCallbackPayloadJSON(t *testing.T) {
|
||||
t.Parallel()
|
||||
raw := []byte(`{"key":"uploads/test.png","hash":"abc","fsize":321,"mimeType":"image/png"}`)
|
||||
got, err := parseQiniuCallbackPayload("application/json", raw)
|
||||
got, err := parseCallbackPayload("application/json", raw)
|
||||
if err != nil {
|
||||
t.Fatalf("parseQiniuCallbackPayload: %v", err)
|
||||
t.Fatalf("parseCallbackPayload: %v", err)
|
||||
}
|
||||
if got.Key != "uploads/test.png" || got.Hash != "abc" || got.Fsize != 321 {
|
||||
t.Fatalf("unexpected payload: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func signQiniu(signing, secret string) string {
|
||||
func signCallback(signing, secret string) string {
|
||||
mac := hmac.New(sha1.New, []byte(secret))
|
||||
_, _ = mac.Write([]byte(signing))
|
||||
return base64.URLEncoding.WithPadding(base64.NoPadding).EncodeToString(mac.Sum(nil))
|
||||
+24
-29
@@ -19,20 +19,20 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
ErrQiniuNotConfigured = errors.New("qiniu is not configured")
|
||||
ErrQiniuCallbackUnauthorized = errors.New("qiniu callback unauthorized")
|
||||
ErrQiniuCallbackInvalidHeader = errors.New("qiniu callback authorization header is invalid")
|
||||
ErrUploadNotConfigured = errors.New("oss upload is not configured")
|
||||
ErrCallbackUnauthorized = errors.New("upload callback unauthorized")
|
||||
ErrCallbackInvalidHeader = errors.New("upload callback authorization header is invalid")
|
||||
)
|
||||
|
||||
type QiniuService struct {
|
||||
cfg config.QiniuConfig
|
||||
type UploadService struct {
|
||||
cfg config.OSSConfig
|
||||
}
|
||||
|
||||
func NewQiniuService(cfg config.QiniuConfig) *QiniuService {
|
||||
return &QiniuService{cfg: cfg}
|
||||
func NewUploadService(cfg config.OSSConfig) *UploadService {
|
||||
return &UploadService{cfg: cfg}
|
||||
}
|
||||
|
||||
type QiniuUploadToken struct {
|
||||
type UploadToken struct {
|
||||
Token string `json:"token"`
|
||||
Key string `json:"key"`
|
||||
UploadURL string `json:"upload_url"`
|
||||
@@ -42,9 +42,9 @@ type QiniuUploadToken struct {
|
||||
|
||||
var extPattern = regexp.MustCompile(`^\.[a-z0-9]{1,10}$`)
|
||||
|
||||
func (s *QiniuService) CreateUploadToken(miniProgramID uint, userID uint, filename string) (QiniuUploadToken, error) {
|
||||
func (s *UploadService) CreateUploadToken(miniProgramID uint, userID uint, filename string) (UploadToken, error) {
|
||||
if s.cfg.AccessKey == "" || s.cfg.SecretKey == "" || s.cfg.Bucket == "" {
|
||||
return QiniuUploadToken{}, ErrQiniuNotConfigured
|
||||
return UploadToken{}, ErrUploadNotConfigured
|
||||
}
|
||||
|
||||
expireSeconds := s.cfg.TokenExpireSeconds
|
||||
@@ -60,11 +60,9 @@ func (s *QiniuService) CreateUploadToken(miniProgramID uint, userID uint, filena
|
||||
|
||||
randomHex, err := randomHex(16)
|
||||
if err != nil {
|
||||
return QiniuUploadToken{}, fmt.Errorf("generate random key: %w", err)
|
||||
return UploadToken{}, fmt.Errorf("generate random key: %w", err)
|
||||
}
|
||||
|
||||
// 统一由后端生成 key,避免前端随意写入任意路径。
|
||||
// 这里按“业务前缀/小程序/用户/日期/随机名”组织,便于后期排查与管理。
|
||||
keyPrefix := strings.Trim(s.cfg.KeyPrefix, "/")
|
||||
key := fmt.Sprintf("%s/mp_%d/user_%d/%s/%s%s",
|
||||
keyPrefix,
|
||||
@@ -76,10 +74,8 @@ func (s *QiniuService) CreateUploadToken(miniProgramID uint, userID uint, filena
|
||||
)
|
||||
|
||||
putPolicy := map[string]interface{}{
|
||||
// scope = "<bucket>:<key>" 表示只允许写入指定 key(更安全)
|
||||
"scope": fmt.Sprintf("%s:%s", s.cfg.Bucket, key),
|
||||
"deadline": expireAt,
|
||||
// 上传完成后返回给前端的 JSON(七牛会做变量替换)
|
||||
"scope": fmt.Sprintf("%s:%s", s.cfg.Bucket, key),
|
||||
"deadline": expireAt,
|
||||
"returnBody": `{"key":"$(key)","hash":"$(etag)","fsize":$(fsize),"mimeType":"$(mimeType)"}`,
|
||||
}
|
||||
if callbackURL := strings.TrimSpace(s.cfg.CallbackURL); callbackURL != "" {
|
||||
@@ -98,7 +94,7 @@ func (s *QiniuService) CreateUploadToken(miniProgramID uint, userID uint, filena
|
||||
|
||||
policyJSON, err := json.Marshal(putPolicy)
|
||||
if err != nil {
|
||||
return QiniuUploadToken{}, fmt.Errorf("marshal put policy: %w", err)
|
||||
return UploadToken{}, fmt.Errorf("marshal put policy: %w", err)
|
||||
}
|
||||
|
||||
encodedPolicy := urlSafeBase64NoPad(policyJSON)
|
||||
@@ -107,7 +103,7 @@ func (s *QiniuService) CreateUploadToken(miniProgramID uint, userID uint, filena
|
||||
|
||||
token := fmt.Sprintf("%s:%s:%s", s.cfg.AccessKey, encodedSign, encodedPolicy)
|
||||
|
||||
return QiniuUploadToken{
|
||||
return UploadToken{
|
||||
Token: token,
|
||||
Key: key,
|
||||
UploadURL: s.cfg.UploadURL,
|
||||
@@ -116,38 +112,37 @@ func (s *QiniuService) CreateUploadToken(miniProgramID uint, userID uint, filena
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *QiniuService) VerifyCallbackSignature(req *http.Request, rawBody []byte) error {
|
||||
func (s *UploadService) VerifyCallbackSignature(req *http.Request, rawBody []byte) error {
|
||||
if s.cfg.AccessKey == "" || s.cfg.SecretKey == "" {
|
||||
return ErrQiniuNotConfigured
|
||||
return ErrUploadNotConfigured
|
||||
}
|
||||
|
||||
authHeader := strings.TrimSpace(req.Header.Get("Authorization"))
|
||||
if authHeader == "" {
|
||||
return ErrQiniuCallbackInvalidHeader
|
||||
return ErrCallbackInvalidHeader
|
||||
}
|
||||
|
||||
parts := strings.SplitN(authHeader, " ", 2)
|
||||
if len(parts) != 2 {
|
||||
return ErrQiniuCallbackInvalidHeader
|
||||
return ErrCallbackInvalidHeader
|
||||
}
|
||||
scheme := strings.TrimSpace(parts[0])
|
||||
if !strings.EqualFold(scheme, "QBox") {
|
||||
// 七牛上传回调使用 QBox;其它 scheme 视为非法。
|
||||
return ErrQiniuCallbackInvalidHeader
|
||||
return ErrCallbackInvalidHeader
|
||||
}
|
||||
|
||||
token := strings.TrimSpace(parts[1])
|
||||
tokenParts := strings.SplitN(token, ":", 2)
|
||||
if len(tokenParts) != 2 {
|
||||
return ErrQiniuCallbackInvalidHeader
|
||||
return ErrCallbackInvalidHeader
|
||||
}
|
||||
accessKey := strings.TrimSpace(tokenParts[0])
|
||||
providedSign := strings.TrimSpace(tokenParts[1])
|
||||
if accessKey == "" || providedSign == "" {
|
||||
return ErrQiniuCallbackInvalidHeader
|
||||
return ErrCallbackInvalidHeader
|
||||
}
|
||||
if accessKey != s.cfg.AccessKey {
|
||||
return ErrQiniuCallbackUnauthorized
|
||||
return ErrCallbackUnauthorized
|
||||
}
|
||||
|
||||
signing := req.URL.Path
|
||||
@@ -159,7 +154,7 @@ func (s *QiniuService) VerifyCallbackSignature(req *http.Request, rawBody []byte
|
||||
|
||||
expected := urlSafeBase64NoPad(hmacSHA1([]byte(s.cfg.SecretKey), []byte(signing)))
|
||||
if !hmac.Equal([]byte(providedSign), []byte(expected)) {
|
||||
return ErrQiniuCallbackUnauthorized
|
||||
return ErrCallbackUnauthorized
|
||||
}
|
||||
return nil
|
||||
}
|
||||
+12
-12
@@ -13,13 +13,13 @@ import (
|
||||
func TestCreateUploadTokenWithCallbackPolicy(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
svc := NewQiniuService(config.QiniuConfig{
|
||||
svc := NewUploadService(config.OSSConfig{
|
||||
AccessKey: "ak-test",
|
||||
SecretKey: "sk-test",
|
||||
Bucket: "bucket-test",
|
||||
UploadURL: "https://upload.qiniup.com",
|
||||
UploadURL: "https://bucket.oss-cn-beijing.aliyuncs.com",
|
||||
KeyPrefix: "uploads/",
|
||||
CallbackURL: "https://api.example.com/api/v1/common/upload/qiniu/callback",
|
||||
CallbackURL: "https://api.example.com/api/v1/common/upload/oss/callback",
|
||||
CallbackBody: "key=$(key)&hash=$(etag)",
|
||||
CallbackBodyType: "application/x-www-form-urlencoded",
|
||||
})
|
||||
@@ -44,7 +44,7 @@ func TestCreateUploadTokenWithCallbackPolicy(t *testing.T) {
|
||||
t.Fatalf("unmarshal policy: %v", err)
|
||||
}
|
||||
|
||||
if got, _ := policy["callbackUrl"].(string); got != "https://api.example.com/api/v1/common/upload/qiniu/callback" {
|
||||
if got, _ := policy["callbackUrl"].(string); got != "https://api.example.com/api/v1/common/upload/oss/callback" {
|
||||
t.Fatalf("callbackUrl=%q, want callback endpoint", got)
|
||||
}
|
||||
if got, _ := policy["callbackBody"].(string); got != "key=$(key)&hash=$(etag)" {
|
||||
@@ -58,14 +58,14 @@ func TestCreateUploadTokenWithCallbackPolicy(t *testing.T) {
|
||||
func TestVerifyCallbackSignature(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
cfg := config.QiniuConfig{
|
||||
cfg := config.OSSConfig{
|
||||
AccessKey: "ak-test",
|
||||
SecretKey: "sk-test",
|
||||
}
|
||||
svc := NewQiniuService(cfg)
|
||||
svc := NewUploadService(cfg)
|
||||
|
||||
body := []byte("key=uploads/test.png&hash=abc")
|
||||
req := httptest.NewRequest("POST", "http://example.com/api/v1/common/upload/qiniu/callback?x=1", strings.NewReader(string(body)))
|
||||
req := httptest.NewRequest("POST", "http://example.com/api/v1/common/upload/oss/callback?x=1", strings.NewReader(string(body)))
|
||||
signing := req.URL.Path + "?" + req.URL.RawQuery + "\n" + string(body)
|
||||
sign := urlSafeBase64NoPad(hmacSHA1([]byte(cfg.SecretKey), []byte(signing)))
|
||||
req.Header.Set("Authorization", "QBox "+cfg.AccessKey+":"+sign)
|
||||
@@ -78,21 +78,21 @@ func TestVerifyCallbackSignature(t *testing.T) {
|
||||
func TestVerifyCallbackSignatureInvalid(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
cfg := config.QiniuConfig{
|
||||
cfg := config.OSSConfig{
|
||||
AccessKey: "ak-test",
|
||||
SecretKey: "sk-test",
|
||||
}
|
||||
svc := NewQiniuService(cfg)
|
||||
svc := NewUploadService(cfg)
|
||||
|
||||
body := []byte("key=uploads/test.png&hash=abc")
|
||||
req := httptest.NewRequest("POST", "http://example.com/api/v1/common/upload/qiniu/callback", strings.NewReader(string(body)))
|
||||
req := httptest.NewRequest("POST", "http://example.com/api/v1/common/upload/oss/callback", strings.NewReader(string(body)))
|
||||
req.Header.Set("Authorization", "QBox ak-test:bad-sign")
|
||||
|
||||
err := svc.VerifyCallbackSignature(req, body)
|
||||
if err == nil {
|
||||
t.Fatalf("expected signature verification error")
|
||||
}
|
||||
if err != ErrQiniuCallbackUnauthorized {
|
||||
t.Fatalf("error=%v, want=%v", err, ErrQiniuCallbackUnauthorized)
|
||||
if err != ErrCallbackUnauthorized {
|
||||
t.Fatalf("error=%v, want=%v", err, ErrCallbackUnauthorized)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"wx_service/internal/marketing/model"
|
||||
"wx_service/internal/marketing/repository"
|
||||
commonmodel "wx_service/internal/model"
|
||||
)
|
||||
|
||||
type AdPlacementHandler struct {
|
||||
repo *repository.AdPlacementRepository
|
||||
}
|
||||
|
||||
func NewAdPlacementHandler(repo *repository.AdPlacementRepository) *AdPlacementHandler {
|
||||
return &AdPlacementHandler{repo: repo}
|
||||
}
|
||||
|
||||
func (h *AdPlacementHandler) AdminList(c *gin.Context) {
|
||||
list, err := h.repo.ListAll()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, commonmodel.Error(http.StatusInternalServerError, "获取广告位列表失败"))
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, commonmodel.Success(list))
|
||||
}
|
||||
|
||||
type adPlacementCreateReq struct {
|
||||
MiniProgramID uint `json:"mini_program_id" binding:"required"`
|
||||
Name string `json:"name" binding:"required"`
|
||||
AdType string `json:"ad_type" binding:"required"`
|
||||
AdUnitID string `json:"ad_unit_id"`
|
||||
Status *int `json:"status"`
|
||||
Description string `json:"description"`
|
||||
}
|
||||
|
||||
func (h *AdPlacementHandler) AdminCreate(c *gin.Context) {
|
||||
var req adPlacementCreateReq
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, commonmodel.Error(http.StatusBadRequest, "参数错误"))
|
||||
return
|
||||
}
|
||||
|
||||
p := &model.AdPlacement{
|
||||
MiniProgramID: req.MiniProgramID,
|
||||
Name: req.Name,
|
||||
AdType: req.AdType,
|
||||
AdUnitID: req.AdUnitID,
|
||||
Description: req.Description,
|
||||
Status: 1,
|
||||
}
|
||||
if req.Status != nil {
|
||||
p.Status = *req.Status
|
||||
}
|
||||
|
||||
if err := h.repo.Create(p); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, commonmodel.Error(http.StatusInternalServerError, "创建失败"))
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, commonmodel.Success(p))
|
||||
}
|
||||
|
||||
type adPlacementUpdateReq struct {
|
||||
Name *string `json:"name"`
|
||||
AdUnitID *string `json:"ad_unit_id"`
|
||||
Status *int `json:"status"`
|
||||
Description *string `json:"description"`
|
||||
}
|
||||
|
||||
func (h *AdPlacementHandler) AdminUpdate(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil || id == 0 {
|
||||
c.JSON(http.StatusBadRequest, commonmodel.Error(http.StatusBadRequest, "无效 ID"))
|
||||
return
|
||||
}
|
||||
|
||||
p, err := h.repo.FindByID(uint(id))
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrAdPlacementNotFound) {
|
||||
c.JSON(http.StatusNotFound, commonmodel.Error(http.StatusNotFound, "广告位不存在"))
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusInternalServerError, commonmodel.Error(http.StatusInternalServerError, "查询失败"))
|
||||
return
|
||||
}
|
||||
|
||||
var req adPlacementUpdateReq
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, commonmodel.Error(http.StatusBadRequest, "参数错误"))
|
||||
return
|
||||
}
|
||||
|
||||
if req.Name != nil {
|
||||
p.Name = *req.Name
|
||||
}
|
||||
if req.AdUnitID != nil {
|
||||
p.AdUnitID = *req.AdUnitID
|
||||
}
|
||||
if req.Status != nil {
|
||||
p.Status = *req.Status
|
||||
}
|
||||
if req.Description != nil {
|
||||
p.Description = *req.Description
|
||||
}
|
||||
|
||||
if err := h.repo.Update(p); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, commonmodel.Error(http.StatusInternalServerError, "更新失败"))
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, commonmodel.Success(p))
|
||||
}
|
||||
|
||||
func (h *AdPlacementHandler) AdminDelete(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil || id == 0 {
|
||||
c.JSON(http.StatusBadRequest, commonmodel.Error(http.StatusBadRequest, "无效 ID"))
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.repo.Delete(uint(id)); err != nil {
|
||||
if errors.Is(err, repository.ErrAdPlacementNotFound) {
|
||||
c.JSON(http.StatusNotFound, commonmodel.Error(http.StatusNotFound, "广告位不存在"))
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusInternalServerError, commonmodel.Error(http.StatusInternalServerError, "删除失败"))
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, commonmodel.Success(nil))
|
||||
}
|
||||
|
||||
func (h *AdPlacementHandler) GetAdConfig(c *gin.Context) {
|
||||
miniProgramIDStr := c.Query("mini_program_id")
|
||||
miniProgramID, _ := strconv.ParseUint(miniProgramIDStr, 10, 64)
|
||||
if miniProgramID == 0 {
|
||||
c.JSON(http.StatusBadRequest, commonmodel.Error(http.StatusBadRequest, "缺少 mini_program_id"))
|
||||
return
|
||||
}
|
||||
|
||||
p, err := h.repo.FindByMiniProgramAndType(uint(miniProgramID), "rewarded_video")
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrAdPlacementNotFound) {
|
||||
c.JSON(http.StatusOK, commonmodel.Success(gin.H{"ad_unit_id": "", "enabled": false}))
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusInternalServerError, commonmodel.Error(http.StatusInternalServerError, "查询失败"))
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, commonmodel.Success(gin.H{
|
||||
"ad_unit_id": p.AdUnitID,
|
||||
"enabled": p.Status == 1 && p.AdUnitID != "",
|
||||
}))
|
||||
}
|
||||
@@ -1,18 +1,31 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"path"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"wx_service/config"
|
||||
qiniuservice "wx_service/internal/common/qiniu/service"
|
||||
"wx_service/internal/common/imageutil"
|
||||
oss "wx_service/internal/common/oss"
|
||||
uploadservice "wx_service/internal/common/upload/service"
|
||||
"wx_service/internal/marketing/service"
|
||||
"wx_service/internal/middleware"
|
||||
"wx_service/internal/model"
|
||||
)
|
||||
|
||||
var adminExtPattern = regexp.MustCompile(`^\.[a-z0-9]{1,10}$`)
|
||||
|
||||
type DownloadHandler struct {
|
||||
svc *service.DownloadService
|
||||
}
|
||||
@@ -93,19 +106,69 @@ func (h *DownloadHandler) AdminStats(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, model.Success(stats))
|
||||
}
|
||||
|
||||
type adminQiniuTokenRequest struct {
|
||||
type adminUploadTokenRequest struct {
|
||||
Filename string `json:"filename"`
|
||||
}
|
||||
|
||||
func (h *DownloadHandler) AdminQiniuToken(c *gin.Context) {
|
||||
var req adminQiniuTokenRequest
|
||||
type adminUploadTokenResponse struct {
|
||||
Token string `json:"token,omitempty"`
|
||||
Key string `json:"key"`
|
||||
UploadURL string `json:"upload_url"`
|
||||
ExpireAt int64 `json:"expire,omitempty"`
|
||||
CDNDomain string `json:"cdn_domain,omitempty"`
|
||||
OSSAccessKey string `json:"oss_access_key_id,omitempty"`
|
||||
OSSPolicy string `json:"oss_policy,omitempty"`
|
||||
OSSSignature string `json:"oss_signature,omitempty"`
|
||||
}
|
||||
|
||||
func (h *DownloadHandler) AdminUploadToken(c *gin.Context) {
|
||||
var req adminUploadTokenRequest
|
||||
_ = c.ShouldBindJSON(&req)
|
||||
|
||||
qiniuSvc := qiniuservice.NewQiniuService(config.AppConfig.Qiniu)
|
||||
token, err := qiniuSvc.CreateUploadToken(0, 0, req.Filename)
|
||||
cfg := config.AppConfig.OSS
|
||||
if cfg.AccessKey == "" || cfg.SecretKey == "" || cfg.Bucket == "" {
|
||||
c.JSON(http.StatusServiceUnavailable, model.Error(http.StatusServiceUnavailable, "未配置上传服务"))
|
||||
return
|
||||
}
|
||||
|
||||
cdnDomain := strings.TrimSpace(cfg.CDNDomain)
|
||||
|
||||
if oss.IsOSSDomain(cdnDomain) {
|
||||
ext := path.Ext(req.Filename)
|
||||
if ext == "" || !adminExtPattern.MatchString(strings.ToLower(ext)) {
|
||||
ext = ".jpg"
|
||||
}
|
||||
keyPrefix := strings.Trim(cfg.KeyPrefix, "/")
|
||||
key := fmt.Sprintf("%s/admin/%s/%x%s",
|
||||
keyPrefix, time.Now().Format("20060102"), time.Now().UnixNano()&0xffffffff, ext)
|
||||
endpoint := oss.ParseOSSEndpoint(cdnDomain)
|
||||
expireSeconds := cfg.TokenExpireSeconds
|
||||
if expireSeconds <= 0 {
|
||||
expireSeconds = 300
|
||||
}
|
||||
policy, signature, err := oss.PostPolicy(cfg.Bucket, endpoint, key, cfg.SecretKey, expireSeconds)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Error(http.StatusInternalServerError, "生成上传凭证失败"))
|
||||
return
|
||||
}
|
||||
uploadURL := oss.UploadHost(cfg.Bucket, endpoint)
|
||||
cdnHost := "https://" + cfg.Bucket + "." + endpoint + ".aliyuncs.com"
|
||||
c.JSON(http.StatusOK, model.Success(adminUploadTokenResponse{
|
||||
Key: key,
|
||||
UploadURL: uploadURL,
|
||||
CDNDomain: cdnHost,
|
||||
OSSAccessKey: cfg.AccessKey,
|
||||
OSSPolicy: policy,
|
||||
OSSSignature: signature,
|
||||
}))
|
||||
return
|
||||
}
|
||||
|
||||
uploadSvc := uploadservice.NewUploadService(cfg)
|
||||
token, err := uploadSvc.CreateUploadToken(0, 0, req.Filename)
|
||||
if err != nil {
|
||||
if errors.Is(err, qiniuservice.ErrQiniuNotConfigured) {
|
||||
c.JSON(http.StatusServiceUnavailable, model.Error(http.StatusServiceUnavailable, "未配置七牛上传服务"))
|
||||
if errors.Is(err, uploadservice.ErrUploadNotConfigured) {
|
||||
c.JSON(http.StatusServiceUnavailable, model.Error(http.StatusServiceUnavailable, "未配置上传服务"))
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusInternalServerError, model.Error(http.StatusInternalServerError, "获取上传凭证失败"))
|
||||
@@ -114,3 +177,124 @@ func (h *DownloadHandler) AdminQiniuToken(c *gin.Context) {
|
||||
|
||||
c.JSON(http.StatusOK, model.Success(token))
|
||||
}
|
||||
|
||||
// AdminUploadFile 接收管理后台上传的文件,服务端代理转发到 OSS,
|
||||
// 同时自动生成一张压缩缩略图一并上传,减少 CDN 占用。
|
||||
func (h *DownloadHandler) AdminUploadFile(c *gin.Context) {
|
||||
file, header, err := c.Request.FormFile("file")
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "请选择要上传的文件"))
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
if header.Size > 10*1024*1024 {
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "文件大小不能超过 10MB"))
|
||||
return
|
||||
}
|
||||
|
||||
cfg := config.AppConfig.OSS
|
||||
if cfg.AccessKey == "" || cfg.SecretKey == "" || cfg.Bucket == "" {
|
||||
c.JSON(http.StatusServiceUnavailable, model.Error(http.StatusServiceUnavailable, "未配置上传服务"))
|
||||
return
|
||||
}
|
||||
|
||||
cdnDomain := strings.TrimSpace(cfg.CDNDomain)
|
||||
if !oss.IsOSSDomain(cdnDomain) {
|
||||
c.JSON(http.StatusServiceUnavailable, model.Error(http.StatusServiceUnavailable, "仅支持 OSS 上传"))
|
||||
return
|
||||
}
|
||||
|
||||
fileData, err := io.ReadAll(file)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Error(http.StatusInternalServerError, "读取文件失败"))
|
||||
return
|
||||
}
|
||||
|
||||
ext := strings.ToLower(path.Ext(header.Filename))
|
||||
if ext == "" || !adminExtPattern.MatchString(ext) {
|
||||
ext = ".jpg"
|
||||
}
|
||||
keyPrefix := strings.Trim(cfg.KeyPrefix, "/")
|
||||
ts := fmt.Sprintf("%x", time.Now().UnixNano()&0xffffffff)
|
||||
origKey := fmt.Sprintf("%s/admin/%s/%s%s", keyPrefix, time.Now().Format("20060102"), ts, ext)
|
||||
thumbKey := fmt.Sprintf("%s/admin/%s/%s_thumb.jpg", keyPrefix, time.Now().Format("20060102"), ts)
|
||||
|
||||
endpoint := oss.ParseOSSEndpoint(cdnDomain)
|
||||
cdnHost := "https://" + cfg.Bucket + "." + endpoint + ".aliyuncs.com"
|
||||
|
||||
origURL, err := uploadToOSS(cfg, endpoint, origKey, header.Filename, fileData)
|
||||
if err != nil {
|
||||
log.Printf("[admin_upload] upload original error: %v", err)
|
||||
c.JSON(http.StatusBadGateway, model.Error(http.StatusBadGateway, "上传原图到 OSS 失败"))
|
||||
return
|
||||
}
|
||||
|
||||
thumbURL := ""
|
||||
thumbData, thumbErr := imageutil.GenerateThumbnail(fileData, header.Header.Get("Content-Type"), imageutil.DefaultResizeOptions())
|
||||
if thumbErr != nil {
|
||||
log.Printf("[admin_upload] thumbnail generation skipped: %v", thumbErr)
|
||||
} else {
|
||||
if url, err := uploadToOSS(cfg, endpoint, thumbKey, "thumb.jpg", thumbData); err != nil {
|
||||
log.Printf("[admin_upload] upload thumbnail error: %v", err)
|
||||
} else {
|
||||
thumbURL = url
|
||||
}
|
||||
}
|
||||
|
||||
if origURL == "" {
|
||||
origURL = cdnHost + "/" + origKey
|
||||
}
|
||||
|
||||
result := gin.H{"url": origURL}
|
||||
if thumbURL != "" {
|
||||
result["thumbnail_url"] = thumbURL
|
||||
}
|
||||
c.JSON(http.StatusOK, model.Success(result))
|
||||
}
|
||||
|
||||
func uploadToOSS(cfg config.OSSConfig, endpoint, key, filename string, data []byte) (string, error) {
|
||||
expireSeconds := cfg.TokenExpireSeconds
|
||||
if expireSeconds <= 0 {
|
||||
expireSeconds = 300
|
||||
}
|
||||
policy, signature, err := oss.PostPolicy(cfg.Bucket, endpoint, key, cfg.SecretKey, expireSeconds)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("generate policy: %w", err)
|
||||
}
|
||||
|
||||
uploadURL := oss.UploadHost(cfg.Bucket, endpoint)
|
||||
var body bytes.Buffer
|
||||
writer := multipart.NewWriter(&body)
|
||||
writer.WriteField("key", key)
|
||||
writer.WriteField("policy", policy)
|
||||
writer.WriteField("OSSAccessKeyId", cfg.AccessKey)
|
||||
writer.WriteField("Signature", signature)
|
||||
fw, err := writer.CreateFormFile("file", filename)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("create form file: %w", err)
|
||||
}
|
||||
fw.Write(data)
|
||||
writer.Close()
|
||||
|
||||
req, err := http.NewRequest(http.MethodPost, uploadURL, &body)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("new request: %w", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", writer.FormDataContentType())
|
||||
|
||||
client := &http.Client{Timeout: 60 * time.Second}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("do request: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
respBody, _ := io.ReadAll(resp.Body)
|
||||
return "", fmt.Errorf("oss status=%d body=%s", resp.StatusCode, string(respBody))
|
||||
}
|
||||
|
||||
cdnHost := "https://" + cfg.Bucket + "." + endpoint + ".aliyuncs.com"
|
||||
return cdnHost + "/" + key, nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"wx_service/internal/marketing/repository"
|
||||
"wx_service/internal/marketing/service"
|
||||
"wx_service/internal/middleware"
|
||||
"wx_service/internal/model"
|
||||
)
|
||||
|
||||
type UserLogoHandler struct {
|
||||
svc *service.UserLogoService
|
||||
}
|
||||
|
||||
func NewUserLogoHandler(svc *service.UserLogoService) *UserLogoHandler {
|
||||
return &UserLogoHandler{svc: svc}
|
||||
}
|
||||
|
||||
func (h *UserLogoHandler) List(c *gin.Context) {
|
||||
user := middleware.MustCurrentUser(c)
|
||||
logos, err := h.svc.List(user.ID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Error(http.StatusInternalServerError, "获取 Logo 列表失败"))
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, model.Success(logos))
|
||||
}
|
||||
|
||||
func (h *UserLogoHandler) Save(c *gin.Context) {
|
||||
user := middleware.MustCurrentUser(c)
|
||||
|
||||
var req service.SaveLogoRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "请求参数错误"))
|
||||
return
|
||||
}
|
||||
|
||||
logo, err := h.svc.Save(user.ID, req)
|
||||
if err != nil {
|
||||
if errors.Is(err, service.ErrLogoLimitReached) || errors.Is(err, service.ErrLogoTooLarge) {
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, err.Error()))
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusInternalServerError, model.Error(http.StatusInternalServerError, "保存 Logo 失败"))
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, model.Success(logo))
|
||||
}
|
||||
|
||||
func (h *UserLogoHandler) Delete(c *gin.Context) {
|
||||
user := middleware.MustCurrentUser(c)
|
||||
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil || id == 0 {
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "无效的 ID"))
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.svc.Delete(uint(id), user.ID); err != nil {
|
||||
if errors.Is(err, repository.ErrUserLogoNotFound) {
|
||||
c.JSON(http.StatusNotFound, model.Error(http.StatusNotFound, "Logo 不存在"))
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusInternalServerError, model.Error(http.StatusInternalServerError, "删除失败"))
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, model.Success(nil))
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package model
|
||||
|
||||
import "time"
|
||||
|
||||
type AdPlacement struct {
|
||||
ID uint `json:"id" gorm:"primaryKey;comment:主键ID"`
|
||||
MiniProgramID uint `json:"mini_program_id" gorm:"not null;index;comment:小程序ID"`
|
||||
Name string `json:"name" gorm:"size:100;not null;comment:广告位名称"`
|
||||
AdType string `json:"ad_type" gorm:"size:50;not null;default:rewarded_video;comment:广告类型(rewarded_video/banner/interstitial)"`
|
||||
AdUnitID string `json:"ad_unit_id" gorm:"size:200;comment:微信广告单元ID"`
|
||||
Status int `json:"status" gorm:"default:1;comment:状态(0禁用/1启用)"`
|
||||
Description string `json:"description" gorm:"size:500;comment:备注说明"`
|
||||
CreatedAt time.Time `json:"created_at" gorm:"comment:创建时间"`
|
||||
UpdatedAt time.Time `json:"updated_at" gorm:"comment:更新时间"`
|
||||
}
|
||||
|
||||
func (AdPlacement) TableName() string {
|
||||
return "marketing_ad_placements"
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package model
|
||||
|
||||
import "time"
|
||||
|
||||
type UserLogo struct {
|
||||
ID uint `json:"id" gorm:"primaryKey;comment:主键ID"`
|
||||
UserID uint `json:"user_id" gorm:"not null;index;comment:用户ID"`
|
||||
URL string `json:"url" gorm:"size:500;not null;comment:Logo CDN地址"`
|
||||
Filename string `json:"filename" gorm:"size:255;comment:原始文件名"`
|
||||
FileSize int64 `json:"file_size" gorm:"comment:文件大小(字节)"`
|
||||
CreatedAt time.Time `json:"created_at" gorm:"comment:创建时间"`
|
||||
}
|
||||
|
||||
func (UserLogo) TableName() string {
|
||||
return "marketing_user_logos"
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
"wx_service/internal/marketing/model"
|
||||
)
|
||||
|
||||
var ErrAdPlacementNotFound = errors.New("ad placement not found")
|
||||
|
||||
type AdPlacementRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewAdPlacementRepository(db *gorm.DB) *AdPlacementRepository {
|
||||
return &AdPlacementRepository{db: db}
|
||||
}
|
||||
|
||||
func (r *AdPlacementRepository) Create(p *model.AdPlacement) error {
|
||||
if err := r.db.Create(p).Error; err != nil {
|
||||
return fmt.Errorf("create ad placement: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *AdPlacementRepository) Update(p *model.AdPlacement) error {
|
||||
if err := r.db.Save(p).Error; err != nil {
|
||||
return fmt.Errorf("update ad placement: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *AdPlacementRepository) Delete(id uint) error {
|
||||
tx := r.db.Delete(&model.AdPlacement{}, id)
|
||||
if tx.Error != nil {
|
||||
return fmt.Errorf("delete ad placement: %w", tx.Error)
|
||||
}
|
||||
if tx.RowsAffected == 0 {
|
||||
return ErrAdPlacementNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *AdPlacementRepository) FindByID(id uint) (*model.AdPlacement, error) {
|
||||
var p model.AdPlacement
|
||||
err := r.db.First(&p, id).Error
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrAdPlacementNotFound
|
||||
}
|
||||
return nil, fmt.Errorf("find ad placement: %w", err)
|
||||
}
|
||||
return &p, nil
|
||||
}
|
||||
|
||||
func (r *AdPlacementRepository) ListAll() ([]model.AdPlacement, error) {
|
||||
var list []model.AdPlacement
|
||||
err := r.db.Order("id DESC").Find(&list).Error
|
||||
return list, err
|
||||
}
|
||||
|
||||
func (r *AdPlacementRepository) FindByMiniProgramAndType(miniProgramID uint, adType string) (*model.AdPlacement, error) {
|
||||
var p model.AdPlacement
|
||||
err := r.db.Where("mini_program_id = ? AND ad_type = ? AND status = 1", miniProgramID, adType).
|
||||
First(&p).Error
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrAdPlacementNotFound
|
||||
}
|
||||
return nil, fmt.Errorf("find ad placement by type: %w", err)
|
||||
}
|
||||
return &p, nil
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
"wx_service/internal/marketing/model"
|
||||
)
|
||||
|
||||
var ErrUserLogoNotFound = errors.New("user logo not found")
|
||||
|
||||
type UserLogoRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewUserLogoRepository(db *gorm.DB) *UserLogoRepository {
|
||||
return &UserLogoRepository{db: db}
|
||||
}
|
||||
|
||||
func (r *UserLogoRepository) Create(logo *model.UserLogo) error {
|
||||
if err := r.db.Create(logo).Error; err != nil {
|
||||
return fmt.Errorf("create user logo: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *UserLogoRepository) FindByUser(userID uint) ([]model.UserLogo, error) {
|
||||
var logos []model.UserLogo
|
||||
err := r.db.Where("user_id = ?", userID).Order("id DESC").Find(&logos).Error
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list user logos: %w", err)
|
||||
}
|
||||
return logos, nil
|
||||
}
|
||||
|
||||
func (r *UserLogoRepository) FindByID(id, userID uint) (*model.UserLogo, error) {
|
||||
var logo model.UserLogo
|
||||
err := r.db.Where("id = ? AND user_id = ?", id, userID).First(&logo).Error
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrUserLogoNotFound
|
||||
}
|
||||
return nil, fmt.Errorf("find user logo: %w", err)
|
||||
}
|
||||
return &logo, nil
|
||||
}
|
||||
|
||||
func (r *UserLogoRepository) Delete(id, userID uint) error {
|
||||
tx := r.db.Where("id = ? AND user_id = ?", id, userID).Delete(&model.UserLogo{})
|
||||
if tx.Error != nil {
|
||||
return fmt.Errorf("delete user logo: %w", tx.Error)
|
||||
}
|
||||
if tx.RowsAffected == 0 {
|
||||
return ErrUserLogoNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *UserLogoRepository) CountByUser(userID uint) (int64, error) {
|
||||
var count int64
|
||||
err := r.db.Model(&model.UserLogo{}).Where("user_id = ?", userID).Count(&count).Error
|
||||
return count, err
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"wx_service/internal/marketing/model"
|
||||
"wx_service/internal/marketing/repository"
|
||||
)
|
||||
|
||||
const MaxLogosPerUser = 3
|
||||
const MaxLogoFileSize = 2 * 1024 * 1024 // 2MB
|
||||
|
||||
var (
|
||||
ErrLogoLimitReached = errors.New("Logo 数量已达上限")
|
||||
ErrLogoTooLarge = errors.New("Logo 文件不能超过 2MB")
|
||||
)
|
||||
|
||||
type UserLogoService struct {
|
||||
repo *repository.UserLogoRepository
|
||||
}
|
||||
|
||||
func NewUserLogoService(repo *repository.UserLogoRepository) *UserLogoService {
|
||||
return &UserLogoService{repo: repo}
|
||||
}
|
||||
|
||||
type SaveLogoRequest struct {
|
||||
URL string `json:"url" binding:"required"`
|
||||
Filename string `json:"filename"`
|
||||
FileSize int64 `json:"file_size"`
|
||||
}
|
||||
|
||||
func (s *UserLogoService) Save(userID uint, req SaveLogoRequest) (*model.UserLogo, error) {
|
||||
if req.FileSize > MaxLogoFileSize {
|
||||
return nil, ErrLogoTooLarge
|
||||
}
|
||||
|
||||
count, err := s.repo.CountByUser(userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if count >= MaxLogosPerUser {
|
||||
return nil, ErrLogoLimitReached
|
||||
}
|
||||
|
||||
logo := &model.UserLogo{
|
||||
UserID: userID,
|
||||
URL: req.URL,
|
||||
Filename: req.Filename,
|
||||
FileSize: req.FileSize,
|
||||
}
|
||||
if err := s.repo.Create(logo); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return logo, nil
|
||||
}
|
||||
|
||||
func (s *UserLogoService) List(userID uint) ([]model.UserLogo, error) {
|
||||
return s.repo.FindByUser(userID)
|
||||
}
|
||||
|
||||
func (s *UserLogoService) Delete(id, userID uint) error {
|
||||
return s.repo.Delete(id, userID)
|
||||
}
|
||||
@@ -330,6 +330,16 @@ func (h *Handler) ListRelapses(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, model.Success(result))
|
||||
}
|
||||
|
||||
// ListDreamPresets 获取管理员预设的梦想目标列表。
|
||||
func (h *Handler) ListDreamPresets(c *gin.Context) {
|
||||
presets, err := h.service.ListDreamPresets(c.Request.Context())
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Error(http.StatusInternalServerError, "获取预设目标失败"))
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, model.Success(gin.H{"items": presets}))
|
||||
}
|
||||
|
||||
// ListRewardGoals 获取梦想目标列表。
|
||||
// @Summary 获取梦想目标列表
|
||||
// @Description 按状态筛选梦想目标,用于梦想实验室页面展示。
|
||||
|
||||
@@ -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,23 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type DreamPreset 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:"-"`
|
||||
|
||||
Title string `gorm:"column:title;size:64;comment:图标名称" json:"title"`
|
||||
CoverImage string `gorm:"column:cover_image;size:500;comment:图标(emoji或图片URL)" json:"cover_image"`
|
||||
IsActive bool `gorm:"column:is_active;default:true;comment:是否启用" json:"is_active"`
|
||||
SortOrder int `gorm:"column:sort_order;default:0;comment:排序" json:"sort_order"`
|
||||
}
|
||||
|
||||
func (DreamPreset) TableName() string {
|
||||
return "fa_dream_goal_preset"
|
||||
}
|
||||
@@ -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变动日志"
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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_log(stubbed),不接真实通道
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
@@ -986,6 +1266,9 @@ func (s *Service) computeSummary(ctx context.Context, uid int, profile quitmodel
|
||||
}
|
||||
|
||||
elapsedDays := daysBetween(normalizeDate(profile.QuitStartDate), today)
|
||||
if currentStreak > elapsedDays {
|
||||
elapsedDays = currentStreak
|
||||
}
|
||||
theoreticalCigs := elapsedDays * profile.BaselineCigsPerDay
|
||||
avoidedCigs := theoreticalCigs - totalRelapseNum
|
||||
if avoidedCigs < 0 {
|
||||
@@ -1004,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,
|
||||
@@ -1013,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
|
||||
}
|
||||
|
||||
@@ -1129,6 +1423,18 @@ func SortRelapses(items []RelapseEventResult) {
|
||||
})
|
||||
}
|
||||
|
||||
// ListDreamPresets 返回启用的预设梦想目标列表。
|
||||
func (s *Service) ListDreamPresets(ctx context.Context) ([]quitmodel.DreamPreset, error) {
|
||||
var presets []quitmodel.DreamPreset
|
||||
if err := s.db.WithContext(ctx).
|
||||
Where("is_active = ?", true).
|
||||
Order("sort_order ASC, id ASC").
|
||||
Find(&presets).Error; err != nil {
|
||||
return nil, fmt.Errorf("list dream presets: %w", err)
|
||||
}
|
||||
return presets, nil
|
||||
}
|
||||
|
||||
func normalizeShowFields(items []string) []string {
|
||||
allowed := map[string]struct{}{
|
||||
"streak_days": {},
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ func registerAdminRoutes(
|
||||
categoryHandler *marketinghandler.CategoryHandler,
|
||||
templateHandler *marketinghandler.TemplateHandler,
|
||||
downloadHandler *marketinghandler.DownloadHandler,
|
||||
adPlacementHandler *marketinghandler.AdPlacementHandler,
|
||||
) {
|
||||
if handler == nil {
|
||||
return
|
||||
@@ -89,6 +90,24 @@ func registerAdminRoutes(
|
||||
protected.PUT("/smoke/motivation-quotes/:id", handler.UpdateSmokeMotivation)
|
||||
protected.DELETE("/smoke/motivation-quotes/:id", handler.DeleteSmokeMotivation)
|
||||
|
||||
protected.GET("/achievement/themes", handler.ListAchievementThemes)
|
||||
protected.GET("/achievement/themes/:id", handler.GetAchievementTheme)
|
||||
protected.POST("/achievement/themes", handler.CreateAchievementTheme)
|
||||
protected.PUT("/achievement/themes/:id", handler.UpdateAchievementTheme)
|
||||
protected.DELETE("/achievement/themes/:id", handler.DeleteAchievementTheme)
|
||||
protected.GET("/achievement/themes/:id/levels", handler.ListAchievementLevels)
|
||||
protected.POST("/achievement/levels", handler.CreateAchievementLevel)
|
||||
protected.PUT("/achievement/levels/:id", handler.UpdateAchievementLevel)
|
||||
protected.DELETE("/achievement/levels/:id", handler.DeleteAchievementLevel)
|
||||
|
||||
protected.GET("/dream-presets", handler.ListDreamPresets)
|
||||
protected.POST("/dream-presets", handler.CreateDreamPreset)
|
||||
protected.PUT("/dream-presets/:id", handler.UpdateDreamPreset)
|
||||
protected.DELETE("/dream-presets/:id", handler.DeleteDreamPreset)
|
||||
|
||||
protected.GET("/quit-checkin/daily-statuses", handler.ListQuitDailyStatuses)
|
||||
protected.GET("/quit-checkin/reward-goals", handler.ListQuitRewardGoals)
|
||||
|
||||
protected.GET("/memberships/overview", handler.MembershipOverview)
|
||||
protected.GET("/memberships/redeem-codes", handler.ListMembershipRedeemCodes)
|
||||
protected.POST("/memberships/redeem-codes", handler.CreateMembershipRedeemCodes)
|
||||
@@ -107,10 +126,21 @@ func registerAdminRoutes(
|
||||
marketing.PUT("/templates/:id", templateHandler.AdminUpdate)
|
||||
marketing.DELETE("/templates/:id", templateHandler.AdminDelete)
|
||||
|
||||
marketing.GET("/stats", downloadHandler.AdminStats)
|
||||
marketing.POST("/upload/qiniu/token", downloadHandler.AdminQiniuToken)
|
||||
marketing.GET("/stats", downloadHandler.AdminStats)
|
||||
marketing.POST("/upload/oss/token", downloadHandler.AdminUploadToken)
|
||||
marketing.POST("/upload", downloadHandler.AdminUploadFile)
|
||||
}
|
||||
|
||||
if adPlacementHandler != nil {
|
||||
ads := protected.Group("/marketing/ad-placements")
|
||||
{
|
||||
ads.GET("", adPlacementHandler.AdminList)
|
||||
ads.POST("", adPlacementHandler.AdminCreate)
|
||||
ads.PUT("/:id", adPlacementHandler.AdminUpdate)
|
||||
ads.DELETE("/:id", adPlacementHandler.AdminDelete)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,19 +3,16 @@ package routes
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
qiniuhandler "wx_service/internal/common/qiniu/handler"
|
||||
uploadhandler "wx_service/internal/common/upload/handler"
|
||||
)
|
||||
|
||||
func registerCommonPublicRoutes(api *gin.RouterGroup, uploadHandler *qiniuhandler.UploadHandler) {
|
||||
// 七牛上传回调:由七牛服务端调用,不能挂登录鉴权。
|
||||
api.POST("/common/upload/qiniu/callback", uploadHandler.QiniuCallback)
|
||||
func registerCommonPublicRoutes(api *gin.RouterGroup, uploadHandler *uploadhandler.UploadHandler) {
|
||||
api.POST("/common/upload/oss/callback", uploadHandler.UploadCallback)
|
||||
}
|
||||
|
||||
func registerCommonRoutes(protected *gin.RouterGroup, uploadHandler *qiniuhandler.UploadHandler) {
|
||||
// 公共接口(所有小程序共用)
|
||||
func registerCommonRoutes(protected *gin.RouterGroup, uploadHandler *uploadhandler.UploadHandler) {
|
||||
common := protected.Group("/common")
|
||||
{
|
||||
// 七牛直传凭证:前端先拿 token,再直传文件到七牛 upload_url
|
||||
common.POST("/upload/qiniu/token", uploadHandler.QiniuToken)
|
||||
common.POST("/upload/oss/token", uploadHandler.GetUploadToken)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,6 +13,8 @@ func registerMarketingRoutes(
|
||||
categoryHandler *marketinghandler.CategoryHandler,
|
||||
templateHandler *marketinghandler.TemplateHandler,
|
||||
downloadHandler *marketinghandler.DownloadHandler,
|
||||
userLogoHandler *marketinghandler.UserLogoHandler,
|
||||
adPlacementHandler *marketinghandler.AdPlacementHandler,
|
||||
) {
|
||||
if categoryHandler == nil || templateHandler == nil || downloadHandler == nil {
|
||||
return
|
||||
@@ -23,6 +25,10 @@ func registerMarketingRoutes(
|
||||
marketing.GET("/categories", categoryHandler.ListEnabled)
|
||||
marketing.GET("/templates", templateHandler.ListEnabled)
|
||||
marketing.GET("/templates/:id", templateHandler.GetDetail)
|
||||
|
||||
if adPlacementHandler != nil {
|
||||
marketing.GET("/ad-config", adPlacementHandler.GetAdConfig)
|
||||
}
|
||||
}
|
||||
|
||||
protectedMarketing := protected.Group("/marketing")
|
||||
@@ -30,6 +36,12 @@ func registerMarketingRoutes(
|
||||
protectedMarketing.POST("/downloads", downloadHandler.Create)
|
||||
protectedMarketing.POST("/ad_callback", downloadHandler.AdCallback)
|
||||
protectedMarketing.GET("/downloads", downloadHandler.ListByUser)
|
||||
|
||||
if userLogoHandler != nil {
|
||||
protectedMarketing.GET("/logos", userLogoHandler.List)
|
||||
protectedMarketing.POST("/logos", userLogoHandler.Save)
|
||||
protectedMarketing.DELETE("/logos/:id", userLogoHandler.Delete)
|
||||
}
|
||||
}
|
||||
|
||||
admin := api.Group("/admin/marketing")
|
||||
@@ -46,6 +58,7 @@ func registerMarketingRoutes(
|
||||
admin.DELETE("/templates/:id", templateHandler.AdminDelete)
|
||||
|
||||
admin.GET("/stats", downloadHandler.AdminStats)
|
||||
admin.POST("/upload/qiniu/token", downloadHandler.AdminQiniuToken)
|
||||
admin.POST("/upload/oss/token", downloadHandler.AdminUploadToken)
|
||||
admin.POST("/upload", downloadHandler.AdminUploadFile)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,10 +17,20 @@ 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)
|
||||
|
||||
v2.GET("/dream-presets", handler.ListDreamPresets)
|
||||
v2.GET("/reward-goals", handler.ListRewardGoals)
|
||||
v2.POST("/reward-goals", handler.CreateRewardGoal)
|
||||
v2.PUT("/reward-goals/:id", handler.UpdateRewardGoal)
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
|
||||
adminhandler "wx_service/internal/admin"
|
||||
authhandler "wx_service/internal/common/auth/handler"
|
||||
qiniuhandler "wx_service/internal/common/qiniu/handler"
|
||||
uploadhandler "wx_service/internal/common/upload/handler"
|
||||
rediscache "wx_service/internal/common/redis/cache"
|
||||
oahandler "wx_service/internal/common/wechat_official/handler"
|
||||
expiryhandler "wx_service/internal/expiry"
|
||||
@@ -29,7 +29,7 @@ func Register(
|
||||
smokeHandler *smokehandler.SmokeHandler,
|
||||
quitPlanHandler *smokehandler.QuitPlanHandler,
|
||||
redeemCodeHandler *membershiphandler.RedeemCodeHandler,
|
||||
uploadHandler *qiniuhandler.UploadHandler,
|
||||
uploadHandler *uploadhandler.UploadHandler,
|
||||
oaOAuthHandler *oahandler.OAuthHandler,
|
||||
sessionCache *rediscache.SessionUserCache,
|
||||
lawyerHandler *lawyerhandler.LawyerHandler,
|
||||
@@ -39,6 +39,8 @@ func Register(
|
||||
marketingCategoryHandler *marketinghandler.CategoryHandler,
|
||||
marketingTemplateHandler *marketinghandler.TemplateHandler,
|
||||
marketingDownloadHandler *marketinghandler.DownloadHandler,
|
||||
marketingUserLogoHandler *marketinghandler.UserLogoHandler,
|
||||
marketingAdPlacementHandler *marketinghandler.AdPlacementHandler,
|
||||
quitCheckinHandler *quitcheckinhandler.Handler,
|
||||
) {
|
||||
// Register 用来集中注册所有 HTTP 路由,便于工程结构更清晰:
|
||||
@@ -48,6 +50,8 @@ func Register(
|
||||
{
|
||||
// 登录接口:用微信 code 换取/创建用户并返回 session_key(作为后续 Bearer Token)
|
||||
api.POST("/auth/login", authHandler.LoginWithWeChat)
|
||||
// H5 开发调试登录(仅 debug 模式可用)
|
||||
api.POST("/auth/dev-login", authHandler.DevLogin)
|
||||
|
||||
// 公众号网页授权:不需要登录(code 本身来自微信授权回调)
|
||||
registerWeChatOfficialRoutes(api, oaOAuthHandler)
|
||||
@@ -62,13 +66,15 @@ func Register(
|
||||
protected.Use(middleware.AuthMiddleware(db, sessionCache))
|
||||
protected.Use(middleware.RequireUserMiddleware())
|
||||
{
|
||||
protected.PUT("/auth/profile", authHandler.UpdateProfile)
|
||||
protected.GET("/auth/mini-program-test-code", authHandler.GetMiniProgramTestCode)
|
||||
registerCommonRoutes(protected, uploadHandler)
|
||||
registerRemoveWatermarkRoutes(api, protected, videoHandler)
|
||||
registerMembershipRoutes(protected, redeemCodeHandler)
|
||||
registerSmokeRoutes(protected, smokeHandler, quitPlanHandler)
|
||||
}
|
||||
|
||||
registerMarketingRoutes(api, protected, adminToken, marketingCategoryHandler, marketingTemplateHandler, marketingDownloadHandler)
|
||||
registerMarketingRoutes(api, protected, adminToken, marketingCategoryHandler, marketingTemplateHandler, marketingDownloadHandler, marketingUserLogoHandler, marketingAdPlacementHandler)
|
||||
}
|
||||
|
||||
apiV2 := router.Group("/api/v2")
|
||||
@@ -81,7 +87,7 @@ func Register(
|
||||
}
|
||||
}
|
||||
|
||||
registerAdminRoutes(router, adminHandler, marketingCategoryHandler, marketingTemplateHandler, marketingDownloadHandler)
|
||||
registerAdminRoutes(router, adminHandler, marketingCategoryHandler, marketingTemplateHandler, marketingDownloadHandler, marketingAdPlacementHandler)
|
||||
|
||||
// 保质期提醒模块使用独立前缀 /api/expiry,与现有 /api/v1 并存。
|
||||
expiryAPI := router.Group("/api/expiry")
|
||||
|
||||
@@ -50,5 +50,9 @@ func registerSmokeRoutes(protected *gin.RouterGroup, smokeHandler *smokehandler.
|
||||
smoke.GET("/quit-plan", quitPlanHandler.GetQuitPlan)
|
||||
smoke.GET("/quit-plan/days", quitPlanHandler.GetQuitPlanDays)
|
||||
smoke.POST("/quit-plan/reset", quitPlanHandler.ResetQuitPlan)
|
||||
|
||||
// 成就系统
|
||||
smoke.GET("/achievement/themes", smokeHandler.ListAchievementThemes)
|
||||
smoke.GET("/achievement", smokeHandler.GetAchievement)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"wx_service/internal/achievement"
|
||||
"wx_service/internal/middleware"
|
||||
"wx_service/internal/model"
|
||||
)
|
||||
|
||||
func (h *SmokeHandler) ListAchievementThemes(c *gin.Context) {
|
||||
themes, err := h.achievementService.ListActiveThemes(c.Request.Context())
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Error(http.StatusInternalServerError, "获取成就主题失败"))
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, model.Success(gin.H{"themes": themes}))
|
||||
}
|
||||
|
||||
func (h *SmokeHandler) GetAchievement(c *gin.Context) {
|
||||
user := middleware.MustCurrentUser(c)
|
||||
ctx := c.Request.Context()
|
||||
uid := int(user.ID)
|
||||
now := time.Now()
|
||||
|
||||
profile, err := h.smokeProfileService.Get(ctx, uid)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Error(http.StatusInternalServerError, "获取用户信息失败"))
|
||||
return
|
||||
}
|
||||
if profile == nil || profile.AchievementThemeID == nil {
|
||||
c.JSON(http.StatusOK, model.Success(gin.H{"achievement": nil}))
|
||||
return
|
||||
}
|
||||
|
||||
var days int
|
||||
if profile.Mode == "quit" {
|
||||
homeData, err := h.quitCheckinService.Home(ctx, uid, now)
|
||||
if err != nil {
|
||||
log.Printf("achievement: quitcheckin home err uid=%d: %v", uid, err)
|
||||
days = 0
|
||||
} else {
|
||||
days = homeData.Summary.CurrentStreakDays
|
||||
}
|
||||
} else {
|
||||
streakDays, err := h.smokeLogService.GetStreakDays(ctx, uid, now)
|
||||
if err != nil {
|
||||
log.Printf("achievement: smoke streak err uid=%d: %v", uid, err)
|
||||
days = 0
|
||||
}
|
||||
days = streakDays
|
||||
}
|
||||
|
||||
ach, err := h.achievementService.GetUserAchievement(ctx, *profile.AchievementThemeID, days)
|
||||
if err != nil {
|
||||
if err == achievement.ErrThemeNotFound {
|
||||
c.JSON(http.StatusOK, model.Success(gin.H{"achievement": nil}))
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusInternalServerError, model.Error(http.StatusInternalServerError, "获取成就信息失败"))
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, model.Success(gin.H{"achievement": ach}))
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package handler
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -10,8 +11,11 @@ import (
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"wx_service/internal/achievement"
|
||||
"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"
|
||||
)
|
||||
|
||||
@@ -22,6 +26,8 @@ type SmokeHandler struct {
|
||||
smokeNextService *smokeservice.SmokeNextService
|
||||
smokeAINextService *smokeservice.SmokeAINextSmokeService
|
||||
smokeShareService *smokeservice.SmokeShareService
|
||||
achievementService *achievement.Service
|
||||
quitCheckinService *quitcheckinservice.Service
|
||||
}
|
||||
|
||||
func NewSmokeHandler(
|
||||
@@ -31,6 +37,8 @@ func NewSmokeHandler(
|
||||
smokeNextService *smokeservice.SmokeNextService,
|
||||
smokeAINextService *smokeservice.SmokeAINextSmokeService,
|
||||
smokeShareService *smokeservice.SmokeShareService,
|
||||
achievementService *achievement.Service,
|
||||
quitCheckinService *quitcheckinservice.Service,
|
||||
) *SmokeHandler {
|
||||
return &SmokeHandler{
|
||||
smokeLogService: smokeLogService,
|
||||
@@ -39,6 +47,8 @@ func NewSmokeHandler(
|
||||
smokeNextService: smokeNextService,
|
||||
smokeAINextService: smokeAINextService,
|
||||
smokeShareService: smokeShareService,
|
||||
achievementService: achievementService,
|
||||
quitCheckinService: quitCheckinService,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,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) {
|
||||
@@ -112,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。
|
||||
@@ -163,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, "创建记录失败,请稍后重试"))
|
||||
@@ -323,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) {
|
||||
@@ -394,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,
|
||||
})
|
||||
|
||||
@@ -27,6 +27,8 @@ type upsertSmokeProfileRequest struct {
|
||||
SleepTime *string `json:"sleep_time"`
|
||||
|
||||
QuitDate *string `json:"quit_date"`
|
||||
|
||||
AchievementThemeID *uint `json:"achievement_theme_id"`
|
||||
}
|
||||
|
||||
func (h *SmokeHandler) GetProfile(c *gin.Context) {
|
||||
@@ -95,17 +97,21 @@ func (h *SmokeHandler) UpsertProfile(c *gin.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
achievementThemeIDProvided := req.AchievementThemeID != nil
|
||||
|
||||
view, err := h.smokeProfileService.Upsert(c.Request.Context(), int(user.ID), smokeservice.UpsertSmokeProfileRequest{
|
||||
BaselineCigsPerDay: req.BaselineCigsPerDay,
|
||||
SmokingYears: req.SmokingYears,
|
||||
PackPriceCent: req.PackPriceCent,
|
||||
Mode: req.Mode,
|
||||
SmokeMotivations: req.SmokeMotivations,
|
||||
QuitMotivations: req.QuitMotivations,
|
||||
WakeUpTime: req.WakeUpTime,
|
||||
SleepTime: req.SleepTime,
|
||||
QuitDateProvided: quitDateProvided,
|
||||
QuitDate: quitDate,
|
||||
BaselineCigsPerDay: req.BaselineCigsPerDay,
|
||||
SmokingYears: req.SmokingYears,
|
||||
PackPriceCent: req.PackPriceCent,
|
||||
Mode: req.Mode,
|
||||
SmokeMotivations: req.SmokeMotivations,
|
||||
QuitMotivations: req.QuitMotivations,
|
||||
WakeUpTime: req.WakeUpTime,
|
||||
SleepTime: req.SleepTime,
|
||||
QuitDateProvided: quitDateProvided,
|
||||
QuitDate: quitDate,
|
||||
AchievementThemeIDProvided: achievementThemeIDProvided,
|
||||
AchievementThemeID: req.AchievementThemeID,
|
||||
})
|
||||
if err != nil {
|
||||
if errors.Is(err, smokeservice.ErrSmokeProfileInvalidTime) {
|
||||
|
||||
@@ -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"`
|
||||
|
||||
@@ -74,6 +74,8 @@ type SmokeUserProfile struct {
|
||||
|
||||
QuitDate *time.Time `gorm:"column:quit_date;type:date;comment:目标戒烟日期" json:"quit_date,omitempty"`
|
||||
|
||||
AchievementThemeID *uint `gorm:"column:achievement_theme_id;comment:成就主题ID" json:"achievement_theme_id,omitempty"`
|
||||
|
||||
OnboardingCompletedAt *time.Time `gorm:"column:onboarding_completed_at;comment:首次补全完成时间" json:"onboarding_completed_at,omitempty"`
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -99,6 +99,9 @@ type UpsertSmokeProfileRequest struct {
|
||||
|
||||
QuitDateProvided bool
|
||||
QuitDate *time.Time
|
||||
|
||||
AchievementThemeIDProvided bool
|
||||
AchievementThemeID *uint
|
||||
}
|
||||
|
||||
func (s *SmokeProfileService) Upsert(ctx context.Context, uid int, req UpsertSmokeProfileRequest) (SmokeProfileView, error) {
|
||||
@@ -166,6 +169,9 @@ func (s *SmokeProfileService) Upsert(ctx context.Context, uid int, req UpsertSmo
|
||||
if req.QuitDateProvided {
|
||||
profile.QuitDate = req.QuitDate
|
||||
}
|
||||
if req.AchievementThemeIDProvided {
|
||||
profile.AchievementThemeID = req.AchievementThemeID
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
profile.Mode = normalizedSmokeMode(profile.Mode)
|
||||
|
||||
@@ -252,6 +252,10 @@ func (s *SmokeLogService) countResisted(ctx context.Context, uid int, start, end
|
||||
return int(count), nil
|
||||
}
|
||||
|
||||
func (s *SmokeLogService) GetStreakDays(ctx context.Context, uid int, asOf time.Time) (int, error) {
|
||||
return s.computeStreakDays(ctx, uid, asOf)
|
||||
}
|
||||
|
||||
func (s *SmokeLogService) computeStreakDays(ctx context.Context, uid int, asOf time.Time) (int, error) {
|
||||
asOf = dateOnly(asOf)
|
||||
start := asOf.AddDate(0, 0, -400)
|
||||
|
||||
Reference in New Issue
Block a user