write_invoice.rs

Die Rust-Datei des Beispiels „Eine Handelsrechnung“. Eine Rechnung: Jede Rechnungsposition folgt auf die vorige, die Summen stehen unter der letzten, und der QR-Code enthält die Überweisung. Der Kunde richtet ein Telefon darauf, und die Banking-App bietet genau den Betrag auf genau das Konto an, ohne dass etwas abgetippt wird.

Rust 872 Zeilen

Wofür dieses Beispiel da ist

Eine Rechnung ist das Dokument, auf das hin ein Unternehmen bezahlt wird. Sie hat auch nie zweimal dieselbe Form: vier Positionen diesen Monat, vierzig im nächsten, und die Summen müssen in jedem Fall darunter landen. Nichts hier steht auf einer Höhe, die jemand vorher gemessen hat — jede Zeile nimmt sich beim Schreiben den Platz, den sie braucht, und die Seite wechselt von selbst, wenn keiner mehr übrig ist.

Was dieses Beispiel zeigt

  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
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
//! Writes a commercial invoice: a letterhead, a billed-lines table, totals, and
//! a payment block whose amount can be paid by scanning a code.
//!
//! This is the document the library is sold to make. It puts a logo, styled
//! text, a paginating table, and a QR code on one page, and the code it draws
//! is a SEPA credit transfer: a phone's banking app reads it and offers to pay
//! the exact amount to the exact account, so a person never types an IBAN by
//! hand.
//!
//! Whether that code pays is not for the page to say, and not for an eye: a
//! scanner says. `scripts/check_qr.sh` points a decoder at the rendered page
//! and reads back the transfer.
//!
//! Every word the page draws is held in `Words`, once per language, and
//! `HQF_PDF_LANG` picks which one is drawn. Figures, dates in the file's own
//! name, the account number and the invoice's number are the same in both.
//!
//! Usage: `cargo run --example write_invoice -- tmp/invoice.pdf [font.ttf]`
//!        `HQF_PDF_LANG=fr cargo run --example write_invoice -- tmp/facture.pdf`

use std::env;
use std::fs;
use std::path::{Path, PathBuf};

use hqf_pdf::content::Content;
use hqf_pdf::cos::Name;
use hqf_pdf::layout::{
    Border, Cell, ColumnWidth, Columns, Margin, Padding, RichText, Row, Rule, Stroke, Style, Table,
    TableFrame, VAlign,
};
use hqf_pdf::{Align, Document, Font, FontHandle, Image, ImageHandle, Page, QrCode, Rgb};

#[path = "shared/out.rs"]
mod out;

#[path = "shared/licence.rs"]
mod licence;

#[path = "shared/language.rs"]
mod language;

#[path = "shared/failure.rs"]
mod failure;

use language::Language;

/// The font the example draws with when none is given on the command line.
fn default_font() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fonts")
        .join("DejaVuSans.ttf")
}

/// The logo the letterhead carries: the committed fixture, so the example runs
/// on any machine. It stands in for the seller's mark.
fn logo_path() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("images")
        .join("hqf_development.png")
}

/// A4, in points.
const PAGE_WIDTH: f64 = 595.276;
const PAGE_HEIGHT: f64 = 841.89;
/// The page's left edge and, mirrored, its right.
const LEFT: f64 = 56.0;
const RIGHT: f64 = PAGE_WIDTH - LEFT;
/// The width the table is fitted across.
const TABLE_WIDTH: f64 = PAGE_WIDTH - 2.0 * LEFT;

/// The ink the headings and rules are drawn in, and the grey of the small
/// print.
const ACCENT: Rgb = Rgb {
    r: 0.11,
    g: 0.33,
    b: 0.55,
};
const MUTED: Rgb = Rgb {
    r: 0.42,
    g: 0.42,
    b: 0.45,
};
const INK: Rgb = Rgb {
    r: 0.1,
    g: 0.1,
    b: 0.12,
};

/// How many lines the invoice bills.
const ITEM_COUNT: usize = 4;

/// What one line of the invoice sells, apart from what it is called: the
/// figures read the same whatever language the page is set in.
struct Item {
    /// How many.
    quantity: u32,
    /// The price of one, before tax.
    unit_price: f64,
}

/// The lines this invoice bills, in the order `Words::items` names them.
const ITEMS: [Item; ITEM_COUNT] = [
    Item {
        quantity: 14,
        unit_price: 620.0,
    },
    Item {
        quantity: 6,
        unit_price: 480.0,
    },
    Item {
        quantity: 1,
        unit_price: 1440.0,
    },
    Item {
        quantity: 2,
        unit_price: 950.0,
    },
];

/// The rate the invoice charges tax at.
const VAT_RATE: f64 = 0.2;

/// What the invoice is called.
const NUMBER: &str = "2026-0142";

/// The seller, and the numbers a French invoice has to carry.
const SELLER: &str = "HQF Development";
const SELLER_ADDRESS: &str = "42 lot les Genêts, 13480 Calas, France";
const SELLER_CONTACT: &str = "contact@hqf-pdf.com";
const SELLER_SIRET: &str = "SIRET 752 492 777 00012";
const SELLER_APE: &str = "APE 6202A";
const SELLER_VAT: &str = "FR59 752 492 777";

/// Who the invoice is billed to.
const BUYER: &str = "Northwind Trading SARL";
const BUYER_STREET: &str = "18 quai du Port";
const BUYER_CITY: &str = "13002 Marseille, France";

/// The account the QR code pays into, ungrouped as the standard wants it, and
/// grouped as the page shows it. The number is a documentation IBAN, not a live
/// account: what the example demonstrates is the transfer, not the destination.
const IBAN: &str = "FR1420041010050500013M02606";
const IBAN_SHOWN: &str = "FR14 2004 1010 0505 0001 3M02 606";

/// Every word the page draws, in one language.
///
/// What is not language stays out of it: the figures, the account number, the
/// invoice's number and the seller's and buyer's names and addresses are drawn
/// from constants of their own and read the same in every language.
#[derive(Debug)]
struct Words {
    /// The word the payment reference and the document's title are built from.
    invoice: &'static str,
    /// The word set large at the head of the page.
    heading: &'static str,
    /// What stands before the invoice's number.
    number_label: &'static str,
    /// What stands before the day the invoice was issued.
    issue_label: &'static str,
    /// That day, written as this language writes a date.
    issue_date: &'static str,
    /// What stands before the day the invoice falls due.
    due_label: &'static str,
    /// That day, written as this language writes a date.
    due_date: &'static str,
    /// The short form of the same, set under the amount owed.
    due_short: &'static str,
    /// The heading over the buyer.
    bill_to: &'static str,
    /// The heading over what is owed.
    amount_due: &'static str,
    /// What each billed line is called, in the order `ITEMS` bills them.
    items: [&'static str; ITEM_COUNT],
    /// The four column headings of the table.
    description: &'static str,
    quantity: &'static str,
    unit_price: &'static str,
    amount: &'static str,
    /// The three totals under the billed lines.
    subtotal: &'static str,
    tax: &'static str,
    total: &'static str,
    /// The heading over the payment block.
    payment: &'static str,
    /// The sentence the payment block sets, cut where the amount and the
    /// invoice's number go into it.
    terms_before: &'static str,
    terms_around_number: &'static str,
    terms_after: &'static str,
    /// What stands before the account number.
    iban_label: &'static str,
    /// What stands under the code.
    caption: &'static str,
    /// The word before the seller's tax number in the footer.
    vat: &'static str,
}

impl Words {
    /// The words the invoice is written in, in `language`.
    fn of(language: Language) -> &'static Self {
        language::pick(&WORDS, language)
    }
}

/// The invoice in English.
const ENGLISH: Words = Words {
    invoice: "Invoice",
    heading: "INVOICE",
    number_label: "Invoice No.",
    issue_label: "Issue date",
    issue_date: "19 July 2026",
    due_label: "Due date",
    due_date: "18 August 2026",
    due_short: "Due",
    bill_to: "BILL TO",
    amount_due: "AMOUNT DUE",
    items: [
        "Web application development",
        "UX and graphic design",
        "Managed hosting — annual plan",
        "On-site training (Django, per day)",
    ],
    description: "Description",
    quantity: "Qty",
    unit_price: "Unit price",
    amount: "Amount",
    subtotal: "Subtotal",
    tax: "VAT at 20 %",
    total: "Total due",
    payment: "PAYMENT",
    terms_before: "Please transfer ",
    terms_around_number: " within 30 days, quoting invoice ",
    terms_after: ". Scan the code to pay the exact amount to the account below.",
    iban_label: "IBAN",
    caption: "Scan to pay — SEPA",
    vat: "VAT",
};

