feat(tenant): 隔离邀请返利与推广追踪数据
This commit is contained in:
@@ -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)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user