Files
junhong_cmp_fiber/internal/query/exchange/list.go
break 93e072e1e2
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 11m42s
feat(换货): AUG26-005 换货业务数据迁移状态与失败恢复
- 新增成对迁移 000222:tb_exchange_order 增加非空 migration_status 与
  migration_failure_reason,按既有 migrate_data/migration_completed 回填历史,
  并加四值 CHECK 约束,不新增索引
- 模型与常量定义四种迁移状态及中文名称,保留既有布尔字段兼容语义
- 物流换货创建恒 not_migrated,发货按请求落 pending/not_migrated,
  完成成功写 migrated/not_migrated 并清空失败原因、同步兼容字段
- 直接换货创建即完成,任一步失败整体回滚,不持久化换货单、不产生 failed
- 迁移失败回滚全部业务修改后,在独立短事务内条件更新 failed 与安全失败原因
  并写失败审计,RowsAffected 为 0 时跳过状态写入但仍写审计
- failed 物流单重试仅限超级管理员或平台用户,授权以锁内 FOR UPDATE 判定为准,
  重试从钱包余额起整表重跑;非 failed 单沿用既有完成门禁
- 列表与详情返回迁移状态与中文名称,仅 failed 返回失败原因;既有三字段保持兼容
- 换货导出在「状态」列后新增中文「迁移状态」列,不导出失败原因
- 同步 order-refund-exchange 主 spec 与验证证据,归档本 Change
- 登记 KNOWN-ISSUE-001:既有标签复制 OnConflict 未声明部分索引谓词(42P10),
  旧资产带标签时迁移最后一步失败,待另立变更修复
2026-09-14 18:32:26 +08:00

158 lines
6.1 KiB
Go

