chore(util): avoid promotion value precision limit (#13145)

This commit is contained in:
Carlos R. L. Rodrigues
2025-08-06 15:49:10 -03:00
committed by GitHub
parent b1cba9fdeb
commit a52708769d
3 changed files with 15 additions and 12 deletions
+5
View File
@@ -0,0 +1,5 @@
---
"@medusajs/utils": patch
---
chore(utils): avoid limit precision for promotion value
+4
View File
@@ -3,6 +3,10 @@ import { BigNumber as BigNumberJS } from "bignumber.js"
import { isDefined } from "../common" import { isDefined } from "../common"
import { BigNumber } from "./big-number" import { BigNumber } from "./big-number"
export const MEDUSA_EPSILON = new BigNumber(
process.env.MEDUSA_EPSILON || "0.0001"
)
type BNInput = BigNumberInput | BigNumber type BNInput = BigNumberInput | BigNumber
export class MathBN { export class MathBN {
static convert(num: BNInput, decimalPlaces?: number): BigNumberJS { static convert(num: BNInput, decimalPlaces?: number): BigNumberJS {
@@ -3,13 +3,10 @@ import {
ApplicationMethodAllocation, ApplicationMethodAllocation,
ApplicationMethodType, ApplicationMethodType,
} from "../../promotion" } from "../../promotion"
import { MathBN } from "../math" import { MathBN, MEDUSA_EPSILON } from "../math"
function getPromotionValueForPercentage(promotion, lineItemAmount) { function getPromotionValueForPercentage(promotion, lineItemAmount) {
return MathBN.convert( return MathBN.mult(MathBN.div(promotion.value, 100), lineItemAmount)
MathBN.mult(MathBN.div(promotion.value, 100), lineItemAmount),
2
)
} }
function getPromotionValueForFixed(promotion, lineItemAmount, lineItemsAmount) { function getPromotionValueForFixed(promotion, lineItemAmount, lineItemsAmount) {
@@ -28,10 +25,7 @@ function getPromotionValueForFixed(promotion, lineItemAmount, lineItemsAmount) {
promotionValueForItem promotionValueForItem
) )
return MathBN.convert( return MathBN.mult(promotionValueForItem, MathBN.div(percentage, 100))
MathBN.mult(promotionValueForItem, MathBN.div(percentage, 100)),
2
)
} }
return promotion.value return promotion.value
} }
@@ -104,8 +98,8 @@ export function calculateAdjustmentAmountFromPromotion(
) )
const applicableAmount = MathBN.sub(lineItemAmount, promotion.applied_value) const applicableAmount = MathBN.sub(lineItemAmount, promotion.applied_value)
if (MathBN.lte(applicableAmount, 0)) { if (MathBN.lte(applicableAmount, MEDUSA_EPSILON)) {
return applicableAmount return MathBN.convert(0)
} }
const promotionValue = getPromotionValue( const promotionValue = getPromotionValue(
@@ -153,7 +147,7 @@ export function calculateAdjustmentAmountFromPromotion(
maximumPromotionAmount maximumPromotionAmount
) )
if (MathBN.lte(applicableAmount, 0)) { if (MathBN.lte(applicableAmount, MEDUSA_EPSILON)) {
return MathBN.convert(0) return MathBN.convert(0)
} }