feat(tenant): 增加双站共享货架与跨站下单

This commit is contained in:
yml
2026-11-15 15:45:00 +08:00
parent abf0fce89b
commit 4eb2bc253b
20 changed files with 767 additions and 31 deletions
+2
View File
@@ -8,6 +8,7 @@ import (
type GameAccount struct {
ID uint64 `gorm:"primaryKey" json:"id"`
SourceTenantID uint64 `gorm:"not null;default:0;index:idx_game_accounts_source_tenant" json:"source_tenant_id"`
OwnerID uint64 `gorm:"not null;index" json:"owner_id"`
GameName string `gorm:"size:64;not null;default:'delta_force'" json:"game_name"`
ServerRegion string `gorm:"size:64;not null" json:"server_region"`
@@ -30,6 +31,7 @@ func (GameAccount) TableName() string {
type RentalListing struct {
ID uint64 `gorm:"primaryKey" json:"id"`
SourceTenantID uint64 `gorm:"not null;default:0;index:idx_rental_listings_source_tenant" json:"source_tenant_id"`
ListingNo string `gorm:"column:listing_no;size:20;not null;uniqueIndex" json:"listing_no"`
AccountID uint64 `gorm:"not null;index" json:"account_id"`
OwnerID uint64 `gorm:"not null;index" json:"owner_id"`
+4
View File
@@ -9,6 +9,9 @@ import (
type RentalOrder struct {
ID uint64 `gorm:"primaryKey" json:"id"`
BuyerTenantID uint64 `gorm:"not null;default:0;index:idx_rental_orders_buyer_tenant_created" json:"buyer_tenant_id"`
SourceTenantID uint64 `gorm:"not null;default:0;index:idx_rental_orders_source_tenant_created" json:"source_tenant_id"`
PaymentTenantID uint64 `gorm:"not null;default:0" json:"payment_tenant_id"`
OrderNo string `gorm:"size:64;not null;uniqueIndex" json:"order_no"`
ListingID uint64 `gorm:"not null;index" json:"listing_id"`
AccountID uint64 `gorm:"not null;index" json:"account_id"`
@@ -19,6 +22,7 @@ type RentalOrder struct {
EstimatedDurationHours int `gorm:"not null;default:24" json:"estimated_duration_hours"`
RentAmountCent int64 `gorm:"not null;default:0" json:"-"`
OwnerRentAmountCent int64 `gorm:"not null;default:0" json:"-"`
SourceAmountCent int64 `gorm:"not null;default:0" json:"-"`
DepositAmountCent int64 `gorm:"not null;default:0" json:"-"`
DepositOriginalAmountCent int64 `gorm:"not null;default:0" json:"-"`
DepositWaivedAmountCent int64 `gorm:"not null;default:0" json:"-"`
+14
View File
@@ -10,6 +10,7 @@ import (
type ListingDTO struct {
ID uint64 `json:"id"`
SourceTenantID uint64 `json:"source_tenant_id"`
ListingNo string `json:"listing_no"`
AccountID uint64 `json:"account_id"`
OwnerID uint64 `json:"owner_id"`
@@ -187,6 +188,19 @@ type PublicListResult struct {
ZoneCounts map[string]int64 `json:"zone_counts"`
}
type TenantListingOfferDTO struct {
TenantID uint64 `json:"tenant_id"`
ListingID uint64 `json:"listing_id"`
DisplayStatus string `json:"display_status"`
PriceCent *int64 `json:"price_cent"`
EffectivePriceCent int64 `json:"effective_price_cent"`
}
type UpdateTenantListingOfferRequest struct {
DisplayStatus string `json:"display_status"`
PriceCent *int64 `json:"price_cent"`
}
type AdminActionRequest struct {
Reason string `json:"reason" binding:"required"`
}
@@ -205,3 +205,34 @@ func (h *Handler) UpdateScreenshots(c *gin.Context) {
}
response.OK(c, item)
}
func (h *Handler) FindTenantOffer(c *gin.Context) {
id, ok := parseID(c)
if !ok {
return
}
item, err := h.service.FindTenantOffer(c.Request.Context(), id)
if err != nil {
writeListingError(c, err)
return
}
response.OK(c, item)
}
func (h *Handler) UpdateTenantOffer(c *gin.Context) {
id, ok := parseID(c)
if !ok {
return
}
var req UpdateTenantListingOfferRequest
if err := c.ShouldBindJSON(&req); err != nil {
response.BadRequest(c, "货架配置参数不正确")
return
}
item, err := h.service.UpdateTenantOffer(c.Request.Context(), id, req)
if err != nil {
writeListingError(c, err)
return
}
response.OK(c, item)
}
@@ -69,6 +69,10 @@ func writeListingError(c *gin.Context, err error) {
response.BadRequest(c, "烽火等级低于"+strconv.Itoa(levelErr.Min)+"级的号无法发布")
case errors.Is(err, ErrInvalidInput):
response.BadRequest(c, "发布信息不符合规则")
case errors.Is(err, ErrTenantRequired):
response.BadRequest(c, "缺少经营租户上下文")
case errors.Is(err, ErrListingNotFound):
response.Error(c, http.StatusNotFound, "not_found", "发布不存在")
case errors.Is(err, ErrListingLocked):
response.Error(c, http.StatusConflict, "listing_locked", "当前发布不可修改")
case errors.Is(err, ErrListingMustOfflineToEdit):
+12 -1
View File
@@ -22,6 +22,7 @@ func (r *Repository) Create(ctx context.Context, ownerID uint64, req CreateReque
if err := r.ensureCreateCooldown(tx, ownerID, publishCooldown, now); err != nil {
return err
}
sourceTenantID := userTenantID(ctx, tx, ownerID)
var site model.DistributionSite
var siteID *uint64
@@ -53,6 +54,7 @@ func (r *Repository) Create(ctx context.Context, ownerID uint64, req CreateReque
listingStatus, reviewStatus, publishedAt := initialPublishState(reviewRequired)
account := model.GameAccount{
SourceTenantID: sourceTenantID,
OwnerID: ownerID,
GameName: "delta_force",
ServerRegion: req.ServerRegion,
@@ -71,6 +73,7 @@ func (r *Repository) Create(ctx context.Context, ownerID uint64, req CreateReque
priceCent := normalizedListingPriceCent(req)
listing := model.RentalListing{
SourceTenantID: sourceTenantID,
ListingNo: listingNo,
AccountID: account.ID,
OwnerID: ownerID,
@@ -193,6 +196,7 @@ func (r *Repository) CreateFromExternalUpload(ctx context.Context, upload extern
return err
}
account := model.GameAccount{
SourceTenantID: owner.TenantID,
OwnerID: owner.ID,
GameName: "delta_force",
ServerRegion: req.ServerRegion,
@@ -210,6 +214,7 @@ func (r *Repository) CreateFromExternalUpload(ctx context.Context, upload extern
}
priceCent := normalizedListingPriceCent(req)
listing := model.RentalListing{
SourceTenantID: owner.TenantID,
ListingNo: listingNo,
AccountID: account.ID,
OwnerID: owner.ID,
@@ -385,7 +390,12 @@ func (r *Repository) ensureUploadOwnerUser(tx *gorm.DB, admin *model.AdminUser)
nickname = admin.Username
}
var user model.User
err := tx.Where("phone = ?", phone).First(&user).Error
tenantID := userTenantID(tx.Statement.Context, tx, 0)
userQuery := tx.Where("phone = ?", phone)
if tenantID > 0 {
userQuery = userQuery.Where("tenant_id = ?", tenantID)
}
err := userQuery.First(&user).Error
if err == nil {
updates := map[string]any{
"nickname": nickname,
@@ -404,6 +414,7 @@ func (r *Repository) ensureUploadOwnerUser(tx *gorm.DB, admin *model.AdminUser)
return nil, err
}
user = model.User{
TenantID: tenantID,
Phone: phone,
Nickname: nickname,
RealnameStatus: "verified",
@@ -167,6 +167,7 @@ func (row listingRow) toDTO() ListingDTO {
reviewStatus, reviewReason := normalizedReviewState(row.Status, row.ReviewStatus, row.ReviewReason)
return ListingDTO{
ID: row.ID,
SourceTenantID: row.SourceTenantID,
ListingNo: row.ListingNo,
AccountID: row.AccountID,
OwnerID: row.OwnerID,
@@ -213,6 +214,7 @@ func toDTO(account model.GameAccount, listing model.RentalListing) *ListingDTO {
reviewStatus, reviewReason := normalizedReviewState(listing.Status, listing.ReviewStatus, listing.ReviewReason)
return &ListingDTO{
ID: listing.ID,
SourceTenantID: listing.SourceTenantID,
ListingNo: listing.ListingNo,
AccountID: account.ID,
OwnerID: listing.OwnerID,
@@ -8,6 +8,7 @@ import (
"hfb_sys/backend/internal/model"
"hfb_sys/backend/internal/modules/rentergrowth"
"hfb_sys/backend/internal/tenancy"
"gorm.io/datatypes"
"gorm.io/gorm"
@@ -24,7 +25,7 @@ func (r *Repository) ListPublic(ctx context.Context, query PublicListQuery) (*Pu
return r.listPublicPage(ctx, query, page, pageSize)
}
db := r.baseQuery(ctx).
db := applyTenantOfferVisibility(ctx, r.baseQuery(ctx)).
Where("l.status = ? AND l.review_status = ? AND l.in_transaction = ?", "published", "approved", false)
if query.DistributionSiteCode != "" {
@@ -40,6 +41,9 @@ func (r *Repository) ListPublic(ctx context.Context, query PublicListQuery) (*Pu
return nil, err
}
items := publicListings(rowsToDTO(rows))
if err := r.applyTenantOfferPrices(ctx, items); err != nil {
return nil, err
}
if err := r.applyShelfMarkup(ctx, query.DistributionSiteCode, items); err != nil {
return nil, err
}
@@ -76,7 +80,8 @@ func (r *Repository) ListPublic(ctx context.Context, query PublicListQuery) (*Pu
func (r *Repository) listPublicPage(ctx context.Context, query PublicListQuery, page int, pageSize int) (*PublicListResult, error) {
var total int64
if err := applyPremiumVisibility(r.db.WithContext(ctx).Table("rental_listings AS l"), query).
countDB := applyTenantOfferVisibility(ctx, r.db.WithContext(ctx).Table("rental_listings AS l"))
if err := applyPremiumVisibility(countDB, query).
Where("l.status = ? AND l.review_status = ? AND l.in_transaction = ?", "published", "approved", false).
Count(&total).Error; err != nil {
return nil, err
@@ -84,7 +89,8 @@ func (r *Repository) listPublicPage(ctx context.Context, query PublicListQuery,
var rows []listingRow
offset := (page - 1) * pageSize
err := applyPublicSQLSort(applyPremiumVisibility(r.baseQuery(ctx), query), query.Sort).
dataDB := applyTenantOfferVisibility(ctx, r.baseQuery(ctx))
err := applyPublicSQLSort(ctx, applyPremiumVisibility(dataDB, query), query.Sort).
Where("l.status = ? AND l.review_status = ? AND l.in_transaction = ?", "published", "approved", false).
Limit(pageSize).
Offset(offset).
@@ -100,8 +106,12 @@ func (r *Repository) listPublicPage(ctx context.Context, query PublicListQuery,
zoneCounts["all"] = nonPremiumTotal
zoneCounts["premium"] = 0
}
items := publicListings(rowsToDTO(rows))
if err := r.applyTenantOfferPrices(ctx, items); err != nil {
return nil, err
}
return &PublicListResult{
Items: publicListings(rowsToDTO(rows)),
Items: items,
Total: total,
Page: page,
PageSize: pageSize,
@@ -173,12 +183,16 @@ func canListPublicWithSQL(query PublicListQuery) bool {
}
}
func applyPublicSQLSort(db *gorm.DB, sortKey string) *gorm.DB {
func applyPublicSQLSort(ctx context.Context, db *gorm.DB, sortKey string) *gorm.DB {
priceExpression := "l.price_cent"
if tenancy.IDFromContext(ctx) > 0 {
priceExpression = "COALESCE(tlo.price_cent, l.price_cent)"
}
switch sortKey {
case "priceAsc":
return db.Order("l.price_cent ASC, l.published_at DESC, l.id DESC")
return db.Order(priceExpression + " ASC, l.published_at DESC, l.id DESC")
case "priceDesc":
return db.Order("l.price_cent DESC, l.published_at DESC, l.id DESC")
return db.Order(priceExpression + " DESC, l.published_at DESC, l.id DESC")
case "coinDesc":
return db.Order("a.haf_coin_amount DESC, l.published_at DESC, l.id DESC")
case "coinAsc":
@@ -196,6 +210,9 @@ func publicShuffleSeed() int64 {
}
func (r *Repository) publicZoneCountsCached(ctx context.Context) (map[string]int64, int64, error) {
if tenancy.IDFromContext(ctx) > 0 {
return r.computePublicZoneCounts(ctx)
}
now := time.Now()
r.publicZoneCountsMu.Lock()
defer r.publicZoneCountsMu.Unlock()
@@ -203,8 +220,22 @@ func (r *Repository) publicZoneCountsCached(ctx context.Context) (map[string]int
return copyPublicZoneCounts(r.publicZoneCounts.Counts), r.publicZoneCounts.NonPremiumTotal, nil
}
counts, nonPremiumTotal, err := r.computePublicZoneCounts(ctx)
if err != nil {
return nil, 0, err
}
r.publicZoneCounts = publicZoneCountCache{
Counts: copyPublicZoneCounts(counts),
NonPremiumTotal: nonPremiumTotal,
ExpiresAt: now.Add(publicZoneCountCacheTTL),
}
return counts, nonPremiumTotal, nil
}
func (r *Repository) computePublicZoneCounts(ctx context.Context) (map[string]int64, int64, error) {
var rows []publicZoneRow
err := r.db.WithContext(ctx).Table("rental_listings AS l").
query := applyTenantOfferVisibility(ctx, r.db.WithContext(ctx).Table("rental_listings AS l"))
err := query.
Select("a.login_platform, a.haf_coin_amount, a.asset_summary, l.is_premium").
Joins("JOIN game_accounts AS a ON a.id = l.account_id").
Where("l.status = ? AND l.review_status = ? AND l.in_transaction = ?", "published", "approved", false).
@@ -245,12 +276,7 @@ func (r *Repository) publicZoneCountsCached(ctx context.Context) (map[string]int
nonPremiumTotal++
}
}
r.publicZoneCounts = publicZoneCountCache{
Counts: counts,
NonPremiumTotal: nonPremiumTotal,
ExpiresAt: now.Add(publicZoneCountCacheTTL),
}
return copyPublicZoneCounts(counts), nonPremiumTotal, nil
return counts, nonPremiumTotal, nil
}
func copyPublicZoneCounts(counts map[string]int64) map[string]int64 {
@@ -262,10 +288,13 @@ func copyPublicZoneCounts(counts map[string]int64) map[string]int64 {
}
func (r *Repository) FindPublic(ctx context.Context, id uint64, siteCode string, viewerUserID uint64) (*ListingDTO, error) {
dto, err := r.findDTO(ctx, "l.id = ? AND l.status = ? AND l.review_status = ? AND l.in_transaction = ?", id, "published", "approved", false)
if err != nil {
var row listingRow
query := applyTenantOfferVisibility(ctx, r.baseQuery(ctx)).
Where("l.id = ? AND l.status = ? AND l.review_status = ? AND l.in_transaction = ?", id, "published", "approved", false)
if err := query.First(&row).Error; err != nil {
return nil, err
}
dto := row.toDTO()
if dto.IsPremium {
canView, err := r.canViewPremium(ctx, viewerUserID)
if err != nil {
@@ -275,13 +304,56 @@ func (r *Repository) FindPublic(ctx context.Context, id uint64, siteCode string,
return nil, gorm.ErrRecordNotFound
}
}
applyPublicListingURLs(dto)
items := []ListingDTO{*dto}
applyPublicListingURLs(&dto)
items := []ListingDTO{dto}
if err := r.applyTenantOfferPrices(ctx, items); err != nil {
return nil, err
}
if err := r.applyShelfMarkup(ctx, siteCode, items); err != nil {
return nil, err
}
*dto = items[0]
return dto, nil
dto = items[0]
return &dto, nil
}
func applyTenantOfferVisibility(ctx context.Context, db *gorm.DB) *gorm.DB {
tenantID := tenancy.IDFromContext(ctx)
if tenantID == 0 {
return db
}
return db.Joins(
"INNER JOIN tenant_listing_offers AS tlo ON tlo.listing_id = l.id AND tlo.tenant_id = ? AND tlo.display_status = 'enabled'",
tenantID,
)
}
func (r *Repository) applyTenantOfferPrices(ctx context.Context, items []ListingDTO) error {
tenantID := tenancy.IDFromContext(ctx)
if tenantID == 0 || len(items) == 0 {
return nil
}
ids := make([]uint64, 0, len(items))
for _, item := range items {
ids = append(ids, item.ID)
}
var offers []model.TenantListingOffer
if err := r.db.WithContext(ctx).
Where("tenant_id = ? AND listing_id IN ?", tenantID, ids).
Find(&offers).Error; err != nil {
return err
}
prices := make(map[uint64]int64, len(offers))
for _, offer := range offers {
if offer.PriceCent != nil && *offer.PriceCent > 0 {
prices[offer.ListingID] = *offer.PriceCent
}
}
for index := range items {
if price, ok := prices[items[index].ID]; ok {
items[index].PriceCent = price
}
}
return nil
}
func (r *Repository) canViewPremium(ctx context.Context, userID uint64) (bool, error) {
@@ -363,10 +435,13 @@ func (r *Repository) FindPublicScreenshotKey(ctx context.Context, id uint64, ind
if index < 0 {
return "", gorm.ErrRecordNotFound
}
dto, err := r.findDTO(ctx, "l.id = ? AND l.status = ? AND l.review_status = ? AND l.in_transaction = ?", id, "published", "approved", false)
if err != nil {
var row listingRow
query := applyTenantOfferVisibility(ctx, r.baseQuery(ctx)).
Where("l.id = ? AND l.status = ? AND l.review_status = ? AND l.in_transaction = ?", id, "published", "approved", false)
if err := query.First(&row).Error; err != nil {
return "", err
}
dto := row.toDTO()
if index >= len(dto.ScreenshotURLS) {
return "", gorm.ErrRecordNotFound
}
+41 -2
View File
@@ -7,7 +7,9 @@ import (
"time"
"gorm.io/gorm"
"gorm.io/gorm/clause"
"hfb_sys/backend/internal/model"
"hfb_sys/backend/internal/tenancy"
)
// ListingChatCreator 发布群创建接口(由 chat 模块实现,避免直接依赖)
@@ -49,13 +51,50 @@ func (r *Repository) SetShelfSyncer(syncer ListingShelfSyncer) {
// syncPublishedShelf 只在商品真正对外可售(published + approved)时铺货到各分站货架。
// 草稿、待审核、已下架商品不需要铺货:分站前台本身就要求 published + approved 才展示。
func (r *Repository) syncPublishedShelf(tx *gorm.DB, listing *model.RentalListing) error {
if r == nil || r.shelfSyncer == nil || listing == nil {
if r == nil || listing == nil {
return nil
}
if listing.Status != "published" || listing.ReviewStatus != "approved" {
return nil
}
return r.shelfSyncer.EnsureListingShelvedTx(tx, listing.ID, listing.AccountID)
if r.shelfSyncer != nil {
if err := r.shelfSyncer.EnsureListingShelvedTx(tx, listing.ID, listing.AccountID); err != nil {
return err
}
}
return r.ensureTenantListingOffersTx(tx, listing.ID)
}
func (r *Repository) ensureTenantListingOffersTx(tx *gorm.DB, listingID uint64) error {
if tx == nil || listingID == 0 {
return nil
}
var tenantIDs []uint64
if err := tx.Model(&model.Tenant{}).
Where("status = ?", "active").
Pluck("id", &tenantIDs).Error; err != nil {
return err
}
if len(tenantIDs) == 0 {
return nil
}
offers := make([]model.TenantListingOffer, 0, len(tenantIDs))
for _, tenantID := range tenantIDs {
offers = append(offers, model.TenantListingOffer{
TenantID: tenantID,
ListingID: listingID,
DisplayStatus: "enabled",
})
}
return tx.Clauses(clause.OnConflict{DoNothing: true}).Create(&offers).Error
}
func userTenantID(ctx context.Context, tx *gorm.DB, userID uint64) uint64 {
var tenantID uint64
if err := tx.Model(&model.User{}).Select("tenant_id").Where("id = ?", userID).Scan(&tenantID).Error; err == nil && tenantID > 0 {
return tenantID
}
return tenancy.IDFromContext(ctx)
}
func (r *Repository) IsQualityOwner(ctx context.Context, userID uint64) (bool, error) {
@@ -70,7 +70,9 @@ func (r *Repository) TransferOwner(ctx context.Context, adminID uint64, listingI
listing.HandoffMode = "owner"
listing.SettlementMode = "owner_wallet"
listing.ManagedAdminID = nil
listing.SourceTenantID = target.TenantID
account.OwnerID = target.ID
account.SourceTenantID = target.TenantID
if err := tx.Save(account).Error; err != nil {
return err
}
@@ -35,6 +35,8 @@ var (
ErrDistributionSiteInvalid = errors.New("invalid distribution site")
ErrPremiumOwnerRequired = errors.New("premium listing requires quality owner")
ErrQualityRatioPremiumOnly = errors.New("quality owner exclusive ratio requires premium zone")
ErrTenantRequired = errors.New("tenant context required")
ErrListingNotFound = errors.New("listing not found")
)
type Service struct {
@@ -0,0 +1,21 @@
package listing
import "context"
func (s *Service) FindTenantOffer(ctx context.Context, listingID uint64) (*TenantListingOfferDTO, error) {
if s.repo == nil {
return nil, ErrDependencyUnavailable
}
return s.repo.FindTenantOffer(ctx, listingID)
}
func (s *Service) UpdateTenantOffer(
ctx context.Context,
listingID uint64,
req UpdateTenantListingOfferRequest,
) (*TenantListingOfferDTO, error) {
if s.repo == nil {
return nil, ErrDependencyUnavailable
}
return s.repo.UpdateTenantOffer(ctx, listingID, req)
}
@@ -0,0 +1,86 @@
package listing
import (
"context"
"errors"
"strings"
"hfb_sys/backend/internal/model"
"hfb_sys/backend/internal/tenancy"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
func (r *Repository) FindTenantOffer(ctx context.Context, listingID uint64) (*TenantListingOfferDTO, error) {
tenantID := tenancy.IDFromContext(ctx)
if tenantID == 0 {
return nil, ErrTenantRequired
}
var listing model.RentalListing
if err := r.db.WithContext(ctx).Select("id, price_cent").First(&listing, listingID).Error; err != nil {
return nil, err
}
var offer model.TenantListingOffer
if err := r.db.WithContext(ctx).
Where("tenant_id = ? AND listing_id = ?", tenantID, listingID).
First(&offer).Error; err != nil {
return nil, err
}
return tenantOfferDTO(offer, listing.PriceCent), nil
}
func (r *Repository) UpdateTenantOffer(
ctx context.Context,
listingID uint64,
req UpdateTenantListingOfferRequest,
) (*TenantListingOfferDTO, error) {
tenantID := tenancy.IDFromContext(ctx)
if tenantID == 0 {
return nil, ErrTenantRequired
}
displayStatus := strings.TrimSpace(req.DisplayStatus)
if displayStatus == "" {
displayStatus = "enabled"
}
if displayStatus != "enabled" && displayStatus != "disabled" {
return nil, ErrInvalidInput
}
if req.PriceCent != nil && *req.PriceCent < 0 {
return nil, ErrInvalidPrice
}
var listing model.RentalListing
if err := r.db.WithContext(ctx).Select("id, price_cent").First(&listing, listingID).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrListingNotFound
}
return nil, err
}
offer := model.TenantListingOffer{
TenantID: tenantID,
ListingID: listingID,
DisplayStatus: displayStatus,
PriceCent: req.PriceCent,
}
if err := r.db.WithContext(ctx).Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "tenant_id"}, {Name: "listing_id"}},
DoUpdates: clause.AssignmentColumns([]string{"display_status", "price_cent", "updated_at"}),
}).Create(&offer).Error; err != nil {
return nil, err
}
return tenantOfferDTO(offer, listing.PriceCent), nil
}
func tenantOfferDTO(offer model.TenantListingOffer, basePriceCent int64) *TenantListingOfferDTO {
effectivePriceCent := basePriceCent
if offer.PriceCent != nil && *offer.PriceCent > 0 {
effectivePriceCent = *offer.PriceCent
}
return &TenantListingOfferDTO{
TenantID: offer.TenantID,
ListingID: offer.ListingID,
DisplayStatus: offer.DisplayStatus,
PriceCent: offer.PriceCent,
EffectivePriceCent: effectivePriceCent,
}
}
@@ -0,0 +1,149 @@
package listing
import (
"context"
"testing"
"hfb_sys/backend/internal/database"
"hfb_sys/backend/internal/model"
"hfb_sys/backend/internal/tenancy"
"gorm.io/datatypes"
)
func listingTenantContext(tenantID uint64) context.Context {
return tenancy.WithScope(context.Background(), tenancy.Scope{TenantID: tenantID})
}
func TestPublicListingUsesCurrentTenantOffer(t *testing.T) {
db := database.NewTestDB()
dachui := model.Tenant{Code: "dachui", Name: "大锤商行", Status: "active"}
jieyou := model.Tenant{Code: "jieyou", Name: "解忧商行", Status: "active"}
other := model.Tenant{Code: "other", Name: "其他租户", Status: "active"}
if err := db.Create(&dachui).Error; err != nil {
t.Fatal(err)
}
if err := db.Create(&jieyou).Error; err != nil {
t.Fatal(err)
}
if err := db.Create(&other).Error; err != nil {
t.Fatal(err)
}
owner := model.User{TenantID: dachui.ID, Phone: "13100000001", Status: "active"}
if err := db.Create(&owner).Error; err != nil {
t.Fatal(err)
}
account := model.GameAccount{
SourceTenantID: dachui.ID, OwnerID: owner.ID, ServerRegion: "国服",
LoginPlatform: "steam", Title: "跨站货架商品", Status: "published",
ScreenshotURLS: datatypes.JSON([]byte(`["/api/files/object?key=listing%2Ftenant-offer.jpg"]`)),
}
if err := db.Create(&account).Error; err != nil {
t.Fatal(err)
}
listing := model.RentalListing{
SourceTenantID: dachui.ID, ListingNo: "L-TENANT-OFFER-1",
AccountID: account.ID, OwnerID: owner.ID, PriceCent: 10000,
Status: "published", ReviewStatus: "approved",
}
if err := db.Create(&listing).Error; err != nil {
t.Fatal(err)
}
jieyouPrice := int64(12000)
offers := []model.TenantListingOffer{
{TenantID: dachui.ID, ListingID: listing.ID, DisplayStatus: "enabled"},
{TenantID: jieyou.ID, ListingID: listing.ID, DisplayStatus: "enabled", PriceCent: &jieyouPrice},
}
if err := db.Create(&offers).Error; err != nil {
t.Fatal(err)
}
repo := NewRepository(db, nil)
dachuiResult, err := repo.ListPublic(listingTenantContext(dachui.ID), PublicListQuery{})
if err != nil {
t.Fatal(err)
}
if dachuiResult.Total != 1 || dachuiResult.Items[0].PriceCent != 10000 {
t.Fatalf("dachui listing = %+v", dachuiResult)
}
jieyouResult, err := repo.ListPublic(listingTenantContext(jieyou.ID), PublicListQuery{Keyword: "跨站货架"})
if err != nil {
t.Fatal(err)
}
if jieyouResult.Total != 1 || jieyouResult.Items[0].PriceCent != 12000 {
t.Fatalf("jieyou listing = %+v", jieyouResult)
}
otherResult, err := repo.ListPublic(listingTenantContext(other.ID), PublicListQuery{})
if err != nil {
t.Fatal(err)
}
if otherResult.Total != 0 {
t.Fatalf("other tenant must not see listing, got %+v", otherResult)
}
updatedPrice := int64(13000)
updated, err := repo.UpdateTenantOffer(listingTenantContext(jieyou.ID), listing.ID, UpdateTenantListingOfferRequest{
DisplayStatus: "enabled",
PriceCent: &updatedPrice,
})
if err != nil {
t.Fatalf("update tenant offer: %v", err)
}
if updated.EffectivePriceCent != 13000 {
t.Fatalf("updated offer price = %d, want 13000", updated.EffectivePriceCent)
}
jieyouResult, err = repo.ListPublic(listingTenantContext(jieyou.ID), PublicListQuery{})
if err != nil {
t.Fatal(err)
}
if jieyouResult.Total != 1 || jieyouResult.Items[0].PriceCent != 13000 {
t.Fatalf("updated jieyou listing price = %+v", jieyouResult)
}
if _, err := repo.UpdateTenantOffer(listingTenantContext(jieyou.ID), listing.ID, UpdateTenantListingOfferRequest{
DisplayStatus: "disabled",
}); err != nil {
t.Fatal(err)
}
if _, err := repo.FindPublic(listingTenantContext(jieyou.ID), listing.ID, "", 0); err == nil {
t.Fatal("disabled tenant offer must hide listing detail")
}
if _, err := repo.FindPublicScreenshotKey(listingTenantContext(jieyou.ID), listing.ID, 0); err == nil {
t.Fatal("disabled tenant offer must hide listing screenshots")
}
}
func TestPublishedListingCreatesOffersForAllActiveTenants(t *testing.T) {
db := database.NewTestDB()
dachui := model.Tenant{Code: "dachui", Name: "大锤商行", Status: "active"}
jieyou := model.Tenant{Code: "jieyou", Name: "解忧商行", Status: "active"}
if err := db.Create(&dachui).Error; err != nil {
t.Fatal(err)
}
if err := db.Create(&jieyou).Error; err != nil {
t.Fatal(err)
}
owner := model.User{TenantID: dachui.ID, Phone: "13100000002", Status: "active"}
if err := db.Create(&owner).Error; err != nil {
t.Fatal(err)
}
repo := NewRepository(db, nil)
dto, err := repo.Create(listingTenantContext(dachui.ID), owner.ID, validCreateRequest(), false, 0)
if err != nil {
t.Fatalf("create listing: %v", err)
}
if dto.SourceTenantID != dachui.ID {
t.Fatalf("source tenant = %d, want %d", dto.SourceTenantID, dachui.ID)
}
var offers []model.TenantListingOffer
if err := db.Where("listing_id = ?", dto.ID).Order("tenant_id ASC").Find(&offers).Error; err != nil {
t.Fatal(err)
}
if len(offers) != 2 || offers[0].TenantID != dachui.ID || offers[1].TenantID != jieyou.ID {
t.Fatalf("tenant offers = %+v", offers)
}
for _, offer := range offers {
if offer.DisplayStatus != "enabled" {
t.Fatalf("offer should default enabled: %+v", offer)
}
}
}
+4
View File
@@ -10,6 +10,9 @@ import (
type OrderDTO struct {
ID uint64 `json:"id"`
BuyerTenantID uint64 `json:"buyer_tenant_id"`
SourceTenantID uint64 `json:"source_tenant_id"`
PaymentTenantID uint64 `json:"payment_tenant_id"`
OrderNo string `json:"order_no"`
ListingID uint64 `json:"listing_id"`
ListingNo string `json:"listing_no"`
@@ -28,6 +31,7 @@ type OrderDTO struct {
DisplayAmountCent int64 `json:"display_amount_cent"`
RentAmountCent *int64 `json:"rent_amount_cent,omitempty"`
OwnerRentAmountCent *int64 `json:"owner_rent_amount_cent,omitempty"`
SourceAmountCent int64 `json:"source_amount_cent"`
DepositAmountCent int64 `json:"deposit_amount_cent"`
DepositOriginalAmountCent int64 `json:"deposit_original_amount_cent"`
DepositWaivedAmountCent int64 `json:"deposit_waived_amount_cent"`
+56 -6
View File
@@ -16,6 +16,7 @@ import (
"hfb_sys/backend/internal/modules/rentergrowth"
smsnode "hfb_sys/backend/internal/modules/sms"
"hfb_sys/backend/internal/processlog"
"hfb_sys/backend/internal/tenancy"
"gorm.io/datatypes"
"gorm.io/gorm"
@@ -35,6 +36,32 @@ func (r *Repository) Create(ctx context.Context, renterID uint64, req CreateRequ
if listing.OwnerID == renterID {
return ErrCannotRentOwnListing
}
var renter model.User
if err := tx.Select("id, tenant_id, register_track_code").First(&renter, renterID).Error; err != nil {
return err
}
requestTenantID := tenancy.IDFromContext(ctx)
if requestTenantID > 0 && renter.TenantID != requestTenantID {
return ErrPermissionDenied
}
buyerTenantID := renter.TenantID
if requestTenantID > 0 {
buyerTenantID = requestTenantID
}
tenantOfferPrice, tenantOfferFound, err := loadTenantOfferPriceTx(tx, buyerTenantID, listing.ID)
if err != nil {
return err
}
if requestTenantID > 0 && !tenantOfferFound {
return ErrListingUnavailable
}
sourceTenantID := listing.SourceTenantID
if sourceTenantID == 0 {
_ = tx.Model(&model.User{}).
Select("tenant_id").
Where("id = ?", listing.OwnerID).
Scan(&sourceTenantID).Error
}
var account model.GameAccount
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&account, listing.AccountID).Error; err != nil {
@@ -64,9 +91,13 @@ func (r *Repository) Create(ctx context.Context, renterID uint64, req CreateRequ
if err != nil {
return err
}
pricing := buildOrderPricing(listing, account)
basePriceCent := listing.PriceCent
sitePriceCent, _, siteRatio := listingpkg.ApplyShelfRatio(account.HafCoinAmount, listing.PriceCent, shelfRatioDelta)
effectiveListing := listing
if tenantOfferFound && tenantOfferPrice != nil && *tenantOfferPrice > 0 {
effectiveListing.PriceCent = *tenantOfferPrice
}
pricing := buildOrderPricing(effectiveListing, account)
basePriceCent := effectiveListing.PriceCent
sitePriceCent, _, siteRatio := listingpkg.ApplyShelfRatio(account.HafCoinAmount, effectiveListing.PriceCent, shelfRatioDelta)
shelfMarkupCent := sitePriceCent - basePriceCent
if sitePriceCent != listing.PriceCent {
pricing.RentAmountCent = sitePriceCent
@@ -118,12 +149,14 @@ func (r *Repository) Create(ctx context.Context, renterID uint64, req CreateRequ
}
sourceTrackCode := sanitizeTrackCode(req.TrackCode)
if sourceTrackCode == "" {
var u model.User
if err := tx.Select("register_track_code").First(&u, renterID).Error; err == nil && u.RegisterTrackCode != "" {
sourceTrackCode = sanitizeTrackCode(u.RegisterTrackCode)
if renter.RegisterTrackCode != "" {
sourceTrackCode = sanitizeTrackCode(renter.RegisterTrackCode)
}
}
order := model.RentalOrder{
BuyerTenantID: buyerTenantID,
SourceTenantID: sourceTenantID,
PaymentTenantID: buyerTenantID,
OrderNo: orderNo,
ListingID: listing.ID,
AccountID: listing.AccountID,
@@ -132,6 +165,7 @@ func (r *Repository) Create(ctx context.Context, renterID uint64, req CreateRequ
EstimatedDurationHours: rentHours,
RentAmountCent: pricing.RentAmountCent,
OwnerRentAmountCent: pricing.OwnerRentAmountCent,
SourceAmountCent: pricing.OwnerRentAmountCent,
DepositAmountCent: depositWaiver.PaidCent,
DepositOriginalAmountCent: depositOriginalAmountCent,
DepositWaivedAmountCent: depositWaiver.WaivedCent,
@@ -200,6 +234,22 @@ func (r *Repository) Create(ctx context.Context, renterID uint64, req CreateRequ
return r.FindForUser(ctx, renterID, createdID, req.DistributionSiteCode)
}
func loadTenantOfferPriceTx(tx *gorm.DB, tenantID uint64, listingID uint64) (*int64, bool, error) {
if tenantID == 0 {
return nil, false, nil
}
var offer model.TenantListingOffer
err := tx.Where("tenant_id = ? AND listing_id = ? AND display_status = ?", tenantID, listingID, "enabled").
First(&offer).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, false, nil
}
if err != nil {
return nil, false, err
}
return offer.PriceCent, true, nil
}
func normalizedCompensationPlan(plan string) string {
if plan == "insurance" {
return "insurance"
@@ -67,6 +67,9 @@ func (row orderRow) toAdminDTO() OrderDTO {
platformFeeCent := row.PlatformFeeCent
return OrderDTO{
ID: row.ID,
BuyerTenantID: row.BuyerTenantID,
SourceTenantID: row.SourceTenantID,
PaymentTenantID: row.PaymentTenantID,
OrderNo: row.OrderNo,
ListingID: row.ListingID,
ListingNo: row.ListingNo,
@@ -85,6 +88,7 @@ func (row orderRow) toAdminDTO() OrderDTO {
DisplayAmountCent: row.RentAmountCent,
RentAmountCent: &rentAmountCent,
OwnerRentAmountCent: &ownerRentAmountCent,
SourceAmountCent: row.SourceAmountCent,
DepositAmountCent: row.DepositAmountCent,
DepositOriginalAmountCent: effectiveDepositOriginalAmountCent(row.RentalOrder),
DepositWaivedAmountCent: row.DepositWaivedAmountCent,
@@ -0,0 +1,171 @@
package order
import (
"context"
"errors"
"sync"
"testing"
"hfb_sys/backend/internal/model"
"hfb_sys/backend/internal/tenancy"
"gorm.io/datatypes"
"gorm.io/gorm"
)
func orderTenantContext(tenantID uint64) context.Context {
return tenancy.WithScope(context.Background(), tenancy.Scope{TenantID: tenantID})
}
func createOrderTenantListing(t *testing.T, db *gorm.DB, tenantIDs ...uint64) (*model.RentalListing, []model.User) {
t.Helper()
var tenants []model.Tenant
for index, tenantID := range tenantIDs {
tenant := model.Tenant{
Code: "tenant_" + string(rune('a'+index)),
Name: "租户",
Status: "active",
}
tenant.ID = tenantID
if err := db.Create(&tenant).Error; err != nil {
t.Fatal(err)
}
tenants = append(tenants, tenant)
}
owner := model.User{TenantID: tenants[0].ID, Phone: "13000000001", Status: "active"}
if err := db.Create(&owner).Error; err != nil {
t.Fatal(err)
}
account := model.GameAccount{
SourceTenantID: tenants[0].ID, OwnerID: owner.ID, ServerRegion: "国服",
LoginPlatform: "steam", Title: "跨租户商品", Status: "published",
AssetSummary: datatypes.JSON([]byte(`{
"price_breakdown": {
"seller_total_price": 80,
"platform_markup_amount": 20
}
}`)),
}
if err := db.Create(&account).Error; err != nil {
t.Fatal(err)
}
listing := model.RentalListing{
SourceTenantID: tenants[0].ID, ListingNo: "L-ORDER-TENANT-1",
AccountID: account.ID, OwnerID: owner.ID, PriceCent: 10000,
Status: listingStatusPublished, ReviewStatus: listingReviewStatusApproved,
}
if err := db.Create(&listing).Error; err != nil {
t.Fatal(err)
}
for index, tenantID := range tenantIDs {
var price *int64
if index > 0 {
value := int64(10000 + index*2000)
price = &value
}
if err := db.Create(&model.TenantListingOffer{
TenantID: tenantID, ListingID: listing.ID, DisplayStatus: "enabled", PriceCent: price,
}).Error; err != nil {
t.Fatal(err)
}
}
renters := make([]model.User, 0, len(tenantIDs)-1)
for index, tenantID := range tenantIDs[1:] {
renter := model.User{
TenantID: tenantID,
Phone: "1300000001" + string(rune('0'+index+1)),
Status: "active",
}
if err := db.Create(&renter).Error; err != nil {
t.Fatal(err)
}
renters = append(renters, renter)
}
return &listing, renters
}
func TestCreateOrderUsesBuyerTenantOfferAndSnapshotsTenantRoles(t *testing.T) {
db := setupOrderTestDB(t)
listing, renters := createOrderTenantListing(t, db, 101, 202, 303)
repo := NewRepository(db)
noOfferTenant := model.Tenant{ID: 404, Code: "tenant_no_offer", Name: "无货架租户", Status: "active"}
if err := db.Create(&noOfferTenant).Error; err != nil {
t.Fatal(err)
}
noOfferRenter := model.User{TenantID: noOfferTenant.ID, Phone: "13000000019", Status: "active"}
if err := db.Create(&noOfferRenter).Error; err != nil {
t.Fatal(err)
}
if _, err := repo.Create(orderTenantContext(noOfferTenant.ID), noOfferRenter.ID, CreateRequest{ListingID: listing.ID}); !errors.Is(err, ErrListingUnavailable) {
t.Fatalf("tenant without offer error = %v, want ErrListingUnavailable", err)
}
dto, err := repo.Create(orderTenantContext(202), renters[0].ID, CreateRequest{ListingID: listing.ID})
if err != nil {
t.Fatalf("create cross-tenant order: %v", err)
}
if dto.BuyerTenantID != 202 || dto.SourceTenantID != 101 || dto.PaymentTenantID != 202 {
t.Fatalf("order tenant snapshots = buyer:%d source:%d payment:%d",
dto.BuyerTenantID, dto.SourceTenantID, dto.PaymentTenantID)
}
if dto.BasePriceCent != 12000 || dto.ShelfMarkupCent != 0 {
t.Fatalf("offer price snapshot = base:%d markup:%d", dto.BasePriceCent, dto.ShelfMarkupCent)
}
if dto.SourceAmountCent != 8000 {
t.Fatalf("source amount snapshot = %d, want 8000", dto.SourceAmountCent)
}
var saved model.RentalOrder
if err := db.First(&saved, dto.ID).Error; err != nil {
t.Fatal(err)
}
if saved.BuyerTenantID != 202 || saved.SourceTenantID != 101 || saved.PaymentTenantID != 202 {
t.Fatalf("saved tenant roles = %+v", saved)
}
if saved.OwnerRentAmountCent != saved.SourceAmountCent {
t.Fatalf("source amount = %d, owner rent = %d", saved.SourceAmountCent, saved.OwnerRentAmountCent)
}
}
func TestConcurrentTenantsCanOnlyRentListingOnce(t *testing.T) {
db := setupOrderTestDB(t)
listing, renters := createOrderTenantListing(t, db, 101, 202, 303)
repo := NewRepository(db)
start := make(chan struct{})
results := make(chan error, 2)
var wg sync.WaitGroup
for index, tenantID := range []uint64{202, 303} {
wg.Add(1)
go func(renterID uint64, tenantID uint64) {
defer wg.Done()
<-start
_, err := repo.Create(orderTenantContext(tenantID), renterID, CreateRequest{ListingID: listing.ID})
results <- err
}(renters[index].ID, tenantID)
}
close(start)
wg.Wait()
close(results)
var success, unavailable int
for err := range results {
switch {
case err == nil:
success++
case errors.Is(err, ErrListingUnavailable):
unavailable++
default:
t.Fatalf("unexpected create order error: %v", err)
}
}
if success != 1 || unavailable != 1 {
t.Fatalf("concurrent order result = success:%d unavailable:%d", success, unavailable)
}
var count int64
if err := db.Model(&model.RentalOrder{}).Where("listing_id = ?", listing.ID).Count(&count).Error; err != nil {
t.Fatal(err)
}
if count != 1 {
t.Fatalf("order count = %d, want 1", count)
}
}
+2
View File
@@ -901,6 +901,8 @@ func New(cfg config.Config, deps Dependencies, logger *zap.Logger) *gin.Engine {
adminRoutes.GET("/listings", requirePerm("listing:view"), listingHandler.ListAdmin)
adminRoutes.GET("/listings/pending", requirePerm("listing:approve"), listingHandler.ListPendingReview)
adminRoutes.GET("/listings/:id", requirePerm("listing:view"), listingHandler.FindAdmin)
adminRoutes.GET("/listings/:id/tenant-offer", requirePerm("listing:view"), listingHandler.FindTenantOffer)
adminRoutes.PUT("/listings/:id/tenant-offer", requirePerm("listing:approve"), listingHandler.UpdateTenantOffer)
adminRoutes.POST("/listings/:id/approve", requirePerm("listing:approve"), listingHandler.Approve)
adminRoutes.POST("/listings/:id/adjust-price", requirePerm("listing:approve"), listingHandler.AdjustReviewPrice)
adminRoutes.PUT("/listings/:id/external-adjustment", requirePerm("listing:edit_external"), listingHandler.AdjustExternalListing)