-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathinvoice.js
More file actions
340 lines (310 loc) · 12.7 KB
/
Copy pathinvoice.js
File metadata and controls
340 lines (310 loc) · 12.7 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
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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
/* invoice.js — data-driven PDF generation.
*
* IMPORTANT: The rendering below is a line-for-line port of the ORIGINAL
* generate() function. Every jsPDF coordinate, font call, rounding step and
* tax formula is preserved EXACTLY so that, for the same inputs, the produced
* PDF is byte-identical to the original app. The only change is the source of
* the values: a plain `data` object instead of live DOM form reads. This lets
* live-print and history-replay share ONE rendering path.
*
* Depends on: jsPDF 1.5.3 (global `jsPDF`) and `drawTemplate` (from
* template-draw.js — the vector template that replaced the background JPEG).
*
* data shape:
* {
* invoiceNumber: string|number,
* invoiceDate: "YYYY-MM-DD", // value of an <input type="date">
* transport: string,
* vehicle: string,
* consignee: string, // multi-line
* items: [ { name, gsm, hsn, size, quantity, bundles, rate }, ... ],
* carriageOutward: number|string,
* otherCharges: number|string,
* igst: bool, sgst: bool, cgst: bool,
* lessAdvance: number|string
* }
*/
// Coerce a possibly-empty/string value to a number (empty -> 0), mirroring the
// original's reliance on value="0" defaults + numeric coercion.
function _num(v) {
var n = parseFloat(v);
return isNaN(n) ? 0 : n;
}
/* computeTotals(data) -> summary object of NUMBERS (for saving metadata + the
* "CHECK AMOUNT" popup). Mirrors the original arithmetic exactly, including the
* round-to-integer step on the grand total. */
function computeTotals(data) {
var items = data.items || [];
var amtfinal = 0;
var totquant = 0;
for (var i = 0; i < items.length; i++) {
var zz = _num(items[i].quantity);
var yy = _num(items[i].rate);
amtfinal = amtfinal + zz * yy;
totquant = totquant + zz * 1;
}
var itemCost = amtfinal;
var xcout = _num(data.carriageOutward);
var xother = _num(data.otherCharges);
amtfinal = amtfinal + xcout + xother;
var xigst = data.igst ? parseFloat(amtfinal * 0.18) : parseFloat(0);
var xcgst = data.cgst ? parseFloat(amtfinal * 0.09) : parseFloat(0);
var xsgst = data.sgst ? parseFloat(amtfinal * 0.09) : parseFloat(0);
var totTax = parseFloat(xigst + xcgst + xsgst);
var extraCost = xcout + xother;
// Original: toFixed(0) then re-parse to toFixed(2). Keep the integer rounding.
var xroundtot = parseFloat(parseFloat(amtfinal + xcgst + xsgst + xigst).toFixed(0));
var xadv = _num(data.lessAdvance);
var gross = parseFloat((xroundtot - xadv));
return {
itemCost: itemCost,
totalQuantity: totquant,
carriageOutward: xcout,
otherCharges: xother,
igst: xigst,
cgst: xcgst,
sgst: xsgst,
tax: totTax,
extraCost: extraCost,
roundedTotal: xroundtot,
lessAdvance: xadv,
gross: gross
};
}
/* renderGstSummary(doc, ctx) — draws the HSN-wise GST breakdown table in the
* empty band on the lower-left of the template (x≈10–95.5mm, y≈204.5mm down),
* to the LEFT of the TOTAL QUANTITY column.
*
* WHY IN CODE (not the image): this table is DYNAMIC — its rows and amounts
* depend on each invoice's HSN codes, taxable values and applied taxes — so it
* cannot be baked into the static background image. It is rendered per invoice.
*
* RECONCILIATION: the original app taxes (itemcost + carriage + other). Here we
* group items' taxable value by HSN and add a single FREIGHT row for
* carriage+other, so the sum of all rows' taxable == that same base. The TOTAL
* row therefore shows CGST / SGST / IGST amounts identical to the boxes already
* printed on the right side of the invoice.
*
* Only renders when at least one GST is applied AND there is at least one item;
* otherwise it draws nothing (so non-GST invoices are unchanged).
*/
function renderGstSummary(doc, ctx) {
var items = ctx.items || [];
var igstOn = ctx.igst === true;
var cgstOn = ctx.cgst === true;
var sgstOn = ctx.sgst === true;
if (!(igstOn || cgstOn || sgstOn) || items.length === 0) return;
// ---- Group item taxable value by HSN (first-seen order) ----
var order = [];
var groups = {};
for (var i = 0; i < items.length; i++) {
var hsnRaw = items[i].hsn == null ? "" : String(items[i].hsn).trim();
var key = hsnRaw === "" ? "—" : hsnRaw; // em-dash when no HSN
var taxable = _num(items[i].quantity) * _num(items[i].rate);
if (!Object.prototype.hasOwnProperty.call(groups, key)) {
groups[key] = 0;
order.push(key);
}
groups[key] += taxable;
}
var rows = [];
for (var k = 0; k < order.length; k++) {
rows.push({ label: order[k], taxable: groups[order[k]] });
}
// Carriage + other charges share the same tax base in the original app.
var freight = _num(ctx.carriageOutward) + _num(ctx.otherCharges);
if (freight > 0) rows.push({ label: "FREIGHT", taxable: freight });
var cRate = cgstOn ? 0.09 : 0;
var sRate = sgstOn ? 0.09 : 0;
var iRate = igstOn ? 0.18 : 0;
// ---- Column geometry (mm) ----
var x0 = 10, x1 = 95.5;
var cols = [
{ key: "hsn", x: 10, w: 14, align: "center", head: "HSN" },
{ key: "taxable", x: 24, w: 18, align: "right", head: "TAXABLE" },
{ key: "cgst", x: 42, w: 11.5, align: "right", head: "CGST" },
{ key: "sgst", x: 53.5, w: 11.5, align: "right", head: "SGST" },
{ key: "igst", x: 65, w: 11.5, align: "right", head: "IGST" },
{ key: "taxamt", x: 76.5, w: 19, align: "right", head: "TAX AMT" }
];
// ---- Row/height sizing to fit the band ----
var tableTop = 204.5;
var bottomMax = 254; // stay above the band's bottom border (~255.4mm)
var titleH = 5;
var nRows = 1 /*header*/ + rows.length + 1 /*total*/;
var rowH = Math.min(5, (bottomMax - tableTop - titleH) / nRows);
if (rowH < 3.4) rowH = 3.4;
var fontSize = rowH >= 4.6 ? 6.5 : (rowH >= 4 ? 6 : 5.5);
var gridTop = tableTop + titleH;
var tableBottom = gridTop + nRows * rowH;
// ---- Clear the WHOLE empty band (wipes the template's stray column
// dividers both under the title and below the table). We stay inside
// the band's outer borders: top border ≈203.5mm, bottom ≈255.4mm,
// left border ≈9.1mm, and the TOTAL QUANTITY separator ≈96.5mm. ----
doc.setFillColor(255, 255, 255);
doc.rect(x0, 204, x1 - x0, 255.2 - 204, "F");
// ---- Frame + inner grid ----
doc.setDrawColor(0, 0, 0);
doc.setLineWidth(0.3);
doc.rect(x0, tableTop, x1 - x0, titleH, "S"); // title band
doc.rect(x0, gridTop, x1 - x0, tableBottom - gridTop, "S"); // grid frame
doc.setLineWidth(0.2);
for (var c = 1; c < cols.length; c++) { // column separators
doc.line(cols[c].x, gridTop, cols[c].x, tableBottom);
}
for (var r = 1; r < nRows; r++) { // row separators
var ry = gridTop + r * rowH;
doc.line(x0, ry, x1, ry);
}
function put(col, text, rowTop, bold) {
doc.setFontType(bold ? "bold" : "normal");
var ty = rowTop + rowH * 0.68;
if (col.align === "right") {
doc.text(String(text), col.x + col.w - 1.5, ty, { align: "right" });
} else {
doc.text(String(text), col.x + col.w / 2, ty, { align: "center" });
}
}
// ---- Title ----
doc.setFontSize(7.5);
doc.setFontType("bold");
doc.text("GST SUMMARY (HSN-WISE)", (x0 + x1) / 2, tableTop + titleH * 0.68, {
align: "center"
});
// ---- Header ----
doc.setFontSize(fontSize);
for (var h = 0; h < cols.length; h++) {
doc.setFontType("bold");
doc.text(cols[h].head, cols[h].x + cols[h].w / 2, gridTop + rowH * 0.68, {
align: "center"
});
}
// ---- Data rows ----
var tBase = 0;
for (var ri = 0; ri < rows.length; ri++) {
var rowTop = gridTop + (ri + 1) * rowH;
var base = rows[ri].taxable;
tBase += base;
var cg = base * cRate, sg = base * sRate, ig = base * iRate;
put(cols[0], rows[ri].label, rowTop, false);
put(cols[1], base.toFixed(2), rowTop, false);
put(cols[2], cg.toFixed(2), rowTop, false);
put(cols[3], sg.toFixed(2), rowTop, false);
put(cols[4], ig.toFixed(2), rowTop, false);
put(cols[5], (cg + sg + ig).toFixed(2), rowTop, false);
}
// ---- Total row (base*rate, so it matches the right-side tax boxes exactly) ----
var totalTop = gridTop + (rows.length + 1) * rowH;
var TCg = tBase * cRate, TSg = tBase * sRate, TIg = tBase * iRate;
put(cols[0], "TOTAL", totalTop, true);
put(cols[1], tBase.toFixed(2), totalTop, true);
put(cols[2], TCg.toFixed(2), totalTop, true);
put(cols[3], TSg.toFixed(2), totalTop, true);
put(cols[4], TIg.toFixed(2), totalTop, true);
put(cols[5], (TCg + TSg + TIg).toFixed(2), totalTop, true);
// restore defaults the surrounding code expects
doc.setFontSize(10);
doc.setFontType("normal");
}
/* generateInvoice(data, doprint)
* doprint === true -> save the PDF file (INVOICE_<number>.pdf)
* doprint !== true -> show the CHECK AMOUNT alert only (no file)
* Returns the computeTotals() summary so callers can persist metadata. */
function generateInvoice(data, doprint) {
var doc = new jsPDF();
// Draw the entire static template as vectors (frame, grid, letterhead,
// column headers, totals labels, footer) instead of stamping a background
// JPEG. See template-draw.js. Same visual layout, ~7.5KB not ~425KB.
drawTemplate(doc);
doc.setFontSize(10);
doc.setFontType("bold");
// ---- Invoice / consignee header (exact original coordinates) ----
doc.text(String(data.invoiceNumber), 42, 62);
var dte = new Date(data.invoiceDate);
var dt = dte.getDate();
var mn = dte.getMonth();
mn++;
var yy = dte.getFullYear();
var findate = String(dt + "/" + mn + "/" + yy);
doc.text(findate, 42, 66.3);
doc.text(String(data.transport), 42, 70.6);
doc.text(String(data.vehicle), 42, 74.9);
var optionstxt = { maxWidth: "125" };
doc.text([String(data.consignee)], 74, 66.3, optionstxt);
doc.setFontType("normal");
// ---- Line items ----
optionstxt = { align: "center", maxWidth: "45" };
var amtfinal = 0;
var totquant = 0;
var items = data.items || [];
for (var sno = 0; sno < items.length; sno++) {
var it = items[sno];
var y = 112 + sno * 13;
doc.text(String(sno + 1) + ".", 15, y, optionstxt);
doc.text(String(it.name), 44, y, optionstxt);
doc.text(String(it.hsn), 75.5, y, optionstxt);
doc.text(String(it.gsm), 90.7, y, optionstxt);
doc.text(String(it.size), 109.2, y, optionstxt);
doc.text(String(it.quantity), 131.1, y, optionstxt);
doc.text(String(it.bundles), 147, y, optionstxt);
doc.text(String(it.rate), 164.5, y, optionstxt);
var zz = it.quantity;
var yy2 = it.rate;
amtfinal = amtfinal + zz * yy2;
totquant = totquant + zz * 1;
var amtcur = zz * yy2;
doc.text(String(amtcur.toFixed(2)), 187, y, optionstxt);
}
// ---- Totals / taxes (exact original arithmetic + coordinates) ----
var xcgst = parseFloat(0);
var xsgst = parseFloat(0);
var xigst = parseFloat(0);
var xcout = _num(data.carriageOutward);
var itemcost = amtfinal;
var xother = _num(data.otherCharges);
amtfinal = amtfinal + xcout + xother;
if (data.igst === true) xigst = parseFloat(amtfinal * 0.18);
if (data.cgst === true) xcgst = parseFloat(amtfinal * 0.09);
if (data.sgst === true) xsgst = parseFloat(amtfinal * 0.09);
var totTax = parseFloat(xigst + xcgst + xsgst).toFixed(2);
var extraCost = xcout + xother;
var xroundtot = parseFloat(amtfinal + xcgst + xsgst + xigst);
xroundtot = xroundtot.toFixed(0);
xroundtot = parseFloat(xroundtot).toFixed(2);
var xadv = _num(data.lessAdvance);
var gross = parseFloat((xroundtot - xadv)).toFixed(2);
doc.text(String(parseFloat(totquant).toFixed(3)), 131.1, 208, optionstxt);
doc.text(String(xcout.toFixed(2)), 187, 208, optionstxt);
doc.text(String(xsgst.toFixed(2)), 187, 224, optionstxt);
doc.text(String(xcgst.toFixed(2)), 187, 230.5, optionstxt);
doc.text(String(xigst.toFixed(2)), 187, 236.5, optionstxt);
doc.text(String(xother.toFixed(2)), 187, 216.5, optionstxt);
doc.text(String(xroundtot), 187, 245, optionstxt);
doc.text(String(xadv.toFixed(2)), 187, 253.5, optionstxt);
doc.setFontType("bold");
doc.text(String(gross), 187, 263, optionstxt);
// ---- HSN-wise GST summary table (dynamic; lower-left empty band) ----
renderGstSummary(doc, {
items: items,
carriageOutward: data.carriageOutward,
otherCharges: data.otherCharges,
igst: data.igst === true,
cgst: data.cgst === true,
sgst: data.sgst === true
});
if (doprint === true) {
doc.save('INVOICE_' + data.invoiceNumber + '.pdf');
} else {
alert(
"\n----------------------------" +
"\nITEM COST: " + itemcost.toFixed(2) +
"\nEXTRA COST: " + extraCost.toFixed(2) +
"\nTAX: " + totTax +
"\nADV PROVIDED: " + xadv.toFixed(2) +
"\n----------------------------" +
"\nFINAL AMOUNT: " + gross +
"\n----------------------------"
);
}
return computeTotals(data);
}