// Package exchange 提供换货读取用例。
package exchange
import (
"context"
"time"
"github.com/break/junhong_cmp_fiber/internal/model"
"github.com/break/junhong_cmp_fiber/internal/model/dto"
"github.com/break/junhong_cmp_fiber/internal/store/postgres"
"github.com/break/junhong_cmp_fiber/pkg/constants"
"github.com/break/junhong_cmp_fiber/pkg/errors"
"github.com/break/junhong_cmp_fiber/pkg/middleware"
"gorm.io/gorm"
)
// ListQuery 查询换货列表并完成权限、分页和响应投影。
type ListQuery struct {
db *gorm.DB
}
type assetSide string
const (
// oldAssetSide 表示旧资产查询侧。
oldAssetSide assetSide = "old"
// newAssetSide 表示新资产查询侧。
newAssetSide assetSide = "new"
)
// NewListQuery 创建换货列表查询。
func NewListQuery(db *gorm.DB) *ListQuery {
return &ListQuery{db: db}
}
// List 按新旧资产关键词和其他列表条件查询换货单。
func (q *ListQuery) List(ctx context.Context, req *dto.ExchangeListRequest) (*dto.ExchangeListResponse, error) {
page := constants.DefaultPage
if req.Page != nil {
page = *req.Page
}
pageSize := constants.DefaultPageSize
if req.PageSize != nil {
pageSize = *req.PageSize
}
query := q.db.WithContext(ctx).Model(&model.ExchangeOrder{})
query = middleware.ApplyShopFilter(ctx, query)
query = applyListFilters(query, req)
var total int64
if err := query.Count(&total).Error; err != nil {
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询换货单数量失败")
}
var orders []*model.ExchangeOrder
offset := (page - 1) * pageSize
if err := query.Order("created_at DESC").Offset(offset).Limit(pageSize).Find(&orders).Error; err != nil {
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询换货单列表失败")
}
submitterIDs := make([]uint, 0, len(orders))
for _, order := range orders {
if order.Creator > 0 {
submitterIDs = append(submitterIDs, order.Creator)
}
}
accounts, err := postgres.NewAccountStore(q.db, nil).GetDisplayAccountsByIDs(ctx, submitterIDs)
if err != nil {
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询换货提交人失败")
}
submitterNames := make(map[uint]string, len(accounts))
for _, account := range accounts {
submitterNames[account.ID] = account.Username
}
items := make([]*dto.ExchangeOrderResponse, 0, len(orders))
for _, order := range orders {
item := projectExchangeOrder(order)
item.SubmitterName = submitterNames[order.Creator]
items = append(items, item)
}
return &dto.ExchangeListResponse{List: items, Total: total, Page: page, PageSize: pageSize}, nil
}
// applyListFilters 组装列表计数和数据查询共用的全部过滤条件。
func applyListFilters(query *gorm.DB, req *dto.ExchangeListRequest) *gorm.DB {
if req.Status != nil {
query = query.Where("status = ?", *req.Status)
}
if req.FlowType != "" {
query = query.Where("COALESCE(NULLIF(flow_type, ''), ?) = ?", constants.ExchangeFlowTypeShipping, req.FlowType)
}
query = applyAssetKeyword(query, oldAssetSide, req.OldAssetKeyword)
query = applyAssetKeyword(query, newAssetSide, req.NewAssetKeyword)
if req.CreatedAtStart != nil {
query = query.Where("created_at >= ?", *req.CreatedAtStart)
}
if req.CreatedAtEnd != nil {
query = query.Where("created_at <= ?", *req.CreatedAtEnd)
}
return query
}
// applyAssetKeyword 使用子查询按资产类型和主键命中,避免依赖历史快照内容或逐行读取资产。
func applyAssetKeyword(query *gorm.DB, side assetSide, keyword string) *gorm.DB {
if keyword == "" {
return query
}
like := "%" + keyword + "%"
cardIDs := query.Session(&gorm.Session{NewDB: true}).Model(&model.IotCard{}).
Select("id").
Where("iccid LIKE ? OR msisdn LIKE ? OR virtual_no LIKE ?", like, like, like)
deviceIDs := query.Session(&gorm.Session{NewDB: true}).Model(&model.Device{}).
Select("id").
Where("virtual_no LIKE ? OR imei LIKE ? OR sn LIKE ?", like, like, like)
prefix := string(side)
return query.Where(
"("+prefix+"_asset_type = ? AND "+prefix+"_asset_id IN (?)) OR ("+prefix+"_asset_type = ? AND "+prefix+"_asset_id IN (?))",
constants.ExchangeAssetTypeIotCard, cardIDs, constants.ExchangeAssetTypeDevice, deviceIDs,
)
}
// projectExchangeOrder 将只读模型投影为列表响应,不用于后续写侧判断。
func projectExchangeOrder(order *model.ExchangeOrder) *dto.ExchangeOrderResponse {
var deletedAt *time.Time
if order.DeletedAt.Valid {
deletedAt = &order.DeletedAt.Time
}
// 失败原因只在迁移失败时对外可见,其他状态一律不返回,避免把历史原因误读为当前状态。
failureReason := ""
if order.MigrationStatus == constants.ExchangeMigrationStatusFailed {
failureReason = order.MigrationFailureReason
}
return &dto.ExchangeOrderResponse{
ID: order.ID, ExchangeNo: order.ExchangeNo,
FlowType: effectiveFlowType(order.FlowType), FlowTypeName: constants.GetExchangeFlowTypeName(order.FlowType),
OldAssetType: order.OldAssetType, OldAssetID: order.OldAssetID, OldAssetIdentifier: order.OldAssetIdentifier,
NewAssetType: order.NewAssetType, NewAssetID: order.NewAssetID, NewAssetIdentifier: order.NewAssetIdentifier,
RecipientName: order.RecipientName, RecipientPhone: order.RecipientPhone, RecipientAddress: order.RecipientAddress,
ExpressCompany: order.ExpressCompany, ExpressNo: order.ExpressNo,
MigrateData: order.MigrateData, MigrationCompleted: order.MigrationCompleted, MigrationBalance: order.MigrationBalance,
MigrationStatus: order.MigrationStatus, MigrationStatusName: constants.GetExchangeMigrationStatusName(order.MigrationStatus),
MigrationFailureReason: failureReason,
ShippedAt: order.ShippedAt, CompletedAt: order.CompletedAt,
ExchangeReason: order.ExchangeReason, Remark: order.Remark,
Status: order.Status, StatusName: constants.GetExchangeStatusName(order.Status), StatusText: constants.GetExchangeStatusName(order.Status),
ShopID: order.ShopID, CreatedAt: order.CreatedAt, UpdatedAt: order.UpdatedAt, DeletedAt: deletedAt,
SubmitterID: order.Creator, Creator: order.Creator, Updater: order.Updater,
}
}
func effectiveFlowType(flowType string) string {
if flowType == "" {
return constants.ExchangeFlowTypeShipping
}
return flowType
}