for a small project I needed some net/gross price calculation. Due to customer's requirements, especially due to rounding issues, there are two different calculation methods:
Method A: Net to Gross
gross = net + taxes
...in other words...
gross = net * ( 1 + taxrate )
Method B: Gross to net
net = gross - taxes
...in other words ...
net = gross / ( 1 + taxrate )
Example
For example users enter net price first, see the calculated gross price and then adjust the gross price by rounding up or so. My aim was to find a simple and user friendly solution so that the details view just does the calculation without being too complex. And this is the result:
----
There are four relevant fields im my prices table.:
- netPrice
- grossPrice
- taxrate_id (Lookup)
- taxrate_rate (Auto-fill from taxrates table)
Method A
When user starts input in netPrice field, the details view switches to calculation method (A) and grossPrice field will be disabled. After user has finished input, the grossPrice is being calculated using Method (A) and enabled afterwards.
To indicate the calculation method, I'm using bootstrap's 'has-success' class which renders a nice green border around an input.
---
Method B
When user starts input in grossPrice field, the details view switches to calculation method (B) and netPrice field will be disabled. After user has finished input, the netPrice is being calculated using Method (B) and enabled afterwards.
As a result, users don't have to care. They can just enter the price in net field OR gross field. The other price will be calculated automatically, even if they change the tax rate:
All that is written in Javascript + JQuery in hooks\cm_prices-dv.js. Detecting input and changes can be done like this:
Code: Select all
$j('#netPrice').on('input', function () {
calcMethod('net2gross');
});
$j('#grossPrice').on('input', function () {
calcMethod('gross2net');
});
$j('#netPrice,#grossPrice').on('change', function () {
recalc();
});
Calculation method looks something like this:
Code: Select all
function recalc() {
// get rate from autofill field taxrate_rate
var rate = getRate();
var gross2net = (_calcMethod == 'gross2net');
if (gross2net) {
var g = gross(); // get gross from grossPrice field
var n = (g / (1 + rate)).toFixed(2); // calc net
net(n); // put result in netPrice field
} else {
var n = net(); // get net from netPrice field
var g = (n * (1 + rate)).toFixed(2); // calc gross
gross(g); // put result in grossPrice field
}
// enable input fields
// ...
}
Hope you like it and my idea and code gives someone a good starting point.
Regards,
Jan