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
+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)
}
}
}