feat(tenant): 隔离邀请返利与推广追踪数据
This commit is contained in:
@@ -22,7 +22,8 @@ func (UserInvitation) TableName() string {
|
||||
// InvitationRebateConfig 邀请返利比例配置表(主站或分销站点)
|
||||
type InvitationRebateConfig struct {
|
||||
ID uint64 `gorm:"primaryKey" json:"id"`
|
||||
DistributionSiteID uint64 `gorm:"not null;uniqueIndex:uk_invitation_rebate_configs_site" json:"distribution_site_id"` // 0=主站
|
||||
TenantID uint64 `gorm:"not null;default:0;uniqueIndex:uk_invitation_rebate_configs_tenant_site,priority:1" json:"tenant_id"`
|
||||
DistributionSiteID uint64 `gorm:"not null;uniqueIndex:uk_invitation_rebate_configs_tenant_site,priority:2" json:"distribution_site_id"` // 0=主站
|
||||
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"`
|
||||
|
||||
@@ -27,7 +27,7 @@ func NewHandler(service *Service) *Handler {
|
||||
func (h *Handler) Redirect(c *gin.Context) {
|
||||
code := strings.TrimSpace(c.Param("code"))
|
||||
if !codePattern.MatchString(code) {
|
||||
c.Redirect(http.StatusFound, "https://hao858.com/")
|
||||
c.Redirect(http.StatusFound, getRequestBaseURL(c)+"/")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -46,7 +46,7 @@ func (h *Handler) Redirect(c *gin.Context) {
|
||||
targetURL, err := h.service.ResolveRedirect(c.Request.Context(), code, ip, ua, referer, visitorID)
|
||||
if err != nil {
|
||||
// 链接不存在或已停用时,优雅兜底跳转至官网首页,附带失效短码参数以备提示
|
||||
c.Redirect(http.StatusFound, "https://hao858.com/?ref_invalid="+url.QueryEscape(code))
|
||||
c.Redirect(http.StatusFound, getRequestBaseURL(c)+"/?ref_invalid="+url.QueryEscape(code))
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -6,8 +6,9 @@ import (
|
||||
|
||||
type AdTrackingLink struct {
|
||||
ID uint64 `gorm:"primaryKey" json:"id"`
|
||||
TenantID uint64 `gorm:"not null;default:0;uniqueIndex:uk_ad_tracking_links_tenant_code,priority:1;index:idx_ad_tracking_links_tenant_status" json:"tenant_id"`
|
||||
Name string `gorm:"size:128;not null" json:"name"`
|
||||
Code string `gorm:"size:64;not null;uniqueIndex:uk_ad_tracking_links_code" json:"code"`
|
||||
Code string `gorm:"size:64;not null;uniqueIndex:uk_ad_tracking_links_tenant_code,priority:2" json:"code"`
|
||||
ChannelType string `gorm:"size:64;not null;default:'other';index:idx_ad_tracking_links_channel" json:"channel_type"`
|
||||
TargetURL string `gorm:"size:512;not null;default:'https://hao858.com/'" json:"target_url"`
|
||||
Status string `gorm:"size:16;not null;default:'active';index:idx_ad_tracking_links_status" json:"status"`
|
||||
@@ -24,6 +25,7 @@ func (AdTrackingLink) TableName() string {
|
||||
|
||||
type AdTrackingClick struct {
|
||||
ID uint64 `gorm:"primaryKey" json:"id"`
|
||||
TenantID uint64 `gorm:"not null;default:0;index:idx_ad_tracking_clicks_tenant_created" json:"tenant_id"`
|
||||
LinkID uint64 `gorm:"not null;index:idx_ad_tracking_clicks_link_created,priority:1" json:"link_id"`
|
||||
Code string `gorm:"size:64;not null;index:idx_ad_tracking_clicks_code_created,priority:1" json:"code"`
|
||||
IP string `gorm:"size:64;not null;default:'';index:idx_ad_tracking_clicks_ip_created,priority:1" json:"ip"`
|
||||
|
||||
@@ -5,6 +5,8 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
@@ -21,12 +23,16 @@ func (r *Repository) CreateLink(ctx context.Context, link *AdTrackingLink) error
|
||||
}
|
||||
|
||||
func (r *Repository) UpdateLink(ctx context.Context, id uint64, updates map[string]interface{}) error {
|
||||
return r.db.WithContext(ctx).Model(&AdTrackingLink{}).Where("id = ?", id).Updates(updates).Error
|
||||
return r.db.WithContext(ctx).Model(&AdTrackingLink{}).
|
||||
Where("id = ? AND tenant_id = ?", id, adTrackingTenantID(ctx)).
|
||||
Updates(updates).Error
|
||||
}
|
||||
|
||||
func (r *Repository) FindLinkByID(ctx context.Context, id uint64) (*AdTrackingLink, error) {
|
||||
var link AdTrackingLink
|
||||
if err := r.db.WithContext(ctx).Where("id = ?", id).First(&link).Error; err != nil {
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("id = ? AND tenant_id = ?", id, adTrackingTenantID(ctx)).
|
||||
First(&link).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &link, nil
|
||||
@@ -34,7 +40,9 @@ func (r *Repository) FindLinkByID(ctx context.Context, id uint64) (*AdTrackingLi
|
||||
|
||||
func (r *Repository) FindLinkByCode(ctx context.Context, code string) (*AdTrackingLink, error) {
|
||||
var link AdTrackingLink
|
||||
if err := r.db.WithContext(ctx).Where("code = ?", code).First(&link).Error; err != nil {
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("code = ? AND tenant_id = ?", code, adTrackingTenantID(ctx)).
|
||||
First(&link).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &link, nil
|
||||
@@ -45,7 +53,8 @@ func (r *Repository) RecordClick(ctx context.Context, click *AdTrackingClick) er
|
||||
}
|
||||
|
||||
func (r *Repository) ListLinks(ctx context.Context, query ListTrackingLinksQuery, baseURL string) ([]TrackingLinkItem, int64, error) {
|
||||
tx := r.db.WithContext(ctx).Model(&AdTrackingLink{})
|
||||
tenantID := adTrackingTenantID(ctx)
|
||||
tx := r.db.WithContext(ctx).Model(&AdTrackingLink{}).Where("tenant_id = ?", tenantID)
|
||||
|
||||
if kw := strings.TrimSpace(query.Keyword); kw != "" {
|
||||
like := "%" + kw + "%"
|
||||
@@ -100,7 +109,7 @@ func (r *Repository) ListLinks(ctx context.Context, query ListTrackingLinksQuery
|
||||
_ = r.db.WithContext(ctx).
|
||||
Table("ad_tracking_clicks").
|
||||
Select("link_id, COUNT(*) as pv, COUNT(DISTINCT visitor_id) as uv, COUNT(DISTINCT ip) as ips").
|
||||
Where("link_id IN (?)", linkIDs).
|
||||
Where("tenant_id = ? AND link_id IN (?)", tenantID, linkIDs).
|
||||
Group("link_id").
|
||||
Scan(&clickStats).Error
|
||||
|
||||
@@ -118,7 +127,7 @@ func (r *Repository) ListLinks(ctx context.Context, query ListTrackingLinksQuery
|
||||
_ = r.db.WithContext(ctx).
|
||||
Table("users").
|
||||
Select("register_track_code, COUNT(*) as reg_count").
|
||||
Where("register_track_code IN (?)", codes).
|
||||
Where("tenant_id = ? AND register_track_code IN (?)", tenantID, codes).
|
||||
Group("register_track_code").
|
||||
Scan(&userStats).Error
|
||||
|
||||
@@ -138,7 +147,7 @@ func (r *Repository) ListLinks(ctx context.Context, query ListTrackingLinksQuery
|
||||
_ = r.db.WithContext(ctx).
|
||||
Table("rental_orders").
|
||||
Select("source_track_code, COUNT(*) as order_count, SUM(CASE WHEN status NOT IN ('pending_payment', 'cancelled', 'closed') THEN 1 ELSE 0 END) as paid_order_count, COALESCE(SUM(CASE WHEN status NOT IN ('pending_payment', 'cancelled', 'closed') THEN rent_amount_cent ELSE 0 END), 0) as paid_gmv_cent").
|
||||
Where("source_track_code IN (?)", codes).
|
||||
Where("buyer_tenant_id = ? AND source_track_code IN (?)", tenantID, codes).
|
||||
Group("source_track_code").
|
||||
Scan(&orderStats).Error
|
||||
|
||||
@@ -191,10 +200,15 @@ func (r *Repository) ListLinks(ctx context.Context, query ListTrackingLinksQuery
|
||||
|
||||
func (r *Repository) GetOverviewStats(ctx context.Context) (*TrackingOverviewStats, error) {
|
||||
stats := &TrackingOverviewStats{}
|
||||
tenantID := adTrackingTenantID(ctx)
|
||||
|
||||
// 链接总数与启用数
|
||||
_ = r.db.WithContext(ctx).Model(&AdTrackingLink{}).Count(&stats.TotalLinks).Error
|
||||
_ = r.db.WithContext(ctx).Model(&AdTrackingLink{}).Where("status = 'active'").Count(&stats.ActiveLinks).Error
|
||||
_ = r.db.WithContext(ctx).Model(&AdTrackingLink{}).
|
||||
Where("tenant_id = ?", tenantID).
|
||||
Count(&stats.TotalLinks).Error
|
||||
_ = r.db.WithContext(ctx).Model(&AdTrackingLink{}).
|
||||
Where("tenant_id = ? AND status = 'active'", tenantID).
|
||||
Count(&stats.ActiveLinks).Error
|
||||
|
||||
// 累计点击
|
||||
type clickTotal struct {
|
||||
@@ -206,6 +220,7 @@ func (r *Repository) GetOverviewStats(ctx context.Context) (*TrackingOverviewSta
|
||||
_ = r.db.WithContext(ctx).
|
||||
Table("ad_tracking_clicks").
|
||||
Select("COUNT(*) as pv, COUNT(DISTINCT visitor_id) as uv, COUNT(DISTINCT ip) as ips").
|
||||
Where("tenant_id = ?", tenantID).
|
||||
Scan(&ct).Error
|
||||
stats.TotalPV = ct.PV
|
||||
stats.TotalUV = ct.UV
|
||||
@@ -214,7 +229,7 @@ func (r *Repository) GetOverviewStats(ctx context.Context) (*TrackingOverviewSta
|
||||
// 累计注册
|
||||
_ = r.db.WithContext(ctx).
|
||||
Table("users").
|
||||
Where("register_track_code IS NOT NULL AND register_track_code != ''").
|
||||
Where("tenant_id = ? AND register_track_code IS NOT NULL AND register_track_code != ''", tenantID).
|
||||
Count(&stats.TotalRegisters).Error
|
||||
|
||||
// 累计订单与GMV
|
||||
@@ -227,7 +242,7 @@ func (r *Repository) GetOverviewStats(ctx context.Context) (*TrackingOverviewSta
|
||||
_ = r.db.WithContext(ctx).
|
||||
Table("rental_orders").
|
||||
Select("COUNT(*) as total_orders, SUM(CASE WHEN status NOT IN ('pending_payment', 'cancelled', 'closed') THEN 1 ELSE 0 END) as total_paid_orders, COALESCE(SUM(CASE WHEN status NOT IN ('pending_payment', 'cancelled', 'closed') THEN rent_amount_cent ELSE 0 END), 0) as total_paid_gmv").
|
||||
Where("source_track_code IS NOT NULL AND source_track_code != ''").
|
||||
Where("buyer_tenant_id = ? AND source_track_code IS NOT NULL AND source_track_code != ''", tenantID).
|
||||
Scan(&ot).Error
|
||||
stats.TotalOrders = ot.TotalOrders
|
||||
stats.TotalPaidOrders = ot.TotalPaidOrders
|
||||
@@ -242,7 +257,7 @@ func (r *Repository) GetOverviewStats(ctx context.Context) (*TrackingOverviewSta
|
||||
_ = r.db.WithContext(ctx).
|
||||
Table("ad_tracking_clicks").
|
||||
Select("COUNT(*) as pv, COUNT(DISTINCT visitor_id) as uv").
|
||||
Where("created_at >= ?", todayStart).
|
||||
Where("tenant_id = ? AND created_at >= ?", tenantID, todayStart).
|
||||
Scan(&todayCt).Error
|
||||
stats.TodayPV = todayCt.PV
|
||||
stats.TodayUV = todayCt.UV
|
||||
@@ -250,7 +265,7 @@ func (r *Repository) GetOverviewStats(ctx context.Context) (*TrackingOverviewSta
|
||||
// 今日注册
|
||||
_ = r.db.WithContext(ctx).
|
||||
Table("users").
|
||||
Where("register_track_code IS NOT NULL AND register_track_code != '' AND created_at >= ?", todayStart).
|
||||
Where("tenant_id = ? AND register_track_code IS NOT NULL AND register_track_code != '' AND created_at >= ?", tenantID, todayStart).
|
||||
Count(&stats.TodayRegisters).Error
|
||||
|
||||
// 今日订单
|
||||
@@ -258,10 +273,14 @@ func (r *Repository) GetOverviewStats(ctx context.Context) (*TrackingOverviewSta
|
||||
_ = r.db.WithContext(ctx).
|
||||
Table("rental_orders").
|
||||
Select("COUNT(*) as total_orders, COALESCE(SUM(CASE WHEN status NOT IN ('pending_payment', 'cancelled', 'closed') THEN rent_amount_cent ELSE 0 END), 0) as total_paid_gmv").
|
||||
Where("source_track_code IS NOT NULL AND source_track_code != '' AND created_at >= ?", todayStart).
|
||||
Where("buyer_tenant_id = ? AND source_track_code IS NOT NULL AND source_track_code != '' AND created_at >= ?", tenantID, todayStart).
|
||||
Scan(&todayOt).Error
|
||||
stats.TodayOrders = todayOt.TotalOrders
|
||||
stats.TodayPaidGMVCent = todayOt.TotalPaidGMV
|
||||
|
||||
return stats, nil
|
||||
}
|
||||
|
||||
func adTrackingTenantID(ctx context.Context) uint64 {
|
||||
return tenancy.IDFromContext(ctx)
|
||||
}
|
||||
|
||||
@@ -9,6 +9,8 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
@@ -29,12 +31,28 @@ var reservedCodes = map[string]bool{
|
||||
}
|
||||
|
||||
func validateTargetURL(rawURL string, allowLocal bool) (string, error) {
|
||||
return validateTargetURLWithHosts(rawURL, allowLocal, "hao858.com", "hao858.com")
|
||||
}
|
||||
|
||||
func validateTargetURLForTenant(ctx context.Context, rawURL string, allowLocal bool) (string, error) {
|
||||
defaultHost := "hao858.com"
|
||||
allowedHosts := []string{"hao858.com"}
|
||||
if scope, ok := tenancy.FromContext(ctx); ok {
|
||||
if host := strings.TrimSpace(strings.ToLower(scope.Host)); host != "" {
|
||||
defaultHost = host
|
||||
allowedHosts = append(allowedHosts, host)
|
||||
}
|
||||
}
|
||||
return validateTargetURLWithHosts(rawURL, allowLocal, defaultHost, allowedHosts...)
|
||||
}
|
||||
|
||||
func validateTargetURLWithHosts(rawURL string, allowLocal bool, defaultHost string, allowedHosts ...string) (string, error) {
|
||||
targetURL := strings.TrimSpace(rawURL)
|
||||
if targetURL == "" {
|
||||
return "https://hao858.com/", nil
|
||||
return "https://" + defaultHost + "/", nil
|
||||
}
|
||||
if strings.HasPrefix(targetURL, "/") {
|
||||
return "https://hao858.com" + targetURL, nil
|
||||
return "https://" + defaultHost + targetURL, nil
|
||||
}
|
||||
if !strings.HasPrefix(targetURL, "http://") && !strings.HasPrefix(targetURL, "https://") {
|
||||
targetURL = "https://" + targetURL
|
||||
@@ -54,7 +72,15 @@ func validateTargetURL(rawURL string, allowLocal bool) (string, error) {
|
||||
}
|
||||
return targetURL, nil
|
||||
}
|
||||
if host != "hao858.com" && !strings.HasSuffix(host, ".hao858.com") {
|
||||
allowed := false
|
||||
for _, candidate := range allowedHosts {
|
||||
candidate = strings.TrimSpace(strings.ToLower(candidate))
|
||||
if candidate != "" && (host == candidate || strings.HasSuffix(host, "."+candidate)) {
|
||||
allowed = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !allowed {
|
||||
return "", ErrDisallowedTargetDomain
|
||||
}
|
||||
return targetURL, nil
|
||||
@@ -89,7 +115,7 @@ func (s *Service) CreateLink(ctx context.Context, adminID uint64, req CreateTrac
|
||||
return nil, ErrCodeAlreadyExists
|
||||
}
|
||||
|
||||
targetURL, err := validateTargetURL(req.TargetURL, s.allowLocalTargets)
|
||||
targetURL, err := validateTargetURLForTenant(ctx, req.TargetURL, s.allowLocalTargets)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -100,6 +126,7 @@ func (s *Service) CreateLink(ctx context.Context, adminID uint64, req CreateTrac
|
||||
}
|
||||
|
||||
link := &AdTrackingLink{
|
||||
TenantID: tenancy.IDFromContext(ctx),
|
||||
Name: strings.TrimSpace(req.Name),
|
||||
Code: code,
|
||||
ChannelType: channelType,
|
||||
@@ -125,7 +152,7 @@ func (s *Service) UpdateLink(ctx context.Context, id uint64, req UpdateTrackingL
|
||||
return ErrLinkNotFound
|
||||
}
|
||||
|
||||
targetURL, err := validateTargetURL(req.TargetURL, s.allowLocalTargets)
|
||||
targetURL, err := validateTargetURLForTenant(ctx, req.TargetURL, s.allowLocalTargets)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -202,6 +229,7 @@ func (s *Service) ResolveRedirect(ctx context.Context, code, ip, ua, referer, vi
|
||||
}
|
||||
|
||||
click := &AdTrackingClick{
|
||||
TenantID: link.TenantID,
|
||||
LinkID: link.ID,
|
||||
Code: link.Code,
|
||||
IP: ip,
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
package adtracking
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
)
|
||||
|
||||
func TestAppendTrackCode(t *testing.T) {
|
||||
@@ -129,3 +132,21 @@ func TestValidateTargetURL(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateTargetURLAllowsCurrentTenantDomain(t *testing.T) {
|
||||
ctx := tenancy.WithScope(context.Background(), tenancy.Scope{
|
||||
TenantID: 2,
|
||||
TenantCode: "jieyou",
|
||||
Host: "zuhaox.com",
|
||||
})
|
||||
got, err := validateTargetURLForTenant(ctx, "https://h5.zuhaox.com/listings", false)
|
||||
if err != nil {
|
||||
t.Fatalf("tenant domain should be allowed: %v", err)
|
||||
}
|
||||
if got != "https://h5.zuhaox.com/listings" {
|
||||
t.Fatalf("target URL = %q", got)
|
||||
}
|
||||
if _, err := validateTargetURLForTenant(ctx, "https://evil.example.com", false); err == nil {
|
||||
t.Fatal("external tenant URL should be rejected")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
package adtracking
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
)
|
||||
|
||||
func TestTrackingLinksAndClicksAreScopedByTenant(t *testing.T) {
|
||||
db := database.NewTestDB()
|
||||
if err := database.AutoMigrateIfMissing(db, &AdTrackingLink{}, &AdTrackingClick{}); err != nil {
|
||||
t.Fatalf("migrate ad tracking tables: %v", err)
|
||||
}
|
||||
repo := NewRepository(db)
|
||||
ctxA := tenancy.WithScope(context.Background(), tenancy.Scope{TenantID: 101, TenantCode: "tenant_a"})
|
||||
ctxB := tenancy.WithScope(context.Background(), tenancy.Scope{TenantID: 202, TenantCode: "tenant_b"})
|
||||
|
||||
links := []*AdTrackingLink{
|
||||
{TenantID: 101, Name: "A站推广", Code: "same_code", Status: "active", TargetURL: "https://hao858.com/", CreatedAt: time.Now()},
|
||||
{TenantID: 202, Name: "B站推广", Code: "same_code", Status: "active", TargetURL: "https://hao858.com/", CreatedAt: time.Now()},
|
||||
}
|
||||
for _, link := range links {
|
||||
if err := repo.CreateLink(context.Background(), link); err != nil {
|
||||
t.Fatalf("create tracking link: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
itemsA, totalA, err := repo.ListLinks(ctxA, ListTrackingLinksQuery{Page: 1, PageSize: 20}, "https://a.example.com")
|
||||
if err != nil {
|
||||
t.Fatalf("list tenant A links: %v", err)
|
||||
}
|
||||
if totalA != 1 || len(itemsA) != 1 || itemsA[0].Name != "A站推广" {
|
||||
t.Fatalf("tenant A links = %+v, total=%d", itemsA, totalA)
|
||||
}
|
||||
linkA, err := repo.FindLinkByCode(ctxA, "same_code")
|
||||
if err != nil || linkA.TenantID != 101 {
|
||||
t.Fatalf("tenant A code lookup = %+v, err=%v", linkA, err)
|
||||
}
|
||||
linkB, err := repo.FindLinkByCode(ctxB, "same_code")
|
||||
if err != nil || linkB.TenantID != 202 {
|
||||
t.Fatalf("tenant B code lookup = %+v, err=%v", linkB, err)
|
||||
}
|
||||
|
||||
if err := repo.RecordClick(ctxA, &AdTrackingClick{
|
||||
TenantID: 101,
|
||||
LinkID: linkA.ID,
|
||||
Code: linkA.Code,
|
||||
VisitorID: "visitor-a",
|
||||
CreatedAt: time.Now(),
|
||||
}); err != nil {
|
||||
t.Fatalf("record tenant A click: %v", err)
|
||||
}
|
||||
overviewA, err := repo.GetOverviewStats(ctxA)
|
||||
if err != nil {
|
||||
t.Fatalf("tenant A overview: %v", err)
|
||||
}
|
||||
overviewB, err := repo.GetOverviewStats(ctxB)
|
||||
if err != nil {
|
||||
t.Fatalf("tenant B overview: %v", err)
|
||||
}
|
||||
if overviewA.TotalLinks != 1 || overviewA.TotalPV != 1 {
|
||||
t.Fatalf("tenant A overview = %+v", overviewA)
|
||||
}
|
||||
if overviewB.TotalLinks != 1 || overviewB.TotalPV != 0 {
|
||||
t.Fatalf("tenant B overview = %+v", overviewB)
|
||||
}
|
||||
}
|
||||
@@ -287,21 +287,27 @@ func (r *Repository) GetRebateConfig(ctx context.Context, siteID uint64) (*model
|
||||
if r == nil || r.db == nil {
|
||||
return nil, ErrDependencyUnavailable
|
||||
}
|
||||
tenantID := tenancy.IDFromContext(ctx)
|
||||
var cfg model.InvitationRebateConfig
|
||||
if siteID > 0 {
|
||||
err := r.db.WithContext(ctx).Where("distribution_site_id = ?", siteID).First(&cfg).Error
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("tenant_id = ? AND distribution_site_id = ?", tenantID, siteID).
|
||||
First(&cfg).Error
|
||||
if err == nil {
|
||||
return &cfg, nil
|
||||
}
|
||||
}
|
||||
// 回退主站配置 (distribution_site_id = 0)
|
||||
err := r.db.WithContext(ctx).Where("distribution_site_id = 0").First(&cfg).Error
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("tenant_id = ? AND distribution_site_id = 0", tenantID).
|
||||
First(&cfg).Error
|
||||
if err == nil {
|
||||
return &cfg, nil
|
||||
}
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
// 返回默认硬编码
|
||||
return &model.InvitationRebateConfig{
|
||||
TenantID: tenantID,
|
||||
DistributionSiteID: 0,
|
||||
FirstMonthRate: DefaultFirstMonthRate,
|
||||
SecondMonthRate: DefaultSecondMonthRate,
|
||||
@@ -317,13 +323,17 @@ func (r *Repository) UpdateRebateConfig(ctx context.Context, siteID uint64, req
|
||||
if r == nil || r.db == nil {
|
||||
return nil, ErrDependencyUnavailable
|
||||
}
|
||||
tenantID := tenancy.IDFromContext(ctx)
|
||||
var cfg model.InvitationRebateConfig
|
||||
err := r.db.WithContext(ctx).Where("distribution_site_id = ?", siteID).First(&cfg).Error
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("tenant_id = ? AND distribution_site_id = ?", tenantID, siteID).
|
||||
First(&cfg).Error
|
||||
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, err
|
||||
}
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
cfg = model.InvitationRebateConfig{
|
||||
TenantID: tenantID,
|
||||
DistributionSiteID: siteID,
|
||||
FirstMonthRate: req.FirstMonthRate,
|
||||
SecondMonthRate: req.SecondMonthRate,
|
||||
@@ -333,7 +343,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).Select("DistributionSiteID", "FirstMonthRate", "SecondMonthRate", "SubsequentRate", "Enabled").Create(&cfg).Error; err != nil {
|
||||
if err := r.db.WithContext(ctx).Select("TenantID", "DistributionSiteID", "FirstMonthRate", "SecondMonthRate", "SubsequentRate", "Enabled").Create(&cfg).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &cfg, nil
|
||||
@@ -619,7 +629,7 @@ func AwardSellerSideRebateTx(tx *gorm.DB, in SellerSideRebateInput) (int64, erro
|
||||
if tx == nil || in.SellerID == 0 || in.SourceID == 0 || in.BasisCent <= 0 {
|
||||
return 0, nil
|
||||
}
|
||||
ctx := context.Background()
|
||||
ctx := invitationTenantContextForUser(tx, in.SellerID)
|
||||
|
||||
var invitation model.UserInvitation
|
||||
if err := tx.WithContext(ctx).
|
||||
@@ -1334,7 +1344,7 @@ func ProcessOrderInvitationRebateWithOptionsTx(tx *gorm.DB, orderID uint64, opts
|
||||
return nil
|
||||
}
|
||||
repo := NewRepository(tx)
|
||||
return repo.processOrderInvitationRebate(context.Background(), tx, orderID, opts)
|
||||
return repo.processOrderInvitationRebate(invitationTenantContextForOrder(tx, orderID), tx, orderID, opts)
|
||||
}
|
||||
|
||||
// OnUserRealnameVerifiedTx 便捷事务入口,供实名认证通过时调用
|
||||
@@ -1343,5 +1353,25 @@ func OnUserRealnameVerifiedTx(tx *gorm.DB, userID uint64) error {
|
||||
return nil
|
||||
}
|
||||
repo := NewRepository(tx)
|
||||
return repo.OnUserRealnameVerified(context.Background(), userID)
|
||||
return repo.OnUserRealnameVerified(invitationTenantContextForUser(tx, userID), userID)
|
||||
}
|
||||
|
||||
func invitationTenantContextForOrder(tx *gorm.DB, orderID uint64) context.Context {
|
||||
ctx := context.Background()
|
||||
var tenantID uint64
|
||||
_ = tx.Table("rental_orders").Select("buyer_tenant_id").Where("id = ?", orderID).Scan(&tenantID).Error
|
||||
if tenantID > 0 {
|
||||
ctx = tenancy.WithScope(ctx, tenancy.Scope{TenantID: tenantID})
|
||||
}
|
||||
return ctx
|
||||
}
|
||||
|
||||
func invitationTenantContextForUser(tx *gorm.DB, userID uint64) context.Context {
|
||||
ctx := context.Background()
|
||||
var tenantID uint64
|
||||
_ = tx.Model(&model.User{}).Select("tenant_id").Where("id = ?", userID).Scan(&tenantID).Error
|
||||
if tenantID > 0 {
|
||||
ctx = tenancy.WithScope(ctx, tenancy.Scope{TenantID: tenantID})
|
||||
}
|
||||
return ctx
|
||||
}
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
package invitation
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/model"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
)
|
||||
|
||||
func TestRebateConfigIsScopedByTenant(t *testing.T) {
|
||||
db := database.NewTestDB()
|
||||
if err := database.AutoMigrateIfMissing(db, &model.InvitationRebateConfig{}); err != nil {
|
||||
t.Fatalf("migrate rebate config: %v", err)
|
||||
}
|
||||
repo := NewRepository(db)
|
||||
ctxA := tenancy.WithScope(context.Background(), tenancy.Scope{TenantID: 101, TenantCode: "tenant_a"})
|
||||
ctxB := tenancy.WithScope(context.Background(), tenancy.Scope{TenantID: 202, TenantCode: "tenant_b"})
|
||||
enabled := true
|
||||
|
||||
if _, err := repo.UpdateRebateConfig(ctxA, 0, UpdateConfigRequest{
|
||||
FirstMonthRate: 0.50,
|
||||
SecondMonthRate: 0.25,
|
||||
SubsequentRate: 0.10,
|
||||
Enabled: &enabled,
|
||||
}); err != nil {
|
||||
t.Fatalf("update tenant A config: %v", err)
|
||||
}
|
||||
if _, err := repo.UpdateRebateConfig(ctxB, 0, UpdateConfigRequest{
|
||||
FirstMonthRate: 0.70,
|
||||
SecondMonthRate: 0.35,
|
||||
SubsequentRate: 0.20,
|
||||
Enabled: &enabled,
|
||||
}); err != nil {
|
||||
t.Fatalf("update tenant B config: %v", err)
|
||||
}
|
||||
|
||||
cfgA, err := repo.GetRebateConfig(ctxA, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("get tenant A config: %v", err)
|
||||
}
|
||||
cfgB, err := repo.GetRebateConfig(ctxB, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("get tenant B config: %v", err)
|
||||
}
|
||||
if cfgA.TenantID != 101 || cfgA.FirstMonthRate != 0.50 {
|
||||
t.Fatalf("tenant A config = %+v", cfgA)
|
||||
}
|
||||
if cfgB.TenantID != 202 || cfgB.FirstMonthRate != 0.70 {
|
||||
t.Fatalf("tenant B config = %+v", cfgB)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
-- +goose Up
|
||||
|
||||
-- 邀请返利配置、推广链接与点击按经营租户隔离。
|
||||
-- distribution_site_id > 0 的历史分销配置保持平台级 tenant_id=0。
|
||||
|
||||
ALTER TABLE invitation_rebate_configs
|
||||
ADD COLUMN tenant_id BIGINT UNSIGNED NOT NULL DEFAULT 0 AFTER id,
|
||||
DROP KEY uk_invitation_rebate_configs_site,
|
||||
ADD UNIQUE KEY uk_invitation_rebate_configs_tenant_site (tenant_id, distribution_site_id),
|
||||
ADD KEY idx_invitation_rebate_configs_tenant (tenant_id);
|
||||
|
||||
UPDATE invitation_rebate_configs
|
||||
SET tenant_id = 0
|
||||
WHERE distribution_site_id > 0;
|
||||
|
||||
UPDATE invitation_rebate_configs
|
||||
SET tenant_id = (SELECT id FROM tenants WHERE code = 'dachui' LIMIT 1)
|
||||
WHERE distribution_site_id = 0;
|
||||
|
||||
INSERT INTO invitation_rebate_configs (
|
||||
tenant_id,
|
||||
distribution_site_id,
|
||||
first_month_rate,
|
||||
second_month_rate,
|
||||
subsequent_rate,
|
||||
enabled,
|
||||
created_at,
|
||||
updated_at
|
||||
)
|
||||
SELECT
|
||||
t.id,
|
||||
0,
|
||||
src.first_month_rate,
|
||||
src.second_month_rate,
|
||||
src.subsequent_rate,
|
||||
src.enabled,
|
||||
NOW(),
|
||||
NOW()
|
||||
FROM tenants t
|
||||
JOIN invitation_rebate_configs src
|
||||
ON src.tenant_id = (SELECT id FROM tenants WHERE code = 'dachui' LIMIT 1)
|
||||
AND src.distribution_site_id = 0
|
||||
WHERE t.status = 'active'
|
||||
AND t.id <> src.tenant_id
|
||||
ON DUPLICATE KEY UPDATE
|
||||
first_month_rate = VALUES(first_month_rate),
|
||||
second_month_rate = VALUES(second_month_rate),
|
||||
subsequent_rate = VALUES(subsequent_rate),
|
||||
enabled = VALUES(enabled);
|
||||
|
||||
ALTER TABLE ad_tracking_links
|
||||
ADD COLUMN tenant_id BIGINT UNSIGNED NOT NULL DEFAULT 0 AFTER id,
|
||||
DROP KEY uk_ad_tracking_links_code,
|
||||
ADD UNIQUE KEY uk_ad_tracking_links_tenant_code (tenant_id, code),
|
||||
ADD KEY idx_ad_tracking_links_tenant_status (tenant_id, status);
|
||||
|
||||
UPDATE ad_tracking_links
|
||||
SET tenant_id = (SELECT id FROM tenants WHERE code = 'dachui' LIMIT 1)
|
||||
WHERE tenant_id = 0;
|
||||
|
||||
ALTER TABLE ad_tracking_clicks
|
||||
ADD COLUMN tenant_id BIGINT UNSIGNED NOT NULL DEFAULT 0 AFTER id,
|
||||
ADD KEY idx_ad_tracking_clicks_tenant_created (tenant_id, created_at);
|
||||
|
||||
UPDATE ad_tracking_clicks c
|
||||
JOIN ad_tracking_links l ON l.id = c.link_id
|
||||
SET c.tenant_id = l.tenant_id
|
||||
WHERE c.tenant_id = 0;
|
||||
|
||||
-- +goose Down
|
||||
|
||||
ALTER TABLE ad_tracking_clicks
|
||||
DROP KEY idx_ad_tracking_clicks_tenant_created,
|
||||
DROP COLUMN tenant_id;
|
||||
|
||||
ALTER TABLE ad_tracking_links
|
||||
DROP KEY idx_ad_tracking_links_tenant_status,
|
||||
DROP KEY uk_ad_tracking_links_tenant_code,
|
||||
ADD UNIQUE KEY uk_ad_tracking_links_code (code),
|
||||
DROP COLUMN tenant_id;
|
||||
|
||||
DELETE c
|
||||
FROM invitation_rebate_configs c
|
||||
WHERE c.tenant_id <> (SELECT id FROM tenants WHERE code = 'dachui' LIMIT 1);
|
||||
|
||||
ALTER TABLE invitation_rebate_configs
|
||||
DROP KEY idx_invitation_rebate_configs_tenant,
|
||||
DROP KEY uk_invitation_rebate_configs_tenant_site,
|
||||
ADD UNIQUE KEY uk_invitation_rebate_configs_site (distribution_site_id),
|
||||
DROP COLUMN tenant_id;
|
||||
Reference in New Issue
Block a user