31e354e31c
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_013nMthbVEmQquxBRKb9Fj8u
65 lines
2.1 KiB
Go
65 lines
2.1 KiB
Go
package store
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
|
|
"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
|
|
}
|