package refund import ( "context" "github.com/break/junhong_cmp_fiber/internal/model" "github.com/break/junhong_cmp_fiber/internal/model/dto" "github.com/break/junhong_cmp_fiber/pkg/constants" "github.com/break/junhong_cmp_fiber/pkg/errors" ) // loadAttemptResponses 批量读取退款申请的审批尝试历史,并补齐每次尝试的审批实例状态。 // // 尝试记录按提交次序升序返回,历史材料与审批结果不被覆盖;未接入尝试模式的存量申请返回空切片。 func (s *Service) loadAttemptResponses(ctx context.Context, refunds []*model.RefundRequest) (map[uint][]dto.RefundAttemptResponse, error) { result := make(map[uint][]dto.RefundAttemptResponse, len(refunds)) refundIDs := make([]uint, 0, len(refunds)) for _, refund := range refunds { if refund == nil || refund.ID == 0 { continue } refundIDs = append(refundIDs, refund.ID) result[refund.ID] = []dto.RefundAttemptResponse{} } if len(refundIDs) == 0 { return result, nil } var attempts []model.RefundRequestAttempt if err := s.db.WithContext(ctx). Where("refund_id IN ?", refundIDs). Order("refund_id ASC, attempt_no ASC, id ASC"). Find(&attempts).Error; err != nil { return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询退款审批尝试记录失败") } if len(attempts) == 0 { return result, nil } instanceIDs := make([]uint, 0, len(attempts)) for index := range attempts { if attempts[index].ApprovalInstanceID != nil && *attempts[index].ApprovalInstanceID > 0 { instanceIDs = append(instanceIDs, *attempts[index].ApprovalInstanceID) } } statuses := map[uint]int{} if len(instanceIDs) > 0 { var instances []model.ApprovalInstance if err := s.db.WithContext(ctx).Select("id", "status").Where("id IN ?", instanceIDs).Find(&instances).Error; err != nil { return nil, errors.Wrap(errors.CodeDatabaseError, err, "批量查询退款审批尝试实例状态失败") } for _, instance := range instances { statuses[instance.ID] = instance.Status } } for index := range attempts { attempt := &attempts[index] item := dto.RefundAttemptResponse{ ID: attempt.ID, AttemptNo: attempt.AttemptNo, Method: attempt.Method, MethodName: constants.RefundMethodName(attempt.Method), RefundAmount: attempt.RefundAmount, FrozenActualReceivedAmount: attempt.FrozenActualReceivedAmount, RefundReason: attempt.RefundReason, CustomerAccountInfo: attempt.CustomerAccountInfo, CustomerVoucherKey: []string(attempt.CustomerVoucherKeys), ChannelRefundRequestNo: attempt.ChannelRefundRequestNo, SubmittedByAccountID: attempt.SubmittedByAccountID, CreatedAt: attempt.CreatedAt.Format("2006-01-02 15:04:05"), } if len(item.CustomerVoucherKey) == 0 { item.CustomerVoucherKey = []string{} } if attempt.ApprovalInstanceID != nil && *attempt.ApprovalInstanceID > 0 { item.ApprovalInstanceID = *attempt.ApprovalInstanceID if status, exists := statuses[*attempt.ApprovalInstanceID]; exists { value := status item.ApprovalStatus = &value item.ApprovalStatusName = constants.GetApprovalStatusName(status) } } result[attempt.RefundID] = append(result[attempt.RefundID], item) } return result, nil }