From c01106c5fb22f70e0b226aebfa6aeb134a31a4e6 Mon Sep 17 00:00:00 2001 From: Michael Bromley Date: Tue, 25 May 2021 16:17:07 +0200 Subject: [PATCH] fix(core): Publish PaymentStateTransitionEvent when settlePayment fails Fixes #886 --- .../src/service/services/payment.service.ts | 38 +++++++++---------- 1 file changed, 17 insertions(+), 21 deletions(-) diff --git a/packages/core/src/service/services/payment.service.ts b/packages/core/src/service/services/payment.service.ts index e250bac21d..003eb86858 100644 --- a/packages/core/src/service/services/payment.service.ts +++ b/packages/core/src/service/services/payment.service.ts @@ -133,33 +133,28 @@ export class PaymentService { payment, paymentMethod.handler.args, ); + const fromState = payment.state; + let toState: PaymentState; + payment.metadata = this.mergePaymentMetadata(payment.metadata, settlePaymentResult.metadata); if (settlePaymentResult.success) { - const fromState = payment.state; - const toState = 'Settled'; - try { - await this.paymentStateMachine.transition(ctx, payment.order, payment, toState); - } catch (e) { - const transitionError = ctx.translate(e.message, { fromState, toState }); - return new PaymentStateTransitionError(transitionError, fromState, toState); - } - payment.metadata = this.mergePaymentMetadata(payment.metadata, settlePaymentResult.metadata); - await this.connection.getRepository(ctx, Payment).save(payment, { reload: false }); - this.eventBus.publish( - new PaymentStateTransitionEvent(fromState, toState, ctx, payment, payment.order), - ); + toState = 'Settled'; } else { + toState = settlePaymentResult.state || 'Error'; payment.errorMessage = settlePaymentResult.errorMessage; - payment.metadata = this.mergePaymentMetadata(payment.metadata, settlePaymentResult.metadata); - await this.paymentStateMachine.transition( - ctx, - payment.order, - payment, - settlePaymentResult.state || 'Error', - ); - await this.connection.getRepository(ctx, Payment).save(payment, { reload: false }); } + try { + await this.paymentStateMachine.transition(ctx, payment.order, payment, toState); + } catch (e) { + const transitionError = ctx.translate(e.message, { fromState, toState }); + return new PaymentStateTransitionError(transitionError, fromState, toState); + } + await this.connection.getRepository(ctx, Payment).save(payment, { reload: false }); + this.eventBus.publish( + new PaymentStateTransitionEvent(fromState, toState, ctx, payment, payment.order), + ); return payment; } + /** * Creates a Payment from the manual payment mutation in the Admin API */ @@ -202,6 +197,7 @@ export class PaymentService { const nonFailedRefunds = payment.refunds?.filter(refund => refund.state !== 'Failed') ?? []; return summate(nonFailedRefunds, 'total'); } + const existingNonFailedRefunds = orderWithRefunds.payments ?.reduce((refunds, p) => [...refunds, ...p.refunds], [] as Refund[])