From cd081d1cddb2daca82e0b570943318e94fbae951 Mon Sep 17 00:00:00 2001 From: yml Date: Thu, 19 Nov 2026 20:29:16 +0800 Subject: [PATCH] =?UTF-8?q?fix(order):=20=E6=94=AF=E6=8C=81=E5=AE=A2?= =?UTF-8?q?=E6=9C=8D=E8=B7=A8=E7=AB=99=E5=A4=84=E7=90=86=E8=AE=A2=E5=8D=95?= =?UTF-8?q?=E4=B8=8E=E9=80=80=E6=AC=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/internal/e2e/tenant_flow_test.go | 11 +-- .../internal/modules/order/admin_actions.go | 6 ++ backend/internal/modules/order/queries.go | 30 ------ .../internal/modules/order/refund_review.go | 4 +- backend/internal/modules/order/service.go | 40 +++----- .../modules/order/tenant_offer_test.go | 40 ++++---- .../internal/modules/order/tenant_scope.go | 75 --------------- backend/internal/modules/payment/dto.go | 25 +++++ backend/internal/modules/payment/handler.go | 13 +++ .../modules/payment/order_payments.go | 93 +++++++++++++++++++ backend/internal/modules/payment/refund.go | 48 +++++++++- backend/internal/modules/payment/service.go | 10 ++ .../modules/payment/tenant_scope_test.go | 42 +++++++++ backend/internal/router/router.go | 1 + backend/internal/router/router_test.go | 1 + .../000111_cs_cross_site_order_actions.sql | 18 ++++ .../src/features/admin/api/adminPayments.ts | 10 ++ .../admin/views/AdminOrderDetailView.vue | 73 ++++++++------- 18 files changed, 349 insertions(+), 191 deletions(-) delete mode 100644 backend/internal/modules/order/tenant_scope.go create mode 100644 backend/internal/modules/payment/order_payments.go create mode 100644 backend/migrations/000111_cs_cross_site_order_actions.sql diff --git a/backend/internal/e2e/tenant_flow_test.go b/backend/internal/e2e/tenant_flow_test.go index 6fbfc87c..ecb4bbdd 100644 --- a/backend/internal/e2e/tenant_flow_test.go +++ b/backend/internal/e2e/tenant_flow_test.go @@ -69,16 +69,13 @@ func TestCrossTenantFlowWithMockPayments(t *testing.T) { refundListing := createCrossTenantListing(t, db, dachui, ownerD, "L-DEMO-REFUND", "大锤退款商品", 9000, 72) seedCrossTenantOffers(t, db, refundListing, dachui.ID, jieyou.ID, 10000) refundOrder := createPaidCrossOrder(t, services, ctxJ, renterJ.ID, refundListing.ID, jieyou.ID, dachui.ID, jieyouMerchant.ID) - refundAmount := int64(0) - if refundOrder.RentAmountCent != nil { - refundAmount = *refundOrder.RentAmountCent - } - refund, err := services.payment.StartRefund(ctxJ, refundOrder.ID, refundAmount, "admin_refund", "双站 mock 退款验收") + // 从货源站发起退款也必须回到买方原支付租户和商户,而不是按当前访问站点退款。 + refund, err := services.order.AdminRefund(ctxD, refundOrder.ID) if err != nil { t.Fatalf("发起 mock 退款: %v", err) } - if refund.TenantID != jieyou.ID || refund.Status != "refunded" { - t.Fatalf("退款租户/状态 = %d/%s, want %d/refunded", refund.TenantID, refund.Status, jieyou.ID) + if refund.RefundStatus != "refunded" { + t.Fatalf("退款状态 = %s, want refunded", refund.RefundStatus) } var refundPayment model.PaymentOrder if err := db.Where("order_id = ? AND biz_type = ?", refundOrder.ID, "admin_refund").First(&refundPayment).Error; err != nil { diff --git a/backend/internal/modules/order/admin_actions.go b/backend/internal/modules/order/admin_actions.go index 1428dece..fcd220c0 100644 --- a/backend/internal/modules/order/admin_actions.go +++ b/backend/internal/modules/order/admin_actions.go @@ -93,6 +93,9 @@ func (r *Repository) AdminClose(ctx context.Context, adminID uint64, orderID uin "order_no": order.OrderNo, "listing_id": order.ListingID, "account_id": order.AccountID, + "buyer_tenant_id": order.BuyerTenantID, + "source_tenant_id": order.SourceTenantID, + "payment_tenant_id": order.PaymentTenantID, "reason": req.Reason, "before_order_status": beforeOrderStatus, "after_order_status": order.Status, @@ -607,6 +610,9 @@ func (r *Repository) AdminSeal(ctx context.Context, adminID uint64, orderID uint "order_no": order.OrderNo, "listing_id": order.ListingID, "account_id": order.AccountID, + "buyer_tenant_id": order.BuyerTenantID, + "source_tenant_id": order.SourceTenantID, + "payment_tenant_id": order.PaymentTenantID, "reason": req.Reason, "before_order_status": beforeOrderStatus, "after_order_status": order.Status, diff --git a/backend/internal/modules/order/queries.go b/backend/internal/modules/order/queries.go index c5aa99b2..cb776be0 100644 --- a/backend/internal/modules/order/queries.go +++ b/backend/internal/modules/order/queries.go @@ -370,7 +370,6 @@ func (r *Repository) FindAdmin(ctx context.Context, orderID uint64) (*OrderDTO, } dto := row.toAdminDTO() dto.SiteRole = tenantOrderRole(ctx, row.RentalOrder) - filterAdminActionsForSiteRole(&dto) applyPaymentDeadline(&dto, row.RentalOrder, pendingPaymentTimeoutMinutes(db)) dto.ActiveDispute = r.activeDisputeDTO(ctx, orderID) dto.Checkout = r.latestCheckoutAdminDTO(ctx, orderID) @@ -388,7 +387,6 @@ func (r *Repository) FindLatestAdminByListing(ctx context.Context, listingID uin } dto := row.toAdminDTO() dto.SiteRole = tenantOrderRole(ctx, row.RentalOrder) - filterAdminActionsForSiteRole(&dto) applyPaymentDeadline(&dto, row.RentalOrder, pendingPaymentTimeoutMinutes(db)) dto.ActiveDispute = r.activeDisputeDTO(ctx, row.ID) dto.Checkout = r.latestCheckoutAdminDTO(ctx, row.ID) @@ -551,16 +549,6 @@ func applyTenantOrderScope(query *gorm.DB, ctx context.Context) *gorm.DB { Where("(o.distribution_site_id IS NULL OR o.distribution_site_id = 0)") } -func applyBuyerTenantOrderScope(query *gorm.DB, ctx context.Context) *gorm.DB { - tenantID := tenancy.IDFromContext(ctx) - if tenantID == 0 { - return query - } - return query. - Where("o.buyer_tenant_id = ?", tenantID). - Where("(o.distribution_site_id IS NULL OR o.distribution_site_id = 0)") -} - func tenantOrderRole(ctx context.Context, order model.RentalOrder) string { tenantID := tenancy.IDFromContext(ctx) if tenantID == 0 { @@ -580,24 +568,6 @@ func tenantOrderRole(ctx context.Context, order model.RentalOrder) string { } } -func filterAdminActionsForSiteRole(dto *OrderDTO) { - if dto == nil || dto.AdminActions == nil || dto.SiteRole == "" || dto.SiteRole == "both" { - return - } - actions := dto.AdminActions - if dto.SiteRole == "buyer" { - actions.ResetHandoff = nil - actions.PlatformHandoff = nil - actions.ForceHandoff = nil - actions.PlatformOfflineSettlement = nil - } - if dto.SiteRole == "source" { - actions.PlatformCheckoutConfirm = nil - actions.PlatformCheckoutCounter = nil - actions.PlatformCheckoutDispute = nil - } -} - type orderRow struct { model.RentalOrder Title string diff --git a/backend/internal/modules/order/refund_review.go b/backend/internal/modules/order/refund_review.go index 8eeb42b8..b742f923 100644 --- a/backend/internal/modules/order/refund_review.go +++ b/backend/internal/modules/order/refund_review.go @@ -7,7 +7,7 @@ import ( // ListPendingRefund 查询所有待客服审核退款的订单。 func (r *Repository) ListPendingRefund(ctx context.Context) ([]OrderDTO, error) { var rows []orderRow - err := applyBuyerTenantOrderScope(r.adminQuery(ctx), ctx). + err := applyTenantOrderScope(r.adminQuery(ctx), ctx). Where("o.refund_status = ?", refundStatusPendingReview). Order("o.updated_at ASC, o.id ASC"). Limit(200). @@ -34,7 +34,7 @@ func (r *Repository) PendingRefundCount(ctx context.Context) (int64, error) { query := r.db.WithContext(ctx). Table("rental_orders AS o"). Where("refund_status = ?", refundStatusPendingReview) - query = applyBuyerTenantOrderScope(query, ctx) + query = applyTenantOrderScope(query, ctx) err := query.Count(&count).Error return count, err } diff --git a/backend/internal/modules/order/service.go b/backend/internal/modules/order/service.go index 577704eb..70cba0fc 100644 --- a/backend/internal/modules/order/service.go +++ b/backend/internal/modules/order/service.go @@ -229,7 +229,7 @@ func (s *Service) AdminClose(ctx context.Context, adminID uint64, orderID uint64 if orderID == 0 || req.Reason == "" { return ErrOrderCannotComplete } - if err := s.ensureAdminOrderCapability(ctx, orderID, tenantOrderCapabilityRefund); err != nil { + if err := s.ensureAdminOrderAccess(ctx, orderID); err != nil { return err } return s.repo.AdminClose(ctx, adminID, orderID, req, meta) @@ -255,7 +255,7 @@ func (s *Service) AdminSeal(ctx context.Context, adminID uint64, orderID uint64, if orderID == 0 || req.Reason == "" { return ErrOrderCannotComplete } - if err := s.ensureAdminOrderCapability(ctx, orderID, tenantOrderCapabilityRefund); err != nil { + if err := s.ensureAdminOrderAccess(ctx, orderID); err != nil { return err } return s.repo.AdminSeal(ctx, adminID, orderID, req, meta) @@ -268,7 +268,7 @@ func (s *Service) AdminResetHandoff(ctx context.Context, adminID uint64, orderID if orderID == 0 || req.Reason == "" { return ErrOrderCannotResetHandoff } - if err := s.ensureAdminOrderCapability(ctx, orderID, tenantOrderCapabilityHandoff); err != nil { + if err := s.ensureAdminOrderAccess(ctx, orderID); err != nil { return err } return s.repo.AdminResetHandoff(ctx, adminID, orderID, req, meta) @@ -281,7 +281,7 @@ func (s *Service) AdminPlatformHandoff(ctx context.Context, adminID uint64, orde if orderID == 0 || req.Content == "" || req.Reason == "" { return nil, ErrOrderCannotHandoff } - if err := s.ensureAdminOrderCapability(ctx, orderID, tenantOrderCapabilityHandoff); err != nil { + if err := s.ensureAdminOrderAccess(ctx, orderID); err != nil { return nil, err } return s.repo.AdminPlatformHandoff(ctx, adminID, orderID, req, meta) @@ -294,7 +294,7 @@ func (s *Service) AdminForceHandoff(ctx context.Context, adminID uint64, orderID if orderID == 0 || req.Reason == "" { return ErrOrderCannotForceHandoff } - if err := s.ensureAdminOrderCapability(ctx, orderID, tenantOrderCapabilityHandoff); err != nil { + if err := s.ensureAdminOrderAccess(ctx, orderID); err != nil { return err } return s.repo.AdminForceHandoff(ctx, adminID, orderID, req, meta) @@ -307,7 +307,7 @@ func (s *Service) AdminPlatformCheckoutConfirm(ctx context.Context, adminID uint if orderID == 0 || req.Reason == "" { return ErrCheckoutCannotConfirm } - if err := s.ensureAdminOrderCapability(ctx, orderID, tenantOrderCapabilityCheckout); err != nil { + if err := s.ensureAdminOrderAccess(ctx, orderID); err != nil { return err } return s.repo.AdminPlatformCheckoutConfirm(ctx, adminID, orderID, req, meta) @@ -320,7 +320,7 @@ func (s *Service) AdminPlatformCheckoutCounter(ctx context.Context, adminID uint if orderID == 0 || req.Reason == "" { return nil, ErrCheckoutCannotCounter } - if err := s.ensureAdminOrderCapability(ctx, orderID, tenantOrderCapabilityCheckout); err != nil { + if err := s.ensureAdminOrderAccess(ctx, orderID); err != nil { return nil, err } return s.repo.AdminPlatformCheckoutCounter(ctx, adminID, orderID, req, meta) @@ -333,7 +333,7 @@ func (s *Service) AdminPlatformCheckoutDispute(ctx context.Context, adminID uint if orderID == 0 || req.Reason == "" { return ErrCheckoutCannotCounter } - if err := s.ensureAdminOrderCapability(ctx, orderID, tenantOrderCapabilityCheckout); err != nil { + if err := s.ensureAdminOrderAccess(ctx, orderID); err != nil { return err } return s.repo.AdminPlatformCheckoutDispute(ctx, adminID, orderID, req, meta) @@ -346,7 +346,7 @@ func (s *Service) AdminMarkOfflineSettlement(ctx context.Context, adminID uint64 if orderID == 0 { return ErrOfflineSettlementCannotMark } - if err := s.ensureAdminOrderCapability(ctx, orderID, tenantOrderCapabilityHandoff); err != nil { + if err := s.ensureAdminOrderAccess(ctx, orderID); err != nil { return err } return s.repo.AdminMarkOfflineSettlement(ctx, adminID, orderID, req, meta) @@ -359,7 +359,7 @@ func (s *Service) AdminHoldDeposit(ctx context.Context, adminID uint64, orderID if orderID == 0 || req.Reason == "" { return ErrDepositCannotHold } - if err := s.ensureAdminOrderCapability(ctx, orderID, tenantOrderCapabilityRefund); err != nil { + if err := s.ensureAdminOrderAccess(ctx, orderID); err != nil { return err } return s.repo.AdminHoldDeposit(ctx, adminID, orderID, req, meta) @@ -372,7 +372,7 @@ func (s *Service) AdminReleaseDeposit(ctx context.Context, adminID uint64, order if orderID == 0 || req.Reason == "" { return ErrDepositCannotHold } - if err := s.ensureAdminOrderCapability(ctx, orderID, tenantOrderCapabilityRefund); err != nil { + if err := s.ensureAdminOrderAccess(ctx, orderID); err != nil { return err } return s.repo.AdminReleaseDeposit(ctx, adminID, orderID, req, meta) @@ -385,7 +385,7 @@ func (s *Service) AdminRefund(ctx context.Context, orderID uint64) (*RefundStatu if orderID == 0 { return nil, ErrOrderCannotComplete } - if err := s.ensureAdminOrderCapability(ctx, orderID, tenantOrderCapabilityRefund); err != nil { + if err := s.ensureAdminOrderAccess(ctx, orderID); err != nil { return nil, err } return s.repo.AdminRefund(ctx, orderID) @@ -398,7 +398,7 @@ func (s *Service) AdminRefundStatus(ctx context.Context, orderID uint64) (*Refun if orderID == 0 { return nil, ErrOrderCannotComplete } - if err := s.ensureAdminOrderCapability(ctx, orderID, tenantOrderCapabilityRefund); err != nil { + if err := s.ensureAdminOrderAccess(ctx, orderID); err != nil { return nil, err } return s.repo.AdminRefundStatus(ctx, orderID) @@ -411,7 +411,7 @@ func (s *Service) AdminApproveRefund(ctx context.Context, orderID uint64) error if orderID == 0 { return ErrOrderCannotComplete } - if err := s.ensureAdminOrderCapability(ctx, orderID, tenantOrderCapabilityRefund); err != nil { + if err := s.ensureAdminOrderAccess(ctx, orderID); err != nil { return err } return s.repo.AdminApproveRefund(ctx, orderID) @@ -424,7 +424,7 @@ func (s *Service) AdminRejectRefund(ctx context.Context, orderID uint64, action if orderID == 0 { return ErrOrderCannotComplete } - if err := s.ensureAdminOrderCapability(ctx, orderID, tenantOrderCapabilityRefund); err != nil { + if err := s.ensureAdminOrderAccess(ctx, orderID); err != nil { return err } return s.repo.AdminRejectRefund(ctx, orderID, action) @@ -460,13 +460,3 @@ func (s *Service) ensureAdminOrderAccess(ctx context.Context, orderID uint64) er } return s.repo.EnsureAdminOrderAccess(ctx, orderID) } - -func (s *Service) ensureAdminOrderCapability(ctx context.Context, orderID uint64, capability string) error { - if s.repo == nil { - return ErrDependencyUnavailable - } - if orderID == 0 { - return ErrOrderCannotComplete - } - return s.repo.EnsureAdminOrderCapability(ctx, orderID, capability) -} diff --git a/backend/internal/modules/order/tenant_offer_test.go b/backend/internal/modules/order/tenant_offer_test.go index a8d6664b..413382f9 100644 --- a/backend/internal/modules/order/tenant_offer_test.go +++ b/backend/internal/modules/order/tenant_offer_test.go @@ -270,23 +270,13 @@ func TestAdminOrdersAreScopedByCurrentTenant(t *testing.T) { if _, err := service.AdminRefundStatus(orderTenantContext(202), orders[1].ID); !errors.Is(err, gorm.ErrRecordNotFound) { t.Fatalf("cross-tenant admin action error = %v", err) } - if err := repo.EnsureAdminOrderCapability(orderTenantContext(101), orders[0].ID, tenantOrderCapabilityRefund); !errors.Is(err, gorm.ErrRecordNotFound) { - t.Fatalf("source tenant refund capability error = %v", err) + for _, tenantID := range []uint64{101, 202} { + if err := repo.EnsureAdminOrderAccess(orderTenantContext(tenantID), orders[0].ID); err != nil { + t.Fatalf("tenant %d order access: %v", tenantID, err) + } } - if err := repo.EnsureAdminOrderCapability(orderTenantContext(202), orders[0].ID, tenantOrderCapabilityRefund); err != nil { - t.Fatalf("buyer tenant refund capability: %v", err) - } - if err := repo.EnsureAdminOrderCapability(orderTenantContext(101), orders[0].ID, tenantOrderCapabilityHandoff); err != nil { - t.Fatalf("source tenant handoff capability: %v", err) - } - if err := repo.EnsureAdminOrderCapability(orderTenantContext(202), orders[0].ID, tenantOrderCapabilityHandoff); !errors.Is(err, gorm.ErrRecordNotFound) { - t.Fatalf("buyer tenant handoff capability error = %v", err) - } - if err := service.AdminClose(orderTenantContext(101), 9, orders[0].ID, AdminActionRequest{Reason: "source close"}, AuditMeta{}); !errors.Is(err, gorm.ErrRecordNotFound) { - t.Fatalf("source tenant close capability error = %v", err) - } - if err := service.AdminSeal(orderTenantContext(101), 9, orders[0].ID, AdminActionRequest{Reason: "source seal"}, AuditMeta{}); !errors.Is(err, gorm.ErrRecordNotFound) { - t.Fatalf("source tenant seal capability error = %v", err) + if err := repo.EnsureAdminOrderAccess(orderTenantContext(303), orders[0].ID); !errors.Is(err, gorm.ErrRecordNotFound) { + t.Fatalf("unrelated tenant order access error = %v", err) } sourceResult, err := repo.ListAdmin(orderTenantContext(101), AdminOrderQuery{Page: 1, PageSize: 20}) @@ -303,4 +293,22 @@ func TestAdminOrdersAreScopedByCurrentTenant(t *testing.T) { if roles[orders[0].ID] != "source" || roles[orders[1].ID] != "buyer" { t.Fatalf("A tenant order roles = %+v", roles) } + + if err := db.Model(&model.RentalOrder{}). + Where("id = ?", orders[0].ID). + Update("refund_status", refundStatusPendingReview).Error; err != nil { + t.Fatal(err) + } + for _, tenantID := range []uint64{101, 202} { + items, err := repo.ListPendingRefund(orderTenantContext(tenantID)) + if err != nil { + t.Fatalf("tenant %d pending refunds: %v", tenantID, err) + } + if len(items) != 1 || items[0].ID != orders[0].ID { + t.Fatalf("tenant %d pending refunds = %+v", tenantID, items) + } + } + if items, err := repo.ListPendingRefund(orderTenantContext(303)); err != nil || len(items) != 0 { + t.Fatalf("unrelated tenant pending refunds = %+v, err=%v", items, err) + } } diff --git a/backend/internal/modules/order/tenant_scope.go b/backend/internal/modules/order/tenant_scope.go deleted file mode 100644 index f0b54478..00000000 --- a/backend/internal/modules/order/tenant_scope.go +++ /dev/null @@ -1,75 +0,0 @@ -package order - -import ( - "context" - - "hfb_sys/backend/internal/logging" - "hfb_sys/backend/internal/tenancy" - - "gorm.io/gorm" -) - -const ( - tenantOrderCapabilityHandoff = "handoff" - tenantOrderCapabilityCheckout = "checkout" - tenantOrderCapabilityRefund = "refund" -) - -func (r *Repository) EnsureAdminOrderCapability(ctx context.Context, orderID uint64, capability string) error { - tenantID := tenancy.IDFromContext(ctx) - if tenantID == 0 { - return nil - } - var order struct { - BuyerTenantID uint64 - SourceTenantID uint64 - DistributionSiteID *uint64 - } - if err := r.db.WithContext(ctx). - Table("rental_orders"). - Select("buyer_tenant_id, source_tenant_id, distribution_site_id"). - Where("id = ?", orderID). - Scan(&order).Error; err != nil { - return err - } - if order.BuyerTenantID == 0 && order.SourceTenantID == 0 { - return gorm.ErrRecordNotFound - } - if order.DistributionSiteID != nil && *order.DistributionSiteID > 0 { - return gorm.ErrRecordNotFound - } - isBuyer := order.BuyerTenantID == tenantID - isSource := order.SourceTenantID == tenantID - if !isBuyer && !isSource { - return gorm.ErrRecordNotFound - } - if r.adminIsPlatformSuper(ctx) { - return nil - } - allowed := false - switch capability { - case tenantOrderCapabilityHandoff: - allowed = isSource - case tenantOrderCapabilityCheckout, tenantOrderCapabilityRefund: - allowed = isBuyer - default: - allowed = true - } - if !allowed { - return gorm.ErrRecordNotFound - } - return nil -} - -func (r *Repository) adminIsPlatformSuper(ctx context.Context) bool { - adminID := logging.AdminIDFromContext(ctx) - if adminID == 0 { - return false - } - var count int64 - err := r.db.WithContext(ctx).Table("admin_user_roles AS aur"). - Joins("JOIN roles AS r ON r.id = aur.role_id"). - Where("aur.admin_user_id = ? AND aur.tenant_id = 0 AND r.code = ?", adminID, "super_admin"). - Count(&count).Error - return err == nil && count > 0 -} diff --git a/backend/internal/modules/payment/dto.go b/backend/internal/modules/payment/dto.go index b094b5e1..bf954251 100644 --- a/backend/internal/modules/payment/dto.go +++ b/backend/internal/modules/payment/dto.go @@ -106,3 +106,28 @@ type AdminPaymentDTO struct { CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` } + +// AdminOrderPaymentDTO 只暴露订单详情处理退款所需的最小支付信息。 +type AdminOrderPaymentDTO struct { + ID uint64 `json:"id"` + TenantID uint64 `json:"tenant_id"` + PaymentNo string `json:"payment_no"` + OrderID uint64 `json:"order_id"` + OrderNo string `json:"order_no"` + UserID uint64 `json:"user_id"` + UserPhone string `json:"user_phone"` + Provider string `json:"provider"` + MerchantID string `json:"merchant_id"` + ThirdOrderID string `json:"third_order_id"` + ProviderOrderID string `json:"provider_order_id"` + PayWay string `json:"pay_way"` + AmountCent int64 `json:"amount_cent"` + BizType string `json:"biz_type"` + Status string `json:"status"` + ErrorCode string `json:"error_code"` + ErrorMessage string `json:"error_message"` + PaidAt *time.Time `json:"paid_at,omitempty"` + NotifiedAt *time.Time `json:"notified_at,omitempty"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` +} diff --git a/backend/internal/modules/payment/handler.go b/backend/internal/modules/payment/handler.go index 87270661..f69994ca 100644 --- a/backend/internal/modules/payment/handler.go +++ b/backend/internal/modules/payment/handler.go @@ -222,6 +222,19 @@ func (h *Handler) AdminList(c *gin.Context) { response.OK(c, result) } +func (h *Handler) AdminOrderPayments(c *gin.Context) { + orderID, ok := parseID(c) + if !ok { + return + } + items, err := h.service.OrderPayments(c.Request.Context(), orderID) + if err != nil { + writePaymentError(c, err) + return + } + response.OK(c, gin.H{"items": items}) +} + func (h *Handler) LeshuaNotify(c *gin.Context) { body, err := io.ReadAll(io.LimitReader(c.Request.Body, 1<<20)) if err != nil { diff --git a/backend/internal/modules/payment/order_payments.go b/backend/internal/modules/payment/order_payments.go new file mode 100644 index 00000000..18240d87 --- /dev/null +++ b/backend/internal/modules/payment/order_payments.go @@ -0,0 +1,93 @@ +package payment + +import ( + "context" + + "hfb_sys/backend/internal/model" + "hfb_sys/backend/internal/tenancy" + + "gorm.io/gorm" +) + +// OrderPayments 返回指定订单在原付款租户下的支付与退款流水。 +// 调用方必须先通过订单访问校验,避免把普通支付列表接口开放给客服。 +func (r *Repository) OrderPayments(ctx context.Context, orderID uint64) ([]AdminOrderPaymentDTO, error) { + if r == nil || r.db == nil { + return nil, ErrDependencyUnavailable + } + + var order struct { + BuyerTenantID uint64 + SourceTenantID uint64 + PaymentTenantID uint64 + DistributionSiteID *uint64 + } + if err := r.db.WithContext(ctx). + Model(&model.RentalOrder{}). + Select("buyer_tenant_id, source_tenant_id, payment_tenant_id, distribution_site_id"). + Where("id = ?", orderID). + Take(&order).Error; err != nil { + if err == gorm.ErrRecordNotFound { + return nil, ErrPaymentNotFound + } + return nil, err + } + + tenantID := tenancy.IDFromContext(ctx) + if tenantID > 0 && order.BuyerTenantID != tenantID && order.SourceTenantID != tenantID { + return nil, ErrPaymentNotFound + } + if order.DistributionSiteID != nil && *order.DistributionSiteID > 0 { + return nil, ErrPaymentNotFound + } + + paymentTenantID := order.PaymentTenantID + if paymentTenantID == 0 { + paymentTenantID = order.BuyerTenantID + } + query := r.db.WithContext(ctx). + Table("payment_orders AS p"). + Select("p.*, COALESCE(u.phone, '') AS user_phone"). + Joins("LEFT JOIN users AS u ON u.id = p.user_id"). + Where("p.order_id = ?", orderID) + if paymentTenantID > 0 { + query = query.Where("p.tenant_id = ?", paymentTenantID) + } + + var rows []adminPaymentRow + if err := query.Order("p.id DESC").Scan(&rows).Error; err != nil { + return nil, err + } + items := make([]AdminOrderPaymentDTO, 0, len(rows)) + for _, row := range rows { + items = append(items, row.toOrderDTO()) + } + return items, nil +} + +func (row adminPaymentRow) toOrderDTO() AdminOrderPaymentDTO { + errorCode, errorMessage := paymentErrorSummary(row.Status, row.RawResponse) + return AdminOrderPaymentDTO{ + ID: row.ID, + TenantID: row.TenantID, + PaymentNo: row.PaymentNo, + OrderID: row.OrderID, + OrderNo: row.OrderNo, + UserID: row.UserID, + UserPhone: row.UserPhone, + Provider: row.Provider, + MerchantID: row.MerchantID, + ThirdOrderID: row.ThirdOrderID, + ProviderOrderID: row.ProviderOrderID, + PayWay: row.PayWay, + AmountCent: row.AmountCent, + BizType: row.BizType, + Status: row.Status, + ErrorCode: errorCode, + ErrorMessage: errorMessage, + PaidAt: row.PaidAt, + NotifiedAt: row.NotifiedAt, + CreatedAt: row.CreatedAt, + UpdatedAt: row.UpdatedAt, + } +} diff --git a/backend/internal/modules/payment/refund.go b/backend/internal/modules/payment/refund.go index d05213b0..81d92e58 100644 --- a/backend/internal/modules/payment/refund.go +++ b/backend/internal/modules/payment/refund.go @@ -21,6 +21,7 @@ func (r *Repository) StartRefund(ctx context.Context, orderID uint64, refundAmou if err != nil { return nil, err } + ctx = scopedTenantContext(ctx, originalPayment.TenantID) runtimeConfig, err := r.runtimeConfigForPayment(ctx, &originalPayment) if err != nil { return nil, ErrPaymentUnavailable @@ -165,6 +166,11 @@ func (r *Repository) StartRefund(ctx context.Context, orderID uint64, refundAmou } func (r *Repository) QueryRefundStatus(ctx context.Context, orderID uint64) (*RefundDTO, error) { var payment model.PaymentOrder + tenantID, err := r.paymentTenantIDForOrder(ctx, orderID) + if err != nil { + return nil, err + } + ctx = scopedTenantContext(ctx, tenantID) query := r.db.WithContext(ctx).Where("order_id = ? AND biz_type IN ?", orderID, refundBizTypes) if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 { query = query.Where("tenant_id = ?", tenantID) @@ -201,9 +207,39 @@ func (r *Repository) SyncRefundStatusByPaymentID(ctx context.Context, paymentID return &dto, nil } func (r *Repository) findOriginalPayment(ctx context.Context, orderID uint64) (model.PaymentOrder, error) { + tenantID, err := r.paymentTenantIDForOrder(ctx, orderID) + if err != nil { + return model.PaymentOrder{}, err + } + return r.findOriginalPaymentInTenant(ctx, orderID, tenantID) +} + +func (r *Repository) paymentTenantIDForOrder(ctx context.Context, orderID uint64) (uint64, error) { + var order struct { + BuyerTenantID uint64 + PaymentTenantID uint64 + } + if err := r.db.WithContext(ctx). + Model(&model.RentalOrder{}). + Select("buyer_tenant_id, payment_tenant_id"). + Where("id = ?", orderID). + Take(&order).Error; err != nil { + if err == gorm.ErrRecordNotFound { + return 0, ErrPaymentNotFound + } + return 0, err + } + if order.PaymentTenantID > 0 { + return order.PaymentTenantID, nil + } + return order.BuyerTenantID, nil +} + +func (r *Repository) findOriginalPaymentInTenant(ctx context.Context, orderID uint64, tenantID uint64) (model.PaymentOrder, error) { var originalPayment model.PaymentOrder - query := r.db.WithContext(ctx).Where("order_id = ? AND status = 'paid' AND biz_type = 'order_pay'", orderID) - if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 { + query := r.db.WithContext(scopedTenantContext(ctx, tenantID)). + Where("order_id = ? AND status = 'paid' AND biz_type = 'order_pay'", orderID) + if tenantID > 0 { query = query.Where("tenant_id = ?", tenantID) } if err := query.Order("id DESC").First(&originalPayment).Error; err != nil { @@ -400,10 +436,16 @@ func refundQueryRequest(payment model.PaymentOrder, originalPayment model.Paymen } func (r *Repository) findOriginalPaymentForRefund(ctx context.Context, payment *model.PaymentOrder) (model.PaymentOrder, error) { + if payment != nil { + ctx = scopedTenantContext(ctx, payment.TenantID) + } if payment != nil && isMohongRefundBizType(payment.BizType) { return r.findOriginalMohongPayment(ctx, payment.OrderID) } - return r.findOriginalPayment(ctx, payment.OrderID) + if payment == nil { + return model.PaymentOrder{}, ErrPaymentNotFound + } + return r.findOriginalPaymentInTenant(ctx, payment.OrderID, payment.TenantID) } func (r *Repository) updateRefundedOrderStatus(ctx context.Context, orderID uint64, refundAmountCent int64, bizType string) error { diff --git a/backend/internal/modules/payment/service.go b/backend/internal/modules/payment/service.go index 5a7a704a..d37db4c9 100644 --- a/backend/internal/modules/payment/service.go +++ b/backend/internal/modules/payment/service.go @@ -141,3 +141,13 @@ func (s *Service) AdminList(ctx context.Context, query AdminPaymentQuery) (*Pagi } return s.repo.AdminList(ctx, query) } + +func (s *Service) OrderPayments(ctx context.Context, orderID uint64) ([]AdminOrderPaymentDTO, error) { + if s.repo == nil { + return nil, ErrDependencyUnavailable + } + if orderID == 0 { + return nil, ErrPaymentNotFound + } + return s.repo.OrderPayments(ctx, orderID) +} diff --git a/backend/internal/modules/payment/tenant_scope_test.go b/backend/internal/modules/payment/tenant_scope_test.go index 8e9174b8..8dd41658 100644 --- a/backend/internal/modules/payment/tenant_scope_test.go +++ b/backend/internal/modules/payment/tenant_scope_test.go @@ -117,3 +117,45 @@ func TestTenantOrderWithoutOwnConfigDoesNotUseOtherTenantDefault(t *testing.T) { t.Fatalf("missing tenant config error = %v", err) } } + +func TestRefundAndOrderPaymentsUsePaymentTenant(t *testing.T) { + db := database.NewTestDB() + order := model.RentalOrder{ + BuyerTenantID: 202, SourceTenantID: 101, PaymentTenantID: 202, + OrderNo: "RO-CROSS-SITE-REFUND", RenterID: 1, + RentAmountCent: 1000, DepositAmountCent: 500, Status: "renting", + } + if err := db.Create(&order).Error; err != nil { + t.Fatal(err) + } + payment := model.PaymentOrder{ + TenantID: 202, PaymentNo: "PAY-CROSS-SITE-REFUND", OrderID: order.ID, + OrderNo: order.OrderNo, UserID: order.RenterID, Provider: "mock", + ThirdOrderID: "PAY-CROSS-SITE-REFUND", PayWay: "ZFBZF", + AmountCent: 1500, BizType: "order_pay", Status: "paid", + } + if err := db.Create(&payment).Error; err != nil { + t.Fatal(err) + } + repo := NewRepository(db, nil, nil) + + original, err := repo.findOriginalPayment(paymentTenantContext(101), order.ID) + if err != nil { + t.Fatalf("find original payment from source tenant: %v", err) + } + if original.ID != payment.ID || original.TenantID != 202 { + t.Fatalf("original payment = %+v", original) + } + + items, err := repo.OrderPayments(paymentTenantContext(101), order.ID) + if err != nil { + t.Fatalf("load order payments from source tenant: %v", err) + } + if len(items) != 1 || items[0].ID != payment.ID || items[0].TenantID != 202 { + t.Fatalf("order payments = %+v", items) + } + + if _, err := repo.OrderPayments(paymentTenantContext(303), order.ID); !errors.Is(err, ErrPaymentNotFound) { + t.Fatalf("unrelated tenant payment access error = %v", err) + } +} diff --git a/backend/internal/router/router.go b/backend/internal/router/router.go index 64dee90e..92d5de86 100644 --- a/backend/internal/router/router.go +++ b/backend/internal/router/router.go @@ -910,6 +910,7 @@ func New(cfg config.Config, deps Dependencies, logger *zap.Logger) *gin.Engine { adminRoutes.POST("/points-mall/redemptions/:id/complete", requirePerm("points_mall:manage"), pointsMallHandler.CompleteRedemption) adminRoutes.GET("/orders", requirePerm("order:list"), orderHandler.AdminList) adminRoutes.GET("/listing-orders/:id/latest", requirePerm("order:view"), orderHandler.AdminLatestByListing) + adminRoutes.GET("/orders/:id/payments", requirePerm("order:view"), paymentHandler.AdminOrderPayments) adminRoutes.GET("/orders/:id", requirePerm("order:view"), orderHandler.AdminDetail) adminRoutes.GET("/orders/:id/handoff-records", requirePerm("order:view"), orderHandler.AdminHandoffRecords) adminRoutes.GET("/orders/:id/process-events", requirePerm("order:view"), orderHandler.AdminProcessEvents) diff --git a/backend/internal/router/router_test.go b/backend/internal/router/router_test.go index 39e9572a..47edea37 100644 --- a/backend/internal/router/router_test.go +++ b/backend/internal/router/router_test.go @@ -58,6 +58,7 @@ func TestExtractedAdminRoutesRemainRegisteredWithoutDuplicates(t *testing.T) { "PUT /api/admin/roles/:id/permissions", "PUT /api/admin/admin-users/:id/password", "POST /api/admin/announcements/:id/publish", + "GET /api/admin/orders/:id/payments", "GET /api/site/context", "GET /api/site/check-domain", "GET /api/distribution/sites/:id/listings", diff --git a/backend/migrations/000111_cs_cross_site_order_actions.sql b/backend/migrations/000111_cs_cross_site_order_actions.sql new file mode 100644 index 00000000..53e120c4 --- /dev/null +++ b/backend/migrations/000111_cs_cross_site_order_actions.sql @@ -0,0 +1,18 @@ +-- +goose Up + +-- 客服继续保留原有权限,并补齐共享订单的跨站处理权限。 +-- 订单访问仍限制为当前租户的买方/出货方订单,退款则按原支付租户执行。 +INSERT IGNORE INTO role_permissions (role_id, permission_id) +SELECT r.id, p.id +FROM roles r +JOIN permissions p ON p.code IN ('order:close', 'order:mark_abnormal') +WHERE r.code = 'cs'; + +-- +goose Down + +DELETE rp +FROM role_permissions rp +JOIN roles r ON r.id = rp.role_id +JOIN permissions p ON p.id = rp.permission_id +WHERE r.code = 'cs' + AND p.code IN ('order:close', 'order:mark_abnormal'); diff --git a/frontend/src/features/admin/api/adminPayments.ts b/frontend/src/features/admin/api/adminPayments.ts index f78ba91e..ef9607ec 100644 --- a/frontend/src/features/admin/api/adminPayments.ts +++ b/frontend/src/features/admin/api/adminPayments.ts @@ -59,3 +59,13 @@ export async function fetchAdminPayments(query: AdminPaymentQuery = {}) { page_size: Number(result?.page_size ?? query.page_size ?? 20), } } + +export async function fetchAdminOrderPayments(orderID: string | number, silent = false) { + const { data } = await apiClient.get>( + `/admin/orders/${orderID}/payments`, + { silent } + ) + return { + items: Array.isArray(data.data?.items) ? data.data.items : [], + } +} diff --git a/frontend/src/features/admin/views/AdminOrderDetailView.vue b/frontend/src/features/admin/views/AdminOrderDetailView.vue index 6e44ff1c..58ed1972 100644 --- a/frontend/src/features/admin/views/AdminOrderDetailView.vue +++ b/frontend/src/features/admin/views/AdminOrderDetailView.vue @@ -28,7 +28,7 @@ import { type RefundStatus, } from '@/features/orders' import { adminCreateOrderDispute } from '@/features/disputes' -import { fetchAdminPayments, type AdminPayment } from '@/features/admin/api/adminPayments' +import { fetchAdminOrderPayments, type AdminPayment } from '@/features/admin/api/adminPayments' import { fetchDisbursementOperators, type ManualEntryOption, @@ -52,6 +52,7 @@ import { } from '@/shared/utils/statusLabels' import { formatDateTime } from '@/shared/utils/time' import { formatGameName, formatListingNo } from '@/shared/utils/listingDisplay' +import { useAdminSessionStore } from '@/stores/adminSession' import AdminOrderMetrics, { type AdminOrderMetric } from '../components/AdminOrderMetrics.vue' import AdminOrderPaymentRecords from '../components/AdminOrderPaymentRecords.vue' import OfflineSettlementDialog from '../components/OfflineSettlementDialog.vue' @@ -68,6 +69,7 @@ import { const route = useRoute() const router = useRouter() +const adminSession = useAdminSessionStore() const loading = ref(false) const submitting = ref(false) const order = ref(null) @@ -183,21 +185,19 @@ const platformCheckoutDisputeAction = computed( const offlineSettlementAction = computed( () => order.value?.admin_actions?.platform_offline_settlement ) -const hasBuyerRole = computed( - () => !order.value?.site_role || ['buyer', 'both'].includes(order.value.site_role) -) -const hasSourceRole = computed( - () => !order.value?.site_role || ['source', 'both'].includes(order.value.site_role) -) +const isSourceOnlyOrder = computed(() => order.value?.site_role === 'source') +const canManageBuyerSide = computed(() => adminSession.hasPermission('order:close')) +const canMarkAbnormal = computed(() => adminSession.hasPermission('order:mark_abnormal')) const resetActionLabel = computed(() => { return resetAction.value?.label || '重置' }) -const canResetHandoff = computed(() => hasSourceRole.value && resetAction.value?.enabled === true) +const canResetHandoff = computed(() => canMarkAbnormal.value && resetAction.value?.enabled === true) const canPlatformHandoff = computed( - () => hasSourceRole.value && platformHandoffAction.value?.enabled === true + () => canMarkAbnormal.value && platformHandoffAction.value?.enabled === true ) const canForceHandoff = computed( - () => hasSourceRole.value && forceHandoffAction.value?.enabled === true + () => + adminSession.hasPermission('order:force_handoff') && forceHandoffAction.value?.enabled === true ) const forceHandoffNeedsContent = computed( () => @@ -205,19 +205,22 @@ const forceHandoffNeedsContent = computed( order.value?.handoff_status === 'owner_timeout' ) const canPlatformCheckoutConfirm = computed( - () => hasBuyerRole.value && platformCheckoutConfirmAction.value?.enabled === true + () => canMarkAbnormal.value && platformCheckoutConfirmAction.value?.enabled === true ) const canPlatformCheckoutCounter = computed( - () => hasBuyerRole.value && platformCheckoutCounterAction.value?.enabled === true + () => canMarkAbnormal.value && platformCheckoutCounterAction.value?.enabled === true ) const canPlatformCheckoutDispute = computed( - () => hasBuyerRole.value && platformCheckoutDisputeAction.value?.enabled === true + () => canMarkAbnormal.value && platformCheckoutDisputeAction.value?.enabled === true ) const canOfflineSettlement = computed( - () => hasSourceRole.value && offlineSettlementAction.value?.enabled === true + () => canMarkAbnormal.value && offlineSettlementAction.value?.enabled === true ) const canAdminCreateDispute = computed( - () => hasBuyerRole.value && canOperate.value && !order.value?.active_dispute + () => + adminSession.hasPermission('dispute:arbitrate') && + canOperate.value && + !order.value?.active_dispute ) const isPlatformManaged = computed( () => @@ -236,13 +239,16 @@ const depositHoldAmountCent = computed(() => Number(order.value?.deposit_hold_am const isDepositHeld = computed(() => depositHoldStatus.value === 'held') const canHoldDeposit = computed( () => - hasBuyerRole.value && + adminSession.hasPermission('order:deposit_hold') && canOperate.value && depositHoldStatus.value === 'none' && Number(order.value?.deposit_amount_cent || 0) > 0 ) const canReleaseDeposit = computed( - () => hasBuyerRole.value && isDepositHeld.value && depositHoldAmountCent.value > 0 + () => + adminSession.hasPermission('order:deposit_hold') && + isDepositHeld.value && + depositHoldAmountCent.value > 0 ) const depositHoldStatusLabel = computed(() => { switch (depositHoldStatus.value) { @@ -402,7 +408,7 @@ const hasOwnerRentBreakdown = computed(() => ownerCoinBasePriceCent.value !== nu const platformFeeBreakdown = computed(() => orderPlatformFeeBreakdown(order.value)) const fundSplitRows = computed(() => { if (!order.value) return [] - if (!hasBuyerRole.value && hasSourceRole.value) { + if (!canManageBuyerSide.value && isSourceOnlyOrder.value) { return [ { label: '本站货源结算金额', @@ -487,15 +493,16 @@ async function loadOrder() { loading.value = true try { order.value = await fetchAdminOrder(String(route.params.id)) - const [handoffs, events] = await Promise.all([ + const [handoffs, events, payments] = await Promise.all([ fetchAdminHandoffRecords(String(route.params.id)), fetchAdminOrderProcessEvents(String(route.params.id)), + fetchAdminOrderPayments(String(route.params.id), true).catch(() => ({ + items: [] as AdminPayment[], + })), ]) handoffRecords.value = handoffs processEvents.value = events - paymentRecords.value = hasBuyerRole.value - ? (await fetchAdminPayments({ order_id: String(route.params.id) })).items - : [] + paymentRecords.value = payments.items await loadRefundStatus() } finally { loading.value = false @@ -503,10 +510,6 @@ async function loadOrder() { } async function loadRefundStatus() { - if (!hasBuyerRole.value) { - refundStatus.value = null - return - } try { refundStatus.value = await adminRefundStatus(Number(route.params.id)) } catch { @@ -1086,17 +1089,21 @@ function formatRatioNumber(value: number) { 发起申诉 - 标记异常 - + 客服关闭 - + 封存订单 @@ -1124,7 +1131,7 @@ function formatRatioNumber(value: number) { - + -
+

退款概况

@@ -1462,7 +1469,7 @@ function formatRatioNumber(value: number) {
- +