4 Commits
Author SHA1 Message Date
yml2213 f19c9f62b7 test(invitation): 建立邀请返利全状态全组合正交测试套件并修复布尔零值持久化缺陷
- 设计并落地 6 大测试组共 37 个组合场景(绑定准入、实名生命周期、周期滑窗阶梯、双边角色矩阵、分站独立继承、金额极值与幂等性)
- 修复 GORM 在 default:true 标签下忽略布尔零值导致分站关闭返利失效的缺陷
- 在 UpdateRebateConfig 中使用显式 Select 保证 Enabled 字段 100% 精确持久化
- 验证方式:go test -v ./internal/modules/invitation/... 全部通过,耗时约 1.2s
2026-10-10 14:07:48 +08:00
yml2213 f5202c6080 style(invitation): 邀请返利界面全面对齐平台金橙品牌色规范
- 顶部 Banner 重构为黑曜石暗金底配金橙光辉,彻底消除蓝色调
- 收益数据卡片、专属推广栏及操作按钮升级为金橙与琥珀暖色系
- 阶梯分成规则卡片更新为首月红橙、次月暖金、永久长青绿三阶体系
- 明细 Tab 指示条、角色标签与分页组件全面对齐品牌设计
- 验证方式:npm run check 与 npm run test 全部通过,无告警与报错
2026-10-10 14:00:53 +08:00
yml2213 825ce83003 feat(auth): 优化PC与移动端登录注册界面并支持邀请码锁定绑定
- 重构 PC 端 LoginView.vue 与移动端 MobileRegisterView.vue,统一契合平台金橙色主体色
- 识别邀请链接并自动填入邀请码,锁定输入框为只读并展示「已绑定邀请码」专属徽章,防止篡改
- 短链 /i/:code 与 /m/i/:code 统一重定向至登录注册页,移除冗余独立落地页
- PC 端页脚完全对齐主站并固定沉底,左侧定制官方品质、安全上号、资金担保平台核心卖点
- 验证方式:npm run check(Prettier + ESLint + vue-tsc)全数通过
2026-10-10 13:48:14 +08:00
yml2213 7cddbe9463 feat(invitation): 支持分销站点自主配置返利比例与权限隔离
- 后端新增分站专属配置及审计接口(/api/distribution/invitation-config 等),基于分站管理员严格鉴权隔离
- 分销独立后台新增「邀请返利设置」页面(Invitations.tsx),支持分站管理员自主开启/调整返利比例并查看本站流水
- 主站后台邀请接口路径补齐 /admin 前缀,解决 404/401 鉴权作用域问题
- 验证方式:backend 单元测试全数通过,distribution-admin 类型与构建检查通过
2026-10-10 13:47:53 +08:00
19 changed files with 3217 additions and 1481 deletions
+1 -1
View File
@@ -26,7 +26,7 @@ type InvitationRebateConfig struct {
FirstMonthRate float64 `gorm:"type:decimal(6,4);not null;default:0.6000" json:"first_month_rate"`
SecondMonthRate float64 `gorm:"type:decimal(6,4);not null;default:0.3000" json:"second_month_rate"`
SubsequentRate float64 `gorm:"type:decimal(6,4);not null;default:0.1500" json:"subsequent_rate"`
Enabled bool `gorm:"not null;default:true" json:"enabled"`
Enabled bool `gorm:"not null" json:"enabled"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
@@ -0,0 +1,818 @@
package invitation
import (
"context"
"fmt"
"testing"
"time"
"hfb_sys/backend/internal/model"
)
// =============================================================================
// 组合测试组 1: 邀请码绑定与实名准入全组合矩阵
// =============================================================================
func TestCombinations_BindingAndAccessControl(t *testing.T) {
db := setupTestDB(t)
repo := NewRepository(db)
ctx := context.Background()
// 1.1 正常组合:邀请人已实名 + 被邀请人未实名 -> 绑定成功,状态 Pending
t.Run("Valid_VerifiedInviter_UnverifiedInvitee", func(t *testing.T) {
code := "code_valid_1"
inviter := model.User{Phone: "13100000001", RealnameStatus: "verified", Status: "active", InviteCode: &code}
db.Create(&inviter)
invitee := model.User{Phone: "13100000002", RealnameStatus: "unverified", Status: "active"}
db.Create(&invitee)
err := repo.BindInvitation(ctx, invitee.ID, code, 0)
if err != nil {
t.Fatalf("正常绑定应成功,实际错误: %v", err)
}
var record model.UserInvitation
if err := db.Where("invitee_id = ?", invitee.ID).First(&record).Error; err != nil {
t.Fatalf("未找到邀请记录: %v", err)
}
if record.Status != StatusPending || record.VerifiedAt != nil {
t.Fatalf("未实名被邀请人状态应为 pending 且无 verified_at,实际: status=%s, verified_at=%v", record.Status, record.VerifiedAt)
}
})
// 1.2 即时激活组合:邀请人已实名 + 被邀请人注册时已实名 -> 绑定成功且直接生效 Active
t.Run("Valid_VerifiedInviter_AlreadyVerifiedInvitee", func(t *testing.T) {
code := "code_valid_2"
inviter := model.User{Phone: "13100000003", RealnameStatus: "verified", Status: "active", InviteCode: &code}
db.Create(&inviter)
invitee := model.User{Phone: "13100000004", RealnameStatus: "verified", Status: "active"}
db.Create(&invitee)
err := repo.BindInvitation(ctx, invitee.ID, code, 0)
if err != nil {
t.Fatalf("已实名用户绑定应成功: %v", err)
}
var record model.UserInvitation
if err := db.Where("invitee_id = ?", invitee.ID).First(&record).Error; err != nil {
t.Fatalf("未找到邀请记录: %v", err)
}
if record.Status != StatusActive || record.VerifiedAt == nil {
t.Fatalf("已实名用户绑定应直接为 active 且有 verified_at,实际: status=%s, verified_at=%v", record.Status, record.VerifiedAt)
}
})
// 1.3 自邀防御组合:自己邀请自己 -> 拒绝
t.Run("Invalid_SelfInvite", func(t *testing.T) {
code := "code_self"
user := model.User{Phone: "13100000005", RealnameStatus: "verified", Status: "active", InviteCode: &code}
db.Create(&user)
err := repo.BindInvitation(ctx, user.ID, code, 0)
if err != ErrSelfInviteNotAllowed {
t.Fatalf("自己邀请自己应返回 ErrSelfInviteNotAllowed,实际: %v", err)
}
})
// 1.4 邀请人未实名组合:邀请人未实名 -> 拒绝绑定
t.Run("Invalid_UnverifiedInviter", func(t *testing.T) {
code := "code_unverified_inviter"
inviter := model.User{Phone: "13100000006", RealnameStatus: "unverified", Status: "active", InviteCode: &code}
db.Create(&inviter)
invitee := model.User{Phone: "13100000007", RealnameStatus: "unverified", Status: "active"}
db.Create(&invitee)
err := repo.BindInvitation(ctx, invitee.ID, code, 0)
if err != ErrInviterNotVerified {
t.Fatalf("未实名邀请人应返回 ErrInviterNotVerified,实际: %v", err)
}
})
// 1.5 邀请码不存在组合 -> 返回 ErrInvalidInviteCode
t.Run("Invalid_NonExistentCode", func(t *testing.T) {
invitee := model.User{Phone: "13100000008", RealnameStatus: "unverified", Status: "active"}
db.Create(&invitee)
err := repo.BindInvitation(ctx, invitee.ID, "not_exist_code_999", 0)
if err != ErrInvalidInviteCode {
t.Fatalf("不存在的邀请码应返回 ErrInvalidInviteCode,实际: %v", err)
}
})
// 1.6 重复绑定组合:被邀请人不可改绑已存在的邀请人
t.Run("Invalid_AlreadyInvited", func(t *testing.T) {
codeA := "code_dup_a"
codeB := "code_dup_b"
inviterA := model.User{Phone: "13100000009", RealnameStatus: "verified", Status: "active", InviteCode: &codeA}
inviterB := model.User{Phone: "13100000010", RealnameStatus: "verified", Status: "active", InviteCode: &codeB}
db.Create(&inviterA)
db.Create(&inviterB)
invitee := model.User{Phone: "13100000011", RealnameStatus: "unverified", Status: "active"}
db.Create(&invitee)
// 首次绑定 A 成功
if err := repo.BindInvitation(ctx, invitee.ID, codeA, 0); err != nil {
t.Fatalf("初次绑定应成功: %v", err)
}
// 尝试二次绑定 B 应被拒绝
err := repo.BindInvitation(ctx, invitee.ID, codeB, 0)
if err != ErrAlreadyInvited {
t.Fatalf("已存在邀请关系二次绑定应返回 ErrAlreadyInvited,实际: %v", err)
}
})
// 1.7 空邀请码组合 -> 幂等安全返回 nil,不写记录
t.Run("EmptyCode_SafeNoop", func(t *testing.T) {
invitee := model.User{Phone: "13100000012", RealnameStatus: "unverified", Status: "active"}
db.Create(&invitee)
if err := repo.BindInvitation(ctx, invitee.ID, "", 0); err != nil {
t.Fatalf("空邀请码应安全返回 nil: %v", err)
}
if err := repo.BindInvitation(ctx, invitee.ID, " ", 0); err != nil {
t.Fatalf("空白字符邀请码应安全返回 nil: %v", err)
}
var count int64
db.Model(&model.UserInvitation{}).Where("invitee_id = ?", invitee.ID).Count(&count)
if count != 0 {
t.Fatalf("空邀请码不应产生邀请记录")
}
})
// 1.8 分站归属组合:传入分站 siteCode 自动解析对应 DistributionSiteID
t.Run("SiteBinding_BySiteCode", func(t *testing.T) {
site := model.DistributionSite{SiteName: "广州分站", SiteCode: "gz_sub", Domain: "gz_sub.test.local", Status: "active"}
db.Create(&site)
code := "code_site_test"
inviter := model.User{Phone: "13100000013", RealnameStatus: "verified", Status: "active", InviteCode: &code}
db.Create(&inviter)
invitee := model.User{Phone: "13100000014", RealnameStatus: "unverified", Status: "active"}
db.Create(&invitee)
err := repo.BindInvitation(ctx, invitee.ID, code, 0, "gz_sub")
if err != nil {
t.Fatalf("带 siteCode 绑定应成功: %v", err)
}
var record model.UserInvitation
db.Where("invitee_id = ?", invitee.ID).First(&record)
if record.DistributionSiteID != site.ID {
t.Fatalf("分站 ID 映射错误: expected=%d, got=%d", site.ID, record.DistributionSiteID)
}
})
}
// =============================================================================
// 组合测试组 2: 被邀请人实名认证生命周期与邀请码自生
// =============================================================================
func TestCombinations_RealnameLifecycleAndSelfInviteCode(t *testing.T) {
db := setupTestDB(t)
repo := NewRepository(db)
ctx := context.Background()
code := "inv_lifecycle_root"
inviter := model.User{Phone: "13200000001", RealnameStatus: "verified", Status: "active", InviteCode: &code}
db.Create(&inviter)
invitee := model.User{Phone: "13200000002", RealnameStatus: "unverified", Status: "active"}
db.Create(&invitee)
// 绑定,当前为 pending
if err := repo.BindInvitation(ctx, invitee.ID, code, 0); err != nil {
t.Fatalf("绑定失败: %v", err)
}
// 2.1 触发实名认证前状态核对
var record model.UserInvitation
db.Where("invitee_id = ?", invitee.ID).First(&record)
if record.Status != StatusPending || record.VerifiedAt != nil {
t.Fatalf("实名前应为 pending")
}
// 2.2 触发实名生效钩子
db.Model(&model.User{}).Where("id = ?", invitee.ID).Update("realname_status", "verified")
if err := repo.OnUserRealnameVerified(ctx, invitee.ID); err != nil {
t.Fatalf("实名回调执行失败: %v", err)
}
// 验证邀请关系翻转为 Active 并记录 VerifiedAt
db.Where("invitee_id = ?", invitee.ID).First(&record)
if record.Status != StatusActive || record.VerifiedAt == nil {
t.Fatalf("实名后状态应翻转为 active 并记录 verified_at")
}
firstVerifiedAt := *record.VerifiedAt
// 验证被邀请人自身是否自动生成了专属邀请码
var updatedInvitee model.User
db.First(&updatedInvitee, invitee.ID)
if updatedInvitee.InviteCode == nil || len(*updatedInvitee.InviteCode) < 6 {
t.Fatalf("实名后自身应自动生成合格邀请码: %v", updatedInvitee.InviteCode)
}
selfCode := *updatedInvitee.InviteCode
// 2.3 实名回调幂等性:重复调用不破坏 VerifiedAt 时间戳,不重置自身邀请码
time.Sleep(10 * time.Millisecond)
if err := repo.OnUserRealnameVerified(ctx, invitee.ID); err != nil {
t.Fatalf("重复实名回调应安全: %v", err)
}
db.Where("invitee_id = ?", invitee.ID).First(&record)
if !record.VerifiedAt.Equal(firstVerifiedAt) {
t.Fatalf("重复调用不应窜改原始 verified_at 时间戳")
}
db.First(&updatedInvitee, invitee.ID)
if *updatedInvitee.InviteCode != selfCode {
t.Fatalf("重复调用不应覆盖已有自身邀请码")
}
}
// =============================================================================
// 组合测试组 3: 周期阶梯判定与时间滑窗组合全覆盖 (表驱动测试)
// =============================================================================
func TestCombinations_CycleStageSlidingWindow(t *testing.T) {
now := time.Now()
customCfg := &model.InvitationRebateConfig{
FirstMonthRate: 0.80,
SecondMonthRate: 0.40,
SubsequentRate: 0.20,
Enabled: true,
}
cases := []struct {
name string
daysAgo int
hoursDelta time.Duration
cfg *model.InvitationRebateConfig
expectedCycle string
expectedRate float64
}{
// 默认比例测试组 (0.60, 0.30, 0.15)
{name: "首日_0天", daysAgo: 0, expectedCycle: CycleFirstMonth, expectedRate: 0.60},
{name: "首月_15天中段", daysAgo: 15, expectedCycle: CycleFirstMonth, expectedRate: 0.60},
{name: "首月临界_30天整", daysAgo: 30, expectedCycle: CycleFirstMonth, expectedRate: 0.60},
{name: "次月临界突破_31天", daysAgo: 31, expectedCycle: CycleSecondMonth, expectedRate: 0.30},
{name: "次月_45天中段", daysAgo: 45, expectedCycle: CycleSecondMonth, expectedRate: 0.30},
{name: "次月临界_60天整", daysAgo: 60, expectedCycle: CycleSecondMonth, expectedRate: 0.30},
{name: "长期临界突破_61天", daysAgo: 61, expectedCycle: CycleSubsequent, expectedRate: 0.15},
{name: "长期_180天半年", daysAgo: 180, expectedCycle: CycleSubsequent, expectedRate: 0.15},
{name: "长期_365天一年", daysAgo: 365, expectedCycle: CycleSubsequent, expectedRate: 0.15},
// 时钟回退防御
{name: "时钟回退_未来时间", daysAgo: -5, expectedCycle: CycleFirstMonth, expectedRate: 0.60},
// 自定义配置比例测试组 (0.80, 0.40, 0.20)
{name: "自定义_首月", daysAgo: 10, cfg: customCfg, expectedCycle: CycleFirstMonth, expectedRate: 0.80},
{name: "自定义_次月", daysAgo: 40, cfg: customCfg, expectedCycle: CycleSecondMonth, expectedRate: 0.40},
{name: "自定义_长期", daysAgo: 100, cfg: customCfg, expectedCycle: CycleSubsequent, expectedRate: 0.20},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
verifiedAt := now.AddDate(0, 0, -tc.daysAgo).Add(-tc.hoursDelta)
rate, cycle, days := CalculateRebateRate(verifiedAt, now, tc.cfg)
if cycle != tc.expectedCycle {
t.Errorf("[%s] 阶段不匹配: expected=%s, got=%s (days=%d)", tc.name, tc.expectedCycle, cycle, days)
}
if rate != tc.expectedRate {
t.Errorf("[%s] 比例不匹配: expected=%.2f, got=%.2f", tc.name, tc.expectedRate, rate)
}
})
}
}
// =============================================================================
// 组合测试组 4: 交易角色双边覆盖所有组合 (买家单边/卖家单边/双边不同/双边同人叠加通吃/双方无邀请/未实名)
// =============================================================================
func TestCombinations_TradeRolesMatrix(t *testing.T) {
db := setupTestDB(t)
repo := NewRepository(db)
ctx := context.Background()
now := time.Now()
// 创建三个独立的合格邀请人 A, B, C
codeA, codeB, codeC := "inv_role_A", "inv_role_B", "inv_role_C"
inviterA := model.User{Phone: "13300000001", RealnameStatus: "verified", Status: "active", InviteCode: &codeA}
inviterB := model.User{Phone: "13300000002", RealnameStatus: "verified", Status: "active", InviteCode: &codeB}
inviterC := model.User{Phone: "13300000003", RealnameStatus: "verified", Status: "active", InviteCode: &codeC}
db.Create(&inviterA)
db.Create(&inviterB)
db.Create(&inviterC)
// 辅助创建订单工具
createOrder := func(renterID, ownerID uint64, rentCent, ownerCent int64) model.RentalOrder {
order := model.RentalOrder{
OrderNo: fmt.Sprintf("ORD-COMB-%d", time.Now().UnixNano()),
RenterID: renterID,
OwnerID: ownerID,
Status: "completed",
SettlementStatus: "settled",
RentAmountCent: rentCent,
OwnerRentAmountCent: ownerCent,
}
db.Create(&order)
return order
}
// 4.1 组合一:仅买家有邀请人 (BuyerOnly)
t.Run("Combo_BuyerOnly", func(t *testing.T) {
buyer := model.User{Phone: "13310000001", RealnameStatus: "verified", Status: "active"}
seller := model.User{Phone: "13310000002", RealnameStatus: "verified", Status: "active"}
db.Create(&buyer)
db.Create(&seller)
// 绑定买家给 A (首月 10 天)
vAt := now.AddDate(0, 0, -10)
db.Create(&model.UserInvitation{InviterID: inviterA.ID, InviteeID: buyer.ID, Status: StatusActive, VerifiedAt: &vAt})
// 订单毛利 200元 (单边基准 100元,首月 60% = 60元)
order := createOrder(buyer.ID, seller.ID, 30000, 10000)
if err := repo.ProcessOrderInvitationRebate(ctx, db, order.ID); err != nil {
t.Fatalf("结算失败: %v", err)
}
var ledgers []model.InvitationRebateLedger
db.Where("order_id = ?", order.ID).Find(&ledgers)
if len(ledgers) != 1 {
t.Fatalf("仅买家有邀请人应生成 1 条流水,实际: %d", len(ledgers))
}
if ledgers[0].TradeRole != "buyer" || ledgers[0].InviterID != inviterA.ID || ledgers[0].RebateAmountCent != 6000 {
t.Fatalf("买家单边返利不符: %+v", ledgers[0])
}
})
// 4.2 组合二:仅卖家有邀请人 (SellerOnly)
t.Run("Combo_SellerOnly", func(t *testing.T) {
buyer := model.User{Phone: "13320000001", RealnameStatus: "verified", Status: "active"}
seller := model.User{Phone: "13320000002", RealnameStatus: "verified", Status: "active"}
db.Create(&buyer)
db.Create(&seller)
// 绑定卖家给 B (次月 40 天,比例 30%)
vAt := now.AddDate(0, 0, -40)
db.Create(&model.UserInvitation{InviterID: inviterB.ID, InviteeID: seller.ID, Status: StatusActive, VerifiedAt: &vAt})
// 订单毛利 200元 (单边基准 100元,次月 30% = 30元)
order := createOrder(buyer.ID, seller.ID, 30000, 10000)
if err := repo.ProcessOrderInvitationRebate(ctx, db, order.ID); err != nil {
t.Fatalf("结算失败: %v", err)
}
var ledgers []model.InvitationRebateLedger
db.Where("order_id = ?", order.ID).Find(&ledgers)
if len(ledgers) != 1 {
t.Fatalf("仅卖家有邀请人应生成 1 条流水,实际: %d", len(ledgers))
}
if ledgers[0].TradeRole != "seller" || ledgers[0].InviterID != inviterB.ID || ledgers[0].RebateAmountCent != 3000 {
t.Fatalf("卖家单边返利不符: %+v", ledgers[0])
}
})
// 4.3 组合三:买卖双方分别有不同邀请人 (DualDistinct: A 拿买家端,B 拿卖家端)
t.Run("Combo_DualDistinctInviters", func(t *testing.T) {
buyer := model.User{Phone: "13330000001", RealnameStatus: "verified", Status: "active"}
seller := model.User{Phone: "13330000002", RealnameStatus: "verified", Status: "active"}
db.Create(&buyer)
db.Create(&seller)
vBuyer := now.AddDate(0, 0, -5) // 买家首月 60%
vSeller := now.AddDate(0, 0, -70) // 卖家长期 15%
db.Create(&model.UserInvitation{InviterID: inviterA.ID, InviteeID: buyer.ID, Status: StatusActive, VerifiedAt: &vBuyer})
db.Create(&model.UserInvitation{InviterID: inviterB.ID, InviteeID: seller.ID, Status: StatusActive, VerifiedAt: &vSeller})
// 订单毛利 200元 (单边基准 100元)
// 买家返利: 100 * 0.6 = 60元 (6000分) 给 A
// 卖家返利: 100 * 0.15 = 15元 (1500分) 给 B
order := createOrder(buyer.ID, seller.ID, 30000, 10000)
if err := repo.ProcessOrderInvitationRebate(ctx, db, order.ID); err != nil {
t.Fatalf("结算失败: %v", err)
}
var ledgers []model.InvitationRebateLedger
db.Where("order_id = ?", order.ID).Order("trade_role asc").Find(&ledgers)
if len(ledgers) != 2 {
t.Fatalf("双边应生成 2 条流水,实际: %d", len(ledgers))
}
// buyer
if ledgers[0].TradeRole != "buyer" || ledgers[0].InviterID != inviterA.ID || ledgers[0].RebateAmountCent != 6000 {
t.Fatalf("买家端流水有误: %+v", ledgers[0])
}
// seller
if ledgers[1].TradeRole != "seller" || ledgers[1].InviterID != inviterB.ID || ledgers[1].RebateAmountCent != 1500 {
t.Fatalf("卖家端流水有误: %+v", ledgers[1])
}
})
// 4.4 组合四:买卖双方为同一邀请人的好友 (DualSame: A 独揽双边叠加通吃)
t.Run("Combo_DualSameInviter_DoubleBonus", func(t *testing.T) {
buyer := model.User{Phone: "13340000001", RealnameStatus: "verified", Status: "active"}
seller := model.User{Phone: "13340000002", RealnameStatus: "verified", Status: "active"}
db.Create(&buyer)
db.Create(&seller)
vBuyer := now.AddDate(0, 0, -10) // 买家首月 60%
vSeller := now.AddDate(0, 0, -20) // 卖家首月 60%
// 两个人都归 C 邀请
db.Create(&model.UserInvitation{InviterID: inviterC.ID, InviteeID: buyer.ID, Status: StatusActive, VerifiedAt: &vBuyer})
db.Create(&model.UserInvitation{InviterID: inviterC.ID, InviteeID: seller.ID, Status: StatusActive, VerifiedAt: &vSeller})
// 订单毛利 200元 (买卖两端基准各 100元)
// C 获得买家端 60元 + 卖家端 60元 = 合计 120元 (12000分)
order := createOrder(buyer.ID, seller.ID, 30000, 10000)
if err := repo.ProcessOrderInvitationRebate(ctx, db, order.ID); err != nil {
t.Fatalf("结算失败: %v", err)
}
var ledgers []model.InvitationRebateLedger
db.Where("order_id = ?", order.ID).Find(&ledgers)
if len(ledgers) != 2 {
t.Fatalf("同一人邀请买卖双方应生成 2 条独立流水,实际: %d", len(ledgers))
}
for _, l := range ledgers {
if l.InviterID != inviterC.ID || l.RebateAmountCent != 6000 {
t.Fatalf("流水信息不符: %+v", l)
}
}
// 验证 C 的钱包余额应收到 12000 分
var walletAcct model.WalletAccount
db.Where("user_id = ? AND distribution_site_id = 0", inviterC.ID).First(&walletAcct)
if walletAcct.AvailableBalanceCent != 12000 {
t.Fatalf("C 的双边叠加可用余额应为 12000分,实际: %d", walletAcct.AvailableBalanceCent)
}
})
// 4.5 组合五:双方均无邀请人 (Neither) -> 0 条流水
t.Run("Combo_NeitherInvited", func(t *testing.T) {
buyer := model.User{Phone: "13350000001", RealnameStatus: "verified", Status: "active"}
seller := model.User{Phone: "13350000002", RealnameStatus: "verified", Status: "active"}
db.Create(&buyer)
db.Create(&seller)
order := createOrder(buyer.ID, seller.ID, 30000, 10000)
if err := repo.ProcessOrderInvitationRebate(ctx, db, order.ID); err != nil {
t.Fatalf("结算失败: %v", err)
}
var count int64
db.Model(&model.InvitationRebateLedger{}).Where("order_id = ?", order.ID).Count(&count)
if count != 0 {
t.Fatalf("无邀请关系不应产生流水,实际 count=%d", count)
}
})
// 4.6 组合六:被邀请人未实名认证 (StatusPending) -> 不产生返利
t.Run("Combo_InviteeNotVerified_NoRebate", func(t *testing.T) {
buyer := model.User{Phone: "13360000001", RealnameStatus: "unverified", Status: "active"}
seller := model.User{Phone: "13360000002", RealnameStatus: "verified", Status: "active"}
db.Create(&buyer)
db.Create(&seller)
// 绑定处于 pending,VerifiedAt 为 nil
db.Create(&model.UserInvitation{InviterID: inviterA.ID, InviteeID: buyer.ID, Status: StatusPending, VerifiedAt: nil})
order := createOrder(buyer.ID, seller.ID, 30000, 10000)
if err := repo.ProcessOrderInvitationRebate(ctx, db, order.ID); err != nil {
t.Fatalf("结算失败: %v", err)
}
var count int64
db.Model(&model.InvitationRebateLedger{}).Where("order_id = ?", order.ID).Count(&count)
if count != 0 {
t.Fatalf("未实名好友产生交易时不应发放返利")
}
})
// 4.7 组合七:邀请人已失信/未实名 -> 不发放返利
t.Run("Combo_InviterLostVerification_NoRebate", func(t *testing.T) {
unvCode := "inv_unv_person"
fakeInviter := model.User{Phone: "13370000001", RealnameStatus: "unverified", Status: "active", InviteCode: &unvCode}
db.Create(&fakeInviter)
buyer := model.User{Phone: "13370000002", RealnameStatus: "verified", Status: "active"}
seller := model.User{Phone: "13370000003", RealnameStatus: "verified", Status: "active"}
db.Create(&buyer)
db.Create(&seller)
vAt := now.AddDate(0, 0, -5)
db.Create(&model.UserInvitation{InviterID: fakeInviter.ID, InviteeID: buyer.ID, Status: StatusActive, VerifiedAt: &vAt})
order := createOrder(buyer.ID, seller.ID, 30000, 10000)
if err := repo.ProcessOrderInvitationRebate(ctx, db, order.ID); err != nil {
t.Fatalf("结算失败: %v", err)
}
var count int64
db.Model(&model.InvitationRebateLedger{}).Where("order_id = ?", order.ID).Count(&count)
if count != 0 {
t.Fatalf("邀请人处于未实名状态时不应发放返利")
}
})
// 4.8 组合八:邀请人自身作为买家(自买自卖防御) -> 拒绝自我返利
t.Run("Combo_SelfPurchaseDefense", func(t *testing.T) {
seller := model.User{Phone: "13380000001", RealnameStatus: "verified", Status: "active"}
db.Create(&seller)
// A 购买,且 A 是自己的邀请关系(异常数据防御)
vAt := now.AddDate(0, 0, -5)
db.Create(&model.UserInvitation{InviterID: inviterA.ID, InviteeID: inviterA.ID, Status: StatusActive, VerifiedAt: &vAt})
order := createOrder(inviterA.ID, seller.ID, 30000, 10000)
if err := repo.ProcessOrderInvitationRebate(ctx, db, order.ID); err != nil {
t.Fatalf("结算失败: %v", err)
}
var count int64
db.Model(&model.InvitationRebateLedger{}).Where("order_id = ?", order.ID).Count(&count)
if count != 0 {
t.Fatalf("邀请人自身购买不应获得买家端自我返利")
}
})
}
// =============================================================================
// 组合测试组 5: 分站独立配置与继承组合 (默认继承/自定义比例/分站关闭返利/跨站拆分)
// =============================================================================
func TestCombinations_MultiTenantSiteConfigs(t *testing.T) {
db := setupTestDB(t)
repo := NewRepository(db)
ctx := context.Background()
now := time.Now()
// 创建两个分站:站点 101 (自定义比例), 站点 102 (关闭返利)
site101 := model.DistributionSite{SiteName: "成都分站", SiteCode: "site_101", Domain: "site101.test.local", Status: "active"}
site102 := model.DistributionSite{SiteName: "武汉分站", SiteCode: "site_102", Domain: "site102.test.local", Status: "active"}
if err := db.Create(&site101).Error; err != nil {
t.Fatalf("创建站点 101 失败: %v", err)
}
if err := db.Create(&site102).Error; err != nil {
t.Fatalf("创建站点 102 失败: %v", err)
}
// 站点 101 配置: 首月 50%, 次月 25%, 长期 10%
enabledTrue := true
_, err := repo.UpdateRebateConfig(ctx, site101.ID, UpdateConfigRequest{
FirstMonthRate: 0.50,
SecondMonthRate: 0.25,
SubsequentRate: 0.10,
Enabled: &enabledTrue,
})
if err != nil {
t.Fatalf("配置站点 101 失败: %v", err)
}
// 站点 102 配置: 关闭返利 Enabled = false
enabledFalse := false
_, err = repo.UpdateRebateConfig(ctx, site102.ID, UpdateConfigRequest{
FirstMonthRate: 0.60,
SecondMonthRate: 0.30,
SubsequentRate: 0.15,
Enabled: &enabledFalse,
})
if err != nil {
t.Fatalf("配置站点 102 失败: %v", err)
}
codeP := "inv_dist_P"
inviter := model.User{Phone: "13400000001", RealnameStatus: "verified", Status: "active", InviteCode: &codeP}
db.Create(&inviter)
// 5.1 组合一:分站自定义比例 (Site 101 订单应按 50% 结算首月)
t.Run("Subsite_CustomRatesApplied", func(t *testing.T) {
buyer := model.User{Phone: "13410000001", RealnameStatus: "verified", Status: "active"}
seller := model.User{Phone: "13410000002", RealnameStatus: "verified", Status: "active"}
db.Create(&buyer)
db.Create(&seller)
vAt := now.AddDate(0, 0, -10)
db.Create(&model.UserInvitation{InviterID: inviter.ID, InviteeID: buyer.ID, DistributionSiteID: site101.ID, Status: StatusActive, VerifiedAt: &vAt})
siteID := site101.ID
order := model.RentalOrder{
OrderNo: fmt.Sprintf("ORD-S101-%d", time.Now().UnixNano()),
DistributionSiteID: &siteID,
RenterID: buyer.ID,
OwnerID: seller.ID,
Status: "completed",
SettlementStatus: "settled",
RentAmountCent: 20000,
OwnerRentAmountCent: 10000, // 毛利 100元 (单边基准 50元 = 5000分)
// 首月 50% = 2500分 (25元)
}
if err := db.Create(&order).Error; err != nil {
t.Fatalf("创建订单失败: %v", err)
}
if err := repo.ProcessOrderInvitationRebate(ctx, db, order.ID); err != nil {
t.Fatalf("结算失败: %v", err)
}
var l model.InvitationRebateLedger
if err := db.Where("order_id = ?", order.ID).First(&l).Error; err != nil {
t.Fatalf("查询流水失败: %v", err)
}
if l.DistributionSiteID != site101.ID || l.RateApplied != 0.50 || l.RebateAmountCent != 2500 {
t.Fatalf("分站 101 返利计算错误: site=%d, rate=%.2f, amount=%d", l.DistributionSiteID, l.RateApplied, l.RebateAmountCent)
}
})
// 5.2 组合二:分站关闭返利开关 (Site 102 订单不产生返利)
t.Run("Subsite_DisabledNoRebate", func(t *testing.T) {
buyer := model.User{Phone: "13420000001", RealnameStatus: "verified", Status: "active"}
seller := model.User{Phone: "13420000002", RealnameStatus: "verified", Status: "active"}
db.Create(&buyer)
db.Create(&seller)
vAt := now.AddDate(0, 0, -10)
db.Create(&model.UserInvitation{InviterID: inviter.ID, InviteeID: buyer.ID, DistributionSiteID: site102.ID, Status: StatusActive, VerifiedAt: &vAt})
siteID := site102.ID
order := model.RentalOrder{
OrderNo: fmt.Sprintf("ORD-S102-%d", time.Now().UnixNano()),
DistributionSiteID: &siteID,
RenterID: buyer.ID,
OwnerID: seller.ID,
Status: "completed",
SettlementStatus: "settled",
RentAmountCent: 20000,
OwnerRentAmountCent: 10000,
}
if err := db.Create(&order).Error; err != nil {
t.Fatalf("创建订单失败: %v", err)
}
if err := repo.ProcessOrderInvitationRebate(ctx, db, order.ID); err != nil {
t.Fatalf("结算失败: %v", err)
}
var count int64
db.Model(&model.InvitationRebateLedger{}).Where("order_id = ?", order.ID).Count(&count)
if count != 0 {
t.Fatalf("分站已关闭返利时不应产生流水")
}
})
// 5.3 组合三:未独立配置的分站自动回退继承主站全局配置
t.Run("Subsite_FallbackToDefault", func(t *testing.T) {
site999 := model.DistributionSite{SiteName: "新分站999", SiteCode: "site_999", Domain: "site999.test.local", Status: "active"}
db.Create(&site999)
cfg, err := repo.GetRebateConfig(ctx, site999.ID)
if err != nil {
t.Fatalf("获取配置失败: %v", err)
}
if cfg.FirstMonthRate != DefaultFirstMonthRate || cfg.SecondMonthRate != DefaultSecondMonthRate || cfg.SubsequentRate != DefaultSubsequentRate {
t.Fatalf("未配置分站应继承主站默认比例: %+v", cfg)
}
})
}
// =============================================================================
// 组合测试组 6: 订单金额边界、极值精度与幂等性测试 (零毛利/负毛利/1分钱精度/非终态/并发幂等)
// =============================================================================
func TestCombinations_OrderAmountEdgeCasesAndIdempotency(t *testing.T) {
db := setupTestDB(t)
repo := NewRepository(db)
ctx := context.Background()
now := time.Now()
code := "inv_edge_tester"
inviter := model.User{Phone: "13500000001", RealnameStatus: "verified", Status: "active", InviteCode: &code}
db.Create(&inviter)
buyer := model.User{Phone: "13500000002", RealnameStatus: "verified", Status: "active"}
seller := model.User{Phone: "13500000003", RealnameStatus: "verified", Status: "active"}
db.Create(&buyer)
db.Create(&seller)
vAt := now.AddDate(0, 0, -5)
db.Create(&model.UserInvitation{InviterID: inviter.ID, InviteeID: buyer.ID, Status: StatusActive, VerifiedAt: &vAt})
// 6.1 组合一:零毛利订单 (RentAmount == OwnerRentAmount) -> 不发返利
t.Run("ZeroProfitOrder", func(t *testing.T) {
order := model.RentalOrder{
OrderNo: fmt.Sprintf("ORD-ZERO-%d", time.Now().UnixNano()),
RenterID: buyer.ID,
OwnerID: seller.ID,
Status: "completed",
SettlementStatus: "settled",
RentAmountCent: 5000,
OwnerRentAmountCent: 5000, // 毛利 0
}
db.Create(&order)
if err := repo.ProcessOrderInvitationRebate(ctx, db, order.ID); err != nil {
t.Fatalf("零毛利处理失败: %v", err)
}
var count int64
db.Model(&model.InvitationRebateLedger{}).Where("order_id = ?", order.ID).Count(&count)
if count != 0 {
t.Fatalf("零毛利不应产生流水")
}
})
// 6.2 组合二:负毛利订单 (RentAmount < OwnerRentAmount) -> 不发返利
t.Run("NegativeProfitOrder", func(t *testing.T) {
order := model.RentalOrder{
OrderNo: fmt.Sprintf("ORD-NEG-%d", time.Now().UnixNano()),
RenterID: buyer.ID,
OwnerID: seller.ID,
Status: "completed",
SettlementStatus: "settled",
RentAmountCent: 4000,
OwnerRentAmountCent: 5000, // 负毛利 -1000
}
db.Create(&order)
if err := repo.ProcessOrderInvitationRebate(ctx, db, order.ID); err != nil {
t.Fatalf("负毛利处理失败: %v", err)
}
var count int64
db.Model(&model.InvitationRebateLedger{}).Where("order_id = ?", order.ID).Count(&count)
if count != 0 {
t.Fatalf("负毛利不应产生流水")
}
})
// 6.3 组合三:极小毛利 1 分钱精度测试 -> 不 panic,安全退出
t.Run("OneCentPennyProfit", func(t *testing.T) {
order := model.RentalOrder{
OrderNo: fmt.Sprintf("ORD-PENNY-%d", time.Now().UnixNano()),
RenterID: buyer.ID,
OwnerID: seller.ID,
Status: "completed",
SettlementStatus: "settled",
RentAmountCent: 101,
OwnerRentAmountCent: 100, // 毛利 1分钱,单边除以2为0
}
db.Create(&order)
if err := repo.ProcessOrderInvitationRebate(ctx, db, order.ID); err != nil {
t.Fatalf("1分钱订单不应报错: %v", err)
}
})
// 6.4 组合四:非终态订单 (如 renting 进行中 / refunded 已退款) -> 不触发结算
t.Run("NonCompletedOrder", func(t *testing.T) {
orderRenting := model.RentalOrder{
OrderNo: fmt.Sprintf("ORD-RENTING-%d", time.Now().UnixNano()),
RenterID: buyer.ID,
OwnerID: seller.ID,
Status: "renting",
SettlementStatus: "unsettled",
RentAmountCent: 20000,
OwnerRentAmountCent: 10000,
}
db.Create(&orderRenting)
if err := repo.ProcessOrderInvitationRebate(ctx, db, orderRenting.ID); err != nil {
t.Fatalf("未结算订单应安全跳过: %v", err)
}
var count int64
db.Model(&model.InvitationRebateLedger{}).Where("order_id = ?", orderRenting.ID).Count(&count)
if count != 0 {
t.Fatalf("租赁中的订单不应提前结算返利")
}
})
// 6.5 组合五:重复触发结算幂等性测试 (调用 5 次,流水与钱包严格唯一)
t.Run("RepeatedSettlementIdempotency", func(t *testing.T) {
order := model.RentalOrder{
OrderNo: fmt.Sprintf("ORD-IDEMP-%d", time.Now().UnixNano()),
RenterID: buyer.ID,
OwnerID: seller.ID,
Status: "completed",
SettlementStatus: "settled",
RentAmountCent: 20000,
OwnerRentAmountCent: 10000, // 毛利 100元,单边基准 50元,首月 60% = 30元 (3000分)
}
db.Create(&order)
// 连续调用 5 次
for i := 0; i < 5; i++ {
if err := repo.ProcessOrderInvitationRebate(ctx, db, order.ID); err != nil {
t.Fatalf("第 %d 次幂等调用失败: %v", i+1, err)
}
}
// 校验返利流水条数
var ledgers []model.InvitationRebateLedger
db.Where("order_id = ?", order.ID).Find(&ledgers)
if len(ledgers) != 1 {
t.Fatalf("重复调用 5 次流水条数应严格为 1,实际: %d", len(ledgers))
}
if ledgers[0].RebateAmountCent != 3000 {
t.Fatalf("返利金额错误: %d", ledgers[0].RebateAmountCent)
}
// 校验钱包流水条数与余额
var walletLedgers []model.WalletLedger
db.Where("biz_no = ? AND biz_type = 'invite_rebate'", order.OrderNo).Find(&walletLedgers)
if len(walletLedgers) != 1 {
t.Fatalf("钱包流水应严格为 1 条,实际: %d", len(walletLedgers))
}
})
}
+139 -1
View File
@@ -1,6 +1,7 @@
package invitation
import (
"context"
"errors"
"net/http"
"strconv"
@@ -13,14 +14,23 @@ import (
"github.com/gin-gonic/gin"
)
type SiteScoper interface {
ScopeSiteID(ctx context.Context, adminID, requested uint64) (uint64, error)
}
type Handler struct {
service *Service
service *Service
siteScoper SiteScoper
}
func NewHandler(service *Service) *Handler {
return &Handler{service: service}
}
func (h *Handler) SetSiteScoper(scoper SiteScoper) {
h.siteScoper = scoper
}
// GetInviteInfo 公开接口:根据邀请码查询邀请人简要信息(用于落地注册页)
func (h *Handler) GetInviteInfo(c *gin.Context) {
code := strings.TrimSpace(c.Param("code"))
@@ -225,3 +235,131 @@ func writeInvitationError(c *gin.Context, err error) {
response.Error(c, http.StatusInternalServerError, "invitation_error", err.Error())
}
}
// DistributionGetConfig 分销端获取本站邀请返利比例配置
func (h *Handler) DistributionGetConfig(c *gin.Context) {
siteID, err := h.resolveDistributionSiteID(c)
if err != nil {
response.Forbidden(c, "无权访问该分销站点")
return
}
cfg, err := h.service.GetRebateConfig(c.Request.Context(), siteID)
if err != nil {
writeInvitationError(c, err)
return
}
response.OK(c, cfg)
}
// DistributionUpdateConfig 分销端更新本站邀请返利比例配置
func (h *Handler) DistributionUpdateConfig(c *gin.Context) {
siteID, err := h.resolveDistributionSiteID(c)
if err != nil {
response.Forbidden(c, "无权操作该分销站点")
return
}
if siteID == 0 {
response.BadRequest(c, "未指定有效分销站点")
return
}
var req UpdateConfigRequest
if err := c.ShouldBindJSON(&req); err != nil {
response.BadRequest(c, "比例参数格式不正确,必须在0到1之间")
return
}
cfg, err := h.service.UpdateRebateConfig(c.Request.Context(), siteID, req)
if err != nil {
writeInvitationError(c, err)
return
}
response.OK(c, cfg)
}
// DistributionListInvitations 分销端查看本站邀请关系
func (h *Handler) DistributionListInvitations(c *gin.Context) {
siteID, err := h.resolveDistributionSiteID(c)
if err != nil {
response.Forbidden(c, "无权访问该分销站点")
return
}
var query AdminInvitationQuery
if err := c.ShouldBindQuery(&query); err != nil {
response.BadRequest(c, "查询参数不正确")
return
}
query.DistributionSiteID = &siteID
items, total, err := h.service.ListAdminInvitations(c.Request.Context(), query)
if err != nil {
writeInvitationError(c, err)
return
}
response.OK(c, gin.H{
"items": items,
"total": total,
"page": query.Page,
"page_size": query.PageSize,
})
}
// DistributionListRebates 分销端查看本站返利支出流水
func (h *Handler) DistributionListRebates(c *gin.Context) {
siteID, err := h.resolveDistributionSiteID(c)
if err != nil {
response.Forbidden(c, "无权访问该分销站点")
return
}
var query AdminRebateLedgerQuery
if err := c.ShouldBindQuery(&query); err != nil {
response.BadRequest(c, "查询参数不正确")
return
}
query.DistributionSiteID = &siteID
items, total, err := h.service.ListAdminRebateLedgers(c.Request.Context(), query)
if err != nil {
writeInvitationError(c, err)
return
}
response.OK(c, gin.H{
"items": items,
"total": total,
"page": query.Page,
"page_size": query.PageSize,
})
}
func (h *Handler) resolveDistributionSiteID(c *gin.Context) (uint64, error) {
adminID, _ := currentAdminID(c)
var requested uint64
if raw := c.Param("id"); raw != "" {
if id, err := strconv.ParseUint(raw, 10, 64); err == nil && id > 0 {
requested = id
}
}
if requested == 0 {
if raw := c.Query("site_id"); raw != "" {
if id, err := strconv.ParseUint(raw, 10, 64); err == nil && id > 0 {
requested = id
}
}
}
if requested == 0 {
if raw := c.Query("distribution_site_id"); raw != "" {
if id, err := strconv.ParseUint(raw, 10, 64); err == nil && id > 0 {
requested = id
}
}
}
if h.siteScoper != nil {
return h.siteScoper.ScopeSiteID(c.Request.Context(), adminID, requested)
}
return requested, nil
}
func currentAdminID(c *gin.Context) (uint64, bool) {
value, ok := c.Get(middleware.ContextAdminID)
if !ok {
return 0, false
}
adminID, ok := value.(uint64)
return adminID, ok
}
@@ -299,7 +299,7 @@ func (r *Repository) UpdateRebateConfig(ctx context.Context, siteID uint64, req
if req.Enabled != nil {
cfg.Enabled = *req.Enabled
}
if err := r.db.WithContext(ctx).Create(&cfg).Error; err != nil {
if err := r.db.WithContext(ctx).Select("DistributionSiteID", "FirstMonthRate", "SecondMonthRate", "SubsequentRate", "Enabled").Create(&cfg).Error; err != nil {
return nil, err
}
return &cfg, nil
@@ -310,7 +310,7 @@ func (r *Repository) UpdateRebateConfig(ctx context.Context, siteID uint64, req
if req.Enabled != nil {
cfg.Enabled = *req.Enabled
}
if err := r.db.WithContext(ctx).Save(&cfg).Error; err != nil {
if err := r.db.WithContext(ctx).Select("FirstMonthRate", "SecondMonthRate", "SubsequentRate", "Enabled").Save(&cfg).Error; err != nil {
return nil, err
}
return &cfg, nil
+13
View File
@@ -352,6 +352,9 @@ func New(cfg config.Config, deps Dependencies, logger *zap.Logger) *gin.Engine {
}
}
distributionHandler := distribution.NewHandler(distributionService)
if invitationHandler != nil && distributionService != nil {
invitationHandler.SetSiteScoper(distributionService)
}
backupMonitorHandler := backupmonitor.NewHandler(cfg.BackupStatusFile)
var adminRoleRepo *adminrole.Repository
if deps.DB != nil {
@@ -684,6 +687,16 @@ func New(cfg config.Config, deps Dependencies, logger *zap.Logger) *gin.Engine {
distributionProtectedRoutes.PUT("/accounts/:id/markup", distributionHandler.UpdateAccountMarkup)
distributionProtectedRoutes.POST("/accounts/batch-markup", distributionHandler.BatchUpdateAccountMarkup)
distributionProtectedRoutes.POST("/accounts/batch-display", distributionHandler.BatchUpdateAccountDisplay)
if invitationHandler != nil {
distributionProtectedRoutes.GET("/sites/:id/invitation-config", invitationHandler.DistributionGetConfig)
distributionProtectedRoutes.PUT("/sites/:id/invitation-config", invitationHandler.DistributionUpdateConfig)
distributionProtectedRoutes.GET("/sites/:id/invitations", invitationHandler.DistributionListInvitations)
distributionProtectedRoutes.GET("/sites/:id/invitation-rebates", invitationHandler.DistributionListRebates)
distributionProtectedRoutes.GET("/invitation-config", invitationHandler.DistributionGetConfig)
distributionProtectedRoutes.PUT("/invitation-config", invitationHandler.DistributionUpdateConfig)
distributionProtectedRoutes.GET("/invitations", invitationHandler.DistributionListInvitations)
distributionProtectedRoutes.GET("/invitation-rebates", invitationHandler.DistributionListRebates)
}
}
adminRoutes := api.Group("/admin", requireAdmin, middleware.RequireAdminPasswordChanged())
+4
View File
@@ -71,6 +71,10 @@ func BadRequest(c *gin.Context, message string) {
Error(c, http.StatusBadRequest, "bad_request", message)
}
func Forbidden(c *gin.Context, message string) {
Error(c, http.StatusForbidden, "forbidden", message)
}
func Unauthorized(c *gin.Context, message string) {
Error(c, http.StatusUnauthorized, "unauthorized", message)
}
+8
View File
@@ -16,6 +16,7 @@ import {
SkinOutlined,
UserOutlined,
WalletOutlined,
GiftOutlined,
} from '@ant-design/icons'
import { getMe, logout, type CurrentMember, getStoredToken } from './api'
import { MemberContext } from './MemberContext'
@@ -29,6 +30,7 @@ import Orders from './pages/Orders'
import Wallet from './pages/Wallet'
import Announcements from './pages/Announcements'
import SiteSettings from './pages/SiteSettings'
import Invitations from './pages/Invitations'
import Login from './pages/Login'
import Storefront from './pages/Storefront'
import './style.css'
@@ -62,6 +64,11 @@ function MainLayout({ member, onLogout }: { member: CurrentMember; onLogout: ()
icon: <SettingOutlined />,
label: <Link to="/rules">{member.is_superadmin ? '比例与税费规则' : '合作政策与权益'}</Link>,
},
{
key: '/invitations',
icon: <GiftOutlined />,
label: <Link to="/invitations">邀请返利设置</Link>,
},
]
const selectedKey = menuItems.some((item) => item && 'key' in item && item.key === location.pathname)
@@ -162,6 +169,7 @@ function MainLayout({ member, onLogout }: { member: CurrentMember; onLogout: ()
<Route path="/sold" element={<Orders kind="sold" />} />
<Route path="/receive" element={<Orders kind="receive" />} />
<Route path="/orders" element={<Orders kind="all" />} />
<Route path="/invitations" element={<Invitations />} />
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
</Layout.Content>
+82
View File
@@ -880,3 +880,85 @@ export async function testSiteSMSConfig(siteID: number, payload: TestSiteSMSConf
const resp = await api.post<ApiResponse<{ message: string }>>(`/admin/distribution/sites/${siteID}/sms-config/test`, payload)
return extract(resp)
}
export interface InvitationRebateConfig {
distribution_site_id: number
first_month_rate: number
second_month_rate: number
subsequent_rate: number
enabled: boolean
updated_at?: string
}
export interface InvitedUserItem {
id: number
inviter_id: number
inviter_phone?: string
inviter_nickname?: string
invitee_id: number
invitee_phone?: string
invitee_nickname?: string
invite_code: string
status: string
verified_at?: string
created_at: string
}
export interface RebateLedgerItem {
id: number
order_id: number
order_no: string
inviter_id: number
inviter_phone?: string
inviter_nickname?: string
invitee_id: number
invitee_phone?: string
invitee_nickname?: string
trade_role: 'buyer' | 'seller'
order_profit_basis_cent: number
single_side_basis_cent: number
rate_applied: number
days_since_verified: number
cycle_stage: string
rebate_amount_cent: number
status: string
settled_at: string
}
export async function fetchSiteInvitationConfig(siteID?: number): Promise<InvitationRebateConfig> {
const url = siteID ? `/distribution/sites/${siteID}/invitation-config` : '/distribution/invitation-config'
const resp = await api.get<ApiResponse<InvitationRebateConfig>>(url)
return extract(resp)
}
export async function updateSiteInvitationConfig(
siteID: number,
payload: {
first_month_rate: number
second_month_rate: number
subsequent_rate: number
enabled: boolean
}
): Promise<InvitationRebateConfig> {
const url = siteID ? `/distribution/sites/${siteID}/invitation-config` : '/distribution/invitation-config'
const resp = await api.put<ApiResponse<InvitationRebateConfig>>(url, payload)
return extract(resp)
}
export async function fetchSiteInvitations(
siteID: number,
params: { page: number; page_size: number; phone?: string; invite_code?: string }
): Promise<{ items: InvitedUserItem[]; total: number; page: number; page_size: number }> {
const url = siteID ? `/distribution/sites/${siteID}/invitations` : '/distribution/invitations'
const resp = await api.get<ApiResponse<{ items: InvitedUserItem[]; total: number; page: number; page_size: number }>>(url, { params })
return extract(resp)
}
export async function fetchSiteRebates(
siteID: number,
params: { page: number; page_size: number; order_no?: string; inviter_phone?: string; invitee_phone?: string }
): Promise<{ items: RebateLedgerItem[]; total: number; page: number; page_size: number }> {
const url = siteID ? `/distribution/sites/${siteID}/invitation-rebates` : '/distribution/invitation-rebates'
const resp = await api.get<ApiResponse<{ items: RebateLedgerItem[]; total: number; page: number; page_size: number }>>(url, { params })
return extract(resp)
}
@@ -0,0 +1,529 @@
import { useEffect, useState, useCallback } from 'react'
import {
Card,
Typography,
Space,
Select,
message,
Button,
Form,
InputNumber,
Switch,
Alert,
Tabs,
Table,
Tag,
Input,
Row,
Col,
} from 'antd'
import {
SettingOutlined,
UserOutlined,
DollarCircleOutlined,
SaveOutlined,
ReloadOutlined,
SearchOutlined,
InfoCircleOutlined,
} from '@ant-design/icons'
import {
fetchSiteInvitationConfig,
updateSiteInvitationConfig,
fetchSiteInvitations,
fetchSiteRebates,
listSites,
formatMoney,
type Site,
type InvitedUserItem,
type RebateLedgerItem,
} from '../api'
import { useMember } from '../MemberContext'
export default function Invitations() {
const member = useMember()
const isSuperadmin = Boolean(member?.is_superadmin)
const [sites, setSites] = useState<Site[]>([])
const [selectedSiteID, setSelectedSiteID] = useState<number>(member?.site_id || 0)
const [activeTab, setActiveTab] = useState<string>('config')
// 配置表单状态
const [loadingConfig, setLoadingConfig] = useState(false)
const [savingConfig, setSavingConfig] = useState(false)
const [form] = Form.useForm()
// 邀请关系状态
const [loadingInvitations, setLoadingInvitations] = useState(false)
const [invitations, setInvitations] = useState<InvitedUserItem[]>([])
const [invitationsTotal, setInvitationsTotal] = useState(0)
const [invitationPage, setInvitationPage] = useState(1)
const [invitationPhone, setInvitationPhone] = useState('')
const [invitationCode, setInvitationCode] = useState('')
// 返利流水状态
const [loadingRebates, setLoadingRebates] = useState(false)
const [rebates, setRebates] = useState<RebateLedgerItem[]>([])
const [rebatesTotal, setRebatesTotal] = useState(0)
const [rebatePage, setRebatePage] = useState(1)
const [rebateOrderNo, setRebateOrderNo] = useState('')
const [rebateInviterPhone, setRebateInviterPhone] = useState('')
// 加载站点列表(仅超管可选站点)
useEffect(() => {
if (isSuperadmin) {
listSites()
.then((data) => {
setSites(data)
if (!selectedSiteID && data.length > 0) {
setSelectedSiteID(data[0].id)
}
})
.catch(() => {
// ignore
})
} else if (member?.site_id) {
setSelectedSiteID(member.site_id)
}
}, [isSuperadmin, member?.site_id, selectedSiteID])
// 加载配置
const loadConfig = useCallback(async (siteID: number) => {
if (!siteID) return
setLoadingConfig(true)
try {
const cfg = await fetchSiteInvitationConfig(siteID)
form.setFieldsValue({
enabled: cfg.enabled !== false,
firstMonthRate: Math.round((cfg.first_month_rate || 0.6) * 100),
secondMonthRate: Math.round((cfg.second_month_rate || 0.3) * 100),
subsequentRate: Math.round((cfg.subsequent_rate || 0.15) * 100),
})
} catch {
message.error('获取本站邀请返利配置失败')
} finally {
setLoadingConfig(false)
}
}, [form])
// 加载邀请关系
const loadInvitations = useCallback(async (siteID: number, page = 1) => {
if (!siteID) return
setLoadingInvitations(true)
try {
const res = await fetchSiteInvitations(siteID, {
page,
page_size: 15,
phone: invitationPhone.trim() || undefined,
invite_code: invitationCode.trim() || undefined,
})
setInvitations(res.items || [])
setInvitationsTotal(res.total || 0)
setInvitationPage(page)
} catch {
message.error('获取邀请关系列表失败')
} finally {
setLoadingInvitations(false)
}
}, [invitationPhone, invitationCode])
// 加载返利流水
const loadRebates = useCallback(async (siteID: number, page = 1) => {
if (!siteID) return
setLoadingRebates(true)
try {
const res = await fetchSiteRebates(siteID, {
page,
page_size: 15,
order_no: rebateOrderNo.trim() || undefined,
inviter_phone: rebateInviterPhone.trim() || undefined,
})
setRebates(res.items || [])
setRebatesTotal(res.total || 0)
setRebatePage(page)
} catch {
message.error('获取返利流水列表失败')
} finally {
setLoadingRebates(false)
}
}, [rebateOrderNo, rebateInviterPhone])
useEffect(() => {
if (selectedSiteID) {
if (activeTab === 'config') {
void loadConfig(selectedSiteID)
} else if (activeTab === 'invitations') {
void loadInvitations(selectedSiteID, 1)
} else if (activeTab === 'rebates') {
void loadRebates(selectedSiteID, 1)
}
}
}, [selectedSiteID, activeTab, loadConfig, loadInvitations, loadRebates])
// 保存配置
const handleSaveConfig = async () => {
try {
const values = await form.validateFields()
setSavingConfig(true)
await updateSiteInvitationConfig(selectedSiteID, {
enabled: Boolean(values.enabled),
first_month_rate: Number((values.firstMonthRate / 100).toFixed(4)),
second_month_rate: Number((values.secondMonthRate / 100).toFixed(4)),
subsequent_rate: Number((values.subsequentRate / 100).toFixed(4)),
})
message.success('分站邀请返利比例配置已保存')
} catch {
message.error('保存返利比例配置失败,请检查输入')
} finally {
setSavingConfig(false)
}
}
const tabItems = [
{
key: 'config',
label: (
<span>
<SettingOutlined /> 本站返利比例自主设置
</span>
),
children: (
<Card loading={loadingConfig} style={{ marginTop: 8 }}>
<Alert
message="分站自主返利机制说明"
description="本站邀请返利支出由本站自身产生的利润出资(收号产生的卖家端收益或本站售出产生的买家端收益)。分站站长可根据本站经营策略自由调整分成比例,独立核算,不影响其他站点。"
type="info"
showIcon
icon={<InfoCircleOutlined />}
style={{ marginBottom: 24 }}
/>
<Form
form={form}
layout="vertical"
style={{ maxWidth: 580 }}
initialValues={{
enabled: true,
firstMonthRate: 60,
secondMonthRate: 30,
subsequentRate: 15,
}}
>
<Form.Item
name="enabled"
label="本站返利总开关"
valuePropName="checked"
extra="关闭后,属于本站收益承担的订单将不再向邀请人计算并发放返利"
>
<Switch checkedChildren="已启用本站返利" unCheckedChildren="暂停本站返利" />
</Form.Item>
<Form.Item
name="firstMonthRate"
label="首月分成比例(被邀请人实名生效 1 ~ 30 天)"
rules={[{ required: true, message: '请输入首月比例' }]}
extra="默认 60%,按本站单边毛利基准计提返利奖励"
>
<InputNumber min={0} max={100} step={5} addonAfter="%" style={{ width: 160 }} />
</Form.Item>
<Form.Item
name="secondMonthRate"
label="次月分成比例(被邀请人实名生效 31 ~ 60 天)"
rules={[{ required: true, message: '请输入次月比例' }]}
extra="默认 30%"
>
<InputNumber min={0} max={100} step={5} addonAfter="%" style={{ width: 160 }} />
</Form.Item>
<Form.Item
name="subsequentRate"
label="往后长期分成比例(实名生效 60 天后永久有效)"
rules={[{ required: true, message: '请输入往后长期比例' }]}
extra="默认 15%,终身持续绑定产生收益"
>
<InputNumber min={0} max={100} step={5} addonAfter="%" style={{ width: 160 }} />
</Form.Item>
<Form.Item style={{ marginTop: 24 }}>
<Button
type="primary"
icon={<SaveOutlined />}
loading={savingConfig}
onClick={handleSaveConfig}
size="large"
>
保存本站比例配置
</Button>
</Form.Item>
</Form>
</Card>
),
},
{
key: 'invitations',
label: (
<span>
<UserOutlined /> 本站邀请关系 ({invitationsTotal})
</span>
),
children: (
<Card style={{ marginTop: 8 }}>
<Space direction="horizontal" style={{ marginBottom: 16 }} wrap>
<Input
placeholder="搜索手机号"
value={invitationPhone}
onChange={(e) => setInvitationPhone(e.target.value)}
style={{ width: 180 }}
allowClear
/>
<Input
placeholder="搜索邀请码"
value={invitationCode}
onChange={(e) => setInvitationCode(e.target.value)}
style={{ width: 160 }}
allowClear
/>
<Button
type="primary"
icon={<SearchOutlined />}
onClick={() => loadInvitations(selectedSiteID, 1)}
>
查询
</Button>
<Button
icon={<ReloadOutlined />}
onClick={() => {
setInvitationPhone('')
setInvitationCode('')
void loadInvitations(selectedSiteID, 1)
}}
>
重置
</Button>
</Space>
<Table<InvitedUserItem>
loading={loadingInvitations}
dataSource={invitations}
rowKey="id"
pagination={{
current: invitationPage,
pageSize: 15,
total: invitationsTotal,
onChange: (p) => loadInvitations(selectedSiteID, p),
showTotal: (total) => `共 ${total} 条邀请关系`,
}}
columns={[
{
title: '邀请人',
key: 'inviter',
render: (_, r) => (
<div>
<div>{r.inviter_nickname || '用户' + r.inviter_id}</div>
<Typography.Text type="secondary" style={{ fontSize: 12 }}>
{r.inviter_phone || '--'}
</Typography.Text>
</div>
),
},
{
title: '邀请码',
dataIndex: 'invite_code',
render: (code) => <Tag color="blue">{code}</Tag>,
},
{
title: '被邀请人',
key: 'invitee',
render: (_, r) => (
<div>
<div>{r.invitee_nickname || '用户' + r.invitee_id}</div>
<Typography.Text type="secondary" style={{ fontSize: 12 }}>
{r.invitee_phone || '--'}
</Typography.Text>
</div>
),
},
{
title: '实名状态',
dataIndex: 'status',
render: (status) =>
status === 'active' ? (
<Tag color="green">已实名生效</Tag>
) : (
<Tag color="orange">注册待实名</Tag>
),
},
{
title: '注册时间',
dataIndex: 'created_at',
},
{
title: '实名通过时间',
dataIndex: 'verified_at',
render: (val) => val || '--',
},
]}
/>
</Card>
),
},
{
key: 'rebates',
label: (
<span>
<DollarCircleOutlined /> 本站返利流水 ({rebatesTotal})
</span>
),
children: (
<Card style={{ marginTop: 8 }}>
<Space direction="horizontal" style={{ marginBottom: 16 }} wrap>
<Input
placeholder="订单号"
value={rebateOrderNo}
onChange={(e) => setRebateOrderNo(e.target.value)}
style={{ width: 180 }}
allowClear
/>
<Input
placeholder="邀请人手机号"
value={rebateInviterPhone}
onChange={(e) => setRebateInviterPhone(e.target.value)}
style={{ width: 160 }}
allowClear
/>
<Button
type="primary"
icon={<SearchOutlined />}
onClick={() => loadRebates(selectedSiteID, 1)}
>
查询
</Button>
<Button
icon={<ReloadOutlined />}
onClick={() => {
setRebateOrderNo('')
setRebateInviterPhone('')
void loadRebates(selectedSiteID, 1)
}}
>
重置
</Button>
</Space>
<Table<RebateLedgerItem>
loading={loadingRebates}
dataSource={rebates}
rowKey="id"
pagination={{
current: rebatePage,
pageSize: 15,
total: rebatesTotal,
onChange: (p) => loadRebates(selectedSiteID, p),
showTotal: (total) => `共 ${total} 条返利流水`,
}}
columns={[
{
title: '订单号',
dataIndex: 'order_no',
render: (no) => <Typography.Text copyable>{no}</Typography.Text>,
},
{
title: '分成端',
dataIndex: 'trade_role',
render: (role) =>
role === 'buyer' ? (
<Tag color="blue">买家端 (本站售出)</Tag>
) : (
<Tag color="green">卖家端 (本站收号)</Tag>
),
},
{
title: '收益基准',
dataIndex: 'single_side_basis_cent',
render: (cent) => formatMoney(cent),
},
{
title: '分成比例',
dataIndex: 'rate_applied',
render: (r, row) => (
<div>
<Tag color="purple">{(r * 100).toFixed(1)}%</Tag>
<span style={{ fontSize: 12, color: '#888' }}>
{row.cycle_stage === 'first_month'
? '首月'
: row.cycle_stage === 'second_month'
? '次月'
: '长期'}
</span>
</div>
),
},
{
title: '返利发放金额',
dataIndex: 'rebate_amount_cent',
render: (cent) => (
<span style={{ color: '#52c41a', fontWeight: 'bold' }}>
+{formatMoney(cent)}
</span>
),
},
{
title: '获益邀请人',
key: 'inviter',
render: (_, r) => (
<div>
<div>{r.inviter_nickname || '用户' + r.inviter_id}</div>
<Typography.Text type="secondary" style={{ fontSize: 12 }}>
{r.inviter_phone || '--'}
</Typography.Text>
</div>
),
},
{
title: '结算时间',
dataIndex: 'settled_at',
},
]}
/>
</Card>
),
},
]
return (
<Space direction="vertical" className="page" style={{ width: '100%' }} size="middle">
<Row justify="space-between" align="middle">
<Col>
<Typography.Title level={3} style={{ marginBottom: 4 }}>
本站邀请返利自主设置
</Typography.Title>
<Typography.Text type="secondary">
分销站点可根据自身经营策略,自由调整本站邀请返利比例并监控本站返利支出与用户绑定流水。
</Typography.Text>
</Col>
<Col>
{isSuperadmin && sites.length > 0 ? (
<Space>
<span>切换分销网站:</span>
<Select
style={{ width: 220 }}
value={selectedSiteID}
onChange={(val) => setSelectedSiteID(val)}
options={sites.map((s) => ({
value: s.id,
label: `${s.site_name} (${s.site_code})`,
}))}
/>
</Space>
) : (
<Tag color="blue" style={{ fontSize: 13, padding: '4px 10px' }}>
当前站点: {member?.site_name} ({member?.site_code})
</Tag>
)}
</Col>
</Row>
<Tabs activeKey={activeTab} onChange={setActiveTab} items={tabItems} />
</Space>
)
}
@@ -126,7 +126,7 @@ async function loadInvitations() {
params.distribution_site_id = invitationQuery.distribution_site_id
}
const { data } = await apiClient.get('/invitations', { params })
const { data } = await apiClient.get('/admin/invitations', { params })
invitations.value = data.data.items || []
invitationsTotal.value = data.data.total || 0
} catch (err) {
@@ -150,7 +150,7 @@ async function loadRebates() {
params.distribution_site_id = rebateQuery.distribution_site_id
}
const { data } = await apiClient.get('/invitations/rebates', { params })
const { data } = await apiClient.get('/admin/invitations/rebates', { params })
rebates.value = data.data.items || []
rebatesTotal.value = data.data.total || 0
} catch (err) {
@@ -231,6 +231,14 @@ function cycleLabel(cycle: string) {
</el-select>
<el-button :icon="Refresh" circle @click="loadConfig" />
</div>
<div v-if="selectedSiteId === 0" class="site-desc-hint">
💡
说明:当前配置为【主站平台订单默认分成比例】(分站未设置专属比例时作为全局兜底)。各加盟分销站可在其专属【分销后台】中自主调整属于该分站的返利比例,分成支出由分站自身收益承担。
</div>
<div v-else class="site-desc-hint">
💡
说明:当前正在为指定分销站维护专属返利比例(该分站管理员亦可在其独立分销后台中自主设置,分成支出由该分站自身收益承担)。
</div>
</div>
<div v-loading="loadingConfig" class="config-form-body">
@@ -507,9 +515,19 @@ function cycleLabel(cycle: string) {
display: flex;
align-items: center;
gap: 12px;
padding-bottom: 18px;
padding-bottom: 14px;
border-bottom: 1px solid #f1f5f9;
margin-bottom: 20px;
margin-bottom: 14px;
}
.site-desc-hint {
font-size: 13px;
color: #475569;
background: #f8fafc;
border-left: 3px solid #3b82f6;
padding: 8px 12px;
border-radius: 4px;
margin-bottom: 18px;
}
.rate-input-box {
File diff suppressed because it is too large Load Diff
@@ -27,7 +27,16 @@ const form = reactive({
const { countDown, sending, handleSendCode } = useSmsCountdown()
onMounted(loadCaptcha)
onMounted(() => {
if (route.query.tab === 'register' || route.query.invite_code || route.query.code) {
void router.replace({
path: '/m/register',
query: route.query,
})
return
}
void loadCaptcha()
})
function switchToPassword() {
loginMode.value = 'password'
@@ -13,10 +13,15 @@ const router = useRouter()
const route = useRoute()
const session = useSessionStore()
const siteStore = useDistributionSiteStore()
const loading = ref(false)
const agreed = ref(false)
const captchaLoading = ref(false)
const captcha = ref<AuthCaptcha | null>(null)
const isInviteLocked = ref(false)
const showPassword = ref(false)
const showConfirmPassword = ref(false)
const form = reactive({
phone: '',
captchaCode: '',
@@ -28,7 +33,14 @@ const form = reactive({
const { countDown, sending, handleSendCode } = useSmsCountdown()
onMounted(loadCaptcha)
onMounted(async () => {
await loadCaptcha()
const qInviteCode = (route.query.invite_code || route.query.code) as string | undefined
if (qInviteCode && qInviteCode.trim()) {
form.inviteCode = qInviteCode.trim()
isInviteLocked.value = true
}
})
async function loadCaptcha() {
captchaLoading.value = true
@@ -54,11 +66,20 @@ async function sendCode() {
}
async function handleRegister() {
if (!agreed.value) {
showToast({
message: '请先阅读并同意用户协议和隐私政策',
icon: 'warning-o',
})
if (!form.phone.trim()) {
showToast({ message: '请输入手机号', icon: 'warning-o' })
return
}
if (!/^1[3-9]\d{9}$/.test(form.phone.trim())) {
showToast({ message: '请输入正确的11位手机号码', icon: 'warning-o' })
return
}
if (!form.captchaCode.trim()) {
showToast({ message: '请输入图形验证码', icon: 'warning-o' })
return
}
if (!form.code.trim()) {
showToast({ message: '请输入短信验证码', icon: 'warning-o' })
return
}
if (!form.password) {
@@ -73,14 +94,27 @@ async function handleRegister() {
showToast({ message: '两次输入的密码不一致', icon: 'warning-o' })
return
}
if (!agreed.value) {
showToast({
message: '请先阅读并同意用户协议和隐私政策',
icon: 'warning-o',
})
return
}
loading.value = true
try {
await session.register(form.phone, form.code, form.password)
await session.register(
form.phone.trim(),
form.code.trim(),
form.password,
form.inviteCode.trim() || undefined
)
showToast({ message: '注册成功', icon: 'success' })
const redirect = typeof route.query.redirect === 'string' ? route.query.redirect : '/m/profile'
await router.replace(redirect)
} catch {
showToast({ message: '注册失败,请检查手机号和验证码', icon: 'cross' })
} catch (error) {
showToast({ message: readError(error, '注册失败,请核对信息'), icon: 'cross' })
} finally {
loading.value = false
}
@@ -90,12 +124,13 @@ async function handleRegister() {
<template>
<main class="mobile-register-shell">
<header class="page-header">
<button class="back-btn" type="button" @click="router.back()">
<button class="back-btn" type="button" aria-label="返回上一页" @click="router.back()">
<van-icon name="arrow-left" :size="20" />
</button>
</header>
<section class="auth-body">
<!-- 品牌信息 -->
<div class="brand-lockup">
<img v-if="siteStore.logoUrl" :src="siteStore.logoUrl" alt="" class="brand-logo-img" />
<div v-else class="brand-logo">{{ siteStore.brandMark }}</div>
@@ -103,30 +138,39 @@ async function handleRegister() {
</div>
<div class="form-section">
<h1>注册</h1>
<div class="form-title-row">
<h1>注册账号</h1>
<RouterLink to="/m/login" class="title-link">已有账号?<b>去登录</b></RouterLink>
</div>
<!-- 手机号 -->
<label class="auth-input-row">
<van-icon name="phone-o" class="row-icon" />
<input
v-model="form.phone"
type="tel"
maxlength="11"
inputmode="tel"
placeholder="手机号"
placeholder="请输入手机号"
autocomplete="tel"
/>
</label>
<!-- 图形验证码 -->
<label class="auth-input-row captcha-row">
<van-icon name="shield-o" class="row-icon" />
<input
v-model="form.captchaCode"
type="text"
maxlength="4"
autocomplete="off"
placeholder="图形验证码"
placeholder="请输入图形验证码"
/>
<button
class="captcha-image-button"
type="button"
:disabled="captchaLoading"
title="点击刷新验证码"
@click="loadCaptcha"
>
<img v-if="captcha" :src="captcha.image" alt="图形验证码" />
@@ -134,13 +178,15 @@ async function handleRegister() {
</button>
</label>
<!-- 短信验证码 -->
<label class="auth-input-row code-row">
<van-icon name="comment-o" class="row-icon" />
<input
v-model="form.code"
type="text"
inputmode="numeric"
maxlength="6"
placeholder="验证码"
placeholder="请输入短信验证码"
/>
<span class="code-action">
<van-button
@@ -156,39 +202,66 @@ async function handleRegister() {
</span>
</label>
<label class="auth-input-row">
<!-- 设置密码 -->
<label class="auth-input-row pwd-row">
<van-icon name="lock" class="row-icon" />
<input
v-model="form.password"
type="password"
:type="showPassword ? 'text' : 'password'"
maxlength="20"
placeholder="设置密码(8-20 位)"
autocomplete="new-password"
/>
<button
type="button"
class="pwd-toggle-btn"
aria-label="切换密码可见性"
@click="showPassword = !showPassword"
>
<van-icon :name="showPassword ? 'eye-o' : 'closed-eye'" size="18" />
</button>
</label>
<label class="auth-input-row">
<!-- 确认密码 -->
<label class="auth-input-row pwd-row">
<van-icon name="lock" class="row-icon" />
<input
v-model="form.confirmPassword"
type="password"
:type="showConfirmPassword ? 'text' : 'password'"
maxlength="20"
placeholder="确认密码"
placeholder="确认登录密码"
autocomplete="new-password"
/>
<button
type="button"
class="pwd-toggle-btn"
aria-label="切换密码可见性"
@click="showConfirmPassword = !showConfirmPassword"
>
<van-icon :name="showConfirmPassword ? 'eye-o' : 'closed-eye'" size="18" />
</button>
</label>
<label class="auth-input-row">
<input v-model="form.inviteCode" maxlength="16" placeholder="邀请码(选填)" />
<!-- 邀请码 -->
<label class="auth-input-row invite-row" :class="{ 'is-locked': isInviteLocked }">
<van-icon name="coupon-o" class="row-icon" />
<input
v-model="form.inviteCode"
maxlength="32"
:readonly="isInviteLocked"
:placeholder="isInviteLocked ? '' : '邀请码(选填)'"
/>
<span v-if="isInviteLocked" class="invite-locked-tag">已绑定邀请码</span>
</label>
<div class="assist-row">
<span>验证码注册</span>
<RouterLink to="/m/login">已有账号?<b>去登录</b></RouterLink>
</div>
<!-- 协议勾选 -->
<div class="agreement-row">
<van-checkbox v-model="agreed" shape="square" icon-size="16px">
<van-checkbox v-model="agreed" shape="square" icon-size="16px" checked-color="#ff6a00">
我已阅读并同意《<b>用户协议</b>》和《<b>隐私政策</b>》
</van-checkbox>
</div>
<!-- 注册按钮 -->
<van-button
type="primary"
block
@@ -200,7 +273,8 @@ async function handleRegister() {
注册并登录
</van-button>
<RouterLink to="/m/login" class="secondary-entry"> 返回登录 </RouterLink>
<!-- 底部快捷跳转 -->
<RouterLink to="/m/login" class="secondary-entry"> 已有账号?去登录 </RouterLink>
</div>
</section>
</main>
@@ -209,9 +283,10 @@ async function handleRegister() {
<style scoped>
.mobile-register-shell {
min-height: 100dvh;
box-sizing: border-box;
background:
radial-gradient(circle at 50% 12%, rgba(20, 119, 255, 0.1), transparent 34%),
linear-gradient(180deg, #f8fbff 0%, #ffffff 70%, #f7fafc 100%);
radial-gradient(circle at 50% 12%, rgba(255, 106, 0, 0.12), transparent 34%),
linear-gradient(180deg, #fff7ed 0%, #ffffff 68%, #fffaf4 100%);
color: #111827;
}
@@ -224,20 +299,20 @@ async function handleRegister() {
display: flex;
align-items: center;
height: 48px;
margin: 0;
padding: 0 18px;
padding: 0 16px;
background: transparent;
}
.back-btn {
display: grid;
width: 34px;
height: 34px;
width: 36px;
height: 36px;
place-items: center;
border: none;
border-radius: 999px;
background: none;
color: #111827;
background: rgba(255, 255, 255, 0.8);
color: #1e293b;
box-shadow: 0 2px 8px rgba(15, 23, 42, 0.06);
}
.auth-body {
@@ -246,113 +321,158 @@ async function handleRegister() {
min-height: 100dvh;
flex-direction: column;
justify-content: center;
padding: 50px 34px 22px;
padding: 56px 24px 32px;
}
/* 品牌头部 */
.brand-lockup {
display: flex;
flex-direction: column;
align-items: center;
gap: 8px;
margin: 0 auto clamp(24px, 4vh, 38px);
margin: 0 auto clamp(20px, 3vh, 32px);
}
.brand-logo {
display: grid;
width: 46px;
height: 46px;
width: 48px;
height: 48px;
place-items: center;
border-radius: 14px;
background: linear-gradient(135deg, #1477ff, #2f8dff);
box-shadow: 0 14px 32px rgba(20, 119, 255, 0.18);
background: linear-gradient(135deg, #ff6a00, #ff8a1f);
box-shadow: 0 10px 26px rgba(255, 106, 0, 0.28);
color: #ffffff;
font-size: 19px;
font-size: 20px;
font-weight: 900;
}
.brand-logo-img {
width: 46px;
height: 46px;
width: 48px;
height: 48px;
border-radius: 14px;
object-fit: cover;
box-shadow: 0 14px 32px rgba(23, 35, 61, 0.12);
box-shadow: 0 10px 26px rgba(23, 35, 61, 0.12);
}
.brand-lockup strong {
display: block;
color: #111827;
font-size: 18px;
color: #0f172a;
font-size: 19px;
font-weight: 900;
letter-spacing: 0;
letter-spacing: 0.3px;
}
/* 表单容器 */
.form-section {
width: min(100%, 420px);
width: min(100%, 400px);
margin: 0 auto;
}
.form-section h1 {
margin: 0 0 20px;
color: #05070a;
font-size: 22px;
.form-title-row {
display: flex;
align-items: baseline;
justify-content: space-between;
margin-bottom: 20px;
}
.form-title-row h1 {
margin: 0;
color: #0f172a;
font-size: 24px;
font-weight: 900;
line-height: 1.2;
}
.title-link {
font-size: 13px;
color: #64748b;
text-decoration: none;
}
.title-link b {
color: #ff6a00;
font-weight: 700;
}
/* 输入框行 Shell */
.auth-input-row {
display: flex;
align-items: center;
min-height: 48px;
margin-bottom: 10px;
padding: 0 16px;
border: 1px solid #e1e5eb;
border-radius: 10px;
background: rgba(255, 255, 255, 0.88);
box-shadow: 0 10px 24px rgba(15, 23, 42, 0.03);
margin-bottom: 12px;
padding: 0 14px;
border: 1px solid #e2e8f0;
border-radius: 12px;
background: #ffffff;
box-shadow: 0 2px 8px rgba(15, 23, 42, 0.02);
transition:
border-color 0.2s,
box-shadow 0.2s;
}
.auth-input-row.code-row {
gap: 8px;
.auth-input-row:focus-within {
border-color: #ff6a00;
box-shadow: 0 0 0 3px rgba(255, 106, 0, 0.12);
}
.auth-input-row.captcha-row {
gap: 10px;
padding-right: 4px;
.row-icon {
font-size: 17px;
color: #94a3b8;
margin-right: 10px;
flex-shrink: 0;
}
.auth-input-row input {
width: 100%;
flex: 1;
min-width: 0;
height: 100%;
border: none;
background: transparent;
color: #0f172a;
font-size: 16px;
font-size: 15px;
outline: none;
}
.auth-input-row input::placeholder {
color: #b6beca;
color: #94a3b8;
font-size: 14px;
}
.code-action {
display: flex;
justify-content: flex-end;
/* 密码明暗切换 */
.pwd-toggle-btn {
border: none;
background: none;
color: #94a3b8;
padding: 4px;
display: grid;
place-items: center;
cursor: pointer;
}
.pwd-toggle-btn:active {
color: #ff6a00;
}
/* 图形验证码 */
.captcha-row {
padding-right: 4px;
}
.captcha-image-button {
display: grid;
flex: 0 0 116px;
width: 116px;
height: 40px;
flex: 0 0 106px;
width: 106px;
height: 38px;
place-items: center;
overflow: hidden;
border: 1px solid #dbe5f0;
border: 1px solid #e2e8f0;
border-radius: 8px;
background: #f8fafc;
color: #1477ff;
color: #ff6a00;
font-size: 12px;
font-weight: 800;
padding: 0;
cursor: pointer;
}
.captcha-image-button:disabled {
@@ -361,104 +481,125 @@ async function handleRegister() {
.captcha-image-button img {
display: block;
width: 120px;
height: 40px;
width: 100%;
height: 100%;
object-fit: cover;
}
.code-btn {
min-width: 82px;
height: 32px;
border-color: #1477ff !important;
border-radius: 8px;
color: #1477ff !important;
font-weight: 700;
/* 短信验证码 */
.code-row {
padding-right: 4px;
}
.assist-row {
.code-action {
display: flex;
align-items: center;
justify-content: space-between;
gap: 14px;
margin: 12px 0 18px;
color: #111827;
font-size: 13px;
justify-content: flex-end;
}
.assist-row span {
min-width: 0;
color: #1477ff;
.code-btn {
min-width: 86px;
height: 36px;
border: 1px solid #fed7aa !important;
border-radius: 8px !important;
background: #fff7ed !important;
color: #ff6a00 !important;
font-weight: 700;
font-size: 13px !important;
}
.assist-row a {
.code-btn:disabled {
border-color: #e2e8f0 !important;
background: #f8fafc !important;
color: #94a3b8 !important;
opacity: 0.65;
}
/* 锁定邀请码 */
.auth-input-row.is-locked {
background: #f8fafc;
border-color: #e2e8f0;
}
.auth-input-row.is-locked input {
color: #0f172a;
font-weight: 700;
letter-spacing: 0.5px;
}
.invite-locked-tag {
flex-shrink: 0;
color: #22252b;
text-decoration: none;
}
.assist-row b {
color: #05070a;
font-weight: 900;
margin-left: 8px;
padding: 3px 8px;
border-radius: 4px;
background: #ecfdf5;
border: 1px solid #a7f3d0;
color: #059669;
font-size: 11px;
font-weight: 700;
white-space: nowrap;
}
/* 协议条款勾选 */
.agreement-row {
display: flex;
align-items: center;
margin: 0 0 18px;
margin: 6px 0 18px;
}
.agreement-row :deep(.van-checkbox__label) {
margin-left: 8px;
color: #252b36;
color: #64748b;
font-size: 12px;
line-height: 1.4;
}
.agreement-row :deep(.van-checkbox__label b) {
color: #1477ff;
color: #ff6a00;
font-weight: 700;
}
/* 注册主按钮(金橙色渐变) */
.primary-button {
height: 48px;
border: none !important;
border-radius: 10px !important;
background: #1477ff !important;
box-shadow: 0 12px 24px rgba(20, 119, 255, 0.18);
font-size: 17px;
font-weight: 900;
border-radius: 12px !important;
background: linear-gradient(135deg, #ff6a00, #ff8a1f) !important;
box-shadow: 0 10px 24px rgba(255, 106, 0, 0.28) !important;
font-size: 16px;
font-weight: 800;
color: #ffffff !important;
letter-spacing: 0.5px;
}
.primary-button:active {
opacity: 0.9;
}
/* 次要入口 */
.secondary-entry {
display: grid;
min-height: 44px;
margin-top: 10px;
place-items: center;
border: 1px solid #e4e8ee;
border-radius: 10px;
background: rgba(255, 255, 255, 0.82);
color: #1477ff;
font-size: 15px;
font-weight: 900;
display: block;
margin-top: 16px;
text-align: center;
color: #64748b;
font-size: 13px;
text-decoration: none;
}
@media (max-height: 760px) {
.secondary-entry:active {
color: #ff6a00;
}
@media (max-height: 740px) {
.auth-body {
justify-content: flex-start;
padding-top: 48px;
padding-top: 52px;
}
.brand-lockup {
margin-bottom: 20px;
}
.form-section h1 {
margin-bottom: 16px;
}
.assist-row {
.form-title-row {
margin-bottom: 14px;
}
}
@@ -110,7 +110,7 @@ export async function fetchMyRebates(
/** 管理端获取返利比例配置(siteId 为 0 时为主站) */
export async function fetchAdminRebateConfig(siteId = 0): Promise<InvitationRebateConfig> {
const { data } = await apiClient.get<ApiResponse<InvitationRebateConfig>>(
'/invitations/configs',
'/admin/invitations/configs',
{
params: { distribution_site_id: siteId },
}
@@ -129,7 +129,7 @@ export async function updateAdminRebateConfig(
}
): Promise<InvitationRebateConfig> {
const { data } = await apiClient.put<ApiResponse<InvitationRebateConfig>>(
'/invitations/configs',
'/admin/invitations/configs',
config,
{
params: { distribution_site_id: siteId },
@@ -1,664 +0,0 @@
<script setup lang="ts">
import { computed, onMounted, onUnmounted, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
Lock,
Iphone,
Key,
View,
Hide,
Present,
WarningFilled,
Check,
} from '@element-plus/icons-vue'
import { fetchAuthCaptcha, sendSmsCode } from '@/features/auth/api/auth'
import { fetchInviteCodeInfo, type InviteCodeInfo } from '@/features/invitation/api/invitation'
import { useSessionStore } from '@/stores/session'
import { useDistributionSiteStore } from '@/stores/distributionSite'
import { readError } from '@/shared/utils/error'
const route = useRoute()
const router = useRouter()
const session = useSessionStore()
const siteStore = useDistributionSiteStore()
const inviteCode = computed(() => String(route.params.code || '').trim())
const loadingInfo = ref(true)
const codeInfo = ref<InviteCodeInfo | null>(null)
// 注册表单状态
const form = reactive({
phone: '',
captchaCode: '',
smsCode: '',
password: '',
confirmPassword: '',
})
const showPassword = ref(false)
const showConfirmPassword = ref(false)
const submitting = ref(false)
// 图形验证码状态
const captchaId = ref('')
const captchaImage = ref('')
const loadingCaptcha = ref(false)
// 短信倒计时
const smsCountdown = ref(0)
let timer: ReturnType<typeof setInterval> | null = null
onMounted(async () => {
await Promise.all([loadCodeInfo(), refreshCaptcha()])
})
onUnmounted(() => {
if (timer) clearInterval(timer)
})
async function loadCodeInfo() {
if (!inviteCode.value) {
loadingInfo.value = false
return
}
loadingInfo.value = true
try {
const res = await fetchInviteCodeInfo(inviteCode.value)
codeInfo.value = res
} catch (_err) {
ElMessage.warning('邀请码查询失败,请核对邀请链接')
} finally {
loadingInfo.value = false
}
}
async function refreshCaptcha() {
loadingCaptcha.value = true
try {
const res = await fetchAuthCaptcha()
captchaId.value = res.captcha_id
captchaImage.value = res.image
} catch (_err) {
ElMessage.error('获取图形验证码失败,请点击刷新')
} finally {
loadingCaptcha.value = false
}
}
async function handleSendSms() {
if (!/^1[3-9]\d{9}$/.test(form.phone)) {
ElMessage.warning('请输入正确的11位手机号码')
return
}
if (!form.captchaCode) {
ElMessage.warning('请先输入图形验证码')
return
}
if (smsCountdown.value > 0) return
try {
await sendSmsCode(form.phone, captchaId.value, form.captchaCode)
ElMessage.success('短信验证码已发送')
smsCountdown.value = 60
timer = setInterval(() => {
smsCountdown.value--
if (smsCountdown.value <= 0 && timer) {
clearInterval(timer)
timer = null
}
}, 1000)
} catch (err) {
ElMessage.error(readError(err, '发送验证码失败'))
await refreshCaptcha()
}
}
async function handleSubmit() {
if (!/^1[3-9]\d{9}$/.test(form.phone)) {
ElMessage.warning('请输入正确的11位手机号码')
return
}
if (!form.smsCode || form.smsCode.length !== 6) {
ElMessage.warning('请输入6位短信验证码')
return
}
if (!form.password || form.password.length < 8 || form.password.length > 20) {
ElMessage.warning('密码长度必须为8-20位')
return
}
if (form.password !== form.confirmPassword) {
ElMessage.warning('两次输入的密码不一致')
return
}
submitting.value = true
try {
await session.register(form.phone, form.smsCode, form.password, inviteCode.value)
ElMessageBox.confirm(
'账号注册成功并已绑定邀请人!根据平台规定,完成实名认证后方可正式激活会员特权与邀请返利资格。是否立即前往实名认证?',
'注册成功',
{
confirmButtonText: '去实名认证',
cancelButtonText: '稍后再说',
type: 'success',
distinguishCancelAndClose: true,
}
)
.then(() => {
router.replace('/realname')
})
.catch(() => {
router.replace('/')
})
} catch (err) {
ElMessage.error(readError(err, '注册失败'))
await refreshCaptcha()
} finally {
submitting.value = false
}
}
</script>
<template>
<div class="invite-register-page">
<div class="invite-card-container">
<!-- 顶部邀请人特权卡片 -->
<div class="invite-header-banner">
<div class="banner-badge">
<el-icon><Present /></el-icon>
<span>专属邀请专享特权</span>
</div>
<h1 class="banner-title">加入 {{ siteStore.siteName || '哈夫币' }}</h1>
<p class="banner-sub">安全便捷的游戏资产租赁与寄售平台 · 租客号主双边返利</p>
<div v-if="loadingInfo" class="inviter-box loading">
<span>正在核对邀请信息...</span>
</div>
<div v-else-if="codeInfo && codeInfo.valid" class="inviter-box valid">
<div class="inviter-avatar">
<img v-if="codeInfo.inviter_avatar" :src="codeInfo.inviter_avatar" alt="avatar" />
<span v-else>{{ (codeInfo.inviter_nickname || '友').slice(0, 1) }}</span>
</div>
<div class="inviter-meta">
<div class="inviter-name">
来自 <strong>{{ codeInfo.inviter_nickname || '平台认证号主' }}</strong> 的邀请
</div>
<div class="inviter-desc">
专属邀请码:<code class="code-pill">{{ inviteCode }}</code>
</div>
</div>
</div>
<div v-else class="inviter-box invalid">
<el-icon color="#e6a23c"><WarningFilled /></el-icon>
<span
>邀请码
<strong>{{ inviteCode }}</strong> 暂未生效或邀请人尚未实名,注册仍可正常完成</span
>
</div>
</div>
<!-- 返利权益亮点条 -->
<div class="rebate-perks-row">
<div class="perk-item">
<span class="perk-rate">60%</span>
<span class="perk-label">首月高额分成</span>
</div>
<div class="perk-divider"></div>
<div class="perk-item">
<span class="perk-rate">30%</span>
<span class="perk-label">次月奖励分成</span>
</div>
<div class="perk-divider"></div>
<div class="perk-item">
<span class="perk-rate">15%</span>
<span class="perk-label">往后终身永久</span>
</div>
</div>
<!-- 注册表单卡片 -->
<div class="register-card-body">
<div class="form-title">创建新账号</div>
<form class="register-form" @submit.prevent="handleSubmit">
<!-- 手机号 -->
<div class="form-group">
<label>手机号码</label>
<div class="input-wrapper">
<el-icon class="input-icon"><Iphone /></el-icon>
<input
v-model="form.phone"
type="tel"
maxlength="11"
placeholder="请输入11位手机号码"
required
/>
</div>
</div>
<!-- 图形验证码 -->
<div class="form-group">
<label>图形验证码</label>
<div class="input-wrapper captcha-wrapper">
<el-icon class="input-icon"><Key /></el-icon>
<input
v-model="form.captchaCode"
type="text"
maxlength="4"
placeholder="请输入图形验证码"
required
/>
<div class="captcha-img-box" @click="refreshCaptcha">
<img v-if="captchaImage" :src="captchaImage" alt="captcha" />
<span v-else>点击获取</span>
</div>
</div>
</div>
<!-- 短信验证码 -->
<div class="form-group">
<label>短信验证码</label>
<div class="input-wrapper sms-wrapper">
<el-icon class="input-icon"><Key /></el-icon>
<input
v-model="form.smsCode"
type="text"
maxlength="6"
placeholder="6位短信验证码"
required
/>
<button
type="button"
class="sms-btn"
:disabled="smsCountdown > 0"
@click="handleSendSms"
>
{{ smsCountdown > 0 ? `${smsCountdown}秒后重试` : '获取验证码' }}
</button>
</div>
</div>
<!-- 密码 -->
<div class="form-group">
<label>登录密码</label>
<div class="input-wrapper">
<el-icon class="input-icon"><Lock /></el-icon>
<input
v-model="form.password"
:type="showPassword ? 'text' : 'password'"
placeholder="设置登录密码(8-20位)"
required
/>
<button type="button" class="pwd-toggle" @click="showPassword = !showPassword">
<el-icon><View v-if="showPassword" /><Hide v-else /></el-icon>
</button>
</div>
</div>
<!-- 确认密码 -->
<div class="form-group">
<label>确认密码</label>
<div class="input-wrapper">
<el-icon class="input-icon"><Lock /></el-icon>
<input
v-model="form.confirmPassword"
:type="showConfirmPassword ? 'text' : 'password'"
placeholder="再次输入登录密码"
required
/>
<button
type="button"
class="pwd-toggle"
@click="showConfirmPassword = !showConfirmPassword"
>
<el-icon><View v-if="showConfirmPassword" /><Hide v-else /></el-icon>
</button>
</div>
</div>
<!-- 邀请码锁定提示 -->
<div class="invite-bind-notice">
<div class="bind-badge">
<el-icon color="#67c23a"><Check /></el-icon>
<span
>已绑定邀请码:<strong>{{ inviteCode }}</strong></span
>
</div>
<p class="bind-tip">注册成功后将自动建立推荐返利关联</p>
</div>
<!-- 提交按钮 -->
<button type="submit" class="submit-btn" :disabled="submitting">
{{ submitting ? '正在注册并绑定...' : '立即注册并领取返利特权' }}
</button>
</form>
<div class="login-redirect">
已有账号?
<RouterLink to="/login" class="login-link">直接登录</RouterLink>
</div>
</div>
</div>
</div>
</template>
<style scoped>
.invite-register-page {
min-height: 100vh;
background: linear-gradient(135deg, #f0f4ff 0%, #e8edf9 100%);
display: flex;
align-items: center;
justify-content: center;
padding: 32px 16px;
box-sizing: border-box;
}
.invite-card-container {
width: 100%;
max-width: 480px;
background: #ffffff;
border-radius: 20px;
box-shadow: 0 12px 40px rgba(30, 58, 138, 0.08);
overflow: hidden;
border: 1px solid rgba(226, 232, 240, 0.8);
}
.invite-header-banner {
background: linear-gradient(135deg, #1e3a8a 0%, #2563eb 100%);
color: #ffffff;
padding: 28px 24px 20px;
text-align: center;
}
.banner-badge {
display: inline-flex;
align-items: center;
gap: 6px;
background: rgba(255, 255, 255, 0.18);
padding: 4px 12px;
border-radius: 20px;
font-size: 12px;
font-weight: 500;
margin-bottom: 12px;
backdrop-filter: blur(4px);
}
.banner-title {
margin: 0;
font-size: 22px;
font-weight: 700;
letter-spacing: 0.5px;
}
.banner-sub {
margin: 8px 0 16px;
font-size: 13px;
opacity: 0.85;
line-height: 1.5;
}
.inviter-box {
background: rgba(255, 255, 255, 0.12);
border-radius: 12px;
padding: 10px 14px;
display: flex;
align-items: center;
gap: 12px;
text-align: left;
backdrop-filter: blur(8px);
}
.inviter-box.invalid {
background: rgba(234, 179, 8, 0.2);
font-size: 12px;
}
.inviter-avatar {
width: 40px;
height: 40px;
border-radius: 50%;
background: #ffffff;
color: #2563eb;
display: flex;
align-items: center;
justify-content: center;
font-weight: 700;
font-size: 16px;
overflow: hidden;
flex-shrink: 0;
}
.inviter-avatar img {
width: 100%;
height: 100%;
object-fit: cover;
}
.inviter-meta {
flex: 1;
}
.inviter-name {
font-size: 13px;
font-weight: 500;
}
.inviter-desc {
font-size: 12px;
opacity: 0.8;
margin-top: 2px;
}
.code-pill {
background: rgba(255, 255, 255, 0.25);
padding: 1px 6px;
border-radius: 4px;
font-family: monospace;
font-weight: 700;
}
.rebate-perks-row {
display: flex;
align-items: center;
justify-content: space-around;
background: #f8fafc;
padding: 12px 16px;
border-bottom: 1px solid #e2e8f0;
}
.perk-item {
display: flex;
flex-direction: column;
align-items: center;
}
.perk-rate {
font-size: 18px;
font-weight: 800;
color: #dc2626;
line-height: 1.2;
}
.perk-label {
font-size: 11px;
color: #64748b;
margin-top: 2px;
}
.perk-divider {
width: 1px;
height: 24px;
background: #cbd5e1;
}
.register-card-body {
padding: 24px;
}
.form-title {
font-size: 16px;
font-weight: 600;
color: #1e293b;
margin-bottom: 16px;
}
.register-form {
display: flex;
flex-direction: column;
gap: 14px;
}
.form-group label {
display: block;
font-size: 13px;
font-weight: 500;
color: #475569;
margin-bottom: 6px;
}
.input-wrapper {
display: flex;
align-items: center;
position: relative;
background: #f8fafc;
border: 1px solid #cbd5e1;
border-radius: 10px;
padding: 0 12px;
transition: all 0.2s;
}
.input-wrapper:focus-within {
border-color: #2563eb;
background: #ffffff;
box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1);
}
.input-icon {
color: #94a3b8;
font-size: 16px;
margin-right: 8px;
}
.input-wrapper input {
flex: 1;
height: 42px;
border: none;
background: transparent;
font-size: 14px;
color: #1e293b;
outline: none;
}
.captcha-img-box {
width: 96px;
height: 36px;
cursor: pointer;
border-radius: 6px;
overflow: hidden;
display: flex;
align-items: center;
justify-content: center;
background: #e2e8f0;
font-size: 12px;
color: #64748b;
}
.captcha-img-box img {
width: 100%;
height: 100%;
object-fit: cover;
}
.sms-btn {
background: #2563eb;
color: #ffffff;
border: none;
border-radius: 6px;
padding: 6px 12px;
font-size: 12px;
font-weight: 500;
cursor: pointer;
white-space: nowrap;
transition: opacity 0.2s;
}
.sms-btn:disabled {
background: #94a3b8;
cursor: not-allowed;
}
.pwd-toggle {
background: none;
border: none;
color: #94a3b8;
cursor: pointer;
padding: 4px;
display: flex;
align-items: center;
}
.invite-bind-notice {
background: #f0fdf4;
border: 1px solid #bbf7d0;
border-radius: 8px;
padding: 10px 12px;
margin-top: 4px;
}
.bind-badge {
display: flex;
align-items: center;
gap: 6px;
font-size: 13px;
color: #166534;
}
.bind-tip {
margin: 4px 0 0 22px;
font-size: 11px;
color: #15803d;
}
.submit-btn {
background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%);
color: #ffffff;
border: none;
border-radius: 10px;
height: 44px;
font-size: 15px;
font-weight: 600;
cursor: pointer;
margin-top: 6px;
box-shadow: 0 4px 12px rgba(37, 99, 235, 0.25);
transition: all 0.2s;
}
.submit-btn:hover:not(:disabled) {
opacity: 0.95;
box-shadow: 0 6px 16px rgba(37, 99, 235, 0.35);
}
.submit-btn:disabled {
background: #94a3b8;
cursor: not-allowed;
box-shadow: none;
}
.login-redirect {
text-align: center;
font-size: 13px;
color: #64748b;
margin-top: 18px;
}
.login-link {
color: #2563eb;
font-weight: 600;
text-decoration: none;
}
.login-link:hover {
text-decoration: underline;
}
</style>
@@ -269,7 +269,10 @@ function cycleLabel(cycle: string) {
<!-- 阶梯分成规则说明 -->
<div class="rules-card">
<div class="rules-header">
<h3>邀请返利分成规则说明</h3>
<div class="rules-header-title">
<div class="rules-title-bar"></div>
<h3>邀请返利分成规则说明</h3>
</div>
<span class="rule-tip">以被邀请人完成实名认证时刻作为周期计算起点</span>
</div>
@@ -462,53 +465,74 @@ function cycleLabel(cycle: string) {
}
.hero-card {
background: linear-gradient(135deg, #1e3a8a 0%, #2563eb 100%);
border-radius: 16px;
position: relative;
overflow: hidden;
background:
radial-gradient(circle at 90% 15%, rgba(255, 106, 0, 0.22) 0%, transparent 50%),
radial-gradient(circle at 10% 85%, rgba(255, 133, 46, 0.12) 0%, transparent 45%),
linear-gradient(145deg, #0d121c 0%, #151d2d 45%, #1e293b 100%);
border: 1px solid rgba(255, 106, 0, 0.25);
border-radius: 20px;
color: #ffffff;
padding: 32px 28px;
padding: 36px 32px;
display: flex;
flex-direction: column;
gap: 20px;
box-shadow: 0 10px 25px rgba(37, 99, 235, 0.15);
gap: 22px;
box-shadow:
0 12px 32px rgba(15, 23, 42, 0.22),
0 4px 16px rgba(255, 106, 0, 0.08);
}
.hero-left {
position: relative;
z-index: 2;
}
.hero-badge {
display: inline-flex;
align-items: center;
gap: 6px;
background: rgba(255, 255, 255, 0.2);
padding: 4px 12px;
background: rgba(255, 106, 0, 0.16);
border: 1px solid rgba(255, 133, 46, 0.4);
color: #ff9b4e;
padding: 4px 14px;
border-radius: 20px;
font-size: 13px;
font-weight: 500;
margin-bottom: 12px;
backdrop-filter: blur(4px);
font-weight: 600;
margin-bottom: 14px;
backdrop-filter: blur(8px);
}
.hero-title {
font-size: 26px;
font-size: 28px;
font-weight: 800;
margin: 0;
letter-spacing: 0.5px;
background: linear-gradient(135deg, #ffffff 60%, #ffd8a8 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
.hero-subtitle {
font-size: 14px;
opacity: 0.9;
margin: 8px 0 0;
line-height: 1.5;
color: #cbd5e1;
margin: 10px 0 0;
line-height: 1.6;
}
.hero-unverified-alert {
background: rgba(234, 179, 8, 0.18);
border: 1px solid rgba(253, 224, 71, 0.4);
border-radius: 12px;
padding: 14px 18px;
position: relative;
z-index: 2;
background: rgba(255, 106, 0, 0.12);
border: 1px solid rgba(255, 106, 0, 0.35);
border-radius: 14px;
padding: 16px 20px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
flex-wrap: wrap;
backdrop-filter: blur(10px);
}
.alert-content {
@@ -519,38 +543,40 @@ function cycleLabel(cycle: string) {
.alert-icon {
font-size: 24px;
color: #fde047;
color: #ff852e;
}
.alert-text strong {
display: block;
font-size: 14px;
color: #fef08a;
color: #fed7aa;
}
.alert-text p {
margin: 2px 0 0;
margin: 3px 0 0;
font-size: 12px;
color: #f8fafc;
color: #e2e8f0;
}
.realname-btn {
background: #facc15;
color: #854d0e;
background: linear-gradient(135deg, #ff6a00 0%, #ff852e 100%);
color: #ffffff;
border: none;
border-radius: 8px;
padding: 8px 16px;
padding: 9px 18px;
font-size: 13px;
font-weight: 700;
cursor: pointer;
display: inline-flex;
align-items: center;
gap: 4px;
transition: opacity 0.2s;
box-shadow: 0 4px 12px rgba(255, 106, 0, 0.3);
transition: all 0.2s;
}
.realname-btn:hover {
opacity: 0.9;
box-shadow: 0 6px 16px rgba(255, 106, 0, 0.45);
transform: translateY(-1px);
}
.stats-row {
@@ -562,10 +588,17 @@ function cycleLabel(cycle: string) {
.stat-card {
background: #ffffff;
border-radius: 14px;
padding: 20px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.04);
border-radius: 16px;
padding: 22px;
box-shadow: 0 2px 12px rgba(15, 23, 42, 0.04);
border: 1px solid #f1f5f9;
transition: all 0.25s ease;
}
.stat-card:hover {
border-color: #fed7aa;
box-shadow: 0 8px 24px rgba(255, 106, 0, 0.08);
transform: translateY(-2px);
}
.stat-header {
@@ -577,28 +610,31 @@ function cycleLabel(cycle: string) {
.stat-label {
font-size: 13px;
color: #64748b;
font-weight: 500;
font-weight: 600;
}
.stat-icon {
font-size: 20px;
padding: 6px;
border-radius: 8px;
padding: 8px;
border-radius: 10px;
}
.stat-icon.income {
background: #fef2f2;
color: #dc2626;
background: #fff7ed;
color: #ea580c;
border: 1px solid #ffedd5;
}
.stat-icon.month {
background: #eff6ff;
color: #2563eb;
background: #fefce8;
color: #d97706;
border: 1px solid #fef08a;
}
.stat-icon.users {
background: #f0fdf4;
color: #16a34a;
border: 1px solid #dcfce7;
}
.stat-value {
@@ -610,14 +646,15 @@ function cycleLabel(cycle: string) {
}
.stat-value strong {
font-size: 28px;
font-size: 30px;
font-weight: 800;
letter-spacing: -0.5px;
}
.currency {
font-size: 18px;
font-weight: 700;
color: #dc2626;
color: #ea580c;
}
.stat-value .unit {
@@ -634,10 +671,10 @@ function cycleLabel(cycle: string) {
.share-box-card {
background: #ffffff;
border-radius: 14px;
padding: 22px;
border-radius: 16px;
padding: 24px;
margin-top: 20px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.04);
box-shadow: 0 2px 12px rgba(15, 23, 42, 0.04);
border: 1px solid #f1f5f9;
}
@@ -645,7 +682,7 @@ function cycleLabel(cycle: string) {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 16px;
margin-bottom: 18px;
}
.share-title {
@@ -654,15 +691,20 @@ function cycleLabel(cycle: string) {
gap: 8px;
font-size: 16px;
font-weight: 700;
color: #1e293b;
color: #0f172a;
}
.share-title .el-icon {
color: #ff6a00;
font-size: 18px;
}
.poster-trigger-btn {
background: #eff6ff;
color: #2563eb;
border: 1px solid #bfdbfe;
border-radius: 6px;
padding: 6px 14px;
background: #fff7ed;
color: #ff6a00;
border: 1px solid #fed7aa;
border-radius: 8px;
padding: 7px 16px;
font-size: 13px;
font-weight: 600;
cursor: pointer;
@@ -673,12 +715,15 @@ function cycleLabel(cycle: string) {
}
.poster-trigger-btn:hover {
background: #dbeafe;
background: #ffedd5;
border-color: #fdba74;
color: #ea580c;
box-shadow: 0 2px 8px rgba(255, 106, 0, 0.15);
}
.share-content-row {
display: grid;
grid-template-columns: 180px 1fr;
grid-template-columns: 200px 1fr;
gap: 16px;
}
@@ -687,13 +732,13 @@ function cycleLabel(cycle: string) {
font-size: 12px;
color: #64748b;
margin-bottom: 6px;
font-weight: 500;
font-weight: 600;
}
.field-box {
background: #f8fafc;
border: 1px solid #e2e8f0;
border-radius: 8px;
background: #fffaf5;
border: 1px solid #fed7aa;
border-radius: 10px;
padding: 8px 12px;
display: flex;
align-items: center;
@@ -702,15 +747,15 @@ function cycleLabel(cycle: string) {
}
.code-text {
font-family: monospace;
font-size: 18px;
font-family: 'DIN Alternate', 'SF Mono', Consolas, monospace;
font-size: 20px;
font-weight: 800;
color: #2563eb;
letter-spacing: 1px;
color: #ff6a00;
letter-spacing: 1.5px;
}
.link-text {
font-family: monospace;
font-family: -apple-system, BlinkMacSystemFont, monospace;
font-size: 13px;
color: #334155;
white-space: nowrap;
@@ -723,8 +768,9 @@ function cycleLabel(cycle: string) {
border: 1px solid #cbd5e1;
color: #475569;
border-radius: 6px;
padding: 5px 10px;
padding: 6px 12px;
font-size: 12px;
font-weight: 500;
cursor: pointer;
display: inline-flex;
align-items: center;
@@ -733,39 +779,60 @@ function cycleLabel(cycle: string) {
transition: all 0.2s;
}
.copy-btn.primary {
background: #2563eb;
border-color: #2563eb;
color: #ffffff;
.copy-btn:hover {
border-color: #ff6a00;
color: #ff6a00;
}
.copy-btn:hover {
opacity: 0.9;
.copy-btn.primary {
background: linear-gradient(135deg, #ff6a00 0%, #ff852e 100%);
border: none;
color: #ffffff;
font-weight: 600;
box-shadow: 0 3px 10px rgba(255, 106, 0, 0.28);
}
.copy-btn.primary:hover {
box-shadow: 0 5px 16px rgba(255, 106, 0, 0.4);
transform: translateY(-1px);
}
.rules-card {
background: #ffffff;
border-radius: 14px;
padding: 22px;
border-radius: 16px;
padding: 24px;
margin-top: 20px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.04);
box-shadow: 0 2px 12px rgba(15, 23, 42, 0.04);
border: 1px solid #f1f5f9;
}
.rules-header {
display: flex;
justify-content: space-between;
align-items: baseline;
align-items: center;
flex-wrap: wrap;
gap: 8px;
margin-bottom: 16px;
margin-bottom: 18px;
}
.rules-header-title {
display: flex;
align-items: center;
gap: 8px;
}
.rules-title-bar {
width: 4px;
height: 16px;
border-radius: 2px;
background: linear-gradient(180deg, #ff6a00, #ff852e);
}
.rules-header h3 {
margin: 0;
font-size: 16px;
font-weight: 700;
color: #1e293b;
color: #0f172a;
}
.rule-tip {
@@ -776,47 +843,73 @@ function cycleLabel(cycle: string) {
.ladder-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
gap: 14px;
margin-bottom: 18px;
gap: 16px;
margin-bottom: 20px;
}
.ladder-item {
border-radius: 10px;
padding: 16px;
border-radius: 12px;
padding: 18px 16px;
text-align: center;
border: 1px solid transparent;
transition: all 0.25s ease;
position: relative;
overflow: hidden;
}
.ladder-item:hover {
transform: translateY(-2px);
box-shadow: 0 6px 18px rgba(0, 0, 0, 0.06);
}
.ladder-first {
background: #fef2f2;
border-color: #fecaca;
background: linear-gradient(180deg, #fff7ed 0%, #ffffff 100%);
border: 1.5px solid #fed7aa;
}
.ladder-second {
background: #fffbeb;
border-color: #fde68a;
background: linear-gradient(180deg, #fefce8 0%, #ffffff 100%);
border: 1px solid #fde68a;
}
.ladder-subsequent {
background: #eff6ff;
border-color: #bfdbfe;
background: linear-gradient(180deg, #f0fdf4 0%, #ffffff 100%);
border: 1px solid #bbf7d0;
}
.ladder-tag {
font-size: 12px;
font-weight: 600;
font-weight: 700;
color: #475569;
}
.ladder-first .ladder-tag {
color: #ea580c;
}
.ladder-second .ladder-tag {
color: #d97706;
}
.ladder-subsequent .ladder-tag {
color: #16a34a;
}
.ladder-rate {
font-size: 32px;
font-size: 34px;
font-weight: 900;
line-height: 1.2;
margin: 6px 0;
margin: 8px 0;
font-family:
'DIN Alternate',
-apple-system,
BlinkMacSystemFont,
'Segoe UI',
Roboto,
sans-serif;
}
.ladder-first .ladder-rate {
color: #dc2626;
color: #ea580c;
}
.ladder-second .ladder-rate {
@@ -824,7 +917,7 @@ function cycleLabel(cycle: string) {
}
.ladder-subsequent .ladder-rate {
color: #2563eb;
color: #16a34a;
}
.ladder-time {
@@ -841,38 +934,39 @@ function cycleLabel(cycle: string) {
.rules-details {
background: #f8fafc;
border-radius: 8px;
padding: 14px 16px;
border-radius: 10px;
padding: 16px 18px;
display: flex;
flex-direction: column;
gap: 8px;
gap: 10px;
border-left: 3px solid #fdba74;
}
.rule-point {
font-size: 13px;
color: #475569;
line-height: 1.5;
line-height: 1.6;
}
.rule-point strong {
color: #1e293b;
color: #0f172a;
}
.details-tabs-card {
background: #ffffff;
border-radius: 14px;
padding: 22px;
border-radius: 16px;
padding: 24px;
margin-top: 20px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.04);
box-shadow: 0 2px 12px rgba(15, 23, 42, 0.04);
border: 1px solid #f1f5f9;
}
.tabs-header {
display: flex;
gap: 16px;
gap: 20px;
border-bottom: 2px solid #f1f5f9;
padding-bottom: 12px;
margin-bottom: 16px;
margin-bottom: 18px;
}
.tab-btn {
@@ -882,13 +976,18 @@ function cycleLabel(cycle: string) {
font-weight: 600;
color: #64748b;
cursor: pointer;
padding: 6px 8px;
padding: 6px 4px;
position: relative;
transition: color 0.2s;
transition: all 0.2s;
}
.tab-btn:hover {
color: #ff6a00;
}
.tab-btn.active {
color: #2563eb;
color: #ff6a00;
font-weight: 700;
}
.tab-btn.active::after {
@@ -897,9 +996,9 @@ function cycleLabel(cycle: string) {
bottom: -14px;
left: 0;
right: 0;
height: 2px;
background: #2563eb;
border-radius: 2px;
height: 3px;
background: linear-gradient(90deg, #ff6a00, #ff852e);
border-radius: 3px;
}
.table-responsive {
@@ -917,50 +1016,59 @@ function cycleLabel(cycle: string) {
background: #f8fafc;
color: #64748b;
font-weight: 600;
padding: 10px 14px;
padding: 12px 14px;
border-bottom: 1px solid #e2e8f0;
}
.data-table td {
padding: 12px 14px;
padding: 14px;
border-bottom: 1px solid #f1f5f9;
color: #1e293b;
transition: background 0.15s;
}
.data-table tbody tr:hover td {
background: #fffaf5;
}
.status-pill {
display: inline-block;
padding: 2px 8px;
border-radius: 4px;
padding: 3px 10px;
border-radius: 6px;
font-size: 12px;
font-weight: 500;
font-weight: 600;
}
.status-pill.active {
background: #f0fdf4;
color: #16a34a;
border: 1px solid #bbf7d0;
}
.status-pill.pending {
background: #fffbeb;
color: #d97706;
border: 1px solid #fde68a;
}
.role-pill {
display: inline-block;
padding: 2px 8px;
border-radius: 4px;
padding: 3px 10px;
border-radius: 6px;
font-size: 12px;
font-weight: 600;
}
.role-pill.buyer {
background: #eff6ff;
color: #2563eb;
background: #fff7ed;
color: #ea580c;
border: 1px solid #fed7aa;
}
.role-pill.seller {
background: #fdf2f8;
color: #db2777;
border: 1px solid #fbcfe8;
}
.cycle-pill {
@@ -969,89 +1077,130 @@ function cycleLabel(cycle: string) {
}
.rebate-amount {
font-weight: 700;
color: #dc2626;
font-weight: 800;
color: #ea580c;
font-size: 14px;
}
.loading-state,
.empty-state {
text-align: center;
padding: 40px 16px;
padding: 48px 16px;
color: #64748b;
font-size: 14px;
}
.empty-state p {
margin-top: 12px;
}
.pagination-bar {
margin-top: 16px;
margin-top: 20px;
display: flex;
justify-content: flex-end;
}
:deep(.el-pagination.is-background .el-pager li.is-active) {
background-color: #ff6a00 !important;
color: #ffffff !important;
}
:deep(.el-pagination.is-background .el-pager li:not(.is-active):hover) {
color: #ff6a00 !important;
}
.poster-modal-body {
text-align: center;
}
.poster-card {
background: linear-gradient(135deg, #1e3a8a 0%, #2563eb 100%);
position: relative;
background:
radial-gradient(circle at 85% 15%, rgba(255, 106, 0, 0.28) 0%, transparent 60%),
radial-gradient(circle at 15% 85%, rgba(255, 133, 46, 0.18) 0%, transparent 55%),
linear-gradient(150deg, #111827 0%, #1a2234 50%, #252f44 100%);
color: #ffffff;
border-radius: 12px;
padding: 20px 16px;
border: 1px solid rgba(255, 106, 0, 0.3);
border-radius: 16px;
padding: 24px 20px;
box-shadow: 0 16px 36px rgba(15, 23, 42, 0.25);
}
.poster-badge {
display: inline-block;
background: rgba(255, 255, 255, 0.2);
padding: 2px 10px;
background: linear-gradient(135deg, #ff6a00 0%, #ff852e 100%);
color: #ffffff;
padding: 3px 12px;
border-radius: 12px;
font-size: 11px;
margin-bottom: 6px;
font-weight: 700;
margin-bottom: 10px;
box-shadow: 0 2px 8px rgba(255, 106, 0, 0.35);
}
.poster-card h3 {
margin: 0;
font-size: 18px;
font-size: 20px;
font-weight: 800;
letter-spacing: 0.5px;
}
.poster-desc {
font-size: 12px;
opacity: 0.85;
margin: 6px 0 16px;
color: #cbd5e1;
margin: 8px 0 18px;
}
.poster-qr-wrap {
width: 180px;
height: 180px;
background: #ffffff;
padding: 8px;
border-radius: 8px;
padding: 10px;
border-radius: 12px;
margin: 0 auto;
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}
.poster-qr-wrap img {
width: 100%;
height: 100%;
display: block;
}
.poster-code-row {
margin-top: 14px;
margin-top: 16px;
font-size: 13px;
color: #e2e8f0;
}
.poster-code-row strong {
color: #fde047;
font-size: 16px;
letter-spacing: 1px;
color: #ff9b4e;
font-size: 18px;
font-weight: 900;
letter-spacing: 1.5px;
}
.poster-tip {
font-size: 12px;
color: #94a3b8;
margin-top: 12px;
margin-top: 14px;
}
@media (max-width: 768px) {
.hero-card {
padding: 24px 18px;
}
.hero-title {
font-size: 22px;
}
.share-content-row {
grid-template-columns: 1fr;
}
.ladder-grid {
grid-template-columns: 1fr;
}
}
</style>
+1
View File
@@ -5,6 +5,7 @@ export const accountRoutes: RouteRecordRaw[] = [
path: '/login',
name: 'login',
component: () => import('@/features/auth/views/LoginView.vue'),
meta: { layout: 'blank' },
},
{
path: '/orders/create',
+10
View File
@@ -43,6 +43,16 @@ export const mobileRoutes: RouteRecordRaw[] = [
component: () => import('@/features/auth/views/MobileRegisterView.vue'),
meta: { layout: 'blank' },
},
{
path: '/m/i/:code',
name: 'mobile-invite-register',
redirect: to => ({
path: '/m/register',
query: {
invite_code: String(to.params.code || ''),
},
}),
},
{
path: '/m/messages',
name: 'mobile-messages',
+8 -3
View File
@@ -39,12 +39,17 @@ export const publicRoutes: RouteRecordRaw[] = [
name: 'crash-detail',
component: () => import('@/features/mohong/views/MohongDetailView.vue'),
},
// 专属邀请注册落地页
// 专属邀请短链重定向
{
path: '/i/:code',
name: 'invite-register',
component: () => import('@/features/invitation/views/InviteRegisterView.vue'),
meta: { layout: 'blank' },
redirect: to => ({
path: '/login',
query: {
tab: 'register',
invite_code: String(to.params.code || ''),
},
}),
},
// 旧路径兼容
{ path: '/mohong', redirect: '/crash' },