feat(distribution): 独立分销前台商城多租户体系、货源与订单数据严格隔离
This commit is contained in:
@@ -121,13 +121,64 @@ type DistributionOrderPage struct {
|
||||
}
|
||||
|
||||
type AccountDisplayDTO struct {
|
||||
ID uint64 `json:"id"`
|
||||
SiteID uint64 `json:"site_id"`
|
||||
AccountID uint64 `json:"account_id"`
|
||||
ListingID uint64 `json:"listing_id"`
|
||||
DisplayStatus string `json:"display_status"`
|
||||
ID uint64 `json:"id"`
|
||||
SiteID uint64 `json:"site_id"`
|
||||
AccountID uint64 `json:"account_id"`
|
||||
ListingID uint64 `json:"listing_id"`
|
||||
DisplayStatus string `json:"display_status"`
|
||||
ListingNo string `json:"listing_no,omitempty"`
|
||||
Title string `json:"title,omitempty"`
|
||||
GameName string `json:"game_name,omitempty"`
|
||||
ServerRegion string `json:"server_region,omitempty"`
|
||||
LoginPlatform string `json:"login_platform,omitempty"`
|
||||
RankLevel string `json:"rank_level,omitempty"`
|
||||
HafCoinAmount int64 `json:"haf_coin_amount,omitempty"`
|
||||
PriceCent int64 `json:"price_cent,omitempty"`
|
||||
DepositAmountCent int64 `json:"deposit_amount_cent,omitempty"`
|
||||
ListingStatus string `json:"listing_status,omitempty"`
|
||||
InTransaction bool `json:"in_transaction,omitempty"`
|
||||
}
|
||||
|
||||
type SyncSiteAccountsResult struct {
|
||||
SyncedCount int64 `json:"synced_count"`
|
||||
SkippedCount int64 `json:"skipped_count"`
|
||||
TotalActive int64 `json:"total_active"`
|
||||
}
|
||||
|
||||
type PublicDistributionListingDTO struct {
|
||||
ListingID uint64 `json:"listing_id"`
|
||||
ListingNo string `json:"listing_no"`
|
||||
AccountID uint64 `json:"account_id"`
|
||||
Title string `json:"title"`
|
||||
GameName string `json:"game_name"`
|
||||
ServerRegion string `json:"server_region"`
|
||||
LoginPlatform string `json:"login_platform"`
|
||||
RankLevel string `json:"rank_level"`
|
||||
HafCoinAmount int64 `json:"haf_coin_amount"`
|
||||
PriceCent int64 `json:"price_cent"`
|
||||
DepositAmountCent int64 `json:"deposit_amount_cent"`
|
||||
InTransaction bool `json:"in_transaction"`
|
||||
SiteCode string `json:"site_code"`
|
||||
SiteName string `json:"site_name"`
|
||||
}
|
||||
|
||||
type PublicDistributionListingsResult struct {
|
||||
Items []PublicDistributionListingDTO `json:"items"`
|
||||
Total int64 `json:"total"`
|
||||
Page int `json:"page"`
|
||||
PageSize int `json:"page_size"`
|
||||
}
|
||||
|
||||
type PublicSiteInfoDTO struct {
|
||||
SiteCode string `json:"site_code"`
|
||||
SiteName string `json:"site_name"`
|
||||
Domain string `json:"domain"`
|
||||
Status string `json:"status"`
|
||||
DisplayAccountEnabled bool `json:"display_account_enabled"`
|
||||
DefaultSupportGroupID *uint64 `json:"default_support_group_id,omitempty"`
|
||||
}
|
||||
|
||||
|
||||
type UpdateAccountDisplayRequest struct {
|
||||
DisplayStatus string `json:"display_status" binding:"required,oneof=enabled disabled sold offline"`
|
||||
}
|
||||
|
||||
@@ -186,10 +186,7 @@ func (h *Handler) CreateFinancialSnapshot(c *gin.Context) {
|
||||
|
||||
func (h *Handler) ListAccountDisplays(c *gin.Context) {
|
||||
siteID := parseQueryUint(c, "site_id")
|
||||
if siteID <= 0 {
|
||||
if siteID == 0 {
|
||||
response.BadRequest(c, "site_id 不正确")
|
||||
}
|
||||
if siteID < 0 {
|
||||
return
|
||||
}
|
||||
adminID, _ := currentAdminID(c)
|
||||
@@ -198,6 +195,10 @@ func (h *Handler) ListAccountDisplays(c *gin.Context) {
|
||||
writeError(c, err)
|
||||
return
|
||||
}
|
||||
if scoped == 0 && siteID == 0 {
|
||||
response.BadRequest(c, "site_id 不正确")
|
||||
return
|
||||
}
|
||||
items, err := h.service.ListAccountDisplays(c.Request.Context(), scoped, c.Query("status"))
|
||||
if err != nil {
|
||||
writeError(c, err)
|
||||
@@ -225,6 +226,75 @@ func (h *Handler) UpdateAccountDisplay(c *gin.Context) {
|
||||
response.OK(c, item)
|
||||
}
|
||||
|
||||
func (h *Handler) SyncSiteAccounts(c *gin.Context) {
|
||||
var siteID uint64
|
||||
id, ok := parseID(c)
|
||||
if ok && id > 0 {
|
||||
siteID = id
|
||||
} else {
|
||||
qID := parseQueryUint(c, "site_id")
|
||||
if qID > 0 {
|
||||
siteID = uint64(qID)
|
||||
}
|
||||
}
|
||||
adminID, _ := currentAdminID(c)
|
||||
scoped, err := h.service.ScopeSiteID(c.Request.Context(), adminID, siteID)
|
||||
if err != nil {
|
||||
writeError(c, err)
|
||||
return
|
||||
}
|
||||
if scoped == 0 {
|
||||
response.BadRequest(c, "site_id 不正确")
|
||||
return
|
||||
}
|
||||
result, err := h.service.SyncSiteAccounts(c.Request.Context(), adminID, scoped)
|
||||
if err != nil {
|
||||
writeError(c, err)
|
||||
return
|
||||
}
|
||||
response.OK(c, result)
|
||||
}
|
||||
|
||||
func (h *Handler) ListPublicSiteListings(c *gin.Context) {
|
||||
siteCode := strings.TrimSpace(c.Param("site_code"))
|
||||
if siteCode == "" {
|
||||
siteCode = strings.TrimSpace(c.Query("site_code"))
|
||||
}
|
||||
if siteCode == "" {
|
||||
response.BadRequest(c, "site_code 不能为空")
|
||||
return
|
||||
}
|
||||
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
|
||||
result, err := h.service.ListPublicSiteListings(c.Request.Context(), siteCode, page, pageSize)
|
||||
if err != nil {
|
||||
writeError(c, err)
|
||||
return
|
||||
}
|
||||
response.OK(c, result)
|
||||
}
|
||||
|
||||
func (h *Handler) GetPublicSiteInfo(c *gin.Context) {
|
||||
code := strings.TrimSpace(c.Query("code"))
|
||||
if code == "" {
|
||||
code = strings.TrimSpace(c.Query("site_code"))
|
||||
}
|
||||
domain := strings.TrimSpace(c.Query("domain"))
|
||||
if code == "" && domain == "" {
|
||||
host := c.Request.Host
|
||||
if colon := strings.Index(host, ":"); colon != -1 {
|
||||
host = host[:colon]
|
||||
}
|
||||
domain = host
|
||||
}
|
||||
info, err := h.service.GetPublicSiteInfo(c.Request.Context(), code, domain)
|
||||
if err != nil {
|
||||
writeError(c, err)
|
||||
return
|
||||
}
|
||||
response.OK(c, info)
|
||||
}
|
||||
|
||||
func (h *Handler) ListPaymentChannels(c *gin.Context) {
|
||||
siteID := parseQueryUint(c, "site_id")
|
||||
if siteID <= 0 {
|
||||
|
||||
@@ -346,17 +346,76 @@ func (r *Repository) FindOrder(ctx context.Context, adminID, id uint64) (*Distri
|
||||
}
|
||||
|
||||
func (r *Repository) ListAccountDisplays(ctx context.Context, siteID uint64, status string) ([]AccountDisplayDTO, error) {
|
||||
var rows []model.DistributionSiteAccount
|
||||
db := r.db.WithContext(ctx).Where("site_id = ?", siteID).Order("id DESC")
|
||||
if status != "" {
|
||||
db = db.Where("display_status = ?", status)
|
||||
type accountDisplayRow struct {
|
||||
ID uint64 `gorm:"column:id"`
|
||||
SiteID uint64 `gorm:"column:site_id"`
|
||||
AccountID uint64 `gorm:"column:account_id"`
|
||||
ListingID uint64 `gorm:"column:listing_id"`
|
||||
DisplayStatus string `gorm:"column:display_status"`
|
||||
ListingNo string `gorm:"column:listing_no"`
|
||||
Title string `gorm:"column:title"`
|
||||
GameName string `gorm:"column:game_name"`
|
||||
ServerRegion string `gorm:"column:server_region"`
|
||||
LoginPlatform string `gorm:"column:login_platform"`
|
||||
RankLevel string `gorm:"column:rank_level"`
|
||||
HafCoinAmount int64 `gorm:"column:haf_coin_amount"`
|
||||
PriceCent int64 `gorm:"column:price_cent"`
|
||||
DepositAmountCent int64 `gorm:"column:deposit_amount_cent"`
|
||||
ListingStatus string `gorm:"column:listing_status"`
|
||||
InTransaction bool `gorm:"column:in_transaction"`
|
||||
}
|
||||
if err := db.Find(&rows).Error; err != nil {
|
||||
|
||||
var rows []accountDisplayRow
|
||||
query := r.db.WithContext(ctx).
|
||||
Table("distribution_site_accounts AS dsa").
|
||||
Select(`
|
||||
dsa.id,
|
||||
dsa.site_id,
|
||||
dsa.account_id,
|
||||
dsa.listing_id,
|
||||
dsa.display_status,
|
||||
COALESCE(l.listing_no, '') AS listing_no,
|
||||
COALESCE(ga.title, '') AS title,
|
||||
COALESCE(ga.game_name, '') AS game_name,
|
||||
COALESCE(ga.server_region, '') AS server_region,
|
||||
COALESCE(ga.login_platform, '') AS login_platform,
|
||||
COALESCE(ga.rank_level, '') AS rank_level,
|
||||
COALESCE(ga.haf_coin_amount, 0) AS haf_coin_amount,
|
||||
COALESCE(l.price_cent, 0) AS price_cent,
|
||||
COALESCE(l.deposit_amount_cent, 0) AS deposit_amount_cent,
|
||||
COALESCE(l.status, '') AS listing_status,
|
||||
COALESCE(l.in_transaction, 0) AS in_transaction
|
||||
`).
|
||||
Joins("LEFT JOIN rental_listings AS l ON l.id = dsa.listing_id").
|
||||
Joins("LEFT JOIN game_accounts AS ga ON ga.id = dsa.account_id").
|
||||
Where("dsa.site_id = ?", siteID)
|
||||
|
||||
if status != "" {
|
||||
query = query.Where("dsa.display_status = ?", status)
|
||||
}
|
||||
if err := query.Order("dsa.id DESC").Scan(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items := make([]AccountDisplayDTO, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
items = append(items, AccountDisplayDTO{ID: row.ID, SiteID: row.SiteID, AccountID: row.AccountID, ListingID: row.ListingID, DisplayStatus: row.DisplayStatus})
|
||||
items = append(items, AccountDisplayDTO{
|
||||
ID: row.ID,
|
||||
SiteID: row.SiteID,
|
||||
AccountID: row.AccountID,
|
||||
ListingID: row.ListingID,
|
||||
DisplayStatus: row.DisplayStatus,
|
||||
ListingNo: row.ListingNo,
|
||||
Title: row.Title,
|
||||
GameName: row.GameName,
|
||||
ServerRegion: row.ServerRegion,
|
||||
LoginPlatform: row.LoginPlatform,
|
||||
RankLevel: row.RankLevel,
|
||||
HafCoinAmount: row.HafCoinAmount,
|
||||
PriceCent: row.PriceCent,
|
||||
DepositAmountCent: row.DepositAmountCent,
|
||||
ListingStatus: row.ListingStatus,
|
||||
InTransaction: row.InTransaction,
|
||||
})
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
@@ -376,10 +435,107 @@ func (r *Repository) UpdateAccountDisplay(ctx context.Context, adminID, id uint6
|
||||
if err := r.db.WithContext(ctx).Save(&row).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
item := &AccountDisplayDTO{ID: row.ID, SiteID: row.SiteID, AccountID: row.AccountID, ListingID: row.ListingID, DisplayStatus: row.DisplayStatus}
|
||||
item := &AccountDisplayDTO{
|
||||
ID: row.ID,
|
||||
SiteID: row.SiteID,
|
||||
AccountID: row.AccountID,
|
||||
ListingID: row.ListingID,
|
||||
DisplayStatus: row.DisplayStatus,
|
||||
}
|
||||
var listing model.RentalListing
|
||||
if err := r.db.WithContext(ctx).First(&listing, row.ListingID).Error; err == nil {
|
||||
item.ListingNo = listing.ListingNo
|
||||
item.PriceCent = listing.PriceCent
|
||||
item.DepositAmountCent = listing.DepositAmountCent
|
||||
item.ListingStatus = listing.Status
|
||||
item.InTransaction = listing.InTransaction
|
||||
}
|
||||
var account model.GameAccount
|
||||
if err := r.db.WithContext(ctx).First(&account, row.AccountID).Error; err == nil {
|
||||
item.Title = account.Title
|
||||
item.GameName = account.GameName
|
||||
item.ServerRegion = account.ServerRegion
|
||||
item.LoginPlatform = account.LoginPlatform
|
||||
item.RankLevel = account.RankLevel
|
||||
item.HafCoinAmount = account.HafCoinAmount
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
|
||||
func (r *Repository) SyncSiteAccounts(ctx context.Context, adminID, siteID uint64) (*SyncSiteAccountsResult, error) {
|
||||
if r.db == nil {
|
||||
return nil, ErrDependencyUnavailable
|
||||
}
|
||||
if err := r.ensureSiteAccess(ctx, adminID, siteID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var site model.DistributionSite
|
||||
if err := r.db.WithContext(ctx).First(&site, siteID).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrSiteNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var activeListings []model.RentalListing
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("status = ? AND review_status = ?", "published", "approved").
|
||||
Order("id ASC").
|
||||
Find(&activeListings).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var existingAccounts []model.DistributionSiteAccount
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("site_id = ?", siteID).
|
||||
Find(&existingAccounts).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
existingMap := make(map[uint64]model.DistributionSiteAccount, len(existingAccounts))
|
||||
for _, ea := range existingAccounts {
|
||||
existingMap[ea.AccountID] = ea
|
||||
}
|
||||
|
||||
var toInsert []model.DistributionSiteAccount
|
||||
seenAccount := make(map[uint64]bool)
|
||||
var skippedCount int64
|
||||
|
||||
for _, l := range activeListings {
|
||||
if seenAccount[l.AccountID] {
|
||||
continue
|
||||
}
|
||||
seenAccount[l.AccountID] = true
|
||||
|
||||
if ea, exists := existingMap[l.AccountID]; exists {
|
||||
if ea.ListingID != l.ID {
|
||||
_ = r.db.WithContext(ctx).Model(&model.DistributionSiteAccount{}).
|
||||
Where("id = ?", ea.ID).Update("listing_id", l.ID).Error
|
||||
}
|
||||
skippedCount++
|
||||
} else {
|
||||
toInsert = append(toInsert, model.DistributionSiteAccount{
|
||||
SiteID: siteID,
|
||||
AccountID: l.AccountID,
|
||||
ListingID: l.ID,
|
||||
DisplayStatus: "enabled",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if len(toInsert) > 0 {
|
||||
if err := r.db.WithContext(ctx).Create(&toInsert).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return &SyncSiteAccountsResult{
|
||||
SyncedCount: int64(len(toInsert)),
|
||||
SkippedCount: skippedCount,
|
||||
TotalActive: int64(len(activeListings)),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *Repository) ListPaymentChannels(ctx context.Context, siteID uint64) ([]PaymentChannelDTO, error) {
|
||||
var rows []model.DistributionSitePaymentChannel
|
||||
if err := r.db.WithContext(ctx).Where("site_id = ?", siteID).Order("priority ASC, id ASC").Find(&rows).Error; err != nil {
|
||||
@@ -860,6 +1016,34 @@ func (r *Repository) OnboardSite(ctx context.Context, req OnboardSiteRequest) (*
|
||||
return err
|
||||
}
|
||||
|
||||
if displayEnabled {
|
||||
var activeListings []model.RentalListing
|
||||
if err := tx.Where("status = ? AND review_status = ?", "published", "approved").Order("id ASC").Find(&activeListings).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if len(activeListings) > 0 {
|
||||
siteAccounts := make([]model.DistributionSiteAccount, 0, len(activeListings))
|
||||
seenAccount := make(map[uint64]bool)
|
||||
for _, l := range activeListings {
|
||||
if seenAccount[l.AccountID] {
|
||||
continue
|
||||
}
|
||||
seenAccount[l.AccountID] = true
|
||||
siteAccounts = append(siteAccounts, model.DistributionSiteAccount{
|
||||
SiteID: site.ID,
|
||||
AccountID: l.AccountID,
|
||||
ListingID: l.ID,
|
||||
DisplayStatus: "enabled",
|
||||
})
|
||||
}
|
||||
if len(siteAccounts) > 0 {
|
||||
if err := tx.Create(&siteAccounts).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
resp = OnboardSiteResponse{
|
||||
Site: siteDTO(site),
|
||||
Rule: ruleDTO(rule),
|
||||
@@ -882,3 +1066,150 @@ func (r *Repository) OnboardSite(ctx context.Context, req OnboardSiteRequest) (*
|
||||
}
|
||||
return &resp, nil
|
||||
}
|
||||
|
||||
func (r *Repository) ListPublicSiteListings(ctx context.Context, siteCode string, page, pageSize int) (*PublicDistributionListingsResult, error) {
|
||||
if r.db == nil {
|
||||
return nil, ErrDependencyUnavailable
|
||||
}
|
||||
if strings.TrimSpace(siteCode) == "" {
|
||||
return nil, ErrSiteNotFound
|
||||
}
|
||||
if page <= 0 {
|
||||
page = 1
|
||||
}
|
||||
if pageSize <= 0 {
|
||||
pageSize = 20
|
||||
}
|
||||
if pageSize > 100 {
|
||||
pageSize = 100
|
||||
}
|
||||
|
||||
var site model.DistributionSite
|
||||
if err := r.db.WithContext(ctx).Where("site_code = ? AND status = 'active'", siteCode).First(&site).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrSiteNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if !site.DisplayAccountEnabled {
|
||||
return &PublicDistributionListingsResult{
|
||||
Items: []PublicDistributionListingDTO{},
|
||||
Total: 0,
|
||||
Page: page,
|
||||
PageSize: pageSize,
|
||||
}, nil
|
||||
}
|
||||
|
||||
type publicListingRow struct {
|
||||
ListingID uint64 `gorm:"column:listing_id"`
|
||||
ListingNo string `gorm:"column:listing_no"`
|
||||
AccountID uint64 `gorm:"column:account_id"`
|
||||
Title string `gorm:"column:title"`
|
||||
GameName string `gorm:"column:game_name"`
|
||||
ServerRegion string `gorm:"column:server_region"`
|
||||
LoginPlatform string `gorm:"column:login_platform"`
|
||||
RankLevel string `gorm:"column:rank_level"`
|
||||
HafCoinAmount int64 `gorm:"column:haf_coin_amount"`
|
||||
PriceCent int64 `gorm:"column:price_cent"`
|
||||
DepositAmountCent int64 `gorm:"column:deposit_amount_cent"`
|
||||
InTransaction bool `gorm:"column:in_transaction"`
|
||||
}
|
||||
|
||||
baseQuery := r.db.WithContext(ctx).
|
||||
Table("distribution_site_accounts AS dsa").
|
||||
Joins("INNER JOIN rental_listings AS l ON l.id = dsa.listing_id AND l.status = 'published' AND l.review_status = 'approved'").
|
||||
Joins("INNER JOIN game_accounts AS ga ON ga.id = dsa.account_id").
|
||||
Where("dsa.site_id = ? AND dsa.display_status = 'enabled'", site.ID)
|
||||
|
||||
var total int64
|
||||
if err := baseQuery.Count(&total).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var rows []publicListingRow
|
||||
err := baseQuery.
|
||||
Select(`
|
||||
dsa.listing_id,
|
||||
l.listing_no,
|
||||
dsa.account_id,
|
||||
COALESCE(ga.title, '') AS title,
|
||||
COALESCE(ga.game_name, '') AS game_name,
|
||||
COALESCE(ga.server_region, '') AS server_region,
|
||||
COALESCE(ga.login_platform, '') AS login_platform,
|
||||
COALESCE(ga.rank_level, '') AS rank_level,
|
||||
COALESCE(ga.haf_coin_amount, 0) AS haf_coin_amount,
|
||||
COALESCE(l.price_cent, 0) AS price_cent,
|
||||
COALESCE(l.deposit_amount_cent, 0) AS deposit_amount_cent,
|
||||
COALESCE(l.in_transaction, 0) AS in_transaction
|
||||
`).
|
||||
Order("dsa.id DESC").
|
||||
Offset((page - 1) * pageSize).
|
||||
Limit(pageSize).
|
||||
Scan(&rows).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
items := make([]PublicDistributionListingDTO, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
items = append(items, PublicDistributionListingDTO{
|
||||
ListingID: row.ListingID,
|
||||
ListingNo: row.ListingNo,
|
||||
AccountID: row.AccountID,
|
||||
Title: row.Title,
|
||||
GameName: row.GameName,
|
||||
ServerRegion: row.ServerRegion,
|
||||
LoginPlatform: row.LoginPlatform,
|
||||
RankLevel: row.RankLevel,
|
||||
HafCoinAmount: row.HafCoinAmount,
|
||||
PriceCent: row.PriceCent,
|
||||
DepositAmountCent: row.DepositAmountCent,
|
||||
InTransaction: row.InTransaction,
|
||||
SiteCode: site.SiteCode,
|
||||
SiteName: site.SiteName,
|
||||
})
|
||||
}
|
||||
|
||||
return &PublicDistributionListingsResult{
|
||||
Items: items,
|
||||
Total: total,
|
||||
Page: page,
|
||||
PageSize: pageSize,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *Repository) GetPublicSiteInfo(ctx context.Context, code, domain string) (*PublicSiteInfoDTO, error) {
|
||||
if r.db == nil {
|
||||
return nil, ErrDependencyUnavailable
|
||||
}
|
||||
code = strings.TrimSpace(code)
|
||||
domain = strings.TrimSpace(domain)
|
||||
if code == "" && domain == "" {
|
||||
return nil, ErrSiteNotFound
|
||||
}
|
||||
|
||||
var site model.DistributionSite
|
||||
query := r.db.WithContext(ctx).Where("status = 'active'")
|
||||
if code != "" {
|
||||
query = query.Where("site_code = ?", code)
|
||||
} else {
|
||||
query = query.Where("domain = ?", domain)
|
||||
}
|
||||
|
||||
if err := query.First(&site).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrSiteNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &PublicSiteInfoDTO{
|
||||
SiteCode: site.SiteCode,
|
||||
SiteName: site.SiteName,
|
||||
Domain: site.Domain,
|
||||
Status: site.Status,
|
||||
DisplayAccountEnabled: site.DisplayAccountEnabled,
|
||||
DefaultSupportGroupID: site.DefaultSupportGroupID,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package distribution
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -16,7 +17,14 @@ func distributionTestDB(t *testing.T) *gorm.DB {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.AutoMigrate(&model.AdminUser{}, &model.Role{}, &model.ChatConversation{}, &model.RentalOrder{}, &model.AuditLog{}, &model.PaymentMerchantConfig{}, &model.DistributionSite{}, &model.DistributionSiteMember{}, &model.DistributionRuleVersion{}, &model.DistributionOrderFinancial{}, &model.DistributionOrderParty{}, &model.DistributionSiteAccount{}, &model.DistributionSitePaymentChannel{}, &model.DistributionSettlementBatch{}, &model.DistributionSettlementItem{}); err != nil {
|
||||
if err := db.AutoMigrate(
|
||||
&model.AdminUser{}, &model.Role{}, &model.ChatConversation{}, &model.RentalOrder{},
|
||||
&model.AuditLog{}, &model.PaymentMerchantConfig{}, &model.DistributionSite{},
|
||||
&model.DistributionSiteMember{}, &model.DistributionRuleVersion{}, &model.DistributionOrderFinancial{},
|
||||
&model.DistributionOrderParty{}, &model.DistributionSiteAccount{}, &model.DistributionSitePaymentChannel{},
|
||||
&model.DistributionSettlementBatch{}, &model.DistributionSettlementItem{},
|
||||
&model.RentalListing{}, &model.GameAccount{},
|
||||
); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return db
|
||||
@@ -177,3 +185,208 @@ func TestScopeSiteIDRestrictsBoundMember(t *testing.T) {
|
||||
t.Fatalf("UpdateAccountDisplay cross-site err = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyncSiteAccountsAndPublicListings(t *testing.T) {
|
||||
db := distributionTestDB(t)
|
||||
repo := NewRepository(db)
|
||||
|
||||
site := model.DistributionSite{
|
||||
SiteCode: "sync_demo",
|
||||
SiteName: "同步演示站",
|
||||
Domain: "sync.example.com",
|
||||
DisplayAccountEnabled: true,
|
||||
Status: "active",
|
||||
}
|
||||
if err := db.Create(&site).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
account1 := model.GameAccount{
|
||||
Title: "三角洲极品金枪号",
|
||||
GameName: "delta_force",
|
||||
ServerRegion: "微信区",
|
||||
LoginPlatform: "PC",
|
||||
RankLevel: "王者",
|
||||
HafCoinAmount: 500000,
|
||||
Status: "active",
|
||||
}
|
||||
if err := db.Create(&account1).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
listing1 := model.RentalListing{
|
||||
ListingNo: "L10001",
|
||||
AccountID: account1.ID,
|
||||
OwnerID: 1,
|
||||
PriceCent: 2500,
|
||||
DepositAmountCent: 10000,
|
||||
Status: "published",
|
||||
ReviewStatus: "approved",
|
||||
InTransaction: false,
|
||||
}
|
||||
if err := db.Create(&listing1).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// 草稿状态的商品不应该被同步
|
||||
listingDraft := model.RentalListing{
|
||||
ListingNo: "L10002",
|
||||
AccountID: 999,
|
||||
OwnerID: 1,
|
||||
PriceCent: 3000,
|
||||
DepositAmountCent: 5000,
|
||||
Status: "draft",
|
||||
ReviewStatus: "pending",
|
||||
}
|
||||
if err := db.Create(&listingDraft).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// 首次同步:应当成功新增 1 条,跳过 0 条
|
||||
res1, err := repo.SyncSiteAccounts(t.Context(), 0, site.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("SyncSiteAccounts err = %v", err)
|
||||
}
|
||||
if res1.SyncedCount != 1 || res1.SkippedCount != 0 || res1.TotalActive != 1 {
|
||||
t.Fatalf("unexpected res1: %+v", res1)
|
||||
}
|
||||
|
||||
// 再次同步:幂等保证,跳过 1 条,新增 0 条
|
||||
res2, err := repo.SyncSiteAccounts(t.Context(), 0, site.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("SyncSiteAccounts retry err = %v", err)
|
||||
}
|
||||
if res2.SyncedCount != 0 || res2.SkippedCount != 1 || res2.TotalActive != 1 {
|
||||
t.Fatalf("unexpected res2: %+v", res2)
|
||||
}
|
||||
|
||||
// 验证管理后台列表查询携带丰富字段
|
||||
displays, err := repo.ListAccountDisplays(t.Context(), site.ID, "")
|
||||
if err != nil {
|
||||
t.Fatalf("ListAccountDisplays err = %v", err)
|
||||
}
|
||||
if len(displays) != 1 {
|
||||
t.Fatalf("expected 1 display, got %d", len(displays))
|
||||
}
|
||||
d := displays[0]
|
||||
if d.Title != "三角洲极品金枪号" || d.GameName != "delta_force" || d.PriceCent != 2500 || d.DepositAmountCent != 10000 || d.ListingNo != "L10001" {
|
||||
t.Fatalf("unexpected enriched display: %+v", d)
|
||||
}
|
||||
|
||||
// 验证公共端点浏览查询
|
||||
pubList, err := repo.ListPublicSiteListings(t.Context(), site.SiteCode, 1, 20)
|
||||
if err != nil {
|
||||
t.Fatalf("ListPublicSiteListings err = %v", err)
|
||||
}
|
||||
if pubList.Total != 1 || len(pubList.Items) != 1 {
|
||||
t.Fatalf("expected 1 public item, got %+v", pubList)
|
||||
}
|
||||
if pubList.Items[0].Title != "三角洲极品金枪号" || pubList.Items[0].SiteCode != site.SiteCode {
|
||||
t.Fatalf("unexpected public item: %+v", pubList.Items[0])
|
||||
}
|
||||
|
||||
// 下架该展示账号后,公共端点不再返回
|
||||
if _, err := repo.UpdateAccountDisplay(t.Context(), 0, d.ID, "disabled"); err != nil {
|
||||
t.Fatalf("UpdateAccountDisplay disabled err = %v", err)
|
||||
}
|
||||
pubList2, err := repo.ListPublicSiteListings(t.Context(), site.SiteCode, 1, 20)
|
||||
if err != nil {
|
||||
t.Fatalf("ListPublicSiteListings after disabled err = %v", err)
|
||||
}
|
||||
if pubList2.Total != 0 || len(pubList2.Items) != 0 {
|
||||
t.Fatalf("expected 0 public items after disabled, got %+v", pubList2)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOnboardSiteAutoSyncsActiveListings(t *testing.T) {
|
||||
db := distributionTestDB(t)
|
||||
repo := NewRepository(db)
|
||||
|
||||
account := model.GameAccount{
|
||||
Title: "王者荣耀国服账号",
|
||||
GameName: "honor_of_kings",
|
||||
ServerRegion: "手Q一区",
|
||||
LoginPlatform: "iOS",
|
||||
Status: "active",
|
||||
}
|
||||
if err := db.Create(&account).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
listing := model.RentalListing{
|
||||
ListingNo: "L20001",
|
||||
AccountID: account.ID,
|
||||
OwnerID: 2,
|
||||
PriceCent: 5000,
|
||||
Status: "published",
|
||||
ReviewStatus: "approved",
|
||||
}
|
||||
if err := db.Create(&listing).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
dispEnabled := true
|
||||
onboardResp, err := repo.OnboardSite(t.Context(), OnboardSiteRequest{
|
||||
SiteCode: "auto_sync_site",
|
||||
SiteName: "自动同步站点",
|
||||
Domain: "auto.example.com",
|
||||
AdminUsername: "auto_admin",
|
||||
AdminPassword: "securepass123",
|
||||
DisplayAccountEnabled: &dispEnabled,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("OnboardSite err = %v", err)
|
||||
}
|
||||
|
||||
displays, err := repo.ListAccountDisplays(t.Context(), onboardResp.Site.ID, "")
|
||||
if err != nil {
|
||||
t.Fatalf("ListAccountDisplays err = %v", err)
|
||||
}
|
||||
if len(displays) != 1 {
|
||||
t.Fatalf("expected 1 auto-synced account, got %d", len(displays))
|
||||
}
|
||||
if displays[0].Title != "王者荣耀国服账号" || displays[0].ListingNo != "L20001" {
|
||||
t.Fatalf("unexpected auto-synced display: %+v", displays[0])
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetPublicSiteInfo(t *testing.T) {
|
||||
db := distributionTestDB(t)
|
||||
repo := NewRepository(db)
|
||||
|
||||
site := model.DistributionSite{
|
||||
SiteCode: "info_site",
|
||||
SiteName: "信息测试站",
|
||||
Domain: "info.example.com",
|
||||
Status: "active",
|
||||
DisplayAccountEnabled: true,
|
||||
}
|
||||
if err := db.Create(&site).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Query by code
|
||||
info, err := repo.GetPublicSiteInfo(t.Context(), "info_site", "")
|
||||
if err != nil {
|
||||
t.Fatalf("GetPublicSiteInfo by code failed: %v", err)
|
||||
}
|
||||
if info.SiteName != "信息测试站" || info.SiteCode != "info_site" {
|
||||
t.Fatalf("unexpected info: %+v", info)
|
||||
}
|
||||
|
||||
// Query by domain
|
||||
infoByDomain, err := repo.GetPublicSiteInfo(t.Context(), "", "info.example.com")
|
||||
if err != nil {
|
||||
t.Fatalf("GetPublicSiteInfo by domain failed: %v", err)
|
||||
}
|
||||
if infoByDomain.SiteName != "信息测试站" {
|
||||
t.Fatalf("unexpected info by domain: %+v", infoByDomain)
|
||||
}
|
||||
|
||||
// Query not found
|
||||
_, err = repo.GetPublicSiteInfo(t.Context(), "not_found", "")
|
||||
if !errors.Is(err, ErrSiteNotFound) {
|
||||
t.Fatalf("expected ErrSiteNotFound, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -218,3 +218,25 @@ func (s *Service) OnboardSite(ctx context.Context, req OnboardSiteRequest) (*Onb
|
||||
return s.repo.OnboardSite(ctx, req)
|
||||
}
|
||||
|
||||
func (s *Service) SyncSiteAccounts(ctx context.Context, adminID, siteID uint64) (*SyncSiteAccountsResult, error) {
|
||||
if err := s.available(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.repo.SyncSiteAccounts(ctx, adminID, siteID)
|
||||
}
|
||||
|
||||
func (s *Service) ListPublicSiteListings(ctx context.Context, siteCode string, page, pageSize int) (*PublicDistributionListingsResult, error) {
|
||||
if err := s.available(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.repo.ListPublicSiteListings(ctx, siteCode, page, pageSize)
|
||||
}
|
||||
|
||||
func (s *Service) GetPublicSiteInfo(ctx context.Context, code, domain string) (*PublicSiteInfoDTO, error) {
|
||||
if err := s.available(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.repo.GetPublicSiteInfo(ctx, code, domain)
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -175,9 +175,10 @@ type PublicListQuery struct {
|
||||
MaxFireLevel *float64
|
||||
MinDailyLoss *float64
|
||||
MaxDailyLoss *float64
|
||||
MinSecretKD *float64
|
||||
MaxSecretKD *float64
|
||||
ResourceRanges map[string]NumberRange
|
||||
MinSecretKD *float64
|
||||
MaxSecretKD *float64
|
||||
ResourceRanges map[string]NumberRange
|
||||
DistributionSiteCode string
|
||||
}
|
||||
|
||||
type NumberRange struct {
|
||||
|
||||
@@ -116,9 +116,10 @@ func parsePublicListQuery(c *gin.Context) PublicListQuery {
|
||||
MaxFireLevel: parseOptionalFloat(c.Query("max_fire_level")),
|
||||
MinDailyLoss: parseOptionalFloat(c.Query("min_daily_loss")),
|
||||
MaxDailyLoss: parseOptionalFloat(c.Query("max_daily_loss")),
|
||||
MinSecretKD: parseOptionalFloat(c.Query("min_secret_kd")),
|
||||
MaxSecretKD: parseOptionalFloat(c.Query("max_secret_kd")),
|
||||
ResourceRanges: parseResourceRanges(c),
|
||||
MinSecretKD: parseOptionalFloat(c.Query("min_secret_kd")),
|
||||
MaxSecretKD: parseOptionalFloat(c.Query("max_secret_kd")),
|
||||
ResourceRanges: parseResourceRanges(c),
|
||||
DistributionSiteCode: strings.TrimSpace(firstNonEmpty(c.Query("distribution_site_code"), c.Query("site_code"))),
|
||||
}
|
||||
if query.PageSize > 50 {
|
||||
query.PageSize = 50
|
||||
|
||||
@@ -16,10 +16,16 @@ func (r *Repository) ListPublic(ctx context.Context, query PublicListQuery) (*Pu
|
||||
return r.listPublicPage(ctx, query, page, pageSize)
|
||||
}
|
||||
|
||||
db := r.baseQuery(ctx).
|
||||
Where("l.status = ? AND l.review_status = ? AND l.in_transaction = ?", "published", "approved", false)
|
||||
|
||||
if query.DistributionSiteCode != "" {
|
||||
db = db.Joins("INNER JOIN distribution_site_accounts AS dsa ON dsa.listing_id = l.id AND dsa.display_status = 'enabled'").
|
||||
Joins("INNER JOIN distribution_sites AS ds ON ds.id = dsa.site_id AND ds.site_code = ? AND ds.status = 'active' AND ds.display_account_enabled = ?", query.DistributionSiteCode, true)
|
||||
}
|
||||
|
||||
var rows []listingRow
|
||||
err := r.baseQuery(ctx).
|
||||
Where("l.status = ? AND l.review_status = ? AND l.in_transaction = ?", "published", "approved", false).
|
||||
Order("l.published_at DESC, l.id DESC").
|
||||
err := db.Order("l.published_at DESC, l.id DESC").
|
||||
Scan(&rows).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -103,6 +109,9 @@ func normalizedPublicPage(query PublicListQuery) (int, int) {
|
||||
}
|
||||
|
||||
func canListPublicWithSQL(query PublicListQuery) bool {
|
||||
if query.DistributionSiteCode != "" {
|
||||
return false
|
||||
}
|
||||
if query.Keyword != "" {
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -746,3 +746,49 @@ func containsString(values []string, target string) bool {
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func TestListPublicWithDistributionSiteCode(t *testing.T) {
|
||||
db := database.NewTestDB()
|
||||
if err := database.MigrateListingLifecycleTestSchema(db); err != nil {
|
||||
t.Fatalf("migrate err: %v", err)
|
||||
}
|
||||
if err := db.AutoMigrate(&model.DistributionSite{}, &model.DistributionSiteAccount{}); err != nil {
|
||||
t.Fatalf("migrate distribution err: %v", err)
|
||||
}
|
||||
|
||||
repo := NewRepository(db, nil)
|
||||
|
||||
account1 := model.GameAccount{Title: "号1", GameName: "delta", Status: "active"}
|
||||
account2 := model.GameAccount{Title: "号2", GameName: "delta", Status: "active"}
|
||||
db.Create(&account1)
|
||||
db.Create(&account2)
|
||||
|
||||
l1 := model.RentalListing{ListingNo: "L101", AccountID: account1.ID, Status: "published", ReviewStatus: "approved", PriceCent: 1000}
|
||||
l2 := model.RentalListing{ListingNo: "L102", AccountID: account2.ID, Status: "published", ReviewStatus: "approved", PriceCent: 2000}
|
||||
db.Create(&l1)
|
||||
db.Create(&l2)
|
||||
|
||||
site := model.DistributionSite{SiteCode: "site_alpha", SiteName: "分销A", Domain: "a.com", Status: "active", DisplayAccountEnabled: true}
|
||||
db.Create(&site)
|
||||
|
||||
dsa := model.DistributionSiteAccount{SiteID: site.ID, AccountID: account1.ID, ListingID: l1.ID, DisplayStatus: "enabled"}
|
||||
db.Create(&dsa)
|
||||
|
||||
res, err := repo.ListPublic(context.Background(), PublicListQuery{
|
||||
DistributionSiteCode: "site_alpha",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("ListPublic err: %v", err)
|
||||
}
|
||||
if len(res.Items) != 1 || res.Items[0].ListingNo != "L101" {
|
||||
t.Fatalf("expected only L101, got %+v", res.Items)
|
||||
}
|
||||
|
||||
allRes, err := repo.ListPublic(context.Background(), PublicListQuery{})
|
||||
if err != nil {
|
||||
t.Fatalf("ListPublic err: %v", err)
|
||||
}
|
||||
if len(allRes.Items) != 2 {
|
||||
t.Fatalf("expected 2 listings for main site, got %d", len(allRes.Items))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -75,6 +75,7 @@ type OrderDTO struct {
|
||||
Checkout *CheckoutDTO `json:"checkout,omitempty"`
|
||||
AdminActions *AdminActionsDTO `json:"admin_actions,omitempty"`
|
||||
PaymentDeadlineAt *time.Time `json:"payment_deadline_at,omitempty"`
|
||||
DistributionSiteID *uint64 `json:"distribution_site_id,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
@@ -95,6 +96,7 @@ type UserOrderListItemDTO struct {
|
||||
Status string `json:"status"`
|
||||
HandoffStatus string `json:"handoff_status"`
|
||||
PaymentDeadlineAt *time.Time `json:"payment_deadline_at,omitempty"`
|
||||
DistributionSiteID *uint64 `json:"distribution_site_id,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package order
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"hfb_sys/backend/pkg/response"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -32,7 +34,8 @@ func (h *Handler) List(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
page, pageSize := parsePagination(c)
|
||||
items, err := h.service.ListForUser(c.Request.Context(), userID, page, pageSize)
|
||||
siteCode := strings.TrimSpace(firstNonEmpty(c.Query("distribution_site_code"), c.Query("site_code")))
|
||||
items, err := h.service.ListForUser(c.Request.Context(), userID, page, pageSize, siteCode)
|
||||
if err != nil {
|
||||
writeOrderError(c, err)
|
||||
return
|
||||
@@ -69,7 +72,8 @@ func (h *Handler) Detail(c *gin.Context) {
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
item, err := h.service.FindForUser(c.Request.Context(), userID, id)
|
||||
siteCode := strings.TrimSpace(firstNonEmpty(c.Query("distribution_site_code"), c.Query("site_code")))
|
||||
item, err := h.service.FindForUser(c.Request.Context(), userID, id, siteCode)
|
||||
if err != nil {
|
||||
writeOrderError(c, err)
|
||||
return
|
||||
|
||||
@@ -129,6 +129,7 @@ func (row orderRow) toAdminDTO() OrderDTO {
|
||||
DepositHeldAt: row.DepositHeldAt,
|
||||
DepositHoldReleasedAt: row.DepositHoldReleasedAt,
|
||||
AdminActions: adminActionsForOrder(row.RentalOrder),
|
||||
DistributionSiteID: row.DistributionSiteID,
|
||||
CreatedAt: row.CreatedAt,
|
||||
UpdatedAt: row.UpdatedAt,
|
||||
}
|
||||
@@ -187,6 +188,7 @@ func (row orderRow) toUserListItem(userID uint64, paymentDeadlineAt *time.Time)
|
||||
Status: row.Status,
|
||||
HandoffStatus: row.HandoffStatus,
|
||||
PaymentDeadlineAt: paymentDeadlineAt,
|
||||
DistributionSiteID: row.DistributionSiteID,
|
||||
CreatedAt: row.CreatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,13 +11,25 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func (r *Repository) ListForUser(ctx context.Context, userID uint64, page, pageSize int) (*UserPaginatedResult, error) {
|
||||
func (r *Repository) ListForUser(ctx context.Context, userID uint64, page, pageSize int, siteCode ...string) (*UserPaginatedResult, error) {
|
||||
page, pageSize = normalizePagination(page, pageSize)
|
||||
base := r.baseQuery(ctx).Where("o.renter_id = ? OR o.owner_id = ?", userID, userID)
|
||||
countBase := r.db.WithContext(ctx).Table("rental_orders AS o").Where("o.renter_id = ? OR o.owner_id = ?", userID, userID)
|
||||
|
||||
var code string
|
||||
if len(siteCode) > 0 {
|
||||
code = strings.TrimSpace(siteCode[0])
|
||||
}
|
||||
if code != "" {
|
||||
base = base.Joins("INNER JOIN distribution_sites AS ds ON ds.id = o.distribution_site_id AND ds.site_code = ?", code)
|
||||
countBase = countBase.Joins("INNER JOIN distribution_sites AS ds ON ds.id = o.distribution_site_id AND ds.site_code = ?", code)
|
||||
} else {
|
||||
base = base.Where("o.distribution_site_id IS NULL OR o.distribution_site_id = 0")
|
||||
countBase = countBase.Where("o.distribution_site_id IS NULL OR o.distribution_site_id = 0")
|
||||
}
|
||||
|
||||
var total int64
|
||||
if err := r.db.WithContext(ctx).Table("rental_orders AS o").
|
||||
Where("o.renter_id = ? OR o.owner_id = ?", userID, userID).
|
||||
Count(&total).Error; err != nil {
|
||||
if err := countBase.Count(&total).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var rows []orderRow
|
||||
@@ -308,12 +320,22 @@ func (r *Repository) FindLatestAdminByListing(ctx context.Context, listingID uin
|
||||
return &dto, nil
|
||||
}
|
||||
|
||||
func (r *Repository) FindForUser(ctx context.Context, userID uint64, orderID uint64) (*OrderDTO, error) {
|
||||
func (r *Repository) FindForUser(ctx context.Context, userID uint64, orderID uint64, siteCode ...string) (*OrderDTO, error) {
|
||||
var row orderRow
|
||||
db := r.db.WithContext(ctx)
|
||||
if err := r.baseQuery(ctx).
|
||||
Where("o.id = ? AND (o.renter_id = ? OR o.owner_id = ?)", orderID, userID, userID).
|
||||
First(&row).Error; err != nil {
|
||||
query := r.baseQuery(ctx).Where("o.id = ? AND (o.renter_id = ? OR o.owner_id = ?)", orderID, userID, userID)
|
||||
|
||||
var code string
|
||||
if len(siteCode) > 0 {
|
||||
code = strings.TrimSpace(siteCode[0])
|
||||
}
|
||||
if code != "" {
|
||||
query = query.Joins("INNER JOIN distribution_sites AS ds ON ds.id = o.distribution_site_id AND ds.site_code = ?", code)
|
||||
} else if len(siteCode) > 0 {
|
||||
query = query.Where("o.distribution_site_id IS NULL OR o.distribution_site_id = 0")
|
||||
}
|
||||
|
||||
if err := query.First(&row).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
dto := row.toDTOForUser(userID)
|
||||
|
||||
@@ -1884,3 +1884,91 @@ func TestAdminPlatformCheckoutConfirmRequiresExplicitConfirmationForZeroOwnerInc
|
||||
t.Fatalf("确认零收入后订单状态 = %s, want %s", completed.Status, orderStatusCompleted)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListForUserAndFindForUserSiteIsolation(t *testing.T) {
|
||||
db := setupOrderTestDB(t)
|
||||
if err := db.AutoMigrate(&model.DistributionSite{}); err != nil {
|
||||
t.Fatalf("migrate distribution_sites err: %v", err)
|
||||
}
|
||||
repo := NewRepository(db)
|
||||
|
||||
owner := model.User{Phone: "13800000010"}
|
||||
db.Create(&owner)
|
||||
renter := model.User{Phone: "13800000020"}
|
||||
db.Create(&renter)
|
||||
|
||||
account := model.GameAccount{OwnerID: owner.ID, Title: "隔离测试账号", Status: "active"}
|
||||
db.Create(&account)
|
||||
listing := model.RentalListing{ListingNo: "L30001", AccountID: account.ID, OwnerID: owner.ID, Status: "published", ReviewStatus: "approved", PriceCent: 1000}
|
||||
db.Create(&listing)
|
||||
|
||||
site := model.DistributionSite{
|
||||
SiteCode: "site_isolate_1",
|
||||
SiteName: "隔离分销站",
|
||||
Domain: "isolate.com",
|
||||
Status: "active",
|
||||
DisplayAccountEnabled: true,
|
||||
}
|
||||
db.Create(&site)
|
||||
|
||||
// Order 1: on main site (distribution_site_id is nil)
|
||||
mainOrder := model.RentalOrder{
|
||||
OrderNo: "RO_MAIN_001",
|
||||
ListingID: listing.ID,
|
||||
AccountID: account.ID,
|
||||
OwnerID: owner.ID,
|
||||
RenterID: renter.ID,
|
||||
Status: orderStatusCompleted,
|
||||
}
|
||||
db.Create(&mainOrder)
|
||||
|
||||
// Order 2: on distribution site (distribution_site_id = site.ID)
|
||||
distOrder := model.RentalOrder{
|
||||
OrderNo: "RO_DIST_001",
|
||||
ListingID: listing.ID,
|
||||
AccountID: account.ID,
|
||||
OwnerID: owner.ID,
|
||||
RenterID: renter.ID,
|
||||
Status: orderStatusCompleted,
|
||||
DistributionSiteID: &site.ID,
|
||||
}
|
||||
db.Create(&distOrder)
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
// 1. Query with site_code = "site_isolate_1": should return ONLY distOrder
|
||||
distList, err := repo.ListForUser(ctx, renter.ID, 1, 20, "site_isolate_1")
|
||||
if err != nil {
|
||||
t.Fatalf("ListForUser distribution err: %v", err)
|
||||
}
|
||||
if len(distList.Items) != 1 || distList.Items[0].OrderNo != "RO_DIST_001" {
|
||||
t.Fatalf("expected only RO_DIST_001, got %+v", distList.Items)
|
||||
}
|
||||
|
||||
// 2. Query without siteCode (main site mode): should return ONLY mainOrder
|
||||
mainList, err := repo.ListForUser(ctx, renter.ID, 1, 20, "")
|
||||
if err != nil {
|
||||
t.Fatalf("ListForUser main err: %v", err)
|
||||
}
|
||||
if len(mainList.Items) != 1 || mainList.Items[0].OrderNo != "RO_MAIN_001" {
|
||||
t.Fatalf("expected only RO_MAIN_001, got %+v", mainList.Items)
|
||||
}
|
||||
|
||||
// 3. FindForUser: distOrder found under "site_isolate_1"
|
||||
dItem, err := repo.FindForUser(ctx, renter.ID, distOrder.ID, "site_isolate_1")
|
||||
if err != nil || dItem.OrderNo != "RO_DIST_001" {
|
||||
t.Fatalf("FindForUser distOrder failed: %v", err)
|
||||
}
|
||||
|
||||
// 4. FindForUser: mainOrder CANNOT be accessed under "site_isolate_1"
|
||||
_, err = repo.FindForUser(ctx, renter.ID, mainOrder.ID, "site_isolate_1")
|
||||
if err == nil {
|
||||
t.Fatalf("expected error accessing mainOrder under distribution site, got nil")
|
||||
}
|
||||
|
||||
// 5. FindForUser: distOrder CANNOT be accessed under main site mode ("")
|
||||
_, err = repo.FindForUser(ctx, renter.ID, distOrder.ID, "")
|
||||
if err == nil {
|
||||
t.Fatalf("expected error accessing distOrder under main site mode, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -148,11 +148,11 @@ func (s *Service) AcceptCheckout(ctx context.Context, userID uint64, orderID uin
|
||||
return s.repo.AcceptCheckout(ctx, userID, orderID)
|
||||
}
|
||||
|
||||
func (s *Service) ListForUser(ctx context.Context, userID uint64, page, pageSize int) (*UserPaginatedResult, error) {
|
||||
func (s *Service) ListForUser(ctx context.Context, userID uint64, page, pageSize int, siteCode ...string) (*UserPaginatedResult, error) {
|
||||
if s.repo == nil {
|
||||
return nil, ErrDependencyUnavailable
|
||||
}
|
||||
return s.repo.ListForUser(ctx, userID, page, pageSize)
|
||||
return s.repo.ListForUser(ctx, userID, page, pageSize, siteCode...)
|
||||
}
|
||||
|
||||
func (s *Service) ListSellerHandoffs(ctx context.Context, userID uint64, query SellerHandoffQuery) (*SellerHandoffPaginatedResult, error) {
|
||||
@@ -377,9 +377,9 @@ func (s *Service) PendingRefundCount(ctx context.Context) (int64, error) {
|
||||
return s.repo.PendingRefundCount(ctx)
|
||||
}
|
||||
|
||||
func (s *Service) FindForUser(ctx context.Context, userID uint64, orderID uint64) (*OrderDTO, error) {
|
||||
func (s *Service) FindForUser(ctx context.Context, userID uint64, orderID uint64, siteCode ...string) (*OrderDTO, error) {
|
||||
if s.repo == nil {
|
||||
return nil, ErrDependencyUnavailable
|
||||
}
|
||||
return s.repo.FindForUser(ctx, userID, orderID)
|
||||
return s.repo.FindForUser(ctx, userID, orderID, siteCode...)
|
||||
}
|
||||
|
||||
@@ -414,6 +414,8 @@ func New(cfg config.Config, deps Dependencies, logger *zap.Logger) *gin.Engine {
|
||||
api.GET("/home-announcements", systemConfigHandler.HomeAnnouncements)
|
||||
api.GET("/mobile-home-config", systemConfigHandler.HomeConfig)
|
||||
api.GET("/public/files/object", fileHandler.PublicObject)
|
||||
api.GET("/distribution/sites/:site_code/listings", distributionHandler.ListPublicSiteListings)
|
||||
api.GET("/distribution/site-info", distributionHandler.GetPublicSiteInfo)
|
||||
api.POST("/payments/leshua/notify", paymentHandler.LeshuaNotify)
|
||||
api.POST("/payments/lakala/notify", paymentHandler.LakalaNotify)
|
||||
api.POST("/payments/shuncheng/notify", paymentHandler.ShunchengNotify)
|
||||
@@ -602,6 +604,7 @@ func New(cfg config.Config, deps Dependencies, logger *zap.Logger) *gin.Engine {
|
||||
{
|
||||
distributionProtectedRoutes.GET("/auth/me", distributionHandler.Me)
|
||||
distributionProtectedRoutes.POST("/auth/logout", distributionHandler.Logout)
|
||||
distributionProtectedRoutes.POST("/sites/:id/sync-accounts", distributionHandler.SyncSiteAccounts)
|
||||
}
|
||||
|
||||
adminRoutes := api.Group("/admin", requireAdmin, middleware.RequireAdminPasswordChanged())
|
||||
@@ -617,6 +620,7 @@ func New(cfg config.Config, deps Dependencies, logger *zap.Logger) *gin.Engine {
|
||||
adminRoutes.GET("/distribution/sites/:id", requirePerm("distribution:site_view"), distributionHandler.GetSite)
|
||||
adminRoutes.POST("/distribution/sites", requirePerm("distribution:site_manage"), distributionHandler.CreateSite)
|
||||
adminRoutes.POST("/distribution/sites/onboard", requirePerm("distribution:site_manage"), distributionHandler.OnboardSite)
|
||||
adminRoutes.POST("/distribution/sites/:id/sync-accounts", requirePerm("distribution:account_display"), distributionHandler.SyncSiteAccounts)
|
||||
adminRoutes.PUT("/distribution/sites/:id", requirePerm("distribution:site_manage"), distributionHandler.UpdateSite)
|
||||
adminRoutes.GET("/distribution/rules", requirePerm("distribution:rule_view"), distributionHandler.ListRules)
|
||||
adminRoutes.POST("/distribution/rules", requirePerm("distribution:rule_manage"), distributionHandler.CreateRule)
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
AccountBookOutlined,
|
||||
ApiOutlined,
|
||||
DashboardOutlined,
|
||||
EyeOutlined,
|
||||
FileSearchOutlined,
|
||||
LogoutOutlined,
|
||||
SettingOutlined,
|
||||
@@ -20,6 +21,7 @@ import Accounts from './pages/Accounts'
|
||||
import Settlements from './pages/Settlements'
|
||||
import Orders from './pages/Orders'
|
||||
import Login from './pages/Login'
|
||||
import Storefront from './pages/Storefront'
|
||||
import './style.css'
|
||||
|
||||
type MenuItem = Required<MenuProps>['items'][number] & { superadminOnly?: boolean }
|
||||
@@ -83,6 +85,26 @@ function MainLayout({ member, onLogout }: { member: CurrentMember; onLogout: ()
|
||||
</div>
|
||||
<div className="header-right">
|
||||
<Space size="middle">
|
||||
{member.site_code && (
|
||||
<Button
|
||||
type="primary"
|
||||
ghost
|
||||
icon={<EyeOutlined />}
|
||||
size="small"
|
||||
onClick={() => {
|
||||
const isLocal = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1'
|
||||
const targetUrl = isLocal
|
||||
? `http://${window.location.hostname}:5189/?site=${member.site_code}`
|
||||
: member.domain
|
||||
? `https://${member.domain}`
|
||||
: `/?site=${member.site_code}`
|
||||
window.open(targetUrl, '_blank')
|
||||
}}
|
||||
style={{ borderColor: '#1677ff', color: '#1677ff' }}
|
||||
>
|
||||
预览分销前台商城 ↗
|
||||
</Button>
|
||||
)}
|
||||
<div className="user-profile">
|
||||
<UserOutlined style={{ color: '#1677ff' }} />
|
||||
<Typography.Text strong style={{ fontSize: 13 }}>
|
||||
@@ -127,9 +149,24 @@ function AppContent() {
|
||||
const navigate = useNavigate()
|
||||
const location = useLocation()
|
||||
|
||||
const isPublicStorefront = location.pathname.startsWith('/site')
|
||||
|
||||
useEffect(() => {
|
||||
let active = true
|
||||
const checkAuth = async () => {
|
||||
// For public storefront, we do not force login
|
||||
if (isPublicStorefront) {
|
||||
try {
|
||||
const profile = await getMe()
|
||||
if (active) setMember(profile)
|
||||
} catch {
|
||||
// ignore auth error on public storefront
|
||||
} finally {
|
||||
if (active) setLoading(false)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// If no token exists and no session, skip getMe
|
||||
if (!getStoredToken() && location.pathname === '/login') {
|
||||
if (active) setLoading(false)
|
||||
@@ -158,7 +195,7 @@ function AppContent() {
|
||||
return () => {
|
||||
active = false
|
||||
}
|
||||
}, [location.pathname, navigate])
|
||||
}, [location.pathname, navigate, isPublicStorefront])
|
||||
|
||||
const handleLogout = async () => {
|
||||
await logout()
|
||||
@@ -171,6 +208,16 @@ function AppContent() {
|
||||
navigate('/', { replace: true })
|
||||
}
|
||||
|
||||
if (isPublicStorefront) {
|
||||
return (
|
||||
<Routes>
|
||||
<Route path="/site" element={<Navigate to="/site/demo" replace />} />
|
||||
<Route path="/site/:siteCode" element={<Storefront />} />
|
||||
<Route path="*" element={<Navigate to="/" replace />} />
|
||||
</Routes>
|
||||
)
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div style={{ height: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
|
||||
|
||||
@@ -170,6 +170,61 @@ export interface AccountDisplay {
|
||||
account_id: number
|
||||
listing_id: number
|
||||
display_status: string
|
||||
listing_no?: string
|
||||
title?: string
|
||||
game_name?: string
|
||||
server_region?: string
|
||||
login_platform?: string
|
||||
rank_level?: string
|
||||
haf_coin_amount?: number
|
||||
price_cent?: number
|
||||
deposit_amount_cent?: number
|
||||
listing_status?: string
|
||||
in_transaction?: boolean
|
||||
}
|
||||
|
||||
export interface SyncSiteAccountsResult {
|
||||
synced_count: number
|
||||
skipped_count: number
|
||||
total_active: number
|
||||
}
|
||||
|
||||
export interface PublicDistributionListing {
|
||||
listing_id: number
|
||||
listing_no: string
|
||||
account_id: number
|
||||
title: string
|
||||
game_name: string
|
||||
server_region: string
|
||||
login_platform: string
|
||||
rank_level: string
|
||||
haf_coin_amount: number
|
||||
price_cent: number
|
||||
deposit_amount_cent: number
|
||||
in_transaction: boolean
|
||||
site_code: string
|
||||
site_name: string
|
||||
}
|
||||
|
||||
export interface PublicDistributionListingsResult {
|
||||
items: PublicDistributionListing[]
|
||||
total: number
|
||||
page: number
|
||||
page_size: number
|
||||
}
|
||||
|
||||
export async function fetchPublicSiteListings(
|
||||
siteCode: string,
|
||||
page = 1,
|
||||
pageSize = 24,
|
||||
): Promise<PublicDistributionListingsResult> {
|
||||
const resp = await api.get<ApiResponse<PublicDistributionListingsResult>>(
|
||||
`/distribution/sites/${siteCode}/listings`,
|
||||
{
|
||||
params: { page, page_size: pageSize },
|
||||
},
|
||||
)
|
||||
return extract(resp)
|
||||
}
|
||||
|
||||
export interface PaymentChannel {
|
||||
@@ -297,6 +352,11 @@ export async function updateAccountDisplay(id: number, displayStatus: string): P
|
||||
return extract(resp)
|
||||
}
|
||||
|
||||
export async function syncSiteAccounts(siteID: number): Promise<SyncSiteAccountsResult> {
|
||||
const resp = await api.post<ApiResponse<SyncSiteAccountsResult>>(`/admin/distribution/sites/${siteID}/sync-accounts`)
|
||||
return extract(resp)
|
||||
}
|
||||
|
||||
export async function listPaymentChannels(siteID: number): Promise<PaymentChannel[]> {
|
||||
const resp = await api.get<ApiResponse<{ items: PaymentChannel[] }>>('/admin/distribution/payment-channels', {
|
||||
params: { site_id: siteID },
|
||||
|
||||
@@ -1,20 +1,32 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { Card, Table, Typography, Space, Select, Tag, message } from 'antd'
|
||||
import { listAccountDisplays, listSites, updateAccountDisplay, type AccountDisplay, type Site } from '../api'
|
||||
import { useEffect, useState, useMemo } from 'react'
|
||||
import { Card, Table, Typography, Space, Select, Tag, message, Button, Input, Modal } from 'antd'
|
||||
import { SyncOutlined, SearchOutlined, CheckCircleOutlined, StopOutlined } from '@ant-design/icons'
|
||||
import {
|
||||
listAccountDisplays,
|
||||
listSites,
|
||||
updateAccountDisplay,
|
||||
syncSiteAccounts,
|
||||
formatMoney,
|
||||
type AccountDisplay,
|
||||
type Site,
|
||||
} from '../api'
|
||||
|
||||
const STATUS_LABELS: Record<string, string> = {
|
||||
enabled: '展示中',
|
||||
disabled: '已下架',
|
||||
sold: '已售出',
|
||||
offline: '已离线',
|
||||
const STATUS_LABELS: Record<string, { label: string; color: string }> = {
|
||||
enabled: { label: '展示中', color: 'success' },
|
||||
disabled: { label: '已下架', color: 'default' },
|
||||
sold: { label: '已售出', color: 'blue' },
|
||||
offline: { label: '已离线', color: 'error' },
|
||||
}
|
||||
|
||||
export default function Accounts() {
|
||||
const [sites, setSites] = useState<Site[]>([])
|
||||
const [siteID, setSiteID] = useState<number>()
|
||||
const [status, setStatus] = useState<string>('')
|
||||
const [keyword, setKeyword] = useState<string>('')
|
||||
const [items, setItems] = useState<AccountDisplay[]>([])
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [syncing, setSyncing] = useState(false)
|
||||
const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([])
|
||||
|
||||
async function load(site?: number, statusFilter?: string) {
|
||||
if (!site) return
|
||||
@@ -40,6 +52,27 @@ export default function Accounts() {
|
||||
.catch(() => message.error('站点加载失败'))
|
||||
}, [])
|
||||
|
||||
async function handleSync() {
|
||||
if (!siteID) {
|
||||
message.warning('请先选择分销站点')
|
||||
return
|
||||
}
|
||||
setSyncing(true)
|
||||
try {
|
||||
const res = await syncSiteAccounts(siteID)
|
||||
message.success(
|
||||
`同步完成!新增可售账号 ${res.synced_count} 个,已存在 ${res.skipped_count} 个(主站当前在售总数 ${res.total_active})`,
|
||||
5,
|
||||
)
|
||||
await load(siteID, status)
|
||||
} catch (error: unknown) {
|
||||
const respMessage = (error as { response?: { data?: { message?: string } } })?.response?.data?.message
|
||||
message.error(respMessage ?? '同步主站商品失败')
|
||||
} finally {
|
||||
setSyncing(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function toggle(item: AccountDisplay) {
|
||||
const next = item.display_status === 'enabled' ? 'disabled' : 'enabled'
|
||||
try {
|
||||
@@ -52,49 +85,237 @@ export default function Accounts() {
|
||||
}
|
||||
}
|
||||
|
||||
async function handleBatchUpdate(targetStatus: 'enabled' | 'disabled') {
|
||||
if (selectedRowKeys.length === 0) {
|
||||
message.warning('请先勾选需要批量操作的账号')
|
||||
return
|
||||
}
|
||||
const actionLabel = targetStatus === 'enabled' ? '批量恢复展示' : '批量下架'
|
||||
Modal.confirm({
|
||||
title: `确认${actionLabel}?`,
|
||||
content: `即将对选中的 ${selectedRowKeys.length} 个账号执行${actionLabel}操作。`,
|
||||
onOk: async () => {
|
||||
let successCount = 0
|
||||
for (const id of selectedRowKeys) {
|
||||
try {
|
||||
await updateAccountDisplay(Number(id), targetStatus)
|
||||
successCount++
|
||||
} catch {
|
||||
// continue next
|
||||
}
|
||||
}
|
||||
message.success(`已完成 ${successCount}/${selectedRowKeys.length} 个账号的${actionLabel}`)
|
||||
setSelectedRowKeys([])
|
||||
if (siteID) void load(siteID, status)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const filteredItems = useMemo(() => {
|
||||
const kw = keyword.trim().toLowerCase()
|
||||
if (!kw) return items
|
||||
return items.filter(
|
||||
(item) =>
|
||||
(item.title && item.title.toLowerCase().includes(kw)) ||
|
||||
(item.listing_no && item.listing_no.toLowerCase().includes(kw)) ||
|
||||
(item.game_name && item.game_name.toLowerCase().includes(kw)) ||
|
||||
(item.server_region && item.server_region.toLowerCase().includes(kw)),
|
||||
)
|
||||
}, [items, keyword])
|
||||
|
||||
const currentSite = sites.find((s) => s.id === siteID)
|
||||
|
||||
return (
|
||||
<Space direction="vertical" className="page">
|
||||
<Typography.Title level={3}>账号展示</Typography.Title>
|
||||
<Space>
|
||||
<Select
|
||||
placeholder="分销网站"
|
||||
style={{ width: 200 }}
|
||||
value={siteID}
|
||||
options={sites.map((site) => ({ label: site.site_name, value: site.id }))}
|
||||
onChange={(value) => {
|
||||
setSiteID(value)
|
||||
void load(value, status)
|
||||
}}
|
||||
/>
|
||||
<Select
|
||||
allowClear
|
||||
placeholder="展示状态"
|
||||
style={{ width: 140 }}
|
||||
options={Object.entries(STATUS_LABELS).map(([value, label]) => ({ label, value }))}
|
||||
onChange={(value) => {
|
||||
setStatus(value ?? '')
|
||||
void load(siteID, value ?? '')
|
||||
}}
|
||||
/>
|
||||
</Space>
|
||||
<Space direction="vertical" className="page" style={{ width: '100%' }}>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
|
||||
<div>
|
||||
<Typography.Title level={3} style={{ marginBottom: 4 }}>
|
||||
商品与账号展示
|
||||
</Typography.Title>
|
||||
<Typography.Text type="secondary">
|
||||
管理当前分销网站对外展示与销售的游戏账号商品,支持实时从主站同步最新上架货源。
|
||||
</Typography.Text>
|
||||
</div>
|
||||
<Button
|
||||
type="primary"
|
||||
icon={<SyncOutlined spin={syncing} />}
|
||||
loading={syncing}
|
||||
onClick={handleSync}
|
||||
style={{ background: '#1677ff' }}
|
||||
>
|
||||
一键同步主站商品
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<Card size="small">
|
||||
<Space wrap style={{ width: '100%', justifyContent: 'space-between' }}>
|
||||
<Space wrap>
|
||||
<Select
|
||||
placeholder="分销网站"
|
||||
style={{ width: 220 }}
|
||||
value={siteID}
|
||||
options={sites.map((site) => ({
|
||||
label: `${site.site_name} (${site.site_code})`,
|
||||
value: site.id,
|
||||
}))}
|
||||
onChange={(value) => {
|
||||
setSiteID(value)
|
||||
setSelectedRowKeys([])
|
||||
void load(value, status)
|
||||
}}
|
||||
/>
|
||||
<Select
|
||||
allowClear
|
||||
placeholder="展示状态"
|
||||
style={{ width: 140 }}
|
||||
value={status || undefined}
|
||||
options={Object.entries(STATUS_LABELS).map(([value, conf]) => ({
|
||||
label: conf.label,
|
||||
value,
|
||||
}))}
|
||||
onChange={(value) => {
|
||||
setStatus(value ?? '')
|
||||
void load(siteID, value ?? '')
|
||||
}}
|
||||
/>
|
||||
<Input
|
||||
placeholder="搜索商品编号/标题/区服"
|
||||
prefix={<SearchOutlined />}
|
||||
style={{ width: 240 }}
|
||||
allowClear
|
||||
value={keyword}
|
||||
onChange={(e) => setKeyword(e.target.value)}
|
||||
/>
|
||||
</Space>
|
||||
|
||||
{selectedRowKeys.length > 0 && (
|
||||
<Space>
|
||||
<Typography.Text type="secondary">已勾选 {selectedRowKeys.length} 项</Typography.Text>
|
||||
<Button
|
||||
size="small"
|
||||
icon={<CheckCircleOutlined />}
|
||||
onClick={() => handleBatchUpdate('enabled')}
|
||||
>
|
||||
批量展示
|
||||
</Button>
|
||||
<Button
|
||||
size="small"
|
||||
danger
|
||||
icon={<StopOutlined />}
|
||||
onClick={() => handleBatchUpdate('disabled')}
|
||||
>
|
||||
批量下架
|
||||
</Button>
|
||||
</Space>
|
||||
)}
|
||||
</Space>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<Table
|
||||
rowKey="id"
|
||||
loading={loading}
|
||||
dataSource={items}
|
||||
pagination={{ pageSize: 20 }}
|
||||
dataSource={filteredItems}
|
||||
rowSelection={{
|
||||
selectedRowKeys,
|
||||
onChange: setSelectedRowKeys,
|
||||
}}
|
||||
pagination={{
|
||||
pageSize: 20,
|
||||
showTotal: (total) => `共 ${total} 个账号商品`,
|
||||
showQuickJumper: true,
|
||||
}}
|
||||
columns={[
|
||||
{ title: '账号 ID', dataIndex: 'account_id' },
|
||||
{ title: '商品 ID', dataIndex: 'listing_id' },
|
||||
{
|
||||
title: '展示状态',
|
||||
title: '商品编号',
|
||||
dataIndex: 'listing_no',
|
||||
width: 140,
|
||||
render: (v: string | undefined, row: AccountDisplay) => (
|
||||
<Space direction="vertical" size={2}>
|
||||
<Typography.Text copyable strong>
|
||||
{v || `#${row.listing_id}`}
|
||||
</Typography.Text>
|
||||
{row.in_transaction && <Tag color="warning">出租中</Tag>}
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '账号信息',
|
||||
dataIndex: 'title',
|
||||
minWidth: 240,
|
||||
render: (_: unknown, row: AccountDisplay) => (
|
||||
<div>
|
||||
<Typography.Text strong style={{ display: 'block', fontSize: 14 }}>
|
||||
{row.title || `账号 #${row.account_id}`}
|
||||
</Typography.Text>
|
||||
<Space size={4} style={{ marginTop: 4 }}>
|
||||
<Tag color="blue">{row.game_name || '默认游戏'}</Tag>
|
||||
{row.server_region && <Tag>{row.server_region}</Tag>}
|
||||
{row.login_platform && <Tag>{row.login_platform}</Tag>}
|
||||
</Space>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '段位 / 资产',
|
||||
width: 140,
|
||||
render: (_: unknown, row: AccountDisplay) => (
|
||||
<div>
|
||||
<div>{row.rank_level ? <Tag color="purple">{row.rank_level}</Tag> : '-'}</div>
|
||||
{row.haf_coin_amount !== undefined && row.haf_coin_amount > 0 && (
|
||||
<Typography.Text type="secondary" style={{ fontSize: 12 }}>
|
||||
哈夫币: {row.haf_coin_amount.toLocaleString()}
|
||||
</Typography.Text>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '租金 / 押金',
|
||||
width: 160,
|
||||
render: (_: unknown, row: AccountDisplay) => (
|
||||
<div>
|
||||
<Typography.Text strong style={{ color: '#cf1322' }}>
|
||||
{formatMoney(row.price_cent)}
|
||||
<span style={{ fontSize: 12, fontWeight: 'normal', color: '#888' }}> /小时</span>
|
||||
</Typography.Text>
|
||||
<div style={{ fontSize: 12, color: '#666' }}>
|
||||
押金: {formatMoney(row.deposit_amount_cent)}
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '主站状态',
|
||||
dataIndex: 'listing_status',
|
||||
width: 110,
|
||||
render: (v: string | undefined) => (
|
||||
<Tag color={v === 'published' ? 'green' : 'default'}>
|
||||
{v === 'published' ? '主站在售' : v || '未知'}
|
||||
</Tag>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '分销展示',
|
||||
dataIndex: 'display_status',
|
||||
render: (v: string) => <Tag color={v === 'enabled' ? 'green' : 'default'}>{STATUS_LABELS[v] ?? v}</Tag>,
|
||||
width: 110,
|
||||
render: (v: string) => {
|
||||
const conf = STATUS_LABELS[v] ?? { label: v, color: 'default' }
|
||||
return <Tag color={conf.color}>{conf.label}</Tag>
|
||||
},
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
width: 120,
|
||||
render: (_: unknown, row: AccountDisplay) => (
|
||||
<a onClick={() => toggle(row)}>{row.display_status === 'enabled' ? '下架' : '恢复展示'}</a>
|
||||
<Button
|
||||
type="link"
|
||||
size="small"
|
||||
danger={row.display_status === 'enabled'}
|
||||
onClick={() => toggle(row)}
|
||||
>
|
||||
{row.display_status === 'enabled' ? '下架' : '恢复展示'}
|
||||
</Button>
|
||||
),
|
||||
},
|
||||
]}
|
||||
|
||||
@@ -0,0 +1,544 @@
|
||||
import { useEffect, useState, useMemo } from 'react'
|
||||
import { useParams, Link } from 'react-router-dom'
|
||||
import {
|
||||
Layout,
|
||||
Typography,
|
||||
Space,
|
||||
Input,
|
||||
Radio,
|
||||
Card,
|
||||
Tag,
|
||||
Button,
|
||||
Modal,
|
||||
Empty,
|
||||
Spin,
|
||||
Badge,
|
||||
message,
|
||||
Descriptions,
|
||||
Divider,
|
||||
} from 'antd'
|
||||
import {
|
||||
ShopOutlined,
|
||||
SearchOutlined,
|
||||
SafetyCertificateOutlined,
|
||||
ThunderboltOutlined,
|
||||
CustomerServiceOutlined,
|
||||
CopyOutlined,
|
||||
CheckCircleOutlined,
|
||||
RightCircleOutlined,
|
||||
RocketOutlined,
|
||||
FireOutlined,
|
||||
} from '@ant-design/icons'
|
||||
import {
|
||||
fetchPublicSiteListings,
|
||||
formatMoney,
|
||||
type PublicDistributionListing,
|
||||
} from '../api'
|
||||
|
||||
export default function Storefront() {
|
||||
const { siteCode = 'demo' } = useParams<{ siteCode: string }>()
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [items, setItems] = useState<PublicDistributionListing[]>([])
|
||||
const [siteName, setSiteName] = useState<string>('')
|
||||
const [keyword, setKeyword] = useState<string>('')
|
||||
const [gameFilter, setGameFilter] = useState<string>('all')
|
||||
const [sortOrder, setSortOrder] = useState<'default' | 'price_asc' | 'price_desc'>('default')
|
||||
const [selectedListing, setSelectedListing] = useState<PublicDistributionListing | null>(null)
|
||||
const [csModalVisible, setCsModalVisible] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
let active = true
|
||||
setLoading(true)
|
||||
fetchPublicSiteListings(siteCode, 1, 100)
|
||||
.then((res) => {
|
||||
if (!active) return
|
||||
setItems(res.items || [])
|
||||
if (res.items && res.items.length > 0) {
|
||||
setSiteName(res.items[0].site_name)
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
if (active) {
|
||||
message.error('加载分销商城商品失败,请检查站点标识')
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (active) setLoading(false)
|
||||
})
|
||||
|
||||
return () => {
|
||||
active = false
|
||||
}
|
||||
}, [siteCode])
|
||||
|
||||
const displayName = siteName || `${siteCode.toUpperCase()} 专属分销商城`
|
||||
|
||||
const filteredItems = useMemo(() => {
|
||||
let list = [...items]
|
||||
if (gameFilter !== 'all') {
|
||||
list = list.filter((i) => (i.game_name || '').toLowerCase() === gameFilter.toLowerCase())
|
||||
}
|
||||
const kw = keyword.trim().toLowerCase()
|
||||
if (kw) {
|
||||
list = list.filter(
|
||||
(i) =>
|
||||
(i.title && i.title.toLowerCase().includes(kw)) ||
|
||||
(i.listing_no && i.listing_no.toLowerCase().includes(kw)) ||
|
||||
(i.server_region && i.server_region.toLowerCase().includes(kw)) ||
|
||||
(i.login_platform && i.login_platform.toLowerCase().includes(kw)) ||
|
||||
(i.rank_level && i.rank_level.toLowerCase().includes(kw)),
|
||||
)
|
||||
}
|
||||
if (sortOrder === 'price_asc') {
|
||||
list.sort((a, b) => a.price_cent - b.price_cent)
|
||||
} else if (sortOrder === 'price_desc') {
|
||||
list.sort((a, b) => b.price_cent - a.price_cent)
|
||||
}
|
||||
return list
|
||||
}, [items, gameFilter, keyword, sortOrder])
|
||||
|
||||
function handleCopyListingNo(no: string) {
|
||||
navigator.clipboard?.writeText(no)
|
||||
message.success(`已复制商品编号:${no}`)
|
||||
}
|
||||
|
||||
function handleRentNow(listing: PublicDistributionListing) {
|
||||
setSelectedListing(listing)
|
||||
}
|
||||
|
||||
function openMainCheckout(listing: PublicDistributionListing) {
|
||||
const mainHost = window.location.hostname
|
||||
// 默认主站前台运行在 5189 端口,生产环境通过域名反代
|
||||
const mainUrl = window.location.port
|
||||
? `http://${mainHost}:5189/orders/create?listing_id=${listing.listing_id}&site_code=${listing.site_code}`
|
||||
: `/orders/create?listing_id=${listing.listing_id}&site_code=${listing.site_code}`
|
||||
window.open(mainUrl, '_blank')
|
||||
}
|
||||
|
||||
return (
|
||||
<Layout style={{ minHeight: '100vh', background: '#0f172a' }}>
|
||||
{/* 顶部导航栏 */}
|
||||
<Layout.Header
|
||||
style={{
|
||||
background: 'rgba(15, 23, 42, 0.95)',
|
||||
backdropFilter: 'blur(8px)',
|
||||
borderBottom: '1px solid rgba(255, 255, 255, 0.1)',
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
padding: '0 24px',
|
||||
position: 'sticky',
|
||||
top: 0,
|
||||
zIndex: 100,
|
||||
}}
|
||||
>
|
||||
<Space size="middle" align="center">
|
||||
<div
|
||||
style={{
|
||||
width: 38,
|
||||
height: 38,
|
||||
borderRadius: 8,
|
||||
background: 'linear-gradient(135deg, #2563eb, #3b82f6)',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
color: '#fff',
|
||||
boxShadow: '0 0 16px rgba(59, 130, 246, 0.5)',
|
||||
}}
|
||||
>
|
||||
<ShopOutlined style={{ fontSize: 20 }} />
|
||||
</div>
|
||||
<div>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
<Typography.Text strong style={{ color: '#fff', fontSize: 16 }}>
|
||||
{displayName}
|
||||
</Typography.Text>
|
||||
<Tag color="gold" style={{ margin: 0, fontSize: 11 }}>
|
||||
官方合作分销
|
||||
</Tag>
|
||||
</div>
|
||||
<Typography.Text style={{ color: '#94a3b8', fontSize: 11, display: 'block' }}>
|
||||
站点标识:{siteCode} · 主站直营货源保障
|
||||
</Typography.Text>
|
||||
</div>
|
||||
</Space>
|
||||
|
||||
<Space size="middle">
|
||||
<Button
|
||||
type="text"
|
||||
icon={<CustomerServiceOutlined />}
|
||||
style={{ color: '#e2e8f0' }}
|
||||
onClick={() => setCsModalVisible(true)}
|
||||
>
|
||||
联系专属客服
|
||||
</Button>
|
||||
<Link to="/">
|
||||
<Button size="small" style={{ background: 'rgba(255,255,255,0.08)', color: '#94a3b8', borderColor: 'rgba(255,255,255,0.15)' }}>
|
||||
分销商后台
|
||||
</Button>
|
||||
</Link>
|
||||
</Space>
|
||||
</Layout.Header>
|
||||
|
||||
{/* Hero Banner */}
|
||||
<div
|
||||
style={{
|
||||
background: 'linear-gradient(180deg, rgba(30, 41, 59, 0.8) 0%, rgba(15, 23, 42, 1) 100%)',
|
||||
padding: '36px 24px 24px',
|
||||
textAlign: 'center',
|
||||
borderBottom: '1px solid rgba(255, 255, 255, 0.05)',
|
||||
}}
|
||||
>
|
||||
<div style={{ maxWidth: 840, margin: '0 auto' }}>
|
||||
<Space direction="vertical" size={12}>
|
||||
<Tag color="blue" icon={<FireOutlined />} style={{ padding: '2px 10px', fontSize: 12 }}>
|
||||
实时同步主站精品号源 · 一键租号
|
||||
</Tag>
|
||||
<Typography.Title
|
||||
level={2}
|
||||
style={{
|
||||
color: '#fff',
|
||||
margin: 0,
|
||||
fontWeight: 700,
|
||||
letterSpacing: 1,
|
||||
}}
|
||||
>
|
||||
【{displayName}】精选游戏账号商城
|
||||
</Typography.Title>
|
||||
<Typography.Paragraph style={{ color: '#94a3b8', fontSize: 14, margin: '0 0 12px' }}>
|
||||
高阶战备 · 王者段位 · 百万哈夫币 · 极速自动交接 · 押金秒退担保
|
||||
</Typography.Paragraph>
|
||||
|
||||
<Space wrap size="large" style={{ justifyContent: 'center', marginTop: 8 }}>
|
||||
<div style={{ color: '#cbd5e1', fontSize: 13 }}>
|
||||
<ThunderboltOutlined style={{ color: '#38bdf8', marginRight: 6 }} />
|
||||
秒级自动交接上号
|
||||
</div>
|
||||
<div style={{ color: '#cbd5e1', fontSize: 13 }}>
|
||||
<SafetyCertificateOutlined style={{ color: '#34d399', marginRight: 6 }} />
|
||||
主站资金与资产存管
|
||||
</div>
|
||||
<div style={{ color: '#cbd5e1', fontSize: 13 }}>
|
||||
<CheckCircleOutlined style={{ color: '#fbbf24', marginRight: 6 }} />
|
||||
租期结束秒退押金
|
||||
</div>
|
||||
</Space>
|
||||
</Space>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 筛选与内容主体 */}
|
||||
<Layout.Content style={{ maxWidth: 1280, width: '100%', margin: '0 auto', padding: '24px 20px 60px' }}>
|
||||
{/* 筛选栏 */}
|
||||
<Card
|
||||
style={{
|
||||
background: '#1e293b',
|
||||
border: '1px solid rgba(255, 255, 255, 0.08)',
|
||||
marginBottom: 24,
|
||||
}}
|
||||
bodyStyle={{ padding: '16px 20px' }}
|
||||
>
|
||||
<Space direction="vertical" style={{ width: '100%' }} size={14}>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap', gap: 12 }}>
|
||||
<Space wrap>
|
||||
<Radio.Group
|
||||
value={gameFilter}
|
||||
onChange={(e) => setGameFilter(e.target.value)}
|
||||
buttonStyle="solid"
|
||||
>
|
||||
<Radio.Button value="all">全部游戏</Radio.Button>
|
||||
<Radio.Button value="delta_force">三角洲行动</Radio.Button>
|
||||
<Radio.Button value="honor_of_kings">王者荣耀</Radio.Button>
|
||||
</Radio.Group>
|
||||
|
||||
<Radio.Group
|
||||
value={sortOrder}
|
||||
onChange={(e) => setSortOrder(e.target.value)}
|
||||
size="middle"
|
||||
>
|
||||
<Radio.Button value="default">默认推荐</Radio.Button>
|
||||
<Radio.Button value="price_asc">租金从低到高</Radio.Button>
|
||||
<Radio.Button value="price_desc">租金从高到低</Radio.Button>
|
||||
</Radio.Group>
|
||||
</Space>
|
||||
|
||||
<Input
|
||||
placeholder="搜索账号标题 / 区服 / 段位"
|
||||
prefix={<SearchOutlined style={{ color: '#94a3b8' }} />}
|
||||
allowClear
|
||||
value={keyword}
|
||||
onChange={(e) => setKeyword(e.target.value)}
|
||||
style={{ width: 260, background: '#0f172a', borderColor: 'rgba(255,255,255,0.1)', color: '#fff' }}
|
||||
/>
|
||||
</div>
|
||||
</Space>
|
||||
</Card>
|
||||
|
||||
{/* 列表区域 */}
|
||||
{loading ? (
|
||||
<div style={{ textAlign: 'center', padding: '80px 0' }}>
|
||||
<Spin size="large" tip="正在载入在售商品..." />
|
||||
</div>
|
||||
) : filteredItems.length === 0 ? (
|
||||
<Card style={{ background: '#1e293b', border: '1px solid rgba(255, 255, 255, 0.08)', padding: '60px 0' }}>
|
||||
<Empty
|
||||
description={
|
||||
<span style={{ color: '#94a3b8' }}>
|
||||
{items.length === 0
|
||||
? '当前分销站点暂无上架商品,站长可通过分销后台一键同步主站商品。'
|
||||
: '未找到符合条件的账号商品,请更换搜索词重试。'}
|
||||
</span>
|
||||
}
|
||||
/>
|
||||
</Card>
|
||||
) : (
|
||||
<div
|
||||
style={{
|
||||
display: 'grid',
|
||||
gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))',
|
||||
gap: 20,
|
||||
}}
|
||||
>
|
||||
{filteredItems.map((item) => (
|
||||
<Card
|
||||
key={item.listing_id}
|
||||
hoverable
|
||||
style={{
|
||||
background: '#1e293b',
|
||||
borderColor: 'rgba(255, 255, 255, 0.08)',
|
||||
borderRadius: 10,
|
||||
overflow: 'hidden',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
transition: 'all 0.25s ease',
|
||||
}}
|
||||
bodyStyle={{ padding: 16, display: 'flex', flexDirection: 'column', flex: 1 }}
|
||||
onClick={() => handleRentNow(item)}
|
||||
>
|
||||
{/* 卡片头部 */}
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
|
||||
<Typography.Text style={{ color: '#64748b', fontSize: 12 }}>
|
||||
#{item.listing_no}
|
||||
</Typography.Text>
|
||||
{item.in_transaction ? (
|
||||
<Badge status="warning" text={<span style={{ color: '#fbbf24', fontSize: 12 }}>出租中</span>} />
|
||||
) : (
|
||||
<Badge status="success" text={<span style={{ color: '#34d399', fontSize: 12 }}>可租用</span>} />
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 账号标题 */}
|
||||
<Typography.Paragraph
|
||||
ellipsis={{ rows: 2 }}
|
||||
strong
|
||||
style={{
|
||||
color: '#f8fafc',
|
||||
fontSize: 15,
|
||||
lineHeight: 1.4,
|
||||
minHeight: 42,
|
||||
marginBottom: 10,
|
||||
}}
|
||||
>
|
||||
{item.title}
|
||||
</Typography.Paragraph>
|
||||
|
||||
{/* 标签属性 */}
|
||||
<Space wrap size={4} style={{ marginBottom: 12 }}>
|
||||
<Tag color="blue" style={{ margin: 0 }}>
|
||||
{item.game_name === 'delta_force' ? '三角洲行动' : item.game_name}
|
||||
</Tag>
|
||||
{item.server_region && (
|
||||
<Tag style={{ margin: 0, background: 'rgba(255,255,255,0.06)', color: '#cbd5e1', border: 'none' }}>
|
||||
{item.server_region}
|
||||
</Tag>
|
||||
)}
|
||||
{item.login_platform && (
|
||||
<Tag style={{ margin: 0, background: 'rgba(255,255,255,0.06)', color: '#cbd5e1', border: 'none' }}>
|
||||
{item.login_platform}
|
||||
</Tag>
|
||||
)}
|
||||
{item.rank_level && (
|
||||
<Tag color="purple" style={{ margin: 0 }}>
|
||||
{item.rank_level}
|
||||
</Tag>
|
||||
)}
|
||||
</Space>
|
||||
|
||||
{/* 资产特色 */}
|
||||
{item.haf_coin_amount > 0 && (
|
||||
<div
|
||||
style={{
|
||||
background: 'rgba(245, 158, 11, 0.1)',
|
||||
border: '1px solid rgba(245, 158, 11, 0.25)',
|
||||
borderRadius: 6,
|
||||
padding: '4px 8px',
|
||||
marginBottom: 12,
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: 6,
|
||||
}}
|
||||
>
|
||||
<span style={{ fontSize: 12 }}>🪙</span>
|
||||
<Typography.Text style={{ color: '#fbbf24', fontSize: 12 }}>
|
||||
哈夫币:{item.haf_coin_amount.toLocaleString()}
|
||||
</Typography.Text>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div style={{ marginTop: 'auto', paddingTop: 10, borderTop: '1px solid rgba(255,255,255,0.06)' }}>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end' }}>
|
||||
<div>
|
||||
<div style={{ color: '#ef4444', fontSize: 18, fontWeight: 700, lineHeight: 1 }}>
|
||||
{formatMoney(item.price_cent)}
|
||||
<span style={{ fontSize: 12, color: '#94a3b8', fontWeight: 400 }}> /时</span>
|
||||
</div>
|
||||
<div style={{ color: '#64748b', fontSize: 11, marginTop: 4 }}>
|
||||
押金:{formatMoney(item.deposit_amount_cent)}
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
type="primary"
|
||||
size="middle"
|
||||
icon={<RocketOutlined />}
|
||||
disabled={item.in_transaction}
|
||||
style={{
|
||||
background: item.in_transaction ? undefined : 'linear-gradient(135deg, #2563eb, #3b82f6)',
|
||||
border: 'none',
|
||||
borderRadius: 6,
|
||||
}}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
handleRentNow(item)
|
||||
}}
|
||||
>
|
||||
{item.in_transaction ? '出租中' : '立即租用'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</Layout.Content>
|
||||
|
||||
{/* 商品详情 & 租号下单弹窗 */}
|
||||
<Modal
|
||||
title={
|
||||
<Space>
|
||||
<ShopOutlined style={{ color: '#3b82f6' }} />
|
||||
<span>账号租赁详情</span>
|
||||
</Space>
|
||||
}
|
||||
open={Boolean(selectedListing)}
|
||||
onCancel={() => setSelectedListing(null)}
|
||||
footer={null}
|
||||
width={620}
|
||||
destroyOnClose
|
||||
>
|
||||
{selectedListing && (
|
||||
<div style={{ paddingTop: 8 }}>
|
||||
<Typography.Title level={4} style={{ marginBottom: 8 }}>
|
||||
{selectedListing.title}
|
||||
</Typography.Title>
|
||||
<Typography.Text type="secondary" style={{ fontSize: 12, display: 'block', marginBottom: 16 }}>
|
||||
商品唯一编号:{selectedListing.listing_no} · 所属分销商:{selectedListing.site_name}
|
||||
</Typography.Text>
|
||||
|
||||
<Descriptions column={2} bordered size="small">
|
||||
<Descriptions.Item label="所属游戏">
|
||||
{selectedListing.game_name === 'delta_force' ? '三角洲行动' : selectedListing.game_name}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="游戏大区">{selectedListing.server_region || '全区通用'}</Descriptions.Item>
|
||||
<Descriptions.Item label="登录平台">{selectedListing.login_platform || 'PC端'}</Descriptions.Item>
|
||||
<Descriptions.Item label="段位天梯">{selectedListing.rank_level || '暂未定级'}</Descriptions.Item>
|
||||
<Descriptions.Item label="哈夫币资产">
|
||||
{selectedListing.haf_coin_amount > 0
|
||||
? `${selectedListing.haf_coin_amount.toLocaleString()} 币`
|
||||
: '无'}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="交接模式">自动快速交接</Descriptions.Item>
|
||||
<Descriptions.Item label="租金标准">
|
||||
<span style={{ color: '#cf1322', fontWeight: 700, fontSize: 16 }}>
|
||||
{formatMoney(selectedListing.price_cent)}
|
||||
</span>{' '}
|
||||
/ 小时
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="安全押金">
|
||||
<span style={{ fontWeight: 600 }}>{formatMoney(selectedListing.deposit_amount_cent)}</span>
|
||||
</Descriptions.Item>
|
||||
</Descriptions>
|
||||
|
||||
<Divider style={{ margin: '16px 0' }} />
|
||||
|
||||
<div
|
||||
style={{
|
||||
background: '#f8fafc',
|
||||
padding: '12px 16px',
|
||||
borderRadius: 8,
|
||||
border: '1px solid #e2e8f0',
|
||||
marginBottom: 20,
|
||||
}}
|
||||
>
|
||||
<Typography.Text strong style={{ display: 'block', marginBottom: 6, color: '#334155' }}>
|
||||
<SafetyCertificateOutlined style={{ color: '#16a34a', marginRight: 6 }} />
|
||||
租号官方保障须知
|
||||
</Typography.Text>
|
||||
<ul style={{ paddingLeft: 18, margin: 0, fontSize: 12, color: '#64748b', lineHeight: 1.8 }}>
|
||||
<li>本账号经平台安全审核,支持密码自动交接或专属上号器直连。</li>
|
||||
<li>严禁在游戏内使用任何作弊辅助、脚本外挂,违规将扣除全部押金并封停账户。</li>
|
||||
<li>租期结束并安全下线后,系统将自动结算并全额退还押金。</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div style={{ display: 'flex', gap: 12 }}>
|
||||
<Button
|
||||
icon={<CopyOutlined />}
|
||||
onClick={() => handleCopyListingNo(selectedListing.listing_no)}
|
||||
style={{ flex: 1 }}
|
||||
>
|
||||
复制商品编号
|
||||
</Button>
|
||||
<Button
|
||||
type="primary"
|
||||
icon={<RightCircleOutlined />}
|
||||
onClick={() => openMainCheckout(selectedListing)}
|
||||
style={{ flex: 2, background: 'linear-gradient(135deg, #2563eb, #3b82f6)', border: 'none' }}
|
||||
>
|
||||
前往主站极速上号
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
|
||||
{/* 专属客服弹窗 */}
|
||||
<Modal
|
||||
title="联系分销站点专属客服"
|
||||
open={csModalVisible}
|
||||
onCancel={() => setCsModalVisible(false)}
|
||||
footer={[
|
||||
<Button key="ok" type="primary" onClick={() => setCsModalVisible(false)}>
|
||||
我知道了
|
||||
</Button>,
|
||||
]}
|
||||
>
|
||||
<div style={{ textAlign: 'center', padding: '16px 0' }}>
|
||||
<CustomerServiceOutlined style={{ fontSize: 48, color: '#3b82f6', marginBottom: 16 }} />
|
||||
<Typography.Title level={4} style={{ margin: '0 0 8px' }}>
|
||||
【{displayName}】专属客服通道
|
||||
</Typography.Title>
|
||||
<Typography.Paragraph type="secondary" style={{ fontSize: 13, marginBottom: 16 }}>
|
||||
如有换号、上号异常、咨询租号或批量合作需求,请联系本站值班客服。
|
||||
</Typography.Paragraph>
|
||||
<div style={{ background: '#f1f5f9', padding: '12px', borderRadius: 8 }}>
|
||||
<Typography.Text strong>分销站点标识:</Typography.Text>
|
||||
<Tag color="blue">{siteCode}</Tag>
|
||||
<div style={{ marginTop: 8, fontSize: 12, color: '#64748b' }}>
|
||||
主站 7x24 小时技术保障支持
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
</Layout>
|
||||
)
|
||||
}
|
||||
@@ -244,3 +244,16 @@ export async function fetchDistributionSettlementItems(batchId: number) {
|
||||
)
|
||||
return data.data.items ?? []
|
||||
}
|
||||
|
||||
export interface SyncSiteAccountsResult {
|
||||
synced_count: number
|
||||
skipped_count: number
|
||||
total_active: number
|
||||
}
|
||||
|
||||
export async function syncDistributionSiteAccounts(siteId: number) {
|
||||
const { data } = await apiClient.post<ApiResponse<SyncSiteAccountsResult>>(
|
||||
`/admin/distribution/sites/${siteId}/sync-accounts`
|
||||
)
|
||||
return data.data
|
||||
}
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, reactive, onMounted } from 'vue'
|
||||
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
|
||||
import { Plus, Shop, Link, DocumentCopy } from '@element-plus/icons-vue'
|
||||
import { Plus, Shop, Link, DocumentCopy, Refresh } from '@element-plus/icons-vue'
|
||||
import {
|
||||
fetchDistributionSites,
|
||||
onboardDistributionSite,
|
||||
syncDistributionSiteAccounts,
|
||||
type DistributionSite,
|
||||
type OnboardDistributionSitePayload,
|
||||
type OnboardDistributionSiteResult,
|
||||
@@ -126,6 +127,22 @@ function openDistributionAdmin() {
|
||||
window.open(`http://${window.location.hostname}:5190`, '_blank')
|
||||
}
|
||||
|
||||
const syncingSiteId = ref<number | null>(null)
|
||||
|
||||
async function handleSyncAccounts(row: DistributionSite) {
|
||||
syncingSiteId.value = row.id
|
||||
try {
|
||||
const res = await syncDistributionSiteAccounts(row.id)
|
||||
ElMessage.success(
|
||||
`同步成功!为【${row.site_name}】新增可售账号 ${res.synced_count} 个,已存在 ${res.skipped_count} 个(主站当前可上架总数 ${res.total_active})`
|
||||
)
|
||||
} catch (err) {
|
||||
ElMessage.error(readError(err, '同步商品失败'))
|
||||
} finally {
|
||||
syncingSiteId.value = null
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
loadSites()
|
||||
})
|
||||
@@ -191,6 +208,19 @@ onMounted(() => {
|
||||
{{ formatDateTime(row.created_at) }}
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="操作" width="140" fixed="right">
|
||||
<template #default="{ row }">
|
||||
<el-button
|
||||
type="primary"
|
||||
link
|
||||
:icon="Refresh"
|
||||
:loading="syncingSiteId === row.id"
|
||||
@click="handleSyncAccounts(row)"
|
||||
>
|
||||
同步商品
|
||||
</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
</el-card>
|
||||
|
||||
|
||||
@@ -106,6 +106,7 @@ export interface PublicListingQuery {
|
||||
max_daily_loss?: number
|
||||
min_secret_kd?: number
|
||||
max_secret_kd?: number
|
||||
distribution_site_code?: string
|
||||
[key: `resource_${string}_min`]: number | undefined
|
||||
[key: `resource_${string}_max`]: number | undefined
|
||||
}
|
||||
@@ -124,8 +125,13 @@ export async function fetchListings(query: PublicListingQuery = {}) {
|
||||
}
|
||||
|
||||
export async function fetchListingsPage(query: PublicListingQuery = {}) {
|
||||
const siteCode =
|
||||
query.distribution_site_code ||
|
||||
(typeof window !== 'undefined' ? localStorage.getItem('hfb_site_code') : '') ||
|
||||
undefined
|
||||
const effectiveQuery = siteCode ? { distribution_site_code: siteCode, ...query } : query
|
||||
const params = Object.fromEntries(
|
||||
Object.entries(query).filter(
|
||||
Object.entries(effectiveQuery).filter(
|
||||
([, value]) => value !== '' && value !== undefined && value !== null
|
||||
)
|
||||
)
|
||||
|
||||
@@ -40,8 +40,20 @@ import HomeStats from '../components/HomeStats.vue'
|
||||
import HomeFilters from '../components/HomeFilters.vue'
|
||||
import HomeZones from '../components/HomeZones.vue'
|
||||
import ListingCard from '../components/ListingCard.vue'
|
||||
import { useDistributionSiteStore } from '@/stores/distributionSite'
|
||||
|
||||
const siteStore = useDistributionSiteStore()
|
||||
|
||||
const announcements = ref<string[]>(defaultHomeAnnouncements)
|
||||
const displayAnnouncements = computed(() => {
|
||||
if (siteStore.isDistribution) {
|
||||
return [
|
||||
`【${siteStore.siteName}】官方认证独立分销站:账号实时同步主站,官方质检,安全秒交接!`,
|
||||
...announcements.value,
|
||||
]
|
||||
}
|
||||
return announcements.value
|
||||
})
|
||||
const banners = ref<HomeBannerSlide[]>(defaultHomeBanners)
|
||||
const awRecycle = ref<AWRecycleConfig>({ ...defaultAWRecycleConfig })
|
||||
const awRecycleDialogVisible = ref(false)
|
||||
@@ -354,9 +366,46 @@ loadHome()
|
||||
|
||||
<template>
|
||||
<section class="pc-home-redesign">
|
||||
<HomeAnnouncement :announcements="announcements" />
|
||||
<HomeAnnouncement :announcements="displayAnnouncements" />
|
||||
|
||||
<main class="home-content">
|
||||
<!-- 分销站专属标识 Banner -->
|
||||
<div v-if="siteStore.isDistribution" class="dist-portal-banner">
|
||||
<div class="dist-portal-content">
|
||||
<div class="dist-portal-tag">
|
||||
<span class="dist-pulse"></span>
|
||||
官方分销认证
|
||||
</div>
|
||||
<h2 class="dist-portal-title">{{ siteStore.siteName }} 专区</h2>
|
||||
<p class="dist-portal-desc">
|
||||
全站上架账号均由平台统一质检与自动交付,订单数据独立隔离,为您提供安全无忧的租号体验。
|
||||
</p>
|
||||
</div>
|
||||
<div class="dist-portal-badges">
|
||||
<div class="dist-badge-item">
|
||||
<span class="badge-icon">🛡️</span>
|
||||
<div class="badge-text">
|
||||
<strong>官方质检</strong>
|
||||
<small>账号状态实时同步</small>
|
||||
</div>
|
||||
</div>
|
||||
<div class="dist-badge-item">
|
||||
<span class="badge-icon">⚡</span>
|
||||
<div class="badge-text">
|
||||
<strong>极速交付</strong>
|
||||
<small>自动交接 快速上号</small>
|
||||
</div>
|
||||
</div>
|
||||
<div class="dist-badge-item">
|
||||
<span class="badge-icon">📑</span>
|
||||
<div class="badge-text">
|
||||
<strong>独立账单</strong>
|
||||
<small>专属订单 隐私隔离</small>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="hero-section">
|
||||
<HomeBanner :banners="banners" />
|
||||
<HomeStats :stats="statCards" />
|
||||
@@ -367,7 +416,7 @@ loadHome()
|
||||
<strong>租号大厅</strong>
|
||||
<small>高哈夫币 · 安全交接 · 随租随玩</small>
|
||||
</RouterLink>
|
||||
<RouterLink class="biz-entry crash" to="/crash">
|
||||
<RouterLink v-if="!siteStore.isDistribution" class="biz-entry crash" to="/crash">
|
||||
<strong>撞车 <em>NEW</em></strong>
|
||||
<small>选购商品 · 支付后进群联系客服</small>
|
||||
</RouterLink>
|
||||
@@ -697,4 +746,112 @@ loadHome()
|
||||
font-weight: 800;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.dist-portal-banner {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 24px;
|
||||
padding: 24px 32px;
|
||||
border-radius: 20px;
|
||||
background: linear-gradient(135deg, #0f172a 0%, #1e293b 50%, #0f172a 100%);
|
||||
border: 1px solid rgba(255, 255, 255, 0.08);
|
||||
box-shadow: 0 10px 30px rgba(15, 23, 42, 0.12);
|
||||
color: #ffffff;
|
||||
}
|
||||
|
||||
.dist-portal-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
max-width: 600px;
|
||||
}
|
||||
|
||||
.dist-portal-tag {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
width: fit-content;
|
||||
padding: 3px 10px;
|
||||
border-radius: 999px;
|
||||
background: rgba(20, 119, 255, 0.2);
|
||||
border: 1px solid rgba(20, 119, 255, 0.4);
|
||||
color: #60a5fa;
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.5px;
|
||||
}
|
||||
|
||||
.dist-pulse {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
border-radius: 50%;
|
||||
background: #38bdf8;
|
||||
box-shadow: 0 0 8px #38bdf8;
|
||||
}
|
||||
|
||||
.dist-portal-title {
|
||||
margin: 0;
|
||||
font-size: 24px;
|
||||
font-weight: 800;
|
||||
color: #f8fafc;
|
||||
letter-spacing: -0.5px;
|
||||
}
|
||||
|
||||
.dist-portal-desc {
|
||||
margin: 0;
|
||||
font-size: 14px;
|
||||
line-height: 1.5;
|
||||
color: #94a3b8;
|
||||
}
|
||||
|
||||
.dist-portal-badges {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.dist-badge-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 12px 18px;
|
||||
border-radius: 14px;
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
border: 1px solid rgba(255, 255, 255, 0.08);
|
||||
backdrop-filter: blur(8px);
|
||||
}
|
||||
|
||||
.badge-icon {
|
||||
font-size: 22px;
|
||||
}
|
||||
|
||||
.badge-text {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.badge-text strong {
|
||||
font-size: 14px;
|
||||
font-weight: 700;
|
||||
color: #f1f5f9;
|
||||
}
|
||||
|
||||
.badge-text small {
|
||||
font-size: 11px;
|
||||
color: #64748b;
|
||||
}
|
||||
|
||||
@media (max-width: 960px) {
|
||||
.dist-portal-banner {
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
}
|
||||
.dist-portal-badges {
|
||||
width: 100%;
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -60,11 +60,30 @@
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.mobile-brand-title-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.mobile-brand strong {
|
||||
color: #0f172a;
|
||||
font-size: 17px;
|
||||
}
|
||||
|
||||
.mobile-brand-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 1px 5px;
|
||||
font-size: 10px;
|
||||
font-weight: 700;
|
||||
color: #ff6a00;
|
||||
background: rgba(255, 106, 0, 0.1);
|
||||
border: 1px solid rgba(255, 106, 0, 0.25);
|
||||
border-radius: 999px;
|
||||
line-height: 1.3;
|
||||
}
|
||||
|
||||
.mobile-brand small {
|
||||
color: #64748b;
|
||||
font-size: 13px;
|
||||
@@ -212,6 +231,46 @@
|
||||
padding: 12px;
|
||||
}
|
||||
|
||||
.mobile-dist-card {
|
||||
margin-bottom: 12px;
|
||||
padding: 12px 14px;
|
||||
border-radius: 12px;
|
||||
background: linear-gradient(135deg, #1e293b 0%, #0f172a 100%);
|
||||
color: #fff;
|
||||
box-shadow: 0 4px 12px rgba(15, 23, 42, 0.12);
|
||||
}
|
||||
|
||||
.dist-card-top {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.dist-card-badge {
|
||||
display: inline-block;
|
||||
padding: 2px 8px;
|
||||
border-radius: 999px;
|
||||
background: rgba(20, 119, 255, 0.25);
|
||||
border: 1px solid rgba(20, 119, 255, 0.4);
|
||||
color: #60a5fa;
|
||||
font-size: 10px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.2px;
|
||||
}
|
||||
|
||||
.dist-card-name {
|
||||
font-size: 15px;
|
||||
font-weight: 800;
|
||||
color: #f8fafc;
|
||||
}
|
||||
|
||||
.dist-card-sub {
|
||||
margin: 6px 0 0;
|
||||
font-size: 12px;
|
||||
color: #94a3b8;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.banner-swipe {
|
||||
margin-bottom: 12px;
|
||||
border-radius: 8px;
|
||||
|
||||
@@ -55,11 +55,13 @@ import {
|
||||
hasGiftResources,
|
||||
} from '@/shared/utils/listingDisplay'
|
||||
import { buildMobileHomeListSignature, useMobileHomeCacheStore } from '@/stores/mobileHomeCache'
|
||||
import { useDistributionSiteStore } from '@/stores/distributionSite'
|
||||
import { useSessionStore } from '@/stores/session'
|
||||
|
||||
const router = useRouter()
|
||||
const route = useRoute()
|
||||
const session = useSessionStore()
|
||||
const siteStore = useDistributionSiteStore()
|
||||
const homeCache = useMobileHomeCacheStore()
|
||||
const scrollEl = ref<HTMLElement | null>(null)
|
||||
const loading = ref(false)
|
||||
@@ -80,6 +82,15 @@ const rangeFilters = ref<Record<string, { min: string; max: string }>>({})
|
||||
const refreshing = ref(false)
|
||||
const searchValue = ref('')
|
||||
const announcements = ref<string[]>(defaultHomeAnnouncements)
|
||||
const displayAnnouncements = computed(() => {
|
||||
if (siteStore.isDistribution) {
|
||||
return [
|
||||
`【${siteStore.siteName}】官方认证分销站,账号实时同步主站,售后有保障!`,
|
||||
...announcements.value,
|
||||
]
|
||||
}
|
||||
return announcements.value
|
||||
})
|
||||
const bannerSlides = ref<HomeBannerSlide[]>(defaultHomeBanners)
|
||||
const awRecycle = ref<AWRecycleConfig>({ ...defaultAWRecycleConfig })
|
||||
const awRecyclePreviewVisible = ref(false)
|
||||
@@ -797,10 +808,15 @@ syncMobileHomeQuery()
|
||||
<section class="mobile-hero">
|
||||
<div class="mobile-topbar">
|
||||
<div class="mobile-brand">
|
||||
<span class="mobile-logo">锤</span>
|
||||
<span class="mobile-logo">{{
|
||||
siteStore.isDistribution ? siteStore.siteName.slice(0, 1) : '锤'
|
||||
}}</span>
|
||||
<div>
|
||||
<strong>大锤商行</strong>
|
||||
<small>哈夫币租号</small>
|
||||
<div class="mobile-brand-title-row">
|
||||
<strong>{{ siteStore.siteName }}</strong>
|
||||
<span v-if="siteStore.isDistribution" class="mobile-brand-badge">官方分销</span>
|
||||
</div>
|
||||
<small>{{ siteStore.isDistribution ? '官方分销·平台保障' : '哈夫币租号' }}</small>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
@@ -844,7 +860,7 @@ syncMobileHomeQuery()
|
||||
:show-indicators="false"
|
||||
touchable
|
||||
>
|
||||
<van-swipe-item v-for="item in announcements" :key="item">
|
||||
<van-swipe-item v-for="item in displayAnnouncements" :key="item">
|
||||
<span>{{ item }}</span>
|
||||
</van-swipe-item>
|
||||
</van-swipe>
|
||||
@@ -855,6 +871,15 @@ syncMobileHomeQuery()
|
||||
<!-- ========== Content 区域 ========== -->
|
||||
<van-pull-refresh v-model="refreshing" @refresh="onRefresh">
|
||||
<section class="mobile-content">
|
||||
<!-- 分销站移动端专属认证卡片 -->
|
||||
<div v-if="siteStore.isDistribution" class="mobile-dist-card">
|
||||
<div class="dist-card-top">
|
||||
<span class="dist-card-badge">官方分销站</span>
|
||||
<strong class="dist-card-name">{{ siteStore.siteName }}</strong>
|
||||
</div>
|
||||
<p class="dist-card-sub">官方平台实时同步 · 统一质检交付 · 专属独立订单</p>
|
||||
</div>
|
||||
|
||||
<!-- Banner 轮播 -->
|
||||
<van-swipe class="banner-swipe" :autoplay="3600" lazy-render>
|
||||
<van-swipe-item v-for="slide in bannerSlides" :key="slide.title || slide.image_url">
|
||||
@@ -891,7 +916,7 @@ syncMobileHomeQuery()
|
||||
<strong>租号大厅</strong>
|
||||
<small>高哈夫币 · 随租随玩</small>
|
||||
</RouterLink>
|
||||
<RouterLink class="biz-entry" to="/crash">
|
||||
<RouterLink v-if="!siteStore.isDistribution" class="biz-entry" to="/crash">
|
||||
<strong>撞车</strong>
|
||||
<small>选购商品 · 一键找客服</small>
|
||||
<em class="biz-entry-badge">NEW</em>
|
||||
@@ -1082,7 +1107,7 @@ syncMobileHomeQuery()
|
||||
>湘ICP备2025146668号</a
|
||||
>
|
||||
<span class="home-footer-divider">|</span>
|
||||
<span class="home-footer-copyright">版权所有 ©2026 大锤网络游戏有限公司</span>
|
||||
<span class="home-footer-copyright">版权所有 ©2026 {{ siteStore.siteName }}</span>
|
||||
</footer>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -319,9 +319,17 @@ export async function fetchPostRentalNotice() {
|
||||
return data.data
|
||||
}
|
||||
|
||||
export async function fetchOrders(page = 1, pageSize = 20) {
|
||||
export async function fetchOrders(page = 1, pageSize = 20, distributionSiteCode?: string) {
|
||||
const siteCode =
|
||||
distributionSiteCode ||
|
||||
(typeof window !== 'undefined' ? localStorage.getItem('hfb_site_code') : '') ||
|
||||
undefined
|
||||
const params: Record<string, unknown> = { page, page_size: pageSize }
|
||||
if (siteCode) {
|
||||
params.distribution_site_code = siteCode
|
||||
}
|
||||
const { data } = await apiClient.get<ApiResponse<PaginatedResult<UserOrderListItem>>>('/orders', {
|
||||
params: { page, page_size: pageSize },
|
||||
params,
|
||||
})
|
||||
return data.data
|
||||
}
|
||||
@@ -343,13 +351,29 @@ export async function fetchSellerHandoffs(
|
||||
return data.data
|
||||
}
|
||||
|
||||
export async function fetchOrder(id: string | number) {
|
||||
const { data } = await apiClient.get<ApiResponse<Order>>(`/orders/${id}`)
|
||||
export async function fetchOrder(id: string | number, distributionSiteCode?: string) {
|
||||
const siteCode =
|
||||
distributionSiteCode ||
|
||||
(typeof window !== 'undefined' ? localStorage.getItem('hfb_site_code') : '') ||
|
||||
undefined
|
||||
const params: Record<string, unknown> = {}
|
||||
if (siteCode) {
|
||||
params.distribution_site_code = siteCode
|
||||
}
|
||||
const { data } = await apiClient.get<ApiResponse<Order>>(`/orders/${id}`, { params })
|
||||
return data.data
|
||||
}
|
||||
|
||||
export async function createOrder(listingId: number) {
|
||||
const { data } = await apiClient.post<ApiResponse<Order>>('/orders', { listing_id: listingId })
|
||||
export async function createOrder(listingId: number, distributionSiteCode?: string) {
|
||||
const siteCode =
|
||||
distributionSiteCode ||
|
||||
(typeof window !== 'undefined' ? localStorage.getItem('hfb_site_code') : '') ||
|
||||
undefined
|
||||
const payload: { listing_id: number; distribution_site_code?: string } = { listing_id: listingId }
|
||||
if (siteCode) {
|
||||
payload.distribution_site_code = siteCode
|
||||
}
|
||||
const { data } = await apiClient.post<ApiResponse<Order>>('/orders', payload)
|
||||
return data.data
|
||||
}
|
||||
|
||||
|
||||
@@ -23,6 +23,7 @@ import {
|
||||
import { centToYuan, formatCent, formatMoney } from '@/shared/utils/money'
|
||||
import { formatDateMinute } from '@/shared/utils/time'
|
||||
import { formatListingNo } from '@/shared/utils/listingDisplay'
|
||||
import { useDistributionSiteStore } from '@/stores/distributionSite'
|
||||
|
||||
type BizType = 'rental' | 'crash'
|
||||
|
||||
@@ -44,6 +45,7 @@ interface UnifiedOrderItem {
|
||||
|
||||
const router = useRouter()
|
||||
const route = useRoute()
|
||||
const siteStore = useDistributionSiteStore()
|
||||
const loading = ref(false)
|
||||
const rentalOrders = ref<UserOrderListItem[]>([])
|
||||
const crashOrders = ref<MohongOrder[]>([])
|
||||
@@ -143,10 +145,11 @@ function onStatusTabChange(name: string | number) {
|
||||
async function loadOrders() {
|
||||
loading.value = true
|
||||
try {
|
||||
const [rentalResult, crashResult] = await Promise.allSettled([
|
||||
fetchOrders(rentalPage.value, rentalPageSize),
|
||||
fetchMyMohongOrders({ page: 1, page_size: 50 }),
|
||||
])
|
||||
const rentalPromise = fetchOrders(rentalPage.value, rentalPageSize)
|
||||
const crashPromise = !siteStore.isDistribution
|
||||
? fetchMyMohongOrders({ page: 1, page_size: 50 })
|
||||
: Promise.resolve(null)
|
||||
const [rentalResult, crashResult] = await Promise.allSettled([rentalPromise, crashPromise])
|
||||
|
||||
if (rentalResult.status === 'fulfilled') {
|
||||
rentalOrders.value = rentalResult.value?.items || []
|
||||
@@ -157,14 +160,16 @@ async function loadOrders() {
|
||||
showToast({ message: '租赁订单加载失败', icon: 'warning-o' })
|
||||
}
|
||||
|
||||
if (crashResult.status === 'fulfilled') {
|
||||
crashOrders.value = crashResult.value?.items || []
|
||||
} else {
|
||||
if (!siteStore.isDistribution && crashResult.status === 'fulfilled' && crashResult.value) {
|
||||
crashOrders.value = crashResult.value.items || []
|
||||
} else if (!siteStore.isDistribution && crashResult.status === 'rejected') {
|
||||
crashOrders.value = []
|
||||
showToast({
|
||||
message: readError(crashResult.reason, '撞车订单加载失败'),
|
||||
icon: 'warning-o',
|
||||
})
|
||||
} else {
|
||||
crashOrders.value = []
|
||||
}
|
||||
} finally {
|
||||
loading.value = false
|
||||
@@ -278,10 +283,20 @@ async function copyListingCode(order: UserOrderListItem) {
|
||||
<button class="back-btn" @click="router.back()">
|
||||
<van-icon name="arrow-left" :size="20" />
|
||||
</button>
|
||||
<h1>我的订单</h1>
|
||||
<div class="header-title-wrap">
|
||||
<h1>我的订单</h1>
|
||||
<span v-if="siteStore.isDistribution" class="m-site-order-tag">
|
||||
{{ siteStore.siteName }}
|
||||
</span>
|
||||
</div>
|
||||
<span class="header-spacer"></span>
|
||||
</header>
|
||||
|
||||
<div v-if="siteStore.isDistribution" class="site-order-notice-bar">
|
||||
<van-icon name="shop-o" class="notice-icon" />
|
||||
<span>当前仅展示【{{ siteStore.siteName }}】专属订单</span>
|
||||
</div>
|
||||
|
||||
<van-tabs
|
||||
v-model:active="activeTab"
|
||||
class="custom-tabs"
|
||||
@@ -471,7 +486,6 @@ async function copyListingCode(order: UserOrderListItem) {
|
||||
}
|
||||
|
||||
.page-header h1 {
|
||||
flex: 1;
|
||||
margin: 0;
|
||||
font-size: 17px;
|
||||
font-weight: 700;
|
||||
@@ -479,6 +493,47 @@ async function copyListingCode(order: UserOrderListItem) {
|
||||
color: #111827;
|
||||
}
|
||||
|
||||
.header-title-wrap {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 6px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.m-site-order-tag {
|
||||
display: inline-block;
|
||||
padding: 2px 8px;
|
||||
border-radius: 999px;
|
||||
background: rgba(20, 119, 255, 0.1);
|
||||
border: 1px solid rgba(20, 119, 255, 0.25);
|
||||
color: #1477ff;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
max-width: 110px;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.site-order-notice-bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 8px 16px;
|
||||
background: linear-gradient(90deg, #eff6ff, #f0fdf4);
|
||||
border-bottom: 1px solid #dbeafe;
|
||||
font-size: 12px;
|
||||
color: #1d4ed8;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.site-order-notice-bar .notice-icon {
|
||||
font-size: 14px;
|
||||
color: #2563eb;
|
||||
}
|
||||
|
||||
.back-btn {
|
||||
display: grid;
|
||||
width: 36px;
|
||||
|
||||
@@ -1,3 +1,22 @@
|
||||
.header-title-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.site-order-tag {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 4px 12px;
|
||||
border-radius: 999px;
|
||||
background: linear-gradient(135deg, rgba(20, 119, 255, 0.08), rgba(0, 198, 251, 0.12));
|
||||
border: 1px solid rgba(20, 119, 255, 0.25);
|
||||
color: #1477ff;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.2px;
|
||||
}
|
||||
|
||||
.orders-toolbar {
|
||||
margin-top: 24px;
|
||||
display: flex;
|
||||
|
||||
@@ -15,6 +15,7 @@ import { centToYuan, formatCent, formatMoney } from '@/shared/utils/money'
|
||||
import { orderStatusLabel } from '@/shared/utils/statusLabels'
|
||||
import { formatDateTime } from '@/shared/utils/time'
|
||||
import { formatListingNo } from '@/shared/utils/listingDisplay'
|
||||
import { useDistributionSiteStore } from '@/stores/distributionSite'
|
||||
|
||||
type BizType = 'rental' | 'crash'
|
||||
|
||||
@@ -42,6 +43,7 @@ const route = useRoute()
|
||||
const router = useRouter()
|
||||
const searchKeyword = ref('')
|
||||
const fallbackPendingPaymentMinutes = 15
|
||||
const siteStore = useDistributionSiteStore()
|
||||
const rentalTotal = ref(0)
|
||||
const rentalPage = ref(1)
|
||||
const rentalPageSize = 20
|
||||
@@ -151,10 +153,11 @@ function handleTabChange(tab: string | number) {
|
||||
async function loadOrders() {
|
||||
loading.value = true
|
||||
try {
|
||||
const [rentalResult, crashResult] = await Promise.allSettled([
|
||||
fetchOrders(rentalPage.value, rentalPageSize),
|
||||
fetchMyMohongOrders({ page: 1, page_size: 50 }),
|
||||
])
|
||||
const rentalPromise = fetchOrders(rentalPage.value, rentalPageSize)
|
||||
const crashPromise = !siteStore.isDistribution
|
||||
? fetchMyMohongOrders({ page: 1, page_size: 50 })
|
||||
: Promise.resolve(null)
|
||||
const [rentalResult, crashResult] = await Promise.allSettled([rentalPromise, crashPromise])
|
||||
|
||||
if (rentalResult.status === 'fulfilled') {
|
||||
rentalOrders.value = rentalResult.value?.items || []
|
||||
@@ -165,11 +168,13 @@ async function loadOrders() {
|
||||
ElMessage.error('租赁订单加载失败')
|
||||
}
|
||||
|
||||
if (crashResult.status === 'fulfilled') {
|
||||
crashOrders.value = crashResult.value?.items || []
|
||||
} else {
|
||||
if (!siteStore.isDistribution && crashResult.status === 'fulfilled' && crashResult.value) {
|
||||
crashOrders.value = crashResult.value.items || []
|
||||
} else if (!siteStore.isDistribution && crashResult.status === 'rejected') {
|
||||
crashOrders.value = []
|
||||
ElMessage.error(readError(crashResult.reason, '撞车订单加载失败'))
|
||||
} else {
|
||||
crashOrders.value = []
|
||||
}
|
||||
} finally {
|
||||
loading.value = false
|
||||
@@ -298,9 +303,17 @@ function bizTypeLabel(bizType: BizType) {
|
||||
<template>
|
||||
<section class="page">
|
||||
<div class="page-header">
|
||||
<p class="eyebrow">ORDERS</p>
|
||||
<h1>我的订单</h1>
|
||||
<p>租赁与撞车订单统一展示,按创建时间倒序排列。</p>
|
||||
<p class="eyebrow">{{ siteStore.isDistribution ? 'DISTRIBUTION ORDERS' : 'ORDERS' }}</p>
|
||||
<div class="header-title-row">
|
||||
<h1>我的订单</h1>
|
||||
<span v-if="siteStore.isDistribution" class="site-order-tag">
|
||||
{{ siteStore.siteName }} · 专属订单
|
||||
</span>
|
||||
</div>
|
||||
<p v-if="siteStore.isDistribution">
|
||||
当前为【{{ siteStore.siteName }}】专属分销商城,仅展示在此分销站产生的订单记录。
|
||||
</p>
|
||||
<p v-else>租赁与撞车订单统一展示,按创建时间倒序排列。</p>
|
||||
</div>
|
||||
|
||||
<div class="orders-toolbar">
|
||||
|
||||
@@ -51,12 +51,32 @@
|
||||
line-height: 1.2;
|
||||
}
|
||||
|
||||
.pc-brand-title-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.pc-brand-text {
|
||||
font-size: 16px;
|
||||
font-weight: 800;
|
||||
color: #17233d;
|
||||
}
|
||||
|
||||
.pc-brand-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 1px 6px;
|
||||
font-size: 10px;
|
||||
font-weight: 700;
|
||||
color: #ff6a00;
|
||||
background: rgba(255, 106, 0, 0.1);
|
||||
border: 1px solid rgba(255, 106, 0, 0.25);
|
||||
border-radius: 999px;
|
||||
line-height: 1.4;
|
||||
letter-spacing: 0.2px;
|
||||
}
|
||||
|
||||
.pc-brand-sub {
|
||||
font-size: 11px;
|
||||
color: #8b9cb5;
|
||||
|
||||
@@ -26,9 +26,11 @@ import {
|
||||
} from '@element-plus/icons-vue'
|
||||
import { ensureSupportChat, resolveSupportScene } from '@/features/chats/api/chats'
|
||||
import { useChatUnreadCount } from '@/features/chats/composables/useChatUnreadCount'
|
||||
import { useDistributionSiteStore } from '@/stores/distributionSite'
|
||||
import { useSessionStore } from '@/stores/session'
|
||||
|
||||
const session = useSessionStore()
|
||||
const siteStore = useDistributionSiteStore()
|
||||
const router = useRouter()
|
||||
const route = useRoute()
|
||||
const { unreadCount, unreadLabel } = useChatUnreadCount(route)
|
||||
@@ -139,10 +141,17 @@ async function handleSupportClick() {
|
||||
<div class="pc-app-shell">
|
||||
<header class="pc-topbar">
|
||||
<RouterLink class="pc-brand" to="/">
|
||||
<span class="pc-brand-mark">锤</span>
|
||||
<span class="pc-brand-mark">{{
|
||||
siteStore.isDistribution ? siteStore.siteName.slice(0, 1) : '锤'
|
||||
}}</span>
|
||||
<div class="pc-brand-info">
|
||||
<span class="pc-brand-text">大锤商行</span>
|
||||
<small class="pc-brand-sub">哈夫币租号</small>
|
||||
<div class="pc-brand-title-row">
|
||||
<span class="pc-brand-text">{{ siteStore.siteName }}</span>
|
||||
<span v-if="siteStore.isDistribution" class="pc-brand-badge">官方分销</span>
|
||||
</div>
|
||||
<small class="pc-brand-sub">{{
|
||||
siteStore.isDistribution ? '官方分销·平台保障' : '哈夫币租号'
|
||||
}}</small>
|
||||
</div>
|
||||
</RouterLink>
|
||||
|
||||
@@ -353,7 +362,7 @@ async function handleSupportClick() {
|
||||
>湘ICP备2025146668号</a
|
||||
>
|
||||
<span class="pc-footer-divider">|</span>
|
||||
<span class="pc-footer-copyright">版权所有 ©2026 大锤网络游戏有限公司</span>
|
||||
<span class="pc-footer-copyright">版权所有 ©2026 {{ siteStore.siteName }}</span>
|
||||
</div>
|
||||
</footer>
|
||||
</div>
|
||||
|
||||
@@ -11,6 +11,7 @@ import { createApp } from 'vue'
|
||||
import App from './App.vue'
|
||||
import router from './router'
|
||||
import { useAdminSessionStore } from './stores/adminSession'
|
||||
import { useDistributionSiteStore } from './stores/distributionSite'
|
||||
import { useSessionStore } from './stores/session'
|
||||
|
||||
const app = createApp(App)
|
||||
@@ -18,6 +19,9 @@ const pinia = createPinia()
|
||||
|
||||
app.use(pinia).use(router)
|
||||
|
||||
// 初始化分销站点租户配置(如 ?site=xxx 或独立域名访问)
|
||||
useDistributionSiteStore(pinia).initSite()
|
||||
|
||||
window.addEventListener('auth-storage-changed', () => {
|
||||
useSessionStore(pinia).syncFromStorage()
|
||||
useAdminSessionStore(pinia).syncFromStorage()
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { apiClient } from '@/shared/api/client'
|
||||
import type { ApiResponse } from '@/shared/types/types'
|
||||
|
||||
export interface DistributionSiteInfo {
|
||||
site_code: string
|
||||
site_name: string
|
||||
domain: string
|
||||
status: string
|
||||
display_account_enabled: boolean
|
||||
default_support_group_id?: number | null
|
||||
}
|
||||
|
||||
export const useDistributionSiteStore = defineStore('distributionSite', {
|
||||
state: () => ({
|
||||
siteCode: localStorage.getItem('hfb_site_code') || '',
|
||||
siteName: localStorage.getItem('hfb_site_name') || '大锤商行',
|
||||
domain: '',
|
||||
isDistribution: Boolean(localStorage.getItem('hfb_site_code')),
|
||||
displayAccountEnabled: true,
|
||||
defaultSupportGroupId: null as number | null,
|
||||
initialized: false,
|
||||
}),
|
||||
|
||||
actions: {
|
||||
async initSite() {
|
||||
// 1. Check URL query params: ?site=xxx or ?site_code=xxx
|
||||
const urlParams = new URLSearchParams(window.location.search)
|
||||
const querySite = (
|
||||
urlParams.get('site') ||
|
||||
urlParams.get('site_code') ||
|
||||
urlParams.get('distribution_site_code') ||
|
||||
''
|
||||
).trim()
|
||||
|
||||
if (querySite) {
|
||||
if (querySite === 'main' || querySite === 'clear' || querySite === '0') {
|
||||
this.resetToMainSite()
|
||||
this.initialized = true
|
||||
return
|
||||
}
|
||||
this.siteCode = querySite
|
||||
localStorage.setItem('hfb_site_code', querySite)
|
||||
}
|
||||
|
||||
const effectiveCode = this.siteCode || localStorage.getItem('hfb_site_code') || ''
|
||||
const hostname = window.location.hostname
|
||||
|
||||
// If we have a site code, query by code.
|
||||
// Otherwise query by domain (for independent domain access in production).
|
||||
let queryUrl = ''
|
||||
if (effectiveCode) {
|
||||
queryUrl = `/distribution/site-info?code=${encodeURIComponent(effectiveCode)}`
|
||||
} else if (hostname && hostname !== 'localhost' && hostname !== '127.0.0.1') {
|
||||
queryUrl = `/distribution/site-info?domain=${encodeURIComponent(hostname)}`
|
||||
}
|
||||
|
||||
if (!queryUrl) {
|
||||
this.resetToMainSite()
|
||||
this.initialized = true
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const { data } = await apiClient.get<ApiResponse<DistributionSiteInfo>>(queryUrl, {
|
||||
silent: true,
|
||||
skipErrorHandler: true,
|
||||
})
|
||||
const info = data.data
|
||||
if (info && info.site_code && info.status === 'active') {
|
||||
this.siteCode = info.site_code
|
||||
this.siteName = info.site_name || info.site_code
|
||||
this.domain = info.domain || ''
|
||||
this.isDistribution = true
|
||||
this.displayAccountEnabled = info.display_account_enabled ?? true
|
||||
this.defaultSupportGroupId = info.default_support_group_id ?? null
|
||||
|
||||
localStorage.setItem('hfb_site_code', this.siteCode)
|
||||
localStorage.setItem('hfb_site_name', this.siteName)
|
||||
|
||||
// Update page title
|
||||
document.title = `【${this.siteName}】租号商城 - 精选游戏账号平台`
|
||||
} else {
|
||||
this.resetToMainSite()
|
||||
}
|
||||
} catch {
|
||||
// If site code was invalid or not found, fall back to main site
|
||||
this.resetToMainSite()
|
||||
} finally {
|
||||
this.initialized = true
|
||||
}
|
||||
},
|
||||
|
||||
resetToMainSite() {
|
||||
this.siteCode = ''
|
||||
this.siteName = '大锤商行'
|
||||
this.domain = ''
|
||||
this.isDistribution = false
|
||||
this.displayAccountEnabled = true
|
||||
this.defaultSupportGroupId = null
|
||||
localStorage.removeItem('hfb_site_code')
|
||||
localStorage.removeItem('hfb_site_name')
|
||||
document.title = '大锤商行 - 官方租号平台'
|
||||
},
|
||||
},
|
||||
})
|
||||
Reference in New Issue
Block a user