MySQL DATETIME(0) 会把小数秒四舍五入,now-2天 可能进位成不足 48 小时而被算作 1 天,导致用例偶发失败;统一 Truncate 到整秒。
1149 lines
42 KiB
Go
1149 lines
42 KiB
Go
package pickup
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"hfb_sys/backend/internal/auditlog"
|
|
"hfb_sys/backend/internal/database"
|
|
"hfb_sys/backend/internal/model"
|
|
|
|
"gorm.io/datatypes"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
func TestBuildPickupPriceSnapshotSplitsOwnerPrice(t *testing.T) {
|
|
raw, err := json.Marshal(map[string]any{
|
|
"price_breakdown": map[string]any{
|
|
"seller_coin_base_price": 233,
|
|
"seller_total_price": 353,
|
|
"platform_markup_amount": 30,
|
|
"consumable_price": 120,
|
|
"seller_ratio": 42.9,
|
|
"buyer_ratio": 35.1,
|
|
},
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("构造资产快照失败: %v", err)
|
|
}
|
|
|
|
snapshot := buildPickupPriceSnapshot(
|
|
model.RentalListing{PriceCent: 38300},
|
|
model.GameAccount{HafCoinAmount: 100000000, AssetSummary: datatypes.JSON(raw)},
|
|
)
|
|
|
|
assertInt64(t, "网站售价", snapshot.ListingPriceCent, 38300)
|
|
assertInt64(t, "号主纯比价格", snapshot.OwnerPurePriceCent, 23300)
|
|
assertInt64(t, "额外物品价格", snapshot.OwnerExtraItemPriceCent, 12000)
|
|
assertInt64(t, "号主总价", snapshot.OwnerTotalPriceCent, 35300)
|
|
assertInt64(t, "兼容号主价", snapshot.OwnerPriceCent, 35300)
|
|
assertInt64(t, "网站加价", snapshot.WebsiteProfitCent, 3000)
|
|
if snapshot.SellerRatio != 42.9 || snapshot.BuyerRatio != 35.1 {
|
|
t.Fatalf("比例 = %.2f/%.2f, want 42.90/35.10", snapshot.SellerRatio, snapshot.BuyerRatio)
|
|
}
|
|
}
|
|
|
|
func TestBuildPickupPriceSnapshotFallsBackToSplitSum(t *testing.T) {
|
|
raw, err := json.Marshal(map[string]any{
|
|
"price_breakdown": map[string]any{
|
|
"seller_coin_base_price": 200,
|
|
"consumable_price": 50,
|
|
},
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("构造资产快照失败: %v", err)
|
|
}
|
|
|
|
snapshot := buildPickupPriceSnapshot(
|
|
model.RentalListing{PriceCent: 30000},
|
|
model.GameAccount{AssetSummary: datatypes.JSON(raw)},
|
|
)
|
|
|
|
assertInt64(t, "拆分合计总价", snapshot.OwnerTotalPriceCent, 25000)
|
|
assertInt64(t, "纯比价格", snapshot.OwnerPurePriceCent, 20000)
|
|
assertInt64(t, "额外物品价格", snapshot.OwnerExtraItemPriceCent, 5000)
|
|
assertInt64(t, "网站加价兜底", snapshot.WebsiteProfitCent, 5000)
|
|
}
|
|
|
|
func TestRepositoryUpdateProfitAllowsPickingUp(t *testing.T) {
|
|
repo, db := newPickupTestRepo(t)
|
|
pickup := seedPickup(t, db, StatusPickingUp)
|
|
|
|
item, err := repo.UpdateProfit(t.Context(), pickup.ID, UpdateProfitRequest{
|
|
ProfitAmountCent: 2500,
|
|
Reason: "线下扣点调整",
|
|
}, 99, auditlog.Meta{RequestID: "req-profit"})
|
|
if err != nil {
|
|
t.Fatalf("UpdateProfit() error = %v", err)
|
|
}
|
|
assertInt64(t, "修改后利润", item.ProfitAmountCent, 2500)
|
|
|
|
var stored model.AdminPickup
|
|
if err := db.First(&stored, pickup.ID).Error; err != nil {
|
|
t.Fatalf("查询提号失败: %v", err)
|
|
}
|
|
assertInt64(t, "数据库利润", stored.ProfitAmountCent, 2500)
|
|
|
|
var audit model.AuditLog
|
|
if err := db.Where("action = ?", "pickup_profit_update").First(&audit).Error; err != nil {
|
|
t.Fatalf("查询审计日志失败: %v", err)
|
|
}
|
|
var detail map[string]any
|
|
if err := json.Unmarshal(audit.Detail, &detail); err != nil {
|
|
t.Fatalf("解析审计日志失败: %v", err)
|
|
}
|
|
assertJSONNumber(t, "旧利润", detail["old_profit_amount_cent"], 1000)
|
|
assertJSONNumber(t, "新利润", detail["new_profit_amount_cent"], 2500)
|
|
if detail["reason"] != "线下扣点调整" {
|
|
t.Fatalf("reason = %v, want 线下扣点调整", detail["reason"])
|
|
}
|
|
}
|
|
|
|
func TestRepositoryUpdateProfitRejectsCompleted(t *testing.T) {
|
|
repo, db := newPickupTestRepo(t)
|
|
pickup := seedPickup(t, db, StatusCompleted)
|
|
|
|
_, err := repo.UpdateProfit(t.Context(), pickup.ID, UpdateProfitRequest{ProfitAmountCent: 2500}, 99, auditlog.Meta{})
|
|
if !errors.Is(err, ErrPickupNotPickingUp) {
|
|
t.Fatalf("UpdateProfit() error = %v, want ErrPickupNotPickingUp", err)
|
|
}
|
|
|
|
var stored model.AdminPickup
|
|
if err := db.First(&stored, pickup.ID).Error; err != nil {
|
|
t.Fatalf("查询提号失败: %v", err)
|
|
}
|
|
assertInt64(t, "已完成提号利润", stored.ProfitAmountCent, 1000)
|
|
|
|
var auditCount int64
|
|
if err := db.Model(&model.AuditLog{}).Where("action = ?", "pickup_profit_update").Count(&auditCount).Error; err != nil {
|
|
t.Fatalf("统计审计日志失败: %v", err)
|
|
}
|
|
if auditCount != 0 {
|
|
t.Fatalf("审计日志数量 = %d, want 0", auditCount)
|
|
}
|
|
}
|
|
|
|
func TestRepositoryListAdminFiltersShopName(t *testing.T) {
|
|
repo, db := newPickupTestRepo(t)
|
|
first := seedPickup(t, db, StatusPickingUp)
|
|
if err := db.Model(&first).Updates(map[string]any{
|
|
"platform": "淘宝",
|
|
"shop_name": "大锤一店",
|
|
}).Error; err != nil {
|
|
t.Fatalf("设置第一条提号店铺失败: %v", err)
|
|
}
|
|
second := first
|
|
second.ID = 0
|
|
second.PickupNo = "PK-PROFIT-002"
|
|
second.ShopName = "大锤二店"
|
|
if err := db.Create(&second).Error; err != nil {
|
|
t.Fatalf("创建第二条提号记录失败: %v", err)
|
|
}
|
|
|
|
result, err := repo.ListAdmin(t.Context(), AdminPickupQuery{ShopName: " 大锤一店 "})
|
|
if err != nil {
|
|
t.Fatalf("ListAdmin() error = %v", err)
|
|
}
|
|
if result.Total != 1 || len(result.Items) != 1 {
|
|
t.Fatalf("店铺筛选结果 = total %d, items %d, want 1", result.Total, len(result.Items))
|
|
}
|
|
if result.Items[0].ShopName != "大锤一店" {
|
|
t.Fatalf("店铺名称 = %q, want 大锤一店", result.Items[0].ShopName)
|
|
}
|
|
}
|
|
|
|
func TestRepositoryListAdminFiltersOwnerPhone(t *testing.T) {
|
|
repo, db := newPickupTestRepo(t)
|
|
pickup := seedPickup(t, db, StatusPickingUp)
|
|
|
|
result, err := repo.ListAdmin(t.Context(), AdminPickupQuery{Keyword: "000000"})
|
|
if err != nil {
|
|
t.Fatalf("ListAdmin() error = %v", err)
|
|
}
|
|
if result.Total != 1 || len(result.Items) != 1 {
|
|
t.Fatalf("手机号搜索结果 = total %d, items %d, want 1", result.Total, len(result.Items))
|
|
}
|
|
if result.Items[0].ID != pickup.ID || result.Items[0].OwnerPhone != "18800000000" {
|
|
t.Fatalf(
|
|
"手机号搜索结果 = id %d, phone %q, want id %d, phone 18800000000",
|
|
result.Items[0].ID,
|
|
result.Items[0].OwnerPhone,
|
|
pickup.ID,
|
|
)
|
|
}
|
|
}
|
|
|
|
func TestRepositoryListAdminFiltersOfflineSettlementStatus(t *testing.T) {
|
|
repo, db := newPickupTestRepo(t)
|
|
first := seedPickup(t, db, StatusCompleted)
|
|
if err := db.Model(&first).Updates(map[string]any{
|
|
"settlement_mode": SettlementModePlatformManaged,
|
|
"offline_settlement_status": OfflineSettlementStatusPending,
|
|
}).Error; err != nil {
|
|
t.Fatalf("设置待线下结算提号失败: %v", err)
|
|
}
|
|
second := first
|
|
second.ID = 0
|
|
second.PickupNo = "PK-OFFLINE-SETTLED-001"
|
|
second.OfflineSettlementStatus = OfflineSettlementStatusSettled
|
|
if err := db.Create(&second).Error; err != nil {
|
|
t.Fatalf("创建已线下结算提号失败: %v", err)
|
|
}
|
|
|
|
result, err := repo.ListAdmin(t.Context(), AdminPickupQuery{OfflineSettlementStatus: OfflineSettlementStatusPending})
|
|
if err != nil {
|
|
t.Fatalf("ListAdmin() error = %v", err)
|
|
}
|
|
if result.Total != 1 || len(result.Items) != 1 || result.Items[0].OfflineSettlementStatus != OfflineSettlementStatusPending {
|
|
t.Fatalf("待线下结算筛选结果 = %+v", result)
|
|
}
|
|
}
|
|
|
|
func TestRepositoryListShopNamesReturnsDistinctPlatformOptions(t *testing.T) {
|
|
repo, db := newPickupTestRepo(t)
|
|
first := seedPickup(t, db, StatusPickingUp)
|
|
if err := db.Model(&first).Updates(map[string]any{
|
|
"platform": "淘宝",
|
|
"shop_name": "大锤一店",
|
|
}).Error; err != nil {
|
|
t.Fatalf("设置第一条提号店铺失败: %v", err)
|
|
}
|
|
for index, row := range []model.AdminPickup{
|
|
{PickupNo: "PK-SHOP-002", ListingID: first.ListingID, AccountID: first.AccountID, OwnerID: first.OwnerID, AdminID: 1, Platform: "淘宝", ShopName: "大锤一店", Status: StatusPickingUp},
|
|
{PickupNo: "PK-SHOP-003", ListingID: first.ListingID, AccountID: first.AccountID, OwnerID: first.OwnerID, AdminID: 1, Platform: "拼多多", ShopName: "大锤二店", Status: StatusPickingUp},
|
|
} {
|
|
if err := db.Create(&row).Error; err != nil {
|
|
t.Fatalf("创建第 %d 条店铺选项失败: %v", index+2, err)
|
|
}
|
|
}
|
|
|
|
names, err := repo.ListShopNames(t.Context(), "淘宝")
|
|
if err != nil {
|
|
t.Fatalf("ListShopNames() error = %v", err)
|
|
}
|
|
if len(names) != 1 || names[0] != "大锤一店" {
|
|
t.Fatalf("淘宝店铺选项 = %v, want [大锤一店]", names)
|
|
}
|
|
}
|
|
|
|
func TestRepositoryListAvailableListingsFiltersAccountSource(t *testing.T) {
|
|
repo, db := newPickupTestRepo(t)
|
|
internal := seedAvailableListing(t, db, "LST-SOURCE-INTERNAL", "站内账号", false)
|
|
external := seedAvailableListing(t, db, "LST-SOURCE-EXTERNAL", "外部账号", true)
|
|
if err := db.Create(&model.ListingUpload{
|
|
UploaderName: "外部号主",
|
|
SourceChannel: "淘宝",
|
|
ListingID: &external.ID,
|
|
Status: "listing_created",
|
|
}).Error; err != nil {
|
|
t.Fatalf("创建外部上传记录失败: %v", err)
|
|
}
|
|
|
|
all, err := repo.ListAvailableListings(t.Context(), AvailableListingQuery{Page: 1, PageSize: 20})
|
|
if err != nil {
|
|
t.Fatalf("ListAvailableListings() error = %v", err)
|
|
}
|
|
if all.Total != 2 || len(all.Items) != 2 {
|
|
t.Fatalf("全部来源结果 = total %d, items %d, want 2", all.Total, len(all.Items))
|
|
}
|
|
|
|
externalResult, err := repo.ListAvailableListings(t.Context(), AvailableListingQuery{
|
|
SourceType: ListingSourceExternal,
|
|
Page: 1,
|
|
PageSize: 20,
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("筛选外部上传 error = %v", err)
|
|
}
|
|
if externalResult.Total != 1 || len(externalResult.Items) != 1 {
|
|
t.Fatalf("外部上传结果 = total %d, items %d, want 1", externalResult.Total, len(externalResult.Items))
|
|
}
|
|
externalItem := externalResult.Items[0]
|
|
if externalItem.ID != external.ID || !externalItem.IsExternalUpload {
|
|
t.Fatalf("外部上传账号 = id %d, external %t, want id %d", externalItem.ID, externalItem.IsExternalUpload, external.ID)
|
|
}
|
|
if externalItem.AccountSource != AccountSourceExternalPlatformManaged || externalItem.SourceChannel != "淘宝" {
|
|
t.Fatalf("外部上传来源 = %q/%q", externalItem.AccountSource, externalItem.SourceChannel)
|
|
}
|
|
if externalItem.HandoffMode != "platform" || externalItem.SettlementMode != "platform_managed" {
|
|
t.Fatalf("外部上传代管模式 = %q/%q", externalItem.HandoffMode, externalItem.SettlementMode)
|
|
}
|
|
|
|
internalResult, err := repo.ListAvailableListings(t.Context(), AvailableListingQuery{
|
|
SourceType: ListingSourceInternal,
|
|
Page: 1,
|
|
PageSize: 20,
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("筛选站内上传 error = %v", err)
|
|
}
|
|
if internalResult.Total != 1 || len(internalResult.Items) != 1 {
|
|
t.Fatalf("站内上传结果 = total %d, items %d, want 1", internalResult.Total, len(internalResult.Items))
|
|
}
|
|
|
|
// 验证分页场景(len(rows) == pageSize 或 page > 1):触发独立 Count 查询,确保不会重复 Join 报错 Error 1066
|
|
pagedResult, err := repo.ListAvailableListings(t.Context(), AvailableListingQuery{
|
|
Page: 1,
|
|
PageSize: 1,
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("分页查询触发 Count 失败: %v", err)
|
|
}
|
|
if pagedResult.Total != 2 || len(pagedResult.Items) != 1 {
|
|
t.Fatalf("分页结果 = total %d, items %d, want total 2, items 1", pagedResult.Total, len(pagedResult.Items))
|
|
}
|
|
|
|
internalItem := internalResult.Items[0]
|
|
if internalItem.ID != internal.ID || internalItem.IsExternalUpload || internalItem.AccountSource != AccountSourceInternal {
|
|
t.Fatalf("站内上传账号 = id %d, external %t, source %q", internalItem.ID, internalItem.IsExternalUpload, internalItem.AccountSource)
|
|
}
|
|
}
|
|
|
|
func TestRepositoryCreateSnapshotsExternalAccountSource(t *testing.T) {
|
|
repo, db := newPickupTestRepo(t)
|
|
listing := seedAvailableListing(t, db, "LST-SOURCE-CREATE", "待提号外部账号", true)
|
|
upload := model.ListingUpload{
|
|
UploaderName: "外部号主",
|
|
SourceChannel: "闲鱼",
|
|
ListingID: &listing.ID,
|
|
Status: "listing_created",
|
|
}
|
|
if err := db.Create(&upload).Error; err != nil {
|
|
t.Fatalf("创建外部上传记录失败: %v", err)
|
|
}
|
|
|
|
item, err := repo.Create(t.Context(), CreateRequest{
|
|
ListingID: listing.ID,
|
|
Platform: "微信",
|
|
ProfitAmountCent: 1200,
|
|
}, 99, auditlog.Meta{RequestID: "req-source"})
|
|
if err != nil {
|
|
t.Fatalf("Create() error = %v", err)
|
|
}
|
|
if item.AccountSource != AccountSourceExternalPlatformManaged || item.SourceChannel != "闲鱼" {
|
|
t.Fatalf("创建来源快照 = %q/%q", item.AccountSource, item.SourceChannel)
|
|
}
|
|
|
|
if err := db.Delete(&upload).Error; err != nil {
|
|
t.Fatalf("删除上传关联失败: %v", err)
|
|
}
|
|
stored, err := repo.FindByID(t.Context(), item.ID)
|
|
if err != nil {
|
|
t.Fatalf("FindByID() error = %v", err)
|
|
}
|
|
if stored.AccountSource != AccountSourceExternalPlatformManaged || stored.SourceChannel != "闲鱼" {
|
|
t.Fatalf("关联删除后的来源快照 = %q/%q", stored.AccountSource, stored.SourceChannel)
|
|
}
|
|
}
|
|
|
|
func TestRepositoryCompleteInternalPickupCreditsWallet(t *testing.T) {
|
|
repo, db := newPickupTestRepo(t)
|
|
listing := seedAvailableListing(t, db, "LST-CMPL-INTERNAL", "站内结算账号", false)
|
|
pickup, err := repo.Create(t.Context(), CreateRequest{ListingID: listing.ID}, 99, auditlog.Meta{})
|
|
if err != nil {
|
|
t.Fatalf("Create() error = %v", err)
|
|
}
|
|
|
|
completed, err := repo.Complete(t.Context(), pickup.ID, CompleteRequest{SettleAmountCent: 12000}, 99, auditlog.Meta{})
|
|
if err != nil {
|
|
t.Fatalf("Complete() error = %v", err)
|
|
}
|
|
if completed.Status != StatusCompleted || completed.SettlementMode != SettlementModeOwnerWallet {
|
|
t.Fatalf("站内提号完成状态 = %q/%q", completed.Status, completed.SettlementMode)
|
|
}
|
|
if completed.OfflineSettlementStatus != OfflineSettlementStatusNone {
|
|
t.Fatalf("站内提号线下结算状态 = %q, want none", completed.OfflineSettlementStatus)
|
|
}
|
|
|
|
var ledger model.WalletLedger
|
|
if err := db.Where("biz_type = ? AND biz_no = ?", "admin_pickup_settle", pickup.PickupNo).First(&ledger).Error; err != nil {
|
|
t.Fatalf("站内提号应生成钱包流水: %v", err)
|
|
}
|
|
assertInt64(t, "站内提号钱包入账", ledger.AmountCent, 12000)
|
|
}
|
|
|
|
// 线下提号不走正常订单结账流程,完成时必须同步给号主邀请人发放返利,
|
|
// 否则邀请人永远拿不到提号产生的分成(历史漏发缺口)。
|
|
func TestRepositoryCompletePickupAwardsSellerInvitationRebate(t *testing.T) {
|
|
repo, db := newPickupTestRepo(t)
|
|
|
|
inviter := model.User{Phone: "19900000001", Nickname: "提号邀请人", RealnameStatus: "verified", Status: "active"}
|
|
if err := db.Create(&inviter).Error; err != nil {
|
|
t.Fatalf("创建邀请人失败: %v", err)
|
|
}
|
|
|
|
listing := seedAvailableListing(t, db, "LST-REBATE-001", "返利提号账号", false)
|
|
// 距提号完成 2 天 => 首月 60% 档;Truncate 到整秒避免 DATETIME(0) 四舍五入影响天数计算。
|
|
verifiedAt := time.Now().AddDate(0, 0, -2).Truncate(time.Second)
|
|
if err := db.Create(&model.UserInvitation{
|
|
InviterID: inviter.ID,
|
|
InviteeID: listing.OwnerID,
|
|
InviteCode: "rebate01",
|
|
Status: "active",
|
|
VerifiedAt: &verifiedAt,
|
|
}).Error; err != nil {
|
|
t.Fatalf("绑定号主邀请关系失败: %v", err)
|
|
}
|
|
|
|
pickup, err := repo.Create(t.Context(), CreateRequest{
|
|
ListingID: listing.ID,
|
|
OrderAmountCent: 20000,
|
|
ProfitAmountCent: 10000,
|
|
}, 99, auditlog.Meta{})
|
|
if err != nil {
|
|
t.Fatalf("Create() error = %v", err)
|
|
}
|
|
|
|
var stored model.AdminPickup
|
|
if err := db.First(&stored, pickup.ID).Error; err != nil {
|
|
t.Fatalf("读取提号记录失败: %v", err)
|
|
}
|
|
if stored.ProfitAmountCent != 10000 {
|
|
t.Fatalf("提号利润被改写为 %d,期望 10000(用例前提失效,请同步调整断言)", stored.ProfitAmountCent)
|
|
}
|
|
|
|
if _, err := repo.Complete(t.Context(), pickup.ID, CompleteRequest{SettleAmountCent: 10000}, 99, auditlog.Meta{}); err != nil {
|
|
t.Fatalf("Complete() error = %v", err)
|
|
}
|
|
|
|
var rebate model.InvitationRebateLedger
|
|
if err := db.Where("source = ? AND order_id = ? AND trade_role = ?", "pickup", pickup.ID, "seller").
|
|
First(&rebate).Error; err != nil {
|
|
t.Fatalf("提号完成应发放号主邀请人返利: %v", err)
|
|
}
|
|
if rebate.InviterID != inviter.ID || rebate.InviteeID != listing.OwnerID {
|
|
t.Fatalf("返利双方 = %d/%d, want %d/%d", rebate.InviterID, rebate.InviteeID, inviter.ID, listing.OwnerID)
|
|
}
|
|
if rebate.OrderNo != pickup.PickupNo {
|
|
t.Fatalf("返利单据号 = %q, want %q", rebate.OrderNo, pickup.PickupNo)
|
|
}
|
|
// 基数 = 提号利润 10000 对半 = 5000,首月 60% = 3000
|
|
assertInt64(t, "提号返利单边基数", rebate.SingleSideBasisCent, 5000)
|
|
assertInt64(t, "提号返利金额", rebate.RebateAmountCent, 3000)
|
|
|
|
var wallet model.WalletLedger
|
|
if err := db.Where("biz_type = ? AND biz_no = ?", "invite_rebate", pickup.PickupNo).First(&wallet).Error; err != nil {
|
|
t.Fatalf("提号返利应写钱包流水: %v", err)
|
|
}
|
|
if wallet.UserID != inviter.ID {
|
|
t.Fatalf("返利入账用户 = %d, want %d", wallet.UserID, inviter.ID)
|
|
}
|
|
assertInt64(t, "提号返利入账金额", wallet.AmountCent, 3000)
|
|
}
|
|
|
|
func TestRepositoryCompletePlatformManagedPickupUsesOfflineSettlement(t *testing.T) {
|
|
repo, db := newPickupTestRepo(t)
|
|
listing := seedAvailableListing(t, db, "LST-CMPL-EXTERNAL", "代管结算账号", true)
|
|
if err := db.Create(&model.ListingUpload{
|
|
UploaderName: "外部号主",
|
|
SourceChannel: "闲鱼",
|
|
ListingID: &listing.ID,
|
|
Status: "listing_created",
|
|
}).Error; err != nil {
|
|
t.Fatalf("创建外部上传记录失败: %v", err)
|
|
}
|
|
pickup, err := repo.Create(t.Context(), CreateRequest{ListingID: listing.ID}, 99, auditlog.Meta{})
|
|
if err != nil {
|
|
t.Fatalf("Create() error = %v", err)
|
|
}
|
|
if pickup.SettlementMode != SettlementModePlatformManaged {
|
|
t.Fatalf("平台代管提号结算模式 = %q", pickup.SettlementMode)
|
|
}
|
|
|
|
completed, err := repo.Complete(t.Context(), pickup.ID, CompleteRequest{SettleAmountCent: 13500}, 99, auditlog.Meta{})
|
|
if err != nil {
|
|
t.Fatalf("Complete() error = %v", err)
|
|
}
|
|
if completed.OfflineSettlementStatus != OfflineSettlementStatusPending {
|
|
t.Fatalf("平台代管提号线下结算状态 = %q, want pending", completed.OfflineSettlementStatus)
|
|
}
|
|
if completed.OfflineSettledAt != nil || completed.OfflineSettledBy != nil {
|
|
t.Fatalf("待线下结算不应记录确认信息: %+v", completed)
|
|
}
|
|
var ledgerCount int64
|
|
if err := db.Model(&model.WalletLedger{}).
|
|
Where("biz_type = ? AND biz_no = ?", "admin_pickup_settle", pickup.PickupNo).
|
|
Count(&ledgerCount).Error; err != nil {
|
|
t.Fatalf("统计钱包流水失败: %v", err)
|
|
}
|
|
if ledgerCount != 0 {
|
|
t.Fatalf("平台代管提号不应生成钱包流水, got %d", ledgerCount)
|
|
}
|
|
|
|
settled, err := repo.MarkOfflineSettlement(t.Context(), pickup.ID, OfflineSettlementRequest{Remark: "已转账"}, 100, auditlog.Meta{})
|
|
if err != nil {
|
|
t.Fatalf("MarkOfflineSettlement() error = %v", err)
|
|
}
|
|
if settled.OfflineSettlementStatus != OfflineSettlementStatusSettled || settled.OfflineSettledAt == nil || settled.OfflineSettledBy == nil || *settled.OfflineSettledBy != 100 {
|
|
t.Fatalf("平台代管线下结算确认结果 = %+v", settled)
|
|
}
|
|
if settled.OfflineSettlementRemark != "已转账" {
|
|
t.Fatalf("线下结算备注 = %q", settled.OfflineSettlementRemark)
|
|
}
|
|
var audit model.AuditLog
|
|
if err := db.Where("action = ? AND biz_id = ?", "pickup_offline_settlement", pickup.ID).First(&audit).Error; err != nil {
|
|
t.Fatalf("确认线下结算应写审计日志: %v", err)
|
|
}
|
|
}
|
|
|
|
func TestRepositoryFinancialAdjustmentCreditsInternalPickupWallet(t *testing.T) {
|
|
repo, db := newPickupTestRepo(t)
|
|
listing := seedAvailableListing(t, db, "LST-ADJUST-INTERNAL", "站内补款账号", false)
|
|
pickup, err := repo.Create(t.Context(), CreateRequest{ListingID: listing.ID, ProfitAmountCent: 1000}, 99, auditlog.Meta{})
|
|
if err != nil {
|
|
t.Fatalf("Create() error = %v", err)
|
|
}
|
|
if _, err = repo.Complete(t.Context(), pickup.ID, CompleteRequest{SettleAmountCent: 12000}, 99, auditlog.Meta{}); err != nil {
|
|
t.Fatalf("Complete() error = %v", err)
|
|
}
|
|
|
|
updated, err := repo.CreateFinancialAdjustment(t.Context(), pickup.ID, FinancialAdjustmentRequest{
|
|
ProfitAmountCent: ptrInt64(1500),
|
|
SettleAmountCent: ptrInt64(13500),
|
|
Reason: "补录实际成交金额",
|
|
}, 100, auditlog.Meta{})
|
|
if err != nil {
|
|
t.Fatalf("CreateFinancialAdjustment() error = %v", err)
|
|
}
|
|
assertInt64(t, "原始利润不变", updated.ProfitAmountCent, 1000)
|
|
assertInt64(t, "有效利润", updated.EffectiveProfitAmountCent, 1500)
|
|
assertInt64(t, "原始结算额不变", updated.SettleAmountCent, 12000)
|
|
assertInt64(t, "有效结算额", updated.EffectiveSettleAmountCent, 13500)
|
|
|
|
var adjustment model.AdminPickupFinancialAdjustment
|
|
if err := db.Where("pickup_id = ?", pickup.ID).First(&adjustment).Error; err != nil {
|
|
t.Fatalf("查询调整流水失败: %v", err)
|
|
}
|
|
if adjustment.Status != FinancialAdjustmentStatusSettled || adjustment.ProfitDeltaCent != 500 || adjustment.SettleDeltaCent != 1500 {
|
|
t.Fatalf("调整流水 = %+v", adjustment)
|
|
}
|
|
var ledger model.WalletLedger
|
|
if err := db.Where("biz_type = ?", "admin_pickup_adjustment").First(&ledger).Error; err != nil {
|
|
t.Fatalf("站内补款应生成钱包流水: %v", err)
|
|
}
|
|
assertInt64(t, "站内补款钱包入账", ledger.AmountCent, 1500)
|
|
}
|
|
|
|
func TestRepositoryFinancialAdjustmentUsesRecoveryForInternalReduction(t *testing.T) {
|
|
repo, db := newPickupTestRepo(t)
|
|
listing := seedAvailableListing(t, db, "LST-ADJUST-RECOVERY", "站内追回账号", false)
|
|
pickup, err := repo.Create(t.Context(), CreateRequest{ListingID: listing.ID}, 99, auditlog.Meta{})
|
|
if err != nil {
|
|
t.Fatalf("Create() error = %v", err)
|
|
}
|
|
if _, err = repo.Complete(t.Context(), pickup.ID, CompleteRequest{SettleAmountCent: 12000}, 99, auditlog.Meta{}); err != nil {
|
|
t.Fatalf("Complete() error = %v", err)
|
|
}
|
|
updated, err := repo.CreateFinancialAdjustment(t.Context(), pickup.ID, FinancialAdjustmentRequest{
|
|
SettleAmountCent: ptrInt64(10000),
|
|
Reason: "实际应结算金额减少",
|
|
}, 100, auditlog.Meta{})
|
|
if err != nil {
|
|
t.Fatalf("CreateFinancialAdjustment() error = %v", err)
|
|
}
|
|
assertInt64(t, "追回后的有效结算额", updated.EffectiveSettleAmountCent, 10000)
|
|
var adjustment model.AdminPickupFinancialAdjustment
|
|
if err := db.Where("pickup_id = ?", pickup.ID).First(&adjustment).Error; err != nil {
|
|
t.Fatalf("查询追回调整失败: %v", err)
|
|
}
|
|
if adjustment.Status != FinancialAdjustmentStatusRecovery || adjustment.SettleDeltaCent != -2000 {
|
|
t.Fatalf("追回调整 = %+v", adjustment)
|
|
}
|
|
var audit model.AuditLog
|
|
if err := db.Where("action = ?", "pickup_financial_adjustment_create").First(&audit).Error; err != nil {
|
|
t.Fatalf("查询财务调整审计日志失败: %v", err)
|
|
}
|
|
if audit.BizType != "admin_pickup" {
|
|
t.Fatalf("财务调整审计业务类型 = %q, want admin_pickup", audit.BizType)
|
|
}
|
|
var ledgerCount int64
|
|
if err := db.Model(&model.WalletLedger{}).Where("biz_type = ?", "admin_pickup_adjustment").Count(&ledgerCount).Error; err != nil {
|
|
t.Fatalf("统计补款流水失败: %v", err)
|
|
}
|
|
if ledgerCount != 0 {
|
|
t.Fatalf("待追回不能直接扣钱包, got %d 条流水", ledgerCount)
|
|
}
|
|
}
|
|
|
|
func TestRepositoryFinancialAdjustmentSettlesPlatformManagedPickupSeparately(t *testing.T) {
|
|
repo, db := newPickupTestRepo(t)
|
|
listing := seedAvailableListing(t, db, "LST-ADJUST-PLATFORM", "代管调整账号", true)
|
|
if err := db.Create(&model.ListingUpload{UploaderName: "外部号主", ListingID: &listing.ID, Status: "listing_created"}).Error; err != nil {
|
|
t.Fatalf("创建外部上传记录失败: %v", err)
|
|
}
|
|
pickup, err := repo.Create(t.Context(), CreateRequest{ListingID: listing.ID}, 99, auditlog.Meta{})
|
|
if err != nil {
|
|
t.Fatalf("Create() error = %v", err)
|
|
}
|
|
if _, err = repo.Complete(t.Context(), pickup.ID, CompleteRequest{SettleAmountCent: 12000}, 99, auditlog.Meta{}); err != nil {
|
|
t.Fatalf("Complete() error = %v", err)
|
|
}
|
|
if _, err = repo.MarkOfflineSettlement(t.Context(), pickup.ID, OfflineSettlementRequest{}, 100, auditlog.Meta{}); err != nil {
|
|
t.Fatalf("MarkOfflineSettlement() error = %v", err)
|
|
}
|
|
updated, err := repo.CreateFinancialAdjustment(t.Context(), pickup.ID, FinancialAdjustmentRequest{
|
|
ProfitAmountCent: ptrInt64(2000),
|
|
SettleAmountCent: ptrInt64(13500),
|
|
Reason: "补录代管打款",
|
|
}, 101, auditlog.Meta{})
|
|
if err != nil {
|
|
t.Fatalf("CreateFinancialAdjustment() error = %v", err)
|
|
}
|
|
if updated.OfflineSettlementStatus != OfflineSettlementStatusSettled {
|
|
t.Fatalf("原线下结算状态不应被重置: %q", updated.OfflineSettlementStatus)
|
|
}
|
|
adjustments, err := repo.ListFinancialAdjustments(t.Context(), pickup.ID)
|
|
if err != nil || len(adjustments) != 1 {
|
|
t.Fatalf("ListFinancialAdjustments() = %+v, %v", adjustments, err)
|
|
}
|
|
if adjustments[0].Status != FinancialAdjustmentStatusPending {
|
|
t.Fatalf("代管补款状态 = %q, want pending", adjustments[0].Status)
|
|
}
|
|
var createAudit model.AuditLog
|
|
if err := db.Where("action = ?", "pickup_financial_adjustment_create").First(&createAudit).Error; err != nil {
|
|
t.Fatalf("查询创建财务调整审计日志失败: %v", err)
|
|
}
|
|
if createAudit.BizType != "admin_pickup" {
|
|
t.Fatalf("创建财务调整审计业务类型 = %q, want admin_pickup", createAudit.BizType)
|
|
}
|
|
if err := repo.SettleFinancialAdjustment(t.Context(), adjustments[0].ID, FinancialAdjustmentSettlementRequest{Remark: "已补款"}, 102, auditlog.Meta{}); err != nil {
|
|
t.Fatalf("SettleFinancialAdjustment() error = %v", err)
|
|
}
|
|
adjustments, err = repo.ListFinancialAdjustments(t.Context(), pickup.ID)
|
|
if err != nil || adjustments[0].Status != FinancialAdjustmentStatusSettled || adjustments[0].SettledBy == nil || *adjustments[0].SettledBy != 102 {
|
|
t.Fatalf("确认后的调整流水 = %+v, %v", adjustments, err)
|
|
}
|
|
var settleAudit model.AuditLog
|
|
if err := db.Where("action = ?", "pickup_financial_adjustment_settle").First(&settleAudit).Error; err != nil {
|
|
t.Fatalf("查询确认财务调整审计日志失败: %v", err)
|
|
}
|
|
if settleAudit.BizType != "admin_pickup" {
|
|
t.Fatalf("确认财务调整审计业务类型 = %q, want admin_pickup", settleAudit.BizType)
|
|
}
|
|
}
|
|
|
|
func TestRepositoryOfflineSettlementProcessesPendingPickupAdjustments(t *testing.T) {
|
|
repo, db := newPickupTestRepo(t)
|
|
listing := seedAvailableListing(t, db, "LST-ADJ-SETTLEMENT", "代管合并结算账号", true)
|
|
if err := db.Create(&model.ListingUpload{UploaderName: "外部号主", ListingID: &listing.ID, Status: "listing_created"}).Error; err != nil {
|
|
t.Fatalf("创建外部上传记录失败: %v", err)
|
|
}
|
|
pickup, err := repo.Create(t.Context(), CreateRequest{ListingID: listing.ID}, 99, auditlog.Meta{})
|
|
if err != nil {
|
|
t.Fatalf("Create() error = %v", err)
|
|
}
|
|
if _, err = repo.Complete(t.Context(), pickup.ID, CompleteRequest{SettleAmountCent: 12000}, 99, auditlog.Meta{}); err != nil {
|
|
t.Fatalf("Complete() error = %v", err)
|
|
}
|
|
if _, err = repo.CreateFinancialAdjustment(t.Context(), pickup.ID, FinancialAdjustmentRequest{
|
|
SettleAmountCent: ptrInt64(10000),
|
|
Reason: "付款前修正应付金额",
|
|
}, 100, auditlog.Meta{}); err != nil {
|
|
t.Fatalf("CreateFinancialAdjustment() error = %v", err)
|
|
}
|
|
adjustments, err := repo.ListFinancialAdjustments(t.Context(), pickup.ID)
|
|
if err != nil || len(adjustments) != 1 || adjustments[0].Status != FinancialAdjustmentStatusPending {
|
|
t.Fatalf("结算前调整流水 = %+v, %v", adjustments, err)
|
|
}
|
|
settled, err := repo.MarkOfflineSettlement(t.Context(), pickup.ID, OfflineSettlementRequest{Remark: "按修正后金额打款"}, 101, auditlog.Meta{})
|
|
if err != nil {
|
|
t.Fatalf("MarkOfflineSettlement() error = %v", err)
|
|
}
|
|
if settled.OfflineSettlementStatus != OfflineSettlementStatusSettled || settled.EffectiveSettleAmountCent != 10000 {
|
|
t.Fatalf("合并线下结算结果 = %+v", settled)
|
|
}
|
|
adjustments, err = repo.ListFinancialAdjustments(t.Context(), pickup.ID)
|
|
if err != nil || adjustments[0].Status != FinancialAdjustmentStatusSettled || adjustments[0].SettledBy == nil || *adjustments[0].SettledBy != 101 {
|
|
t.Fatalf("合并结算后的调整流水 = %+v, %v", adjustments, err)
|
|
}
|
|
}
|
|
|
|
func ptrInt64(value int64) *int64 {
|
|
return &value
|
|
}
|
|
|
|
func assertInt64(t *testing.T, name string, got, want int64) {
|
|
t.Helper()
|
|
if got != want {
|
|
t.Fatalf("%s = %d, want %d", name, got, want)
|
|
}
|
|
}
|
|
|
|
func assertJSONNumber(t *testing.T, name string, got any, want float64) {
|
|
t.Helper()
|
|
value, ok := got.(float64)
|
|
if !ok || value != want {
|
|
t.Fatalf("%s = %v, want %.0f", name, got, want)
|
|
}
|
|
}
|
|
|
|
func newPickupTestRepo(t *testing.T) (*Repository, *gorm.DB) {
|
|
t.Helper()
|
|
db := database.NewTestDB()
|
|
if err := database.AutoMigrateIfMissing(db,
|
|
&model.User{},
|
|
&model.AdminUser{},
|
|
&model.GameAccount{},
|
|
&model.RentalListing{},
|
|
&model.ListingUpload{},
|
|
&model.AdminPickup{},
|
|
&model.AdminPickupFinancialAdjustment{},
|
|
&model.PickupShop{},
|
|
&model.WalletAccount{},
|
|
&model.WalletLedger{},
|
|
&model.AuditLog{},
|
|
&model.ProcessEvent{},
|
|
&model.Notification{},
|
|
&model.ListingStatusEvent{},
|
|
); err != nil {
|
|
t.Fatalf("迁移测试表失败: %v", err)
|
|
}
|
|
return NewRepository(db), db
|
|
}
|
|
|
|
func seedAvailableListing(t *testing.T, db *gorm.DB, listingNo, title string, external bool) model.RentalListing {
|
|
t.Helper()
|
|
owner := model.User{Phone: "188" + listingNo}
|
|
if err := db.Create(&owner).Error; err != nil {
|
|
t.Fatalf("创建候选号主失败: %v", err)
|
|
}
|
|
account := model.GameAccount{
|
|
OwnerID: owner.ID,
|
|
ServerRegion: "测试区",
|
|
LoginPlatform: "微信",
|
|
Title: title,
|
|
Status: "published",
|
|
}
|
|
if err := db.Create(&account).Error; err != nil {
|
|
t.Fatalf("创建候选账号失败: %v", err)
|
|
}
|
|
listing := model.RentalListing{
|
|
ListingNo: listingNo,
|
|
AccountID: account.ID,
|
|
OwnerID: owner.ID,
|
|
PriceCent: 10000,
|
|
Status: "published",
|
|
ReviewStatus: "approved",
|
|
HandoffMode: "owner",
|
|
SettlementMode: "owner_wallet",
|
|
}
|
|
if external {
|
|
listing.HandoffMode = "platform"
|
|
listing.SettlementMode = "platform_managed"
|
|
}
|
|
if err := db.Create(&listing).Error; err != nil {
|
|
t.Fatalf("创建候选上架记录失败: %v", err)
|
|
}
|
|
return listing
|
|
}
|
|
|
|
func seedPickup(t *testing.T, db *gorm.DB, status string) model.AdminPickup {
|
|
t.Helper()
|
|
owner := model.User{Phone: "18800000000"}
|
|
if err := db.Create(&owner).Error; err != nil {
|
|
t.Fatalf("创建号主失败: %v", err)
|
|
}
|
|
account := model.GameAccount{
|
|
OwnerID: owner.ID,
|
|
ServerRegion: "测试区",
|
|
LoginPlatform: "微信",
|
|
Title: "测试账号",
|
|
Status: "rented",
|
|
}
|
|
if err := db.Create(&account).Error; err != nil {
|
|
t.Fatalf("创建账号失败: %v", err)
|
|
}
|
|
listing := model.RentalListing{
|
|
ListingNo: "LST-PROFIT-001",
|
|
AccountID: account.ID,
|
|
OwnerID: owner.ID,
|
|
PriceCent: 10000,
|
|
Status: "rented",
|
|
ReviewStatus: "approved",
|
|
}
|
|
if err := db.Create(&listing).Error; err != nil {
|
|
t.Fatalf("创建上架记录失败: %v", err)
|
|
}
|
|
pickup := model.AdminPickup{
|
|
PickupNo: "PK-PROFIT-001",
|
|
ListingID: listing.ID,
|
|
AccountID: account.ID,
|
|
OwnerID: owner.ID,
|
|
AdminID: 1,
|
|
ProfitAmountCent: 1000,
|
|
Status: status,
|
|
}
|
|
if err := db.Create(&pickup).Error; err != nil {
|
|
t.Fatalf("创建提号记录失败: %v", err)
|
|
}
|
|
return pickup
|
|
}
|
|
|
|
func TestApplyAdminPickupFiltersSmartRouting(t *testing.T) {
|
|
db := database.NewDryRunDB()
|
|
|
|
tests := []struct {
|
|
name string
|
|
query AdminPickupQuery
|
|
wantSQLFrag string
|
|
}{
|
|
{
|
|
name: "11位手机号路由至users(phone)",
|
|
query: AdminPickupQuery{Keyword: "13800138000"},
|
|
wantSQLFrag: "owner.phone = ?",
|
|
},
|
|
{
|
|
name: "PK前缀提号编号路由至admin_pickups(pickup_no)",
|
|
query: AdminPickupQuery{Keyword: "PK202609051000"},
|
|
wantSQLFrag: "p.pickup_no = ?",
|
|
},
|
|
{
|
|
name: "L前缀商品编号路由至rental_listings(listing_no)",
|
|
query: AdminPickupQuery{Keyword: "L20260905100"},
|
|
wantSQLFrag: "l.listing_no = ?",
|
|
},
|
|
{
|
|
name: "短数字ID路由至主键及关联ID",
|
|
query: AdminPickupQuery{Keyword: "12345"},
|
|
wantSQLFrag: "p.id = ? OR p.listing_id = ? OR p.account_id = ? OR p.owner_id = ?",
|
|
},
|
|
{
|
|
name: "12位时间计算的纯数字商品编号路由至rental_listings(listing_no)",
|
|
query: AdminPickupQuery{Keyword: "202609040184"},
|
|
wantSQLFrag: "l.listing_no = ?",
|
|
},
|
|
{
|
|
name: "普通文字退回多列LIKE模糊匹配",
|
|
query: AdminPickupQuery{Keyword: "测试账号"},
|
|
wantSQLFrag: "p.pickup_no LIKE ? OR l.listing_no LIKE ? OR a.title LIKE ? OR owner.phone LIKE ?",
|
|
},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
stmt := applyAdminPickupFilters(db.Table("admin_pickups AS p"), tt.query).Find(&[]struct{}{}).Statement
|
|
sql := stmt.SQL.String()
|
|
if !strings.Contains(sql, tt.wantSQLFrag) {
|
|
t.Fatalf("期望 SQL 包含 %q, 实际生成: %s", tt.wantSQLFrag, sql)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestRepositoryCreateExtraFieldsAndQueryTimeRange(t *testing.T) {
|
|
repo, db := newPickupTestRepo(t)
|
|
listing := seedAvailableListing(t, db, "LST-TEST-EXTRA-01", "测试商品带扩展字段", false)
|
|
|
|
created, err := repo.Create(t.Context(), CreateRequest{
|
|
ListingID: listing.ID,
|
|
Operator: "运营小张",
|
|
Platform: "淘宝",
|
|
ThirdPartyOrderNo: "TB-20261009-8888",
|
|
ShopName: "测试大锤专营",
|
|
OrderAmountCent: 12800,
|
|
DepositAmountCent: 5000,
|
|
ProfitAmountCent: 3000,
|
|
Remark: "测试提号备注",
|
|
}, 1, auditlog.Meta{})
|
|
if err != nil {
|
|
t.Fatalf("Create() error = %v", err)
|
|
}
|
|
|
|
if created.Operator != "运营小张" {
|
|
t.Fatalf("Operator = %q, want %q", created.Operator, "运营小张")
|
|
}
|
|
if created.ThirdPartyOrderNo != "TB-20261009-8888" {
|
|
t.Fatalf("ThirdPartyOrderNo = %q, want %q", created.ThirdPartyOrderNo, "TB-20261009-8888")
|
|
}
|
|
assertInt64(t, "OrderAmountCent", created.OrderAmountCent, 12800)
|
|
assertInt64(t, "DepositAmountCent", created.DepositAmountCent, 5000)
|
|
|
|
detail, err := repo.FindByID(t.Context(), created.ID)
|
|
if err != nil {
|
|
t.Fatalf("FindByID() error = %v", err)
|
|
}
|
|
if detail.Operator != "运营小张" || detail.ThirdPartyOrderNo != "TB-20261009-8888" {
|
|
t.Fatalf("FindByID fields mismatch: %+v", detail)
|
|
}
|
|
|
|
// 测试时间范围筛选
|
|
now := time.Now()
|
|
before1Hour := now.Add(-1 * time.Hour)
|
|
after1Hour := now.Add(1 * time.Hour)
|
|
before2Hour := now.Add(-2 * time.Hour)
|
|
|
|
// 命中的时间范围
|
|
hitRes, err := repo.ListAdmin(t.Context(), AdminPickupQuery{
|
|
StartTime: &before1Hour,
|
|
EndTime: &after1Hour,
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("ListAdmin() with time range error = %v", err)
|
|
}
|
|
if hitRes.Total < 1 {
|
|
t.Fatalf("ListAdmin() in-range total = %d, want >= 1", hitRes.Total)
|
|
}
|
|
|
|
// 未命中的时间范围(过去)
|
|
missRes, err := repo.ListAdmin(t.Context(), AdminPickupQuery{
|
|
StartTime: &before2Hour,
|
|
EndTime: &before1Hour,
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("ListAdmin() with miss range error = %v", err)
|
|
}
|
|
if missRes.Total != 0 {
|
|
t.Fatalf("ListAdmin() out-of-range total = %d, want 0", missRes.Total)
|
|
}
|
|
}
|
|
|
|
func TestRepositoryPickupShopCRUDAndOptions(t *testing.T) {
|
|
repo, _ := newPickupTestRepo(t)
|
|
|
|
// 1. 创建店铺
|
|
shop1, err := repo.CreateShop(t.Context(), CreatePickupShopRequest{
|
|
Name: "旗舰一店",
|
|
Platform: "淘宝",
|
|
Status: "active",
|
|
SortOrder: 10,
|
|
Remark: "测试店铺一",
|
|
}, 1, auditlog.Meta{})
|
|
if err != nil {
|
|
t.Fatalf("CreateShop() error = %v", err)
|
|
}
|
|
if shop1.ID == 0 || shop1.Name != "旗舰一店" {
|
|
t.Fatalf("CreateShop() result = %+v", shop1)
|
|
}
|
|
|
|
// 2. 重名校验
|
|
_, err = repo.CreateShop(t.Context(), CreatePickupShopRequest{
|
|
Name: "旗舰一店",
|
|
}, 1, auditlog.Meta{})
|
|
if !errors.Is(err, ErrPickupShopNameExists) {
|
|
t.Fatalf("CreateShop() duplicate error = %v, want ErrPickupShopNameExists", err)
|
|
}
|
|
|
|
// 3. 创建第二个店铺
|
|
shop2, err := repo.CreateShop(t.Context(), CreatePickupShopRequest{
|
|
Name: "拼多多二店",
|
|
Platform: "拼多多",
|
|
Status: "active",
|
|
SortOrder: 20,
|
|
Remark: "测试店铺二",
|
|
}, 1, auditlog.Meta{})
|
|
if err != nil {
|
|
t.Fatalf("CreateShop(2) error = %v", err)
|
|
}
|
|
|
|
// 4. 查询店铺列表
|
|
shops, err := repo.ListShops(t.Context(), PickupShopQuery{})
|
|
if err != nil {
|
|
t.Fatalf("ListShops() error = %v", err)
|
|
}
|
|
if len(shops) != 2 {
|
|
t.Fatalf("ListShops() length = %d, want 2", len(shops))
|
|
}
|
|
// 权重 20 的应该排在前面
|
|
if shops[0].Name != "拼多多二店" {
|
|
t.Fatalf("ListShops() first = %s, want 拼多多二店", shops[0].Name)
|
|
}
|
|
|
|
// 5. 更新店铺
|
|
updated, err := repo.UpdateShop(t.Context(), shop1.ID, UpdatePickupShopRequest{
|
|
Name: "旗舰一店改名",
|
|
Platform: "淘宝",
|
|
Status: "disabled",
|
|
SortOrder: 5,
|
|
Remark: "修改备注",
|
|
}, 1, auditlog.Meta{})
|
|
if err != nil {
|
|
t.Fatalf("UpdateShop() error = %v", err)
|
|
}
|
|
if updated.Name != "旗舰一店改名" || updated.Status != "disabled" {
|
|
t.Fatalf("UpdateShop() result = %+v", updated)
|
|
}
|
|
|
|
// 6. ListShopNames 选项列表(仅返回 active 店铺)
|
|
options, err := repo.ListShopNames(t.Context(), "")
|
|
if err != nil {
|
|
t.Fatalf("ListShopNames() error = %v", err)
|
|
}
|
|
if len(options) != 1 || options[0] != "拼多多二店" {
|
|
t.Fatalf("ListShopNames() options = %v, want [拼多多二店]", options)
|
|
}
|
|
|
|
// 7. 删除店铺
|
|
if err := repo.DeleteShop(t.Context(), shop2.ID, 1, auditlog.Meta{}); err != nil {
|
|
t.Fatalf("DeleteShop() error = %v", err)
|
|
}
|
|
shopsAfterDelete, err := repo.ListShops(t.Context(), PickupShopQuery{Status: "active"})
|
|
if err != nil {
|
|
t.Fatalf("ListShops() after delete error = %v", err)
|
|
}
|
|
if len(shopsAfterDelete) != 0 {
|
|
t.Fatalf("active shops after delete length = %d, want 0", len(shopsAfterDelete))
|
|
}
|
|
}
|
|
|
|
func TestRepositoryHistoricalShopStatsAndMapping(t *testing.T) {
|
|
repo, db := newPickupTestRepo(t)
|
|
|
|
// 1. 创建标准店铺
|
|
stdShop1, err := repo.CreateShop(t.Context(), CreatePickupShopRequest{
|
|
Name: "王大锤游戏",
|
|
Platform: "淘宝",
|
|
Status: "active",
|
|
}, 1, auditlog.Meta{})
|
|
if err != nil {
|
|
t.Fatalf("CreateShop() error = %v", err)
|
|
}
|
|
|
|
// 2. 插入测试提号记录
|
|
listing1 := seedAvailableListing(t, db, "LST-MAP-01", "映射测试商品1", false)
|
|
_, err = repo.Create(t.Context(), CreateRequest{
|
|
ListingID: listing1.ID,
|
|
ShopName: "王大锤游戏",
|
|
}, 1, auditlog.Meta{})
|
|
if err != nil {
|
|
t.Fatalf("Create() error = %v", err)
|
|
}
|
|
|
|
listing2 := seedAvailableListing(t, db, "LST-MAP-02", "映射测试商品2", false)
|
|
_, err = repo.Create(t.Context(), CreateRequest{
|
|
ListingID: listing2.ID,
|
|
ShopName: "王大锤游戏专营",
|
|
}, 1, auditlog.Meta{})
|
|
if err != nil {
|
|
t.Fatalf("Create() error = %v", err)
|
|
}
|
|
|
|
listing3 := seedAvailableListing(t, db, "LST-MAP-03", "映射测试商品3", false)
|
|
_, err = repo.Create(t.Context(), CreateRequest{
|
|
ListingID: listing3.ID,
|
|
ShopName: "淘宝王大锤商行",
|
|
}, 1, auditlog.Meta{})
|
|
if err != nil {
|
|
t.Fatalf("Create() error = %v", err)
|
|
}
|
|
|
|
// 3. 获取历史聚合统计
|
|
stats, err := repo.GetHistoricalShopStats(t.Context())
|
|
if err != nil {
|
|
t.Fatalf("GetHistoricalShopStats() error = %v", err)
|
|
}
|
|
if stats.TotalShops < 3 {
|
|
t.Fatalf("stats.TotalShops = %d, want >= 3", stats.TotalShops)
|
|
}
|
|
if stats.StandardCount < 1 {
|
|
t.Fatalf("stats.StandardCount = %d, want >= 1", stats.StandardCount)
|
|
}
|
|
|
|
// 4. 批量映射
|
|
mapRes, err := repo.MapHistoricalShops(t.Context(), MapHistoricalShopsRequest{
|
|
FromShopNames: []string{"王大锤游戏专营", "淘宝王大锤商行"},
|
|
TargetShopName: "王大锤游戏",
|
|
Remark: "测试批量映射",
|
|
}, 1, auditlog.Meta{})
|
|
if err != nil {
|
|
t.Fatalf("MapHistoricalShops() error = %v", err)
|
|
}
|
|
if mapRes.UpdatedPickupsCount != 2 {
|
|
t.Fatalf("UpdatedPickupsCount = %d, want 2", mapRes.UpdatedPickupsCount)
|
|
}
|
|
if mapRes.TargetShopID != stdShop1.ID {
|
|
t.Fatalf("TargetShopID = %d, want %d", mapRes.TargetShopID, stdShop1.ID)
|
|
}
|
|
|
|
// 5. 再次统计
|
|
statsAfter, err := repo.GetHistoricalShopStats(t.Context())
|
|
if err != nil {
|
|
t.Fatalf("GetHistoricalShopStats() error = %v", err)
|
|
}
|
|
if statsAfter.MappedCount < 2 {
|
|
t.Fatalf("statsAfter.MappedCount = %d, want >= 2", statsAfter.MappedCount)
|
|
}
|
|
|
|
// 6. 验证新建提号自动归一化
|
|
listing4 := seedAvailableListing(t, db, "LST-MAP-04", "映射测试商品4", false)
|
|
createdWithAlias, err := repo.Create(t.Context(), CreateRequest{
|
|
ListingID: listing4.ID,
|
|
ShopName: "王大锤游戏专营",
|
|
}, 1, auditlog.Meta{})
|
|
if err != nil {
|
|
t.Fatalf("Create() with alias error = %v", err)
|
|
}
|
|
if createdWithAlias.ShopName != "王大锤游戏" {
|
|
t.Fatalf("createdWithAlias.ShopName = %q, want 王大锤游戏", createdWithAlias.ShopName)
|
|
}
|
|
if createdWithAlias.RawShopName != "王大锤游戏专营" {
|
|
t.Fatalf("createdWithAlias.RawShopName = %q, want 王大锤游戏专营", createdWithAlias.RawShopName)
|
|
}
|
|
|
|
// 7. 取消映射
|
|
if err := repo.DeleteShopMapping(t.Context(), "王大锤游戏专营", 1, auditlog.Meta{}); err != nil {
|
|
t.Fatalf("DeleteShopMapping() error = %v", err)
|
|
}
|
|
}
|
|
|
|
func TestRepositoryUpdateThirdPartyOrderNo(t *testing.T) {
|
|
t.Run("成功补录第三方单号并记录审计", func(t *testing.T) {
|
|
repo, db := newPickupTestRepo(t)
|
|
pickup := seedPickup(t, db, StatusPickingUp)
|
|
|
|
item, err := repo.UpdateThirdPartyOrderNo(t.Context(), pickup.ID, UpdateThirdPartyOrderNoRequest{
|
|
ThirdPartyOrderNo: "TB-20261009-8888",
|
|
}, 99, auditlog.Meta{RequestID: "req-third-party-order-no"})
|
|
if err != nil {
|
|
t.Fatalf("UpdateThirdPartyOrderNo() error = %v", err)
|
|
}
|
|
if item.ThirdPartyOrderNo != "TB-20261009-8888" {
|
|
t.Fatalf("item.ThirdPartyOrderNo = %q, want TB-20261009-8888", item.ThirdPartyOrderNo)
|
|
}
|
|
|
|
var stored model.AdminPickup
|
|
if err := db.First(&stored, pickup.ID).Error; err != nil {
|
|
t.Fatalf("查询提号失败: %v", err)
|
|
}
|
|
if stored.ThirdPartyOrderNo != "TB-20261009-8888" {
|
|
t.Fatalf("stored.ThirdPartyOrderNo = %q, want TB-20261009-8888", stored.ThirdPartyOrderNo)
|
|
}
|
|
|
|
// 验证审计日志
|
|
var audit model.AuditLog
|
|
if err := db.Where("action = ?", "pickup_third_party_order_no_update").First(&audit).Error; err != nil {
|
|
t.Fatalf("查询审计日志失败: %v", err)
|
|
}
|
|
var detail map[string]any
|
|
if err := json.Unmarshal(audit.Detail, &detail); err != nil {
|
|
t.Fatalf("解析审计日志失败: %v", err)
|
|
}
|
|
if detail["new_third_party_order_no"] != "TB-20261009-8888" {
|
|
t.Fatalf("detail[new_third_party_order_no] = %v, want TB-20261009-8888", detail["new_third_party_order_no"])
|
|
}
|
|
|
|
// 空单号拒绝
|
|
_, err = repo.UpdateThirdPartyOrderNo(t.Context(), pickup.ID, UpdateThirdPartyOrderNoRequest{
|
|
ThirdPartyOrderNo: " ",
|
|
}, 99, auditlog.Meta{})
|
|
if !errors.Is(err, ErrInvalidThirdPartyOrderNo) {
|
|
t.Fatalf("UpdateThirdPartyOrderNo() with blank error = %v, want ErrInvalidThirdPartyOrderNo", err)
|
|
}
|
|
})
|
|
|
|
t.Run("已取消提号单拒绝补录", func(t *testing.T) {
|
|
repo, db := newPickupTestRepo(t)
|
|
cancelledPickup := seedPickup(t, db, StatusCancelled)
|
|
|
|
_, err := repo.UpdateThirdPartyOrderNo(t.Context(), cancelledPickup.ID, UpdateThirdPartyOrderNoRequest{
|
|
ThirdPartyOrderNo: "TB-CANCELLED-999",
|
|
}, 99, auditlog.Meta{})
|
|
if !errors.Is(err, ErrPickupCancelled) {
|
|
t.Fatalf("UpdateThirdPartyOrderNo() on cancelled error = %v, want ErrPickupCancelled", err)
|
|
}
|
|
})
|
|
}
|
|
|