-
Notifications
You must be signed in to change notification settings - Fork 5
/
lib.js
236 lines (205 loc) · 6.13 KB
/
lib.js
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
const { isString, groupBy } = require("lodash");
const fs = require("fs");
const path = require("path");
const yaml = require("js-yaml");
const moment = require("moment");
const numeral = require("numeral");
const puppeteer = require("puppeteer");
const handlebars = require("handlebars");
let translation = {};
// Helper functions
const setLanguage = function(lang) {
if (lang !== "en") {
require(`numeral/locales/${lang}`);
}
numeral.locale(lang);
moment.locale(lang);
translation = require(`${__dirname}/locales/${lang}.json`);
};
const roundToPrecision = function(value, quantityPrecision) {
if (quantityPrecision == null) {
quantityPrecision = 0;
}
if (isNaN(value)) {
value = 0;
}
return parseFloat(value.toFixed(quantityPrecision));
};
const roundCurrency = (value) => roundToPrecision(value, 2);
const sum = (items) => items.reduce((r, a) => r + a, 0);
const calculateNet = (items) => sum(items.map((a) => a.net_value));
const calculateTotal = (items) => sum(items.map((a) => a.total_value));
const svgToDataURL = svgStr => {
const encoded = encodeURIComponent(svgStr)
.replace(/'/g, '%27')
.replace(/"/g, '%22')
const header = 'data:image/svg+xml,'
const dataUrl = header + encoded
return dataUrl
}
// Default language setting
setLanguage("de");
// Business logic transformation
const transformData = function(data) {
data = {
invoice: {},
receiver: {},
items: [],
intro_text: "",
outro_text: "",
...data,
};
if (data.invoice.language == null) {
data.invoice.language = "de";
}
setLanguage(data.invoice.language);
if (data.invoice.date == null) {
data.invoice.date = new Date();
}
if (data.invoice.template == null) {
data.invoice.template = "default";
}
if (data.invoice.location == null) {
data.invoice.location = data.sender.town;
}
if (data.invoice.currency == null) {
data.invoice.currency = "€";
}
if (data.invoice.quantityPrecision == null) {
data.invoice.quantityPrecision = 0;
}
data.items = data.items.map(function(item) {
item = {
quantity: 1,
tax_rate: 0,
...item,
};
if (item.title == null) {
throw new Error("An invoice item needs a title.");
}
if (item.price == null) {
throw new Error("An invoice item needs a price.");
}
if (isString(item.quantity)) {
item.quantity = new Function(
`return ${item.quantity.replace(/\#/g, "//")};`
)();
}
item.quantity = roundToPrecision(
item.quantity,
data.invoice.quantityPrecision
);
item.net_value = item.quantity * item.price;
item.tax_value = item.net_value * (item.tax_rate / 100);
item.total_value = item.net_value * (1 + item.tax_rate / 100);
item.net_value = roundCurrency(item.net_value);
item.tax_value = roundCurrency(item.tax_value);
item.total_value = roundCurrency(item.total_value);
return item;
});
data.totals = {
net: calculateNet(data.items),
total: calculateTotal(data.items),
tax: Object.entries(groupBy(data.items, "tax_rate"))
.map(([tax_rate, tax_group]) => ({
rate: tax_rate,
total: sum(tax_group.map((a) => a.tax_value)),
}))
.filter((tax) => tax.total !== 0),
};
return data;
};
exports.compile = async function compile(inFilename, outFilename) {
let data = yaml.load(fs.readFileSync(inFilename, "utf8"));
data = transformData(data);
let templateFolder = `${__dirname}/templates/${data.invoice.template}`;
if (
fs.existsSync(
path.join(path.dirname(inFilename), "templates", data.invoice.template)
)
) {
console.log(`Using custom template \`${data.invoice.template}\``);
templateFolder = path.join(
path.dirname(inFilename),
"templates",
data.invoice.template
);
}
data.stylesheet = fs.readFileSync(`${templateFolder}/style.css`, "utf8");
data.logo_url = svgToDataURL(
fs.readFileSync(`${templateFolder}/logo.svg`, "utf8")
);
// Prepare rendering
handlebars.registerHelper("plusOne", (value) => value + 1);
handlebars.registerHelper("number", (value) =>
numeral(value).format("0[.]0[0]")
);
handlebars.registerHelper(
"money",
(value) => `${numeral(value).format("0,0.00")} ${data.invoice.currency}`
);
handlebars.registerHelper("percent", (value) =>
numeral(value / 100).format("0 %")
);
handlebars.registerHelper("date", (value) => moment(value).format("LL"));
handlebars.registerHelper("lines", function(options) {
let contents = options.fn();
contents = contents.split(/<br\s*\/?>/);
contents = contents
.map((a) => a.trim())
.filter((a) => a != null && a !== "");
contents = contents.join("<br>");
return contents;
});
handlebars.registerHelper(
"pre",
(contents) =>
new handlebars.SafeString(
contents
.split(/\n/)
.map((a) => handlebars.Utils.escapeExpression(a))
.join("<br>")
)
);
handlebars.registerHelper("t", (phrase) =>
translation[phrase] != null ? translation[phrase] : phrase
);
// Rendering
const mainTemplate = handlebars.compile(
fs.readFileSync(`${templateFolder}/main.html`, "utf8")
);
const headerTemplate = handlebars.compile(
fs.readFileSync(`${templateFolder}/header.html`, "utf8")
);
const footerTemplate = handlebars.compile(
fs.readFileSync(`${templateFolder}/footer.html`, "utf8")
);
const browser = await puppeteer.launch({
args: [
// Required for Docker version of Puppeteer
"--no-sandbox",
"--disable-setuid-sandbox",
// This will write shared memory files into /tmp instead of /dev/shm,
// because Docker’s default for /dev/shm is 64MB
"--disable-dev-shm-usage",
],
});
const page = await browser.newPage();
await page.setContent(mainTemplate(data), {
waitUntil: "networkidle2",
});
await page.pdf({
path: outFilename,
format: "A4",
headerTemplate: headerTemplate(data),
footerTemplate: footerTemplate(data),
displayHeaderFooter: true,
printBackground: true,
margin: {
top: "45mm",
bottom: "45mm",
},
});
await browser.close();
console.log(`Created ${outFilename}`);
};