feat: arithmetic calc price function
This commit is contained in:
parent
3f835bd2f0
commit
3e619e6856
1 changed files with 60 additions and 1 deletions
|
|
@ -1,4 +1,63 @@
|
|||
import { storeToRefs } from 'pinia';
|
||||
import { useConfigStore } from 'src/stores/config';
|
||||
|
||||
const configStore = useConfigStore();
|
||||
const { data: config } = storeToRefs(configStore);
|
||||
|
||||
export function precisionRound(number: number, precision = 2) {
|
||||
var factor = Math.pow(10, precision);
|
||||
const factor = Math.pow(10, precision);
|
||||
return Math.round(number * factor) / factor;
|
||||
}
|
||||
|
||||
export function calculatePrice(
|
||||
data: {
|
||||
price: number;
|
||||
vat?: number;
|
||||
discount?: number;
|
||||
amount?: number;
|
||||
calcVat?: boolean;
|
||||
vatIncluded?: boolean;
|
||||
output: 'vat' | 'total' | 'beforeVat';
|
||||
} = {
|
||||
price: 0,
|
||||
vat: 0.07,
|
||||
discount: 0,
|
||||
amount: 1,
|
||||
calcVat: false,
|
||||
vatIncluded: false,
|
||||
output: 'total',
|
||||
},
|
||||
) {
|
||||
const {
|
||||
price,
|
||||
vat = config.value?.vat || 0.07,
|
||||
discount = 0,
|
||||
amount = 1,
|
||||
calcVat = false,
|
||||
vatIncluded = false,
|
||||
output = 'total',
|
||||
} = data;
|
||||
|
||||
// Calculate VAT
|
||||
const calculatedVat = calcVat
|
||||
? precisionRound((price * amount - discount) * vat)
|
||||
: 0;
|
||||
|
||||
// Calculate total
|
||||
const total = precisionRound(
|
||||
price * amount -
|
||||
discount +
|
||||
precisionRound(
|
||||
calcVat ? price * (discount ? amount : 1) - discount * vat : 0,
|
||||
),
|
||||
);
|
||||
|
||||
// Calculate before VAT
|
||||
const beforeVat = vatIncluded ? precisionRound(price / (1 + vat)) : price;
|
||||
|
||||
// Return based on output selection
|
||||
if (output === 'vat') return calculatedVat;
|
||||
if (output === 'total') return total;
|
||||
if (output === 'beforeVat') return beforeVat;
|
||||
return 0;
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue