129 lines
4.8 KiB
Go
129 lines
4.8 KiB
Go
package store
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"time"
|
|
|
|
"gorm.io/gorm"
|
|
|
|
"github.com/wangjia/pay/internal/model"
|
|
)
|
|
|
|
var (
|
|
ErrOrderNotFound = errors.New("store: order not found")
|
|
ErrAttemptNotFound = errors.New("store: attempt not found")
|
|
)
|
|
|
|
// GetOrder returns an order by out_trade_no.
|
|
func (s *OrderStore) GetOrder(outTradeNo string) (*model.OrderV2, error) {
|
|
var o model.OrderV2
|
|
if err := s.db.Where("out_trade_no = ?", outTradeNo).First(&o).Error; err != nil {
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
return nil, ErrOrderNotFound
|
|
}
|
|
return nil, fmt.Errorf("store.GetOrder: %w", err)
|
|
}
|
|
return &o, nil
|
|
}
|
|
|
|
// AttemptByProviderRef resolves an attempt from a bare provider_ref, so settlement
|
|
// can recover out_trade_no + channel from a callback/query that only carries the ref.
|
|
func (s *OrderStore) AttemptByProviderRef(providerRef string) (*model.Attempt, error) {
|
|
var a model.Attempt
|
|
if err := s.db.Where("provider_ref = ?", providerRef).First(&a).Error; err != nil {
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
return nil, ErrAttemptNotFound
|
|
}
|
|
return nil, fmt.Errorf("store.AttemptByProviderRef: %w", err)
|
|
}
|
|
return &a, nil
|
|
}
|
|
|
|
// ListAttemptsByStatus lists attempts in a status (for query-sync fallback).
|
|
func (s *OrderStore) ListAttemptsByStatus(status model.AttemptStatus, limit int) ([]model.Attempt, error) {
|
|
if limit <= 0 || limit > 200 {
|
|
limit = 100
|
|
}
|
|
var out []model.Attempt
|
|
if err := s.db.Where("status = ?", status).Order("id ASC").Limit(limit).Find(&out).Error; err != nil {
|
|
return nil, fmt.Errorf("store.ListAttemptsByStatus: %w", err)
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// ExpirePendingAttempts marks all pending attempts of an order as expired
|
|
// (used before a retry spawns a fresh attempt). Order status is untouched.
|
|
func (s *OrderStore) ExpirePendingAttempts(outTradeNo string) (int64, error) {
|
|
res := s.db.Model(&model.Attempt{}).
|
|
Where("out_trade_no = ? AND status = ?", outTradeNo, model.AttemptPending).
|
|
Update("status", model.AttemptExpired)
|
|
if res.Error != nil {
|
|
return 0, fmt.Errorf("store.ExpirePendingAttempts: %w", res.Error)
|
|
}
|
|
return res.RowsAffected, nil
|
|
}
|
|
|
|
// PaidAttempt returns the settled (paid) attempt of an order — the payment a
|
|
// refund reverses (channel + provider_ref for the original transaction).
|
|
func (s *OrderStore) PaidAttempt(outTradeNo string) (*model.Attempt, error) {
|
|
var a model.Attempt
|
|
err := s.db.Where("out_trade_no = ? AND status = ?", outTradeNo, model.AttemptPaid).First(&a).Error
|
|
if err != nil {
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
return nil, ErrAttemptNotFound
|
|
}
|
|
return nil, fmt.Errorf("store.PaidAttempt: %w", err)
|
|
}
|
|
return &a, nil
|
|
}
|
|
|
|
// ApplyRefundToOrder advances a settled order's status per cumulative refunds:
|
|
// fully refunded → refunded, else → partially_refunded. Guard: only from a
|
|
// post-paid, non-fully-refunded state (paid / partially_refunded / refunding).
|
|
func (s *OrderStore) ApplyRefundToOrder(outTradeNo string, fully bool) (bool, error) {
|
|
next := model.OrderPartRefundedV2
|
|
if fully {
|
|
next = model.OrderRefundedV2
|
|
}
|
|
res := s.db.Model(&model.OrderV2{}).
|
|
Where("out_trade_no = ? AND status IN ?", outTradeNo,
|
|
[]model.OrderStatusV2{model.OrderPaidV2, model.OrderPartRefundedV2, model.OrderRefundingV2}).
|
|
Update("status", next)
|
|
if res.Error != nil {
|
|
return false, fmt.Errorf("store.ApplyRefundToOrder: %w", res.Error)
|
|
}
|
|
return res.RowsAffected > 0, nil
|
|
}
|
|
|
|
// ExpireStaleOrders closes pending orders whose created_at predates cutoff
|
|
// (TTL 到期未付),条件 UPDATE 只翻 status=pending 的行——与并发 settle 翻 paid
|
|
// 互斥(谁先谁赢,另一方 RowsAffected=0),故幂等且崩溃安全。含"零尝试孤儿单"
|
|
// (建单后 CreateAttempt 失败、无 attempt 的 pending 单):它 status 仍是 pending,
|
|
// 同样被扫到关闭(P2-T4 复审记录的缺口)。cutoff 由调用方用注入时钟算,store 不碰时钟。
|
|
//
|
|
// 注:与 ExpirePendingAttempts 语义不同——那个是 attempt 级(标 attempt expired,
|
|
// 订单不动,retry 前用);这个是 order 级(标整张订单 expired)。
|
|
func (s *OrderStore) ExpireStaleOrders(cutoff time.Time, limit int) (int64, error) {
|
|
if limit <= 0 || limit > 1000 {
|
|
limit = 500
|
|
}
|
|
// 先选主键再批量 UPDATE:回避 "UPDATE ... ORDER BY LIMIT" 的方言差异(sqlite/mysql)。
|
|
var ids []uint64
|
|
if err := s.db.Model(&model.OrderV2{}).
|
|
Where("status = ? AND created_at < ?", model.OrderPendingV2, cutoff).
|
|
Order("id ASC").Limit(limit).Pluck("id", &ids).Error; err != nil {
|
|
return 0, fmt.Errorf("store.ExpireStaleOrders select: %w", err)
|
|
}
|
|
if len(ids) == 0 {
|
|
return 0, nil
|
|
}
|
|
res := s.db.Model(&model.OrderV2{}).
|
|
Where("id IN ? AND status = ?", ids, model.OrderPendingV2). // status 守卫兜住 select→update 间的并发翻转
|
|
Update("status", model.OrderExpiredV2)
|
|
if res.Error != nil {
|
|
return 0, fmt.Errorf("store.ExpireStaleOrders update: %w", res.Error)
|
|
}
|
|
return res.RowsAffected, nil
|
|
}
|