/// The invoice in French.
const FRENCH: Words = Words {
    invoice: "Facture",
    heading: "FACTURE",
    number_label: "Facture n°",
    issue_label: "Date d’émission",
    issue_date: "19 juillet 2026",
    due_label: "Échéance",
    due_date: "18 août 2026",
    due_short: "Échéance",
    bill_to: "FACTURÉ À",
    amount_due: "MONTANT DÛ",
    items: [
        "Développement d’application web",
        "Conception graphique et UX",
        "Hébergement infogéré — forfait annuel",
        "Formation sur site (Django, par jour)",
    ],
    description: "Désignation",
    quantity: "Qté",
    unit_price: "Prix unitaire",
    amount: "Montant",
    subtotal: "Total HT",
    tax: "TVA 20 %",
    total: "Total TTC",
    payment: "PAIEMENT",
    terms_before: "Payable par virement de ",
    terms_around_number: " sous 30 jours. Merci de rappeler le numéro de facture ",
    terms_after: ". Scannez le code pour payer le montant exact sur le compte ci-dessous.",
    iban_label: "IBAN",
    caption: "Scannez pour payer — SEPA",
    vat: "TVA",
};

/// The invoice in Dutch.
const DUTCH: Words = Words {
    invoice: "Factuur",
    heading: "FACTUUR",
    number_label: "Factuur nr.",
    issue_label: "Factuurdatum",
    issue_date: "19 juli 2026",
    due_label: "Vervaldatum",
    due_date: "18 augustus 2026",
    due_short: "Te betalen",
    bill_to: "FACTUUR AAN",
    amount_due: "TE BETALEN BEDRAG",
    items: [
        "Ontwikkeling van een webapplicatie",
        "UX- en grafisch ontwerp",
        "Beheerde hosting — jaarabonnement",
        "Training op locatie (Django, per dag)",
    ],
    description: "Omschrijving",
    quantity: "Aantal",
    unit_price: "Stukprijs",
    amount: "Bedrag",
    subtotal: "Subtotaal",
    tax: "Btw 20 %",
    total: "Te betalen",
    payment: "BETALING",
    terms_before: "Maak",
    terms_around_number: " binnen 30 dagen over, onder vermelding van factuur",
    terms_after: ". Scan de code om het exacte bedrag naar de rekening hieronder te betalen.",
    iban_label: "IBAN",
    caption: "Scan om te betalen — SEPA",
    vat: "Btw",
};

/// The invoice in Portuguese.
const PORTUGUESE: Words = Words {
    invoice: "Fatura",
    heading: "FATURA",
    number_label: "Fatura n.º",
    issue_label: "Data de emissão",
    issue_date: "19 de julho de 2026",
    due_label: "Data de vencimento",
    due_date: "18 de agosto de 2026",
    due_short: "Vence",
    bill_to: "FATURAR A",
    amount_due: "MONTANTE A PAGAR",
    items: [
        "Desenvolvimento de aplicação web",
        "Design UX e gráfico",
        "Alojamento gerido — plano anual",
        "Formação presencial (Django, por dia)",
    ],
    description: "Descrição",
    quantity: "Qtd.",
    unit_price: "Preço unitário",
    amount: "Montante",
    subtotal: "Subtotal",
    tax: "IVA a 20 %",
    total: "Total a pagar",
    payment: "PAGAMENTO",
    terms_before: "Transfira",
    terms_around_number: " no prazo de 30 dias, indicando a fatura",
    terms_after: ". Leia o código para pagar o montante exato para a conta abaixo.",
    iban_label: "IBAN",
    caption: "Ler para pagar — SEPA",
    vat: "NIF",
};

