Enhance AI and Redis integration for smoke logging features
- Added AI configuration options to .env.example and config.go for OpenAI integration. - Implemented Redis caching for session management in main.go and auth middleware. - Updated smoke logging service to support real smoking time (`smoke_at`) and AI advice retrieval. - Enhanced API routes to include endpoints for AI advice and unlock functionality for non-members. - Improved database schema with new tables for AI advice and unlock records. - Expanded documentation to cover new AI features and Redis caching implementation.
This commit is contained in:
@@ -17,6 +17,16 @@ SHORT_VIDEO_API_KEY=replace-with-real-key
|
||||
SHORT_VIDEO_FREE_QUOTA=20
|
||||
SHORT_VIDEO_TIMEOUT_SECONDS=5
|
||||
|
||||
# AI 配置(OpenAI-compatible)
|
||||
# 例:OpenAI = https://api.openai.com/v1
|
||||
AI_BASE_URL=https://api.openai.com/v1
|
||||
AI_API_KEY=replace-with-ai-api-key
|
||||
AI_MODEL=gpt-4o-mini
|
||||
AI_TIMEOUT_SECONDS=15
|
||||
|
||||
# 简易后台接口鉴权(用于生成兑换码等)
|
||||
ADMIN_API_TOKEN=replace-with-strong-random-token
|
||||
|
||||
# 七牛直传配置(Kodo)
|
||||
QINIU_ACCESS_KEY=replace-with-access-key
|
||||
QINIU_SECRET_KEY=replace-with-secret-key
|
||||
@@ -34,3 +44,11 @@ QINIU_TOKEN_EXPIRE_SECONDS=300
|
||||
WECHAT_OA_APP_ID=replace-with-oa-appid
|
||||
WECHAT_OA_APP_SECRET=replace-with-oa-appsecret
|
||||
WECHAT_OA_TIMEOUT_SECONDS=5
|
||||
|
||||
# Redis(可选,用于缓存 session_key -> user)
|
||||
# 不配置 REDIS_ADDR 时,程序会自动禁用 Redis,保持原来每次请求查 MySQL 的方式。
|
||||
REDIS_ADDR=127.0.0.1:6379
|
||||
REDIS_PASSWORD=
|
||||
REDIS_DB=0
|
||||
REDIS_KEY_PREFIX=wx_service:
|
||||
REDIS_SESSION_TTL_SECONDS=86400
|
||||
|
||||
+24
-2
@@ -10,9 +10,14 @@ import (
|
||||
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"
|
||||
oahandler "wx_service/internal/common/wechat_official/handler"
|
||||
oaservice "wx_service/internal/common/wechat_official/service"
|
||||
"wx_service/internal/database"
|
||||
membershiphandler "wx_service/internal/membership/handler"
|
||||
membershipmodel "wx_service/internal/membership/model"
|
||||
membershipservice "wx_service/internal/membership/service"
|
||||
"wx_service/internal/model"
|
||||
rmhandler "wx_service/internal/remove_watermark/handler"
|
||||
rmmodel "wx_service/internal/remove_watermark/model"
|
||||
@@ -35,9 +40,14 @@ func main() {
|
||||
if err := database.AutoMigrate(
|
||||
&model.MiniProgram{},
|
||||
&model.User{},
|
||||
&model.UserMembership{},
|
||||
&membershipmodel.MembershipRedeemCode{},
|
||||
&membershipmodel.MembershipRedemption{},
|
||||
&rmmodel.VideoParseLog{},
|
||||
&rmmodel.VideoParseUnlock{},
|
||||
&smokemodel.SmokeLog{},
|
||||
&smokemodel.SmokeAIAdvice{},
|
||||
&smokemodel.SmokeAIAdviceUnlock{},
|
||||
); err != nil {
|
||||
log.Fatalf("auto migrate failed: %v", err)
|
||||
}
|
||||
@@ -57,7 +67,11 @@ func main() {
|
||||
videoHandler := rmhandler.NewVideoHandler(videoService)
|
||||
|
||||
smokeLogService := smokeservice.NewSmokeLogService(database.DB)
|
||||
smokeHandler := smokehandler.NewSmokeHandler(smokeLogService)
|
||||
smokeAIAdviceService := smokeservice.NewSmokeAIAdviceService(database.DB, config.AppConfig.AI)
|
||||
smokeHandler := smokehandler.NewSmokeHandler(smokeLogService, smokeAIAdviceService)
|
||||
|
||||
redeemCodeService := membershipservice.NewRedeemCodeService(database.DB, config.AppConfig.Admin.Token)
|
||||
redeemCodeHandler := membershiphandler.NewRedeemCodeHandler(redeemCodeService)
|
||||
|
||||
qiniuService := qiniuservice.NewQiniuService(config.AppConfig.Qiniu)
|
||||
uploadHandler := qiniuhandler.NewUploadHandler(qiniuService)
|
||||
@@ -65,8 +79,16 @@ func main() {
|
||||
oaService := oaservice.NewWeChatOAService(config.AppConfig.WeChatOA)
|
||||
oaOAuthHandler := oahandler.NewOAuthHandler(oaService)
|
||||
|
||||
var sessionCache *rediscache.SessionUserCache
|
||||
redisClient, err := redisservice.NewClient(config.AppConfig.Redis)
|
||||
if err != nil {
|
||||
log.Printf("redis disabled: %v", err)
|
||||
} else if redisClient != nil {
|
||||
sessionCache = rediscache.NewSessionUserCache(redisClient.Redis(), redisClient.KeyPrefix(), redisClient.SessionTTL())
|
||||
}
|
||||
|
||||
// 6) 注册路由:把 URL 映射到 handler
|
||||
routes.Register(router, database.DB, authHandler, videoHandler, smokeHandler, uploadHandler, oaOAuthHandler)
|
||||
routes.Register(router, database.DB, authHandler, videoHandler, smokeHandler, redeemCodeHandler, uploadHandler, oaOAuthHandler, sessionCache)
|
||||
|
||||
// 7) 启动监听端口
|
||||
addr := ":" + config.AppConfig.Server.Port
|
||||
|
||||
@@ -14,8 +14,11 @@ type Config struct {
|
||||
Database DatabaseConfig
|
||||
JWT JWTConfig
|
||||
ShortVideo ShortVideoConfig
|
||||
AI AIConfig
|
||||
Admin AdminConfig
|
||||
Qiniu QiniuConfig
|
||||
WeChatOA WeChatOfficialConfig
|
||||
Redis RedisConfig
|
||||
}
|
||||
|
||||
type ServerConfig struct {
|
||||
@@ -42,6 +45,19 @@ type ShortVideoConfig struct {
|
||||
RequestTimeout time.Duration
|
||||
}
|
||||
|
||||
// AIConfig 用于“AI 建议/问答”等能力的通用配置(OpenAI-compatible)。
|
||||
type AIConfig struct {
|
||||
BaseURL string
|
||||
APIKey string
|
||||
Model string
|
||||
RequestTimeout time.Duration
|
||||
}
|
||||
|
||||
// AdminConfig 用于简单的后台/运维接口鉴权(如生成兑换码)。
|
||||
type AdminConfig struct {
|
||||
Token string
|
||||
}
|
||||
|
||||
// QiniuConfig 用于七牛云(Kodo)直传相关配置。
|
||||
// 前端通常会向后端请求 upload token,然后直传文件到七牛。
|
||||
type QiniuConfig struct {
|
||||
@@ -61,6 +77,15 @@ type WeChatOfficialConfig struct {
|
||||
RequestTimeout time.Duration
|
||||
}
|
||||
|
||||
// RedisConfig 用于可选的 Redis 缓存(例如缓存 session_key -> user,减少 DB 查询)。
|
||||
type RedisConfig struct {
|
||||
Addr string
|
||||
Password string
|
||||
DB int
|
||||
KeyPrefix string
|
||||
SessionTTLSeconds int
|
||||
}
|
||||
|
||||
var AppConfig *Config
|
||||
|
||||
func LoadConfig() {
|
||||
@@ -90,6 +115,15 @@ func LoadConfig() {
|
||||
FreeDailyQuota: getEnvAsInt("SHORT_VIDEO_FREE_QUOTA", 20),
|
||||
RequestTimeout: time.Duration(getEnvAsInt("SHORT_VIDEO_TIMEOUT_SECONDS", 5)) * time.Second,
|
||||
},
|
||||
AI: AIConfig{
|
||||
BaseURL: getEnv("AI_BASE_URL", "https://api.openai.com/v1"),
|
||||
APIKey: getEnv("AI_API_KEY", ""),
|
||||
Model: getEnv("AI_MODEL", "gpt-4o-mini"),
|
||||
RequestTimeout: time.Duration(getEnvAsInt("AI_TIMEOUT_SECONDS", 15)) * time.Second,
|
||||
},
|
||||
Admin: AdminConfig{
|
||||
Token: getEnv("ADMIN_API_TOKEN", ""),
|
||||
},
|
||||
Qiniu: QiniuConfig{
|
||||
AccessKey: getEnv("QINIU_ACCESS_KEY", ""),
|
||||
SecretKey: getEnv("QINIU_SECRET_KEY", ""),
|
||||
@@ -104,6 +138,13 @@ func LoadConfig() {
|
||||
AppSecret: getEnv("WECHAT_OA_APP_SECRET", ""),
|
||||
RequestTimeout: time.Duration(getEnvAsInt("WECHAT_OA_TIMEOUT_SECONDS", 5)) * time.Second,
|
||||
},
|
||||
Redis: RedisConfig{
|
||||
Addr: getEnv("REDIS_ADDR", ""),
|
||||
Password: getEnv("REDIS_PASSWORD", ""),
|
||||
DB: getEnvAsInt("REDIS_DB", 0),
|
||||
KeyPrefix: getEnv("REDIS_KEY_PREFIX", "wx_service:"),
|
||||
SessionTTLSeconds: getEnvAsInt("REDIS_SESSION_TTL_SECONDS", 86400),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
- `docs/common/response.md`
|
||||
- `docs/common/upload_qiniu.md`
|
||||
- `docs/common/wechat_official.md`
|
||||
- `docs/common/redis.md`
|
||||
|
||||
## 去水印小程序
|
||||
|
||||
|
||||
@@ -30,3 +30,7 @@
|
||||
## 微信公众号
|
||||
|
||||
- `docs/common/wechat_official.md`
|
||||
|
||||
## Redis
|
||||
|
||||
- `docs/common/redis.md`
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
# Redis(可选)
|
||||
|
||||
当前项目引入 Redis 的主要目的:缓存 `session_key -> user`,减少每个受保护接口都查询 MySQL(尤其在并发增大时更明显)。
|
||||
|
||||
## 什么时候需要
|
||||
|
||||
- 访问量变大,MySQL 压力主要来自“鉴权查用户”这种高频读
|
||||
- 需要做更复杂的能力:限流、计数、分布式锁、异步队列等
|
||||
|
||||
## 配置
|
||||
|
||||
见 `.env.example`:
|
||||
|
||||
- `REDIS_ADDR`
|
||||
- `REDIS_PASSWORD`
|
||||
- `REDIS_DB`
|
||||
- `REDIS_KEY_PREFIX`
|
||||
- `REDIS_SESSION_TTL_SECONDS`
|
||||
|
||||
说明:
|
||||
- 如果不配置 `REDIS_ADDR`,程序会自动禁用 Redis,行为与之前一致。
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
# 会员兑换码 API
|
||||
|
||||
所有接口前缀:`/api/v1`
|
||||
除登录外都需要:`Authorization: Bearer <session_key>`(见:`docs/common/auth.md`)
|
||||
|
||||
## 1) 生成兑换码(后台口令)
|
||||
|
||||
`POST /api/v1/membership/redeem_codes`
|
||||
|
||||
Header:
|
||||
- `X-Admin-Token: <ADMIN_API_TOKEN>`
|
||||
|
||||
请求体:
|
||||
```json
|
||||
{
|
||||
"count": 10,
|
||||
"plan": "month",
|
||||
"duration_days": 30,
|
||||
"expires_at": "2026-12-31 23:59:59",
|
||||
"max_uses": 1
|
||||
}
|
||||
```
|
||||
|
||||
说明:
|
||||
- 需要在环境变量配置 `ADMIN_API_TOKEN`,否则接口会返回 503。
|
||||
- 兑换码明文只在生成时返回;服务端只保存 `sha256(code)`。
|
||||
|
||||
成功响应(示例):
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"message": "success",
|
||||
"data": {
|
||||
"count": 10,
|
||||
"codes": [
|
||||
{ "code": "ABCD...1234", "plan": "month" }
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 2) 使用兑换码开通/延长会员
|
||||
|
||||
`POST /api/v1/membership/redeem`
|
||||
|
||||
请求体:
|
||||
```json
|
||||
{
|
||||
"code": "ABCD...1234"
|
||||
}
|
||||
```
|
||||
|
||||
成功响应(示例):
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"message": "success",
|
||||
"data": {
|
||||
"plan": "month",
|
||||
"starts_at": "2026-01-03T10:00:00+08:00",
|
||||
"ends_at": "2026-02-02T10:00:00+08:00",
|
||||
"extended": false,
|
||||
"code_suffix": "X7K9Q2"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
常见错误:
|
||||
- `400`:兑换码无效/过期/已被使用/不可用
|
||||
- `401`:未登录或 token 失效
|
||||
|
||||
+54
-1
@@ -12,6 +12,7 @@
|
||||
```json
|
||||
{
|
||||
"smoke_time": "2025-12-31",
|
||||
"smoke_at": "2025-12-31 08:30:00",
|
||||
"remark": "压力大",
|
||||
"level": 2,
|
||||
"num": 3
|
||||
@@ -20,6 +21,7 @@
|
||||
|
||||
说明:
|
||||
- `smoke_time` 可选;不传则默认“当天”。
|
||||
- `smoke_at` 可选;真实抽烟时间(格式 `YYYY-MM-DD HH:MM:SS`)。用于“按时间节点分析/AI 建议”;不传则可用 `createtime` 近似。
|
||||
- `level/num` 可选;不传或传 `<=0` 时会按 `1` 处理。
|
||||
|
||||
curl 示例:
|
||||
@@ -28,7 +30,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","remark":"压力大","level":2,"num":3}'
|
||||
-d '{"smoke_time":"2025-12-31","smoke_at":"2025-12-31 08:30:00","remark":"压力大","level":2,"num":3}'
|
||||
```
|
||||
|
||||
成功响应示例(字段以实际为准):
|
||||
@@ -40,6 +42,7 @@ curl -X POST 'http://127.0.0.1:8080/api/v1/smoke/logs' \
|
||||
"data": {
|
||||
"id": 5202,
|
||||
"smoke_time": "2025-12-31T00:00:00+08:00",
|
||||
"smoke_at": "2025-12-31T08:30:00+08:00",
|
||||
"remark": "压力大",
|
||||
"createtime": 1735600000,
|
||||
"updatetime": 1735600000,
|
||||
@@ -94,6 +97,7 @@ curl -X GET 'http://127.0.0.1:8080/api/v1/smoke/logs/5202' \
|
||||
```json
|
||||
{
|
||||
"smoke_time": "2026-01-01",
|
||||
"smoke_at": "2026-01-01 21:10:00",
|
||||
"remark": "聚会",
|
||||
"level": 3,
|
||||
"num": 1
|
||||
@@ -102,6 +106,7 @@ curl -X GET 'http://127.0.0.1:8080/api/v1/smoke/logs/5202' \
|
||||
|
||||
注意:
|
||||
- 如果你想“清空 smoke_time”,请传空字符串:`{"smoke_time":""}`。
|
||||
- 如果你想“清空 smoke_at”,请传空字符串:`{"smoke_at":""}`。
|
||||
- 如果传 `null` 或者不传 `smoke_time`,后端会认为你没有修改该字段。
|
||||
|
||||
## 5) 删除记录(软删除)
|
||||
@@ -120,3 +125,51 @@ curl -X GET 'http://127.0.0.1:8080/api/v1/smoke/logs/5202' \
|
||||
}
|
||||
```
|
||||
|
||||
## 6) 获取 AI 戒烟建议(会员 + 广告解锁并行)
|
||||
|
||||
`GET /api/v1/smoke/ai/advice?date=2026-01-02`
|
||||
|
||||
说明:
|
||||
- `date` 可选,默认“昨天”(建议针对哪一天的数据)。
|
||||
- 权限:会员用户直接可用;非会员需要先对该 `date` 完成“看广告解锁”(见下一个接口)。
|
||||
- 建议结果会按 `uid + date + prompt_version` 缓存(表:`fa_smoke_ai_advice`)。
|
||||
|
||||
未满足权限时的建议响应(示例):
|
||||
```json
|
||||
{
|
||||
"code": 403,
|
||||
"message": "需要会员或观看广告解锁后才可生成建议",
|
||||
"data": {
|
||||
"date": "2026-01-02",
|
||||
"need": "vip_or_ad"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
成功响应(示例):
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"message": "success",
|
||||
"data": {
|
||||
"date": "2026-01-02",
|
||||
"advice": "..."
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 7) 看广告解锁(用于非会员)
|
||||
|
||||
`POST /api/v1/smoke/ai/advice_unlocks`
|
||||
|
||||
请求体:
|
||||
```json
|
||||
{
|
||||
"date": "2026-01-02",
|
||||
"ad_watched_at": "2026-01-03 09:00:00"
|
||||
}
|
||||
```
|
||||
|
||||
说明:
|
||||
- 该接口用于记录“已完成观看广告”,落库到 `fa_smoke_ai_advice_unlocks`(`uid + unlock_date` 唯一)。
|
||||
- `ad_watched_at` 可由后端取当前时间;如需审计/对账可保留前端上报并做校验。
|
||||
|
||||
@@ -15,3 +15,35 @@
|
||||
- 该表使用旧系统字段:`createtime/updatetime/deletetime`(秒级时间戳),并非 GORM 默认的 `created_at/updated_at/deleted_at`。
|
||||
- 接口层通过 Token 识别用户,`uid` 由后端从登录用户推导,不允许前端传入。
|
||||
|
||||
### 真实抽烟时间(推荐使用 `smoke_at`)
|
||||
|
||||
为支持“按时间节点分析”(例如:昨天哪些时段更容易想抽),建议在 `fa_smoke_log` 中新增:
|
||||
- `smoke_at`:真实抽烟时间(精确到时分秒,可补录)
|
||||
|
||||
数据约定建议:
|
||||
- 前端若提供了真实时间:写入 `smoke_at`;并同步写 `smoke_time = date(smoke_at)`,方便沿用现有按天筛选。
|
||||
- 前端未提供真实时间:`smoke_at=NULL`,时间节点可用 `createtime` 作为近似(但补录会造成偏差)。
|
||||
|
||||
### AI 戒烟建议(会员 + 广告解锁并行)
|
||||
|
||||
面向会员用户提供“昨日 AI 建议”;非会员用户在完成当日/指定日期的“看广告解锁”后也可生成建议。
|
||||
|
||||
涉及表(DDL 见:`docs/sql/smoke.sql`):
|
||||
- `fa_smoke_ai_advice`:按 `uid + advice_date + prompt_version` 缓存建议结果,避免重复调用 AI。
|
||||
- `fa_smoke_ai_advice_unlocks`:非会员用户的“每日解锁”记录(按 `uid + unlock_date` 唯一)。
|
||||
|
||||
建议的权限判断顺序:
|
||||
1) 若用户是会员:直接允许生成/获取建议。
|
||||
2) 否则:查询 `fa_smoke_ai_advice_unlocks` 是否已对 `unlock_date=昨天(或请求 date)` 解锁;已解锁则允许。
|
||||
3) 否则:拒绝并提示“开通会员或观看广告解锁”。
|
||||
|
||||
会员判断建议使用通用会员表:
|
||||
- `user_memberships`(DDL 见:`docs/sql/users.sql`)
|
||||
|
||||
无支付系统时,可用兑换码开通会员:
|
||||
- API:`docs/membership/API.md`
|
||||
- DDL:`docs/sql/membership.sql`
|
||||
|
||||
给 AI 的输入(最小必需)建议包含:
|
||||
- 昨日总量:`SUM(num)`
|
||||
- 时间节点列表:按 `COALESCE(smoke_at, FROM_UNIXTIME(createtime))` 排序的多条记录(每条带 `num/level/remark`)
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
-- 会员兑换码(用于无支付系统时的会员开通)
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `membership_redeem_codes` (
|
||||
`id` bigint unsigned NOT NULL AUTO_INCREMENT,
|
||||
`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
`updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
`deleted_at` datetime DEFAULT NULL,
|
||||
|
||||
`code_hash` varchar(64) NOT NULL COMMENT 'sha256(code) hex;不存明文',
|
||||
`code_suffix` varchar(16) DEFAULT NULL COMMENT '展示/审计用后缀',
|
||||
|
||||
`plan` varchar(30) NOT NULL DEFAULT 'default',
|
||||
`duration_days` int NOT NULL,
|
||||
`expires_at` datetime DEFAULT NULL,
|
||||
|
||||
`max_uses` int NOT NULL DEFAULT 1,
|
||||
`used_uses` int NOT NULL DEFAULT 0,
|
||||
`status` varchar(20) NOT NULL DEFAULT 'active' COMMENT 'active/disabled',
|
||||
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uniq_redeem_code_hash` (`code_hash`),
|
||||
KEY `idx_redeem_code_suffix` (`code_suffix`),
|
||||
KEY `idx_redeem_code_deleted` (`deleted_at`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `membership_redemptions` (
|
||||
`id` bigint unsigned NOT NULL AUTO_INCREMENT,
|
||||
`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
`updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
`deleted_at` datetime DEFAULT NULL,
|
||||
|
||||
`mini_program_id` bigint unsigned NOT NULL,
|
||||
`user_id` bigint unsigned NOT NULL,
|
||||
`redeem_code_id` bigint unsigned NOT NULL,
|
||||
`code_suffix` varchar(16) DEFAULT NULL,
|
||||
`membership_id` bigint unsigned NOT NULL,
|
||||
`client_ip` varchar(64) DEFAULT NULL,
|
||||
`user_agent` varchar(255) DEFAULT NULL,
|
||||
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_redemption_user_date` (`mini_program_id`,`user_id`,`created_at`),
|
||||
KEY `idx_redemption_code` (`redeem_code_id`),
|
||||
KEY `idx_redemption_deleted` (`deleted_at`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
+41
-1
@@ -5,12 +5,52 @@ CREATE TABLE `fa_smoke_log` (
|
||||
`id` int(11) NOT NULL AUTO_INCREMENT,
|
||||
`uid` int(11) NOT NULL COMMENT '用户ID',
|
||||
`smoke_time` date DEFAULT NULL COMMENT '抽烟时间',
|
||||
`smoke_at` datetime DEFAULT NULL COMMENT '真实抽烟时间(可补录,精确到时分秒;为空则可用 createtime 近似)',
|
||||
`remark` text COMMENT '抽烟原因',
|
||||
`createtime` int(11) DEFAULT NULL COMMENT '创建时间',
|
||||
`updatetime` int(11) DEFAULT NULL COMMENT '修改时间',
|
||||
`deletetime` int(11) DEFAULT NULL COMMENT '删除时间',
|
||||
`level` bigint(2) DEFAULT '1' COMMENT '烟瘾程度',
|
||||
`num` int(2) DEFAULT '1' COMMENT '抽烟数量',
|
||||
PRIMARY KEY (`id`,`uid`)
|
||||
PRIMARY KEY (`id`,`uid`),
|
||||
KEY `idx_smoke_uid_date` (`uid`,`smoke_time`),
|
||||
KEY `idx_smoke_uid_at` (`uid`,`smoke_at`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='抽烟记录';
|
||||
|
||||
-- AI 戒烟建议(按天缓存,避免重复调用;通常 date=昨天)
|
||||
-- 说明:
|
||||
-- - access gating:会员用户直接可用;非会员需要先完成“看广告解锁”(见 fa_smoke_ai_advice_unlocks)
|
||||
-- - input_snapshot:建议将“昨日总量 + 时间节点列表”作为 JSON 落库,便于追溯与复现
|
||||
CREATE TABLE IF NOT EXISTS `fa_smoke_ai_advice` (
|
||||
`id` bigint unsigned NOT NULL AUTO_INCREMENT,
|
||||
`uid` int(11) NOT NULL COMMENT '用户ID',
|
||||
`advice_date` date NOT NULL COMMENT '建议针对的日期(通常=昨天)',
|
||||
`prompt_version` varchar(30) NOT NULL DEFAULT 'v1' COMMENT '提示词版本',
|
||||
`provider` varchar(30) DEFAULT NULL COMMENT 'AI 提供方(可选)',
|
||||
`model` varchar(60) DEFAULT NULL COMMENT '模型名(可选)',
|
||||
`input_snapshot` json NOT NULL COMMENT '当次输入快照(昨日总量+节点)',
|
||||
`advice` mediumtext NOT NULL COMMENT 'AI 建议内容(文本/Markdown)',
|
||||
`tokens_in` int DEFAULT NULL,
|
||||
`tokens_out` int DEFAULT NULL,
|
||||
`cost_cent` int DEFAULT NULL COMMENT '成本(分,可选)',
|
||||
`createtime` int(11) DEFAULT NULL COMMENT '创建时间',
|
||||
`updatetime` int(11) DEFAULT NULL COMMENT '修改时间',
|
||||
`deletetime` int(11) DEFAULT NULL COMMENT '删除时间',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uniq_smoke_ai_advice` (`uid`,`advice_date`,`prompt_version`),
|
||||
KEY `idx_smoke_ai_advice_uid_date` (`uid`,`advice_date`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='每日AI戒烟建议';
|
||||
|
||||
-- 每日广告解锁记录(非会员:当天/指定日期解锁后即可生成建议)
|
||||
CREATE TABLE IF NOT EXISTS `fa_smoke_ai_advice_unlocks` (
|
||||
`id` bigint unsigned NOT NULL AUTO_INCREMENT,
|
||||
`uid` int(11) NOT NULL COMMENT '用户ID',
|
||||
`unlock_date` date NOT NULL COMMENT '解锁的建议日期(通常=昨天)',
|
||||
`ad_watched_at` datetime NOT NULL COMMENT '完成观看时间',
|
||||
`createtime` int(11) DEFAULT NULL COMMENT '创建时间',
|
||||
`updatetime` int(11) DEFAULT NULL COMMENT '修改时间',
|
||||
`deletetime` int(11) DEFAULT NULL COMMENT '删除时间',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uniq_smoke_ai_unlock` (`uid`,`unlock_date`),
|
||||
KEY `idx_smoke_ai_unlock_uid_date` (`uid`,`unlock_date`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='AI戒烟建议-广告解锁';
|
||||
|
||||
@@ -32,3 +32,23 @@ CREATE TABLE IF NOT EXISTS `users` (
|
||||
KEY `idx_users_deleted_at` (`deleted_at`),
|
||||
CONSTRAINT `fk_users_mini_program` FOREIGN KEY (`mini_program_id`) REFERENCES `mini_programs`(`id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
-- 会员订阅(通用能力:可给多个功能做“会员优先/免广告”策略)
|
||||
-- 说明:
|
||||
-- - 会员判断:存在 `status='active' AND ends_at > NOW()` 的记录即可视为会员
|
||||
-- - 如果你不想引入该表,也可以选择在 users 表新增 `vip_expires_at` 字段(但扩展性较弱)
|
||||
CREATE TABLE IF NOT EXISTS `user_memberships` (
|
||||
`id` bigint unsigned NOT NULL AUTO_INCREMENT,
|
||||
`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
`updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
`deleted_at` datetime DEFAULT NULL,
|
||||
`mini_program_id` bigint unsigned NOT NULL,
|
||||
`user_id` bigint unsigned NOT NULL,
|
||||
`plan` varchar(30) NOT NULL COMMENT '例如:month/year/lifetime',
|
||||
`status` varchar(20) NOT NULL COMMENT 'active/canceled/expired',
|
||||
`starts_at` datetime NOT NULL,
|
||||
`ends_at` datetime NOT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_membership_user` (`mini_program_id`,`user_id`,`ends_at`),
|
||||
KEY `idx_membership_status` (`mini_program_id`,`user_id`,`status`,`ends_at`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
@@ -5,6 +5,7 @@ go 1.23.6
|
||||
require (
|
||||
github.com/gin-gonic/gin v1.11.0
|
||||
github.com/joho/godotenv v1.5.1
|
||||
github.com/redis/go-redis/v9 v9.17.2
|
||||
gorm.io/driver/mysql v1.6.0
|
||||
gorm.io/gorm v1.31.1
|
||||
)
|
||||
@@ -13,7 +14,9 @@ require (
|
||||
filippo.io/edwards25519 v1.1.0 // indirect
|
||||
github.com/bytedance/sonic v1.14.0 // indirect
|
||||
github.com/bytedance/sonic/loader v0.3.0 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/cloudwego/base64x v0.1.6 // indirect
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.8 // indirect
|
||||
github.com/gin-contrib/sse v1.1.0 // indirect
|
||||
github.com/go-playground/locales v0.14.1 // indirect
|
||||
|
||||
@@ -1,14 +1,22 @@
|
||||
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
|
||||
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
|
||||
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
|
||||
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
|
||||
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
|
||||
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
|
||||
github.com/bytedance/sonic v1.14.0 h1:/OfKt8HFw0kh2rj8N0F6C/qPGRESq0BbaNZgcNXXzQQ=
|
||||
github.com/bytedance/sonic v1.14.0/go.mod h1:WoEbx8WTcFJfzCe0hbmyTGrfjt8PzNEBdxlNUO24NhA=
|
||||
github.com/bytedance/sonic/loader v0.3.0 h1:dskwH8edlzNMctoruo8FPTJDF3vLtDT0sXZwvZJyqeA=
|
||||
github.com/bytedance/sonic/loader v0.3.0/go.mod h1:N8A3vUdtUebEY2/VQC0MyhYeKUFosQU6FxH2JmUe6VI=
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M=
|
||||
github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
|
||||
github.com/gabriel-vasile/mimetype v1.4.8 h1:FfZ3gj38NjllZIeJAmMhr+qKL8Wu+nOoI3GqacKw1NM=
|
||||
github.com/gabriel-vasile/mimetype v1.4.8/go.mod h1:ByKUIKGjh1ODkGM1asKUbQZOLGrPjydw3hYPU2YU9t8=
|
||||
github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w=
|
||||
@@ -58,6 +66,8 @@ github.com/quic-go/qpack v0.5.1 h1:giqksBPnT/HDtZ6VhtFKgoLOWmlyo9Ei6u9PqzIMbhI=
|
||||
github.com/quic-go/qpack v0.5.1/go.mod h1:+PC4XFrEskIVkcLzpEkbLqq1uCoxPhQuvK5rH1ZgaEg=
|
||||
github.com/quic-go/quic-go v0.54.0 h1:6s1YB9QotYI6Ospeiguknbp2Znb/jZYjZLRXn9kMQBg=
|
||||
github.com/quic-go/quic-go v0.54.0/go.mod h1:e68ZEaCdyviluZmy44P6Iey98v/Wfz6HCjQEm+l8zTY=
|
||||
github.com/redis/go-redis/v9 v9.17.2 h1:P2EGsA4qVIM3Pp+aPocCJ7DguDHhqrXNhVcEp4ViluI=
|
||||
github.com/redis/go-redis/v9 v9.17.2/go.mod h1:u410H11HMLoB+TP67dz8rL9s6QW2j76l0//kSOd3370=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"wx_service/internal/model"
|
||||
)
|
||||
|
||||
type SessionUserCache struct {
|
||||
rc *redis.Client
|
||||
keyPrefix string
|
||||
ttl time.Duration
|
||||
}
|
||||
|
||||
func NewSessionUserCache(rc *redis.Client, keyPrefix string, ttl time.Duration) *SessionUserCache {
|
||||
return &SessionUserCache{
|
||||
rc: rc,
|
||||
keyPrefix: keyPrefix,
|
||||
ttl: ttl,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *SessionUserCache) Get(ctx context.Context, token string) (*model.User, bool, error) {
|
||||
if c == nil || c.rc == nil || token == "" {
|
||||
return nil, false, nil
|
||||
}
|
||||
key := c.sessionKey(token)
|
||||
val, err := c.rc.Get(ctx, key).Bytes()
|
||||
if err != nil {
|
||||
if errors.Is(err, redis.Nil) {
|
||||
return nil, false, nil
|
||||
}
|
||||
return nil, false, fmt.Errorf("redis get: %w", err)
|
||||
}
|
||||
|
||||
var user model.User
|
||||
if err := json.Unmarshal(val, &user); err != nil {
|
||||
_ = c.rc.Del(ctx, key).Err()
|
||||
return nil, false, nil
|
||||
}
|
||||
return &user, true, nil
|
||||
}
|
||||
|
||||
func (c *SessionUserCache) Set(ctx context.Context, token string, user *model.User) error {
|
||||
if c == nil || c.rc == nil || token == "" || user == nil {
|
||||
return nil
|
||||
}
|
||||
key := c.sessionKey(token)
|
||||
body, err := json.Marshal(user)
|
||||
if err != nil {
|
||||
return fmt.Errorf("marshal user: %w", err)
|
||||
}
|
||||
if err := c.rc.Set(ctx, key, body, c.ttl).Err(); err != nil {
|
||||
return fmt.Errorf("redis set: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *SessionUserCache) sessionKey(token string) string {
|
||||
prefix := c.keyPrefix
|
||||
if prefix != "" && !strings.HasSuffix(prefix, ":") {
|
||||
prefix += ":"
|
||||
}
|
||||
return prefix + "session_user:" + token
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"wx_service/config"
|
||||
)
|
||||
|
||||
type Client struct {
|
||||
rc *redis.Client
|
||||
keyPrefix string
|
||||
sessionTTL time.Duration
|
||||
}
|
||||
|
||||
func NewClient(cfg config.RedisConfig) (*Client, error) {
|
||||
if cfg.Addr == "" {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
rc := redis.NewClient(&redis.Options{
|
||||
Addr: cfg.Addr,
|
||||
Password: cfg.Password,
|
||||
DB: cfg.DB,
|
||||
})
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer cancel()
|
||||
if err := rc.Ping(ctx).Err(); err != nil {
|
||||
return nil, fmt.Errorf("ping redis: %w", err)
|
||||
}
|
||||
|
||||
ttlSeconds := cfg.SessionTTLSeconds
|
||||
if ttlSeconds <= 0 {
|
||||
ttlSeconds = 86400
|
||||
}
|
||||
|
||||
return &Client{
|
||||
rc: rc,
|
||||
keyPrefix: cfg.KeyPrefix,
|
||||
sessionTTL: time.Duration(ttlSeconds) * time.Second,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *Client) Redis() *redis.Client {
|
||||
return c.rc
|
||||
}
|
||||
|
||||
func (c *Client) KeyPrefix() string {
|
||||
return c.keyPrefix
|
||||
}
|
||||
|
||||
func (c *Client) SessionTTL() time.Duration {
|
||||
return c.sessionTTL
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"wx_service/internal/middleware"
|
||||
"wx_service/internal/model"
|
||||
membershipservice "wx_service/internal/membership/service"
|
||||
)
|
||||
|
||||
type RedeemCodeHandler struct {
|
||||
svc *membershipservice.RedeemCodeService
|
||||
}
|
||||
|
||||
func NewRedeemCodeHandler(svc *membershipservice.RedeemCodeService) *RedeemCodeHandler {
|
||||
return &RedeemCodeHandler{svc: svc}
|
||||
}
|
||||
|
||||
type generateRedeemCodesRequest struct {
|
||||
Count int `json:"count"`
|
||||
Plan string `json:"plan"`
|
||||
DurationDays int `json:"duration_days"`
|
||||
ExpiresAt *string `json:"expires_at"`
|
||||
MaxUses int `json:"max_uses"`
|
||||
}
|
||||
|
||||
func (h *RedeemCodeHandler) Generate(c *gin.Context) {
|
||||
adminToken := c.GetHeader("X-Admin-Token")
|
||||
if err := h.svc.ValidateAdminToken(adminToken); err != nil {
|
||||
switch {
|
||||
case errors.Is(err, membershipservice.ErrAdminTokenRequired):
|
||||
c.JSON(http.StatusServiceUnavailable, model.Error(http.StatusServiceUnavailable, "未配置后台口令,请联系管理员"))
|
||||
return
|
||||
default:
|
||||
c.JSON(http.StatusUnauthorized, model.Error(http.StatusUnauthorized, "无权限"))
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
var req generateRedeemCodesRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "请求参数错误"))
|
||||
return
|
||||
}
|
||||
|
||||
var expiresAt *time.Time
|
||||
if req.ExpiresAt != nil && *req.ExpiresAt != "" {
|
||||
parsed, err := time.ParseInLocation("2006-01-02 15:04:05", *req.ExpiresAt, time.Local)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "expires_at 格式错误,应为 YYYY-MM-DD HH:MM:SS"))
|
||||
return
|
||||
}
|
||||
expiresAt = &parsed
|
||||
}
|
||||
|
||||
codes, err := h.svc.Generate(c.Request.Context(), membershipservice.GenerateRedeemCodesRequest{
|
||||
Count: req.Count,
|
||||
Plan: req.Plan,
|
||||
DurationDays: req.DurationDays,
|
||||
ExpiresAt: expiresAt,
|
||||
MaxUses: req.MaxUses,
|
||||
})
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, model.Success(gin.H{
|
||||
"count": len(codes),
|
||||
"codes": codes,
|
||||
}))
|
||||
}
|
||||
|
||||
type redeemRequest struct {
|
||||
Code string `json:"code" binding:"required"`
|
||||
}
|
||||
|
||||
func (h *RedeemCodeHandler) Redeem(c *gin.Context) {
|
||||
user, ok := middleware.CurrentUser(c)
|
||||
if !ok {
|
||||
c.JSON(http.StatusUnauthorized, model.Error(http.StatusUnauthorized, "未登录或登录已过期"))
|
||||
return
|
||||
}
|
||||
|
||||
var req redeemRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "请求参数错误"))
|
||||
return
|
||||
}
|
||||
|
||||
res, err := h.svc.Redeem(c.Request.Context(), user, req.Code, c.ClientIP(), c.GetHeader("User-Agent"))
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, membershipservice.ErrRedeemCodeInvalid):
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "兑换码无效"))
|
||||
return
|
||||
case errors.Is(err, membershipservice.ErrRedeemCodeExpired):
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "兑换码已过期"))
|
||||
return
|
||||
case errors.Is(err, membershipservice.ErrRedeemCodeUsedUp):
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "兑换码已被使用"))
|
||||
return
|
||||
case errors.Is(err, membershipservice.ErrRedeemCodeDisabled):
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "兑换码不可用"))
|
||||
return
|
||||
default:
|
||||
c.JSON(http.StatusInternalServerError, model.Error(http.StatusInternalServerError, "兑换失败,请稍后重试"))
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, model.Success(gin.H{
|
||||
"plan": res.Plan,
|
||||
"starts_at": res.StartsAt,
|
||||
"ends_at": res.EndsAt,
|
||||
"extended": res.Extended,
|
||||
"code_suffix": res.CodeSuffix,
|
||||
}))
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// MembershipRedeemCode 存储会员兑换码(只存 hash,不存明文 code)。
|
||||
type MembershipRedeemCode 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:"-"`
|
||||
|
||||
// CodeHash 是 code 的 sha256(hex);避免 DB 泄漏导致所有兑换码被直接使用。
|
||||
CodeHash string `gorm:"size:64;uniqueIndex" json:"-"`
|
||||
// CodeSuffix 用于展示/审计(例如最后 6 位)
|
||||
CodeSuffix string `gorm:"size:16;index" json:"code_suffix"`
|
||||
|
||||
Plan string `gorm:"size:30" json:"plan"`
|
||||
DurationDays int `json:"duration_days"`
|
||||
ExpiresAt *time.Time `json:"expires_at,omitempty"`
|
||||
|
||||
MaxUses int `gorm:"default:1" json:"max_uses"`
|
||||
UsedUses int `gorm:"default:0" json:"used_uses"`
|
||||
|
||||
Status string `gorm:"size:20;default:active" json:"status"` // active/disabled
|
||||
}
|
||||
|
||||
func (MembershipRedeemCode) TableName() string {
|
||||
return "membership_redeem_codes"
|
||||
}
|
||||
|
||||
type MembershipRedemption 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:"-"`
|
||||
|
||||
MiniProgramID uint `gorm:"index:idx_redeem_user_date,priority:1" json:"mini_program_id"`
|
||||
UserID uint `gorm:"index:idx_redeem_user_date,priority:2" json:"user_id"`
|
||||
|
||||
RedeemCodeID uint `gorm:"index" json:"redeem_code_id"`
|
||||
CodeSuffix string `gorm:"size:16" json:"code_suffix"`
|
||||
|
||||
MembershipID uint `gorm:"index" json:"membership_id"`
|
||||
|
||||
ClientIP string `gorm:"size:64" json:"client_ip,omitempty"`
|
||||
UserAgent string `gorm:"size:255" json:"user_agent,omitempty"`
|
||||
}
|
||||
|
||||
func (MembershipRedemption) TableName() string {
|
||||
return "membership_redemptions"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,278 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
|
||||
"wx_service/internal/membership/model"
|
||||
usermodel "wx_service/internal/model"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrAdminTokenRequired = errors.New("admin api token is not configured")
|
||||
ErrInvalidAdminToken = errors.New("invalid admin token")
|
||||
|
||||
ErrRedeemCodeInvalid = errors.New("redeem code is invalid")
|
||||
ErrRedeemCodeExpired = errors.New("redeem code is expired")
|
||||
ErrRedeemCodeUsedUp = errors.New("redeem code is already used")
|
||||
ErrRedeemCodeDisabled = errors.New("redeem code is disabled")
|
||||
)
|
||||
|
||||
type RedeemCodeService struct {
|
||||
db *gorm.DB
|
||||
adminToken string
|
||||
}
|
||||
|
||||
func NewRedeemCodeService(db *gorm.DB, adminToken string) *RedeemCodeService {
|
||||
return &RedeemCodeService{
|
||||
db: db,
|
||||
adminToken: adminToken,
|
||||
}
|
||||
}
|
||||
|
||||
type GenerateRedeemCodesRequest struct {
|
||||
Count int
|
||||
Plan string
|
||||
DurationDays int
|
||||
ExpiresAt *time.Time
|
||||
MaxUses int
|
||||
}
|
||||
|
||||
type GeneratedRedeemCode struct {
|
||||
Code string `json:"code"`
|
||||
Plan string `json:"plan"`
|
||||
}
|
||||
|
||||
func (s *RedeemCodeService) ValidateAdminToken(token string) error {
|
||||
if s.adminToken == "" {
|
||||
return ErrAdminTokenRequired
|
||||
}
|
||||
if token == "" || token != s.adminToken {
|
||||
return ErrInvalidAdminToken
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *RedeemCodeService) Generate(ctx context.Context, req GenerateRedeemCodesRequest) ([]GeneratedRedeemCode, error) {
|
||||
count := req.Count
|
||||
if count <= 0 {
|
||||
count = 1
|
||||
}
|
||||
if count > 500 {
|
||||
count = 500
|
||||
}
|
||||
plan := strings.TrimSpace(req.Plan)
|
||||
if plan == "" {
|
||||
plan = "default"
|
||||
}
|
||||
if req.DurationDays <= 0 {
|
||||
return nil, fmt.Errorf("duration_days must be > 0")
|
||||
}
|
||||
maxUses := req.MaxUses
|
||||
if maxUses <= 0 {
|
||||
maxUses = 1
|
||||
}
|
||||
|
||||
results := make([]GeneratedRedeemCode, 0, count)
|
||||
records := make([]model.MembershipRedeemCode, 0, count)
|
||||
|
||||
// 生成时尽量保证唯一性;如遇碰撞(极低概率)则重试。
|
||||
for len(records) < count {
|
||||
code, err := generateCode(20)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
hash := hashCode(code)
|
||||
suffix := suffixOf(code, 6)
|
||||
|
||||
records = append(records, model.MembershipRedeemCode{
|
||||
CodeHash: hash,
|
||||
CodeSuffix: suffix,
|
||||
Plan: plan,
|
||||
DurationDays: req.DurationDays,
|
||||
ExpiresAt: req.ExpiresAt,
|
||||
MaxUses: maxUses,
|
||||
UsedUses: 0,
|
||||
Status: "active",
|
||||
})
|
||||
results = append(results, GeneratedRedeemCode{Code: code, Plan: plan})
|
||||
}
|
||||
|
||||
if err := s.db.WithContext(ctx).Create(&records).Error; err != nil {
|
||||
return nil, fmt.Errorf("save redeem codes: %w", err)
|
||||
}
|
||||
return results, nil
|
||||
}
|
||||
|
||||
type RedeemResult struct {
|
||||
Plan string `json:"plan"`
|
||||
StartsAt time.Time `json:"starts_at"`
|
||||
EndsAt time.Time `json:"ends_at"`
|
||||
Extended bool `json:"extended"`
|
||||
CodeSuffix string `json:"code_suffix"`
|
||||
}
|
||||
|
||||
func (s *RedeemCodeService) Redeem(ctx context.Context, user *usermodel.User, code string, clientIP string, userAgent string) (*RedeemResult, error) {
|
||||
normalized := normalizeCode(code)
|
||||
if normalized == "" {
|
||||
return nil, ErrRedeemCodeInvalid
|
||||
}
|
||||
hash := hashCode(normalized)
|
||||
|
||||
now := time.Now()
|
||||
var result *RedeemResult
|
||||
|
||||
err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var redeemCode model.MembershipRedeemCode
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
|
||||
Where("code_hash = ? AND deleted_at IS NULL", hash).
|
||||
First(&redeemCode).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return ErrRedeemCodeInvalid
|
||||
}
|
||||
return fmt.Errorf("load redeem code: %w", err)
|
||||
}
|
||||
|
||||
if redeemCode.Status != "" && redeemCode.Status != "active" {
|
||||
return ErrRedeemCodeDisabled
|
||||
}
|
||||
if redeemCode.ExpiresAt != nil && redeemCode.ExpiresAt.Before(now) {
|
||||
return ErrRedeemCodeExpired
|
||||
}
|
||||
if redeemCode.MaxUses <= 0 {
|
||||
redeemCode.MaxUses = 1
|
||||
}
|
||||
if redeemCode.UsedUses >= redeemCode.MaxUses {
|
||||
return ErrRedeemCodeUsedUp
|
||||
}
|
||||
if redeemCode.DurationDays <= 0 {
|
||||
return fmt.Errorf("redeem code duration_days invalid")
|
||||
}
|
||||
|
||||
// 兑换:先创建/延长会员,再计数,最后写 redemption log。
|
||||
var membership usermodel.UserMembership
|
||||
var hasActive bool
|
||||
if err := tx.
|
||||
Where("mini_program_id = ? AND user_id = ? AND status = ? AND ends_at > ?",
|
||||
user.MiniProgramID, user.ID, "active", now).
|
||||
Order("ends_at DESC").
|
||||
First(&membership).Error; err == nil {
|
||||
hasActive = true
|
||||
} else if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return fmt.Errorf("load membership: %w", err)
|
||||
}
|
||||
|
||||
base := now
|
||||
if hasActive && membership.EndsAt.After(now) {
|
||||
base = membership.EndsAt
|
||||
}
|
||||
newEnds := base.AddDate(0, 0, redeemCode.DurationDays)
|
||||
|
||||
if hasActive {
|
||||
if err := tx.Model(&membership).Updates(map[string]interface{}{
|
||||
"ends_at": newEnds,
|
||||
"updated_at": now,
|
||||
}).Error; err != nil {
|
||||
return fmt.Errorf("extend membership: %w", err)
|
||||
}
|
||||
} else {
|
||||
membership = usermodel.UserMembership{
|
||||
MiniProgramID: user.MiniProgramID,
|
||||
UserID: user.ID,
|
||||
Plan: redeemCode.Plan,
|
||||
Status: "active",
|
||||
StartsAt: now,
|
||||
EndsAt: newEnds,
|
||||
}
|
||||
if err := tx.Create(&membership).Error; err != nil {
|
||||
return fmt.Errorf("create membership: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := tx.Model(&redeemCode).UpdateColumn("used_uses", gorm.Expr("used_uses + 1")).Error; err != nil {
|
||||
return fmt.Errorf("update redeem usage: %w", err)
|
||||
}
|
||||
|
||||
redemption := model.MembershipRedemption{
|
||||
MiniProgramID: user.MiniProgramID,
|
||||
UserID: user.ID,
|
||||
RedeemCodeID: redeemCode.ID,
|
||||
CodeSuffix: redeemCode.CodeSuffix,
|
||||
MembershipID: membership.ID,
|
||||
ClientIP: truncateString(clientIP, 64),
|
||||
UserAgent: truncateString(userAgent, 255),
|
||||
}
|
||||
if err := tx.Create(&redemption).Error; err != nil {
|
||||
return fmt.Errorf("create redemption log: %w", err)
|
||||
}
|
||||
|
||||
result = &RedeemResult{
|
||||
Plan: redeemCode.Plan,
|
||||
StartsAt: membership.StartsAt,
|
||||
EndsAt: newEnds,
|
||||
Extended: hasActive,
|
||||
CodeSuffix: redeemCode.CodeSuffix,
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func normalizeCode(code string) string {
|
||||
c := strings.TrimSpace(code)
|
||||
c = strings.ReplaceAll(c, "-", "")
|
||||
c = strings.ReplaceAll(c, " ", "")
|
||||
c = strings.ToUpper(c)
|
||||
return c
|
||||
}
|
||||
|
||||
func hashCode(code string) string {
|
||||
sum := sha256.Sum256([]byte(code))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func suffixOf(code string, n int) string {
|
||||
if n <= 0 {
|
||||
return ""
|
||||
}
|
||||
if len(code) <= n {
|
||||
return code
|
||||
}
|
||||
return code[len(code)-n:]
|
||||
}
|
||||
|
||||
func generateCode(length int) (string, error) {
|
||||
if length <= 0 {
|
||||
length = 16
|
||||
}
|
||||
// 去掉易混淆字符:0/O, 1/I/L
|
||||
const alphabet = "ABCDEFGHJKMNPQRSTUVWXYZ23456789"
|
||||
buf := make([]byte, length)
|
||||
if _, err := rand.Read(buf); err != nil {
|
||||
return "", fmt.Errorf("rand: %w", err)
|
||||
}
|
||||
out := make([]byte, length)
|
||||
for i, b := range buf {
|
||||
out[i] = alphabet[int(b)%len(alphabet)]
|
||||
}
|
||||
return string(out), nil
|
||||
}
|
||||
|
||||
func truncateString(s string, max int) string {
|
||||
if max <= 0 || len(s) <= max {
|
||||
return s
|
||||
}
|
||||
return s[:max]
|
||||
}
|
||||
@@ -7,15 +7,17 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
|
||||
rediscache "wx_service/internal/common/redis/cache"
|
||||
"wx_service/internal/model"
|
||||
)
|
||||
|
||||
const ContextCurrentUserKey = "currentUser"
|
||||
|
||||
func AuthMiddleware(db *gorm.DB) gin.HandlerFunc {
|
||||
func AuthMiddleware(db *gorm.DB, sessionCache *rediscache.SessionUserCache) gin.HandlerFunc {
|
||||
// AuthMiddleware 是一个 Gin 中间件:
|
||||
// - 从 Authorization: Bearer <token> 里取 token
|
||||
// - 用 token(这里是 session_key)查用户
|
||||
// - (可选) 优先从 Redis 缓存读取,减少每次都访问数据库
|
||||
// - 查到后放进 gin.Context,供后面的 handler 使用
|
||||
return func(c *gin.Context) {
|
||||
token := extractToken(c.GetHeader("Authorization"))
|
||||
@@ -24,6 +26,14 @@ func AuthMiddleware(db *gorm.DB) gin.HandlerFunc {
|
||||
return
|
||||
}
|
||||
|
||||
if sessionCache != nil {
|
||||
if cachedUser, ok, err := sessionCache.Get(c.Request.Context(), token); err == nil && ok && cachedUser != nil {
|
||||
c.Set(ContextCurrentUserKey, cachedUser)
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
var user model.User
|
||||
if err := db.WithContext(c.Request.Context()).Where("session_key = ?", token).First(&user).Error; err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
@@ -34,6 +44,10 @@ func AuthMiddleware(db *gorm.DB) gin.HandlerFunc {
|
||||
return
|
||||
}
|
||||
|
||||
if sessionCache != nil {
|
||||
_ = sessionCache.Set(c.Request.Context(), token, &user)
|
||||
}
|
||||
|
||||
c.Set(ContextCurrentUserKey, &user)
|
||||
c.Next()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// UserMembership 表示会员订阅记录(DDL 见 docs/sql/users.sql)。
|
||||
type UserMembership 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:"-"`
|
||||
|
||||
MiniProgramID uint `gorm:"index:idx_membership_user,priority:1;index:idx_membership_status,priority:1" json:"mini_program_id"`
|
||||
UserID uint `gorm:"index:idx_membership_user,priority:2;index:idx_membership_status,priority:2" json:"user_id"`
|
||||
|
||||
Plan string `gorm:"size:30" json:"plan"`
|
||||
Status string `gorm:"size:20;index:idx_membership_status,priority:3" json:"status"`
|
||||
|
||||
StartsAt time.Time `json:"starts_at"`
|
||||
EndsAt time.Time `gorm:"index:idx_membership_user,priority:3;index:idx_membership_status,priority:4" json:"ends_at"`
|
||||
}
|
||||
|
||||
func (UserMembership) TableName() string {
|
||||
return "user_memberships"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
package routes
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
membershiphandler "wx_service/internal/membership/handler"
|
||||
)
|
||||
|
||||
func registerMembershipRoutes(protected *gin.RouterGroup, redeemCodeHandler *membershiphandler.RedeemCodeHandler) {
|
||||
// 会员兑换码:生成(后台口令鉴权)+ 兑换(登录用户)
|
||||
membership := protected.Group("/membership")
|
||||
{
|
||||
membership.POST("/redeem_codes", redeemCodeHandler.Generate)
|
||||
membership.POST("/redeem", redeemCodeHandler.Redeem)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,9 @@ import (
|
||||
|
||||
authhandler "wx_service/internal/common/auth/handler"
|
||||
qiniuhandler "wx_service/internal/common/qiniu/handler"
|
||||
rediscache "wx_service/internal/common/redis/cache"
|
||||
oahandler "wx_service/internal/common/wechat_official/handler"
|
||||
membershiphandler "wx_service/internal/membership/handler"
|
||||
"wx_service/internal/middleware"
|
||||
rmhandler "wx_service/internal/remove_watermark/handler"
|
||||
smokehandler "wx_service/internal/smoke/handler"
|
||||
@@ -20,8 +22,10 @@ func Register(
|
||||
authHandler *authhandler.AuthHandler,
|
||||
videoHandler *rmhandler.VideoHandler,
|
||||
smokeHandler *smokehandler.SmokeHandler,
|
||||
redeemCodeHandler *membershiphandler.RedeemCodeHandler,
|
||||
uploadHandler *qiniuhandler.UploadHandler,
|
||||
oaOAuthHandler *oahandler.OAuthHandler,
|
||||
sessionCache *rediscache.SessionUserCache,
|
||||
) {
|
||||
// Register 用来集中注册所有 HTTP 路由,便于工程结构更清晰:
|
||||
// - main 只负责初始化(配置/DB/依赖注入)
|
||||
@@ -36,10 +40,11 @@ func Register(
|
||||
|
||||
// 需要登录的接口组:统一挂载鉴权中间件
|
||||
protected := api.Group("")
|
||||
protected.Use(middleware.AuthMiddleware(db))
|
||||
protected.Use(middleware.AuthMiddleware(db, sessionCache))
|
||||
{
|
||||
registerCommonRoutes(protected, uploadHandler)
|
||||
registerRemoveWatermarkRoutes(protected, videoHandler)
|
||||
registerMembershipRoutes(protected, redeemCodeHandler)
|
||||
registerSmokeRoutes(protected, smokeHandler)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,5 +15,9 @@ func registerSmokeRoutes(protected *gin.RouterGroup, smokeHandler *smokehandler.
|
||||
smoke.GET("/logs/:id", smokeHandler.Get)
|
||||
smoke.PUT("/logs/:id", smokeHandler.Update)
|
||||
smoke.DELETE("/logs/:id", smokeHandler.Delete)
|
||||
|
||||
// AI 戒烟建议(会员优先;非会员需看广告解锁)
|
||||
smoke.GET("/ai/advice", smokeHandler.GetAIAdvice)
|
||||
smoke.POST("/ai/advice_unlocks", smokeHandler.UnlockAIAdvice)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"wx_service/internal/middleware"
|
||||
"wx_service/internal/model"
|
||||
smokeservice "wx_service/internal/smoke/service"
|
||||
)
|
||||
|
||||
type unlockAIAdviceRequest struct {
|
||||
Date string `json:"date"`
|
||||
AdWatchedAt string `json:"ad_watched_at"`
|
||||
}
|
||||
|
||||
func (h *SmokeHandler) GetAIAdvice(c *gin.Context) {
|
||||
user, ok := middleware.CurrentUser(c)
|
||||
if !ok {
|
||||
c.JSON(http.StatusUnauthorized, model.Error(http.StatusUnauthorized, "未登录或登录已过期"))
|
||||
return
|
||||
}
|
||||
|
||||
dateStr := c.Query("date")
|
||||
adviceDate := yesterdayDate()
|
||||
if dateStr != "" {
|
||||
parsed, err := time.ParseInLocation(dateLayout, dateStr, time.Local)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "date 格式错误,应为 YYYY-MM-DD"))
|
||||
return
|
||||
}
|
||||
adviceDate = parsed
|
||||
}
|
||||
|
||||
record, err := h.smokeAIAdviceService.GetOrGenerate(c.Request.Context(), user, adviceDate, smokeservice.DefaultAdvicePromptVersion)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, smokeservice.ErrAIAdviceLocked):
|
||||
c.JSON(http.StatusForbidden, model.Error(http.StatusForbidden, "需要会员或观看广告解锁后才可生成建议"))
|
||||
return
|
||||
case errors.Is(err, smokeservice.ErrAIServiceDisabled):
|
||||
c.JSON(http.StatusServiceUnavailable, model.Error(http.StatusServiceUnavailable, "AI 服务暂不可用,请联系管理员"))
|
||||
return
|
||||
case errors.Is(err, smokeservice.ErrNoSmokeLogs):
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "该日期没有抽烟记录,无法生成建议"))
|
||||
return
|
||||
default:
|
||||
c.JSON(http.StatusInternalServerError, model.Error(http.StatusInternalServerError, "生成建议失败,请稍后重试"))
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, model.Success(gin.H{
|
||||
"date": record.AdviceDate.Format(dateLayout),
|
||||
"advice": record.Advice,
|
||||
}))
|
||||
}
|
||||
|
||||
func (h *SmokeHandler) UnlockAIAdvice(c *gin.Context) {
|
||||
user, ok := middleware.CurrentUser(c)
|
||||
if !ok {
|
||||
c.JSON(http.StatusUnauthorized, model.Error(http.StatusUnauthorized, "未登录或登录已过期"))
|
||||
return
|
||||
}
|
||||
|
||||
var req unlockAIAdviceRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil && !errors.Is(err, io.EOF) {
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "请求参数错误"))
|
||||
return
|
||||
}
|
||||
|
||||
unlockDate := yesterdayDate()
|
||||
if req.Date != "" {
|
||||
parsed, err := time.ParseInLocation(dateLayout, req.Date, time.Local)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "date 格式错误,应为 YYYY-MM-DD"))
|
||||
return
|
||||
}
|
||||
unlockDate = parsed
|
||||
}
|
||||
|
||||
if err := h.smokeAIAdviceService.Unlock(c.Request.Context(), user, unlockDate); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Error(http.StatusInternalServerError, "解锁失败,请稍后重试"))
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, model.Success(gin.H{
|
||||
"unlocked": true,
|
||||
"date": unlockDate.Format(dateLayout),
|
||||
}))
|
||||
}
|
||||
|
||||
func yesterdayDate() time.Time {
|
||||
now := time.Now().In(time.Local)
|
||||
y := now.AddDate(0, 0, -1)
|
||||
return time.Date(y.Year(), y.Month(), y.Day(), 0, 0, 0, 0, time.Local)
|
||||
}
|
||||
@@ -15,18 +15,25 @@ import (
|
||||
|
||||
type SmokeHandler struct {
|
||||
smokeLogService *smokeservice.SmokeLogService
|
||||
smokeAIAdviceService *smokeservice.SmokeAIAdviceService
|
||||
}
|
||||
|
||||
func NewSmokeHandler(smokeLogService *smokeservice.SmokeLogService) *SmokeHandler {
|
||||
return &SmokeHandler{smokeLogService: smokeLogService}
|
||||
func NewSmokeHandler(smokeLogService *smokeservice.SmokeLogService, smokeAIAdviceService *smokeservice.SmokeAIAdviceService) *SmokeHandler {
|
||||
return &SmokeHandler{
|
||||
smokeLogService: smokeLogService,
|
||||
smokeAIAdviceService: smokeAIAdviceService,
|
||||
}
|
||||
}
|
||||
|
||||
// dateLayout 用于解析前端传入的日期字符串(例如:2025-12-31)
|
||||
const dateLayout = "2006-01-02"
|
||||
const dateTimeLayout = "2006-01-02 15:04:05"
|
||||
|
||||
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"`
|
||||
@@ -55,8 +62,19 @@ func (h *SmokeHandler) Create(c *gin.Context) {
|
||||
smokeTime = &parsed
|
||||
}
|
||||
|
||||
var smokeAt *time.Time
|
||||
if req.SmokeAt != "" {
|
||||
parsed, err := time.ParseInLocation(dateTimeLayout, req.SmokeAt, time.Local)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "smoke_at 格式错误,应为 YYYY-MM-DD HH:MM:SS"))
|
||||
return
|
||||
}
|
||||
smokeAt = &parsed
|
||||
}
|
||||
|
||||
record, err := h.smokeLogService.Create(c.Request.Context(), int(user.ID), smokeservice.CreateSmokeLogRequest{
|
||||
SmokeTime: smokeTime,
|
||||
SmokeAt: smokeAt,
|
||||
Remark: req.Remark,
|
||||
Level: req.Level,
|
||||
Num: req.Num,
|
||||
@@ -145,6 +163,7 @@ func (h *SmokeHandler) List(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"`
|
||||
@@ -184,9 +203,26 @@ func (h *SmokeHandler) Update(c *gin.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
smokeAtProvided := req.SmokeAt != nil
|
||||
var smokeAt *time.Time
|
||||
if req.SmokeAt != nil {
|
||||
if *req.SmokeAt == "" {
|
||||
smokeAt = nil
|
||||
} else {
|
||||
parsed, err := time.ParseInLocation(dateTimeLayout, *req.SmokeAt, time.Local)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "smoke_at 格式错误,应为 YYYY-MM-DD HH:MM:SS"))
|
||||
return
|
||||
}
|
||||
smokeAt = &parsed
|
||||
}
|
||||
}
|
||||
|
||||
record, err := h.smokeLogService.Update(c.Request.Context(), int(user.ID), id, smokeservice.UpdateSmokeLogRequest{
|
||||
SmokeTimeProvided: smokeTimeProvided,
|
||||
SmokeTime: smokeTime,
|
||||
SmokeAtProvided: smokeAtProvided,
|
||||
SmokeAt: smokeAt,
|
||||
Remark: req.Remark,
|
||||
Level: req.Level,
|
||||
Num: req.Num,
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
package model
|
||||
|
||||
import "time"
|
||||
|
||||
// SmokeAIAdvice 对应表 fa_smoke_ai_advice(每日 AI 戒烟建议缓存)。
|
||||
//
|
||||
// 注意:沿用旧系统字段(createtime/updatetime/deletetime 为秒级时间戳),不使用 gorm.Model。
|
||||
type SmokeAIAdvice struct {
|
||||
ID uint `gorm:"primaryKey;autoIncrement" json:"id"`
|
||||
UID int `gorm:"column:uid;index:idx_smoke_ai_advice_uid_date,priority:1;uniqueIndex:uniq_smoke_ai_advice,priority:1" json:"-"`
|
||||
|
||||
AdviceDate time.Time `gorm:"column:advice_date;type:date;index:idx_smoke_ai_advice_uid_date,priority:2;uniqueIndex:uniq_smoke_ai_advice,priority:2" json:"advice_date"`
|
||||
PromptVersion string `gorm:"column:prompt_version;size:30;default:v1;uniqueIndex:uniq_smoke_ai_advice,priority:3" json:"prompt_version"`
|
||||
|
||||
Provider string `gorm:"column:provider;size:30" json:"provider,omitempty"`
|
||||
Model string `gorm:"column:model;size:60" json:"model,omitempty"`
|
||||
|
||||
InputSnapshot []byte `gorm:"column:input_snapshot;type:json" json:"input_snapshot,omitempty"`
|
||||
Advice string `gorm:"column:advice;type:mediumtext" json:"advice"`
|
||||
|
||||
TokensIn *int `gorm:"column:tokens_in" json:"tokens_in,omitempty"`
|
||||
TokensOut *int `gorm:"column:tokens_out" json:"tokens_out,omitempty"`
|
||||
CostCent *int `gorm:"column:cost_cent" json:"cost_cent,omitempty"`
|
||||
|
||||
CreateTime *int64 `gorm:"column:createtime" json:"createtime,omitempty"`
|
||||
UpdateTime *int64 `gorm:"column:updatetime" json:"updatetime,omitempty"`
|
||||
DeleteTime *int64 `gorm:"column:deletetime" json:"deletetime,omitempty"`
|
||||
}
|
||||
|
||||
func (SmokeAIAdvice) TableName() string {
|
||||
return "fa_smoke_ai_advice"
|
||||
}
|
||||
|
||||
// SmokeAIAdviceUnlock 对应表 fa_smoke_ai_advice_unlocks(非会员用户的每日广告解锁记录)。
|
||||
type SmokeAIAdviceUnlock struct {
|
||||
ID uint `gorm:"primaryKey;autoIncrement" json:"id"`
|
||||
UID int `gorm:"column:uid;index:idx_smoke_ai_unlock_uid_date,priority:1;uniqueIndex:uniq_smoke_ai_unlock,priority:1" json:"-"`
|
||||
|
||||
UnlockDate time.Time `gorm:"column:unlock_date;type:date;index:idx_smoke_ai_unlock_uid_date,priority:2;uniqueIndex:uniq_smoke_ai_unlock,priority:2" json:"unlock_date"`
|
||||
AdWatchedAt time.Time `gorm:"column:ad_watched_at" json:"ad_watched_at"`
|
||||
|
||||
CreateTime *int64 `gorm:"column:createtime" json:"createtime,omitempty"`
|
||||
UpdateTime *int64 `gorm:"column:updatetime" json:"updatetime,omitempty"`
|
||||
DeleteTime *int64 `gorm:"column:deletetime" json:"deletetime,omitempty"`
|
||||
}
|
||||
|
||||
func (SmokeAIAdviceUnlock) TableName() string {
|
||||
return "fa_smoke_ai_advice_unlocks"
|
||||
}
|
||||
@@ -13,6 +13,8 @@ type SmokeLog struct {
|
||||
|
||||
// smoke_time 在库里是 date 类型(只包含日期,不包含时分秒)。
|
||||
SmokeTime *time.Time `gorm:"column:smoke_time;type:date" json:"smoke_time,omitempty"`
|
||||
// smoke_at:真实抽烟时间(可补录,精确到时分秒)
|
||||
SmokeAt *time.Time `gorm:"column:smoke_at;type:datetime" json:"smoke_at,omitempty"`
|
||||
|
||||
Remark string `gorm:"column:remark;type:text" json:"remark,omitempty"`
|
||||
|
||||
|
||||
@@ -0,0 +1,406 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
"wx_service/config"
|
||||
usermodel "wx_service/internal/model"
|
||||
smokemodel "wx_service/internal/smoke/model"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrAIAdviceLocked = errors.New("ai advice is locked, vip or ad unlock required")
|
||||
ErrAIServiceDisabled = errors.New("ai service is not configured")
|
||||
ErrNoSmokeLogs = errors.New("no smoke logs for date")
|
||||
)
|
||||
|
||||
const (
|
||||
DefaultAdvicePromptVersion = "v1"
|
||||
defaultTemperature = 0.7
|
||||
)
|
||||
|
||||
type SmokeAIAdviceService struct {
|
||||
db *gorm.DB
|
||||
cfg config.AIConfig
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
func NewSmokeAIAdviceService(db *gorm.DB, cfg config.AIConfig) *SmokeAIAdviceService {
|
||||
timeout := cfg.RequestTimeout
|
||||
if timeout <= 0 {
|
||||
timeout = 15 * time.Second
|
||||
}
|
||||
return &SmokeAIAdviceService{
|
||||
db: db,
|
||||
cfg: cfg,
|
||||
client: &http.Client{
|
||||
Timeout: timeout,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
type adviceSnapshotNode struct {
|
||||
Time string `json:"time"`
|
||||
Num int `json:"num"`
|
||||
Level int64 `json:"level"`
|
||||
Remark string `json:"remark,omitempty"`
|
||||
}
|
||||
|
||||
type adviceSnapshot struct {
|
||||
Date string `json:"date"`
|
||||
TotalNum int `json:"total_num"`
|
||||
Nodes []adviceSnapshotNode `json:"nodes"`
|
||||
}
|
||||
|
||||
func (s *SmokeAIAdviceService) GetOrGenerate(ctx context.Context, user *usermodel.User, adviceDate time.Time, promptVersion string) (*smokemodel.SmokeAIAdvice, error) {
|
||||
if promptVersion == "" {
|
||||
promptVersion = DefaultAdvicePromptVersion
|
||||
}
|
||||
|
||||
cached, err := s.getCached(ctx, int(user.ID), adviceDate, promptVersion)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if cached != nil {
|
||||
return cached, nil
|
||||
}
|
||||
|
||||
allowed, err := s.isAllowed(ctx, user, adviceDate)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !allowed {
|
||||
return nil, ErrAIAdviceLocked
|
||||
}
|
||||
|
||||
snapshot, snapshotJSON, err := s.buildSnapshot(ctx, int(user.ID), adviceDate)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
adviceText, modelName, tokensIn, tokensOut, err := s.callAI(ctx, snapshot)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
now := time.Now().Unix()
|
||||
createTime := now
|
||||
updateTime := now
|
||||
|
||||
record := smokemodel.SmokeAIAdvice{
|
||||
UID: int(user.ID),
|
||||
AdviceDate: dateOnly(adviceDate),
|
||||
PromptVersion: promptVersion,
|
||||
Provider: "openai-compatible",
|
||||
Model: modelName,
|
||||
InputSnapshot: snapshotJSON,
|
||||
Advice: adviceText,
|
||||
TokensIn: tokensIn,
|
||||
TokensOut: tokensOut,
|
||||
CreateTime: &createTime,
|
||||
UpdateTime: &updateTime,
|
||||
}
|
||||
|
||||
if err := s.db.WithContext(ctx).Create(&record).Error; err != nil {
|
||||
return nil, fmt.Errorf("save ai advice: %w", err)
|
||||
}
|
||||
return &record, nil
|
||||
}
|
||||
|
||||
func (s *SmokeAIAdviceService) Unlock(ctx context.Context, user *usermodel.User, unlockDate time.Time) error {
|
||||
now := time.Now()
|
||||
nowUnix := now.Unix()
|
||||
startOfDay := dateOnly(unlockDate)
|
||||
|
||||
var existing smokemodel.SmokeAIAdviceUnlock
|
||||
tx := s.db.WithContext(ctx)
|
||||
err := tx.Where("uid = ? AND unlock_date = ? AND (deletetime IS NULL OR deletetime = 0)", user.ID, startOfDay.Format("2006-01-02")).
|
||||
First(&existing).Error
|
||||
if err == nil {
|
||||
return tx.Model(&existing).Updates(map[string]interface{}{
|
||||
"ad_watched_at": now,
|
||||
"updatetime": nowUnix,
|
||||
}).Error
|
||||
}
|
||||
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return fmt.Errorf("load unlock record: %w", err)
|
||||
}
|
||||
|
||||
createTime := nowUnix
|
||||
updateTime := nowUnix
|
||||
record := smokemodel.SmokeAIAdviceUnlock{
|
||||
UID: int(user.ID),
|
||||
UnlockDate: startOfDay,
|
||||
AdWatchedAt: now,
|
||||
CreateTime: &createTime,
|
||||
UpdateTime: &updateTime,
|
||||
}
|
||||
if err := tx.Create(&record).Error; err != nil {
|
||||
return fmt.Errorf("create unlock record: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *SmokeAIAdviceService) getCached(ctx context.Context, uid int, adviceDate time.Time, promptVersion string) (*smokemodel.SmokeAIAdvice, error) {
|
||||
var record smokemodel.SmokeAIAdvice
|
||||
err := s.db.WithContext(ctx).
|
||||
Where("uid = ? AND advice_date = ? AND prompt_version = ? AND (deletetime IS NULL OR deletetime = 0)",
|
||||
uid, dateOnly(adviceDate).Format("2006-01-02"), promptVersion).
|
||||
First(&record).Error
|
||||
if err == nil {
|
||||
return &record, nil
|
||||
}
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, fmt.Errorf("load cached advice: %w", err)
|
||||
}
|
||||
|
||||
func (s *SmokeAIAdviceService) isAllowed(ctx context.Context, user *usermodel.User, adviceDate time.Time) (bool, error) {
|
||||
isVIP, err := s.isVIP(ctx, user)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if isVIP {
|
||||
return true, nil
|
||||
}
|
||||
return s.isUnlocked(ctx, int(user.ID), adviceDate)
|
||||
}
|
||||
|
||||
func (s *SmokeAIAdviceService) isVIP(ctx context.Context, user *usermodel.User) (bool, error) {
|
||||
now := time.Now()
|
||||
var count int64
|
||||
if err := s.db.WithContext(ctx).
|
||||
Model(&usermodel.UserMembership{}).
|
||||
Where("mini_program_id = ? AND user_id = ? AND status = ? AND ends_at > ?",
|
||||
user.MiniProgramID, user.ID, "active", now).
|
||||
Count(&count).Error; err != nil {
|
||||
return false, fmt.Errorf("check vip: %w", err)
|
||||
}
|
||||
return count > 0, nil
|
||||
}
|
||||
|
||||
func (s *SmokeAIAdviceService) isUnlocked(ctx context.Context, uid int, adviceDate time.Time) (bool, error) {
|
||||
startOfDay := dateOnly(adviceDate)
|
||||
var unlock smokemodel.SmokeAIAdviceUnlock
|
||||
err := s.db.WithContext(ctx).
|
||||
Where("uid = ? AND unlock_date = ? AND (deletetime IS NULL OR deletetime = 0)", uid, startOfDay.Format("2006-01-02")).
|
||||
First(&unlock).Error
|
||||
if err == nil {
|
||||
return true, nil
|
||||
}
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return false, nil
|
||||
}
|
||||
return false, fmt.Errorf("check unlock: %w", err)
|
||||
}
|
||||
|
||||
func (s *SmokeAIAdviceService) buildSnapshot(ctx context.Context, uid int, adviceDate time.Time) (adviceSnapshot, []byte, error) {
|
||||
var logs []smokemodel.SmokeLog
|
||||
if err := s.db.WithContext(ctx).
|
||||
Where("uid = ? AND smoke_time = ? AND (deletetime IS NULL OR deletetime = 0)", uid, dateOnly(adviceDate).Format("2006-01-02")).
|
||||
Find(&logs).Error; err != nil {
|
||||
return adviceSnapshot{}, nil, fmt.Errorf("load smoke logs: %w", err)
|
||||
}
|
||||
if len(logs) == 0 {
|
||||
return adviceSnapshot{}, nil, ErrNoSmokeLogs
|
||||
}
|
||||
|
||||
type timedLog struct {
|
||||
log smokemodel.SmokeLog
|
||||
eventAt time.Time
|
||||
hasEvent bool
|
||||
}
|
||||
|
||||
timed := make([]timedLog, 0, len(logs))
|
||||
total := 0
|
||||
for _, l := range logs {
|
||||
total += l.Num
|
||||
var eventAt time.Time
|
||||
has := false
|
||||
if l.SmokeAt != nil {
|
||||
eventAt = *l.SmokeAt
|
||||
has = true
|
||||
} else if l.CreateTime != nil && *l.CreateTime > 0 {
|
||||
eventAt = time.Unix(*l.CreateTime, 0).In(time.Local)
|
||||
has = true
|
||||
}
|
||||
timed = append(timed, timedLog{log: l, eventAt: eventAt, hasEvent: has})
|
||||
}
|
||||
|
||||
// 按时间节点排序(若没有 event time,则排在最后,仍保持稳定)
|
||||
sort.SliceStable(timed, func(i, j int) bool {
|
||||
a := timed[i]
|
||||
b := timed[j]
|
||||
if a.hasEvent && b.hasEvent {
|
||||
if !a.eventAt.Equal(b.eventAt) {
|
||||
return a.eventAt.Before(b.eventAt)
|
||||
}
|
||||
return a.log.ID < b.log.ID
|
||||
}
|
||||
if a.hasEvent != b.hasEvent {
|
||||
return a.hasEvent
|
||||
}
|
||||
return a.log.ID < b.log.ID
|
||||
})
|
||||
|
||||
nodes := make([]adviceSnapshotNode, 0, len(timed))
|
||||
for _, t := range timed {
|
||||
timeLabel := ""
|
||||
if t.hasEvent {
|
||||
timeLabel = t.eventAt.Format("15:04")
|
||||
}
|
||||
nodes = append(nodes, adviceSnapshotNode{
|
||||
Time: timeLabel,
|
||||
Num: t.log.Num,
|
||||
Level: t.log.Level,
|
||||
Remark: t.log.Remark,
|
||||
})
|
||||
}
|
||||
|
||||
snap := adviceSnapshot{
|
||||
Date: dateOnly(adviceDate).Format("2006-01-02"),
|
||||
TotalNum: total,
|
||||
Nodes: nodes,
|
||||
}
|
||||
|
||||
b, err := json.Marshal(snap)
|
||||
if err != nil {
|
||||
return adviceSnapshot{}, nil, fmt.Errorf("marshal snapshot: %w", err)
|
||||
}
|
||||
return snap, b, nil
|
||||
}
|
||||
|
||||
func (s *SmokeAIAdviceService) callAI(ctx context.Context, snap adviceSnapshot) (string, string, *int, *int, error) {
|
||||
if s.cfg.APIKey == "" || s.cfg.Model == "" || s.cfg.BaseURL == "" {
|
||||
return "", "", nil, nil, ErrAIServiceDisabled
|
||||
}
|
||||
|
||||
systemPrompt := strings.TrimSpace(`
|
||||
你是一名专业的戒烟教练与行为改变顾问。你需要基于用户昨天的抽烟总量与时间节点,给出可执行、可量化的戒烟/控烟建议。
|
||||
要求:
|
||||
1) 用中文输出;
|
||||
2) 先给出对昨天模式的简短分析(1-3条);
|
||||
3) 给出今天的具体行动方案(至少5条,包含替代行为、触发场景应对、时间节点策略);
|
||||
4) 给出一个“如果忍不住想抽”的 60 秒应对流程;
|
||||
5) 语气友好、不指责;不提供医疗诊断。
|
||||
`)
|
||||
|
||||
userPrompt := fmt.Sprintf("用户昨日数据(JSON):\n%s", mustJSON(snap))
|
||||
|
||||
reqBody := chatCompletionRequest{
|
||||
Model: s.cfg.Model,
|
||||
Messages: []chatMessage{
|
||||
{Role: "system", Content: systemPrompt},
|
||||
{Role: "user", Content: userPrompt},
|
||||
},
|
||||
Temperature: defaultTemperature,
|
||||
}
|
||||
|
||||
payload, err := json.Marshal(reqBody)
|
||||
if err != nil {
|
||||
return "", "", nil, nil, fmt.Errorf("marshal ai request: %w", err)
|
||||
}
|
||||
|
||||
endpoint := strings.TrimRight(s.cfg.BaseURL, "/") + "/chat/completions"
|
||||
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(payload))
|
||||
if err != nil {
|
||||
return "", "", nil, nil, fmt.Errorf("build ai request: %w", err)
|
||||
}
|
||||
httpReq.Header.Set("Content-Type", "application/json")
|
||||
httpReq.Header.Set("Authorization", "Bearer "+s.cfg.APIKey)
|
||||
|
||||
resp, err := s.client.Do(httpReq)
|
||||
if err != nil {
|
||||
return "", "", nil, nil, fmt.Errorf("call ai: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return "", "", nil, nil, fmt.Errorf("read ai response: %w", err)
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", "", nil, nil, fmt.Errorf("ai http %d: %s", resp.StatusCode, truncateString(string(body), 512))
|
||||
}
|
||||
|
||||
var parsed chatCompletionResponse
|
||||
if err := json.Unmarshal(body, &parsed); err != nil {
|
||||
return "", "", nil, nil, fmt.Errorf("parse ai response: %w", err)
|
||||
}
|
||||
if len(parsed.Choices) == 0 {
|
||||
return "", "", nil, nil, errors.New("ai response has no choices")
|
||||
}
|
||||
|
||||
content := strings.TrimSpace(parsed.Choices[0].Message.Content)
|
||||
if content == "" {
|
||||
return "", "", nil, nil, errors.New("ai response content is empty")
|
||||
}
|
||||
|
||||
modelName := parsed.Model
|
||||
if modelName == "" {
|
||||
modelName = s.cfg.Model
|
||||
}
|
||||
|
||||
var tokensIn, tokensOut *int
|
||||
if parsed.Usage != nil {
|
||||
tokensIn = &parsed.Usage.PromptTokens
|
||||
tokensOut = &parsed.Usage.CompletionTokens
|
||||
}
|
||||
|
||||
return content, modelName, tokensIn, tokensOut, nil
|
||||
}
|
||||
|
||||
type chatMessage struct {
|
||||
Role string `json:"role"`
|
||||
Content string `json:"content"`
|
||||
}
|
||||
|
||||
type chatCompletionRequest struct {
|
||||
Model string `json:"model"`
|
||||
Messages []chatMessage `json:"messages"`
|
||||
Temperature float64 `json:"temperature,omitempty"`
|
||||
}
|
||||
|
||||
type chatCompletionResponse struct {
|
||||
Model string `json:"model"`
|
||||
Choices []struct {
|
||||
Message chatMessage `json:"message"`
|
||||
} `json:"choices"`
|
||||
Usage *struct {
|
||||
PromptTokens int `json:"prompt_tokens"`
|
||||
CompletionTokens int `json:"completion_tokens"`
|
||||
TotalTokens int `json:"total_tokens"`
|
||||
} `json:"usage"`
|
||||
}
|
||||
|
||||
func dateOnly(t time.Time) time.Time {
|
||||
local := t.In(time.Local)
|
||||
return time.Date(local.Year(), local.Month(), local.Day(), 0, 0, 0, 0, time.Local)
|
||||
}
|
||||
|
||||
func mustJSON(v any) string {
|
||||
b, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
return "{}"
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
func truncateString(s string, max int) string {
|
||||
if max <= 0 || len(s) <= max {
|
||||
return s
|
||||
}
|
||||
return s[:max]
|
||||
}
|
||||
@@ -25,6 +25,7 @@ func NewSmokeLogService(db *gorm.DB) *SmokeLogService {
|
||||
|
||||
type CreateSmokeLogRequest struct {
|
||||
SmokeTime *time.Time
|
||||
SmokeAt *time.Time
|
||||
Remark string
|
||||
Level int64
|
||||
Num int
|
||||
@@ -44,7 +45,14 @@ func (s *SmokeLogService) Create(ctx context.Context, uid int, req CreateSmokeLo
|
||||
num = 1
|
||||
}
|
||||
|
||||
smokeAt := req.SmokeAt
|
||||
|
||||
// smokeTime 用于“按天筛选”;如果传了 smokeAt,建议用其日期部分回填 smokeTime,避免出现不一致。
|
||||
smokeTime := req.SmokeTime
|
||||
if smokeAt != nil {
|
||||
day := time.Date(smokeAt.Year(), smokeAt.Month(), smokeAt.Day(), 0, 0, 0, 0, smokeAt.Location())
|
||||
smokeTime = &day
|
||||
}
|
||||
if smokeTime == nil {
|
||||
today := time.Now()
|
||||
startOfDay := time.Date(today.Year(), today.Month(), today.Day(), 0, 0, 0, 0, today.Location())
|
||||
@@ -54,6 +62,7 @@ func (s *SmokeLogService) Create(ctx context.Context, uid int, req CreateSmokeLo
|
||||
record := smokemodel.SmokeLog{
|
||||
UID: uid,
|
||||
SmokeTime: smokeTime,
|
||||
SmokeAt: smokeAt,
|
||||
Remark: req.Remark,
|
||||
CreateTime: &createTime,
|
||||
UpdateTime: &updateTime,
|
||||
@@ -148,6 +157,11 @@ type UpdateSmokeLogRequest struct {
|
||||
// - true:前端传了 smoke_time(可以设置为具体日期,也可以清空为 NULL)
|
||||
SmokeTimeProvided bool
|
||||
SmokeTime *time.Time
|
||||
// SmokeAtProvided 用于区分:
|
||||
// - false:前端没传 smoke_at(不修改)
|
||||
// - true:前端传了 smoke_at(可以设置为具体时间,也可以清空为 NULL)
|
||||
SmokeAtProvided bool
|
||||
SmokeAt *time.Time
|
||||
Remark *string
|
||||
Level *int64
|
||||
Num *int
|
||||
@@ -163,6 +177,13 @@ func (s *SmokeLogService) Update(ctx context.Context, uid int, id int, req Updat
|
||||
if req.SmokeTimeProvided {
|
||||
updates["smoke_time"] = req.SmokeTime
|
||||
}
|
||||
if req.SmokeAtProvided {
|
||||
updates["smoke_at"] = req.SmokeAt
|
||||
if req.SmokeAt != nil {
|
||||
day := time.Date(req.SmokeAt.Year(), req.SmokeAt.Month(), req.SmokeAt.Day(), 0, 0, 0, 0, req.SmokeAt.Location())
|
||||
updates["smoke_time"] = &day
|
||||
}
|
||||
}
|
||||
if req.Remark != nil {
|
||||
updates["remark"] = *req.Remark
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user