优化支付日志和配置删除提示
This commit is contained in:
@@ -89,7 +89,7 @@ func main() {
|
|||||||
if deps.DB != nil {
|
if deps.DB != nil {
|
||||||
ordertimeout.New(deps.DB, deps.Redis, logger).Start(jobCtx)
|
ordertimeout.New(deps.DB, deps.Redis, logger).Start(jobCtx)
|
||||||
if paymentConfigRepo := newPaymentConfigRepositoryForJobs(cfg, deps.DB, logger); paymentConfigRepo != nil {
|
if paymentConfigRepo := newPaymentConfigRepositoryForJobs(cfg, deps.DB, logger); paymentConfigRepo != nil {
|
||||||
paymentRepo := payment.NewRepository(deps.DB, paymentConfigRepo, nil)
|
paymentRepo := payment.NewRepository(deps.DB, paymentConfigRepo, nil, payment.WithLogger(logger))
|
||||||
refundretry.New(deps.DB, deps.Redis, logger, paymentRepo).Start(jobCtx)
|
refundretry.New(deps.DB, deps.Redis, logger, paymentRepo).Start(jobCtx)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
package logging
|
||||||
|
|
||||||
|
import "context"
|
||||||
|
|
||||||
|
type requestIDContextKey struct{}
|
||||||
|
|
||||||
|
// WithRequestID 把请求 ID 写入标准 context,供非 HTTP 层日志关联请求链路。
|
||||||
|
func WithRequestID(ctx context.Context, requestID string) context.Context {
|
||||||
|
if ctx == nil || requestID == "" {
|
||||||
|
return ctx
|
||||||
|
}
|
||||||
|
return context.WithValue(ctx, requestIDContextKey{}, requestID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// RequestIDFromContext 从标准 context 读取请求 ID。
|
||||||
|
func RequestIDFromContext(ctx context.Context) string {
|
||||||
|
if ctx == nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
value, ok := ctx.Value(requestIDContextKey{}).(string)
|
||||||
|
if !ok {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return value
|
||||||
|
}
|
||||||
@@ -57,7 +57,7 @@ func New(cfg config.LogConfig) (*zap.Logger, error) {
|
|||||||
return zap.New(
|
return zap.New(
|
||||||
zapcore.NewTee(cores...),
|
zapcore.NewTee(cores...),
|
||||||
zap.AddCaller(),
|
zap.AddCaller(),
|
||||||
zap.AddStacktrace(zapcore.ErrorLevel),
|
zap.AddStacktrace(zapcore.PanicLevel),
|
||||||
), nil
|
), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import (
|
|||||||
"crypto/rand"
|
"crypto/rand"
|
||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
|
|
||||||
|
"hfb_sys/backend/internal/logging"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -20,6 +22,7 @@ func RequestID() gin.HandlerFunc {
|
|||||||
}
|
}
|
||||||
c.Set(ContextRequestID, requestID)
|
c.Set(ContextRequestID, requestID)
|
||||||
c.Writer.Header().Set(RequestIDHeader, requestID)
|
c.Writer.Header().Set(RequestIDHeader, requestID)
|
||||||
|
c.Request = c.Request.WithContext(logging.WithRequestID(c.Request.Context(), requestID))
|
||||||
c.Next()
|
c.Next()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
package payment
|
package payment
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
"io"
|
"io"
|
||||||
"log"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
@@ -15,15 +15,60 @@ import (
|
|||||||
"hfb_sys/backend/pkg/response"
|
"hfb_sys/backend/pkg/response"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
|
"go.uber.org/zap"
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Handler struct {
|
type Handler struct {
|
||||||
service *Service
|
service *Service
|
||||||
|
logger *zap.Logger
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewHandler(service *Service) *Handler {
|
func NewHandler(service *Service, options ...HandlerOption) *Handler {
|
||||||
return &Handler{service: service}
|
handler := &Handler{
|
||||||
|
service: service,
|
||||||
|
logger: zap.NewNop(),
|
||||||
|
}
|
||||||
|
for _, option := range options {
|
||||||
|
option(handler)
|
||||||
|
}
|
||||||
|
if handler.logger == nil {
|
||||||
|
handler.logger = zap.NewNop()
|
||||||
|
}
|
||||||
|
return handler
|
||||||
|
}
|
||||||
|
|
||||||
|
type HandlerOption func(*Handler)
|
||||||
|
|
||||||
|
// WithHandlerLogger 为支付 HTTP 处理器注入结构化日志器。
|
||||||
|
func WithHandlerLogger(logger *zap.Logger) HandlerOption {
|
||||||
|
return func(handler *Handler) {
|
||||||
|
if logger != nil {
|
||||||
|
handler.logger = logger
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) log() *zap.Logger {
|
||||||
|
if h == nil || h.logger == nil {
|
||||||
|
return zap.NewNop()
|
||||||
|
}
|
||||||
|
return h.logger
|
||||||
|
}
|
||||||
|
|
||||||
|
func notifyLogFields(ctx context.Context, provider string, params map[string]string, contentType string, bodySize int, fields ...zap.Field) []zap.Field {
|
||||||
|
base := paymentLogFields(ctx,
|
||||||
|
zap.String("provider", provider),
|
||||||
|
zap.String("third_order_id", params["third_order_id"]),
|
||||||
|
zap.String("provider_order_id", firstNonEmpty(params["provider_order_id"], params["leshua_order_id"], params["schc_order_id"])),
|
||||||
|
zap.String("merchant_refund_id", params["merchant_refund_id"]),
|
||||||
|
zap.String("provider_refund_id", firstNonEmpty(params["provider_refund_id"], params["leshua_refund_id"], params["schc_refund_id"])),
|
||||||
|
zap.String("status", params["status"]),
|
||||||
|
zap.String("amount", params["amount"]),
|
||||||
|
zap.String("content_type", contentType),
|
||||||
|
zap.Int("body_size", bodySize),
|
||||||
|
)
|
||||||
|
return append(base, fields...)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) Start(c *gin.Context) {
|
func (h *Handler) Start(c *gin.Context) {
|
||||||
@@ -103,22 +148,14 @@ func (h *Handler) LeshuaNotify(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
rawPayload := string(body)
|
rawPayload := string(body)
|
||||||
contentType := c.GetHeader("Content-Type")
|
contentType := c.GetHeader("Content-Type")
|
||||||
log.Printf(
|
h.log().Info("payment notify received", notifyLogFields(c.Request.Context(), "leshua", params, contentType, len(body))...)
|
||||||
"[payment] leshua notify received third_order_id=%s leshua_order_id=%s status=%s amount=%s content_type=%s raw_payload=%s",
|
|
||||||
params["third_order_id"],
|
|
||||||
params["leshua_order_id"],
|
|
||||||
params["status"],
|
|
||||||
params["amount"],
|
|
||||||
contentType,
|
|
||||||
rawPayload,
|
|
||||||
)
|
|
||||||
result, err := h.service.HandleLeshuaNotify(c.Request.Context(), params, rawPayload, contentType)
|
result, err := h.service.HandleLeshuaNotify(c.Request.Context(), params, rawPayload, contentType)
|
||||||
if err != nil || result == nil || !result.OK {
|
if err != nil || result == nil || !result.OK {
|
||||||
log.Printf("[payment] leshua notify failed third_order_id=%s err=%v", params["third_order_id"], err)
|
h.log().Warn("payment notify failed", notifyLogFields(c.Request.Context(), "leshua", params, contentType, len(body), zap.Error(err))...)
|
||||||
c.String(http.StatusOK, "FAIL")
|
c.String(http.StatusOK, "FAIL")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
log.Printf("[payment] leshua notify processed third_order_id=%s status=%s", params["third_order_id"], params["status"])
|
h.log().Info("payment notify processed", notifyLogFields(c.Request.Context(), "leshua", params, contentType, len(body))...)
|
||||||
c.String(http.StatusOK, result.Message)
|
c.String(http.StatusOK, result.Message)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -136,22 +173,14 @@ func (h *Handler) LakalaNotify(c *gin.Context) {
|
|||||||
rawPayload := string(body)
|
rawPayload := string(body)
|
||||||
contentType := c.GetHeader("Content-Type")
|
contentType := c.GetHeader("Content-Type")
|
||||||
authorization := c.GetHeader("Authorization")
|
authorization := c.GetHeader("Authorization")
|
||||||
log.Printf(
|
h.log().Info("payment notify received", notifyLogFields(c.Request.Context(), "lakala", params, contentType, len(body))...)
|
||||||
"[payment] lakala notify received third_order_id=%s provider_order_id=%s status=%s amount=%s content_type=%s raw_payload=%s",
|
|
||||||
params["third_order_id"],
|
|
||||||
params["provider_order_id"],
|
|
||||||
params["status"],
|
|
||||||
params["amount"],
|
|
||||||
contentType,
|
|
||||||
rawPayload,
|
|
||||||
)
|
|
||||||
result, err := h.service.HandleNotify(c.Request.Context(), "lakala", params, rawPayload, contentType, authorization)
|
result, err := h.service.HandleNotify(c.Request.Context(), "lakala", params, rawPayload, contentType, authorization)
|
||||||
if err != nil || result == nil || !result.OK {
|
if err != nil || result == nil || !result.OK {
|
||||||
log.Printf("[payment] lakala notify failed third_order_id=%s err=%v", params["third_order_id"], err)
|
h.log().Warn("payment notify failed", notifyLogFields(c.Request.Context(), "lakala", params, contentType, len(body), zap.Error(err))...)
|
||||||
c.JSON(http.StatusOK, gin.H{"code": "FAIL", "message": "失败"})
|
c.JSON(http.StatusOK, gin.H{"code": "FAIL", "message": "失败"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
log.Printf("[payment] lakala notify processed third_order_id=%s status=%s", params["third_order_id"], params["status"])
|
h.log().Info("payment notify processed", notifyLogFields(c.Request.Context(), "lakala", params, contentType, len(body))...)
|
||||||
c.JSON(http.StatusOK, gin.H{"code": "SUCCESS", "message": "执行成功"})
|
c.JSON(http.StatusOK, gin.H{"code": "SUCCESS", "message": "执行成功"})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -169,23 +198,14 @@ func (h *Handler) ShunchengNotify(c *gin.Context) {
|
|||||||
rawPayload := string(body)
|
rawPayload := string(body)
|
||||||
contentType := c.GetHeader("Content-Type")
|
contentType := c.GetHeader("Content-Type")
|
||||||
authorization := c.GetHeader("Authorization")
|
authorization := c.GetHeader("Authorization")
|
||||||
log.Printf(
|
h.log().Info("payment notify received", notifyLogFields(c.Request.Context(), "shuncheng", params, contentType, len(body))...)
|
||||||
"[payment] shuncheng notify received third_order_id=%s schc_order_id=%s schc_refund_id=%s status=%s amount=%s content_type=%s raw_payload=%s",
|
|
||||||
params["third_order_id"],
|
|
||||||
params["schc_order_id"],
|
|
||||||
params["schc_refund_id"],
|
|
||||||
params["status"],
|
|
||||||
params["amount"],
|
|
||||||
contentType,
|
|
||||||
rawPayload,
|
|
||||||
)
|
|
||||||
result, err := h.service.HandleNotify(c.Request.Context(), "shuncheng", params, rawPayload, contentType, authorization)
|
result, err := h.service.HandleNotify(c.Request.Context(), "shuncheng", params, rawPayload, contentType, authorization)
|
||||||
if err != nil || result == nil || !result.OK {
|
if err != nil || result == nil || !result.OK {
|
||||||
log.Printf("[payment] shuncheng notify failed third_order_id=%s err=%v", params["third_order_id"], err)
|
h.log().Warn("payment notify failed", notifyLogFields(c.Request.Context(), "shuncheng", params, contentType, len(body), zap.Error(err))...)
|
||||||
c.String(http.StatusOK, "FAIL")
|
c.String(http.StatusOK, "FAIL")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
log.Printf("[payment] shuncheng notify processed third_order_id=%s status=%s", params["third_order_id"], params["status"])
|
h.log().Info("payment notify processed", notifyLogFields(c.Request.Context(), "shuncheng", params, contentType, len(body))...)
|
||||||
c.String(http.StatusOK, result.Message)
|
c.String(http.StatusOK, result.Message)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,9 +2,11 @@ package payment
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"gorm.io/gorm"
|
|
||||||
"hfb_sys/backend/internal/model"
|
"hfb_sys/backend/internal/model"
|
||||||
"log"
|
|
||||||
|
"go.uber.org/zap"
|
||||||
|
"gorm.io/gorm"
|
||||||
)
|
)
|
||||||
|
|
||||||
func (r *Repository) HandleLeshuaNotify(ctx context.Context, params map[string]string, rawPayload string, contentType string) (*NotifyResult, error) {
|
func (r *Repository) HandleLeshuaNotify(ctx context.Context, params map[string]string, rawPayload string, contentType string) (*NotifyResult, error) {
|
||||||
@@ -31,7 +33,15 @@ func (r *Repository) HandleNotify(ctx context.Context, provider string, params m
|
|||||||
|
|
||||||
if amount := parseCent(params["amount"]); amount > 0 && amount != payment.AmountCent {
|
if amount := parseCent(params["amount"]); amount > 0 && amount != payment.AmountCent {
|
||||||
if err := r.recordNotifyDiagnostic(ctx, payment.ID, params, rawPayload, contentType, verify, "amount_mismatch"); err != nil {
|
if err := r.recordNotifyDiagnostic(ctx, payment.ID, params, rawPayload, contentType, verify, "amount_mismatch"); err != nil {
|
||||||
log.Printf("[payment] %s notify diagnostic save failed third_order_id=%s err=%v", runtimeConfig.Provider, params["third_order_id"], err)
|
r.log().Warn("payment notify diagnostic save failed", paymentLogFields(ctx, appendFields(
|
||||||
|
paymentOrderFields(payment),
|
||||||
|
runtimeConfigFields(runtimeConfig),
|
||||||
|
[]zap.Field{
|
||||||
|
zap.String("diagnostic_status", "amount_mismatch"),
|
||||||
|
zap.Error(err),
|
||||||
|
},
|
||||||
|
)...,
|
||||||
|
)...)
|
||||||
}
|
}
|
||||||
return nil, ErrPaymentVerifyFailed
|
return nil, ErrPaymentVerifyFailed
|
||||||
}
|
}
|
||||||
@@ -106,22 +116,37 @@ func (r *Repository) verifyNotify(ctx context.Context, payment *model.PaymentOrd
|
|||||||
}
|
}
|
||||||
verify, err := runtimeConfig.Channel.VerifyNotify(params, rawPayload, contentType, authorization)
|
verify, err := runtimeConfig.Channel.VerifyNotify(params, rawPayload, contentType, authorization)
|
||||||
if err != nil || !verify.OK {
|
if err != nil || !verify.OK {
|
||||||
log.Printf(
|
r.log().Warn("payment notify verify failed", paymentLogFields(ctx, appendFields(
|
||||||
"[payment] %s notify verify failed payment_id=%d third_order_id=%s got=%s expected=%s keys=%v base_string=%s",
|
paymentOrderFields(payment),
|
||||||
runtimeConfig.Provider,
|
runtimeConfigFields(runtimeConfig),
|
||||||
payment.ID,
|
[]zap.Field{
|
||||||
params["third_order_id"],
|
zap.String("sign_got", verify.Got),
|
||||||
verify.Got,
|
zap.String("sign_expected", firstNonEmpty(verify.Expected["notify_key"], verify.Expected["notify_cert"], verify.Expected["error"])),
|
||||||
firstNonEmpty(verify.Expected["notify_key"], verify.Expected["notify_cert"], verify.Expected["error"]),
|
zap.Strings("param_keys", verify.ParamKeys),
|
||||||
verify.ParamKeys,
|
zap.String("sign_base_string", firstNonEmpty(verify.BaseString["notify_key"], verify.BaseString["notify_cert"])),
|
||||||
firstNonEmpty(verify.BaseString["notify_key"], verify.BaseString["notify_cert"]),
|
zap.Error(err),
|
||||||
)
|
},
|
||||||
|
)...,
|
||||||
|
)...)
|
||||||
if err := r.recordNotifyDiagnostic(ctx, payment.ID, params, rawPayload, contentType, verify, "verify_failed"); err != nil {
|
if err := r.recordNotifyDiagnostic(ctx, payment.ID, params, rawPayload, contentType, verify, "verify_failed"); err != nil {
|
||||||
log.Printf("[payment] %s notify diagnostic save failed payment_id=%d err=%v", runtimeConfig.Provider, payment.ID, err)
|
r.log().Warn("payment notify diagnostic save failed", paymentLogFields(ctx, appendFields(
|
||||||
|
paymentOrderFields(payment),
|
||||||
|
runtimeConfigFields(runtimeConfig),
|
||||||
|
[]zap.Field{
|
||||||
|
zap.String("diagnostic_status", "verify_failed"),
|
||||||
|
zap.Error(err),
|
||||||
|
},
|
||||||
|
)...,
|
||||||
|
)...)
|
||||||
}
|
}
|
||||||
return verify, ErrPaymentVerifyFailed
|
return verify, ErrPaymentVerifyFailed
|
||||||
}
|
}
|
||||||
log.Printf("[payment] %s notify verified payment_id=%d third_order_id=%s matched_key=%s", runtimeConfig.Provider, payment.ID, params["third_order_id"], verify.MatchedKey)
|
r.log().Info("payment notify verified", paymentLogFields(ctx, appendFields(
|
||||||
|
paymentOrderFields(payment),
|
||||||
|
runtimeConfigFields(runtimeConfig),
|
||||||
|
[]zap.Field{zap.String("matched_key", verify.MatchedKey)},
|
||||||
|
)...,
|
||||||
|
)...)
|
||||||
return verify, nil
|
return verify, nil
|
||||||
}
|
}
|
||||||
func (r *Repository) recordNotifyDiagnostic(ctx context.Context, paymentID uint64, params map[string]string, rawPayload string, contentType string, verify channelVerifyNotifyResult, status string) error {
|
func (r *Repository) recordNotifyDiagnostic(ctx context.Context, paymentID uint64, params map[string]string, rawPayload string, contentType string, verify channelVerifyNotifyResult, status string) error {
|
||||||
|
|||||||
@@ -3,12 +3,14 @@ package payment
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"gorm.io/gorm"
|
"time"
|
||||||
"gorm.io/gorm/clause"
|
|
||||||
"hfb_sys/backend/internal/model"
|
"hfb_sys/backend/internal/model"
|
||||||
"hfb_sys/backend/internal/timeutil"
|
"hfb_sys/backend/internal/timeutil"
|
||||||
"log"
|
|
||||||
"time"
|
"go.uber.org/zap"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
"gorm.io/gorm/clause"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Start 发起订单支付,并按请求支付方式选择对应默认渠道配置。
|
// Start 发起订单支付,并按请求支付方式选择对应默认渠道配置。
|
||||||
@@ -58,8 +60,11 @@ func (r *Repository) Start(ctx context.Context, userID uint64, orderID uint64, r
|
|||||||
return nil, ErrPaymentUnavailable
|
return nil, ErrPaymentUnavailable
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Printf("[payment] payment start order_id=%d order_no=%s payment_id=%d provider=%s amount_cent=%d third_order_id=%s",
|
r.log().Info("payment start", paymentLogFields(ctx, appendFields(
|
||||||
orderID, orderRow.OrderNo, payment.ID, runtimeConfig.Provider, payment.AmountCent, payment.ThirdOrderID)
|
paymentOrderFields(payment),
|
||||||
|
runtimeConfigFields(runtimeConfig),
|
||||||
|
)...,
|
||||||
|
)...)
|
||||||
resp, err := runtimeConfig.Channel.CreatePayment(ctx, channelCreatePaymentRequest{
|
resp, err := runtimeConfig.Channel.CreatePayment(ctx, channelCreatePaymentRequest{
|
||||||
ThirdOrderID: payment.ThirdOrderID,
|
ThirdOrderID: payment.ThirdOrderID,
|
||||||
AmountCent: payment.AmountCent,
|
AmountCent: payment.AmountCent,
|
||||||
@@ -73,14 +78,26 @@ func (r *Repository) Start(ctx context.Context, userID uint64, orderID uint64, r
|
|||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
_ = r.markPaymentFailed(ctx, payment.ID, nil, err.Error())
|
_ = r.markPaymentFailed(ctx, payment.ID, nil, err.Error())
|
||||||
log.Printf("[payment] payment request failed order_id=%d payment_id=%d provider=%s amount_cent=%d err=%v",
|
r.log().Warn("payment request failed", paymentLogFields(ctx, appendFields(
|
||||||
orderID, payment.ID, runtimeConfig.Provider, payment.AmountCent, err)
|
paymentOrderFields(payment),
|
||||||
|
runtimeConfigFields(runtimeConfig),
|
||||||
|
[]zap.Field{zap.Error(err)},
|
||||||
|
)...,
|
||||||
|
)...)
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if !resp.OK {
|
if !resp.OK {
|
||||||
_ = r.markPaymentFailed(ctx, payment.ID, resp.Raw, resp.ErrorMessage)
|
_ = r.markPaymentFailed(ctx, payment.ID, resp.Raw, resp.ErrorMessage)
|
||||||
log.Printf("[payment] payment rejected order_id=%d payment_id=%d provider=%s amount_cent=%d code=%s message=%s",
|
r.log().Warn("payment rejected", paymentLogFields(ctx, appendFields(
|
||||||
orderID, payment.ID, runtimeConfig.Provider, payment.AmountCent, firstNonEmpty(resp.Raw["code"], resp.Raw["resp_code"], resp.Raw["result_code"]), resp.ErrorMessage)
|
paymentOrderFields(payment),
|
||||||
|
runtimeConfigFields(runtimeConfig),
|
||||||
|
[]zap.Field{
|
||||||
|
zap.String("channel_code", firstNonEmpty(resp.Raw["code"], resp.Raw["resp_code"], resp.Raw["result_code"])),
|
||||||
|
zap.String("channel_message", resp.ErrorMessage),
|
||||||
|
zap.Strings("raw_response_keys", stringMapKeys(resp.Raw)),
|
||||||
|
},
|
||||||
|
)...,
|
||||||
|
)...)
|
||||||
return nil, ErrPaymentUnavailable
|
return nil, ErrPaymentUnavailable
|
||||||
}
|
}
|
||||||
if err := r.db.WithContext(ctx).Model(&model.PaymentOrder{}).Where("id = ?", payment.ID).Updates(map[string]any{
|
if err := r.db.WithContext(ctx).Model(&model.PaymentOrder{}).Where("id = ?", payment.ID).Updates(map[string]any{
|
||||||
@@ -100,8 +117,11 @@ func (r *Repository) Start(ctx context.Context, userID uint64, orderID uint64, r
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
r.recordConfigUsage(ctx, runtimeConfig, latest)
|
r.recordConfigUsage(ctx, runtimeConfig, latest)
|
||||||
log.Printf("[payment] payment result order_id=%d order_no=%s payment_id=%d provider=%s amount_cent=%d status=%s provider_order_id=%s",
|
r.log().Info("payment result", paymentLogFields(ctx, appendFields(
|
||||||
orderID, orderRow.OrderNo, latest.ID, runtimeConfig.Provider, latest.AmountCent, latest.Status, latest.ProviderOrderID)
|
paymentOrderFields(latest),
|
||||||
|
runtimeConfigFields(runtimeConfig),
|
||||||
|
)...,
|
||||||
|
)...)
|
||||||
dto := toDTO(*latest)
|
dto := toDTO(*latest)
|
||||||
return &dto, nil
|
return &dto, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,13 +3,14 @@ package payment
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"log"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"hfb_sys/backend/internal/model"
|
||||||
|
|
||||||
|
"go.uber.org/zap"
|
||||||
"gorm.io/datatypes"
|
"gorm.io/datatypes"
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
"gorm.io/gorm/clause"
|
"gorm.io/gorm/clause"
|
||||||
"hfb_sys/backend/internal/model"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func (r *Repository) StartRefund(ctx context.Context, orderID uint64, refundAmountCent int64, bizType string, remark string) (*RefundDTO, error) {
|
func (r *Repository) StartRefund(ctx context.Context, orderID uint64, refundAmountCent int64, bizType string, remark string) (*RefundDTO, error) {
|
||||||
@@ -29,7 +30,11 @@ func (r *Repository) StartRefund(ctx context.Context, orderID uint64, refundAmou
|
|||||||
if existing {
|
if existing {
|
||||||
latest, syncErr := r.syncRefundPayment(ctx, refundOrder, refundOrder.Status != "refunded")
|
latest, syncErr := r.syncRefundPayment(ctx, refundOrder, refundOrder.Status != "refunded")
|
||||||
if syncErr != nil {
|
if syncErr != nil {
|
||||||
log.Printf("[payment] sync existing refund failed order_id=%d payment_id=%d biz_type=%s err=%v", orderID, refundOrder.ID, bizType, syncErr)
|
r.log().Warn("payment existing refund sync failed", paymentLogFields(ctx, appendFields(
|
||||||
|
paymentOrderFields(refundOrder),
|
||||||
|
[]zap.Field{zap.String("biz_type", bizType), zap.Error(syncErr)},
|
||||||
|
)...,
|
||||||
|
)...)
|
||||||
dto := toRefundDTO(*refundOrder)
|
dto := toRefundDTO(*refundOrder)
|
||||||
return &dto, nil
|
return &dto, nil
|
||||||
}
|
}
|
||||||
@@ -59,16 +64,32 @@ func (r *Repository) StartRefund(ctx context.Context, orderID uint64, refundAmou
|
|||||||
return &dto, nil
|
return &dto, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Printf("[payment] refund start order_id=%d order_no=%s payment_id=%d biz_type=%s provider=%s amount_cent=%d merchant_refund_id=%s origin_third_order_id=%s origin_provider_order_id=%s",
|
r.log().Info("payment refund start", paymentLogFields(ctx, appendFields(
|
||||||
orderID, originalPayment.OrderNo, refundOrder.ID, bizType, runtimeConfig.Provider, refundAmountCent, refundOrder.ThirdOrderID, originalPayment.ThirdOrderID, refundOriginProviderOrderID(originalPayment))
|
paymentOrderFields(refundOrder),
|
||||||
|
runtimeConfigFields(runtimeConfig),
|
||||||
|
[]zap.Field{
|
||||||
|
zap.String("merchant_refund_id", refundOrder.ThirdOrderID),
|
||||||
|
zap.String("origin_third_order_id", originalPayment.ThirdOrderID),
|
||||||
|
zap.String("origin_provider_order_id", refundOriginProviderOrderID(originalPayment)),
|
||||||
|
},
|
||||||
|
)...,
|
||||||
|
)...)
|
||||||
r.recordConfigUsage(ctx, runtimeConfig, refundOrder)
|
r.recordConfigUsage(ctx, runtimeConfig, refundOrder)
|
||||||
if err := r.markOrderRefunding(ctx, orderID, refundAmountCent); err != nil {
|
if err := r.markOrderRefunding(ctx, orderID, refundAmountCent); err != nil {
|
||||||
log.Printf("[payment] mark order refunding failed order_id=%d err=%v", orderID, err)
|
r.log().Warn("payment mark order refunding failed", paymentLogFields(ctx,
|
||||||
|
zap.Uint64("order_id", orderID),
|
||||||
|
zap.Int64("refund_amount_cent", refundAmountCent),
|
||||||
|
zap.Error(err),
|
||||||
|
)...)
|
||||||
}
|
}
|
||||||
|
|
||||||
if runtimeConfig.Channel == nil {
|
if runtimeConfig.Channel == nil {
|
||||||
if err := r.markRefundFailed(ctx, refundOrder.ID, orderID, refundAmountCent, map[string]string{"error": "payment channel unavailable"}, nil); err != nil {
|
if err := r.markRefundFailed(ctx, refundOrder.ID, orderID, refundAmountCent, map[string]string{"error": "payment channel unavailable"}, nil); err != nil {
|
||||||
log.Printf("[payment] mark refund failed status failed order_id=%d payment_id=%d err=%v", orderID, refundOrder.ID, err)
|
r.log().Warn("payment mark refund failed status failed", paymentLogFields(ctx, appendFields(
|
||||||
|
paymentOrderFields(refundOrder),
|
||||||
|
[]zap.Field{zap.Error(err)},
|
||||||
|
)...,
|
||||||
|
)...)
|
||||||
}
|
}
|
||||||
return nil, ErrPaymentUnavailable
|
return nil, ErrPaymentUnavailable
|
||||||
}
|
}
|
||||||
@@ -87,18 +108,38 @@ func (r *Repository) StartRefund(ctx context.Context, orderID uint64, refundAmou
|
|||||||
rawRequest = resp.RawRequest
|
rawRequest = resp.RawRequest
|
||||||
}
|
}
|
||||||
if markErr := r.markRefundFailed(ctx, refundOrder.ID, orderID, refundAmountCent, map[string]string{"error": err.Error()}, rawRequest); markErr != nil {
|
if markErr := r.markRefundFailed(ctx, refundOrder.ID, orderID, refundAmountCent, map[string]string{"error": err.Error()}, rawRequest); markErr != nil {
|
||||||
log.Printf("[payment] mark refund failed status failed order_id=%d payment_id=%d err=%v", orderID, refundOrder.ID, markErr)
|
r.log().Warn("payment mark refund failed status failed", paymentLogFields(ctx, appendFields(
|
||||||
|
paymentOrderFields(refundOrder),
|
||||||
|
[]zap.Field{zap.Error(markErr)},
|
||||||
|
)...,
|
||||||
|
)...)
|
||||||
}
|
}
|
||||||
log.Printf("[payment] refund request failed order_id=%d payment_id=%d biz_type=%s provider=%s amount_cent=%d err=%v",
|
r.log().Warn("payment refund request failed", paymentLogFields(ctx, appendFields(
|
||||||
orderID, refundOrder.ID, bizType, runtimeConfig.Provider, refundAmountCent, err)
|
paymentOrderFields(refundOrder),
|
||||||
|
runtimeConfigFields(runtimeConfig),
|
||||||
|
[]zap.Field{zap.Error(err)},
|
||||||
|
)...,
|
||||||
|
)...)
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if !resp.OK {
|
if !resp.OK {
|
||||||
if markErr := r.markRefundFailed(ctx, refundOrder.ID, orderID, refundAmountCent, resp.Raw, resp.RawRequest); markErr != nil {
|
if markErr := r.markRefundFailed(ctx, refundOrder.ID, orderID, refundAmountCent, resp.Raw, resp.RawRequest); markErr != nil {
|
||||||
log.Printf("[payment] mark refund rejected status failed order_id=%d payment_id=%d err=%v", orderID, refundOrder.ID, markErr)
|
r.log().Warn("payment mark refund rejected status failed", paymentLogFields(ctx, appendFields(
|
||||||
|
paymentOrderFields(refundOrder),
|
||||||
|
[]zap.Field{zap.Error(markErr)},
|
||||||
|
)...,
|
||||||
|
)...)
|
||||||
}
|
}
|
||||||
log.Printf("[payment] refund rejected order_id=%d payment_id=%d biz_type=%s provider=%s amount_cent=%d code=%s message=%s",
|
r.log().Warn("payment refund rejected", paymentLogFields(ctx, appendFields(
|
||||||
orderID, refundOrder.ID, bizType, runtimeConfig.Provider, refundAmountCent, firstNonEmpty(resp.Raw["code"], resp.Raw["resp_code"], resp.Raw["result_code"]), resp.ErrorMessage)
|
paymentOrderFields(refundOrder),
|
||||||
|
runtimeConfigFields(runtimeConfig),
|
||||||
|
[]zap.Field{
|
||||||
|
zap.String("channel_code", firstNonEmpty(resp.Raw["code"], resp.Raw["resp_code"], resp.Raw["result_code"])),
|
||||||
|
zap.String("channel_message", resp.ErrorMessage),
|
||||||
|
zap.Strings("raw_response_keys", stringMapKeys(resp.Raw)),
|
||||||
|
},
|
||||||
|
)...,
|
||||||
|
)...)
|
||||||
return nil, ErrPaymentUnavailable
|
return nil, ErrPaymentUnavailable
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -111,8 +152,15 @@ func (r *Repository) StartRefund(ctx context.Context, orderID uint64, refundAmou
|
|||||||
}); err != nil {
|
}); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
log.Printf("[payment] refund result order_id=%d payment_id=%d biz_type=%s provider=%s amount_cent=%d status=%s provider_refund_id=%s",
|
r.log().Info("payment refund result", paymentLogFields(ctx, appendFields(
|
||||||
orderID, refundOrder.ID, bizType, runtimeConfig.Provider, refundAmountCent, resp.Status, resp.ProviderRefundID)
|
paymentOrderFields(refundOrder),
|
||||||
|
runtimeConfigFields(runtimeConfig),
|
||||||
|
[]zap.Field{
|
||||||
|
zap.String("refund_status", resp.Status),
|
||||||
|
zap.String("provider_refund_id", resp.ProviderRefundID),
|
||||||
|
},
|
||||||
|
)...,
|
||||||
|
)...)
|
||||||
|
|
||||||
latest, err := r.findPaymentByID(ctx, refundOrder.ID)
|
latest, err := r.findPaymentByID(ctx, refundOrder.ID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -259,7 +307,11 @@ func (r *Repository) syncRefundPayment(ctx context.Context, payment *model.Payme
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
if resp != nil && resp.RawRequest != nil {
|
if resp != nil && resp.RawRequest != nil {
|
||||||
if updateErr := r.updateRefundRawRequest(ctx, payment.ID, resp.RawRequest); updateErr != nil {
|
if updateErr := r.updateRefundRawRequest(ctx, payment.ID, resp.RawRequest); updateErr != nil {
|
||||||
log.Printf("[payment] update refund query raw request failed payment_id=%d err=%v", payment.ID, updateErr)
|
r.log().Warn("payment refund query raw request update failed", paymentLogFields(ctx, appendFields(
|
||||||
|
paymentOrderFields(payment),
|
||||||
|
[]zap.Field{zap.Error(updateErr)},
|
||||||
|
)...,
|
||||||
|
)...)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return nil, err
|
return nil, err
|
||||||
|
|||||||
@@ -2,18 +2,22 @@ package payment
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"log"
|
"sort"
|
||||||
|
|
||||||
"gorm.io/gorm"
|
"hfb_sys/backend/internal/logging"
|
||||||
"hfb_sys/backend/internal/model"
|
"hfb_sys/backend/internal/model"
|
||||||
"hfb_sys/backend/internal/modules/order"
|
"hfb_sys/backend/internal/modules/order"
|
||||||
"hfb_sys/backend/internal/modules/paymentconfig"
|
"hfb_sys/backend/internal/modules/paymentconfig"
|
||||||
|
|
||||||
|
"go.uber.org/zap"
|
||||||
|
"gorm.io/gorm"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Repository struct {
|
type Repository struct {
|
||||||
db *gorm.DB
|
db *gorm.DB
|
||||||
configRepo *paymentconfig.Repository
|
configRepo *paymentconfig.Repository
|
||||||
orderRepo *order.Repository
|
orderRepo *order.Repository
|
||||||
|
logger *zap.Logger
|
||||||
}
|
}
|
||||||
|
|
||||||
type runtimePaymentConfig struct {
|
type runtimePaymentConfig struct {
|
||||||
@@ -51,12 +55,91 @@ func RefundBizTypes() []string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// NewRepository 创建支付仓库,注入支付配置仓库和订单仓库。
|
// NewRepository 创建支付仓库,注入支付配置仓库和订单仓库。
|
||||||
func NewRepository(db *gorm.DB, configRepo *paymentconfig.Repository, orderRepo *order.Repository) *Repository {
|
func NewRepository(db *gorm.DB, configRepo *paymentconfig.Repository, orderRepo *order.Repository, options ...RepositoryOption) *Repository {
|
||||||
return &Repository{
|
repo := &Repository{
|
||||||
db: db,
|
db: db,
|
||||||
configRepo: configRepo,
|
configRepo: configRepo,
|
||||||
orderRepo: orderRepo,
|
orderRepo: orderRepo,
|
||||||
|
logger: zap.NewNop(),
|
||||||
}
|
}
|
||||||
|
for _, option := range options {
|
||||||
|
option(repo)
|
||||||
|
}
|
||||||
|
if repo.logger == nil {
|
||||||
|
repo.logger = zap.NewNop()
|
||||||
|
}
|
||||||
|
return repo
|
||||||
|
}
|
||||||
|
|
||||||
|
type RepositoryOption func(*Repository)
|
||||||
|
|
||||||
|
// WithLogger 为支付仓库注入结构化日志器。
|
||||||
|
func WithLogger(logger *zap.Logger) RepositoryOption {
|
||||||
|
return func(repo *Repository) {
|
||||||
|
if logger != nil {
|
||||||
|
repo.logger = logger
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) log() *zap.Logger {
|
||||||
|
if r == nil || r.logger == nil {
|
||||||
|
return zap.NewNop()
|
||||||
|
}
|
||||||
|
return r.logger
|
||||||
|
}
|
||||||
|
|
||||||
|
func paymentLogFields(ctx context.Context, fields ...zap.Field) []zap.Field {
|
||||||
|
base := []zap.Field{zap.String("module", "payment")}
|
||||||
|
if requestID := logging.RequestIDFromContext(ctx); requestID != "" {
|
||||||
|
base = append(base, zap.String("request_id", requestID))
|
||||||
|
}
|
||||||
|
return append(base, fields...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func runtimeConfigFields(runtimeConfig *runtimePaymentConfig) []zap.Field {
|
||||||
|
if runtimeConfig == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return []zap.Field{
|
||||||
|
zap.Uint64("payment_config_id", runtimeConfig.ID),
|
||||||
|
zap.String("provider", runtimeConfig.Provider),
|
||||||
|
zap.String("merchant_id", runtimeConfig.MerchantID),
|
||||||
|
zap.String("pay_way", runtimeConfig.PayWay),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func paymentOrderFields(payment *model.PaymentOrder) []zap.Field {
|
||||||
|
if payment == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return []zap.Field{
|
||||||
|
zap.Uint64("payment_id", payment.ID),
|
||||||
|
zap.Uint64("order_id", payment.OrderID),
|
||||||
|
zap.String("order_no", payment.OrderNo),
|
||||||
|
zap.String("third_order_id", payment.ThirdOrderID),
|
||||||
|
zap.String("provider_order_id", payment.ProviderOrderID),
|
||||||
|
zap.Int64("amount_cent", payment.AmountCent),
|
||||||
|
zap.String("biz_type", payment.BizType),
|
||||||
|
zap.String("status", payment.Status),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func appendFields(groups ...[]zap.Field) []zap.Field {
|
||||||
|
var out []zap.Field
|
||||||
|
for _, group := range groups {
|
||||||
|
out = append(out, group...)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func stringMapKeys(value map[string]string) []string {
|
||||||
|
keys := make([]string, 0, len(value))
|
||||||
|
for key := range value {
|
||||||
|
keys = append(keys, key)
|
||||||
|
}
|
||||||
|
sort.Strings(keys)
|
||||||
|
return keys
|
||||||
}
|
}
|
||||||
|
|
||||||
// isMockMode 判断当前运行时配置是否为模拟支付。
|
// isMockMode 判断当前运行时配置是否为模拟支付。
|
||||||
@@ -158,6 +241,10 @@ func (r *Repository) recordConfigUsage(ctx context.Context, runtimeConfig *runti
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
if err := r.configRepo.RecordUsage(ctx, runtimeConfig.ID, payment.ID, runtimeConfig.Provider, runtimeConfig.MerchantID, payment.AmountCent, payment.BizType); err != nil {
|
if err := r.configRepo.RecordUsage(ctx, runtimeConfig.ID, payment.ID, runtimeConfig.Provider, runtimeConfig.MerchantID, payment.AmountCent, payment.BizType); err != nil {
|
||||||
log.Printf("[payment] record config usage failed config_id=%d payment_id=%d err=%v", runtimeConfig.ID, payment.ID, err)
|
r.log().Warn("payment config usage record failed", paymentLogFields(ctx,
|
||||||
|
zap.Uint64("payment_config_id", runtimeConfig.ID),
|
||||||
|
zap.Uint64("payment_id", payment.ID),
|
||||||
|
zap.Error(err),
|
||||||
|
)...)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -46,6 +46,7 @@ type ConfigDTO struct {
|
|||||||
Status string `json:"status"`
|
Status string `json:"status"`
|
||||||
Environment string `json:"environment"`
|
Environment string `json:"environment"`
|
||||||
BusinessTags []string `json:"business_tags"`
|
BusinessTags []string `json:"business_tags"`
|
||||||
|
ReferenceCount int64 `json:"reference_count"`
|
||||||
TotalTransactions int64 `json:"total_transactions"`
|
TotalTransactions int64 `json:"total_transactions"`
|
||||||
TotalAmountCent int64 `json:"total_amount_cent"`
|
TotalAmountCent int64 `json:"total_amount_cent"`
|
||||||
LastUsedAt *string `json:"last_used_at"`
|
LastUsedAt *string `json:"last_used_at"`
|
||||||
|
|||||||
@@ -66,6 +66,9 @@ func (r *Repository) List(ctx context.Context, query ListQuery) ([]ConfigDTO, in
|
|||||||
if err := r.applySuccessfulPaymentStats(ctx, dtos); err != nil {
|
if err := r.applySuccessfulPaymentStats(ctx, dtos); err != nil {
|
||||||
return nil, 0, err
|
return nil, 0, err
|
||||||
}
|
}
|
||||||
|
if err := r.applyReferenceCounts(ctx, dtos); err != nil {
|
||||||
|
return nil, 0, err
|
||||||
|
}
|
||||||
|
|
||||||
return dtos, total, nil
|
return dtos, total, nil
|
||||||
}
|
}
|
||||||
@@ -87,6 +90,9 @@ func (r *Repository) FindByID(ctx context.Context, id uint64, includeSecret bool
|
|||||||
if err := r.applySuccessfulPaymentStats(ctx, statDTOs); err != nil {
|
if err := r.applySuccessfulPaymentStats(ctx, statDTOs); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
if err := r.applyReferenceCounts(ctx, statDTOs); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
dto = statDTOs[0]
|
dto = statDTOs[0]
|
||||||
if includeSecret {
|
if includeSecret {
|
||||||
if err := appendAuditLog(r.db.WithContext(ctx), actorID, "payment_config.view_secret", item.ID, meta, map[string]any{
|
if err := appendAuditLog(r.db.WithContext(ctx), actorID, "payment_config.view_secret", item.ID, meta, map[string]any{
|
||||||
@@ -145,6 +151,29 @@ func (r *Repository) applySuccessfulPaymentStats(ctx context.Context, dtos []Con
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// applyReferenceCounts 使用删除保护的同一口径统计配置被支付记录引用的次数。
|
||||||
|
func (r *Repository) applyReferenceCounts(ctx context.Context, dtos []ConfigDTO) error {
|
||||||
|
for idx := range dtos {
|
||||||
|
count, err := r.referenceCount(ctx, dtos[idx])
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
dtos[idx].ReferenceCount = count
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) referenceCount(ctx context.Context, dto ConfigDTO) (int64, error) {
|
||||||
|
var count int64
|
||||||
|
db := r.db.WithContext(ctx).Model(&model.PaymentOrder{}).
|
||||||
|
Where("payment_config_id = ?", dto.ID).
|
||||||
|
Or("(payment_config_id = ? OR payment_config_id IS NULL) AND provider = ? AND merchant_id = ? AND pay_way = ?", 0, dto.Provider, dto.MerchantID, dto.PayWay)
|
||||||
|
if err := db.Count(&count).Error; err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return count, nil
|
||||||
|
}
|
||||||
|
|
||||||
type nullableTime struct {
|
type nullableTime struct {
|
||||||
Time *time.Time
|
Time *time.Time
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -121,6 +121,20 @@ func TestListUsesSuccessfulPaymentStats(t *testing.T) {
|
|||||||
BizType: "order_pay",
|
BizType: "order_pay",
|
||||||
Status: "closed",
|
Status: "closed",
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
PaymentNo: "PAY-LEGACY",
|
||||||
|
OrderID: 3,
|
||||||
|
OrderNo: "ORD-LEGACY",
|
||||||
|
UserID: 2,
|
||||||
|
PaymentConfigID: 0,
|
||||||
|
Provider: "lakala",
|
||||||
|
MerchantID: "M1",
|
||||||
|
ThirdOrderID: "PAY-LEGACY",
|
||||||
|
PayWay: "WXZF",
|
||||||
|
AmountCent: 10130,
|
||||||
|
BizType: "order_pay",
|
||||||
|
Status: "failed",
|
||||||
|
},
|
||||||
}
|
}
|
||||||
if err := db.Create(&payments).Error; err != nil {
|
if err := db.Create(&payments).Error; err != nil {
|
||||||
t.Fatalf("create payments failed: %v", err)
|
t.Fatalf("create payments failed: %v", err)
|
||||||
@@ -137,6 +151,9 @@ func TestListUsesSuccessfulPaymentStats(t *testing.T) {
|
|||||||
if items[0].TotalTransactions != 1 || items[0].TotalAmountCent != 10130 {
|
if items[0].TotalTransactions != 1 || items[0].TotalAmountCent != 10130 {
|
||||||
t.Fatalf("success stats = %d/%d, want 1/10130", items[0].TotalTransactions, items[0].TotalAmountCent)
|
t.Fatalf("success stats = %d/%d, want 1/10130", items[0].TotalTransactions, items[0].TotalAmountCent)
|
||||||
}
|
}
|
||||||
|
if items[0].ReferenceCount != 3 {
|
||||||
|
t.Fatalf("reference_count = %d, want 3", items[0].ReferenceCount)
|
||||||
|
}
|
||||||
if items[0].LastUsedAt == nil {
|
if items[0].LastUsedAt == nil {
|
||||||
t.Fatal("last success pay time should not be nil")
|
t.Fatal("last success pay time should not be nil")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -233,10 +233,10 @@ func New(cfg config.Config, deps Dependencies, logger *zap.Logger) *gin.Engine {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if deps.DB != nil {
|
if deps.DB != nil {
|
||||||
paymentRepo = payment.NewRepository(deps.DB, paymentConfigRepo, orderRepo)
|
paymentRepo = payment.NewRepository(deps.DB, paymentConfigRepo, orderRepo, payment.WithLogger(logger))
|
||||||
}
|
}
|
||||||
paymentService := payment.NewService(paymentRepo)
|
paymentService := payment.NewService(paymentRepo)
|
||||||
paymentHandler := payment.NewHandler(paymentService)
|
paymentHandler := payment.NewHandler(paymentService, payment.WithHandlerLogger(logger))
|
||||||
var notificationRepo *notification.Repository
|
var notificationRepo *notification.Repository
|
||||||
if deps.DB != nil {
|
if deps.DB != nil {
|
||||||
notificationRepo = notification.NewRepository(deps.DB)
|
notificationRepo = notification.NewRepository(deps.DB)
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ export interface PaymentConfig {
|
|||||||
status: string
|
status: string
|
||||||
environment: string
|
environment: string
|
||||||
business_tags: string[] | null
|
business_tags: string[] | null
|
||||||
|
reference_count: number
|
||||||
total_transactions: number
|
total_transactions: number
|
||||||
total_amount_cent: number
|
total_amount_cent: number
|
||||||
last_used_at: string | null
|
last_used_at: string | null
|
||||||
|
|||||||
@@ -289,11 +289,12 @@ function tableRowClassName({ row }: { row: PaymentConfig }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function canDeleteConfig(row: PaymentConfig) {
|
function canDeleteConfig(row: PaymentConfig) {
|
||||||
return row.total_transactions <= 0
|
return (row.reference_count || 0) <= 0
|
||||||
}
|
}
|
||||||
|
|
||||||
function deleteDisabledReason(row: PaymentConfig) {
|
function deleteDisabledReason(row: PaymentConfig) {
|
||||||
return canDeleteConfig(row) ? '删除配置' : '已有交易记录,需要保留用于退款、查询和回调验签'
|
if (canDeleteConfig(row)) return '删除配置'
|
||||||
|
return `已有 ${row.reference_count || 0} 条支付记录引用,需要保留用于退款、查询和回调验签`
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
@@ -420,10 +421,13 @@ function deleteDisabledReason(row: PaymentConfig) {
|
|||||||
<span v-else class="standby-badge">备用</span>
|
<span v-else class="standby-badge">备用</span>
|
||||||
</template>
|
</template>
|
||||||
</el-table-column>
|
</el-table-column>
|
||||||
<el-table-column label="成功支付" min-width="150">
|
<el-table-column label="支付记录" min-width="150">
|
||||||
<template #default="{ row }">
|
<template #default="{ row }">
|
||||||
<div class="usage-cell">
|
<div class="usage-cell">
|
||||||
<div>成功: {{ row.total_transactions }} 笔</div>
|
<div>成功: {{ row.total_transactions }} 笔</div>
|
||||||
|
<div :class="{ 'usage-reference-locked': (row.reference_count || 0) > 0 }">
|
||||||
|
引用: {{ row.reference_count || 0 }} 条
|
||||||
|
</div>
|
||||||
<div>金额: ¥{{ formatAmount(row.total_amount_cent) }}</div>
|
<div>金额: ¥{{ formatAmount(row.total_amount_cent) }}</div>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
@@ -661,6 +665,11 @@ function deleteDisabledReason(row: PaymentConfig) {
|
|||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.usage-reference-locked {
|
||||||
|
color: #dc2626;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
.action-buttons {
|
.action-buttons {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
|
|||||||
Reference in New Issue
Block a user