/// The invoice in Italian.
const ITALIAN: Words = Words {
    invoice: "Fattura",
    heading: "FATTURA",
    number_label: "Fattura n.",
    issue_label: "Data di emissione",
    issue_date: "19 luglio 2026",
    due_label: "Data di scadenza",
    due_date: "18 agosto 2026",
    due_short: "Scadenza",
    bill_to: "INTESTATARIO",
    amount_due: "IMPORTO DOVUTO",
    items: [
        "Sviluppo di applicazione web",
        "Design UX e grafico",
        "Hosting gestito — piano annuale",
        "Formazione in sede (Django, al giorno)",
    ],
    description: "Descrizione",
    quantity: "Qtà",
    unit_price: "Prezzo unitario",
    amount: "Importo",
    subtotal: "Imponibile",
    tax: "IVA al 20 %",
    total: "Totale dovuto",
    payment: "PAGAMENTO",
    terms_before: "Si prega di versare",
    terms_around_number: " entro 30 giorni, citando la fattura",
    terms_after: ". Inquadrate il codice per pagare l’importo esatto sul conto qui sotto.",
    iban_label: "IBAN",
    caption: "Inquadrare per pagare — SEPA",
    vat: "P. IVA",
};

/// The invoice in Spanish.
const SPANISH: Words = Words {
    invoice: "Factura",
    heading: "FACTURA",
    number_label: "Factura n.º",
    issue_label: "Fecha de emisión",
    issue_date: "19 de julio de 2026",
    due_label: "Vencimiento",
    due_date: "18 de agosto de 2026",
    due_short: "Vence",
    bill_to: "FACTURAR A",
    amount_due: "IMPORTE A PAGAR",
    items: [
        "Desarrollo de aplicación web",
        "Diseño UX y gráfico",
        "Alojamiento gestionado — plan anual",
        "Formación presencial (Django, por día)",
    ],
    description: "Descripción",
    quantity: "Cant.",
    unit_price: "Precio unitario",
    amount: "Importe",
    subtotal: "Subtotal",
    tax: "IVA al 20 %",
    total: "Total a pagar",
    payment: "PAGO",
    terms_before: "Transfiera ",
    terms_around_number: " en 30 días, indicando la factura ",
    terms_after: ". Escanee el código para pagar el importe exacto a la cuenta de abajo.",
    iban_label: "IBAN",
    caption: "Escanear para pagar — SEPA",
    vat: "IVA",
};

/// The invoice in German.
const GERMAN: Words = Words {
    invoice: "Rechnung",
    heading: "RECHNUNG",
    number_label: "Rechnung Nr.",
    issue_label: "Rechnungsdatum",
    issue_date: "19. Juli 2026",
    due_label: "Fälligkeitsdatum",
    due_date: "18. August 2026",
    due_short: "Fällig",
    bill_to: "RECHNUNG AN",
    amount_due: "ZU ZAHLEN",
    items: [
        "Entwicklung einer Webanwendung",
        "UX- und Grafikdesign",
        "Verwaltetes Hosting — Jahrestarif",
        "Schulung vor Ort (Django, je Tag)",
    ],
    description: "Beschreibung",
    quantity: "Menge",
    unit_price: "Einzelpreis",
    amount: "Betrag",
    subtotal: "Zwischensumme",
    tax: "MwSt. 20 %",
    total: "Zu zahlen",
    payment: "ZAHLUNG",
    terms_before: "Bitte überweisen Sie ",
    terms_around_number: " innerhalb von 30 Tagen unter Angabe der Rechnungsnummer ",
    terms_after: ". Scannen Sie den Code, um den genauen Betrag auf das Konto unten zu zahlen.",
    iban_label: "IBAN",
    caption: "Zum Bezahlen scannen — SEPA",
    vat: "USt-IdNr.",
};

/// Every language the example is written in. A language is added by writing its
/// own set of words and naming it here.
static WORDS: [(Language, &Words); 7] = [
    (Language::English, &ENGLISH),
    (Language::French, &FRENCH),
    (Language::German, &GERMAN),
    (Language::Spanish, &SPANISH),
    (Language::Italian, &ITALIAN),
    (Language::Portuguese, &PORTUGUESE),
    (Language::Dutch, &DUTCH),
];

/// An amount, as an invoice writes it: "4 250.00 EUR".
fn amount(value: f64) -> String {
    let fixed = format!("{value:.2}");
    let (units, hundredths) = fixed.split_once('.').unwrap_or((fixed.as_str(), "00"));

    let mut grouped = String::new();
    for (index, digit) in units.chars().enumerate() {
        if index > 0 && (units.len() - index) % 3 == 0 {
            grouped.push(' ');
        }
        grouped.push(digit);
    }

    format!("{grouped}.{hundredths} EUR")
}

