feat: Totals calculation (#6980)

This commit is contained in:
Carlos R. L. Rodrigues
2024-04-07 16:50:40 +02:00
committed by GitHub
parent 7302d078a9
commit b6879f017a
48 changed files with 1674 additions and 571 deletions
+17 -14
View File
@@ -27,9 +27,11 @@ import {
UpsertPaymentCollectionDTO,
} from "@medusajs/types"
import {
BigNumber,
InjectManager,
InjectTransactionManager,
isString,
MathBN,
MedusaContext,
MedusaError,
ModulesSdkUtils,
@@ -43,7 +45,6 @@ import {
PaymentSession,
Refund,
} from "@models"
import BigNumber from "bignumber.js"
import { entityNameToLinkableKeysMap, joinerConfig } from "../joiner-config"
import PaymentProviderService from "./payment-provider"
@@ -532,15 +533,14 @@ export default class PaymentModuleService<
}
const capturedAmount = payment.captures.reduce((captureAmount, next) => {
const amountAsBigNumber = new BigNumber(next.raw_amount.value)
return captureAmount.plus(amountAsBigNumber)
}, BigNumber(0))
return MathBN.add(captureAmount, next.raw_amount)
}, MathBN.convert(0))
const authorizedAmount = BigNumber(payment.raw_amount.value)
const newCaptureAmount = BigNumber(data.amount)
const remainingToCapture = authorizedAmount.minus(capturedAmount)
const authorizedAmount = new BigNumber(payment.raw_amount)
const newCaptureAmount = new BigNumber(data.amount)
const remainingToCapture = MathBN.sub(authorizedAmount, capturedAmount)
if (newCaptureAmount.gt(remainingToCapture)) {
if (MathBN.gt(newCaptureAmount, remainingToCapture)) {
throw new MedusaError(
MedusaError.Types.INVALID_DATA,
`You cannot capture more than the authorized amount substracted by what is already captured.`
@@ -567,7 +567,10 @@ export default class PaymentModuleService<
)
// When the entire authorized amount has been captured, we mark it fully capture by setting the captured_at field
if (capturedAmount.plus(newCaptureAmount).eq(authorizedAmount)) {
const totalCaptured = MathBN.convert(
MathBN.add(capturedAmount, newCaptureAmount)
)
if (MathBN.gte(totalCaptured, authorizedAmount)) {
await this.paymentService_.update(
{ id: payment.id, captured_at: new Date() },
sharedContext
@@ -600,12 +603,12 @@ export default class PaymentModuleService<
}
const capturedAmount = payment.captures.reduce((captureAmount, next) => {
const amountAsBigNumber = new BigNumber(next.raw_amount.value)
return captureAmount.plus(amountAsBigNumber)
}, BigNumber(0))
const refundAmount = BigNumber(data.amount)
const amountAsBigNumber = new BigNumber(next.raw_amount)
return MathBN.add(captureAmount, amountAsBigNumber)
}, MathBN.convert(0))
const refundAmount = new BigNumber(data.amount)
if (capturedAmount.lt(refundAmount)) {
if (MathBN.lt(capturedAmount, refundAmount)) {
throw new MedusaError(
MedusaError.Types.INVALID_DATA,
`You cannot refund more than what is captured on the payment.`