forked from RequestNetwork/requestNetwork
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.ts
More file actions
70 lines (62 loc) · 2.38 KB
/
utils.ts
File metadata and controls
70 lines (62 loc) · 2.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import { BigNumber, FixedNumber } from 'ethers';
import { Invoice, InvoiceItem } from './types';
export const getInvoiceTotal = (invoice: Invoice): BigNumber => {
return invoice.invoiceItems.reduce(
(acc, item) => acc.add(getInvoiceLineTotal(item)),
BigNumber.from(0),
);
};
export const getInvoiceLineTotal = (item: InvoiceItem): BigNumber => {
// Support for rnf_version < 0.0.3
const tax = item.taxPercent
? { type: 'percentage', amount: String(item.taxPercent) }
: item.tax || { type: 'percentage', amount: '0' };
const taxPercent = tax.amount && tax.type === 'percentage' ? Number(tax.amount) + 100 : 100;
const taxFixed =
tax.amount && tax.type === 'fixed' ? BigNumber.from(tax.amount) : BigNumber.from(0);
const discount = item.discount ? BigNumber.from(item.discount) : BigNumber.from(0);
return BigNumber.from(
FixedNumber.from(item.unitPrice)
// accounts for floating quantities
.mulUnsafe(FixedNumber.fromString(item.quantity.toString()))
.subUnsafe(FixedNumber.from(discount))
// accounts for floating taxes
.mulUnsafe(FixedNumber.fromString(taxPercent.toString()))
// Removes the percentage multiplier
.divUnsafe(FixedNumber.from(100))
.addUnsafe(FixedNumber.from(taxFixed))
.round(0)
.toString()
// Removes the .0
.split('.')[0],
);
};
export const getInvoiceTotalWithoutTax = (invoice: Invoice): BigNumber => {
return invoice.invoiceItems.reduce(
(acc, item) => acc.add(getInvoiceLineTotalWithoutTax(item)),
BigNumber.from(0),
);
};
export const getInvoiceLineTotalWithoutTax = (item: InvoiceItem): BigNumber => {
const discount = item.discount ? BigNumber.from(item.discount) : BigNumber.from(0);
return BigNumber.from(
FixedNumber.from(item.unitPrice)
// accounts for floating quantities
.mulUnsafe(FixedNumber.fromString(item.quantity.toString()))
.subUnsafe(FixedNumber.from(discount))
.round(0)
.toString()
.split('.')[0],
);
};
export const getInvoiceTaxTotal = (invoice: Invoice): BigNumber => {
const invoiceTotalWithoutTax = invoice.invoiceItems.reduce(
(acc, item) => acc.add(getInvoiceLineTotalWithoutTax(item)),
BigNumber.from(0),
);
const invoiceTotal = invoice.invoiceItems.reduce(
(acc, item) => acc.add(getInvoiceLineTotal(item)),
BigNumber.from(0),
);
return invoiceTotal.sub(invoiceTotalWithoutTax);
};