Files
verify/backend/internal/router/app/account.go
T
admin e09d177843
Docker Build / Build and Push Docker Image (push) Successful in 5s
Docker Build / Deploy to Server (push) Successful in 1s
fix(billing): 计时扣费从未生效、扣费不记账、卡型与应用计费方式不校验
设计评审时查出来的四条,都带回归测试。

1) timer 扣费永远不触发(真 bug)
   handler 先把 LastHeartbeatAt 覆盖成 now,紧接着又拿它算 elapsed,
   now - now = 0,永远小于扣费间隔。用「按时间扣费」的应用从不扣钱,
   不报错、不告警、日志里也看不出来。
   修:先把旧心跳存进 prevHeartbeat,再用它算间隔。
   附带修了重新查库后 LastHeartbeatAt 被拉回旧值的问题(补回 now)。

2) 扣了钱却不写消费流水
   consumption_records 生产库里一直是 0 条:财务页在查这张表,
   但没有任何代码往里写。用户投诉「余额怎么少了」拿不出账。
   修:扣费成功后写 ConsumptionRecord(含余额快照、单号)。记账失败只告警
   不阻断,但会留日志。

3) 卡密首次激活不写充值流水
   只有 payment.go 那条「充到已有主体」的路径记账,「首次激活开新主体」
   漏了,导致卡密收入在财务上查不出来。
   修:resolveCardSubject 在事务里补写 RechargeRecord(金额=卡型售价)。

4) 卡型计费方式与应用 billing_type 不校验
   应用按订阅计费、卡型却建成余额型(或反之),用户充进去的字段
   没有任何逻辑会读 —— 钱花了、没效果、还不报错。
   修:新建/更新卡型时校验,不匹配直接 400 并说明原因。
   免费应用不限制。

另外消除了一处重复实现:
   卡型 value/value_unit 换算成时长原来在 resolveCardSubject 和 payment.go
   各写一遍,而且前者少了 minute/hour 两个单位(按分钟/小时计价的卡走首次
   激活会掉进 default 按「秒」算,30 分钟变 30 秒)。
   现在统一走 service.CardTypeDuration / ApplyCardTypeToSubject。

测试(sqlite 内存库 + 真实 handler 调用):
   TestTimerDeductionActuallyFires        余额 100→99、写 1 条流水、心跳时间更新
   TestTimerDeductionSkipsWhenIntervalNotReached  间隔未到不扣
   TestCardActivationWritesRechargeRecord 激活写流水、卡绑主体
   TestCardRechargeThenLoginReusesSubject 同卡二次登录回原主体、只记一次账
   TestCheckCardTypeMatchesAppBilling     8 组匹配/不匹配组合

验证方式:把 timer 修复临时撤掉重跑 TestTimerDeductionActuallyFires,
确定它会 FAIL(余额仍是 100),恢复后 PASS —— 证明测试真的能抓到这个 bug。
2026-11-29 12:01:02 +08:00

255 lines
7.6 KiB
Go

package app
import (
"fmt"
"log"
"time"
"verification-platform-backend/internal/database"
"verification-platform-backend/internal/model"
"verification-platform-backend/internal/service"
"verification-platform-backend/pkg/response"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
)
func SetupAccountRoutes(r *gin.RouterGroup) {
r.GET("/account", handleAppGetAccount)
r.POST("/heartbeat", handleAppHeartbeat)
}
func handleAppGetAccount(c *gin.Context) {
appKey := c.Param("appKey")
var app model.Application
if err := database.DB.Where("app_key = ?", appKey).First(&app).Error; err != nil {
response.Error(c, 404, "应用不存在")
return
}
if service.GetApplicationDisabledStatus(app.ID) {
response.Error(c, 403, "该应用已被禁用")
return
}
var req struct {
UserID uint `json:"user_id"`
}
if err := c.ShouldBindJSON(&req); err != nil {
response.Error(c, 400, "参数错误")
return
}
var user model.AppUser
if err := database.DB.First(&user, req.UserID).Error; err != nil {
response.Error(c, 404, "用户不存在")
return
}
response.Success(c, gin.H{
"user_id": user.ID,
"username": user.Username,
"balance": user.Balance,
"status": user.Status,
})
}
func handleAppHeartbeat(c *gin.Context) {
appKey := c.Param("appKey")
var app model.Application
if err := database.DB.Where("app_key = ?", appKey).First(&app).Error; err != nil {
response.Error(c, 404, "应用不存在")
return
}
if service.GetApplicationDisabledStatus(app.ID) {
response.Error(c, 403, "该应用已被禁用")
return
}
// 从 JWT token 中获取用户信息
userIDInterface, exists := c.Get("user_id")
if !exists {
response.Error(c, 401, "未授权")
return
}
userID := userIDInterface.(uint)
usernameInterface, _ := c.Get("username")
username := usernameInterface.(string)
// 从 JWT token 中获取设备信息
deviceIDInterface, exists := c.Get("device_id")
deviceID := ""
if exists {
deviceID = deviceIDInterface.(string)
}
instanceIDInterface, exists := c.Get("instance_id")
instanceID := ""
if exists {
instanceID = instanceIDInterface.(string)
}
if instanceID == "" {
instanceID = deviceID
}
var user model.AppUser
if err := database.DB.First(&user, userID).Error; err != nil {
response.Error(c, 404, "用户不存在")
return
}
if blocked, reason := checkRiskControl(c, app.ID, deviceID, username); blocked {
log.Printf("[DEBUG] Heartbeat blocked by risk control: %s", reason)
response.Error(c, 403, reason)
return
}
now := time.Now()
// 计时扣费必须拿「上一次心跳」来算间隔。下面这行会先把 LastHeartbeatAt
// 改成 now,所以这里必须先把旧值留一份 —— 否则 elapsed 恒为 0,
// timer 模式永远不扣费(曾经就是这个 bug,线上不会报错,只是静默免费)。
prevHeartbeat := user.LastHeartbeatAt
user.LastHeartbeatAt = &now
if app.BillingType != "free" && app.DeductionMode == "auto" && app.DeductionAmount > 0 {
shouldDeduct := false
switch app.DeductionType {
case "timer":
if prevHeartbeat != nil {
elapsed := now.Sub(*prevHeartbeat)
var interval time.Duration
switch app.DeductionUnit {
case "minute":
interval = time.Duration(app.DeductionInterval) * time.Minute
case "hour":
interval = time.Duration(app.DeductionInterval) * time.Hour
case "day":
interval = time.Duration(app.DeductionInterval) * 24 * time.Hour
default:
interval = time.Duration(app.DeductionInterval) * time.Minute
}
if elapsed >= interval {
shouldDeduct = true
}
}
case "login":
shouldDeduct = true
}
if shouldDeduct {
if user.Balance == -1 {
log.Printf("[DEBUG] User %d is permanent member, skip deduction", user.ID)
} else if app.BillingType == "subscription" {
if user.ExpiryAt == nil || user.ExpiryAt.Before(now) {
log.Printf("[DEBUG] User %d subscription expired, ExpiryAt=%v", user.ID, user.ExpiryAt)
response.Error(c, 403, "订阅已过期")
return
}
log.Printf("[DEBUG] User %d subscription valid, skip balance deduction", user.ID)
} else {
result := database.DB.Model(&model.AppUser{}).Where("id = ? AND balance >= ?", user.ID, app.DeductionAmount).
Update("balance", gorm.Expr("balance - ?", app.DeductionAmount))
if result.Error != nil || result.RowsAffected == 0 {
log.Printf("[DEBUG] User %d has insufficient balance: %.2f < %.2f", user.ID, user.Balance, app.DeductionAmount)
response.Error(c, 403, "余额不足")
return
}
// 重新查库会把 LastHeartbeatAt 拉回旧值,这里补回 now,
// 否则本次心跳时间丢失,下次间隔会被算长
database.DB.Where("id = ?", user.ID).First(&user)
user.LastHeartbeatAt = &now
// 扣了钱就必须留账。consumption_records 原来一直是 0 条:
// 财务页在查这张表,但没有任何代码往里写,等于扣费无法对账。
consumeRecord := model.ConsumptionRecord{
UserID: user.ID,
ApplicationID: app.ID,
OrderNo: generateOrderNo("C"),
Type: "verification",
Content: fmt.Sprintf("心跳扣费:%s", app.Name),
Description: fmt.Sprintf("每 %d %s 扣 %g", app.DeductionInterval,
app.DeductionUnit, app.DeductionAmount),
Amount: app.DeductionAmount,
BalanceAfter: user.Balance,
Status: "success",
}
if err := database.DB.Create(&consumeRecord).Error; err != nil {
// 记账失败不阻断用户使用,但必须留痕,否则就成了静默少账
log.Printf("[WARN] 写消费流水失败 user=%d amount=%.2f: %v", user.ID, app.DeductionAmount, err)
}
log.Printf("[DEBUG] Deducted %.2f from user %d, new balance: %.2f", app.DeductionAmount, user.ID, user.Balance)
}
}
}
if err := database.DB.Save(&user).Error; err != nil {
response.Error(c, 500, "更新心跳失败")
return
}
if deviceID != "" {
var device model.UserDevice
err := database.DB.Where("user_id = ? AND application_id = ? AND device_id = ?", user.ID, app.ID, deviceID).First(&device).Error
if err != nil {
device = model.UserDevice{
UserID: user.ID,
ApplicationID: app.ID,
DeviceID: deviceID,
DeviceName: deviceID,
Status: "active",
}
if err := database.DB.Create(&device).Error; err != nil {
log.Printf("[DEBUG] Failed to create device: %v", err)
}
}
if device.ID > 0 {
var session model.DeviceSession
sessionErr := database.DB.Where("device_id = ? AND instance_id = ?", device.ID, instanceID).First(&session).Error
if sessionErr != nil {
session = model.DeviceSession{
UserDeviceID: device.ID,
UserID: user.ID,
ApplicationID: app.ID,
InstanceID: instanceID,
LastHeartbeat: &now,
}
if err := database.DB.Create(&session).Error; err != nil {
log.Printf("[DEBUG] Failed to create session: %v", err)
}
} else {
session.LastHeartbeat = &now
if err := database.DB.Save(&session).Error; err != nil {
log.Printf("[DEBUG] Failed to update session: %v", err)
}
}
}
}
// 根据运营模式返回不同参数
heartbeatData := gin.H{
"message": "心跳成功",
}
// 永久会员返回永久标识
if user.Balance == -1 {
heartbeatData["is_permanent"] = true
} else if app.BillingType == "subscription" {
// 订阅模式返回到期时间
if user.ExpiryAt != nil {
heartbeatData["expiry_at"] = user.ExpiryAt.Format("2006-01-02 15:04:05")
heartbeatData["expiry_timestamp"] = user.ExpiryAt.Unix()
}
} else if app.BillingType != "free" {
// 余额模式返回余额
heartbeatData["balance"] = user.Balance
}
response.SuccessWithMessage(c, "心跳成功", heartbeatData)
}