/// The line the QR code carries: a SEPA credit transfer in the EPC069-12
/// format, the one a banking app reads to offer a transfer of `total` to the
/// seller. The BIC line is left empty, which the standard allows for an account
/// reachable in the single euro payments area, and the reference travels as
/// free text, in the language the page is set in.
fn sepa_transfer(words: &Words, total: f64) -> String {
    [
        "BCD",
        "002",
        "1",
        "SCT",
        "",
        SELLER,
        IBAN,
        &format!("EUR{total:.2}"),
        "",
        "",
        &format!("{} {NUMBER}", words.invoice),
    ]
    .join("\n")
}

/// Draws a line of text, left-aligned, in a colour of its own.
fn text(content: &mut Content, font: &FontHandle, size: f64, x: f64, y: f64, color: Rgb, s: &str) {
    let _ = content.set_fill(color);
    content.begin_text();
    let _ = content.set_font(font, size);
    let _ = content.text_origin(x, y);
    content.show_glyphs(&font.glyphs(s));
    content.end_text();
}

/// Draws a line of text whose right edge sits at `right`.
fn text_right(
    content: &mut Content,
    font: &FontHandle,
    size: f64,
    right: f64,
    y: f64,
    color: Rgb,
    s: &str,
) {
    text(
        content,
        font,
        size,
        right - font.measure(s, size),
        y,
        color,
        s,
    );
}

/// A horizontal rule from `LEFT` to `RIGHT` at height `y`.
fn rule(content: &mut Content, y: f64, width: f64, color: Rgb) -> Result<(), hqf_pdf::Error> {
    content.set_stroke(color)?;
    content.set_line_width(width)?;
    content.move_to(LEFT, y)?;
    content.line_to(RIGHT, y)?;
    content.stroke();
    Ok(())
}

/// The invoice's table: a heading row, the billed lines, and the totals.
fn invoice_table<'a>(
    font: &'a FontHandle,
    words: &'static Words,
) -> Result<Table<'a>, hqf_pdf::Error> {
    // The description takes whatever the three figure columns leave it.
    let columns = Columns::new(
        vec![
            ColumnWidth::Fraction(1.0),
            ColumnWidth::Points(46.0),
            ColumnWidth::Points(94.0),
            ColumnWidth::Points(94.0),
        ],
        TABLE_WIDTH,
    )?;

    let mut table = Table::new(columns);
    table.header(1);
    table
        .rule(Rule::Frame, Stroke::new(0.8, ACCENT))
        .rule(Rule::HorizontalOther, Stroke::new(0.25, Rgb::gray(0.78)))
        .rule(Rule::Horizontal(1), Stroke::new(0.8, ACCENT))
        .rule(Rule::HorizontalFromEnd(1), Stroke::new(0.8, ACCENT));

    let pad = Padding::symmetric(6.0, 5.0);
    let heading = |label: &str| {
        Cell::new(font, 9.0, label)
            .padding(pad)
            .fill(ACCENT)
            .color(Rgb::gray(1.0))
            .valign(VAlign::Middle)
    };

    table.push(
        Row::new()
            .cell(heading(words.description))
            .cell(heading(words.quantity).align(Align::Right))
            .cell(heading(words.unit_price).align(Align::Right))
            .cell(heading(words.amount).align(Align::Right))
            .min_height(22.0),
    );

    let mut total = 0.0;
    for (index, (item, label)) in ITEMS.iter().zip(words.items).enumerate() {
        let line_total = f64::from(item.quantity) * item.unit_price;
        total += line_total;

        let figure = |value: String| {
            Cell::new(font, 9.0, value)
                .padding(pad)
                .align(Align::Right)
                .valign(VAlign::Middle)
        };

        let mut row = Row::new()
            .cell(
                Cell::new(font, 9.0, label)
                    .padding(pad)
                    .valign(VAlign::Middle),
            )
            .cell(figure(item.quantity.to_string()))
            .cell(figure(amount(item.unit_price)))
            .cell(figure(amount(line_total)))
            .min_height(19.0);

        if index % 2 == 1 {
            row = row.fill(Rgb::gray(0.96));
        }
        table.push(row);
    }

    let tax = total * VAT_RATE;
    for (label, value, size, is_grand_total) in [
        (words.subtotal, total, 9.0, false),
        (words.tax, tax, 9.0, false),
        (words.total, total + tax, 10.0, true),
    ] {
        // The grand total is boxed off the grid so it reads as a total, not as
        // one more line: the label carries the box's left edge and the figure
        // its right, so the two trace one box between them.
        let (label_border, value_border, box_margin) = if is_grand_total {
            let stroke = Stroke::new(0.8, ACCENT);
            (
                Border::none().top(&stroke).bottom(&stroke).left(&stroke),
                Border::none().top(&stroke).bottom(&stroke).right(&stroke),
                Margin::symmetric(0.0, 2.0),
            )
        } else {
            (Border::none(), Border::none(), Margin::NONE)
        };

        table.push(
            Row::new()
                .cell(
                    Cell::new(font, size, label)
                        .span(3)
                        .align(Align::Right)
                        .padding(pad)
                        .margin(box_margin)
                        .border(label_border.clone()),
                )
                .cell(
                    Cell::new(font, size, amount(value))
                        .align(Align::Right)
                        .padding(pad)
                        .margin(box_margin)
                        .border(value_border.clone()),
                )
                .min_height(18.0),
        );
    }

    Ok(table)
}

/// Draws the letterhead: the mark, the seller's name, the word the page is, and
/// the invoice's number and dates, closed off by a rule.
fn letterhead(
    content: &mut Content,
    font: &FontHandle,
    logo: &ImageHandle,
    words: &Words,
) -> Result<(), hqf_pdf::Error> {
    let (logo_w, logo_h) = logo.fit_within(84.0, 84.0)?;
    content.draw_image(logo, LEFT, 826.5 - logo_h, logo_w, logo_h)?;

    text(content, font, 8.5, LEFT, 768.0, MUTED, SELLER_ADDRESS);
    text(content, font, 8.5, LEFT, 756.0, MUTED, SELLER_CONTACT);

    text_right(content, font, 30.0, RIGHT, 796.0, ACCENT, words.heading);
    text_right(
        content,
        font,
        9.5,
        RIGHT,
        770.0,
        INK,
        &format!("{} {NUMBER}", words.number_label),
    );
    text_right(
        content,
        font,
        9.5,
        RIGHT,
        757.0,
        MUTED,
        &format!("{} {}", words.issue_label, words.issue_date),
    );
    text_right(
        content,
        font,
        9.5,
        RIGHT,
        744.0,
        MUTED,
        &format!("{} {}", words.due_label, words.due_date),
    );

    rule(content, 730.0, 1.2, ACCENT)
}

/// Draws who the invoice is to, and — set apart on the right — what it comes
/// to.
fn parties(content: &mut Content, font: &FontHandle, words: &Words, total: f64) {
    text(content, font, 8.0, LEFT, 712.0, MUTED, words.bill_to);
    text(content, font, 11.0, LEFT, 697.0, INK, BUYER);
    text(content, font, 9.0, LEFT, 683.0, MUTED, BUYER_STREET);
    text(content, font, 9.0, LEFT, 671.0, MUTED, BUYER_CITY);

    text_right(content, font, 8.0, RIGHT, 712.0, MUTED, words.amount_due);
    text_right(content, font, 17.0, RIGHT, 694.0, ACCENT, &amount(total));
    text_right(
        content,
        font,
        9.0,
        RIGHT,
        678.0,
        MUTED,
        &format!("{} {}", words.due_short, words.due_date),
    );
}

