commerce_funds-8.x-1.7/js/calculate_fees.js
js/calculate_fees.js
/**
* @file
* Real-time fees calculations.
*/
((Drupal) => {
/**
* Behaviors to calculate fees on transactions.
*
* @type {Drupal~behavior}
*
* @prop {Drupal~behaviorAttach} attach
* Attaches fees calculation behavior for transactions.
*/
Drupal.behaviors.calculate_fees = {
attach(context) {
once('calculateFees', 'body', context).forEach(() => {
const description = drupalSettings.funds.fees;
const fees = description.match(
/.+: (\d+\.?(\d+)?)(%| .+)( \(min\. (\d+) .+\))?./,
);
if (!fees) {
return 0;
}
const rate = parseFloat(fees[1]);
let fixed = fees[5] !== undefined ? parseFloat(fees[5]) : false;
// No rates, only fixed fees.
if (fees[3] !== '%') {
fixed = 'rate';
}
const fundsAmountElements = document.querySelectorAll('.funds-amount');
fundsAmountElements.forEach((element) => {
const descriptionField = element.nextElementSibling;
if (
!descriptionField ||
!descriptionField.classList.contains('description')
) {
return 0;
}
const displayFees = () => {
// Calculate total.
const inputValue = parseFloat(element.value);
const totalRate = (inputValue + (inputValue * rate) / 100).toFixed(
2,
);
let total = totalRate;
if (fixed && fixed !== 'rate') {
const totalFixed = (inputValue + fixed).toFixed(2);
if (totalFixed > totalRate) {
total = totalFixed;
}
} else if (fixed && fixed === 'rate') {
total = (inputValue + rate).toFixed(2);
}
descriptionField.innerHTML = `${description}<br>Total paid: ${
Number.isNaN(total) ? 0 : total
}`;
};
element.addEventListener('input', () => {
displayFees();
});
});
});
},
};
})(Drupal);
