summaryrefslogtreecommitdiffstats
path: root/src/pdf-invoice/pdf-invoice.vala
blob: d92c93faffc3081fbd6cd09a015e4ef4f9cbf0f5 (plain)
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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
/* Copyright 2013, Sebastian Reichel <sre@ring0.de>
 * Copyright 2017-2018, Johannes Rudolph <johannes.rudolph@gmx.com>
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

[DBus (name = "io.mainframe.shopsystem.InvoicePDF")]
public class InvoicePDF {
	Config cfg;

	/* A4 sizes (in points, 72 DPI) */
	private const double width = 595.27559;  /* 210mm */
	private const double height = 841.88976; /* 297mm */

	/* invoice content, which should appear in the PDF */
	public string invoice_id { set; owned get; default = ""; }
	public int64  invoice_date { set; get; default = 0; }
	public InvoiceEntry[] invoice_entries { set; owned get; default = null; }
	public InvoiceRecipient invoice_recipient {
		set;
		owned get;
		default = InvoiceRecipient() {
			firstname = "",
			lastname = "",
			street = "",
			postal_code = "",
			city = "",
			gender = ""
		};
	}

	/* pdf data */
	private uint8[] data;
	private uint useddatalength;

	/* internal helper */
	private DateTime previous_tm;

	private string datadir;

	private const string[] calendermonths = {
		"Januar",
		"Februar",
		"März",
		"April",
		"Mai",
		"Juni",
		"Juli",
		"August",
		"September",
		"Oktober",
		"November",
		"Dezember"
	};

	string longname;
	string vat;

	public InvoicePDF(string datadir) throws DBusError, IOError, KeyFileError {
		this.datadir = datadir;
		cfg = Bus.get_proxy_sync(BusType.SYSTEM, "io.mainframe.shopsystem.Config", "/io/mainframe/shopsystem/config");
		longname = cfg.get_string("GENERAL", "longname");
		vat = cfg.get_string("INVOICE", "vat");
	}

	private void render_svg(Cairo.Context ctx, string file) {
		try {
			var svg = new Rsvg.Handle.from_file(file);
			svg.render_cairo(ctx);
		} catch(Error e) {
			error("Could not load SVG: %s\n", e.message);
		}
	}

	private void draw_footer(Cairo.Context ctx) {
		ctx.save();
		ctx.translate(-20, 818);
		ctx.scale(1.42, 1.42);
		render_svg(ctx, datadir + "/footer-line.svg");
		ctx.restore();
	}

	private void draw_logo(Cairo.Context ctx) {
		ctx.save();
		ctx.translate(366,25);
		render_svg(ctx, datadir + "/logo.svg");
		ctx.restore();
	}

	private void draw_address(Cairo.Context ctx) throws DBusError, IOError, KeyFileError {
		ctx.save();
		ctx.set_source_rgb(0, 0, 0);
		ctx.set_line_width(1.0);

		/* upper fold mark (20 mm left, 85 mm width, 51.5 mm top) */
		ctx.move_to(56.69, 146);
		ctx.line_to(297.59, 146);
		ctx.stroke();

		/* actually LMSans8 */
		ctx.set_source_rgb(0, 0, 0);
		ctx.select_font_face("LMSans10", Cairo.FontSlant.NORMAL, Cairo.FontWeight.NORMAL);
		ctx.set_font_size(8.45);

		ctx.move_to(56.5, 142);
		ctx.show_text(cfg.get_string("INVOICE", "addressrow"));

		/* actually LMRoman12 */
		ctx.select_font_face("LMSans10", Cairo.FontSlant.NORMAL, Cairo.FontWeight.NORMAL);
		ctx.set_font_size(12.3);

		ctx.move_to(56.5, 184);
		ctx.show_text(invoice_recipient.firstname + " " + invoice_recipient.lastname);

		ctx.move_to(56.5, 198);
		ctx.show_text(invoice_recipient.street);

		/* actually LMRoman12 */
		ctx.select_font_face("LMSans10", Cairo.FontSlant.NORMAL, Cairo.FontWeight.BOLD);
		ctx.move_to(56.5, 227);
		ctx.show_text(invoice_recipient.postal_code + " " + invoice_recipient.city);

		ctx.restore();
	}

	private void draw_folding_marks(Cairo.Context ctx) {
		ctx.save();
		ctx.set_source_rgb(0, 0, 0);
		ctx.set_line_width(1.0);

		/* upper fold mark (105 mm) */
		ctx.move_to(10, 297.65);
		ctx.line_to(15, 297.65);
		ctx.stroke();

		/* middle fold mark (148.5 mm)*/
		ctx.move_to(10, 420.912);
		ctx.line_to(23, 420.912);
		ctx.stroke();

		/* lower fold mark (210 mm)*/
		ctx.move_to(10, 595.3);
		ctx.line_to(15, 595.3);
		ctx.stroke();

		ctx.restore();
	}

	private void draw_date(Cairo.Context ctx) {
		ctx.save();
		ctx.move_to(56.5, 280.0);
		ctx.set_source_rgb(0, 0, 0);

		/* get pango layout */
		var layout = Pango.cairo_create_layout(ctx);

		/* setup font */
		var font = new Pango.FontDescription();
		font.set_family("LMSans10");
		font.set_size((int) 9.0 * Pango.SCALE);
		layout.set_font_description(font);

		/* right alignment */
		layout.set_alignment(Pango.Alignment.RIGHT);
		layout.set_wrap(Pango.WrapMode.WORD_CHAR);

		/* set page width */
		layout.set_width((int) 446 * Pango.SCALE);

		/* write invoice date */
		var invdate = new DateTime.from_unix_local(invoice_date);
		var day = "%d".printf(invdate.get_day_of_month());
		var month = invdate.get_month();
		var year = "%d".printf(invdate.get_year());
		var date = day + ". " + calendermonths[month-1] + " " + year;
		layout.set_text(date, date.length);

		/* render text */
		Pango.cairo_update_layout(ctx, layout);
		Pango.cairo_show_layout(ctx, layout);

		ctx.restore();
	}

	private void draw_title(Cairo.Context ctx) {
		ctx.save();

		/* actually LMRoman12 */
		ctx.set_source_rgb(0, 0, 0);
		ctx.select_font_face("LMSans10", Cairo.FontSlant.NORMAL, Cairo.FontWeight.BOLD);
		ctx.set_font_size(12.9);

		ctx.move_to(56.5, 323);

		ctx.show_text(@"Rechnung Nr. $invoice_id");

		ctx.restore();
	}

	private void draw_footer_text_left(Cairo.Context ctx) throws DBusError, IOError, KeyFileError {
		ctx.save();
		ctx.move_to(64.0, 742.0);
		ctx.set_source_rgb(0, 0, 0);

		/* get pango layout */
		var layout = Pango.cairo_create_layout(ctx);

		/* setup font */
		var font = new Pango.FontDescription();
		font.set_family("LMRoman8");
		font.set_size((int) 6.0 * Pango.SCALE);
		layout.set_font_description(font);

		/* left alignment */
		layout.set_alignment(Pango.Alignment.LEFT);
		layout.set_wrap(Pango.WrapMode.WORD_CHAR);

		/* set line spacing */
		layout.set_spacing((int) (-2.0 * Pango.SCALE));

		/* set page width */
		layout.set_width((int) 140 * Pango.SCALE);

		var text = cfg.get_string("INVOICE", "footer1");

		/* write invoice date */
		layout.set_markup(text, text.length);

		/* render text */
		Pango.cairo_update_layout(ctx, layout);
		Pango.cairo_show_layout(ctx, layout);

		ctx.restore();
	}

	private void draw_footer_text_middle(Cairo.Context ctx) throws DBusError, IOError, KeyFileError {
		ctx.save();
		ctx.move_to(216.5, 742.0);
		ctx.set_source_rgb(0, 0, 0);

		/* get pango layout */
		var layout = Pango.cairo_create_layout(ctx);

		/* setup font */
		var font = new Pango.FontDescription();
		font.set_family("LMRoman8");
		font.set_size((int) 6.0 * Pango.SCALE);
		layout.set_font_description(font);

		/* left alignment */
		layout.set_alignment(Pango.Alignment.LEFT);
		layout.set_wrap(Pango.WrapMode.WORD_CHAR);

		/* set line spacing */
		layout.set_spacing((int) (-2.0 * Pango.SCALE));

		/* set page width */
		layout.set_width((int) 190 * Pango.SCALE);

		var text = cfg.get_string("INVOICE", "footer2");

		/* write invoice date */
		layout.set_markup(text, text.length);

		/* render text */
		Pango.cairo_update_layout(ctx, layout);
		Pango.cairo_show_layout(ctx, layout);

		ctx.restore();
	}

	private void draw_footer_text_right(Cairo.Context ctx) throws DBusError, IOError, KeyFileError {
		ctx.save();
		ctx.move_to(410.0, 742.0);
		ctx.set_source_rgb(0, 0, 0);

		/* get pango layout */
		var layout = Pango.cairo_create_layout(ctx);

		/* setup font */
		var font = new Pango.FontDescription();
		font.set_family("LMRoman8");
		font.set_size((int) 6.0 * Pango.SCALE);
		layout.set_font_description(font);

		/* left alignment */
		layout.set_alignment(Pango.Alignment.LEFT);
		layout.set_wrap(Pango.WrapMode.WORD_CHAR);

		/* set line spacing */
		layout.set_spacing((int) (-2.0 * Pango.SCALE));

		/* set page width */
		layout.set_width((int) 150 * Pango.SCALE);

		var text = cfg.get_string("INVOICE", "footer3");

		/* write invoice date */
		layout.set_markup(text, text.length);

		/* render text */
		Pango.cairo_update_layout(ctx, layout);
		Pango.cairo_show_layout(ctx, layout);

		ctx.restore();
	}

	private Price get_sum() {
		Price sum = 0;
		foreach(var e in invoice_entries) {
			sum += e.price;
		}
		return sum;
	}

	private string get_address() {
		if(invoice_recipient.gender == "masculinum")
			return "Sehr geehrter Herr";
		else if(invoice_recipient.gender == "femininum")
			return "Sehr geehrte Frau";
		else
			return "Moin";
	}

	private void draw_first_page_text(Cairo.Context ctx) throws IOError {
		ctx.save();
		ctx.move_to(56.5, 352.5);
		ctx.set_source_rgb(0, 0, 0);

		/* get pango layout */
		var layout = Pango.cairo_create_layout(ctx);

		/* setup font */
		var font = new Pango.FontDescription();
		font.set_family("LMRoman12");
		font.set_size((int) 9.0 * Pango.SCALE);
		layout.set_font_description(font);

		/* left alignment */
		layout.set_alignment(Pango.Alignment.LEFT);
		layout.set_wrap(Pango.WrapMode.WORD_CHAR);

		/* set line spacing */
		layout.set_spacing((int) (-2.1 * Pango.SCALE));

		/* set page width */
		layout.set_width((int) 446 * Pango.SCALE);

		string address = get_address();
		Price sum = get_sum();

		/* load text template */
		try {
			var text = "";
			FileUtils.get_contents(datadir + "/pdf-template.txt", out text);
			text = text.replace("{{{ADDRESS}}}", address);
			text = text.replace("{{{LASTNAME}}}", invoice_recipient.lastname);
			text = text.replace("{{{SUM}}}", @"$sum");
			text = text.replace("{{{ORGANIZATION}}}", longname);

			if(vat == "yes") {
				text = text.replace("{{{VAT}}}", "");
			} else {
				string vattext;

				try {
					FileUtils.get_contents(datadir + "/" + "vat.txt", out vattext);
				} catch(GLib.FileError e) {
					throw new IOError.FAILED("Could not open VAT template: %s", e.message);
				}

				text = text.replace("{{{VAT}}}", vattext);
			}

			layout.set_markup(text, text.length);
		} catch(GLib.FileError e) {
			error("File Error: %s\n", e.message);
		}

		/* render text */
		Pango.cairo_update_layout(ctx, layout);
		Pango.cairo_show_layout(ctx, layout);

		ctx.restore();
	}

	private void draw_invoice_table_header(Cairo.Context ctx) {
		ctx.save();

		/* border & font color */
		ctx.set_source_rgb(0, 0, 0);

		/* line width of the border */
		ctx.set_line_width(0.8);

		/* header font */
		ctx.select_font_face("LMSans10", Cairo.FontSlant.NORMAL, Cairo.FontWeight.BOLD);
		ctx.set_font_size(12);

		/* borders */
		ctx.move_to(58, 50);
		ctx.line_to(530, 50);
		ctx.line_to(530, 65);
		ctx.line_to(58, 65);
		ctx.line_to(58, 50);
		ctx.move_to(120, 50);
		ctx.line_to(120, 65);
		ctx.move_to(180, 50);
		ctx.line_to(180, 65);
		ctx.move_to(480, 50);
		ctx.line_to(480, 65);
		ctx.stroke();

		/* header text */
		ctx.move_to(62, 61.5);
		ctx.show_text("Datum");
		ctx.move_to(124, 61.5);
		ctx.show_text("Uhrzeit");
		ctx.move_to(184, 61.5);
		ctx.show_text("Artikel");
		ctx.move_to(484, 61.5);
		ctx.show_text("Preis");

		ctx.restore();
	}

	private void draw_invoice_table_footer(Cairo.Context ctx, double y) {
		ctx.save();

		/* border & font color */
		ctx.set_source_rgb(0, 0, 0);

		/* line width of the border */
		ctx.set_line_width(0.8);

		/* end of table is just a line */
		ctx.move_to(58, y);
		ctx.line_to(530, y);
		ctx.stroke();

		ctx.restore();
	}

	private bool draw_invoice_table_entry(Cairo.Context ctx, double y, InvoiceEntry e, out double newy) throws InvoicePDFError {
		ctx.save();

		/* border & font color */
		ctx.set_source_rgb(0, 0, 0);

		/* y remains the same by default */
		newy = y;

		/* generate strings for InvoiceEntry */
		var tm = new DateTime.from_unix_local(e.timestamp);
		var date = tm.format("%Y-%m-%d");
		var time = tm.format("%H:%M:%S");
		var article = e.product.name;
		var price = @"$(e.price)€".replace(".", ",");

		if(e.price > 999999) {
			throw new InvoicePDFError.PRICE_TOO_HIGH("Prices > 9999.99€ are not supported!");
		}

		if(tm.get_year() > 9999) {
			throw new InvoicePDFError.TOO_FAR_IN_THE_FUTURE("Years after 9999 are not supported!");
		}

		/* if date remains the same do not add it again */
		if(previous_tm != null &&
		   previous_tm.get_year() == tm.get_year() &&
		   previous_tm.get_month() == tm.get_month() &&
		   previous_tm.get_day_of_month() == tm.get_day_of_month()) {
			date = "";
		}

		/* move to position for article text */
		ctx.move_to(184, y);

		/* get pango layout */
		var layout = Pango.cairo_create_layout(ctx);

		/* setup font */
		var font = new Pango.FontDescription();
		font.set_family("LMSans10");
		font.set_size((int) 8 * Pango.SCALE);
		layout.set_font_description(font);

		/* left alignment */
		layout.set_alignment(Pango.Alignment.LEFT);
		layout.set_wrap(Pango.WrapMode.WORD_CHAR);

		/* set line spacing */
		layout.set_spacing((int) (-2.0 * Pango.SCALE));

		/* set page width */
		layout.set_width((int) 290 * Pango.SCALE);

		/* write invoice date */
		layout.set_text(article, article.length);

		/* get height of text */
		int w,h;
		layout.get_size(out w, out h);
		double height = h/Pango.SCALE;

		/* verify that the text fits on the page */
		if(750 < y + height)
			return false;

		/* render article text */
		Pango.cairo_update_layout(ctx, layout);
		Pango.cairo_show_layout(ctx, layout);

		/* render date, time (toy font api uses different y than pango) */
		ctx.select_font_face("LMSans10", Cairo.FontSlant.NORMAL, Cairo.FontWeight.NORMAL);
		ctx.set_font_size(11);
		ctx.move_to(62, y+12.0);
		ctx.show_text(date);
		ctx.move_to(124, y+12.0);
		ctx.show_text(time);

		/* render price */
		ctx.move_to(484, y);
		var pricelayout = Pango.cairo_create_layout(ctx);
		pricelayout.set_font_description(font);
		pricelayout.set_alignment(Pango.Alignment.RIGHT);
		pricelayout.set_width((int) 42 * Pango.SCALE);
		pricelayout.set_text(price, price.length);
		Pango.cairo_update_layout(ctx, pricelayout);
		Pango.cairo_show_layout(ctx, pricelayout);

		/* add borders */
		ctx.set_line_width(0.8);
		ctx.move_to(58, y);
		ctx.line_to(58, y+height);
		ctx.move_to(120, y);
		ctx.line_to(120, y+height);
		ctx.move_to(180, y);
		ctx.line_to(180, y+height);
		ctx.move_to(480, y);
		ctx.line_to(480, y+height);
		ctx.move_to(530, y);
		ctx.line_to(530, y+height);
		ctx.stroke();

		ctx.restore();

		newy += height;
		previous_tm = tm;

		return true;
	}

	private void draw_invoice_table(Cairo.Context ctx) throws InvoicePDFError {
		ctx.save();

		draw_footer(ctx);
		draw_invoice_table_header(ctx);

		/* initial position for entries */
		double y = 65;

		foreach(var entry in invoice_entries) {
			if(!draw_invoice_table_entry(ctx, y, entry, out y)) {
				/* entry could not be added, because end of page has been reached */
				draw_invoice_table_footer(ctx, y);
				ctx.show_page();

				/* draw page footer & table header on new page */
				draw_footer(ctx);
				draw_invoice_table_header(ctx);

				/* reset position */
				y = 65;

				/* always print date on new pages */
				previous_tm = null;

				/* retry adding the entry */
				if(!draw_invoice_table_entry(ctx, y, entry, out y)) {
					throw new InvoicePDFError.ARTICLE_NAME_TOO_LONG("Article name \"%s\" does not fit on a single page!", entry.product.name);
				}
			}
		}

		draw_invoice_table_footer(ctx, y);
		ctx.show_page();

		ctx.restore();
	}

	private Cairo.Status pdf_write(uchar[] newdata) {
		if(data == null) {
			data = newdata;
			useddatalength = newdata.length;
		} else {
			if(useddatalength + newdata.length > data.length) {
				uint8[] alldata = new uint8[data.length + newdata.length + 512];
				Posix.memcpy(alldata, data, data.length);
				data = alldata;
			}

			Posix.memcpy((uint8*) data + useddatalength, newdata, newdata.length);
			useddatalength += newdata.length;
		}

		return Cairo.Status.SUCCESS;
	}

	public uint8[] generate() throws DBusError, IOError, InvoicePDFError, KeyFileError {
		data = null;

		var document = new Cairo.PdfSurface.for_stream(pdf_write, width, height);

		var ctx = new Cairo.Context(document);

		if(invoice_id == "")
			throw new InvoicePDFError.NO_INVOICE_ID("No invoice ID given!");

		if(invoice_entries == null)
			throw new InvoicePDFError.NO_INVOICE_DATA("No invoice data given!");

		if(invoice_date == 0)
			throw new InvoicePDFError.NO_INVOICE_DATE("No invoice date given!");

		if(invoice_recipient.firstname == "" && invoice_recipient.lastname == "")
			throw new InvoicePDFError.NO_INVOICE_RECIPIENT("No invoice recipient given!");

		/* first page */
		draw_logo(ctx);
		draw_address(ctx);
		draw_folding_marks(ctx);
		draw_footer(ctx);
		draw_footer_text_left(ctx);
		draw_footer_text_middle(ctx);
		draw_footer_text_right(ctx);
		draw_date(ctx);
		draw_title(ctx);
		draw_first_page_text(ctx);
		ctx.show_page();

		/* following pages: invoice table */
		draw_invoice_table(ctx);

		document.finish();
		document.flush();

		return data;
	}

	public void clear() throws DBusError, IOError {
		invoice_date                  = 0;
		invoice_id                    = "";
		invoice_recipient.firstname   = "";
		invoice_recipient.lastname    = "";
		invoice_recipient.street      = "";
		invoice_recipient.postal_code = "";
		invoice_recipient.city        = "";
		invoice_recipient.gender      = "";

		invoice_entries               = null;
	}
}