/// Draws the payment block: how to pay in words, the account in figures, and
/// the same transfer as a scannable code beside it, then the legal footer.
fn payment(
    content: &mut Content,
    font: &FontHandle,
    words: &Words,
    table_bottom: f64,
    total: f64,
) -> Result<(), hqf_pdf::Error> {
    let block_top = table_bottom - 40.0;
    text(content, font, 10.0, LEFT, block_top, ACCENT, words.payment);

    // The due amount is underlined mid-line, which is what rich text is for.
    let body = Style::new(font, 9.5);
    let marked = Style::new(font, 9.5).underline();
    let terms = RichText::new()
        .span(words.terms_before, &body)
        .span(amount(total), &marked)
        .span(
            format!("{}{NUMBER}{}", words.terms_around_number, words.terms_after),
            &body,
        );
    let terms_top = block_top - 16.0;
    let lines = terms.break_lines(300.0);
    content.set_fill(INK)?;
    terms.draw(content, &lines, LEFT, terms_top, 300.0)?;

    let iban_y = terms_top - RichText::height(&lines) - 10.0;
    text(content, font, 9.0, LEFT, iban_y, MUTED, words.iban_label);
    text(content, font, 9.5, LEFT + 34.0, iban_y, INK, IBAN_SHOWN);

    // The code sits at the right, drawn as a square from its lower-left corner,
    // level with the payment words and clear of the table above.
    let code = QrCode::new(&sepa_transfer(words, total))?;
    let side = 104.0;
    let code_x = RIGHT - side;
    let code_bottom = block_top + 4.0 - side;
    content.set_fill(Rgb::gray(0.0))?;
    content.draw_qr(&code, code_x, code_bottom, side)?;
    let caption_x = code_x + (side - font.measure(words.caption, 8.0)) / 2.0;
    text(
        content,
        font,
        8.0,
        caption_x,
        code_bottom - 12.0,
        MUTED,
        words.caption,
    );

    // The foot of the page: what the law asks a French invoice to carry.
    rule(content, 74.0, 0.5, Rgb::gray(0.8))?;
    let mentions = format!(
        "{SELLER} · {SELLER_ADDRESS} · {SELLER_SIRET} · {SELLER_APE} · {} {SELLER_VAT}",
        words.vat
    );
    let mentions_x = LEFT + (TABLE_WIDTH - font.measure(&mentions, 7.0)) / 2.0;
    text(content, font, 7.0, mentions_x, 62.0, MUTED, &mentions);

    Ok(())
}

fn main() -> std::process::ExitCode {
    failure::reported(run())
}

fn run() -> Result<(), Box<dyn std::error::Error>> {
    let language = Language::from_environment()?;
    let words = Words::of(language);

    let mut args = env::args().skip(1);
    // A named file is written as named; the default one carries the language,
    // so the two languages do not overwrite each other in `tmp/`.
    let path = args
        .next()
        .unwrap_or_else(|| language.file_name(&out::default_path("invoice")));
    let font_path = args.next().map_or_else(default_font, PathBuf::from);

    let mut doc = Document::new();
    doc.set_license(licence::licensed());
    doc.set_info(Name::new("Title"), &format!("{} {NUMBER}", words.invoice));

    let font = doc.add_font(Font::parse(fs::read(&font_path)?)?);
    let logo = doc.add_image(Image::parse(fs::read(logo_path())?)?);

    let total = ITEMS
        .iter()
        .map(|item| f64::from(item.quantity) * item.unit_price)
        .sum::<f64>()
        * (1.0 + VAT_RATE);

    let mut content = Content::new();
    letterhead(&mut content, &font, &logo, words)?;
    parties(&mut content, &font, words, total);

    // The billed lines, fitted onto this page: the invoice is short enough to
    // sit on one, but the table would continue onto the next were it not.
    let table = invoice_table(&font, words)?;
    let table_top = 645.0;
    let placed = table.fit(TableFrame::new(LEFT, table_top, table_top - 250.0), 0)?;
    placed.draw(&mut content)?;

    payment(
        &mut content,
        &font,
        words,
        table_top - placed.height(),
        total,
    )?;

    let mut page = Page::new(PAGE_WIDTH, PAGE_HEIGHT);
    page.content = content.into_bytes();
    doc.add_page(page)?;

    let bytes = doc.to_bytes()?;
    if let Some(parent) = Path::new(&path).parent() {
        fs::create_dir_all(parent)?;
    }
    fs::write(&path, &bytes)?;

    println!("wrote {path}: {} bytes, {} due", bytes.len(), amount(total));
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::{WORDS, language};

    /// The lines two languages are allowed to write the same way, each with
    /// what makes the two the same word.
    const SPARED: [&str; 7] = [
        // An account number goes by its four letters in French as in English.
        r#"iban_label: "IBAN""#,
        // Written the same way in Spanish.
        r#"subtotal: "Subtotal""#,
        // Written the same way in Italian.
        r#"tax: "IVA al 20 %""#,
        // Written the same way in Portuguese.
        r#"due_date: "18 de agosto de 2026""#,
        r#"due_short: "Vence""#,
        r#"payment: "PAGAMENTO""#,
        r#"total: "Total a pagar""#,
    ];

    #[test]
    fn every_language_draws_the_invoice_in_its_own_words() {
        let untranslated = language::untranslated_lines(&WORDS, &SPARED);

        assert!(
            untranslated.is_empty(),
            "the invoice says these in more than one language: {untranslated:?}"
        );
    }
}