64 lines
1.8 KiB
Go
64 lines
1.8 KiB
Go
package repository
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
|
|
"gorm.io/gorm"
|
|
"pay-bridge/internal/model"
|
|
)
|
|
|
|
// RefundOrderRepository 退款记录数据访问
|
|
type RefundOrderRepository struct {
|
|
db *gorm.DB
|
|
}
|
|
|
|
func NewRefundOrderRepository(db *gorm.DB) *RefundOrderRepository {
|
|
return &RefundOrderRepository{db: db}
|
|
}
|
|
|
|
// Create 创建退款单
|
|
func (r *RefundOrderRepository) Create(ctx context.Context, refund *model.RefundOrder) error {
|
|
return r.db.WithContext(ctx).Create(refund).Error
|
|
}
|
|
|
|
// GetByRefundNo 按 refund_no 查询
|
|
func (r *RefundOrderRepository) GetByRefundNo(ctx context.Context, refundNo string) (*model.RefundOrder, error) {
|
|
var refund model.RefundOrder
|
|
err := r.db.WithContext(ctx).Where("refund_no = ?", refundNo).First(&refund).Error
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
return nil, nil
|
|
}
|
|
return &refund, err
|
|
}
|
|
|
|
// SumRefundedAmount 统计某笔交易已退款总额(成功+处理中)
|
|
func (r *RefundOrderRepository) SumRefundedAmount(ctx context.Context, tradeNo string) (int64, error) {
|
|
var total int64
|
|
err := r.db.WithContext(ctx).Model(&model.RefundOrder{}).
|
|
Where("trade_no = ? AND status IN ?", tradeNo, []model.RefundStatus{
|
|
model.RefundStatusPending,
|
|
model.RefundStatusProcessing,
|
|
model.RefundStatusSuccess,
|
|
}).
|
|
Select("COALESCE(SUM(refund_amount), 0)").
|
|
Scan(&total).Error
|
|
return total, err
|
|
}
|
|
|
|
// UpdateStatus 更新退款状态
|
|
func (r *RefundOrderRepository) UpdateStatus(ctx context.Context, refundNo string, fromStatus, toStatus model.RefundStatus, updates map[string]any) (bool, error) {
|
|
if updates == nil {
|
|
updates = make(map[string]any)
|
|
}
|
|
updates["status"] = toStatus
|
|
|
|
result := r.db.WithContext(ctx).Model(&model.RefundOrder{}).
|
|
Where("refund_no = ? AND status = ?", refundNo, fromStatus).
|
|
Updates(updates)
|
|
if result.Error != nil {
|
|
return false, result.Error
|
|
}
|
|
return result.RowsAffected > 0, nil
|
|
}
|