@medusajs/core-flows
Version:
Set of workflow definitions for Medusa
54 lines • 3 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.refundCapturedPaymentsWorkflow = exports.refundCapturedPaymentsWorkflowId = void 0;
const utils_1 = require("@medusajs/framework/utils");
const workflows_sdk_1 = require("@medusajs/framework/workflows-sdk");
const common_1 = require("../../../common");
const refund_payments_1 = require("../../../payment/workflows/refund-payments");
exports.refundCapturedPaymentsWorkflowId = "refund-captured-payments-workflow";
/**
* This workflow refunds a payment.
*/
exports.refundCapturedPaymentsWorkflow = (0, workflows_sdk_1.createWorkflow)(exports.refundCapturedPaymentsWorkflowId, (input) => {
const orderQuery = (0, common_1.useQueryGraphStep)({
entity: "orders",
fields: [
"id",
"status",
"summary",
"payment_collections.payments.id",
"payment_collections.payments.amount",
"payment_collections.payments.refunds.id",
"payment_collections.payments.refunds.amount",
"payment_collections.payments.captures.id",
"payment_collections.payments.captures.amount",
],
filters: { id: input.order_id },
options: { throwIfKeyNotFound: true },
}).config({ name: "get-order" });
const order = (0, workflows_sdk_1.transform)({ orderQuery }, ({ orderQuery }) => orderQuery.data[0]);
const refundPaymentsData = (0, workflows_sdk_1.transform)({ order, input }, ({ order, input }) => {
const payments = (0, utils_1.deepFlatMap)(order, "payment_collections.payments", ({ payments }) => payments);
const capturedPayments = payments.filter((payment) => payment.captures?.length);
return capturedPayments
.map((payment) => {
const capturedAmount = (payment.captures || []).reduce((acc, capture) => utils_1.MathBN.sum(acc, capture.amount), utils_1.MathBN.convert(0));
const refundedAmount = (payment.refunds || []).reduce((acc, refund) => utils_1.MathBN.sum(acc, refund.amount), utils_1.MathBN.convert(0));
const amountToRefund = utils_1.MathBN.sub(capturedAmount, refundedAmount);
return {
payment_id: payment.id,
created_by: input.created_by,
amount: amountToRefund,
note: input.note,
};
})
.filter((payment) => utils_1.MathBN.gt(payment.amount, 0));
});
const totalCaptured = (0, workflows_sdk_1.transform)({ refundPaymentsData }, ({ refundPaymentsData }) => refundPaymentsData.reduce((acc, refundPayment) => utils_1.MathBN.sum(acc, refundPayment.amount), utils_1.MathBN.convert(0)));
(0, workflows_sdk_1.when)({ totalCaptured }, ({ totalCaptured }) => {
return !!utils_1.MathBN.gt(totalCaptured, 0);
}).then(() => {
refund_payments_1.refundPaymentsWorkflow.runAsStep({ input: refundPaymentsData });
});
});
//# sourceMappingURL=refund-captured-payments.js.map
;